The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tools): refuse unbound worker run-lifecycle mutations
KeyArgo7c2b5b598156
diff --git a/tests/tools/test_kanban_complete_parents_tool.py b/tests/tools/test_kanban_complete_parents_tool.pyindex ddf094b8109..3097225e23f 100644--- a/tests/tools/test_kanban_complete_parents_tool.py+++ b/tests/tools/test_kanban_complete_parents_tool.py@@ -34,6 +34,7 @@ def running_child_with_parent(monkeypatch, tmp_path):child_id = kb.create_task(conn, title="child work", assignee="test-worker", parents=[parent_id])assert kb.claim_task(conn, child_id) is not None+ run_id = kb._current_run_id(conn, child_id)# Parent reopens mid-run: the #113373 timeline.with kb.write_txn(conn):conn.execute(@@ -43,6 +44,7 @@ def running_child_with_parent(monkeypatch, tmp_path):finally:conn.close()monkeypatch.setenv("HERMES_KANBAN_TASK", child_id)+ monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(run_id))return parent_id, child_iddiff --git a/tests/tools/test_kanban_tools.py b/tests/tools/test_kanban_tools.pyindex babfe6114ee..0094a5cd819 100644--- a/tests/tools/test_kanban_tools.py+++ b/tests/tools/test_kanban_tools.py@@ -64,9 +64,13 @@ def worker_env(monkeypatch, tmp_path):try:tid = kb.create_task(conn, title="worker-test", assignee="test-worker")kb.claim_task(conn, tid)+ run_id = kb._current_run_id(conn, tid)finally:conn.close()monkeypatch.setenv("HERMES_KANBAN_TASK", tid)+ # A real dispatcher always pins the worker's run id; simulate that so the+ # run-lifecycle tools can prove ownership (see test_unbound_worker_cannot_mutate_card).+ monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(run_id))return tid@@ -206,6 +210,70 @@ def test_request_review_accepts_installed_profile(monkeypatch, worker_env, tmp_passert (task.status, task.assignee) == ("review", "verifier")+def test_unbound_worker_cannot_mutate_card(monkeypatch, worker_env):+ """A dispatcher-spawned worker that cannot resolve its run id must be refused+ on every run-lifecycle mutation. ``expected_run_id=None`` would silently skip+ the run-ownership CAS in kanban_db, so an unbound stale worker could complete+ a card a live successor owns (regression for #116239)."""+ from hermes_cli import kanban_db as kb+ from hermes_cli import kanban_db_connect as kbc+ from tools import kanban_tools as kt++ # Worker is scoped to the task (HERMES_KANBAN_TASK set by the fixture) but+ # has NO run id — the unbound state the dispatcher never produces.+ monkeypatch.delenv("HERMES_KANBAN_RUN_ID", raising=False)++ for handler, args in [+ (kt._handle_complete, {"summary": "stale worker says done"}),+ (kt._handle_block, {"reason": "stale worker blocks"}),+ (kt._handle_request_review, {"summary": "stale worker hands off"}),+ (kt._handle_request_changes, {"reason": "stale worker requests changes"}),+ ]:+ out = json.loads(handler(args))+ assert "refused" in out.get("error", ""), f"{handler.__name__} did not refuse: {out}"++ # Nothing moved: the card is still running under its original run.+ with kbc.connect() as conn:+ task = kb.get_task(conn, worker_env)+ assert task.status == "running"+ assert task.current_run_id is not None++ # A bound worker (run id present) still completes normally — the guard only+ # fires on the unbound state, never on the legitimate dispatcher path.+ with kbc.connect() as conn:+ run_id = kb.get_task(conn, worker_env).current_run_id+ monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(run_id))+ out = json.loads(kt._handle_complete({"summary": "bound worker done"}))+ assert out.get("ok") is True+ with kbc.connect() as conn:+ assert kb.get_task(conn, worker_env).status == "done"+++def test_malformed_run_id_refused_but_nonlifecycle_allowed(monkeypatch, worker_env):+ """A malformed (non-integer) HERMES_KANBAN_RUN_ID is treated as unbound and+ refuses run-lifecycle mutations, while non-lifecycle tools (heartbeat /+ attach) that do not terminate a run stay available to the 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++ monkeypatch.setenv("HERMES_KANBAN_RUN_ID", "not-an-int")++ # Run-lifecycle mutations are refused on a malformed run id.+ out = json.loads(kt._handle_complete({"summary": "stale worker says done"}))+ assert "refused" in out.get("error", "")++ # Non-lifecycle tools are NOT gated: heartbeat still extends the claim.+ out = json.loads(kt._handle_heartbeat({}))+ assert out.get("ok") is True+ with kbc.connect() as conn:+ assert kb.get_task(conn, worker_env).status == "running"++++++def test_complete_goal_mode_rejected_by_judge(monkeypatch, tmp_path):"""Goal-mode tasks must pass the auxiliary judge before completion.Regression for #38367: workers bypassing the judge via early kanban_complete."""@@ -231,9 +299,11 @@ def test_complete_goal_mode_rejected_by_judge(monkeypatch, tmp_path):body="Must achieve X with verified evidence.", goal_mode=True)kb.claim_task(conn, goal_task_id)+ run_id = kb._current_run_id(conn, goal_task_id)finally:conn.close()monkeypatch.setenv("HERMES_KANBAN_TASK", goal_task_id)+ monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(run_id))# Mock the judge to reject the completion. The gate only runs when a# judge is reachable, so force the availability probe True as well.@@ -299,9 +369,11 @@ def _make_goal_mode_worker_env(monkeypatch, tmp_path):body="Must achieve X.", goal_mode=True,)kb.claim_task(conn, goal_task_id)+ run_id = kb._current_run_id(conn, goal_task_id)finally:conn.close()monkeypatch.setenv("HERMES_KANBAN_TASK", goal_task_id)+ monkeypatch.setenv("HERMES_KANBAN_RUN_ID", str(run_id))return goal_task_iddiff --git a/tools/kanban_tools.py b/tools/kanban_tools.pyindex 3292eadd387..95a12537c83 100644--- a/tools/kanban_tools.py+++ b/tools/kanban_tools.py@@ -104,6 +104,15 @@ def _check_kanban_orchestrator_mode() -> bool:# --- Shared helpers: validation failures raise _Reject; _kanban_handler renders it ---+# Worker tools that terminate or transition a run's ownership. An unbound worker+# (HERMES_KANBAN_RUN_ID unresolvable) must not run these: expected_run_id=None+# would silently skip the run-ownership CAS in kanban_db. Non-lifecycle tools+# (heartbeat / attach / attach_url) do not terminate a run and are not gated.+_RUN_LIFECYCLE_TOOLS = frozenset({+ "kanban_complete", "kanban_block",+ "kanban_request_review", "kanban_request_changes",+})+class _Reject(Exception):"""Carries a finished ``tool_error`` payload out of a validation helper."""@@ -200,10 +209,36 @@ def _enforce_worker_task_ownership(tid: str) -> None:def _worker_guard(tool_name: str, args: dict) -> str:"""Worker mutation preamble, in order: delegate-child rejection, task id- resolution, task-scope ownership. Returns the task id."""+ resolution, task-scope ownership, run-identity proof. Returns the task id.++ A dispatcher-spawned worker (``HERMES_KANBAN_TASK`` set) that cannot name+ its run id is refused on the run-lifecycle mutations: ``expected_run_id=None``+ would silently skip the run-ownership CAS in ``kanban_db`` (``complete_task`` /+ ``block_task`` / ``request_review`` / ``request_changes`` only append+ ``AND current_run_id = ?`` when the value is not ``None``), so an unbound+ stale worker could complete a card a live successor owns. This mirrors+ ``agent/kanban_stop.py``, which already treats an unbound run id as unknown+ and fails closed. CLI / human / orchestrator paths (no ``HERMES_KANBAN_TASK``)+ legitimately pass ``expected_run_id=None`` and are unaffected. Non-lifecycle+ worker tools (heartbeat / attach / attach_url) do not terminate a run and are+ not gated here.+ """_reject_delegated_child_mutation(tool_name)tid = _require_task_id(args)_enforce_worker_task_ownership(tid)+ if (+ tool_name in _RUN_LIFECYCLE_TOOLS+ and os.environ.get("HERMES_KANBAN_TASK")+ and _worker_run_id(tid) is None+ ):+ raise _Reject(+ f"{tool_name} refused: this worker cannot resolve its "+ "HERMES_KANBAN_RUN_ID, so it cannot prove ownership of the card's "+ "current run. A stale or unbound worker must not terminate a run a "+ "live successor owns. Re-run through the dispatcher so the run id is "+ "pinned, or use an orchestrator/CLI path that passes an explicit "+ "expected_run_id."+ )return tid