The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: preserve Kanban board discovery and unknown owner attempts
Teknium90e2b2eb3adb
diff --git a/gateway/session_kanban.py b/gateway/session_kanban.pyindex cbde203b782..eef41e63198 100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@ -17,13 +17,13 @@ def build_kanban_policy(connection, params, config):raise RuntimeStoreError('permission_denied')if actor.profile_id != authority.profile_id:raise RuntimeStoreError('profile_mismatch')- if (set(params) != {'board', 'task_id', 'run_id', 'claim_lock'}+ if (set(params) not in ({'board', 'task_id', 'run_id', 'claim_lock'}, {'board', 'task_id', 'run_id', 'claim_lock', 'db'})or any(not isinstance(params[k], str) or not params[k] for k in ('board', 'task_id', 'claim_lock'))or type(params['run_id']) is not int):raise RuntimeStoreError('invalid_params')try:board = kb._require_slug(params['board'])- path = kb.kanban_db_path(board=board).resolve()+ path = Path(params['db']).resolve(strict=True) if 'db' in params else kb.kanban_db_path(board=board).resolve()with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True)) as conn:conn.row_factory = sqlite3.Rowtask = kb.get_task(conn, params['task_id'])@@ -34,6 +34,10 @@ def build_kanban_policy(connection, params, config):raise RuntimeStoreError('stale_kanban_claim')if Path(resolve_profile_env(task.assignee)).resolve() != Path(authority.profile_id).resolve():raise RuntimeStoreError('profile_mismatch')+ bound = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='owner_admitted' ORDER BY id DESC LIMIT 1",+ (task.id, task.current_run_id)).fetchone()+ if bound and json.loads(bound[0])['request_id'] != 'kanban:' + json.dumps([board, task.id, task.current_run_id], separators=(',', ':')):+ raise RuntimeStoreError('stale_kanban_claim')context = kb.build_worker_context(conn, task.id)except (ValueError, OSError, sqlite3.Error) as exc:raise RuntimeStoreError('invalid_kanban_claim') from exc@@ -47,11 +51,12 @@ def build_kanban_policy(connection, params, config):if policy.model is None:from gateway.run import _resolve_gateway_modelpolicy = replace(policy, model=_resolve_gateway_model(policy.config()))- context = dict(params, db=str(path), workspace=cwd, branch=task.branch_name, tenant=task.tenant,+ context = dict(params, workspace=cwd, branch=task.branch_name, tenant=task.tenant,profile=task.assignee, workspaces_root=str(kb.workspaces_root(board=board).resolve()),skills=list(task.skills or ()), goal_mode=task.goal_mode, goal_max_turns=task.goal_max_turns,goal_text='\n\n'.join(p for p in (task.title, task.body) if p), context=context,max_runtime_seconds=task.max_runtime_seconds, accept_hooks=True)+ context['db'] = str(path)request = json.loads(policy.request_json)request.update(source='kanban', board=board, task_id=task.id, run_id=task.current_run_id)return replace(policy, source='kanban', platform='cli', toolsets=tuple(sorted(set(policy.toolsets) | {'kanban'})),@@ -76,7 +81,7 @@ async def run_task(connection, params):if saved:policy = restore_policy(saved['policy'])context = json.loads(policy.kanban_json or '{}')- if (not connection.native_owner or set(params) != {'board', 'task_id', 'run_id', 'claim_lock'}+ if (not connection.native_owner or set(params) not in ({'board', 'task_id', 'run_id', 'claim_lock'}, {'board', 'task_id', 'run_id', 'claim_lock', 'db'})or any(params[k] != context.get(k) for k in params)):raise RuntimeStoreError('permission_denied')from gateway.session_local_recovery import restore_local_session@@ -85,6 +90,23 @@ async def run_task(connection, params):policy, private = build_kanban_policy(connection, params, _load_gateway_config())ref = create_local_session(authority, connection.actor, {'request_id': request_id},trusted_policy=policy, trusted_secrets=private)+ from hermes_cli.kanban_db_connect import connect_closing+ from hermes_cli import kanban_db as kb+ import os+ import psutil+ context = json.loads(policy.kanban_json)+ with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):+ task = kb.get_task(conn, params['task_id'])+ if task and task.status == 'running' and task.current_run_id == params['run_id'] and task.claim_lock == params['claim_lock']:+ marker = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='owner_admitted' ORDER BY id DESC LIMIT 1",+ (task.id, task.current_run_id)).fetchone()+ if marker and json.loads(marker[0])['session_id'] != ref.session_id:+ raise RuntimeStoreError('stale_kanban_claim')+ if not marker:+ kb._append_event(conn, task.id, 'owner_admitted',+ {'db': str(Path(authority.db.db_path).resolve()), 'session_id': ref.session_id,+ 'request_id': request_id, 'pid': os.getpid(), 'birth': psutil.Process().create_time()},+ run_id=task.current_run_id)await connection.resume(ref, {})receipt = await authority.submit(connection.actor, Submission(request_id, ref,{'text': f'work kanban task {params["task_id"]}'}, 'queue'))diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex ec7f16f05ef..5f41f55f594 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -2304,7 +2304,10 @@ def release_stale_claims(conn: sqlite3.Connection, *, signal_fn=None) -> int:"WHERE status = 'running' AND claim_expires IS NOT NULL "" AND claim_expires < ?", (now,),).fetchall()+ from hermes_cli.kanban_owner_recovery import owner_reclaim_pausedfor row in stale:+ if owner_reclaim_paused(conn, row["id"]):+ continuehost_local = (row["claim_lock"] or "").startswith(host_prefix)hb = row["last_heartbeat_at"]# Backstop: a heartbeat older than the max-stale threshold means nodiff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex 668801c0078..405915aaf7d 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -436,7 +436,10 @@ def enforce_max_runtime(conn: sqlite3.Connection, *, signal_fn=None) -> list[str" AND COALESCE(r.started_at, t.started_at) IS NOT NULL "" AND t.worker_pid IS NOT NULL").fetchall()+ from hermes_cli.kanban_owner_recovery import owner_reclaim_pausedfor row in rows:+ if owner_reclaim_paused(conn, row["id"]):+ continuelock = row["claim_lock"] or ""if not lock.startswith(host_prefix):continue@@ -536,7 +539,10 @@ def detect_stale_running("WHERE t.status = 'running'").fetchall()+ from hermes_cli.kanban_owner_recovery import owner_reclaim_pausedfor row in rows:+ if owner_reclaim_paused(conn, row["id"]):+ continueif row["active_started_at"] is None:continueelapsed = now - int(row["active_started_at"])@@ -619,7 +625,10 @@ def reconcile_orphaned_running(conn: sqlite3.Connection) -> list[str]:"WHERE status = 'running' "" AND (claim_lock IS NULL OR claim_expires IS NULL)").fetchall()+ from hermes_cli.kanban_owner_recovery import owner_reclaim_pausedfor row in rows:+ if owner_reclaim_paused(conn, row["id"]):+ continuetid = row["id"]pid = row["worker_pid"]if pid and _kb._pid_alive(pid):@@ -815,7 +824,10 @@ def _reclaim_dead_workers(conn: sqlite3.Connection) -> _CrashSweep:"WHERE status = 'running' AND worker_pid IS NOT NULL").fetchall()host_prefix = _kb._host_prefix()+ from hermes_cli.kanban_owner_recovery import owner_reclaim_pausedfor row in rows:+ if owner_reclaim_paused(conn, row["id"]):+ continuelock = row["claim_lock"] or ""if not lock.startswith(host_prefix):continuediff --git a/hermes_cli/kanban_owner_recovery.py b/hermes_cli/kanban_owner_recovery.pynew file mode 100644index 00000000000..a6350d04474--- /dev/null+++ b/hermes_cli/kanban_owner_recovery.py@@ -0,0 +1,31 @@+"""Read-only canonical admission fences for dispatcher reclaim paths."""+from contextlib import closing+import json+from pathlib import Path+import sqlite3+import psutil+++def owner_reclaim_paused(conn, task_id):+ """Missing/ambiguous owner receipts never authorize another attempt."""+ marker = 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='owner_admitted' ORDER BY e.id DESC LIMIT 1",+ (task_id,)).fetchone()+ if marker is None:+ return False+ try:+ binding = json.loads(marker['payload'])+ with closing(sqlite3.connect(Path(binding['db']).as_uri() + '?mode=ro', uri=True)) as owner:+ row = owner.execute('SELECT status,outcome FROM session_admissions WHERE target_session_id=? AND request_id=?',+ (binding['session_id'], binding['request_id'])).fetchone()+ if row is not None and row[0] == 'terminal':+ # Discard acknowledges uncertainty, not permission to repeat effects.+ return row[1] == 'interrupted'+ if row is None or row[0] in {'queued', 'unknown'}:+ return True+ return psutil.Process(binding['pid']).create_time() != binding['birth']+ except (OSError, ValueError, KeyError, sqlite3.Error):+ return True+ except psutil.Error:+ return Truediff --git a/hermes_cli/kanban_worker_client.py b/hermes_cli/kanban_worker_client.pyindex 6c686852cb0..62b1ef07027 100644--- a/hermes_cli/kanban_worker_client.py+++ b/hermes_cli/kanban_worker_client.py@@ -1,6 +1,7 @@"""Dispatcher subprocess: submit one claim to its profile owner; never run an agent."""import asyncioimport os+from pathlib import Pathimport sys@@ -9,7 +10,7 @@ async def run(params, board_db):if os.environ.get('HERMES_TUI_GATEWAY_URL'):raise GatewayClientError('Kanban requires the assigned local profile owner')async with connect_gateway() as client:- accepted = await client.rpc('kanban.run', **params)+ accepted = await client.rpc('kanban.run', **dict(params, db=str(Path(board_db).resolve())))sid, receipt = accepted['session_id'], accepted['receipt']print(f'Session: {sid}', file=sys.stderr)while receipt['status'] not in {'terminal', 'unknown'}:diff --git a/tests/gateway/fixtures/kanban_owner_probe.py b/tests/gateway/fixtures/kanban_owner_probe.pyindex 449bc6a918f..3d594231e86 100644--- a/tests/gateway/fixtures/kanban_owner_probe.py+++ b/tests/gateway/fixtures/kanban_owner_probe.py@@ -156,7 +156,7 @@ def main():assert receipt['client_exit'] == ('rate_limited', kb.KANBAN_RATE_LIMIT_EXIT_CODE), receiptassert receipt['cooldown'] == 'rate_limit_cooldown', receiptelif peer.mode == 'crash':- assert task.status == 'ready' and task.consecutive_failures == 1 and run['outcome'] == 'crashed', receipt+ assert task.status == 'running' and task.consecutive_failures == 0 and run['outcome'] is None, receiptelif peer.mode == 'timeout':assert task.status == 'ready' and task.consecutive_failures == 1 and run['outcome'] == 'timed_out', receiptfinally:diff --git a/tests/gateway/fixtures/kanban_recovery_probe.py b/tests/gateway/fixtures/kanban_recovery_probe.pynew file mode 100644index 00000000000..99807157ae0--- /dev/null+++ b/tests/gateway/fixtures/kanban_recovery_probe.py@@ -0,0 +1,183 @@+"""Disposable ordinary owner, actual dispatcher, custom paths and process death."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+import os+from pathlib import Path+import signal+import sqlite3+import subprocess+import sys+import threading+import time++from kanban_owner_probe import Model as BaseModel+from local_recovery_probe import daemon, websocket, rpc+++class Model(BaseModel):+ def do_POST(self):+ try:+ super().do_POST()+ except (BrokenPipeError, ConnectionResetError):+ pass+++def main():+ root = Path(__file__).resolve().parents[3]+ home = Path(os.environ['HERMES_HOME'])+ home.mkdir(parents=True)+ user = Path(os.environ['HOME'])+ user.mkdir(parents=True)+ mode = os.environ['KANBAN_RECOVERY_MODE']+ owner = home / 'profiles/assigned' if mode == 'cross_profile' else home+ owner.mkdir(parents=True, exist_ok=True)+ os.environ['HERMES_KANBAN_HOME'] = str(home / 'shared')+ board_path = home / 'custom.sqlite' if mode == 'custom' else home / 'shared/kanban/boards/owned/kanban.db'+ os.environ['HERMES_KANBAN_DB'] = str(board_path)+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests, peer.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'+ workspace = home / 'workspace'+ workspace.mkdir()+ cfg = {'gateway': {'multiplex_profiles': False},+ 'model': {'provider': 'custom', 'default': 'frozen-model', 'base_url': url},+ 'auxiliary': {'title_generation': {'enabled': False}},+ 'platform_toolsets': {'cli': []}, 'kanban': {'dispatch_in_gateway': False}}+ (owner / 'config.yaml').write_text(json.dumps(cfg))+ env = dict(os.environ, HERMES_HOME=str(owner), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ # Already-running owner deliberately has no dispatcher-specific board overrides.+ for key in list(env):+ if key.startswith('HERMES_KANBAN_'):+ env.pop(key)+ from hermes_cli import kanban_db as kb, kanban_db_dispatch as dispatch+ from hermes_cli.kanban_db_connect import connect+ os.environ['HERMES_KANBAN_CRASH_GRACE_SECONDS'] = '0'+ clients, receipt = [], {'mode': mode}+ original_popen = subprocess.Popen+ def spawn(*args, **kwargs):+ if 'hermes_cli.kanban_worker_client' in args[0]:+ # Trace only the transport client's tree, not the independently started owner.+ args = (['strace', '-f', '-e', 'trace=openat', '-o', str(home / 'client.strace'), *args[0]], *args[1:])+ child = original_popen(*args, **kwargs)+ clients.append(child)+ return child+ return original_popen(*args, **kwargs)+ def wait_for(predicate):+ until = time.monotonic() + 50+ while time.monotonic() < until:+ if predicate():+ return+ time.sleep(.05)+ raise AssertionError(('deadline', receipt, [p.poll() for p in clients],+ list((home / 'shared').rglob('*.log'))))+ def admission():+ with closing(sqlite3.connect((owner / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:+ db.row_factory = sqlite3.Row+ row = db.execute('SELECT * FROM session_admissions').fetchone()+ return dict(row) if row else None+ async def retry(desc, params, *, resolve=False):+ async with websocket(owner, desc) as ws:+ answer = await rpc(ws, 'kanban.run', **params)+ assert 'result' in answer, answer+ for changed in ({'board': 'foreign'}, {'claim_lock': 'forged'}, {'db': str(home / 'other.sqlite')}, {'run_id': params['run_id'] + 1}):+ bad = await rpc(ws, 'kanban.run', **(params | changed))+ assert 'error' in bad, bad+ if resolve:+ value = answer['result']['receipt']+ rejected = await rpc(ws, 'prompt.resolve_unknown', session_id=answer['result']['session_id'],+ admission_id=value['admission_id'], execution_generation=value['execution_generation'] + 1)+ assert 'error' in rejected, rejected+ result = await rpc(ws, 'prompt.resolve_unknown', session_id=answer['result']['session_id'],+ admission_id=value['admission_id'], execution_generation=value['execution_generation'])+ assert 'result' in result, result+ return answer['result']+ try:+ with closing(connect(board='owned')) as conn:+ tid = kb.create_task(conn, title='RECOVERY_TASK', assignee='assigned' if mode == 'cross_profile' else 'default',+ workspace_kind='dir', workspace_path=str(workspace), goal_mode=True, goal_max_turns=2)+ with daemon(root, owner, env, barrier=False) as (proc, desc):+ subprocess.Popen = spawn+ try:+ launched = dispatch.dispatch_once(conn, board='owned', max_spawn=1)+ finally:+ subprocess.Popen = original_popen+ assert [s[0] for s in launched.spawned] == [tid], launched+ task = kb.get_task(conn, tid)+ params = dict(board='owned', task_id=tid, run_id=task.current_run_id, claim_lock=task.claim_lock,+ db=str(board_path.resolve()))+ wait_for(lambda: peer.blocked.is_set() or any(p.poll() is not None for p in clients))+ assert peer.blocked.is_set(), 'Owner failed to discover dispatcher board'+ active = kb.get_task(conn, tid)+ first = admission()+ receipt.update(session_id=first['target_session_id'], run_id=task.current_run_id, claim_lock=task.claim_lock)+ if mode == 'restart':+ proc.kill(); proc.wait(timeout=10)+ # Model effects are ambiguous: terminate the exact owned executing interpreter.+ os.kill(active.worker_pid, signal.SIGKILL)+ dispatch._recent_worker_exits.clear()+ swept = dispatch.dispatch_once(conn, board='owned', max_spawn=1)+ assert not swept.spawned and kb.get_task(conn, tid).current_run_id == task.current_run_id+ else:+ peer.release.set()+ wait_for(lambda: admission()['status'] == 'terminal')+ wait_for(lambda: kb.get_task(conn, tid).status == 'done')+ assert asyncio.run(retry(desc, params))['session_id'] == first['target_session_id']+ if mode == 'restart':+ cfg['model']['default'] = 'changed-default'+ (owner / 'config.yaml').write_text(json.dumps(cfg))+ for generation in range(2):+ with daemon(root, owner, env, barrier=False) as (proc, desc):+ answer = asyncio.run(retry(desc, params))+ assert answer['receipt']['status'] == 'unknown', answer+ assert answer['session_id'] == first['target_session_id']+ with closing(sqlite3.connect((owner / 'state.db').as_uri() + '?mode=ro', uri=True)) as db:+ frozen = json.loads(db.execute('SELECT value FROM state_meta WHERE key=?',+ ('gateway.local_policy.v1:' + first['target_session_id'],)).fetchone()[0])+ assert frozen['policy']['model'] == 'frozen-model', frozen+ private = json.loads(frozen['policy']['kanban_json'])+ assert private['db'] == str(board_path.resolve()) and private['claim_lock'] == task.claim_lock+ # Elapse TTL, heartbeat and runtime to exercise every reclaim route.+ conn.execute('UPDATE tasks SET claim_expires=1,last_heartbeat_at=1,max_runtime_seconds=1 WHERE id=?', (tid,))+ conn.execute('UPDATE task_runs SET started_at=1 WHERE id=?', (task.current_run_id,))+ conn.commit()+ dispatch._recent_worker_exits.clear()+ swept = dispatch.dispatch_once(conn, board='owned', max_spawn=1, stale_timeout_seconds=1)+ same = kb.get_task(conn, tid)+ assert not swept.spawned and same.status == 'running', (swept, same)+ assert (same.current_run_id, same.claim_lock) == (task.current_run_id, task.claim_lock)+ assert same.consecutive_failures == 0+ assert len(peer.requests) == 1, peer.requests+ if generation == 1:+ asyncio.run(retry(desc, params, resolve=True))+ assert admission()['status'] == 'terminal'+ dispatch.dispatch_once(conn, board='owned', max_spawn=0)+ assert kb.get_task(conn, tid).status == 'running'+ # Discarding unknown admission is not permission to rerun the card.+ kb.block_task(conn, tid, reason='Operator resolves ambiguous attempt', expected_run_id=task.current_run_id)+ assert kb.get_task(conn, tid).status == 'blocked'+ receipt['unknown_preserved_two_restarts'] = True+ receipt.update(inference_calls=len(peer.requests), frozen_model=peer.requests[0]['model'])+ assert peer.requests[0]['model'] == 'frozen-model'+ wait_for(lambda: all(p.poll() is not None for p in clients))+ trace = (home / 'client.strace').read_text()+ writes = [line for line in trace.splitlines() if 'state.db' in line and ('O_RDWR' in line or 'O_WRONLY' in line)]+ assert not writes, writes+ receipt['client_canonical_writable_opens'] = len(writes)+ 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 / 'receipt.json').write_text(json.dumps(receipt, indent=2))+ (home / 'model-requests.json').write_text(json.dumps(peer.requests, indent=2))+ print(json.dumps(receipt))+++if __name__ == '__main__':+ main()diff --git a/tests/gateway/test_kanban_recovery.py b/tests/gateway/test_kanban_recovery.pynew file mode 100644index 00000000000..22699e0841f--- /dev/null+++ b/tests/gateway/test_kanban_recovery.py@@ -0,0 +1,21 @@+"""Real dispatch preserves custom board identity and unknown attempts."""+import json+import os+from pathlib import Path+import subprocess+import sys++import pytest++[email protected]('mode', ['custom', 'cross_profile', 'restart'])+def test_owner_board_recovery(tmp_path, mode):+ repo = Path(__file__).resolve().parents[2]+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}+ env.update(HOME=str(tmp_path / 'user'), HERMES_HOME=str(tmp_path / 'state'),+ PYTHONPATH=str(repo), KANBAN_RECOVERY_MODE=mode)+ result = subprocess.run([sys.executable, str(repo / 'tests/gateway/fixtures/kanban_recovery_probe.py')],+ cwd=repo, env=env, stdin=subprocess.DEVNULL,+ capture_output=True, text=True, timeout=180)+ assert result.returncode == 0, result.stdout + result.stderr+ print(json.dumps(json.loads((tmp_path / 'state/receipt.json').read_text())))diff --git a/tests/gateway/test_session_kanban.py b/tests/gateway/test_session_kanban.pyindex 7526b0febb0..75cbbf0e6c7 100644--- a/tests/gateway/test_session_kanban.py+++ b/tests/gateway/test_session_kanban.py@@ -65,7 +65,7 @@ def test_real_dispatcher_lifecycle(tmp_path, mode):receipt = json.loads((tmp_path / 'state' / 'receipt.json').read_text())print(json.dumps(receipt))if mode != 'complete':- assert receipt['task_status'] == 'ready'+ assert receipt['task_status'] == ('running' if mode == 'crash' else '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']diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 01012f9ff8d..15c2b47ef09 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -1153,6 +1153,21 @@ needed — each profile gateway simply delivers through its own adapters.## Runs — one row per attempt+Canonical workers execute through the assigned profile's gateway owner. The local+transport carries the dispatcher's exact board database path, including custom+paths and shared boards assigned to another profile; it does not create a separate+transcript writer. The owner validates the task/run/claim and freezes its policy.++If the owner or managed worker disappears with an **unknown** admission, the card+keeps its run and claim. PID death, expired claims, stale heartbeats and runtime+limits do not automatically reexecute that ambiguous attempt. An unavailable+owner ledger also pauses reclaim. Resolve the unknown admission explicitly using+`prompt.resolve_unknown` with its admission ID and execution generation. This+acknowledges uncertainty; it does **not** authorize another Kanban attempt. Inspect+the effects, then explicitly complete or block the card; unblock a blocked card+only when a new attempt is intended. Confirmed timeouts and provider rate-limit+results retain their ordinary retry/failure-accounting behavior.+A task is a logical unit of work; a **run** is one attempt to execute it. When the dispatcher claims a ready task it creates a row in `task_runs` and points `tasks.current_run_id` at it. When that attempt ends — completed, blocked, crashed, timed out, spawn-failed, reclaimed — the run row closes with an `outcome` and the task's pointer clears. A task that's been attempted three times has three `task_runs` rows.Why two tables instead of just mutating the task: you need **full attempt history** for real-world postmortems ("the second reviewer attempt got to approve, the third merged"), and you need a clean place to hang per-attempt metadata — which files changed, which tests ran, which findings a reviewer noted. Those are run facts, not task facts.