The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): preserve receipt identity and durable terminal facts
Tekniumd6bcc9987839
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.pyindex 9668a2f2aaa..c8aec94bc12 100644--- a/hermes_cli/update_receipt.py+++ b/hermes_cli/update_receipt.py@@ -218,21 +218,36 @@ def _persist_running(data: dict[str, Any]) -> None:directory = _receipt_dir()directory.mkdir(parents=True, exist_ok=True)- payload = (json.dumps({**data, "writer_pid": os.getpid()}, indent=2, default=str) + "\n").encode("utf-8")- _atomic_bytes(_run_file(directory, data), payload)+ path = _run_file(directory, data)+ # A completion child can finalize while its parent still holds the pre-child+ # context. That stale running snapshot must never undo the terminal receipt.+ with suppress(OSError, ValueError):+ stored = json.loads(path.read_text(encoding="utf-8-sig"))+ if stored.get("update_id") == data.get("update_id") and stored.get("finished_at"):+ return+ from hermes_cli.process_identity import _process_create_time++ payload = (json.dumps({**data, "writer_pid": os.getpid(),+ "writer_create_time": _process_create_time(os.getpid())},+ indent=2, default=str) + "\n").encode("utf-8")+ _atomic_bytes(path, payload)_atomic_bytes(directory / "latest.json", payload)def _owner_alive(record: dict[str, Any]) -> bool:from hermes_cli.process_identity import _pid_alive_matches- for key in ("pid", "writer_pid"):+ identities = {}+ for key, time_key in (("pid", "pid_create_time"), ("writer_pid", "writer_create_time")):pid = record.get(key)- if isinstance(pid, int) and pid > 0 and pid != os.getpid():- create_time = record.get("pid_create_time") if key == "pid" else None- if _pid_alive_matches(pid, create_time) is not False:- return True- return False+ if isinstance(pid, int) and pid > 0:+ # Older receipts recorded no writer incarnation. Do not let a duplicate+ # bare PID override the original owner's proven creation-time mismatch.+ create_time = record.get(time_key)+ if pid not in identities or identities[pid] is None:+ identities[pid] = create_time+ return any(_pid_alive_matches(pid, create_time) is not False+ for pid, create_time in identities.items())def reconcile_interrupted_runs() -> list[dict[str, Any]]:@@ -355,6 +370,7 @@ def record_user_action(step: str, reason: str) -> None:``hermes update`` exits 1, as #122557 established for an unrestored autostash."""_record("fact", f"update user action {step}", "user_action", {"step": step, "reason": " ".join(str(reason).split())[:500]})+ persist_running_receipt()def amend_terminal_followup(update_id: str, step: str, reason: str) -> None:diff --git a/tests/hermes_cli/test_update_post_commit_followups.py b/tests/hermes_cli/test_update_post_commit_followups.pyindex e928f1b75d1..f07ed21e03b 100644--- a/tests/hermes_cli/test_update_post_commit_followups.py+++ b/tests/hermes_cli/test_update_post_commit_followups.py@@ -82,7 +82,11 @@ def test_live_running_record_is_not_reclaimed(tmp_path, monkeypatch):own_id = update_receipt._current.get().data["update_id"]for path in (tmp_path / "logs/update_receipts").glob("*.json"):data = json.loads(path.read_text())- data.update(pid=os.getppid(), writer_pid=os.getppid(), pid_create_time=None) # alive+ from hermes_cli.process_identity import _process_create_time++ parent_time = _process_create_time(os.getppid())+ data.update(pid=os.getppid(), writer_pid=os.getppid(),+ pid_create_time=parent_time, writer_create_time=parent_time)path.write_text(json.dumps(data))assert update_receipt.reconcile_interrupted_runs() == [](archived,) = (tmp_path / "logs/update_receipts").glob(f"update_*_{own_id}.json")diff --git a/tests/hermes_cli/test_update_receipt_durability.py b/tests/hermes_cli/test_update_receipt_durability.pynew file mode 100644index 00000000000..11a8ead1b55--- /dev/null+++ b/tests/hermes_cli/test_update_receipt_durability.py@@ -0,0 +1,112 @@+"""Receipt recovery must preserve terminal and user-action facts across processes."""+from __future__ import annotations++import json+import os+from pathlib import Path+import subprocess+import sys+import textwrap++ROOT = Path(__file__).resolve().parents[2]+++def _run(tmp_path: Path, body: str) -> dict:+ home = tmp_path / "account"+ state = home / ".hermes"+ state.mkdir(parents=True)+ script = tmp_path / "receipt_probe.py"+ script.write_text(textwrap.dedent("""+ import json, os, subprocess, sys+ from pathlib import Path+ sys.path.insert(0, sys.argv[1])+ from hermes_cli import update_receipt as receipts+ from hermes_cli.process_identity import _process_create_time+ """) + textwrap.dedent(body), encoding="utf-8")+ env = {key: value for key, value in os.environ.items()+ if not key.startswith(("HERMES_", "PYTEST_"))}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state),+ HERMES_RUNTIME_DIR=str(tmp_path / "tools"),+ XDG_CONFIG_HOME=str(home / ".config"), XDG_CACHE_HOME=str(home / ".cache"),+ PYTHONPATH=os.pathsep.join([str(ROOT), *filter(None, sys.path)]),+ PYTHONDONTWRITEBYTECODE="1")+ done = subprocess.run([sys.executable, str(script), str(ROOT)], env=env, cwd=tmp_path,+ text=True, capture_output=True, timeout=60)+ assert done.returncode == 0, done.stdout + done.stderr+ return json.loads((tmp_path / "result.json").read_text(encoding="utf-8"))+++def test_nested_begin_does_not_reconcile_live_outer_receipt(tmp_path):+ result = _run(tmp_path, """+ receipts.begin_update_receipt()+ outer = dict(receipts._current.get().data)+ receipts.begin_update_receipt()+ archive = receipts._run_file(receipts._receipt_dir(), outer)+ before = json.loads(archive.read_text())+ receipts.finalize_pending_update_receipt(0)+ restored = receipts.current_correlation_id()+ receipts.finalize_pending_update_receipt(0)+ Path('result.json').write_text(json.dumps({+ 'outcome': before['outcome'], 'restored': restored, 'outer': outer['update_id']}))+ """)+ assert result["outcome"] == "running"+ assert result["restored"] == result["outer"]+++def test_writer_identity_cannot_resurrect_a_mismatched_owner(tmp_path):+ result = _run(tmp_path, """+ child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])+ try:+ ct = _process_create_time(child.pid)+ assert ct is not None+ same = {'pid': child.pid, 'writer_pid': child.pid, 'pid_create_time': ct - 60}+ writer = {'pid': 0, 'writer_pid': child.pid, 'writer_create_time': ct - 60}+ control = {'pid': child.pid, 'writer_pid': child.pid, 'pid_create_time': ct}+ Path('result.json').write_text(json.dumps({+ 'same': receipts._owner_alive(same), 'writer': receipts._owner_alive(writer),+ 'control': receipts._owner_alive(control)}))+ finally:+ child.terminate()+ child.wait(timeout=10)+ """)+ assert result == {"same": False, "writer": False, "control": True}+++def test_user_action_survives_interrupt_before_next_stage(tmp_path):+ result = _run(tmp_path, """+ receipts.begin_update_receipt()+ receipts.record_user_action('local_changes', 'Reapply stash@{0} by hand')+ running = receipts.read_latest_receipt()+ receipts.finalize_interrupted_update_receipt('operator interrupted')+ terminal = receipts.read_latest_receipt()+ Path('result.json').write_text(json.dumps({'running': running, 'terminal': terminal}))+ """)+ expected = {"step": "local_changes", "reason": "Reapply stash@{0} by hand"}+ assert result["running"].get("user_action") == expected+ assert result["terminal"].get("user_action") == expected+ assert result["terminal"]["outcome"] == "interrupted"+++def test_parent_followup_does_not_replace_child_terminal_with_running(tmp_path):+ result = _run(tmp_path, """+ receipts.begin_update_receipt()+ frozen = dict(receipts._current.get().data)+ Path('request.json').write_text(json.dumps(frozen))+ child = subprocess.run([sys.executable, '-c',+ 'import json,sys; from pathlib import Path; '+ 'from hermes_cli.update_completion import _resume_receipt; '+ 'from hermes_cli.update_receipt import finalize_pending_update_receipt; '+ '_resume_receipt(json.loads(Path("request.json").read_text())); '+ 'finalize_pending_update_receipt(0)'], check=True)+ before = receipts.read_latest_receipt()+ receipts.record_followup('windows_resume', 'recovery refused')+ receipts.amend_terminal_followup(frozen['update_id'], 'windows_resume', 'recovery refused')+ after = receipts.read_latest_receipt()+ archive = json.loads(receipts._run_file(receipts._receipt_dir(), frozen).read_text())+ Path('result.json').write_text(json.dumps({'before': before, 'after': after, 'archive': archive}))+ """)+ assert result["before"]["outcome"] == "success"+ for terminal in (result["after"], result["archive"]):+ assert terminal["outcome"] == "success"+ assert terminal["finished_at"] == result["before"]["finished_at"]+ assert [row["step"] for row in terminal["followups"]] == ["windows_resume"]