The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the ZIP dirty-tree gate refuses on user files named like update artifacts instead of deleting them (review F15)
Teknium83bf7a59a3de
diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex 8f6107478b5..f09f4304f5b 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -184,13 +184,13 @@ def _commit_staged_replacements(staged, *, on_committed=None) -> None:def _zip_overlay_block_reason(- root: Path, *, ignore_staging_artifacts: bool = False, shipped: Optional[Collection[str]] = None,+ root: Path, *, staged: Collection[str] = (), shipped: Optional[Collection[str]] = None,) -> Optional[str]:"""Why overlaying a ZIP onto ``root`` would destroy work, or None if safe.The swap replaces every top-level entry (minus a tiny preserve set) and deletes backups, so uncommitted- edits and untracked files are gone. Fails closed when git status cannot run. ``ignore_staging_artifacts``- is for the pre-swap re-check: phase 1 leaves our own ``*.hermes-update-staging`` siblings that git+ edits and untracked files are gone. Fails closed when git status cannot run. ``staged`` is for the+ pre-swap re-check: phase 1 leaves ``<entry>.hermes-update-staging`` for those entries, which gitreports as untracked; without the filter the re-check always refuses. ``shipped`` is the extractedZIP's top-level entry set once known (the re-check); before the download the tracked root entries standin for it. A gitignored path under a root entry the ZIP does not ship is never touched by the swap.@@ -228,7 +228,7 @@ def _zip_overlay_block_reason(dirty = any(line.strip()and not _is_zip_preserved_entry_status_line(line, shipped)- and not (ignore_staging_artifacts and _is_zip_staging_artifact_status_line(line))+ and not _is_zip_staging_artifact_status_line(line, staged)for line in (result.stdout or "").splitlines())return "the working tree has uncommitted changes or untracked files" if dirty else None@@ -265,10 +265,12 @@ def _is_zip_preserved_entry_status_line(line: str, shipped: Optional[Collection[nested == keep or nested.startswith(f"{keep}/") for keep in _ZIP_PRESERVED_NESTED.get(top, ()))-def _is_zip_staging_artifact_status_line(line: str) -> bool:- """True when a porcelain status line is our own two-phase-swap artifact."""+def _is_zip_staging_artifact_status_line(line: str, staged: Collection[str] = ()) -> bool:+ """True when a porcelain status line is Hermes' own: a root breadcrumb, or the staging copy of an+ 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.endswith(_ZIP_STAGING_ARTIFACT_SUFFIXES) or top in _ZIP_HERMES_ROOT_ARTIFACTS+ return top in _ZIP_HERMES_ROOT_ARTIFACTS or top in {item + _ZIP_STAGING_ARTIFACT_SUFFIXES[0] for item in staged}def _abort_zip_update_if_dirty_tree() -> None:@@ -277,9 +279,10 @@ def _abort_zip_update_if_dirty_tree() -> None:See #87304."""from hermes_cli.update_cmd import _m- # Our own staging/backup siblings and breadcrumbs are never user work: counting them refused- # every retry after an interrupted swap (the next run's staging clears them per entry).- reason = _zip_overlay_block_reason(_m().PROJECT_ROOT, ignore_staging_artifacts=True)+ # Settle an interrupted swap first: only its journal tells its staging/backup siblings apart from a+ # user's lookalike file, and once settled none are left to refuse the retry on.+ restore_interrupted_zip_swap(_m().PROJECT_ROOT)+ reason = _zip_overlay_block_reason(_m().PROJECT_ROOT)if reason is None:returnprint(f"✗ ZIP fallback refused: {reason}.")@@ -429,7 +432,7 @@ def _journaled_stage_and_swap(extracted: str, entries: list[str], root: Path, ta# installed, so recovery must not delete whatever (a user's new file) now sits at that path.# TOCTOU re-check right before the swap: download + extract + staging can take minutes and# work created meanwhile would be destroyed. Our own staging siblings are filtered out.- recheck_reason = _zip_overlay_block_reason(root, ignore_staging_artifacts=True, shipped=entries)+ recheck_reason = _zip_overlay_block_reason(root, staged=entries, shipped=entries)if recheck_reason is not None:_discard_staged(staged)_drop_journal_if_clean(root, entries)diff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.pyindex 80aa379a1cb..d282261475c 100644--- a/tests/hermes_cli/test_update_zip_fallback_guards.py+++ b/tests/hermes_cli/test_update_zip_fallback_guards.py@@ -194,10 +194,13 @@ def test_status_uses_untracked_files_all(tmp_path, monkeypatch):def test_staging_artifact_lines_are_recognized():- is_artifact = update_cmd._is_zip_staging_artifact_status_line+ def is_artifact(line):+ return update_cmd._is_zip_staging_artifact_status_line(line, ["agent", "cli.py", "tools"])+assert is_artifact("?? agent.hermes-update-staging/")assert is_artifact("?? cli.py.hermes-update-staging")- assert is_artifact("?? tools.hermes-update-old/")+ # Staging already removed every backup: one at re-check time is not this run's (review F15).+ assert not is_artifact("?? tools.hermes-update-old/")# Nested user files under a staging-lookalike directory don't match the# top-level test only when the TOP level itself is not an artifact.assert not is_artifact("?? agent/scratch/wip.py")@@ -210,10 +213,10 @@ def test_recheck_ignores_own_staging_artifacts(tmp_path, monkeypatch):monkeypatch.setattr(update_cmd.subprocess,"run",- _porcelain_run("?? agent.hermes-update-staging/\n?? cli.py.hermes-update-old\n"),+ _porcelain_run("?? agent.hermes-update-staging/\n?? cli.py.hermes-update-staging\n"),)assert (- update_cmd._zip_overlay_block_reason(tmp_path, ignore_staging_artifacts=True)+ update_cmd._zip_overlay_block_reason(tmp_path, staged=["agent", "cli.py"])is None)# Without the flag the same output still refuses (pre-download check).@@ -228,7 +231,7 @@ def test_recheck_still_blocks_user_files_amid_staging_artifacts(tmp_path, monkey_porcelain_run("?? agent.hermes-update-staging/\n?? my-notes.md\n"),)reason = update_cmd._zip_overlay_block_reason(- tmp_path, ignore_staging_artifacts=True+ tmp_path, staged=["agent"])assert reason is not None@@ -292,6 +295,43 @@ def test_zip_overlay_flag_is_valid_against_real_git(tmp_path):+def _git_install(root):+ subprocess.run(["git", "init", "-q", str(root)], check=True)+ (root / "alpha").mkdir()+ (root / "alpha" / "x.py").write_text("x = 1\n", encoding="utf-8")+ (root / "cli.py").write_text("print('cli')\n", encoding="utf-8")+ subprocess.run(["git", "-C", str(root), "add", "-A"], check=True)+ subprocess.run(["git", "-C", str(root), "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "init"],+ check=True)++[email protected]("name", ["alpha.hermes-update-staging", "cli.py.hermes-update-old"])+def test_zip_gate_refuses_and_keeps_a_user_file_named_like_an_update_artifact(tmp_path, monkeypatch, name):+ """Staging deletes ``<entry>.hermes-update-staging``/``-old``: a user's own file by that name (no+ journal claims it) is user work the gate must refuse on, leaving it untouched."""+ _git_install(tmp_path)+ (tmp_path / name).write_text("PRECIOUS USER BYTES", 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+ assert (tmp_path / name).read_text(encoding="utf-8") == "PRECIOUS USER BYTES"+++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++ _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]])+ 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()+ assert (tmp_path / "alpha" / "x.py").read_text(encoding="utf-8") == "x = 1\n"+def test_preserved_filter_does_not_split_non_rename_lines():"""A plain ignored FILE literally named 'venv -> node_modules' is ONE