The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): tolerate BOM receipts and preserve rollback bytes
ethernet562394273631
diff --git a/hermes_cli/_old_updater.py b/hermes_cli/_old_updater.pyindex 2dbaa640b33..5987706905e 100644--- a/hermes_cli/_old_updater.py+++ b/hermes_cli/_old_updater.py@@ -96,7 +96,7 @@ def _run_child(request: dict) -> tuple[int, dict]:[sys.executable, "-I", "-S", "-B", "-X", "utf8", str(root / "hermes_cli/_update_takeover.py"),str(context), str(result)], cwd=root, env=env,)- completed = json.loads(result.read_text(encoding="utf-8")) if result.is_file() else {}+ completed = json.loads(result.read_text(encoding="utf-8-sig")) if result.is_file() else {}if not isinstance(completed, dict):raise ValueError("invalid update takeover acknowledgement")return child.returncode if child.returncode >= 0 else 1, completeddiff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.pyindex e2afa662402..a6de50fc006 100644--- a/hermes_cli/_update_takeover.py+++ b/hermes_cli/_update_takeover.py@@ -57,7 +57,7 @@ def _record_failure(request: dict, result: Path, code: int, detail: str) -> Nonedef main() -> int:context, result = map(Path, sys.argv[1:3])- request = json.loads(context.read_text(encoding="utf-8"))+ request = json.loads(context.read_text(encoding="utf-8-sig"))sys.path.insert(0, request["root"])if "stopped_serves" in request:# Historical atexit cleanup may run after the update's result is fixed.diff --git a/hermes_cli/gitlock.py b/hermes_cli/gitlock.pyindex d77d533de46..43a7634e4c0 100644--- a/hermes_cli/gitlock.py+++ b/hermes_cli/gitlock.py@@ -283,8 +283,9 @@ def repair_broken_shallow_boundaries(repo_root: Path) -> int:if probe.returncode == 0:return 0with _ShallowLock(shallow_path):- original = shallow_path.read_text(encoding="utf-8")- existing = {line for line in original.splitlines() if line}+ # Keep the rollback image byte-exact, including BOM and line endings.+ original = shallow_path.read_bytes()+ existing = {line for line in original.decode("utf-8-sig").splitlines() if line}if not existing:return 0# Boundary candidates: commits recorded as *fetch tips* in remote-tracking@@ -314,7 +315,7 @@ def repair_broken_shallow_boundaries(repo_root: Path) -> int:# Self-check under the same lock hold (rev-list never takes# shallow.lock): the rollback cannot be defeated by lock contention.if not _git_stdout_lines(repo_root, ["rev-list", "--count", "--all", "--reflog"]):- shallow_path.write_text(original, encoding="utf-8")+ shallow_path.write_bytes(original)logger.debug("shallow boundary repair self-check failed; file restored")return 0logger.info("Restored %d broken shallow boundary(ies) in %s", len(repaired), repo_root)@@ -343,7 +344,9 @@ def prune_stale_shallow_grafts(repo_root: Path) -> int:if shallow_path is None:return 0with _ShallowLock(shallow_path):- lines = [line for line in shallow_path.read_text(encoding="utf-8").splitlines() if line]+ # Decode for pruning, but retain the same capture for a lossless rollback.+ original = shallow_path.read_bytes()+ lines = [line for line in original.decode("utf-8-sig").splitlines() if line]if not lines:return 0keep = set(lines) & {@@ -353,7 +356,6 @@ def prune_stale_shallow_grafts(repo_root: Path) -> int:}if len(keep) == len(lines):return 0- original = shallow_path.read_text(encoding="utf-8")_write_shallow(shallow_path, "\n".join(sorted(keep)) + "\n", suffix=".hermes-prune")# Fail-safe: if any reachable walk now crosses a boundary we wrongly# removed, put the grafts back — a growing file beats a broken repo.@@ -363,7 +365,7 @@ def prune_stale_shallow_grafts(repo_root: Path) -> int:_git_stdout_lines(repo_root, ["rev-list", "--count", "--all"]) and \_git_stdout_lines(repo_root, ["rev-list", "--count", "--all", "--reflog"])if not still_walks:- shallow_path.write_text(original, encoding="utf-8")+ shallow_path.write_bytes(original)logger.debug("shallow prune self-check failed; grafts restored")return 0logger.info("Pruned %d stale shallow graft(s) in %s", len(lines) - len(keep), repo_root)diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex 668e9c5af2a..da9fbf8d96b 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -70,7 +70,7 @@ def run_completion(request: dict) -> dict:try:if os.name == "posix":try:- os.killpg(proc.pid, signal.SIGKILL)+ os.killpg(proc.pid, signal.SIGKILL) # windows-footgun: ok — os.name == "posix"; own isolated groupexcept ProcessLookupError:passelse:@@ -92,7 +92,7 @@ def run_completion(request: dict) -> dict:proc.stdout.close()code = _exit_status(code)try:- result = json.loads(result_path.read_text(encoding="utf-8"))+ result = json.loads(result_path.read_text(encoding="utf-8-sig"))if result["schema"] != 1 or result["update_id"] != request["receipt"]["update_id"]:raise ValueError("completion response identity mismatch")if result["exit_code"] != code:@@ -126,7 +126,7 @@ def _read_terminal_receipt(request: dict) -> dict | None:directory = Path(request["home"]) / "logs/update_receipts"# Never latest.json: another profile/context may have finalized more recently.for path in directory.glob(f"update_*_{request['receipt']['update_id']}.json"):- data = json.loads(path.read_text(encoding="utf-8"))+ data = json.loads(path.read_text(encoding="utf-8-sig"))if data.get("update_id") == request["receipt"]["update_id"] and data.get("finished_at"):return datareturn None@@ -245,7 +245,7 @@ def _finish(request: dict, result_path: Path) -> int:def main() -> int:request_path, result_path = map(Path, sys.argv[1:3])- request = json.loads(request_path.read_text(encoding="utf-8"))+ request = json.loads(request_path.read_text(encoding="utf-8-sig"))if request["schema"] != 1:raise ValueError("unsupported source completion request")root = Path(__file__).resolve().parents[1]diff --git a/hermes_cli/update_finish.py b/hermes_cli/update_finish.pyindex 55a8bf4ecff..1149a586b7d 100644--- a/hermes_cli/update_finish.py+++ b/hermes_cli/update_finish.py@@ -45,7 +45,7 @@ def _restore_plan(data):def main(context: Path, result: Path) -> int:- request = json.loads(context.read_text(encoding="utf-8"))+ request = json.loads(context.read_text(encoding="utf-8-sig"))root = Path(request["root"])sys.path.insert(0, str(root))from hermes_cli import update_receiptdiff --git a/hermes_cli/update_serve_resume.py b/hermes_cli/update_serve_resume.pyindex c4732f38da7..af862bdcc70 100644--- a/hermes_cli/update_serve_resume.py+++ b/hermes_cli/update_serve_resume.py@@ -9,7 +9,7 @@ import sysdef main(context: Path, result: Path) -> int:handled = Falsetry:- request = json.loads(context.read_text(encoding="utf-8"))+ request = json.loads(context.read_text(encoding="utf-8-sig"))root = Path(request["root"])token = request["stopped_serves"]if not token.get("pending"):diff --git a/tests/hermes_cli/test_old_updater_takeover.py b/tests/hermes_cli/test_old_updater_takeover.pyindex a9a9809b986..4f405c0aa99 100644--- a/tests/hermes_cli/test_old_updater_takeover.py+++ b/tests/hermes_cli/test_old_updater_takeover.py@@ -12,7 +12,8 @@ import pytest@pytest.mark.parametrize("status", [0, 7])-def test_takeover_waits_propagates_status_and_never_reenters_old_code(tmp_path, status):[email protected]("encoding", ["utf-8", "utf-8-sig"])+def test_takeover_waits_propagates_status_and_never_reenters_old_code(tmp_path, status, encoding):source = Path(__file__).resolve().parents[2]root = tmp_path / "updated checkout"package = root / "hermes_cli"@@ -33,10 +34,10 @@ def test_takeover_waits_propagates_status_and_never_reenters_old_code(tmp_path,"assert request['pre_update_version'] == 'old-version'\n""assert request['home'] == os.environ['HERMES_HOME']\n""with Path(request['home'], 'runs').open('a') as stream: stream.write('child\\n')\n"- "Path(sys.argv[2]).write_text(json.dumps({'resume_handled': True}))\n"+ f"Path(sys.argv[2]).write_text(json.dumps({{'resume_handled': True}}), encoding={encoding!r})\n"f"raise SystemExit({status})\n", encoding="utf-8",)- home = tmp_path / "isolated home"+ home = tmp_path / "isolated home 日本 café"home.mkdir()program = root / "historical.py"program.write_text(@@ -95,7 +96,7 @@ def test_only_known_early_updater_restarts_with_original_arguments(tmp_path, pos" _update_node_dependencies()\n""def cmd_update(post_pull):\n _cmd_update_impl(post_pull)\n", encoding="utf-8",)- home = tmp_path / "isolated home"+ home = tmp_path / "isolated home 日本 café"home.mkdir()argv = [str(root / "historical.py"), "--profile", "work profile", "update", "--yes","--keep-stash", "--switch-branch", "--force", "--gateway"]@@ -138,7 +139,7 @@ def test_atexit_recovers_only_stopped_serves_after_cached_update(tmp_path, acknof"Path(sys.argv[2]).write_text(json.dumps({{'serves_handled': {acknowledged!r}}} if cleanup else {{}}))\n"f"raise SystemExit({cleanup_status} if cleanup else 7)\n", encoding="utf-8",)- home = tmp_path / "isolated home"+ home = tmp_path / "isolated home 日本 café"home.mkdir()program = root / "historical.py"program.write_text(@@ -245,6 +246,36 @@ def test_serve_resume_child_leaves_token_unhandled_when_imports_fail(tmp_path):assert "Stopped serve recovery failed" in result.stderr[email protected]("encoding", ["utf-8", "utf-8-sig"])[email protected]("entrypoint", ["_update_takeover", "update_serve_resume"])+def test_completed_serve_token_is_acknowledged_without_preparation(tmp_path, encoding, entrypoint):+ source = Path(__file__).resolve().parents[2]+ root = tmp_path / "checkout 日本 café"+ package = root / "hermes_cli"+ package.mkdir(parents=True)+ for name in ("_update_takeover.py", "update_serve_resume.py"):+ shutil.copy2(source / "hermes_cli" / name, package / name)+ # Only selection is supplied. The two real entrypoints must carry the+ # request without importing PM or launching any completed backend twice.+ (package / "_launchers.py").write_text(+ "import sys\nresolve_store_python = lambda root: sys.executable\n", encoding="utf-8")+ (package / "runtime_paths.py").write_text(+ "import os\nactivation_environment = lambda root: dict(os.environ)\n", encoding="utf-8")+ context, result_path = tmp_path / "request.json", tmp_path / "result.json"+ context.write_text(json.dumps({"root": str(root), "stopped_serves": {"pending": False}},+ ensure_ascii=False), encoding=encoding)+ before = context.read_bytes()+ child = subprocess.run(+ [sys.executable, "-I", "-S", "-B", str(package / f"{entrypoint}.py"),+ str(context), str(result_path)], cwd=tmp_path, capture_output=True,+ text=True, encoding="utf-8", timeout=30,+ )+ assert child.returncode == 0, child.stdout + child.stderr+ assert json.loads(result_path.read_text(encoding="utf-8-sig")) == {"serves_handled": True}+ assert not result_path.read_bytes().startswith(b"\xef\xbb\xbf")+ assert context.read_bytes() == before++def test_bootstrap_lock_remains_live_without_application_dependencies(tmp_path):root = Path(__file__).resolve().parents[2]script = (diff --git a/tests/hermes_cli/test_shallow_boundary_repair.py b/tests/hermes_cli/test_shallow_boundary_repair.pyindex 465b894b6d8..eb5987f3d14 100644--- a/tests/hermes_cli/test_shallow_boundary_repair.py+++ b/tests/hermes_cli/test_shallow_boundary_repair.py@@ -13,6 +13,8 @@ from __future__ import annotationsimport subprocessfrom pathlib import Path+import pytest+import hermes_cli.gitlock as gitlock@@ -144,3 +146,40 @@ def test_repair_does_not_mask_unrelated_object_loss(tmp_path):assert gitlock.repair_broken_shallow_boundaries(clone) == 0fsck = git(clone, "fsck", "--connectivity-only", check=False)assert "missing" in (fsck.stdout + fsck.stderr) or "broken link" in (fsck.stdout + fsck.stderr)++[email protected]("operation", ["repair", "prune"])+def test_failed_shallow_maintenance_restores_original_bytes(tmp_path, caplog, operation):+ clone = fixture(tmp_path)+ if operation == "repair":+ corrupt_fixture(clone)+ git(clone, "config", "user.email", "[email protected]")+ git(clone, "config", "user.name", "t")+ git(clone, "commit", "--allow-empty", "-qm", "local1")+ git(clone, "commit", "--allow-empty", "-qm", "local2")+ victim = git(clone, "rev-parse", "HEAD~1").stdout.strip()+ (clone / ".git/objects" / victim[:2] / victim[2:]).unlink()+ shallow = clone / ".git/shallow"+ # A failed self-check must restore even noncanonical line endings verbatim.+ original = shallow.read_bytes().replace(b"\n", b"\r\n")+ shallow.write_bytes(original)+ assert not _walks(clone)+ with caplog.at_level("DEBUG", logger="hermes_cli.gitlock"):+ maintain = (gitlock.repair_broken_shallow_boundaries if operation == "repair"+ else gitlock.prune_stale_shallow_grafts)+ assert maintain(clone) == 0+ assert "self-check failed" in caplog.text+ assert shallow.read_bytes() == original+ assert not shallow.with_suffix(".lock").exists()++[email protected]("bom", [b"", b"\xef\xbb\xbf"])+def test_bom_shallow_prune_rolls_back_without_losing_bytes(tmp_path, caplog, bom):+ clone = fixture(tmp_path)+ shallow = clone / ".git/shallow"+ original = bom + shallow.read_bytes().replace(b"\n", b"\r\n")+ shallow.write_bytes(original)+ with caplog.at_level("DEBUG", logger="hermes_cli.gitlock"):+ assert gitlock.prune_stale_shallow_grafts(clone) == 0+ assert "self-check failed" in caplog.text+ assert shallow.read_bytes() == originaldiff --git a/tests/hermes_cli/test_update_completion_process.py b/tests/hermes_cli/test_update_completion_process.pyindex bfb1eedf846..0f1b8eacb81 100644--- a/tests/hermes_cli/test_update_completion_process.py+++ b/tests/hermes_cli/test_update_completion_process.py@@ -119,7 +119,7 @@ def transition(tmp_path):" path = pathlib.Path(os.environ['HERMES_HOME']) / 'logs/update_receipts'\n"" path.mkdir(parents=True, exist_ok=True)\n"" path = path / ('update_test_' + r.correlation_id + '.json')\n"- " path.write_text(json.dumps(r.data))\n"+ " path.write_text(json.dumps(r.data, ensure_ascii=False), encoding=r.data.get('encoding', 'utf-8'))\n"" _current.set(None)\n"" return path\n")@@ -138,10 +138,14 @@ def transition(tmp_path):return root, git, old, new, request-def test_old_process_new_git_tree_completes_in_fresh_python(transition, tmp_path):[email protected]("bom_boundary", [None, "request", "receipt"])+def test_old_process_new_git_tree_completes_in_fresh_python(transition, tmp_path, bom_boundary):from hermes_cli import update_completionroot, git, old, new, request = transition+ request["pre_update_version"] = "日本 café"+ if bom_boundary == "receipt":+ request["receipt"]["encoding"] = "utf-8-sig"# Copy executable code, not its text shape: the process exercises the real transport.shutil.copy2(update_completion.__file__, root / "hermes_cli/update_completion.py")git("add", ".")@@ -152,6 +156,8 @@ def test_old_process_new_git_tree_completes_in_fresh_python(transition, tmp_path"import importlib.util, json, os, subprocess, sys\n""spec = importlib.util.spec_from_file_location('transport', sys.argv[1])\n""transport = importlib.util.module_from_spec(spec); spec.loader.exec_module(transport)\n"+ f"if {bom_boundary == 'request'!r}:\n"+ " transport._write_json = lambda path, data: path.write_text(json.dumps(data, ensure_ascii=False), encoding='utf-8-sig')\n""import pm\nassert pm.OLD_API\n""subprocess.run(['git', 'checkout', sys.argv[2]], check=True)\n""result = transport.run_completion(json.loads(sys.argv[3]))\n"@@ -176,6 +182,7 @@ def test_old_process_new_git_tree_completes_in_fresh_python(transition, tmp_pathassert by_name["build"]["pid"] == by_name["maintenance"]["pid"] == by_name["restart"]["pid"]assert by_name["maintenance"]["snapshots"] == {"work": "work-before"}assert by_name["maintenance"]["pre_update_snapshot_id"] == "active-before"+ assert by_name["maintenance"]["pre_update_version"] == "日本 café"assert by_name["restart"]["profiles"] == ["work"]assert [e["name"] for e in events].index("exit_marker") < [e["name"] for e in events].index("restart")@@ -589,17 +596,22 @@ def test_taskkill_failure_still_reaps_child_and_preserves_interrupt(tmp_path, mochild.wait(timeout=5)-def test_forged_terminal_receipt_cannot_acknowledge_success(transition):[email protected]("encoding", ["utf-8", "utf-8-sig"])[email protected]("correlated", [False, True])+def test_only_correlated_terminal_receipt_can_acknowledge_success(transition, encoding, correlated):from hermes_cli.update_completion import run_completionroot, git, old, new, request = transition+ receipt = {"update_id": request["receipt"]["update_id"] if correlated else "wrong",+ "outcome": "success", "finished_at": "now", "detail": "日本 café"}(root / "hermes_cli/update_completion.py").write_text("import json, pathlib, sys\n""request = json.loads(pathlib.Path(sys.argv[1]).read_text())\n""pathlib.Path(sys.argv[2]).write_text(json.dumps(dict(\n"" schema=1, update_id=request['receipt']['update_id'], exit_code=0,\n"- " windows_resume={}, receipt={'update_id': 'wrong', 'outcome': 'success'})))\n"+ f" windows_resume={{}}, receipt={receipt!r}), ensure_ascii=False), encoding={encoding!r})\n",+ encoding="utf-8",)response = run_completion(request)- assert response["exit_code"] != 0- assert response["receipt"] is None+ assert response["exit_code"] == (0 if correlated else 1)+ assert response["receipt"] == (receipt if correlated else None)diff --git a/tests/hermes_cli/test_update_finish.py b/tests/hermes_cli/test_update_finish.pyindex 2a307cca9f3..8d6259df58e 100644--- a/tests/hermes_cli/test_update_finish.py+++ b/tests/hermes_cli/test_update_finish.py@@ -108,7 +108,7 @@ def completion(tmp_path, monkeypatch):import syscontext, result, fault = sys.argv[1:]- request = json.loads(Path(context).read_text())+ request = json.loads(Path(context).read_text(encoding="utf-8-sig"))root = Path(request['root'])sys.path.insert(0, str(root))@@ -225,6 +225,8 @@ def test_failure_preserves_original_receipt_before_build(completion, fault):message = "kind"elif fault == "receipt":message = "cannot accept prepared receipt"+ request["receipt"]["steps"][0]["detail"] = "日本 café"+ context.write_text(json.dumps(request, ensure_ascii=False), encoding="utf-8-sig")before = context.read_bytes()child = run(fault)assert child.returncode == 1, child.stdout + child.stderr