The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): ZIP dirty-tree guard admits what the swap cannot destroy
teknium171335fe2b40a
diff --git a/hermes_cli/AGENTS.md b/hermes_cli/AGENTS.mdindex c22640d8218..c21c9e0e26e 100644--- a/hermes_cli/AGENTS.md+++ b/hermes_cli/AGENTS.md@@ -115,10 +115,15 @@ it guards. `plan → snapshot → apply → restart-per-kind → verify → repo- **Apply**: git pull, or the Windows ZIP fallback — which fires ONLY when git itself failed(`_should_zip_fallback_on_update_error`, argv-classified; a dependency-install failure must nevertrigger a tree-clobbering re-download), REFUSES a dirty working tree (`-uall` + a pre-swap TOCTOU- re-check — but ADMITS the gitignored build outputs below and `__pycache__/`, which every real- install has), and grafts the live nested build outputs (`_ZIP_PRESERVED_NESTED`: `apps/desktop/- {release,dist,node_modules}`, `hermes_cli/web_dist`) into the staged swap by hardlink (the GitHub- source ZIP has none of them; without the graft the swap deletes them). Post-swap, the Desktop+ re-check — but classifies a `!!` line by whether the swap would destroy it: an ignored path under a+ root entry the ZIP does not ship (`.bytecode-fingerprint`, `.hermes-bootstrap-complete`,+ `hermes_agent.egg-info/`; tracked root entries stand in for the ZIP set before the download, the+ re-check gets the real one), a nested `__pycache__`/`node_modules`, or a `_ZIP_PRESERVED_NESTED`+ output is admitted; other ignored files under shipped dirs still block), and grafts the live nested+ build outputs (`_ZIP_PRESERVED_NESTED`: `apps/desktop/{release,dist,node_modules,build}`,+ `hermes_cli/web_dist`, `ui-tui/{dist,node_modules,packages/hermes-ink/dist}`, `web/node_modules`,+ `scripts/whatsapp-bridge/node_modules`) into the staged swap by hardlink (the GitHub source ZIP has+ none of them; without the graft the swap deletes them). Post-swap, the Desktoprebuild decision also trusts the build stamp under HERMES_HOME, so an install that already lostits artifacts in an earlier update is rebuilt instead of "forgotten" (#90495).- **Restart-per-kind**: systemd and launchd restarts are FLEET-WIDE (every `hermes-gateway*` unit /diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.pyindex d23e5302813..efb8b99948a 100644--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@ -11,7 +11,7 @@ import shutilimport subprocessimport sysfrom pathlib import Path-from typing import Optional+from typing import Collection, Optionalfrom hermes_cli.update_cmd_common import _best_effortfrom hermes_constants import project_venv_dir@@ -29,8 +29,11 @@ _ZIP_PRESERVED_TOP_LEVEL = {"venv", ".venv", "node_modules", ".git", ".env"}# its own node_modules (electron itself), and the dashboard assets. The dirty-tree guard admits them and# `_stage_entries` grafts the live copies into the staged tree so the swap keeps them (#90495)._ZIP_PRESERVED_NESTED = {- "apps": ("desktop/release", "desktop/dist", "desktop/node_modules"),+ "apps": ("desktop/release", "desktop/dist", "desktop/node_modules", "desktop/build"),"hermes_cli": ("web_dist",),+ "scripts": ("whatsapp-bridge/node_modules",),+ "ui-tui": ("dist", "node_modules", "packages/hermes-ink/dist"),+ "web": ("node_modules",),}_STASH_HINT = " Stash or commit your changes, then rerun `hermes update`."@@ -125,13 +128,17 @@ def _commit_staged_replacements(staged) -> None:_remove_path(backup, ignore_errors=True)-def _zip_overlay_block_reason(root: Path, *, ignore_staging_artifacts: bool = False) -> Optional[str]:+def _zip_overlay_block_reason(+ root: Path, *, ignore_staging_artifacts: bool = False, 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 uncommittededits 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- reports as untracked; without the filter the re-check always refuses.+ reports as untracked; without the filter the re-check always refuses. ``shipped`` is the extracted+ ZIP's top-level entry set once known (the re-check); before the download the tracked root entries stand+ in for it. A gitignored path under a root entry the ZIP does not ship is never touched by the swap.Fail closed when git status cannot run: unknown dirtiness is not a license to clobber the tree (#87304)."""@@ -147,6 +154,15 @@ def _zip_overlay_block_reason(root: Path, *, ignore_staging_artifacts: bool = Fagit_cmd + ["status", "--porcelain", "--untracked-files=all", "--ignored=matching"],cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace",)+ if result.returncode == 0 and shipped is None:+ # Before the download the ZIP's entry set is unknown; the tracked root entries stand in for it (the+ # pre-swap re-check gets the real set), so an ignored root entry the swap never touches cannot refuse.+ tracked = subprocess.run(+ git_cmd + ["ls-tree", "--name-only", "HEAD"],+ cwd=root, capture_output=True, text=True, encoding="utf-8", errors="replace",+ )+ shipped = set(tracked.stdout.splitlines()) if tracked.returncode == 0 else None+ result.returncode = tracked.returncodeif result.returncode != 0:detail = (result.stderr or result.stdout or "").strip().splitlines()return f"could not check the working tree{f' ({detail[0]})' if detail else ''}"@@ -154,7 +170,7 @@ def _zip_overlay_block_reason(root: Path, *, ignore_staging_artifacts: bool = Fa# swap, so they must not cause a false refusal. Everything else — including ignored files — blocks.dirty = any(line.strip()- and not _is_zip_preserved_entry_status_line(line)+ and not _is_zip_preserved_entry_status_line(line, shipped)and not (ignore_staging_artifacts and _is_zip_staging_artifact_status_line(line))for line in (result.stdout or "").splitlines())@@ -165,11 +181,14 @@ def _status_top_level(path: str) -> str:return path.strip().strip('"').replace("\\", "/").rstrip("/").split("/", 1)[0]-def _is_zip_preserved_entry_status_line(line: str) -> bool:- """True when every path on a porcelain status line sits under a preserved top-level entry, or the- line is a gitignored (``!!``) build output the swap keeps (`_ZIP_PRESERVED_NESTED`) or regenerates- (``__pycache__``) — every real install has both, and blocking on them made the ZIP fallback refuse- all of them. Tracked edits, renames and other untracked/ignored user files still block.+def _is_zip_preserved_entry_status_line(line: str, shipped: Optional[Collection[str]] = None) -> bool:+ """True when the swap would not destroy what a porcelain status line names: every path sits under a+ preserved top-level entry; or the line is gitignored (``!!``) and under a root entry the ZIP does not+ ship (``.bytecode-fingerprint``, ``.hermes-bootstrap-complete``, ``hermes_agent.egg-info/`` — the swap+ replaces ``shipped`` entries only); or a ``!!`` build output nested under a shipped dir that the swap+ keeps (`_ZIP_PRESERVED_NESTED`) or regenerates (``__pycache__``, ``node_modules``). Every real install+ has all of these, and blocking on them made the ZIP fallback refuse every install. Tracked edits,+ renames and other untracked/ignored user files still block.The ``" -> "`` split applies ONLY to R/C codes: porcelain v1 doesn't quote plain names with spaces, so``venv -> node_modules`` on a ``!!``/``??`` line is ONE path and splitting would fail-open. Requiring@@ -183,7 +202,9 @@ def _is_zip_preserved_entry_status_line(line: str) -> bool:return Falsepath = payload.strip().strip('"').replace("\\", "/").rstrip("/")top, _, nested = path.partition("/")- return path.rsplit("/", 1)[-1] == "__pycache__" or any(+ if shipped is not None and top not in shipped:+ return True+ return path.rsplit("/", 1)[-1] in ("__pycache__", "node_modules") or any(nested == keep or nested.startswith(f"{keep}/") for keep in _ZIP_PRESERVED_NESTED.get(top, ()))@@ -326,7 +347,8 @@ def _download_and_swap_zip(branch: str, zip_url: str) -> None:try:# 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(_m().PROJECT_ROOT, ignore_staging_artifacts=True)+ recheck_reason = _zip_overlay_block_reason(+ _m().PROJECT_ROOT, ignore_staging_artifacts=True, shipped=entries)if recheck_reason is not None:_discard_staged(staged)print(f"✗ ZIP fallback aborted before the swap: {recheck_reason}.")diff --git a/tests/hermes_cli/test_update_zip_fallback_guards.py b/tests/hermes_cli/test_update_zip_fallback_guards.pyindex c72ecc407ac..0bc3df2f276 100644--- a/tests/hermes_cli/test_update_zip_fallback_guards.py+++ b/tests/hermes_cli/test_update_zip_fallback_guards.py@@ -10,6 +10,7 @@ has already succeeded by then, so the ZIP cannot fix the actual failure.from __future__ import annotations+import shutilimport subprocessfrom types import SimpleNamespacefrom unittest.mock import patch@@ -116,6 +117,8 @@ def _porcelain_run(stdout: str, returncode: int = 0):joined = " ".join(str(c) for c in cmd)if "status" in joined and "--porcelain" in joined:return subprocess.CompletedProcess(cmd, returncode, stdout=stdout, stderr="")+ if "ls-tree" in joined: # tracked root entries = what the ZIP ships+ return subprocess.CompletedProcess(cmd, 0, stdout="hermes_cli\nscratch\n", stderr="")return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")return fake_run@@ -276,7 +279,7 @@ def test_zip_overlay_flag_is_valid_against_real_git(tmp_path):ignored user files."""subprocess.run(["git", "init", "-q", str(tmp_path)], check=True)- (tmp_path / ".gitignore").write_text("*.local\nvenv/\n.venv/\n")+ (tmp_path / ".gitignore").write_text("*.local\nvenv/\n.venv/\n", encoding="utf-8")subprocess.run(["git", "-C", str(tmp_path), "add", ".gitignore"], check=True)@@ -290,19 +293,20 @@ def test_zip_overlay_flag_is_valid_against_real_git(tmp_path):)# Clean tree: guard must pass (flag valid, no false refusal).assert update_cmd._zip_overlay_block_reason(tmp_path) is None- # Ignored user file: guard must block.- (tmp_path / "data.local").write_text("x")- reason = update_cmd._zip_overlay_block_reason(tmp_path)+ # Ignored user file under a shipped (tracked) dir: the swap would delete it, guard must block.+ (tmp_path / "pkg").mkdir()+ (tmp_path / "pkg" / "data.local").write_text("x", encoding="utf-8")+ reason = update_cmd._zip_overlay_block_reason(tmp_path, shipped={"pkg"})assert reason is not None# Ignored preserved entry: still no refusal.- (tmp_path / "data.local").unlink()+ shutil.rmtree(tmp_path / "pkg")(tmp_path / "venv").mkdir()- (tmp_path / "venv" / "lib.py").write_text("x")+ (tmp_path / "venv" / "lib.py").write_text("x", encoding="utf-8")assert update_cmd._zip_overlay_block_reason(tmp_path) is None# uv-default ``.venv`` is a supported layout (#112958): the ignored dir is the live runtime,# not user data the overlay would destroy — refusing here made ZIP fallback impossible.(tmp_path / ".venv").mkdir()- (tmp_path / ".venv" / "lib.py").write_text("x")+ (tmp_path / ".venv" / "lib.py").write_text("x", encoding="utf-8")assert update_cmd._zip_overlay_block_reason(tmp_path) is Nonediff --git a/tests/hermes_cli/test_update_zip_release_preserve.py b/tests/hermes_cli/test_update_zip_release_preserve.pyindex 4cc8e8c2c27..b6488076ce6 100644--- a/tests/hermes_cli/test_update_zip_release_preserve.py+++ b/tests/hermes_cli/test_update_zip_release_preserve.py@@ -28,13 +28,13 @@ def test_staged_apps_swap_preserves_live_release_dir(tmp_path, monkeypatch):(live_apps / "release" / "win-unpacked").mkdir(parents=True)(live_apps / "release" / "win-unpacked" / "Hermes.exe").write_bytes(b"MZbuilt")(live_apps / "electron").mkdir()- (live_apps / "electron" / "main.ts").write_text("old source")+ (live_apps / "electron" / "main.ts").write_text("old source", encoding="utf-8")# extracted ZIP: new source, NO release dir (GitHub source archive shape)extracted = tmp_path / "extracted"zip_apps = extracted / "apps" / "desktop"(zip_apps / "electron").mkdir(parents=True)- (zip_apps / "electron" / "main.ts").write_text("new source")+ (zip_apps / "electron" / "main.ts").write_text("new source", encoding="utf-8")monkeypatch.setattr(hermes_main, "PROJECT_ROOT", root)@@ -52,7 +52,7 @@ def test_staged_apps_swap_preserves_live_release_dir(tmp_path, monkeypatch):_commit_staged_replacements([(staged_path, dst)])# New source landed AND the built desktop app survived.- assert (root / "apps" / "desktop" / "electron" / "main.ts").read_text() == (+ assert (root / "apps" / "desktop" / "electron" / "main.ts").read_text(encoding="utf-8") == ("new source")exe = root / "apps" / "desktop" / "release" / "win-unpacked" / "Hermes.exe"@@ -77,18 +77,18 @@ def test_zip_swap_keeps_every_nested_build_output_and_the_guard_admits_them(tmp_(root / rel).parent.mkdir(parents=True)(root / rel).write_bytes(data)(root / "hermes_cli" / "__pycache__").mkdir()- (root / "hermes_cli" / "x.py").write_text("old")+ (root / "hermes_cli" / "x.py").write_text("old", encoding="utf-8")# Extracted ZIP: new source, none of the outputs — except dist/, which a future archive may ship.extracted = tmp_path / "extracted"(extracted / "apps" / "desktop" / "dist").mkdir(parents=True)(extracted / "apps" / "desktop" / "dist" / "index.html").write_bytes(b"shipped renderer")(extracted / "hermes_cli").mkdir()- (extracted / "hermes_cli" / "x.py").write_text("new")+ (extracted / "hermes_cli" / "x.py").write_text("new", encoding="utf-8")_commit_staged_replacements(_stage_entries(str(extracted), ["apps", "hermes_cli"], str(root)))- assert (root / "hermes_cli" / "x.py").read_text() == "new"+ assert (root / "hermes_cli" / "x.py").read_text(encoding="utf-8") == "new"for rel, data in outputs.items():if rel.startswith("apps/desktop/dist/"):continue@@ -99,9 +99,57 @@ def test_zip_swap_keeps_every_nested_build_output_and_the_guard_admits_them(tmp_# The dirty-tree guard sees these outputs as ``!!`` lines; they must not refuse the swap.for line in ("!! apps/desktop/release/", "!! apps/desktop/dist/", "!! apps/desktop/node_modules/",- "!! hermes_cli/web_dist/", "!! hermes_cli/__pycache__/", "!! __pycache__/"):+ "!! apps/desktop/build/", "!! hermes_cli/web_dist/", "!! hermes_cli/__pycache__/",+ "!! __pycache__/", "!! ui-tui/dist/", "!! ui-tui/packages/hermes-ink/dist/",+ "!! scripts/whatsapp-bridge/node_modules/", "!! web/node_modules/", "!! tests-js/node_modules/"):assert _is_zip_preserved_entry_status_line(line), line# ...while other gitignored data, untracked files and renames into those dirs still block.for line in ("!! apps/desktop/notes.local", "?? apps/desktop/release/", "!! hermes_cli/web_dist_backup/","R src/x -> apps/desktop/release/x"):assert not _is_zip_preserved_entry_status_line(line), line+++def test_guard_admits_a_real_installs_ignored_set_and_blocks_only_what_the_swap_destroys(tmp_path):+ """Real git + the repo's own .gitignore, seeded with every ``!!`` line a real installer-made install+ carries (markers written at the checkout root by update/install, the egg-info, every nested build+ output). Blocking on any of them kept the ZIP fallback — and the graft — unreachable (#90495)."""+ import subprocess++ from hermes_cli.update_cmd_zip import _zip_overlay_block_reason++ root = tmp_path / "install"+ root.mkdir()+ subprocess.run(["git", "init", "-q", str(root)], check=True)+ repo = Path(__file__).resolve().parents[2]+ (root / "ui-tui").mkdir()+ for rel in (".gitignore", "ui-tui/.gitignore"): # ui-tui/dist is ignored by the nested file+ shutil.copy(repo / rel, root / rel)+ for tracked in ("apps/desktop/package.json", "hermes_cli/main.py", "scripts/whatsapp-bridge/index.js",+ "ui-tui/package.json", "web/package.json", "tests-js/a.test.ts", "run_agent.py"):+ (root / tracked).parent.mkdir(parents=True, exist_ok=True)+ (root / tracked).write_text("src", 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)+ for ignored in (".bytecode-fingerprint", ".hermes-bootstrap-complete", ".install_method",+ "hermes_agent.egg-info/PKG-INFO", "hermes_cli/__pycache__/main.pyc", "__pycache__/x.pyc",+ "apps/desktop/release/win-unpacked/Hermes.exe", "apps/desktop/dist/index.html",+ "apps/desktop/build/icon.ico", "apps/desktop/node_modules/electron/index.js",+ "hermes_cli/web_dist/index.html", "ui-tui/dist/entry.js", "ui-tui/node_modules/x/index.js",+ "ui-tui/packages/hermes-ink/dist/index.js", "web/node_modules/x/index.js",+ "tests-js/node_modules/x/index.js", "scripts/whatsapp-bridge/node_modules/x/index.js",+ "venv/lib.py", "node_modules/x/index.js", ".env"):+ (root / ignored).parent.mkdir(parents=True, exist_ok=True)+ (root / ignored).write_text("artifact", encoding="utf-8")+ status = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "-uall", "--ignored=matching"],+ capture_output=True, text=True, check=True).stdout+ assert status.count("!!") >= 19 and "??" not in status, status # the fixture really is all-ignored++ assert _zip_overlay_block_reason(root) is None+ # The pre-swap re-check knows the ZIP's real entry set: a root entry it ships would be replaced.+ shipped = {"apps", "hermes_cli", "scripts", "ui-tui", "web", "tests-js", "run_agent.py"}+ assert _zip_overlay_block_reason(root, shipped=shipped) is None+ assert _zip_overlay_block_reason(root, shipped=shipped | {"hermes_agent.egg-info"}) is not None+ # Gitignored user data under a shipped dir is destroyed by the swap: still refused.+ (root / "apps" / "desktop" / ".env").write_text("mine", encoding="utf-8")+ assert _zip_overlay_block_reason(root) is not Nonediff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex 1cd6cb8d753..bb55d9807e0 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -520,6 +520,10 @@ redirect here.If a Desktop chat or bot stops responding while the connection still shows **Connected**, select that bot/profile or gateway, open the status bar's gateway menu, and click **Reconnect gateway**. Reconnect stays available for open, connecting, and disconnected transports. It redials the active route without restarting Desktop or deliberately closing other routes' sockets. In-flight requests on the selected socket can be interrupted; this is an explicit recovery action, not a backend or model restart.+### The app vanished after `hermes update`++An earlier update that replaced the checkout without keeping `apps/desktop/release/` leaves no packaged app to launch. As long as `HERMES_HOME/desktop-build-stamp.json` (written only by a successful Desktop build) still exists, the next `hermes update` notices the missing app and rebuilds it. To rebuild by hand: `hermes desktop --build-only --force-build`. On Windows the ZIP fallback also keeps the built app, its renderer bundle and its Electron `node_modules` across the swap.+### The local backend stopped in the backgroundIf the local Hermes backend process exits after it was ready, Desktop restarts it on its own and shows a **Hermes stopped working in the background** notice; the chat reconnects once the replacement is up. `HERMES_HOME/logs/desktop.log` records the exit code together with the backend's last output lines (`Hermes backend exited (1)` followed by `Recent backend output:`), so the reason it died is in the log even when the app recovered by itself. A backend that keeps dying within seconds of every restart points at the backend itself — look at the traceback in that tail. After three such restarts within two minutes Desktop stops respawning and shows a **keeps crashing** notice instead of cycling; relaunch the app once the cause is fixed.