The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve Kanban execution PID and durable worker outcomes
Tekniumd4fd07d21239
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.pyindex 097bb0fe159..cbde203b782 100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@ -125,6 +125,7 @@ def bind_worker_context(frame):# Reclaim/timeout must track the executing interpreter, not its disposable viewer.conn.execute('UPDATE tasks SET worker_pid=? WHERE id=?', (os.getpid(), task.id))conn.execute('UPDATE task_runs SET worker_pid=? WHERE id=?', (os.getpid(), context['run_id']))+ kb._append_event(conn, task.id, 'worker_bound', {'pid': os.getpid(), 'claim_lock': context['claim_lock']}, run_id=context['run_id'])os.environ.update(env)os.chdir(context['workspace'])from agent.shell_hooks import register_from_config@@ -135,6 +136,36 @@ def run_worker_turns(agent, frame, history):context = json.loads(frame['policy'].get('kanban_json') or 'null')if context is None:return agent.run_conversation(frame['text'], conversation_history=history)+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE+ code = 1+ try:+ result = _run_task_turns(agent, frame, history, context)+ code = KANBAN_RATE_LIMIT_EXIT_CODE if result.get('failed') and result.get('failure_reason') in {'rate_limit', 'billing'} else int(bool(result.get('failed') or result.get('interrupted')))+ return result+ finally:+ import os+ from hermes_cli.kanban_db_connect import connect_closing+ from hermes_cli import kanban_db as kb+ with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):+ row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",+ (context['task_id'], context['run_id'])).fetchone()+ if row and json.loads(row[0]) == {'pid': os.getpid(), 'claim_lock': context['claim_lock']}:+ # Closing a run clears its claim/PID and replaces metadata; keep the+ # result in the immutable attempt event stream instead.+ kb._append_event(conn, context['task_id'], 'worker_result',+ {'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code}, run_id=context['run_id'])+++def worker_exit_code(path, params):+ """Read only the dispatcher's exact attempt; never infer success from admission settlement."""+ with closing(sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True)) as conn:+ row = conn.execute("SELECT payload FROM task_events WHERE run_id=? AND task_id=? AND kind='worker_result' ORDER BY id DESC LIMIT 1",+ (params['run_id'], params['task_id'])).fetchone()+ result = json.loads(row[0]) if row else {}+ return result.get('exit_code', 1) if result.get('claim_lock') == params['claim_lock'] else 1+++def _run_task_turns(agent, frame, history, context):from agent.skill_commands import build_preloaded_skills_promptskills, loaded, missing = build_preloaded_skills_prompt(context['skills'], task_id=agent.session_id)if missing and not loaded:diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 13505aa71a3..668801c0078 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -750,9 +750,12 @@ class _DeadWorker:return "rate_limited" if self.rate_limited else "crashed"-def _classify_dead_worker(pid: int, claimer: Optional[str]) -> _DeadWorker:+def _classify_dead_worker(pid: int, claimer: Optional[str], exit_code=None) -> _DeadWorker:"""Map a dead worker's reaped exit status to its reclaim bookkeeping."""kind, code = _classify_worker_exit(pid)+ if exit_code is not None:+ code = exit_code+ kind = "rate_limited" if code == _kb.KANBAN_RATE_LIMIT_EXIT_CODE else ("clean_exit" if code == 0 else "nonzero_exit")if kind == "clean_exit":# rc=0 while still ``running``: usually the work succeeded and only the# paperwork was skipped; the corrective sentence reaches the retry@@ -825,7 +828,15 @@ def _reclaim_dead_workers(conn: sqlite3.Connection) -> _CrashSweep:continuepid = int(row["worker_pid"])- dead = _classify_dead_worker(pid, row["claim_lock"])+ # Managed interpreters are children of the authority, not this dispatcher.+ # Their exact-run result survives a dispatcher restart and cannot be reaped here.+ run = conn.execute(+ "SELECT e.payload FROM task_events e JOIN tasks t ON t.current_run_id=e.run_id "+ "WHERE t.id=? AND e.task_id=t.id AND e.kind='worker_result' ORDER BY e.id DESC LIMIT 1",+ (row["id"],)).fetchone()+ result = _kb._json_dict(run["payload"]) if run else {}+ exit_code = result.get("exit_code") if result.get("claim_lock") == row["claim_lock"] and result.get("pid") == pid else None+ dead = _classify_dead_worker(pid, row["claim_lock"], exit_code)retry_status = _kb._retry_status_for_run(conn, row["id"])dead.event_payload["retry_status"] = retry_statuscur = conn.execute(@@ -1097,12 +1108,17 @@ def _record_task_failure(return True-def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int) -> None:- """Record the spawned child's pid + emit a ``spawned`` event carrying it."""+def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int, *, run_id=None, claim_lock=None) -> None:+ """Publish the launcher only while this claim has no executing worker yet."""with _kb.write_txn(conn):- conn.execute("UPDATE tasks SET worker_pid = ? WHERE id = ?", (int(pid), task_id))- run_id = _kb._current_run_id(conn, task_id)- if run_id is not None:+ if run_id is None:+ run_id = _kb._current_run_id(conn, task_id)+ cur = conn.execute(+ "UPDATE tasks SET worker_pid = ? WHERE id = ? AND status = 'running' "+ "AND current_run_id IS ? AND worker_pid IS NULL "+ "AND (? IS NULL OR claim_lock = ?)",+ (int(pid), task_id, run_id, claim_lock, claim_lock))+ if cur.rowcount:conn.execute("UPDATE task_runs SET worker_pid = ? WHERE id = ?", (int(pid), run_id))_kb._append_event(conn, task_id, "spawned", {"pid": int(pid)}, run_id=run_id)@@ -1575,7 +1591,7 @@ def _dispatch_lane_task(try:pid = _call_spawn_fn(spawn_fn if spawn_fn is not None else _default_spawn, claimed, str(workspace), board)if pid:- _set_worker_pid(conn, claimed.id, int(pid))+ _set_worker_pid(conn, claimed.id, int(pid), run_id=claimed.current_run_id, claim_lock=claimed.claim_lock)# Fires AFTER the PID (when reported) is durably persisted. Best-effort._kb._fire_worker_spawned_hook(conn, claimed, str(workspace), pid, board=board)# consecutive_failures is deliberately NOT reset here: resetting ondiff --git a/hermes_cli/kanban_worker_client.py b/hermes_cli/kanban_worker_client.pyindex 76ec172760e..6c686852cb0 100644--- a/hermes_cli/kanban_worker_client.py+++ b/hermes_cli/kanban_worker_client.py@@ -4,7 +4,7 @@ import osimport sys-async def run(params):+async def run(params, board_db):from hermes_cli.gateway_client import connect_gateway, GatewayClientErrorif os.environ.get('HERMES_TUI_GATEWAY_URL'):raise GatewayClientError('Kanban requires the assigned local profile owner')@@ -17,20 +17,22 @@ async def run(params):receipt = await client.rpc('prompt.receipt', session_id=sid, admission_id=receipt['admission_id'])if receipt['status'] == 'unknown':raise GatewayClientError('Kanban execution unknown; retained by owner')- return 0 if receipt.get('outcome') == 'completed' else 1+ from gateway.session_kanban import worker_exit_code+ return worker_exit_code(board_db, params)def main():try:params = {'board': os.environ['HERMES_KANBAN_BOARD'], 'task_id': os.environ['HERMES_KANBAN_TASK'],'run_id': int(os.environ['HERMES_KANBAN_RUN_ID']), 'claim_lock': os.environ['HERMES_KANBAN_CLAIM_LOCK']}+ board_db = os.environ['HERMES_KANBAN_DB']# Owner startup must never inherit this worker's task/tool/goal identity.for key in list(os.environ):if key.startswith('HERMES_KANBAN_') and key != 'HERMES_KANBAN_HOME':os.environ.pop(key)for key in ('HERMES_SESSION_SOURCE', 'HERMES_TENANT', 'TERMINAL_CWD'):os.environ.pop(key, None)- return asyncio.run(run(params))+ return asyncio.run(run(params, board_db))except (KeyError, ValueError, OSError) as exc:print(f'Kanban owner refused: {exc}', file=sys.stderr)return 1diff --git a/tests/gateway/fixtures/kanban_owner_probe.py b/tests/gateway/fixtures/kanban_owner_probe.pyindex d827c1d2018..449bc6a918f 100644--- a/tests/gateway/fixtures/kanban_owner_probe.py+++ b/tests/gateway/fixtures/kanban_owner_probe.py@@ -8,6 +8,7 @@ from pathlib import Pathimport subprocessimport sysimport threading+import timefrom local_recovery_probe import daemon, websocket, rpc@@ -21,6 +22,19 @@ class Model(BaseHTTPRequestHandler):messages = body.get('messages', [])if messages:self.server.requests.append(body)+ if messages and not self.server.blocked.is_set():+ self.server.blocked.set()+ assert self.server.release.wait(65)+ if messages and self.server.mode in {'rate_limit', 'billing'}:+ payload = json.dumps({'error': {'message': 'Rate limit exceeded' if self.server.mode == 'rate_limit' else 'Insufficient quota',+ 'type': 'rate_limit_error' if self.server.mode == 'rate_limit' else 'insufficient_quota',+ 'code': 'rate_limit_exceeded' if self.server.mode == 'rate_limit' else 'insufficient_quota'}}).encode()+ self.send_response(429)+ self.send_header('Content-Type', 'application/json')+ self.send_header('Content-Length', str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+ returnhas_result = any(m['role'] == 'tool' for m in messages)message = {'role': 'assistant', 'content': 'OWNED_COMPLETE'}finish = 'stop'@@ -52,6 +66,8 @@ def main():os.environ['HERMES_KANBAN_HOME'] = str(home)peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)peer.requests = []+ peer.mode = os.environ.get('KANBAN_PROBE_MODE', 'complete')+ peer.blocked, peer.release = threading.Event(), threading.Event()threading.Thread(target=peer.serve_forever, daemon=True).start()url = f'http://127.0.0.1:{peer.server_port}/v1'os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)@@ -64,7 +80,7 @@ def main():hook.write_text('from pathlib import Path\nPath(' + repr(str(home / 'hook-effect')) + ').write_text("accepted")\n', encoding='utf-8')cfg = {'gateway': {'multiplex_profiles': False}, 'model': {'provider': 'custom', 'default': 'loop-model', 'base_url': url},'auxiliary': {'title_generation': {'enabled': False}}, 'platform_toolsets': {'cli': ['terminal', 'file']},- 'terminal': {'backend': 'local'}, 'kanban': {'dispatch_in_gateway': False},+ 'terminal': {'backend': 'local'}, 'agent': {'api_max_retries': 1}, 'kanban': {'dispatch_in_gateway': False},'hooks': {'post_tool_call': [{'command': f'{sys.executable} {hook}'}]}}(home / 'config.yaml').write_text(json.dumps(cfg), encoding='utf-8')from hermes_cli import kanban_db as kb@@ -72,27 +88,82 @@ def main():from hermes_cli import kanban_db_dispatch as dispatch# Pin the installed launcher to this checkout for base/fixed argv comparisons.dispatch._resolve_hermes_argv = lambda: [sys.executable, '-m', 'hermes_cli.main']- _worker_argv = dispatch._worker_argv+ os.environ['HERMES_KANBAN_CRASH_GRACE_SECONDS'] = '0'with closing(connect(board='owned')) as conn:tid = kb.create_task(conn, title='KANBAN_TASK_SENTINEL', body='Acceptance: finish owned card', assignee='default',- workspace_kind='dir', workspace_path=str(workspace), skills=['owned-skill'], goal_mode=True, goal_max_turns=2)- kb.recompute_ready(conn)- task = kb.claim_task(conn, tid)+ workspace_kind='dir', workspace_path=str(workspace), skills=['owned-skill'],+ goal_mode=peer.mode == 'complete', goal_max_turns=2,+ max_runtime_seconds=3600 if peer.mode == 'timeout' else None)env = dict(os.environ)- worker_env = env | {'HERMES_KANBAN_TASK': tid, 'HERMES_KANBAN_BOARD': 'owned',- 'HERMES_KANBAN_RUN_ID': str(task.current_run_id), 'HERMES_KANBAN_CLAIM_LOCK': task.claim_lock,- 'HERMES_KANBAN_DB': str(kb.kanban_db_path(board='owned'))}- params = dict(task_id=tid, board='owned', run_id=task.current_run_id, claim_lock=task.claim_lock)- receipt = {}+ receipt, clients = {}, []+ original_popen = subprocess.Popen+ def spawn(*args, **kwargs):+ child = original_popen(*args, **kwargs)+ if 'hermes_cli.kanban_worker_client' in args[0]:+ clients.append(child)+ if peer.mode == 'timeout':+ assert peer.blocked.wait(55), 'managed worker did not reach loopback'+ with closing(connect(board='owned')) as snapshot:+ receipt['managed_pid'] = kb.get_task(snapshot, tid).worker_pid+ return child+ def wait_for(predicate):+ deadline = time.monotonic() + 60+ while time.monotonic() < deadline:+ if predicate():+ return+ time.sleep(.05)+ raise AssertionError(('deadline', receipt))try:with daemon(root, home, env, barrier=False) as (proc, desc):- command = _worker_argv(task, 'default', str(home))- if os.environ.get('KANBAN_PROBE_TRACE'):- command = ['strace', '-f', '-e', 'trace=openat', '-o', str(home / 'client.strace'), *command]- result = subprocess.run(command, cwd=workspace, env=worker_env,- stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=80)- receipt.update(worker_rc=result.returncode, stdout=result.stdout, stderr=result.stderr)- assert result.returncode == 0, receipt+ subprocess.Popen = spawn+ try:+ with closing(connect(board='owned')) as conn:+ launched = dispatch.dispatch_once(conn, board='owned', max_spawn=1)+ assert [s[0] for s in launched.spawned] == [tid], launched+ task = kb.get_task(conn, tid)+ params = dict(task_id=tid, board='owned', run_id=task.current_run_id, claim_lock=task.claim_lock)+ assert peer.blocked.wait(55), 'model never reached'+ active = kb.get_task(conn, tid)+ receipt.update(client_pid=clients[0].pid, stored_pid=active.worker_pid, run_id=task.current_run_id)+ if peer.mode == 'timeout':+ receipt['pid_preserved'] = active.worker_pid == receipt['managed_pid'] != clients[0].pid+ # Deterministically elapse this owned attempt; keep real timeout/kill logic.+ conn.execute('UPDATE task_runs SET started_at=? WHERE id=?', (int(time.time()) - 3601, task.current_run_id))+ conn.commit()+ swept = dispatch.dispatch_once(conn, board='owned', max_spawn=0)+ receipt.update(timed_out=swept.timed_out, managed_dead=not kb._pid_alive(receipt['managed_pid']))+ assert receipt['pid_preserved'] and receipt['managed_dead'], receipt+ elif peer.mode == 'crash':+ import signal+ os.kill(active.worker_pid, signal.SIGKILL)+ peer.release.set()+ if peer.mode != 'timeout':+ wait_for(lambda: not kb._pid_alive(active.worker_pid))+ wait_for(lambda: not kb._pid_alive(clients[0].pid))+ dispatch.reap_worker_zombies()+ receipt['client_exit'] = dispatch._classify_worker_exit(clients[0].pid)+ dispatch._recent_worker_exits.clear()+ swept = dispatch.dispatch_once(conn, board='owned', max_spawn=0)+ task = kb.get_task(conn, tid)+ run = dict(conn.execute('SELECT * FROM task_runs WHERE id=?', (params['run_id'],)).fetchone())+ from gateway.session_kanban import worker_exit_code+ assert worker_exit_code(kb.kanban_db_path(board='owned'), params | {'claim_lock': 'foreign'}) == 1+ receipt.update(task_status=task.status, failures=task.consecutive_failures, run_outcome=run['outcome'],+ run_metadata=kb._json_dict(run['metadata']), rate_limited=swept.rate_limited,+ cooldown=dispatch.check_respawn_guard(conn, tid))+ if peer.mode in {'rate_limit', 'billing'}:+ assert task.status == 'ready' and task.consecutive_failures == 0 and run['outcome'] == 'rate_limited', receipt+ assert receipt['client_exit'] == ('rate_limited', kb.KANBAN_RATE_LIMIT_EXIT_CODE), receipt+ assert receipt['cooldown'] == 'rate_limit_cooldown', receipt+ elif peer.mode == 'crash':+ assert task.status == 'ready' and task.consecutive_failures == 1 and run['outcome'] == 'crashed', receipt+ elif peer.mode == 'timeout':+ assert task.status == 'ready' and task.consecutive_failures == 1 and run['outcome'] == 'timed_out', receipt+ finally:+ subprocess.Popen = original_popen+ if peer.mode != 'complete':+ return+ assert receipt['client_exit'] == ('clean_exit', 0), receiptasync def retry():async with websocket(home, desc) as ws:first = await rpc(ws, 'kanban.run', **params)@@ -114,11 +185,16 @@ def main():task_context='KANBAN_TASK_SENTINEL' in wire, skill_context='KANBAN_SKILL_SENTINEL' in wire,hook_effect=(home / 'hook-effect').exists())finally:+ peer.release.set()+ for child in clients:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=10)peer.shutdown()peer.server_close()(home / 'model-requests.json').write_text(json.dumps(peer.requests, indent=2), encoding='utf-8')(home / 'receipt.json').write_text(json.dumps(receipt, indent=2), encoding='utf-8')- print(json.dumps(receipt))+ print(json.dumps(receipt))if __name__ == '__main__':diff --git a/tests/gateway/test_session_kanban.py b/tests/gateway/test_session_kanban.pyindex 388f82cb14c..7526b0febb0 100644--- a/tests/gateway/test_session_kanban.py+++ b/tests/gateway/test_session_kanban.py@@ -51,19 +51,43 @@ def test_claim_freezes_task_policy_and_rejects_forgery(tmp_path, monkeypatch):build_policy({'source': 'kanban', 'cwd': str(workspace)}, config)-def test_real_dispatcher_argv_completes_owned_task(tmp_path):[email protected]('mode', ['complete', 'timeout', 'rate_limit', 'billing', 'crash'])+def test_real_dispatcher_lifecycle(tmp_path, mode):import osimport subprocessimport sysrepo = Path(__file__).resolve().parents[2]env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ', 'SYSTEMROOT') if k in os.environ}- env.update(HOME=str(tmp_path / 'home'), HERMES_HOME=str(tmp_path / 'state'), PYTHONPATH=str(repo))+ env.update(HOME=str(tmp_path / 'home'), HERMES_HOME=str(tmp_path / 'state'), PYTHONPATH=str(repo), KANBAN_PROBE_MODE=mode)result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'kanban_owner_probe.py')],env=env, cwd=repo, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=150)assert result.returncode == 0, result.stdout + result.stderrreceipt = json.loads((tmp_path / 'state' / 'receipt.json').read_text())+ print(json.dumps(receipt))+ if mode != 'complete':+ assert receipt['task_status'] == 'ready'+ returnassert receipt['task_status'] == 'done' and receipt['source'] == 'kanban'assert receipt['tools'] and receipt['task_context'] and receipt['skill_context'] and receipt['hook_effect']assert receipt['admissions'] == 1 and receipt['retry_same_session']assert receipt['goal_continuation'] and receipt['stable_prefix']print(json.dumps(receipt))+++def test_late_launcher_cannot_stamp_replacement_claim(tmp_path, monkeypatch):+ from contextlib import closing+ from hermes_cli import kanban_db as kb, kanban_db_dispatch as dispatch+ from hermes_cli.kanban_db_connect import connect+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setenv('HERMES_KANBAN_HOME', str(tmp_path))+ monkeypatch.delenv('HERMES_KANBAN_DB', raising=False)+ monkeypatch.delenv('HERMES_DELEGATED_CHILD', raising=False)+ with closing(connect(board='owned')) as conn:+ tid = kb.create_task(conn, title='Owned race', assignee='default')+ old = kb.claim_task(conn, tid)+ kb.block_task(conn, tid, reason='replace claim', expected_run_id=old.current_run_id)+ kb.unblock_task(conn, tid)+ new = kb.claim_task(conn, tid)+ dispatch._set_worker_pid(conn, tid, 424242, run_id=old.current_run_id, claim_lock=old.claim_lock)+ assert kb.get_task(conn, tid).worker_pid is None+ assert conn.execute('SELECT worker_pid FROM task_runs WHERE id=?', (new.current_run_id,)).fetchone()[0] is None