`hermes chat` starts check_for_updates in a daemon thread. On an official
source checkout (stable by default since 6a92a2aa49) it verifies the
release tag with `git ls-remote --tags origin`, which forks
`git remote-https`. Spawned with a plain subprocess.run, it shared the
CLI's process group and nothing owned it: a /exit while GitHub was slow
abandoned the thread, and git + its helper reparented to init (the 0.23.2
release E2E caught them, test_terminal_transcript_pty[cli-turns]). Its
60s timeout also killed only git, not the helper.
Both remote-touching probes (the stable tag check and _branch_tip's
ls-remote) now go through source_check.remote_git_run ->
bounded_probe_run(owned=True): own process group, handed to the
owner-death supervisor while it runs, the whole group killed on timeout.
The PTY harness sandbox now sets updates.check: false, as tui_pty's
does: the attached `gateway run` (which outlives /exit by design) runs
the same check, and the E2E must not talk to real GitHub.
Tests and callers substitute their own worker controls; the event that ends the forwarder belongs
to the turn that started it, not to the controls object.
On POSIX the watcher waits with no deadline for the old gateway to exit, checking only that its
PID exists, so a PID reused between polls held it on an unrelated process forever. The parent now
records the old process's start time when it arms the watcher, and the watcher stops waiting once
the PID is gone or belongs to a different process. The watcher source moves to its own module to
keep gateway.py under its size cap.
Every retired shim called stop_for_relaunch() unconditionally, so a current-tree
caller (a plugin, a serve/dashboard/gateway, main.__getattr__'s lazy export)
reaching one ran the whole update-finish takeover: dependency sync, desktop
rebuild, gateway restart, backend kill -- and the restarted process could reach
the shim again (#122656). lazy_deps.install_specs and psutil_android's import
were already gated on in_historical_update(); the other 60 shims were not.
One shared gate, _old_updater.stop_historical_updater(hook, error): hands off
exactly as before when a historical updater entrypoint frame is on the stack
(or the process already handed off and is unwinding), otherwise raises a
catchable error (ImportError for installer-shaped shims, matching
install_specs; RetiredUpdaterHook otherwise). install_specs now uses it too.
main._write_update_incomplete_marker resolves to a gated old_updater_deps shim
instead of aliasing stop_for_relaunch. Every frozen-surface name is retained.
Fixes#124881Fixes#122656
With the repository's filter commands emptied, `git status` and `git diff`
hash the raw bytes and store that stat refresh in `.git/index`. A file that
differs from HEAD only through its clean filter (git-crypt or LFS adopted on
an already-committed file) then dropped out of the user's own `git status`
after `/diff`, `@diff` or a dashboard view, and the dashboard's `add -A`
skipped it.
When at least one filter key is emptied, set GIT_OPTIONAL_LOCKS=0 and
diff.autoRefreshIndex=false so these read-only calls leave the index alone.
Repositories without filters keep today's refresh.
Co-authored-by: BearHuddleston <bear@bearhuddleston.dev>
An exported GIT_DIR/GIT_WORK_TREE (dotfiles alias, git hook) retargets every
`git -C <checkout>` at the user's other repo, so an installer rerun stashed and
reset that repo, and the plugin foreign-checkout guard passed because GIT_DIR
disables discovery. install.sh unsets the location vars in the repository and
complete stages (subshells); install.ps1 clears and restores them around the
same stages; noninteractive_git_env drops them for every internal git call.
install.ps1 also builds the probe ceiling from the link-resolved InstallDir
without a trailing separator, matching install.sh's `pwd -P`.
Fixes#146032
The check flagged start_new_session (keyword or dict key) and os.setsid/setpgid/setpgrp, but not
Popen's process_group= keyword, which also puts the child in a group of its own, nor the
item-assignment shape kwargs["start_new_session"] = True. Seven production sites used those shapes
unmarked, so "a new detached spawn can't bypass it" was not true. All three shapes now count for
both keywords (process_group=None, the default, does not).
The six sites it now finds are all awaited with a group-killing timeout or run a gateway restart
that must not share the updater's group; each gets a `detached-spawn: ok` marker with that reason
(shell hooks, the Windows-safe probe runner, update steps, git repack, the two update recovery
restarts). The seventh is in update_custody's embedded watchdog script, a string the AST never sees.
Tests: the four new shapes are flagged and process_group=None / start_new_session=False items are
not; the new cases fail on the prior checker.
A child started in its own session or group (start_new_session, os.setsid /
setpgid / setpgrp, windows_detach_popen_kwargs) does not die with a SIGKILLed
Hermes: it reparents to init and runs forever. That is how every family this PR
migrates leaked. With the families on spawn_owned, this keeps the class closed.
scripts/check_detached_spawns.py (AST) flags those shapes in the production trees
unless the line, or the line above it, says `detached-spawn: ok — <why>`. It runs
in scripts/check ("detached-spawns") and as a blocking lint.yml step. The baseline
is empty: every remaining site is on spawn_owned / own_process_groups, or carries
its reason. The reasons this commit adds are the census verdicts:
- must outlive the starter on purpose: restart watchers, /update and the updater
hand-offs, dashboard/desktop/service launches, cron and kanban workers
(restart-safe), the update-custody watchdog itself;
- awaited with a group kill on timeout: cron scripts, rg search, the Browser Use
CLI, update completion (holds the checkout lock fd);
- covered by its own parent guard: the compute host (compute_host._parent_guard_loop
flushes sessions; a supervisor KILL could cut that short);
- not a spawn: the wake-word `start_new_session` config key and event field.
tests/scripts/test_check_detached_spawns.py: each shape flagged, non-detached and
commented/string shapes not, the marker opts out on its line or the line above
and nowhere else, tests and the helper are out of scope, main() fails on a new
unmarked spawn, and the repository scan is empty. Teeth: appending an unmarked
start_new_session Popen to tools/file_operations_search.py turns
`scripts/check --only detached-spawns` red (rc 1); restoring it turns it green.
Every cache keyed on a file's stat signature had the bug the config caches had: a same-size
in-place rewrite in one coarse timestamp tick keeps mtime, ctime, size and inode, so the older
parse was served for the rest of the process. Move the helper to utils.file_cache_version
(file_signature + content digest while the file is under 2 s old; always_digest for signatures
compared much later, where the racy digest going empty would read as a change) and key every
cache that can hold a secret, token, pairing/allowlist, route or config on it:
- auth.py: global auth-store memo, Nous auth-status memo (was mtime only)
- gateway/pairing.py approved-users cache (a revocation kept access)
- run_profile_reconcile: served-profile signature (always_digest: a false change reconnects
adapters) and the hook-consent signature
- webhook dynamic routes (route HMAC secrets), Feishu comment pairing/rules cache (mtime only)
- MCP OAuth tokens-file reload check (mtime only; always_digest: a reload tears the session down)
- config parse-failure record (always_digest), named-custom-provider memo, model aliases,
gateway.standalone memo, profile model read, MoA preset, agent raw config,
tui_gateway raw config cache, onboarding due stamp, free-tier inventory stamp,
provider model-list credential fingerprint, git safe.directory key, skills prompt
manifest
config_cache_version takes its stat through config_version, so its errors and seams are unchanged.
Left alone: the tool-definition cache key and the platform manifest stamp (a safe worker must
never open config.yaml or a plugin file; the MoA preset cache is skipped in one instead) and the
CLI MCP watcher seed (pinned to file_signature by a main test).
Review round on the commit-graph refresh (Greptile + re-review):
- Global graph setting is ignored: core.commitGraph=false is read with the
user's global/system git config, which the writer's isolated env blanks.
- Expired slots allow duplicate writers: check and claim of the maintenance
slot run under one flock/msvcrt lock on the slot file, which is never
unlinked; a failed spawn gives back only a claim holding its own pid.
- Linked worktrees and submodules (a .git file) were skipped: the common git
dir is resolved once (update_lock._git_common_dir) and used for the object
store, slot, debris sweep and fresh stamp, on the update spawn and on the
`hermes -w` pass alike.
- Timeouts were silent: the kill is logged at WARNING, with the timeout
unrounded.
- kill_process_tree(grace>0) returned once the leader exited on SIGTERM,
orphaning a group member that ignores it: the rest of the group it led is
SIGKILLed. grace=0 is unchanged.
- The child's failure line was lost when <home>/logs did not exist: the log
dir is created at failure time via mkdir_under_hermes_home (a deleted
profile is not resurrected), and a log that cannot be opened no longer
raises out of the logger.
Review round on #144647 (head d016f04694d):
- CI routing: the refresh (slot claim, bounded runner, stale check, detached spawn) moves to
hermes_cli/git_commit_graph.py, routed to e2e_upgrade with the update pipeline. The update path
imports it instead of all of worktree_ops; worktree_ops keeps its repack seams and imports the
shared slot claim and runner from it (no cycle).
- W1: the -w pass runs in whatever repo it was launched from, so its refresh sweeps only the
object-store locks (clear_stale_git_locks(names=OBJECT_STORE_LOCK_NAMES)); index.lock / HEAD.lock
there belong to the user's git. The install checkout's update sweep is unchanged.
- W2: timeout/exit reaping SIGTERMs the git tree first and SIGKILLs only after a 5 s grace
(kill_process_tree(grace=), default unchanged for every other caller), so git deletes
commit-graph-chain.lock and tmp_graph_*. The age-gated tmp sweep now also takes
objects/info/commit-graphs/tmp_graph_*.
- N1: a breakaway-forbidding Windows job gets the no-breakaway retry, and a spawn that fails gives
the 6 h slot back.
- N2: the detached child logs a failed write (git's fatal line) to the home's agent.log/errors.log.
- core.commitGraph=false in the target repo skips the write.
- N3: a successful no-op write stamps hermes-commit-graph.fresh, so an idle repo is not rewritten
every slot.
- N4: test_update_finish's completion child and every in-process hermes_cli test stub the
detached spawn; no writer outlives a test run.
- Greptile: the refresh test now runs on a treeless clone over a Bloom graph and asserts the
write adds no pack (red when --no-changed-paths is dropped).
`update_custody.run` (a timed-out Windows update child) re-implemented the tree kill and the
bounded pipe drain of `_subprocess_compat.bounded_probe_run`: its own `taskkill /T /F` copy of
`kill_process_tree`, then `communicate()` bounded, abandoning pipes a missed descendant still
holds. Both now call `kill_and_drain`. It stays correct for the job-bound child: the tree kill
never touches the update's job (which also holds the update's other children), the drained
output still rides on the re-raised TimeoutExpired, and abandoned pipes are detached so the
`with popen()` exit never closes a pipe a reader thread is blocked on. The probe keeps closing
its own private job first.
Tests: test_a_timed_out_child_never_waits_on_a_grandchild_holding_its_pipes and
tests/hermes_cli/test_bounded_probe_run.py (unchanged) pass. (kshitijk4poor review)
What: git_pack_tidy's `pack-objects --stdin-packs` merge (main a0f47657b9) now goes through
update_custody.run_git, and `pack-objects` is a LOCAL_MUTATOR: it holds the checkout lock fd, and
inside an update on Windows it is job-bound. A timeout or spawn failure still reads as out of time;
a custody refusal propagates like every other updater git's. bounded_probe_run loses the
`popen_kwargs` parameter this branch added for the gc fold, which #132927 removed; nothing passes it.
Why: the tidy replaced the gc fold this branch had put in custody, and arrived as a bare git
spawned during `hermes update` under the update lock. It writes a pack the update then moves into
the object store; outside custody a killed update could leave it writing into
hermes-tidy-staging after the lock is free, and on Windows it was outside the update's job.
The tidy only runs under the lock (main.py acquires UpdateLock before _cmd_update_impl), so on
Windows it always takes custody's bounded drain, not the bare subprocess.run timeout cleanup
bounded_probe_run exists to avoid (#68609).
Red: test_merges_down_to_the_target_into_one_pack_whatever_the_size_limit saw custody spawn only
[('config', False), ('config', False)]. Green: pack tidy, custody, bounded probe, build stamp and
no-window-flag suites, 45 passed.
m3: installer checkouts are partial clones, so a move (reset --hard, merge
--ff-only, checkout) lazily fetched the target's missing objects as a child
holding the checkout lock fd, with the user's credential helper; a
credential-cache daemon it started held the checkout for its lifetime.
Mutators now run with -c credential.helper=, and before a move run_git
fetches what it will read (git diff <HEAD or empty tree> <target>) without
the fd and with the helpers, so a private fork still authenticates.
m4: consolidate_lazy_fetch_packs ran gc --auto with neither the fd nor a
death signal; gc/repack/pack-objects outlived a killed owner and repacked
under the next one. gc (it packs refs) is a local mutator and its bounded
runner gets run_git's custody via update_custody.spawn_kwargs (POSIX: the
lock fd its children inherit). pull is dropped from LOCAL_MUTATORS (unused;
its network half must not hold the fd). The module doc names the exception
and the read-only source_releases/source_check readers.
The convert-first step runs in the bootstrap interpreter, which cannot import
update_cmd (ruamel), so it carried its own raw os.environ copy (the spawn-env
guard flagged it) and lacked the Windows console-hide flags (#117781).
Move the body unchanged to _subprocess_compat.no_prompt_git_kwargs: prompts
off, credential helpers kept, consoles hidden. update_cmd keeps the
_no_prompt_git_kwargs name as an import because old updaters load it after
the checkout swap (tests/compat/old_updater_surface.json); existing callers
are untouched.
Each `hermes update` now spends at most 60 s on the on-demand packs a
partial clone piles up (#129712), and every finished unit is kept, so a
large checkout converges over a few updates instead of blocking one
update for 20+ minutes:
1. Erase on-demand packs (empty .promisor marker, older than an hour)
that hold no commits. Their objects are copies of what the promisor
remote serves; git fetches what it needs again. This frees disk,
which the old gc fold never did. A pack holding commits is kept
because a ref may point into it; a pack git cannot classify in time
counts as holding one.
2. While more than 50 promisor packs remain, merge the smallest few
with `git pack-objects --stdin-packs` (cost proportional to those
packs, no reachability walk), marker first and index last so the
merged pack is a promisor pack from the moment git sees it.
Verdicts and a merge batch size that halves after a timed-out merge are
remembered in .git/hermes-pack-tidy.json, so no update repeats work an
earlier one could not finish. bounded_probe_run gains `input=` for
stdin-fed git commands.
r2 gate: Path(stdout.strip()) dropped a trailing space in the checkout path, so include
targets resolved to a missing file and were skipped. With a caller-set GIT_DIR or
GIT_WORK_TREE git prints origins relative to another base; refuse instead of guessing.
Gate follow-ups for the includeIf walk: git prints repo-local origins relative to the
worktree top level, so discovery from a subdirectory looked for the target in the wrong
place and skipped it (fail open). Resolve relative origins against `rev-parse
--show-toplevel` (one extra spawn, only when an include is present). Read each target once,
refuse a non-regular target (FIFO/device/directory) and more than 16 targets, so a repo
cannot make every hardened call spawn without bound. One discovery-regexp constant and a
single include-key matcher.
Filter discovery refused every repository with a repo-local includeIf, so `hermes -w`,
kanban/subagent worktrees and the recovery hint stopped working inside actions/checkout
checkouts (which write an includeIf credential include) and similar setups. Read each
includeIf target directly, whatever its condition, and neutralize the filter commands it
defines alongside the ones found through --includes. One probe now lists both the filter
keys and the include paths (with --show-origin, so relative paths resolve against the file
that names them). A missing target is skipped as git skips it; an include nested inside an
include target, an unreadable target or a non-file origin still refuses.
bounded_probe_run returns a CompletedProcess from communicate() with
text=True, so stdout is always a str once proc is not None; the
`or ""` guard could never fire. GIT_CONFIG_COUNT is always written by
noninteractive_git_env (it pops any caller value and sets
str(len(overrides))), so the defensive `.get(..., "0") or 0` parse
only hid that invariant.
Three gaps in noninteractive_repo_git_env, two probe-verified:
- Dedup was on key.lower(), but git keeps the subsection's case:
[filter "evil"] + [filter "Evil"] with `filter=Evil` overrode only the
lowercase driver and the hostile smudge ran. Dedup on the exact name
`git config --name-only` prints.
- Only includeIf "onbranch:" failed closed. includeIf "gitdir:<repo>/.git/
worktrees/" matches the new worktree's git dir during `worktree add`, so it
loads a filter discovery never saw. Refuse on ANY repo-local includeIf
(global/system config is already /dev/null).
- The discovery probe used subprocess.run(timeout=2), which on Windows can
deadlock in the post-timeout communicate() and flashes a console. Use
bounded_probe_run (rc 1 = "no filters" stays a verdict, so not
bounded_git_probe).
Also share the refusal stderr as FILTER_DISCOVERY_FAILED across the kanban
and worktree-gc call sites and the test, and fold the fail-closed test into
the filter test (shared repo/env helpers) with case_collision and
gitdir_include rows.
Every discovered filter key adds GIT_CONFIG_KEY/VALUE env entries. A repository
with tens of thousands of filter sections makes the spawned git fail with
OSError(7, "Argument list too long") inside kanban/worktree-gc `_git`, which do
not expect it. Past 256 keys, fail closed like any other untrusted discovery.
One parametrized invariant covers both fail-closed paths (onbranch include and
filter flood) through the kanban `worktree add` call.
Fixes#126017
noninteractive_repo_git_env discovers repository-named filter keys with
`git config --includes`, which evaluates includeIf "onbranch:..." against the
branch checked out NOW. A `worktree add -b X` then checks out X, git loads the
X-only include, and its smudge filter runs with no override pinned. Any
onbranch include in the effective config means the inventory cannot be trusted,
so return None and let callers skip the automatic git call.
Refs #126017
The session-start workspace snapshot runs git status, which re-hashes a
re-timestamped file through the repo-named clean filter, and a delegated
subagent's worktree add runs the smudge filter. Both now use
noninteractive_repo_git_env and skip the call when filter discovery fails.
(cherry picked from commit 04170a83d19a026fe6c5f968ce6e61b61f53c418)
A repository names its clean/smudge/process filter drivers in .gitattributes, so the
fixed GIT_CONFIG_KEY pins in noninteractive_git_env cannot enumerate them. Discover the
checkout's filter command keys under the isolated env and append empty command overrides
plus required=false. Discovery failure returns None so callers skip the git call.
Ported from #126075.
(cherry picked from commit ebdb7feb263512a2e76f06d9ee20d483af6adc24)
A console-less parent (pythonw backend, detached daemons) allocates a visible
console per bare spawn, so Windows startup flashes ~7-8 console windows
(#117781) and the GPU statusbar flashes two more every 5s (#101895). Threads
creationflags=windows_hide_flags() through every hermes_cli spawn site the
desktop reaches: gitlock (tasklist probe + git plumbing), the scheduled-task
PowerShell probe, the updater's _git_run/_no_prompt_git_kwargs/_GIT_TEXT_KW
runners, the safe-directory config probe, and consolidates the statusbar's two
nvidia-smi reads per poll into one cached hidden query. The statusbar also
stops polling while the document is hidden and resumes on visibilitychange
(#120262).
Supersedes #117805, #117833, #102047, #120285 (thanks @JoaoMarcos44, @Finn763,
@monerostar, @szzhoujiarui).
After the package-manager handoff, hermes update finishes on the bare store
interpreter and spawns the detached restart watcher as sys.executable -c.
The watcher imported gateway.status (utils -> hermes_yaml -> ruamel) and
hermes_cli.config, died with ModuleNotFoundError before relaunching, and
left every manually started gateway down after the update (gated on #124649).
Move the stdlib liveness probe (zombie-aware POSIX kill(0), Windows
OpenProcess) into hermes_cli._subprocess_compat, have gateway.status's
fallback delegate to it, and import only stdlib-backed modules in the
watcher.
Fixes#124649.
A git-less Windows ZIP install has no .git and never runs git, yet
_prepare_git_command called expose_pm_git() before it checked
use_zip_update: offline or with no pin, pm.ensure raised and aborted an
update that never needed git. expose_pm_git now takes the project root
and does nothing unless it is a git checkout (both callers).
When install.ps1 runs as one process, the git it staged into PM's store
is on the inherited PATH, so expose_pm_git returned early and PM's facts
never recorded it; plain hermes processes (plugin git installs, doctor,
version info) had no git until the first `hermes update`. A git found
under PM's store is now treated as that unrecorded copy and ensured, so
the source completion writes the git fact at install time.
Co-authored-by: JoaoMarcos44 <joaomarcosdias444@gmail.com>
expose_pm_git() probed with a bare shutil.which, which the managed-runtime
resolution guard rejects outside hermes_platform/. Route the lookup through
hermes_platform.resolver.locate_command instead.
On a Windows machine with no git, scripts/install.ps1 stages the pinned Git
for Windows into the pm store for its own process only, and pm's facts
never record it. Every later product process that ran a bare `git` failed:
- `hermes update` died before its first step:
"✗ Update failed: [WinError 2] The system cannot find the file specified"
- the source completion that finishes an installer re-run or an update
found no commit, deleted the install stamp, and the next boot wrote an
adoption stamp that names no commit. It also printed
"Could not refresh release history ([WinError 2] ...)".
expose_pm_git(): when Windows resolves no git, ensure PM's git explicitly
(both callers are user-initiated, like ensure_tools_for_sync) and put its
composed PATH (cmd and usr\bin) on the process, so children inherit it.
The update calls it before its first git, and the source completion calls it
before its builds and stamp. A machine with a working git is untouched.
main_desktop already ensures PM's git for its build for the same reason.
Conflict resolutions and semantic fixups:
- utils.py / hermes_yaml.py: main widened ruamel's round-trip emitter so a long
double-quoted scalar is never folded after an escaped backslash. pm-clean builds
every rt emitter through hermes_yaml.roundtrip_yaml(), so the width lives there
(ROUNDTRIP_YAML_WIDTH moves with it); xai_retirement imports it from hermes_yaml.
- hermes_cli/banner.py: keep pm-clean's removal of the banner update check. Main's
GIT_NO_LAZY_FETCH fix for it applies to its replacement, source_check: every
read-only probe (source_git_env) now refuses promisor lazy fetches, and the
partial-clone test targets that probe (red without the flag).
- .github/workflows/tests.yml: keep setup-pm; main's uv pin bump does not apply.
Main's WAL-capable SQLite gates are kept, run against $HERMES_PYTHON (the
PM-pinned interpreter, SQLite 3.53.1). The e2e step takes main's
--include-integration invocation.
- apps/desktop: package.json has no build block here, so main's macOS locale-marker
restore joins the darwin branch of the existing after-pack.mjs, and its test
loads the hook from electron-builder.config.cjs and imports PlatformPackager
from app-builder-lib's root (electron-builder 27 exports no ./out paths). The
win32 row is dropped: this hook sanitizes and signs PE trees on win32 by design.
- reconciliation.ts: main's rowId hydration (#119326) was merged into the first of
pm-clean's split helpers only; the resolver is now one helper both halves use.
- en.ts: both sides' keys kept. tests/tools/test_lazy_deps.py stays deleted.
- Tests main added with `import yaml` use hermes_yaml, like the rest of the tree.
In a partial (blobless/treeless) clone, the passive update check's
`git merge-base --is-ancestor <fresh upstream tip> HEAD` asked about an
object the clone had never fetched, so git spawned `git fetch` from the
promisor remote to download it (~233k objects for a real install, no
negotiation). The 5 s probe timeout killed only the merge-base process;
the fetch child kept running orphaned and left partial packs behind, on
every launch.
Every banner git probe and every `bounded_git_probe` (session-start
coding context, TUI gateway branch/root probes) now runs with
GIT_NO_LAZY_FETCH=1 (NO_LAZY_FETCH_ENV). A missing object makes the probe
fail fast; the ancestry check then falls through to the compare API, which
is already the path for tips not in local history. `hermes update` keeps
lazy fetch: its checkout/merge legitimately needs missing blobs.
Resolved toward the branch: PM provisions uv/python (main's install.ps1 uv-shim
salvage + its test and workflow steps dropped), the shim re-exec stays retired,
package.json carries no electron-builder block (afterExtract identity stamp wired
into electron-builder.config.cjs instead; after-pack.mjs keeps signing only),
Desktop workspace-deps helpers stay retired. Main's scratch-dir bootstrap
(export_scratch_tmp_env) is taken and re-run after profile resolution.
On windows-latest (wine2e run 35430217919) the MSYS `sleep` grandchild of the
bash probe survived kill_process_tree: taskkill /T walks live parent pids and a
Cygwin exec lets the forked stub exit once the new image runs, so the grandchild
had a dead parent and kept the captured pipes open — the #73403 pipe-holder.
bounded_probe_run now spawns through local_runtime.processes.spawn_server
(Job Object, KILL_ON_JOB_CLOSE, no breakaway) and closes the job on timeout and
after a normal exit. POSIX path unchanged (spawn_server returns a plain Popen).
Reconcile plugin declarations and validation through PM's atomic generation publication; preserve external runtimes, target markers, and conflict refusal. Keep one source-update completion owner and port upstream lifecycle changes to the PM desktop/runtime paths.
bounded_probe_run collapses spawn failure and timeout into one None, so a venv
interpreter that exists but cannot be executed (PermissionError, ENOEXEC, fork
failure) was reported as "timed out before reporting import health" -- a bogus
warning on the git path and sys.exit(1) on the ZIP path -- and the
`except OSError: return {}` branch beneath it was dead. Let the Popen error
propagate (opt-in flag, default unchanged for the other probes) so "we could not
run our own probe" says nothing about the checkout and no longer blocks the
update, while a spawned child that hangs is still a verdict.
Restores the non-fatal test the earlier rewrite dropped, now driving the real
bounded_probe_run/Popen: red on the previous head, green here.
Review finding: spawn failure of the import probe reported as a fatal timeout.
Delete consumer-side Git discovery caches and layout reconstruction. Share the selected environment while preserving PM acquisition policy, system Git fallback and downstream config isolation. Route Matrix binding through its existing dependency operation and explicit setup through sync_venv.
Real Git regression tests cover absent ambient PATH, changed selection, unsupported target and failed acquisition. Independent final review: 100 focused tests pass, including malicious Git config and Matrix setup contracts. Native Windows execution was not run.
Tests: fold the ambient GIT_CONFIG_KEY_n negative and the isolation-still-in-force
assertions into the ordering test, and drop the two positive-only cases it subsumes.
What remains pins the injected sequence to git's own `config -z --get-all` output and
asserts the real trust decision (named repo usable, unrelated cross-owner repo refused).
Cost: noninteractive_git_env() runs on every internal git call, including the banner
startup probe, and the two `git config` children added ~10 ms per call against ~0.2 ms
before. Memoise per process on the inputs that select the config files plus the
system/global candidates' mtimes, so an edit to ~/.gitconfig is picked up without a
restart (verified live: 128 -> 0 within one process after appending safe.directory).
Review of #107748 found the carry path serialized the user's trust policy
incorrectly, and the mistake could WIDEN trust rather than merely reformat it.
safe.directory is an ordered multi-valued protected setting: an empty value
resets every entry seen so far. That is the documented mechanism for revoking a
system-wide `safe.directory=*` and then naming only the repositories you
actually trust. The previous helper broke all three properties that make it work:
* read `--global` before `--system` (git's precedence is system, then global)
* dropped empty entries via `if entry:`, deleting the reset marker
* de-duplicated values, though it is a sequence and not a set
Reproduced with real git (2.55.0 here, 2.47.3 by the reviewer). Given
system `safe.directory=*`, global `safe.directory=` then `/trusted/only`:
real git, user's own policy -> rc=128 (dubious ownership)
previous head's sequence `/trusted/only`, `*` -> rc=0 (trust widened)
this head's sequence `*`, ``, `/trusted/only` -> rc=128 (matches real git)
So a user who had deliberately revoked a machine-wide wildcard silently got it
back inside Hermes's internal git calls. That contradicted the "read-only and
non-widening" claim the original change rested on.
Fix: read scopes lowest-precedence first (system, then global) and replay every
value verbatim -- no de-duplication, no dropping of empty reset markers. Read
with `git config -z` so a value containing whitespace or a newline stays the one
entry git reads it as, instead of being split into several bogus trust entries
by splitlines()/strip(). The trailing field of a -z stream is always empty and
is discarded; interior empty fields are real resets and survive.
Two invariant tests, both proven red on the previous implementation:
* the injected sequence equals `git config -z --get-all safe.directory` for
the same two config files, asserting git's documented reset shape
* an E2E trust decision under GIT_TEST_ASSUME_DIFFERENT_OWNER=1: the named
repo stays usable and an unrelated cross-owner repo is still refused,
proving the reset still revokes the wildcard
13 passed in tests/hermes_cli/test_noninteractive_git.py, 69 in
tests/security/test_gitspawn_config_injection.py and
tests/tools/test_checkpoint_manager.py.
`noninteractive_git_env()` blanks GIT_CONFIG_GLOBAL/SYSTEM to /dev/null so a
user's config cannot hang Hermes's internal git plumbing with pagers, hooks or
credential prompts. Sound intent, but it also discards `safe.directory` — and
git honours that key ONLY from global/system config (it is rejected from
repo-level config by design, so a hostile repo cannot self-authorise).
Result: every internal git call fails on a repo whose st_uid != geteuid():
$ hermes -w
✗ Failed to create worktree: fatal: detected dubious ownership in
repository at '/mnt/nas/py/repo'
That hits NFS/CIFS mounts without idmapping, shared checkouts, and containers
with a remapped uid. The user's own `git config --global --add safe.directory`
is correctly set and their interactive git works — Hermes throws the setting
away before git reads it, so the error's own suggested remedy can never fix it.
There is no config or env escape hatch: the blanking is unconditional.
Reproducer (any repo where the checkout uid differs from the caller's):
git rev-parse HEAD # works
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null \
GIT_CONFIG_NOSYSTEM=1 git rev-parse HEAD # dubious ownership
Fix: read the user's real `safe.directory` values before the isolation is
applied, then re-inject them over the GIT_CONFIG_KEY_n channel, which survives
GIT_CONFIG_GLOBAL=/dev/null. Isolation is unchanged — global/system config stay
pointed at /dev/null and every hardening override still applies, since a later
key of the same name wins in git's config order.
Read-only and non-widening: only values already present in the user's own
config are carried, so this grants no trust they had not granted. Ambient
GIT_CONFIG_KEY_n injection is still stripped first, so a caller cannot launder
an attacker-controlled path in this way — covered by a regression test.
Tests: three cases in TestNoninteractiveGitEnv — entries carried past
isolation, no entries injected when the user configured none, and ambient
injection not trusted. All pin GIT_CONFIG_SYSTEM at an empty file, since a real
/etc/gitconfig on the test host can otherwise leak entries and mask the
assertions.
Verified on Arch Linux, git 2.x, repo on an NFSv4 mount (uid 1024 vs caller
1000): `git worktree add` under the patched env returns rc=0 where it
previously failed. 80 passed in tests/hermes_cli/test_noninteractive_git.py,
tests/security/test_gitspawn_config_injection.py and
tests/tools/test_checkpoint_manager.py, including the pre-existing assertions
that the isolation stays in force.
The old contract described the replacement tree, not the code still running
in installations that update to it. Deleted managed_uv imports escaped it.
Inventory the full reachable update-channel history, discover old entrypoint
paths and helper extractions, then union those imports with the working tree.
Refuse shallow regeneration. Preserve old names when current callers vanish.
Keep same-named function alternatives and require module-scope bindings.
Restore the additional historical names as inert shims. Installer boundaries
stop for relaunch rather than enable fallback installs. Keep live DingTalk
dependency setup on PM rather than the retired lazy_deps import.
History enumeration covers 33,720 commits at 1021a03256 and 8,078 selected
file versions. The generated contract contains 496 required imports with no
missing names. Dynamic edges and their manual-review limits remain visible.
No claim is made that static analysis proves all runtime plugin imports or
every historical platform path. See tests/compat/README.md.
Verification: 622 targeted tests passed with file retries disabled, including
the frozen contract, historical shims, real PM launch tests, and DingTalk.
Ruff, focused type checks, import guard, and comment prose checks passed.
The full suite and native Windows execution were not run locally.
Merge upstream b1f003e186 while preserving PM runtime ownership and
Python 3.14 worker startup, Windows signing, and macOS wait recovery.
Keep retired runtime modules deleted. Port upstream updater preflight
checks into the checkout strategy and preserve live build logging.
Carry checkpoint filename handling and process recovery into the current
module layout. Regenerate locks and adapt incoming platform test markers.
Focused Python and JavaScript tests, desktop and root-test typechecks,
conflict-path lint checks, lock validation, and retired-import checks pass.
The full test suite and packaged release builds were not run.
ssh bypasses stdin=DEVNULL and GIT_TERMINAL_PROMPT: when a git child
dials an SSH remote whose host key is unknown, ssh opens /dev/tty
directly and its yes/no prompt steals the caller's terminal — exactly
what noninteractive_git_env exists to prevent. Pin core.sshCommand to
"ssh -o BatchMode=yes" at the config-injection layer so the ssh child
fails instead of prompting; an agent-authenticated ssh still succeeds,
and an explicit user GIT_SSH_COMMAND env var still takes precedence
(#104591).