Skip to content

The agent that grows with you

fix(update): an unreadable or unknown ZIP journal keeps itself and every backup (review F33, F35, F16)

Tekniumfb4121cd0f2e
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index a5f67e28813..050f352784d 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -718,6 +718,25 @@ 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."""
+ import json
+
+ try:
+ data = json.loads(raw)
+ except ValueError:
+ return None
+ if not isinstance(data, dict) or data.get("phase") not in ("staging", "swapping", "committed"):
+ return None
+ entries = data.get("entries")
+ if not isinstance(entries, list):
+ 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):
+ return None
+ return data["phase"], [(name, existed) for name, existed in entries]
+
+
def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:
"""Finish or roll back a ZIP swap whose owner died; True when the tree changed (relaunch).
@@ -736,18 +755,23 @@ def restore_interrupted_zip_swap(project_root: Path | None = None) -> bool:
print(f"⚠ An interrupted ZIP update cannot be settled: {owned.reason}.", file=sys.stderr)
if not owned or not journal.is_file():
return False
- import json
-
try:
- data = json.loads(journal.read_text(encoding="utf-8-sig"))
- phase, entries = data["phase"], [(str(n), bool(e)) for n, e in data["entries"]]
- except (OSError, ValueError, KeyError, TypeError):
- phase, entries = "staging", [] # unreadable: never guess which live entry to move
+ raw = journal.read_text(encoding="utf-8-sig")
+ except OSError as exc: # transient (AV, sharing violation): the journal is still the record
+ print(f"⚠ Could not read the interrupted ZIP update's journal ({exc}); the next launch retries.",
+ file=sys.stderr)
+ return False
+ parsed = _parse_zip_swap_journal(raw)
+ if parsed is None:
+ # Never guess which live entry to move, and never retire the only record of a mixed tree.
+ print(f"⚠ The interrupted ZIP update's journal {journal} is unreadable or from another version; "
+ "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
changed = False
failed = False
for name, existed in reversed(entries):
- if not name or "/" in name or "\\" in name or name in (".", ".."):
- continue
dst = root / name
staging, old = Path(f"{dst}{_ZIP_STAGING_SUFFIX}"), Path(f"{dst}{_ZIP_OLD_SUFFIX}")
try:
diff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.py
index d33cc24a4da..22217b466f9 100644
--- a/tests/hermes_cli/test_early_recovery.py
+++ b/tests/hermes_cli/test_early_recovery.py
@@ -209,3 +209,31 @@ def test_zip_journal_writer_never_writes_through_a_preexisting_temp(tmp_path, li
assert secret.read_text(encoding="utf-8") == "API_KEY=keep\n"
journal = root / er.ZIP_SWAP_JOURNAL
assert not journal.is_symlink() and '"phase": "staging"' in journal.read_text(encoding="utf-8")
+
+
[email protected]("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):
+ """A mid-swap tree (a.py new with its backup, b.py old with its staging copy) whose journal cannot
+ be read or understood is never settled by guesswork: the journal and every sibling stay."""
+ root = tmp_path / "install"
+ root.mkdir()
+ for name, text in {"a.py": "NEW_A", "a.py.hermes-update-old": "OLD_A", "b.py": "OLD_B",
+ "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")
+ if body == "read-error": # one transient read failure (AV scan, sharing violation)
+ real = Path.read_text
+
+ def flaky(self, *args, **kwargs):
+ if self == journal:
+ raise PermissionError(13, "in use")
+ return real(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", flaky)
+ assert er.restore_interrupted_zip_swap(root) is False
+ assert journal.is_file()
+ assert {p.name: p.read_text(encoding="utf-8") for p in root.iterdir() if p != journal and p.suffix != ".lock"} == {
+ "a.py": "NEW_A", "a.py.hermes-update-old": "OLD_A", "b.py": "OLD_B", "b.py.hermes-update-staging": "NEW_B"}