Skip to content

The agent that grows with you

fix(kanban): close review graph race gaps

Jakub Wolniewicz4ab998a7de4d
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index 4438847b404..bf78d0708ff 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -4208,7 +4208,7 @@ def _resume_status_from_events(conn: sqlite3.Connection, task_id: str) -> str:
"SELECT payload FROM task_events "
"WHERE task_id = ? AND kind IN ("
"'blocked', 'block_loop_detected', 'dependency_wait', 'gave_up', "
- "'unblocked', 'changes_requested', 'review_reopened', 'reclaimed', "
+ "'unblocked', 'changes_requested', 'review_reopened', 'status', 'reclaimed', "
"'stale', 'timed_out', 'crashed', 'spawn_failed', 'rate_limited'"
") ORDER BY id DESC LIMIT 1",
(task_id,),
@@ -4318,6 +4318,17 @@ def recompute_ready(
# Claim / complete / block
# ---------------------------------------------------------------------------
+def _parents_satisfied(conn: sqlite3.Connection, task_id: str) -> bool:
+ """Return whether every direct parent is terminal for dependency gating."""
+ return conn.execute(
+ "SELECT 1 FROM task_links l "
+ "JOIN tasks p ON p.id = l.parent_id "
+ "WHERE l.child_id = ? "
+ "AND p.status NOT IN ('done', 'archived') LIMIT 1",
+ (task_id,),
+ ).fetchone() is None
+
+
def claim_task(
conn: sqlite3.Connection,
task_id: str,
@@ -4452,9 +4463,8 @@ def claim_review_task(
Returns the claimed ``Task`` on success, ``None`` if the task was
already claimed (or is not in ``review`` status).
- Unlike ``claim_task`` (which handles ``ready -> running``), this
- does NOT check parent dependencies — the task already passed that
- gate on its original ``todo -> ready -> running`` transition.
+ Parent dependencies are re-checked because a previously completed parent
+ may have been reopened while this task waited in review.
Creates a new run entry so the review agent's lifecycle is tracked
independently from the original worker run.
@@ -4463,6 +4473,23 @@ def claim_review_task(
lock = claimer or _claimer_id()
expires = now + _resolve_claim_ttl_seconds(ttl_seconds)
with write_txn(conn):
+ if not _parents_satisfied(conn, task_id):
+ demoted = conn.execute(
+ "UPDATE tasks SET status = 'todo' "
+ "WHERE id = ? AND status = 'review' AND claim_lock IS NULL",
+ (task_id,),
+ )
+ if demoted.rowcount == 1:
+ _append_event(
+ conn,
+ task_id,
+ "dependency_wait",
+ {
+ "reason": "parent_reopened",
+ "source_status": "review",
+ },
+ )
+ return None
cur = conn.execute(
"""
UPDATE tasks
@@ -4974,6 +5001,7 @@ def complete_task(
metadata: Optional[dict] = None,
created_cards: Optional[Iterable[str]] = None,
expected_run_id: Optional[int] = None,
+ fire_lifecycle_hook: bool = True,
) -> bool:
"""Transition ``running|ready|blocked|review -> done`` and record ``result``.
@@ -5008,6 +5036,10 @@ def complete_task(
and never blocks.
"""
now = int(time.time())
+ # Fail before validating cards or staging artifacts; re-check inside the
+ # final write transaction below to close the parent-reopen race.
+ if not _parents_satisfied(conn, task_id):
+ return False
# Gate: verify created_cards BEFORE the main write txn. A rejected
# completion still needs an auditable event, so we emit it in a
@@ -5040,6 +5072,11 @@ def complete_task(
conn, task_id, metadata, summary=summary, result=result,
)
with write_txn(conn):
+ # Parent completion is a hard invariant even for direct human review
+ # approval. A parent may have been reopened after this task entered
+ # ``review`` or ``running``.
+ if not _parents_satisfied(conn, task_id):
+ return False
if expected_run_id is None:
cur = conn.execute(
"""
@@ -5168,14 +5205,15 @@ def complete_task(
# Clean up the scratch workspace and any stale tmux session for the worker.
_cleanup_workspace(conn, task_id)
_done_task = get_task(conn, task_id)
- _fire_kanban_lifecycle_hook(
- "kanban_task_completed",
- task_id,
- board=get_current_board(),
- assignee=_done_task.assignee if _done_task else None,
- run_id=run_id,
- summary=(summary if summary is not None else result),
- )
+ if fire_lifecycle_hook:
+ _fire_kanban_lifecycle_hook(
+ "kanban_task_completed",
+ task_id,
+ board=get_current_board(),
+ assignee=_done_task.assignee if _done_task else None,
+ run_id=run_id,
+ summary=(summary if summary is not None else result),
+ )
return True
@@ -5996,6 +6034,8 @@ def request_review(
exposed to the review dispatcher.
"""
with write_txn(conn):
+ if not _parents_satisfied(conn, task_id):
+ return False
trow = conn.execute(
"SELECT assignee FROM tasks WHERE id = ?", (task_id,),
).fetchone()
diff --git a/hermes_cli/kanban_swarm.py b/hermes_cli/kanban_swarm.py
index 8b7ba0b4b9e..639d565b220 100644
--- a/hermes_cli/kanban_swarm.py
+++ b/hermes_cli/kanban_swarm.py
@@ -92,6 +92,10 @@ def create_swarm(
idempotency_key: Optional[str] = None,
) -> SwarmCreated:
"""Atomically create a durable, immediately dispatchable Kanban swarm."""
+ activation_summary = (
+ "Swarm topology planned; root remains the shared blackboard."
+ )
+ activated = False
with kb.write_txn(conn):
created = _create_swarm_uncommitted(
conn,
@@ -109,19 +113,32 @@ def create_swarm(
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,
+ 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=activation_summary,
+ metadata={
+ "kind": "kanban_swarm_v1",
+ "goal": goal.strip(),
+ "worker_count": len(created.worker_ids),
+ },
+ fire_lifecycle_hook=False,
+ ):
+ raise RuntimeError("could not activate the completed swarm topology")
+ activated = True
+ if activated:
+ root = kb.get_task(conn, created.root_id)
+ run = kb.latest_run(conn, created.root_id)
+ kb._fire_kanban_lifecycle_hook(
+ "kanban_task_completed",
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")
+ board=kb.get_current_board(),
+ assignee=root.assignee if root else None,
+ run_id=run.id if run else None,
+ summary=activation_summary,
+ )
return created
diff --git a/plugins/kanban/dashboard/plugin_api.py b/plugins/kanban/dashboard/plugin_api.py
index 465a0b7f8c7..5342ff681bd 100644
--- a/plugins/kanban/dashboard/plugin_api.py
+++ b/plugins/kanban/dashboard/plugin_api.py
@@ -1141,16 +1141,19 @@ def _set_status_direct(
# the dependency gate. Demote those children immediately so the
# dashboard does not keep advertising stale-ready work.
for row in conn.execute(
- "SELECT child_id FROM task_links WHERE parent_id = ? ORDER BY child_id",
+ "SELECT c.id AS child_id, c.status AS child_status "
+ "FROM task_links l JOIN tasks c ON c.id = l.child_id "
+ "WHERE l.parent_id = ? ORDER BY c.id",
(task_id,),
).fetchall():
child_id = row["child_id"]
+ child_status = row["child_status"]
demoted = conn.execute(
"UPDATE tasks SET status = 'todo' "
- "WHERE id = ? AND status = 'ready'",
+ "WHERE id = ? AND status IN ('ready', 'review')",
(child_id,),
)
- if demoted.rowcount == 1:
+ if demoted.rowcount == 1 and child_status in {"ready", "review"}:
conn.execute(
"INSERT INTO task_events (task_id, kind, payload, created_at) "
"VALUES (?, 'status', ?, ?)",
@@ -1161,6 +1164,9 @@ def _set_status_direct(
"status": "todo",
"reason": "parent_reopened",
"parent": task_id,
+ "resume_status": (
+ "review" if child_status == "review" else "ready"
+ ),
}
),
int(time.time()),
diff --git a/tests/hermes_cli/test_kanban_review_lifecycle_complete.py b/tests/hermes_cli/test_kanban_review_lifecycle_complete.py
index 165bbab2797..c9a0bb4e814 100644
--- a/tests/hermes_cli/test_kanban_review_lifecycle_complete.py
+++ b/tests/hermes_cli/test_kanban_review_lifecycle_complete.py
@@ -177,6 +177,37 @@ def test_review_changes_reapply_parent_gate(conn):
assert regated.status == "todo"
+def test_parent_reopen_blocks_request_review_until_parent_is_done(conn) -> None:
+ parent_id = kb.create_task(conn, title="Parent", assignee="planner")
+ assert kb.complete_task(conn, parent_id)
+ task_id = kb.create_task(
+ conn,
+ title="Implementation with reopened parent",
+ assignee="builder",
+ parents=[parent_id],
+ )
+ implementation = kb.claim_task(conn, task_id)
+ assert implementation is not None
+ with kb.write_txn(conn):
+ conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (parent_id,))
+ assert not kb.request_review(
+ conn,
+ task_id,
+ summary="must wait",
+ expected_run_id=implementation.current_run_id,
+ )
+ still_running = kb.get_task(conn, task_id)
+ assert still_running is not None
+ assert still_running.status == "running"
+ assert kb.complete_task(conn, parent_id)
+ assert kb.request_review(
+ conn,
+ task_id,
+ summary="parent stable",
+ expected_run_id=implementation.current_run_id,
+ )
+
+
def test_request_changes_fails_closed_on_malformed_review_provenance(conn):
task_id = kb.create_task(conn, title="Malformed handoff", assignee="builder")
implementation = kb.claim_task(conn, task_id, claimer="builder:1")
diff --git a/tests/hermes_cli/test_kanban_swarm.py b/tests/hermes_cli/test_kanban_swarm.py
index c4acf57928e..1d1da21e984 100644
--- a/tests/hermes_cli/test_kanban_swarm.py
+++ b/tests/hermes_cli/test_kanban_swarm.py
@@ -55,6 +55,7 @@ def test_create_swarm_graph_is_atomic_and_rolls_back_partial_build(
writer = kb.connect(db_path)
reader = kb.connect(db_path)
original_create = kb.create_task
+ original_complete = kb.complete_task
calls = 0
def observed_create(*args, **kwargs):
@@ -85,6 +86,39 @@ def test_create_swarm_graph_is_atomic_and_rolls_back_partial_build(
)
assert writer.execute("SELECT COUNT(*) FROM tasks").fetchone()[0] == 0
assert reader.execute("SELECT COUNT(*) FROM tasks").fetchone()[0] == 0
+
+ monkeypatch.setattr(kb, "create_task", original_create)
+ monkeypatch.setattr(kb, "complete_task", lambda *args, **kwargs: False)
+ with pytest.raises(RuntimeError, match="could not activate"):
+ create_swarm(
+ writer,
+ goal="Fail activation atomically",
+ workers=[
+ SwarmWorkerSpec(profile="worker-a", title="A", body="A"),
+ ],
+ 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
+
+ hooks: list[tuple[str, bool]] = []
+ monkeypatch.setattr(kb, "complete_task", original_complete)
+ monkeypatch.setattr(
+ kb,
+ "_fire_kanban_lifecycle_hook",
+ lambda event, *_args, **_kwargs: hooks.append(
+ (event, writer.in_transaction)
+ ),
+ )
+ create_swarm(
+ writer,
+ goal="Commit before lifecycle hook",
+ workers=[SwarmWorkerSpec(profile="worker-a", title="A", body="A")],
+ verifier_assignee="reviewer",
+ synthesizer_assignee="writer",
+ )
+ assert hooks == [("kanban_task_completed", False)]
finally:
reader.close()
writer.close()
diff --git a/tests/plugins/test_kanban_dashboard_plugin.py b/tests/plugins/test_kanban_dashboard_plugin.py
index 7a8b56ef0bd..1693d288bbf 100644
--- a/tests/plugins/test_kanban_dashboard_plugin.py
+++ b/tests/plugins/test_kanban_dashboard_plugin.py
@@ -297,6 +297,81 @@ def test_reopening_parent_demotes_ready_child(client):
assert child_after_reopen["status"] == "todo"
+def test_reopening_parent_retracts_review_and_blocks_approval(client):
+ with kb.connect() as conn:
+ parent_id = kb.create_task(conn, title="parent", assignee="planner")
+ assert kb.complete_task(conn, parent_id)
+ child_id = kb.create_task(
+ conn,
+ title="child in review",
+ assignee="reviewer",
+ parents=[parent_id],
+ )
+ grandchild_id = kb.create_task(
+ conn,
+ title="downstream",
+ assignee="writer",
+ parents=[child_id],
+ )
+ implementation = kb.claim_task(conn, child_id)
+ assert implementation is not None
+ assert kb.request_review(
+ conn,
+ child_id,
+ summary="ready",
+ expected_run_id=implementation.current_run_id,
+ )
+ active_review = kb.claim_review_task(conn, child_id)
+ assert active_review is not None
+
+ response = client.patch(
+ f"/api/plugins/kanban/tasks/{parent_id}",
+ json={"status": "ready"},
+ )
+ assert response.status_code == 200, response.text
+
+ with kb.connect() as conn:
+ child = kb.get_task(conn, child_id)
+ assert child is not None
+ assert child.status == "running"
+ assert not kb.complete_task(
+ conn,
+ child_id,
+ summary="must not approve",
+ expected_run_id=active_review.current_run_id,
+ )
+ assert kb.reclaim_task(conn, child_id, signal_fn=lambda *_args: None)
+ assert kb.claim_review_task(conn, child_id) is None
+ child = kb.get_task(conn, child_id)
+ assert child is not None
+ assert child.status == "todo"
+ grandchild = kb.get_task(conn, grandchild_id)
+ assert grandchild is not None
+ assert grandchild.status == "todo"
+
+ response = client.patch(
+ f"/api/plugins/kanban/tasks/{parent_id}",
+ json={"status": "done"},
+ )
+ assert response.status_code == 200, response.text
+
+ with kb.connect() as conn:
+ child = kb.get_task(conn, child_id)
+ assert child is not None
+ assert child.status == "review"
+ review = kb.claim_review_task(conn, child_id)
+ assert review is not None
+ assert kb.complete_task(
+ conn,
+ child_id,
+ summary="approved after parent stabilized",
+ expected_run_id=review.current_run_id,
+ )
+ grandchild = kb.get_task(conn, grandchild_id)
+ assert grandchild is not None
+ assert grandchild.status == "ready"
+
+
# ---------------------------------------------------------------------------
# DELETE /tasks/:id
# ---------------------------------------------------------------------------
diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.md
index 38d5e32b396..f308248daf7 100644
--- a/website/docs/user-guide/features/kanban.md
+++ b/website/docs/user-guide/features/kanban.md
@@ -269,10 +269,11 @@ hermes kanban block t_abc "need input" --ids t_def t_hij
```
:::note Where an unblocked task lands
-`unblock` itself only ever moves a task to **`ready`** (all parents `done`) or
-**`todo`** (a parent is still open — the task is dependency-gated and the
-dispatcher auto-promotes it once the parent finishes). It never routes to
-`triage`.
+`unblock` restores the safe source phase: **`review`** for reviewer-origin work
+whose parents are complete, **`ready`** for implementation work whose parents
+are complete, or **`todo`** while any parent remains open. A `todo` task keeps
+its source-phase provenance and returns to `review` or `ready` automatically
+when the dependency gate clears. `unblock` never routes directly to `triage`.
If you unblock a task and it later shows up in **`triage`**, the unblock is not
what put it there. A subsequent *re-block for the same reason* did: after a task
@@ -306,7 +307,7 @@ parent, missing input, unmet capability) before unblocking, or raise
| `kanban_attachments` | List a task's attachments. | — |
| `kanban_create` | (Orchestrators) fan out into child tasks with an `assignee`, optional `parents`, `skills`, etc. | `title`, `assignee` |
| `kanban_link` | (Orchestrators) add a `parent_id → child_id` dependency edge after the fact. | `parent_id`, `child_id` |
-| `kanban_unblock` | (Orchestrators) move a blocked task to `ready` when all parents are done, or `todo` while any parent remains open. | `task_id` |
+| `kanban_unblock` | (Orchestrators) restore a blocked task to its source phase (`review` or `ready`), or `todo` while a parent remains open. | `task_id` |
A typical worker turn looks like:
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/kanban.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/kanban.md
index 9a5d40514f0..8a1a9524555 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/kanban.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/kanban.md
@@ -207,7 +207,7 @@ hermes kanban block t_abc "need input" --ids t_def t_hij
| `kanban_comment` | 向任务线程追加持久化备注。 | `task_id`、`body` |
| `kanban_create` | (编排器)将任务扇出为带有 `assignee`、可选 `parents`、`skills` 等的子任务。 | `title`、`assignee` |
| `kanban_link` | (编排器)事后添加 `parent_id → child_id` 依赖边。 | `parent_id`、`child_id` |
-| `kanban_unblock` | (编排器)将被阻塞的任务移回 `ready`。 | `task_id` |
+| `kanban_unblock` | (编排器)将阻塞任务恢复到来源阶段(`review` 或 `ready`);父任务仍开放时进入 `todo`。 | `task_id` |
典型的 worker 轮次如下所示: