The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: worktree archive keeps submodule work and late staged edits, reports retained trees
Tekniumccb3c9a4e8c5
diff --git a/hermes_cli/worktree_archive.py b/hermes_cli/worktree_archive.pyindex dece66b448f..ad622a0177d 100644--- a/hermes_cli/worktree_archive.py+++ b/hermes_cli/worktree_archive.py@@ -52,6 +52,7 @@ class Archive:sha: strcreated: floatmeta: dict = field(default_factory=dict)+ staged: str = "" # staged_state() of exactly the index this archive captureddef _env(cwd, index: Optional[str] = None) -> dict:@@ -173,16 +174,74 @@ def _untracked(wt: Path, env) -> list[str]:return [p for p in out.split("\0") if p]+SUBMODULE_REASON = "submodule "+++def submodule_work(wt_path, _depth: int = 0) -> Optional[str]:+ """Why an initialized submodule of *wt_path* holds work a snapshot cannot carry, or None.++ A snapshot records a submodule only as its ``160000`` gitlink, and removing the worktree+ deletes the submodule checkout and its per-worktree ``modules/`` repository. So a populated+ submodule that is dirty (tracked or untracked), checked out at another commit than recorded,+ or holding any commit/stash no remote-tracking ref has, keeps the tree. Uninitialized+ submodules, and clean ones whose commits all exist on a remote, are safe. Read-only.+ """+ wt = Path(wt_path)+ env = _env(wt)+ env["GIT_OPTIONAL_LOCKS"] = "0"+ staged = _ok(["ls-files", "--stage", "-z"], wt, env)+ links = [e.split("\t", 1)[1] for e in staged.split("\0") if e.startswith("160000 ") and "\t" in e]+ populated = [p for p in dict.fromkeys(links) if (wt / p / ".git").exists()]+ if not populated:+ return None+ # --ignore-submodules=none overrides diff.ignoreSubmodules/.gitmodules ignore=all; the S flags+ # (C = new commit, M = tracked changes, U = untracked files) recurse into nested submodules.+ status = _ok(["status", "--porcelain=v2", "-z", "-uno", "--no-renames", "--ignore-submodules=none"], wt, env)+ for entry in status.split("\0"):+ fields = entry.split(" ")+ if entry[:2] in ("1 ", "2 ", "u ") and len(fields) > 2 and fields[2].startswith("S") \+ and fields[2] != "S...":+ path = entry.split(" ", 10 if entry[0] == "u" else (9 if entry[0] == "2" else 8))[-1]+ return f"{SUBMODULE_REASON}{path.split(chr(9))[0]} has uncommitted work or a new commit"+ for rel in populated:+ sub = wt / rel+ senv = _env(sub)+ local_only = _ok(["rev-list", "-n1", "--all", "--not", "--remotes"], sub, senv).strip()+ if local_only:+ return f"{SUBMODULE_REASON}{rel} has commits or stashes on no remote"+ if _depth < 8:+ nested = submodule_work(sub, _depth + 1)+ if nested:+ return nested.replace(SUBMODULE_REASON, f"{SUBMODULE_REASON}{rel}/", 1)+ return None+++def staged_state(wt_path) -> str:+ """Digest of the semantic staged entries (mode, blob id, stage, path) of *wt_path*.++ A stat-only index refresh (``git status``) leaves it unchanged; any ``git add``/``apply+ --cached``/``rm --cached`` changes it. Raises :class:`ArchiveError` when git fails.+ """+ wt = Path(wt_path)+ return _digest_index(wt, _env(wt))+++def _digest_index(wt: Path, env) -> str:+ import hashlib+ env = {**env, "GIT_OPTIONAL_LOCKS": "0"}+ return hashlib.sha256(_ok(["ls-files", "--stage", "-z"], wt, env).encode("utf-8", "surrogateescape")).hexdigest()++def archive_preflight(wt_path) -> Optional[str]:"""Why *wt_path* cannot be snapshotted losslessly, or None. Read-only."""try:wt = Path(wt_path)embedded = [p for p in _untracked(wt, _env(wt)) if p.endswith("/")]+ if not embedded:+ return submodule_work(wt)except (ArchiveError, OSError, subprocess.SubprocessError) as exc:return str(exc)- if embedded:- return f"untracked embedded repository {embedded[0].rstrip('/')} cannot be archived"- return None+ return f"untracked embedded repository {embedded[0].rstrip('/')} cannot be archived"def _split_oversized(wt: Path, untracked: list[str], max_mb: float) -> list[dict]:@@ -217,6 +276,11 @@ def snapshot_worktree(repo_root: str, wt_path, *, reason: str, max_untracked_mb:"""wt = Path(wt_path)env = _env(wt)+ # Shared refusal point (sweep, exit-time Archive, subagent finalization): a gitlink records+ # no submodule work, and removing the tree would delete it.+ unsafe = submodule_work(wt)+ if unsafe:+ raise ArchiveError(unsafe)head = _ok(["rev-parse", "--verify", "HEAD^{commit}"], wt, env).strip()branch = _run(["symbolic-ref", "--short", "-q", "HEAD"], wt, env).stdout.strip() or Nonegit_dir = Path(_ok(["rev-parse", "--absolute-git-dir"], wt, env).strip())@@ -234,6 +298,7 @@ def snapshot_worktree(repo_root: str, wt_path, *, reason: str, max_untracked_mb:shutil.copyfile(git_dir / "index", tmp_index)else:_ok(["read-tree", head], wt, tenv)+ staged = _digest_index(wt, tenv)# Staged state first (fails on an unmerged index: a conflicted tree is never archived).index_tree = _ok(["write-tree"], wt, tenv).strip()empty_tree = _ok(["mktree"], wt, env, stdin_text="").strip()@@ -256,7 +321,8 @@ def snapshot_worktree(repo_root: str, wt_path, *, reason: str, max_untracked_mb:leftover.unlink(missing_ok=True)ref = _create_ref(repo_root, wt.name, sha, env)logger.info("Archived worktree %s -> %s (%s)", wt, ref, reason)- return Archive(ref=ref, name=ref[len(ARCHIVE_PREFIX):], sha=sha, created=meta["created"], meta=meta)+ return Archive(ref=ref, name=ref[len(ARCHIVE_PREFIX):], sha=sha, created=meta["created"], meta=meta,+ staged=staged)def _parse_meta(body: str) -> dict:diff --git a/hermes_cli/worktree_cmd.py b/hermes_cli/worktree_cmd.pyindex 660b14ba09e..71017e046cf 100644--- a/hermes_cli/worktree_cmd.py+++ b/hermes_cli/worktree_cmd.py@@ -94,7 +94,10 @@ def _sweep(repo_root: str, dry_run: bool, older_than: Optional[float] = None) ->_, _, archived = worktree_sweep.execute_plan(repo_root, plan, settings)from hermes_cli.worktree_archive import prune_expired_archivesexpired = prune_expired_archives(repo_root, settings["archive_retention_days"])- return plan, [f"archived + removed → {ref}" for ref in archived] + [f"deleted expired archive {r}" for r in expired]+ from agent.i18n import t+ saved = [t("cli.worktree.sweep_archived_removed" if removed else "cli.worktree.sweep_archived_kept", ref=ref)+ for ref, removed in archived]+ return plan, saved + [f"deleted expired archive {r}" for r in expired]def _attended_records(records, plan) -> list:diff --git a/hermes_cli/worktree_exit.py b/hermes_cli/worktree_exit.pyindex 20764e4d7c9..be63c0eaa9b 100644--- a/hermes_cli/worktree_exit.py+++ b/hermes_cli/worktree_exit.py@@ -101,10 +101,8 @@ def apply_exit_choice(info: dict, echo) -> bool:echo(f"\033[31m{t('cli.worktree.archive_failed', path=path, error=str(exc) or 'interrupted')}\033[0m")return Truename = ref.rsplit("/", 1)[-1]- echo(f"\033[32m{t('cli.worktree.archived', path=path, ref=ref)}\033[0m")+ echo(f"\033[32m{t('cli.worktree.archived' if removed else 'cli.worktree.archived_kept', path=path, ref=ref)}\033[0m")echo(f" {t('cli.worktree.restore_hint', name=name)}")- if not removed:- echo(f" {t('cli.worktree.archive_not_removed', path=path)}")return Truefrom hermes_cli._subprocess_compat import noninteractive_git_envfrom hermes_cli.worktree_ops import _git_quiet, release_lsp_clientsdiff --git a/hermes_cli/worktree_sweep.py b/hermes_cli/worktree_sweep.pyindex 853252d60fa..f2d3750635a 100644--- a/hermes_cli/worktree_sweep.py+++ b/hermes_cli/worktree_sweep.py@@ -6,7 +6,8 @@ tiers and classifier, then removes an idle dirty/unpushed tree only after archivworking state to ``refs/hermes/archive/<tree>`` (``worktree_archive``); a failed archive keepsthe tree. Never touched, at any age or budget: Kanban ``t_<hex>`` trees, trees whose ``hermes``lock owner still runs, trees any live process sits in (cwd or open file), and trees with file or-ref activity younger than their tier. With ``archive_dirty: false`` and no size budget the+ref activity younger than their tier, and trees whose initialized submodules hold work+(``keep-submodule-work``: an archive records only the gitlink). With ``archive_dirty: false`` and no size budget theclassic pruner runs unchanged.``plan_sweep`` is read-only (``hermes worktree prune --dry-run`` prints it); ``execute_plan``@@ -195,6 +196,13 @@ def _tier_hours(name: str, max_age_hours: float) -> float:return prune_tier_hours(name, max_age_hours)+def _unarchivable_action(why: str) -> str:+ """``keep-submodule-work`` for submodule edits/commits a gitlink cannot carry, else+ ``keep-unarchivable``."""+ from hermes_cli.worktree_archive import SUBMODULE_REASON+ return "keep-submodule-work" if why.startswith(SUBMODULE_REASON) else "keep-unarchivable"++def _plan_survivor(repo_root: str, entry: Path, verdict: str, lock_state, settings: dict,tier_hours: float, now: float) -> tuple[str, str, Optional[str], Optional[float]]:"""(action, reason, lock_state, last_activity) for a dirty/unpushed tree past its tier."""@@ -211,7 +219,7 @@ def _plan_survivor(repo_root: str, entry: Path, verdict: str, lock_state, settinreturn f"keep-{verdict}", what, lock_state, active # idle: only the size budget may evict itunsafe = archive_preflight(str(entry))if unsafe:- return "keep-unarchivable", unsafe, lock_state, active+ return _unarchivable_action(unsafe), unsafe, lock_state, activereturn "archive-remove", what, lock_state, active@@ -232,7 +240,7 @@ def _apply_budget(decisions: list[Decision], max_total_gb: float) -> None:breakunsafe = archive_preflight(d.path)if unsafe:- d.action, d.reason = "keep-unarchivable", unsafe+ d.action, d.reason = _unarchivable_action(unsafe), unsafecontinued.action, d.reason = "archive-remove", f"{d.reason}; over worktrees.max_total_gb={max_total_gb:g}"total -= d.size_mb or 0@@ -330,6 +338,19 @@ def _in_use_since(path: str, since: float, exclude=()) -> Optional[str]:return None+def _index_moved(path: str, captured: str) -> Optional[str]:+ """Why the staged state of *path* no longer matches the archive (``git add``/``apply+ --cached`` after the capture: the index is not a file-mtime signal), or None. A stat-only+ refresh by ``git status`` does not count. Unreadable index = moved (keep the tree)."""+ from hermes_cli.worktree_archive import ArchiveError, staged_state+ try:+ if staged_state(path) == captured:+ return None+ except (ArchiveError, OSError, subprocess.SubprocessError):+ pass+ return "staged changes since the snapshot"++def archive_then_remove(repo_root: str, path: str, *, reason: str, max_untracked_mb: float,unlock: bool, remote_heads_fn=None, keep_branch: bool = False,exclude_pids=(),@@ -337,8 +358,8 @@ def archive_then_remove(repo_root: str, path: str, *, reason: str, max_untracked"""Snapshot *path*, then remove it -> ``(archive_ref, kept_branch, removed)``.Raises ``ArchiveError`` (tree untouched) when the snapshot fails. Right after the snapshot the- tree is checked again: a process (other than *exclude_pids*) now working in it, or any edit- made while the snapshot ran, keeps the tree (``removed`` False; the archive stays). The branch+ tree is checked again: a process (other than *exclude_pids*) now working in it, any edit+ made while the snapshot ran, or staged entries that differ from the captured index keep the tree (``removed`` False; the archive stays). The branchsurvives when it is protected or published on a remote (an open PR may still need it);otherwise the archive ref anchors its commits and the local branch is deleted."""@@ -347,7 +368,7 @@ def archive_then_remove(repo_root: str, path: str, *, reason: str, max_untrackedfrom hermes_cli._subprocess_compat import noninteractive_git_envstarted = time.time()arc = snapshot_worktree(repo_root, path, reason=reason, max_untracked_mb=max_untracked_mb)- busy = _in_use_since(path, started, exclude=exclude_pids)+ busy = _in_use_since(path, started, exclude=exclude_pids) or _index_moved(path, arc.staged)if busy:logger.warning("Archived %s to %s but keeping it: %s", path, arc.ref, busy)return arc.ref, None, False@@ -393,9 +414,11 @@ def _recheck(repo_root: str, d: Decision) -> tuple[Optional[str], Optional[str]]return None, lock_state-def execute_plan(repo_root: str, plan: list[Decision], settings: dict) -> tuple[list[str], set, list[str]]:- """Apply a frozen plan -> ``(preserved_stale, kept_branches, archived_refs)``. Each tree is- re-gated (lock, live process, fresh activity) right before it is archived or removed."""+def execute_plan(repo_root: str, plan: list[Decision], settings: dict+ ) -> tuple[list[str], set, list[tuple[str, bool]]]:+ """Apply a frozen plan -> ``(preserved_stale, kept_branches, [(archive_ref, removed)])``. Each+ tree is re-gated (lock, live process, fresh activity) right before it is archived or removed;+ ``removed`` is False when the archive was saved but the tree was kept (changed meanwhile)."""from hermes_cli import worktree_ops as opsfrom hermes_cli.worktree_archive import ArchiveErrormemo: dict = {}@@ -406,7 +429,7 @@ def execute_plan(repo_root: str, plan: list[Decision], settings: dict) -> tuple[return memo["heads"]kept_branches: set = set()- archived: list[str] = []+ archived: list[tuple[str, bool]] = []preserved: list[str] = [f"{d.name} ({d.reason})" for d in plan if d.action.startswith("keep-")]for d in (d for d in plan if d.action in _DESTRUCTIVE):why_keep, lock_state = _recheck(repo_root, d)@@ -419,14 +442,16 @@ def execute_plan(repo_root: str, plan: list[Decision], settings: dict) -> tuple[kept_branches |= keptcontinuetry:- ref, kept, _removed = archive_then_remove(+ ref, kept, removed = archive_then_remove(repo_root, d.path, reason=f"sweep: {d.reason}", max_untracked_mb=settings["archive_max_file_mb"],unlock=lock_state == "dead", remote_heads_fn=remote_heads)except (ArchiveError, OSError, subprocess.SubprocessError) as exc:logger.warning("Keeping worktree %s: archive failed (%s)", d.name, exc)preserved.append(f"{d.name} (archive failed)")continue- archived.append(ref)+ archived.append((ref, removed))+ if not removed:+ preserved.append(f"{d.name} (archived to {ref}, kept: changed during the sweep)")if kept:kept_branches.add(kept)return preserved, kept_branches, archived@@ -438,9 +463,10 @@ def run_sweep(repo_root: str, max_age_hours: int, settings: dict) -> None:from hermes_cli.worktree_archive import prune_expired_archivesplan = plan_sweep(repo_root, max_age_hours, settings)preserved, kept_branches, archived = execute_plan(repo_root, plan, settings)- if archived:+ removed = [ref for ref, gone in archived if gone]+ if removed:logger.warning("Archived and removed %d idle worktree(s) with unmerged work; restore any with "- "`hermes worktree restore <name>` (`hermes worktree list` shows archives).", len(archived))+ "`hermes worktree restore <name>` (`hermes worktree list` shows archives).", len(removed))if preserved:logger.warning("Preserving %d stale worktree(s) (run `hermes worktree prune --dry-run` for reasons): %s",len(preserved), ", ".join(sorted(preserved)[:20]))diff --git a/locales/af.yaml b/locales/af.yamlindex 76f60469b63..9c0d6ef5680 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Werkboom geargiveer na {ref} en verwyder: {path}"restore_hint: "Herstel dit met: hermes worktree restore {name}"archive_failed: "✗ Kon nie {path} argiveer nie, word behou: {error}"- archive_not_removed: "Die argief is gestoor, maar {path} kon nie verwyder word nie; verwyder dit met die hand."+ archived_kept: "✓ Werkboom geargiveer na {ref} maar behou (dit het verander, is in gebruik, of kon nie verwyder word nie): {path}"+ sweep_archived_removed: "geargiveer + verwyder → {ref}"+ sweep_archived_kept: "geargiveer, behou (verander tydens die opruiming) → {ref}"discarded: "Werkboom verwyder en sy veranderinge weggegooi: {path}"display:verb:diff --git a/locales/ar.yaml b/locales/ar.yamlindex 23a33a58260..f17953a663f 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ تمت أرشفة الـ worktree في {ref} وإزالته: {path}"restore_hint: "لاستعادته: hermes worktree restore {name}"archive_failed: "✗ تعذّرت أرشفة {path}، سيُحتفظ به: {error}"- archive_not_removed: "تم حفظ الأرشيف، لكن تعذّرت إزالة {path}؛ أزله يدويًا."+ archived_kept: "✓ تمت أرشفة الـ worktree في {ref} لكن احتُفظ به (تغيّر، أو قيد الاستخدام، أو تعذّرت إزالته): {path}"+ sweep_archived_removed: "أُرشف + أُزيل → {ref}"+ sweep_archived_kept: "أُرشف، واحتُفظ به (تغيّر أثناء التنظيف) → {ref}"discarded: "تمت إزالة الـ worktree وتجاهل تغييراته: {path}"display:verb:diff --git a/locales/de.yaml b/locales/de.yamlindex b718bc5b637..fd4690f38c1 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree nach {ref} archiviert und entfernt: {path}"restore_hint: "Wiederherstellen mit: hermes worktree restore {name}"archive_failed: "✗ {path} konnte nicht archiviert werden, wird behalten: {error}"- archive_not_removed: "Das Archiv ist gespeichert, aber {path} konnte nicht entfernt werden; bitte manuell entfernen."+ archived_kept: "✓ Worktree nach {ref} archiviert, aber behalten (geändert, in Benutzung oder nicht entfernbar): {path}"+ sweep_archived_removed: "archiviert + entfernt → {ref}"+ sweep_archived_kept: "archiviert, behalten (während der Bereinigung geändert) → {ref}"discarded: "Worktree entfernt und Änderungen verworfen: {path}"display:verb:diff --git a/locales/en.yaml b/locales/en.yamlindex e54f58cf295..d98d2a07bb6 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -3409,7 +3409,9 @@ cli:archived: "✓ Worktree archived to {ref} and removed: {path}"restore_hint: "Restore it with: hermes worktree restore {name}"archive_failed: "✗ Could not archive {path}, keeping it: {error}"- archive_not_removed: "The archive is saved, but {path} could not be removed; remove it by hand."+ archived_kept: "✓ Worktree archived to {ref} but kept (it changed, is in use, or could not be removed): {path}"+ sweep_archived_removed: "archived + removed → {ref}"+ sweep_archived_kept: "archived, kept (changed during the sweep) → {ref}"discarded: "Worktree removed and its changes discarded: {path}"display:diff --git a/locales/es.yaml b/locales/es.yamlindex 32640b9a4ad..1ee37f4a4a4 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree archivado en {ref} y eliminado: {path}"restore_hint: "Restáuralo con: hermes worktree restore {name}"archive_failed: "✗ No se pudo archivar {path}, se conserva: {error}"- archive_not_removed: "El archivo está guardado, pero no se pudo eliminar {path}; elimínalo manualmente."+ archived_kept: "✓ Worktree archivado en {ref} pero conservado (cambió, está en uso o no se pudo eliminar): {path}"+ sweep_archived_removed: "archivado + eliminado → {ref}"+ sweep_archived_kept: "archivado, conservado (cambió durante la limpieza) → {ref}"discarded: "Worktree eliminado y cambios descartados: {path}"display:verb:diff --git a/locales/fr.yaml b/locales/fr.yamlindex 97264c8d2cb..a458e4ef744 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -3625,7 +3625,9 @@ cli:archived: "✓ Worktree archivé dans {ref} et supprimé : {path}"restore_hint: "Pour le restaurer : hermes worktree restore {name}"archive_failed: "✗ Impossible d'archiver {path}, conservé : {error}"- archive_not_removed: "L'archive est enregistrée, mais {path} n'a pas pu être supprimé ; supprimez-le manuellement."+ archived_kept: "✓ Worktree archivé dans {ref} mais conservé (modifié, en cours d'utilisation ou impossible à supprimer) : {path}"+ sweep_archived_removed: "archivé + supprimé → {ref}"+ sweep_archived_kept: "archivé, conservé (modifié pendant le nettoyage) → {ref}"discarded: "Worktree supprimé et modifications abandonnées : {path}"display:verb:diff --git a/locales/ga.yaml b/locales/ga.yamlindex d2bc56f1e9d..461f547b75f 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree cartlannaithe go {ref} agus bainte: {path}"restore_hint: "Athchóirigh é le: hermes worktree restore {name}"archive_failed: "✗ Níorbh fhéidir {path} a chartlannú, á choinneáil: {error}"- archive_not_removed: "Tá an chartlann sábháilte, ach níorbh fhéidir {path} a bhaint; bain de láimh é."+ archived_kept: "✓ Worktree cartlannaithe go {ref} ach coinnithe (athraíodh é, tá sé in úsáid, nó níorbh fhéidir é a bhaint): {path}"+ sweep_archived_removed: "cartlannaithe + bainte → {ref}"+ sweep_archived_kept: "cartlannaithe, coinnithe (athraithe le linn an scuabtha) → {ref}"discarded: "Worktree bainte agus a athruithe caite uait: {path}"display:verb:diff --git a/locales/hu.yaml b/locales/hu.yamlindex 2a66a89bdc5..38c619094ad 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -3325,7 +3325,9 @@ cli:archived: "✓ Worktree archiválva ide: {ref}, és eltávolítva: {path}"restore_hint: "Visszaállítás: hermes worktree restore {name}"archive_failed: "✗ {path} archiválása sikertelen, megtartva: {error}"- archive_not_removed: "Az archívum elmentve, de {path} nem távolítható el; töröld kézzel."+ archived_kept: "✓ Worktree archiválva ide: {ref}, de megtartva (változott, használatban van, vagy nem távolítható el): {path}"+ sweep_archived_removed: "archiválva + eltávolítva → {ref}"+ sweep_archived_kept: "archiválva, megtartva (a takarítás közben változott) → {ref}"discarded: "Worktree eltávolítva, változásai elvetve: {path}"display:verb:diff --git a/locales/it.yaml b/locales/it.yamlindex ac1c8b7c72a..706ad4a5e7a 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree archiviato in {ref} e rimosso: {path}"restore_hint: "Ripristinalo con: hermes worktree restore {name}"archive_failed: "✗ Impossibile archiviare {path}, lo mantengo: {error}"- archive_not_removed: "L'archivio è salvato, ma non è stato possibile rimuovere {path}; rimuovilo manualmente."+ archived_kept: "✓ Worktree archiviato in {ref} ma mantenuto (modificato, in uso o non rimovibile): {path}"+ sweep_archived_removed: "archiviato + rimosso → {ref}"+ sweep_archived_kept: "archiviato, mantenuto (modificato durante la pulizia) → {ref}"discarded: "Worktree rimosso e modifiche scartate: {path}"display:verb:diff --git a/locales/ja.yaml b/locales/ja.yamlindex d5b9f250b6c..6576d5a6247 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ ワークツリーを {ref} にアーカイブして削除しました: {path}"restore_hint: "復元するには: hermes worktree restore {name}"archive_failed: "✗ {path} をアーカイブできなかったため保持します: {error}"- archive_not_removed: "アーカイブは保存されましたが、{path} を削除できませんでした。手動で削除してください。"+ archived_kept: "✓ ワークツリーを {ref} にアーカイブしましたが保持しました (変更された、使用中、または削除できませんでした): {path}"+ sweep_archived_removed: "アーカイブして削除 → {ref}"+ sweep_archived_kept: "アーカイブ済み、保持 (掃除中に変更されました) → {ref}"discarded: "ワークツリーを削除し、変更を破棄しました: {path}"display:verb:diff --git a/locales/ko.yaml b/locales/ko.yamlindex ed4e4ee1c78..6ba95338f5b 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ 워크트리를 {ref}에 보관하고 제거했어요: {path}"restore_hint: "복원하려면: hermes worktree restore {name}"archive_failed: "✗ {path}을(를) 보관하지 못해 유지해요: {error}"- archive_not_removed: "보관은 완료됐지만 {path}을(를) 제거하지 못했어요. 직접 제거해 주세요."+ archived_kept: "✓ 워크트리를 {ref}에 보관했지만 유지했어요 (변경됐거나, 사용 중이거나, 제거할 수 없음): {path}"+ sweep_archived_removed: "보관 후 제거 → {ref}"+ sweep_archived_kept: "보관됨, 유지 (정리 중 변경됨) → {ref}"discarded: "워크트리를 제거하고 변경 사항을 버렸어요: {path}"display:verb:diff --git a/locales/pt.yaml b/locales/pt.yamlindex 8d78313be18..c209b3a1347 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree arquivada em {ref} e removida: {path}"restore_hint: "Restaure com: hermes worktree restore {name}"archive_failed: "✗ Não foi possível arquivar {path}; mantendo: {error}"- archive_not_removed: "O arquivo foi salvo, mas não foi possível remover {path}; remova manualmente."+ archived_kept: "✓ Worktree arquivada em {ref}, mas mantida (foi alterada, está em uso ou não pôde ser removida): {path}"+ sweep_archived_removed: "arquivada + removida → {ref}"+ sweep_archived_kept: "arquivada, mantida (alterada durante a limpeza) → {ref}"discarded: "Worktree removida e alterações descartadas: {path}"display:verb:diff --git a/locales/ru.yaml b/locales/ru.yamlindex 95ad56fa18e..c6bb64ed5d2 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree заархивирован в {ref} и удалён: {path}"restore_hint: "Восстановить: hermes worktree restore {name}"archive_failed: "✗ Не удалось заархивировать {path}, оставляю: {error}"- archive_not_removed: "Архив сохранён, но удалить {path} не удалось; удалите вручную."+ archived_kept: "✓ Worktree заархивирован в {ref}, но сохранён (изменился, используется или не удалось удалить): {path}"+ sweep_archived_removed: "заархивирован + удалён → {ref}"+ sweep_archived_kept: "заархивирован, сохранён (изменился во время очистки) → {ref}"discarded: "Worktree удалён, изменения отброшены: {path}"display:verb:diff --git a/locales/tr.yaml b/locales/tr.yamlindex 2cfbaec9ffe..b43311086c1 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Worktree {ref} konumuna arşivlendi ve kaldırıldı: {path}"restore_hint: "Geri yüklemek için: hermes worktree restore {name}"archive_failed: "✗ {path} arşivlenemedi, korunuyor: {error}"- archive_not_removed: "Arşiv kaydedildi ancak {path} kaldırılamadı; elle kaldırın."+ archived_kept: "✓ Worktree {ref} konumuna arşivlendi ama tutuldu (değişti, kullanımda veya kaldırılamadı): {path}"+ sweep_archived_removed: "arşivlendi + kaldırıldı → {ref}"+ sweep_archived_kept: "arşivlendi, tutuldu (temizlik sırasında değişti) → {ref}"discarded: "Worktree kaldırıldı ve değişiklikleri atıldı: {path}"display:verb:diff --git a/locales/uk.yaml b/locales/uk.yamlindex 5a4c1d1b45f..6c431541925 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ Робоче дерево заархівовано в {ref} і видалено: {path}"restore_hint: "Відновити: hermes worktree restore {name}"archive_failed: "✗ Не вдалося заархівувати {path}, залишаємо: {error}"- archive_not_removed: "Архів збережено, але {path} не вдалося видалити; видаліть вручну."+ archived_kept: "✓ Робоче дерево заархівовано в {ref}, але збережено (змінилося, використовується або не вдалося видалити): {path}"+ sweep_archived_removed: "заархівовано + видалено → {ref}"+ sweep_archived_kept: "заархівовано, збережено (змінилося під час очищення) → {ref}"discarded: "Робоче дерево видалено, зміни відкинуто: {path}"display:verb:diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex 89947b2d88e..b6d9ff2b9f2 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ 工作樹已封存至 {ref} 並移除:{path}"restore_hint: "還原方式:hermes worktree restore {name}"archive_failed: "✗ 無法封存 {path},保留:{error}"- archive_not_removed: "封存已儲存,但無法移除 {path};請手動移除。"+ archived_kept: "✓ 工作樹已封存至 {ref},但已保留(有變更、使用中或無法移除):{path}"+ sweep_archived_removed: "已封存並移除 → {ref}"+ sweep_archived_kept: "已封存,保留(清理期間有變更)→ {ref}"discarded: "工作樹已移除,變更已捨棄:{path}"display:verb:diff --git a/locales/zh.yaml b/locales/zh.yamlindex b781a921d10..c4cf597bb1e 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -3308,7 +3308,9 @@ cli:archived: "✓ 工作树已归档到 {ref} 并移除:{path}"restore_hint: "恢复方式:hermes worktree restore {name}"archive_failed: "✗ 无法归档 {path},保留:{error}"- archive_not_removed: "归档已保存,但无法移除 {path};请手动移除。"+ archived_kept: "✓ 工作树已归档到 {ref},但已保留(有变更、使用中或无法移除):{path}"+ sweep_archived_removed: "已归档并移除 → {ref}"+ sweep_archived_kept: "已归档,保留(清理期间有变更)→ {ref}"discarded: "工作树已移除,更改已丢弃:{path}"display:verb:diff --git a/tests/hermes_cli/test_worktree_snapshot_prune.py b/tests/hermes_cli/test_worktree_snapshot_prune.pyindex 46101684c57..eed30e5b3bc 100644--- a/tests/hermes_cli/test_worktree_snapshot_prune.py+++ b/tests/hermes_cli/test_worktree_snapshot_prune.py@@ -166,34 +166,81 @@ def test_sweep_archives_idle_work_and_never_touches_live_kanban_or_young_trees(rassert kept.exists() and (kept / "notes.md").read_text(encoding="utf-8-sig") == "uncommitted\n", kept.name-def test_a_tree_resumed_mid_sweep_is_never_removed(repo, monkeypatch):+def test_a_tree_resumed_mid_sweep_is_never_removed(repo, monkeypatch, capsys):"""I2 at the removal boundary: a process entering a later tree while an earlier one is being- archived, or an edit made while a tree's own snapshot ran, keeps that tree."""- from hermes_cli import worktree_archive, worktree_sweep+ archived, an edit made while a tree's own snapshot ran, or an index-only edit (``git apply+ --cached``: no file, HEAD or reflog mtime moves) made right after capture keeps that tree, and+ the sweep reports it as archived-but-kept, not removed."""+ from hermes_cli import worktree_archive, worktree_cmd, worktree_sweepfirst, second = _tree(repo, "lane-a", dirty=True), _tree(repo, "lane-b", dirty=True)- for tree in (first, second):+ staged = _tree(repo, "lane-staged", dirty=True)+ for tree in (first, second, staged):_idle(tree)- plan = worktree_sweep.plan_sweep(str(repo), settings=worktree_sweep.sweep_settings())- assert {d.name for d in plan if d.action == "archive-remove"} == {"lane-a", "lane-b"}real_snapshot, sleepers = worktree_archive.snapshot_worktree, []+ patch = ("--- a/b.py\n+++ b/b.py\n@@ -1 +1 @@\n-x = 1\n+NEW STAGED CONTENT\n")def snapshot_then_user_returns(repo_root, wt_path, **kw):arc = real_snapshot(repo_root, wt_path, **kw)+ if Path(wt_path).name == "lane-staged":+ subprocess.run(["git", "apply", "--cached", "-"], cwd=str(wt_path), input=patch.encode(), check=True)+ subprocess.run(["git", "status", "--porcelain"], cwd=str(wt_path), capture_output=True, check=True)+ return arc(Path(wt_path) / "notes.md").write_text("edited during the snapshot\n", encoding="utf-8")sleepers.append(subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], cwd=str(second)))return arcmonkeypatch.setattr(worktree_archive, "snapshot_worktree", snapshot_then_user_returns)try:- worktree_sweep.execute_plan(str(repo), plan, worktree_sweep.sweep_settings())+ plan, actions = worktree_cmd._sweep(str(repo), dry_run=False)finally:for proc in sleepers:proc.kill()proc.wait()+ assert {d.name for d in plan if d.action == "archive-remove"} == {"lane-a", "lane-b", "lane-staged"}assert (first / "notes.md").read_text(encoding="utf-8-sig") == "edited during the snapshot\n"assert second.exists() and (second / "notes.md").read_text(encoding="utf-8-sig") == "uncommitted\n"- assert [ref.rsplit("/", 1)[-1] for ref in _archives(repo)] == ["lane-a"]+ assert staged.exists() and _git(["show", ":b.py"], staged) == "NEW STAGED CONTENT"+ assert sorted(ref.rsplit("/", 1)[-1] for ref in _archives(repo)) == ["lane-a", "lane-staged"]+ assert sorted(actions) == ["archived, kept (changed during the sweep) → refs/hermes/archive/lane-a",+ "archived, kept (changed during the sweep) → refs/hermes/archive/lane-staged"]+++def test_dirty_submodule_work_is_never_archived_away(repo, tmp_path):+ """C1: a snapshot records a submodule only as its gitlink, so a tree whose initialized+ submodule holds uncommitted edits survives the real sweep byte-for-byte, and the shared+ snapshot entry point (exit-time Archive, subagent finalization) refuses it too. A tree whose+ submodule is clean at the recorded commit is still archived and removed."""+ from hermes_cli.worktree_archive import ArchiveError, snapshot_worktree++ sub_origin, sub_work = tmp_path / "sub.git", tmp_path / "subwork"+ _git(["init", "-q", "--bare", "-b", "main", str(sub_origin)], tmp_path)+ _git(["init", "-q", "-b", "main", str(sub_work)], tmp_path)+ (sub_work / "file.txt").write_text("base\n", encoding="utf-8")+ _git(["add", "-A"], sub_work)+ _git(["commit", "-qm", "sub"], sub_work)+ _git(["push", "-q", str(sub_origin), "main"], sub_work)+ _git(["-c", "protocol.file.allow=always", "submodule", "add", "-q", str(sub_origin), "sub"], repo)+ _git(["commit", "-qm", "add submodule"], repo)+ trees = {}+ for name in ("lane-subdirty", "lane-subclean"):+ trees[name] = _tree(repo, name, dirty=True)+ _git(["-c", "protocol.file.allow=always", "submodule", "update", "-q", "--init"], trees[name])+ dirty_file = trees["lane-subdirty"] / "sub" / "file.txt"+ dirty_file.write_bytes(b"base\nUNCOMMITTED SUBMODULE EDIT\r\n")+ for tree in trees.values():+ _idle(tree)+ from hermes_cli import worktree_sweep+ plan = {d.name: d.action for d in worktree_sweep.plan_sweep(str(repo), settings=worktree_sweep.sweep_settings())}+ assert plan == {"lane-subdirty": "keep-submodule-work", "lane-subclean": "archive-remove"}++ worktree_ops._prune_stale_worktrees(str(repo))++ assert dirty_file.read_bytes() == b"base\nUNCOMMITTED SUBMODULE EDIT\r\n"+ assert not trees["lane-subclean"].exists(), "a clean submodule at the recorded commit is archivable"+ assert [ref.rsplit("/", 1)[-1] for ref in _archives(repo)] == ["lane-subclean"]+ with pytest.raises(ArchiveError, match="submodule sub"):+ snapshot_worktree(str(repo), trees["lane-subdirty"], reason="session exit")def test_prune_older_than_bounds_what_the_sweep_removes(repo, capsys):diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.pyindex 8d1000f39cd..2af985fbc6b 100644--- a/tools/subagent_worktree.py+++ b/tools/subagent_worktree.py@@ -225,9 +225,13 @@ def _archive_finished_worktree(info: dict[str, str], payload: dict[str, Any]) ->return payloadpayload["archive"] = refpayload["pruned"] = removed- payload["note"] = (f"Worktree archived to {ref} and removed; branch {info.get('branch')} kept. "- f"Restore the full tree (including uncommitted edits) with "- f"`hermes worktree restore {ref.rsplit('/', 1)[-1]}`.")+ if removed:+ payload["note"] = (f"Worktree archived to {ref} and removed; branch {info.get('branch')} kept. "+ f"Restore the full tree (including uncommitted edits) with "+ f"`hermes worktree restore {ref.rsplit('/', 1)[-1]}`.")+ else:+ payload["note"] = (f"Worktree archived to {ref} but kept at {path} (it changed after the snapshot "+ f"or could not be removed); branch {info.get('branch')} kept.")return payloaddiff --git a/website/docs/user-guide/git-worktrees.md b/website/docs/user-guide/git-worktrees.mdindex 68f993f4030..9156bdb5b91 100644--- a/website/docs/user-guide/git-worktrees.md+++ b/website/docs/user-guide/git-worktrees.md@@ -213,12 +213,15 @@ repositories' `.worktrees/`:| A live hermes lock owner, or any live process whose cwd (Linux: or an open file) is inside | never touched || File, `HEAD` or reflog activity younger than its tier (a deleted file counts through its folder) | never touched || Kanban task trees (`t_<hex>`) | never touched (the Kanban GC owns them) |+| An initialized submodule with uncommitted edits, a different commit than recorded, or commits on no remote | kept (`keep-submodule-work`: an archive records only the submodule pointer) |An archive is a commit stored at `refs/hermes/archive/<tree>` holding thetree's `HEAD`, staged changes, unstaged changes and untracked files (files your`.gitignore` excludes, such as `node_modules/` or `.venv/`, are not captured).It is built with a temporary index, so the tree itself is never modified; if-the archive cannot be built, the tree is kept. File bytes are stored and+the archive cannot be built, the tree is kept. If the tree is entered or its+staged changes move (`git add`, `git apply --cached`) while the archive is+being built, the archive is saved and the tree is kept too. File bytes are stored andrestored exactly: no `.gitattributes`, `info/attributes`, `core.attributesFile`line-ending or filter rule is applied. Untracked files larger than`worktrees.archive_max_file_mb` are left out and listed in the archive. A