The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): stash only what the update collides with, and ask before stashing
Teknium005fbe80586c
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex cd5d2a84e7e..209197eea75 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -1408,8 +1408,15 @@ def _prepare_checkout_for_update(print(f" ⚠ Currently on detached HEAD — switching to {branch} for update...")# Before the stash: its refs/stash would contain HEAD until it is dropped._park_detached_head(git_cmd, _m().PROJECT_ROOT, branch)+ # A local terminal answers "keep local changes?" before anything moves (declining discards,+ # so nothing is stashed); a no-op update never asks. Forks stay unscoped: the upstream sync+ # lands on a ref fetched only later.+ prompt_for_restore = not assume_yes and (gateway_mode or (sys.stdin.isatty() and sys.stdout.isatty()))+ ask_first = prompt_for_restore and not gateway_mode and (+ not in_place_update or _resolved_commit(git_cmd, target_ref) != _capture_head_sha(git_cmd, _m().PROJECT_ROOT))auto_stash_ref = _m()._stash_local_changes_if_needed(- git_cmd, _m().PROJECT_ROOT, checkout_move=_moves_for(_windows_gateway_resume))+ git_cmd, _m().PROJECT_ROOT, checkout_move=_moves_for(_windows_gateway_resume), ask_first=ask_first,+ untracked_targets=() if is_fork else (target_ref, f"origin/{branch}", f"refs/heads/{branch}"))moved_from_sha = Nonerollback_branch = Noneif not release_tag and not in_place_update and current_branch != branch:@@ -1428,10 +1435,7 @@ def _prepare_checkout_for_update(_exit_after_failed_branch_switch(git_cmd, branch, track_result, auto_stash_ref, gw_input_fn, _windows_gateway_resume)- prompt_for_restore = (- auto_stash_ref is not None- and not assume_yes- and (gateway_mode or (sys.stdin.isatty() and sys.stdout.isatty())))+ prompt_for_restore = auto_stash_ref is not None and prompt_for_restore and not ask_firstif release_tag:# An ancestor release still needs applying when switching channels.diff --git a/hermes_cli/update_cmd_stash.py b/hermes_cli/update_cmd_stash.pyindex b73e140a542..c9969eef7ee 100644--- a/hermes_cli/update_cmd_stash.py+++ b/hermes_cli/update_cmd_stash.py@@ -6,6 +6,7 @@ Origin helpers are imported lazily per function (no cycle; test patches on the oimport loggingimport re+from dataclasses import dataclassimport subprocessfrom datetime import datetime, timedelta, timezone, UTCfrom pathlib import Path@@ -85,15 +86,142 @@ def _print_first_line(text: str) -> None:print(f" {text.strip().splitlines()[0]}")-def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path, *, checkout_move=None) -> Optional[str]:- """Stash local changes before the update moves the checkout; the stash commit, or None when clean.- ``checkout_move`` binds the push (and its cleanup reset) to the paused gateways' tree gate."""+def _porcelain_records(porcelain_z: str) -> list[str]:+ """``status --porcelain -z`` records; a rename/copy's second (prefix-less) field is skipped."""+ fields, records = porcelain_z.split("\0"), []+ i = 0+ while i < len(fields):+ if len(fields[i]) > 3:+ records.append(fields[i])+ i += 1 if fields[i][0] not in "RC" else 2+ else:+ i += 1+ return records+++def _target_tree_paths(git_cmd: list[str], cwd: Path, refs) -> Optional[tuple[set[str], set[str]]]:+ """Casefolded (files, directories) the update can write, unioned over every *ref* that resolves;+ None when no ref resolves or a tree cannot be read. Casefolded so a case-insensitive filesystem's+ ``Config.py`` vs ``config.py`` still counts as a collision (over-stashing is always safe)."""+ files: set[str] = set()+ read_any = False+ for ref in dict.fromkeys(refs):+ resolved = _git_quiet(git_cmd, ["rev-parse", "-q", "--verify", f"{ref}^{{tree}}"], cwd, text=True)+ if resolved is None:+ return None+ if resolved.returncode:+ continue # e.g. no local branch of that name: it cannot be landed on+ paths = _git_paths_z(git_cmd, ["ls-tree", "-r", "--name-only", "-z", ref], cwd)+ if paths is None:+ return None+ files |= {p.casefold() for p in paths}+ read_any = True+ if not read_any:+ return None+ dirs = {p.rsplit("/", i)[0] for p in files for i in range(1, p.count("/") + 1)}+ return files, dirs+++def _untracked_collides(entry: str, files: set[str], dirs: set[str]) -> bool:+ """Whether the update could write where the untracked *entry* (a ``dir/`` record or a file) sits."""+ path = entry.rstrip("/").casefold()+ if path in files or path in dirs:+ return True+ parts = path.split("/")+ return any("/".join(parts[:i]) in files for i in range(1, len(parts)))+++@dataclass(frozen=True)+class _LocalChanges:+ """What ``git status`` shows, split by what the update has to move out of its way."""++ porcelain: str+ tracked: bool # any modified/staged/deleted tracked path+ stash_untracked: tuple[str, ...] # untracked entries the update could overwrite+ leave_untracked: tuple[str, ...] # untracked entries no target touches: never moved++ @property+ def needs_moving(self) -> bool:+ return self.tracked or bool(self.stash_untracked)+++def _scan_local_changes(git_cmd: list[str], cwd: Path, untracked_targets=()) -> Optional[_LocalChanges]:+ """Local changes, or None when the tree is clean. An untracked file the update cannot write over+ blocks no pull or checkout, so with *untracked_targets* (every ref the update may land on) only the+ colliding ones are moved; without targets, or when a target tree is unreadable, all of them are."""+ from hermes_cli.update_cmd_git import _git_run+ status = _git_run(git_cmd, ["status", "--porcelain", "-z"], cwd, check=True)+ if not status.stdout.strip():+ return None+ records = _porcelain_records(status.stdout)+ untracked = [r[3:] for r in records if r.startswith("?? ")]+ trees = _target_tree_paths(git_cmd, cwd, untracked_targets) if untracked_targets and untracked else None+ collide = [u for u in untracked if trees is None or _untracked_collides(u, *trees)]+ return _LocalChanges(+ porcelain=status.stdout, tracked=len(untracked) < len(records),+ stash_untracked=tuple(collide), leave_untracked=tuple(u for u in untracked if u not in collide))+++def _literal(path: str, *magic: str) -> str:+ """Pathspec matching *path* byte-for-byte (relative to the checkout root git runs in)."""+ return f":({','.join(('literal', *magic))}){path}"+++def _ask_keep_local_changes(changes: _LocalChanges) -> bool:+ """The restore question, asked BEFORE anything moves: keeping means stash and re-apply after the+ update; declining discards now, so no stash entry is ever left behind. Closed stdin keeps them."""+ print("→ Local changes detected:")+ for line in (f" • tracked file edits: {'yes' if changes.tracked else 'none'}",+ f" • untracked files the update would overwrite: {len(changes.stash_untracked)}"):+ print(line)+ if changes.leave_untracked:+ print(f" ({len(changes.leave_untracked)} other untracked entr"+ f"{'y stays' if len(changes.leave_untracked) == 1 else 'ies stay'} in place either way.)")+ print("Keep these changes after updating? [Y/n] (n deletes them now)")+ try:+ response = input().strip().lower()+ except (EOFError, UnicodeDecodeError):+ response = ""+ return response not in {"n", "no"}+++def _discard_local_changes_before_update(+ git_cmd: list[str], cwd: Path, changes: _LocalChanges, *, checkout_move=None) -> None:+ """Delete exactly what would have been stashed: tracked edits and the colliding untracked entries."""+ from hermes_cli.update_cmd_git import _git_run, _no_move+ from hermes_cli.update_receipt import record_step+ with (checkout_move or _no_move)(revert=True): # every tracked change goes back to HEAD+ if changes.tracked:+ _git_run(git_cmd, ["reset", "--hard", "HEAD"], cwd, check=True)+ if changes.stash_untracked:+ _git_run(git_cmd, ["clean", "-f", "-d", "--", *(_literal(p) for p in changes.stash_untracked)],+ cwd, check=True)+ print("→ Discarded local changes (you chose not to keep them).")+ record_step("local_changes_stash", True, "discarded before update (user declined keeping them)")+++def _stash_local_changes_if_needed(+ git_cmd: list[str], cwd: Path, *, checkout_move=None, untracked_targets=(),+ ask_first: bool = False) -> Optional[str]:+ """Stash local changes before the update moves the checkout; the stash commit, or None when+ nothing needs moving. ``checkout_move`` binds the push (and its cleanup reset) to the paused+ gateways' tree gate; ``untracked_targets`` scopes untracked files (``_scan_local_changes``).+ ``ask_first`` asks whether to keep them; a "no" discards them instead of stashing (None)."""global _pending_autostashfrom hermes_cli.update_cmd_git import _git_run, _no_move_pending_autostash = None- status = _git_run(git_cmd, ["status", "--porcelain", "-z"], cwd, check=True)- if not status.stdout.strip():+ changes = _scan_local_changes(git_cmd, cwd, untracked_targets)+ if changes is None:+ return None+ if changes.leave_untracked:+ print(f"→ Leaving {len(changes.leave_untracked)} untracked entr"+ f"{'y' if len(changes.leave_untracked) == 1 else 'ies'} in place (the update does not touch them).")+ if not changes.needs_moving:+ return None+ if ask_first and not _ask_keep_local_changes(changes):+ _discard_local_changes_before_update(git_cmd, cwd, changes, checkout_move=checkout_move)return None+ status = subprocess.CompletedProcess([], 0, changes.porcelain, "")# Unmerged index entries (interrupted merge/rebase) make `git stash` fail with# "needs merge"; `git reset` drops only the index conflict state, not the tree.if _git_run(git_cmd, ["ls-files", "--unmerged"], cwd).stdout.strip():@@ -115,17 +243,19 @@ def _stash_local_changes_if_needed(git_cmd: list[str], cwd: Path, *, checkout_moprint("→ Local changes detected — stashing before update...")prev_stash = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd).stdout.strip()with (checkout_move or _no_move)(revert=True): # push and reset put every tracked change back to HEAD- stash_ref = _push_stash(git_cmd, cwd, stash_name, prev_stash)+ stash_ref = _push_stash(git_cmd, cwd, stash_name, prev_stash, leave=changes.leave_untracked)_pending_autostash = (- stash_ref, len([entry for entry in status.stdout.split("\0") if entry]))+ stash_ref, len(_porcelain_records(status.stdout)) - len(changes.leave_untracked))return stash_ref-def _push_stash(git_cmd: list[str], cwd: Path, stash_name: str, prev_stash: str) -> str:+def _push_stash(git_cmd: list[str], cwd: Path, stash_name: str, prev_stash: str, leave=()) -> str:"""``git stash push``; the stash commit. Raises when nothing was saved; resets tracked leftovers- when a push saved everything but could not clean up."""+ when a push saved everything but could not clean up. Untracked entries in *leave* stay on disk+ (an exclude pathspec: git never hashes them, which is what made a 55 GB stray dir take minutes)."""from hermes_cli.update_cmd_git import _git_run- push = _git_run(git_cmd, ["stash", "push", "--include-untracked", "-m", stash_name], cwd)+ scope = ["--", ".", *(_literal(p, "exclude") for p in leave)] if leave else []+ push = _git_run(git_cmd, ["stash", "push", "--include-untracked", "-m", stash_name, *scope], cwd)_print_nonempty(push.stdout)stash_probe = _git_run(git_cmd, ["rev-parse", "--verify", "refs/stash"], cwd)stash_ref = stash_probe.stdout.strip()diff --git a/tests/hermes_cli/test_update_scoped_autostash.py b/tests/hermes_cli/test_update_scoped_autostash.pynew file mode 100644index 00000000000..a6c98ca85d3--- /dev/null+++ b/tests/hermes_cli/test_update_scoped_autostash.py@@ -0,0 +1,65 @@+"""``hermes update`` moves only the local changes the update would collide with, and asks before stashing.++An untracked directory the update never writes (a 55 GB leftover worktree copy) used to be hashed into+the autostash and deleted from disk on every update; declining the restore then parked it in git stash.+"""++import subprocess++from hermes_cli import update_cmd_stash+++def _git(cwd, *args):+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout+++def _behind_clone(tmp_path):+ up, work = tmp_path / "up", tmp_path / "work"+ up.mkdir()+ _git(up, "init", "-q", "-b", "main")+ for repo_cfg in (("user.email", "t@t"), ("user.name", "t")):+ _git(up, "config", *repo_cfg)+ (up / "a.txt").write_text("a\n")+ _git(up, "add", ".")+ _git(up, "commit", "-qm", "init")+ _git(tmp_path, "clone", "-q", str(up), str(work))+ (up / "pkg").mkdir()+ (up / "pkg" / "new.py").write_text("upstream\n")+ _git(up, "add", ".")+ _git(up, "commit", "-qm", "adds pkg/new.py")+ _git(work, "fetch", "-q", "origin")+ (work / "a.txt").write_text("a\nmine\n") # tracked edit+ (work / "pkg").mkdir()+ (work / "pkg" / "new.py").write_text("my copy\n") # untracked, collides with the update+ (work / "stray").mkdir()+ (work / "stray" / "big.bin").write_text("x" * 4096) # untracked, the update never writes here+ return work+++_TARGETS = ("origin/main", "refs/heads/main")+++def test_only_colliding_untracked_files_are_stashed(tmp_path):+ work = _behind_clone(tmp_path)++ ref = update_cmd_stash._stash_local_changes_if_needed(["git"], work, untracked_targets=_TARGETS)++ stashed = _git(work, "stash", "show", "--include-untracked", "--name-only", ref).split()+ assert sorted(stashed) == ["a.txt", "pkg/new.py"]+ assert (work / "stray" / "big.bin").read_text() == "x" * 4096+ _git(work, "merge", "--ff-only", "-q", "origin/main") # the left-behind file blocks nothing+++def test_declining_up_front_discards_without_a_stash_entry(tmp_path, monkeypatch):+ work = _behind_clone(tmp_path)+ monkeypatch.setattr("builtins.input", lambda *a: "n")++ ref = update_cmd_stash._stash_local_changes_if_needed(+ ["git"], work, untracked_targets=_TARGETS, ask_first=True)++ assert ref is None+ assert _git(work, "stash", "list") == ""+ assert (work / "a.txt").read_text() == "a\n"+ assert not (work / "pkg" / "new.py").exists()+ assert (work / "stray" / "big.bin").exists()+ _git(work, "merge", "--ff-only", "-q", "origin/main")diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex baf1febbc50..819280965fd 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -2089,7 +2089,7 @@ Additional behavior:- **Gateway restart.** After a successful update, Hermes attempts to restart all running gateway profiles of the home being updated (its root and every `profiles/<name>` under it) automatically so they pick up the new code. Gateways and `hermes-gateway*` services that belong to a different `HERMES_HOME` on the same machine — another install, or a scratch home running `hermes update` — are named in the output and left alone. Use `hermes gateway restart` when you want to restart a gateway without applying an update.- **Restart-phase recovery.** If the in-process restart phase aborts while importing the freshly pulled tree, supervised gateway profiles are retried through a clean Python process. Only restarts independently confirmed by systemd (`systemctl --user is-active`) are reported as verified; a relaunch that merely exited 0 is recorded as `relaunch_attempted` and the restart stays owed (a `gateway_restart` follow-up; the update itself still exits 0 because the code is in place). Manual gateways and serve/dashboard runtimes are never killed without a relaunch authority; they are recorded as skipped with a reason and remain in the incomplete-update report with the exact restart command.- **Update receipts + fleet version check.** Every run writes a machine-readable receipt to `~/.hermes/logs/update_receipts/` in the root Hermes home, even from a sticky profile (pre-update fleet plan, steps, skips with reasons, restart outcome, follow-ups; `latest.json` points at the newest and reads `running` while an update is in progress). After the restart phase the updater verifies each live gateway's running code against the updated checkout and prints a per-profile version matrix. A gateway still on pre-update code does not fail the update once the new code is in place: the update prints a `⚠` line with the exact restart command, exits 0, records a `gateway_restart` follow-up, and keeps the restart owed — every CLI start warns about it and the next `hermes update` retries it.-- **Local source changes.** For git installs, dirty tracked files and untracked files are auto-stashed before branch checkout or pull (`git stash push --include-untracked`). Interactive terminal updates ask before restoring the stash. Non-interactive updates restore it by default; set `updates.non_interactive_local_changes: discard` only on managed installs where local source edits should be thrown away after a successful pull. If stash restore conflicts or the pull fails, the stash is left in place for manual recovery.+- **Local source changes.** For git installs, dirty tracked files are auto-stashed before branch checkout or pull, together with any untracked file at a path the update adds. Other untracked files and folders stay where they are, untouched, because they cannot block the update. Interactive terminal updates ask "Keep these changes after updating?" before anything is stashed: yes stashes them and puts them back after the pull, no deletes them right away, so no stash entry is left behind. A run with nothing to pull does not ask. Non-interactive updates restore it by default; set `updates.non_interactive_local_changes: discard` only on managed installs where local source edits should be thrown away after a successful pull. If stash restore conflicts or the pull fails, the stash is left in place for manual recovery.- **npm lockfile churn.** Before stashing or switching branches, Hermes makes a best-effort cleanup of tracked `package-lock.json` diffs produced by npm install/build steps. Commit or manually stash intentional lockfile edits before running `hermes update`.- **Pairing data snapshot.** Even when `--backup` is off, `hermes update` takes a lightweight snapshot of `~/.hermes/pairing/` and the Feishu comment rules before `git pull`. You can roll it back with `hermes backup restore --state pre-update` if a pull rewrites a file you were editing.- **Legacy `hermes.service` warning.** If Hermes detects a pre-rename `hermes.service` systemd unit (instead of the current `hermes-gateway.service`), it prints a one-time migration hint so you can avoid flap-loop issues.diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 4264bac05c2..808b59c2023 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -216,7 +216,7 @@ updates:Point-in-time copies of `config.yaml` itself (taken before `hermes setup` rewrites it, before `hermes migrate` edits it, every time the file parses successfully, and when it fails to parse) go to `backups/config/config.yaml.<reason>.<timestamp>`. Identical repeats are skipped and only the newest five per reason are kept, so they never pile up beside `config.yaml`. If `config.yaml` is broken, Hermes serves the newest `good` copy instead of built-in defaults and warns on every start until the YAML is fixed; the broken file is never modified.-For git installs, Hermes auto-stashes dirty tracked files and untracked files before checking out the update branch or pulling. Interactive terminal updates prompt before restoring that stash. Non-interactive updates (desktop/chat app, gateway, or `--yes`) use `updates.non_interactive_local_changes`: `stash` restores local source edits after a successful pull, while `discard` drops the update-created stash after a successful pull. Use `discard` only on managed installs where local source edits are never meant to persist.+For git installs, Hermes auto-stashes dirty tracked files, plus any untracked file at a path the update adds, before checking out the update branch or pulling. Untracked files the update never writes stay in place. Interactive terminal updates ask whether to keep the changes before stashing anything; answering no deletes them instead of leaving a stash entry behind. Non-interactive updates (desktop/chat app, gateway, or `--yes`) use `updates.non_interactive_local_changes`: `stash` restores local source edits after a successful pull, while `discard` drops the update-created stash after a successful pull. Use `discard` only on managed installs where local source edits are never meant to persist.Before that stash step, Hermes also restores tracked `package-lock.json` diffs left by npm install/build churn. Commit or manually stash intentional lockfile edits before updating.