Skip to content

The agent that grows with you

fix(kanban): warn once when an inherited delegation fence rejects the worker's auto-heartbeat

teknium163fb1a7d36d3
diff --git a/tests/cron/test_cron_kanban_env_isolation.py b/tests/cron/test_cron_kanban_env_isolation.py
index 9e8badc95f0..a177de98057 100644
--- a/tests/cron/test_cron_kanban_env_isolation.py
+++ b/tests/cron/test_cron_kanban_env_isolation.py
@@ -400,17 +400,23 @@ def test_dispatcher_grants_only_the_assigned_worker_scope(tmp_path, monkeypatch)
root = str(Path(__file__).resolve().parents[2])
worker.write_text(
f"#!{sys.executable}\nimport sys, os, json;sys.path.insert(0, {root!r})\n"
- "from tools.kanban_tools import _handle_complete\n"
- f"result=_handle_complete({{'summary':'assigned worker'}});open({str(output)!r}, 'w').write(result)\n"
+ "from tools.kanban_tools import _handle_complete, heartbeat_current_worker_from_env\n"
+ "beat=heartbeat_current_worker_from_env()\n"
+ f"result=json.loads(_handle_complete({{'summary':'assigned worker'}}));result['beat']=beat\n"
+ f"open({str(output)!r}, 'w').write(json.dumps(result))\n"
)
worker.chmod(0o700)
monkeypatch.setenv("HERMES_BIN", str(worker))
# Building a new worker under an existing task must replace, not inherit, its scope.
monkeypatch.setenv("HERMES_KANBAN_TASK", "prior-task")
+ # A dispatcher launched from an agent's shell carries the descendant fence itself; the worker it
+ # grants a task to must not (an inherited marker fences the worker's own heartbeat + handoff).
+ monkeypatch.setenv("HERMES_DELEGATED_CHILD_CONTEXT", str(tmp_path))
pid = _default_spawn(task, str(tmp_path), board="default")
assert pid is not None
os.waitpid(pid, 0) # windows-footgun: ok — Linux-only real dispatcher spawn
- assert json.loads(output.read_text())["ok"]
+ result = json.loads(output.read_text())
+ assert result["ok"] and result["beat"] is True, result
assert kb.get_task(conn, tid).status == "done"
assert os.environ["HERMES_KANBAN_TASK"] == "prior-task"
conn.close()
diff --git a/tests/tools/test_delegate_kanban_isolation.py b/tests/tools/test_delegate_kanban_isolation.py
index 960ae29864f..28658cdfb1d 100644
--- a/tests/tools/test_delegate_kanban_isolation.py
+++ b/tests/tools/test_delegate_kanban_isolation.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
+import logging
import os
import shlex
import sys
@@ -177,9 +178,13 @@ def test_delegate_child_execute_code_env_bridges_contextvar_and_scrubs_kanban(
def test_auto_heartbeat_reports_failure_without_mutating_fenced_child_board(
monkeypatch,
tmp_path,
+ caplog,
):
- """An inherited child marker fences both bridge writes instead of faking success."""
+ """An inherited child marker fences both bridge writes instead of faking success, and says
+ so once at WARNING (the DEBUG-only refusal hid a starving claim for a day). An in-process
+ delegate child stays fenced too, quietly, without consuming the worker's heartbeat window."""
kb, tid, _workspace, _attachments_root = _make_running_kanban_task(monkeypatch, tmp_path)
+ from agent.delegation_context import delegated_child_context
from hermes_cli import kanban_db_connect as kbc
from tools import kanban_tools
@@ -189,8 +194,20 @@ def test_auto_heartbeat_reports_failure_without_mutating_fenced_child_board(
events_before = kb.list_events(conn, tid)
monkeypatch.setenv("HERMES_DELEGATED_CHILD_CONTEXT", str(tmp_path / ".hermes"))
monkeypatch.setattr(kanban_tools, "_auto_heartbeat_last_attempt", 0.0)
+ monkeypatch.setattr(kanban_tools, "_auto_heartbeat_fence_warned", False)
+
+ with caplog.at_level(logging.WARNING, logger="tools.kanban_tools"):
+ assert kanban_tools.heartbeat_current_worker_from_env() is False
+ monkeypatch.setattr(kanban_tools, "_auto_heartbeat_last_attempt", 0.0)
+ assert kanban_tools.heartbeat_current_worker_from_env() is False
+ fence_warnings = [r for r in caplog.records if "HERMES_DELEGATED_CHILD_CONTEXT" in r.getMessage()]
+ assert len(fence_warnings) == 1 and tid in fence_warnings[0].getMessage()
- assert kanban_tools.heartbeat_current_worker_from_env() is False
+ monkeypatch.delenv("HERMES_DELEGATED_CHILD_CONTEXT")
+ monkeypatch.setattr(kanban_tools, "_auto_heartbeat_last_attempt", 0.0)
+ with delegated_child_context("child-1"):
+ assert kanban_tools.heartbeat_current_worker_from_env() is False
+ assert kanban_tools._auto_heartbeat_last_attempt == 0.0
task_after = kb.get_task(conn, tid)
assert task_after.claim_expires == task_before.claim_expires
diff --git a/tools/kanban_tools.py b/tools/kanban_tools.py
index 3fd9a58ced5..3292eadd387 100644
--- a/tools/kanban_tools.py
+++ b/tools/kanban_tools.py
@@ -447,17 +447,22 @@ def _goal_gate(tool_name: str, task, tid: str, evidence: str) -> None:
# for the explicit tool which carries a model-supplied note.
_AUTO_HEARTBEAT_MIN_INTERVAL_SECONDS = 60.0
_auto_heartbeat_last_attempt: float = 0.0
+_auto_heartbeat_fence_warned = False
def heartbeat_current_worker_from_env() -> bool:
"""Claim extension + board heartbeat for the current worker; True iff both writes
succeed. ``HERMES_KANBAN_RUN_ID`` pins the run row so a reclaimed stale run is not
heartbeated; ``HERMES_KANBAN_CLAIM_LOCK`` absent -> default claimer (local workers)."""
- global _auto_heartbeat_last_attempt
+ global _auto_heartbeat_last_attempt, _auto_heartbeat_fence_warned
tid = os.environ.get("HERMES_KANBAN_TASK")
now = time.monotonic()
if not tid or (now - _auto_heartbeat_last_attempt) < _AUTO_HEARTBEAT_MIN_INTERVAL_SECONDS:
return False
+ if _is_delegated_child_context():
+ # An in-process delegate child's activity is not the worker's liveness; checked before
+ # stamping the window so a chatty child cannot starve the worker's own heartbeat.
+ return False
_auto_heartbeat_last_attempt = now
try:
from hermes_cli import kanban_db_dispatch as kbd
@@ -469,6 +474,20 @@ def heartbeat_current_worker_from_env() -> bool:
op = fn.__name__
try:
succeeded = bool(fn(conn, tid, **kwargs)) and succeeded
+ except PermissionError as exc:
+ # The board fence rejected the worker's own liveness write: this process
+ # inherited HERMES_DELEGATED_CHILD_CONTEXT next to HERMES_KANBAN_TASK, so it is
+ # a delegate descendant, not the dispatcher's worker (kanban_complete refuses
+ # too). Loud once: at DEBUG the board just showed a worker that never beats.
+ succeeded = False
+ if not _auto_heartbeat_fence_warned:
+ _auto_heartbeat_fence_warned = True
+ logger.warning(
+ "kanban auto-heartbeat for task %s refused (%s): this process carries "
+ "HERMES_DELEGATED_CHILD_CONTEXT together with HERMES_KANBAN_TASK, so the board "
+ "treats it as a delegate_task descendant and its claim will not be extended by "
+ "activity. Only the dispatcher's own spawn grants worker scope; do not copy a "
+ "worker's environment into a hand-launched process.", tid, exc)
except Exception:
logger.debug("auto-heartbeat: %s failed", op, exc_info=True)
succeeded = False
diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.md
index 96e36a702f9..837799590ec 100644
--- a/website/docs/user-guide/features/kanban.md
+++ b/website/docs/user-guide/features/kanban.md
@@ -553,6 +553,8 @@ Every profile that works kanban tasks automatically gets the worker lifecycle
3. Call `kanban_heartbeat(note="...")` every few minutes during long operations. **If your work may run longer than 1 hour, call `kanban_heartbeat` at least once an hour** — the dispatcher reclaims tasks that have been running past `kanban.dispatch_stale_timeout_seconds` (default 4 h) with no heartbeat in the last hour, on the assumption the worker crashed without cleanup. A reclaim is benign (the task goes back to `ready` for re-dispatch without a failure-counter tick) but you lose your current run's progress.
4. Complete with `kanban_complete(summary="...", metadata={...})`, hand a code change off for same-card review with `kanban_request_review(summary="...")`, or `kanban_block(reason="...")` if stuck.
+Normal tool activity also extends the claim automatically (the worker mirrors its in-process liveness onto the board about once a minute). That bridge only works for a process the dispatcher spawned itself: a process that carries `HERMES_DELEGATED_CHILD_CONTEXT` next to `HERMES_KANBAN_TASK` (a `delegate_task` descendant, or a hand-launched copy of a worker's environment) is fenced from the board — its auto-heartbeat logs one `kanban auto-heartbeat for task … refused` warning and `kanban_complete` / `kanban_request_review` refuse. Fix the launch (let the dispatcher spawn the worker) rather than exporting the marker away.
+
That final terminal board call (`kanban_complete` / `kanban_request_review` /
`kanban_block`; reviewers end with `kanban_complete` or `kanban_request_changes`)
is part of the worker