The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(kanban): dependency-gate refusals name their cause on every surface
teknium10cdc325b463a
diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.pyindex 32f01545db4..c8f029ca0ed 100644--- a/hermes_cli/kanban.py+++ b/hermes_cli/kanban.py@@ -694,19 +694,14 @@ def _cmd_diagnostics(args: argparse.Namespace) -> int:def _cmd_link(args: argparse.Namespace) -> int:- worker_task_id = os.environ.get("HERMES_KANBAN_TASK")+ # A worker linking its own running card (dependency-block handoff) proves+ # ownership with its run id; linking a foreign task never needs one.expected_child_run_id = (_worker_run_id_for(args.child_id)- if args.child_id == worker_task_id- else None- )+ if args.child_id == os.environ.get("HERMES_KANBAN_TASK") else None)with kbc.connect_closing() as conn:- gated = kb.link_tasks(- conn,- args.parent_id,- args.child_id,- expected_child_run_id=expected_child_run_id,- )+ gated = kb.link_tasks(conn, args.parent_id, args.child_id,+ expected_child_run_id=expected_child_run_id)print(f"Linked {args.parent_id} -> {args.child_id}")if gated:print(@@ -810,8 +805,6 @@ def _worker_run_id_for(task_id: str) -> Optional[int]:env_tid = os.environ.get("HERMES_KANBAN_TASK")if env_tid and env_tid != task_id:raise ValueError(f"worker is scoped to task {env_tid}; refusing to mutate {task_id}")- if os.environ.get("HERMES_KANBAN_BOARD") != kb.get_current_board():- return Noneraw = os.environ.get("HERMES_KANBAN_RUN_ID")if os.environ.get("HERMES_KANBAN_TASK") != task_id or not raw:return None@@ -899,7 +892,7 @@ def _cmd_complete(args: argparse.Namespace) -> int:return Falsefail_msg[tid] = f"cannot complete {tid} (unknown id or terminal state)"try:- return kb.complete_task(conn, tid, result=args.result, summary=summary, metadata=metadata,+ done = kb.complete_task(conn, tid, result=args.result, summary=summary, metadata=metadata,expected_run_id=_worker_run_id_for(tid),force=bool(getattr(args, "force", False)))except kb.LiveClaimError:@@ -907,6 +900,15 @@ def _cmd_complete(args: argparse.Namespace) -> int:f"worker, `hermes kanban reclaim {tid}` to release it, or re-run with "f"--force to close its run and complete anyway.")return False+ if not done:+ # complete_task returns bare False for a dependency refusal too;+ # name the open parents instead of claiming the id is unknown.+ blockers = kb.unsatisfied_parents(conn, tid)+ if blockers:+ detail = ", ".join(f"{pid} ({status})" for pid, status in blockers)+ fail_msg[tid] = (f"cannot complete {tid}: unsatisfied parent dependencies: {detail}; "+ f"complete the parents first, or `hermes kanban unlink <parent> {tid}`.")+ return donereturn _bulk_apply(ids, op, lambda tid: f"Completed {tid}", fail_msg.__getitem__)diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex aae8f911a43..64c9852d738 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -2172,8 +2172,6 @@ def recompute_ready(conn: sqlite3.Connection, failure_limit: int = None) -> int:def _parents_satisfied(conn: sqlite3.Connection, task_id: str) -> bool:"""Return whether every direct parent is terminal for dependency gating."""return conn.execute(- # Check if this task has children that still need the workspace. If any child is not yet- # done/archived, defer cleanup so the child can read handoff artifacts from the workspace (#33774)."SELECT 1 FROM task_links l ""JOIN tasks p ON p.id = l.parent_id ""WHERE l.child_id = ? "@@ -2181,6 +2179,20 @@ def _parents_satisfied(conn: sqlite3.Connection, task_id: str) -> bool:).fetchone() is None+def unsatisfied_parents(conn: sqlite3.Connection, task_id: str) -> list[tuple[str, str]]:+ """``(parent_id, status)`` for every direct parent :func:`_parents_satisfied`+ still counts as open (``done`` / ``archived`` release the child), in id+ order, so a refusal or a board view can name the blockers instead of the+ caller guessing. Read-only."""+ rows = conn.execute(+ "SELECT p.id, p.status FROM task_links l "+ "JOIN tasks p ON p.id = l.parent_id "+ "WHERE l.child_id = ? AND p.status NOT IN ('done', 'archived') "+ "ORDER BY p.id", (task_id,),+ ).fetchall()+ return [(row["id"], row["status"]) for row in rows]++def _claim_and_open_run(conn: sqlite3.Connection, task_id: str, source_status: str, lock: str, expires: int, now: int,*, event_extra: Optional[dict] = None,diff --git a/hermes_cli/kanban_diagnostics.py b/hermes_cli/kanban_diagnostics.pyindex 38ec59b440f..9e255ab9f1b 100644--- a/hermes_cli/kanban_diagnostics.py+++ b/hermes_cli/kanban_diagnostics.py@@ -533,6 +533,40 @@ def _rule_review_dependency_deadlock(task, events, runs, now, cfg) -> list[Diagn)]+def _rule_running_with_open_parents(task, events, runs, now, cfg) -> list[Diagnostic]:+ """A ``running`` card with a direct parent that is not ``done``/``archived``:+ the dependency gate is not holding it (the parent reopened mid-run, or the+ edge predates the running-child refusal) and ``kanban_complete`` will be+ refused until the parents finish. Graph-aware; mutates nothing."""+ if _task_field(task, "status") != "running":+ return []+ graph = cfg.get("_graph")+ if not isinstance(graph, dict):+ return []+ open_parents = [+ parent for parent in (graph.get("parents") or [])+ if isinstance(parent, dict) and parent.get("id")+ and parent.get("status") not in ("done", "archived")+ ]+ if not open_parents:+ return []+ task_id = str(_task_field(task, "id") or "")+ parent_ids = [str(parent["id"]) for parent in open_parents]+ seen_at = int(_task_field(task, "started_at", default=0) or 0) or now+ return [Diagnostic(+ kind="running_with_open_parents", severity="warning",+ title=f"Running while {len(parent_ids)} parent(s) are not done",+ detail="This card is running concurrently with a parent it declares a dependency on, so the "+ "parent's work is not serialised ahead of it and completion will be refused until every "+ "parent is done or archived. Finish the parent, or unlink the edge if it was never meant "+ "to gate this run.",+ actions=[_cli_hint("Unlink the parent that should not gate this run",+ f"hermes kanban unlink {parent_ids[0]} {task_id}")],+ first_seen_at=seen_at, last_seen_at=now, count=len(parent_ids),+ data={"open_parents": [{"id": p["id"], "status": p.get("status")} for p in open_parents]},+ )]++def _rule_stuck_in_blocked(task, events, runs, now, cfg) -> list[Diagnostic]:"""Blocked for >= cfg["blocked_stale_hours"] (default 24) with no commentor unblock since the last ``blocked`` event."""@@ -686,6 +720,7 @@ _RULES: list[RuleFn] = [_rule_repeated_failures,_rule_repeated_crashes,_rule_review_dependency_deadlock,+ _rule_running_with_open_parents,_rule_stuck_in_blocked,_rule_block_unblock_cycling,_rule_stranded_in_ready,diff --git a/tests/hermes_cli/test_kanban_cli.py b/tests/hermes_cli/test_kanban_cli.pyindex f6a2ee82d83..e44ca8cd27f 100644--- a/tests/hermes_cli/test_kanban_cli.py+++ b/tests/hermes_cli/test_kanban_cli.py@@ -83,7 +83,6 @@ def test_worker_link_preserves_foreign_child_rules(kanban_home, monkeypatch):assert kb.claim_task(conn, running_child, claimer="other") is not Nonemonkeypatch.setenv("HERMES_KANBAN_TASK", worker)- monkeypatch.setenv("HERMES_KANBAN_BOARD", "default")monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(worker_run_id))assert kc._cmd_link(argparse.Namespace(@@ -99,32 +98,6 @@ def test_worker_link_preserves_foreign_child_rules(kanban_home, monkeypatch):assert kb.parent_ids(conn, running_child) == []-def test_worker_link_does_not_borrow_ownership_across_boards(kanban_home, monkeypatch):- with kbc.connect_closing() as conn:- worker = kb.create_task(conn, title="worker")- assert kb.claim_task(conn, worker, claimer="worker") is not None- worker_run_id = kb.get_task(conn, worker).current_run_id-- kb.create_board("alt")- with kbc.connect_closing(board="alt") as conn:- parent = kb.create_task(conn, title="alternate parent")- child = kb.create_task(conn, title="colliding worker")- conn.execute("UPDATE tasks SET id = ? WHERE id = ?", (worker, child))- conn.commit()- assert kb.claim_task(conn, worker, claimer="other") is not None- assert kb.get_task(conn, worker).current_run_id == worker_run_id-- monkeypatch.setenv("HERMES_KANBAN_TASK", worker)- monkeypatch.setenv("HERMES_KANBAN_BOARD", "default")- monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(worker_run_id))- with kb.scoped_current_board("alt"):- with pytest.raises(ValueError, match="child is already running"):- kc._cmd_link(argparse.Namespace(parent_id=parent, child_id=worker))-- with kbc.connect_closing(board="alt") as conn:- assert kb.parent_ids(conn, worker) == []--def test_board_override_is_isolated_per_concurrent_call(kanban_home, monkeypatch):kb.create_board("alpha")kb.create_board("beta")diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.pyindex 3f37bf8c57a..c2407598505 100644--- a/tests/hermes_cli/test_kanban_db.py+++ b/tests/hermes_cli/test_kanban_db.py@@ -1195,23 +1195,6 @@ def test_link_tasks_rejects_unowned_running_child_without_recording_edge(kanban_assert "linked" not in [event.kind for event in kb.list_events(conn, child)]-def test_link_tasks_allows_owning_current_run_dependency_handoff(kanban_home):- """The active worker may link its own card before dependency-blocking it."""- with kbc.connect() as conn:- parent = kb.create_task(conn, title="review parent")- child = kb.create_task(conn, title="active child")- assert kb.claim_task(conn, child, claimer="worker") is not None- run_id = kb.get_task(conn, child).current_run_id-- gated = kb.link_tasks(- conn, parent, child, expected_child_run_id=run_id,- )-- assert gated is False- assert kb.parent_ids(conn, child) == [parent]- assert "linked" in [event.kind for event in kb.list_events(conn, child)]--def test_link_tasks_no_dependency_wait_when_parent_done(kanban_home):"""A done parent demotes nothing and reports no gate."""with kbc.connect() as conn:diff --git a/tests/hermes_cli/test_kanban_diagnostics.py b/tests/hermes_cli/test_kanban_diagnostics.pyindex af9fc1696b1..ca1c4dede66 100644--- a/tests/hermes_cli/test_kanban_diagnostics.py+++ b/tests/hermes_cli/test_kanban_diagnostics.py@@ -82,6 +82,19 @@ def _run(outcome="completed", run_id=1, error=None):+def test_running_with_open_parents_fires_only_while_running():+ """A running card whose parent is not terminal is flagged; the same graph+ on a ready/todo card (the gate is holding it) and a done parent are not."""+ graph = {"parents": [{"id": "t_parent", "title": "p", "status": "todo"}], "children": []}+ diags = kd.compute_task_diagnostics(_task(status="running", started_at=100), [], [], graph=graph)+ assert [d.kind for d in diags] == ["running_with_open_parents"]+ assert diags[0].data["open_parents"] == [{"id": "t_parent", "status": "todo"}]+ assert "hermes kanban unlink t_parent t_demo00" in diags[0].actions[0].payload["command"]+ assert kd.compute_task_diagnostics(_task(status="todo"), [], [], graph=graph) == []+ done_graph = {"parents": [{"id": "t_parent", "title": "p", "status": "done"}], "children": []}+ assert kd.compute_task_diagnostics(_task(status="running"), [], [], graph=done_graph) == []++def test_stuck_in_blocked_fires_past_threshold():now = int(time.time())task = _task(status="blocked")diff --git a/tests/tools/test_kanban_complete_parents_tool.py b/tests/tools/test_kanban_complete_parents_tool.pyindex 04f4feffe60..65054630aee 100644--- a/tests/tools/test_kanban_complete_parents_tool.py+++ b/tests/tools/test_kanban_complete_parents_tool.py@@ -1,4 +1,4 @@-"""Tool-surface parents reporting for kanban_complete. Regression for #113373.+"""Dependency refusals name the open parents on every surface.``complete_task`` reports every refusal as bare ``False``. On the CLI surfacethe open PRs #110323/#110330/#110334 make the parents refusal actionable;@@ -65,116 +65,29 @@ def test_complete_names_unsatisfied_parent(running_child_with_parent):assert kb.get_task(conn, child_id).status == "running"finally:conn.close()+ # The board view names the same parents on the running card.+ shown = json.loads(kt._handle_show({"task_id": child_id}))+ assert shown["unsatisfied_parents"] == [{"id": parent_id, "status": "todo"}]-def test_complete_multiple_parents_deterministic_order(monkeypatch, tmp_path):- """Several unfinished parents are all named, in stable id order."""- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setenv("HERMES_PROFILE", "test-worker")- monkeypatch.delenv("HERMES_SESSION_ID", raising=False)- from pathlib import Path as _Path- monkeypatch.setattr(_Path, "home", lambda: tmp_path)-- from hermes_cli import kanban_db as kb- from hermes_cli import kanban_db_connect as kbc- from tools import kanban_tools as kt- kb._INITIALIZED_PATHS.clear()- kb.init_db()- conn = kbc.connect()- try:- p1 = kb.create_task(conn, title="gate one", assignee="op")- p2 = kb.create_task(conn, title="gate two", assignee="op")- for p in (p1, p2):- assert kb.complete_task(conn, p, result="x")- child = kb.create_task(- conn, title="child", assignee="test-worker", parents=[p2, p1])- assert kb.claim_task(conn, child) is not None- # Both gates reopen mid-run.- with kb.write_txn(conn):- conn.execute(- "UPDATE tasks SET status = 'todo', completed_at = NULL "- "WHERE id IN (?, ?)", (p1, p2),- )- finally:- conn.close()- monkeypatch.setenv("HERMES_KANBAN_TASK", child)- out = json.loads(kt._handle_complete(- {"task_id": child, "summary": "done"}))- assert out.get("error")- # Deterministic id order: ids are random hex, so sort first rather than- # assuming creation order.- first, second = sorted([p1, p2])- assert out["error"].index(first) < out["error"].index(second)+def test_cli_complete_names_unsatisfied_parent(running_child_with_parent, monkeypatch, capsys):+ """`hermes kanban complete` (operator, --force) reports the same blockers."""+ import argparse+ from hermes_cli import kanban as kc-def _isolated_home(monkeypatch, tmp_path):- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- from pathlib import Path as _Path- monkeypatch.setattr(_Path, "home", lambda: tmp_path)- from hermes_cli import kanban_db as kb- kb._INITIALIZED_PATHS.clear()- kb.init_db()---def test_complete_unknown_id_stays_generic(monkeypatch, tmp_path):- """Missing tasks keep the generic message (no phantom parent lookup)."""- _isolated_home(monkeypatch, tmp_path)+ parent_id, child_id = running_child_with_parentmonkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)- from tools import kanban_tools as kt- out = json.loads(kt._handle_complete(- {"task_id": "t_deadbeefdeadbeef", "summary": "x"}))- assert "unknown id, stale run, or already terminal" in out.get("error", "")---def test_complete_terminal_stays_generic(monkeypatch, tmp_path):- """An already-done task keeps the generic message (no parents to name)."""- _isolated_home(monkeypatch, tmp_path)- monkeypatch.setenv("HERMES_PROFILE", "test-worker")- from hermes_cli import kanban_db as kb- from hermes_cli import kanban_db_connect as kbc- from tools import kanban_tools as kt- conn = kbc.connect()- try:- tid = kb.create_task(conn, title="t", assignee="test-worker")- assert kb.claim_task(conn, tid) is not None- assert kb.complete_task(conn, tid, result="done")- finally:- conn.close()- monkeypatch.setenv("HERMES_KANBAN_TASK", tid)- out = json.loads(kt._handle_complete({"task_id": tid, "summary": "again"}))- assert "unknown id, stale run, or already terminal" in out.get("error", "")---def test_complete_happy_path_unchanged(monkeypatch, tmp_path):- """Parents done -> completion still succeeds exactly as before."""- _isolated_home(monkeypatch, tmp_path)- monkeypatch.setenv("HERMES_PROFILE", "test-worker")- from hermes_cli import kanban_db as kb- from hermes_cli import kanban_db_connect as kbc- from tools import kanban_tools as kt- conn = kbc.connect()- try:- parent = kb.create_task(conn, title="p", assignee="op")- assert kb.complete_task(conn, parent, result="p done")- child = kb.create_task(- conn, title="c", assignee="test-worker", parents=[parent])- assert kb.claim_task(conn, child) is not None- finally:- conn.close()- monkeypatch.setenv("HERMES_KANBAN_TASK", child)- out = json.loads(kt._handle_complete({"task_id": child, "summary": "c done"}))- assert out.get("ok") is True+ rc = kc._cmd_complete(argparse.Namespace(+ task_ids=[child_id], result=None, summary=None, metadata=None, force=True))+ out = capsys.readouterr()+ assert rc != 0+ assert parent_id in out.out + out.err+ assert "unknown id or terminal state" not in out.out + out.errdef test_delegate_description_states_child_handoff_contract():- """Spawn-time surfacing (#113373 ask 1): the delegate_task schema tells the- parent up front that a child cannot close tracked work and must hand back- findings. Keyword-level so rewording does not break CI."""+ """Spawn-time surfacing: the delegate_task schema tells the parent up front+ that a child cannot close tracked work and must hand back findings."""from tools.delegate_tool import _build_top_level_description- desc = _build_top_level_description()- assert "tracked work" in desc- assert len(desc) <= 2200+ assert "tracked work" in _build_top_level_description()diff --git a/tests/tools/test_kanban_tools.py b/tests/tools/test_kanban_tools.pyindex f3108c2fd66..babfe6114ee 100644--- a/tests/tools/test_kanban_tools.py+++ b/tests/tools/test_kanban_tools.py@@ -539,7 +539,6 @@ def test_link_running_child_allows_owner_but_rejects_foreign(monkeypatch, workerforeign_child = kb.create_task(conn, title="foreign worker")assert kb.claim_task(conn, foreign_child, claimer="other") is not None- monkeypatch.setenv("HERMES_KANBAN_BOARD", "default")monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(own_run_id))own = json.loads(kt._handle_link({"parent_id": own_parent, "child_id": worker_env}))foreign = json.loads(kt._handle_link(@@ -553,34 +552,6 @@ def test_link_running_child_allows_owner_but_rejects_foreign(monkeypatch, workerassert kb.parent_ids(conn, foreign_child) == []-def test_link_running_child_does_not_borrow_ownership_across_boards(monkeypatch, worker_env):- from hermes_cli import kanban_db as kb- from hermes_cli import kanban_db_connect as kbc- from tools import kanban_tools as kt-- with kbc.connect() as conn:- own_run_id = kb.get_task(conn, worker_env).current_run_id-- kb.create_board("alt")- with kbc.connect(board="alt") as conn:- parent = kb.create_task(conn, title="alternate parent")- child = kb.create_task(conn, title="colliding worker")- conn.execute("UPDATE tasks SET id = ? WHERE id = ?", (worker_env, child))- conn.commit()- assert kb.claim_task(conn, worker_env, claimer="other") is not None- assert kb.get_task(conn, worker_env).current_run_id == own_run_id-- monkeypatch.setenv("HERMES_KANBAN_BOARD", "default")- monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(own_run_id))- result = json.loads(kt._handle_link({- "board": "alt", "parent_id": parent, "child_id": worker_env,- }))-- assert "child is already running" in result["error"]- with kbc.connect(board="alt") as conn:- assert kb.parent_ids(conn, worker_env) == []--def test_unblock_happy_path(monkeypatch, worker_env):monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)from hermes_cli import kanban_db as kbdiff --git a/tools/kanban_tools.py b/tools/kanban_tools.pyindex 24f456c1347..9da18c182ad 100644--- a/tools/kanban_tools.py+++ b/tools/kanban_tools.py@@ -167,10 +167,8 @@ def _own_task_env(task_id: str, var: str) -> Optional[str]:return os.environ.get(var) if os.environ.get("HERMES_KANBAN_TASK") == task_id else None-def _worker_run_id(task_id: str, target_board: Optional[str] = None) -> Optional[int]:- """This worker's dispatcher run id, optionally bound to its pinned board."""- if target_board is not None and os.environ.get("HERMES_KANBAN_BOARD") != target_board:- return None+def _worker_run_id(task_id: str) -> Optional[int]:+ """This worker's dispatcher run id when it is scoped to task_id."""raw = _own_task_env(task_id, "HERMES_KANBAN_RUN_ID")try:return int(raw) if raw else None@@ -524,6 +522,10 @@ def _handle_show(args: dict, **kw) -> str:return json.dumps({"task": _fields(task, _TASK_FIELDS),"parents": kb.parent_ids(conn, tid),+ # Non-terminal parents; on a running card this means the dependency+ # gate is not holding it and kanban_complete will refuse.+ "unsatisfied_parents": [+ {"id": pid, "status": status} for pid, status in kb.unsatisfied_parents(conn, tid)],"children": kb.child_ids(conn, tid),"comments": [_fields(c, _COMMENT_FIELDS) for c in kb.list_comments(conn, tid)],# Capped; full log via CLI.@@ -563,25 +565,6 @@ def _handle_list(args: dict, **kw) -> str:"promoted": promoted})-def _unsatisfied_parent_blockers(kb, conn, tid: str) -> list[tuple[str, str]]:- """``(parent_id, status)`` for every direct parent not in a terminal state.-- Read-only mirror of the ``task_links`` join in ``kanban_db._parents_satisfied``- (``done`` / ``archived`` release the child), in deterministic id order, so a- ``complete_task`` refusal that only returns ``False`` can still name the- actionable blockers. Advisory reporting only: queried after the authoritative- write, so a concurrent parent completion may have already cleared it.- """- rows = conn.execute(- "SELECT p.id, p.status FROM task_links l "- "JOIN tasks p ON p.id = l.parent_id "- "WHERE l.child_id = ? AND p.status NOT IN ('done', 'archived') "- "ORDER BY p.id",- (tid,),- ).fetchall()- return [(row["id"], row["status"]) for row in rows]--@_kanban_handler("kanban_complete")def _handle_complete(args: dict, **kw) -> str:"""Mark the current task done with a structured handoff."""@@ -640,10 +623,9 @@ def _handle_complete(args: dict, **kw) -> str:task = kb.get_task(conn, tid)if not ok:# complete_task reports every refusal as bare False; a reopened or- # never-finished parent is the actionable one (#113373: the worker's- # done work was refused as "stale run"). Name the blockers so the- # worker/operator completes the parents instead of re-running.- blockers = _unsatisfied_parent_blockers(kb, conn, tid)+ # never-finished parent is the actionable one. Name the blockers so+ # the worker/operator completes the parents instead of re-running.+ blockers = kb.unsatisfied_parents(conn, tid)if blockers:detail = ", ".join(f"{pid} ({status})" for pid, status in blockers)raise _Reject(@@ -1067,19 +1049,17 @@ def _handle_unblock(args: dict, **kw) -> str:@_kanban_handler("kanban_link")def _handle_link(args: dict, **kw) -> str:- """Add a dependency edge, proving ownership for an active child handoff."""+ """Add a parent→child dependency edge after the fact (cycles/self-links/running+ children → ValueError). A worker linking its OWN running card proves ownership+ with its run id so the dependency-block handoff still works."""_reject_delegated_child_mutation("kanban_link")parent_id = args.get("parent_id")child_id = args.get("child_id")_check(parent_id and child_id, "both parent_id and child_id are required")with _board(args.get("board")) as (kb, conn):- target_board = kb._normalize_board_slug(args.get("board")) or kb.get_current_board()gated = kb.link_tasks(- conn,- parent_id=parent_id,- child_id=child_id,- expected_child_run_id=_worker_run_id(child_id, target_board),- )+ conn, parent_id=parent_id, child_id=child_id,+ expected_child_run_id=_worker_run_id(str(child_id)))return _ok(parent_id=parent_id, child_id=child_id, gated=gated,**({"gated_by": parent_id} if gated else {}))diff --git a/website/docs/user-guide/features/kanban-worker-lanes.md b/website/docs/user-guide/features/kanban-worker-lanes.mdindex 39c7d53c2b1..6507462f9e2 100644--- a/website/docs/user-guide/features/kanban-worker-lanes.md+++ b/website/docs/user-guide/features/kanban-worker-lanes.md@@ -133,6 +133,7 @@ So lane authors don't have to reimplement these:- **Run-level retry** — when a task is retried (post-block, post-crash, post-reclaim), the worker can use the `expected_run_id` parameter on terminating tools to fail fast if its own run was already superseded.- **Per-task max runtime** — `task.max_runtime_seconds` hard-caps wall-clock time per run, regardless of PID liveness. Catches genuinely-deadlocked workers that the live-PID extension would otherwise keep running.- **Stranded-task detection** — a ready task whose assignee never produces a claim within `kanban.stranded_threshold_seconds` (default 30 min) shows up in `hermes kanban diagnostics` as a `stranded_in_ready` warning. Severity escalates to error at 2x the threshold and critical at 6x. Catches typo'd assignees, deleted profiles, and down external worker pools in one signal — identity-agnostic, no per-board allowlist to curate.+- **Running with open parents** — a `running` card whose direct parent is not `done`/`archived` (the parent reopened mid-run, or the link predates the running-child refusal) shows a `running_with_open_parents` warning: the dependency gate is not serialising the two runs and `kanban_complete` will be refused until the parent finishes. Read-only; suggests `hermes kanban unlink`.- **Legacy review dependency deadlock** — a parent sticky-blocked with `review-required:` while one or more direct children remain dependency-gated in `todo` produces an immediate `review_dependency_deadlock` error. The diagnostic is read-only: it suggests completing the finished phase or unlinking the incorrect edge but never removes a user block automatically.## Relateddiff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex e04b4c83954..70e8152bd37 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -405,7 +405,7 @@ Dispatcher-owned workers receive their task lifecycle tools automatically.| `kanban_attach_url` | Attach a file to a task by URL. | `url` || `kanban_attachments` | List a task's attachments. | — || `kanban_create` | (Orchestrators) fan out into child tasks with an `assignee`, optional `parents`, `skills`, etc. Returns `gated: true` + `gated_by` when an open parent parked the new card in `todo`. | `title`, `assignee` |-| `kanban_link` | (Orchestrators) add a `parent_id → child_id` dependency edge after the fact. Returns `gated: true` when the child was `ready` and got demoted back to `todo` because the parent is not done — the child will only run after the parent completes. | `parent_id`, `child_id` |+| `kanban_link` | (Orchestrators) add a `parent_id → child_id` dependency edge after the fact. Returns `gated: true` when the child was `ready` and got demoted back to `todo` because the parent is not done — the child will only run after the parent completes. Refused with `child is already running` when the child is already claimed — an edge added after the claim cannot serialise the run (a worker may still link its *own* running card ahead of a `kind=dependency` block). | `parent_id`, `child_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:@@ -1277,6 +1277,8 @@ Runs are exposed on the dashboard (Run History section in the drawer, one colour**Bulk close caveat.** `hermes kanban complete a b c --summary X` is refused — structured handoff is per-run, so copy-pasting the same summary to N tasks is almost always wrong. Bulk close *without* `--summary` / `--metadata` still works for the common "I finished a pile of admin tasks" case.+**Dependency refusal on complete names the parents.** `kanban_complete` / `hermes kanban complete` on a card whose direct parent is not `done`/`archived` (a parent reopened mid-run, or an edge that predates the running-child refusal) reports `unsatisfied parent dependencies: t_… (todo)` instead of the generic "unknown id, stale run, or already terminal" text; the card stays in-flight. `kanban_show` lists the same parents under `unsatisfied_parents`, and `hermes kanban show` / `hermes kanban diagnostics` / the dashboard raise a `running_with_open_parents` warning on a running card in that state. Finish the parent or `hermes kanban unlink <parent> <child>`; there is no force path through the dependency gate.+**Live-claim guard on complete.** A `running` task whose worker holds a live claim is only completed by that worker (`kanban_complete` from inside the run) or by an explicit operator override: `hermes kanban complete <id> --force` and the dashboard's "mark done" action. A claim-less `hermes kanban complete <id>` or an orchestrator session's `kanban_complete` is refused with a pointer to `--force` / `hermes kanban reclaim`, so a second session can no longer close a live worker's run underneath it. Completing `ready`, `blocked` or `review` cards without a claim is unchanged.**Reclaimed runs from status changes.** If you drag a running task off `running` in the dashboard (back to `ready`, or straight to `todo`), or archive a task that was still running, the in-flight run closes with `outcome='reclaimed'` rather than being orphaned. The `task_runs` row is always in a terminal state when `tasks.current_run_id` is `NULL`, and vice versa — that invariant holds across CLI, dashboard, dispatcher, and notifier.