Skip to content

The agent that grows with you

feat: archive stale dirty worktrees before removing them, sweep every repo, ask on dirty exit

Teknium3882113085a9
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 59222a67c7f..bbb132c0b94 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -392,6 +392,15 @@ model:
# worktree_sync: true # Default — branch from the fetched remote tip
# worktree_sync: false # Branch from local HEAD (offline / pinned base)
+# Stale worktree sweep (startup of `hermes -w` + every 6h from the cron ticker, over
+# every repo Hermes created a worktree in). Idle dirty/unpushed trees are archived to
+# refs/hermes/archive/<tree> and removed; `hermes worktree restore <name>` brings one back.
+# worktrees:
+# archive_dirty: true # false = never remove dirty/unpushed trees (old behaviour)
+# archive_max_file_mb: 50 # untracked files above this are listed, not archived
+# archive_retention_days: 30 # archive refs older than this are deleted (0 = keep)
+# max_total_gb: 0 # optional budget for idle trees; oldest evicted first
+
# =============================================================================
# Kanban Review Dispatch
# =============================================================================
diff --git a/cli.py b/cli.py
index 61b31129e64..58616470dd7 100644
--- a/cli.py
+++ b/cli.py
@@ -558,6 +558,9 @@ def _cleanup_worktree(info: dict[str, str] | None = None) -> None:
if not Path(wt_path).exists():
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
+ return
if _worktree_is_dirty(wt_path, repo_root, timeout=10):
# Uncommitted work: say so, and don't hint at `remove --force`, which would destroy it.
diff --git a/cron/scheduler.py b/cron/scheduler.py
index bcd93d8d1a5..6594a3f487a 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -4022,15 +4022,20 @@ _last_dead_owner_reap_at: dict[str, float] = {}
# Worktree prune throttle: the cron tick is the only reliably periodic process on gateway boxes.
_WORKTREE_MAINTENANCE_INTERVAL_SECONDS = 6 * 3600.0
-_last_worktree_maintenance_at: Optional[float] = None
+_last_worktree_maintenance_at: Optional[dict] = None # profile home -> monotonic stamp
_worktree_maintenance_lock = threading.Lock()
def _worktree_maintenance_repos() -> list[str]:
- """Repos whose ``.worktrees/`` to keep pruned: the hermes checkout plus job workdir repo roots,
- filtered to those that actually have a ``.worktrees/`` dir."""
+ """Repos whose ``.worktrees/`` to keep pruned: the hermes checkout, job workdir repo roots and
+ every repo this profile created a worktree in (``worktree_registry``), filtered to those that
+ actually have a ``.worktrees/`` dir."""
repos: set = set()
+ with contextlib.suppress(Exception):
+ from hermes_cli.worktree_registry import registered_repos
+ repos.update(registered_repos())
+
# Hermes source checkout (git installs only; wheel installs have no .git).
with contextlib.suppress(Exception):
install_root = Path(__file__).resolve().parent.parent
@@ -4059,18 +4064,24 @@ def _worktree_maintenance_repos() -> list[str]:
def _maybe_run_worktree_maintenance() -> None:
"""Throttled worktree prune from the cron tick, on a daemon thread so the tick never waits on
- git. Same conservative pruner as ``hermes -w`` startup (dirty/unpushed/locked trees untouched).
- Errors never propagate: GC is hygiene, not scheduling."""
+ git. Same pruner as ``hermes -w`` startup (idle dirty/unpushed trees archived before removal,
+ live trees untouched). Throttled per profile home: a multiplexed tick runs once per served
+ profile, and each must sweep its own registered repos under its own config. The thread runs in
+ a copy of the caller's context so the profile-home override travels with it. Errors never
+ propagate: GC is hygiene, not scheduling."""
global _last_worktree_maintenance_at
+ import contextvars
+
+ from hermes_constants import get_hermes_home
+
+ home = str(get_hermes_home())
now = time.monotonic()
with _worktree_maintenance_lock:
- if (
- _last_worktree_maintenance_at is not None
- and now - _last_worktree_maintenance_at
- < _WORKTREE_MAINTENANCE_INTERVAL_SECONDS
- ):
+ stamps = _last_worktree_maintenance_at or {}
+ last = stamps.get(home)
+ if last is not None and now - last < _WORKTREE_MAINTENANCE_INTERVAL_SECONDS:
return
- _last_worktree_maintenance_at = now
+ _last_worktree_maintenance_at = {**stamps, home: now}
def _run() -> None:
try:
@@ -4087,7 +4098,8 @@ def _maybe_run_worktree_maintenance() -> None:
except Exception:
logger.debug("Cron worktree maintenance skipped", exc_info=True)
- threading.Thread(target=_run, name="cron-worktree-prune", daemon=True).start()
+ threading.Thread(target=contextvars.copy_context().run, args=(_run,), name="cron-worktree-prune",
+ daemon=True).start()
def _acquire_tick_lock(lock_file):
diff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.py
index 8cf83a9b8d5..cce21be34aa 100644
--- a/hermes_cli/cli_tui_runtime_mixin.py
+++ b/hermes_cli/cli_tui_runtime_mixin.py
@@ -541,6 +541,12 @@ 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.
+ import cli as _cli_mod
+ if not _cli_mod._signal_watchdog_armed:
+ from hermes_cli.worktree_exit import ask_exit_choice
+ with suppress(Exception):
+ ask_exit_choice(_cli_mod._active_worktree)
_run_cleanup()
self._print_exit_summary()
self._release_active_session()
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 9efeaa94c72..203517890d8 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -492,6 +492,22 @@ DEFAULT_CONFIG = {
# browser_cdp / browser_evaluate capabilities.
"extension_control": {"enabled": False, "developer_mode": False},
},
+ # Stale git worktree lifecycle (`hermes -w`, `/worktree new`, subagent isolation, Desktop). The
+ # sweep runs at `hermes -w` startup and every 6h from the cron ticker over every repo Hermes made
+ # a worktree in. Trees idle past their tier (hermes-*/subagent-* 24h, named 72h) that are clean
+ # and merged are removed; dirty or unpushed ones are archived to refs/hermes/archive/<tree>
+ # first (`hermes worktree restore <name>`). Live trees and Kanban t_<hex> trees are never touched.
+ "worktrees": {
+ # false = never remove a dirty/unpushed tree (the pre-archive behaviour, exactly).
+ "archive_dirty": True,
+ # Untracked files larger than this (MB) are left out of the archive and listed in it.
+ "archive_max_file_mb": 50,
+ # The sweep deletes archive refs older than this many days. 0 keeps them forever.
+ "archive_retention_days": 30,
+ # Optional size budget (GB) for idle trees: past it the oldest idle trees are archived and
+ # removed first. Live, young and Kanban trees are never counted or touched. 0 = off.
+ "max_total_gb": 0,
+ },
# Filesystem checkpoints: snapshot the working directory once per turn (on the first
# write_file/patch call); restore with /rollback. Opt-in via `hermes chat --checkpoints` or
# enabled=True (most users never use /rollback). Single shared shadow store with real pruning.
@@ -2717,44 +2733,7 @@ DEFAULT_CONFIG = {
}
-def _env(description, prompt, **keys):
- """One OPTIONAL_ENV_VARS entry; keyword order is preserved as dict key order."""
- return {"description": description, "prompt": prompt, **keys}
-
-
-_OMIT = object()
-
-
-def _category(category, password, advanced):
- """Entry factory for one category with its usual password/advanced defaults.
-
- ``url``/``help``/``tools`` are only written when passed; ``password=None`` omits the key;
- ``advanced`` is only written when true. Key order matches the plain ``_env`` entries.
- """
- def make(description, prompt, url=_OMIT, *, help=_OMIT, tools=_OMIT, password=password,
- advanced=advanced):
- d = {"description": description, "prompt": prompt}
- d.update((k, v) for k, v in (("help", help), ("url", url), ("tools", tools)) if v is not _OMIT)
- if password is not None:
- d["password"] = password
- d["category"] = category
- if advanced:
- d["advanced"] = True
- return d
- return make
-
-
-_prov = _category("provider", password=True, advanced=True)
-_tool = _category("tool", password=True, advanced=False)
-_msg = _category("messaging", password=False, advanced=False)
-_skill = _category("skill", password=True, advanced=True)
-_setting = _category("setting", password=False, advanced=False)
-
-
-def _base_url(name, prompt_name=None):
- """Provider ``*_BASE_URL`` override entry (advanced, not a secret)."""
- prompt = f"{prompt_name or name} base URL (leave empty for default)"
- return _prov(f"{name} base URL override", prompt, None, password=False)
+from hermes_cli.config_defaults_env import _base_url, _env, _msg, _prov, _setting, _skill, _tool
# Optional environment variables that enhance functionality. Feeds the dashboard keys page and setup
diff --git a/hermes_cli/config_defaults_env.py b/hermes_cli/config_defaults_env.py
new file mode 100644
index 00000000000..f982f2914ce
--- /dev/null
+++ b/hermes_cli/config_defaults_env.py
@@ -0,0 +1,41 @@
+"""Entry factories for ``config_defaults.OPTIONAL_ENV_VARS`` (pure-data leaf, no imports)."""
+
+
+def _env(description, prompt, **keys):
+ """One OPTIONAL_ENV_VARS entry; keyword order is preserved as dict key order."""
+ return {"description": description, "prompt": prompt, **keys}
+
+
+_OMIT = object()
+
+
+def _category(category, password, advanced):
+ """Entry factory for one category with its usual password/advanced defaults.
+
+ ``url``/``help``/``tools`` are only written when passed; ``password=None`` omits the key;
+ ``advanced`` is only written when true. Key order matches the plain ``_env`` entries.
+ """
+ def make(description, prompt, url=_OMIT, *, help=_OMIT, tools=_OMIT, password=password,
+ advanced=advanced):
+ d = {"description": description, "prompt": prompt}
+ d.update((k, v) for k, v in (("help", help), ("url", url), ("tools", tools)) if v is not _OMIT)
+ if password is not None:
+ d["password"] = password
+ d["category"] = category
+ if advanced:
+ d["advanced"] = True
+ return d
+ return make
+
+
+_prov = _category("provider", password=True, advanced=True)
+_tool = _category("tool", password=True, advanced=False)
+_msg = _category("messaging", password=False, advanced=False)
+_skill = _category("skill", password=True, advanced=True)
+_setting = _category("setting", password=False, advanced=False)
+
+
+def _base_url(name, prompt_name=None):
+ """Provider ``*_BASE_URL`` override entry (advanced, not a secret)."""
+ prompt = f"{prompt_name or name} base URL (leave empty for default)"
+ return _prov(f"{name} base URL override", prompt, None, password=False)
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.py
index 02f5ccbff26..164939511a1 100644
--- a/hermes_cli/main_tui_launch.py
+++ b/hermes_cli/main_tui_launch.py
@@ -544,6 +544,12 @@ def _launch_tui(
attached_session = _read_tui_active_session_file(active_session_file) or resume_session_id
with contextlib.suppress(OSError):
os.unlink(active_session_file)
+ if wt_info and code in {0, 130}:
+ from hermes_cli.worktree_exit import ask_exit_choice
+ ask_exit_choice(wt_info)
+ from hermes_cli.worktree_exit import apply_exit_choice
+ if wt_info and apply_exit_choice(wt_info, print):
+ wt_info = None # archived or discarded at the user's request
if wt_info:
# Quitting detaches a viewer; the gateway may still be executing in
# this checkout and future resumes retain its frozen cwd.
diff --git a/hermes_cli/subcommands/worktree.py b/hermes_cli/subcommands/worktree.py
index c9dad255a69..951f92630fa 100644
--- a/hermes_cli/subcommands/worktree.py
+++ b/hermes_cli/subcommands/worktree.py
@@ -7,11 +7,12 @@ def build_worktree_parser(subparsers) -> None:
"""Attach the ``worktree`` subcommand to ``subparsers``."""
worktree_parser = subparsers.add_parser(
"worktree", help="Audit and reclaim accumulated git worktrees and merged branches",
- description="Attended reclaim for the .worktrees/ directory hermes -w sessions "
- "accumulate. Never deletes uncommitted tracked changes, unique "
- "unpushed commits, or in-use trees; untracked-only scratch is "
- "archived to ~/.hermes/archive/worktree-prune/ before removal. See: "
- "https://hermes-agent.nousresearch.com/docs/user-guide/cli#worktree-cleanup")
+ description="Audit, reclaim and restore the .worktrees/ trees Hermes sessions "
+ "accumulate. Idle trees with uncommitted changes or unpushed commits are "
+ "archived to refs/hermes/archive/<tree> before removal "
+ "(worktrees.archive_dirty); `restore` brings one back. In-use trees are "
+ "never touched. See: "
+ "https://hermes-agent.nousresearch.com/docs/user-guide/git-worktrees")
worktree_subparsers = worktree_parser.add_subparsers(dest="worktree_action")
worktree_list = worktree_subparsers.add_parser(
"list", aliases=["ls", "audit"],
@@ -41,6 +42,12 @@ def build_worktree_parser(subparsers) -> None:
"--branches-only", action="store_true",
help="Only delete merged local branches; leave worktrees alone")
+ worktree_restore = worktree_subparsers.add_parser(
+ "restore", help="Recreate an archived worktree (tracked, staged and untracked files)")
+ worktree_restore.add_argument("name", help="Archive name or tree name (see `hermes worktree list`)")
+ worktree_restore.add_argument("--path", help="Restore here instead of the original path")
+ worktree_restore.add_argument("--repo", help="Repo root (default: current repo)")
+
def _dispatch_worktree(_args):
from hermes_cli.worktree_cmd import cmd_worktree
diff --git a/hermes_cli/web_git.py b/hermes_cli/web_git.py
index 04d82195cb8..fd034df2ef1 100644
--- a/hermes_cli/web_git.py
+++ b/hermes_cli/web_git.py
@@ -744,6 +744,8 @@ def worktree_add(cwd: str, options: dict) -> dict:
if "already exists" not in (err or "").lower():
raise RuntimeError(err.strip() or "git worktree add failed")
_git_ok(root, ["worktree", "add", target, branch])
+ from hermes_cli.worktree_registry import record_worktree_repo
+ record_worktree_repo(root)
return {"path": target, "branch": branch, "repoRoot": root}
diff --git a/hermes_cli/worktree_archive.py b/hermes_cli/worktree_archive.py
new file mode 100644
index 00000000000..102630f11f5
--- /dev/null
+++ b/hermes_cli/worktree_archive.py
@@ -0,0 +1,298 @@
+"""Restorable snapshots of git worktrees: ``refs/hermes/archive/<tree>``.
+
+A snapshot is two commits built with a TEMPORARY index (the tree's real index and working files
+are only read): ``I`` = the staged state (tree of a copy of the real index, parent ``HEAD``) and
+``W`` = the whole working state (tracked + non-ignored untracked files, parents ``HEAD`` and
+``I``), the same shape ``git stash -u`` produces. ``W`` carries the metadata (original path,
+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
+(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.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import shutil
+import subprocess
+import time
+import uuid
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+ARCHIVE_PREFIX = "refs/hermes/archive/"
+_SUBJECT = "hermes worktree archive: "
+_IDENTITY = {
+ "GIT_AUTHOR_NAME": "Hermes worktree archive", "GIT_AUTHOR_EMAIL": "hermes-archive@localhost",
+ "GIT_COMMITTER_NAME": "Hermes worktree archive", "GIT_COMMITTER_EMAIL": "hermes-archive@localhost",
+}
+# Raw bytes in, raw bytes out: no line-ending conversion on either side of the round trip.
+_RAW_CONFIG = (("core.autocrlf", "false"), ("core.safecrlf", "false"), ("core.eol", "lf"))
+
+
+class ArchiveError(RuntimeError):
+ """The snapshot (or restore) could not be completed; callers must keep the tree."""
+
+
+@dataclass
+class Archive:
+ ref: str
+ name: str
+ sha: str
+ created: float
+ meta: dict = field(default_factory=dict)
+
+
+def _env(cwd, index: Optional[str] = None) -> dict:
+ from hermes_cli._subprocess_compat import noninteractive_repo_git_env
+ env = noninteractive_repo_git_env(cwd)
+ if env is None:
+ raise ArchiveError("git filter discovery failed")
+ env.update(_IDENTITY)
+ start = int(env["GIT_CONFIG_COUNT"])
+ for offset, (key, value) in enumerate(_RAW_CONFIG):
+ env[f"GIT_CONFIG_KEY_{start + offset}"] = key
+ env[f"GIT_CONFIG_VALUE_{start + offset}"] = value
+ env["GIT_CONFIG_COUNT"] = str(start + len(_RAW_CONFIG))
+ if index:
+ env["GIT_INDEX_FILE"] = index
+ return env
+
+
+def _run(args, cwd, env, timeout: float = 300, stdin_text: Optional[str] = None):
+ return subprocess.run(["git", *args], cwd=str(cwd), env=env, capture_output=True, text=True, # windows-footgun: ok -- encoding passed on the next line
+ encoding="utf-8", errors="surrogateescape", timeout=timeout,
+ input=stdin_text, stdin=None if stdin_text is not None else subprocess.DEVNULL,
+ check=False)
+
+
+def _ok(args, cwd, env, **kw) -> str:
+ result = _run(args, cwd, env, **kw)
+ if result.returncode != 0:
+ raise ArchiveError(f"git {args[0]} failed: {result.stderr.strip()[-300:]}")
+ return result.stdout
+
+
+def _raw_attrs(args, cwd, env, empty_tree: str, **kw) -> str:
+ """Run a content-converting command with attributes read from the empty tree (git >= 2.40);
+ older git lacks ``--attr-source`` and falls back to the checkout's own attributes."""
+ result = _run(["--attr-source", empty_tree, *args], cwd, env, **kw)
+ if result.returncode != 0 and "attr-source" in result.stderr:
+ result = _run(args, cwd, env, **kw)
+ if result.returncode != 0:
+ raise ArchiveError(f"git {args[0]} failed: {result.stderr.strip()[-300:]}")
+ return result.stdout
+
+
+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"
+ return safe.replace("..", "-").removesuffix(".lock")
+
+
+def _untracked(wt: Path, env) -> list[str]:
+ out = _ok(["ls-files", "--others", "--exclude-standard", "-z"], wt, env)
+ return [p for p in out.split("\0") if p]
+
+
+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("/")]
+ 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
+
+
+def _split_oversized(wt: Path, untracked: list[str], max_mb: float) -> list[dict]:
+ if max_mb <= 0:
+ return []
+ cap = max_mb * 1024 * 1024
+ skipped = []
+ for rel in untracked:
+ try:
+ size = os.lstat(wt / rel).st_size
+ except OSError:
+ continue
+ if size > cap:
+ skipped.append({"path": rel, "bytes": size})
+ return skipped
+
+
+def _create_ref(repo_root: str, name: str, sha: str, env) -> str:
+ base = ARCHIVE_PREFIX + ref_safe(name)
+ stamp = time.strftime("%Y%m%dT%H%M%S")
+ for ref in (base, f"{base}--{stamp}", *(f"{base}--{stamp}-{i}" for i in range(2, 50))):
+ # Empty old value = create only: two racing sweeps never overwrite each other's archive.
+ if _run(["update-ref", "-m", "hermes worktree archive", ref, sha, ""], repo_root, env).returncode == 0:
+ return ref
+ raise ArchiveError(f"could not create an archive ref for {name}")
+
+
+def snapshot_worktree(repo_root: str, wt_path, *, reason: str, max_untracked_mb: float = 50) -> Archive:
+ """Archive the full working state of *wt_path*; raises :class:`ArchiveError` on any failure.
+
+ Never writes the tree's real index or working files (temporary ``GIT_INDEX_FILE`` only).
+ """
+ wt = Path(wt_path)
+ env = _env(wt)
+ head = _ok(["rev-parse", "--verify", "HEAD^{commit}"], wt, env).strip()
+ branch = _run(["symbolic-ref", "--short", "-q", "HEAD"], wt, env).stdout.strip() or None
+ git_dir = Path(_ok(["rev-parse", "--absolute-git-dir"], wt, env).strip())
+ untracked = _untracked(wt, env)
+ embedded = [p for p in untracked if p.endswith("/")]
+ if embedded:
+ raise ArchiveError(f"untracked embedded repository {embedded[0].rstrip('/')} cannot be archived")
+ skipped = _split_oversized(wt, untracked, max_untracked_mb)
+
+ token = f"hermes-archive-{os.getpid()}-{uuid.uuid4().hex[:8]}"
+ tmp_index, pathspec = git_dir / f"{token}.index", git_dir / f"{token}.pathspec"
+ try:
+ tenv = _env(wt, index=str(tmp_index))
+ if (git_dir / "index").is_file():
+ shutil.copyfile(git_dir / "index", tmp_index)
+ else:
+ _ok(["read-tree", head], 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()
+ specs = [":(top)"] + [f":(top,exclude,literal){s['path']}" for s in skipped]
+ 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)
+ 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),
+ "branch": branch, "head": head, "index_commit": index_commit,
+ "created": int(time.time()), "reason": reason, "skipped_untracked": skipped}
+ message = f"{_SUBJECT}{wt.name}\n\n{json.dumps(meta, indent=1, ensure_ascii=False)}\n"
+ sha = _ok(["commit-tree", work_tree, "-p", head, "-p", index_commit], wt, env,
+ stdin_text=message).strip()
+ finally:
+ for leftover in (tmp_index, tmp_index.with_name(tmp_index.name + ".lock"), pathspec):
+ 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)
+
+
+def _parse_meta(body: str) -> dict:
+ start = body.find("{")
+ try:
+ meta = json.loads(body[start:]) if start >= 0 else {}
+ except ValueError:
+ meta = {}
+ return meta if isinstance(meta, dict) else {}
+
+
+def list_archives(repo_root: str) -> list[Archive]:
+ """Every archive in *repo_root*, newest first. Read-only; [] when git fails."""
+ try:
+ env = _env(repo_root)
+ out = _ok(["for-each-ref", "--sort=-creatordate",
+ "--format=%(refname)%00%(objectname)%00%(creatordate:unix)%00%(contents:body)%00",
+ ARCHIVE_PREFIX], repo_root, env, timeout=60)
+ except (ArchiveError, OSError, subprocess.SubprocessError):
+ return []
+ archives = []
+ for record in out.split("\0\n"):
+ parts = record.split("\0")
+ if len(parts) < 4 or not parts[0].startswith(ARCHIVE_PREFIX):
+ continue
+ meta = _parse_meta(parts[3])
+ created = float(meta.get("created") or parts[2] or 0)
+ archives.append(Archive(ref=parts[0], name=parts[0][len(ARCHIVE_PREFIX):], sha=parts[1],
+ created=created, meta=meta))
+ return archives
+
+
+def find_archive(repo_root: str, name: str) -> Optional[Archive]:
+ """Exact archive name/ref first, else the newest archive of the tree called *name*."""
+ archives = list_archives(repo_root)
+ wanted = name.removeprefix(ARCHIVE_PREFIX)
+ for arc in archives:
+ if arc.name == wanted:
+ return arc
+ return next((a for a in archives if a.meta.get("name") == name or a.name == ref_safe(name)), None)
+
+
+def prune_expired_archives(repo_root: str, retention_days: float, *, now: Optional[float] = None,
+ dry_run: bool = False) -> list[str]:
+ """Delete archive refs older than *retention_days* (0 keeps them forever)."""
+ if not retention_days or retention_days <= 0:
+ return []
+ cutoff = (now or time.time()) - retention_days * 86400
+ expired = [a for a in list_archives(repo_root) if a.created and a.created < cutoff]
+ if dry_run or not expired:
+ return [a.ref for a in expired]
+ env = _env(repo_root)
+ deleted = []
+ for arc in expired:
+ if _run(["update-ref", "-d", arc.ref, arc.sha], repo_root, env).returncode == 0:
+ deleted.append(arc.ref)
+ return deleted
+
+
+def _branch_tip(repo_root: str, branch: str, env) -> Optional[str]:
+ result = _run(["rev-parse", "--verify", "-q", f"refs/heads/{branch}^{{commit}}"], repo_root, env)
+ return result.stdout.strip() if result.returncode == 0 else None
+
+
+def _checked_out_branches(repo_root: str, env) -> set:
+ out = _run(["worktree", "list", "--porcelain"], repo_root, env).stdout
+ return {line[len("branch refs/heads/"):] for line in out.splitlines() if line.startswith("branch refs/heads/")}
+
+
+def _add_args(repo_root: str, dest: Path, branch: Optional[str], head: str, env) -> tuple[list, bool]:
+ """``worktree add`` argv restoring *branch* when that is safe -> (argv, detached)."""
+ base = ["worktree", "add", "--no-checkout"]
+ if branch:
+ tip = _branch_tip(repo_root, branch, env)
+ if tip is None:
+ return [*base, "-b", branch, str(dest), head], False
+ if tip == head and branch not in _checked_out_branches(repo_root, env):
+ return [*base, str(dest), branch], False
+ return [*base, "--detach", str(dest), head], True
+
+
+def restore_archive(repo_root: str, name: str, target=None) -> dict:
+ """Recreate the archived tree at its original path (or *target*); raises ArchiveError."""
+ arc = find_archive(repo_root, name)
+ if arc is None:
+ raise ArchiveError(f"no archive named {name}")
+ meta = arc.meta
+ head = meta.get("head") or f"{arc.sha}^1"
+ index_commit = meta.get("index_commit") or f"{arc.sha}^2"
+ dest = Path(target or meta.get("path") or Path(repo_root) / ".worktrees" / arc.name).absolute()
+ if dest.exists() and (not dest.is_dir() or any(dest.iterdir())):
+ raise ArchiveError(f"{dest} already exists; pass a different path")
+ env = _env(repo_root)
+ args, detached = _add_args(repo_root, dest, meta.get("branch"), head, env)
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ _ok(args, repo_root, env)
+ wenv = _env(dest)
+ 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)
+ _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
+ record_worktree_repo(repo_root)
+ return {"path": str(dest), "branch": meta.get("branch"), "detached": detached, "head": head,
+ "ref": arc.ref, "skipped_untracked": meta.get("skipped_untracked") or []}
diff --git a/hermes_cli/worktree_cmd.py b/hermes_cli/worktree_cmd.py
index 2d64c734c6f..256fcfb29e3 100644
--- a/hermes_cli/worktree_cmd.py
+++ b/hermes_cli/worktree_cmd.py
@@ -1,7 +1,7 @@
-"""``hermes worktree`` — audit (``list [--json] [--older-than DAYS]``) and reclaim
-(``prune [--dry-run] [--json] [--older-than DAYS] [--trees-only | --branches-only]``)
-accumulated git worktrees/branches. ``--json`` output is the only thing written to stdout in
-that mode so scripts can consume it."""
+"""``hermes worktree`` — audit (``list [--json] [--older-than DAYS]``), reclaim
+(``prune [--dry-run] [--json] [--older-than DAYS] [--trees-only | --branches-only]``) and
+``restore <name> [--path DIR]`` accumulated git worktrees/branches. ``--json`` output is the only
+thing written to stdout in that mode so scripts can consume it."""
from __future__ import annotations
@@ -21,14 +21,18 @@ def _list(worktree_gc, repo_root: str, args) -> int:
records = worktree_gc.audit_worktrees(repo_root, older_than_days=older_than)
external = worktree_gc.audit_external_trees(repo_root)
branch_records = worktree_gc.audit_branches(repo_root)
+ from hermes_cli.worktree_archive import list_archives
+ archives = list_archives(repo_root)
if getattr(args, "json", False):
print(json.dumps({
"repo": repo_root,
"trees": [asdict(r) for r in records],
"external_trees": [asdict(r) for r in external],
"branches": [asdict(b) for b in branch_records],
+ "archives": [asdict(a) for a in archives],
}, indent=2))
return 0
+ _print_archives(archives)
if not records and not external:
print("No worktrees under .worktrees/ — nothing to reclaim.")
return 0
@@ -54,15 +58,70 @@ def _list(worktree_gc, repo_root: str, args) -> int:
return 0
+def _print_archives(archives) -> None:
+ if not archives:
+ return
+ import time
+ print(f"{len(archives)} archived worktree(s) (restore with `hermes worktree restore <name>`):")
+ for a in archives:
+ age = (time.time() - a.created) / 86400 if a.created else 0
+ skipped = len(a.meta.get("skipped_untracked") or [])
+ extra = f", {skipped} large untracked file(s) not captured" if skipped else ""
+ print(f" {a.name:40} {age:5.1f}d {a.meta.get('branch') or 'detached'} "
+ f"({a.meta.get('reason') or '?'}{extra})")
+ print()
+
+
+def _sweep_lines(plan) -> list[str]:
+ lines = [f"{'TREE':40} {'IDLE':>7} {'DECISION':20} REASON"]
+ for d in sorted(plan, key=lambda x: (x.action, x.name)):
+ lines.append(f"{d.name[:40]:40} {d.age_hours:>6.1f}h {d.action:20} {d.reason}")
+ counts: dict = {}
+ for d in plan:
+ counts[d.action] = counts.get(d.action, 0) + 1
+ lines.append("Sweep totals: " + (", ".join(f"{k}={v}" for k, v in sorted(counts.items())) or "nothing to do"))
+ 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)."""
+ from hermes_cli import worktree_sweep
+ settings = worktree_sweep.sweep_settings()
+ plan = worktree_sweep.plan_sweep(repo_root, settings=settings)
+ if dry_run or worktree_sweep.classic_mode(settings):
+ return plan, []
+ _, _, archived = worktree_sweep.execute_plan(repo_root, plan, settings)
+ from hermes_cli.worktree_archive import prune_expired_archives
+ expired = 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]
+
+
+def _attended_records(records, plan) -> list:
+ """The attended reclaim's records minus trees the sweep already decided (archived, removed,
+ kanban) and minus any tree a live process works in: those are never touched here either."""
+ from hermes_cli.worktree_sweep import classic_mode, live_process_pids, sweep_settings
+ if classic_mode(sweep_settings()):
+ return records
+ owned = {d.path for d in plan if d.action != "skip-young"}
+ records = [r for r in records if r.path not in owned]
+ live = live_process_pids([r.path for r in records])
+ return [r for r in records if not live.get(r.path)]
+
+
def _prune(worktree_gc, repo_root: str, args) -> int:
dry_run = bool(getattr(args, "dry_run", False))
as_json = bool(getattr(args, "json", False))
older_than = getattr(args, "older_than", None)
actions: list = []
kept: list = []
+ plan: list = []
if not getattr(args, "branches_only", False):
+ plan, actions = _sweep(repo_root, dry_run)
+ if not as_json:
+ print("\n".join(_sweep_lines(plan)) + "\n")
actions += worktree_gc.prune_missing_registrations(repo_root, dry_run=dry_run)
- tree_records = worktree_gc.audit_worktrees(repo_root, with_sizes=False, older_than_days=older_than)
+ tree_records = _attended_records(
+ worktree_gc.audit_worktrees(repo_root, with_sizes=False, older_than_days=older_than), plan)
actions += worktree_gc.reclaim_worktrees(repo_root, dry_run=dry_run, records=tree_records)
kept = [r for r in tree_records if r.verdict == "keep"
and "kanban" not in r.reason and "in use" not in r.reason]
@@ -79,9 +138,11 @@ def _prune(worktree_gc, repo_root: str, args) -> int:
"dry_run": dry_run,
"actions": actions,
"preserved": [asdict(r) for r in kept],
+ "sweep": [d.as_dict() for d in plan],
}, indent=2))
return 0
if actions:
+ print("Attended reclaim (`hermes worktree prune` only; the automatic sweep is the table above):")
for line in actions:
print(f" {line}")
print(f"{len(actions)} action(s) {'planned' if dry_run else 'done'}.")
@@ -90,7 +151,29 @@ def _prune(worktree_gc, repo_root: str, args) -> int:
return 0
-_ACTIONS = {"list": _list, "prune": _prune}
+def _restore(_worktree_gc, repo_root: str, args) -> int:
+ from hermes_cli.worktree_archive import ArchiveError, restore_archive
+ name = getattr(args, "name", None)
+ if not name:
+ print("Usage: hermes worktree restore <name> [--path DIR]")
+ return 1
+ try:
+ result = restore_archive(repo_root, name, getattr(args, "path", None))
+ except ArchiveError as exc:
+ print(f"✗ {exc}")
+ return 1
+ print(f"✓ Restored {result['ref']} → {result['path']}")
+ if result["detached"]:
+ print(f" Detached at {result['head'][:12]} (branch {result['branch'] or '-'} moved or is checked out "
+ "elsewhere); create a branch with `git switch -c <name>`.")
+ else:
+ print(f" Branch: {result['branch']}")
+ for item in result["skipped_untracked"]:
+ print(f" Not captured (over the size cap): {item['path']} ({item['bytes'] // (1024 * 1024)} MB)")
+ return 0
+
+
+_ACTIONS = {"list": _list, "prune": _prune, "restore": _restore}
def cmd_worktree(args) -> int:
diff --git a/hermes_cli/worktree_exit.py b/hermes_cli/worktree_exit.py
new file mode 100644
index 00000000000..1f1506e9509
--- /dev/null
+++ b/hermes_cli/worktree_exit.py
@@ -0,0 +1,114 @@
+"""The keep / archive / discard question when an interactive ``hermes -w`` session exits with a
+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
+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).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import sys
+from typing import Optional
+
+from agent.i18n import t
+
+logger = logging.getLogger(__name__)
+
+KEEP, ARCHIVE, DISCARD = "keep", "archive", "discard"
+
+
+def _has_tty() -> bool:
+ try:
+ return sys.stdin.isatty() and sys.stdout.isatty()
+ except (AttributeError, ValueError):
+ return False
+
+
+def worktree_state(info: dict) -> Optional[str]:
+ """``"dirty"``, ``"unpushed"`` or None (clean and pushed / gone)."""
+ from hermes_cli.worktree_ops import _worktree_has_unpushed_commits, _worktree_is_dirty
+ path, repo_root = info.get("path", ""), info.get("repo_root", "")
+ if not path or not os.path.isdir(path):
+ return None
+ if _worktree_is_dirty(path, repo_root, timeout=10):
+ return "dirty"
+ if _worktree_has_unpushed_commits(path, timeout=10):
+ return "unpushed"
+ return None
+
+
+def _still_in_use(path: str, grace_s: float = 5.0) -> bool:
+ """Whether a live process (other than this one) still works in *path* after a short grace:
+ the TUI's own backend (``tui_gateway``) takes a moment to exit after the Ink UI closes."""
+ import time
+
+ from hermes_cli.worktree_sweep import live_process_pids
+ deadline = time.monotonic() + grace_s
+ while live_process_pids([path], exclude=(os.getpid(),)).get(path):
+ if time.monotonic() >= deadline:
+ return True
+ time.sleep(0.25)
+ return False
+
+
+def ask_exit_choice(info: Optional[dict]) -> str:
+ """Ask what to do with a dirty/unpushed tree; records the answer in ``info["exit_choice"]``."""
+ if not info or not _has_tty():
+ return KEEP
+ state = worktree_state(info)
+ if state is None:
+ return KEEP
+ if _still_in_use(info["path"]):
+ return KEEP # something still runs in there; never offer to delete it
+ from hermes_cli.curses_ui import curses_radiolist
+ title = t(f"cli.worktree.exit_question_{state}", path=info["path"])
+ items = [t("cli.worktree.exit_choice_keep"), t("cli.worktree.exit_choice_archive"),
+ t("cli.worktree.exit_choice_discard")]
+ try: # Esc / Ctrl-C / a curses failure all resolve to Keep (index 0)
+ idx = curses_radiolist(title, items, selected=0, cancel_returns=0)
+ except Exception:
+ logger.debug("worktree exit question failed; keeping the tree", exc_info=True)
+ idx = None
+ choice = {1: ARCHIVE, 2: DISCARD}.get(idx, KEEP) if isinstance(idx, int) else KEEP
+ info["exit_choice"] = choice
+ return choice
+
+
+def apply_exit_choice(info: dict, echo) -> bool:
+ """Carry out an Archive/Discard answer -> 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")
+ if choice not in (ARCHIVE, DISCARD):
+ return False
+ path, repo_root, branch = info["path"], info["repo_root"], info.get("branch")
+ if choice == ARCHIVE:
+ from hermes_cli.worktree_archive import ArchiveError
+ from hermes_cli.worktree_sweep import archive_then_remove, sweep_settings
+ try:
+ ref, _kept, removed = archive_then_remove(
+ repo_root, path, reason="session exit", unlock=True,
+ 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")
+ return True
+ name = ref.rsplit("/", 1)[-1]
+ echo(f"\033[32m{t('cli.worktree.archived', 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 True
+ from hermes_cli._subprocess_compat import noninteractive_git_env
+ from hermes_cli.worktree_ops import _git_quiet, release_lsp_clients
+ release_lsp_clients(path)
+ _git_quiet(["worktree", "unlock", path], repo_root, log="git worktree unlock failed (non-fatal)")
+ _git_quiet(["worktree", "remove", path, "--force"], repo_root, timeout=60, log="Failed to remove worktree")
+ if branch and not os.path.isdir(path):
+ _git_quiet(["branch", "-D", branch], repo_root, log=f"Failed to delete branch {branch}",
+ env=noninteractive_git_env())
+ echo(f"\033[33m{t('cli.worktree.discarded', path=path)}\033[0m")
+ return True
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index 70aa0047525..402f0ee1e8e 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -466,6 +466,8 @@ def _setup_worktree(repo_root: str | None = None, sync_base: bool = True,
except Exception as e:
logger.debug("git worktree lock failed (non-fatal): %s", e)
+ from hermes_cli.worktree_registry import record_worktree_repo
+ record_worktree_repo(repo_root)
_cprint(f"\033[32m✓ Worktree created:\033[0m {wt_path}")
print(f" Branch: {branch_name}")
print(f" Base: {base_label}")
@@ -1044,12 +1046,14 @@ def _reap_prune_verdicts(repo_root: str, verdicts: list, stale_work_cutoff: floa
def _prune_stale_worktrees(repo_root: str, max_age_hours: int = 24) -> None:
"""Remove stale worktrees and orphaned branches on startup.
- Guards at every tier and age: dirty trees are never removed; unpushed commits are never
- removed UNLESS patch-equivalent to upstream, the PR is MERGED on GitHub, or the head EXACTLY
- matches origin (tree reaped, branch kept). Live-locked trees are skipped; dead locks are
- unlocked first. Trees preserved >7 days are listed in one WARNING so work can't rot silently.
- Phases: ``_prune_candidates`` -> ``_classify_prune_candidates`` -> ``_reap_prune_verdicts``
- -> ``_prune_orphaned_branches``.
+ Default (``worktrees.archive_dirty: true``): ``worktree_sweep.run_sweep`` — an idle dirty or
+ unpushed tree past its tier is archived to ``refs/hermes/archive/<tree>`` and then removed;
+ live trees (lock owner or any process inside) and Kanban trees are never touched.
+ ``archive_dirty: false`` (no size budget) runs the classic pass below: dirty trees are never
+ removed; unpushed commits are never removed UNLESS patch-equivalent to upstream, the PR is
+ MERGED on GitHub, or the head EXACTLY matches origin (tree reaped, branch kept). Live-locked
+ trees are skipped; dead locks are unlocked first. Phases: ``_prune_candidates`` ->
+ ``_classify_prune_candidates`` -> ``_reap_prune_verdicts`` -> ``_prune_orphaned_branches``.
"""
try:
_prune_stale_worktree_trees(repo_root, max_age_hours)
@@ -1083,6 +1087,13 @@ def _prune_stale_worktree_trees(repo_root: str, max_age_hours: int) -> None:
if _repo_is_shallow(repo_root):
_deepen_shallow_repo(repo_root)
+ from hermes_cli import worktree_sweep
+ settings = worktree_sweep.sweep_settings()
+ if not worktree_sweep.classic_mode(settings):
+ worktree_sweep.run_sweep(repo_root, max_age_hours, settings)
+ _warn_worktree_footprint(repo_root)
+ return
+
now = time.time()
candidates = _prune_candidates(worktrees_dir, max_age_hours, now)
if not candidates:
@@ -1098,8 +1109,11 @@ def _prune_stale_worktree_trees(repo_root: str, max_age_hours: int) -> None:
len(preserved_stale), ", ".join(sorted(preserved_stale)))
_prune_orphaned_branches(repo_root, protect=kept_branches)
+ _warn_worktree_footprint(repo_root)
+
- # The conservative startup pass accumulates trees it can never reclaim; say so once per launch.
+def _warn_worktree_footprint(repo_root: str) -> None:
+ """The startup pass can leave trees it may not reclaim; say so once per launch."""
try:
from hermes_cli.worktree_gc import worktrees_summary
diff --git a/hermes_cli/worktree_registry.py b/hermes_cli/worktree_registry.py
new file mode 100644
index 00000000000..8f3ed594caa
--- /dev/null
+++ b/hermes_cli/worktree_registry.py
@@ -0,0 +1,70 @@
+"""Per-profile registry of every repository Hermes has created a worktree in.
+
+The 6-hourly cron sweep (``cron.scheduler._worktree_maintenance_repos``) only knew the Hermes
+checkout and cron job workdirs, so trees made by ``hermes -w`` / ``/worktree new`` / subagent
+isolation / the Desktop git pane in any other repo were never swept. Each creation path records
+its repo here; the sweep unions this list with its other sources.
+
+The file lives under the ACTIVE profile's home (``get_hermes_home()``), so one profile's sweep
+never visits another profile's repos. Writes are atomic under a cross-process lock; entries whose
+repo no longer exists are dropped on every read-modify-write and filtered on read.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import threading
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+_REGISTRY_NAME = "worktree_repos.json"
+_holder = threading.local()
+
+
+def registry_path() -> Path:
+ from hermes_constants import get_hermes_home
+ return get_hermes_home() / _REGISTRY_NAME
+
+
+def _repo_exists(repo: str) -> bool:
+ return (Path(repo) / ".git").exists()
+
+
+def _read(path: Path) -> list[str]:
+ from utils import read_json_or_empty
+ repos = read_json_or_empty(path).get("repos")
+ return [r for r in repos if isinstance(r, str) and r] if isinstance(repos, list) else []
+
+
+def registered_repos() -> list[str]:
+ """Registered repo roots that still exist (read-only; never creates the file)."""
+ try:
+ return [r for r in _read(registry_path()) if _repo_exists(r)]
+ except Exception:
+ logger.debug("worktree registry read failed", exc_info=True)
+ return []
+
+
+def record_worktree_repo(repo_root) -> None:
+ """Remember *repo_root* as a repo with Hermes-made worktrees. Never raises."""
+ if not repo_root:
+ return
+ try:
+ from hermes_cli.auth import _file_lock
+ from utils import atomic_json_write
+
+ repo = os.path.realpath(str(repo_root))
+ path = registry_path()
+ with _file_lock(path.with_name(path.name + ".lock"), _holder, 5.0,
+ "Timed out waiting for the worktree registry lock"):
+ current = _read(path)
+ kept = [r for r in dict.fromkeys(current) if _repo_exists(r)]
+ if repo in kept and kept == current:
+ return
+ if repo not in kept:
+ kept.append(repo)
+ atomic_json_write(path, {"version": 1, "repos": kept})
+ except Exception:
+ logger.debug("worktree registry update failed for %s", repo_root, exc_info=True)
diff --git a/hermes_cli/worktree_sweep.py b/hermes_cli/worktree_sweep.py
new file mode 100644
index 00000000000..466f032eace
--- /dev/null
+++ b/hermes_cli/worktree_sweep.py
@@ -0,0 +1,381 @@
+"""Snapshot-then-delete sweep for stale worktrees (``worktrees.archive_dirty``, default on).
+
+The classic pruner (``worktree_ops._prune_stale_worktree_trees``) never removes a dirty or
+unpushed tree at any age, so leftovers of finished lanes pile up forever. This sweep keeps its
+tiers and classifier, then removes an idle dirty/unpushed tree only after archiving its full
+working state to ``refs/hermes/archive/<tree>`` (``worktree_archive``); a failed archive keeps
+the 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
+classic pruner runs unchanged.
+
+``plan_sweep`` is read-only (``hermes worktree prune --dry-run`` prints it); ``execute_plan``
+applies a frozen plan.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import subprocess
+import sys
+import time
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from typing import Optional
+
+logger = logging.getLogger("cli")
+
+_DEFAULTS = {"archive_dirty": True, "archive_max_file_mb": 50, "archive_retention_days": 30, "max_total_gb": 0}
+_PROTECTED_BRANCHES = {"main", "master", "develop", "dev", "trunk"}
+_ARCHIVE_REASONS = {"dirty": "uncommitted changes", "unpushed": "unpushed commits"}
+
+
+@dataclass
+class Decision:
+ name: str
+ path: str
+ action: str # remove | remove-keep-branch | archive-remove | skip-* | keep-*
+ reason: str
+ age_hours: float
+ branch: Optional[str] = None
+ mtime: float = 0.0
+ force: bool = False
+ verdict: str = ""
+ lock_state: Optional[str] = None
+ size_mb: Optional[int] = None
+
+ def as_dict(self) -> dict:
+ return asdict(self)
+
+
+def sweep_settings() -> dict:
+ """``worktrees.*`` from the active profile's config (defaults on any read failure)."""
+ settings = dict(_DEFAULTS)
+ try:
+ from hermes_cli.config import load_config_readonly
+ section = load_config_readonly().get("worktrees") or {}
+ if isinstance(section, dict):
+ settings.update({k: section[k] for k in _DEFAULTS if section.get(k) is not None})
+ except Exception:
+ logger.debug("worktrees config unreadable; using defaults", exc_info=True)
+ settings["archive_dirty"] = bool(settings["archive_dirty"])
+ for key in ("archive_max_file_mb", "archive_retention_days", "max_total_gb"):
+ try:
+ settings[key] = max(0.0, float(settings[key]))
+ except (TypeError, ValueError):
+ settings[key] = float(_DEFAULTS[key])
+ return settings
+
+
+def classic_mode(settings: dict) -> bool:
+ """True when the sweep must behave exactly like the pre-archive pruner."""
+ return not settings["archive_dirty"] and not settings["max_total_gb"]
+
+
+# ---------------------------------------------------------------- live-work detection
+
+
+def _inside(target: str, roots: list[str]) -> Optional[str]:
+ for root in roots:
+ if target == root or target.startswith(root + os.sep):
+ return root
+ return None
+
+
+def _proc_links(pid_dir: Path):
+ yield pid_dir / "cwd"
+ try:
+ yield from (pid_dir / "fd").iterdir()
+ except OSError:
+ return
+
+
+def _linux_live_pids(roots: list[str], exclude: frozenset) -> dict[str, list[int]]:
+ hits: dict[str, list[int]] = {}
+ for pid_dir in Path("/proc").iterdir():
+ if not pid_dir.name.isdigit() or int(pid_dir.name) in exclude:
+ continue
+ for link in _proc_links(pid_dir):
+ try:
+ target = os.readlink(link)
+ except OSError:
+ continue
+ root = _inside(target.removesuffix(" (deleted)"), roots)
+ if root is not None:
+ hits.setdefault(root, []).append(int(pid_dir.name))
+ break
+ return hits
+
+
+def _psutil_live_pids(roots: list[str], exclude: frozenset) -> dict[str, list[int]]:
+ hits: dict[str, list[int]] = {}
+ try:
+ import psutil
+ except ImportError:
+ return hits
+ for proc in psutil.process_iter(["pid"]):
+ try:
+ if proc.pid in exclude:
+ continue
+ root = _inside(os.path.realpath(proc.cwd()), roots)
+ except (psutil.Error, OSError):
+ continue
+ if root is not None:
+ hits.setdefault(root, []).append(proc.pid)
+ return hits
+
+
+def live_process_pids(paths, exclude=()) -> dict[str, list[int]]:
+ """``{path: [pid, ...]}`` for every *path* some live process works in: cwd or an open fd on
+ Linux (``/proc``), cwd elsewhere (psutil, best-effort). Keys are the paths as given;
+ *exclude* pids are ignored (an exiting session's own process)."""
+ real = {os.path.realpath(str(p)): str(p) for p in paths}
+ if not real:
+ return {}
+ roots = sorted(real, key=len, reverse=True)
+ try:
+ skip = frozenset(int(p) for p in exclude)
+ hits = (_linux_live_pids(roots, skip) if sys.platform.startswith("linux")
+ else _psutil_live_pids(roots, skip))
+ except OSError:
+ hits = {}
+ return {real[root]: pids for root, pids in hits.items()}
+
+
+def _last_activity(path: str) -> float:
+ """Newest mtime among the tree's ref/reflog files and every changed or untracked file.
+
+ 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.
+ """
+ from hermes_cli._subprocess_compat import noninteractive_repo_git_env
+ newest = 0.0
+ wt = Path(path)
+ env = noninteractive_repo_git_env(path)
+ if env is None:
+ return time.time() # unverifiable: treat as active
+ 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()
+ 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)
+ except (OSError, subprocess.SubprocessError):
+ return time.time()
+ 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:
+ try:
+ newest = max(newest, candidate.lstat().st_mtime)
+ except OSError:
+ continue
+ return newest
+
+
+# ---------------------------------------------------------------- planning
+
+
+def _tier_hours(name: str, max_age_hours: float) -> float:
+ return max_age_hours if name.startswith("hermes-") else max_age_hours * 3
+
+
+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."""
+ 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
+ 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
+ if not settings["archive_dirty"]:
+ return f"keep-{verdict}", what, lock_state # 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
+
+
+def _apply_budget(decisions: list[Decision], max_total_gb: float) -> None:
+ """Evict the oldest idle kept trees (archive first) until they fit *max_total_gb*.
+
+ Only idle past-tier trees count or move; live, young and kanban trees are invisible here.
+ """
+ from hermes_cli.worktree_archive import archive_preflight
+ from hermes_cli.worktree_gc import _tree_size_mb
+ eligible = [d for d in decisions if d.action in ("keep-dirty", "keep-unpushed")]
+ for d in eligible:
+ d.size_mb = _tree_size_mb(Path(d.path), timeout=120) or 0
+ total = sum(d.size_mb or 0 for d in eligible)
+ budget_mb = max_total_gb * 1024
+ for d in sorted(eligible, key=lambda x: x.mtime):
+ if total <= budget_mb:
+ break
+ unsafe = archive_preflight(d.path)
+ if unsafe:
+ d.action, d.reason = "keep-unarchivable", unsafe
+ continue
+ d.action, d.reason = "archive-remove", f"{d.reason}; over worktrees.max_total_gb={max_total_gb:g}"
+ total -= d.size_mb or 0
+
+
+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)."""
+ import re
+
+ from hermes_cli import worktree_ops as ops
+ settings = settings or sweep_settings()
+ now = now or time.time()
+ worktrees_dir = Path(repo_root) / ".worktrees"
+ if not worktrees_dir.is_dir():
+ return []
+ candidates = ops._prune_candidates(worktrees_dir, max_age_hours, now)
+ doomed_names = {entry.name for entry, _m, _f in candidates}
+ decisions: list[Decision] = []
+ for entry in sorted(worktrees_dir.iterdir()):
+ if not entry.is_dir() or entry.name in doomed_names:
+ continue
+ try:
+ age = (now - entry.stat().st_mtime) / 3600
+ except OSError:
+ continue
+ kanban = re.match(r"^t_[0-9a-f]+$", entry.name)
+ decisions.append(Decision(entry.name, str(entry), "skip-kanban" if kanban else "skip-young",
+ "owned by kanban gc" if kanban else "younger than its age tier", round(age, 1)))
+ verdicts = ops._classify_prune_candidates(repo_root, candidates) if candidates else []
+ # 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:
+ d = Decision(entry.name, str(entry), "", "", round((now - mtime) / 3600, 1), mtime=mtime, force=force,
+ verdict=verdict, lock_state=lock_state)
+ 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":
+ d.action, d.reason = "skip-live-lock", "lock owner still running"
+ 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)
+ 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"])
+ return decisions
+
+
+# ---------------------------------------------------------------- execution
+
+
+def _branch_published(repo_root: str, branch: str, remote_heads: Optional[dict]) -> bool:
+ """Whether *branch* exists on a remote. Unknown (``ls-remote`` failed) counts as published:
+ deleting a branch is never needed for safety, so doubt keeps it."""
+ from hermes_cli.worktree_ops import _git_out
+ try:
+ if _git_out(["remote"], repo_root) == "":
+ return False # no remote at all: nothing could have been published
+ if remote_heads is None or branch in remote_heads:
+ return True
+ refs = _git_out(["for-each-ref", "--format=%(refname)", f"refs/remotes/*/{branch}"], repo_root)
+ except (OSError, subprocess.SubprocessError):
+ return True # unknown: keep the branch
+ return refs is None or bool(refs.strip())
+
+
+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,
+ ) -> 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.
+ """
+ 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
+ arc = snapshot_worktree(repo_root, path, reason=reason, max_untracked_mb=max_untracked_mb)
+ release_lsp_clients(path)
+ if unlock:
+ _git_quiet(["worktree", "unlock", path], repo_root, log=f"unlock {path}")
+ removed = _git(["worktree", "remove", "--force", path], repo_root, timeout=60)
+ if removed.returncode != 0:
+ logger.warning("Archived %s to %s but could not remove it: %s", path, arc.ref, removed.stderr.strip())
+ return arc.ref, None, False
+ branch = arc.meta.get("branch")
+ if not branch or keep_branch or branch in _PROTECTED_BRANCHES:
+ return arc.ref, branch, True
+ if remote_heads_fn is None:
+ from hermes_cli.worktree_ops import _fetch_remote_branch_heads
+ heads = _fetch_remote_branch_heads(repo_root, timeout=10)
+ else:
+ heads = remote_heads_fn()
+ if _branch_published(repo_root, branch, heads):
+ return arc.ref, branch, True
+ _git(["branch", "-D", branch], repo_root, stdin=subprocess.DEVNULL, env=noninteractive_git_env())
+ return arc.ref, None, True
+
+
+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)``."""
+ 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():
+ if "heads" not in memo:
+ 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)
+ 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):
+ 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)
+ 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)
+ if kept:
+ kept_branches.add(kept)
+ return preserved, kept_branches, archived
+
+
+def run_sweep(repo_root: str, max_age_hours: int, settings: dict) -> None:
+ """Plan + execute + archive retention for one repo (the archive-mode pruner)."""
+ from hermes_cli import worktree_ops as ops
+ from hermes_cli.worktree_archive import prune_expired_archives
+ plan = plan_sweep(repo_root, max_age_hours, settings)
+ preserved, kept_branches, archived = execute_plan(repo_root, plan, settings)
+ if archived:
+ 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))
+ if preserved:
+ logger.warning("Preserving %d stale worktree(s) (run `hermes worktree prune --dry-run` for reasons): %s",
+ len(preserved), ", ".join(sorted(preserved)[:20]))
+ expired = prune_expired_archives(repo_root, settings["archive_retention_days"])
+ if expired:
+ logger.info("Deleted %d worktree archive(s) older than %g days", len(expired), settings["archive_retention_days"])
+ ops._prune_orphaned_branches(repo_root, protect=kept_branches)
diff --git a/locales/af.yaml b/locales/af.yaml
index d341d51cb08..d4ed7fff359 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ Werkboom het ongecommitte veranderinge, word behou: {path}"
clean_up_manually: "Om met die hand op te ruim: git worktree remove --force {path}"
cleaned_up: "✓ Werkboom opgeruim: {path}"
+ exit_question_dirty: "Hierdie werkboom het ongecommitte veranderinge: {path}"
+ exit_question_unpushed: "Hierdie werkboom het commits wat nie gestoot is nie: {path}"
+ 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"
+ 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."
+ discarded: "Werkboom verwyder en sy veranderinge weggegooi: {path}"
display:
verb:
web_search: "Soek op die web"
@@ -3727,7 +3737,7 @@ tips:
t241: "Die gateway kas AIAgent-instansies per sessie — om hierdie kas te vernietig breek Anthropic se prompt-kasing."
t242: "Enige webwerf kan vaardighede via /.well-known/skills/index.json blootstel — die vaardigheidshub ontdek hulle outomaties."
t243: "Die vaardigheids-ouditlog by ~/.hermes/skills/.hub/audit.log hou elke installasie- en verwyderingsbewerking by."
- t244: "Verouderde git-worktrees word by opstart outomaties opgeruim: skoon, volledig saamgevoegde bome word gesnoei; vuil of ongepushte werk word altyd bewaar."
+ t244: "Verouderde git-werkbome word outomaties opgeruim: skoon, saamgevoegde bome word verwyder; ledige werkbome met ongecommitte of ongestootte werk word eers geargiveer en kan met hermes worktree restore herstel word."
t245: "Profiele skei Hermes-toestand via HERMES_HOME; gasheer-gereedskapsubprosesse behou jou werklike HOME tensy terminal.home_mode op profile gestel is."
t246: "Die HERMES_HOME_MODE-omgewingsveranderlike (oktaal, bv. 0701) stel eie gidstoestemmings vir webbediener-deurkruising."
t247: "Houermodus: plaas .container-mode in HERMES_HOME en die gasheer-CLI voer outomaties binne die houer uit."
diff --git a/locales/ar.yaml b/locales/ar.yaml
index a039eb9f82a..e67ce4650b1 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ يحتوي worktree على تغييرات غير مودعة، سيُحتفظ به: {path}"
clean_up_manually: "للتنظيف يدويًا: git worktree remove --force {path}"
cleaned_up: "✓ تم تنظيف worktree: {path}"
+ exit_question_dirty: "يحتوي هذا الـ worktree على تغييرات غير مودعة: {path}"
+ exit_question_unpushed: "يحتوي هذا الـ worktree على إيداعات غير مدفوعة: {path}"
+ exit_choice_keep: "الاحتفاظ بالـ worktree (افتراضي)"
+ exit_choice_archive: "أرشفته وإزالته (قابل للاستعادة)"
+ exit_choice_discard: "إزالته وتجاهل التغييرات"
+ archived: "✓ تمت أرشفة الـ worktree في {ref} وإزالته: {path}"
+ restore_hint: "لاستعادته: hermes worktree restore {name}"
+ archive_failed: "✗ تعذّرت أرشفة {path}، سيُحتفظ به: {error}"
+ archive_not_removed: "تم حفظ الأرشيف، لكن تعذّرت إزالة {path}؛ أزله يدويًا."
+ discarded: "تمت إزالة الـ worktree وتجاهل تغييراته: {path}"
display:
verb:
web_search: "يبحث في الويب"
@@ -3727,7 +3737,7 @@ tips:
t241: "تخزّن البوّابة مثيلات AIAgent مؤقتًا لكل جلسة — وتدمير هذه الذاكرة المؤقتة يعطّل تخزين مطالبات Anthropic المؤقت."
t242: "يمكن لأي موقع ويب عرض مهارات عبر /.well-known/skills/index.json — ويكتشفها مركز المهارات تلقائيًا."
t243: "يتتبّع سجل تدقيق المهارات في ~/.hermes/skills/.hub/audit.log كل عملية تثبيت وإزالة."
- t244: "تُنظَّف worktrees القديمة في git تلقائيًا عند البدء: تُحذف الأشجار النظيفة المدمجة بالكامل؛ ويُحفظ دائمًا أي عمل غير مكتمل أو غير مدفوع."
+ t244: "تُنظَّف worktrees القديمة في git تلقائيًا: تُحذف الأشجار النظيفة المدمجة؛ أما الأشجار الخاملة التي تحتوي على تغييرات غير مودعة أو غير مدفوعة فتُؤرشف أولًا ويمكن استعادتها باستخدام hermes worktree restore."
t245: "تحدّد الملفات التعريفية نطاق حالة Hermes عبر HERMES_HOME؛ وتحتفظ عمليات الأدوات الفرعية على المضيف بـ HOME الحقيقي ما لم يكن terminal.home_mode هو profile."
t246: "يضبط متغير البيئة HERMES_HOME_MODE (ثماني، مثل 0701) صلاحيات مخصصة للمجلد لتمكين خادم الويب من عبوره."
t247: "وضع الحاوية: ضع .container-mode في HERMES_HOME وسينفّذ سطر أوامر المضيف نفسه تلقائيًا داخل الحاوية."
diff --git a/locales/de.yaml b/locales/de.yaml
index 6bebe47ccd8..cdf05adab4d 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ Worktree hat nicht committete Änderungen, wird behalten: {path}"
clean_up_manually: "Manuell aufräumen mit: git worktree remove --force {path}"
cleaned_up: "✓ Worktree aufgeräumt: {path}"
+ exit_question_dirty: "Dieser Worktree hat nicht committete Änderungen: {path}"
+ exit_question_unpushed: "Dieser Worktree hat nicht gepushte Commits: {path}"
+ exit_choice_keep: "Worktree behalten (Standard)"
+ exit_choice_archive: "Archivieren und entfernen (wiederherstellbar)"
+ exit_choice_discard: "Entfernen und Änderungen verwerfen"
+ 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."
+ discarded: "Worktree entfernt und Änderungen verworfen: {path}"
display:
verb:
web_search: "Suche im Web"
@@ -3727,7 +3737,7 @@ tips:
t241: "Das Gateway hält AIAgent-Instanzen pro Sitzung im Cache — wird dieser Cache zerstört, funktioniert das Prompt-Caching von Anthropic nicht mehr."
t242: "Jede Website kann Skills über /.well-known/skills/index.json bereitstellen — der Skills-Hub entdeckt sie automatisch."
t243: "Das Skills-Audit-Log unter ~/.hermes/skills/.hub/audit.log protokolliert jede Installation und Entfernung."
- t244: "Veraltete Git-Worktrees werden beim Start automatisch bereinigt: saubere, vollständig gemergte Trees werden entfernt; ungespeicherte oder nicht gepushte Arbeit bleibt immer erhalten."
+ t244: "Veraltete Git-Worktrees werden automatisch bereinigt: saubere, gemergte Trees werden entfernt; inaktive Trees mit nicht committeten oder nicht gepushten Änderungen werden vorher archiviert und lassen sich mit hermes worktree restore wiederherstellen."
t245: "Profile begrenzen den Hermes-Zustand über HERMES_HOME; Host-Tool-Unterprozesse behalten Ihr echtes HOME, sofern terminal.home_mode nicht auf profile steht."
t246: "Die Umgebungsvariable HERMES_HOME_MODE (oktal, z. B. 0701) setzt eigene Verzeichnisrechte für den Zugriff durch Webserver."
t247: "Container-Modus: Legen Sie .container-mode in HERMES_HOME ab, und die Host-CLI wechselt automatisch per exec in den Container."
diff --git a/locales/en.yaml b/locales/en.yaml
index 24933d5b0ef..f16d61564d8 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -3400,6 +3400,16 @@ cli:
uncommitted_keeping: "⚠ Worktree has uncommitted changes, keeping: {path}"
clean_up_manually: "To clean up manually: git worktree remove --force {path}"
cleaned_up: "✓ Worktree cleaned up: {path}"
+ exit_question_dirty: "This worktree has uncommitted changes: {path}"
+ exit_question_unpushed: "This worktree has commits that are not pushed: {path}"
+ exit_choice_keep: "Keep the worktree (default)"
+ exit_choice_archive: "Archive and remove it (restorable)"
+ exit_choice_discard: "Remove it and discard the changes"
+ 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."
+ discarded: "Worktree removed and its changes discarded: {path}"
display:
# Tool verbs, spinner/progress text, completion rows and failure suffixes (agent/display.py).
@@ -3841,7 +3851,7 @@ tips:
t241: "The gateway caches AIAgent instances per session — destroying this cache breaks Anthropic prompt caching."
t242: "Any website can expose skills via /.well-known/skills/index.json — the skills hub discovers them automatically."
t243: "The skills audit log at ~/.hermes/skills/.hub/audit.log tracks every install and removal operation."
- t244: "Stale git worktrees are auto-cleaned on startup: clean, fully-merged trees get pruned; dirty or unpushed work is always preserved."
+ t244: "Stale git worktrees are auto-cleaned: clean merged trees are removed; idle dirty or unpushed trees are archived first and restorable with hermes worktree restore."
t245: "Profiles scope Hermes state via HERMES_HOME; host tool subprocesses keep your real HOME unless terminal.home_mode is profile."
t246: "HERMES_HOME_MODE env var (octal, e.g. 0701) sets custom directory permissions for web server traversal."
t247: "Container mode: place .container-mode in HERMES_HOME and the host CLI auto-execs into the container."
diff --git a/locales/es.yaml b/locales/es.yaml
index 8ec065cc0dc..4fd6b3b29c8 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ El worktree tiene cambios sin commit, se conserva: {path}"
clean_up_manually: "Para limpiar manualmente: git worktree remove --force {path}"
cleaned_up: "✓ Worktree limpiado: {path}"
+ exit_question_dirty: "Este worktree tiene cambios sin commit: {path}"
+ exit_question_unpushed: "Este worktree tiene commits sin push: {path}"
+ exit_choice_keep: "Conservar el worktree (predeterminado)"
+ exit_choice_archive: "Archivarlo y eliminarlo (recuperable)"
+ exit_choice_discard: "Eliminarlo y descartar los cambios"
+ 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."
+ discarded: "Worktree eliminado y cambios descartados: {path}"
display:
verb:
web_search: "Buscando en la web"
@@ -3727,7 +3737,7 @@ tips:
t241: "El gateway cachea las instancias de AIAgent por sesión: destruir este caché rompe el caché de prompts de Anthropic."
t242: "Cualquier sitio web puede exponer skills vía /.well-known/skills/index.json: el hub de skills las descubre automáticamente."
t243: "El registro de auditoría de skills en ~/.hermes/skills/.hub/audit.log rastrea cada operación de instalación y eliminación."
- t244: "Los worktrees de git obsoletos se limpian automáticamente al iniciar: los árboles limpios y totalmente fusionados se eliminan; el trabajo sucio o sin push siempre se conserva."
+ t244: "Los worktrees de git obsoletos se limpian automáticamente: los árboles limpios y fusionados se eliminan; los inactivos con cambios sin commit o sin push se archivan primero y se pueden restaurar con hermes worktree restore."
t245: "Los perfiles delimitan el estado de Hermes mediante HERMES_HOME; los subprocesos de herramientas del host conservan tu HOME real salvo que terminal.home_mode sea profile."
t246: "La variable de entorno HERMES_HOME_MODE (octal, p. ej. 0701) fija permisos de directorio personalizados para el acceso del servidor web."
t247: "Modo contenedor: coloca .container-mode en HERMES_HOME y la CLI del host se ejecutará automáticamente dentro del contenedor."
diff --git a/locales/fr.yaml b/locales/fr.yaml
index 73dd83005ba..68b98ad2cff 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -3616,6 +3616,16 @@ cli:
uncommitted_keeping: "⚠ Le worktree a des modifications non commitées, conservé : {path}"
clean_up_manually: "Pour nettoyer manuellement : git worktree remove --force {path}"
cleaned_up: "✓ Worktree nettoyé : {path}"
+ exit_question_dirty: "Ce worktree contient des modifications non commitées : {path}"
+ exit_question_unpushed: "Ce worktree contient des commits non poussés : {path}"
+ 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"
+ 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."
+ discarded: "Worktree supprimé et modifications abandonnées : {path}"
display:
verb:
web_search: "Recherche sur le web"
@@ -4052,7 +4062,7 @@ tips:
t241: "Le gateway met en cache les instances AIAgent par session — détruire ce cache casse le cache de prompt Anthropic."
t242: "N'importe quel site web peut exposer des skills via /.well-known/skills/index.json — le hub de skills les découvre automatiquement."
t243: "Le journal d'audit des skills dans ~/.hermes/skills/.hub/audit.log trace chaque installation et suppression."
- t244: "Les worktrees git obsolètes sont nettoyés automatiquement au démarrage : les arbres propres et entièrement fusionnés sont supprimés ; le travail modifié ou non poussé est toujours préservé."
+ t244: "Les worktrees git obsolètes sont nettoyés automatiquement : les arbres propres et fusionnés sont supprimés ; les arbres inactifs avec des modifications non commitées ou non poussées sont d'abord archivés et restaurables avec hermes worktree restore."
t245: "Les profils délimitent l'état d'Hermes via HERMES_HOME ; les sous-processus d'outils sur l'hôte conservent votre vrai HOME sauf si terminal.home_mode vaut profile."
t246: "La variable d'environnement HERMES_HOME_MODE (octal, ex. 0701) définit des permissions de répertoire personnalisées pour la traversée par le serveur web."
t247: "Mode conteneur : placez .container-mode dans HERMES_HOME et la CLI hôte s'exécute automatiquement dans le conteneur."
diff --git a/locales/ga.yaml b/locales/ga.yaml
index 1e5291e5a7b..8641036b608 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ Tá athruithe gan tiomantas sa worktree, á choinneáil: {path}"
clean_up_manually: "Chun glanadh de láimh: git worktree remove --force {path}"
cleaned_up: "✓ Worktree glanta: {path}"
+ exit_question_dirty: "Tá athruithe gan tiomantas sa worktree seo: {path}"
+ exit_question_unpushed: "Tá tiomantais gan bhrú sa worktree seo: {path}"
+ 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"
+ 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 é."
+ discarded: "Worktree bainte agus a athruithe caite uait: {path}"
display:
verb:
web_search: "ag cuardach an ghréasáin"
@@ -3727,7 +3737,7 @@ tips:
t241: "Taisceann an gateway ásca AIAgent in aghaidh an tseisiúin — má scriostar an taisce seo, briseann sé taisceadh leideanna Anthropic."
t242: "Is féidir le suíomh gréasáin ar bith scileanna a nochtadh trí /.well-known/skills/index.json — aimsíonn mol na scileanna iad go huathoibríoch."
t243: "Rianaíonn loga iniúchta na scileanna ag ~/.hermes/skills/.hub/audit.log gach oibríocht suiteála agus baint."
- t244: "Glantar worktrees git seanchaite go huathoibríoch ag am tosaithe: bearrtar crainn ghlana atá cumaiscthe go hiomlán; caomhnaítear obair shalach nó neamhbhrúite i gcónaí."
+ t244: "Glantar worktrees git seanchaite go huathoibríoch: baintear crainn ghlana chumaiscthe; déantar crainn dhíomhaoine a bhfuil athruithe gan tiomantas nó gan bhrú iontu a chartlannú ar dtús, agus is féidir iad a athchóiriú le hermes worktree restore."
t245: "Scópálann próifílí staid Hermes trí HERMES_HOME; coinníonn fophróisis uirlisí an óstaigh do HOME fírinneach mura bhfuil terminal.home_mode socraithe go profile."
t246: "Socraíonn athróg timpeallachta HERMES_HOME_MODE (ochtnártha, m.sh. 0701) ceadanna eolaire saincheaptha le haghaidh trasnaithe freastalaí gréasáin."
t247: "Mód coimeádáin: cuir .container-mode in HERMES_HOME agus déanann CLI an óstaigh uath-exec isteach sa choimeádán."
diff --git a/locales/hu.yaml b/locales/hu.yaml
index 112e9fefcc6..da1268684e1 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -3316,6 +3316,16 @@ cli:
uncommitted_keeping: "⚠ A worktree-ben nem commitolt változások vannak, megtartva: {path}"
clean_up_manually: "Kézi takarításhoz: git worktree remove --force {path}"
cleaned_up: "✓ Worktree eltakarítva: {path}"
+ exit_question_dirty: "Ebben a worktree-ben nem commitolt változások vannak: {path}"
+ exit_question_unpushed: "Ebben a worktree-ben feltöltetlen commitok vannak: {path}"
+ 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"
+ 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."
+ discarded: "Worktree eltávolítva, változásai elvetve: {path}"
display:
verb:
web_search: "Keresés a weben"
@@ -3744,7 +3754,7 @@ tips:
t241: "Az átjáró munkamenetenként gyorsítótárazza az AIAgent példányokat – e cache törlése elrontja az Anthropic prompt-gyorsítótárazást."
t242: "Bármely weboldal közzétehet skilleket a /.well-known/skills/index.json címen – a skill hub automatikusan felfedezi őket."
t243: "A skill auditnapló a ~/.hermes/skills/.hub/audit.log fájlban minden telepítést és eltávolítást rögzít."
- t244: "Az elavult git worktree-k indításkor automatikusan törlődnek: a tiszta, teljesen beolvasztott fák kikerülnek; a piszkos vagy fel nem töltött munka mindig megmarad."
+ t244: "Az elavult git worktree-k automatikusan törlődnek: a tiszta, beolvasztott fák kikerülnek; a tétlen, nem commitolt vagy fel nem töltött munkát tartalmazó fák előbb archiválódnak, és a hermes worktree restore paranccsal visszaállíthatók."
t245: "A profilok a HERMES_HOME útján határolják a Hermes állapotát; a gazdagép eszközfolyamatai megtartják a valódi HOME-ot, hacsak a terminal.home_mode nem profile."
t246: "A HERMES_HOME_MODE környezeti változó (oktális, pl. 0701) egyedi mappajogosultságot állít be a webszerver bejárásához."
t247: "Konténer mód: helyezz egy .container-mode fájlt a HERMES_HOME-ba, és a gazda CLI automatikusan a konténerbe lép át."
diff --git a/locales/it.yaml b/locales/it.yaml
index 599d1806933..3a36eb0e838 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ Il worktree ha modifiche non committate, mantengo: {path}"
clean_up_manually: "Per pulire manualmente: git worktree remove --force {path}"
cleaned_up: "✓ Worktree pulito: {path}"
+ exit_question_dirty: "Questo worktree ha modifiche non committate: {path}"
+ exit_question_unpushed: "Questo worktree ha commit non inviati: {path}"
+ exit_choice_keep: "Mantieni il worktree (predefinito)"
+ exit_choice_archive: "Archivialo e rimuovilo (ripristinabile)"
+ exit_choice_discard: "Rimuovilo e scarta le modifiche"
+ 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."
+ discarded: "Worktree rimosso e modifiche scartate: {path}"
display:
verb:
web_search: "Ricerca sul web"
@@ -3727,7 +3737,7 @@ tips:
t241: "Il gateway mette in cache le istanze AIAgent per sessione — distruggere questa cache rompe il prompt caching di Anthropic."
t242: "Qualsiasi sito web può esporre skill tramite /.well-known/skills/index.json — l'hub delle skill le scopre automaticamente."
t243: "Il log di audit delle skill in ~/.hermes/skills/.hub/audit.log traccia ogni operazione di installazione e rimozione."
- t244: "I worktree git obsoleti vengono puliti automaticamente all'avvio: gli alberi puliti e completamente uniti vengono rimossi; il lavoro non committato o non pushato viene sempre preservato."
+ t244: "I worktree git obsoleti vengono puliti automaticamente: gli alberi puliti e già uniti vengono rimossi; quelli inattivi con modifiche non committate o non inviate vengono prima archiviati e si possono ripristinare con hermes worktree restore."
t245: "I profili delimitano lo stato di Hermes tramite HERMES_HOME; i sottoprocessi degli strumenti host mantengono la tua HOME reale a meno che terminal.home_mode sia profile."
t246: "La variabile d'ambiente HERMES_HOME_MODE (ottale, es. 0701) imposta permessi di directory personalizzati per l'attraversamento da parte del server web."
t247: "Modalità container: metti .container-mode in HERMES_HOME e la CLI host passa automaticamente in esecuzione nel container."
diff --git a/locales/ja.yaml b/locales/ja.yaml
index 3842ae2e594..92428628b13 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ ワークツリーに未コミットの変更があるため保持します: {path}"
clean_up_manually: "手動でクリーンアップするには: git worktree remove --force {path}"
cleaned_up: "✓ ワークツリーをクリーンアップしました: {path}"
+ exit_question_dirty: "このワークツリーには未コミットの変更があります: {path}"
+ exit_question_unpushed: "このワークツリーには未プッシュのコミットがあります: {path}"
+ exit_choice_keep: "ワークツリーを保持する(デフォルト)"
+ exit_choice_archive: "アーカイブして削除する(復元可能)"
+ exit_choice_discard: "削除して変更を破棄する"
+ archived: "✓ ワークツリーを {ref} にアーカイブして削除しました: {path}"
+ restore_hint: "復元するには: hermes worktree restore {name}"
+ archive_failed: "✗ {path} をアーカイブできなかったため保持します: {error}"
+ archive_not_removed: "アーカイブは保存されましたが、{path} を削除できませんでした。手動で削除してください。"
+ discarded: "ワークツリーを削除し、変更を破棄しました: {path}"
display:
verb:
web_search: "ウェブを検索中"
@@ -3727,7 +3737,7 @@ tips:
t241: "ゲートウェイはセッションごとに AIAgent インスタンスをキャッシュします。このキャッシュを破棄すると Anthropic のプロンプトキャッシュが壊れます。"
t242: "どの Web サイトも /.well-known/skills/index.json でスキルを公開でき、スキルハブが自動的に検出します。"
t243: "~/.hermes/skills/.hub/audit.log のスキル監査ログには、すべてのインストールと削除の操作が記録されます。"
- t244: "古い git ワークツリーは起動時に自動整理されます。クリーンで完全にマージ済みのツリーは削除され、変更や未プッシュの作業があるものは必ず保持されます。"
+ t244: "古い git ワークツリーは自動的に整理されます。クリーンでマージ済みのツリーは削除され、未コミットまたは未プッシュの変更がある放置されたツリーは先にアーカイブされ、hermes worktree restore で復元できます。"
t245: "プロファイルは HERMES_HOME で Hermes の状態を分離します。terminal.home_mode が profile でない限り、ホスト側ツールのサブプロセスは本来の HOME を維持します。"
t246: "環境変数 HERMES_HOME_MODE(8 進数、例: 0701)で、Web サーバーがたどれるようにディレクトリのパーミッションを指定できます。"
t247: "コンテナモード: HERMES_HOME に .container-mode を置くと、ホストの CLI が自動的にコンテナ内で実行されます。"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index 75a774d7fc4..58be7799fde 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ 워크트리에 커밋되지 않은 변경 사항이 있어 유지해요: {path}"
clean_up_manually: "직접 정리하려면: git worktree remove --force {path}"
cleaned_up: "✓ 워크트리를 정리했어요: {path}"
+ exit_question_dirty: "이 워크트리에 커밋되지 않은 변경 사항이 있어요: {path}"
+ exit_question_unpushed: "이 워크트리에 푸시되지 않은 커밋이 있어요: {path}"
+ exit_choice_keep: "워크트리 유지 (기본값)"
+ exit_choice_archive: "보관 후 제거 (복원 가능)"
+ exit_choice_discard: "제거하고 변경 사항 버리기"
+ archived: "✓ 워크트리를 {ref}에 보관하고 제거했어요: {path}"
+ restore_hint: "복원하려면: hermes worktree restore {name}"
+ archive_failed: "✗ {path}을(를) 보관하지 못해 유지해요: {error}"
+ archive_not_removed: "보관은 완료됐지만 {path}을(를) 제거하지 못했어요. 직접 제거해 주세요."
+ discarded: "워크트리를 제거하고 변경 사항을 버렸어요: {path}"
display:
verb:
web_search: "웹 검색 중"
@@ -3727,7 +3737,7 @@ tips:
t241: "게이트웨이는 세션별로 AIAgent 인스턴스를 캐시해요 — 이 캐시를 없애면 Anthropic 프롬프트 캐싱이 깨져요."
t242: "어떤 웹사이트든 /.well-known/skills/index.json으로 스킬을 공개할 수 있어요 — 스킬 허브가 자동으로 찾아내요."
t243: "~/.hermes/skills/.hub/audit.log의 스킬 감사 로그는 모든 설치와 제거 작업을 기록해요."
- t244: "오래된 git 워크트리는 시작 시 자동 정리돼요: 깨끗하고 완전히 병합된 트리는 제거되고, 변경 중이거나 푸시되지 않은 작업은 항상 보존돼요."
+ t244: "오래된 git 워크트리는 자동으로 정리돼요: 깨끗하고 병합된 트리는 제거되고, 커밋되지 않았거나 푸시되지 않은 작업이 있는 유휴 트리는 먼저 보관되며 hermes worktree restore로 복원할 수 있어요."
t245: "프로필은 HERMES_HOME으로 Hermes 상태를 분리해요; 호스트 도구의 하위 프로세스는 terminal.home_mode가 profile이 아닌 한 실제 HOME을 유지해요."
t246: "HERMES_HOME_MODE 환경 변수(8진수, 예: 0701)는 웹 서버 접근을 위한 사용자 정의 디렉터리 권한을 설정해요."
t247: "컨테이너 모드: HERMES_HOME에 .container-mode를 두면 호스트 CLI가 자동으로 컨테이너 안에서 실행돼요."
diff --git a/locales/pt.yaml b/locales/pt.yaml
index 29f29addb18..88b631b9738 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ A worktree tem alterações não commitadas; mantendo: {path}"
clean_up_manually: "Para limpar manualmente: git worktree remove --force {path}"
cleaned_up: "✓ Worktree limpa: {path}"
+ exit_question_dirty: "Esta worktree tem alterações não commitadas: {path}"
+ exit_question_unpushed: "Esta worktree tem commits não enviados (push): {path}"
+ 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"
+ 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."
+ discarded: "Worktree removida e alterações descartadas: {path}"
display:
verb:
web_search: "Pesquisando na web"
@@ -3727,7 +3737,7 @@ tips:
t241: "O gateway mantém instâncias de AIAgent em cache por sessão — destruir esse cache quebra o cache de prompt da Anthropic."
t242: "Qualquer site pode expor skills via /.well-known/skills/index.json — o hub de skills as descobre automaticamente."
t243: "O log de auditoria de skills em ~/.hermes/skills/.hub/audit.log registra toda operação de instalação e remoção."
- t244: "Worktrees git obsoletos são limpos automaticamente na inicialização: árvores limpas e totalmente mescladas são removidas; trabalho sujo ou não enviado é sempre preservado."
+ t244: "Worktrees git obsoletas são limpas automaticamente: árvores limpas e mescladas são removidas; árvores ociosas com alterações não commitadas ou não enviadas são arquivadas antes e podem ser restauradas com hermes worktree restore."
t245: "Perfis delimitam o estado do Hermes via HERMES_HOME; subprocessos de ferramentas do host mantêm seu HOME real, a menos que terminal.home_mode seja profile."
t246: "A variável de ambiente HERMES_HOME_MODE (octal, ex.: 0701) define permissões de diretório personalizadas para travessia pelo servidor web."
t247: "Modo contêiner: coloque .container-mode em HERMES_HOME e a CLI do host executa automaticamente dentro do contêiner."
diff --git a/locales/ru.yaml b/locales/ru.yaml
index af83a2770ef..3bf292fb266 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ В worktree есть незакоммиченные изменения, оставляю: {path}"
clean_up_manually: "Чтобы очистить вручную: git worktree remove --force {path}"
cleaned_up: "✓ Worktree очищен: {path}"
+ exit_question_dirty: "В этом worktree есть незакоммиченные изменения: {path}"
+ exit_question_unpushed: "В этом worktree есть неотправленные коммиты: {path}"
+ exit_choice_keep: "Оставить worktree (по умолчанию)"
+ exit_choice_archive: "Архивировать и удалить (можно восстановить)"
+ exit_choice_discard: "Удалить и отбросить изменения"
+ archived: "✓ Worktree заархивирован в {ref} и удалён: {path}"
+ restore_hint: "Восстановить: hermes worktree restore {name}"
+ archive_failed: "✗ Не удалось заархивировать {path}, оставляю: {error}"
+ archive_not_removed: "Архив сохранён, но удалить {path} не удалось; удалите вручную."
+ discarded: "Worktree удалён, изменения отброшены: {path}"
display:
verb:
web_search: "Ищу в интернете"
@@ -3727,7 +3737,7 @@ tips:
t241: "Шлюз кэширует экземпляры AIAgent по сеансам — сброс этого кэша ломает кэширование промптов Anthropic."
t242: "Любой сайт может публиковать навыки через /.well-known/skills/index.json — хаб навыков находит их автоматически."
t243: "Журнал аудита навыков в ~/.hermes/skills/.hub/audit.log фиксирует каждую установку и удаление."
- t244: "Устаревшие git worktree очищаются при запуске автоматически: чистые, полностью слитые деревья удаляются; незакоммиченная или неотправленная работа всегда сохраняется."
+ t244: "Устаревшие git worktree очищаются автоматически: чистые слитые деревья удаляются; неактивные деревья с незакоммиченными или неотправленными изменениями сначала архивируются, и их можно восстановить командой hermes worktree restore."
t245: "Профили изолируют состояние Hermes через HERMES_HOME; подпроцессы инструментов на хосте сохраняют ваш настоящий HOME, если terminal.home_mode не равен profile."
t246: "Переменная окружения HERMES_HOME_MODE (восьмеричная, например 0701) задаёт свои права на каталог для обхода веб-сервером."
t247: "Контейнерный режим: положите .container-mode в HERMES_HOME — и CLI на хосте автоматически выполнится внутри контейнера."
diff --git a/locales/tr.yaml b/locales/tr.yaml
index c99b4e7e5c3..a7843d2018a 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ Worktree'de commit edilmemiş değişiklikler var, korunuyor: {path}"
clean_up_manually: "Elle temizlemek için: git worktree remove --force {path}"
cleaned_up: "✓ Worktree temizlendi: {path}"
+ exit_question_dirty: "Bu worktree'de commit edilmemiş değişiklikler var: {path}"
+ exit_question_unpushed: "Bu worktree'de push edilmemiş commit'ler var: {path}"
+ 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"
+ 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."
+ discarded: "Worktree kaldırıldı ve değişiklikleri atıldı: {path}"
display:
verb:
web_search: "Web'de arıyor"
@@ -3727,7 +3737,7 @@ tips:
t241: "Gateway, AIAgent örneklerini oturum başına önbelleğe alır — bu önbelleği yok etmek Anthropic istem önbelleğini bozar."
t242: "Herhangi bir web sitesi /.well-known/skills/index.json üzerinden skill yayımlayabilir — skill hub'ı bunları otomatik keşfeder."
t243: "~/.hermes/skills/.hub/audit.log konumundaki skill denetim günlüğü her kurma ve kaldırma işlemini kaydeder."
- t244: "Bayat git worktree'leri başlangıçta otomatik temizlenir: temiz, tamamen birleştirilmiş ağaçlar budanır; kirli veya push edilmemiş çalışmalar her zaman korunur."
+ t244: "Bayat git worktree'leri otomatik temizlenir: temiz ve birleştirilmiş ağaçlar kaldırılır; commit edilmemiş veya push edilmemiş çalışma içeren boştaki ağaçlar önce arşivlenir ve hermes worktree restore ile geri yüklenebilir."
t245: "Profiller Hermes durumunu HERMES_HOME ile ayırır; terminal.home_mode profile olarak ayarlanmadıkça ana makine araç alt süreçleri gerçek HOME'unuzu korur."
t246: "HERMES_HOME_MODE ortam değişkeni (sekizlik, örn. 0701), web sunucusu erişimi için özel dizin izinleri belirler."
t247: "Container modu: HERMES_HOME içine .container-mode koyun; ana makine CLI'sı otomatik olarak container içine geçer."
diff --git a/locales/uk.yaml b/locales/uk.yaml
index f9e45452656..00e729ee02e 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ У робочому дереві є незафіксовані зміни, залишаємо: {path}"
clean_up_manually: "Щоб очистити вручну: git worktree remove --force {path}"
cleaned_up: "✓ Робоче дерево очищено: {path}"
+ exit_question_dirty: "У цьому робочому дереві є незафіксовані зміни: {path}"
+ exit_question_unpushed: "У цьому робочому дереві є невідправлені коміти: {path}"
+ exit_choice_keep: "Залишити робоче дерево (типово)"
+ exit_choice_archive: "Архівувати й видалити (можна відновити)"
+ exit_choice_discard: "Видалити й відкинути зміни"
+ archived: "✓ Робоче дерево заархівовано в {ref} і видалено: {path}"
+ restore_hint: "Відновити: hermes worktree restore {name}"
+ archive_failed: "✗ Не вдалося заархівувати {path}, залишаємо: {error}"
+ archive_not_removed: "Архів збережено, але {path} не вдалося видалити; видаліть вручну."
+ discarded: "Робоче дерево видалено, зміни відкинуто: {path}"
display:
verb:
web_search: "Шукає в інтернеті"
@@ -3727,7 +3737,7 @@ tips:
t241: "Шлюз кешує екземпляри AIAgent для кожного сеансу — знищення цього кешу ламає кешування промптів Anthropic."
t242: "Будь-який сайт може публікувати навички через /.well-known/skills/index.json — хаб навичок знаходить їх автоматично."
t243: "Журнал аудиту навичок у ~/.hermes/skills/.hub/audit.log фіксує кожне встановлення та видалення."
- t244: "Застарілі робочі дерева git автоматично прибираються під час запуску: чисті, повністю злиті дерева видаляються; незбережена або невідправлена робота завжди зберігається."
+ t244: "Застарілі робочі дерева git прибираються автоматично: чисті злиті дерева видаляються; неактивні дерева з незафіксованими або невідправленими змінами спершу архівуються, і їх можна відновити командою hermes worktree restore."
t245: "Профілі ізолюють стан Hermes через HERMES_HOME; підпроцеси інструментів хоста зберігають ваш справжній HOME, якщо terminal.home_mode не дорівнює profile."
t246: "Змінна середовища HERMES_HOME_MODE (вісімкова, напр. 0701) задає власні права доступу до каталогу для обходу вебсервером."
t247: "Контейнерний режим: покладіть .container-mode у HERMES_HOME — і CLI хоста автоматично виконуватиметься всередині контейнера."
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index a559c1abc31..f2e35b983d5 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ 工作樹有未提交的變更,保留:{path}"
clean_up_manually: "手動清理方式:git worktree remove --force {path}"
cleaned_up: "✓ 工作樹已清理:{path}"
+ exit_question_dirty: "此工作樹有未提交的變更:{path}"
+ exit_question_unpushed: "此工作樹有未推送的提交:{path}"
+ exit_choice_keep: "保留工作樹(預設)"
+ exit_choice_archive: "封存並移除(可還原)"
+ exit_choice_discard: "移除並捨棄變更"
+ archived: "✓ 工作樹已封存至 {ref} 並移除:{path}"
+ restore_hint: "還原方式:hermes worktree restore {name}"
+ archive_failed: "✗ 無法封存 {path},保留:{error}"
+ archive_not_removed: "封存已儲存,但無法移除 {path};請手動移除。"
+ discarded: "工作樹已移除,變更已捨棄:{path}"
display:
verb:
web_search: "搜尋網頁中"
@@ -3727,7 +3737,7 @@ tips:
t241: "閘道會為每個工作階段快取 AIAgent 實例 — 清除這個快取會破壞 Anthropic 的提示快取。"
t242: "任何網站都可以透過 /.well-known/skills/index.json 公開技能 — 技能中心會自動發現它們。"
t243: "~/.hermes/skills/.hub/audit.log 的技能稽核日誌會記錄每一次安裝與移除操作。"
- t244: "過期的 git 工作樹會在啟動時自動清理:乾淨且已完全合併的樹會被移除;有未提交或未推送的工作則一律保留。"
+ t244: "過期的 git 工作樹會自動清理:乾淨且已合併的樹會被移除;閒置且有未提交或未推送工作的樹會先封存,可用 hermes worktree restore 還原。"
t245: "設定檔透過 HERMES_HOME 隔離 Hermes 狀態;除非 terminal.home_mode 設為 profile,主機工具子程序會保留你真正的 HOME。"
t246: "HERMES_HOME_MODE 環境變數(八進位,例如 0701)可設定自訂目錄權限,供網頁伺服器穿越存取。"
t247: "容器模式:在 HERMES_HOME 放置 .container-mode,主機 CLI 就會自動 exec 進入容器。"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index 78d91b242a2..66cacf5d295 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -3299,6 +3299,16 @@ cli:
uncommitted_keeping: "⚠ 工作树有未提交的更改,保留:{path}"
clean_up_manually: "手动清理:git worktree remove --force {path}"
cleaned_up: "✓ 工作树已清理:{path}"
+ exit_question_dirty: "此工作树有未提交的更改:{path}"
+ exit_question_unpushed: "此工作树有未推送的提交:{path}"
+ exit_choice_keep: "保留工作树(默认)"
+ exit_choice_archive: "归档并移除(可恢复)"
+ exit_choice_discard: "移除并丢弃更改"
+ archived: "✓ 工作树已归档到 {ref} 并移除:{path}"
+ restore_hint: "恢复方式:hermes worktree restore {name}"
+ archive_failed: "✗ 无法归档 {path},保留:{error}"
+ archive_not_removed: "归档已保存,但无法移除 {path};请手动移除。"
+ discarded: "工作树已移除,更改已丢弃:{path}"
display:
verb:
web_search: "搜索网页"
@@ -3727,7 +3737,7 @@ tips:
t241: "网关按会话缓存 AIAgent 实例——销毁这个缓存会破坏 Anthropic 的提示词缓存。"
t242: "任何网站都可以通过 /.well-known/skills/index.json 公开技能——技能中心会自动发现它们。"
t243: "技能审计日志位于 ~/.hermes/skills/.hub/audit.log,记录每一次安装和移除操作。"
- t244: "启动时会自动清理过期的 git 工作树:干净且已完全合并的会被清除;有未提交或未推送改动的始终保留。"
+ t244: "过期的 git 工作树会自动清理:干净且已合并的会被移除;闲置且有未提交或未推送改动的会先归档,可用 hermes worktree restore 恢复。"
t245: "配置档通过 HERMES_HOME 隔离 Hermes 状态;除非 terminal.home_mode 设为 profile,主机工具子进程仍使用你真实的 HOME。"
t246: "HERMES_HOME_MODE 环境变量(八进制,如 0701)为 Web 服务器遍历设置自定义目录权限。"
t247: "容器模式:在 HERMES_HOME 中放置 .container-mode,主机 CLI 就会自动切换到容器内执行。"
diff --git a/tests/hermes_cli/test_worktree_gc.py b/tests/hermes_cli/test_worktree_gc.py
index bd1c370f0c0..3ec8f7ccf06 100644
--- a/tests/hermes_cli/test_worktree_gc.py
+++ b/tests/hermes_cli/test_worktree_gc.py
@@ -420,7 +420,7 @@ class TestCmdWorktreeJson:
_add_worktree(repo, "hermes-json")
assert cmd_worktree(self._ns(repo, "list")) == 0
payload = json.loads(capsys.readouterr().out)
- assert set(payload) == {"repo", "trees", "external_trees", "branches"}
+ assert set(payload) == {"repo", "trees", "external_trees", "branches", "archives"}
names = [t["name"] for t in payload["trees"]]
assert "hermes-json" in names
tree = next(t for t in payload["trees"] if t["name"] == "hermes-json")
diff --git a/tests/hermes_cli/test_worktree_snapshot_prune.py b/tests/hermes_cli/test_worktree_snapshot_prune.py
new file mode 100644
index 00000000000..5424aa9b1c5
--- /dev/null
+++ b/tests/hermes_cli/test_worktree_snapshot_prune.py
@@ -0,0 +1,207 @@
+"""Invariants of the snapshot-then-delete worktree sweep (``worktrees.archive_dirty``).
+
+Real git repos, real processes, no mocks: an idle dirty/unpushed tree past its tier is removed
+only after a restorable archive exists (I1/I4); live, kanban and young trees are never touched
+(I2/I3); ``archive_dirty: false`` keeps the classic never-delete-dirty pruner (I6); the cron sweep
+visits the repos the ACTIVE profile registered (I7); a non-interactive exit never prompts (I5).
+"""
+
+import hashlib
+import os
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+from hermes_cli import worktree_ops
+
+
+def _git(args, cwd):
+ result = subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=str(cwd),
+ capture_output=True, text=True, check=False)
+ assert result.returncode == 0, f"git {args}: {result.stderr}"
+ return result.stdout.strip()
+
+
+def repo(tmp_path):
+ origin = tmp_path / "origin.git"
+ _git(["init", "-q", "--bare", "-b", "main", str(origin)], tmp_path)
+ clone = tmp_path / "repo"
+ _git(["init", "-q", "-b", "main", str(clone)], tmp_path)
+ (clone / ".gitignore").write_text(".worktrees/\nnode_modules/\n", encoding="utf-8")
+ (clone / ".gitattributes").write_text("*.txt text eol=crlf\n", encoding="utf-8")
+ (clone / "a.txt").write_text("one\ntwo\n", encoding="utf-8")
+ (clone / "b.py").write_text("x = 1\n", encoding="utf-8")
+ _git(["add", "-A"], clone)
+ _git(["commit", "-qm", "init"], clone)
+ _git(["remote", "add", "origin", str(origin)], clone)
+ _git(["push", "-q", "origin", "main"], clone)
+ _git(["fetch", "-q", "origin"], clone)
+ (clone / ".worktrees").mkdir()
+ return clone
+
+
+def _tree(repo, name, *, dirty=False, unpushed=False):
+ path = repo / ".worktrees" / name
+ _git(["worktree", "add", "-q", "-b", f"wt/{name}", str(path), "HEAD"], repo)
+ if unpushed:
+ (path / "feature.py").write_text(f"work for {name}\n", encoding="utf-8")
+ _git(["add", "feature.py"], path)
+ _git(["commit", "-qm", "wip"], path)
+ if dirty:
+ (path / "notes.md").write_text("uncommitted\n", encoding="utf-8")
+ return path
+
+
+def _idle(path, hours=100):
+ """Age the tree AND its activity (files, HEAD, reflog) so the sweep sees it as idle."""
+ stamp = time.time() - hours * 3600
+ git_dir = Path(_git(["rev-parse", "--absolute-git-dir"], path))
+ for item in [*path.rglob("*"), git_dir / "HEAD", git_dir / "logs" / "HEAD", path]:
+ if item.exists():
+ os.utime(item, (stamp, stamp), follow_symlinks=False)
+
+
+def _archives(repo):
+ out = _git(["for-each-ref", "--format=%(refname)", "refs/hermes/archive/"], repo)
+ return [line for line in out.splitlines() if line]
+
+
+def _digest(path):
+ return {str(f.relative_to(path)): hashlib.sha256(f.read_bytes()).hexdigest()
+ for f in sorted(path.rglob("*")) if f.is_file() and ".git" not in f.parts and "node_modules" not in f.parts}
+
+
+def _set_worktrees_config(text):
+ from hermes_constants import get_hermes_home
+ home = get_hermes_home()
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(text, encoding="utf-8")
+
+
+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."""
+ from hermes_cli.worktree_archive import restore_archive, snapshot_worktree
+
+ wt = _tree(repo, "lane-roundtrip", unpushed=True)
+ (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
+ (wt / "a.txt").write_bytes(b"one\r\nTWO\r\n") # raw CRLF bytes under eol=crlf
+ (wt / "new dir").mkdir()
+ (wt / "new dir" / "blob.bin").write_bytes(os.urandom(4096))
+ (wt / "node_modules").mkdir()
+ (wt / "node_modules" / "dep.js").write_text("ignored, never archived\n", encoding="utf-8")
+ (wt / "big.dat").write_bytes(b"\0" * (2 * 1024 * 1024))
+ git_dir = Path(_git(["rev-parse", "--absolute-git-dir"], wt))
+ index_before, files_before = (git_dir / "index").read_bytes(), _digest(wt)
+ head, staged = _git(["rev-parse", "HEAD"], wt), _git(["diff", "--cached"], wt)
+
+ arc = snapshot_worktree(str(repo), wt, reason="test", max_untracked_mb=1)
+ assert (git_dir / "index").read_bytes() == index_before
+ assert _digest(wt) == files_before
+ assert [s["path"] for s in arc.meta["skipped_untracked"]] == ["big.dat"]
+ assert "node_modules/dep.js" not in _git(["ls-tree", "-r", "--name-only", arc.sha], repo)
+
+ _git(["worktree", "remove", "--force", str(wt)], repo)
+ _git(["branch", "-D", "wt/lane-roundtrip"], repo)
+ restored = restore_archive(str(repo), "lane-roundtrip")
+ assert restored["path"] == str(wt) and restored["branch"] == "wt/lane-roundtrip"
+ assert _digest(wt) == {k: v for k, v in files_before.items() if k != "big.dat"}
+ assert _git(["rev-parse", "HEAD"], wt) == head
+ assert _git(["diff", "--cached"], wt) == staged
+
+
+def test_sweep_archives_idle_work_and_never_touches_live_kanban_or_young_trees(repo):
+ """I1/I2/I3/I4 on one board through the real pruner entry point."""
+ clean = _tree(repo, "lane-clean")
+ dirty = _tree(repo, "lane-dirty", dirty=True)
+ unpushed = _tree(repo, "hermes-unpushed", unpushed=True)
+ live_cwd = _tree(repo, "lane-live-cwd", dirty=True)
+ live_lock = _tree(repo, "hermes-live-lock", dirty=True)
+ _git(["worktree", "lock", "--reason", f"hermes pid={os.getpid()}", str(live_lock)], repo)
+ kanban = _tree(repo, "t_0abc12", dirty=True)
+ young = _tree(repo, "lane-young", dirty=True)
+ 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):
+ _idle(tree)
+ sleeper = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"], cwd=str(live_cwd))
+ try:
+ worktree_ops._prune_stale_worktrees(str(repo))
+ finally:
+ sleeper.kill()
+ sleeper.wait()
+
+ assert not clean.exists()
+ for gone in (dirty, unpushed):
+ assert not gone.exists(), f"idle {gone.name} should be archived then removed"
+ archived = {ref.rsplit("/", 1)[-1] for ref in _archives(repo)}
+ assert archived == {"lane-dirty", "hermes-unpushed"}
+ 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_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")
+ clean = _tree(repo, "lane-clean")
+ dirty = _tree(repo, "lane-dirty", dirty=True)
+ unpushed = _tree(repo, "hermes-unpushed", unpushed=True)
+ for tree in (clean, dirty, unpushed):
+ _idle(tree)
+ worktree_ops._prune_stale_worktrees(str(repo))
+ assert not clean.exists()
+ assert dirty.exists() and unpushed.exists()
+ assert _archives(repo) == []
+
+
+def test_cron_sweep_visits_only_the_active_profiles_registered_repos(repo, tmp_path, monkeypatch):
+ """I7: a worktree made under profile A registers its repo for A's sweep only, and a
+ registered repo that was deleted drops out."""
+ import cron.scheduler as sched
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ home_a, home_b = tmp_path / "home-a", tmp_path / "home-b"
+ home_a.mkdir()
+ home_b.mkdir()
+ monkeypatch.setattr("cron.jobs.load_jobs", list)
+ token = set_hermes_home_override(str(home_a))
+ try:
+ assert worktree_ops._setup_worktree(repo_root=str(repo), sync_base=False, name="reg") is not None
+ gone = tmp_path / "gone"
+ _git(["init", "-q", str(gone)], tmp_path)
+ (gone / ".worktrees").mkdir()
+ from hermes_cli.worktree_registry import record_worktree_repo
+ record_worktree_repo(gone)
+ import shutil
+ shutil.rmtree(gone)
+ repos_a = sched._worktree_maintenance_repos()
+ finally:
+ reset_hermes_home_override(token)
+ token = set_hermes_home_override(str(home_b))
+ try:
+ repos_b = sched._worktree_maintenance_repos()
+ finally:
+ reset_hermes_home_override(token)
+ assert os.path.realpath(repo) in repos_a
+ assert str(gone) not in repos_a and os.path.realpath(gone) not in repos_a
+ assert os.path.realpath(repo) not in repos_b
+
+
+def test_exit_question_never_prompts_without_a_tty(repo, monkeypatch):
+ """I5: a dirty tree at a non-interactive exit is kept without any prompt."""
+ from hermes_cli import curses_ui, worktree_exit
+
+ wt = _tree(repo, "hermes-exit", dirty=True)
+ monkeypatch.setattr(curses_ui, "curses_radiolist",
+ lambda *a, **k: pytest.fail("non-interactive exit must never prompt"))
+ info = {"path": str(wt), "repo_root": str(repo), "branch": "wt/hermes-exit"}
+ assert worktree_exit.ask_exit_choice(info) == worktree_exit.KEEP
+ assert "exit_choice" not in info and wt.exists()
diff --git a/tests/tools/test_subagent_worktree.py b/tests/tools/test_subagent_worktree.py
index 0d63492785e..c13b5e4c574 100644
--- a/tests/tools/test_subagent_worktree.py
+++ b/tests/tools/test_subagent_worktree.py
@@ -115,7 +115,7 @@ class SubagentWorktreeTests(unittest.TestCase):
branches = _git(["branch", "--list", info["branch"]], repo).stdout
self.assertEqual(branches.strip(), "")
- def test_finalize_keeps_worktree_with_commits(self):
+ def test_finalize_archives_worktree_with_commits(self):
repo = _make_repo(self.tmp)
info = sw.create_subagent_worktree(str(repo), "work1")
assert info is not None
@@ -126,19 +126,26 @@ class SubagentWorktreeTests(unittest.TestCase):
_git(["config", "user.name", "Child"], wt)
_git(["commit", "-q", "-m", "child work"], wt)
payload = sw.finalize_subagent_worktree(info)
- self.assertFalse(payload["pruned"])
+ # Contract (snapshot-then-delete, approved 2026-10-17): never removed without a
+ # restorable archive; the branch stays for the parent to merge.
+ self.assertTrue(payload["pruned"])
self.assertEqual(payload["commits"], 1)
- self.assertTrue(os.path.isdir(info["path"]))
+ self.assertFalse(os.path.isdir(info["path"]))
+ self.assertEqual(_git(["rev-parse", payload["archive"] + "^1"], repo).stdout,
+ _git(["rev-parse", info["branch"]], repo).stdout)
- def test_finalize_keeps_dirty_worktree(self):
+ def test_finalize_archives_dirty_worktree(self):
repo = _make_repo(self.tmp)
info = sw.create_subagent_worktree(str(repo), "dirty1")
assert info is not None
(Path(info["path"]) / "wip.txt").write_text("uncommitted\n", encoding="utf-8")
payload = sw.finalize_subagent_worktree(info)
- self.assertFalse(payload["pruned"])
+ # Contract (snapshot-then-delete, approved 2026-10-17): the uncommitted file lives on in
+ # the archive commit before the tree is removed.
+ self.assertTrue(payload["pruned"])
self.assertTrue(payload["dirty"])
- self.assertTrue(os.path.isdir(info["path"]))
+ self.assertFalse(os.path.isdir(info["path"]))
+ self.assertEqual(_git(["show", payload["archive"] + ":wip.txt"], repo).stdout, "uncommitted\n")
def test_finalize_keeps_worktree_when_git_inspection_fails(self):
"""#88113: a non-zero git status exit must not be read as "clean".
diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.py
index 1999007c026..b50641c6419 100644
--- a/tools/subagent_worktree.py
+++ b/tools/subagent_worktree.py
@@ -2,8 +2,10 @@
Git-only (outside a repo children share the parent's cwd); local terminal backend only (on
docker/ssh/modal the host worktree is invisible in the sandbox, so isolation is skipped). One
-worktree per child under ``<repo>/.worktrees/subagent-<id>``, branch ``hermes-subagent/<id>``;
-pruned only on proof (zero commits AND clean, both probes ok), else kept + ``inspection_failed``.
+worktree per child under ``<repo>/.worktrees/subagent-<id>``, branch ``hermes-subagent/<id>``.
+On finish: zero commits AND clean (both probes ok) -> removed; work left behind -> archived to
+``refs/hermes/archive/<tree>`` then removed (``worktrees.archive_dirty``, branch kept so the parent
+can merge it); a failed probe or archive -> kept + flagged.
"""
from __future__ import annotations
@@ -100,6 +102,8 @@ def create_subagent_worktree(parent_cwd: Optional[str], subagent_id: Optional[st
logger.warning("subagent worktree: git worktree add failed: %s", result.stderr.strip())
return None
logger.info("subagent worktree created: %s (branch %s)", wt_path, branch)
+ from hermes_cli.worktree_registry import record_worktree_repo
+ record_worktree_repo(repo_root)
return {"path": str(wt_path), "branch": branch, "repo_root": repo_root, "base_commit": base_commit}
@@ -176,6 +180,8 @@ def finalize_subagent_worktree(info: dict[str, str], *, prune: bool = True) -> d
if failed:
# Destructive cleanup requires affirmative proof; defaults prove nothing.
return mark_worktree_payload_unproven(payload, "; ".join(failed), unmeasured="/".join(unmeasured))
+ if prune and (payload["commits"] or payload["dirty"]):
+ return _archive_finished_worktree(info, payload)
if prune and payload["commits"] == 0 and not payload["dirty"]:
cwd = info.get("repo_root", "") or path
try:
@@ -193,6 +199,37 @@ def finalize_subagent_worktree(info: dict[str, str], *, prune: bool = True) -> d
return payload
+def _archive_finished_worktree(info: dict[str, str], payload: dict[str, Any]) -> dict[str, Any]:
+ """A finished child left commits or edits: snapshot them, then remove the tree.
+
+ The branch is kept (the parent reviews and merges it); the archive also covers uncommitted
+ edits. ``worktrees.archive_dirty: false`` or a failed snapshot keeps the tree as before.
+ """
+ from hermes_cli.worktree_archive import ArchiveError
+ from hermes_cli.worktree_sweep import archive_then_remove, live_process_pids, sweep_settings
+ settings = sweep_settings()
+ if not settings["archive_dirty"]:
+ return payload
+ path = info.get("path", "")
+ # A server or watcher the child started may still run in the tree: leave it to the sweep.
+ if live_process_pids([path], exclude=(os.getpid(),)).get(path):
+ logger.info("subagent worktree: a live process works in %s; keeping it", path)
+ return payload
+ 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)
+ except (ArchiveError, OSError, subprocess.SubprocessError) as exc:
+ logger.warning("subagent worktree: archive failed, keeping %s: %s", path, exc)
+ return payload
+ payload["archive"] = ref
+ payload["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]}`.")
+ return payload
+
+
def build_worktree_context_note(info: dict[str, str]) -> str:
"""Context block telling the child to work inside its isolated worktree."""
return (
@@ -202,5 +239,6 @@ def build_worktree_context_note(info: dict[str, str]) -> str:
"All file edits and shell commands must happen inside this worktree directory (your "
"terminal already starts there). Do NOT cd to the main repository checkout. Commit your "
"changes to your branch when done; the parent agent will review and merge your branch. If "
- "you make no commits and leave the tree clean, the worktree is discarded automatically."
+ "you make no commits and leave the tree clean, the worktree is discarded automatically; "
+ "otherwise it is archived (restorable) and removed when you finish."
)
diff --git a/website/docs/reference/slash-commands.md b/website/docs/reference/slash-commands.md
index 4add1c493fa..2cfd74a74a6 100644
--- a/website/docs/reference/slash-commands.md
+++ b/website/docs/reference/slash-commands.md
@@ -68,7 +68,7 @@ Type `/` in the CLI to open the autocomplete menu. Built-in commands are case-in
| `/bg <prompt>` | Run a prompt in a separate background session. The agent processes your prompt independently — your current session stays free for other work. Results appear as a panel when the task finishes. See [CLI Background Sessions](../user-guide/cli.md#background-sessions). |
| `/btw <question>` | Ask a quick side question **about the current conversation** without interrupting it. A one-shot auxiliary LLM call answers from a read-only snapshot of the transcript — the live session's history and prompt cache are untouched, and the current turn keeps running. For independent work with a fresh context, use `/bg`. |
| `/branch [--here] [name]` (alias: `/fork`) | Branch the current session into an independent copy (explore a different path). On Discord, Telegram, Slack and Matrix the branch opens in a **new sibling thread** and the current chat stays on the original session; `--here` switches the current chat onto the branch instead (the pre-#66023 behaviour). The CLI and platforms without threads always branch in place. Classic CLI: refused mid-turn like `/handoff` — wait for the current response to finish, then retry. |
-| `/worktree [new [name]\|list]` | **CLI only.** Inspect or create isolated git worktrees mid-session (inspired by Copilot CLI's `/worktree new`). Bare `/worktree` shows the active worktree; `/worktree list` lists the repo's worktrees; `/worktree new [name]` creates a worktree under `.worktrees/` (branched from the freshly-fetched remote tip, honoring `worktree_sync`) and retargets the session's terminal and file tools into it. Named trees use your name (`hermes/<name>` branch); unnamed ones get a random `hermes-<id>`. On exit the tree is kept only if it has unpushed commits — same lifecycle as `hermes -w`. See [Git Worktrees](../user-guide/git-worktrees.md). |
+| `/worktree [new [name]\|list]` | **CLI only.** Inspect or create isolated git worktrees mid-session (inspired by Copilot CLI's `/worktree new`). Bare `/worktree` shows the active worktree; `/worktree list` lists the repo's worktrees; `/worktree new [name]` creates a worktree under `.worktrees/` (branched from the freshly-fetched remote tip, honoring `worktree_sync`) and retargets the session's terminal and file tools into it. Named trees use your name (`hermes/<name>` branch); unnamed ones get a random `hermes-<id>`. On exit a dirty or unpushed tree triggers the keep / archive / remove question — same lifecycle as `hermes -w`. See [Git Worktrees](../user-guide/git-worktrees.md). |
| `/handoff <platform>` | **CLI only.** Hand the current session off to a messaging platform (Telegram, Discord, Slack, WhatsApp, Signal, Matrix). The gateway picks it up immediately, creates a fresh thread on platforms that support threads (Telegram topics, Discord text-channel threads, Slack and Matrix message-anchored threads), re-binds the destination to your CLI session_id so the full role-aware transcript replays, and forges a synthetic user turn so the agent confirms it's working in the new place. Your CLI exits cleanly on success with a `/resume` hint; resume locally any time with `/resume <title>`. Refused mid-turn. Requires the gateway to be running and a home channel configured for the target platform (`/sethome` from the destination chat). See [Cross-Platform Handoff](../user-guide/sessions.md#cross-platform-handoff). |
| `/journey [list\|delete <id>\|edit <id>]` (aliases: `/learning`, `/memory-graph`) | Open the learning journey timeline of learned skills + memories. Works in the classic CLI, as a TUI overlay, and in the desktop app (Star Map panel). Not available on messaging platforms. See [Learning Journey](../user-guide/features/memory.md#learning-journey-journey). |
diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.md
index 25561c48be7..43299714cab 100644
--- a/website/docs/user-guide/cli.md
+++ b/website/docs/user-guide/cli.md
@@ -66,16 +66,19 @@ With `hermes --tui -w`, closing the terminal detaches from the gateway-owned
session. Its worktree is retained even when clean: the turn may still be running
there, and resuming the session uses the same working directory. Review and prune
it after the session's work is finished.
-A conservative pruner runs automatically at startup (it only removes clean,
-fully-merged scratch trees past an age threshold), but preserved trees and
-merged local branches still accumulate on busy machines. Reclaim them
-explicitly:
+A sweep runs automatically at `hermes -w` startup and every 6 hours from the
+cron ticker: idle clean+merged trees are removed, and idle trees with
+uncommitted changes or unpushed commits are **archived, then removed**
+(restorable with `hermes worktree restore <name>`; see
+[Stale worktree sweep](./git-worktrees.md#stale-worktree-sweep-and-restore)).
+Reclaim or inspect explicitly:
```bash
-hermes worktree list # audit: age, size, verdict, reason per tree
-hermes worktree list --json # machine-readable audit (trees, external trees, branches)
-hermes worktree prune # remove safe trees + delete merged branches
-hermes worktree prune --dry-run # show the plan without changing anything
+hermes worktree list # audit: age, size, verdict, reason per tree + archives
+hermes worktree list --json # machine-readable audit (trees, external trees, branches, archives)
+hermes worktree prune # run the sweep now + delete merged branches
+hermes worktree prune --dry-run # print every archive/remove/skip decision and why; changes nothing
+hermes worktree restore <name> # recreate an archived tree (add --path DIR to put it elsewhere)
hermes worktree prune --older-than 7 # only reap trees idle for 7+ days
hermes worktree prune --trees-only # leave local branches alone
hermes worktree prune --branches-only # leave worktrees alone
@@ -93,8 +96,9 @@ touches the tree the session is running in).
Safety guarantees (all modes, any age):
-- Uncommitted **tracked** changes are never deleted.
-- **Unique unpushed commits** are never deleted — commits that were
+- Uncommitted changes and **unique unpushed commits** are never deleted
+ without a restorable archive (`refs/hermes/archive/<tree>`); with
+ `worktrees.archive_dirty: false` they are never deleted at all — commits that were
rebase/squash-merged upstream are detected via `git cherry`
patch-equivalence and count as merged, which is what lets the dominant
"merged PR, tree preserved forever" leak finally reclaim.
@@ -109,7 +113,9 @@ Safety guarantees (all modes, any age):
removed but its **branch ref is kept**, so the lane is one
`git worktree add .worktrees/<name> <branch>` away from restored. If the
remote can't be reached, the tree is preserved.
-- Trees **in use by a running hermes session** are never touched.
+- 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.
- **Untracked-only scratch** (PR body drafts, notes) is archived to
`~/.hermes/archive/worktree-prune/` before its tree is removed — never
destroyed.
@@ -117,10 +123,10 @@ Safety guarantees (all modes, any age):
commits are all on upstream is safe to delete; branches with unique work,
checked-out branches, and `main`/`master`/`develop` are always kept.
-The same conservative pruner also runs from the cron scheduler (at most once
-every 6 hours, in the background), so gateway-only machines — where nobody
-launches `hermes -w` for days — no longer accumulate merged scratch trees
-between CLI sessions.
+The same sweep also runs from the cron scheduler (at most once every 6 hours
+per profile, in the background) over every repository the profile created a
+worktree in, so gateway-only machines — where nobody launches `hermes -w` for
+days — no longer accumulate scratch trees between CLI sessions.
When `.worktrees/` grows past 10 trees or 5 GB, startup prints a one-line
notice pointing at these commands.
diff --git a/website/docs/user-guide/git-worktrees.md b/website/docs/user-guide/git-worktrees.md
index b2d130198f8..6c855aaf16f 100644
--- a/website/docs/user-guide/git-worktrees.md
+++ b/website/docs/user-guide/git-worktrees.md
@@ -51,7 +51,8 @@ Hermes creates `.worktrees/my-experiment/` inside the repo (branch
`worktree_sync: false`), and retargets the session's terminal and file tools
into it — no restart needed. Omit the name to get a random `hermes-<id>`
tree. `/worktree` alone shows the active tree; `/worktree list` lists all of
-them. On exit the tree is kept only if it has unpushed commits, exactly like
+them. On exit a clean, pushed tree is removed; a tree with uncommitted changes
+or unpushed commits triggers the same keep / archive / remove question as
`hermes -w`.
### Manually with git
@@ -181,6 +182,73 @@ hermes -w -z "Fix issue #123"
For parallel agents, open multiple terminals and run `hermes -w` in each — every invocation gets its own worktree and branch automatically.
+### Leaving a session with unfinished work
+
+When an interactive `hermes -w` session (classic CLI or `--tui`) exits and its
+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.
+- **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
+terminal never ask: the tree is kept and the stale-worktree sweep handles it
+later. A clean tree whose commits are pushed is removed without asking.
+
+## Stale worktree sweep and restore
+
+Every repository Hermes creates a worktree in (`hermes -w`, `/worktree new`,
+subagent worktree isolation, the desktop app's git pane) is recorded in
+`<HERMES_HOME>/worktree_repos.json` for the active profile. At `hermes -w`
+startup and every 6 hours from the cron ticker, Hermes sweeps each of those
+repositories' `.worktrees/`:
+
+| Tree | Decision |
+|---|---|
+| 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 |
+| 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
+`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.
+
+```bash
+hermes worktree list # trees plus archives (name, age, branch, reason)
+hermes worktree prune --dry-run # every archive/remove/skip decision and why; changes nothing
+hermes worktree restore lane-x # recreate .worktrees/lane-x with its branch, staged and untracked files
+hermes worktree restore lane-x --path ../lane-x-review
+```
+
+Restore puts the branch back when it is missing or still points at the
+archived `HEAD`; otherwise the tree comes back detached at that commit.
+Archives older than `worktrees.archive_retention_days` are deleted by the
+sweep.
+
+```yaml
+worktrees:
+ archive_dirty: true # false = never remove dirty/unpushed trees (the old behaviour)
+ archive_max_file_mb: 50 # untracked files above this are listed, not archived
+ archive_retention_days: 30 # 0 keeps archives forever
+ max_total_gb: 0 # optional budget for idle trees; oldest are archived + removed first
+```
+
+There is no limit on how many trees may exist: hundreds of parallel subagents
+each keep their tree for as long as they work in it. `max_total_gb` only ever
+evicts idle trees past their tier.
+
+Subagent worktrees (`delegation.worktree_isolation: true`) follow the same
+rule when the child finishes: a clean tree is removed, and a tree with commits
+or edits is archived and removed with its branch kept for the parent to merge.
+
## Putting It All Together
- Use **git worktrees** to give each Hermes session its own clean checkout.