The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bootstrap): launch-time completion is owed by a marker, not by currency
ethernetd500d051844d
diff --git a/hermes_bootstrap.py b/hermes_bootstrap.pyindex 5e47162c45c..bba7799741c 100644--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@ -359,8 +359,13 @@ if not _pm_repair:raise SystemExit(subprocess.call(_command))os.execv(str(_launch_python), _command)except Exception as exc:- print(f"hermes: source-update completion failed: {exc}", file=sys.stderr)- raise SystemExit(1) from None+ # Degrade, never brick the CLI: the previous dependency generation is still selected+ # (a failed sync commits nothing), so an offline or half-finished update leaves a+ # usable Hermes plus a warning. Activation below is the real gate — a tree whose+ # dependencies cannot load still exits with the repair remedy.+ print(f"hermes: source-update completion failed: {exc}; "+ "running with the previous dependencies — run `hermes update` to finish it",+ file=sys.stderr)recover_if_needed(_root)try:activate_dependencies(_root)diff --git a/hermes_cli/venv_sync.py b/hermes_cli/venv_sync.pyindex 5f576c33fac..4f29b8c4dc0 100644--- a/hermes_cli/venv_sync.py+++ b/hermes_cli/venv_sync.py@@ -124,11 +124,31 @@ def sync(project_root: Path | None = None, *, check: bool = False) -> dict:return {"state": "failed", "ok": False, "detail": str(exc)}+#: Answered from the tree alone; a metadata query must never wait on (or fail with)+#: a network-bound source-update completion.+_METADATA_FLAGS = frozenset({"-h", "--help", "-V", "--version"})+++def completion_pending_path(project_root: Path) -> Path:+ """Marker for a source update whose dependency sync committed but whose tail+ (launchers, products, maintenance) has not finished.++ Lives beside PM's facts, not in the checkout: it is per-install state, and a+ root-level file would trip the ZIP updater's dirty-tree check.+ """+ from pm.environments import install_state_dir++ return install_state_dir(project_root) / "source-completion-pending"++def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:"""Finish a self-managed source update before importing app dependencies.- PM's successful input stamp is the only completion signal. Old updaters- need not write a marker (and cannot accidentally clear this obligation).+ PM's successful input stamp signals a finished dependency sync; the+ ``source-completion-pending`` marker signals the tail still owed after it,+ so a tail that failed is retried on the next launch WITHOUT rebuilding+ dependencies that are already current. Old updaters need not write a+ marker (and cannot accidentally clear this obligation).Return the store interpreter when this process must restart cleanly."""import os@@ -138,6 +158,7 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:root = Path(project_root).resolve()if (command_argv(argv)[:1] == ["pm"]+ or _METADATA_FLAGS & set(argv)or os.environ.get("HERMES_DISABLE_LAZY_INSTALLS", "").lower() in ("1", "true", "yes")or not (root / ".git").exists()or not (root / "pyproject.toml").is_file()):@@ -151,21 +172,52 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:if stamp.get("updateMechanism") != "self":return None # Developer checkouts and packaged runtimes retain their owner.- from hermes_cli._early_recovery import _marker_owner_is_live- from hermes_cli.update_lock import read_live_update-import pmfrom hermes_cli._launchers import resolve_store_python- from pm.environments import activation_environment, runtime_facts_path+ from hermes_cli.update_lock import UpdateLock, read_live_updatecurrent = pm.venv_is_current(project_root=root)+ pending = completion_pending_path(root)+ if not current or pending.is_file():+ lock = UpdateLock()+ if not lock.acquire():+ raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")+ # The tail imports the application, whose entry point runs this very function:+ # under the launching process's own claim (its pid is our ancestor) we ARE that+ # tail and owe nothing — without this, a pending marker recurses forever.+ if not lock.acquired and read_live_update() is not None:+ return None+ try:+ _finish_source_update(root, current=current, pending=pending)+ finally:+ lock.release()+ python = resolve_store_python(root)+ if python is None:+ raise RuntimeError("source update has no managed Python; run `hermes pm install`")+ if not current or python.absolute() != Path(sys.executable).absolute():+ publish_launchers(root)+ return python+ return None+++def _finish_source_update(root: Path, *, current: bool, pending: Path) -> None:+ """Sync dependencies when they are stale, then run the tail the marker still owes."""+ import sys+ import pm+ from hermes_cli._early_recovery import _marker_owner_is_live+ from pm.environments import activation_environment, runtime_facts_path+if not current:# Existing markers guard liveness, never create the completion obligation.# Current post-sync verification children can boot under a live updater.legacy_markers = (root / ".update-incomplete", root / ".lazy-refresh-incomplete")- if any(_marker_owner_is_live(marker) for marker in legacy_markers) or read_live_update():+ if any(_marker_owner_is_live(marker) for marker in legacy_markers):raise RuntimeError("an update is still running; wait for it to exit, then relaunch Hermes")print("hermes: completing source-update dependencies...", file=sys.stderr, flush=True)+ # Owed from before the sync commits: a crash between the commit and the+ # tail must leave the tail, not a "current" install with nothing built.+ pending.parent.mkdir(parents=True, exist_ok=True)+ pending.write_text("source update tail not finished\n", encoding="utf-8")# Main-era installers selected [all] but had no PM ledger. Established# PM installs retain their recorded extras and plugin union instead.extras = ["all"] if not runtime_facts_path(root).is_file() else None@@ -174,33 +226,32 @@ def prepare_launch(project_root: Path, argv: list[str]) -> Path | None:# must not make early recovery immediately rebuild it a second time.for name in (".update-incomplete", ".lazy-refresh-incomplete"):(root / name).unlink(missing_ok=True)- # Sync commits the dependency generation, but a source update also owes- # the product builds and the post-build maintenance -- the tail every- # install and finished update shares (hermes_cli/source_completion.py).- # Those builds need PM's selected interpreter with its dependencies- # activated, so hand that file THIS interpreter and let it re-exec- # itself, exactly as the installers do.- desktop_app = root / "apps/desktop"- desktop = ((desktop_app / "dist/index.html").is_file()- or any((desktop_app / "release").glob("*")))- code = subprocess.call(- [sys.executable, "-I", "-B", "-u",- str(root / "hermes_cli/source_completion.py"),- "--source", str(root), "--finish-update",- *(("--desktop",) if desktop else ())],- cwd=root, env=activation_environment(root),+ else:+ print("hermes: finishing an interrupted source update...", file=sys.stderr, flush=True)+ # Sync commits the dependency generation, but a source update also owes+ # the product builds and the post-build maintenance -- the tail every+ # install and finished update shares (hermes_cli/source_completion.py).+ # Those builds need PM's selected interpreter with its dependencies+ # activated, so hand that file THIS interpreter and let it re-exec+ # itself, exactly as the installers do.+ desktop_app = root / "apps/desktop"+ desktop = ((desktop_app / "dist/index.html").is_file()+ or any((desktop_app / "release").glob("*")))+ # The tail's progress lines go to stderr: this is an automatic repair in+ # front of whatever command the user ran, and that command may be+ # emitting machine-readable stdout (a JSON probe, a piped query).+ code = subprocess.call(+ [sys.executable, "-I", "-B", "-u",+ str(root / "hermes_cli/source_completion.py"),+ "--source", str(root), "--finish-update",+ *(("--desktop",) if desktop else ())],+ cwd=root, env=activation_environment(root), stdout=sys.__stderr__,+ )+ if code != 0:+ raise RuntimeError(+ "source update completion failed; run `hermes update` to finish it")- if code != 0:- raise RuntimeError(- "source update completion failed; run `hermes update` to finish it"- )- python = resolve_store_python(root)- if python is None:- raise RuntimeError("source update has no managed Python; run `hermes pm install`")- if not current or python.absolute() != Path(sys.executable).absolute():- publish_launchers(root)- return python- return None+ pending.unlink()def relaunch_command(diff --git a/tests/hermes_cli/test_update_launch_completion.py b/tests/hermes_cli/test_update_launch_completion.pyindex 7fa588c59e6..0e96f2b7c16 100644--- a/tests/hermes_cli/test_update_launch_completion.py+++ b/tests/hermes_cli/test_update_launch_completion.py@@ -21,16 +21,92 @@ def completion_tail(monkeypatch):scratch tree here — building products with the selected interpreter; the tests belowcover the sync decision, not the build."""- spawned = []+ class Spawned(list):+ exit_code = 0+ kwargs: dict = {}++ spawned = Spawned()def call(command, **kwargs):spawned.append(command)- return 0+ spawned.kwargs = kwargs+ return spawned.exit_codemonkeypatch.setattr(venv_sync.subprocess, "call", call)return spawned+def _self_checkout(tmp_path, monkeypatch):+ root = tmp_path / "checkout"+ root.mkdir()+ (root / ".git").mkdir()+ (root / "pyproject.toml").write_text("[project]\nname='example'\n")+ (root / "install-stamp.json").write_text(json.dumps({"updateMechanism": "self"}))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)+ return root++[email protected]("argv", [["--version"], ["-V"], ["--help"], ["-p", "work", "-h"]])+def test_metadata_query_never_waits_on_source_completion(tmp_path, monkeypatch, argv):+ """`hermes --version` offline must answer from the tree, not run a network-bound sync."""+ import pm++ root = _self_checkout(tmp_path, monkeypatch)+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: pytest.fail("metadata query reached PM"))+ assert venv_sync.prepare_launch(root, argv) is None+++def test_failed_completion_tail_is_retried_without_rebuilding_dependencies(tmp_path, monkeypatch, completion_tail):+ """Dependencies committed, tail failed: the next launch owes the tail only."""+ import pm+ from hermes_cli import _launchers++ root = _self_checkout(tmp_path, monkeypatch)+ fact = runtime_facts_path(root)+ syncs = []+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: fact.is_file())+ monkeypatch.setattr(_launchers, "resolve_store_python", lambda _: Path(sys.executable))++ def sync(extras=None, **kwargs):+ syncs.append(extras)+ fact.parent.mkdir(parents=True, exist_ok=True)+ fact.write_text(json.dumps({"packages": {"venv": {"stamp": "complete", "extras": ["all"]}}}))++ monkeypatch.setattr(pm, "sync_venv", sync)+ completion_tail.exit_code = 1+ with pytest.raises(RuntimeError, match="run `hermes update`"):+ venv_sync.prepare_launch(root, [])+ assert len(syncs) == 1 and len(completion_tail) == 1+ assert pm.venv_is_current()++ with pytest.raises(RuntimeError, match="run `hermes update`"):+ venv_sync.prepare_launch(root, [])+ assert len(syncs) == 1, "current dependencies were rebuilt for a tail retry"+ assert len(completion_tail) == 2++ completion_tail.exit_code = 0+ # Dependencies are already this interpreter's: the tail alone owes no re-exec.+ assert venv_sync.prepare_launch(root, []) is None+ assert len(syncs) == 1 and len(completion_tail) == 3+ assert venv_sync.prepare_launch(root, []) is None+ assert len(completion_tail) == 3, "a finished tail was run again"+++def test_completion_tail_output_stays_off_stdout(tmp_path, monkeypatch, completion_tail):+ """The automatic tail runs in front of the user's command, which may be piping JSON."""+ import pm+ from hermes_cli import _launchers++ root = _self_checkout(tmp_path, monkeypatch)+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: False)+ monkeypatch.setattr(pm, "sync_venv", lambda *a, **kw: None)+ monkeypatch.setattr(_launchers, "resolve_store_python", lambda _: Path(sys.executable))+ venv_sync.prepare_launch(root, [])+ assert completion_tail.kwargs["stdout"] is sys.__stderr__++def test_first_launch_syncs_without_marker_then_uses_completion_fact(tmp_path, monkeypatch, completion_tail):import pmfrom hermes_cli import _launchers@@ -51,7 +127,7 @@ def test_first_launch_syncs_without_marker_then_uses_completion_fact(tmp_path, mdef sync(extras=None, **kwargs):calls.append((extras, kwargs))- fact.parent.mkdir(parents=True)+ fact.parent.mkdir(parents=True, exist_ok=True)fact.write_text(json.dumps({"packages": {"venv": {"stamp": "complete", "extras": ["all"]}}}))monkeypatch.setattr(pm, "sync_venv", sync)@@ -185,3 +261,25 @@ def test_live_old_update_blocks_launch_sync(tmp_path, monkeypatch):monkeypatch.setattr(_launchers, "resolve_store_python", lambda _: Path(sys.executable))assert venv_sync.prepare_launch(root, []) is Noneassert marker.is_file()+++def test_launch_under_the_owning_update_does_not_run_the_tail_again(tmp_path, monkeypatch, completion_tail):+ """The tail imports the application, whose entry point runs prepare_launch: inside the+ process tree of the update that owns the pending tail it must be a no-op, not recurse."""+ import time+ import pm+ from hermes_cli.update_lock import update_marker_path++ root = _self_checkout(tmp_path, monkeypatch)+ pending = venv_sync.completion_pending_path(root)+ pending.parent.mkdir(parents=True)+ pending.write_text("owed\n")+ monkeypatch.setattr(pm, "venv_is_current", lambda **kw: True)+ marker = update_marker_path()+ marker.parent.mkdir(parents=True, exist_ok=True)+ marker.write_text(f"{os.getppid()}\n{int(time.time())}\n") # an ancestor holds the update++ assert venv_sync.prepare_launch(root, []) is None+ assert completion_tail == []+ assert pending.is_file(), "the owning update's obligation was discharged by its own tail"+diff --git a/tests/pm/test_cold_runtime_e2e.py b/tests/pm/test_cold_runtime_e2e.pyindex 671b054d40e..581ca60f725 100644--- a/tests/pm/test_cold_runtime_e2e.py+++ b/tests/pm/test_cold_runtime_e2e.py@@ -188,10 +188,14 @@ assert importlib.util.find_spec('idna') is Noneassert launch_report["version"] == list(sys.version_info[:2])assert Path(launch_report["idna"]).is_relative_to(hermes_home / "installs")assert launched.stderr.count("completing source-update dependencies") == 1+ # The launch finished the update's shared tail, whose maintenance migrates+ # config.yaml; `pm repair` below must then leave that migrated file alone.+ assert "_config_version" in config.read_text()finally:server.shutdown()server.server_close()thread.join(timeout=10)+ expected_config = config.read_text()report_code = """import json@@ -270,7 +274,9 @@ print(json.dumps({'yaml': ruamel.yaml.__file__, 'idna': idna.__file__,assert repaired_fact["extras"] == initial_fact["extras"]assert repaired_fact["stamp"] == initial_fact["stamp"]assert Path(repaired_fact["resolved_lock"]).read_bytes() == lock_before- assert config.read_text() == "plugins:\n enabled: [cold-proof]\n"+ assert config.read_text() == expected_config+ if not bootstrap_name:+ assert expected_config == "plugins:\n enabled: [cold-proof]\n"assert not (state / ".repair-incomplete").exists()assert not (repo / "venv").exists()assert not (repo / ".venv").exists()diff --git a/tests/pm/test_source_update_launch.py b/tests/pm/test_source_update_launch.pyindex ca6049038a7..66fc59e566d 100644--- a/tests/pm/test_source_update_launch.py+++ b/tests/pm/test_source_update_launch.py@@ -391,3 +391,53 @@ def test_real_bootstrap_reexecs_before_app_imports(source_launch, tmp_path, isolassert json.loads(receipt.read_text(encoding="utf-8"))["outcome"] == "ok"assert not (root / ".update-incomplete").exists()assert not (root / ".lazy-refresh-incomplete").exists()++[email protected]("posix")[email protected]("argv", [[], ["--version"]])+def test_failed_launch_completion_degrades_to_a_warning(source_launch, tmp_path, isolated_python, argv):+ """An update whose dependency sync cannot finish (offline, bad lock) must leave a usable+ CLI on the previous generation with a warning — and a metadata query must not even try."""+ root, store_python, worker_command = source_launch+ repository = Path(__file__).resolve().parents[2]+ shutil.copy2(repository / "hermes_bootstrap.py", root / "hermes_bootstrap.py")+ (root / "launch_test_tools.py").write_text(+ "import sys\n"+ "from pathlib import Path\n"+ f"sys.path.insert(1, {str(repository)!r})\n"+ "import pm.client\n"+ "from pm import paths\n"+ f"paths.lockfile_path = lambda: Path({str(tmp_path / 'tool-lock.json')!r})\n"+ f"pm.client.runtime_command = lambda *args, **kwargs: {worker_command!r}\n",+ encoding="utf-8",+ )+ entry = root / "launch_probe.py"+ entry.write_text(+ "import launch_test_tools\n"+ "import hermes_bootstrap\n"+ "import json, sys\n"+ "print(json.dumps({'executable': sys.executable, 'args': sys.argv[1:]}))\n",+ encoding="utf-8",+ )+ pm.sync_venv(["all"], explicit=True, project_root=root)+ previous = _fact(root)+ lock = root / "uv.lock"+ lock.write_text("version = 1\nnot valid TOML\n", encoding="utf-8")+ assert not pm.venv_is_current(project_root=root)+ before_receipts = _receipts(tmp_path)++ result = subprocess.run(+ [str(isolated_python), str(entry), *argv], cwd=root,+ env=dict(os.environ), capture_output=True, text=True, timeout=60,+ )++ assert result.returncode == 0, result.stderr+ assert json.loads(result.stdout) == {"executable": str(isolated_python), "args": argv}+ assert _fact(root) == previous+ if argv:+ assert "source-update completion failed" not in result.stderr+ assert _receipts(tmp_path) == before_receipts, "a metadata query attempted a dependency sync"+ else:+ assert "source-update completion failed" in result.stderr+ assert "hermes update" in result.stderr+