_subprocess_compat.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. """Windows subprocess compatibility helpers.
  2. * ``["npm", ...]`` — on Windows ``npm`` is ``npm.cmd``, a batch shim; ``Popen`` fails with
  3. WinError 193 because CreateProcessW can't run a ``.cmd`` without ``shell=True``/PATHEXT.
  4. * ``start_new_session=True`` — POSIX ``os.setsid()`` detach; silently ignored on Windows, whose
  5. equivalent is the ``CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW`` creationflags bundle.
  6. """
  7. from __future__ import annotations
  8. import os
  9. import re
  10. import shutil
  11. import subprocess
  12. import sys
  13. from pathlib import Path
  14. from typing import Mapping, NoReturn, Sequence
  15. __all__ = [
  16. "FILTER_DISCOVERY_FAILED",
  17. "IS_WINDOWS",
  18. "NO_DRIVER_DIFF_FLAGS",
  19. "NO_LAZY_FETCH_ENV",
  20. "bounded_git_probe",
  21. "bounded_probe_run",
  22. "expose_pm_git",
  23. "noninteractive_git_env",
  24. "noninteractive_repo_git_env",
  25. "pid_exists_stdlib",
  26. "pid_is_hermes",
  27. "resolve_node_command",
  28. "restore_ambient_pythonpath",
  29. "selected_git_env",
  30. "split_command_line",
  31. "suppress_platform_ver_console",
  32. "windows_detach_flags",
  33. "windows_detach_flags_without_breakaway",
  34. "windows_detach_popen_kwargs",
  35. "windows_hide_flags",
  36. ]
  37. # Flags that neutralize *attribute-scoped* diff drivers on any diff-rendering git command. A
  38. # malicious repo can name a driver in ``.gitattributes`` (``* diff=evil``) and point it at an
  39. # arbitrary program via ``[diff "evil"] command=/textconv=`` in ``.git/config``; because the
  40. # attacker chooses the name, ``GIT_CONFIG_KEY`` overrides in ``noninteractive_git_env`` cannot
  41. # enumerate it — only these flags do. ``--no-ext-diff`` kills ``command=``; ``--no-textconv`` kills
  42. # ``textconv=``; each alone leaves the other live. Repository-named clean/smudge/process filters
  43. # are handled separately by ``noninteractive_repo_git_env`` at repo-scoped automatic call sites.
  44. NO_DRIVER_DIFF_FLAGS = ("--no-ext-diff", "--no-textconv")
  45. # Only these subcommands accept ``NO_DRIVER_DIFF_FLAGS`` — ``status`` and friends reject them
  46. # (``unknown option``), so the helper gates on this set rather than blanket-prepending.
  47. _DIFF_RENDERING_SUBCOMMANDS = frozenset({"diff", "show", "log", "blame"})
  48. # Options that consume the FOLLOWING token, so that value is never mistaken for the subcommand
  49. # (``-C diff`` is a path; ``-c diff=x`` is a config pair).
  50. _GIT_VALUE_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path"}
  51. def run(cmd, **kwargs) -> NoReturn:
  52. # Shim to suppress old updater work until relaunch. Do not start its installer.
  53. from hermes_cli._old_updater import stop_for_relaunch
  54. stop_for_relaunch()
  55. def harden_git_argv(args: Sequence[str]) -> list[str]:
  56. """Copy of subcommand-first git *args* (no leading ``"git"``) with :data:`NO_DRIVER_DIFF_FLAGS`
  57. inserted right after a diff-rendering subcommand; other subcommands are returned unchanged.
  58. Pair with :func:`noninteractive_git_env`: the env layer disables fsmonitor/hooks/pager/editor/
  59. credential sinks, this closes the one class (attacker-named attribute drivers) env cannot reach.
  60. """
  61. out = list(args)
  62. i = 0
  63. while i < len(out):
  64. tok = out[i]
  65. if tok in _GIT_VALUE_OPTS:
  66. i += 2
  67. continue
  68. if tok.startswith("-"):
  69. i += 1
  70. continue
  71. if tok in _DIFF_RENDERING_SUBCOMMANDS:
  72. return out[: i + 1] + list(NO_DRIVER_DIFF_FLAGS) + out[i + 1 :]
  73. return out # first non-option token is a non-diff subcommand
  74. return out
  75. IS_WINDOWS = sys.platform == "win32"
  76. # Private launcher-to-child metadata. This is diagnostic state, not user config.
  77. _WINDOWS_GATEWAY_BREAKAWAY_ENV = "_HERMES_GATEWAY_BREAKAWAY"
  78. def split_command_line(line: str) -> list[str]:
  79. """Split a user-supplied command line into tokens, Windows-safely.
  80. ``shlex.split`` (posix=True) treats every backslash as an escape, mangling Windows paths. On
  81. Windows use ``posix=False`` and strip one layer of matching quotes per token; on POSIX this is
  82. exactly ``shlex.split``. Raises ValueError on unbalanced quotes.
  83. ``shlex.split(line)`` (posix=True) treats every backslash as an escape character, so Windows paths are
  84. silently mangled: ``C:\\Users\\me\\out.txt`` becomes ``C:Usersmeout.txt`` — no error, just a wrong path
  85. that then "succeeds" against a mangled relative filename (#83934) or makes a valid hook script report
  86. "not executable" (#78293).
  87. """
  88. import shlex
  89. if not IS_WINDOWS:
  90. return shlex.split(line)
  91. out: list[str] = []
  92. for tok in shlex.split(line, posix=False):
  93. if len(tok) >= 2 and tok[0] == tok[-1] and tok[0] in ("'", '"'):
  94. tok = tok[1:-1]
  95. out.append(tok)
  96. return out
  97. # -----------------------------------------------------------------------------
  98. # Node ecosystem launcher resolution
  99. # -----------------------------------------------------------------------------
  100. def restore_ambient_pythonpath(env: Mapping[str, str]) -> dict:
  101. """Re-add the ambient ``PYTHONPATH`` to a child environment that a
  102. ``build_subprocess_env``-style factory already built.
  103. No-boot-through-venv: the boot interpreter is the pm STORE python, whose
  104. imports arrive via ``PYTHONPATH=<repo>;<venv>/site-packages`` (it has no
  105. editable install). The subprocess-env factories strip Hermes-owned
  106. PYTHONPATH entries so agent-run children on DIFFERENT interpreter
  107. versions never load the backend's C extensions — but a child that
  108. re-execs THIS interpreter (``sys.executable -m hermes_cli.main``) runs
  109. on the same version and needs those entries back. Prepending keeps the
  110. launcher's repo-first ordering intact.
  111. """
  112. merged = dict(env)
  113. ambient = os.environ.get("PYTHONPATH")
  114. if ambient:
  115. existing = merged.get("PYTHONPATH", "")
  116. merged["PYTHONPATH"] = (
  117. ambient + os.pathsep + existing if existing else ambient
  118. )
  119. return merged
  120. def resolve_node_command(name: str, argv: Sequence[str]) -> list[str]:
  121. """Resolve a Node-ecosystem command name (``npm``, ``npx``, ``yarn``…) to an absolute-path argv.
  122. On Windows these ship as ``.cmd`` batch shims that CreateProcessW won't execute by bare name;
  123. ``shutil.which`` resolves via PATHEXT to a fully-qualified path whose extension routes it
  124. through ``cmd.exe /c``.
  125. """
  126. resolved = shutil.which(name)
  127. return [resolved or name, *argv]
  128. # Win32 CreationFlags — defined here because CREATE_NO_WINDOW / DETACHED_PROCESS aren't guaranteed
  129. # to exist on stdlib subprocess for older Pythons or non-Windows builds.
  130. _CREATE_NEW_PROCESS_GROUP = 0x00000200
  131. # DETACHED_PROCESS (0x00000008) is intentionally NOT part of any flag bundle — do not re-add it
  132. # (the recurring console-flash bug #54220 / #56747): (1) MSDN: CREATE_NO_WINDOW "is ignored if used with either
  133. # CREATE_NEW_CONSOLE or DETACHED_PROCESS"; (2) a DETACHED_PROCESS child has NO console, so every
  134. # console-subsystem descendant (git, gh, cmd, node, powershell, …) allocates its own — a visible
  135. # flash per spawn, including inside third-party libraries no per-site sweep can reach. A
  136. # CREATE_NO_WINDOW child instead OWNS a hidden console all descendants inherit (A/B verified on
  137. # Windows 11 by the desktop backend fix, commit aa2ae36c3f: with per-site hide flags neutered,
  138. # naive git/gh/cmd spawns don't flash under a hidden-console parent and do under a console-less one).
  139. # 1. Combining them means DETACHED_PROCESS governs and the no-window bit is dead. 2. See #54220, #56747.
  140. _CREATE_NO_WINDOW = 0x08000000
  141. # Escape any Win32 job object the parent belongs to. Without this a detached child inherits the
  142. # parent's job, and when that parent (Electron, Tauri, Windows Terminal, the Desktop bootstrap
  143. # installer) dies the OS tears down the whole job — taking the "detached" child with it. Critical
  144. # for the post-update gateway watcher spawned from inside Electron's job.
  145. _CREATE_BREAKAWAY_FROM_JOB = 0x01000000
  146. def windows_detach_flags() -> int:
  147. """Win32 creationflags detaching a child from the parent console/group; 0 elsewhere.
  148. Pair with the default ``start_new_session=False`` (POSIX uses ``start_new_session=True``).
  149. CREATE_NEW_PROCESS_GROUP stops Ctrl+C propagating; CREATE_NO_WINDOW gives the child a hidden
  150. console descendants (git, gh, cmd, node, …) inherit so they don't flash — deliberately replacing
  151. the old DETACHED_PROCESS approach, which re-created the per-descendant console-flash bug
  152. (#54220/#56747) at every spawn; CREATE_BREAKAWAY_FROM_JOB escapes Electron/Tauri job objects. A
  153. job that forbids breakaway yields PermissionError from Popen — callers catch OSError and fall
  154. back to :func:`windows_detach_flags_without_breakaway`.
  155. Rationale: This both detaches it from the parent's console lifetime (closing the launching terminal
  156. doesn't CTRL_CLOSE it) AND gives every console-subsystem descendant (git, gh, cmd, node, …) a console to
  157. inherit, so they don't allocate visible flashing ones. This deliberately replaces the old
  158. ``DETACHED_PROCESS`` approach: MSDN specifies CREATE_NO_WINDOW is *ignored* when combined with
  159. DETACHED_PROCESS, and a truly console-less daemon re-creates the per-descendant console-flash bug
  160. (#54220/#56747) at every spawn — see the note on ``_DETACHED_PROCESS`` above. Electron (Desktop app) and
  161. Tauri (bootstrap installer) wrap their children in job objects; without breakaway, those children die
  162. when the parent process exits even though they have their own console. This was the missing flag that
  163. made the post-update gateway respawn watcher silently die alongside the Tauri updater after the Electron
  164. Desktop's update flow finished.
  165. """
  166. if not IS_WINDOWS:
  167. return 0
  168. return _CREATE_NEW_PROCESS_GROUP | _CREATE_NO_WINDOW | _CREATE_BREAKAWAY_FROM_JOB
  169. def windows_detach_flags_without_breakaway() -> int:
  170. """:func:`windows_detach_flags` minus ``CREATE_BREAKAWAY_FROM_JOB``; 0 on non-Windows."""
  171. if not IS_WINDOWS:
  172. return 0
  173. return _CREATE_NEW_PROCESS_GROUP | _CREATE_NO_WINDOW
  174. def windows_hide_flags() -> int:
  175. """Win32 creationflags hiding the child's console without detaching it; 0 elsewhere.
  176. For short-lived synchronous helpers (``taskkill``, ``where``, version probes): no flash, but the
  177. child stays in the parent's process group and job so Ctrl+C and job teardown still propagate.
  178. Stdio is inherited, so ``capture_output=True`` works.
  179. """
  180. return _CREATE_NO_WINDOW if IS_WINDOWS else 0
  181. def no_prompt_git_kwargs() -> dict:
  182. """``subprocess.run`` kwargs for the updater's network git calls.
  183. GitHub answers anonymous fetches with HTTP 401 during outages (and for
  184. unreachable repos); git then prompts ``Username for 'https://github.com':``
  185. on the inherited terminal and the update sits there forever. Disable the
  186. prompt so the fetch fails fast into ``_classify_fetch_failure``. Only the
  187. *prompt* is disabled — a configured credential helper / askpass still
  188. runs, so a private-fork origin keeps authenticating non-interactively.
  189. Lives here, dependency-free, because the update hand-off's bootstrap
  190. interpreter runs the treeless conversion before any dependency exists.
  191. """
  192. env = dict(os.environ)
  193. env["GIT_TERMINAL_PROMPT"] = "0"
  194. env["GCM_INTERACTIVE"] = "Never"
  195. # Every network git spawn (fetch/pull/shallow heal) runs under a console-less
  196. # desktop backend on Windows; hide the per-spawn console (#117781).
  197. return {"stdin": subprocess.DEVNULL, "env": env, "creationflags": windows_hide_flags()}
  198. def suppress_platform_ver_console() -> None:
  199. """Stub ``platform._syscmd_ver`` on Windows so it never flashes a console. No-op elsewhere.
  200. ``platform.win32_ver()`` shells out ``cmd /c ver`` without CREATE_NO_WINDOW, so a windowless
  201. parent (pythonw gateway, kanban workers) flashes a cmd window whenever a dependency touches
  202. ``platform.uname()`` at import. With the stub, ``win32_ver()`` takes its documented fallback to
  203. ``sys.getwindowsversion()`` — same data, in-process. Call before heavy imports.
  204. """
  205. if not IS_WINDOWS:
  206. return
  207. try:
  208. import platform
  209. if hasattr(platform, "_syscmd_ver"):
  210. def _quiet_syscmd_ver(system="", release="", version="",
  211. supported_platforms=("win32", "win16", "dos")):
  212. return system, release, version
  213. platform._syscmd_ver = _quiet_syscmd_ver
  214. except Exception:
  215. pass # Purely cosmetic hardening — never let it break startup.
  216. def windows_detach_popen_kwargs() -> dict:
  217. """Popen kwargs detaching a child on Windows, or ``start_new_session=True`` on POSIX.
  218. Bare ``start_new_session=True`` is accepted but has no effect on Windows: the child stays
  219. attached to the parent console and dies when it closes.
  220. """
  221. if IS_WINDOWS:
  222. return {"creationflags": windows_detach_flags()}
  223. # detached-spawn: ok — the detach helper itself; every call site is checked on its own
  224. return {"start_new_session": True}
  225. # Read-only probes must never lazy-fetch. In a partial (blobless/treeless) clone a missing object makes
  226. # git spawn ``git fetch`` from the promisor remote, and a probe's timeout kills only its own git: the
  227. # startup update check's ``merge-base --is-ancestor <fresh upstream tip>`` started a ~233k-object
  228. # history download on every launch that ran on orphaned, piling up partial packs. With this set the
  229. # probe fails fast on the missing object instead (git >= 2.44; older git ignores the variable).
  230. NO_LAZY_FETCH_ENV = {"GIT_NO_LAZY_FETCH": "1"}
  231. # GIT_CONFIG_KEY_n/VALUE_n overrides for internal git children: no credential/askpass prompts, no
  232. # repo-configured fsmonitor/hooks/pager/editor/external-diff programs.
  233. _GIT_CONFIG_INJECT_PREFIXES = ("GIT_CONFIG_KEY_", "GIT_CONFIG_VALUE_")
  234. _GIT_CONFIG_OVERRIDES = {
  235. "credential.helper": "",
  236. "core.askPass": "",
  237. "core.fsmonitor": "false",
  238. "core.untrackedCache": "false",
  239. "core.hooksPath": os.devnull,
  240. "core.pager": "cat",
  241. "core.editor": "true",
  242. "sequence.editor": "true",
  243. "diff.external": "",
  244. # ssh itself bypasses stdin=DEVNULL/GIT_TERMINAL_PROMPT and opens /dev/tty directly — an
  245. # unknown host key (or password auth) prompts there and steals the caller's terminal (#104591).
  246. # BatchMode makes ssh fail instead of prompting; a working ssh-agent still succeeds. Injected
  247. # at the config layer so an explicit user GIT_SSH_COMMAND (env) still takes precedence.
  248. "core.sshCommand": "ssh -o BatchMode=yes",
  249. }
  250. def _safe_directory_cache_key(env: Mapping[str, str]) -> tuple:
  251. """Everything that decides which files ``git config --system/--global`` reads, plus the
  252. global candidates' ``file_cache_version`` so an edit to ``~/.gitconfig`` is picked up without a restart."""
  253. home = env.get("HOME", "")
  254. xdg = env.get("XDG_CONFIG_HOME") or os.path.join(home, ".config")
  255. candidates = (
  256. env.get("GIT_CONFIG_SYSTEM") or "/etc/gitconfig",
  257. env.get("GIT_CONFIG_GLOBAL") or os.path.join(home, ".gitconfig"),
  258. os.path.join(xdg, "git", "config"),
  259. )
  260. from utils import file_cache_version
  261. stamps = []
  262. for path in candidates:
  263. try:
  264. stamps.append(file_cache_version(path))
  265. except OSError:
  266. stamps.append(None)
  267. return (
  268. env.get("GIT_CONFIG_GLOBAL"), env.get("GIT_CONFIG_SYSTEM"), env.get("GIT_CONFIG_NOSYSTEM"),
  269. home, env.get("XDG_CONFIG_HOME"), env.get("PATH"), *stamps,
  270. )
  271. _safe_directory_cache: dict[tuple, list[str]] = {}
  272. def _user_safe_directories(base_env: Mapping[str, str]) -> list[str]:
  273. """The user's configured ``safe.directory`` values, in git's own effective order.
  274. Read with ``git config -z --get-all`` under *base_env* (the caller's untouched environment) so
  275. an explicit ``GIT_CONFIG_GLOBAL``/``GIT_CONFIG_SYSTEM`` still points at the file the user means.
  276. Best-effort: any failure (git missing, malformed config, timeout) yields no entries and leaves
  277. the caller exactly as it behaved before. Memoised per process on the inputs that select the
  278. config files (and the global file's mtime): ``noninteractive_git_env()`` runs on every internal
  279. git call, including the startup banner probe, and two ``git config`` children per call is
  280. ~10 ms against ~0.2 ms for the rest of the function.
  281. ``safe.directory`` is an *ordered* multi-valued setting and an empty value resets every entry
  282. seen so far, so a user can revoke a system-wide ``safe.directory=*`` and then name only the
  283. repositories they actually trust. Order and empty resets are therefore policy, not formatting:
  284. scopes are read lowest-precedence first (system, then global) and every value is preserved
  285. verbatim -- no de-duplication (it is a sequence, not a set) and no dropping of the reset
  286. marker, either of which would resurrect a revoked wildcard and widen trust. ``-z`` keeps a
  287. value containing whitespace or a newline as the single entry git reads it as.
  288. """
  289. cache_key = _safe_directory_cache_key(base_env)
  290. cached = _safe_directory_cache.get(cache_key)
  291. if cached is not None:
  292. return list(cached)
  293. env = dict(base_env)
  294. # --get-all itself must not be derailed by ambient injection or an interactive prompt.
  295. for key in list(env):
  296. if key == "GIT_CONFIG_PARAMETERS" or key.startswith(_GIT_CONFIG_INJECT_PREFIXES):
  297. env.pop(key, None)
  298. env.pop("GIT_CONFIG_COUNT", None)
  299. env["GIT_TERMINAL_PROMPT"] = "0"
  300. values: list[str] = []
  301. for scope in ("--system", "--global"):
  302. try:
  303. proc = subprocess.run(
  304. ["git", "config", scope, "-z", "--get-all", "safe.directory"],
  305. capture_output=True, text=True, encoding="utf-8", errors="replace",
  306. timeout=5, stdin=subprocess.DEVNULL, env=env, check=False,
  307. creationflags=windows_hide_flags(),
  308. )
  309. except (OSError, subprocess.SubprocessError):
  310. continue
  311. if proc.returncode != 0:
  312. continue
  313. # -z terminates every value with NUL, so the trailing split field is always empty and is
  314. # not a config entry; interior empty fields are real reset markers and must survive.
  315. records = proc.stdout.split("\0")
  316. if records and records[-1] == "":
  317. records.pop()
  318. values.extend(records)
  319. _safe_directory_cache[cache_key] = list(values)
  320. return values
  321. def selected_git_env(base: Mapping[str, str] | None = None) -> dict[str, str]:
  322. """PM's full Git environment, or the original base for system-Git fallback.
  323. Keep lazy acquisition under PM's policy (not just installed-package lookup).
  324. Unsupported targets and failed acquisition must not disable a working system
  325. Git. Callers apply their own config/security isolation after selection.
  326. """
  327. env = dict(base if base is not None else os.environ)
  328. try:
  329. from pm import ensure
  330. return ensure("git", base_env=env).env
  331. except Exception:
  332. return env
  333. def expose_pm_git(project_root: Path) -> None:
  334. """Put PM's git on PATH, and in PM's facts, for a Windows git checkout.
  335. install.ps1 stages the pinned Git for Windows into PM's store for its own
  336. process only, and PM's facts never record it, so every later bare ``git``
  337. (``hermes update``, the source-completion stamp, plugin installs, doctor)
  338. died with ``[WinError 2]``. A git found under PM's store is that unrecorded
  339. copy inherited from the installer, so it is recorded too. Callers are
  340. explicit user actions (like ``ensure_tools_for_sync``), so acquire PM's git
  341. outright; children inherit the PATH. The machine's own git, and a git-less
  342. ZIP install that never runs git, are untouched. Raises what ``pm.ensure``
  343. raises.
  344. """
  345. if sys.platform != "win32" or not (Path(project_root) / ".git").exists():
  346. return
  347. from hermes_platform.resolver import locate_command
  348. from pm.paths import store_root
  349. found = locate_command("git").command
  350. if found and not Path(found[0]).resolve().is_relative_to(store_root()):
  351. return
  352. from pm import ensure
  353. env = ensure("git", explicit=True).env
  354. path = next((value for key, value in env.items() if key.upper() == "PATH"), None)
  355. if path:
  356. os.environ["PATH"] = path
  357. def noninteractive_git_env(base: Mapping[str, str] | None = None) -> dict[str, str]:
  358. """Environment for *internal* git invocations that must never prompt.
  359. Copy of ``base`` (default ``os.environ``) with ``GIT_TERMINAL_PROMPT=0`` (fail instead of
  360. prompting), ``GCM_INTERACTIVE=Never`` (no Git Credential Manager dialog), and isolated git
  361. config: inherited ``GIT_CONFIG_*`` injection, global/system config, pagers, editors, fsmonitor,
  362. external diff and hooks are all disabled so a user's repo/global config cannot hang or mutate
  363. Hermes's plumbing calls. ``core.sshCommand`` is pinned to ``ssh -o BatchMode=yes`` so the ssh
  364. child of a fetch/ls-remote fails instead of prompting — ssh bypasses ``stdin=DEVNULL`` and
  365. opens ``/dev/tty`` directly (#104591); an agent-authenticated ssh still succeeds, and an
  366. explicit user ``GIT_SSH_COMMAND`` env var still takes precedence over this config-layer pin.
  367. ``GIT_ASKPASS``/``SSH_ASKPASS`` env vars are left alone, but OpenSSH BatchMode disables
  368. passphrase/password prompts, including SSH askpass. Usable keys and ssh-agent authentication
  369. still work; Git's own working askpass helper is unaffected. Pair with
  370. ``stdin=subprocess.DEVNULL``. Internal plumbing only — the agent-facing terminal tool has its
  371. own policy layer and visible PTY.
  372. Hermes shells out to git from many non-interactive contexts — MCP catalog installs, plugin
  373. install/update, profile distribution staging, worktree base fetches, desktop review-pane fetch/push.
  374. When the remote is private, misconfigured, or requires auth, git's default behavior is to prompt on the
  375. inherited terminal (or via an askpass helper), which silently hangs the operation until its timeout — or
  376. forever at call sites without one. Ported from openai/codex#34540 / #34612 ("detach non-interactive
  377. subprocesses from stdin"): a background tool invocation must fail fast with a readable error, not wait
  378. for input nobody can type.
  379. """
  380. env = dict(base if base is not None else os.environ)
  381. # Captured before the isolation below rewrites GIT_CONFIG_GLOBAL/SYSTEM to /dev/null --
  382. # reading after that point would resolve the user's config to an empty file.
  383. safe_directories = _user_safe_directories(base if base is not None else os.environ)
  384. env["GIT_TERMINAL_PROMPT"] = "0"
  385. env["GCM_INTERACTIVE"] = "Never"
  386. # Drop caller-supplied config injection; the GIT_CONFIG_COUNT block is rebuilt below so
  387. # ambient -c values cannot re-enable pagers, hooks, fsmonitor, editors or credential prompts.
  388. for key in list(env):
  389. if key == "GIT_CONFIG_PARAMETERS" or key.startswith(_GIT_CONFIG_INJECT_PREFIXES):
  390. env.pop(key, None)
  391. env.pop("GIT_CONFIG_COUNT", None)
  392. env["GIT_CONFIG_GLOBAL"] = os.devnull
  393. env["GIT_CONFIG_SYSTEM"] = os.devnull
  394. env["GIT_CONFIG_NOSYSTEM"] = "1"
  395. env["GIT_PAGER"] = "cat"
  396. env["PAGER"] = "cat"
  397. env["GIT_EDITOR"] = "true"
  398. overrides = list(_GIT_CONFIG_OVERRIDES.items())
  399. # safe.directory is honoured ONLY from global/system config (git rejects it from repo-level
  400. # config so a hostile repo cannot self-authorise), and both are blanked just above. Without
  401. # re-injection every internal git call fails "detected dubious ownership" on any repo whose
  402. # st_uid != geteuid() -- NFS/CIFS mounts without idmapping, shared checkouts, containers with
  403. # a remapped uid -- even though the user's own `git config --global --add safe.directory` is
  404. # correctly set and their interactive git works fine. Carried over the GIT_CONFIG_KEY_n
  405. # channel, which survives GIT_CONFIG_GLOBAL=/dev/null. Read-only and non-widening: the values
  406. # are replayed in git's own effective order, empty reset markers included (see
  407. # _user_safe_directories), so a global reset still revokes a system-wide wildcard exactly as it
  408. # does for the user's interactive git. Appended last, but the hardening overrides above are
  409. # distinct keys, so they are unaffected by ordering within safe.directory.
  410. overrides.extend(("safe.directory", value) for value in safe_directories)
  411. env["GIT_CONFIG_COUNT"] = str(len(overrides))
  412. for idx, (key, value) in enumerate(overrides):
  413. env[f"GIT_CONFIG_KEY_{idx}"] = key
  414. env[f"GIT_CONFIG_VALUE_{idx}"] = value
  415. return env
  416. _FILTER_COMMAND_KEY = re.compile(r"^filter\..+\.(?:clean|smudge|process)$", re.IGNORECASE)
  417. # ``includeIf`` is evaluated against the CURRENT checkout: ``onbranch:`` against the current branch,
  418. # ``gitdir:`` against the current git dir (``.git/worktrees/<name>`` during ``worktree add``), so
  419. # the spawned git can load an include this discovery's ``--includes`` skipped. Every include target
  420. # is therefore read directly, whatever its condition, and its filter names are neutralized too.
  421. # Global/system config is already /dev/null, so only repo-local includes reach this.
  422. _INCLUDE_IF_KEY = re.compile(r"^includeif\..*\.path$", re.IGNORECASE)
  423. # Any include (conditional or not) inside an include target: discovery does not walk it twice.
  424. _INCLUDE_KEY = re.compile(r"^include(?:if\..*)?\.path$", re.IGNORECASE)
  425. # `git config --get-regexp` pattern for the keys discovery reads (filter commands and includes).
  426. _DISCOVERY_KEYS_REGEXP = r"^(filter\..*\.(clean|smudge|process)|include\.path|includeif\..*\.path)$"
  427. # Each include target costs one bounded spawn on every hardened git call; refuse past this many.
  428. _MAX_INCLUDE_TARGETS = 16
  429. # Each discovered key costs two env entries; a repo with tens of thousands of filters would make
  430. # every spawn fail with E2BIG ("Argument list too long"), so refuse past a generous cap.
  431. _MAX_FILTER_KEYS = 256
  432. # Stand-in stderr for a git call refused because filter discovery could not be trusted.
  433. FILTER_DISCOVERY_FAILED = "git filter discovery failed"
  434. def noninteractive_repo_git_env(
  435. cwd: str | os.PathLike[str],
  436. base: Mapping[str, str] | None = None,
  437. ) -> dict[str, str] | None:
  438. """Harden internal git for one repository, including named clean/smudge/process filters.
  439. The static environment can pin fixed config keys such as core.fsmonitor and
  440. core.hooksPath, but a repository chooses filter driver names through .gitattributes.
  441. Discover the effective filter command keys for this checkout and append empty command
  442. overrides plus required=false to the already-isolated config block. Discovery is
  443. bounded and fail-closed: if filter discovery cannot be trusted, callers skip the
  444. automatic git operation instead of running with only partial hardening.
  445. """
  446. env = noninteractive_git_env(base)
  447. # bounded_probe_run, not subprocess.run: Windows' post-timeout communicate() can deadlock and
  448. # a bare spawn flashes a console. (Not bounded_git_probe: rc 1 = "no filters" is a verdict.)
  449. # One probe lists the filter keys and the include paths with their origin file: -z --show-origin
  450. # yields "file:<origin>", "<key>\n<value>" pairs.
  451. proc = bounded_probe_run(
  452. ["git", "-C", str(cwd), "config", "--includes", "--show-origin", "-z", "--get-regexp",
  453. _DISCOVERY_KEYS_REGEXP],
  454. timeout=2, env=env,
  455. )
  456. if proc is None or proc.returncode not in (0, 1):
  457. return None
  458. names: list[str] = []
  459. targets: set[Path] = set()
  460. toplevel: Path | None = None
  461. fields = proc.stdout.split("\0")
  462. for origin, entry in zip(fields[0::2], fields[1::2]):
  463. key, _, value = entry.partition("\n")
  464. if not _INCLUDE_IF_KEY.fullmatch(key):
  465. names.append(key)
  466. continue
  467. if not origin.startswith("file:"):
  468. return None
  469. origin_path = Path(origin[len("file:"):])
  470. if not origin_path.is_absolute():
  471. # git prints repo-local origins relative to the worktree top level, not to *cwd*; with a
  472. # caller-set GIT_DIR/GIT_WORK_TREE they are relative to something else, so refuse.
  473. if env.get("GIT_DIR") or env.get("GIT_WORK_TREE"):
  474. return None
  475. if toplevel is None:
  476. top = bounded_probe_run(["git", "-C", str(cwd), "rev-parse", "--show-toplevel"],
  477. timeout=2, env=env)
  478. if top is None or top.returncode != 0:
  479. return None
  480. toplevel = Path(top.stdout.rstrip("\r\n")) # a checkout path may end in a space
  481. origin_path = toplevel / origin_path
  482. # A relative include path resolves against the directory of the config file naming it.
  483. target = (origin_path.parent / os.path.expanduser(value)).resolve()
  484. if target in targets or not target.exists():
  485. continue # already read, or missing (git skips a missing include file)
  486. if not target.is_file() or len(targets) >= _MAX_INCLUDE_TARGETS:
  487. return None # a FIFO/device/directory, or too many targets to read on every call
  488. targets.add(target)
  489. probe = bounded_probe_run(
  490. ["git", "config", "--file", str(target), "--name-only", "-z", "--get-regexp", _DISCOVERY_KEYS_REGEXP],
  491. timeout=2, env=env,
  492. )
  493. if probe is None or probe.returncode not in (0, 1):
  494. return None
  495. found = probe.stdout.split("\0")
  496. # An include inside an include target would need the same walk again; refuse instead.
  497. if any(_INCLUDE_KEY.fullmatch(name) for name in found):
  498. return None
  499. names.extend(found)
  500. keys: list[str] = []
  501. required: list[str] = []
  502. seen: set[str] = set()
  503. # Dedup on the exact key name git prints: section and variable lowercased, subsection case kept,
  504. # and ``[filter "Evil"]`` is a different driver from ``[filter "evil"]``.
  505. for raw in names:
  506. key = raw.strip()
  507. if not key or key in seen or not _FILTER_COMMAND_KEY.fullmatch(key):
  508. continue
  509. seen.add(key)
  510. keys.append(key)
  511. if len(keys) > _MAX_FILTER_KEYS:
  512. return None
  513. required_key = key.rsplit(".", 1)[0] + ".required"
  514. if required_key not in seen:
  515. seen.add(required_key)
  516. required.append(required_key)
  517. start = int(env["GIT_CONFIG_COUNT"]) # always set by noninteractive_git_env
  518. overrides = [(key, "") for key in keys] + [(key, "false") for key in required]
  519. for offset, (key, value) in enumerate(overrides):
  520. env[f"GIT_CONFIG_KEY_{start + offset}"] = key
  521. env[f"GIT_CONFIG_VALUE_{start + offset}"] = value
  522. env["GIT_CONFIG_COUNT"] = str(start + len(overrides))
  523. return env
  524. def posix_is_zombie(pid: int) -> bool:
  525. """Zombie via ``/proc/<pid>/stat`` field 3, or ``ps -o state=`` without /proc (macOS/BSD)."""
  526. try:
  527. with open(f"/proc/{pid}/stat", encoding="utf-8") as fh:
  528. stat_fields = fh.read().split()
  529. return len(stat_fields) > 2 and stat_fields[2] == "Z"
  530. except FileNotFoundError:
  531. try:
  532. r = subprocess.run(
  533. ["ps", "-o", "state=", "-p", str(pid)],
  534. capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5,
  535. check=False,
  536. )
  537. return r.returncode == 0 and r.stdout.strip().startswith("Z")
  538. except Exception:
  539. pass
  540. except (IndexError, PermissionError, OSError):
  541. pass
  542. return False
  543. def win32_pid_exists(pid: int) -> bool:
  544. """psutil-free Windows liveness probe via OpenProcess/WaitForSingleObject."""
  545. try:
  546. import ctypes
  547. kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
  548. # Pin restypes: default c_int mangles WAIT_* DWORDs into negatives.
  549. kernel32.OpenProcess.restype = ctypes.c_void_p
  550. kernel32.WaitForSingleObject.restype = ctypes.c_uint
  551. kernel32.GetLastError.restype = ctypes.c_uint
  552. PROCESS_QUERY_LIMITED_INFORMATION, SYNCHRONIZE = 0x1000, 0x100000 # SYNCHRONIZE: for Wait*
  553. WAIT_TIMEOUT, ERROR_ACCESS_DENIED = 0x00000102, 5
  554. handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, False, pid)
  555. if not handle:
  556. # ERROR_INVALID_PARAMETER (87): PID definitely gone. ACCESS_DENIED: exists
  557. # but owned by another user/session. Any other error: conservative False.
  558. return kernel32.GetLastError() == ERROR_ACCESS_DENIED
  559. try:
  560. # WAIT_TIMEOUT = still running; anything else = gone.
  561. return kernel32.WaitForSingleObject(handle, 0) == WAIT_TIMEOUT
  562. finally:
  563. kernel32.CloseHandle(handle)
  564. except (OSError, AttributeError):
  565. return False
  566. def pid_exists_stdlib(pid: int) -> bool:
  567. """Stdlib-only "is this PID alive" check that never signals the target (zombies report dead).
  568. For code that must run without the dependency environment: the detached gateway restart
  569. watcher is started by whatever interpreter the updater runs on (the bare store Python after
  570. the package-manager handoff), so it cannot import ``gateway.status`` (``utils`` pulls in
  571. ``ruamel``). ``gateway.status._pid_exists`` prefers psutil and falls back to this.
  572. """
  573. pid = int(pid)
  574. if IS_WINDOWS:
  575. return win32_pid_exists(pid)
  576. if posix_is_zombie(pid): # a zombie still answers os.kill(pid, 0)
  577. return False
  578. try:
  579. os.kill(pid, 0) # windows-footgun: ok — POSIX-only branch (Windows returned above)
  580. except PermissionError:
  581. return True # Exists but we can't signal it.
  582. except OSError: # ProcessLookupError included
  583. return False
  584. return True
  585. def _process_start_time(pid: int) -> int | None:
  586. """The repository's stable process-start fingerprint, if available."""
  587. try:
  588. from gateway.status import get_process_start_time
  589. return get_process_start_time(pid)
  590. except Exception:
  591. return None
  592. def _text_names_hermes(text: str) -> bool:
  593. r"""True when *text* names Hermes at a path-segment / token boundary.
  594. A bare ``"hermes" in text`` substring test would also match unrelated processes whose paths
  595. merely contain the letters (``...\shermesa\...``) — the false-positive class this prevents.
  596. """
  597. return any(token.startswith(("hermes", ".hermes"))
  598. for token in re.split(r"[\\/\s=,;\"']+", text.lower()))
  599. def _process_command_is_hermes(pid: int) -> bool:
  600. """Best-effort check that *pid* currently runs Hermes code."""
  601. try:
  602. import psutil
  603. process = psutil.Process(pid)
  604. command = " ".join(process.cmdline() or [])
  605. executable = process.exe() or ""
  606. return _text_names_hermes(f"{command} {executable}")
  607. except Exception:
  608. return False
  609. def pid_is_hermes(pid: int, *, expected_start_time: int | None = None) -> bool:
  610. """Whether it is safe to use ``taskkill`` for *pid*.
  611. The PID must be valid, currently exist, and identify a Hermes process. When the caller captured
  612. a start-time fingerprint before the destructive action, the live process must still have the
  613. same ``(pid, start_time)`` identity. Any ambiguity fails closed.
  614. """
  615. if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
  616. return False
  617. if not IS_WINDOWS:
  618. if expected_start_time is None:
  619. return True
  620. try:
  621. return _process_start_time(pid) == expected_start_time
  622. except Exception:
  623. return False
  624. try:
  625. current_start_time = _process_start_time(pid)
  626. except Exception:
  627. return False
  628. if current_start_time is None:
  629. return False
  630. if expected_start_time is not None and current_start_time != expected_start_time:
  631. return False
  632. try:
  633. return _process_command_is_hermes(pid)
  634. except Exception:
  635. return False
  636. def kill_process_tree(proc: subprocess.Popen, *, grace: float = 0.0) -> None:
  637. """Best-effort terminate *proc* and its descendants on both platforms; never raises.
  638. ``grace`` > 0 (POSIX): SIGTERM the tree first and SIGKILL only if *proc* outlives ``grace``
  639. seconds, so a git can delete its lock and tmp files on the way out (Windows always forces);
  640. when *proc* exits in time, what is left of the group it leads is SIGKILLed.
  641. ``proc.kill()`` alone only terminates the direct child. This is cleanup on an already-failing
  642. path whose contract is to fail open, so every failure (access denied, already reaped) is
  643. swallowed rather than escaping the caller's ``except``.
  644. On Windows a suspended descendant (e.g. ``git.exe``) can survive holding duplicates of the captured pipe
  645. handles, which keeps the pipes from reaching EOF and leaks two reader threads + the process per fired
  646. timeout — ``taskkill /T /F`` takes the whole tree down so the bounded drain that follows can actually
  647. reach EOF. On POSIX the same class exists: killing the launcher leaves descendants (credential helpers,
  648. ``git-remote-https``, hook children) running and holding the pipe write ends. Callers spawn the child in
  649. its own process group (``process_group=0``, Python ≥3.11), so when — and only when — the child leads its
  650. own group (``pgid == pid``), the entire group is signalled with ``os.killpg``. The ownership check means
  651. a fallback spawn that shares our group can never cause us to kill unrelated processes. Ported from
  652. openai/codex#36793 ("Terminate timed-out Git process trees"); generalized for the shell-hook runner via
  653. openai/codex#37527 ("Terminate timed-out hook process trees").
  654. """
  655. try:
  656. from agent.deadline import kill_process_tree as _deadline_kill_tree
  657. if grace > 0 and not IS_WINDOWS:
  658. import signal as _signal
  659. try:
  660. leads_group = os.getpgid(proc.pid) == proc.pid
  661. except ProcessLookupError:
  662. leads_group = False
  663. _deadline_kill_tree(proc.pid, sig=_signal.SIGTERM)
  664. try:
  665. proc.wait(timeout=grace)
  666. except subprocess.TimeoutExpired:
  667. pass
  668. else:
  669. # The leader went on TERM; a group member that ignores it would outlive us. The
  670. # pgid stays reserved while any member lives, so this reaches only that group.
  671. if leads_group:
  672. try:
  673. os.killpg(proc.pid, _signal.SIGKILL) # windows-footgun: ok — POSIX-only branch
  674. except ProcessLookupError:
  675. pass
  676. return
  677. _deadline_kill_tree(proc.pid)
  678. except Exception:
  679. _legacy_kill_process_tree(proc)
  680. return
  681. # Ensure Popen's own bookkeeping sees the exit so communicate()/wait() cannot hang.
  682. try:
  683. proc.kill()
  684. except OSError:
  685. pass
  686. def _legacy_kill_process_tree(proc: subprocess.Popen) -> None:
  687. """Local tree-kill fallback when agent.deadline is unavailable (partial install, cycle)."""
  688. if not IS_WINDOWS:
  689. # Verify the child leads its own process group before signalling, never a shared group.
  690. try:
  691. import signal as _signal
  692. pgid = os.getpgid(proc.pid)
  693. if pgid == proc.pid:
  694. os.killpg(pgid, _signal.SIGKILL) # windows-footgun: ok — inside `if not IS_WINDOWS` gate
  695. except Exception:
  696. pass
  697. try:
  698. proc.kill()
  699. except OSError:
  700. pass
  701. if IS_WINDOWS:
  702. # No identity guard on purpose: *proc* is our own retained Popen handle, so the PID cannot
  703. # be recycled while we hold it. The fail-closed ``pid_is_hermes`` guard is for BARE pids.
  704. try:
  705. subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)],
  706. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  707. stdin=subprocess.DEVNULL, timeout=2, check=False,
  708. creationflags=windows_hide_flags())
  709. except Exception:
  710. pass
  711. def bounded_probe_run(
  712. argv: Sequence[str], *, timeout: float, errors: str = "replace",
  713. env: Mapping[str, str] | None = None, cwd: str | os.PathLike[str] | None = None,
  714. raise_on_spawn_failure: bool = False, input: str | None = None,
  715. ) -> subprocess.CompletedProcess[str] | None:
  716. """Deadlock-safe ``subprocess.run(argv, capture_output=True, timeout=…)`` for fail-open probes.
  717. ``input`` is written to the child's stdin (closed afterwards); without it stdin is ``DEVNULL``.
  718. Returns a ``CompletedProcess`` when the child finished within *timeout* (any exit code), or
  719. ``None`` on spawn failure or timeout. With ``raise_on_spawn_failure=True`` the ``Popen``
  720. exception propagates instead, so callers that treat a *timeout* as a verdict can still tell
  721. "our own probe never started" apart from "the child hung".
  722. Why not ``subprocess.run``: on Windows, ``run()``'s post-timeout cleanup calls an *unbounded*
  723. ``communicate()`` after killing the direct child. Killing it can leave a descendant (``git.exe`` under a
  724. launcher shim, ``conhost.exe`` under wmic/powershell) holding duplicates of the captured stdout/stderr
  725. handles, so the pipes never reach EOF and the reader-thread join blocks forever. The wmic /
  726. ``Get-CimInstance Win32_Process`` gateway scan hit exactly this during ``hermes update`` on slow-WMI
  727. machines (#87134); the git probes hit it first (#68609 / #66037).
  728. """
  729. # detached-spawn: ok — awaited probe; a timeout or failure tree-kills its group (kill_and_drain)
  730. _popen_kwargs: dict = {"creationflags": windows_hide_flags()} if IS_WINDOWS else {"process_group": 0}
  731. job = None
  732. try:
  733. # Windows: contain the probe in a Job Object. `taskkill /T` walks LIVE parent pids, and a
  734. # Cygwin/MSYS `exec` lets the forked stub exit once the new image runs, so a Git Bash grandchild
  735. # (`sleep`, `cat`) has a dead parent and survives the tree-kill holding our pipes (#73403, proven
  736. # on windows-latest). KILL_ON_JOB_CLOSE reaches it regardless of ancestry.
  737. from hermes_cli.local_runtime.processes import spawn_server
  738. proc, job = spawn_server(
  739. list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  740. stdin=subprocess.DEVNULL if input is None else subprocess.PIPE,
  741. text=True, encoding="utf-8", errors=errors,
  742. env=dict(env) if env is not None else None, cwd=cwd, **_popen_kwargs)
  743. except Exception:
  744. if raise_on_spawn_failure:
  745. raise
  746. return None
  747. try:
  748. stdout, stderr = proc.communicate(input=input, timeout=timeout)
  749. except Exception:
  750. # Timeout OR any other communicate() failure (torn-down pipe, decode error): tree-kill and
  751. # drain bounded — leaving it running would leak the suspended-descendant class this guards.
  752. _close_job(job)
  753. kill_and_drain(proc, 1)
  754. return None
  755. # The probe exited on its own; anything it left behind (`&` jobs) goes with the job.
  756. _close_job(job)
  757. return subprocess.CompletedProcess(list(argv), proc.returncode, stdout, stderr)
  758. def kill_and_drain(proc: subprocess.Popen, seconds: float) -> tuple | None:
  759. """Tree-kill *proc* (:func:`kill_process_tree`), then read what its pipes still hold for at
  760. most *seconds*: ``(stdout, stderr)``, or ``None`` when a descendant the kill missed still
  761. holds them. Those pipes are left to ``communicate()``'s reader threads, never closed
  762. (closing a pipe a thread is reading blocks; a ``with Popen`` exit would close them)."""
  763. kill_process_tree(proc)
  764. try:
  765. return proc.communicate(timeout=seconds)
  766. except (OSError, ValueError, subprocess.SubprocessError):
  767. proc.stdin = proc.stdout = proc.stderr = None
  768. return None
  769. def _close_job(job) -> None:
  770. if job is None:
  771. return
  772. try:
  773. job.close()
  774. except Exception:
  775. pass
  776. def bounded_git_probe(argv: Sequence[str], *, timeout: float, env: Mapping[str, str] | None = None) -> str:
  777. """Run a short ``git`` probe and return stripped stdout, or ``""`` on ANY failure.
  778. On Windows ``run()``'s post-timeout cleanup calls an unbounded ``communicate()``; a suspended
  779. descendant git.exe holding the pipe handles then blocks forever. Here: bounded ``communicate``,
  780. tree-kill plus a 1s drain, then abandon the pipes; on POSIX the probe gets its own process
  781. group so cleanup also takes down credential/remote helpers.
  782. Security (GHSA-7x36-8jrh-v4pw): these probes run automatically against whatever directory the
  783. session sits in, before any tool call or trust prompt, and an index refresh executes the
  784. repo-configured ``core.fsmonitor`` program. Every probe therefore runs under
  785. :func:`noninteractive_git_env`; diff-rendering callers additionally pass
  786. :data:`NO_DRIVER_DIFF_FLAGS` (attribute-scoped drivers can't be disabled via env).
  787. Killing the PATH-resolved launcher can leave a suspended descendant ``git.exe`` holding duplicates of
  788. the captured stdout/stderr handles, so the pipes never reach EOF and the reader-thread join blocks
  789. forever. On the Desktop agent-build path (``_start_agent_build → _session_info → branch() → run_git``)
  790. that turned an optional branch label into ``agent initialization timed out`` (issues #68609 / #66037).
  791. The normal-path spawn contract mirrors the previous ``run`` call byte-for-byte: PIPE/PIPE/DEVNULL,
  792. ``text`` with UTF-8 ``errors="replace"`` decoding, and the hidden-window ``creationflags`` on Windows
  793. only. On POSIX the probe is additionally placed in its own process group (``process_group=0``, Python
  794. ≥3.11) so timeout cleanup can take down descendants — credential helpers, ``git-remote-https``, hook
  795. children — with the launcher instead of orphaning them (see :func:`kill_process_tree`; port of
  796. openai/codex#36793). ``process_group`` only changes which group the child belongs to; it does not detach
  797. the terminal or alter the fast path.
  798. """
  799. result = bounded_probe_run(argv, timeout=timeout, env={**(env or noninteractive_git_env()), **NO_LAZY_FETCH_ENV})
  800. if result is None or result.returncode != 0:
  801. return ""
  802. return (result.stdout or "").strip()