Skip to content

The agent that grows with you

fix(tui): `--tui -w` keeps a clean tree the gateway still schedules work in

Teknium3f7393ca6ee9
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.py
index d3780b85e12..8a928a03b3c 100644
--- a/hermes_cli/main_tui_launch.py
+++ b/hermes_cli/main_tui_launch.py
@@ -401,21 +401,27 @@ 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.
+ detaches the viewer), still schedules work for one (an active loop, heartbeat or goal
+ continuation, or a cron job bound to it), another viewer still holds one, or 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
+ from hermes_cli.worktree_ops import _retained_tree_is_live, _tree_still_served
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):
+ db_path = str(get_hermes_home() / "state.db")
+ if _retained_tree_is_live(db_path, path, pending_only=True):
return False
if _still_in_use(path):
return False
+ # After the grace above: a legacy sidecar stamps its rows ``tui_shutdown`` as it exits.
+ if _tree_still_served(db_path, path):
+ return False
from cli import _cleanup_worktree
_cleanup_worktree(wt_info)
except Exception:
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index 78e22160b8a..49b6249f4a9 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -819,6 +819,84 @@ def _retain_worktree_for_session(repo_root: str, worktree_path: str, session_id:
return result.returncode == 0
+def _inside_tree(worktree_path: str):
+ """``inside(path) -> 0/1``: *path* is the tree or under it (native path identity: Windows is
+ case-insensitive, either separator; the tree's own spelling and its resolved one)."""
+ def key(value) -> str:
+ return os.path.normcase(str(value)).replace("\\", "/").rstrip("/")
+
+ roots = {key(Path(worktree_path)), key(Path(worktree_path).resolve())}
+
+ def inside(cwd) -> int:
+ return int(bool(cwd) and any(key(cwd) == r or key(cwd).startswith(r + "/") for r in roots))
+ return inside
+
+
+# The gateway's own records that it will still act in a session after its last viewer quits:
+# an active /loop, /heartbeat or /goal (its continuation) row (``hermes_cli.loops`` / ``heartbeat`` /
+# ``goals``, keyed by the stored session id, status ``active`` when the field is absent), and a row
+# no viewer close ended: Ink's exit detaches with ``tui_shutdown`` and the owner ends the idle row
+# only once no other viewer holds it (``gateway/session_viewer_close.py``).
+_SERVED_TREE_SQL = (
+ "SELECT 1 FROM sessions s WHERE hermes_inside_tree(s.cwd) AND (s.ended_at IS NULL OR EXISTS ("
+ "SELECT 1 FROM state_meta m WHERE m.key IN ('loop:'||s.id, 'heartbeat:'||s.id, 'goal:'||s.id) "
+ "AND (json_valid(m.value)=0 OR COALESCE(json_extract(m.value,'$.status'),'active')='active'))) LIMIT 1")
+
+
+def _tree_still_served(db_path: str, worktree_path: str) -> Optional[str]:
+ """Why the gateway still needs a ``--tui -w`` tree the launcher is about to remove, or None.
+
+ Beyond pending admissions (``_retained_tree_is_live(pending_only=True)``): scheduled work for a
+ session inside it (an active loop, heartbeat or goal continuation), another viewer still holding
+ such a session (its row was not ended by the quit), or an enabled cron job that runs in the tree
+ (``workdir``) or is bound to such a session's local chat. Reads only; unreadable fails SAFE."""
+ import sqlite3
+ from urllib.parse import quote
+
+ path = Path(db_path)
+ chats: set = set()
+ if path.is_file():
+ try:
+ conn = sqlite3.connect(f"file:{quote(str(path))}?mode=ro", uri=True, timeout=2)
+ try:
+ conn.create_function("hermes_inside_tree", 1, _inside_tree(worktree_path), deterministic=True)
+ if conn.execute(_SERVED_TREE_SQL).fetchone():
+ return "session"
+ chats = {row[0] for row in conn.execute(
+ "SELECT chat_id FROM sessions WHERE hermes_inside_tree(cwd) AND chat_id IS NOT NULL")}
+ finally:
+ conn.close()
+ except sqlite3.Error as exc:
+ logger.debug("retained worktree serve check failed (%s); keeping tree", exc)
+ return "unreadable"
+ return "cron" if _cron_bound_to_tree(worktree_path, chats) else None
+
+
+def _cron_bound_to_tree(worktree_path: str, chats: set) -> bool:
+ """An enabled, non-terminal cron job whose ``workdir`` is inside the tree, or whose origin is
+ the local chat of a session there. Reads ``jobs.json`` directly (``load_jobs`` may repair-write);
+ an unreadable store fails SAFE."""
+ try:
+ from cron.jobs import _current_cron_store, _parse_jobs_file, is_job_runnable, is_terminal_job
+ jobs_file = _current_cron_store().jobs_file
+ if not jobs_file.exists():
+ return False
+ data, _ = _parse_jobs_file(jobs_file)
+ except Exception as exc: # health: allow BLE001 -- an unreadable cron store keeps the tree (fail safe)
+ logger.debug("cron store unreadable (%s); keeping tree", exc)
+ return True
+ jobs = data.get("jobs") if isinstance(data, dict) else data
+ inside = _inside_tree(worktree_path)
+ for job in jobs if isinstance(jobs, list) else ():
+ if not isinstance(job, dict) or not is_job_runnable(job) or is_terminal_job(job):
+ continue
+ origin = job.get("origin") if isinstance(job.get("origin"), dict) else {}
+ if inside(job.get("workdir")) or (
+ str(origin.get("platform") or "").lower() == "local" and str(origin.get("chat_id") or "") in chats):
+ return True
+ return False
+
+
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 (*pending_only*: pending work alone, the exiting
@@ -830,13 +908,7 @@ def _retained_tree_is_live(db_path: str, worktree_path: str, *, pending_only: bo
path = Path(db_path)
if not path.is_file():
return False
- def key(value) -> str: # native path identity: Windows is case-insensitive, either separator
- return os.path.normcase(str(value)).replace("\\", "/").rstrip("/")
-
- roots = {key(Path(worktree_path)), key(Path(worktree_path).resolve())}
-
- def inside(cwd) -> int:
- return int(bool(cwd) and any(key(cwd) == r or key(cwd).startswith(r + "/") for r in roots))
+ inside = _inside_tree(worktree_path)
try:
conn = sqlite3.connect(f"file:{quote(str(path))}?mode=ro", uri=True, timeout=2)
try:
diff --git a/tests/hermes_cli/test_tui_worktree_clean_quit.py b/tests/hermes_cli/test_tui_worktree_clean_quit.py
index 77475b158c9..8741642f576 100644
--- a/tests/hermes_cli/test_tui_worktree_clean_quit.py
+++ b/tests/hermes_cli/test_tui_worktree_clean_quit.py
@@ -46,6 +46,10 @@ def test_tui_worktree_quit_removes_only_a_clean_idle_tree(tmp_path, monkeypatch,
db.create_session('tui-wt', 'tui', cwd=env['HERMES_TUI_CWD'])
if case != 'clean':
db.append_message('tui-wt', 'user', 'hello')
+ if case != 'pending_turn':
+ # Ink's exit detaches with ``tui_shutdown``; the owner ends the idle row once no other
+ # viewer holds it (gateway/session_viewer_close.py).
+ db.end_session('tui-wt', 'tui_shutdown')
db.close()
if case == 'pending_turn': # an accepted turn the gateway has not finished yet
conn = sqlite3.connect(db_path)
@@ -73,3 +77,93 @@ def test_tui_worktree_quit_removes_only_a_clean_idle_tree(tmp_path, monkeypatch,
assert wt_info['branch'] in _branches(repo)
if case == 'dirty':
assert (tree / 'work.txt').read_text() == 'uncommitted'
+
+
+def _quit_with(tmp_path, monkeypatch, prepare):
+ """Run ``hermes --tui -w`` whose Ink session ``prepare(db, cwd)`` shapes, then quit; the tree."""
+ 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', 'every 10m: run the tests')
+ prepare(db, env['HERMES_TUI_CWD'])
+ 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)
+ return Path(wt_info['path']), repo, wt_info
+
+
+def _scheduled(kind, status='active'):
+ """The gateway's own per-session automation row, as /loop, /heartbeat and /goal store it."""
+ import time
+ if kind == 'loop':
+ from hermes_cli.loops import LoopState
+ return LoopState(prompt='run the tests', interval_seconds=600, next_due_at=time.time() + 600,
+ status=status, route={'platform': 'local', 'chat_id': 'tui-wt'}).to_json()
+ if kind == 'heartbeat':
+ from hermes_cli.heartbeat import HeartbeatState
+ return HeartbeatState(prompt='check in', interval_seconds=600, status=status).to_json()
+ from hermes_cli.goals import GoalState
+ return GoalState(goal='ship it', status=status).to_json()
+
+
[email protected]('kind', ['loop', 'heartbeat', 'goal'])
+def test_quit_keeps_a_clean_tree_while_the_gateway_has_scheduled_work_for_its_session(tmp_path, monkeypatch, kind):
+ """N8 review F4: ``/loop`` / ``/heartbeat`` / an active ``/goal`` on the ``--tui -w`` session
+ keeps running on the gateway after the viewer quits; between ticks no admission is pending, and
+ removing the tree made the next tick run in a missing cwd (``workspace_unavailable``)."""
+ def prepare(db, _cwd):
+ db.set_meta(f'{kind}:tui-wt', _scheduled(kind))
+ db.end_session('tui-wt', 'tui_shutdown')
+ tree, repo, wt_info = _quit_with(tmp_path, monkeypatch, prepare)
+ assert tree.is_dir(), f'{kind}: tree removed while the gateway still schedules work in it'
+ assert wt_info['branch'] in _branches(repo)
+
+
[email protected]('kind', ['loop', 'heartbeat', 'goal'])
+def test_finished_scheduled_work_does_not_keep_the_tree(tmp_path, monkeypatch, kind):
+ def prepare(db, _cwd):
+ db.set_meta(f'{kind}:tui-wt', _scheduled(kind, status='cleared'))
+ db.end_session('tui-wt', 'tui_shutdown')
+ tree, repo, wt_info = _quit_with(tmp_path, monkeypatch, prepare)
+ assert not tree.exists() and wt_info['branch'] not in _branches(repo)
+
+
+def test_quit_keeps_the_tree_while_another_viewer_still_holds_the_session(tmp_path, monkeypatch):
+ """Ink's exit detaches with ``tui_shutdown``; the owner leaves the row open while another viewer
+ (a Desktop window on the same session) still holds it, and that viewer's next turn needs the cwd."""
+ tree, repo, wt_info = _quit_with(tmp_path, monkeypatch, lambda db, _cwd: None)
+ assert tree.is_dir()
+ assert wt_info['branch'] in _branches(repo)
+
+
[email protected]('bound', ['workdir', 'origin'])
+def test_quit_keeps_the_tree_while_a_cron_job_is_bound_to_it(tmp_path, monkeypatch, bound):
+ from cron import jobs
+
+ def prepare(db, cwd):
+ db.end_session('tui-wt', 'tui_shutdown')
+ db._execute_write(lambda conn: conn.execute("UPDATE sessions SET chat_id='local-chat' WHERE id='tui-wt'"))
+ if bound == 'workdir':
+ jobs.create_job('run the tests', 'every 10m', workdir=cwd)
+ else:
+ jobs.create_job('run the tests', 'every 10m', origin={'platform': 'local', 'chat_id': 'local-chat'})
+ tree, repo, wt_info = _quit_with(tmp_path, monkeypatch, prepare)
+ assert tree.is_dir(), f'cron {bound}: tree removed while a job still runs there'
+ assert wt_info['branch'] in _branches(repo)