Skip to content

The agent that grows with you

fix: worktree sweep honours --older-than, re-gates each tree, archives exact bytes

Teknium71a83d74d581
diff --git a/cli.py b/cli.py
index 58616470dd7..d6afbd3f052 100644
--- a/cli.py
+++ b/cli.py
@@ -559,7 +559,7 @@ def _cleanup_worktree(info: dict[str, str] | None = None) -> None:
return
_active_worktree = None
from hermes_cli.worktree_exit import apply_exit_choice
- if apply_exit_choice(info, _cprint): # the exit question's Archive / Discard answer
+ if apply_exit_choice(info, _cprint): # an exit-question answer not applied yet (normally none)
return
if _worktree_is_dirty(wt_path, repo_root, timeout=10):
diff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.py
index cce21be34aa..75d9af97534 100644
--- a/hermes_cli/cli_tui_runtime_mixin.py
+++ b/hermes_cli/cli_tui_runtime_mixin.py
@@ -541,12 +541,14 @@ class CLITuiRuntimeMixin:
# turn fires it in the gateway when the interrupted turn finalizes.
if self.agent and self._agent_running and not _gateway_owns_session_end(self.agent):
_invoke_interrupted_session_end(self.agent, self.agent.session_id, "shutdown")
- # Before _run_cleanup arms the exit watchdog; a signal-driven exit never asks.
+ # Ask AND apply before _run_cleanup arms the exit watchdog, so a large archive is never cut
+ # short; a signal-driven exit never asks.
import cli as _cli_mod
- if not _cli_mod._signal_watchdog_armed:
- from hermes_cli.worktree_exit import ask_exit_choice
- with suppress(Exception):
+ if not _cli_mod._signal_watchdog_armed and _cli_mod._active_worktree:
+ from hermes_cli.worktree_exit import apply_exit_choice, ask_exit_choice
+ with suppress(Exception, KeyboardInterrupt):
ask_exit_choice(_cli_mod._active_worktree)
+ apply_exit_choice(_cli_mod._active_worktree, _cprint)
_run_cleanup()
self._print_exit_summary()
self._release_active_session()
diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.py
index fd034df2ef1..1d4f8a2aff5 100644
--- a/hermes_cli/web_git.py
+++ b/hermes_cli/web_git.py
@@ -718,7 +718,11 @@ def worktree_add(cwd: str, options: dict) -> dict:
root = _main_root(cwd)
options = options or {}
if options.get("existingBranch"):
- return _worktree_for_existing(root, options["existingBranch"])
+ result = _worktree_for_existing(root, options["existingBranch"])
+ if result.get("path") != root: # a new checkout, not a switch of the main tree
+ from hermes_cli.worktree_registry import record_worktree_repo
+ record_worktree_repo(root)
+ return result
slug = _slugify(options.get("name") or f"work-{os.urandom(4).hex()}")
branch = _sanitize_branch(options.get("branch") or "") or f"hermes/{slug}"
diff --git a/hermes_cli/worktree_archive.py b/hermes_cli/worktree_archive.py
index 102630f11f5..dece66b448f 100644
--- a/hermes_cli/worktree_archive.py
+++ b/hermes_cli/worktree_archive.py
@@ -7,9 +7,10 @@ are only read): ``I`` = the staged state (tree of a copy of the real index, pare
branch, HEAD, reason, skipped files) as JSON in its message, and the ref keeps every object
reachable, so the tree and even its branch can be deleted without losing work.
-Bytes are stored raw: clean/smudge filters are neutralized (``noninteractive_repo_git_env``),
-``core.autocrlf`` is off and ``.gitattributes`` are read from the empty tree, so a restore writes
-back exactly the bytes that were archived. Untracked files over a size cap are skipped and listed
+Bytes are stored raw: every tracked/untracked regular file is re-hashed with
+``hash-object --no-filters`` and restored by writing the blob bytes directly, so no attribute
+source (``.gitattributes``, ``$GIT_COMMON_DIR/info/attributes``, ``core.attributesFile``) and no
+clean/smudge/eol conversion can change them; a restore writes back exactly the archived bytes. Untracked files over a size cap are skipped and listed
(so ``.git`` never balloons with build artefacts the ignore rules missed); an untracked embedded
repository cannot be captured at all and fails the snapshot, which keeps the tree.
"""
@@ -94,6 +95,73 @@ def _raw_attrs(args, cwd, env, empty_tree: str, **kw) -> str:
return result.stdout
+def _run_bytes(args, cwd, env, data: bytes, timeout: float = 300) -> bytes:
+ result = subprocess.run(["git", *args], cwd=str(cwd), env=env, capture_output=True, input=data,
+ timeout=timeout, check=False)
+ if result.returncode != 0:
+ raise ArchiveError(f"git {args[0]} failed: {result.stderr.decode('utf-8', 'replace').strip()[-300:]}")
+ return result.stdout
+
+
+def _regular_entries(cwd, env) -> list[tuple[str, str, str]]:
+ """``(mode, sha, path)`` for every regular-file entry of the index ``env`` points at."""
+ out = _ok(["ls-files", "-s", "-z"], cwd, env)
+ entries = []
+ for record in out.split("\0"):
+ meta, _, path = record.partition("\t")
+ parts = meta.split()
+ if path and len(parts) == 3 and parts[0] in ("100644", "100755"):
+ entries.append((parts[0], parts[1], path))
+ return entries
+
+
+def _rehash_raw(wt: Path, tenv) -> None:
+ """Replace every regular-file blob in the temporary index with the file's exact bytes.
+
+ ``add`` runs content conversion from every attribute source, and ``--attr-source`` only
+ replaces ``.gitattributes``: ``info/attributes`` and ``core.attributesFile`` still apply.
+ ``hash-object --no-filters`` skips all of it.
+ """
+ entries = [e for e in _regular_entries(wt, tenv) if os.path.isfile(wt / e[2]) and not os.path.islink(wt / e[2])]
+ if not entries:
+ return
+ shas: list[str] = []
+ # --stdin-paths reads one path per line and C-unquotes a leading '"': hash those one by one.
+ batch = [p for _m, _s, p in entries if "\n" not in p and not p.startswith('"')]
+ if batch:
+ data = "".join(p + "\n" for p in batch).encode("utf-8", "surrogateescape")
+ shas = _run_bytes(["hash-object", "-w", "--no-filters", "--stdin-paths"], wt, tenv, data).decode().split()
+ by_path = dict(zip(batch, shas))
+ for _m, _s, path in entries:
+ if path not in by_path:
+ raw = (wt / path).read_bytes()
+ by_path[path] = _run_bytes(["hash-object", "-w", "--no-filters", "--stdin"], wt, tenv, raw).decode().strip()
+ info = "".join(f"{mode} {by_path[path]}\t{path}\0" for mode, _s, path in entries)
+ _run_bytes(["update-index", "-z", "--index-info"], wt, tenv, info.encode("utf-8", "surrogateescape"))
+
+
+def _write_raw(dest: Path, env) -> None:
+ """Overwrite every regular file of the index with its blob's exact bytes (no smudge/eol)."""
+ entries = _regular_entries(dest, env)
+ if not entries:
+ return
+ out = _run_bytes(["cat-file", "--batch"], dest, env, "".join(f"{s}\n" for _m, s, _p in entries).encode())
+ pos = 0
+ for _mode, _sha, path in entries:
+ header_end = out.index(b"\n", pos)
+ size = int(out[pos:header_end].split()[2])
+ body = out[header_end + 1:header_end + 1 + size]
+ pos = header_end + 1 + size + 1
+ target = dest / path
+ if target.is_symlink():
+ target.unlink()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ mode = target.stat().st_mode if target.exists() else None
+ target.write_bytes(body)
+ if mode is not None:
+ os.chmod(target, mode)
+
+
def ref_safe(name: str) -> str:
"""A tree name as a single valid ref component."""
safe = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-.") or "tree"
@@ -173,9 +241,8 @@ def snapshot_worktree(repo_root: str, wt_path, *, reason: str, max_untracked_mb:
pathspec.write_bytes(("\0".join(specs) + "\0").encode("utf-8", "surrogateescape"))
_raw_attrs(["add", "-A", "--pathspec-from-file", str(pathspec), "--pathspec-file-nul"],
wt, tenv, empty_tree)
- # Unmodified tracked files keep their normalized (e.g. LF) index blob; re-hash them raw so
- # a CRLF/smudged checkout comes back byte-for-byte.
- _raw_attrs(["add", "--renormalize", "--", ":(top)"], wt, tenv, empty_tree)
+ # Every blob from the exact bytes on disk (add converted them per attributes).
+ _rehash_raw(wt, tenv)
work_tree = _ok(["write-tree"], wt, tenv).strip()
index_commit = _ok(["commit-tree", index_tree, "-p", head, "-m", f"index of {wt.name}"], wt, env).strip()
meta = {"version": 1, "name": wt.name, "path": str(wt), "repo_root": str(repo_root),
@@ -290,6 +357,7 @@ def restore_archive(repo_root: str, name: str, target=None) -> dict:
empty_tree = _ok(["mktree"], dest, wenv, stdin_text="").strip()
_ok(["read-tree", f"{arc.sha}^{{tree}}"], dest, wenv)
_raw_attrs(["checkout-index", "-a", "-f"], dest, wenv, empty_tree)
+ _write_raw(dest, wenv) # checkout-index still converted per info/attributes
_ok(["read-tree", f"{index_commit}^{{tree}}"], dest, wenv)
_run(["update-index", "-q", "--refresh"], dest, wenv)
from hermes_cli.worktree_registry import record_worktree_repo
diff --git a/hermes_cli/worktree_cmd.py b/hermes_cli/worktree_cmd.py
index 256fcfb29e3..660b14ba09e 100644
--- a/hermes_cli/worktree_cmd.py
+++ b/hermes_cli/worktree_cmd.py
@@ -83,11 +83,12 @@ def _sweep_lines(plan) -> list[str]:
return lines
-def _sweep(repo_root: str, dry_run: bool) -> tuple[list, list[str]]:
- """The automatic sweep's plan for this repo (applied unless *dry_run*) -> (plan, actions)."""
+def _sweep(repo_root: str, dry_run: bool, older_than: Optional[float] = None) -> tuple[list, list[str]]:
+ """The automatic sweep's plan for this repo (applied unless *dry_run*) -> (plan, actions).
+ *older_than* (days) bounds what the plan may archive or remove before anything runs."""
from hermes_cli import worktree_sweep
settings = worktree_sweep.sweep_settings()
- plan = worktree_sweep.plan_sweep(repo_root, settings=settings)
+ plan = worktree_sweep.plan_sweep(repo_root, settings=settings, older_than_days=older_than)
if dry_run or worktree_sweep.classic_mode(settings):
return plan, []
_, _, archived = worktree_sweep.execute_plan(repo_root, plan, settings)
@@ -116,7 +117,7 @@ def _prune(worktree_gc, repo_root: str, args) -> int:
kept: list = []
plan: list = []
if not getattr(args, "branches_only", False):
- plan, actions = _sweep(repo_root, dry_run)
+ plan, actions = _sweep(repo_root, dry_run, older_than)
if not as_json:
print("\n".join(_sweep_lines(plan)) + "\n")
actions += worktree_gc.prune_missing_registrations(repo_root, dry_run=dry_run)
diff --git a/hermes_cli/worktree_exit.py b/hermes_cli/worktree_exit.py
index 1f1506e9509..20764e4d7c9 100644
--- a/hermes_cli/worktree_exit.py
+++ b/hermes_cli/worktree_exit.py
@@ -3,7 +3,8 @@ dirty or unpushed worktree.
Asked once, in the foreground, after the UI released the terminal: by the classic CLI in
``_tui_shutdown`` (before ``_run_cleanup`` arms the exit watchdog) and by the TUI launcher after
-the Ink child exits. The answer is applied by the exit cleanup. Only a real interactive session
+the Ink child exits. The answer is applied right there, synchronously, before any exit watchdog
+or teardown runs: a large archive is never cut short, and a failed one keeps the tree. Only a real interactive session
asks: ``-q``/``-z``/cron/gateway never reach these call sites, a missing TTY or a signal-driven
shutdown skips the question, and every skip means Keep (the sweep archives the tree later).
"""
@@ -80,21 +81,24 @@ def ask_exit_choice(info: Optional[dict]) -> str:
def apply_exit_choice(info: dict, echo) -> bool:
- """Carry out an Archive/Discard answer -> True when the tree was handled (removed or a
+ """Carry out an Archive/Discard answer once -> True when the tree was handled (removed or a
message printed). Keep (or no answer) -> False: the caller's default keep path runs."""
- choice = info.get("exit_choice")
+ choice = info.pop("exit_choice", None)
if choice not in (ARCHIVE, DISCARD):
return False
path, repo_root, branch = info["path"], info["repo_root"], info.get("branch")
if choice == ARCHIVE:
+ import subprocess
+
from hermes_cli.worktree_archive import ArchiveError
from hermes_cli.worktree_sweep import archive_then_remove, sweep_settings
+ echo(t("cli.worktree.archiving", path=path))
try:
ref, _kept, removed = archive_then_remove(
- repo_root, path, reason="session exit", unlock=True,
+ repo_root, path, reason="session exit", unlock=True, exclude_pids=(os.getpid(),),
max_untracked_mb=sweep_settings()["archive_max_file_mb"])
- except (ArchiveError, OSError) as exc:
- echo(f"\033[31m{t('cli.worktree.archive_failed', path=path, error=exc)}\033[0m")
+ except (ArchiveError, OSError, subprocess.SubprocessError, KeyboardInterrupt) as exc:
+ echo(f"\033[31m{t('cli.worktree.archive_failed', path=path, error=str(exc) or 'interrupted')}\033[0m")
return True
name = ref.rsplit("/", 1)[-1]
echo(f"\033[32m{t('cli.worktree.archived', path=path, ref=ref)}\033[0m")
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index 402f0ee1e8e..3563b9cbc1e 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -909,18 +909,28 @@ def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10
return "dead" if pid is not None else "live" # a session lock without its store: unverifiable
+# Trees Hermes names itself (``hermes -w`` sessions, subagent isolation) age on the base tier.
+_AUTO_TREE_PREFIXES = ("hermes-", "subagent-")
+
+
+def prune_tier_hours(name: str, max_age_hours: float) -> float:
+ """Idle hours before a tree may be reclaimed: *max_age_hours* for Hermes-made trees
+ (``hermes-*``, ``subagent-*``), 3x for deliberately named ones."""
+ return max_age_hours if name.startswith(_AUTO_TREE_PREFIXES) else max_age_hours * 3
+
+
def _prune_candidates(worktrees_dir: Path, max_age_hours: int, now: float) -> list:
"""Phase 1, stat-only age filter -> ``[(entry, mtime, force)]`` for trees past their soft cutoff.
- Kanban trees (``t_<hex>``) belong to the kanban gc. ``hermes-*`` trees age on *max_age_hours*,
- deliberately named trees at 3x; *force* marks the hard (3x) tier.
+ Kanban trees (``t_<hex>``) belong to the kanban gc. Hermes-made trees age on *max_age_hours*,
+ deliberately named trees at 3x (``prune_tier_hours``); *force* marks the hard (3x) tier.
"""
kanban_re = re.compile(r"^t_[0-9a-f]+$")
candidates: list = []
for entry in sorted(worktrees_dir.iterdir()):
if not entry.is_dir() or kanban_re.match(entry.name):
continue
- tier_hours = max_age_hours if entry.name.startswith("hermes-") else max_age_hours * 3
+ tier_hours = prune_tier_hours(entry.name, max_age_hours)
try:
mtime = entry.stat().st_mtime
if mtime > now - (tier_hours * 3600):
diff --git a/hermes_cli/worktree_sweep.py b/hermes_cli/worktree_sweep.py
index 466f032eace..853252d60fa 100644
--- a/hermes_cli/worktree_sweep.py
+++ b/hermes_cli/worktree_sweep.py
@@ -44,6 +44,8 @@ class Decision:
verdict: str = ""
lock_state: Optional[str] = None
size_mb: Optional[int] = None
+ tier_hours: float = 0.0
+ planned_at: float = 0.0
def as_dict(self) -> dict:
return asdict(self)
@@ -144,11 +146,13 @@ def live_process_pids(paths, exclude=()) -> dict[str, list[int]]:
def _last_activity(path: str) -> float:
- """Newest mtime among the tree's ref/reflog files and every changed or untracked file.
+ """Newest mtime among the tree's HEAD/reflog, every changed or untracked file, and the
+ directory holding each changed path.
The tree dir's own mtime only moves when a top-level entry is created or removed, so a lane
- editing files deep inside for days still looks idle by it. ``GIT_OPTIONAL_LOCKS=0`` keeps
- this probe from refreshing (and re-stamping) the index.
+ editing files deep inside for days still looks idle by it. A deleted file has no mtime; its
+ nearest surviving parent directory was stamped by the unlink. The index is not a signal:
+ the classifier's own ``git status`` may rewrite it. ``GIT_OPTIONAL_LOCKS=0`` keeps this probe from refreshing (and re-stamping) the index.
"""
from hermes_cli._subprocess_compat import noninteractive_repo_git_env
newest = 0.0
@@ -159,7 +163,7 @@ def _last_activity(path: str) -> float:
env["GIT_OPTIONAL_LOCKS"] = "0"
try:
git_dir = subprocess.run(["git", "rev-parse", "--absolute-git-dir"], cwd=path, env=env, capture_output=True,
- text=True, timeout=10, stdin=subprocess.DEVNULL, check=False).stdout.strip()
+ text=True, encoding="utf-8", errors="surrogateescape", timeout=10, stdin=subprocess.DEVNULL, check=False).stdout.strip()
status = subprocess.run(["git", "status", "--porcelain", "-z", "-uall", "--no-renames"], cwd=path, env=env,
capture_output=True, text=True, encoding="utf-8", errors="surrogateescape",
timeout=60, stdin=subprocess.DEVNULL, check=False)
@@ -168,8 +172,14 @@ def _last_activity(path: str) -> float:
if status.returncode != 0:
return time.time()
candidates = [Path(git_dir) / name for name in ("HEAD", "logs/HEAD")] if git_dir else []
- candidates += [wt / entry[3:] for entry in status.stdout.split("\0") if len(entry) > 3]
- for candidate in candidates:
+ changed = [wt / entry[3:] for entry in status.stdout.split("\0") if len(entry) > 3]
+ candidates += changed
+ for item in changed:
+ parent = item.parent
+ while parent != wt and not parent.exists() and wt in parent.parents:
+ parent = parent.parent # a whole deleted subtree: its surviving ancestor moved
+ candidates.append(parent)
+ for candidate in dict.fromkeys(candidates):
try:
newest = max(newest, candidate.lstat().st_mtime)
except OSError:
@@ -181,27 +191,28 @@ def _last_activity(path: str) -> float:
def _tier_hours(name: str, max_age_hours: float) -> float:
- return max_age_hours if name.startswith("hermes-") else max_age_hours * 3
+ from hermes_cli.worktree_ops import prune_tier_hours
+ return prune_tier_hours(name, max_age_hours)
def _plan_survivor(repo_root: str, entry: Path, verdict: str, lock_state, settings: dict,
- tier_hours: float, now: float) -> tuple[str, str, Optional[str]]:
- """(action, reason, lock_state) for a dirty/unpushed tree past its tier."""
+ 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."""
from hermes_cli import worktree_ops as ops
from hermes_cli.worktree_archive import archive_preflight
what = _ARCHIVE_REASONS[verdict]
lock_state = ops._worktree_lock_is_live(repo_root, str(entry), timeout=5)
if lock_state == "live":
- return "skip-live-lock", "lock owner still running", lock_state
+ return "skip-live-lock", "lock owner still running", lock_state, None
active = _last_activity(str(entry))
if active > now - tier_hours * 3600:
- return "skip-young", f"{what}; last activity {(now - active) / 3600:.1f}h ago", lock_state
+ return "skip-young", f"{what}; last activity {(now - active) / 3600:.1f}h ago", lock_state, active
if not settings["archive_dirty"]:
- return f"keep-{verdict}", what, lock_state # idle: only the size budget may evict it
+ return f"keep-{verdict}", what, lock_state, active # idle: only the size budget may evict it
unsafe = archive_preflight(str(entry))
if unsafe:
- return "keep-unarchivable", unsafe, lock_state
- return "archive-remove", what, lock_state
+ return "keep-unarchivable", unsafe, lock_state, active
+ return "archive-remove", what, lock_state, active
def _apply_budget(decisions: list[Decision], max_total_gb: float) -> None:
@@ -227,9 +238,16 @@ def _apply_budget(decisions: list[Decision], max_total_gb: float) -> None:
total -= d.size_mb or 0
+_DESTRUCTIVE = ("remove", "remove-keep-branch", "archive-remove")
+
+
def plan_sweep(repo_root: str, max_age_hours: int = 24, settings: Optional[dict] = None,
- now: Optional[float] = None) -> list[Decision]:
- """Read-only decision for every tree under ``<repo>/.worktrees`` (kanban/young included)."""
+ now: Optional[float] = None, older_than_days: Optional[float] = None) -> list[Decision]:
+ """Read-only decision for every tree under ``<repo>/.worktrees`` (kanban/young included).
+
+ *older_than_days* (``hermes worktree prune --older-than``) only restricts: a tree idle for
+ less than that is never archived or removed, whatever its tier.
+ """
import re
from hermes_cli import worktree_ops as ops
@@ -255,8 +273,9 @@ def plan_sweep(repo_root: str, max_age_hours: int = 24, settings: Optional[dict]
# archive_dirty: false is the classic pruner verbatim (I6), which has no process check.
live = {} if classic_mode(settings) else live_process_pids([str(v[0]) for v in verdicts])
for entry, mtime, force, verdict, lock_state in verdicts:
+ tier = _tier_hours(entry.name, max_age_hours)
d = Decision(entry.name, str(entry), "", "", round((now - mtime) / 3600, 1), mtime=mtime, force=force,
- verdict=verdict, lock_state=lock_state)
+ verdict=verdict, lock_state=lock_state, tier_hours=tier, planned_at=now)
if live.get(str(entry)):
d.action, d.reason = "skip-live-process", f"in use by pid {', '.join(map(str, live[str(entry)][:5]))}"
elif verdict == "locked-live":
@@ -264,14 +283,20 @@ def plan_sweep(repo_root: str, max_age_hours: int = 24, settings: Optional[dict]
elif verdict in _ARCHIVE_REASONS and classic_mode(settings):
d.action, d.reason = f"keep-{verdict}", _ARCHIVE_REASONS[verdict]
elif verdict in _ARCHIVE_REASONS:
- d.action, d.reason, d.lock_state = _plan_survivor(
- repo_root, entry, verdict, lock_state, settings, _tier_hours(entry.name, max_age_hours), now)
+ d.action, d.reason, d.lock_state, active = _plan_survivor(
+ repo_root, entry, verdict, lock_state, settings, tier, now)
+ if active:
+ d.age_hours = min(d.age_hours, round((now - active) / 3600, 1))
else:
d.action = "remove-keep-branch" if verdict == "reap-keep-branch" else "remove"
d.reason = "pushed to origin; branch kept" if verdict == "reap-keep-branch" else "clean and merged/pushed"
decisions.append(d)
if settings["max_total_gb"]:
_apply_budget(decisions, settings["max_total_gb"])
+ if older_than_days is not None:
+ for d in decisions:
+ if d.action in _DESTRUCTIVE and d.age_hours < older_than_days * 24:
+ d.action, d.reason = "skip-young", f"idle {d.age_hours:.1f}h (--older-than {older_than_days:g})"
return decisions
@@ -293,19 +318,39 @@ def _branch_published(repo_root: str, branch: str, remote_heads: Optional[dict])
return refs is None or bool(refs.strip())
+def _in_use_since(path: str, since: float, exclude=()) -> Optional[str]:
+ """Why *path* must not be removed now: a live process works in it, or a file/ref in it
+ changed at or after *since*. None = still idle."""
+ pids = live_process_pids([path], exclude=exclude).get(path)
+ if pids:
+ return f"in use by pid {', '.join(map(str, pids[:5]))}"
+ active = _last_activity(path)
+ if active >= since:
+ return f"changed {max(0.0, time.time() - active):.0f}s ago"
+ return None
+
+
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=(),
) -> tuple[str, Optional[str], bool]:
"""Snapshot *path*, then remove it -> ``(archive_ref, kept_branch, removed)``.
- Raises ``ArchiveError`` (tree untouched) when the snapshot fails. The branch survives 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.
+ 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
+ survives 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.
"""
from hermes_cli.worktree_archive import snapshot_worktree
from hermes_cli.worktree_ops import _git, _git_quiet, release_lsp_clients
from hermes_cli._subprocess_compat import noninteractive_git_env
+ started = 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)
+ if busy:
+ logger.warning("Archived %s to %s but keeping it: %s", path, arc.ref, busy)
+ return arc.ref, None, False
release_lsp_clients(path)
if unlock:
_git_quiet(["worktree", "unlock", path], repo_root, log=f"unlock {path}")
@@ -327,13 +372,32 @@ def archive_then_remove(repo_root: str, path: str, *, reason: str, max_untracked
return arc.ref, None, True
+def _recheck(repo_root: str, d: Decision) -> tuple[Optional[str], Optional[str]]:
+ """Fresh gate for ONE planned tree, run immediately before it is touched -> (why_keep,
+ lock_state). Earlier trees in the batch can take minutes to archive; a user may have entered
+ this one meanwhile."""
+ from hermes_cli import worktree_ops as ops
+ if not os.path.isdir(d.path):
+ return "gone", None
+ lock_state = ops._worktree_lock_is_live(repo_root, d.path, timeout=5)
+ if lock_state == "live":
+ return "lock owner still running", lock_state
+ since = d.planned_at or time.time()
+ if d.action == "archive-remove" and d.tier_hours:
+ since = min(since, time.time() - d.tier_hours * 3600) # back inside its idle tier
+ busy = _in_use_since(d.path, since)
+ if busy:
+ return busy, lock_state
+ if d.action != "archive-remove" and ops._worktree_is_dirty(d.path, repo_root, timeout=10):
+ return "new uncommitted changes", lock_state
+ 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)``."""
+ """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."""
from hermes_cli import worktree_ops as ops
from hermes_cli.worktree_archive import ArchiveError
- doomed = [d for d in plan if d.action in ("remove", "remove-keep-branch", "archive-remove")]
- # Classification can take minutes on a big board: re-check liveness right before acting.
- live = live_process_pids([d.path for d in doomed])
memo: dict = {}
def remote_heads():
@@ -341,18 +405,23 @@ def execute_plan(repo_root: str, plan: list[Decision], settings: dict) -> tuple[
memo["heads"] = ops._fetch_remote_branch_heads(repo_root, timeout=10)
return memo["heads"]
- reap = [(Path(d.path), d.mtime, d.force, d.verdict, d.lock_state) for d in doomed
- if d.action != "archive-remove" and not live.get(d.path)]
- _, kept_branches = ops._reap_prune_verdicts(repo_root, reap, 0.0)
+ kept_branches: set = set()
archived: list[str] = []
preserved: list[str] = [f"{d.name} ({d.reason})" for d in plan if d.action.startswith("keep-")]
- for d in doomed:
- if d.action != "archive-remove" or live.get(d.path):
+ for d in (d for d in plan if d.action in _DESTRUCTIVE):
+ why_keep, lock_state = _recheck(repo_root, d)
+ if why_keep:
+ logger.info("Sweep: keeping %s (%s)", d.name, why_keep)
+ continue
+ if d.action != "archive-remove":
+ _, kept = ops._reap_prune_verdicts(
+ repo_root, [(Path(d.path), d.mtime, d.force, d.verdict, lock_state)], 0.0)
+ kept_branches |= kept
continue
try:
ref, kept, _removed = archive_then_remove(
repo_root, d.path, reason=f"sweep: {d.reason}", max_untracked_mb=settings["archive_max_file_mb"],
- unlock=d.lock_state == "dead", remote_heads_fn=remote_heads)
+ 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)")
diff --git a/locales/af.yaml b/locales/af.yaml
index d4ed7fff359..76f60469b63 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Hou die werkboom (verstek)"
exit_choice_archive: "Argiveer en verwyder dit (herstelbaar)"
exit_choice_discard: "Verwyder dit en gooi die veranderinge weg"
+ archiving: "Argiveer {path} … (dit kan 'n rukkie neem vir 'n groot boom)"
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}"
diff --git a/locales/ar.yaml b/locales/ar.yaml
index e67ce4650b1..23a33a58260 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "الاحتفاظ بالـ worktree (افتراضي)"
exit_choice_archive: "أرشفته وإزالته (قابل للاستعادة)"
exit_choice_discard: "إزالته وتجاهل التغييرات"
+ archiving: "جارٍ أرشفة {path} … (قد يستغرق ذلك بعض الوقت لشجرة كبيرة)"
archived: "✓ تمت أرشفة الـ worktree في {ref} وإزالته: {path}"
restore_hint: "لاستعادته: hermes worktree restore {name}"
archive_failed: "✗ تعذّرت أرشفة {path}، سيُحتفظ به: {error}"
diff --git a/locales/de.yaml b/locales/de.yaml
index cdf05adab4d..b718bc5b637 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Worktree behalten (Standard)"
exit_choice_archive: "Archivieren und entfernen (wiederherstellbar)"
exit_choice_discard: "Entfernen und Änderungen verwerfen"
+ archiving: "Archiviere {path} … (bei einem großen Tree kann das dauern)"
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}"
diff --git a/locales/en.yaml b/locales/en.yaml
index f16d61564d8..e54f58cf295 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -3405,6 +3405,7 @@ cli:
exit_choice_keep: "Keep the worktree (default)"
exit_choice_archive: "Archive and remove it (restorable)"
exit_choice_discard: "Remove it and discard the changes"
+ archiving: "Archiving {path} … (this can take a while for a large tree)"
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}"
diff --git a/locales/es.yaml b/locales/es.yaml
index 4fd6b3b29c8..32640b9a4ad 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Conservar el worktree (predeterminado)"
exit_choice_archive: "Archivarlo y eliminarlo (recuperable)"
exit_choice_discard: "Eliminarlo y descartar los cambios"
+ archiving: "Archivando {path} … (puede tardar en un árbol grande)"
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}"
diff --git a/locales/fr.yaml b/locales/fr.yaml
index 68b98ad2cff..97264c8d2cb 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -3621,6 +3621,7 @@ cli:
exit_choice_keep: "Conserver le worktree (par défaut)"
exit_choice_archive: "L'archiver et le supprimer (restaurable)"
exit_choice_discard: "Le supprimer et abandonner les modifications"
+ archiving: "Archivage de {path} … (cela peut prendre du temps pour un grand arbre)"
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}"
diff --git a/locales/ga.yaml b/locales/ga.yaml
index 8641036b608..d2bc56f1e9d 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Coinnigh an worktree (réamhshocrú)"
exit_choice_archive: "Cartlannaigh agus bain é (is féidir é a athchóiriú)"
exit_choice_discard: "Bain é agus caith na hathruithe uait"
+ archiving: "{path} á chartlannú … (féadfaidh sé seo tamall a thógáil do chrann mór)"
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}"
diff --git a/locales/hu.yaml b/locales/hu.yaml
index da1268684e1..2a66a89bdc5 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -3321,6 +3321,7 @@ cli:
exit_choice_keep: "Worktree megtartása (alapértelmezett)"
exit_choice_archive: "Archiválás és eltávolítás (visszaállítható)"
exit_choice_discard: "Eltávolítás a változások elvetésével"
+ archiving: "{path} archiválása … (nagy fánál ez eltarthat egy ideig)"
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}"
diff --git a/locales/it.yaml b/locales/it.yaml
index 3a36eb0e838..ac1c8b7c72a 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Mantieni il worktree (predefinito)"
exit_choice_archive: "Archivialo e rimuovilo (ripristinabile)"
exit_choice_discard: "Rimuovilo e scarta le modifiche"
+ archiving: "Archiviazione di {path} … (può richiedere tempo per un albero grande)"
archived: "✓ Worktree archiviato in {ref} e rimosso: {path}"
restore_hint: "Ripristinalo con: hermes worktree restore {name}"
archive_failed: "✗ Impossibile archiviare {path}, lo mantengo: {error}"
diff --git a/locales/ja.yaml b/locales/ja.yaml
index 92428628b13..d5b9f250b6c 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "ワークツリーを保持する(デフォルト)"
exit_choice_archive: "アーカイブして削除する(復元可能)"
exit_choice_discard: "削除して変更を破棄する"
+ archiving: "{path} をアーカイブしています…(大きなツリーでは時間がかかることがあります)"
archived: "✓ ワークツリーを {ref} にアーカイブして削除しました: {path}"
restore_hint: "復元するには: hermes worktree restore {name}"
archive_failed: "✗ {path} をアーカイブできなかったため保持します: {error}"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index 58be7799fde..ed4e4ee1c78 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "워크트리 유지 (기본값)"
exit_choice_archive: "보관 후 제거 (복원 가능)"
exit_choice_discard: "제거하고 변경 사항 버리기"
+ archiving: "{path} 보관 중… (큰 트리는 시간이 걸릴 수 있습니다)"
archived: "✓ 워크트리를 {ref}에 보관하고 제거했어요: {path}"
restore_hint: "복원하려면: hermes worktree restore {name}"
archive_failed: "✗ {path}을(를) 보관하지 못해 유지해요: {error}"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index 88b631b9738..8d78313be18 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Manter a worktree (padrão)"
exit_choice_archive: "Arquivar e remover (restaurável)"
exit_choice_discard: "Remover e descartar as alterações"
+ archiving: "Arquivando {path} … (pode demorar em uma árvore grande)"
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}"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index 3bf292fb266..95ad56fa18e 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Оставить worktree (по умолчанию)"
exit_choice_archive: "Архивировать и удалить (можно восстановить)"
exit_choice_discard: "Удалить и отбросить изменения"
+ archiving: "Архивирование {path} … (для большого дерева это может занять время)"
archived: "✓ Worktree заархивирован в {ref} и удалён: {path}"
restore_hint: "Восстановить: hermes worktree restore {name}"
archive_failed: "✗ Не удалось заархивировать {path}, оставляю: {error}"
diff --git a/locales/tr.yaml b/locales/tr.yaml
index a7843d2018a..2cfbaec9ffe 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Worktree'yi koru (varsayılan)"
exit_choice_archive: "Arşivle ve kaldır (geri yüklenebilir)"
exit_choice_discard: "Kaldır ve değişiklikleri at"
+ archiving: "{path} arşivleniyor … (büyük bir ağaçta bu biraz sürebilir)"
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}"
diff --git a/locales/uk.yaml b/locales/uk.yaml
index 00e729ee02e..5a4c1d1b45f 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "Залишити робоче дерево (типово)"
exit_choice_archive: "Архівувати й видалити (можна відновити)"
exit_choice_discard: "Видалити й відкинути зміни"
+ archiving: "Архівування {path} … (для великого дерева це може зайняти час)"
archived: "✓ Робоче дерево заархівовано в {ref} і видалено: {path}"
restore_hint: "Відновити: hermes worktree restore {name}"
archive_failed: "✗ Не вдалося заархівувати {path}, залишаємо: {error}"
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index f2e35b983d5..89947b2d88e 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "保留工作樹(預設)"
exit_choice_archive: "封存並移除(可還原)"
exit_choice_discard: "移除並捨棄變更"
+ archiving: "正在封存 {path} …(大型工作樹可能需要一些時間)"
archived: "✓ 工作樹已封存至 {ref} 並移除:{path}"
restore_hint: "還原方式:hermes worktree restore {name}"
archive_failed: "✗ 無法封存 {path},保留:{error}"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index 66cacf5d295..b781a921d10 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -3304,6 +3304,7 @@ cli:
exit_choice_keep: "保留工作树(默认)"
exit_choice_archive: "归档并移除(可恢复)"
exit_choice_discard: "移除并丢弃更改"
+ archiving: "正在归档 {path} …(大型工作树可能需要一些时间)"
archived: "✓ 工作树已归档到 {ref} 并移除:{path}"
restore_hint: "恢复方式:hermes worktree restore {name}"
archive_failed: "✗ 无法归档 {path},保留:{error}"
diff --git a/tests/hermes_cli/test_web_server_git.py b/tests/hermes_cli/test_web_server_git.py
index 7e08ed24adf..a94a827a651 100644
--- a/tests/hermes_cli/test_web_server_git.py
+++ b/tests/hermes_cli/test_web_server_git.py
@@ -1,4 +1,5 @@
import asyncio
+import os
import subprocess
import threading
from pathlib import Path
@@ -251,6 +252,9 @@ def test_worktree_add_existing_remote_branch_tracks_not_detaches(client, repo_wi
cwd=tree, check=True, capture_output=True, text=True,
).stdout.strip()
assert upstream == "origin/feature"
+ # Registered for the periodic sweep like every other worktree-creation path.
+ from hermes_cli.worktree_registry import registered_repos
+ assert os.path.realpath(repo_with_remote) in registered_repos()
def test_worktree_add_from_origin_base_does_not_track(client, repo_with_remote):
diff --git a/tests/hermes_cli/test_worktree_snapshot_prune.py b/tests/hermes_cli/test_worktree_snapshot_prune.py
index 5424aa9b1c5..46101684c57 100644
--- a/tests/hermes_cli/test_worktree_snapshot_prune.py
+++ b/tests/hermes_cli/test_worktree_snapshot_prune.py
@@ -83,11 +83,18 @@ def _set_worktrees_config(text):
def test_removed_dirty_tree_restores_byte_for_byte_and_archiving_never_touches_the_tree(repo):
- """I1 + I4: HEAD, staged, unstaged (CRLF) and untracked bytes survive delete -> restore;
- the archive step leaves the real index and every working file untouched."""
+ """I1 + I4: HEAD, staged, unstaged (CRLF) and untracked bytes survive delete -> restore,
+ even under eol rules from info/attributes and core.attributesFile (which ``--attr-source``
+ does not replace); the archive step leaves the real index and every working file untouched."""
from hermes_cli.worktree_archive import restore_archive, snapshot_worktree
+ (repo / ".git" / "info").mkdir(exist_ok=True)
+ (repo / ".git" / "info" / "attributes").write_text("*.md text eol=crlf\n", encoding="utf-8")
+ (repo / "attrs").write_text("*.cfg text eol=lf\n", encoding="utf-8")
+ _git(["config", "core.attributesFile", str(repo / "attrs")], repo)
wt = _tree(repo, "lane-roundtrip", unpushed=True)
+ (wt / "lf.md").write_bytes(b"lf only\n") # restore must not add CR
+ (wt / "crlf.cfg").write_bytes(b"keep\r\nthe CR\r\n") # archive must not strip CR
(wt / "b.py").write_text("x = 2\n", encoding="utf-8")
_git(["add", "b.py"], wt)
(wt / "b.py").write_text("x = 3\n", encoding="utf-8") # unstaged on top of a staged change
@@ -129,8 +136,17 @@ def test_sweep_archives_idle_work_and_never_touches_live_kanban_or_young_trees(r
unarchivable = _tree(repo, "lane-embedded", dirty=True)
_git(["init", "-q", str(unarchivable / "inner")], repo)
(unarchivable / "inner" / "f").write_text("x", encoding="utf-8")
- for tree in (clean, dirty, unpushed, live_cwd, live_lock, kanban, unarchivable):
+ subagent = _tree(repo, "subagent-done", dirty=True)
+ deleted = _tree(repo, "lane-deleted")
+ (deleted / "sub").mkdir()
+ (deleted / "sub" / "x.py").write_text("x\n", encoding="utf-8")
+ (deleted / "sub" / "y.py").write_text("y\n", encoding="utf-8")
+ _git(["add", "sub"], deleted)
+ _git(["commit", "-qm", "sub"], deleted)
+ for tree in (clean, dirty, unpushed, live_cwd, live_lock, kanban, unarchivable, deleted):
_idle(tree)
+ _idle(subagent, hours=30) # past the 24h hermes-made tier, inside 72h
+ (deleted / "sub" / "x.py").unlink() # the newest work: a deletion in a subdir
sleeper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"], cwd=str(live_cwd))
try:
worktree_ops._prune_stale_worktrees(str(repo))
@@ -141,13 +157,61 @@ def test_sweep_archives_idle_work_and_never_touches_live_kanban_or_young_trees(r
assert not clean.exists()
for gone in (dirty, unpushed):
assert not gone.exists(), f"idle {gone.name} should be archived then removed"
+ assert not subagent.exists(), "subagent-* trees age on the 24h tier"
archived = {ref.rsplit("/", 1)[-1] for ref in _archives(repo)}
- assert archived == {"lane-dirty", "hermes-unpushed"}
+ assert archived == {"lane-dirty", "hermes-unpushed", "subagent-done"}
+ assert (deleted / "sub" / "y.py").exists(), "a fresh deletion is activity: the tree is not idle"
assert _git(["show", "refs/hermes/archive/lane-dirty:notes.md"], repo) == "uncommitted"
for kept in (live_cwd, live_lock, kanban, young, unarchivable):
assert 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):
+ """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
+
+ first, second = _tree(repo, "lane-a", dirty=True), _tree(repo, "lane-b", dirty=True)
+ for tree in (first, second):
+ _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, []
+
+ def snapshot_then_user_returns(repo_root, wt_path, **kw):
+ arc = real_snapshot(repo_root, wt_path, **kw)
+ (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 arc
+
+ monkeypatch.setattr(worktree_archive, "snapshot_worktree", snapshot_then_user_returns)
+ try:
+ worktree_sweep.execute_plan(str(repo), plan, worktree_sweep.sweep_settings())
+ finally:
+ for proc in sleepers:
+ proc.kill()
+ proc.wait()
+ 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"]
+
+
+def test_prune_older_than_bounds_what_the_sweep_removes(repo, capsys):
+ """`hermes worktree prune --older-than N` never archives or removes a tree idle < N days."""
+ import argparse
+
+ from hermes_cli.worktree_cmd import cmd_worktree
+
+ dirty, clean = _tree(repo, "hermes-dirty", dirty=True), _tree(repo, "hermes-clean")
+ for tree in (dirty, clean):
+ _idle(tree) # ~4 days idle: past every tier
+ args = argparse.Namespace(repo=str(repo), worktree_action="prune", dry_run=False, json=True,
+ older_than=30, trees_only=True, branches_only=False)
+ assert cmd_worktree(args) == 0
+ assert dirty.exists() and clean.exists()
+ assert _archives(repo) == []
+
+
def test_archive_dirty_false_keeps_the_classic_never_delete_dirty_pruner(repo):
"""I6: the opt-out removes exactly what the classic pruner removes and archives nothing."""
_set_worktrees_config("worktrees:\n archive_dirty: false\n")
diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.py
index b50641c6419..8d1000f39cd 100644
--- a/tools/subagent_worktree.py
+++ b/tools/subagent_worktree.py
@@ -218,7 +218,8 @@ def _archive_finished_worktree(info: dict[str, str], payload: dict[str, Any]) ->
try:
ref, _kept, removed = archive_then_remove(
info.get("repo_root", "") or path, path, reason="subagent finished",
- max_untracked_mb=settings["archive_max_file_mb"], unlock=False, keep_branch=True)
+ max_untracked_mb=settings["archive_max_file_mb"], unlock=False, keep_branch=True,
+ exclude_pids=(os.getpid(),))
except (ArchiveError, OSError, subprocess.SubprocessError) as exc:
logger.warning("subagent worktree: archive failed, keeping %s: %s", path, exc)
return payload
diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.md
index 43299714cab..0577ae53853 100644
--- a/website/docs/user-guide/cli.md
+++ b/website/docs/user-guide/cli.md
@@ -88,8 +88,9 @@ Worktrees registered **outside** `.worktrees/` (created by hand or by another
tool) are reported read-only in `list` output and are never removed. The one
exception is metadata: registrations whose directory no longer exists are
dropped via `git worktree prune` (no files are touched). `--older-than DAYS`
-only ever narrows what gets reaped — a tree carrying real work is kept at any
-age regardless of the flag.
+only ever narrows what gets reaped, including what the stale-worktree sweep
+archives and removes during that run: a tree idle for less than DAYS is
+never touched.
Inside a session, `/worktree prune [--dry-run]` does the same (and never
touches the tree the session is running in).
@@ -115,7 +116,8 @@ Safety guarantees (all modes, any age):
remote can't be reached, the tree is preserved.
- Trees **in use** are never touched: a running hermes session's lock, or any
live process whose working directory (or, on Linux, an open file) is inside
- the tree.
+ the tree. Each tree is checked again right before it is archived or removed,
+ and again after its archive is built; a tree that changed meanwhile is kept.
- **Untracked-only scratch** (PR body drafts, notes) is archived to
`~/.hermes/archive/worktree-prune/` before its tree is removed — never
destroyed.
diff --git a/website/docs/user-guide/git-worktrees.md b/website/docs/user-guide/git-worktrees.md
index 6c855aaf16f..68f993f4030 100644
--- a/website/docs/user-guide/git-worktrees.md
+++ b/website/docs/user-guide/git-worktrees.md
@@ -189,7 +189,9 @@ worktree has uncommitted changes or unpushed commits, Hermes asks:
- **Keep the worktree** (default, also what Enter/Esc picks) — nothing changes.
- **Archive and remove it** — the full working state is archived (see below)
- and the tree is removed; Hermes prints the `hermes worktree restore` command.
+ and the tree is removed before the session finishes exiting, so a large tree
+ is never cut short; Hermes prints the `hermes worktree restore` command. If
+ the archive fails, the tree is kept.
- **Remove it and discard the changes** — only when you pick it explicitly.
One-shot runs (`-q`, `-z`), cron jobs, gateway sessions and any exit without a
@@ -209,14 +211,16 @@ repositories' `.worktrees/`:
| Idle past its tier (`hermes-*`/`subagent-*` 24 h, named trees 72 h), clean and merged or pushed | removed |
| Idle past its tier with uncommitted changes or unpushed commits | **archived, then removed** |
| 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 | 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 archive is a commit stored at `refs/hermes/archive/<tree>` holding the
tree'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. Untracked files larger than
+the archive cannot be built, the tree is kept. File bytes are stored and
+restored 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
branch that exists on a remote (an open PR) is kept; otherwise the archive
holds its commits and the local branch is deleted.