The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): serialize source-completion tails on the shared update lock; skip Windows file-manager metadata in freshness hashing (#123376, #122803)
Brooklyn Nicholsondde4bc7bb735
diff --git a/hermes_cli/source_completion.py b/hermes_cli/source_completion.pyindex 96b7a79dab9..f3df7d9cf47 100644--- a/hermes_cli/source_completion.py+++ b/hermes_cli/source_completion.py@@ -42,11 +42,51 @@ def complete_source_checkout(Returns the SQLite runtime verdict: a positive unsafe-runtime probe withholdssuccess here exactly as it does at the end of an update."""+ from hermes_cli.update_lock import UpdateLock, describe_holder++ root = Path(root)+ # This tail is the last mutating step of an install or update, and its product+ # builds run for minutes. A gateway restarted while it runs (launchd KeepAlive,+ # a service manager, a second `hermes` launch) reaches the same tail through+ # venv_sync, and `hermes update` runs its own: two completions then build the+ # same output directories concurrently and race on install-stamp.json (#123376).+ # Claim the shared update lock so stacked completions serialize. A tail whose+ # orchestrator already holds the lock (venv_sync's interrupted-update finish,+ # the updater's completion child) runs under its parent's claim, exactly as+ # `hermes update` does under the desktop handoff pid.+ lock = UpdateLock()+ if not lock.acquire():+ raise RuntimeError(+ f"an update is still running ({describe_holder(lock.holder)}); "+ "wait for it to exit, then relaunch Hermes"+ )+ try:+ return _complete_locked(+ root, desktop=desktop, assume_yes=assume_yes, gateway_mode=gateway_mode,+ pre_update_snapshot_id=pre_update_snapshot_id,+ pre_update_version=pre_update_version,+ completion_message=completion_message, announce=announce,+ )+ finally:+ lock.release()+++def _complete_locked(+ root: Path,+ *,+ desktop: bool,+ assume_yes: bool,+ gateway_mode: bool,+ pre_update_snapshot_id: str | None,+ pre_update_version: str | None,+ completion_message: str | None,+ announce: str | None,+) -> bool:+ """The completion body; callers hold the update lock already."""from hermes_cli.source_build import build_update_productsfrom hermes_cli.update_cmd_maint import _run_post_update_maintenancefrom hermes_cli.venv_sync import publish_launchers- root = Path(root)try:from hermes_cli._subprocess_compat import expose_pm_gitdiff --git a/scripts/build/freshness.mjs b/scripts/build/freshness.mjsindex 4c1aec34d08..f489d4c965c 100644--- a/scripts/build/freshness.mjs+++ b/scripts/build/freshness.mjs@@ -9,13 +9,15 @@ const receiptName = 'hermes-build.json'const workspaces = { tui: 'ui-tui', web: 'web', desktop: 'apps/desktop' }const generated = new Set(['node_modules', 'dist', 'build', 'release', '.cache', '.git', 'coverage', 'test-results', 'playwright-report'])-// macOS Finder metadata is never a build input, and it can land in ANY hashed tree-// (source, output or a prepared dir) the moment the checkout is opened in Finder mid-build-// — .DS_Store, AppleDouble ._* sidecars and .localized. Skip it everywhere so it can't flip-// a freshness hash and abort `hermes update` (#122632).-const macMetadata = name => {+// OS file-manager metadata is never a build input, and it can land in ANY hashed+// tree (source, output or a prepared dir) the moment the checkout is opened in+// Finder or Explorer mid-build — .DS_Store, AppleDouble ._* sidecars and+// .localized on macOS, Thumbs.db and Desktop.ini on Windows. Skip it everywhere+// so it can't flip a freshness hash and abort `hermes update` (#122632, #122803).+const osMetadata = name => {const base = name.split('/').pop()- return base === '.DS_Store' || base === '.localized' || base.startsWith('._')+ return base === '.DS_Store' || base === '.localized'+ || base === 'Thumbs.db' || base === 'Desktop.ini' || base.startsWith('._')}// buildTui bundles these source roots (including the Ink source alias), not@@ -31,7 +33,7 @@ const tuiInputs = [function treeHash(root, inputs, skip, contents = () => true) {const hash = createHash('sha256')function visit(name) {- if (macMetadata(name) || skip(name)) return+ if (osMetadata(name) || skip(name)) returnconst file = join(root, name)hash.update(name.replaceAll('\\', '/')).update('\0')if (!existsSync(file)) { hash.update('missing\0'); return }diff --git a/tests/hermes_cli/test_source_completion_stamp.py b/tests/hermes_cli/test_source_completion_stamp.pyindex cdf82639fb1..c445aafcd37 100644--- a/tests/hermes_cli/test_source_completion_stamp.py+++ b/tests/hermes_cli/test_source_completion_stamp.py@@ -2,9 +2,12 @@import jsonimport os-from pathlib import Pathimport subprocessimport sys+import time+from pathlib import Path++import pytestfrom hermes_cli.source_completion import complete_source_checkoutfrom hermes_cli.source_stamp import write_source_stamp@@ -55,6 +58,73 @@ def test_failed_source_completion_does_not_publish_identity(tmp_path, monkeypatcassert not (root / "install-stamp.json").exists()+def _sandboxed_marker(tmp_path, monkeypatch):+ """Point every update-lock reader at a marker inside this test's sandbox."""+ marker = tmp_path / ".hermes-update-in-progress"+ monkeypatch.setattr("hermes_cli.update_lock.update_marker_path", lambda: marker)+ return marker+++def foreign_pid():+ """A live process that is not an ancestor of this test: a stand-in updater."""+ proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"],+ stdin=subprocess.DEVNULL)+ yield proc.pid+ proc.kill()+ proc.wait()+++def test_completion_holds_the_update_lock_during_the_tail(tmp_path, monkeypatch):+ """Two completions must not build the same products concurrently (#123376).++ A gateway restarted while an update's tail runs reaches this same function+ through venv_sync; without the shared lock both build the same output dirs+ and race on install-stamp.json.+ """+ root = _repo(tmp_path)+ marker = _sandboxed_marker(tmp_path, monkeypatch)+ seen = {}++ def build(_root, *, desktop):+ from hermes_cli.update_lock import read_live_update++ seen["holder"] = read_live_update()++ monkeypatch.setattr("hermes_cli.source_build.build_update_products", build)+ monkeypatch.setattr("hermes_cli.venv_sync.publish_launchers", lambda root: None)+ monkeypatch.setattr("hermes_cli.update_cmd_maint._run_post_update_maintenance", lambda **_kwargs: True)++ assert complete_source_checkout(root, desktop=False, assume_yes=True)++ assert seen["holder"] is not None, "the tail must hold the shared lock while it builds"+ assert seen["holder"].pid == os.getpid()+ assert not marker.exists(), "a completed tail must release the lock for the next launch"+++def test_completion_refuses_to_stack_on_a_live_update(tmp_path, monkeypatch, foreign_pid):+ root = _repo(tmp_path)+ marker = _sandboxed_marker(tmp_path, monkeypatch)+ marker.write_text(f"{foreign_pid}\n{int(time.time())}\n", encoding="utf-8")+ _completion_dependencies(monkeypatch, lambda **_kwargs: True)++ with pytest.raises(RuntimeError, match="an update is still running"):+ complete_source_checkout(root, desktop=False, assume_yes=True)+++def test_completion_runs_under_a_parents_claim_without_releasing_it(tmp_path, monkeypatch):+ """A tail spawned by an orchestrator that holds the lock (venv_sync's+ interrupted-update finish, the updater's own completion child) runs under+ its parent's claim and leaves the parent's marker untouched."""+ root = _repo(tmp_path)+ marker = _sandboxed_marker(tmp_path, monkeypatch)+ marker.write_text(f"{os.getppid()}\n{int(time.time())}\n", encoding="utf-8")+ _completion_dependencies(monkeypatch, lambda **_kwargs: True)++ assert complete_source_checkout(root, desktop=False, assume_yes=True)+ assert marker.exists(), "the parent still owns its claim after our tail"++def _verify_bootstrap_receipt(root: Path) -> subprocess.CompletedProcess:"""The same verifier the Windows install/update E2E runs after an update."""script = Path(__file__).resolve().parents[2] / "scripts" / "verify-bootstrap-version-stamp.py"