The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): durable records publish through an unpredictable temp and never delete a user's file
Teknium78b7de9cfb3c
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 4a5b3cad9b6..639f4ad6d78 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -695,21 +695,26 @@ def zip_swap_owner_lock(root: Path, *, wait: float = 0.0):def write_zip_swap_journal(root: Path, phase: str, entries: list) -> None:import json- journal = Path(root) / ZIP_SWAP_JOURNAL- write_durable_text(journal, json.dumps({"pid": os.getpid(), "phase": phase, "entries": entries}),- tmp=journal.with_name(journal.name + ".tmp"))+ write_durable_text(Path(root) / ZIP_SWAP_JOURNAL,+ json.dumps({"pid": os.getpid(), "phase": phase, "entries": entries}))-def write_durable_text(path: Path, text: str, *, tmp: Path | None = None) -> None:+def write_durable_text(path: Path, text: str) -> None:"""``text`` at ``path`` as one durable record, never a half-written one.- A fresh inode every time: writing into a pre-existing temp would follow its symlink or hardlink- onto another file (.env). fsync before the rename: an empty record over a mixed tree is no record.- The default temp name carries the pid, so two writers never unlink each other's temp.+ The temp is an unpredictable name created exclusively (no-follow) beside ``path``: a pre-existing+ name there is never written through (its symlink or hardlink would carry the record onto another+ file) and never deleted (it may be a user's file: review Z5). fsync before the rename: an empty+ record over a mixed tree is no record."""- tmp = tmp if tmp is not None else path.with_name(f"{path.name}.{os.getpid()}.tmp")- tmp.unlink(missing_ok=True)- fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o644)+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)+ while True:+ tmp = path.with_name(f"{path.name}.{os.urandom(6).hex()}.tmp")+ try:+ fd = os.open(tmp, flags, 0o644)+ break+ except FileExistsError:+ continue # 48 random bits taken: draw again, never reuse the nametry:with os.fdopen(fd, "w", encoding="utf-8") as handle:handle.write(text)diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 15580b3dcca..73230580703 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -24,8 +24,11 @@ _ZIP_STAGING_ARTIFACT_SUFFIXES = ".hermes-update-staging", ".hermes-update-old"# Hermes' own root breadcrumbs: the swap journal + its owner lock, and the update/refresh markers.# They are never user work, so the dirty-tree guard must not refuse (and wedge) on them._ZIP_HERMES_ROOT_ARTIFACTS = frozenset({- ".hermes-update-zip-swap", ".hermes-update-zip-swap.lock", ".hermes-update-zip-swap.tmp",- ".update-incomplete", ".lazy-refresh-incomplete"})+ ".hermes-update-zip-swap", ".hermes-update-zip-swap.lock", ".update-incomplete", ".lazy-refresh-incomplete"})+# A journal temp a killed writer left (``write_durable_text``'s unpredictable name). The swap never+# touches it (no ZIP ships it) and nothing deletes it, so admitting it risks no user bytes. A file at+# the old fixed ``.hermes-update-zip-swap.tmp`` name is no longer Hermes': it blocks (review Z5).+_ZIP_JOURNAL_TEMP = re.compile(r"\.hermes-update-zip-swap\.[0-9a-f]{12}\.tmp")# Single source of truth for entries the ZIP swap preserves — used by the dirty-tree filter and the swap loop._ZIP_PRESERVED_TOP_LEVEL = {"venv", ".venv", "node_modules", ".git", ".env"}@@ -270,7 +273,8 @@ def _is_zip_staging_artifact_status_line(line: str, staged: Collection[str] = ()entry this run staged. Any other ``*.hermes-update-staging``/``-old`` may be a user's file (a manual``cp -r tools tools.hermes-update-old``) that staging would delete, so it blocks."""top = _status_top_level(line[3:] if len(line) >= 3 else line)- return top in _ZIP_HERMES_ROOT_ARTIFACTS or top in {item + _ZIP_STAGING_ARTIFACT_SUFFIXES[0] for item in staged}+ return (top in _ZIP_HERMES_ROOT_ARTIFACTS or bool(_ZIP_JOURNAL_TEMP.fullmatch(top))+ or top in {item + _ZIP_STAGING_ARTIFACT_SUFFIXES[0] for item in staged})def _abort_zip_update_if_dirty_tree() -> None:diff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.pyindex d04384bcb1b..6a62e43d9be 100644--- a/tests/hermes_cli/test_early_recovery.py+++ b/tests/hermes_cli/test_early_recovery.py@@ -211,6 +211,20 @@ def test_zip_journal_writer_never_writes_through_a_preexisting_temp(tmp_path, liassert not journal.is_symlink() and '"phase": "staging"' in journal.read_text(encoding="utf-8-sig")+def test_zip_journal_publication_never_deletes_a_file_at_its_old_fixed_temp_name(tmp_path):+ """The writer unlinked ``.hermes-update-zip-swap.tmp`` before its exclusive create: a user's file by+ that name was erased (review Z5). Its temp is now unpredictable: the file survives, byte for byte."""+ root = tmp_path / "install"+ root.mkdir()+ user = root / (er.ZIP_SWAP_JOURNAL + ".tmp")+ user.write_text("USER NOTES\n", encoding="utf-8")+ er.write_zip_swap_journal(root, "staging", [["a.py", True]])+ er.write_zip_swap_journal(root, "swapping", [["a.py", True]])+ assert user.read_text(encoding="utf-8-sig") == "USER NOTES\n"+ assert '"phase": "swapping"' in (root / er.ZIP_SWAP_JOURNAL).read_text(encoding="utf-8-sig")+ assert sorted(p.name for p in root.iterdir()) == sorted([er.ZIP_SWAP_JOURNAL, user.name])++@pytest.mark.parametrize("body", ["", "{not json", '{"phase": "swap", "entries": [["a.py", true]]}','{"phase": "swapping", "entries": [["../a.py", true]]}', "read-error"])def test_an_unparsed_zip_journal_keeps_itself_and_every_backup(tmp_path, monkeypatch, body):diff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.pyindex af90e5ca4b8..f0f0d4b3194 100644--- a/tests/hermes_cli/test_update_zip_fallback_guards.py+++ b/tests/hermes_cli/test_update_zip_fallback_guards.py@@ -318,6 +318,19 @@ def test_zip_gate_refuses_and_keeps_a_user_file_named_like_an_update_artifact(tmassert (tmp_path / name).read_text(encoding="utf-8-sig") == "PRECIOUS USER BYTES"+def test_zip_gate_refuses_on_a_user_file_at_the_old_fixed_journal_temp_name(tmp_path, monkeypatch):+ """The gate exempted ``.hermes-update-zip-swap.tmp`` as Hermes' own before any journal existed, and+ the journal writer then deleted it (review Z5). Only the writer's unpredictable temp is exempt now."""+ _git_install(tmp_path)+ user = tmp_path / ".hermes-update-zip-swap.tmp"+ user.write_text("USER NOTES", encoding="utf-8")+ monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)+ with pytest.raises(SystemExit) as exc_info:+ update_cmd._abort_zip_update_if_dirty_tree()+ assert exc_info.value.code == 1 and user.read_text(encoding="utf-8-sig") == "USER NOTES"+ assert update_cmd._is_zip_staging_artifact_status_line("?? .hermes-update-zip-swap.0123456789ab.tmp")++def test_zip_gate_admits_the_retry_after_an_interrupted_swap(tmp_path, monkeypatch):"""The siblings an interrupted swap's journal owns never refuse the retry: they are settled first."""from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, write_zip_swap_journal