self_repo_guard.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. """Detect Git operations that can rewrite the checkout backing this process."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. import re
  6. import shlex
  7. import subprocess
  8. from dataclasses import dataclass, field
  9. from pathlib import Path
  10. from typing import Callable
  11. from tools.approval_detection import (
  12. _bash_exec_payload, _deobfuscate_shell_word_for_detection, _iter_shell_command_starts,
  13. _is_shell_comment_start, _read_shell_word, _scan_shell)
  14. # bisect drives repeated checkouts of the running root — the exact skew hazard guarded here.
  15. _WORKTREE_MUTATIONS = frozenset({
  16. "checkout", "switch", "rebase", "merge", "pull", "restore", "clean", "cherry-pick", "revert",
  17. "bisect"})
  18. _WORKTREE_TARGET_ACTIONS = frozenset({"move", "remove"})
  19. _STASH_SAFE_ACTIONS = frozenset({"list", "show", "create", "store", "drop", "clear"})
  20. _RESET_WORKTREE_MODES = frozenset({"--hard", "--merge", "--keep"})
  21. # `reset`/`stash`/`clean`/`restore` reach this set only in their SAFE forms (_mutates_worktree
  22. # runs first); listing them skips a pointless `git config --get alias.<sub>` subprocess.
  23. _KNOWN_GIT_BUILTINS = frozenset({
  24. "add", "am", "apply", "blame", "branch", "bundle", "cat-file", "clean", "clone", "commit",
  25. "config", "describe", "diff", "fetch", "format-patch", "grep", "help", "init", "log",
  26. "ls-files", "ls-remote", "ls-tree", "maintenance", "merge-base", "mv", "notes", "push",
  27. "range-diff", "reflog", "remote", "repack", "replace", "reset", "restore", "rev-list",
  28. "rev-parse", "rm", "shortlog", "show", "show-ref", "stash", "status", "submodule", "tag",
  29. "worktree"})
  30. _SHELL_EXECUTABLES = frozenset({"bash", "dash", "ksh", "sh", "zsh"})
  31. _ASSIGNMENT_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=(.*)", re.DOTALL)
  32. _RESET_HARD_RE = re.compile(r"--h(?:a(?:r(?:d)?)?)?\Z")
  33. # ``<<-`` opener + optional blanks + a quoted delimiter (closing quote required) or a bare word.
  34. _HEREDOC_OPENER_RE = re.compile(
  35. r"<<(?P<dash>-?)[ \t]*(?:(?P<q>['\"])(?P<quoted>.*?)(?P=q)|(?!['\"])(?P<bare>[^\s;|&<>]*))")
  36. _NO_OPTIONS: frozenset[str] = frozenset()
  37. # Wrapper executables skipped to reach the real command -> options that consume an argument.
  38. _WRAPPER_OPTIONS_WITH_ARG: dict[str, frozenset[str]] = {
  39. "sudo": frozenset({
  40. "-C", "--chdir", "-c", "--close-from", "-g", "--group", "-h", "--host",
  41. "-p", "--prompt", "-R", "--chroot", "-T", "--command-timeout", "-u", "--user"}),
  42. "env": frozenset({"-a", "--argv0", "-C", "--chdir", "-S", "--split-string", "-u", "--unset"}),
  43. "command": _NO_OPTIONS, "builtin": _NO_OPTIONS, "nohup": _NO_OPTIONS, "setsid": _NO_OPTIONS,
  44. "exec": frozenset({"-a"}), "nice": frozenset({"-n", "--adjustment"}),
  45. "time": frozenset({"-f", "--format", "-o", "--output"})}
  46. _MAX_RECURSION = 4
  47. # git global options that consume the next argument (-C/--work-tree/-c are acted on).
  48. _GIT_GLOBAL_OPTIONS_WITH_ARG = frozenset(
  49. {"-C", "-c", "--work-tree", "--git-dir", "--namespace", "--exec-path"})
  50. @dataclass
  51. class _Heredoc:
  52. delimiter: str
  53. strip_tabs: bool
  54. opener: int # offset of the ``<<`` in the masked command
  55. body: list[str] = field(default_factory=list)
  56. @dataclass
  57. class _ShellContext: # one `(` / `$(` / backtick nesting level and its live quote state
  58. kind: str
  59. opener: int
  60. quote: str | None = None
  61. def get_running_source_root() -> Path | None:
  62. """The source checkout backing this process, if there is one."""
  63. try:
  64. root = Path(__file__).resolve().parent.parent
  65. except (OSError, RuntimeError):
  66. return None
  67. return root if (root / ".git").exists() else None
  68. def _resolve(path_str: str, base: Path) -> Path:
  69. path = base / Path(os.path.expanduser(path_str)) # ``/`` keeps an absolute right operand
  70. with contextlib.suppress(OSError, RuntimeError, ValueError):
  71. return path.resolve()
  72. return path
  73. def _is_within(path: Path, root: Path) -> bool:
  74. with contextlib.suppress(OSError, RuntimeError, ValueError):
  75. return path == root or path.is_relative_to(root)
  76. return False
  77. def _executable_name(value: str) -> str:
  78. return Path(value.replace("\\", "/")).name.removesuffix(".exe").lower()
  79. def _shell_words_at(command: str, start: int) -> list[str]:
  80. """Deobfuscated words of the simple command at ``start`` (stops at a newline, a redirection
  81. or a trailing ``# comment``; max 64). The fd prefix of ``2>/dev/null`` / ``2>&1`` belongs to
  82. the redirection, not to the command's operands."""
  83. words: list[str] = []
  84. cursor = start
  85. for _ in range(64):
  86. word_start, word_end, raw_word = _read_shell_word(command, cursor)
  87. if word_start == word_end or (words and "\n" in command[cursor:word_start]) or (
  88. _is_shell_comment_start(command, word_start)) or (
  89. raw_word.isdigit() and command[word_end : word_end + 1] in ("<", ">")):
  90. break
  91. words.append(_deobfuscate_shell_word_for_detection(raw_word))
  92. cursor = word_end
  93. return words
  94. def _consume_options(
  95. words: list[str], start: int, options_with_arg: frozenset[str] = _NO_OPTIONS) -> int:
  96. """Index of the first positional at/after ``start`` (``--`` ends options)."""
  97. index = start
  98. while index < len(words) and words[index].startswith("-") and words[index] != "-":
  99. if words[index] == "--":
  100. return index + 1
  101. index += 2 if "=" not in words[index] and words[index] in options_with_arg else 1
  102. return index
  103. def _command_parts(words: list[str]) -> tuple[dict[str, str], str | None, list[str]]:
  104. """Split leading VAR=value assignments and wrappers off -> (env, executable, args)."""
  105. env: dict[str, str] = {}
  106. index = 0
  107. while index < len(words):
  108. if _ASSIGNMENT_RE.fullmatch(words[index]):
  109. name, value = words[index].split("=", 1)
  110. env[name] = value
  111. index += 1
  112. continue
  113. executable = _executable_name(words[index])
  114. wrapper_options = _WRAPPER_OPTIONS_WITH_ARG.get(executable)
  115. if wrapper_options is None:
  116. return env, words[index], words[index + 1 :]
  117. if executable == "command" and words[index + 1 : index + 2] in (["-v"], ["-V"]):
  118. break # `command -v/-V` only reports; nothing runs
  119. index = _consume_options(words, index + 1, wrapper_options)
  120. return env, None, []
  121. def _scope_keys(command: str, starts: list[int]) -> dict[int, tuple[int, ...]]:
  122. """Map each command start to the tuple of enclosing ``(``/``$(``/backtick openers."""
  123. contexts = [_ShellContext("root", -1)]
  124. scopes: dict[int, tuple[int, ...]] = {}
  125. cursor = 0
  126. for start in sorted(set(starts)):
  127. while cursor < start:
  128. context = contexts[-1]
  129. quote = context.quote
  130. char = command[cursor]
  131. closes = quote is None and len(contexts) > 1 # an unquoted closer may pop a scope
  132. if quote is not None and char == quote:
  133. context.quote = None
  134. elif quote == "'":
  135. pass # single quotes: no escapes, no substitutions
  136. elif char == "\\" and cursor + 1 < start:
  137. cursor += 1
  138. elif quote is None and char in "'\"":
  139. context.quote = char
  140. # Unquoted or inside double quotes: substitutions still open scopes.
  141. elif command.startswith("$(", cursor):
  142. contexts.append(_ShellContext("$(", cursor))
  143. cursor += 1
  144. elif quote is None and char == "(":
  145. contexts.append(_ShellContext("(", cursor))
  146. elif (char == ")" and closes and context.kind in {"(", "$("}) or (
  147. char == "`" and closes and context.kind == "`"):
  148. contexts.pop()
  149. elif char == "`":
  150. contexts.append(_ShellContext("`", cursor))
  151. cursor += 1
  152. scopes[start] = tuple(item.opener for item in contexts[1:])
  153. return scopes
  154. def _operator_before(command: str, start: int) -> str | None:
  155. """The list/grouping operator (or newline) immediately preceding a command start."""
  156. head = command[:start].rstrip()
  157. for tail in (head[-2:], head[-1:]):
  158. if tail in {"&&", "||", ";", "|", "&", "(", "{"}:
  159. return tail
  160. return "\n" if "\n" in command[len(head):start] else None
  161. def _cd_target(executable: str, args: list[str], cwd: Path) -> Path | None:
  162. """Directory a ``cd``/``pushd`` would land in (existing dirs only), else None."""
  163. if _executable_name(executable) not in {"cd", "pushd"}:
  164. return None
  165. index = _consume_options(args, 0)
  166. if index >= len(args) or args[index] == "-":
  167. return None
  168. target = _resolve(args[index], cwd)
  169. return target if target.is_dir() else None
  170. def _shell_script_arg(args: list[str]) -> str | None:
  171. """Script string owned by a shell's ``-c``, if present. ``_bash_exec_payload`` parses bash's
  172. real option grammar (``-o pipefail -c '<script>'``); when it finds no ``-c``, fall back to a
  173. permissive scan: zsh/dash/ksh letters (``zsh -yc``) would otherwise fail this guard open."""
  174. has_c, payload = _bash_exec_payload(args)
  175. if has_c:
  176. return payload
  177. for index, arg in enumerate(args):
  178. if arg == "--" or not arg.startswith("-"):
  179. return None
  180. if "c" in arg[1:]:
  181. return args[index + 1] if index + 1 < len(args) else None
  182. return None
  183. def _executes_heredoc_body(words: list[str]) -> bool:
  184. """A bare shell (no ``-c`` script, no script operand) executes whatever it reads on stdin."""
  185. _, executable, args = _command_parts(words)
  186. return bool(
  187. executable and _executable_name(executable) in _SHELL_EXECUTABLES
  188. and _shell_script_arg(args) is None
  189. and not any(arg and not arg.startswith("-") for arg in args))
  190. def _group_token(masked: str, index: int) -> bool:
  191. """``{`` / ``}`` at ``index`` is a brace-group delimiter (its own word), not ``${x}``/``a{b,c}``."""
  192. before = masked[index - 1] if index else " "
  193. after = masked[index + 1] if index + 1 < len(masked) else " "
  194. return (before.isspace() or before in "(;&|") and (after.isspace() or after in ";)|&")
  195. def _pipeline_end(masked: str, opener: int) -> int:
  196. """Offset where the pipeline carrying a heredoc ends: the first ``;``/``&&``/``||``/``&`` or
  197. bare newline at top level. Newlines right after ``|`` continue the pipeline (the consumer may
  198. follow the terminator line). Inside a group the walk runs on until the group closes, then a
  199. pipe after the closer continues it (``(cat <<EOF; echo) | bash``) and anything else ends it."""
  200. depth = 0
  201. level: int | None = None # nesting depth of the opener's command, once the scan reaches it
  202. after_pipe = False
  203. backtick = False
  204. for kind, index, end, quote in _scan_shell(masked, comments=True):
  205. if level is None and index >= opener:
  206. level = depth
  207. if kind == "comment":
  208. continue
  209. if kind != "char" or quote is not None:
  210. after_pipe = False # part of a word
  211. continue
  212. char = masked[index]
  213. if char.isspace():
  214. if char == "\n" and level == 0 and depth == 0 and not after_pipe:
  215. return index
  216. continue
  217. if char in ";&|":
  218. if char == "&" and (masked[index - 1] in "<>" or masked.startswith("&>", index)):
  219. continue # `2>&1` / `>&2` / `&>file` redirect fds: not a list operator
  220. if char == "|" and not masked.startswith("||", index):
  221. after_pipe = True
  222. elif level == 0 and depth == 0 and masked[index - 1] != "|": # `|&` is a pipe
  223. return index
  224. continue
  225. after_pipe = False
  226. if char == "`":
  227. depth += -1 if backtick else 1
  228. backtick = not backtick
  229. elif char == "(" or (char == "{" and _group_token(masked, index)):
  230. depth += 1
  231. elif char == ")" or (char == "}" and _group_token(masked, index)):
  232. depth -= 1
  233. if level is not None and depth < level:
  234. rest = masked[end:].lstrip(" \t")
  235. if not rest.startswith("|") or rest.startswith("||"):
  236. return index
  237. level = depth
  238. return len(masked)
  239. def _shell_consumes_heredoc(
  240. masked: str, starts: list[int], scopes: dict[int, tuple[int, ...]], opener: int) -> bool:
  241. """Whether a bare shell reads the heredoc body: the command owning the ``<<`` or anything
  242. downstream in its pipeline. Pipe-joined segments, and the groups or substitutions inside them,
  243. all inherit the pipe as stdin (``| tee f | bash``, ``| (bash)``, ``| { echo; bash; }``)."""
  244. scope = scopes[opener]
  245. owner = max((start for start in starts if start <= opener and scopes[start] == scope),
  246. default=None)
  247. end = _pipeline_end(masked, opener)
  248. candidates = [*([owner] if owner is not None else []),
  249. *(start for start in starts if opener < start < end)]
  250. return any(_executes_heredoc_body(_shell_words_at(masked, start)) for start in candidates)
  251. def _heredoc_specs(line: str) -> list[_Heredoc]:
  252. """Heredoc openers on one command line, with their ``<<`` offsets."""
  253. specs: list[_Heredoc] = []
  254. quote: str | None = None
  255. index = 0
  256. while index < len(line):
  257. char = line[index]
  258. if quote:
  259. if char == "\\" and quote == '"' and index + 1 < len(line):
  260. index += 1 # skip the escaped character too
  261. elif char == quote:
  262. quote = None
  263. elif char in "'\"":
  264. quote = char
  265. if quote or not line.startswith("<<", index) or line.startswith("<<<", index):
  266. index += 1
  267. continue
  268. opener = _HEREDOC_OPENER_RE.match(line, index)
  269. if opener is None: # unterminated quoted delimiter: give up on this line
  270. break
  271. start, index = index, opener.end()
  272. delimiter = opener.group("quoted") if opener.group("q") else opener.group("bare")
  273. if delimiter:
  274. specs.append(_Heredoc(delimiter, bool(opener.group("dash")), start))
  275. return specs
  276. def _join_continued_line(lines: list[str], index: int) -> tuple[str, int]:
  277. """Physical line ``index`` plus every line a trailing ``\\`` joins onto it -> (line, next).
  278. The shell removes backslash-newline before it reads anything else, so the heredoc body only
  279. starts after the joined line: ``cat <<EOF | \\`` + ``bash`` pipes the body into bash. The pair
  280. is blanked (offsets preserved) so the joined text reads as one command line."""
  281. line = lines[index]
  282. index += 1
  283. while index < len(lines):
  284. text = line.rstrip("\r\n")
  285. newline = line[len(text):]
  286. if not newline or (len(text) - len(text.rstrip("\\"))) % 2 == 0:
  287. break
  288. line = text[:-1] + " " * (1 + len(newline)) + lines[index]
  289. index += 1
  290. return line, index
  291. def _mask_heredocs(command: str) -> tuple[str, list[_Heredoc]]:
  292. """Blank heredoc bodies -> (masked command, heredocs with their bodies). Unterminated heredocs
  293. run to end of input and are still reported."""
  294. output: list[str] = []
  295. offset = 0
  296. pending: list[_Heredoc] = []
  297. finished: list[_Heredoc] = []
  298. lines = command.splitlines(keepends=True)
  299. index = 0
  300. while index < len(lines):
  301. if not pending:
  302. line, index = _join_continued_line(lines, index)
  303. for spec in _heredoc_specs(line):
  304. spec.opener += offset
  305. pending.append(spec)
  306. output.append(line)
  307. offset += len(line)
  308. continue
  309. line = lines[index]
  310. index += 1
  311. current = pending[0]
  312. candidate = line.rstrip("\r\n")
  313. if (candidate.lstrip("\t") if current.strip_tabs else candidate) == current.delimiter:
  314. finished.append(pending.pop(0))
  315. else:
  316. current.body.append(line)
  317. output.append(re.sub(r"[^\r\n]", " ", line))
  318. offset += len(line)
  319. return "".join(output), finished + pending
  320. def _record_alias(config: str, aliases: dict[str, str]) -> None:
  321. """Record an inline ``-c alias.<name>=<value>`` git config override."""
  322. key, sep, value = config.partition("=")
  323. if sep and key.lower().startswith("alias."):
  324. aliases[key[6:].lower()] = value
  325. def _git_target_and_subcommand(
  326. args: list[str], current_dir: Path, env: dict[str, str],
  327. ) -> tuple[Path, str | None, list[str], dict[str, str]]:
  328. """Parse git's global options -> (target dir, subcommand, sub args, inline aliases)."""
  329. target = current_dir
  330. work_tree: str | None = None
  331. aliases: dict[str, str] = {}
  332. index = 0
  333. while index < len(args):
  334. arg = args[index]
  335. if arg == "--":
  336. index += 1
  337. break
  338. if not arg.startswith("-"):
  339. break
  340. # Separate-argument form (`-C dir`) vs attached form (`-Cdir`, `--work-tree=dir`, `-cK=V`).
  341. if arg in _GIT_GLOBAL_OPTIONS_WITH_ARG:
  342. option, value = arg, args[index + 1] if index + 1 < len(args) else None
  343. index += 2
  344. else:
  345. option, value = next(((o, arg[len(o):]) for o in ("-C", "--work-tree=", "-c")
  346. if arg.startswith(o) and len(arg) > len(o)), (None, None))
  347. index += 1
  348. if option == "-C" and value is not None:
  349. target = _resolve(value, target)
  350. elif option and option.startswith("--work-tree") and value is not None:
  351. work_tree = value
  352. elif option == "-c" and value is not None:
  353. _record_alias(value, aliases) # only alias.* overrides matter; others are ignored
  354. explicit_work_tree = work_tree or env.get("GIT_WORK_TREE")
  355. if explicit_work_tree:
  356. target = _resolve(explicit_work_tree, target)
  357. return target, args[index].lower() if index < len(args) else None, args[index + 1 :], aliases
  358. def _has_flag(args: list[str], long: str, letter: str, short_only: bool = False) -> bool:
  359. """``--long`` present, or ``letter`` inside a dash-prefixed arg (``-fdn``; ``short_only``
  360. additionally excludes ``--`` args from the letter scan)."""
  361. return any(
  362. arg == long or (arg.startswith("-") and letter in arg[1:]
  363. and not (short_only and arg.startswith("--")))
  364. for arg in args)
  365. # Subcommands whose worktree impact depends on their arguments -> predicate(args).
  366. _CONDITIONAL_MUTATIONS: dict[str, Callable[[list[str]], bool]] = {
  367. "reset": lambda args: any(
  368. arg in _RESET_WORKTREE_MODES or _RESET_HARD_RE.fullmatch(arg) for arg in args),
  369. "stash": lambda args: next(
  370. (arg for arg in args if not arg.startswith("-")), "push") not in _STASH_SAFE_ACTIONS,
  371. "clean": lambda args: not _has_flag(args, "--dry-run", "n", short_only=True),
  372. # `restore` touches the worktree unless ONLY --staged was requested.
  373. "restore": lambda args: (_has_flag(args, "--worktree", "W")
  374. or not _has_flag(args, "--staged", "S"))}
  375. def _mutates_worktree(subcommand: str, args: list[str]) -> bool:
  376. check = _CONDITIONAL_MUTATIONS.get(subcommand, lambda _args: subcommand in _WORKTREE_MUTATIONS)
  377. return check(args)
  378. def _inspect_git_worktree(args: list[str], cwd: Path, root: Path) -> str | None:
  379. """Block `worktree remove|move` aimed at the running root, from any directory."""
  380. action_index = _consume_options(args, 0)
  381. action = args[action_index].lower() if action_index < len(args) else None
  382. target_index = _consume_options(args, action_index + 1)
  383. if (action in _WORKTREE_TARGET_ACTIONS and target_index < len(args)
  384. and _resolve(args[target_index], cwd) == root):
  385. return f"git worktree {action}"
  386. return None
  387. def _read_git_alias(executable: str, target: Path, alias: str) -> str | None:
  388. with contextlib.suppress(OSError, subprocess.SubprocessError):
  389. result = subprocess.run(
  390. [executable, "-C", str(target), "config", "--get", f"alias.{alias}"],
  391. stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=1, check=False)
  392. return (result.stdout.strip() or None) if result.returncode == 0 else None
  393. return None
  394. def _inspect_git(
  395. executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path, depth: int
  396. ) -> str | None:
  397. target, subcommand, sub_args, inline_aliases = _git_target_and_subcommand(
  398. args, current_dir, env)
  399. if subcommand is None:
  400. return None
  401. if subcommand == "worktree": # names its victim as an argument: the cwd check does not apply
  402. return _inspect_git_worktree(sub_args, target, root)
  403. if not _is_within(target, root):
  404. return None
  405. if _mutates_worktree(subcommand, sub_args):
  406. return f"git {subcommand}"
  407. if subcommand in _KNOWN_GIT_BUILTINS or depth >= _MAX_RECURSION:
  408. return None
  409. alias = (inline_aliases[subcommand] if subcommand in inline_aliases
  410. else _read_git_alias(executable, target, subcommand))
  411. if not alias:
  412. return None
  413. if alias.startswith("!"): # shell alias: scan it as a command
  414. return _find_mutation(alias[1:], target, root, depth + 1)
  415. try:
  416. alias_args = shlex.split(alias, posix=True)
  417. except ValueError:
  418. return None
  419. return _inspect_git(executable, [*alias_args, *sub_args], target, {}, root, depth + 1)
  420. def _inspect_github_cli(
  421. executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path, depth: int
  422. ) -> str | None:
  423. if not _is_within(current_dir, root):
  424. return None
  425. index = _consume_options(args, 0, frozenset({"-R", "--repo", "--hostname"}))
  426. is_checkout = args[index : index + 2] == ["pr", "checkout"]
  427. return f"{_executable_name(executable)} pr checkout" if is_checkout else None
  428. def _inspect_shell(
  429. executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path, depth: int
  430. ) -> str | None:
  431. script = _shell_script_arg(args)
  432. return _find_mutation(script, current_dir, root, depth + 1) if script else None
  433. # executable name -> inspector(executable, args, current_dir, env, root, depth)
  434. _INSPECTORS: dict[str, Callable[..., str | None]] = {
  435. "git": _inspect_git, "gh": _inspect_github_cli, "hub": _inspect_github_cli,
  436. **{shell: _inspect_shell for shell in _SHELL_EXECUTABLES}}
  437. def _find_mutation(command: str, cwd: Path, root: Path, depth: int = 0) -> str | None:
  438. """Name of the first command in ``command`` that would rewrite ``root``, else None."""
  439. if depth > _MAX_RECURSION:
  440. return None
  441. masked_command, heredocs = _mask_heredocs(command)
  442. starts = sorted(set(_iter_shell_command_starts(masked_command)))
  443. scopes = _scope_keys(masked_command, [*starts, *(heredoc.opener for heredoc in heredocs)])
  444. # Bodies a bare shell reads (`bash <<EOF`, `cat <<EOF | bash`) are scripts: scan them.
  445. for heredoc in heredocs:
  446. if _shell_consumes_heredoc(masked_command, starts, scopes, heredoc.opener) and (
  447. operation := _find_mutation("".join(heredoc.body), cwd, root, depth + 1)):
  448. return operation
  449. # cwd per subshell scope; `cd` applies to the NEXT command only via `&&`, `;`, newline.
  450. cwd_by_scope: dict[tuple[int, ...], Path] = {(): cwd}
  451. pending_cd: dict[tuple[int, ...], Path] = {}
  452. for start in starts:
  453. scope = scopes[start]
  454. cwd_by_scope.setdefault(scope, cwd_by_scope.get(scope[:-1], cwd))
  455. pending = pending_cd.pop(scope, None)
  456. if pending is not None and _operator_before(masked_command, start) in {"&&", ";", "\n"}:
  457. cwd_by_scope[scope] = pending
  458. env, executable, args = _command_parts(_shell_words_at(masked_command, start))
  459. if executable is None:
  460. continue
  461. current_dir = cwd_by_scope[scope]
  462. if (cd_target := _cd_target(executable, args, current_dir)) is not None:
  463. pending_cd[scope] = cd_target
  464. elif (inspect := _INSPECTORS.get(_executable_name(executable))) and (
  465. operation := inspect(executable, args, current_dir, env, root, depth)):
  466. return operation
  467. return None
  468. def guard_active() -> bool:
  469. """Windows-only: NTFS locks loaded .py/.pyd files, so overwriting the live checkout can
  470. corrupt the running process. On POSIX open handles keep the old inode alive; the mixed-module
  471. hazard is limited to later lazy imports — not worth blocking every git workflow for."""
  472. return os.name == "nt"
  473. def detect_self_repo_git_mutation(
  474. command: str, cwd: str | None, source_root: Path | None = None) -> tuple[bool, str | None]:
  475. """-> (blocked, message): whether a command would rewrite the live source checkout."""
  476. root = source_root if source_root is not None else get_running_source_root()
  477. if root is None or not command:
  478. return False, None
  479. root = _resolve(str(root), Path("/"))
  480. operation = _find_mutation(command, _resolve(cwd or "/", Path("/")), root)
  481. return (True, _block_message(operation, root)) if operation is not None else (False, None)
  482. def _block_message(operation: str, root: Path) -> str:
  483. hermes_home = os.environ.get("HERMES_HOME", "").strip()
  484. scratch = (Path(hermes_home).expanduser() if hermes_home else Path.home() / ".hermes") / "scratch"
  485. return (
  486. f"Blocked: `{operation}` would rewrite Hermes's live source checkout "
  487. f"({root}) and can mix module versions in this running process. "
  488. f"Use a separate worktree or a shared clone on real disk, e.g. "
  489. f"`git clone --shared {root} {scratch}/<task>` — avoid /tmp for " # no-tmp: ok — guidance telling the model to AVOID /tmp
  490. "clones that install node/python deps: /tmp is usually RAM-backed tmpfs and a few " # no-tmp: ok — guidance telling the model to AVOID /tmp
  491. "dependency installs can fill it and ENOSPC other work. Delete the clone when the branch "
  492. "is pushed. To change this checkout, stop Hermes, run the command externally, then restart "
  493. "Hermes.")