Skip to content

The agent that grows with you

fix(cli): a classic -w session gets its clean tree back on resume

kshitijk4poor26409f994c6b
diff --git a/cli.py b/cli.py
index 73d015f08de..dbb48dad3a7 100644
--- a/cli.py
+++ b/cli.py
@@ -1639,7 +1639,8 @@ def _start_worktree_setup(list_tools, list_toolsets, worktree, w):
def _create_worktree() -> None:
try:
- _wt_result["info"] = _setup_worktree(sync_base=_sync_base)
+ # The session freezes this cwd: recorded so a resume recreates the tree quit removed (N8).
+ _wt_result["info"] = _setup_worktree(sync_base=_sync_base, retain_db=get_hermes_home() / "state.db")
except Exception:
logger.debug("worktree setup failed", exc_info=True)
_wt_result["info"] = None
diff --git a/hermes_cli/main_resume_args.py b/hermes_cli/main_resume_args.py
index 81ce3cb76ba..18257341db4 100644
--- a/hermes_cli/main_resume_args.py
+++ b/hermes_cli/main_resume_args.py
@@ -25,15 +25,29 @@ def import_foreign_resume(args) -> None:
args.resume = _imported_id
+def _frozen_cwd(db, session_id) -> str:
+ """The cwd the owner runs *session_id*'s tools in (its local policy), or "" without one. The
+ row's cwd is main's stamp, which for a classic ``-w`` session is the repo root, not the tree."""
+ import sqlite3
+
+ from hermes_state_local import local_receipt
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ return str(local_receipt(db, session_id)["policy"].get("cwd") or "").strip()
+ except (RuntimeStoreError, KeyError, AttributeError, sqlite3.Error): # no readable policy: use the row's cwd
+ return ""
+
+
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)."""
+ """A resumed session whose frozen cwd is a ``-w`` / ``--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 = ""
from hermes_cli.main import _session_db
with _session_db() as db: # a store error is swallowed: nothing to recreate
- cwd = ((db.get_session(args.resume) or {}).get("cwd") or "").strip()
+ cwd = (_frozen_cwd(db, args.resume)
+ or ((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
diff --git a/hermes_cli/tui_worktree_resume.py b/hermes_cli/tui_worktree_resume.py
index b9dd9d05290..57f10bcb90b 100644
--- a/hermes_cli/tui_worktree_resume.py
+++ b/hermes_cli/tui_worktree_resume.py
@@ -42,8 +42,8 @@ def _read() -> dict:
def record_tui_worktree(wt_info: dict) -> None:
- """Remember a tree the ``--tui -w`` launcher created, or a classic ``/worktree new`` moved its
- gateway session into. Never raises."""
+ """Remember a tree the ``-w`` / ``--tui -w`` launcher created, or a classic ``/worktree new``
+ moved its gateway session into. Never raises."""
try:
from hermes_cli.auth import _file_lock
from utils import atomic_json_write
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index 8f4e363f8ca..d23d5d1cc5f 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -421,8 +421,10 @@ def _setup_worktree(repo_root: str | None = None, sync_base: bool = True,
*sync_base* branches from the fetched remote tip (``_resolve_worktree_base``), else local
HEAD. *name* replaces the random ``hermes-<id>``; named trees lack the ``hermes-`` prefix so
- the pruner ages them on its slower schedule. *retain_db* (``--tui -w``) names the profile
- store in the lock: the tree outlives its launcher while a session there can resume in it.
+ the pruner ages them on its slower schedule. *retain_db* (``-w``, ``--tui -w``) records the tree
+ for resume and names the profile store in the lock. A ``--tui -w`` tree outlives its launcher
+ while a session there can resume in it; a classic ``-w`` row's cwd is the repo root, so its
+ reaped clean tree is recreated on resume instead.
Set ``worktree_sync: false`` in config to branch from local ``HEAD`` (the pre-#10760-followup behavior).
"""
@@ -468,7 +470,7 @@ def _setup_worktree(repo_root: str | None = None, sync_base: bool = True,
from hermes_cli.worktree_registry import record_worktree_repo
record_worktree_repo(repo_root)
- if retain_db is not None: # a --tui -w tree: a resume may recreate it once quit removed it (N8)
+ if retain_db is not None: # a -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}")
@@ -798,7 +800,7 @@ def _worktree_branch_pushed_exact(
return False
-# ``hermes pid=<pid>`` (classic launch), ``hermes pid=<pid> db=<state.db>`` (``--tui -w`` launch)
+# ``hermes pid=<pid>`` (``/worktree new``), ``hermes pid=<pid> db=<state.db>`` (``-w`` / ``--tui -w`` launch)
# and ``hermes session=<id> db=<state.db>`` (re-lock when the TUI exits). Read raw from the admin
# dir: plain ``list --porcelain`` C-quotes a reason holding a backslash, a quote, a control or a
# non-ASCII byte (every Windows path), and the ``db=`` path would never parse.
@@ -956,11 +958,13 @@ def _worktree_lock_is_live(repo_root: str, worktree_path: str, timeout: int = 10
"""Lock state: ``"live"`` (owning pid runs / a resumable session works in the tree),
``"dead"`` (pid and sessions 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. A ``--tui -w`` tree
- also names its profile's ``state.db`` from creation, so a launcher killed with its terminal
- (SIGHUP skips the exit re-lock) still keeps the tree. Fails SAFE toward "live", including
- a ``hermes`` reason this version cannot parse.
+ A Hermes tree locks with reason ``hermes pid=<pid>``; ``worktree remove --force`` refuses
+ locked trees, so a crashed session's lock would keep its tree forever. A ``-w`` tree
+ also names its profile's ``state.db`` from creation, so a ``--tui -w`` launcher killed with
+ its terminal (SIGHUP skips the exit re-lock) still keeps the tree while a resumable session's
+ row cwd is inside it. A classic ``-w`` row's cwd is the repo root: its tree is only recorded,
+ and a reaped clean one is recreated on resume. Fails SAFE toward "live", including a
+ ``hermes`` reason this version cannot parse.
"""
try:
found, reason = _worktree_lock_reason(repo_root, worktree_path, timeout)
diff --git a/tests/hermes_cli/test_tui_worktree_resume_recreate.py b/tests/hermes_cli/test_tui_worktree_resume_recreate.py
index 128b2bdbad2..1d0adf4225e 100644
--- a/tests/hermes_cli/test_tui_worktree_resume_recreate.py
+++ b/tests/hermes_cli/test_tui_worktree_resume_recreate.py
@@ -147,3 +147,82 @@ def test_resume_never_creates_a_missing_dir_the_launcher_did_not_make(tmp_path,
_resume('plain')
assert not foreign.exists()
assert not (tmp_path / 'gone').exists()
+
+
+def test_a_store_error_reading_the_policy_falls_back_to_the_row_cwd(tmp_path, monkeypatch):
+ """The frozen-policy read failing on the store (e.g. no ``state_meta`` table) still recreates
+ the tree from the row's cwd instead of skipping the resume step."""
+ import sqlite3
+
+ import hermes_state_local
+ 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)
+ tree = Path(_setup_worktree(str(repo), sync_base=False, retain_db=get_hermes_home() / 'state.db')['path'])
+ 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)
+
+ def broken(*_a, **_k):
+ raise sqlite3.OperationalError('no such table: state_meta')
+
+ monkeypatch.setattr(hermes_state_local, 'local_receipt', broken)
+ monkeypatch.chdir(tmp_path)
+ _resume('tui-wt')
+ assert tree.is_dir()
+
+
+
+async def test_resume_recreates_the_removed_classic_worktree(tmp_path, monkeypatch):
+ """Classic ``hermes -w`` runs its session's tools in the tree (frozen policy cwd) while the row
+ keeps main's stamp, the repo root. Quit removes the clean tree; ``-c`` now gets it back."""
+ import cli
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_local import create_local_session
+ from hermes_cli import main as m
+
+ repo = _repo(tmp_path)
+ monkeypatch.chdir(repo)
+ monkeypatch.setitem(cli.CLI_CONFIG, 'worktree_sync', False)
+ monkeypatch.setitem(sys.modules, 'model_tools', SimpleNamespace(get_tool_definitions=lambda **_: []))
+ monkeypatch.setattr(cli.atexit, 'register', lambda *_a, **_k: None)
+ monkeypatch.setattr(cli, '_prune_stale_worktrees', lambda *_: None)
+ monkeypatch.setattr(cli, '_maintain_pack_health', lambda *_: None)
+ monkeypatch.setattr(cli, '_active_worktree', None)
+ monkeypatch.setenv('TERMINAL_CWD', str(tmp_path))
+ wt_info = cli._start_worktree_setup(False, False, True, False)() # the -w launcher
+ tree = Path(wt_info['path'])
+
+ from gateway import run
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ try:
+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='owner')
+ actor = AuthorityConnection(authority, object(), {'user_id': 'human', 'profile_id': 'fixture'}).actor
+ # What GatewaySessionStore.create sends for -w: TERMINAL_CWD (the tree), row stamp os.getcwd().
+ ref = create_local_session(authority, actor, {'request_id': 'w', 'source': 'cli', 'cwd': str(tree),
+ 'row_cwd': str(repo), 'model': 'm', 'toolsets': []})
+ assert authority.db.get_session(ref.session_id)['cwd'] == str(repo)
+ cli._cleanup_worktree(wt_info) # quit
+ assert not tree.exists(), 'precondition: quit removes the clean tree'
+
+ monkeypatch.chdir(tmp_path)
+ args = SimpleNamespace(resume=ref.session_id, continue_last=None, in_dir=None, worktree=False,
+ no_restore_cwd=False, create_if_missing=False)
+ m._resolve_chat_session_args(args, use_tui=False)
+ assert tree.is_dir(), 'the resumed -w session\'s turns are refused workspace_unavailable'
+ assert _turn_runs_in(tree)
+ finally:
+ store.close_all_db_handles()