Skip to content

The agent that grows with you

fix(kanban): preserve owned dependency handoffs

fangliquanflq117b77965d70
diff --git a/hermes_cli/kanban.py b/hermes_cli/kanban.py
index 94d8e323bc5..2ea787da245 100644
--- a/hermes_cli/kanban.py
+++ b/hermes_cli/kanban.py
@@ -695,7 +695,12 @@ def _cmd_diagnostics(args: argparse.Namespace) -> int:
def _cmd_link(args: argparse.Namespace) -> int:
with kbc.connect_closing() as conn:
- gated = kb.link_tasks(conn, args.parent_id, args.child_id)
+ gated = kb.link_tasks(
+ conn,
+ args.parent_id,
+ args.child_id,
+ expected_child_run_id=_worker_run_id_for(args.child_id),
+ )
print(f"Linked {args.parent_id} -> {args.child_id}")
if gated:
print(
diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py
index 1499e11cf1e..aae8f911a43 100644
--- a/hermes_cli/kanban_db.py
+++ b/hermes_cli/kanban_db.py
@@ -1617,13 +1617,21 @@ def set_reasoning_effort(conn: sqlite3.Connection, task_id: str, effort: Optiona
# --- Links ---
-def link_tasks(conn: sqlite3.Connection, parent_id: str, child_id: str) -> bool:
+def link_tasks(
+ conn: sqlite3.Connection,
+ parent_id: str,
+ child_id: str,
+ *,
+ expected_child_run_id: Optional[int] = None,
+) -> bool:
"""Link ``parent_id -> child_id``. Returns True when the link gated a
``ready`` child back to ``todo`` (the new parent is not yet terminal), so
callers can surface the demotion instead of a silent status flip.
- A running child cannot be gated retroactively, so reject the edge rather
- than record a dependency that did not constrain the active run.
+ A running child cannot normally be gated retroactively, so reject the edge
+ rather than record a dependency that did not constrain the active run. The
+ owning worker may link its own active run for a subsequent dependency-block
+ handoff by supplying its trusted ``expected_child_run_id``.
"""
if parent_id == child_id:
raise ValueError("a task cannot depend on itself")
@@ -1632,7 +1640,13 @@ def link_tasks(conn: sqlite3.Connection, parent_id: str, child_id: str) -> bool:
missing = _missing_task_ids(conn, [parent_id, child_id])
if missing:
raise ValueError(f"unknown task(s): {', '.join(missing)}")
- if _task_status(conn, child_id) == "running":
+ child = conn.execute(
+ "SELECT status, current_run_id FROM tasks WHERE id = ?", (child_id,),
+ ).fetchone()
+ if child["status"] == "running" and (
+ expected_child_run_id is None
+ or child["current_run_id"] != expected_child_run_id
+ ):
raise ValueError(f"cannot link {parent_id} -> {child_id}: child is already running")
if _would_cycle(conn, parent_id, child_id):
raise ValueError(f"linking {parent_id} -> {child_id} would create a cycle")
diff --git a/tests/hermes_cli/test_kanban_block_kinds.py b/tests/hermes_cli/test_kanban_block_kinds.py
index eb316520259..3b8025c4348 100644
--- a/tests/hermes_cli/test_kanban_block_kinds.py
+++ b/tests/hermes_cli/test_kanban_block_kinds.py
@@ -94,7 +94,12 @@ def test_dependency_then_parent_done_promotes(kanban_home: Path) -> None:
with kbc.connect_closing() as conn:
parent = kb.create_task(conn, title="parent", assignee="worker")
child = _running_task(conn, title="child")
- kb.link_tasks(conn, parent_id=parent, child_id=child)
+ kb.link_tasks(
+ conn,
+ parent_id=parent,
+ child_id=child,
+ expected_child_run_id=kb.get_task(conn, child).current_run_id,
+ )
kb.block_task(conn, child, reason="wait", kind="dependency")
assert kb.get_task(conn, child).status == "todo"
# Finish the parent, then let recompute_ready run.
diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.py
index 571e96a1d70..3f37bf8c57a 100644
--- a/tests/hermes_cli/test_kanban_db.py
+++ b/tests/hermes_cli/test_kanban_db.py
@@ -1181,8 +1181,8 @@ def test_link_tasks_emits_dependency_wait_when_demoting_ready_child(kanban_home)
assert payload["parent"] == parent
-def test_link_tasks_rejects_running_child_without_recording_edge(kanban_home):
- """Regression for #113374: a dependency added after claim cannot gate that run."""
+def test_link_tasks_rejects_unowned_running_child_without_recording_edge(kanban_home):
+ """Regression for #113374: an unowned dependency cannot gate an active run."""
with kbc.connect() as conn:
parent = kb.create_task(conn, title="unfinished parent")
child = kb.create_task(conn, title="claimed child")
@@ -1195,6 +1195,23 @@ def test_link_tasks_rejects_running_child_without_recording_edge(kanban_home):
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/tools/test_kanban_tools.py b/tests/tools/test_kanban_tools.py
index 0bb4241ae74..babfe6114ee 100644
--- a/tests/tools/test_kanban_tools.py
+++ b/tests/tools/test_kanban_tools.py
@@ -527,6 +527,31 @@ def test_link_happy_path(worker_env):
assert d["ok"] is True
+def test_link_running_child_allows_owner_but_rejects_foreign(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_parent = kb.create_task(conn, title="own review")
+ own_run_id = kb.get_task(conn, worker_env).current_run_id
+ foreign_parent = kb.create_task(conn, title="foreign review")
+ foreign_child = kb.create_task(conn, title="foreign worker")
+ assert kb.claim_task(conn, foreign_child, claimer="other") is not None
+
+ 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(
+ {"parent_id": foreign_parent, "child_id": foreign_child},
+ ))
+
+ assert own["ok"] is True
+ assert "child is already running" in foreign["error"]
+ with kbc.connect() as conn:
+ assert kb.parent_ids(conn, worker_env) == [own_parent]
+ assert kb.parent_ids(conn, foreign_child) == []
+
+
def test_unblock_happy_path(monkeypatch, worker_env):
monkeypatch.delenv("HERMES_KANBAN_TASK", raising=False)
from hermes_cli import kanban_db as kb
diff --git a/tools/kanban_tools.py b/tools/kanban_tools.py
index 152907eb6d6..51f3ebe2b94 100644
--- a/tools/kanban_tools.py
+++ b/tools/kanban_tools.py
@@ -1035,13 +1035,18 @@ def _handle_unblock(args: dict, **kw) -> str:
@_kanban_handler("kanban_link")
def _handle_link(args: dict, **kw) -> str:
- """Add a parent→child dependency edge after the fact (cycles/self-links → ValueError)."""
+ """Add a dependency edge, proving ownership for an active child handoff."""
_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):
- gated = kb.link_tasks(conn, parent_id=parent_id, child_id=child_id)
+ gated = kb.link_tasks(
+ conn,
+ parent_id=parent_id,
+ child_id=child_id,
+ expected_child_run_id=_worker_run_id(child_id),
+ )
return _ok(parent_id=parent_id, child_id=child_id, gated=gated,
**({"gated_by": parent_id} if gated else {}))
diff --git a/tools/kanban_tools_schemas.py b/tools/kanban_tools_schemas.py
index dbe7312d021..7642b6d58ae 100644
--- a/tools/kanban_tools_schemas.py
+++ b/tools/kanban_tools_schemas.py
@@ -524,7 +524,9 @@ KANBAN_LINK_SCHEMA = _schema(
(
"Add a parent→child dependency edge after both tasks already "
"exist. The child won't promote to 'ready' until all parents "
- "are 'done'. Cycles and self-links are rejected."
+ "are 'done'. Cycles and self-links are rejected. A running child "
+ "is rejected unless the active owning worker is linking its own "
+ "card for a dependency handoff."
),
{
"parent_id": {"type": "string", "description": "Parent task id."},
diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.md
index cabc5d4248d..e04b4c83954 100644
--- a/website/docs/user-guide/features/kanban.md
+++ b/website/docs/user-guide/features/kanban.md
@@ -117,7 +117,7 @@ They coexist: a kanban worker may call `delegate_task` internally during its run
below. Single-project users stay on the `default` board and never see the
word "board" outside this docs section.
- **Task** — a row with title, optional body, one assignee (a profile name), status (`triage | todo | ready | running | blocked | review | done | archived`), optional tenant namespace, optional idempotency key (dedup for retried automation).
-- **Link** — `task_links` row recording a parent → child dependency. The dispatcher promotes `todo → ready` when all parents are `done`.
+- **Link** — `task_links` row recording a parent → child dependency. The dispatcher promotes `todo → ready` when all parents are `done`. Adding a link to a running child is rejected because it cannot gate work already claimed; the one exception is an active worker linking its own card, with dispatcher-provided run ownership, immediately before a dependency-block handoff.
- **Comment** — the inter-agent protocol. Agents and humans append comments; when a worker is (re-)spawned it reads the full comment thread as part of its context.
- **Workspace** — the directory a worker operates in. Three kinds:
- `scratch` (default) — fresh tmp dir under `~/.hermes/kanban/workspaces/<id>/` (or `~/.hermes/kanban/boards/<slug>/workspaces/<id>/` on non-default boards). **Deleted when the task completes** — scratch is ephemeral by design. Files explicitly declared through `kanban_complete(artifacts=[...])` or `kanban_request_review(artifacts=[...])` are copied into durable per-task attachment storage before cleanup (a review handoff stages them at handoff time, since the reviewer's later completion is what deletes the scratch workspace); existing deliverable paths in legacy completion summaries receive the same treatment. Other scratch files are removed. A missing declared scratch artifact keeps the task in-flight so the worker can correct the path and retry. Use `worktree:` or `dir:<path>` when the whole workspace should remain available. The first time a scratch workspace is created on an install, the dispatcher logs a warning and emits a `tip_scratch_workspace` event on the task (visible via `hermes kanban show <id>`).