The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): a resume recreates the --tui -w worktree quit removed, so its turns run
Teknium9e49003893c9
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 7c5e4e644ec..4ab26c77bbd 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1526,6 +1526,22 @@ def _import_foreign_resume(args) -> None:args.resume = _imported_id+def _recreate_resumed_tui_worktree(args) -> None:+ """A resumed session whose frozen cwd is a ``--tui -w`` tree that quit removed gets that tree+ back before attaching, or the owner refuses every turn ``workspace_unavailable`` (N8)."""+ if not getattr(args, "resume", None) or getattr(args, "worktree", False):+ return+ cwd = ""+ with _session_db() as db: # a store error is swallowed: nothing to recreate+ cwd = ((db.get_session(args.resume) or {}).get("cwd") or "").strip()+ if not cwd or os.path.isdir(cwd):+ return+ from hermes_cli.tui_worktree_resume import recreate_tui_worktree+ tree = recreate_tui_worktree(cwd, args.resume)+ if tree:+ print(f"↪ recreated the session's worktree: {tree}")++def _resolve_chat_session_args(args, use_tui: bool) -> None:"""Normalize --in / --resume / --continue on ``args`` before agent init.@@ -1560,6 +1576,8 @@ def _resolve_chat_session_args(args, use_tui: bool) -> None:# On miss keep the original so _init_agent reports "Session not found" with it.args.resume = _resolve_session_by_name_or_id(resume_val) or resume_val+ _recreate_resumed_tui_worktree(args)+# cd back into a resumed session's recorded cwd (opt out: --no-restore-cwd;# --worktree owns its own dir). A missing dir warns and stays put.if (diff --git a/hermes_cli/tui_worktree_resume.py b/hermes_cli/tui_worktree_resume.pynew file mode 100644index 00000000000..2303456a5bf--- /dev/null+++ b/hermes_cli/tui_worktree_resume.py@@ -0,0 +1,131 @@+"""Bring back a ``hermes --tui -w`` worktree a resume needs (N8).++Quitting a clean, idle ``--tui -w`` session removes its tree and branch, but the session's policy+froze that cwd, and the owner refuses every turn in a missing directory (``workspace_unavailable``).+So the launcher records each tree it creates in the profile's ``tui_worktrees.json``, and a resume+whose session cwd is such a missing tree recreates it at the same path before attaching: from its+branch when that still exists, else a new branch of the same name from the repo's current HEAD.++Only a path this profile's launcher recorded, directly under its repo's ``.worktrees/``, is ever+created; any other missing directory is left alone (the resume warns as before).+"""++from __future__ import annotations++import logging+import os+import subprocess+import threading+from pathlib import Path+from typing import Optional++logger = logging.getLogger(__name__)++_RECORD_NAME = "tui_worktrees.json"+_MAX_RECORDS = 500+_holder = threading.local()+++def _record_path() -> Path:+ from hermes_constants import get_hermes_home+ return get_hermes_home() / _RECORD_NAME+++def _key(path) -> str:+ return os.path.normcase(os.path.realpath(str(path)))+++def _read() -> dict:+ from utils import read_json_or_empty+ trees = read_json_or_empty(_record_path()).get("trees")+ return trees if isinstance(trees, dict) else {}+++def record_tui_worktree(wt_info: dict) -> None:+ """Remember a tree the ``--tui -w`` launcher created. Never raises."""+ try:+ from hermes_cli.auth import _file_lock+ from utils import atomic_json_write++ path = _record_path()+ with _file_lock(path.with_name(path.name + ".lock"), _holder, 5.0,+ "Timed out waiting for the TUI worktree record lock"):+ trees = {k: v for k, v in _read().items()+ if isinstance(v, dict) and (Path(str(v.get("repo_root") or "")) / ".git").exists()}+ trees[_key(wt_info["path"])] = {"path": str(wt_info["path"]), "branch": wt_info["branch"],+ "repo_root": str(wt_info["repo_root"])}+ atomic_json_write(path, {"version": 1, "trees": dict(list(trees.items())[-_MAX_RECORDS:])})+ except Exception: # health: allow BLE001 -- a lost record only means no recreate on resume+ logger.debug("TUI worktree record failed for %s", wt_info.get("path"), exc_info=True)+++def _recorded_tree_for(cwd: str) -> Optional[dict]:+ """The launcher's record of the missing tree *cwd* is (or is inside), or None."""+ try:+ trees = _read()+ except Exception: # health: allow BLE001 -- unreadable record: create nothing+ return None+ probe = Path(cwd)+ for candidate in (probe, *probe.parents):+ entry = trees.get(_key(candidate))+ if not isinstance(entry, dict):+ continue+ repo = Path(str(entry.get("repo_root") or ""))+ tree = Path(str(entry.get("path") or ""))+ branch = str(entry.get("branch") or "")+ # Only a direct child of the repo's Hermes worktree dir, as _setup_worktree makes them.+ if (branch and (repo / ".git").exists()+ and _key(tree.parent) == _key(repo / ".worktrees") and _key(tree) == _key(candidate)):+ return {"path": str(tree), "branch": branch, "repo_root": str(repo)}+ return None+ return None+++def _branch_exists(repo_root: str, branch: str) -> bool:+ from hermes_cli.worktree_ops import _git+ result = _git(["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], repo_root)+ return result.returncode == 0+++def recreate_tui_worktree(cwd: str, session_id: str) -> Optional[str]:+ """Recreate the launcher-made tree a resumed session's missing *cwd* names -> its path, or None.++ Reuses the branch when it survived (its commits come back), else makes it again from the repo's+ current HEAD. The tree is locked for the session so the stale-tree prune keeps it. Never raises.+ """+ if not cwd or os.path.isdir(cwd):+ return None+ entry = _recorded_tree_for(cwd)+ if entry is None:+ return None+ from hermes_cli._subprocess_compat import noninteractive_repo_git_env+ from hermes_cli.worktree_ops import (+ _copy_worktree_includes,+ _git,+ _git_quiet,+ _retain_worktree_for_session,+ )+ from hermes_constants import get_hermes_home++ repo_root, tree, branch = entry["repo_root"], Path(entry["path"]), entry["branch"]+ if tree.exists(): # a file, or a dir that appeared since: never overwrite it+ return None+ env = noninteractive_repo_git_env(repo_root)+ if env is None:+ return None+ try:+ # A tree deleted by hand leaves its admin entry; drop it so the path can be added again.+ _git_quiet(["worktree", "prune"], repo_root, timeout=15, stdin=subprocess.DEVNULL, env=env)+ tree.parent.mkdir(parents=True, exist_ok=True)+ args = ([str(tree), branch] if _branch_exists(repo_root, branch)+ else [str(tree), "-b", branch, "HEAD"])+ result = _git(["worktree", "add", *args], repo_root, timeout=120, stdin=subprocess.DEVNULL, env=env)+ if result.returncode != 0:+ logger.warning("could not recreate worktree %s: %s", tree, result.stderr.strip())+ return None+ _copy_worktree_includes(repo_root, tree)+ _retain_worktree_for_session(repo_root, str(tree), session_id, get_hermes_home() / "state.db")+ except (OSError, subprocess.SubprocessError) as exc:+ logger.warning("could not recreate worktree %s: %s", tree, exc)+ return None+ return str(tree)diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex 49b6249f4a9..8f4e363f8ca 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -468,6 +468,9 @@ def _setup_worktree(repo_root: str | None = None, sync_base: bool = True,from hermes_cli.worktree_registry import record_worktree_reporecord_worktree_repo(repo_root)+ if retain_db is not None: # a --tui -w tree: a resume may recreate it once quit removed it (N8)+ from hermes_cli.tui_worktree_resume import record_tui_worktree+ record_tui_worktree({"path": str(wt_path), "branch": branch_name, "repo_root": repo_root})_cprint(f"\033[32m✓ Worktree created:\033[0m {wt_path}")print(f" Branch: {branch_name}")print(f" Base: {base_label}")diff --git a/tests/hermes_cli/test_tui_worktree_resume_recreate.py b/tests/hermes_cli/test_tui_worktree_resume_recreate.pynew file mode 100644index 00000000000..128b2bdbad2--- /dev/null+++ b/tests/hermes_cli/test_tui_worktree_resume_recreate.py@@ -0,0 +1,149 @@+"""N8 review 2.2: quitting a clean ``hermes --tui -w`` session that had a conversation removes its+tree and branch, but the session's policy froze that cwd, so a later resume had every turn refused+``workspace_unavailable``. A resume (``--tui --resume``, ``-c``, classic CLI; all go through+``_resolve_chat_session_args``) now recreates a missing tree the ``--tui -w`` launcher created, at+the same path, before attaching. Other missing directories are never created."""+import json+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++GIT = ['git', '-c', 'user.name=Test', '-c', '[email protected]']+++def _repo(tmp_path):+ repo = tmp_path / 'repo'+ subprocess.run(['git', 'init', '-q', '-b', 'main', str(repo)], check=True)+ (repo / '.gitignore').write_text('.worktrees/\n')+ subprocess.run([*GIT, '-C', str(repo), 'add', '.gitignore'], check=True)+ subprocess.run([*GIT, '-C', str(repo), 'commit', '-qm', 'fixture'], check=True)+ return repo+++def _branches(repo):+ return subprocess.run(['git', '-C', str(repo), 'branch', '--format=%(refname:short)'],+ capture_output=True, text=True, check=True).stdout.split()+++def _quit_clean_session_with_history(tmp_path, monkeypatch):+ """``hermes --tui -w``, one user + assistant exchange, ``/quit`` (row ended ``tui_shutdown``)."""+ from hermes_cli import main_tui_launch+ from hermes_cli.worktree_ops import _setup_worktree+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB++ repo = _repo(tmp_path)+ monkeypatch.chdir(repo)+ monkeypatch.setenv('HERMES_PYTHON', sys.executable)+ wt_info = _setup_worktree(str(repo), sync_base=False, retain_db=get_hermes_home() / 'state.db')+ monkeypatch.setattr(main_tui_launch, '_setup_tui_worktree', lambda: wt_info)+ monkeypatch.setattr(main_tui_launch, '_make_tui_argv', lambda *_: (['node'], Path('.')))+ monkeypatch.setattr(main_tui_launch, '_print_tui_exit_summary', lambda *_: None)++ def ink(_argv, cwd=None, env=None):+ db = SessionDB(db_path=get_hermes_home() / 'state.db')+ db.create_session('tui-wt', 'tui', cwd=env['HERMES_TUI_CWD'])+ db.append_message('tui-wt', 'user', 'hello')+ db.append_message('tui-wt', 'assistant', 'hi')+ db.end_session('tui-wt', 'tui_shutdown')+ db.close()+ Path(env['HERMES_TUI_ACTIVE_SESSION_FILE']).write_text(json.dumps({'session_id': 'tui-wt'}))+ return 0++ monkeypatch.setattr(main_tui_launch.subprocess, 'call', ink)+ with pytest.raises(SystemExit):+ main_tui_launch._launch_tui(worktree=True)+ tree = Path(wt_info['path'])+ assert not tree.exists(), 'precondition: the clean idle tree is removed on quit (N8)'+ return repo, tree, wt_info+++def _resume(session_id, **extra):+ from hermes_cli import main as m+ args = SimpleNamespace(resume=session_id, continue_last=None, in_dir=None, worktree=False,+ no_restore_cwd=False, create_if_missing=False, **extra)+ m._resolve_chat_session_args(args, use_tui=True)+ return args+++def _turn_runs_in(cwd):+ """The owner's readiness gate a resumed turn passes through (``policy_scope``)."""+ from gateway.session_policy import policy_scope+ from hermes_state_runtime import RuntimeStoreError+ try:+ with policy_scope(SimpleNamespace(cwd=str(cwd))):+ pass+ except RuntimeStoreError as exc:+ return str(exc) != 'workspace_unavailable'+ except Exception: # health: allow BLE001 -- past the readiness gate; the stub policy is incomplete+ return True+ return True++[email protected]('no_restore_cwd', [False, True])+def test_resume_recreates_the_removed_tui_worktree_so_turns_run(tmp_path, monkeypatch, no_restore_cwd):+ repo, tree, wt_info = _quit_clean_session_with_history(tmp_path, monkeypatch)+ monkeypatch.chdir(tmp_path)+ from hermes_cli import main as m+ args = SimpleNamespace(resume='tui-wt', continue_last=None, in_dir=None, worktree=False,+ no_restore_cwd=no_restore_cwd, create_if_missing=False)+ m._resolve_chat_session_args(args, use_tui=True)+ assert tree.is_dir(), ('quit removed the resumable session\'s worktree; the resumed session\'s '+ 'turns are refused workspace_unavailable')+ assert _turn_runs_in(tree)+ assert wt_info['branch'] in _branches(repo)+ head = subprocess.run(['git', '-C', str(tree), 'rev-parse', '--abbrev-ref', 'HEAD'],+ capture_output=True, text=True, check=True).stdout.strip()+ assert head == wt_info['branch']+ if not no_restore_cwd:+ assert Path.cwd().resolve() == tree.resolve()+++def test_resume_reuses_the_surviving_branch(tmp_path, monkeypatch):+ """A tree removed while its branch survived comes back on that branch, at its commit."""+ from hermes_cli.worktree_ops import _setup_worktree+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB++ repo = _repo(tmp_path)+ monkeypatch.chdir(repo)+ wt_info = _setup_worktree(str(repo), sync_base=False, retain_db=get_hermes_home() / 'state.db')+ tree = Path(wt_info['path'])+ (tree / 'f.txt').write_text('work')+ subprocess.run([*GIT, '-C', str(tree), 'add', 'f.txt'], check=True)+ subprocess.run([*GIT, '-C', str(tree), 'commit', '-qm', 'work'], check=True)+ tip = subprocess.run(['git', '-C', str(tree), 'rev-parse', 'HEAD'], capture_output=True, text=True,+ check=True).stdout.strip()+ db = SessionDB(db_path=get_hermes_home() / 'state.db')+ db.create_session('tui-wt', 'tui', cwd=str(tree))+ db.append_message('tui-wt', 'user', 'hello')+ db.close()+ subprocess.run(['git', '-C', str(repo), 'worktree', 'remove', '--force', '--force', str(tree)], check=True)+ assert not tree.exists() and wt_info['branch'] in _branches(repo)++ _resume('tui-wt')+ assert (tree / 'f.txt').read_text() == 'work'+ assert subprocess.run(['git', '-C', str(tree), 'rev-parse', 'HEAD'], capture_output=True, text=True,+ check=True).stdout.strip() == tip+++def test_resume_never_creates_a_missing_dir_the_launcher_did_not_make(tmp_path, monkeypatch):+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB++ repo = _repo(tmp_path)+ foreign = repo / '.worktrees' / 'hermes-deadbeef' # looks like ours; no launcher record+ db = SessionDB(db_path=get_hermes_home() / 'state.db')+ db.create_session('other', 'tui', cwd=str(foreign))+ db.append_message('other', 'user', 'hello')+ db.create_session('plain', 'tui', cwd=str(tmp_path / 'gone'))+ db.append_message('plain', 'user', 'hello')+ db.close()+ monkeypatch.chdir(tmp_path)+ _resume('other')+ _resume('plain')+ assert not foreign.exists()+ assert not (tmp_path / 'gone').exists()diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.mdindex bf448e96865..0c1bc757fd4 100644--- a/website/docs/user-guide/cli.md+++ b/website/docs/user-guide/cli.md@@ -63,10 +63,20 @@ hermes -w -z "Fix issue #123" # Single query in worktree`hermes -w` sessions create disposable worktrees under `<repo>/.worktrees/`.With `hermes --tui -w`, closing the terminal detaches from the gateway-owned-session. A clean worktree with no turn still queued or running is removed with-its branch on quit. One with uncommitted changes or unpushed commits, or with a-turn the gateway is still running there, is retained, and resuming the session-uses the same working directory.+session. A clean worktree is removed with its branch on quit unless something+still needs it. It is retained when it has uncommitted changes or unpushed+commits, when the gateway still has a turn queued or running there, when a+session in it has an active `/loop`, `/heartbeat` or `/goal`, when an enabled+cron job runs in it or is bound to such a session, or when another viewer (a+Desktop window, say) still holds that session. Resuming a session uses its+working directory: if quit removed the worktree, `hermes --tui --resume <id>`,+`hermes --tui -c` and the classic `hermes --resume`/`-c` recreate it at the same+path before attaching (on its branch if that still exists, else on a new branch+of the same name from the repo's current `HEAD`). Only worktrees that+`hermes --tui -w` itself created are recreated. The quit-time check reads the+session store and then removes the tree; a viewer that attaches and submits in+the moment between the two is not seen, so that turn can find its directory+gone.A sweep runs automatically at `hermes -w` startup and every 6 hours from thecron ticker: idle clean+merged trees are removed, and idle trees withuncommitted changes or unpushed commits are **archived, then removed**