The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(serve): hold work admission through cooperative retirement
brooklyn!98745df3b9cb
diff --git a/cron/bot_chat_delivery.py b/cron/bot_chat_delivery.pyindex 90d08037847..1cc21a3ce2c 100644--- a/cron/bot_chat_delivery.py+++ b/cron/bot_chat_delivery.py@@ -68,10 +68,13 @@ def defer(key: str, job: dict, content: str, profile: str, home: Path) -> dict:def drain(root: Path | None = None) -> None:"""Serialize drains across processes without holding the producer lock."""+ from hermes_cli.backend_retirement import retirement+root = root if root is not None else _root()- if root.is_dir():- with _FileLock(root / ".drain.lock"):- _drain(root)+ with retirement.work() as admitted:+ if admitted and root.is_dir():+ with _FileLock(root / ".drain.lock"):+ _drain(root)def _drain(root: Path) -> None:@@ -118,17 +121,27 @@ def drain_in_background() -> None:root = home / "cron" / "bot_chat_pending"if not root.is_dir():return+ from hermes_cli.backend_retirement import retirement+with _running_lock:- if home in _running:+ if home in _running or not retirement.acquire():return_running.add(home)+ def release():+ with _running_lock:+ _running.discard(home)+ retirement.release()+def run():try:drain(root)finally:- with _running_lock:- _running.discard(home)+ release()- threading.Thread(target=contextvars.copy_context().run, args=(run,), daemon=True,- name="cron-bot-chat-drain").start()+ try:+ threading.Thread(target=contextvars.copy_context().run, args=(run,), daemon=True,+ name="cron-bot-chat-drain").start()+ except BaseException:+ release()+ raisediff --git a/cron/scheduler.py b/cron/scheduler.pyindex 991b782df6b..d8394923d26 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -581,8 +581,10 @@ def try_register_running_job(job_id: str) -> bool:Registration also makes the run visible to ``get_running_job_ids`` (the gateway shutdown drain, #60432)and ``mark_running_jobs_interrupted``."""- with _running_lock:- if job_id in _running_job_ids:+ from hermes_cli.backend_retirement import retirement++ with retirement.work() as admitted, _running_lock:+ if not admitted or job_id in _running_job_ids:return False_running_job_ids.add(job_id)# Same critical section as the add: no window where an in-flight id lacks an age the sweep@@ -3809,108 +3811,7 @@ def _sweep_mcp_orphans_when_all_done(futures: list) -> None:_f.add_done_callback(_on_done)-def tick(- verbose: bool = True, adapters=None, loop=None, sync: bool = True, *, can_dispatch=None):- """Check and run all due jobs. File-locked so only one tick runs at a time (gateway ticker vs- standalone daemon / manual tick). ``can_dispatch``: optional gate; false leaves due jobs for the- next allowed tick. Returns the number of jobs executed (0 if another tick holds the lock)."""- # Stale-code yield gate — BEFORE the lock race. A process whose checkout was updated under it- # serves mixed sys.modules (jobs die on ImportErrors); if a fresher gateway holds the runtime- # lock, ITS ticker dispatches. With no fresh holder (desktop-standalone) the tick proceeds.- _skew = _should_yield_tick_to_fresh_gateway()- if _skew is not None:- _log_tick_yield_once(f"boot={_skew[0]} disk={_skew[1]}")- raise CronTickYielded(_skew[0], _skew[1])-- lock_dir, lock_file = _get_lock_paths()- _ensure_cron_dir(lock_dir)- lock_fd = _acquire_tick_lock(lock_file)- if lock_fd is None:- return 0-- try:- # `hermes pause` ESTOP: skip dispatch, never touch in-flight runs; check_paused logs once.- with contextlib.suppress(ImportError):- from agent.estop import check_paused as _estop_check_paused- if _estop_check_paused("cron", logger):- return 0-- if can_dispatch is not None and not can_dispatch():- logger.debug("Cron dispatch paused while gateway drains existing work")- return 0-- from cron.bot_chat_delivery import drain, drain_in_background- if sync:- drain()- else:- drain_in_background()- _maybe_reap_dead_owners()- # Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.- try:- _maybe_run_worktree_maintenance()- except Exception as _wt_exc:- logger.debug("Worktree maintenance dispatch failed: %s", _wt_exc)-- due_jobs = get_due_jobs()- _sweep_stale_inflight_for_tick(due_jobs)-- if not due_jobs:- # Idle tick: skip config load + pool setup, but still reap crashed jobs' MCP orphans.- if verbose:- # Idle tick: skip config load + pool partitioning entirely (#33612 — the gateway ticker- # calls tick(verbose=False) every 60s, so idle ticks previously fell through to- # load_config()). Still run the post-tick MCP orphan sweep: main intentionally sweeps on- # idle ticks so orphaned stdio children from crashed jobs are reaped even when nothing is- # due.- logger.info("%s - No jobs due", _hermes_now().strftime('%H:%M:%S'))- _sweep_mcp_orphans()- return 0-- if verbose:- logger.info("%s - %s job(s) due", _hermes_now().strftime('%H:%M:%S'), len(due_jobs))-- # Advance next_run_at for recurring jobs FIRST, under the lock, before any execution- # (at-most-once). Re-advancing running jobs keeps the grace window alive; mark_job_run- # overwrites it on completion. Composes with the claim-time advance in claim_job_for_fire.- advance_next_runs([job["id"] for job in due_jobs])-- _max_workers = _resolve_max_parallel_workers()- if verbose:- logger.info(- "Running %d job(s) in parallel (max_workers=%s)",- len(due_jobs),- _max_workers if _max_workers else "unbounded")-- def _process_job(job: dict) -> bool:- return _process_due_job(job, adapters, loop, verbose)-- # Persistent pool, non-blocking dispatch. Already-running jobs are skipped; mark_job_run- # re-arms next_run_at on completion, so no catch-up queue is needed.- _results: list = []- _all_futures: list = []- pool = _get_parallel_pool(_max_workers)- for job in due_jobs:- fut = _submit_with_guard(job, pool, _process_job)- if fut is None:- continue- _all_futures.append(fut)- if not sync:- _results.append(True) # optimistically counted-- if sync:- for f in concurrent.futures.as_completed(_all_futures):- try:- _results.append(f.result())- except Exception as exc:- logger.error("Cron job future failed: %s", exc)- _results.append(False)- _sweep_mcp_orphans()- return sum(_results)-- _sweep_mcp_orphans_when_all_done(_all_futures)- return sum(_results)- finally:- _release_tick_lock(lock_fd)+from cron.scheduler_tick import tick # noqa: E402# ---------------------------------------------------------------------------diff --git a/cron/scheduler_tick.py b/cron/scheduler_tick.pynew file mode 100644index 00000000000..3afd054d671--- /dev/null+++ b/cron/scheduler_tick.py@@ -0,0 +1,121 @@+"""In-process tick admission and dispatch; job execution stays in scheduler.py."""++import concurrent.futures+import contextlib+++def tick(verbose=True, adapters=None, loop=None, sync=True, *, can_dispatch=None):+ from hermes_cli.backend_retirement import retirement++ # Hold admission through the entire scan/advance/submit handoff. A predicate alone races+ # prepare after the check but before a due job enters the running-job ledger.+ with retirement.work() as admitted:+ if not admitted:+ return 0+ return _tick_admitted(verbose, adapters, loop, sync, can_dispatch=can_dispatch)+++def _tick_admitted(+ verbose: bool = True, adapters=None, loop=None, sync: bool = True, *, can_dispatch=None):+ """Check and run all due jobs. File-locked so only one tick runs at a time (gateway ticker vs+ standalone daemon / manual tick). ``can_dispatch``: optional gate; false leaves due jobs for the+ next allowed tick. Returns the number of jobs executed (0 if another tick holds the lock)."""+ from cron import scheduler as _sched++ # Stale-code yield gate — BEFORE the lock race. A process whose checkout was updated under it+ # serves mixed sys.modules (jobs die on ImportErrors); if a fresher gateway holds the runtime+ # lock, ITS ticker dispatches. With no fresh holder (desktop-standalone) the tick proceeds.+ _skew = _sched._should_yield_tick_to_fresh_gateway()+ if _skew is not None:+ _sched._log_tick_yield_once(f"boot={_skew[0]} disk={_skew[1]}")+ raise _sched.CronTickYielded(_skew[0], _skew[1])++ lock_dir, lock_file = _sched._get_lock_paths()+ _sched._ensure_cron_dir(lock_dir)+ lock_fd = _sched._acquire_tick_lock(lock_file)+ if lock_fd is None:+ return 0++ try:+ # `hermes pause` ESTOP: skip dispatch, never touch in-flight runs; check_paused logs once.+ with contextlib.suppress(ImportError):+ from agent.estop import check_paused as _estop_check_paused+ if _estop_check_paused("cron", _sched.logger):+ return 0++ if can_dispatch is not None and not can_dispatch():+ _sched.logger.debug("Cron dispatch paused while gateway drains existing work")+ return 0++ from cron.bot_chat_delivery import drain, drain_in_background+ if sync:+ drain()+ else:+ drain_in_background()+ _sched._maybe_reap_dead_owners()+ # Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.+ try:+ _sched._maybe_run_worktree_maintenance()+ except Exception as _wt_exc:+ _sched.logger.debug("Worktree maintenance dispatch failed: %s", _wt_exc)++ due_jobs = _sched.get_due_jobs()+ _sched._sweep_stale_inflight_for_tick(due_jobs)++ if not due_jobs:+ # Idle tick: skip config load + pool setup, but still reap crashed jobs' MCP orphans.+ if verbose:+ # Idle tick: skip config load + pool partitioning entirely (#33612 — the gateway ticker+ # calls tick(verbose=False) every 60s, so idle ticks previously fell through to+ # load_config()). Still run the post-tick MCP orphan sweep: main intentionally sweeps on+ # idle ticks so orphaned stdio children from crashed jobs are reaped even when nothing is+ # due.+ _sched.logger.info("%s - No jobs due", _sched._hermes_now().strftime('%H:%M:%S'))+ _sched._sweep_mcp_orphans()+ return 0++ if verbose:+ _sched.logger.info("%s - %s job(s) due", _sched._hermes_now().strftime('%H:%M:%S'), len(due_jobs))++ # Advance next_run_at for recurring jobs FIRST, under the lock, before any execution+ # (at-most-once). Re-advancing running jobs keeps the grace window alive; mark_job_run+ # overwrites it on completion. Composes with the claim-time advance in claim_job_for_fire.+ _sched.advance_next_runs([job["id"] for job in due_jobs])++ _max_workers = _sched._resolve_max_parallel_workers()+ if verbose:+ _sched.logger.info(+ "Running %d job(s) in parallel (max_workers=%s)",+ len(due_jobs),+ _max_workers if _max_workers else "unbounded")++ def _process_job(job: dict) -> bool:+ return _sched._process_due_job(job, adapters, loop, verbose)++ # Persistent pool, non-blocking dispatch. Already-running jobs are skipped; mark_job_run+ # re-arms next_run_at on completion, so no catch-up queue is needed.+ _results: list = []+ _all_futures: list = []+ pool = _sched._get_parallel_pool(_max_workers)+ for job in due_jobs:+ fut = _sched._submit_with_guard(job, pool, _process_job)+ if fut is None:+ continue+ _all_futures.append(fut)+ if not sync:+ _results.append(True) # optimistically counted++ if sync:+ for f in concurrent.futures.as_completed(_all_futures):+ try:+ _results.append(f.result())+ except Exception as exc:+ _sched.logger.error("Cron job future failed: %s", exc)+ _results.append(False)+ _sched._sweep_mcp_orphans()+ return sum(_results)++ _sched._sweep_mcp_orphans_when_all_done(_all_futures)+ return sum(_results)+ finally:+ _sched._release_tick_lock(lock_fd)diff --git a/hermes_cli/backend_retirement.py b/hermes_cli/backend_retirement.pynew file mode 100644index 00000000000..9882e8a9b79--- /dev/null+++ b/hermes_cli/backend_retirement.py@@ -0,0 +1,103 @@+"""Process-owned admission fence for cooperative Desktop backend retirement.++The gate belongs to the process, not a profile or transport. Diagnostic ledgers alone cannot+close the check/use race: every source of new work must reserve admission before dispatch.+"""++from contextlib import contextmanager+import logging+import secrets+import threading+import time+++class RetirementFence:+ """Exclusive 30-second prepare permit; commit closes admission permanently.++ Tokens are random and recognized only by this process instance. A committed prepare+ returns the same token so a client can recover a lost commit response without reopening.+ """++ def __init__(self):+ self._lock = threading.Lock()+ self._active = 0+ self._preparing = False+ self._token = None+ self._committed = False+ self._expires_at = 0.0+ self._now = time.monotonic++ def _expire(self):+ if self._token is not None and not self._committed and self._now() >= self._expires_at:+ self._token = None++ def acquire(self):+ with self._lock:+ self._expire()+ if self._preparing or self._token is not None:+ return False+ self._active += 1+ return True++ def release(self):+ with self._lock:+ self._active -= 1++ def active_count(self):+ with self._lock:+ return self._active++ @contextmanager+ def work(self):+ admitted = self.acquire()+ try:+ yield admitted+ finally:+ if admitted:+ self.release()++ def prepare(self):+ from hermes_cli.web_server_idle_proof import idle_proof++ with self._lock:+ self._expire()+ if self._committed:+ return {"ok": True, "idle": True, "token": self._token}+ if self._preparing or self._token is not None or self._active:+ return {"ok": False, "idle": False}+ self._preparing = True+ # No admissions can cross the freeze. Do not hold our lock while reading ledgers:+ # some callers already hold a session/cron lock when reserving their work.+ verdict = None+ try:+ verdict = idle_proof()["idle"]+ except Exception:+ logging.getLogger(__name__).warning("Retirement idle probe unavailable", exc_info=True)+ finally:+ with self._lock:+ self._preparing = False+ if verdict is True:+ self._token = token = secrets.token_urlsafe(32)+ self._expires_at = self._now() + 30.0+ if verdict is not True:+ return {"ok": False, "idle": verdict}+ return {"ok": True, "idle": True, "token": token}++ def commit(self, token):+ with self._lock:+ self._expire()+ if not token or token != self._token:+ return {"ok": False}+ self._committed = True+ return {"ok": True}++ def cancel(self, token):+ with self._lock:+ self._expire()+ if not token or token != self._token or self._committed:+ return {"ok": False}+ self._token = None+ return {"ok": True}+++retirement = RetirementFence()diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.pyindex ba5f67f5116..88263c48ce7 100644--- a/hermes_cli/web_routers/status.py+++ b/hermes_cli/web_routers/status.py@@ -119,14 +119,32 @@ async def get_health():@router.get("/api/health/idle")async def get_health_idle(request: Request):- """Backend-proven idleness for the Desktop pool's cooperative retirement (token-gated, unlike- ``/api/health``: whether a turn is running is activity recon). ``idle`` is True/False/None —- None means "cannot prove", which the Desktop treats as busy."""+ """Token-gated diagnostic snapshot; never a retirement permit. None means cannot prove idle."""from hermes_cli.web_server_idle_proof import idle_proof_require_token(request)return {"ok": True, **idle_proof()}[email protected]("/api/health/retirement")+async def post_health_retirement(request: Request):+ from hermes_cli.backend_retirement import retirement++ _require_token(request)+ try:+ body = await request.json()+ except ValueError:+ raise HTTPException(status_code=400, detail="JSON body required")+ if not isinstance(body, dict) or body.get("action") not in ("prepare", "commit", "cancel"):+ raise HTTPException(status_code=400, detail="action must be prepare, commit, or cancel")+ action = body["action"]+ if action == "prepare":+ return await run_in_threadpool(retirement.prepare)+ token = body.get("token")+ if not isinstance(token, str) or not token:+ raise HTTPException(status_code=400, detail="token required")+ return getattr(retirement, action)(token)++# Profile segment mirrors hermes_cli.profiles._PROFILE_ID_RE. Platform segment mirrors the# Platform enum's normalized values: built-in members plus plugin directory names# (lowercased), which allow hyphens as well as underscores (e.g. ``reviewer:foo-bar``).diff --git a/hermes_cli/web_server_idle_exit.py b/hermes_cli/web_server_idle_exit.pyindex 91d69b166d4..459398bc992 100644--- a/hermes_cli/web_server_idle_exit.py+++ b/hermes_cli/web_server_idle_exit.py@@ -94,6 +94,13 @@ def wrap_asgi_with_ws_tracking(app, tracker: IdleClientTracker):_probe_failure_logged = False+def _session_work_in_flight(session: dict) -> bool:+ if any(session.get(key) for key in ("running", "queued_prompt", "queued_prompts", "_auto_continue_scheduled")):+ return True+ return any(thread.is_alive() for key in ("_run_thread", "_agent_build_thread")+ if (thread := session.get(key)) is not None)++def turn_in_flight() -> Optional[bool]:"""True/False from the gateway's running-session table OR the in-process cron scheduler; Nonewhen neither can be read. The session table lives on ``tui_gateway.server`` (the voice mixin's@@ -105,12 +112,17 @@ def turn_in_flight() -> Optional[bool]:global _probe_failure_loggedtry:import tui_gateway.server as gateway+ from hermes_cli.backend_retirement import retirement++ if retirement.active_count():+ return Truewith gateway._sessions_lock:- running = any(s.get("running") for s in gateway._sessions.values())+ running = any(_session_work_in_flight(s) for s in gateway._sessions.values())if running:return True+ from tools.async_delegation import active_countfrom cron.scheduler import get_running_job_ids- return bool(get_running_job_ids())+ return bool(active_count() or get_running_job_ids())except Exception:if not _probe_failure_logged:_probe_failure_logged = Truediff --git a/hermes_cli/web_server_idle_proof.py b/hermes_cli/web_server_idle_proof.pyindex b0c4618259c..879ad3bd255 100644--- a/hermes_cli/web_server_idle_proof.py+++ b/hermes_cli/web_server_idle_proof.py@@ -1,17 +1,10 @@-"""Backend-proven idleness for a Desktop-pooled ``hermes serve`` child.+"""Diagnostic work snapshot for a Desktop-pooled ``hermes serve`` child.-The Desktop caps local pooled backends (3 by default) and keeps a hard slot lease for the lifetime-of each child. Its renderer refreshes ``lastActiveAt`` every 60s for every open socket, so a-bot-tile-pinned resident is "fresh" forever even when it is doing nothing — occupied is not busy.-When a foreground open finds the pool full, the Desktop may retire one resident, but only one the-BACKEND itself can prove idle. The renderer's own turn bookkeeping cannot see cron fires-(``HERMES_DESKTOP=1`` runs the in-process ticker), messaging-platform turns served by a pooled-backend, or a session blocked on an approval, so it is never the proof.--:func:`idle_proof` reads the same ledgers the SSH idle-exit watchdog trusts-(:func:`hermes_cli.web_server_idle_exit.turn_in_flight`: running gateway sessions plus running cron-jobs) and adds the human-input ledgers (open server→client requests, unresolved gateway approvals).-It fails closed: anything it cannot read yields ``idle: None`` and the Desktop must not retire.+Reads process admission, session/worker, delegation, cron and human-input ledgers. Unreadable+state is indeterminate, never idle. This snapshot alone is NOT permission to retire: only+``backend_retirement.RetirementFence.prepare`` freezes admission before taking the snapshot,+and only a confirmed commit permits the client to stop that exact backend generation.+The separate messaging gateway process owns its own lifecycle and drain protocol."""from __future__ import annotationsdiff --git a/tests/cron/test_retirement_dispatch.py b/tests/cron/test_retirement_dispatch.pynew file mode 100644index 00000000000..7f3d2512556--- /dev/null+++ b/tests/cron/test_retirement_dispatch.py@@ -0,0 +1,90 @@+"""The tick-to-worker handoff must have no retirement-sized gap after can_dispatch."""++from concurrent.futures import ThreadPoolExecutor+from datetime import datetime, timezone+import threading+++def test_passed_gate_tick_and_queued_job_remain_busy_until_real_worker_exit(tmp_path, monkeypatch):+ from cron import jobs, scheduler+ from hermes_cli import backend_retirement++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ script = tmp_path / "job.py"+ script.write_text("print('no model')\n")+ job = jobs.create_job(prompt=None, schedule=datetime.now(timezone.utc).isoformat(), script=str(script), no_agent=True)+ for name in ("_maybe_run_worktree_maintenance", "_sweep_mcp_orphans", "_maybe_reap_dead_owners"):+ monkeypatch.setattr(scheduler, name, lambda: None)+ monkeypatch.setattr(scheduler, "_should_yield_tick_to_fresh_gateway", lambda: None)+ reached, release_tick, running, release_job = (threading.Event() for _ in range(4))+ due = scheduler.get_due_jobs+ gate_calls = []++ def get_due_jobs():+ reached.set()+ assert release_tick.wait(10)+ return due()++ def process_job(*args):+ running.set()+ assert release_job.wait(10)+ return True++ monkeypatch.setattr(scheduler, "get_due_jobs", get_due_jobs)+ monkeypatch.setattr(scheduler, "_process_due_job", process_job)+ with ThreadPoolExecutor(max_workers=1) as pool, ThreadPoolExecutor(max_workers=1) as ticker:+ monkeypatch.setattr(scheduler, "_get_parallel_pool", lambda *args: pool)+ tick = ticker.submit(scheduler.tick, verbose=False, sync=False, can_dispatch=lambda: gate_calls.append(True) or True)+ try:+ assert reached.wait(10)+ assert gate_calls+ assert not scheduler.get_running_job_ids()+ assert fence.prepare() == {"ok": False, "idle": False}+ release_tick.set()+ assert tick.result(10) == 1+ assert running.wait(10)+ assert job["id"] in scheduler.get_running_job_ids()+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release_tick.set()+ release_job.set()+ assert not scheduler.get_running_job_ids()+ token = fence.prepare()["token"]+ assert scheduler.tick(verbose=False, sync=False) == 0+ assert scheduler.try_register_running_job("manual-late") is False+ assert fence.commit(token) == {"ok": True}+ assert scheduler.tick(verbose=False, sync=False) == 0+++def test_detached_cron_delivery_keeps_admission_after_its_tick_returns(tmp_path, monkeypatch):+ from cron import bot_chat_delivery+ from hermes_cli import backend_retirement+ from hermes_constants import get_hermes_home++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ root = get_hermes_home() / "cron" / "bot_chat_pending"+ root.mkdir(parents=True)+ entered, release = threading.Event(), threading.Event()++ def drain(root):+ entered.set()+ assert release.wait(10)++ monkeypatch.setattr(bot_chat_delivery, "_drain", drain)+ try:+ bot_chat_delivery.drain_in_background()+ assert entered.wait(10)+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release.set()+ for thread in threading.enumerate():+ if thread.name == "cron-bot-chat-drain":+ thread.join(10)+ token = fence.prepare()["token"]+ entered.clear()+ bot_chat_delivery.drain_in_background()+ bot_chat_delivery.drain(root)+ assert not entered.is_set()+ assert fence.cancel(token) == {"ok": True}diff --git a/tests/hermes_cli/test_backend_retirement.py b/tests/hermes_cli/test_backend_retirement.pynew file mode 100644index 00000000000..8229765f5d0--- /dev/null+++ b/tests/hermes_cli/test_backend_retirement.py@@ -0,0 +1,77 @@+"""Cooperative retirement is a reservation, never a sampled idle verdict."""++from fastapi.testclient import TestClient+++def test_retirement_reserves_admission_until_cancel_or_permanent_commit(monkeypatch):+ from hermes_cli import web_server+ from tui_gateway import server+ from hermes_cli import backend_retirement++ monkeypatch.setattr(backend_retirement, "retirement", backend_retirement.RetirementFence())+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "retirement-test-token")+ monkeypatch.setitem(server._methods, "test.retirement", lambda rid, params: server._ok(rid, {}))+ client = TestClient(web_server.app)+ headers = {"X-Hermes-Session-Token": "retirement-test-token"}+ rpc = {"id": "test", "method": "test.retirement", "params": {}}++ def post(action, token=None, authenticated=True):+ return client.post("/api/health/retirement", json={"action": action, **({"token": token} if token else {})},+ headers=headers if authenticated else {})++ assert post("prepare", authenticated=False).status_code == 401+ for invalid in ({"action": []}, {"action": "commit"}, {"action": "cancel", "token": 123}, []):+ assert client.post("/api/health/retirement", json=invalid, headers=headers).status_code == 400+ assert client.post("/api/health/retirement", content="not json", headers=headers).status_code == 400+ assert "result" in server.handle_request(rpc)+ prepared = post("prepare")+ assert prepared.status_code == 200+ permit = prepared.json()+ assert permit == {"ok": True, "idle": True, "token": permit["token"]}+ assert isinstance(permit["token"], str) and permit["token"]+ # A diagnostic GET neither grants nor cancels the exclusive permit.+ assert client.get("/api/health/idle", headers=headers).json()["idle"] is True+ assert "error" in server.handle_request(rpc)+ assert post("prepare").json() == {"ok": False, "idle": False}+ assert post("cancel", "wrong-token").json() == {"ok": False}+ assert "error" in server.handle_request(rpc)+ assert post("cancel", permit["token"]).json() == {"ok": True}+ assert "result" in server.handle_request(rpc)+ next_permit = post("prepare").json()["token"]+ assert next_permit != permit["token"]+ assert post("commit", permit["token"]).json() == {"ok": False}+ assert post("commit", next_permit).json() == {"ok": True}+ assert post("commit", next_permit).json() == {"ok": True}+ assert post("cancel", next_permit).json() == {"ok": False}+ assert "error" in server.handle_request(rpc)+ # Recover a lost commit response without ever reopening the retired generation.+ assert post("prepare").json() == {"ok": True, "idle": True, "token": next_permit}+++def test_only_uncommitted_permits_expire_and_unreadable_work_never_grants(monkeypatch):+ from hermes_cli.backend_retirement import RetirementFence+ from hermes_cli import web_server_idle_proof++ fence = RetirementFence()+ now = [100.0]+ monkeypatch.setattr(fence, "_now", lambda: now[0], raising=False)+ first = fence.prepare()["token"]+ now[0] += 30.0+ assert fence.commit(first) == {"ok": False}+ assert fence.cancel(first) == {"ok": False}+ with fence.work() as admitted:+ assert admitted+ assert fence.prepare() == {"ok": False, "idle": False}+ second = fence.prepare()["token"]+ assert first != second+ assert RetirementFence().commit(second) == {"ok": False}+ now[0] += 29.0+ assert fence.commit(second) == {"ok": True}+ now[0] += 3600.0+ assert fence.commit(second) == {"ok": True}+ assert fence.prepare() == {"ok": True, "idle": True, "token": second}+ assert fence.cancel(second) == {"ok": False}+ with fence.work() as admitted:+ assert not admitted+ monkeypatch.setattr(web_server_idle_proof, "idle_proof", lambda: {"idle": None})+ assert RetirementFence().prepare() == {"ok": False, "idle": None}diff --git a/tests/hermes_cli/test_retirement_atomicity.py b/tests/hermes_cli/test_retirement_atomicity.pynew file mode 100644index 00000000000..2d4df9106b7--- /dev/null+++ b/tests/hermes_cli/test_retirement_atomicity.py@@ -0,0 +1,50 @@+"""Freeze admission before consulting ledgers, without holding a lock across their locks."""++from concurrent.futures import ThreadPoolExecutor+import threading+++def test_prepare_freezes_admission_without_blocking_other_work_locks(monkeypatch):+ from hermes_cli.backend_retirement import RetirementFence+ from hermes_cli import web_server_idle_proof++ fence = RetirementFence()+ probing, release, attempted = (threading.Event() for _ in range(3))++ def probe():+ probing.set()+ assert release.wait(10)+ return {"idle": None}++ def admit():+ with fence.work() as admitted:+ attempted.set()+ return admitted++ monkeypatch.setattr(web_server_idle_proof, "idle_proof", probe)+ with ThreadPoolExecutor(max_workers=2) as pool:+ preparing = pool.submit(fence.prepare)+ try:+ assert probing.wait(10)+ arriving = pool.submit(admit)+ assert attempted.wait(3), "admission must not wait on a ledger lock held by its own caller"+ assert arriving.result(10) is False+ finally:+ release.set()+ assert preparing.result(10) == {"ok": False, "idle": None}+ with fence.work() as admitted:+ assert admitted # unreadable/busy probe did not leave a fence behind+++def test_probe_failure_refuses_the_permit_without_wedging_admission(monkeypatch):+ from hermes_cli.backend_retirement import RetirementFence+ from hermes_cli import web_server_idle_proof++ def broken_probe():+ raise OSError("ledger unavailable")++ fence = RetirementFence()+ monkeypatch.setattr(web_server_idle_proof, "idle_proof", broken_probe)+ assert fence.prepare() == {"ok": False, "idle": None}+ with fence.work() as admitted:+ assert admitteddiff --git a/tests/hermes_cli/test_web_server_idle_proof.py b/tests/hermes_cli/test_web_server_idle_proof.pyindex eb27be4e934..71ae2915268 100644--- a/tests/hermes_cli/test_web_server_idle_proof.py+++ b/tests/hermes_cli/test_web_server_idle_proof.py@@ -75,6 +75,26 @@ def test_idle_proof_reads_the_real_cron_and_human_input_ledgers():assert idle_proof()["idle"] is True+def test_queued_prompts_and_unwinding_workers_are_not_idle(monkeypatch):+ from tui_gateway import server++ session = {"running": False, "history_lock": threading.RLock()}+ monkeypatch.setitem(server._sessions, "queued-retirement", session)+ server._enqueue_prompt(session, "accepted follow-up", None)+ assert idle_proof()["idle"] is False+ session.pop("queued_prompt")+ release = threading.Event()+ thread = threading.Thread(target=lambda: release.wait(10), daemon=True)+ session["_run_thread"] = thread+ thread.start()+ try:+ assert idle_proof()["idle"] is False+ finally:+ release.set()+ thread.join(10)+ assert idle_proof()["idle"] is True++# ---------------------------------------------------------------------------# Live children: three real desktop-shaped ``serve`` processes, one held busy# ---------------------------------------------------------------------------diff --git a/tests/tools/test_async_delegation_retirement.py b/tests/tools/test_async_delegation_retirement.pynew file mode 100644index 00000000000..7f91d97b5e3--- /dev/null+++ b/tests/tools/test_async_delegation_retirement.py@@ -0,0 +1,44 @@+"""Background delegations cannot outlive the admission proof used to retire their process."""++import threading+++def test_async_delegations_hold_busy_accounting_through_finalization(tmp_path, monkeypatch):+ from hermes_cli import backend_retirement+ from hermes_cli.web_server_idle_proof import idle_proof+ from tools import async_delegation++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ entered, release = threading.Event(), threading.Event()++ def runner():+ entered.set()+ assert release.wait(10)+ return {"summary": "test done"}++ def dispatch():+ return async_delegation.dispatch_async_delegation(+ goal="test", context=None, toolsets=None, role="leaf", model=None,+ session_key="test", runner=runner)++ token = fence.prepare()["token"]+ try:+ assert dispatch()["status"] == "rejected"+ assert not entered.is_set()+ assert fence.cancel(token) == {"ok": True}+ handle = dispatch()+ assert handle["status"] == "dispatched"+ assert entered.wait(10)+ assert async_delegation.active_count() > 0+ assert idle_proof()["idle"] is False+ assert fence.prepare() == {"ok": False, "idle": False}+ # A stalled record may be force-finalized before its stuck runner really unwinds.+ async_delegation._finalize(handle["delegation_id"], {"error": "test stall"}, "stalled")+ assert async_delegation.active_count() == 0+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release.set()+ if async_delegation._executor is not None:+ async_delegation._executor.shutdown(wait=True)+ assert fence.prepare()["ok"] is Truediff --git a/tests/tui_gateway/test_auto_continue.py b/tests/tui_gateway/test_auto_continue.pyindex 213a925db48..83b7905bc17 100644--- a/tests/tui_gateway/test_auto_continue.py+++ b/tests/tui_gateway/test_auto_continue.py@@ -35,7 +35,7 @@ from tui_gateway.turn_marker import (class _InlineThread:"""Run threads synchronously so tests observe final state."""- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target = targetself._args = argsself._kwargs = kwargs or {}diff --git a/tests/tui_gateway/test_bot_live_owner_delivery.py b/tests/tui_gateway/test_bot_live_owner_delivery.pyindex 2ab59d61f2c..3c294b6f037 100644--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@ -3,6 +3,7 @@ import threadingfrom types import SimpleNamespacefrom tui_gateway.method_ctx import rebind+from tui_gateway.session_lifecycle import _session_turn_admissionfrom tui_gateway import session_notifications, session_auto_continuefrom tui_gateway.turn_marker import record_turn_start, read_turn_marker@@ -13,6 +14,7 @@ def test_refused_input_commits_failed_mailbox_receipt(tmp_path):import loggingimport timefrom tui_gateway import prompt_turn+ from tui_gateway.session_lifecycle import _start_session_workfrom tools import bot_live_delivery as mailboxowner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",@@ -25,6 +27,7 @@ def test_refused_input_commits_failed_mailbox_receipt(tmp_path):noop = lambda *args, **kwargs: Nonesubmit = rebind(prompt_turn._run_prompt_submit, {"threading": threading, "time": time, "logger": logging.getLogger(__name__),+ "_start_session_work": _start_session_work,"_sessions_lock": threading.RLock(), "_sessions": {},"_admit_prompt_turn": lambda *args: ([], agent),"_emit": noop, "bind_transport": noop, "reset_transport": noop,@@ -79,6 +82,7 @@ def test_local_work_blocks_mailbox_claim_without_consuming_envelope(monkeypatch,return Truepoll = rebind(session_notifications._poll_bot_live_delivery_once, {"_session_home": lambda session: tmp_path,+ "_session_turn_admission": _session_turn_admission,"_run_prompt_submit": submit,"_notif_release_turn": lambda session: session.update(running=False),})@@ -103,7 +107,8 @@ def test_mailbox_poll_skips_owner_lookup_without_a_mailbox(monkeypatch, tmp_pathimport tools.bot_live_delivery as mailboxlookups = []monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: lookups.append(home) or None)- poll = rebind(session_notifications._poll_bot_live_delivery_once, {"_session_home": lambda session: tmp_path})+ poll = rebind(session_notifications._poll_bot_live_delivery_once, {+ "_session_home": lambda session: tmp_path, "_session_turn_admission": _session_turn_admission})session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "chat","active_session_lease": SimpleNamespace(lease_id="lease", released=False)}assert poll("live", session) is Falsediff --git a/tests/tui_gateway/test_composite_carrier_rewind.py b/tests/tui_gateway/test_composite_carrier_rewind.pyindex 394d992b696..89260bb7bd6 100644--- a/tests/tui_gateway/test_composite_carrier_rewind.py+++ b/tests/tui_gateway/test_composite_carrier_rewind.py@@ -479,8 +479,8 @@ def test_prompt_row_id_rewind_preserves_scaffold_before_regeneration(}class _ImmediateThread:- def __init__(self, target=None, daemon=None):- self._target = target+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):+ self._target = lambda: target(*args, **(kwargs or {}))def start(self):self._target()diff --git a/tests/tui_gateway/test_failed_turn_retention.py b/tests/tui_gateway/test_failed_turn_retention.pyindex 30987d5a9ea..24f009ed9ae 100644--- a/tests/tui_gateway/test_failed_turn_retention.py+++ b/tests/tui_gateway/test_failed_turn_retention.py@@ -32,7 +32,7 @@ from tui_gateway import serverclass _InlineThread:"""Run the turn synchronously so tests observe its final state."""- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target = targetself._args = argsself._kwargs = kwargs or {}diff --git a/tests/tui_gateway/test_hosted_room_turn_slot_release.py b/tests/tui_gateway/test_hosted_room_turn_slot_release.pyindex 97885dad639..62dc5cf9857 100644--- a/tests/tui_gateway/test_hosted_room_turn_slot_release.py+++ b/tests/tui_gateway/test_hosted_room_turn_slot_release.py@@ -17,7 +17,7 @@ from tui_gateway.hosted_room_driver import ROOM_SESSION_SOURCEclass _InlineThread:- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target, self._args, self._kwargs = target, args, kwargs or {}def start(self):diff --git a/tests/tui_gateway/test_none_agent_turn_guard.py b/tests/tui_gateway/test_none_agent_turn_guard.pyindex 8b8d03611c6..7ac3ab51c7e 100644--- a/tests/tui_gateway/test_none_agent_turn_guard.py+++ b/tests/tui_gateway/test_none_agent_turn_guard.py@@ -19,7 +19,7 @@ from tui_gateway.user_messages import AGENT_BUILD_ABANDONEDclass _InlineThread:"""Run the turn synchronously so tests observe its final state."""- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target, self._args, self._kwargs = target, args, kwargs or {}def start(self):diff --git a/tests/tui_gateway/test_prompt_accept_logging.py b/tests/tui_gateway/test_prompt_accept_logging.pyindex e60b36e69eb..719466b2a87 100644--- a/tests/tui_gateway/test_prompt_accept_logging.py+++ b/tests/tui_gateway/test_prompt_accept_logging.py@@ -31,7 +31,7 @@ from tui_gateway import serverclass _InlineThread:"""Run the turn synchronously so tests observe its final state."""- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target = targetself._args = argsself._kwargs = kwargs or {}diff --git a/tests/tui_gateway/test_relay_live_author.py b/tests/tui_gateway/test_relay_live_author.pyindex 0b109f03373..65f657fd124 100644--- a/tests/tui_gateway/test_relay_live_author.py+++ b/tests/tui_gateway/test_relay_live_author.py@@ -33,7 +33,7 @@ def _session(agent=None, **extra):class _InlineThread:- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target, self._args, self._kwargs = target, args, kwargs or {}def start(self):diff --git a/tests/tui_gateway/test_retirement_admission.py b/tests/tui_gateway/test_retirement_admission.pynew file mode 100644index 00000000000..8260cb8979c--- /dev/null+++ b/tests/tui_gateway/test_retirement_admission.py@@ -0,0 +1,95 @@+"""Every admission source participates in the same process retirement fence."""++from concurrent.futures import ThreadPoolExecutor+import queue+import threading++import pytest+++def runtime(monkeypatch):+ from tui_gateway import server+ from hermes_cli import backend_retirement++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ return server, fence+++class Transport:+ def __init__(self):+ self.frames = queue.Queue()++ def write(self, frame):+ self.frames.put(frame)+ return True+++def test_queued_and_running_rpc_hold_admission_until_the_response(runtime, monkeypatch):+ from hermes_cli.web_server_idle_proof import idle_proof++ server, fence = runtime+ release_pool, entered, release_handler = (threading.Event() for _ in range(3))+ transport = Transport()++ def handler(rid, params):+ entered.set()+ assert release_handler.wait(10)+ return server._ok(rid, {"done": True})++ monkeypatch.setitem(server._methods, "test.retirement", handler)+ monkeypatch.setattr(server, "_LONG_HANDLERS", {"test.retirement"})+ with ThreadPoolExecutor(max_workers=1) as pool:+ monkeypatch.setattr(server, "_pool", pool)+ blocked = pool.submit(release_pool.wait, 10)+ try:+ assert server.dispatch({"id": "test", "method": "test.retirement"}, transport) is None+ assert fence.prepare() == {"ok": False, "idle": False}+ assert idle_proof()["idle"] is False+ release_pool.set()+ blocked.result(10)+ assert entered.wait(10)+ assert fence.prepare() == {"ok": False, "idle": False}+ release_handler.set()+ assert transport.frames.get(timeout=10)["result"] == {"done": True}+ finally:+ release_pool.set()+ release_handler.set()+ assert idle_proof()["idle"] is True+ token = fence.prepare()["token"]+ assert server.dispatch({"id": "late", "method": "test.retirement"}, transport)["error"]["code"] == 5035+ assert fence.cancel(token) == {"ok": True}+++def test_prompt_claim_and_automatic_continuations_cannot_cross_prepare(runtime, monkeypatch):+ server, fence = runtime+ session = {"history_lock": threading.RLock(), "running": False, "history": []}+ dispatched = []+ monkeypatch.setattr(server, "_run_prompt_submit", lambda *a, **kw: dispatched.append(a))+ token = fence.prepare()["token"]+ err, _ = server._lock_in_submit_turn("r", "s", session, "hello", {}, False, None, None, None)+ assert err and err["error"]["code"] == 5035+ assert session["running"] is False+ session["queued_prompt"] = {"text": "next", "transport": None}+ assert server._drain_queued_prompt("r", "s", session) is False+ assert session["queued_prompt"]["text"] == "next"+ assert server._notif_claim_turn(session) is False+ # Use a separate idle session so the goal branch is reached without the queued prompt.+ goal_session = {"history_lock": threading.RLock(), "running": False}+ server._run_post_turn_followups("r", "s", goal_session, {}, "keep going")+ assert goal_session["running"] is False+ assert not dispatched+ from types import SimpleNamespace+ from tools import bot_live_delivery++ monkeypatch.setattr(bot_live_delivery, "has_mailbox", lambda home: True)+ monkeypatch.setattr(bot_live_delivery, "find_canonical_live_owner", lambda home: {+ "lease_id": "l", "live_session_id": "s", "session_id": "stored"})+ monkeypatch.setattr(bot_live_delivery, "claim_pending_delivery", lambda *a: pytest.fail("retiring backend claimed a delivery"))+ mailbox_session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "stored",+ "active_session_lease": SimpleNamespace(lease_id="l", released=False)}+ assert server._poll_bot_live_delivery_once("s", mailbox_session) is False+ assert fence.cancel(token) == {"ok": True}+ assert server._notif_claim_turn(session) is True+ assert session["running"] is Truediff --git a/tests/tui_gateway/test_retirement_continuations.py b/tests/tui_gateway/test_retirement_continuations.pynew file mode 100644index 00000000000..8755aa15c12--- /dev/null+++ b/tests/tui_gateway/test_retirement_continuations.py@@ -0,0 +1,77 @@+"""Retirement cannot splice between a turn's completion and its automatic successors."""++import threading+import types+++def test_crash_continuation_reserves_before_build_and_refuses_prepared_backend(tmp_path, monkeypatch):+ from hermes_cli import backend_retirement+ from tui_gateway import server+ from tui_gateway.turn_marker import record_turn_start++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ monkeypatch.setattr(server, "_auto_continue_config", lambda: (True, 3600, 3))+ session = {"profile_home": str(tmp_path), "history_lock": threading.RLock(), "running": False}+ record_turn_start(tmp_path, "recovery", "unfinished")+ building, release = threading.Event(), threading.Event()++ def build(*args):+ building.set()+ assert release.wait(10)++ monkeypatch.setattr(server, "_start_agent_build", build)+ monkeypatch.setattr(server, "_wait_agent", lambda *args, **kw: {"error": "no model in test"})+ token = fence.prepare()["token"]+ try:+ assert server._maybe_schedule_auto_continue("s", session, "recovery") is None+ assert not building.is_set()+ assert fence.cancel(token) == {"ok": True}+ assert server._maybe_schedule_auto_continue("s", session, "recovery") is not None+ assert building.wait(10)+ assert not session["running"]+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release.set()+ for thread in threading.enumerate():+ if thread.name == "auto-continue-s":+ thread.join(10)+ assert fence.prepare()["ok"] is True+++def test_prompt_worker_stays_busy_after_running_flag_until_finalizers_finish(tmp_path, monkeypatch):+ from hermes_cli import backend_retirement+ from tui_gateway import server++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ agent = types.SimpleNamespace(session_id="retirement-turn", clear_interrupt=lambda: None,+ run_conversation=lambda *args, **kwargs: {"final_response": "done"})+ session = {"agent": agent, "session_key": "retirement-turn", "history": [], "profile_home": str(tmp_path),+ "history_lock": threading.RLock(), "history_version": 0, "running": True, "attached_images": [],+ "image_counter": 0, "cols": 80, "slash_worker": None, "show_reasoning": False,+ "tool_progress_mode": "all", "inflight_turn": None}+ for name in ("_wire_callbacks", "_sync_agent_model_with_config", "_register_session_cwd", "_sync_session_key_after_compress"):+ monkeypatch.setattr(server, name, lambda *args, **kw: None)+ monkeypatch.setattr(server, "_emit", lambda *args, **kw: None)+ monkeypatch.setattr(server, "_session_cwd", lambda session: str(tmp_path))+ monkeypatch.setattr(server, "_tts_stream_begin", lambda: None)+ monkeypatch.setattr(server, "_get_usage", lambda agent: {})+ finishing, release = threading.Event(), threading.Event()++ def finish(*args):+ finishing.set()+ assert release.wait(10)++ monkeypatch.setattr(server, "_emit_settled_session_info", finish)+ monkeypatch.setitem(server._sessions, "s", session)+ try:+ assert server._run_prompt_submit("r", "s", session, "hello") is True+ assert finishing.wait(10)+ assert session["running"] is False+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release.set()+ if thread := session.get("_run_thread"):+ thread.join(10)+ assert fence.prepare()["ok"] is Truediff --git a/tests/tui_gateway/test_retirement_workers.py b/tests/tui_gateway/test_retirement_workers.pynew file mode 100644index 00000000000..2a82a6a0349--- /dev/null+++ b/tests/tui_gateway/test_retirement_workers.py@@ -0,0 +1,65 @@+"""Detached work must retain process admission, including scoped side-agent cleanup."""++import contextvars+from pathlib import Path+import queue+import threading+++def test_side_workers_hold_admission_through_cleanup_and_preserve_profile_scope(tmp_path, monkeypatch):+ from hermes_cli import backend_retirement+ from hermes_constants import get_hermes_home+ from agent.secret_scope import get_secret, set_multiplex_active+ from tui_gateway import server++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ homes = [tmp_path / "a", tmp_path / "b"]+ for home in homes:+ home.mkdir()+ (home / "config.yaml").write_text("terminal:\n backend: local\n")+ (home / ".env").write_text(f"RETIREMENT_SCOPE={home.name}\n")+ marker = contextvars.ContextVar("retirement_test_marker", default="missing")+ marker.set("inherited")+ emitted = queue.Queue()+ monkeypatch.setattr(server, "_emit", lambda *a: emitted.put(a))+ set_multiplex_active(True)+ try:+ for home in [homes[0], homes[1], homes[0]]:+ entered, release, cleaning, release_cleanup = (threading.Event() for _ in range(4))+ observed = []++ def body():+ observed.append((get_hermes_home(), get_secret("RETIREMENT_SCOPE"), marker.get()))+ entered.set()+ assert release.wait(10)+ return "finished"++ def cleanup():+ cleaning.set()+ assert release_cleanup.wait(10)++ session = {"profile_home": str(home), "cwd": str(tmp_path)}+ try:+ result = server._spawn_side_agent("r", session, "side", "parent", "background.complete", body, cleanup=cleanup)+ assert result["result"]["task_id"] == "side"+ assert entered.wait(10)+ assert fence.prepare() == {"ok": False, "idle": False}+ assert observed == [(home, home.name, "inherited")]+ release.set()+ assert cleaning.wait(10)+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release.set()+ release_cleanup.set()+ # The cleanup event happens before the admission finalizer: join the real worker.+ for thread in threading.enumerate():+ if thread.name == "side-agent-side":+ thread.join(10)+ emitted.get(timeout=10)+ token = fence.prepare()["token"]+ assert "error" in server._spawn_side_agent("r", session, "late", "parent", "background.complete", body)+ assert fence.cancel(token) == {"ok": True}+ finally:+ set_multiplex_active(False)diff --git a/tests/tui_gateway/test_session_control.py b/tests/tui_gateway/test_session_control.pyindex 774243fcebc..a022fca1508 100644--- a/tests/tui_gateway/test_session_control.py+++ b/tests/tui_gateway/test_session_control.py@@ -428,7 +428,7 @@ class TestUpdatePublication:emitted = self._capture(server, monkeypatch)class _InlineThread:- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._t, self._a, self._k = target, args, kwargs or {}def start(self):diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.pyindex 3af104b90b8..ab6ab6b3a57 100644--- a/tests/tui_gateway/test_tui_gateway_server.py+++ b/tests/tui_gateway/test_tui_gateway_server.py@@ -7137,7 +7137,7 @@ def test_prompt_submit_empty_truncation_allowed_with_confirm(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -11300,7 +11300,7 @@ def test_prompt_submit_sets_approval_session_key(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -11340,7 +11340,7 @@ def test_prompt_submit_expands_context_refs(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -12783,7 +12783,7 @@ def test_prompt_submit_history_version_mismatch_surfaces_warning(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -12876,7 +12876,7 @@ def test_prompt_submit_merges_on_model_switch_marker(monkeypatch):return _is_model_switch_marker(entry)class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -12975,7 +12975,7 @@ def test_prompt_submit_merges_on_personality_pivot_marker(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -13086,7 +13086,7 @@ def test_prompt_submit_history_version_match_persists_normally(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -13196,7 +13196,7 @@ def test_prompt_submit_can_truncate_before_user_ordinal(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -13360,7 +13360,7 @@ def test_prompt_submit_truncate_ordinal_skips_display_kind_rows(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -13460,7 +13460,7 @@ def test_prompt_submit_truncate_translates_display_prefix_ordinal(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -13749,7 +13749,7 @@ def test_run_prompt_submit_registers_turn_thread_for_interrupt(monkeypatch):calls = {"interrupted": False, "started": False}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetdef start(self):@@ -13820,7 +13820,7 @@ def test_interrupt_before_agent_ready_prevents_late_turn_start(monkeypatch):calls = {"run_prompt": 0}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetthreads.append(self)@@ -13890,7 +13890,7 @@ def test_cancelled_turn_before_agent_ready_emits_error_event(monkeypatch):calls = {"run_prompt": 0}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetthreads.append(self)@@ -13962,7 +13962,7 @@ def test_session_not_running_before_agent_ready_emits_error_event(monkeypatch):calls = {"run_prompt": 0}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetthreads.append(self)@@ -14028,7 +14028,7 @@ def test_slow_agent_build_delivers_prompt_instead_of_timing_out(monkeypatch):calls = {"run_prompt": 0}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetthreads.append(self)@@ -14104,7 +14104,7 @@ def test_slow_agent_build_emits_keyed_progress_notice(monkeypatch):calls = {"run_prompt": 0}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetthreads.append(self)@@ -14188,7 +14188,7 @@ def test_agent_build_failure_surfaces_error_and_drops_turn(monkeypatch):calls = {"run_prompt": 0}class _FakeThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self.target = targetthreads.append(self)@@ -16835,7 +16835,7 @@ def test_model_options_refresh_allows_custom_provider_probes(monkeypatch):class _ImmediateThread:"""Runs the target callable synchronously so assertions can follow."""- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -18491,7 +18491,7 @@ def test_notification_poller_delivers_completion(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):self._target()@@ -18559,7 +18559,7 @@ def test_notification_poller_skips_consumed(monkeypatch):return {"final_response": "ok", "messages": []}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):self._target()@@ -20986,7 +20986,7 @@ def test_prompt_submit_passes_persist_user_message_to_agent(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -21029,7 +21029,7 @@ def test_prompt_submit_releases_old_history_before_heap_trim(monkeypatch, tmp_pa}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -21410,7 +21410,7 @@ def test_personality_marker_does_not_shift_truncate_ordinal(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):@@ -21530,7 +21530,7 @@ def test_prompt_submit_truncation_archives_instead_of_deleting(monkeypatch):}class _ImmediateThread:- def __init__(self, target=None, daemon=None):+ def __init__(self, target=None, daemon=None, **_thread_options):self._target = targetdef start(self):diff --git a/tests/tui_gateway/test_turn_finished_failure_cause.py b/tests/tui_gateway/test_turn_finished_failure_cause.pyindex 307b89a0202..dcc47ee978c 100644--- a/tests/tui_gateway/test_turn_finished_failure_cause.py+++ b/tests/tui_gateway/test_turn_finished_failure_cause.py@@ -34,7 +34,7 @@ from tui_gateway import serverclass _InlineThread:"""Run the turn synchronously so tests observe its final state."""- def __init__(self, target=None, daemon=None, args=(), kwargs=None):+ def __init__(self, target=None, daemon=None, args=(), kwargs=None, name=None):self._target = targetself._args = argsself._kwargs = kwargs or {}diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 6aaf2b5debc..2de901dc48e 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -526,7 +526,16 @@ def _batch_status(combined: Dict[str, Any]) -> str:return "error" if child_results and all(r.get("status") not in ok for r in child_results) else "completed"-def _dispatch(+def _dispatch(**kwargs) -> Dict[str, Any]:+ from hermes_cli.backend_retirement import retirement++ with retirement.work() as admitted:+ if not admitted:+ return {"status": "rejected", "error": "backend is retiring; reconnect to continue"}+ return _dispatch_admitted(**kwargs)+++def _dispatch_admitted(*, delegation_id: str, goal: str, goals: Optional[List[str]], context: Optional[str],toolsets: Optional[List[str]], role: str, model: Optional[str], session_key: str,parent_session_id: Optional[str], runner: Callable[[], Dict[str, Any]], origin_ui_session_id: str,@@ -589,10 +598,16 @@ def _dispatch(finally:_finalize(delegation_id, result, status)+ from hermes_cli.backend_retirement import retirement++ # The outer dispatch reservation prevents a freeze during this handoff. Retain a worker+ # reservation too: the stall monitor may finalize its registry record before it really exits.+ retirement.acquire()try:- # Propagate the dispatching profile so the detached child resolves get_hermes_home() correctly.- executor.submit(propagate_context_to_thread(_worker))+ future = executor.submit(propagate_context_to_thread(_worker))+ future.add_done_callback(lambda _: retirement.release())except Exception as exc: # pragma: no cover — pool submit failure is rare+ retirement.release()with _records_lock:_records.pop(delegation_id, None)with _DB_LOCK, _transaction() as conn:diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 3a838627c5a..e318c087182 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -527,7 +527,9 @@ def _lock_in_submit_turn("""Under ``history_lock``: refuse watch-child races / malformed truncation, apply thecut, mark the turn running + in flight. Returns ``(err, survivor_fields)``."""fields = {}- with session["history_lock"]:+ with _session_turn_admission(session) as admitted:+ if not admitted:+ return _err(rid, 5035, "backend is retiring; reconnect to continue"), fields# A watch session's run lives in the PARENT turn (own running flag False); typing# mid-run would build a second agent racing the child on the same stored session.if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):@@ -971,7 +973,8 @@ def _spawn_side_agent(cleanup()_clear_session_context(session_tokens)- threading.Thread(target=run, daemon=True).start()+ if _start_session_work(run, name=f"side-agent-{task_id}") is None:+ return _err(rid, 5035, "backend is retiring; reconnect to continue")return _ok(rid, {"task_id": task_id})diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 37681600167..a7af899d11b 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -426,8 +426,8 @@ def _run_post_turn_followups(if _drain_queued_prompt(rid, sid, session):returnif goal_followup:- with session["history_lock"]:- if session.get("running"):+ with _session_turn_admission(session) as admitted:+ if not admitted or session.get("running"):return # user already sent something — their turn winssession["running"] = True_dispatch_followup_turn(rid, sid, session, goal_followup, "goal continuation dispatch")@@ -945,7 +945,6 @@ def _run_prompt_submit(session.pop("_auto_continue_scheduled", None)_emit_settled_session_info(sid, session, st.agent)_run_post_turn_followups(rid, sid, session, st.result, goal_followup)- run_thread = threading.Thread(target=run, daemon=True)# The handle is resolved BEFORE _sessions_lock: a profile session opens its own SessionDB through the# state registry, and _sessions_lock gates every create/close/prompt on this backend.with _routing_provenance_db(session) as routing_db, _sessions_lock:@@ -956,8 +955,7 @@ def _run_prompt_submit(# still run its turn, but its stamp stays (#106459).if registered is session:_reopen_routed_session_row(routing_db, sid, session)- session["_run_thread"] = run_thread- run_thread.start()+ can_start = _start_session_work(run, name=f"prompt-turn-{sid}", session=session) is not Noneif not can_start:with session["history_lock"]:session["running"] = Falsediff --git a/tui_gateway/rpc_dispatch.py b/tui_gateway/rpc_dispatch.pynew file mode 100644index 00000000000..fecbe5ef0df--- /dev/null+++ b/tui_gateway/rpc_dispatch.py@@ -0,0 +1,93 @@+"""JSON-RPC admission and worker dispatch. Rebound onto the server namespace."""++from __future__ import annotations++from .method_ctx import bind_module+++def handle_request(req: dict) -> dict | None:+ from hermes_cli.backend_retirement import retirement++ with retirement.work() as admitted:+ if not admitted:+ return _err(req.get("id"), 5035, "backend is retiring; reconnect to continue")+ return _handle_admitted_request(req)+++def _handle_admitted_request(req: dict) -> dict | None:+ normalized = _normalize_request(req)+ if isinstance(normalized, dict):+ return normalized+ rid, method, params = normalized+ if not (fn := _methods.get(method)):+ return _err(rid, -32601, f"unknown method: {method} — the client and the Hermes backend are out of sync "+ "(different versions); run `hermes update` and restart both")+ # Test doubles register straight into ``_methods`` without a contract; every production+ # handler comes through ``register_method`` and therefore has one.+ contract = _contracts.METHODS.get(method)+ if contract is not None:+ params, problem = _contracts.validate_params(contract, params)+ if problem is not None:+ return _err(rid, 4000, problem)+ token = _current_rpc_method.set(method)+ try:+ response = fn(rid, params)+ except ProfileUnavailableError as exc:+ return _err(rid, 4064, str(exc))+ finally:+ _current_rpc_method.reset(token)+ if contract is not None and isinstance(response, dict) and isinstance(response.get("result"), dict):+ _contracts.check_params_accepted(contract, params)+ _contracts.check_result(contract, response["result"])+ return response+++def dispatch(req: dict, transport: Optional[Transport] = None) -> dict | None:+ """Route inbound RPCs — long handlers to the pool (returns None; the worker writes its own+ response via the bound transport), everything else inline (returns the response dict).+ *transport* pins every write of this request — events included — to that transport;+ omitted → the module stdio transport (``tui_gateway.entry`` behaviour)."""+ t = transport or _stdio_transport+ token = bind_transport(t)+ try:+ from tui_gateway import server_requests+ if server_requests.is_response_frame(req):+ # The renderer answering one of OUR requests (clarify, approval, …): no response frame goes back.+ if not server_requests.resolve_response(req) and not _relay_compute_host_response(req):+ logger.debug("dropping response for unknown server request id=%r", req.get("id"))+ return None+ normalized = _normalize_request(req)+ if isinstance(normalized, dict):+ return normalized+ if normalized[1] not in _LONG_HANDLERS:+ return handle_request(req)+ from hermes_cli.backend_retirement import retirement++ # Reserve BEFORE enqueueing: a queued handler has accepted work even though no worker runs yet.+ if not retirement.acquire():+ return _err(req.get("id"), 5035, "backend is retiring; reconnect to continue")+ try:+ ctx = contextvars.copy_context() # the pool worker must see the bound transport+ if normalized[1] in _CONNECTOR_RPC_METHODS:+ ctx.run(_capture_connector_rpc_owner, normalized[2])++ def run():+ try:+ resp = _handle_admitted_request(req)+ except Exception as exc:+ resp = _err(req.get("id"), -32000, f"handler error: {exc}")+ if resp is not None:+ t.write(resp)+ future = _pool.submit(lambda: ctx.run(run))+ except BaseException:+ retirement.release()+ raise+ # Also releases cancelled queued futures; the worker's own finally would never execute.+ future.add_done_callback(lambda _: retirement.release())+ return None+ finally:+ reset_transport(token)+++def register(server):+ bind_module(globals(), server)diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex eebae0cdf00..dadbbd85925 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -818,33 +818,6 @@ def _normalize_request(req: Any) -> tuple[Any, str, dict] | dict:return rid, method, params if params is not None else {}-def handle_request(req: dict) -> dict | None:- normalized = _normalize_request(req)- if isinstance(normalized, dict):- return normalized- rid, method, params = normalized- if not (fn := _methods.get(method)):- return _err(rid, -32601, f"unknown method: {method} — the client and the Hermes backend are out of sync "- "(different versions); run `hermes update` and restart both")- # Test doubles register straight into ``_methods`` without a contract; every production- # handler comes through ``register_method`` and therefore has one.- contract = _contracts.METHODS.get(method)- if contract is not None:- params, problem = _contracts.validate_params(contract, params)- if problem is not None:- return _err(rid, 4000, problem)- token = _current_rpc_method.set(method)- try:- response = fn(rid, params)- except ProfileUnavailableError as exc:- return _err(rid, 4064, str(exc))- finally:- _current_rpc_method.reset(token)- if contract is not None and isinstance(response, dict) and isinstance(response.get("result"), dict):- _contracts.check_params_accepted(contract, params)- _contracts.check_result(contract, response["result"])- return response-def _current_session_steer_authority(session_id: str) -> tuple[Transport | None, dict | None]:"""Unforgeable steering authority for this RPC context: the public session id is only a lookup@@ -866,41 +839,6 @@ def _current_session_steer_authority(session_id: str) -> tuple[Transport | None,return transport, session-def dispatch(req: dict, transport: Optional[Transport] = None) -> dict | None:- """Route inbound RPCs — long handlers to the pool (returns None; the worker writes its own- response via the bound transport), everything else inline (returns the response dict).- *transport* pins every write of this request — events included — to that transport;- omitted → the module stdio transport (``tui_gateway.entry`` behaviour)."""- t = transport or _stdio_transport- token = bind_transport(t)- try:- from tui_gateway import server_requests- if server_requests.is_response_frame(req):- # The renderer answering one of OUR requests (clarify, approval, …): no response frame goes back.- if not server_requests.resolve_response(req) and not _relay_compute_host_response(req):- logger.debug("dropping response for unknown server request id=%r", req.get("id"))- return None- normalized = _normalize_request(req)- if isinstance(normalized, dict):- return normalized- if normalized[1] not in _LONG_HANDLERS:- return handle_request(req)- ctx = contextvars.copy_context() # the pool worker must see the bound transport- if normalized[1] in _CONNECTOR_RPC_METHODS:- ctx.run(_capture_connector_rpc_owner, normalized[2])-- def run():- try:- resp = handle_request(req)- except Exception as exc:- resp = _err(req.get("id"), -32000, f"handler error: {exc}")- if resp is not None:- t.write(resp)- _pool.submit(lambda: ctx.run(run))- return None- finally:- reset_transport(token)-def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:ready = session.get("agent_ready")@@ -3274,6 +3212,7 @@ from .mcp_rpc_helpers import summarize_server as _mcp_summarize_server # noqa:from . import ( # noqa: E402methods_voice as _methods_voice, methods_browser as _methods_browser, methods_slash as _methods_slash,methods_complete_helpers as _methods_complete_helpers, session_auto_continue as _session_auto_continue,+ rpc_dispatch as _rpc_dispatch,agent_callbacks as _agent_callbacks, session_history as _session_history,prompt_attachments as _prompt_attachments, session_notifications as _session_notifications,tool_progress as _tool_progress, change_watcher as _change_watcher,@@ -3294,7 +3233,7 @@ from . import ( # noqa: E402for _m in (_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,_session_compression, _change_watcher, _tool_progress, _session_notifications,- _prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue,+ _prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _rpc_dispatch,_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,_methods_browser_control, _methods_session, _methods_prompt, _methods_config,_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex 3ef4fb8cd64..a3f8c1c134d 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -115,7 +115,9 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->except Exception as exc:_notif_log_failure("auto-continue dispatch failed", exc)_notif_release_turn(session) # rebound from session_notifications- threading.Thread(target=kickoff, daemon=True).start()+ if _start_session_work(kickoff, name=f"auto-continue-{sid}") is None:+ session["_auto_continue_scheduled"] = False+ return Nonelogger.info("auto-continue scheduled for session %s (attempt %d, interrupted %.0fs ago)", session_key, attempt, age)return {"attempt": attempt, "interrupted_at": marker["started_at"]}@@ -286,8 +288,8 @@ def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any,def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:"""Fire a queued next-turn prompt if one is waiting and the session is idle. True when dispatched: the callerskips lower-priority follow-ups this cycle (the user's message wins)."""- with session["history_lock"]:- if session.get("_closing") or not (queued := session.get("queued_prompt")) or session.get("running"):+ with _session_turn_admission(session) as admitted:+ if not admitted or session.get("_closing") or not (queued := session.get("queued_prompt")) or session.get("running"):return Falsequeue_generation = int(session.get("_queued_prompt_generation", 0))_ac_set_queue(session, session.get("queued_prompts") or [])diff --git a/tui_gateway/session_lifecycle.py b/tui_gateway/session_lifecycle.pyindex 04ecc2ced81..92e790c5dcc 100644--- a/tui_gateway/session_lifecycle.py+++ b/tui_gateway/session_lifecycle.py@@ -12,6 +12,40 @@ import contextlibfrom .method_ctx import bind_module+def _session_turn_admission(session: dict):+ """Hold process admission until the history-locked running claim is visible to idle probes."""+ from hermes_cli.backend_retirement import retirement++ with retirement.work() as admitted, session["history_lock"]:+ yield admitted+++def _start_session_work(target, *, name: str, session: dict | None = None):+ """Reserve before spawning; release only after the worker (including cleanup) has unwound."""+ from agent.memory_provider import spawn_context_thread+ from hermes_cli.backend_retirement import retirement++ if not retirement.acquire():+ return None++ def run():+ try:+ target()+ finally:+ retirement.release()++ try:+ thread = spawn_context_thread(run, name=name)+ if session is not None:+ session["_run_thread"] = thread+ thread.start()+ return thread+ except BaseException:+ retirement.release()+ raise++def _notify_session_boundary(event_type: str, session_id: str | None, platform: str | None = None) -> None:"""Fire session lifecycle hooks with CLI parity."""with contextlib.suppress(Exception):diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex 3ba919d9fda..d31f5e18419 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -144,10 +144,11 @@ def _notif_release_turn(session: dict) -> None:def _notif_claim_turn(session: dict) -> bool:"""Claim the idle session (running=True) under history_lock; False if a turn is live."""- with session["history_lock"]:- claimed = not session.get("running")+ with _session_turn_admission(session) as admitted:+ if not admitted or session.get("running"):+ return Falsesession["running"] = True- return claimed+ return Truedef _notif_log_failure(what: str, exc: BaseException) -> None:@@ -552,8 +553,8 @@ def _poll_bot_live_delivery_once(sid: str, session: dict) -> bool:# lookup below costs a state.db open plus the exclusive active-session registry lock every pass (#111719).if not has_mailbox(home):return False- with session["history_lock"]:- if any(session.get(key) for key in (+ with _session_turn_admission(session) as admitted:+ if not admitted or any(session.get(key) for key in ("running", "_closing", "_finalized", "queued_prompt", "queued_prompts","_auto_continue_scheduled")) or session.get("agent") is None:return False