The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: keep a retained --tui -w worktree while its session is resumable
Teknium49771f7b2e30
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.pyindex 34a3b418d54..beae2a2b97e 100644--- a/hermes_cli/main_tui_launch.py+++ b/hermes_cli/main_tui_launch.py@@ -471,11 +471,19 @@ def _launch_tui(if code in {0, 130}:_print_tui_exit_summary(resume_session_id, active_session_file)finally:+ attached_session = _read_tui_active_session_file(active_session_file) or resume_session_idwith contextlib.suppress(OSError):os.unlink(active_session_file)if wt_info:# Quitting detaches a viewer; the gateway may still be executing in# this checkout and future resumes retain its frozen cwd.+ if attached_session:+ # The launch lock names this (exiting) pid; hand it to the session so a later+ # launch's stale prune keeps the tree while the session is resumable.+ from hermes_cli.config import get_hermes_home+ from hermes_cli.worktree_ops import _retain_worktree_for_session+ _retain_worktree_for_session(wt_info["repo_root"], wt_info["path"], attached_session,+ get_hermes_home() / "state.db")print(f"Worktree retained for this session: {wt_info['path']}", file=sys.stderr)# Exit code 42 = TUI requested an update. Relaunch as `hermes update`;diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.pyindex 864ba74f028..a2ced52bf06 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -787,11 +787,57 @@ def _worktree_branch_pushed_exact(return False+_RETAINED_LOCK_RE = re.compile(r"hermes session=(\S+) db=(.+)$")+++def _retain_worktree_for_session(repo_root: str, worktree_path: str, session_id: str, db_path) -> bool:+ """Re-lock a ``--tui -w`` tree its exiting launcher retains, naming the session that uses it.++ The launch lock's ``hermes pid=<pid>`` dies with the launcher, and the next launch's stale+ prune would then reap a clean tree whose session (its frozen cwd) is still resumable. The+ replacement lock stays live while that session can be resumed (``_retained_session_is_live``).+ """+ _git_quiet(["worktree", "unlock", worktree_path], repo_root, log="worktree unlock before retain failed")+ try:+ result = _git(["worktree", "lock", "--reason", f"hermes session={session_id} db={db_path}",+ worktree_path], repo_root)+ except (OSError, subprocess.SubprocessError) as exc:+ logger.debug("worktree retain lock failed for %s: %s", worktree_path, exc)+ return False+ return result.returncode == 0+++def _retained_session_is_live(session_id: str, db_path: str) -> bool:+ """Whether a retained tree's session is still resumable: its row exists with history or+ pending gateway work. A missing store means the profile is gone; unreadable fails SAFE (live)."""+ import sqlite3+ from urllib.parse import quote++ path = Path(db_path)+ if not path.is_file():+ return False+ try:+ conn = sqlite3.connect(f"file:{quote(str(path))}?mode=ro", uri=True, timeout=2)+ try:+ row = conn.execute(+ "SELECT 1 FROM sessions s WHERE s.id=? AND (s.message_count>0 OR EXISTS ("+ "SELECT 1 FROM session_admissions a WHERE a.target_session_id=s.id AND a.status!='terminal'))",+ (session_id,)).fetchone()+ finally:+ conn.close()+ except sqlite3.Error as exc:+ logger.debug("retained worktree session check failed (%s); keeping tree", exc)+ return True+ return row is not None++def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10):- """Lock state: ``"live"`` (owning pid runs), ``"dead"`` (pid gone / non-hermes reason), None (unlocked).+ """Lock state: ``"live"`` (owning pid runs / retained session resumable), ``"dead"`` (pid or+ session gone / non-hermes reason), None (unlocked).``hermes -w`` locks with reason ``hermes pid=<pid>``; ``worktree remove --force`` refuses- locked trees, so a crashed session's lock would keep its tree forever. Fails SAFE toward "live".+ locked trees, so a crashed session's lock would keep its tree forever. A tree the TUI+ retained on exit is locked ``hermes session=<id> db=<state.db>`` instead. Fails SAFE toward "live"."""try:listing = _git_out(["worktree", "list", "--porcelain"], repo_root, timeout=timeout)@@ -812,6 +858,8 @@ def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10if current != target:continuereason = line[len("locked"):].strip()+ if retained := _RETAINED_LOCK_RE.search(reason):+ return "live" if _retained_session_is_live(*retained.groups()) else "dead"m = re.search(r"hermes pid=(\d+)", reason)if not m:# A foreign lock here is a leftover; the age/dirty/unpushed gates already passed.diff --git a/tests/hermes_cli/test_gateway_launch_lifetime.py b/tests/hermes_cli/test_gateway_launch_lifetime.pyindex 9e01c09fa06..21e89576533 100644--- a/tests/hermes_cli/test_gateway_launch_lifetime.py+++ b/tests/hermes_cli/test_gateway_launch_lifetime.py@@ -27,3 +27,53 @@ def test_tui_detach_preserves_real_clean_worktree(tmp_path, monkeypatch):assert exited.value.code == 0assert checkout.is_dir()assert (checkout / '.git').is_file()++[email protected]('resumable', [True, False])+def test_retained_tui_worktree_survives_stale_prune_while_its_session_resumes(tmp_path, monkeypatch, resumable):+ """The launch lock names the exiting launcher's pid; once it is gone a later launch's 24 h+ prune must still keep a clean retained tree whose session can be resumed (and only then)."""+ import json+ import os+ import time++ from hermes_cli import main_tui_launch+ from hermes_cli.worktree_ops import _prune_stale_worktrees, _setup_worktree+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB++ repo = tmp_path / 'repo'+ git = ['git', '-c', 'user.name=Test', '-c', '[email protected]']+ 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)+ monkeypatch.chdir(repo)+ monkeypatch.setenv('HERMES_PYTHON', sys.executable)+ wt_info = _setup_worktree(str(repo), sync_base=False)+ # The real launcher exits with the TUI, so its `hermes pid=<pid>` launch lock is dead by the next launch.+ subprocess.run(['git', '-C', str(repo), 'worktree', 'unlock', wt_info['path']], check=True)+ subprocess.run(['git', '-C', str(repo), 'worktree', 'lock', '--reason', 'hermes pid=999999999',+ wt_info['path']], check=True)+ 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'])+ if resumable:+ db.append_message('tui-wt', 'user', 'keep my checkout')+ db.close()+ Path(env['HERMES_TUI_ACTIVE_SESSION_FILE']).write_text(json.dumps({'session_id': 'tui-wt'}))+ ink.checkout = Path(env['HERMES_TUI_CWD'])+ return 0++ monkeypatch.setattr(main_tui_launch.subprocess, 'call', ink)+ with pytest.raises(SystemExit):+ main_tui_launch._launch_tui(worktree=True)+ # The launcher is gone; the next launch runs its prune a day later.+ old = time.time() - 25 * 3600+ os.utime(ink.checkout, (old, old))+ _prune_stale_worktrees(str(repo))+ assert ink.checkout.is_dir() is resumable