The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): ZIP recovery deletes only the entries its journal proves it made
Teknium896672770710
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.pyindex 14b5184d742..88b6a423c16 100644--- a/hermes_cli/_early_recovery.py+++ b/hermes_cli/_early_recovery.py@@ -6,6 +6,7 @@ import contextlibimport errnoimport osimport re+import statimport subprocessimport sysimport time@@ -692,11 +693,30 @@ def zip_swap_owner_lock(root: Path, *, wait: float = 0.0):os.close(fd)-def write_zip_swap_journal(root: Path, phase: str, entries: list) -> None:+def write_zip_swap_journal(root: Path, phase: str, entries: list, gen: str) -> None:+ """Publish the swap journal: ``entries`` are ``[name, existed, staged_id, live_id]`` (ids from+ ``zip_entry_identity``, "" while unknown); ``gen`` is the run's random tag (its backup temps)."""import jsonwrite_durable_text(Path(root) / ZIP_SWAP_JOURNAL,- json.dumps({"pid": os.getpid(), "phase": phase, "entries": entries}))+ json.dumps({"pid": os.getpid(), "gen": gen, "phase": phase, "entries": entries}))+++def zip_entry_identity(path) -> str:+ """The entry's own identity (lstat, never its target); "" when absent or unidentifiable.++ The ZIP journal's provenance: recovery deletes only an entry whose identity it recorded when the+ swap made it (a staging copy, or the live entry its backup links/renames), never a lookalike. A+ non-directory adds size and mtime: a file deleted and recreated often gets the same inode back.+ A directory is ``dev:ino:type`` only: a staged tree's own mtime moves while it is being filled."""+ try:+ st = os.lstat(path)+ except OSError:+ return ""+ if not st.st_ino:+ return ""+ base = f"{st.st_dev}:{st.st_ino}:{stat.S_IFMT(st.st_mode):o}"+ return base if stat.S_ISDIR(st.st_mode) else f"{base}:{st.st_size}:{st.st_mtime_ns}"def write_durable_text(path: Path, text: str) -> None:@@ -729,7 +749,6 @@ def write_durable_text(path: Path, text: str) -> None:def _drop_path(path: Path) -> None:if path.is_dir() and not path.is_symlink():import shutil- import stattry:shutil.rmtree(path)@@ -756,8 +775,8 @@ def _drop_path(path: Path) -> None:path.unlink()-def _parse_zip_swap_journal(raw: str) -> tuple[str, list[tuple[str, bool]]] | None:- """``(phase, [(entry name, existed)])`` from a journal this code wrote, else None."""+def _parse_zip_swap_journal(raw: str) -> tuple[str, str, list[tuple[str, bool, str, str]]] | None:+ """``(phase, gen, [(entry name, existed, staged_id, live_id)])`` from a journal this code wrote, else None."""import jsontry:@@ -766,13 +785,62 @@ def _parse_zip_swap_journal(raw: str) -> tuple[str, list[tuple[str, bool]]] | Noreturn Noneif not isinstance(data, dict) or data.get("phase") not in ("staging", "swapping", "committed"):return None- entries = data.get("entries")- if not isinstance(entries, list):+ entries, gen = data.get("entries"), data.get("gen")+ if not isinstance(entries, list) or not isinstance(gen, str) or not re.fullmatch(r"[0-9a-f]{12}", gen):return None- if not all(isinstance(e, list) and len(e) == 2 and isinstance(e[0], str) and isinstance(e[1], bool)- and e[0] not in ("", ".", "..") and "/" not in e[0] and "\\" not in e[0] for e in entries):+ if not all(isinstance(e, list) and len(e) == 4 and all(isinstance(v, str) for v in (e[0], e[2], e[3]))+ and isinstance(e[1], bool) and e[0] not in ("", ".", "..") and "/" not in e[0] and "\\" not in e[0]+ for e in entries):return None- return data["phase"], [(name, existed) for name, existed in entries]+ return data["phase"], gen, [(name, existed, staged, live) for name, existed, staged, live in entries]+++def _discard_unless_owned(path: Path, identity: str, kept: list[Path]) -> None:+ """Delete ``path`` only when it is provably the entry the swap recorded; anything else (a later+ user file at the suffix, a foreign journal's victim) is renamed aside, never deleted (review Z1)."""+ if not os.path.lexists(path):+ return+ if identity and zip_entry_identity(path) == identity:+ _drop_path(path)+ else:+ kept.append(_keep_aside(path))+++def _settle_zip_entry(root: Path, phase: str, gen: str, entry: tuple[str, bool, str, str], kept: list[Path]) -> bool:+ """Finish or roll back one journaled entry; True when the live tree changed.++ Presence is the ENTRY's (lexists/lstat), never its target's: a dangling symlink backup is the only+ copy of a tracked symlink, not "no backup" (review Z3). Restoring a backup never deletes bytes, so+ it needs no provenance; every deletion does (``_discard_unless_owned``)."""+ name, existed, staged_id, live_id = entry+ here = os.path.lexists+ dst = root / name+ staging, old = Path(f"{dst}{_ZIP_STAGING_SUFFIX}"), Path(f"{dst}{_ZIP_OLD_SUFFIX}")+ changed = False+ if phase == "swapping":+ # Staging finished before this phase, so a backup now is the one the swap made from the old+ # entry: it existed, whatever an older journal recorded.+ existed = existed or here(old)+ if existed and here(old) and not (live_id and zip_entry_identity(dst) == live_id):+ if (old.is_file() and not old.is_symlink() and staged_id and zip_entry_identity(dst) == staged_id+ and not dst.is_dir()):+ os.replace(old, dst) # a file entry never goes missing, not even here+ else:+ _discard_unless_owned(dst, staged_id, kept)+ os.rename(old, dst) # moves a symlink itself, never its target+ changed = True+ elif not existed and here(dst) and not here(staging):+ _discard_unless_owned(dst, staged_id, kept)+ changed = True+ elif existed and not here(dst) and here(old):+ os.rename(old, dst) # the backup is the only copy left+ changed = True+ for leftover, identity in ((staging, staged_id), (old, live_id)):+ _discard_unless_owned(leftover, identity, kept)+ # ``<old>.<gen>.tmp``: a backup copy killed before its rename (no-hardlink file systems); the run's+ # unpredictable tag is its provenance.+ _drop_path(Path(f"{old}.{gen}.tmp"))+ return changeddef restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:@@ -783,6 +851,8 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:the venv was built for; ``hermes update`` redoes it). ``staging``: nothing live moved -> drop thestaging copies. Either way no ``*.hermes-update-staging``/``-old`` sibling is left to wedge thenext run's free-space or dirty-tree checks. A live owner (lock held) is never second-guessed.+ Provenance (review Z1): a sibling or entry is deleted only when its identity is the one the journal+ recorded; anything else is kept aside under a ``.hermes-update-kept`` name and reported."""root = _project_root() if project_root is None else Path(project_root)journal = root / ZIP_SWAP_JOURNAL@@ -806,43 +876,24 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:"it and every `*.hermes-update-old` backup were kept. Put back what each backup replaced ""(or reinstall), then delete the journal.", file=sys.stderr)return False- phase, entries = parsed+ phase, gen, entries = parsedchanged = Falsefailed = False- # Presence is the ENTRY's (lexists/lstat), never its target's: a dangling symlink backup is the- # only copy of a tracked symlink, not "no backup" (review Z3).- here = os.path.lexists- for name, existed in reversed(entries):- dst = root / name- staging, old = Path(f"{dst}{_ZIP_STAGING_SUFFIX}"), Path(f"{dst}{_ZIP_OLD_SUFFIX}")+ kept: list[Path] = []+ for entry in reversed(entries):try:- if phase == "swapping":- # Staging finished before this phase, so a backup now is the one the swap made- # from the old entry: it existed, whatever an older journal recorded.- existed = existed or here(old)- if existed and here(old):- if old.is_file() and not old.is_symlink() and not dst.is_dir():- os.replace(old, dst) # a file entry never goes missing, not even here- else:- _drop_path(dst)- os.rename(old, dst) # moves a symlink itself, never its target- changed = True- elif not existed and here(dst) and not here(staging):- _drop_path(dst)- changed = True- elif existed and not here(dst) and here(old):- os.rename(old, dst) # the backup is the only copy left- changed = True- # ``<old>.tmp``: a backup copy killed before its rename (no-hardlink file systems).- for leftover in (staging, old, Path(f"{old}.tmp")):- _drop_path(leftover)+ changed = _settle_zip_entry(root, phase, gen, entry, kept) or changedexcept OSError as exc:failed = True- print(f"⚠ Could not settle {name} after an interrupted ZIP update: {exc}", file=sys.stderr)+ print(f"⚠ Could not settle {entry[0]} after an interrupted ZIP update: {exc}", file=sys.stderr)+ if kept:+ print("⚠ An interrupted ZIP update's recovery found entries it could not prove were its own and "+ f"kept them aside instead of deleting them: {', '.join(map(str, kept))}. Delete each once "+ "you know it is not yours.", file=sys.stderr)# Retire the journal only on a verified terminal state, not an exception-free loop: no sibling# (staging copy, backup, backup temp) left that only this journal could still explain.- siblings = (_ZIP_STAGING_SUFFIX, _ZIP_OLD_SUFFIX, _ZIP_OLD_SUFFIX + ".tmp")- unsettled = [name for name, _existed in entries if any(here(f"{root / name}{s}") for s in siblings)]+ siblings = (_ZIP_STAGING_SUFFIX, _ZIP_OLD_SUFFIX, f"{_ZIP_OLD_SUFFIX}.{gen}.tmp")+ unsettled = [e[0] for e in entries if any(os.path.lexists(f"{root / e[0]}{x}") for x in siblings)]if failed or unsettled:if unsettled and not failed:print(f"⚠ The interrupted ZIP update left {', '.join(unsettled)} unsettled; its journal "diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex a67d3a0339d..056b359c7c9 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -15,7 +15,8 @@ from pathlib import Pathfrom typing import Collection, Optionalfrom hermes_cli._early_recovery import (- ZIP_SWAP_JOURNAL, _drop_path, restore_interrupted_zip_swap, write_zip_swap_journal, zip_swap_owner_lock)+ ZIP_SWAP_JOURNAL, _drop_path, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity,+ zip_swap_owner_lock)# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.update_cmd")@@ -75,9 +76,10 @@ def _atomic_replace_dir(src: str, dst: str) -> None:_commit_staged_replacements([(_stage_replacement(src, dst), dst)])-def _stage_replacement(src: str, dst: str) -> str:+def _stage_replacement(src: str, dst: str, on_created=None) -> str:"""Phase 1: copy *src* (dir or file) to a sibling staging path for *dst*; return it.- Touches nothing live, so a failure here leaves the install untouched."""+ Touches nothing live, so a failure here leaves the install untouched. ``on_created(staging)`` runs+ once the staging entry exists (a directory: before it is filled), so the journal can record it."""staging = f"{dst}.hermes-update-staging"backup = f"{dst}.hermes-update-old"# A prior run may have died mid-swap leaving the backup as the ONLY copy. Restore it BEFORE@@ -86,16 +88,32 @@ def _stage_replacement(src: str, dst: str) -> str:os.rename(backup, dst)# Fail closed: a leftover backup that survives would later be taken for this swap's own backup# (rollback and journal recovery put it back as the live entry).- for leftover in (staging, backup, f"{backup}.tmp"):+ for leftover in (staging, backup):_drop_path(Path(leftover))if os.path.lexists(leftover):raise OSError(f"could not remove the leftover {leftover}")# Never through the reusable pathname: copy2 opens it following a symlink planted after the sweep# (review Z2). copytree's own os.mkdir is exclusive and never follows; a file is created the same way.if os.path.isdir(src):- shutil.copytree(src, staging)+ os.mkdir(staging)+ made = zip_entry_identity(staging)+ if on_created is not None:+ on_created(staging)+ if zip_entry_identity(staging) != made: # swapped while the journal recorded it: never fill that+ raise OSError(f"the staging directory {staging} was replaced while it was being created")+ try:+ shutil.copytree(src, staging, dirs_exist_ok=True)+ except BaseException:+ # A failed stage leaves nothing (a full disk must not shrink further on the retry). Best+ # effort, like _discard_staged: the journal's recovery drops what this cannot.+ with suppress(OSError):+ if zip_entry_identity(staging) == made:+ _remove_path(staging)+ raiseelse:_copy_file_exclusive(src, staging)+ if on_created is not None:+ on_created(staging)return staging@@ -144,12 +162,13 @@ def _hardlink_backup(path: str, backup: str) -> bool:return True-def _file_backup(path: str, backup: str) -> None:+def _file_backup(path: str, backup: str, tag: str = "") -> None:"""Back up the regular file ``path`` as a complete ``backup`` while ``path`` stays in place: a hardlink,- or where links are unsupported (FAT32/exFAT/SMB) a synced copy landed whole by ``os.replace``."""+ or where links are unsupported (FAT32/exFAT/SMB) a synced copy landed whole by ``os.replace``. The+ copy's temp carries the journal's random ``tag``: recovery deletes only its own run's temp."""if _hardlink_backup(path, backup):return- tmp = f"{backup}.tmp"+ tmp = f"{backup}.{tag or os.urandom(6).hex()}.tmp"try:_copy_file_exclusive(path, tmp, sync=True) # never through a planted <backup>.tmp link (Z2)os.replace(tmp, backup)@@ -159,7 +178,7 @@ def _file_backup(path: str, backup: str) -> None:raise-def _commit_staged_replacements(staged, *, on_committed=None) -> None:+def _commit_staged_replacements(staged, *, on_committed=None, tag: str = "") -> None:"""Phase 2: swap every staged entry into place, rolling back all on failure.Per-entry safety wasn't enough: a partway failure over ~90 entries left a mixed-version tree (every@@ -182,7 +201,7 @@ def _commit_staged_replacements(staged, *, on_committed=None) -> None:for staging, dst in staged:backup = f"{dst}.hermes-update-old"if os.path.isfile(dst) and not os.path.islink(dst):- _file_backup(dst, backup)+ _file_backup(dst, backup, tag)swapped.append((dst, backup))os.replace(staging, dst)continue@@ -405,16 +424,19 @@ def _graft_nested_artifacts(item: str, live: str, staging: str) -> None:shutil.copytree(source, destination, symlinks=True, copy_function=_link_or_copy_artifact)-def _stage_entries(extracted: str, entries: list[str], project_root: str) -> list[tuple[str, str]]:+def _stage_entries(extracted: str, entries: list[str], project_root: str,+ on_created=None) -> list[tuple[str, str]]:"""Phase 1 for every entry; on failure nothing is live yet, so drop partial staging copies so a retrystarts from the same free space. Each entry is recorded BEFORE its copy starts: a copy that fails- partway (an unreadable source file) leaves a partial staging tree that must be dropped too."""+ partway (an unreadable source file) leaves a partial staging tree that must be dropped too.+ ``on_created(index, staging)``: the journal's hook as each staging entry comes into existence."""staged: list[tuple[str, str]] = []try:- for item in entries:+ for index, item in enumerate(entries):dst = os.path.join(project_root, item)staged.append((f"{dst}.hermes-update-staging", dst))- _stage_replacement(os.path.join(extracted, item), dst)+ _stage_replacement(os.path.join(extracted, item), dst,+ None if on_created is None else (lambda path, i=index: on_created(i, path)))# The source ZIP carries only source; the built outputs (#70337/#87331 release/, then# dist/, apps/desktop/node_modules and web_dist — #90495) exist only in the LIVE tree. Graft# them into the staged copy BEFORE the swap so the commit preserves them atomically.@@ -456,11 +478,20 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, taraise RuntimeError("another `hermes update` is swapping this install right now"if owned.reason == "busy" else f"no ZIP swap lock, no swap ({owned.reason})")# A leftover backup counts: _stage_replacement puts it back as the entry before the swap.+ # Each entry also carries the identities recovery needs before it may delete anything (review+ # Z1): its staging copy's, recorded as the copy comes into existence, and the live entry's (the+ # one its backup links or renames), recorded at the swapping phase.journal_entries = [[item, any(os.path.lexists(os.path.join(root, item + suffix))- for suffix in ("", ".hermes-update-old"))] for item in entries]- write_zip_swap_journal(root, "staging", journal_entries)+ for suffix in ("", ".hermes-update-old")), "", ""] for item in entries]+ gen = os.urandom(6).hex()+ write_zip_swap_journal(root, "staging", journal_entries, gen)++ def record_staged(index: int, staging: str) -> None:+ journal_entries[index][2] = zip_entry_identity(staging)+ write_zip_swap_journal(root, "staging", journal_entries, gen)+try:- staged = _stage_entries(extracted, entries, str(root))+ staged = _stage_entries(extracted, entries, str(root), record_staged)except BaseException:_drop_journal_if_clean(root, entries) # _stage_entries dropped its copies, if it couldraise@@ -494,9 +525,11 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, taraise SyntaxError(f"{rel}: {reason}")# The commit point: tail + fleet restart owed before the first live rename._commit.arm_commit_obligations(root, target_sha or "")- write_zip_swap_journal(root, "swapping", journal_entries)+ for entry in journal_entries:+ entry[3] = zip_entry_identity(root / entry[0])+ write_zip_swap_journal(root, "swapping", journal_entries, gen)_commit_staged_replacements(- staged, on_committed=lambda: write_zip_swap_journal(root, "committed", journal_entries))+ staged, on_committed=lambda: write_zip_swap_journal(root, "committed", journal_entries, gen), tag=gen)# Committed: the new tree is whole. A journal that cannot go now (AV/indexer holding it) says# "committed", which the next launch's recovery settles by keeping the new tree.with suppress(OSError):diff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.pyindex 15bc737281b..d91d5820532 100644--- a/tests/hermes_cli/test_early_recovery.py+++ b/tests/hermes_cli/test_early_recovery.py@@ -205,7 +205,7 @@ def test_zip_journal_writer_never_writes_through_a_preexisting_temp(tmp_path, litmp.symlink_to(secret)except OSError:pytest.skip("symlinks need privileges here")- er.write_zip_swap_journal(root, "staging", [["a.py", True]])+ er.write_zip_swap_journal(root, "staging", [["a.py", True, "", ""]], "0123456789ab")assert secret.read_text(encoding="utf-8-sig") == "API_KEY=keep\n"journal = root / er.ZIP_SWAP_JOURNALassert not journal.is_symlink() and '"phase": "staging"' in journal.read_text(encoding="utf-8-sig")@@ -218,8 +218,8 @@ def test_zip_journal_publication_never_deletes_a_file_at_its_old_fixed_temp_nameroot.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]])+ er.write_zip_swap_journal(root, "staging", [["a.py", True, "", ""]], "0123456789ab")+ er.write_zip_swap_journal(root, "swapping", [["a.py", True, "", ""]], "0123456789ab")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])@@ -246,7 +246,9 @@ def test_an_interrupted_swap_restores_its_backup_by_entry_not_by_target(tmp_pathelse:_symlink_or_skip(old, "gone.txt" if kind == "dangling-symlink" else "target.txt")(root / "alpha").write_text("NEW", encoding="utf-8")- er.write_zip_swap_journal(root, "swapping", [["alpha", True]])+ # As the swap journals it: the staged copy (now live) and the moved-aside original by identity.+ er.write_zip_swap_journal(root, "swapping", [["alpha", True, er.zip_entry_identity(root / "alpha"),+ er.zip_entry_identity(old)]], "0123456789ab")assert er.restore_interrupted_zip_swap(root) is Truealpha = root / "alpha"@@ -269,8 +271,8 @@ def test_an_unparsed_zip_journal_keeps_itself_and_every_backup(tmp_path, monkeyp"b.py.hermes-update-staging": "NEW_B"}.items():(root / name).write_text(text, encoding="utf-8")journal = root / er.ZIP_SWAP_JOURNAL- journal.write_text('{"phase": "swapping", "entries": [["a.py", true], ["b.py", true]]}'- if body == "read-error" else body, encoding="utf-8")+ journal.write_text('{"phase": "swapping", "gen": "0123456789ab", "entries": [["a.py", true, "", ""], '+ '["b.py", true, "", ""]]}' if body == "read-error" else body, encoding="utf-8")if body == "read-error": # one transient read failure (AV scan, sharing violation)real = Path.read_textdiff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.pyindex f0f0d4b3194..650fd1c6643 100644--- a/tests/hermes_cli/test_update_zip_fallback_guards.py+++ b/tests/hermes_cli/test_update_zip_fallback_guards.py@@ -333,13 +333,14 @@ def test_zip_gate_refuses_on_a_user_file_at_the_old_fixed_journal_temp_name(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+ from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, write_zip_swap_journal, zip_entry_identity_git_install(tmp_path)leftover = tmp_path / "alpha.hermes-update-staging"leftover.mkdir()(leftover / "x.py").write_text("x = 2\n", encoding="utf-8")- write_zip_swap_journal(tmp_path, "staging", [["alpha", True], ["cli.py", True]])+ write_zip_swap_journal(tmp_path, "staging", [["alpha", True, zip_entry_identity(leftover), ""],+ ["cli.py", True, "", ""]], "0123456789ab")monkeypatch.setattr(hermes_main, "PROJECT_ROOT", tmp_path)update_cmd._abort_zip_update_if_dirty_tree()assert not leftover.exists() and not (tmp_path / ZIP_SWAP_JOURNAL).exists()diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.pyindex d4cb0d0f39d..f96b7b15b0e 100644--- a/tests/hermes_cli/test_update_zip_two_phase.py+++ b/tests/hermes_cli/test_update_zip_two_phase.py@@ -662,14 +662,16 @@ def test_a_backup_copy_killed_before_its_rename_is_cleared_by_the_recovery(tmp_p"""On a file system without hardlinks ``_file_backup`` copies to ``<entry>.hermes-update-old.tmp``first. A kill inside that copy left the temp behind: recovery dropped only staging and the backup,so every later ZIP update refused on "uncommitted changes" (review C4)."""- from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap, write_zip_swap_journal+ from hermes_cli._early_recovery import (+ ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap, write_zip_swap_journal, zip_entry_identity)live = tmp_path / "live"live.mkdir()(live / "a.py").write_text("old\n", encoding="utf-8")(live / "a.py.hermes-update-staging").write_text("new\n", encoding="utf-8")- (live / "a.py.hermes-update-old.tmp").write_text("ol", encoding="utf-8") # the killed copy- write_zip_swap_journal(live, "swapping", [["a.py", True]])+ (live / "a.py.hermes-update-old.0123456789ab.tmp").write_text("ol", encoding="utf-8") # the killed copy+ write_zip_swap_journal(live, "swapping", [["a.py", True, zip_entry_identity(live / "a.py.hermes-update-staging"),+ zip_entry_identity(live / "a.py")]], "0123456789ab")restore_interrupted_zip_swap(live)@@ -678,6 +680,83 @@ def test_a_backup_copy_killed_before_its_rename_is_cleared_by_the_recovery(tmp_passert (live / "a.py").read_text(encoding="utf-8") == "old\n"+def _swap_killed(tmp_path, monkeypatch, *, live: dict, new: dict, install_first: bool) -> Path:+ """Run the real journaled stage+swap and kill it inside the swap: nothing renamed yet, or only the+ first staged entry renamed into place. The journal the real writer left is what recovery reads."""+ from hermes_cli import update_cmd_commit+ from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL++ root, extracted = tmp_path / "live", tmp_path / "extracted"+ for d, files in ((root, live), (extracted, new)):+ d.mkdir()+ for name, text in files.items():+ (d / name).write_text(text, encoding="utf-8")+ monkeypatch.setattr(update_cmd_commit, "arm_commit_obligations", lambda *a, **k: None)++ def killed(staged, **_kw):+ if install_first: # the real swap's first step: backup (hardlink) when live, then the rename+ staging, dst = staged[0]+ if os.path.lexists(dst):+ update_cmd_zip._file_backup(dst, dst + ".hermes-update-old")+ os.replace(staging, dst)+ raise RuntimeError("killed mid-swap")++ with monkeypatch.context() as fault:+ fault.setattr(update_cmd_zip, "_commit_staged_replacements", killed)+ with pytest.raises(RuntimeError, match="killed"):+ update_cmd_zip._journaled_stage_and_swap(str(extracted), sorted(new), root, None)+ assert (root / ZIP_SWAP_JOURNAL).exists(), "harness: the kill must leave the journal"+ return root+++def test_recovery_never_installs_or_deletes_a_backup_suffix_created_after_the_kill(tmp_path, monkeypatch):+ """A swap killed before any rename; then a user file appears at ``cli.py.hermes-update-old``. The+ path-only journal took it for the swap's backup: it overwrote the live cli.py with it, and the old+ bytes were gone (review Z1). Recovery now proves a backup is the entry it recorded before using or+ deleting it: the live file stays, the user's file is kept aside, byte for byte."""+ from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap++ root = _swap_killed(tmp_path, monkeypatch, live={"cli.py": "LIVE"}, new={"cli.py": "NEW"}, install_first=False)+ (root / "cli.py.hermes-update-old").write_text("USER LATER", encoding="utf-8")++ restore_interrupted_zip_swap(root)++ assert (root / "cli.py").read_text(encoding="utf-8") == "LIVE"+ kept = [p for p in root.iterdir() if p.read_bytes() == b"USER LATER"]+ assert len(kept) == 1 and kept[0].name != "cli.py"+ assert not (root / "cli.py.hermes-update-staging").exists() and not (root / ZIP_SWAP_JOURNAL).exists()+++def test_recovery_never_deletes_a_user_file_that_replaced_an_installed_entry(tmp_path, monkeypatch):+ """A new entry (notes.md) was renamed into place, then the swap was killed; the user then replaced+ notes.md with a file of their own. Recovery deleted whatever sat at the journaled name (review Z1);+ only the entry the swap installed (its recorded staging identity) may go."""+ from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap++ root = _swap_killed(tmp_path, monkeypatch, live={}, new={"notes.md": "NEW"}, install_first=True)+ (root / "notes.md").unlink()+ (root / "notes.md").write_text("USER NOTES", encoding="utf-8")++ restore_interrupted_zip_swap(root)++ assert [p.read_text(encoding="utf-8") for p in root.iterdir() if p.name.startswith("notes.md")] == ["USER NOTES"]+ assert not (root / ZIP_SWAP_JOURNAL).exists()+++def test_recovery_still_rolls_back_an_authentic_killed_swap(tmp_path, monkeypatch):+ """The control: a swap killed after installing its first entry rolls back to the old tree, and every+ staging copy and backup the swap itself made is deleted (provenance proven), with nothing kept aside."""+ from hermes_cli._early_recovery import ZIP_SWAP_JOURNAL, restore_interrupted_zip_swap++ root = _swap_killed(tmp_path, monkeypatch, live={"a.py": "OLD_A", "b.py": "OLD_B"},+ new={"a.py": "NEW_A", "b.py": "NEW_B", "c.py": "NEW_C"}, install_first=True)+ assert (root / "a.py").read_text(encoding="utf-8") == "NEW_A", "harness: a.py was installed"+ assert restore_interrupted_zip_swap(root) is True+ assert {p.name: p.read_text(encoding="utf-8") for p in root.iterdir() if not p.name.startswith(".")} == {+ "a.py": "OLD_A", "b.py": "OLD_B"}+ assert not (root / ZIP_SWAP_JOURNAL).exists()++@pytest.mark.parametrize("requires", [">=3.8", ">=3.99"])def test_the_zip_gate_never_admits_a_conflict_marker_even_for_a_newer_python(tmp_path, monkeypatch, requires):"""A release whose requires-python excludes this interpreter skipped the ZIP pre-commit gate