The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): `hermes --tui -w` removes a clean worktree on quit again
Teknium1e55d1ca87d9
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.pyindex 164939511a1..d3780b85e12 100644--- a/hermes_cli/main_tui_launch.py+++ b/hermes_cli/main_tui_launch.py@@ -397,6 +397,33 @@ def _setup_tui_worktree() -> dict:return wt_info+def _remove_idle_clean_tui_worktree(wt_info: dict) -> bool:+ """Remove the ``--tui -w`` checkout on quit when nothing still needs it (N8) -> True if gone.++ Kept when the gateway has queued or started work for a session inside it (quitting only+ detaches the viewer), when another process still works in it, and by ``_cleanup_worktree``+ when it is dirty, holds unpushed commits or something no branch keeps.+ """+ from hermes_cli.config import get_hermes_home+ from hermes_cli.worktree_exit import _still_in_use+ from hermes_cli.worktree_ops import _retained_tree_is_live++ path = wt_info.get("path")+ if not path or not Path(path).is_dir():+ return False+ try:+ if _retained_tree_is_live(str(get_hermes_home() / "state.db"), path, pending_only=True):+ return False+ if _still_in_use(path):+ return False+ from cli import _cleanup_worktree+ _cleanup_worktree(wt_info)+ except Exception:+ logger.debug("TUI worktree cleanup failed; keeping %s", path, exc_info=True)+ return False+ return not Path(path).exists()++def _require_bypass_model(env: dict, model: Optional[str], resume_session_id: Optional[str]) -> None:"""A --safe-mode / --ignore-user-config session reads no profile default model, so the ownerrefuses its session.create without one (bare invalid_params). Say so before the TUI starts,@@ -550,6 +577,8 @@ def _launch_tui(from hermes_cli.worktree_exit import apply_exit_choiceif wt_info and apply_exit_choice(wt_info, print):wt_info = None # archived or discarded at the user's request+ if wt_info and _remove_idle_clean_tui_worktree(wt_info):+ wt_info = None # clean and idle: removed with its branch, as before the shared gatewayif 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/worktree_ops.py b/hermes_cli/worktree_ops.pyindex 337fedcf7cc..78e22160b8a 100644--- a/hermes_cli/worktree_ops.py+++ b/hermes_cli/worktree_ops.py@@ -819,10 +819,11 @@ def _retain_worktree_for_session(repo_root: str, worktree_path: str, session_id:return result.returncode == 0-def _retained_tree_is_live(db_path: str, worktree_path: str) -> bool:+def _retained_tree_is_live(db_path: str, worktree_path: str, *, pending_only: bool = False) -> bool:"""Whether a session that can still be resumed has its frozen cwd inside the retained tree:- a row with history or pending gateway work. A missing store means the profile is gone;- unreadable fails SAFE (live)."""+ a row with history or pending gateway work (*pending_only*: pending work alone, the exiting+ ``--tui -w`` launcher's "is the gateway still using it" check). A missing store means the+ profile is gone; unreadable fails SAFE (live)."""import sqlite3from urllib.parse import quote@@ -841,9 +842,10 @@ def _retained_tree_is_live(db_path: str, worktree_path: str) -> bool:try:conn.create_function("hermes_inside_tree", 1, inside, deterministic=True)row = conn.execute(- "SELECT 1 FROM sessions s WHERE hermes_inside_tree(s.cwd) AND (s.message_count>0 OR EXISTS ("- "SELECT 1 FROM session_admissions a WHERE a.target_session_id=s.id AND a.status!='terminal')) "- "LIMIT 1").fetchone()+ "SELECT 1 FROM sessions s WHERE hermes_inside_tree(s.cwd) AND ("+ + ("" if pending_only else "s.message_count>0 OR ")+ + "EXISTS (SELECT 1 FROM session_admissions a WHERE a.target_session_id=s.id "+ "AND a.status!='terminal')) LIMIT 1").fetchone()finally:conn.close()except sqlite3.Error as exc:diff --git a/tests/hermes_cli/test_gateway_launch_lifetime.py b/tests/hermes_cli/test_gateway_launch_lifetime.pyindex d0db5c0208f..d65daf6f89f 100644--- a/tests/hermes_cli/test_gateway_launch_lifetime.py+++ b/tests/hermes_cli/test_gateway_launch_lifetime.py@@ -6,27 +6,28 @@ import sysimport pytest-def test_tui_detach_preserves_real_clean_worktree(tmp_path, monkeypatch):- from hermes_cli import main_tui_launch- repo = tmp_path / 'repo'- repo.mkdir()- subprocess.run(['git', 'init', '-q', str(repo)], check=True)- subprocess.run(['git', '-C', str(repo), '-c', 'user.name=Test', '-c', '[email protected]',- 'commit', '--allow-empty', '-qm', 'fixture'], check=True)- checkout = tmp_path / 'worktree'- subprocess.run(['git', '-C', str(repo), 'worktree', 'add', '-qb', 'fixture-work', str(checkout)], check=True)- monkeypatch.chdir(repo)- monkeypatch.setenv('HERMES_PYTHON', sys.executable)- monkeypatch.setattr(main_tui_launch, '_setup_tui_worktree', lambda: {- 'path': str(checkout), 'repo_root': str(repo), 'branch': 'fixture-work'})- monkeypatch.setattr(main_tui_launch, '_make_tui_argv', lambda *_: (['node'], Path('.')))- monkeypatch.setattr(main_tui_launch.subprocess, 'call', lambda *_, **__: 0)- monkeypatch.setattr(main_tui_launch, '_print_tui_exit_summary', lambda *_: None)- with pytest.raises(SystemExit) as exited:- main_tui_launch._launch_tui(worktree=True)- assert exited.value.code == 0- assert checkout.is_dir()- assert (checkout / '.git').is_file()+def _pending_turn(db_path, sid, status='queued'):+ """An accepted turn the gateway still owes this session: quitting the viewer keeps its tree (N8)."""+ import sqlite3+ conn = sqlite3.connect(db_path)+ try:+ conn.execute(+ "INSERT INTO session_admissions(admission_id,request_id,principal_id,target_session_id,lineage_json,"+ "payload_json,payload_digest,intent,status,outcome,owner_epoch,generation) "+ "VALUES(?,?,'p',?,'[]','{}','d','queue',?,NULL,1,1)", (f'adm-{sid}', f'req-{sid}', sid, status))+ conn.commit()+ finally:+ conn.close()+++def _finish_turns(db_path):+ import sqlite3+ conn = sqlite3.connect(db_path)+ try:+ conn.execute("UPDATE session_admissions SET status='terminal', outcome='completed'")+ conn.commit()+ finally:+ conn.close()@pytest.mark.parametrize('resumable', [True, False])@@ -65,6 +66,7 @@ def test_retained_tui_worktree_survives_stale_prune_while_its_session_resumes(tmif resumable:db.append_message('tui-wt', 'user', 'keep my checkout')db.close()+ _pending_turn(get_hermes_home() / 'state.db', 'tui-wt')Path(env['HERMES_TUI_ACTIVE_SESSION_FILE']).write_text(json.dumps({'session_id': 'tui-wt'}))ink.checkout = Path(env['HERMES_TUI_CWD'])return 0@@ -72,7 +74,8 @@ def test_retained_tui_worktree_survives_stale_prune_while_its_session_resumes(tmmonkeypatch.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.+ # The turn finished and the launcher is gone; the next launch runs its prune a day later.+ _finish_turns(get_hermes_home() / 'state.db')old = time.time() - 25 * 3600os.utime(ink.checkout, (old, old))_prune_stale_worktrees(str(repo))@@ -118,6 +121,7 @@ def test_retained_tui_worktree_kept_while_any_session_in_it_resumes(tmp_path, moif case == 'after_new': # /new: the attached session has nothing sent yetdb.create_session(attached := 'tui-b', 'tui', cwd=env['HERMES_TUI_CWD'])db.close()+ _pending_turn(get_hermes_home() / 'state.db', attached)Path(env['HERMES_TUI_ACTIVE_SESSION_FILE']).write_text(json.dumps({'session_id': attached}))ink.checkout = Path(env['HERMES_TUI_CWD'])return 0@@ -132,6 +136,7 @@ def test_retained_tui_worktree_kept_while_any_session_in_it_resumes(tmp_path, mosubprocess.run(['git', '-C', str(repo), 'worktree', 'unlock', str(ink.checkout)], check=True)subprocess.run(['git', '-C', str(repo), 'worktree', 'lock', '--reason',re.sub(r'pid=\d+', 'pid=999999999', reason), str(ink.checkout)], check=True)+ _finish_turns(get_hermes_home() / 'state.db')old = time.time() - 25 * 3600os.utime(ink.checkout, (old, old))worktree_ops._prune_stale_worktrees(str(repo))diff --git a/tests/hermes_cli/test_tui_worktree_clean_quit.py b/tests/hermes_cli/test_tui_worktree_clean_quit.pynew file mode 100644index 00000000000..77475b158c9--- /dev/null+++ b/tests/hermes_cli/test_tui_worktree_clean_quit.py@@ -0,0 +1,75 @@+"""N8: quitting ``hermes --tui -w`` removes a clean worktree (and its branch), as ``main`` did+before #106742; a dirty one, or one the gateway still has queued/started work in, is kept."""+import json+import sqlite3+import subprocess+import sys+from pathlib import Path++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()++[email protected]('case', ['clean', 'clean_with_history', 'dirty', 'pending_turn'])+def test_tui_worktree_quit_removes_only_a_clean_idle_tree(tmp_path, monkeypatch, case):+ 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_path = get_hermes_home() / 'state.db'+ db = SessionDB(db_path=db_path)+ db.create_session('tui-wt', 'tui', cwd=env['HERMES_TUI_CWD'])+ if case != 'clean':+ db.append_message('tui-wt', 'user', 'hello')+ db.close()+ if case == 'pending_turn': # an accepted turn the gateway has not finished yet+ conn = sqlite3.connect(db_path)+ conn.execute(+ "INSERT INTO session_admissions(admission_id,request_id,principal_id,target_session_id,"+ "lineage_json,payload_json,payload_digest,intent,status,outcome,owner_epoch,generation) "+ "VALUES('adm-1','req-1','p','tui-wt','[]','{}','d','queue','queued',NULL,1,1)")+ conn.commit()+ conn.close()+ if case == 'dirty':+ (Path(env['HERMES_TUI_CWD']) / 'work.txt').write_text('uncommitted')+ 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) as exited:+ main_tui_launch._launch_tui(worktree=True)+ assert exited.value.code == 0+ tree = Path(wt_info['path'])+ if case in ('clean', 'clean_with_history'):+ assert not tree.exists()+ assert wt_info['branch'] not in _branches(repo)+ else:+ assert tree.is_dir()+ assert wt_info['branch'] in _branches(repo)+ if case == 'dirty':+ assert (tree / 'work.txt').read_text() == 'uncommitted'diff --git a/website/docs/user-guide/cli.md b/website/docs/user-guide/cli.mdindex 3afc1a35d1f..bf448e96865 100644--- a/website/docs/user-guide/cli.md+++ b/website/docs/user-guide/cli.md@@ -63,9 +63,10 @@ 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. 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.+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.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**