The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): harden review graph handoffs
Jakub Wolniewicz0fe4d9022386
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex 1bb08f5e68f..e47e9972bc5 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -2802,14 +2802,35 @@ def write_txn(conn: sqlite3.Connection):"""Context manager for an IMMEDIATE write transaction.Use for any multi-statement write (creating a task + link, claiming a- task + recording an event, etc.). A claim CAS inside this context is+ task + recording an event, etc.). A claim CAS inside this context isatomic -- at most one concurrent writer can succeed.+ Nested callers use SQLite savepoints rather than opening a second+ ``BEGIN IMMEDIATE``. This lets graph builders compose the existing atomic+ task operations under one outer commit, so the dispatcher can never+ observe a partially constructed multi-card graph.+The explicit ROLLBACK on exception is wrapped in try/except so thata SQLite auto-rollback (which leaves no active transaction) does notshadow the original exception with a spurious rollback error."""_assert_not_delegated_child_mutation()+ if getattr(conn, "in_transaction", False):+ savepoint = f"hermes_nested_{secrets.token_hex(8)}"+ conn.execute(f"SAVEPOINT {savepoint}")+ try:+ yield conn+ except Exception:+ try:+ conn.execute(f"ROLLBACK TO {savepoint}")+ conn.execute(f"RELEASE {savepoint}")+ except sqlite3.OperationalError:+ pass+ raise+ else:+ conn.execute(f"RELEASE {savepoint}")+ return+_execute_boundary_with_retry(conn, "BEGIN IMMEDIATE")try:yield conn@@ -6248,18 +6269,47 @@ def reopen_review_task(conn: sqlite3.Connection, task_id: str) -> bool:note="invariant recovery on review reopen",)new_status = _landing_status_after_parents(conn, task_id)+ review_event = conn.execute(+ "SELECT payload FROM task_events "+ "WHERE task_id = ? AND kind = 'review_requested' "+ "ORDER BY id DESC LIMIT 1",+ (task_id,),+ ).fetchone()+ try:+ handoff = (+ json.loads(review_event["payload"])+ if review_event and review_event["payload"]+ else {}+ )+ except (json.JSONDecodeError, TypeError):+ handoff = {}+ implementer = handoff.get("implementer")+ if not isinstance(implementer, str) or not implementer.strip():+ implementer = None+ assignee_sql = ", assignee = ?" if implementer else ""+ params: tuple[Any, ...] = (+ (new_status, implementer, task_id)+ if implementer+ else (new_status, task_id)+ )cur = conn.execute("UPDATE tasks SET status = ?, current_run_id = NULL, ""claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, ""consecutive_failures = 0, last_failure_error = NULL "- "WHERE id = ? AND status = 'review'",- (new_status, task_id),+ + assignee_sql+ + " WHERE id = ? AND status = 'review'",+ params,)if cur.rowcount != 1:return False+ payload: dict[str, Any] = {"status": new_status}+ if implementer:+ payload["implementer"] = implementer_append_event(- conn, task_id, "review_reopened",- {"status": new_status} if new_status != "ready" else None,+ conn,+ task_id,+ "review_reopened",+ payload if payload != {"status": "ready"} else None,)return True@@ -9072,7 +9122,9 @@ def _dispatch_once_locked(# kanban lifecycle is already injected into every worker's system# prompt via KANBAN_GUIDANCE, so this is the only extra skill the# review agent needs.- claimed.skills = ["sdlc-review"]+ claimed.skills = list(+ dict.fromkeys([*(claimed.skills or []), "sdlc-review"])+ )_spawn = spawn_fn if spawn_fn is not None else _default_spawntry:import inspectdiff --git a/hermes_cli/kanban_swarm.py b/hermes_cli/kanban_swarm.pyindex 4903d91275c..8b7ba0b4b9e 100644--- a/hermes_cli/kanban_swarm.py+++ b/hermes_cli/kanban_swarm.py@@ -90,6 +90,57 @@ def create_swarm(workspace_path: Optional[str] = None,priority: int = 0,idempotency_key: Optional[str] = None,+) -> SwarmCreated:+ """Atomically create a durable, immediately dispatchable Kanban swarm."""+ with kb.write_txn(conn):+ created = _create_swarm_uncommitted(+ conn,+ goal=goal,+ workers=workers,+ verifier_assignee=verifier_assignee,+ synthesizer_assignee=synthesizer_assignee,+ root_title=root_title,+ verifier_title=verifier_title,+ synthesizer_title=synthesizer_title,+ tenant=tenant,+ created_by=created_by,+ workspace_kind=workspace_kind,+ workspace_path=workspace_path,+ priority=priority,+ idempotency_key=idempotency_key,+ )+ root = kb.get_task(conn, created.root_id)+ if root is not None and root.status == "blocked":+ if not kb.complete_task(+ conn,+ created.root_id,+ summary="Swarm topology planned; root remains the shared blackboard.",+ metadata={+ "kind": "kanban_swarm_v1",+ "goal": goal.strip(),+ "worker_count": len(created.worker_ids),+ },+ ):+ raise RuntimeError("could not activate the completed swarm topology")+ return created+++def _create_swarm_uncommitted(+ conn: sqlite3.Connection,+ *,+ goal: str,+ workers: Iterable[SwarmWorkerSpec],+ verifier_assignee: str,+ synthesizer_assignee: str,+ root_title: Optional[str] = None,+ verifier_title: str = "Verify swarm outputs",+ synthesizer_title: str = "Synthesize swarm outputs",+ tenant: Optional[str] = None,+ created_by: str = "swarm-orchestrator",+ workspace_kind: str = "scratch",+ workspace_path: Optional[str] = None,+ priority: int = 0,+ idempotency_key: Optional[str] = None,) -> SwarmCreated:"""Create a durable Kanban swarm graph.@@ -122,6 +173,7 @@ def create_swarm(tenant=tenant,priority=priority,idempotency_key=idempotency_key,+ initial_status="blocked",workspace_kind=workspace_kind,workspace_path=workspace_path,)@@ -142,17 +194,6 @@ def create_swarm(synthesizer_id=str(synthesizer_id),)- kb.complete_task(- conn,- root,- summary="Swarm topology planned; root remains the shared blackboard.",- metadata={- "kind": "kanban_swarm_v1",- "goal": goal,- "worker_count": len(worker_specs),- },- )-context_suffix = _swarm_context(root, goal)worker_ids: list[str] = []for spec in worker_specs:diff --git a/tests/hermes_cli/test_kanban_review_lifecycle.py b/tests/hermes_cli/test_kanban_review_lifecycle.pyindex 47cdaf8f433..c3337a980da 100644--- a/tests/hermes_cli/test_kanban_review_lifecycle.py+++ b/tests/hermes_cli/test_kanban_review_lifecycle.py@@ -286,7 +286,7 @@ def test_review_requested_event_is_claimable_for_wake(kanban_home: Path) -> None# ----------------------------------------------------------------------------# Dispatcher gate: no phantom reviewer without an autonomous reviewer agent+# Dispatcher gate: operators may opt out of autonomous review dispatch# ---------------------------------------------------------------------------@@ -294,8 +294,8 @@ def test_review_dispatch_gate_prevents_phantom_reviewer(kanban_home: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""With ``kanban.review_dispatch=false`` the dispatcher must NOT claim a- task parked in ``review`` (no autonomous reviewer in this deployment —- it waits for a human). Flipping the knob back on proves the gate, not+ task parked in ``review`` (this deployment explicitly waits for a human).+ Flipping the knob back on proves the gate, notsomething else, is what suppressed the claim."""import hermes_cli.config as cfgmodimport hermes_cli.profiles as profmod@@ -322,8 +322,8 @@ def test_review_dispatch_gate_prevents_phantom_reviewer(assert tid not in [s[0] for s in res_off.spawned]assert kb.get_task(conn, tid).status == "review"- # Gate ON (opt-in; requires an installed sdlc-review agent) -> the- # review task is picked up by the dispatcher.+ # Gate ON (the default; sdlc-review is bundled) -> the review task is+ # picked up by the dispatcher.monkeypatch.setattr(cfgmod, "load_config",lambda *a, **k: {"kanban": {"review_dispatch": True}},@@ -332,6 +332,45 @@ def test_review_dispatch_gate_prevents_phantom_reviewer(assert tid in [s[0] for s in res_on.spawned]+def test_review_dispatch_preserves_task_skills_and_adds_reviewer_skill(+ kanban_home: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ import hermes_cli.config as cfgmod+ import hermes_cli.profiles as profmod++ monkeypatch.setattr(profmod, "profile_exists", lambda name: True)+ monkeypatch.setattr(+ cfgmod,+ "load_config",+ lambda *args, **kwargs: {"kanban": {"review_dispatch": True}},+ )+ captured: list[list[str]] = []++ def spawn(task, workspace):+ captured.append(list(task.skills or []))+ return None++ with kb.connect() as conn:+ task_id = kb.create_task(+ conn,+ title="domain review",+ assignee="reviewer",+ skills=["domain-specific-review"],+ )+ implementation = kb.claim_task(conn, task_id)+ assert implementation is not None+ assert kb.request_review(+ conn,+ task_id,+ summary="ready",+ expected_run_id=implementation.current_run_id,+ )+ result = kb.dispatch_once(conn, spawn_fn=spawn)++ assert task_id in [task[0] for task in result.spawned]+ assert captured == [["domain-specific-review", "sdlc-review"]]++# ---------------------------------------------------------------------------# reopen: a follow-up sends a review task back out for another pass# ---------------------------------------------------------------------------@@ -345,15 +384,21 @@ def test_reopen_review_task_returns_to_ready(kanban_home: Path) -> None:tid = kb.create_task(conn, title="reopen me", assignee="worker")kb.claim_task(conn, tid)kb.request_review(- conn, tid, summary="v1",+ conn, tid, summary="v1", reviewer="reviewer",expected_run_id=kb.get_task(conn, tid).current_run_id,)- assert kb.get_task(conn, tid).status == "review"+ reviewing = kb.get_task(conn, tid)+ assert reviewing is not None+ assert reviewing.status == "review"+ assert reviewing.assignee == "reviewer"ok = kb.reopen_review_task(conn, tid)assert ok is Truerow = _row(conn, tid)assert row["status"] == "ready"+ reopened = kb.get_task(conn, tid)+ assert reopened is not None+ assert reopened.assignee == "worker"assert row["current_run_id"] is Noneassert (row["block_recurrences"] or 0) == 0assert _events(conn, tid, kind="review_reopened")diff --git a/tests/hermes_cli/test_kanban_swarm.py b/tests/hermes_cli/test_kanban_swarm.pyindex eeb6f917a3c..6832942f6ef 100644--- a/tests/hermes_cli/test_kanban_swarm.py+++ b/tests/hermes_cli/test_kanban_swarm.py@@ -1,3 +1,4 @@+import pytestfrom hermes_cli import kanban_db as kbfrom hermes_cli.kanban_swarm import (@@ -42,6 +43,48 @@ def test_create_swarm_builds_parallel_workers_verifier_and_synthesizer(tmp_path)conn.close()+def test_create_swarm_graph_is_atomic_and_rolls_back_partial_build(+ tmp_path, monkeypatch: pytest.MonkeyPatch+):+ db_path = tmp_path / "kanban.db"+ writer = kb.connect(db_path)+ reader = kb.connect(db_path)+ original_create = kb.create_task+ calls = 0++ def observed_create(*args, **kwargs):+ nonlocal calls+ calls += 1+ task_id = original_create(*args, **kwargs)+ if calls == 1:+ # Releasing the nested create_task savepoint must not expose the+ # root before the whole graph's outer transaction commits.+ visible = reader.execute("SELECT COUNT(*) FROM tasks").fetchone()[0]+ assert visible == 0+ if calls == 3:+ raise RuntimeError("synthetic graph-construction failure")+ return task_id++ monkeypatch.setattr(kb, "create_task", observed_create)+ try:+ with pytest.raises(RuntimeError, match="synthetic graph-construction failure"):+ create_swarm(+ writer,+ goal="Build atomically",+ workers=[+ SwarmWorkerSpec(profile="worker-a", title="A", body="A"),+ SwarmWorkerSpec(profile="worker-b", title="B", body="B"),+ ],+ verifier_assignee="reviewer",+ synthesizer_assignee="writer",+ )+ assert writer.execute("SELECT COUNT(*) FROM tasks").fetchone()[0] == 0+ assert reader.execute("SELECT COUNT(*) FROM tasks").fetchone()[0] == 0+ finally:+ reader.close()+ writer.close()++def test_swarm_blackboard_merges_structured_updates(tmp_path):conn = kb.connect(tmp_path / "kanban.db")try:diff --git a/tests/plugins/test_kanban_dashboard_plugin.py b/tests/plugins/test_kanban_dashboard_plugin.pyindex bab63e8c784..692aaa722b7 100644--- a/tests/plugins/test_kanban_dashboard_plugin.py+++ b/tests/plugins/test_kanban_dashboard_plugin.py@@ -244,6 +244,7 @@ def test_patch_review_lifecycle_preserves_handoff_and_reopens(client):assert run is not Noneassert run.outcome == "review_requested"assert run.metadata == {"tests_run": 4}+ assert kb.assign_task(conn, task["id"], "reviewer")response = client.patch(f"/api/plugins/kanban/tasks/{task['id']}",@@ -251,6 +252,7 @@ def test_patch_review_lifecycle_preserves_handoff_and_reopens(client):)assert response.status_code == 200, response.textassert response.json()["task"]["status"] == "ready"+ assert response.json()["task"]["assignee"] == "builder"with kb.connect() as conn:assert any(event.kind == "review_reopened"diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 39c77a4887f..38d5e32b396 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -836,7 +836,7 @@ hermes kanban swarm "Design a multi-region failover plan" \--verifier reviewer --synthesizer writer```-The resulting graph dispatches normally — workers run in parallel, the verifier wakes after they all finish, the synthesizer wakes after the verifier marks the work clean.+The resulting graph is committed atomically: dispatchers and dashboard readers see either no new swarm or the complete topology, never a partially linked root/worker/verifier graph. It then dispatches normally — workers run in parallel, the verifier wakes after they all finish, and the synthesizer wakes after the verifier marks the work clean.## `/kanban` slash command {#kanban-slash-command}