Skip to content

The agent that grows with you

fix(kanban): host spawn refusals stop charging cards; oneshot-unit dispatch scope-wraps workers

teknium1eb28bc1bf7e9
diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.py
index a46fb0c376e..915231180c6 100644
--- a/hermes_cli/kanban_db_dispatch.py
+++ b/hermes_cli/kanban_db_dispatch.py
@@ -1231,6 +1231,7 @@ def _record_task_failure(
release_claim: bool = False,
end_run: bool = False,
event_payload_extra: Optional[dict] = None,
+ infrastructure: bool = False,
) -> bool:
"""Record a non-success outcome and maybe trip the circuit breaker; every
non-success path funnels through here so ``consecutive_failures`` stays
@@ -1243,6 +1244,12 @@ def _record_task_failure(
``blocked`` + ``gave_up``). Threshold: per-task ``max_retries`` >
``failure_limit`` > ``DEFAULT_FAILURE_LIMIT``. ``force_trip`` trips
unconditionally (caller applied its own bounded-retry policy).
+
+ ``infrastructure=True``: the host refused the spawn (no restart-safe scope,
+ #114720) — nothing about the card ran, so the run and event are recorded
+ with ``infrastructure: true`` but ``consecutive_failures`` is left alone and
+ the breaker never trips; the card stays retryable and
+ :func:`check_respawn_guard` spaces the retries.
"""
if failure_limit is None:
failure_limit = DEFAULT_FAILURE_LIMIT
@@ -1259,7 +1266,7 @@ def _record_task_failure(
if release_claim
else ("review" if row["status"] == "review" else "ready")
)
- failures = int(row["consecutive_failures"]) + 1
+ failures = int(row["consecutive_failures"]) + (0 if infrastructure else 1)
# Per-task override wins over caller-supplied and default thresholds.
task_override = _kb._row_get(row, "max_retries")
@@ -1268,7 +1275,7 @@ def _record_task_failure(
else:
effective_limit, limit_source = int(failure_limit), "dispatcher"
- if not (force_trip or failures >= effective_limit):
+ if infrastructure or not (force_trip or failures >= effective_limit):
if release_claim:
# Spawn path: restore the claimed source phase + clear claim.
conn.execute(
@@ -1286,15 +1293,13 @@ def _record_task_failure(
)
# Timeout/crash path's caller already emitted its own event.
if end_run:
+ detail = {"failures": failures, "retry_status": retry_status}
+ if infrastructure:
+ detail["infrastructure"] = True
run_id = _kb._end_run(
- conn, task_id, outcome=outcome, status=outcome, error=error,
- metadata={"failures": failures, "retry_status": retry_status},
- )
- _kb._append_event(
- conn, task_id, outcome,
- {"error": error, "failures": failures, "retry_status": retry_status},
- run_id=run_id,
+ conn, task_id, outcome=outcome, status=outcome, error=error, metadata=detail,
)
+ _kb._append_event(conn, task_id, outcome, {"error": error, **detail}, run_id=run_id)
return False
# Spawn path (release_claim) is still running and also clears claim
@@ -1372,6 +1377,8 @@ def check_respawn_guard(
"""Return a guard reason if ``task_id`` should NOT be re-spawned, else None.
Called per ready/review row before any claim attempt. Priority order:
+ ``"infrastructure_cooldown"`` (latest run is a ``spawn_failed`` the host
+ refused — no restart-safe scope — within the cooldown; never counted),
``"rate_limit_cooldown"`` (latest run ``rate_limited`` within the cooldown;
checked BEFORE ``blocker_auth`` because the requeue stamps a quota-flavored
``last_failure_error`` that would otherwise park the task forever — that
@@ -1396,13 +1403,21 @@ def check_respawn_guard(
# 1. Rate-limit cooldown — see docstring for why this precedes blocker_auth.
# LATEST run only: a newer crash/completion supersedes the rate-limit run.
+ # An infrastructure spawn refusal (#114720) shares the cooldown: the host
+ # condition is not the card's, so it retries forever, spaced, and never
+ # reaches the breaker.
rl_cooldown = _kb._resolve_rate_limit_cooldown_seconds()
latest_run = conn.execute(
- "SELECT outcome, ended_at FROM task_runs "
+ "SELECT outcome, ended_at, metadata FROM task_runs "
"WHERE task_id = ? AND ended_at IS NOT NULL "
"ORDER BY ended_at DESC LIMIT 1",
(task_id,),
).fetchone()
+ if latest_run is not None and latest_run["outcome"] == "spawn_failed":
+ if rl_cooldown > 0 and _kb._json_dict(latest_run["metadata"]).get("infrastructure"):
+ ended_at = latest_run["ended_at"]
+ if ended_at is not None and (now - int(ended_at)) < rl_cooldown:
+ return "infrastructure_cooldown"
if latest_run is not None and latest_run["outcome"] == "rate_limited":
if rl_cooldown <= 0:
# Cooldown disabled — respawn immediately, skipping blocker_auth so
@@ -1949,9 +1964,17 @@ def _dispatch_lane_task(
_count_spawn(claimed.assignee)
return True
except Exception as exc:
+ from tools.process_registry import RestartSafeScopeUnavailable
+
+ # The host refused the spawn (no restart-safe scope): nothing about the
+ # card ran, so it must not spend the card's retry budget (#114720).
+ infrastructure = isinstance(exc, RestartSafeScopeUnavailable)
+ if infrastructure:
+ _kb._log.warning("kanban dispatcher: spawn of %s deferred, host cannot place the worker: %s", claimed.id, exc)
if _record_task_failure(
conn, claimed.id, str(exc),
outcome="spawn_failed", failure_limit=failure_limit, release_claim=True, end_run=True,
+ infrastructure=infrastructure,
):
result.auto_blocked.append(claimed.id)
return False
@@ -2546,10 +2569,15 @@ def _open_worker_log(task: Task, board: Optional[str]):
def _restart_safe_worker_argv(task: Task, command: list[str]) -> list[str]:
- """Wrap a managed-gateway worker in the shared restart-safe scope.
-
- Kanban workers are long-lived agentic runs, so they never take cron's
- degraded mode: ``require_restart_safe_scope=True`` makes the helper raise.
+ """Wrap a systemd-hosted dispatcher's worker in the shared restart-safe scope.
+
+ Kanban workers are long-lived agentic runs that outlive the dispatcher
+ tick, so they never take cron's degraded mode under the managed gateway:
+ ``require_restart_safe_scope=True`` makes the helper raise
+ ``RestartSafeScopeUnavailable`` there (an infrastructure spawn failure the
+ dispatcher does not charge to the card). Under any other systemd unit
+ (``Type=oneshot`` dispatch timers, #113612) ``outlives_parent=True`` gets the
+ worker its own scope so the unit's cgroup teardown cannot kill it.
"""
from tools.process_registry import restart_safe_gateway_child_argv
@@ -2561,6 +2589,7 @@ def _restart_safe_worker_argv(task: Task, command: list[str]) -> list[str]:
command,
unit_suffix=f"kanban-{task.id}-run-missing",
require_restart_safe_scope=True,
+ outlives_parent=True,
)
if dispatch.mode != "in_process":
raise RuntimeError(
@@ -2573,6 +2602,7 @@ def _restart_safe_worker_argv(task: Task, command: list[str]) -> list[str]:
command,
unit_suffix=f"kanban-{task.id}-run-{task.current_run_id}",
require_restart_safe_scope=True,
+ outlives_parent=True,
).argv
diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.py
index c2407598505..4dd37391626 100644
--- a/tests/hermes_cli/test_kanban_db.py
+++ b/tests/hermes_cli/test_kanban_db.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import concurrent.futures
+import json
import os
import sqlite3
import subprocess
@@ -427,6 +428,57 @@ def test_respawn_guard_defers_rate_limited_within_cooldown(
assert kbd.check_respawn_guard(conn, tid) is None
+def test_infrastructure_spawn_refusal_never_charges_the_card(
+ kanban_home, monkeypatch, all_assignees_spawnable,
+):
+ """The host refusing to place a worker (managed gateway, user bus gone —
+ #114720) is not a card failure: through the REAL spawn boundary and the
+ real dispatcher accounting, ``consecutive_failures`` stays put, the breaker
+ never parks the card as a bare ``blocked``, the run is tagged
+ ``infrastructure`` and the guard spaces the retries. A control spawn
+ failure on the same card still counts."""
+ import tools.process_registry as process_registry
+
+ monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: True)
+ monkeypatch.setenv("INVOCATION_ID", "managed-gateway")
+ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)
+ monkeypatch.setenv("HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS", "0")
+
+ def spawn_via_real_boundary(task, workspace, board=None):
+ kbd._restart_safe_worker_argv(task, ["hermes", "chat"]) # raises: real probe verdict, real _degrade()
+ raise AssertionError("unreachable")
+
+ with kbc.connect() as conn:
+ tid = kb.create_task(conn, title="bus is down", assignee="a")
+ for _ in range(3):
+ res = kbd.dispatch_once(conn, spawn_fn=spawn_via_real_boundary, failure_limit=2)
+ assert res.auto_blocked == []
+ row = conn.execute(
+ "SELECT status, block_kind, consecutive_failures, last_failure_error FROM tasks WHERE id = ?", (tid,),
+ ).fetchone()
+ assert (row["status"], row["block_kind"], row["consecutive_failures"]) == ("ready", None, 0)
+ assert "enable-linger" in row["last_failure_error"]
+ runs = conn.execute(
+ "SELECT outcome, metadata FROM task_runs WHERE task_id = ? ORDER BY id", (tid,),
+ ).fetchall()
+ assert [r["outcome"] for r in runs] == ["spawn_failed"] * 3
+ assert all(json.loads(r["metadata"])["infrastructure"] is True for r in runs)
+
+ monkeypatch.setenv("HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS", "300")
+ assert kbd.check_respawn_guard(conn, tid) == "infrastructure_cooldown"
+
+ # Control: an ordinary spawn failure on the same card still spends budget.
+ monkeypatch.setenv("HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS", "0")
+
+ def spawn_broken(task, workspace, board=None):
+ raise RuntimeError("profile launcher exploded")
+
+ kbd.dispatch_once(conn, spawn_fn=spawn_broken, failure_limit=2)
+ assert conn.execute(
+ "SELECT consecutive_failures FROM tasks WHERE id = ?", (tid,),
+ ).fetchone()[0] == 1
+
+
diff --git a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
index 3b7bd85cfc1..e6088ea2ecb 100644
--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py
@@ -130,6 +130,8 @@ def test_standalone_dispatcher_keeps_direct_worker_spawn(
class FakeProc:
pid = 4243
+ # Standalone = no systemd unit at all (CI runners inherit INVOCATION_ID).
+ monkeypatch.delenv("INVOCATION_ID", raising=False)
monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kwargs: captured_cmd.extend(cmd) or FakeProc())
monkeypatch.setattr("tools.process_registry._is_supervised_gateway_process", lambda: False)
monkeypatch.setattr(
@@ -141,6 +143,51 @@ def test_standalone_dispatcher_keeps_direct_worker_spawn(
assert captured_cmd[:3] == ["hermes", "-p", "coder"]
+def test_oneshot_unit_dispatcher_scope_wraps_or_warns_never_dooms_silently(
+ worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ """A dispatcher under any systemd unit that is NOT the supervised gateway (a
+ ``Type=oneshot`` dispatch timer, #113612) loses its cgroup at unit exit. With a
+ user bus the worker gets its own ``hermes-worker-*`` scope; without one the
+ spawn still happens (the unit's ``KillMode``/lifetime is unknowable, a
+ long-lived sequencer keeps working) but the operator is told exactly why the
+ workers may die. A cron caller under the same unit is unchanged."""
+ from tools import process_registry
+
+ workspace, task = worker_setup
+ spawned: list[list[str]] = []
+
+ class FakeProc:
+ pid = 4243
+
+ monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kwargs: spawned.append(list(cmd)) or FakeProc())
+ monkeypatch.setenv("INVOCATION_ID", "oneshot-dispatch-timer")
+ monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: False)
+ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: True)
+ monkeypatch.setattr(
+ process_registry, "_build_systemd_scope_argv",
+ lambda cmd, unit_suffix: ["systemd-run", "--user", "--scope", "--unit", f"hermes-worker-{unit_suffix}", *cmd],
+ )
+
+ kbd._default_spawn(task, str(workspace))
+ assert spawned[-1][:3] == ["systemd-run", "--user", "--scope"]
+ assert f"hermes-worker-kanban-{task.id}-run-{task.current_run_id}" in spawned[-1]
+
+ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)
+ monkeypatch.setattr(process_registry, "_scope_degraded_warned", False)
+ with caplog.at_level("WARNING", logger=process_registry.logger.name):
+ kbd._default_spawn(task, str(workspace))
+ assert spawned[-1][:3] == ["hermes", "-p", "coder"]
+ warned = [r.getMessage() for r in caplog.records if "KILLED when the unit exits" in r.getMessage()]
+ assert len(warned) == 1 and "KillMode=process" in warned[0]
+
+ cron = process_registry.restart_safe_gateway_child_argv(
+ ["hermes", "cron"], unit_suffix="cron-job-1", require_restart_safe_scope=True,
+ )
+ assert cron.mode == "in_process"
+
+
@pytest.mark.linux_only
def test_real_user_systemd_scope_preserves_worker_context(
worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch
diff --git a/tools/process_registry.py b/tools/process_registry.py
index a7bd4130e1d..673880e09d5 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -295,19 +295,36 @@ def _build_systemd_scope_argv(shell_argv: List[str], unit_suffix: str) -> List[s
_scope_degraded_warned = False
-def _warn_scope_degraded_once(detail: str) -> None:
+class RestartSafeScopeUnavailable(RuntimeError):
+ """A ``require_restart_safe_scope=True`` child could not get its transient scope.
+
+ Host-level (no user D-Bus / no ``systemd-run``), never a property of the
+ child being launched: callers that keep per-job retry budgets must not
+ charge it (a kanban card parked ``blocked`` for an unreachable bus, #114720).
+ """
+
+
+def _warn_scope_degraded_once(detail: str, *, consequence: str) -> None:
"""Warn once per process: the condition is host-level and the probe verdict
is cached, so this would otherwise fire on every cron dispatch."""
global _scope_degraded_warned
if _scope_degraded_warned:
return
_scope_degraded_warned = True
- logger.warning(
- "managed gateway: %s; cron children are dispatched as direct external subprocesses "
- "without restart-safe cgroup isolation (killed if the gateway restarts mid-job). "
- "Set cron.require_restart_safe_scope=true in config.yaml to fail closed instead.",
- detail,
- )
+ logger.warning("%s; %s", detail, consequence)
+
+
+_CRON_DEGRADED_CONSEQUENCE = (
+ "cron children are dispatched as direct external subprocesses without restart-safe "
+ "cgroup isolation (killed if the gateway restarts mid-job). Set "
+ "cron.require_restart_safe_scope=true in config.yaml to fail closed instead."
+)
+_UNIT_DEGRADED_CONSEQUENCE = (
+ "workers are spawned unmanaged inside this systemd unit's cgroup and will be KILLED when the "
+ "unit exits (Type=oneshot dispatch timers lose every worker within a second). Give the unit's "
+ "user a session bus (`loginctl enable-linger <user>`) so workers get their own scope, or set "
+ "KillMode=process on the unit."
+)
class GatewayChildDispatch(NamedTuple):
@@ -348,6 +365,7 @@ def scoped_spawn_lost_user_bus(spawn_env: Dict[str, str]) -> bool:
def restart_safe_gateway_child_argv(
command: List[str], *, unit_suffix: str, require_restart_safe_scope: bool,
+ outlives_parent: bool = False,
) -> GatewayChildDispatch:
"""Place a managed-systemd gateway child outside the gateway cgroup.
@@ -355,20 +373,38 @@ def restart_safe_gateway_child_argv(
cgroup, so children that must survive it run in a transient user scope.
Hosts with no user systemd session (containers, LXCs without linger) cannot
create one; hard-failing there is a silent cron outage, so callers state the
- policy: ``require_restart_safe_scope=True`` raises (kanban's long-lived
- workers), ``False`` degrades to a direct external subprocess with a
- once-per-process warning (cron, behind ``cron.require_restart_safe_scope``).
+ policy: ``require_restart_safe_scope=True`` raises
+ :class:`RestartSafeScopeUnavailable` (kanban's long-lived workers), ``False``
+ degrades to a direct external subprocess with a once-per-process warning
+ (cron, behind ``cron.require_restart_safe_scope``).
+
+ ``outlives_parent=True`` (fire-and-forget kanban workers): any *other*
+ systemd unit — a ``Type=oneshot`` dispatch timer, an operator's sequencer
+ service — tears its cgroup down when it exits, so the child is scope-wrapped
+ there too (#113612). Whether that unit actually kills its children
+ (``KillMode``, lifetime) is not knowable here, so without a user bus it
+ degrades with a loud warning instead of refusing: a long-lived
+ ``Type=simple`` sequencer without linger keeps working. A cron job blocks its
+ caller until it finishes and never needs this.
"""
if not _IS_LINUX:
return GatewayChildDispatch("in_process", command)
- if not _is_supervised_gateway_process() or not os.environ.get("INVOCATION_ID"):
+ if not os.environ.get("INVOCATION_ID"):
+ return GatewayChildDispatch("in_process", command)
+ supervised_gateway = _is_supervised_gateway_process()
+ if not supervised_gateway and not outlives_parent:
return GatewayChildDispatch("in_process", command)
def _degrade(detail: str) -> GatewayChildDispatch:
- if require_restart_safe_scope:
- # Stored as the cron execution's error and shown on the job row: name the remedy.
- raise RuntimeError(f"cannot create restart-safe systemd scope for gateway child: {detail}")
- _warn_scope_degraded_once(detail)
+ if supervised_gateway:
+ if require_restart_safe_scope:
+ # Stored as the cron execution's error and shown on the job row: name the remedy.
+ raise RestartSafeScopeUnavailable(
+ f"cannot create restart-safe systemd scope for gateway child: {detail}"
+ )
+ _warn_scope_degraded_once(f"managed gateway: {detail}", consequence=_CRON_DEGRADED_CONSEQUENCE)
+ else:
+ _warn_scope_degraded_once(f"systemd unit dispatch: {detail}", consequence=_UNIT_DEGRADED_CONSEQUENCE)
return GatewayChildDispatch("degraded", command)
if not _systemd_run_user_scope_available():
diff --git a/website/docs/user-guide/features/cron.md b/website/docs/user-guide/features/cron.md
index 05863ffc27a..65248eaf684 100644
--- a/website/docs/user-guide/features/cron.md
+++ b/website/docs/user-guide/features/cron.md
@@ -374,7 +374,7 @@ cron:
require_restart_safe_scope: true
```
-The lasting fix is a user session for the gateway user: `sudo loginctl enable-linger <gateway-user>` (and `XDG_RUNTIME_DIR` / `DBUS_SESSION_BUS_ADDRESS` in the unit for system-level installs), then restart the gateway. Kanban workers always require a scope and fail closed regardless of this key.
+The lasting fix is a user session for the gateway user: `sudo loginctl enable-linger <gateway-user>` (and `XDG_RUNTIME_DIR` / `DBUS_SESSION_BUS_ADDRESS` in the unit for system-level installs), then restart the gateway. Kanban workers always require a scope under the managed gateway regardless of this key: a spawn the host cannot scope is recorded on the card as an infrastructure failure and retried later, never charged to the card (see the [Kanban docs](kanban.md#workers-and-systemd-cgroups)).
The worker is the gateway's own interpreter running `python -m cron.scheduler`, with the gateway's checkout pinned on its `PYTHONPATH` (plus any entries the gateway itself was started with), so it imports the same Hermes tree the gateway runs — regardless of the venv's editable-install mapping, the unit's `WorkingDirectory`, or `PYTHONSAFEPATH` on the host. A worker that dies before acknowledging the handoff records its own stderr tail in the job's last error and in the execution ledger, so the failing import (or whatever killed it) is named instead of a bare exit code.
diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.md
index 9ff023ab937..e3b2cc8b913 100644
--- a/website/docs/user-guide/features/kanban.md
+++ b/website/docs/user-guide/features/kanban.md
@@ -314,6 +314,32 @@ gateway docs). Without a running gateway, `ready` tasks stay where they are
until one comes up — `hermes kanban create` warns about this at creation
time.
+#### Workers and systemd cgroups
+
+Workers are fire-and-forget processes that outlive the dispatcher tick, so
+wherever the dispatcher runs inside a systemd unit the worker is launched in
+its own transient scope (`systemd-run --user --scope --unit hermes-worker-kanban-<task>-run-<run>`)
+and survives that unit's exit or restart. Creating the scope needs the
+dispatching user's session bus (`/run/user/<uid>/bus`); on a system-level
+install give the user one with `sudo loginctl enable-linger <user>`.
+
+- **Gateway dispatcher** (`dispatch_in_gateway: true`, gateway under systemd):
+ the scope is mandatory. If the bus is unreachable the spawn is refused and
+ recorded on the card as an *infrastructure* failure — `spawn_failed` with
+ `metadata.infrastructure: true`, the linger remedy in `last_failure_error`,
+ a warning in the gateway log — and the card stays `ready`. It does **not**
+ advance `consecutive_failures`, so a host blip never parks cards as a bare
+ `blocked`; the respawn guard spaces the retries (`infrastructure_cooldown`,
+ same window as the rate-limit cooldown) until the bus is back.
+- **`hermes kanban dispatch` from your own unit** (a `Type=oneshot` timer, a
+ sequencer service): the worker gets the same scope when the bus is
+ reachable. Without one the worker is still spawned — inside *your* unit's
+ cgroup — and the dispatcher logs once, loudly, that the unit's exit will kill
+ it. `Type=oneshot` with the default `KillMode=control-group` loses every
+ worker within a second of the pass finishing; either enable linger so the
+ scope can be created, or set `KillMode=process` on that unit so its exit
+ only kills the dispatcher itself.
+
Running `hermes kanban daemon` as a separate process is **deprecated**;
use the gateway. If you truly cannot run the gateway (headless host
policy forbids long-lived services, etc.) a `--force` escape hatch keeps
@@ -957,7 +983,7 @@ hermes kanban create "nightly backup audit" \
### Respawn guard
-The dispatcher refuses to re-spawn a ready task when it hit a quota/auth/429 error on the previous run (`blocker_auth`), or completed a run successfully within the guard window (`recent_success`), or a recent task comment links to a GitHub PR (`active_pr`). This prevents repeat worker storms on the same bug or task while a human catches up. See the `respawn_guarded` row in the [event reference](#event-reference).
+The dispatcher refuses to re-spawn a ready task when it hit a quota/auth/429 error on the previous run (`blocker_auth`), or completed a run successfully within the guard window (`recent_success`), or a recent task comment links to a GitHub PR (`active_pr`). Two cooldowns hold a card without ever counting against it: `rate_limit_cooldown` after a quota-wall requeue and `infrastructure_cooldown` after the host refused to place the worker (no restart-safe systemd scope — see [Workers and systemd cgroups](#workers-and-systemd-cgroups)); both share the `HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS` window (default 300 s). This prevents repeat worker storms on the same bug or task while a human catches up. See the `respawn_guarded` row in the [event reference](#event-reference).
To see why a ready card is not spawning, run `hermes kanban dispatch --dry-run` — the output lists `Guarded (<reason>): <task id>` per held card (and `respawn_guarded`, `rate_limited`, `skipped_locked`, `memory_pressure` with `--json`). The gateway's and the standalone daemon's "dispatcher stuck" warning also names what the last tick held back, e.g. `Last tick held back: active_pr=1`.
@@ -1355,7 +1381,7 @@ Every transition appends a row to `task_events`. Each row carries an optional `r
| `timed_out` | `{pid, elapsed_seconds, limit_seconds, sigkill}` | `max_runtime_seconds` exceeded; dispatcher SIGTERM'd (then SIGKILL'd after 5 s grace) and re-queued. |
| `stale` | `{elapsed_seconds, last_heartbeat_at, heartbeat_age_seconds, timeout_seconds, pid, terminated}` | Task ran longer than `kanban.dispatch_stale_timeout_seconds` (default 4 h) AND no `kanban_heartbeat` arrived in the last hour. Dispatcher SIGTERM'd the host-local worker (if any), reset the task to `ready` for re-dispatch. Does NOT tick the failure counter (stale is dispatcher-side absence detection, not a worker fault). Workers running long operations should call `kanban_heartbeat` at least once an hour to avoid this. |
| `reconciled` | `{reason, claim_lock, claim_expires, worker_pid}` | Orphaned-card reconciliation: the card was `running` with broken claim bookkeeping (`claim_lock` or `claim_expires` NULL — crash mid-claim, manual SQL, DB restore) and no live worker, so none of the TTL/crash/stale paths could ever recover it. The dispatcher requeued it to `ready` with an explanatory comment. Gated by `kanban.reconcile_orphans` in config.yaml (default `true`). |
-| `respawn_guarded` | `{reason}` | Dispatcher refused to re-spawn this ready task this tick. Reasons: `blocker_auth` (last failure was a quota/auth/429 error — wait for the rate window to reset), `recent_success` (a completed run happened in the last hour — wait for review before re-running), `active_pr` (a GitHub PR URL appears in a recent comment — a prior worker already opened a PR). The task stays in `ready`; the next tick gets another chance to spawn. If the underlying condition persists, the normal `consecutive_failures` circuit breaker will auto-block via `gave_up` after `failure_limit` failures. |
+| `respawn_guarded` | `{reason}` | Dispatcher refused to re-spawn this ready task this tick. Reasons: `infrastructure_cooldown` (the host refused the last spawn — no restart-safe systemd scope — and the cooldown has not elapsed; never counted against the card), `rate_limit_cooldown` (the last run hit a quota wall; same cooldown, never counted), `blocker_auth` (last failure was a quota/auth/429 error — wait for the rate window to reset), `recent_success` (a completed run happened in the last hour — wait for review before re-running), `active_pr` (a GitHub PR URL appears in a recent comment — a prior worker already opened a PR). The task stays in `ready`; the next tick gets another chance to spawn. If the underlying condition persists, the normal `consecutive_failures` circuit breaker will auto-block via `gave_up` after `failure_limit` failures. |
| `spawn_failed` | `{error, failures}` | One spawn attempt failed (missing PATH, workspace unmountable, …). Counter increments; task returns to `ready` for retry. |
| `protocol_violation` | `{pid, claimer, exit_code, protocol_violation, worker_output?}` | Worker exited successfully while the task was still `running`, usually because it answered without a terminal board call (`kanban_complete`, `kanban_request_review` or `kanban_block`). Emitted on every violation (the payload's `protocol_violation: true` marker is copied into the run metadata and feeds the violation-only retry budget). Below the budget — up to `_PROTOCOL_VIOLATION_FAILURE_LIMIT` (default 3) *consecutive* violations, per-task `max_retries` overriding — the task simply returns to `ready` for another attempt; when the streak reaches the bound the dispatcher also emits `gave_up` and auto-blocks. `worker_output` carries the worker's own last printed text (usually its explanation of why it stopped), also folded into `last_failure_error` and shown to the retry worker as the prior-attempt error. |
| `gave_up` | `{failures, effective_limit, limit_source, error}` | Circuit breaker fired after N consecutive non-successful attempts. Task auto-blocks with the last error. The effective limit resolves as task `max_retries`, then dispatcher `failure_limit` / `kanban.failure_limit`, then the built-in default. |