The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(kanban-db): compact docstrings/comments in the four split modules (AST-identical, every WHY kept)
Teknium464ee35248a0
diff --git a/hermes_cli/kanban_db_connect.py b/hermes_cli/kanban_db_connect.pyindex 29187e0177b..f2cacb6d8f1 100644--- a/hermes_cli/kanban_db_connect.py+++ b/hermes_cli/kanban_db_connect.py@@ -44,20 +44,16 @@ _SQLITE_HEADER = b"SQLite format 3\x00"DEFAULT_BUSY_TIMEOUT_MS = 120_000-# Maximum number of ``<db>.corrupt.<hash>.bak`` quarantine files retained per-# board DB. Content-addressing already dedupes identical corrupt bytes, but-# repeatedly-mutating corruption (partial repairs, further damage between-# dispatcher retries) mints a new fingerprint each time; without a cap a user-# accumulated 124 backups. Oldest-by-mtime files beyond the cap are pruned-# right after each new backup is created.+# Cap on ``<db>.corrupt.<hash>.bak`` quarantines per board: content-addressing+# dedupes identical bytes, but mutating corruption mints a new fingerprint each+# time (one user hit 124). Oldest-by-mtime beyond the cap are pruned after each+# new backup._CORRUPT_BACKUP_RETENTION = 10-# Bounded acquire for the cross-process init lock (#36644). The original bare-# blocking flock had no timeout, so a wedged holder blocked the dispatcher's-# next-tick connect forever. We retry a non-blocking acquire up to this-# deadline, polling at this interval, then proceed without the cross-process-# lock (the in-process _INIT_LOCK + idempotent init remain the backstop).+# Bounded init-lock acquire: a bare blocking flock let a wedged holder block the+# dispatcher's next-tick connect forever. Poll non-blocking until the deadline,+# then proceed without the lock (in-process _INIT_LOCK + idempotent init backstop)._INIT_LOCK_TIMEOUT_SECONDS = 10.0@@ -65,24 +61,17 @@ _INIT_LOCK_POLL_SECONDS = 0.05def _resolve_busy_timeout_ms() -> int:- """Return the SQLite busy timeout for Kanban connections.-- Kanban is the shared cross-profile dispatch bus, so worker stampedes are- expected. A long busy timeout lets SQLite serialize writers via WAL rather- than surfacing transient ``database is locked`` failures during bursts.- """+ """Return the SQLite busy timeout for Kanban connections. Kanban is the+ shared cross-profile dispatch bus, so worker stampedes are expected; a+ long timeout lets WAL serialize writers instead of surfacing transient+ ``database is locked`` failures."""return _kb._env_int("HERMES_KANBAN_BUSY_TIMEOUT_MS", DEFAULT_BUSY_TIMEOUT_MS, minimum=1)def _sqlite_connect(path: Path) -> sqlite3.Connection:- """Open a Kanban SQLite connection with consistent lock waiting.-- Uses ``connect_tracked`` so the live-connection registry knows this file- is open: while it is, byte-level probes of the same file are refused,- because an ``open()``/``close()`` would cancel this process's POSIX- advisory locks on the database (see ``hermes_cli.sqlite_safe_read``).- The registration is released automatically when the connection closes.- """+ """Open a Kanban SQLite connection via ``connect_tracked``: while registered,+ byte-level probes of the file are refused because an ``open()``/``close()``+ would cancel this process's POSIX advisory locks (see ``sqlite_safe_read``)."""from hermes_cli.sqlite_safe_read import connect_trackedbusy_timeout_ms = _resolve_busy_timeout_ms()@@ -93,15 +82,13 @@ def _sqlite_connect(path: Path) -> sqlite3.Connection:timeout=busy_timeout_ms / 1000.0,)try:- # ``sqlite3.connect(timeout=...)`` normally maps to busy_timeout, but set- # the PRAGMA explicitly so it is observable and survives future wrapper- # changes. Parameter binding is not supported for PRAGMA assignments.+ # Explicit PRAGMA (besides connect(timeout=)) so it is observable and+ # survives wrapper changes; PRAGMA assignments can't bind parameters.conn.execute(f"PRAGMA busy_timeout={busy_timeout_ms}")except BaseException:- # A half-open connection abandoned here would leak its fd AND leave a- # stale entry in the connect_tracked live-connection registry (which- # only clears on close), permanently blocking byte-level probes of- # this database file. Close before re-raising.+ # A half-open connection would leak its fd AND leave a stale entry in the+ # connect_tracked registry (cleared only on close), permanently blocking+ # byte-level probes of this file.with contextlib.suppress(Exception):conn.close()raise@@ -110,9 +97,7 @@ def _sqlite_connect(path: Path) -> sqlite3.Connection:def _try_lock_nb(handle) -> bool:"""One non-blocking exclusive lock attempt on ``handle``; False when held elsewhere.-- Windows uses a 1-byte ``msvcrt.locking`` range at offset 0, POSIX ``flock``.- """+ Windows: 1-byte ``msvcrt.locking`` range at offset 0; POSIX: ``flock``."""if _kb._IS_WINDOWS:import msvcrt@@ -145,20 +130,15 @@ def _unlock(handle) -> None:def _cross_process_init_lock(path: Path):"""Serialize first-connect WAL/schema/integrity setup across processes.- ``_INIT_LOCK`` only protects threads inside one Python process. During a- dispatcher burst, many worker processes can all hit a fresh/legacy board at- once and each process has an empty ``_INITIALIZED_PATHS`` cache. This file- lock keeps header validation, integrity probing, WAL activation, and- additive migrations single-file/single-writer across the whole host while- leaving normal post-init DB usage concurrent under SQLite WAL.-- The acquire is **bounded**: a blocking ``flock`` let one stalled holder (or- a stale lock from a wedged worker) hang every other ``connect()`` — the- gateway dispatcher's next tick included — with no traceback. We retry a- non-blocking acquire until a deadline, then WARN and proceed WITHOUT the- lock. Safe because ``_INIT_LOCK`` still serializes same-process threads- and init is idempotent (``CREATE TABLE IF NOT EXISTS`` + additive- migrations): two racing first-inits mean redundant work, not corruption.+ ``_INIT_LOCK`` only covers one process's threads; a dispatcher burst has+ many worker processes hit a fresh/legacy board with empty+ ``_INITIALIZED_PATHS`` caches. Post-init usage stays concurrent under WAL.++ **Bounded** acquire: a blocking ``flock`` let one stalled/stale holder hang+ every ``connect()`` (the gateway dispatcher's next tick included) with no+ traceback. After the deadline we WARN and proceed WITHOUT the lock — safe+ because ``_INIT_LOCK`` still serializes same-process threads and init is+ idempotent: two racing first-inits mean redundant work, not corruption."""path.parent.mkdir(parents=True, exist_ok=True)lock_path = path.with_name(path.name + ".init.lock")@@ -193,29 +173,21 @@ def _cross_process_init_lock(path: Path):@contextlib.contextmanagerdef _dispatch_tick_lock(db_path: Path):- """Non-blocking single-writer guard around one dispatcher tick.-- Yields ``True`` when this process holds the board's dispatch lock and- may proceed with the tick, or ``False`` when another process already- holds it (the caller should skip the tick this round).-- An orphan gateway (``gateway run --replace`` / restart on a systemd or- launchd host escaping the service cgroup) becomes a second long-lived- writer on the same ``kanban.db``; two dispatchers both pass SQLite- ``busy_timeout`` and race on WAL frames — the root cause of multi-writer- corruption. ``_guard_supervised_gateway_conflict`` blocks the common way- an orphan is born; this lock is the defense-in-depth regardless of how- the second dispatcher got there.-- **Non-blocking** on purpose: the gateway's async watcher must never stall- on a held lock. A loser skips its tick (the winner is making progress on- the same board) and tries again next interval.-- Board-scoped: the lock file is a ``.dispatch.lock`` sibling of the- board's ``kanban.db``, so unrelated boards tick independently. On- platforms without ``fcntl``/``msvcrt`` the guard degrades to a no-op- (yields ``True``) — single-writer enforcement is best-effort and the- orphan-dispatcher scenario is specific to POSIX service managers.+ """Non-blocking single-writer guard around one dispatcher tick; yields+ ``True`` if this process holds the board's dispatch lock, else ``False``+ (caller skips the tick).++ An orphan gateway (``gateway run --replace`` / restart escaping a systemd+ or launchd service cgroup) becomes a second long-lived writer; two+ dispatchers both pass ``busy_timeout`` and race on WAL frames — the root+ cause of multi-writer corruption. ``_guard_supervised_gateway_conflict``+ blocks the common birth of an orphan; this lock is defense-in-depth.++ **Non-blocking** on purpose: the gateway's async watcher must never stall;+ a loser retries next interval while the winner makes progress. Board-scoped+ via a ``.dispatch.lock`` sibling of ``kanban.db``. Without+ ``fcntl``/``msvcrt`` it degrades to a no-op (yields ``True``) — the orphan+ scenario is specific to POSIX service managers."""lock_path = db_path.with_name(db_path.name + ".dispatch.lock")handle = None@@ -228,8 +200,8 @@ def _dispatch_tick_lock(db_path: Path):except (OSError, AttributeError):acquired = Falseexcept OSError:- # Could not even open the lock file (permissions, read-only FS).- # Degrade to a no-op so a probe failure never blocks dispatch.+ # Can't even open the lock file (permissions, read-only FS): degrade to+ # a no-op so a probe failure never blocks dispatch.acquired = Truehandle = Nonetry:@@ -245,24 +217,15 @@ def _dispatch_tick_lock(db_path: Path):handle.close()-# Periodic WAL checkpoint state for the dispatcher tick path. The kanban-# connections run with ``wal_autocheckpoint=100``, but a passive-# autocheckpoint can be starved on a busy multi-process board (any reader-# with an open snapshot blocks the WAL reset), letting the -wal file grow-# between gateway restarts. Once per coarse interval the dispatcher issues-# an explicit ``wal_checkpoint(PASSIVE)``.-#-# PASSIVE, not TRUNCATE (same class fix as the state.db checkpoints,-# #45383/#80255/#44795): the dispatch flock only makes the dispatcher the-# sole *dispatcher* — CLI kanban commands in other processes write to the-# same board without taking that flock, so a TRUNCATE here races live-# writers exactly like the state.db close() path did. PASSIVE never takes-# the exclusive checkpoint lock; the WAL file size is instead bounded by-# ``journal_size_limit`` (set at connection init) which truncates the file-# on the writer's natural post-checkpoint reset.-# Best-effort: a busy/locked checkpoint is logged at DEBUG and retried next-# interval. Keyed per resolved DB path so multi-board dispatchers checkpoint-# each board on its own clock.+# Periodic explicit WAL checkpoint from the dispatcher tick: a passive+# autocheckpoint can be starved on a busy multi-process board (any open reader+# snapshot blocks the WAL reset), letting -wal grow between gateway restarts.+# PASSIVE, not TRUNCATE (same fix class as state.db): the dispatch flock only+# makes this the sole *dispatcher* — CLI kanban commands in other processes+# write to the same board without it, so a TRUNCATE would race live writers.+# PASSIVE never takes the exclusive checkpoint lock; WAL size is bounded by+# ``journal_size_limit`` (set at connection init) on the writer's natural+# post-checkpoint reset. Best-effort, keyed per resolved DB path._WAL_CHECKPOINT_INTERVAL_SECONDS = 300.0@@ -273,13 +236,9 @@ _WAL_CHECKPOINT_LOCK = threading.Lock()def _maybe_checkpoint_wal(conn: sqlite3.Connection, db_path: Path) -> None:- """Run ``PRAGMA wal_checkpoint(PASSIVE)`` at a coarse interval.-- Called from the dispatcher tick while the board's dispatch lock is- held. No-ops (cheaply) until ``_WAL_CHECKPOINT_INTERVAL_SECONDS`` has- elapsed since this process last checkpointed this board. Never raises:- the checkpoint is pure hygiene and must not fail a dispatch tick.- """+ """``PRAGMA wal_checkpoint(PASSIVE)`` at most once per interval per board,+ from the dispatcher tick under the dispatch lock. Never raises: pure+ hygiene, must not fail a tick."""try:key = str(db_path.resolve())except OSError:@@ -289,8 +248,8 @@ def _maybe_checkpoint_wal(conn: sqlite3.Connection, db_path: Path) -> None:last = _kb._LAST_WAL_CHECKPOINT.get(key)if last is not None and (now - last) < _WAL_CHECKPOINT_INTERVAL_SECONDS:return- # Claim the slot before doing the work so concurrent ticks (other- # threads in this process) don't double-checkpoint on the boundary.+ # Claim the slot first so concurrent same-process ticks don't+ # double-checkpoint on the boundary._kb._LAST_WAL_CHECKPOINT[key] = nowtry:row = conn.execute("PRAGMA wal_checkpoint(PASSIVE)").fetchone()@@ -321,13 +280,10 @@ def _looks_like_tls_record_at(data: bytes, offset: int) -> bool:def _validate_sqlite_header(path: Path) -> None:"""Fail early with an actionable error for non-SQLite Kanban DB files.-- ``sqlite3.connect()`` creates missing and zero-byte files, so those are- allowed. Existing non-empty files must have the SQLite header before we- hand them to SQLite/WAL setup. This keeps corrupted page-0 failures from- being collapsed into a generic PRAGMA error and lets the gateway's corrupt- board handling identify the board by fingerprint.- """+ ``sqlite3.connect()`` creates missing and zero-byte files, so those pass;+ non-empty files must carry the SQLite header, so a corrupt page 0 isn't+ collapsed into a generic PRAGMA error and the gateway's corrupt-board+ handling can identify the board by fingerprint."""try:stat = path.stat()except FileNotFoundError:@@ -336,10 +292,9 @@ def _validate_sqlite_header(path: Path) -> None:returnif stat.st_size == 0:return- # Byte-level probe, so it must run BEFORE any connection to this path- # exists (connect() calls it under the init lock, ahead of _sqlite_connect).- # read_header_bytes_preopen refuses once a connection is live, because the- # close() would cancel this process's POSIX locks on the file.+ # Byte-level probe: must run BEFORE any connection to this path exists+ # (read_header_bytes_preopen refuses once one is live, because the close()+ # would cancel this process's POSIX locks).from hermes_cli.sqlite_safe_read import read_header_bytes_preopenhead = read_header_bytes_preopen(path, length=64)@@ -359,12 +314,9 @@ def _validate_sqlite_header(path: Path) -> None:class KanbanDbCorruptError(RuntimeError):- """Raised when an existing kanban DB file fails integrity checks.-- Fail-closed guard against silent recreation of a corrupt board file,- which would otherwise destroy the user's tasks. Carries both the- original path and the timestamped backup we made before refusing.- """+ """Raised when an existing kanban DB file fails integrity checks — a+ fail-closed guard against silently recreating a corrupt board (which would+ destroy the user's tasks). Carries the path and the backup made first."""def __init__(self, db_path: Path, backup_path: Optional[Path], reason: str):self.db_path = db_path@@ -380,19 +332,12 @@ class KanbanDbCorruptError(RuntimeError):def _prune_corrupt_backups(parent: Path, base_name: str, keep: Optional[Path] = None,) -> None:- """Cap the number of retained ``<db>.corrupt.<hash>.bak`` files.-- Content-addressed backups dedupe identical corrupt bytes, but a board- whose file keeps changing between corruption events (partial repairs,- ongoing damage, fleets of retrying dispatchers) can still accumulate- backups without bound — a user reported 124 of them. After creating a- new backup we keep only the ``_CORRUPT_BACKUP_RETENTION`` most recent- (by mtime) and delete the rest, including their copied ``-wal``/``-shm``- sidecars. ``keep`` (the just-created backup) is never pruned regardless- of its mtime — ``shutil.copy2`` preserves the source file's timestamp,- which may be older than existing backups. Best-effort: prune failures- never mask the corruption error the caller is about to raise.- """+ """Keep only the ``_CORRUPT_BACKUP_RETENTION`` newest (by mtime)+ ``<db>.corrupt.<hash>.bak`` files plus their ``-wal``/``-shm`` copies.+ ``keep`` (the just-created backup) is never pruned regardless of mtime —+ ``shutil.copy2`` preserves the source timestamp, which may be older than+ existing backups. Best-effort: prune failures never mask the corruption+ error the caller is about to raise."""try:backups = [candidate@@ -424,37 +369,22 @@ def _prune_corrupt_backups(def _backup_corrupt_db(path: Path) -> Optional[Path]:- """Copy a corrupt DB (and its WAL/SHM sidecars) to a content-addressed backup.-- The backup filename is deterministic in the main DB's sha256, so repeated- quarantines of the same corrupt bytes (gateway restarts, dispatcher retries,- multi-profile fleets all hitting the same shared DB) reuse one backup- instead of amplifying disk usage by N. If the corrupt bytes actually- change between attempts — e.g. a partial repair or further damage — the- fingerprint changes and a separate backup is preserved.-- Returns the backup path of the main DB file, or ``None`` if the copy- itself failed (the caller still raises loudly in that case).-- Writes are confined to the original DB's parent directory. The backup- basename is derived purely from ``path.name`` and a content hash, never- from caller-supplied directory segments — no traversal is possible.- """- # Resolve once and pin the parent so subsequent path operations cannot- # escape it. ``Path.resolve()`` collapses any ``..`` segments and- # symlinks, and we only ever write inside ``parent``.+ """Copy a corrupt DB (and WAL/SHM sidecars) to a content-addressed backup.+ The name is deterministic in the main DB's sha256, so repeated quarantines+ of the same bytes reuse one backup while changed bytes get a separate one.+ Returns the main backup path, or ``None`` if the copy failed (the caller+ still raises loudly). Writes are confined to the DB's parent directory:+ the basename derives only from ``path.name`` + content hash."""+ # Pin the resolved parent (``resolve()`` collapses ``..`` and symlinks); we+ # only ever write inside it.resolved = path.resolve()parent = resolved.parentbase_name = resolved.name # basename only- # This reads the whole DB file to fingerprint it. That is a close()-on-a-- # database-file hazard (it cancels this process's POSIX advisory locks --- # see hermes_cli.sqlite_safe_read), so it must only run once the board has- # been taken out of service. Every caller reaches here on the corrupt/- # quarantine path after closing its probe connection, but another- # SessionDB/kanban connection elsewhere in the process would still be at- # risk -- so REFUSE rather than warn-and-proceed. Losing a forensic copy- # is strictly better than corrupting the live database we are trying to- # rescue.+ # Fingerprinting reads the whole file — a close()-on-a-database-file hazard+ # (cancels this process's POSIX advisory locks; see sqlite_safe_read), so it+ # must only run once the board is out of service. Another SessionDB/kanban+ # connection in this process would still be at risk — so REFUSE rather than+ # warn-and-proceed: losing a forensic copy beats corrupting the live DB.from hermes_cli.sqlite_safe_read import has_live_connectionif has_live_connection(resolved):@@ -482,8 +412,8 @@ def _backup_corrupt_db(path: Path) -> Optional[Path]:shutil.copy2(resolved, candidate)except OSError:return None- # A NEW backup landed on disk — enforce the retention cap so- # mutating-corruption loops can't accumulate quarantines forever.+ # A NEW backup landed — enforce the retention cap so mutating-corruption+ # loops can't accumulate quarantines forever._prune_corrupt_backups(parent, base_name, keep=candidate)for suffix in ("-wal", "-shm"):sidecar = parent / (base_name + suffix)@@ -497,13 +427,10 @@ def _backup_corrupt_db(path: Path) -> Optional[Path]:return candidate-# Repairable integrity_check error classes. Both shapes are *index-scoped*:-# the table b-tree is intact and only a secondary index disagrees with it,-# which REINDEX rebuilds losslessly from the table data. The index name is-# parsed generically from the message — no hardcoded index list. Any other-# integrity_check message (page corruption, "database disk image is-# malformed", freelist damage, …) is NOT repairable this way and keeps the-# fail-closed behavior.+# Repairable integrity_check error classes — both *index-scoped*: the table+# b-tree is intact and REINDEX rebuilds the index losslessly. The index name is+# parsed generically (no hardcoded list). Anything else (page corruption,+# "malformed", freelist damage, …) keeps the fail-closed behavior._REPAIRABLE_INDEX_ERROR_PATTERNS = (re.compile(r"^wrong # of entries in index (?P<index>.+)$"),re.compile(r"^row \d+ missing from index (?P<index>.+)$"),@@ -522,12 +449,9 @@ def _run_integrity_check(conn: sqlite3.Connection) -> list[str]:def _probe_integrity(path: Path) -> list[str]:- """Open ``path`` read/write and return its ``integrity_check`` messages.-- Opening read/write lets SQLite recover or checkpoint a healthy WAL /- hot-journal DB before we judge it. ``sqlite3.OperationalError`` (locked,- busy, transient IO) propagates raw — it is not corruption.- """+ """Open ``path`` read/write (so SQLite can recover/checkpoint a healthy WAL+ / hot-journal DB before we judge it) and return ``integrity_check``+ messages. ``OperationalError`` (locked/busy) propagates raw — not corruption."""probe = _sqlite_connect(path)try:return _run_integrity_check(probe)@@ -536,13 +460,9 @@ def _probe_integrity(path: Path) -> list[str]:def _repairable_index_names(messages: list[str]) -> Optional[list[str]]:- """Return the distinct index names iff EVERY message is index-repairable.-- ``None`` when any line falls outside the repairable index-class errors- (or when there are no messages at all) — the caller must then fail- closed exactly as before. Order of first appearance is preserved so the- REINDEX pass is deterministic.- """+ """Distinct index names iff EVERY message is index-repairable, else ``None``+ (caller fails closed; also ``None`` for no messages). First-appearance+ order is preserved so the REINDEX pass is deterministic."""names: list[str] = []saw_any = Falsefor raw in messages:@@ -567,15 +487,10 @@ def _repairable_index_names(messages: list[str]) -> Optional[list[str]]:def _attempt_index_reindex_repair(path: Path, index_names: list[str],) -> tuple[bool, list[str]]:- """REINDEX the named indexes, then re-run ``PRAGMA integrity_check``.-- Tries a per-index ``REINDEX "<name>"`` first (cheapest, most targeted);- if any per-index statement fails — e.g. the parsed name does not resolve- because integrity_check reported an internal/auto index — falls back to- a bare ``REINDEX`` of the whole database. Returns- ``(clean, post_repair_messages)``; never raises. Callers must hold the- board's cross-process init flock so no other process connects mid-repair.- """+ """REINDEX the named indexes (per-index first; bare ``REINDEX`` fallback if+ a parsed name is an internal/auto index), then re-run integrity_check.+ Returns ``(clean, post_repair_messages)``; never raises. Callers must hold+ the board's cross-process init flock so nothing connects mid-repair."""try:conn = _sqlite_connect(path)except sqlite3.Error as exc:@@ -586,8 +501,7 @@ def _attempt_index_reindex_repair(escaped = name.replace('"', '""')conn.execute(f'REINDEX "{escaped}"')except sqlite3.Error:- # Per-index rebuild failed (unresolvable parsed name, auto- # index, …) — bare REINDEX rebuilds every index in the DB.+ # Per-index rebuild failed — bare REINDEX rebuilds every index.conn.execute("REINDEX")messages = _run_integrity_check(conn)except sqlite3.Error as exc:@@ -600,24 +514,16 @@ def _attempt_index_reindex_repair(def _guard_existing_db_is_healthy(path: Path) -> None:"""Run ``PRAGMA integrity_check`` on an existing non-empty DB file.- The probe opens read/write so SQLite can recover/checkpoint a healthy- WAL/hot-journal DB before we declare it corrupt. Narrow auto-repair: when- the failure is ONLY index-scoped (``wrong # of entries in index`` / ``row- N missing from index``) the table b-trees are intact and REINDEX rebuilds- losslessly — take the content-addressed corrupt backup FIRST, REINDEX- under the caller-held init flock, re-check, proceed only if clean. Any- other failure (page corruption, ``malformed``, unclean re-check) fails- closed: copy the file + WAL/SHM sidecars to a backup and raise- :class:`KanbanDbCorruptError` so callers never recreate the schema on top- of a damaged DB. ``sqlite3.OperationalError`` (lock/busy) is NOT- corruption and propagates raw (no spurious ``.corrupt`` backup). No-op for- missing / zero-byte (fresh) files and paths already proven healthy this- process. ``path`` comes from user-controlled-but-trusted sources; it is- resolved here and all writes are confined to its parent so stray ``..``- segments collapse before any I/O.+ Narrow auto-repair when the failure is ONLY index-scoped (table b-trees+ intact): content-addressed corrupt backup FIRST, REINDEX under the+ caller-held init flock, re-check, proceed only if clean. Anything else+ (page corruption, ``malformed``, unclean re-check) fails closed: back up+ the file + sidecars and raise :class:`KanbanDbCorruptError` so callers+ never recreate the schema on top of a damaged DB. ``OperationalError``+ (lock/busy) is NOT corruption and propagates raw (no spurious backup).+ No-op for missing / zero-byte files and paths already proven healthy this+ process. All writes are confined to the resolved path's parent."""- # Resolve before any I/O. ``Path.resolve()`` normalizes ``..`` and- # symlinks, giving us a canonical path whose parent dir we can pin.try:resolved = path.resolve()except OSError:@@ -639,14 +545,14 @@ def _guard_existing_db_is_healthy(path: Path) -> None:f"{messages[0] if messages else '<no row>'!r}")except sqlite3.OperationalError:- # Lock contention, busy, transient IO — not corruption. Let it propagate.+ # Lock contention / busy — not corruption. Propagate.raiseexcept sqlite3.DatabaseError as exc:reason = f"sqlite refused to open file: {exc}"if reason is None:return- # Quarantine FIRST — both the repair path and the fail-closed path- # preserve the pre-touch bytes before anything mutates the file.+ # Quarantine FIRST — both the repair and fail-closed paths preserve the+ # pre-touch bytes before anything mutates the file.backup = _backup_corrupt_db(resolved)index_names = _repairable_index_names(messages)if index_names:@@ -674,18 +580,10 @@ def _guard_existing_db_is_healthy(path: Path) -> None:@dataclassclass RepairResult:- """Outcome of :func:`repair_db` for CLI/status reporting.-- ``status`` is one of:-- * ``"ok"`` — integrity_check was already clean; nothing done.- * ``"repaired"`` — index-only errors found, REINDEX applied, re-check- clean. ``backup_path`` holds the pre-repair quarantine copy.- * ``"corrupt"`` — still corrupt: either a non-index error class- (fail-closed, no repair attempted) or a REINDEX whose re-check did- not come back clean.- * ``"missing"`` — no DB file (or zero-byte placeholder); nothing to do.- """+ """Outcome of :func:`repair_db`. ``status``: ``"ok"`` (already clean),+ ``"repaired"`` (index-only errors, REINDEX applied, re-check clean;+ ``backup_path`` is the pre-repair copy), ``"corrupt"`` (non-index error+ class, or re-check still dirty), ``"missing"`` (no / zero-byte file)."""status: strdb_path: Path@@ -701,21 +599,12 @@ def repair_db(board: Optional[str] = None,) -> RepairResult:"""Probe a kanban DB and apply the narrow index-REINDEX repair if needed.-- Shares the exact policy of :func:`_guard_existing_db_is_healthy`: only- integrity failures composed *entirely* of index-scoped errors are- repairable; the corrupt bytes are quarantined via- :func:`_backup_corrupt_db` BEFORE any mutation; the REINDEX runs under- the board's cross-process init flock; and anything else stays corrupt- (fail-closed) for the caller to surface. Unlike the guard this never- raises :class:`KanbanDbCorruptError` — it returns a structured- :class:`RepairResult` so ``hermes kanban repair`` can report and choose- its own exit code.-- Transient ``sqlite3.OperationalError`` (locked/busy) still propagates- raw, exactly like the guard: a locked healthy DB is not corruption and- must not be quarantined.- """+ Same policy as :func:`_guard_existing_db_is_healthy` (quarantine BEFORE+ any mutation; REINDEX under the init flock; anything non-index stays+ corrupt), but returns a :class:`RepairResult` instead of raising so+ ``hermes kanban repair`` can pick its exit code. ``OperationalError``+ (locked/busy) still propagates raw: a locked healthy DB must not be+ quarantined."""path = db_path if db_path is not None else _kb.kanban_db_path(board=board)try:resolved = path.resolve()@@ -735,8 +624,8 @@ def repair_db(# Locked/busy — not corruption; let the caller report it raw.raiseexcept sqlite3.DatabaseError as exc:- # Same quarantine the connect-time guard takes for a file- # sqlite refuses to open at all (e.g. malformed page 1).+ # Same quarantine the connect-time guard takes when sqlite+ # refuses to open the file at all.return RepairResult(status="corrupt",db_path=resolved,@@ -772,20 +661,16 @@ def repair_db(def _schema_is_present(conn: sqlite3.Connection) -> bool:- """Whether an open connection actually sees the kanban schema.-- ``tasks`` is the sentinel: :data:`SCHEMA_SQL` always creates it, and- SQLite loses tables all-or-nothing (a file is either the one we- initialized or a fresh one created by this very open), so one- ``sqlite_master`` lookup on the already-resident page 1 is enough. Cheap- by design — it runs on every steady-state :func:`connect`.- """+ """Whether an open connection actually sees the kanban schema. ``tasks`` is+ the sentinel (SCHEMA_SQL always creates it; SQLite loses tables+ all-or-nothing), so one ``sqlite_master`` lookup on the resident page 1+ suffices — cheap by design, it runs on every steady-state connect()."""try:row = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='tasks' LIMIT 1").fetchone()except sqlite3.DatabaseError:- # Unreadable schema table is not this guard's call — let the full init+ # Unreadable schema table is not this guard's call — the full init# path's header/integrity probes classify and quarantine it.return Falsereturn row is not None@@ -793,33 +678,28 @@ def _schema_is_present(conn: sqlite3.Connection) -> bool:def _open_configured(path: Path, under_lock) -> tuple[sqlite3.Connection, Any]:"""Open ``path`` with the kanban PRAGMA set, then run ``under_lock(conn)``.-- WAL activation and ``under_lock`` share the process-local ``_INIT_LOCK``- critical section: WAL setup can take an exclusive lock while SQLite- creates sidecar files for a fresh DB, and concurrent gateway startup- threads must not race before ``_INITIALIZED_PATHS`` is populated. The- connection is closed if anything raises.- """+ WAL activation and ``under_lock`` share the ``_INIT_LOCK`` critical section:+ WAL setup can take an exclusive lock while SQLite creates sidecars for a+ fresh DB, and concurrent gateway startup threads must not race before+ ``_INITIALIZED_PATHS`` is populated. Closed if anything raises."""conn = _sqlite_connect(path)try:conn.row_factory = sqlite3.Rowwith _INIT_LOCK:- # WAL doesn't work on network filesystems (NFS/SMB/FUSE); the shared- # helper falls back to DELETE with one ERROR log (see- # hermes_state._WAL_INCOMPAT_MARKERS).+ # WAL doesn't work on network filesystems; the helper falls back to+ # DELETE with one ERROR log (see hermes_state._WAL_INCOMPAT_MARKERS).from hermes_state import apply_wal_with_fallbackapply_wal_with_fallback(conn, db_label=f"kanban.db ({path.name})")- # FULL (was NORMAL): fsync before each checkpoint to narrow the+ # FULL (not NORMAL): fsync before each checkpoint to narrow the# crash window that can leave a b-tree page header torn.conn.execute("PRAGMA synchronous=FULL")conn.execute("PRAGMA wal_autocheckpoint=100")# Bound the WAL file: the periodic explicit checkpoint is PASSIVE- # (never truncates), so SQLite trims the -wal file to this limit on- # the writer's natural post-checkpoint reset. 8 MiB is generous.+ # (never truncates), so SQLite trims -wal to this limit on the+ # writer's natural post-checkpoint reset.conn.execute("PRAGMA journal_size_limit=8388608")conn.execute("PRAGMA foreign_keys=ON")- # Zero freed pages so a later torn write cannot expose stale cell- # content; persisted in the DB header for new DBs.+ # Zero freed pages so a later torn write can't expose stale cells.conn.execute("PRAGMA secure_delete=ON")# Surface corrupt cells as read errors instead of silent wrong data.conn.execute("PRAGMA cell_size_check=ON")@@ -835,40 +715,29 @@ def connect(*,board: Optional[str] = None,) -> sqlite3.Connection:- """Open (and initialize if needed) the kanban DB.-- WAL is (re)enabled on every connection so a re-created file stays robust.- The first connection per path auto-runs :func:`init_db` (fresh installs- and tests need no separate init step); later ones skip the schema check- via ``_INITIALIZED_PATHS``. Path: explicit ``db_path`` as-is, else- ``board``, else :func:`kanban_db_path` (``HERMES_KANBAN_DB`` ->- ``HERMES_KANBAN_BOARD`` -> ``<root>/kanban/current`` -> ``default``).- """+ """Open (and initialize if needed) the kanban DB. WAL is (re)enabled on+ every connection so a re-created file stays robust; the first connection+ per path auto-runs :func:`init_db`, later ones skip via+ ``_INITIALIZED_PATHS``. Path: explicit ``db_path``, else ``board``, else+ :func:`kanban_db_path` (``HERMES_KANBAN_DB`` -> ``HERMES_KANBAN_BOARD`` ->+ ``<root>/kanban/current`` -> ``default``)."""path = db_path if db_path is not None else _kb.kanban_db_path(board=board)path.parent.mkdir(parents=True, exist_ok=True)- # Fast path: once THIS process has initialized this path, the expensive- # first-open work (header validation, integrity probe, schema + additive- # migrations) is already done and cached in _INITIALIZED_PATHS. Acquiring- # the cross-process init lock on every connect is what let a single stalled+ # Fast path: once THIS process has initialized this path, skip the+ # cross-process init lock. Taking it on every connect let a single stalled# holder (e.g. an external `hermes kanban list` mid-integrity-probe) block- # the long-lived gateway dispatcher's next-tick connect() forever — an- # unbounded flock with no timeout, no LOCK_NB, no recovery (#36644). On the- # steady-state path there is nothing for the cross-process lock to protect- # (no schema/migration writes run), so skip it entirely and just open the- # connection with WAL/pragmas under the cheap in-process _INIT_LOCK.+ # the gateway dispatcher's next-tick connect() forever, and steady-state has+ # nothing for it to protect (no schema/migration writes).resolved = str(path.resolve())if resolved in _INITIALIZED_PATHS:conn, schema_present = _open_configured(path, _schema_is_present)if schema_present:return conn- # The cache says "initialized", the file says otherwise: it was deleted- # or replaced under a live process, and the open above silently- # recreated an empty DB. Left alone, every query on this path fails- # with "no such table: tasks" for the rest of the process's life and- # the board just renders empty (#83445). Drop the stale cache entry and- # fall through to the full init path, which re-runs the header and- # integrity probes and the schema script under the cross-process lock.+ # Cache says "initialized", file says otherwise: it was deleted or+ # replaced under a live process and the open silently recreated an empty+ # DB. Left alone, every query fails with "no such table: tasks" for the+ # rest of the process's life. Drop the stale entry and re-init.conn.close()with _INIT_LOCK:_INITIALIZED_PATHS.discard(resolved)@@ -879,26 +748,19 @@ def connect()with _kb._cross_process_init_lock(path):- # Read-only file/sidecar preflight (port of kilocode#12508) —- # repair-or-refuse before the header/integrity probes so a stray- # read-only kanban.db fails with an actionable message instead of- # "attempt to write a readonly database" mid-init.+ # Read-only file/sidecar preflight first, so a stray read-only kanban.db+ # fails actionably instead of "attempt to write a readonly database".from hermes_state import preflight_db_writabilitypreflight_db_writability(path, db_label=f"kanban.db ({path.name})")- # Cheap byte-level check first — catches the #29507 TLS-overwrite shape- # and other invalid-header cases without opening a sqlite connection.+ # Cheap byte-level header check before any sqlite connection, then the+ # full integrity probe (cached per path via _INITIALIZED_PATHS)._validate_sqlite_header(path)- # Full integrity probe — catches corruption past the header (malformed- # pages, broken internal metadata). Cached per-path after first success- # via _INITIALIZED_PATHS so it only runs once per process per path._guard_existing_db_is_healthy(path)resolved = str(path.resolve())def _init_if_needed(conn: sqlite3.Connection) -> None:- # Idempotent: CREATE TABLE IF NOT EXISTS + the additive migrations,- # cached so later connect() calls in this process are cheap. Runs- # under _INIT_LOCK so same-process dispatcher threads can't race- # through the ALTER TABLE pass with stale PRAGMA snapshots.+ # Idempotent; runs under _INIT_LOCK so same-process dispatcher+ # threads can't race the ALTER TABLE pass with stale PRAGMA snapshots.if resolved not in _INITIALIZED_PATHS:conn.executescript(_kb.SCHEMA_SQL)_migrate_add_optional_columns(conn)@@ -914,15 +776,10 @@ def connect_closing(*,board: Optional[str] = None,):- """Open a kanban DB connection and guarantee it is closed on exit.-- Use this instead of ``with kb.connect() as conn:`` — sqlite3's connection- context manager only commits/rolls back; it does NOT close the file- descriptor. Long-lived processes (gateway, dashboard) that route every- kanban operation through ``connect()`` otherwise leak FDs to ``kanban.db``- / ``kanban.db-wal`` until ``[Errno 24] Too many open files`` kills them.- ``connect()`` itself is unchanged for callers that manage the lifetime.- """+ """Open a kanban DB connection and guarantee it is closed on exit. Use+ instead of ``with kb.connect() as conn:`` — sqlite3's context manager only+ commits/rolls back, it does NOT close the fd, so long-lived processes+ (gateway, dashboard) leak FDs until ``[Errno 24] Too many open files``."""conn = _kb.connect(db_path=db_path, board=board)try:yield conn@@ -936,21 +793,14 @@ def init_db(*,board: Optional[str] = None,) -> Path:- """Create the schema if it doesn't exist; return the path used.-- Kept as a public entry point so CLI ``hermes kanban init`` and the- daemon have something explicit to call. Unlike :func:`connect`'s- first-time auto-init (which caches by path), ``init_db`` always- re-runs the migration pass. Callers that know the on-disk schema- may have drifted — tests that write legacy event kinds directly,- external tools that upgrade an old DB file — can call this to- force re-migration.- """+ """Create the schema if it doesn't exist; return the path used. Unlike+ :func:`connect`'s cached first-time auto-init, this always re-runs the+ migration pass — callers that know the on-disk schema may have drifted+ (tests writing legacy event kinds, external upgrades) use it to force it."""path = db_path if db_path is not None else _kb.kanban_db_path(board=board)path.parent.mkdir(parents=True, exist_ok=True)resolved = str(path.resolve())- # Clear the cache entry so the underlying connect() re-runs the- # schema + migration pass unconditionally.+ # Clear the cache entry so connect() re-runs schema + migrations.with _INIT_LOCK:_INITIALIZED_PATHS.discard(resolved)with contextlib.closing(_kb.connect(path)):@@ -958,8 +808,8 @@ def init_db(return path-# Additive ``tasks`` columns, in the order legacy DBs receive them (order is-# the physical column order for ``SELECT *`` on migrated boards).+# Additive ``tasks`` columns in the order legacy DBs receive them (= physical+# column order for ``SELECT *`` on migrated boards)._EARLY_TASK_COLUMNS = (("tenant", "tenant TEXT"),("result", "result TEXT"),@@ -984,9 +834,8 @@ _RENAMED_TASK_COLUMNS = ()-# NULL / 0 defaults on every column below reproduce the behaviour existing-# rows had before the column existed (worker-profile model/provider/reasoning,-# global failure limit, single-shot worker, untyped human block, ...).+# NULL / 0 defaults below reproduce the behaviour existing rows had before the+# column existed._LATER_TASK_COLUMNS = (("max_runtime_seconds", "max_runtime_seconds INTEGER"),("last_heartbeat_at", "last_heartbeat_at INTEGER"),@@ -1004,38 +853,29 @@ _LATER_TASK_COLUMNS = (# Ralph-style goal loop toggle; 0 = classic single-shot worker.("goal_mode", "goal_mode INTEGER NOT NULL DEFAULT 0"),("goal_max_turns", "goal_max_turns INTEGER"),- # Originating agent/chat session id (``HERMES_SESSION_ID``, e.g. ACP).("session_id", "session_id TEXT"),# Typed block reason (VALID_BLOCK_KINDS); NULL = generic human blocker.("block_kind", "block_kind TEXT"),- # Unblock-loop counter; existing rows start at 0.("block_recurrences", "block_recurrences INTEGER NOT NULL DEFAULT 0"),)def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:- """Add columns that were introduced after v1 release to legacy DBs.-- Called by ``init_db`` so opening an old DB is always safe.- """+ """Add columns introduced after v1 to legacy DBs (called via ``init_db``)."""cols = {row["name"] for row in conn.execute("PRAGMA table_info(tasks)")}for name, ddl in _EARLY_TASK_COLUMNS:if name not in cols:_add_column_if_missing(conn, "tasks", name, ddl)- # ``idx_tasks_idempotency`` is created unconditionally below alongside- # the other additive-column indexes.# Re-snapshot: DBs partially migrated by older releases may already carry- # later columns (e.g. ``consecutive_failures``) even when the first- # snapshot did not, so the legacy-column migration stays idempotent.+ # later columns (e.g. ``consecutive_failures``), keeping the legacy-column+ # migration idempotent.cols = {row["name"] for row in conn.execute("PRAGMA table_info(tasks)")}- # Legacy column migration: ``spawn_failures`` → ``consecutive_failures``- # and ``last_spawn_error`` → ``last_failure_error``. ADD-then-copy rather- # than ``RENAME COLUMN``: very old DBs may lack the legacy column entirely- # (RENAME raises "no such column"), and RENAME reparses the whole schema,- # failing if views/triggers reference the old name. Preserves historical- # counter values when the legacy columns do exist.+ # Legacy renames via ADD-then-copy rather than ``RENAME COLUMN``: very old+ # DBs may lack the legacy column entirely (RENAME raises "no such column"),+ # and RENAME reparses the whole schema, failing if views/triggers reference+ # the old name. Historical counter values are preserved when present.for name, ddl, legacy, copy_sql in _RENAMED_TASK_COLUMNS:if name not in cols:added = _add_column_if_missing(conn, "tasks", name, ddl)@@ -1048,13 +888,11 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:else:_add_column_if_missing(conn, "tasks", name, ddl)- # Indexes over additive ``tasks`` columns must be created after the- # columns exist. Keeping them in SCHEMA_SQL breaks legacy boards: SQLite- # parses each statement in ``executescript`` against the live schema, so a- # ``CREATE INDEX`` over a missing column aborts initialization before the- # additive ``ALTER TABLE`` migrations below can run. Re-running them here- # is cheap thanks to ``IF NOT EXISTS`` and stays correct on fresh DBs- # (where the columns already exist from SCHEMA_SQL).+ # Indexes over additive ``tasks`` columns must be created AFTER the columns+ # exist: ``executescript`` parses each statement against the live schema,+ # so a ``CREATE INDEX`` over a missing column in SCHEMA_SQL would abort+ # init on legacy boards before the ALTER TABLE pass runs. ``IF NOT EXISTS``+ # keeps re-running here cheap and correct on fresh DBs.conn.execute("CREATE INDEX IF NOT EXISTS idx_tasks_tenant ON tasks(tenant)")conn.execute("CREATE INDEX IF NOT EXISTS idx_tasks_idempotency ON tasks(idempotency_key)"@@ -1063,15 +901,13 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:"CREATE INDEX IF NOT EXISTS idx_tasks_session_id ON tasks(session_id)")- # task_events gained a run_id column; back-fill it as NULL for- # historical events (they predate runs and can't be attributed).+ # task_events.run_id back-fills as NULL for historical events (they predate+ # runs and can't be attributed).ev_cols = {row["name"] for row in conn.execute("PRAGMA table_info(task_events)")}if "run_id" not in ev_cols:_add_column_if_missing(conn, "task_events", "run_id", "run_id INTEGER")- # Same ordering rule as the additive ``tasks`` indexes above: create the- # index after the additive column migration so legacy ``task_events``- # tables don't fail during SCHEMA_SQL execution before ``run_id`` exists.+ # Same ordering rule as the ``tasks`` indexes above: index after column.conn.execute("CREATE INDEX IF NOT EXISTS idx_events_run ""ON task_events(run_id, id)"@@ -1090,7 +926,7 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:("chat_type", "chat_type TEXT"),# Platform-specific stable alt ID (Signal UUID, Feishu union_id, ...)# so an active-wake replay reconstructs the SAME ``build_session_key``- # (which prefers ``user_id_alt`` over ``user_id``). NULL is inert.+ # (which prefers ``user_id_alt``). NULL is inert.("user_id_alt", "user_id_alt TEXT"),("delivery_metadata", "delivery_metadata TEXT"),):@@ -1099,23 +935,21 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:_add_column_if_missing(conn, "kanban_notify_subs", name, ddl)if name == "delivery_mode":# Backfill ONLY on first-add: pre-column gateway subscriptions- # had de facto active wake (the notifier woke the originating- # session whenever the task carried a session_id); defaulting- # them to 'notify' would silently disable that on upgrade.- # TUI/CLI rows keep 'notify' (matches _maybe_auto_subscribe).- # A user's later explicit downgrade is never overwritten.+ # had de facto active wake; defaulting them to 'notify' would+ # silently disable that on upgrade. TUI/CLI rows keep 'notify'+ # (matches _maybe_auto_subscribe). A later explicit downgrade+ # is never overwritten.conn.execute("UPDATE kanban_notify_subs SET delivery_mode = 'notify+wake' ""WHERE platform != 'tui'")- # One-shot backfill: any task that is 'running' before runs existed- # had its claim_lock / claim_expires / worker_pid on the task row.- # Synthesize a matching task_runs row so subsequent end-run / heartbeat- # calls have something to write to. Wrapped in write_txn to serialize- # against any concurrent dispatcher, and the per-row UPDATE uses- # ``current_run_id IS NULL`` as a CAS guard so a racing claim can't- # produce an orphaned row if it interleaves with the backfill pass.+ # One-shot backfill: tasks 'running' before runs existed carried+ # claim_lock / claim_expires / worker_pid on the task row; synthesize a+ # matching task_runs row so end-run / heartbeat have something to write.+ # write_txn serializes against concurrent dispatchers, and the per-row+ # UPDATE uses ``current_run_id IS NULL`` as a CAS guard so a racing claim+ # can't produce an orphaned row.runs_exist = conn.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='task_runs'").fetchone() is not None@@ -1145,11 +979,10 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:started,),)- # CAS: only install the pointer if nothing else claimed- # the task between our SELECT and here (shouldn't happen- # under the write_txn, but belt-and-suspenders). If the- # CAS fails we've got an orphan run_row — mark it- # reclaimed so it doesn't look in-flight.+ # CAS: only install the pointer if nothing claimed the task+ # since our SELECT (belt-and-suspenders under write_txn). On+ # failure mark the orphan run row reclaimed so it doesn't+ # look in-flight.upd = conn.execute("UPDATE tasks SET current_run_id = ? ""WHERE id = ? AND current_run_id IS NULL",@@ -1163,10 +996,8 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:(int(time.time()), cur.lastrowid),)- # One-shot event-kind rename pass. The old names ("ready", "priority",- # "spawn_auto_blocked") still worked but were awkward on the wire;- # rename them in-place so existing DBs migrate cleanly. Fires once- # per DB because after the UPDATE no rows match the old kinds.+ # One-shot event-kind rename: old names still worked but were awkward on+ # the wire. Fires once per DB — after the UPDATE no rows match.for old, new in (("ready", "promoted"),("priority", "reprioritized"),@@ -1177,19 +1008,17 @@ def _migrate_add_optional_columns(conn: sqlite3.Connection) -> None:_rebuild_drifted_tables(conn)-# Legacy DBs defined these tables with a ``TEXT PRIMARY KEY`` id (or, for-# ``kanban_notify_subs``, a nullable ``TEXT last_event_id``). The current-# schema uses ``INTEGER PRIMARY KEY AUTOINCREMENT`` / ``INTEGER NOT NULL-# DEFAULT 0``. ``CREATE TABLE IF NOT EXISTS`` skips existing tables-# regardless of schema and ``_add_column_if_missing`` only adds columns, so-# neither can fix a drifted column type — the table must be rebuilt. See-# #35096.+# Legacy DBs defined these tables with a ``TEXT PRIMARY KEY`` id (or a nullable+# ``TEXT last_event_id`` for ``kanban_notify_subs``); the current schema uses+# ``INTEGER PRIMARY KEY AUTOINCREMENT`` / ``INTEGER NOT NULL DEFAULT 0``.+# ``CREATE TABLE IF NOT EXISTS`` skips existing tables and+# ``_add_column_if_missing`` only adds columns, so a drifted column type+# requires a rebuild.#-# Each entry pairs the canonical CREATE TABLE with the CREATE INDEX-# statements that DROP TABLE would otherwise take down with it (including-# ``idx_events_run``, added by the additive pass above). To guard against-# this list drifting from SCHEMA_SQL, ``test_rebuilt_schema_matches_fresh``-# asserts a rebuilt legacy DB is byte-identical to a fresh one.+# Each entry pairs the canonical CREATE TABLE with the CREATE INDEX statements+# DROP TABLE would take down with it (incl. ``idx_events_run`` from the additive+# pass). ``test_rebuilt_schema_matches_fresh`` guards this list against+# drifting from SCHEMA_SQL._REBUILD_SPECS = {"task_events": ("CREATE TABLE task_events ("@@ -1255,19 +1084,14 @@ def _rebuild_drifted_tables(conn: sqlite3.Connection) -> None:"""Rebuild any kanban table whose column types drifted from SCHEMA_SQL.Old boards crash the gateway notifier (``int(None)`` on a NULL id in- ``unseen_events_for_sub``) and never match the ``id > cursor`` filter, so- every kanban notification is silently lost (#35096). Each affected table is- rebuilt with the standard SQLite pattern — CREATE new → INSERT shared- columns → DROP old → RENAME — recreating its indexes too (DROP TABLE takes- them down). The legacy TEXT ids are dropped (they aren't valid integers);- AUTOINCREMENT assigns fresh ones and ``last_event_id`` cursors reset to 0,- so the first post-migration tick replays a task's event history once —- the safe failure mode for a feature that was already fully broken.-- The whole pass runs in one transaction so an interruption can't leave a- table half-renamed, and under ``connect()``'s init locks so nothing races- it. Idempotent: a correctly-typed DB skips every table and returns without- opening a transaction.+ ``unseen_events_for_sub``) and never match ``id > cursor``, so every+ notification is silently lost. Rebuild is CREATE new → INSERT shared+ columns → DROP old → RENAME, recreating indexes (DROP TABLE takes them+ down). Legacy TEXT ids are dropped; AUTOINCREMENT assigns fresh ones and+ ``last_event_id`` cursors reset to 0, so the first post-migration tick+ replays a task's event history once — the safe failure mode for a feature+ that was already fully broken. One transaction so an interruption can't+ leave a table half-renamed, under ``connect()``'s init locks. Idempotent."""drifted = [t for t in _REBUILD_SPECS if _table_has_drifted(conn, t)]if not drifted:@@ -1310,26 +1134,19 @@ def _rebuild_drifted_tables(conn: sqlite3.Connection) -> None:def _check_file_length_invariant(conn: sqlite3.Connection) -> None:- """Compare SQLite's own page accounting against the file size on disk.-- Raises sqlite3.DatabaseError if the file is shorter than the header claims- (torn-extend corruption).-- Both sides are read WITHOUT opening the database file. The header side- comes from ``PRAGMA page_count`` over the existing connection; the on-disk- side from ``stat()``. An earlier version read the header field with a bare- ``open(path,"rb")`` -- but ``close()`` cancels every POSIX advisory lock- this process holds on the file, so that probe silently dropped the locks- of concurrent writers (and of a running VACUUM) and let other processes- write into a database a writer still believed it owned. That is the- documented corruption route in sqlite.org/howtocorrupt.html section 2.2.- """+ """Raise ``sqlite3.DatabaseError`` if the file is shorter than its header+ page count claims (torn-extend). Both sides are read WITHOUT opening the+ database file (``PRAGMA page_count`` on the existing connection; ``stat()``+ for disk): an earlier bare ``open(path,"rb")`` probe was wrong because+ ``close()`` cancels every POSIX advisory lock this process holds on the+ file, silently dropping concurrent writers' (and a running VACUUM's) locks+ and letting other processes write into a database a writer still believed+ it owned (sqlite.org/howtocorrupt.html §2.2)."""from hermes_cli.sqlite_safe_read import file_length_matches_header- # In WAL mode a just-committed page can still live in the -wal file, so- # the main file legitimately lags its page count. Only enforce the- # invariant under a rollback journal, where every committed page must- # already be in the main file.+ # In WAL mode a just-committed page can still live in -wal, so the main+ # file legitimately lags its page count; only enforce under a rollback+ # journal, where every committed page must already be in the main file.try:row = conn.execute("PRAGMA journal_mode").fetchone()journal_mode = str(row[0]).lower() if row and row[0] is not None else ""@@ -1346,15 +1163,14 @@ def _check_file_length_invariant(conn: sqlite3.Connection) -> None:)-# SQLite's own busy_timeout uses a near-deterministic backoff, so concurrent-# writers re-collide in lockstep under a stampede. A jittered retry on the-# transaction boundary breaks that convoy. Mirrors state.db's _execute_write:-# a fixed 20-150ms jitter band (a 20ms floor prevents a near-zero retry from-# busy-spinning back into the collision). Only BEGIN IMMEDIATE and COMMIT are-# retried -- both are idempotent re-issues that touch no transaction body, so a-# CAS inside write_txn is never replayed. kanban keeps fewer retries than-# state.db (5 vs 15) because its 120s busy_timeout already absorbs most waits;-# the retry is the backstop for the tail SQLite returns BUSY on immediately.+# SQLite's busy_timeout backoff is near-deterministic, so stampeding writers+# re-collide in lockstep; a jittered retry on the transaction boundary breaks+# the convoy (mirrors state.db's _execute_write: 20-150ms band, the 20ms floor+# prevents busy-spinning back into the collision). Only BEGIN IMMEDIATE and+# COMMIT are retried — idempotent re-issues that touch no transaction body, so+# a CAS inside write_txn is never replayed. Fewer retries than state.db (5 vs+# 15): the 120s busy_timeout absorbs most waits; this is the backstop for the+# tail where SQLite returns BUSY immediately._BUSY_MAX_RETRIES = 5@@ -1384,26 +1200,18 @@ def _execute_boundary_with_retry(conn: sqlite3.Connection, sql: str) -> None:@contextlib.contextmanagerdef write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False):- """Context manager for an IMMEDIATE write transaction.-- Use for any multi-statement write (creating a task + link, claiming a- task + recording an event, etc.). A claim CAS inside this context is- atomic -- at most one concurrent writer can succeed.-- Nesting is an explicit opt-in: a caller already inside a transaction- gets a loud ``RuntimeError`` unless it passes ``allow_nested=True``,- in which case a SQLite savepoint is used instead of a second- ``BEGIN IMMEDIATE``. Only composition primitives that graph builders- deliberately run under one outer commit (``create_task``,- ``add_comment``) opt in — helpers with post-commit side effects- (``complete_task`` & co.) must never run under an open outer- transaction, because their side effects (workspace cleanup, ready+ """Context manager for an IMMEDIATE write transaction; a claim CAS inside+ is atomic — at most one concurrent writer succeeds.++ Nesting is an explicit opt-in (``allow_nested=True`` → savepoint instead+ of a second ``BEGIN IMMEDIATE``; otherwise a loud ``RuntimeError``). Only+ composition primitives graph builders run under one outer commit+ (``create_task``, ``add_comment``) opt in — helpers with post-commit side+ effects (``complete_task`` & co.) must never run under an open outer+ transaction, because those side effects (workspace cleanup, readyrecomputation, failure-counter clears) would fire while the outer- transaction can still roll back.-- The explicit ROLLBACK on exception is wrapped in try/except so that- a SQLite auto-rollback (which leaves no active transaction) does not- shadow the original exception with a spurious rollback error.+ transaction can still roll back. The ROLLBACK on exception is wrapped so a+ SQLite auto-rollback doesn't shadow the original exception."""_kb._assert_not_delegated_child_mutation()if getattr(conn, "in_transaction", False):@@ -1436,9 +1244,8 @@ def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False):try:conn.execute("ROLLBACK")except sqlite3.OperationalError:- # SQLite has already auto-rolled-back the transaction (typical- # under EIO, lock contention, or corruption). Nothing to undo;- # do not let this secondary failure shadow the real one.+ # SQLite already auto-rolled-back (EIO, contention, corruption);+ # don't let this secondary failure shadow the real one.passraiseelse:@@ -1450,8 +1257,7 @@ def write_txn(conn: sqlite3.Connection, *, allow_nested: bool = False):with contextlib.suppress(sqlite3.OperationalError):conn.execute("ROLLBACK")raise- # Post-commit file-length check: header page_count must match actual file pages.- # A discrepancy means a torn-extend — raise now rather than silently corrupt.+ # Post-commit torn-extend check — raise now rather than silently corrupt._kb._check_file_length_invariant(conn)diff --git a/hermes_cli/kanban_db_dispatch.py b/hermes_cli/kanban_db_dispatch.pyindex e1bd1597d25..0381dfd2c0e 100644--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@ -30,10 +30,8 @@ if TYPE_CHECKING:_log = logging.getLogger("hermes_cli.kanban_db")-# After this many consecutive non-success attempts on a task/profile, the-# dispatcher stops retrying and parks the task in ``blocked`` with a reason so-# a human can investigate. Prevents retry storms when a worker repeatedly times-# out, crashes, or cannot spawn.+# After this many consecutive non-success attempts on a task/profile the+# dispatcher parks the task in ``blocked`` with a reason — prevents retry storms.DEFAULT_FAILURE_LIMIT = 2@@ -41,8 +39,7 @@ DEFAULT_FAILURE_LIMIT = 2DEFAULT_SPAWN_FAILURE_LIMIT = DEFAULT_FAILURE_LIMIT-# Max bytes to keep in a single worker log file. The dispatcher truncates-# and rotates on spawn if the file is larger than this at spawn time.+# Worker log files larger than this at spawn time are rotated.DEFAULT_LOG_ROTATE_BYTES = 2 * 1024 * 1024 # 2 MiB@@ -73,13 +70,10 @@ _RESPAWN_BLOCKER_RE = re.compile(_RESPAWN_GUARD_SUCCESS_WINDOW = 3600 # 1 hour-# Cooldown after a rate-limited (quota-wall) requeue before the dispatcher-# re-spawns the worker. Without this, a task released by the rate-limit path-# would be re-spawned on the very next tick and immediately bounce off the-# same quota wall, burning a worker slot every tick for hours. The cooldown-# spaces retries out so the board keeps cheaply probing whether quota is back-# without thrashing. Overridable via ``HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS``-# for operators who want a tighter/looser probe cadence.+# Cooldown after a rate-limited (quota-wall) requeue before re-spawning. Without+# it the task would re-spawn on the very next tick and bounce off the same quota+# wall, burning a worker slot every tick for hours. Overridable via+# ``HERMES_KANBAN_RATE_LIMIT_COOLDOWN_SECONDS``.DEFAULT_RATE_LIMIT_COOLDOWN_SECONDS = 300 # 5 minutes@@ -165,14 +159,11 @@ class DispatchResult:deferred tasks stay queued for the next tick."""-# Bounded registry of recently-reaped worker child exits, populated by the-# reap loop at the top of ``dispatch_once`` and consulted by-# ``detect_crashed_workers`` to classify a dead-pid task.-#-# Entry: ``pid -> (raw_wait_status, reaped_at_epoch)``. We keep raw status-# so both ``os.WIFEXITED`` / ``os.WEXITSTATUS`` and ``os.WIFSIGNALED`` can-# be consulted. Entries are trimmed by age (and total size cap as a-# belt-and-braces against unbounded growth on exotic platforms).+# Bounded registry of recently-reaped worker exits, filled by the reap loop in+# ``dispatch_once`` and read by ``detect_crashed_workers`` to classify a dead-pid+# task. Entry: ``pid -> (raw_wait_status, reaped_at_epoch)``; raw status kept so+# both WIFEXITED/WEXITSTATUS and WIFSIGNALED can be consulted. Trimmed by age+# plus a total size cap._RECENT_WORKER_EXIT_TTL_SECONDS = 600@@ -183,21 +174,15 @@ _recent_worker_exits: "dict[int, tuple[int, float]]" = {}def _record_worker_exit(pid: int, raw_status: int) -> None:- """Record a reaped child's exit status for later classification.-- Called from the reap loop in ``dispatch_once``. Safe to call many- times; duplicate pids overwrite (pids can cycle, latest wins).- """+ """Record a reaped child's exit status; duplicate pids overwrite (latest wins)."""if not pid or pid <= 0:returnnow = time.time()_recent_worker_exits[int(pid)] = (int(raw_status), now)- # Age-based trim: drop entries older than the TTL.if len(_recent_worker_exits) > _RECENT_WORKER_EXITS_MAX // 2:cutoff = now - _RECENT_WORKER_EXIT_TTL_SECONDSfor _pid in [p for p, (_s, t) in _recent_worker_exits.items() if t < cutoff]:_recent_worker_exits.pop(_pid, None)- # Size cap as a final guard.if len(_recent_worker_exits) > _RECENT_WORKER_EXITS_MAX:# Drop oldest half.ordered = sorted(_recent_worker_exits.items(), key=lambda kv: kv[1][1])@@ -208,15 +193,13 @@ def _record_worker_exit(pid: int, raw_status: int) -> None:def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":"""Return ``(kind, code)`` for a reaped worker PID.- ``clean_exit`` (status 0 — a still-``running`` task is a protocol- violation: worker exited without ``kanban_complete``/``kanban_block``, so- auto-block, retrying just loops); ``rate_limited`` (status- ``KANBAN_RATE_LIMIT_EXIT_CODE`` — provider quota wall, released back to+ ``clean_exit`` (status 0 while still ``running`` = protocol violation:+ no ``kanban_complete``/``kanban_block``, so auto-block — retrying just+ loops); ``rate_limited`` (``KANBAN_RATE_LIMIT_EXIT_CODE`` — released to``ready`` WITHOUT counting a failure so a long quota window can't trip the- breaker); ``nonzero_exit`` (real error); ``signaled`` (OOM/SIGKILL, real- crash; ``code`` is the signal); ``unknown`` (pid not in the reap registry- — reaped elsewhere or died between reap tick and liveness check — fall- back to the crashed-counter path; ``code`` is None).+ breaker); ``nonzero_exit``; ``signaled`` (OOM/SIGKILL; ``code`` is the+ signal); ``unknown`` (pid not in the reap registry — fall back to the+ crashed-counter path; ``code`` is None)."""entry = _recent_worker_exits.get(int(pid))if entry is None:@@ -238,11 +221,7 @@ def _classify_worker_exit(pid: int) -> "tuple[str, Optional[int]]":def reap_worker_zombies() -> "list[int]":- """Reap all zombie children of this process without blocking.-- Returns the list of reaped PIDs. Safe to call when there are no- children (returns []). No-op on Windows.- """+ """Reap all zombie children without blocking; returns reaped PIDs. No-op on Windows."""reaped: "list[int]" = []if os.name != "nt":try:@@ -263,33 +242,21 @@ def reap_worker_zombies() -> "list[int]":def _pid_alive(pid: Optional[int]) -> bool:"""Return True if ``pid`` is still running on this host.- Cross-platform: uses ``OpenProcess`` + ``WaitForSingleObject`` on- Windows (via ``gateway.status._pid_exists``) and ``os.kill(pid, 0)``- on POSIX. Returns False for falsy PIDs or on any OS error.-- **DO NOT** use ``os.kill(pid, 0)`` directly on Windows — Python's- Windows ``os.kill`` treats ``sig=0`` as ``CTRL_C_EVENT`` (bpo-14484)- and will broadcast it to the target's console group, potentially+ Uses ``gateway.status._pid_exists`` (OpenProcess on Windows, ``os.kill(pid, 0)``+ on POSIX). **DO NOT** call ``os.kill(pid, 0)`` directly on Windows — there+ ``sig=0`` is ``CTRL_C_EVENT`` broadcast to the console group, potentiallykilling unrelated processes.- **Zombie handling:** the existence check succeeds against zombie- processes (post-exit, pre-reap) because the process table entry- still exists. A worker that exits without being reaped by its- parent would stay "alive" to the dispatcher forever. Dispatcher- workers are started via ``start_new_session=True`` + intentional- Popen handle abandonment, so init reaps them quickly — but during- the window between exit and reap, we'd otherwise see stale "alive"- signals. On Linux we peek at ``/proc/<pid>/status`` and treat- ``State: Z`` as dead. On macOS we ask ``ps`` for the BSD ``stat``- field and treat values containing ``Z`` as dead.+ Zombies (exited, not yet reaped) still pass the existence check, so a+ worker would look "alive" forever between exit and reap. Linux: peek at+ ``/proc/<pid>/status`` and treat ``State: Z`` as dead; macOS: ask ``ps``+ for the BSD ``stat`` field and treat ``Z`` as dead."""if not pid or pid <= 0:return Falsefrom gateway.status import _pid_existsif not _pid_exists(int(pid)):return False- # Still here → process exists. Check for zombie on platforms- # where we have a cheap, deterministic process-state probe.if sys.platform == "linux":try:with open(f"/proc/{int(pid)}/status", "r", encoding="utf-8") as f:@@ -301,8 +268,6 @@ def _pid_alive(pid: Optional[int]) -> bool:breakexcept (FileNotFoundError, PermissionError, OSError):# proc entry gone → already reaped; treat as dead.- # PermissionError shouldn't happen for our own children but- # be defensive.passelif sys.platform == "darwin":try:@@ -358,9 +323,8 @@ def _terminate_reclaimed_worker(try:kill(int(pid), signal.SIGTERM)except ProcessLookupError:- # Process is already gone — that's a successful termination, not a- # survival. Leaving terminated=False here would make the reclaim guard- # misread a dead worker as still-alive and defer forever.+ # Already gone = successful termination. Leaving terminated=False would+ # make the reclaim guard misread a dead worker as alive and defer forever.info["terminated"] = Truereturn infoexcept OSError:@@ -374,8 +338,7 @@ def _terminate_reclaimed_worker(if _kb._pid_alive(pid):try:- # signal.SIGKILL doesn't exist on Windows; fall back to SIGTERM- # (which maps to TerminateProcess via the stdlib shim).+ # signal.SIGKILL doesn't exist on Windows; SIGTERM maps to TerminateProcess._sigkill = getattr(signal, "SIGKILL", signal.SIGTERM)kill(int(pid), _sigkill)info["sigkill"] = True@@ -389,11 +352,10 @@ def _terminate_reclaimed_worker(def _worker_survived_termination(termination: dict) -> bool:"""True when we tried to kill our own host-local worker and it is still alive.- Reclaiming in this state would release the claim and let the dispatcher- spawn a second worker while the first is still running — the duplication- loop. Only host-local workers we actually signalled count: a non-local- claim lock or a no-op attempt (no ``os.kill`` available) must fall through- to the normal release path, since we cannot manage that worker anyway.+ Reclaiming then would release the claim and spawn a second worker while the+ first still runs — the duplication loop. Only host-local workers we actually+ signalled count; a non-local lock or no-op attempt (no ``os.kill``) must fall+ through to the normal release path since we cannot manage that worker anyway."""return bool(termination.get("termination_attempted")@@ -414,10 +376,9 @@ def _defer_reclaim_for_live_worker("""Hold a claim whose worker survived termination instead of releasing it.Extends ``claim_expires`` by ``RECLAIM_DEFER_GRACE_SECONDS`` so the task- stays ``running`` (no duplicate spawn) and records a ``reclaim_deferred``- event so the hold is visible in ``hermes kanban tail``. The next dispatch- tick retries the kill; this is self-correcting because not spawning a- duplicate is what lets the throttled worker finally die.+ stays ``running`` (no duplicate spawn) and records ``reclaim_deferred``.+ The next tick retries the kill; not spawning a duplicate is what lets the+ throttled worker finally die."""grace = now + _kb.RECLAIM_DEFER_GRACE_SECONDSwith _kb.write_txn(conn):@@ -452,13 +413,9 @@ def heartbeat_worker() -> bool:"""Record a ``heartbeat`` event + touch ``last_heartbeat_at``.- Called by long-running workers as a liveness signal orthogonal to- the PID check. A worker that forks a long-lived child (train loop,- video encode, web crawl) can have its Python still alive while the- actual work process is stuck; periodic heartbeats catch that.-- Returns True on success, False if the task is not in a state that- should be heartbeating (not running, or claim expired).+ Liveness signal orthogonal to the PID check: a worker whose forked child+ (train loop, crawl) is stuck can still have a live Python process.+ Returns False if the task is not running or its claim expired."""now = int(time.time())with _kb.write_txn(conn):@@ -501,15 +458,10 @@ def enforce_max_runtime() -> list[str]:"""Terminate workers whose per-task ``max_runtime_seconds`` has elapsed.- Sends SIGTERM, waits a short grace window, then SIGKILL. Emits a- ``timed_out`` event and restores the task's source phase so the next- dispatcher tick re-spawns the same kind of worker — unless the circuit- breaker has already given up, in which case the task stays blocked- where ``_record_spawn_failure`` parked it.-- Runs host-local: only tasks claimed by this host are candidates- (same reasoning as ``detect_crashed_workers``). ``signal_fn`` is a- test hook; defaults to ``os.kill`` on POSIX.+ SIGTERM, short grace, then SIGKILL. Emits ``timed_out`` and restores the+ task's source phase so the next tick re-spawns the same kind of worker —+ unless the circuit breaker already gave up, leaving it blocked. Host-local+ only (same reasoning as ``detect_crashed_workers``). ``signal_fn`` is a test hook."""import signaltimed_out: list[str] = []@@ -530,18 +482,16 @@ def enforce_max_runtime(lock = row["claim_lock"] or ""if not lock.startswith(host_prefix):continue- # Runtime is per attempt, not lifetime-of-task. ``tasks.started_at``- # intentionally records the first time a task ever started, so retries- # must be measured from the active task_runs row when present.+ # Runtime is per attempt: ``tasks.started_at`` records the FIRST start,+ # so retries must be measured from the active task_runs row.elapsed = now - int(row["active_started_at"])if elapsed < int(row["max_runtime_seconds"]):continuepid = int(row["worker_pid"])tid = row["id"]- # SIGTERM then SIGKILL. Keep it simple: 5 s grace. Workers that- # want a cleaner shutdown can install their own SIGTERM handler- # before the grace expires.+ # SIGTERM then SIGKILL after 5 s grace; workers wanting a cleaner+ # shutdown install their own SIGTERM handler.killed = Falsekill = signal_fn if signal_fn is not None else (os.kill if hasattr(os, "kill") else None@@ -591,11 +541,9 @@ def enforce_max_runtime(conn, tid, "timed_out", payload, run_id=run_id,)timed_out.append(tid)- # Increment the unified failure counter. Outside the write_txn- # above because ``_record_task_failure`` opens its own. If the- # breaker trips, this flips the retried task to ``blocked`` and- # emits a ``gave_up`` event on top of the ``timed_out`` we- # already emitted.+ # Outside the write_txn above because ``_record_task_failure`` opens its+ # own. If the breaker trips this flips the task to ``blocked`` and emits+ # ``gave_up`` on top of the ``timed_out`` already emitted.if cur.rowcount == 1:_kb._record_task_failure(conn, tid,@@ -612,10 +560,8 @@ def enforce_max_runtime(return timed_out-# Heartbeat staleness heartbeat gap — if a running task hasn't sent a-# heartbeat in this many seconds it's considered inactive regardless of-# the ``dispatch_stale_timeout_seconds`` threshold. Hardcoded at 1 hour-# to match the original spec (">4h started + no commits in 1h").+# A running task with no heartbeat for this long is inactive regardless of+# ``dispatch_stale_timeout_seconds`` (spec: ">4h started + no commits in 1h")._STALE_HEARTBEAT_GAP_SECONDS = 3600@@ -627,13 +573,11 @@ def detect_stale_running() -> list[str]:"""Reclaim ``running`` tasks with no heartbeat progress; returns their ids.- Stale = running longer than ``stale_timeout_seconds`` (from the active- run's ``started_at``, else ``tasks.started_at``) AND ``last_heartbeat_at``- older than ``_STALE_HEARTBEAT_GAP_SECONDS`` or NULL. The task returns to- its source phase, the run closes ``outcome='stale'`` and a live host-local- worker is terminated. Blocked tasks are never candidates;- ``stale_timeout_seconds=0`` disables the check. ``signal_fn`` is a test- hook (default ``os.kill`` on POSIX).+ Stale = running longer than ``stale_timeout_seconds`` (active run's+ ``started_at``, else ``tasks.started_at``) AND ``last_heartbeat_at`` older+ than ``_STALE_HEARTBEAT_GAP_SECONDS`` or NULL. Task returns to its source+ phase, run closes ``outcome='stale'``, live host-local worker is terminated.+ ``stale_timeout_seconds=0`` disables the check. ``signal_fn`` is a test hook."""if stale_timeout_seconds <= 0:return []@@ -651,24 +595,22 @@ def detect_stale_running().fetchall()for row in rows:- # Skip if no started_at (shouldn't happen for running, but be safe).if row["active_started_at"] is None:continueelapsed = now - int(row["active_started_at"])if elapsed < stale_timeout_seconds:- continue # not old enough to check+ continuelast_hb = row["last_heartbeat_at"]hb_age = (now - int(last_hb)) if last_hb is not None else Noneif hb_age is not None and hb_age < _STALE_HEARTBEAT_GAP_SECONDS:- continue # recent heartbeat → still alive+ continuepid = row["worker_pid"]tid = row["id"]lock = row["claim_lock"] or ""- # Terminate the worker if it's still host-local.termination = _kb._terminate_reclaimed_worker(pid, lock, signal_fn=signal_fn,)@@ -720,15 +662,10 @@ def detect_stale_running()reclaimed.append(tid)- # Intentionally NOT calling _record_task_failure here. Stale reclaim- # is dispatcher-side detection of an absent heartbeat; the task is- # going straight back to its source phase for re-dispatch. Counting it as- # a worker failure would let two legitimately-long-running tasks- # (>4h without explicit heartbeat) trip the circuit breaker and- # auto-block, even though no worker actually failed. The 'stale'- # event already lives in task_events for auditability; that's the- # right surface for "this happened" without conflating with the- # spawn_failed / timed_out / crashed counters.+ # Intentionally NOT calling _record_task_failure: stale reclaim is+ # dispatcher-side detection of an absent heartbeat, not a worker failure.+ # Counting it would let legitimately long-running tasks (>4h, no explicit+ # heartbeat) trip the breaker. The 'stale' event is the audit surface.return reclaimed@@ -738,15 +675,12 @@ def reconcile_orphaned_running() -> list[str]:"""Requeue ``running`` cards with broken claim bookkeeping; returns their ids.- A task can sit ``running`` with ``claim_lock``/``claim_expires`` NULL- (crash mid-claim, manual SQL, DB restore) and no other recovery path- touches it — ``release_stale_claims`` needs ``claim_expires``,- ``detect_crashed_workers`` needs a host-local lock + pid,- ``detect_stale_running`` is off by default — so it is a zombie forever.- Orphans go back to ``ready`` with an explanatory comment, a leaked run is- closed and a ``reconciled`` event appended; a row still recording a live- host-local PID is deferred to a later tick so no duplicate is spawned- beside a possibly-alive worker. Safe to call every tick.+ A task ``running`` with NULL ``claim_lock``/``claim_expires`` (crash+ mid-claim, manual SQL, DB restore) is a zombie forever: ``release_stale_claims``+ needs ``claim_expires``, ``detect_crashed_workers`` needs a host-local lock ++ pid, ``detect_stale_running`` is off by default. Orphans go back to ``ready``+ with a comment, leaked run closed, ``reconciled`` event; a row with a live+ host-local PID is deferred so no duplicate spawns beside it."""now = int(time.time())reconciled: list[str] = []@@ -759,8 +693,7 @@ def reconcile_orphaned_running(tid = row["id"]pid = row["worker_pid"]if pid and _kb._pid_alive(pid):- # The recorded worker may still be doing real work — never- # requeue beside a live process. Retry next tick.+ # Never requeue beside a live process. Retry next tick._kb._log.debug("kanban reconcile: task %s has broken claim bookkeeping but ""pid %s is alive on this host — deferring", tid, pid,@@ -806,50 +739,33 @@ def reconcile_orphaned_running(def _error_fingerprint(error_text: str) -> str:- """Normalize an error message for grouping identical failures.-- Strips host-specific details (PIDs, timestamps) so that errors- with the same root cause produce the same fingerprint.- """+ """Normalize an error message (strip PIDs, timestamps) so same-root-cause errors group."""fp = re.sub(r'\bpid \d+\b', 'pid N', error_text[:80])fp = re.sub(r'\b\d{10,}\b', '<TS>', fp)return fp.lower().strip()# ~96% of "clean exit without a terminal tool call" tasks complete on a later-# run, so a protocol violation is NOT deterministic — bounded retry before the-# breaker trips. The budget is a violation-only STREAK-# (``_protocol_violation_streak``), independent of ``consecutive_failures``:-# other failure kinds neither consume nor extend it, and a below-budget-# violation doesn't tick the unified counter. Per-task ``max_retries``-# overrides it, as for every other failure kind.+# run, so a protocol violation gets a bounded retry before the breaker trips.+# The budget is a violation-only STREAK (``_protocol_violation_streak``),+# independent of ``consecutive_failures``: other failure kinds neither consume+# nor extend it. Per-task ``max_retries`` overrides it._PROTOCOL_VIOLATION_FAILURE_LIMIT = 3-# Closed runs to walk when counting the streak; the streak trips at a handful,-# so anything past a few dozen rows means "way past the bound" anyway.+# Closed runs to walk when counting the streak; it trips at a handful anyway._PROTOCOL_VIOLATION_SCAN_LIMIT = 50def _protocol_violation_streak(conn: sqlite3.Connection, task_id: str) -> int:"""Count the task's trailing run of clean-exit protocol violations.- Walks the task's closed runs newest-first — including the violation run- ``detect_crashed_workers`` just closed — and counts how many in a row were- clean-exit protocol violations:-- * ``rate_limited`` runs are neutral and skipped: a quota wall says nothing- about the task, exactly as it is neutral for the unified- ``consecutive_failures`` counter.- * Any other closed run (completed, plain crash, timeout, spawn failure,- reclaim, …) breaks the streak, so the bounded retry budget counts ONLY- protocol violations — mixed failure kinds can neither consume nor- extend it.-- Violation runs are recognized by the ``protocol_violation`` marker that- ``detect_crashed_workers`` stamps into the run metadata; the violation- error text is matched as a fallback for runs recorded before the marker- existed.+ Walks closed runs newest-first (including the one ``detect_crashed_workers``+ just closed). ``rate_limited`` runs are neutral and skipped (a quota wall+ says nothing about the task); any other closed run breaks the streak, so+ the budget counts ONLY protocol violations. Violations are recognized by the+ ``protocol_violation`` run-metadata marker, with the error text as fallback+ for runs recorded before the marker existed."""streak = 0rows = conn.execute(@@ -876,38 +792,29 @@ def _protocol_violation_streak(conn: sqlite3.Connection, task_id: str) -> int:def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:"""Reclaim ``running`` tasks whose worker PID is no longer alive.- Appends a ``crashed`` event and restores the task's source phase.- Different from ``release_stale_claims``: this checks liveness- immediately rather than waiting for the claim TTL.-- Only tasks claimed by *this host* are considered — PIDs from other hosts- are meaningless, and ``_default_spawn`` always runs workers on the- dispatcher's host.-- A clean exit (rc=0) with the task still ``running`` is a protocol- violation (worker answered conversationally without ``kanban_complete`` /- ``kanban_block``); it gets a bounded violation-only retry budget before- the breaker trips (see ``_protocol_violation_streak``).-- An exit with ``KANBAN_RATE_LIMIT_EXIT_CODE`` is a provider quota wall,- NOT a task failure: released to its source phase WITHOUT counting a- failure (a long quota window must not trip the breaker) and stamped with- a quota-blocker error so ``check_respawn_guard`` defers the respawn. Those- ids surface via the ``_last_rate_limited`` function attribute; the public- return stays the crashed-only ``list[str]``.+ Appends ``crashed`` and restores the task's source phase; unlike+ ``release_stale_claims`` it checks liveness immediately rather than waiting+ for the claim TTL. Only tasks claimed by *this host* — PIDs from other hosts+ are meaningless, and ``_default_spawn`` always runs workers locally.++ Clean exit (rc=0) while still ``running`` is a protocol violation (no+ ``kanban_complete``/``kanban_block``); it gets a bounded violation-only retry+ budget (``_protocol_violation_streak``). ``KANBAN_RATE_LIMIT_EXIT_CODE`` is a+ quota wall, NOT a failure: released WITHOUT counting a failure and stamped+ with a quota-blocker error so ``check_respawn_guard`` defers respawn. Those+ ids surface via the ``_last_rate_limited`` function attribute; the return+ stays crashed-only."""crashed: list[str] = []rate_limited: list[str] = []- # Per-crash details collected inside the main txn, used after it- # closes to run ``_record_task_failure`` (which needs its own- # write_txn so can't nest). ``protocol_violation`` flags the- # clean-exit-but-still-running case, which is accounted against its- # own bounded violation streak instead of the unified failure- # counter (see the post-txn loop below).+ # Collected inside the main txn, used after it closes to run+ # ``_record_task_failure`` (needs its own write_txn, can't nest).+ # ``protocol_violation`` marks the clean-exit case, accounted against its+ # own bounded streak instead of the unified failure counter.crash_details: list[tuple[str, int, str, bool, str]] = []# (task_id, pid, claimer, protocol_violation, error_text)- # Worker-exit observer payloads (RFC #58548), collected inside the main- # txn and fired only after every reclaim/accounting txn has committed.+ # Worker-exit observer payloads, fired only after every reclaim/accounting+ # txn has committed.exited_hook_payloads: list[dict] = []with _kb.write_txn(conn):rows = conn.execute(@@ -917,13 +824,11 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:).fetchall()host_prefix = _kb._host_prefix()for row in rows:- # Only check liveness for claims owned by this host.lock = row["claim_lock"] or ""if not lock.startswith(host_prefix):continue- # Skip liveness check inside the launch-window grace period- # so a freshly-spawned worker isn't reclaimed before its PID- # is visible on /proc.+ # Launch-window grace so a freshly-spawned worker isn't reclaimed+ # before its PID is visible on /proc.started_at = _kb._row_get(row, "started_at")if started_at is not None:grace = _kb._resolve_crash_grace_seconds()@@ -936,10 +841,9 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:kind, code = _kb._classify_worker_exit(pid)rate_limited_exit = Falseif kind == "clean_exit":- # rc=0 with the task still ``running``: exited without- # ``kanban_complete`` / ``kanban_block``. Usually the work- # succeeded and only the paperwork was skipped; the corrective- # sentence reaches the retry worker via ``build_worker_context``.+ # rc=0 while still ``running``: usually the work succeeded and+ # only the paperwork was skipped; the corrective sentence reaches+ # the retry worker via ``build_worker_context``.protocol_violation = Trueerror_text = ("worker exited cleanly (rc=0) without calling "@@ -955,14 +859,12 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:"claimer": row["claim_lock"],"exit_code": code,# Durable marker for _protocol_violation_streak: _end_run- # copies this payload into the run metadata, which is how- # the violation-only retry budget is derived later.+ # copies this payload into the run metadata."protocol_violation": True,}elif kind == "rate_limited":- # EX_TEMPFAIL quota wall — NOT a task failure. Release to the- # source phase (respawn guard defers it) and do NOT count a- # failure so a long quota window can't trip the breaker.+ # Quota wall — NOT a task failure. Release to the source phase+ # and do NOT count a failure so a long quota window can't trip the breaker.protocol_violation = Falserate_limited_exit = Trueerror_text = (@@ -999,8 +901,7 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:(retry_status, row["id"], pid, row["claim_lock"]),)if cur.rowcount == 1:- # Rate-limited requeues are a clean release, not a crash —- # record the run outcome as ``rate_limited`` so the board+ # Record a rate-limited requeue as ``rate_limited`` so board# history doesn't show a phantom crash for a quota wall._run_outcome = "rate_limited" if rate_limited_exit else "crashed"run_id = _kb._end_run(@@ -1035,9 +936,8 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:else:if protocol_violation:# A below-budget violation never reaches- # ``_record_task_failure`` (which stamps this column- # for every other kind), yet the board UI and the retry- # worker's context need the corrective message.+ # ``_record_task_failure`` (which stamps this column), yet+ # the board UI and retry worker need the corrective message.conn.execute("UPDATE tasks SET last_failure_error = ? ""WHERE id = ?",@@ -1048,16 +948,12 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:(row["id"], pid, row["claim_lock"],protocol_violation, error_text))- # Outside the main txn: account each crash and maybe trip the breaker- # (blocked + ``gave_up`` on top of the event already emitted).- # Protocol violations get a BOUNDED violation-only retry budget- # (``_protocol_violation_streak``; see ``_PROTOCOL_VIOLATION_FAILURE_LIMIT``- # for why) — independent of ``consecutive_failures``, with per-task- # ``max_retries`` taking top precedence. Systemic same-error crashes still- # trip immediately.+ # Outside the main txn: account each crash and maybe trip the breaker.+ # Protocol violations get a BOUNDED violation-only budget independent of+ # ``consecutive_failures`` (per-task ``max_retries`` takes precedence);+ # systemic same-error crashes still trip immediately.auto_blocked: list[str] = []if crash_details:- # Fingerprint errors to detect systemic failures._fp_counts: dict[str, int] = {}for _, _, _, _, err_text in crash_details:fp = _error_fingerprint(err_text)@@ -1077,10 +973,9 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:else _PROTOCOL_VIOLATION_FAILURE_LIMIT)if streak < violation_limit:- # Below budget: already back at ``ready`` with- # ``last_failure_error`` stamped. Deliberately no- # ``_record_task_failure`` — must not consume the unified- # failure budget.+ # Below budget: already back at ``ready`` with the error+ # stamped. No ``_record_task_failure`` — must not consume+ # the unified failure budget.continue# ``force_trip``: the decision (incl. per-task ``max_retries``)# was already made against the violation streak above.@@ -1115,18 +1010,13 @@ def detect_crashed_workers(conn: sqlite3.Connection) -> list[str]:)if tripped:auto_blocked.append(tid)- # Stash auto-blocked ids on the function for the dispatch loop to pick up.- # Keeps the public return type (``list[str]``) stable for direct callers- # and tests that destructure the result; ``dispatch_once`` reads this- # side-channel attribute to populate ``DispatchResult.auto_blocked``.+ # Side-channel attributes keep the public ``list[str]`` return stable;+ # ``dispatch_once`` reads them to populate ``DispatchResult``. Rate-limited+ # requeues did NOT count a failure and are NOT crashes.detect_crashed_workers._last_auto_blocked = auto_blocked # type: ignore[attr-defined]- # Same side-channel for rate-limited requeues — these did NOT count a- # failure and are NOT crashes, so they stay out of the ``crashed`` return.detect_crashed_workers._last_rate_limited = rate_limited # type: ignore[attr-defined]- # Worker-lifecycle observer (RFC #58548): exit events are tick-derived- # from this reclaim pass — fired only now, after the main reclaim txn- # AND the breaker accounting above have committed, so subscribers always- # observe fully durable board state.+ # Fired only now, after the reclaim txn AND breaker accounting have+ # committed, so subscribers always observe fully durable board state.if exited_hook_payloads and _kb._kanban_observer_consumed("on_kanban_worker_exited"):_board = _kb.get_current_board()for hook_fields in exited_hook_payloads:@@ -1152,27 +1042,20 @@ def _record_task_failure(end_run: bool = False,event_payload_extra: Optional[dict] = None,) -> bool:- """Record a non-success outcome (spawn_failed / crashed / timed_out)- and maybe trip the circuit breaker.-- Every non-success path funnels through here so ``consecutive_failures``- and the auto-block threshold stay consistent. Returns True when the task- was auto-blocked, False when just updated in place.-- Modes: ``release_claim=True, end_run=True`` is the spawn-failure path- (task still running with an open run: restore its source phase — or- ``blocked`` on trip — release the claim, close the run with- ``outcome=<outcome>``). ``release_claim=False, end_run=False`` is the- timeout/crash path (caller ALREADY restored the phase and closed the run;- only the counter moves, and a trip re-transitions to ``blocked`` with a- ``gave_up`` event). ``event_payload_extra`` merges into that payload.-- Effective threshold: per-task ``max_retries`` (nothing overrides it), then- the caller's ``failure_limit`` (``kanban.failure_limit``), then- ``DEFAULT_FAILURE_LIMIT``. ``force_trip=True`` trips unconditionally —- the caller already applied its own bounded-retry policy (the- protocol-violation streak in ``detect_crashed_workers``); the order above- is then only reported in the payload. The failure is still counted.+ """Record a non-success outcome (spawn_failed / crashed / timed_out) and+ maybe trip the circuit breaker. Every non-success path funnels through+ here so ``consecutive_failures`` stays consistent. Returns True when the+ task was auto-blocked.++ ``release_claim=True, end_run=True`` is the spawn-failure path (task still+ running with an open run: restore source phase — or ``blocked`` on trip —+ release the claim, close the run). ``release_claim=False, end_run=False``+ is the timeout/crash path (caller ALREADY restored the phase and closed the+ run; only the counter moves, a trip re-transitions to ``blocked`` with+ ``gave_up``). Threshold: per-task ``max_retries`` (nothing overrides it),+ then ``failure_limit``, then ``DEFAULT_FAILURE_LIMIT``. ``force_trip=True``+ trips unconditionally — the caller already applied its own bounded-retry+ policy; the failure is still counted."""if failure_limit is None:failure_limit = DEFAULT_FAILURE_LIMIT@@ -1191,8 +1074,7 @@ def _record_task_failure()failures = int(row["consecutive_failures"]) + 1- # Per-task override wins over both caller-supplied and default- # thresholds. None (the common case) falls through.+ # Per-task override wins over caller-supplied and default thresholds.task_override = _kb._row_get(row, "max_retries")if task_override is not None:effective_limit = int(task_override)@@ -1202,9 +1084,8 @@ def _record_task_failure(limit_source = "dispatcher"if force_trip or failures >= effective_limit:- # Trip the breaker. Spawn path (release_claim) is still running- # and also clears claim state; the timeout/crash path already- # restored the source phase with the claim cleared.+ # Spawn path (release_claim) is still running and also clears claim+ # state; the timeout/crash path already did.conn.execute("UPDATE tasks SET status = 'blocked', "+ ("claim_lock = NULL, claim_expires = NULL, worker_pid = NULL, "@@ -1243,7 +1124,6 @@ def _record_task_failure()blocked = Trueelse:- # Below threshold.if release_claim:# Spawn path: restore the claimed source phase + clear claim.conn.execute(@@ -1254,14 +1134,12 @@ def _record_task_failure((retry_status, failures, error[:500], task_id),)else:- # Timeout/crash path: caller already restored the source phase.conn.execute("UPDATE tasks SET consecutive_failures = ?, ""last_failure_error = ? WHERE id = ?",(failures, error[:500], task_id),)if end_run:- # Spawn path: close the open run with outcome.run_id = _kb._end_run(conn, task_id,outcome=outcome, status=outcome,@@ -1284,8 +1162,7 @@ def _record_task_failure(return blocked-# Backward-compat alias. Old name is referenced from tests and possibly-# third-party callers. New code should call ``_record_task_failure``.+# Backward-compat alias; new code should call ``_record_task_failure``.def _record_spawn_failure(conn: sqlite3.Connection,task_id: str,@@ -1303,12 +1180,7 @@ def _record_spawn_failure(def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int) -> None:- """Record the spawned child's pid + emit a ``spawned`` event.-- The event's payload carries the pid so a human reading ``hermes kanban- tail`` can correlate log lines with OS-level traces without opening- the drawer.- """+ """Record the spawned child's pid + emit a ``spawned`` event carrying it."""with _kb.write_txn(conn):conn.execute("UPDATE tasks SET worker_pid = ? WHERE id = ?",@@ -1326,12 +1198,9 @@ def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int) -> None:def _clear_failure_counter(conn: sqlite3.Connection, task_id: str) -> None:"""Reset the unified consecutive-failures counter.- Called from ``complete_task`` on successful completion — a fresh- success means the task + profile combination is working and any- past failures are history. NOT called on spawn success anymore:- a successful spawn proves the worker could start but says nothing- about whether the run will succeed, so we need to let timeouts and- crashes accumulate across spawn boundaries.+ Called from ``complete_task`` on success. NOT called on spawn success: a+ spawn proves the worker could start, not that the run will succeed, so+ timeouts and crashes must accumulate across spawn boundaries."""with _kb.write_txn(conn):conn.execute(@@ -1350,44 +1219,31 @@ def check_respawn_guard() -> Optional[str]:"""Return a guard reason if ``task_id`` should NOT be re-spawned, else None.- Called per ready/review task in ``dispatch_once`` before any claim attempt.- Returning a reason defers the spawn this tick; the task stays in its- source phase and gets another chance on the next dispatcher tick.-- ``lane`` is the dispatch column (``"ready"`` / ``"review"``). The review- lane skips ``recent_success`` and ``active_pr``: a recent PR comment (and- often a completed run) is the *precondition* of a review handoff, not a- duplicate-work signal. Cooldown and auth-blocker apply in every lane.+ Called per ready/review task in ``dispatch_once`` before any claim attempt;+ a reason defers the spawn this tick. The review lane skips+ ``recent_success`` and ``active_pr``: a recent PR comment / completed run+ is the *precondition* of a review handoff, not a duplicate-work signal.Checks in priority order:- ``"rate_limit_cooldown"``- Latest run ended ``rate_limited`` (EX_TEMPFAIL quota wall) within- ``_resolve_rate_limit_cooldown_seconds()``; defer until it elapses,- then allow a cheap probe. Checked BEFORE ``blocker_auth`` because the- rate-limit requeue stamps a quota-flavored ``last_failure_error`` that- would otherwise match the auth regex and park the task forever (that- path never increments ``consecutive_failures``, so the breaker can't- free it).-- ``"blocker_auth"``- ``last_failure_error`` matches a quota / auth pattern; retrying now- won't help. ``consecutive_failures`` still trips the breaker after- ``failure_limit``, so a persistent auth error eventually blocks while- a transient 429 gets a few ticks of recovery.-- ``"recent_success"``- A completed run within ``_RESPAWN_GUARD_SUCCESS_WINDOW``; wait for an- explicit re-queue. Bypassed when a re-queue event (status, promote,- unblock, reclaim) arrives AFTER that completion — a deliberate re-run.-- ``"active_pr"``- A GitHub PR URL in a comment within ``_RESPAWN_GUARD_PR_WINDOW``;- re-spawning risks a duplicate PR.+ ``"rate_limit_cooldown"`` — latest run ended ``rate_limited`` within+ ``_resolve_rate_limit_cooldown_seconds()``. Checked BEFORE+ ``blocker_auth`` because the rate-limit requeue stamps a quota-flavored+ ``last_failure_error`` that would otherwise match the auth regex and+ park the task forever (that path never increments+ ``consecutive_failures``, so the breaker can't free it).+ ``"blocker_auth"`` — ``last_failure_error`` matches a quota/auth pattern.+ ``consecutive_failures`` still trips the breaker eventually, so a+ persistent auth error blocks while a transient 429 gets a few ticks.+ ``"recent_success"`` — completed run within ``_RESPAWN_GUARD_SUCCESS_WINDOW``.+ Bypassed when a re-queue event (status, promote, unblock, reclaim)+ arrives AFTER that completion — a deliberate re-run.+ ``"active_pr"`` — GitHub PR URL in a comment within+ ``_RESPAWN_GUARD_PR_WINDOW``; re-spawning risks a duplicate PR.Stale / dead claim locks are NOT a guard reason — ``release_stale_claims``and ``detect_crashed_workers`` reset those only after verifying the lock- is genuinely dead (no live PID on this host).+ is genuinely dead."""row = conn.execute("SELECT last_failure_error FROM tasks WHERE id = ?",@@ -1398,16 +1254,8 @@ def check_respawn_guard(now = int(time.time())- # 1. Rate-limit cooldown. The most recent run ended ``rate_limited``- # (quota wall) — defer while inside the cooldown window, then allow a- # cheap probe. Must run BEFORE the blocker_auth regex check, because a- # rate-limit requeue stamps a quota-flavored last_failure_error that- # the regex would otherwise match → defer forever (no failure counter- # increment on this path means the breaker can never free it).- #- # We look at the LATEST run only (ORDER BY ended_at DESC LIMIT 1): if a- # newer crash/completion superseded the rate-limit run, this guard- # no longer applies and the normal paths take over.+ # 1. Rate-limit cooldown — see docstring for why this precedes blocker_auth.+ # LATEST run only: a newer crash/completion supersedes the rate-limit run.rl_cooldown = _kb._resolve_rate_limit_cooldown_seconds()latest_run = conn.execute("SELECT outcome, ended_at FROM task_runs "@@ -1420,18 +1268,15 @@ def check_respawn_guard(and latest_run["outcome"] == "rate_limited"):if rl_cooldown <= 0:- # Cooldown disabled — respawn immediately, and skip the- # blocker_auth regex so the stamped rate-limit text doesn't- # re-trap the task.+ # Cooldown disabled — respawn immediately, skipping blocker_auth so+ # the stamped rate-limit text doesn't re-trap the task.return Noneended_at = latest_run["ended_at"]if ended_at is not None and (now - int(ended_at)) < rl_cooldown:return "rate_limit_cooldown"- # Cooldown elapsed — allow the respawn. Return early so the- # blocker_auth check below doesn't catch the rate-limit text we- # stamped on the task; this path intentionally retries forever- # (cheaply, spaced by the cooldown) until quota returns or a real- # crash/completion supersedes it.+ # Cooldown elapsed — return early so blocker_auth doesn't catch the+ # stamped rate-limit text; this path intentionally retries forever+ # (spaced by the cooldown) until quota returns or a real run supersedes it.return None# 2. Quota / auth blocker: retrying immediately will not help.@@ -1439,18 +1284,15 @@ def check_respawn_guard(if err and _RESPAWN_BLOCKER_RE.search(err):return "blocker_auth"- # Review-lane spawns stop here: a recent completed run and a fresh PR- # URL comment are the canonical *inputs* to a review handoff (worker- # opened a PR, then requested review), not signals of duplicate work.+ # Review-lane spawns stop here: a recent completed run and a fresh PR URL+ # are the canonical *inputs* to a review handoff, not duplicate-work signals.if lane == "review":return None- # 3. Completed run within guard window — proof of recent success.- # Exception: an explicit re-queue AFTER that success (an operator- # dragging done→ready, a dependency re-promotion, an unblock, a- # reclaim) is a deliberate "run it again" — honor it instead of- # deferring. Without this, a manual done→ready just sits there,- # silently held by the guard, until the window elapses.+ # 3. Completed run within guard window. Exception: an explicit re-queue+ # AFTER that success (done→ready drag, re-promotion, unblock, reclaim) is+ # a deliberate "run it again" — otherwise a manual done→ready would sit+ # silently held until the window elapses.cutoff = now - _RESPAWN_GUARD_SUCCESS_WINDOWrecent_completed = conn.execute("SELECT ended_at FROM task_runs "@@ -1501,11 +1343,9 @@ def _has_spawnable(conn: sqlite3.Connection, status: str) -> bool:def has_spawnable_ready(conn: sqlite3.Connection) -> bool:"""True iff a ready+assigned+unclaimed task maps to a real Hermes profile.- Health telemetry uses it to tell "stuck" (``0 spawned`` with spawnable- work) from "correctly idle" (only control-plane lanes waiting on terminals- that pull via ``claim_task``). Falls back to "any assigned" when- ``profile_exists`` is unimportable (partial install) so the warning still- fires when degraded.+ Lets health telemetry tell "stuck" (``0 spawned`` with spawnable work) from+ "correctly idle" (only control-plane lanes waiting on ``claim_task``). Falls+ back to "any assigned" when ``profile_exists`` is unimportable."""return _has_spawnable(conn, "ready")@@ -1516,11 +1356,8 @@ def has_spawnable_review(conn: sqlite3.Connection) -> bool:def review_dispatch_enabled() -> bool:- """Return whether first-class review tasks should dispatch automatically.-- The default is true because Hermes ships the ``sdlc-review`` skill and the- review lifecycle includes a supported reviewer-owned changes-requested- transition. Operators can disable it for human-only review boards.+ """Whether review tasks dispatch automatically. Default true (Hermes ships+ ``sdlc-review``); operators disable it for human-only review boards."""try:from hermes_cli.config import load_config@@ -1535,24 +1372,20 @@ def review_dispatch_enabled() -> bool:# Memory-aware dispatch guard## With no ``kanban.max_in_progress`` on a busy board the dispatcher fanned out-# 26-31 workers on a 1 GiB VM and OOM'd the host. Two safeguards: a-# memory-DERIVED default cap when the operator never set one-# (``resolve_max_in_progress``, sized from MemTotal), and a live-# memory-PRESSURE guard inside the tick (``_memory_pressure_level``) because-# a static cap can't see other tenants of the box. Both fail open: non-Linux-# or any read error → empty sample → no cap / "unknown" (no restriction).+# ~30 workers on a 1 GiB VM and OOM'd the host. Two safeguards: a memory-DERIVED+# default cap when the operator never set one (``resolve_max_in_progress``), and+# a live memory-PRESSURE guard inside the tick (``_memory_pressure_level``)+# because a static cap can't see other tenants. Both fail open: non-Linux or+# any read error → empty sample → no cap / "unknown".# ----------------------------------------------------------------------------# Assumed per-worker memory footprint for the derived default cap. Hermes-# workers are full agent processes (Python + model client + tool subprocesses);-# ~512 MiB is a deliberately conservative planning number so the derived cap-# errs toward fewer workers on small VMs.+# Assumed per-worker footprint for the derived cap; deliberately conservative+# so the cap errs toward fewer workers on small VMs.MEMORY_GUARD_MB_PER_WORKER = 512-# Bounds for the derived default: never below 2 (a board must still make-# progress on the smallest hosted VM) and never above 8 (operators who want-# more fan-out on big iron should say so explicitly in config).+# Derived default bounds: never below 2 (smallest VM must still progress),+# never above 8 (more fan-out must be explicit in config).DERIVED_MAX_IN_PROGRESS_FLOOR = 2@@ -1562,12 +1395,9 @@ DERIVED_MAX_IN_PROGRESS_CEILING = 8def _system_memory_sample() -> dict:"""Best-effort system memory snapshot (KiB values), ``{}`` when unknown.- Delegates to :func:`gateway.lifecycle_ledger.sample_memory` (pure /proc- reads, Linux-only, never raises). Local import keeps ``kanban_db``- importable in stripped-down environments without the gateway package.- Module-level indirection is also the test seam — the shared conftest- patches this to ``{}`` so suite results don't depend on the CI runner's- live memory state.+ Local import keeps ``kanban_db`` importable without the gateway package.+ Module-level indirection is also the test seam — conftest patches this to+ ``{}`` so results don't depend on the CI runner's live memory."""try:from gateway.lifecycle_ledger import sample_memory@@ -1577,12 +1407,10 @@ def _system_memory_sample() -> dict:def derive_default_max_in_progress(sample: Optional[Mapping[str, Any]] = None) -> Optional[int]:- """Memory-derived default for ``kanban.max_in_progress`` when unset.-- ``clamp(MemTotal / MEMORY_GUARD_MB_PER_WORKER, FLOOR, CEILING)`` — e.g.- a 1 GiB VM derives 2, a 4 GiB VM derives 8. Returns ``None`` (no cap,- pre-fix behaviour) when total memory can't be determined, so dev- machines on macOS/Windows are unaffected.+ """Memory-derived default for ``kanban.max_in_progress`` when unset:+ ``clamp(MemTotal / MEMORY_GUARD_MB_PER_WORKER, FLOOR, CEILING)``. Returns+ ``None`` (no cap) when total memory is unknown, so macOS/Windows dev+ machines are unaffected."""if sample is None:sample = _kb._system_memory_sample()@@ -1597,12 +1425,9 @@ def derive_default_max_in_progress(sample: Optional[Mapping[str, Any]] = None) -def resolve_max_in_progress(configured: Optional[int]) -> Optional[int]:- """Return the effective global concurrency cap for a dispatch tick.-- An explicit operator-configured value always wins. When unset, fall back- to the memory-derived default (see :func:`derive_default_max_in_progress`).- Callers that parse config (gateway dispatcher, ``hermes kanban dispatch``)- should route through this so both paths agree.+ """Effective global concurrency cap: explicit config wins, else the+ memory-derived default. All config-parsing callers route through this so+ both paths agree."""if configured is not None:return configured@@ -1612,10 +1437,8 @@ def resolve_max_in_progress(configured: Optional[int]) -> Optional[int]:def configured_max_in_progress() -> Optional[int]:"""Read ``kanban.max_in_progress`` from config, or None when unset/invalid.- Small shared parser so every dispatch entry point (gateway watcher, CLI- dispatch, standalone daemon) agrees on what "explicitly configured"- means: a positive integer wins, anything else falls through to the- memory-derived default via :func:`resolve_max_in_progress`.+ Shared so every dispatch entry point agrees on "explicitly configured": a+ positive integer wins, anything else falls through to the derived default."""try:from hermes_cli.config import load_config_readonly@@ -1634,14 +1457,11 @@ def configured_max_in_progress() -> Optional[int]:def count_running_tasks(conn: sqlite3.Connection) -> int:- """Return the number of tasks currently in ``status='running'``.-- Used by the gateway's multi-board sweep to account for workers on- OTHER boards against the host-level concurrency budget (OOF-30): the- memory-derived cap bounds the machine, so each board's tick must see- the machine's total, not just its own. Fails open to 0 — a broken- board must not brick dispatch on healthy ones (corruption is handled- separately by the watcher's quarantine logic).+ """Number of tasks in ``status='running'``.++ Used by the multi-board sweep to count OTHER boards' workers against the+ host-level budget — the memory-derived cap bounds the machine, not the+ board. Fails open to 0 so a broken board doesn't brick dispatch on healthy ones."""try:return int(@@ -1656,16 +1476,10 @@ def count_running_tasks(conn: sqlite3.Connection) -> int:def count_running_tasks_other_boards(board: Optional[str] = None) -> int:"""Total ``running`` tasks across every board EXCEPT ``board``.- The concurrency caps bound the HOST (workers are OS processes sharing- one machine's memory), but each board's dispatch tick only sees its own- DB. Without this, a memory-derived cap of N gets multiplied by the- number of active boards — reproduced in review of OOF-30: two boards- each spawned N workers on a derived N-worker host budget.-- Boards are matched by resolved DB path, so the ``HERMES_KANBAN_DB``- override (which pins every board to one file) naturally yields 0.- Fails open per board: one broken/corrupt board must not brick dispatch- on the healthy ones.+ Caps bound the HOST, but each board's tick only sees its own DB; without+ this a derived cap of N gets multiplied by the number of active boards.+ Boards are matched by resolved DB path, so ``HERMES_KANBAN_DB`` (pins every+ board to one file) yields 0. Fails open per board."""try:current_path = str(_kb.kanban_db_path(board=board).expanduser().resolve())@@ -1697,13 +1511,12 @@ def count_running_tasks_other_boards(board: Optional[str] = None) -> int:def _memory_pressure_level(sample: Optional[Mapping[str, Any]] = None) -> str:- """Classify current system memory pressure: ok/elevated/critical/unknown.+ """Classify system memory pressure: ok/elevated/critical/unknown.- Reuses :func:`gateway.memory_status.classify_pressure` so the dispatcher's- idea of "critical" matches the memory banner users see on the dashboard- and the lifecycle ledger's OOM-suspicion heuristics (NS-608/NS-656).- ``unknown`` (non-Linux, read failure) imposes no restriction — the guard- must never brick dispatch on hosts where /proc isn't available.+ Reuses :func:`gateway.memory_status.classify_pressure` so "critical" matches+ the dashboard banner and lifecycle-ledger OOM heuristics. ``unknown``+ (non-Linux, read failure) imposes no restriction — never brick dispatch+ where /proc is unavailable."""if sample is None:sample = _kb._system_memory_sample()@@ -1735,19 +1548,16 @@ def dispatch_once() -> DispatchResult:"""Run one dispatcher tick under the board's single-writer lock.- Wraps :func:`_dispatch_once_locked` in the non-blocking board-scoped- :func:`_dispatch_tick_lock` so two dispatchers on one ``kanban.db`` (the- service-managed gateway plus an orphan that escaped its cgroup) never- race a write tick on WAL frames. The loser returns an empty- ``DispatchResult`` with ``skipped_locked=True`` and writes nothing; the- lock is keyed on the resolved DB path so unrelated boards tick in parallel.+ Wraps :func:`_dispatch_once_locked` in the non-blocking :func:`_dispatch_tick_lock`+ so two dispatchers on one ``kanban.db`` never race a write tick on WAL+ frames. The loser returns an empty ``DispatchResult`` with+ ``skipped_locked=True`` and writes nothing; the lock is keyed on the+ resolved DB path so unrelated boards tick in parallel."""try:db_path = _kb.kanban_db_path(board=board)except Exception:- # Path resolution should never fail, but if it somehow does we- # must not lose the tick — fall through to an unguarded dispatch- # rather than dropping work.+ # Must not lose the tick — fall through to an unguarded dispatch.result = _dispatch_once_locked(conn,spawn_fn=spawn_fn,@@ -1782,14 +1592,10 @@ def dispatch_once(max_in_progress_per_profile=max_in_progress_per_profile,reconcile_orphans=reconcile_orphans,)- # Still under the dispatch lock: run the periodic PASSIVE WAL- # checkpoint (see _maybe_checkpoint_wal; the -wal file size is- # bounded by journal_size_limit on the writer's natural reset).+ # Still under the dispatch lock: periodic PASSIVE WAL checkpoint._kb._maybe_checkpoint_wal(conn, db_path)- # The dispatch lock has been released here. Fire the tick observer- # strictly OUTSIDE the single-writer critical section (#56066 sweeper- # finding / #64231 disposition): a slow subscriber must never extend- # the lock hold and stall a sibling dispatcher's tick.+ # Lock released. Fire the tick observer strictly OUTSIDE the critical+ # section: a slow subscriber must never stall a sibling dispatcher's tick._kb._fire_dispatch_tick_hook(result, board=board, dry_run=dry_run)return result@@ -1810,18 +1616,14 @@ def _dispatch_lane_task(per_profile_running: dict[str, int],) -> bool:"""Guard, claim, resolve the workspace and spawn one ready/review row.-- Shared tail of both dispatch lanes. Returns True when a spawn slot was- consumed (real spawn, or a would-be spawn under ``dry_run``); every skip- is recorded on ``result``.+ Returns True when a spawn slot was consumed (real or ``dry_run``); every+ skip is recorded on ``result``."""task_id = row["id"]- # Skip tasks whose assignee is not a real Hermes profile: ``_default_spawn``- # runs ``hermes -p <assignee>``, which fails on startup for control-plane- # lanes (interactive terminals that pull via ``claim_task``), and the task- # would loop ready→crash→ready forever. Bucketed apart from- # skipped_unassigned: the operator cannot fix it by assigning a profile,- # and health telemetry uses the distinction to suppress "stuck" warnings.+ # Non-profile assignees (control-plane lanes that pull via ``claim_task``)+ # would fail ``hermes -p <assignee>`` at startup and loop ready→crash→ready+ # forever. Bucketed apart from skipped_unassigned: the operator cannot fix+ # it by assigning a profile, and health telemetry suppresses "stuck" for it.try:from hermes_cli.profiles import profile_exists # local import: avoids cycleexcept Exception:@@ -1829,17 +1631,13 @@ def _dispatch_lane_task(if profile_exists is not None and not profile_exists(assignee):result.skipped_nonspawnable.append(task_id)return False- # Per-profile concurrency cap: even with global headroom, refuse to spawn- # for an assignee already at its in-flight cap so one profile's local- # model / API quota / browser pool isn't overwhelmed by a fan-out.+ # Per-profile cap: one profile's local model / API quota / browser pool+ # must not be overwhelmed by a fan-out even with global headroom.if per_profile_cap is not None:current = per_profile_running.get(assignee, 0)if current >= per_profile_cap:result.skipped_per_profile_capped.append((task_id, assignee, current))return False- # Respawn guard: defer this tick when useful work is already in-flight /- # recent or the last failure is a deterministic blocker (quota / auth).- # consecutive_failures still trips the auto-block breaker eventually.guard_reason = _kb.check_respawn_guard(conn, task_id, lane=lane)if guard_reason is not None:result.respawn_guarded.append((task_id, guard_reason))@@ -1850,8 +1648,7 @@ def _dispatch_lane_task(return Falseif dry_run:result.spawned.append((task_id, assignee, ""))- # Count the would-be spawn so the cap check sees it on later rows;- # otherwise dry_run under-reports the capped subset.+ # Count the would-be spawn so the cap check sees it on later rows.if per_profile_cap is not None and assignee:per_profile_running[assignee] = per_profile_running.get(assignee, 0) + 1return True@@ -1869,15 +1666,13 @@ def _dispatch_lane_task(if _record_spawn_failure(conn, claimed.id, f"workspace: {exc}", failure_limit=failure_limit):result.auto_blocked.append(claimed.id)return False- # Persist the resolved workspace path so the worker can cd there._kb.set_workspace_path(conn, claimed.id, str(workspace))if claimed.workspace_kind == "worktree":_kb.set_branch_name(conn, claimed.id, resolved_branch_name or (claimed.branch_name or "").strip() or f"wt/{claimed.id}")_kb._maybe_emit_scratch_tip(conn, claimed.id, claimed.workspace_kind)if lane == "review":- # Force-load the sdlc-review skill (AC verification, merge, ...). The- # mandatory kanban lifecycle is already in every worker's system- # prompt via KANBAN_GUIDANCE, so this is the only extra skill needed.+ # Force-load sdlc-review; the kanban lifecycle is already in every+ # worker's system prompt via KANBAN_GUIDANCE.claimed.skills = list(dict.fromkeys([*(claimed.skills or []), "sdlc-review"]))_spawn = spawn_fn if spawn_fn is not None else _default_spawntry:@@ -1894,16 +1689,14 @@ def _dispatch_lane_task(pid = _spawn(claimed, str(workspace))if pid:_set_worker_pid(conn, claimed.id, int(pid))- # Worker-lifecycle observer: fires AFTER spawn_fn returned and the PID- # (when reported) is durably persisted. Best-effort.+ # Fires AFTER the PID (when reported) is durably persisted. Best-effort._kb._fire_worker_spawned_hook(conn, claimed, str(workspace), pid, board=board)- # consecutive_failures is deliberately NOT reset here: a successful- # spawn doesn't prove the run will succeed, and resetting on spawn- # would let a task that keeps timing out loop forever. Cleared only- # on successful completion (complete_task).+ # consecutive_failures is deliberately NOT reset here: resetting on+ # spawn would let a task that keeps timing out loop forever. Cleared+ # only on successful completion (complete_task).result.spawned.append((claimed.id, claimed.assignee or "", str(workspace)))- # Track the new in-flight count so later rows in this tick respect- # the per-profile cap; subsequent ticks re-query from the DB.+ # Later rows in this tick respect the per-profile cap; subsequent+ # ticks re-query from the DB.if per_profile_cap is not None and claimed.assignee:per_profile_running[claimed.assignee] = per_profile_running.get(claimed.assignee, 0) + 1return True@@ -1918,10 +1711,9 @@ def _apply_default_assignee() -> bool:"""Persist ``kanban.default_assignee`` on an unassigned ready row.- Mutating the row (not just the in-memory view) keeps diagnostics and board- state consistent: the task is now legitimately owned by the default, not- "unassigned but secretly routed". ``dry_run`` reports the would-be- assignment without writing. Returns False when the write failed.+ Mutating the row keeps board state honest: the task is legitimately owned+ by the default, not "unassigned but secretly routed". ``dry_run`` reports+ without writing. Returns False when the write failed."""if dry_run:return True@@ -1964,76 +1756,50 @@ def _dispatch_once_locked((dead host-local PID) running tasks, promote todo -> ready where allparents are done, then for each ready task with an assignee atomicallyclaim and call ``spawn_fn(task, workspace_path, board) -> Optional[int]``,- recording the returned PID as ``worker_pid`` so later ticks catch crashes- before the TTL expires.-- After ``failure_limit`` consecutive per-task failures the task is- auto-blocked with the last error as reason (no thrashing on an unfixable- task). ``max_spawn`` is a live per-board concurrency cap (running + this- tick's spawns), not a per-tick budget — a per-tick reading would grow- concurrency by N every tick. ``max_in_progress`` is a host-level cap over- every active board plus this tick's spawns: workers are OS processes- sharing one machine's memory, so a per-board reading would multiply it by- the board count. ``spawn_fn`` defaults to ``_default_spawn`` (tests stub- it); ``board`` pins workspace/log/db resolution for this tick, else the- current-board chain is used.+ recording the PID as ``worker_pid`` so later ticks catch crashes before+ the TTL expires.++ After ``failure_limit`` consecutive failures the task is auto-blocked.+ ``max_spawn`` is a live per-board concurrency cap (running + this tick's+ spawns), not a per-tick budget — a per-tick reading would grow concurrency+ by N every tick. ``max_in_progress`` is a host-level cap over every active+ board: workers share one machine's memory, so a per-board reading would+ multiply it by the board count."""- # Reap zombie children from previously spawned workers. See- # reap_worker_zombies() for the full rationale.reap_worker_zombies()result = DispatchResult()result.reclaimed = _kb.release_stale_claims(conn)if reconcile_orphans:- # Orphaned-card reconciliation: requeue 'running' cards whose claim- # bookkeeping is broken (no valid claim, dead/gone worker) that the- # TTL/crash/stale paths can never see. See reconcile_orphaned_running.result.reconciled_orphans = reconcile_orphaned_running(conn)result.stale = detect_stale_running(conn, stale_timeout_seconds=stale_timeout_seconds,)result.crashed = detect_crashed_workers(conn)- # detect_crashed_workers stashes protocol-violation auto-blocks on- # itself so the public list-return stays stable. Pull them into the- # DispatchResult here so telemetry / tests see the trip.+ # Side-channel attributes (see detect_crashed_workers); rate-limited tasks+ # went back to ``ready`` and the respawn guard defers them until quota clears.result.auto_blocked.extend(getattr(detect_crashed_workers, "_last_auto_blocked", []))- # Rate-limited requeues (quota wall, no failure counted) — surface for- # telemetry / tests. These tasks went back to ``ready`` and the respawn- # guard will defer them until the quota window clears.result.rate_limited.extend(getattr(detect_crashed_workers, "_last_rate_limited", []))result.timed_out = enforce_max_runtime(conn)result.promoted = _kb.recompute_ready(conn, failure_limit=failure_limit)- # Count tasks already running so max_spawn enforces concurrency rather- # than a per-tick spawn budget. See the docstring above for the full- # rationale; the short version is that a 60-second tick interval with a- # per-tick budget of N would grow concurrency by N every tick on a busy- # board, since "running" tasks aren't reclaimed by completion alone —- # they sit in status='running' until the worker calls- # kanban_complete/kanban_block (or the dispatcher TTL-reclaims them).+ # Count already-running tasks so max_spawn enforces concurrency, not a+ # per-tick budget: "running" tasks stay running until the worker calls+ # kanban_complete/kanban_block or the TTL reclaims them.running_count = 0spawn_budget: Optional[int] = Noneif max_spawn is not None or max_in_progress is not None:running_count = count_running_tasks(conn)- # Convert any concurrency caps into a shared additional-spawns budget- # for this tick. Both ready and review loops consume from the same- # budget so the total number of new workers stays bounded.+ # Both ready and review loops consume from the same budget.if max_spawn is not None:if running_count >= max_spawn:return resultspawn_budget = max_spawn - running_count- # Honour kanban.max_in_progress across both ready and review queues: if- # the board already has enough running tasks, skip this tick entirely.- # When there is room left, intersect the remaining in-progress budget- # with any explicit max_spawn cap above.- #- # max_in_progress is a HOST-level cap, not a per-board one (OOF-30):- # workers are OS processes sharing one machine's memory, so running- # workers on every other board count against the same budget. Without- # this, N active boards multiply the cap by N — exactly the fan-out- # the memory-derived default exists to prevent.+ # max_in_progress is a HOST-level cap: running workers on every other board+ # count against the same budget, else N boards multiply the cap by N —+ # exactly the fan-out the memory-derived default exists to prevent.if max_in_progress is not None:total_running = running_count + count_running_tasks_other_boards(board)if total_running >= max_in_progress:@@ -2042,13 +1808,10 @@ def _dispatch_once_locked(if spawn_budget is None or spawn_budget > remaining:spawn_budget = remaining- # Memory-pressure guard (OOF-30/OOF-77): even a well-chosen static cap- # can't see the host's actual memory state (other tenants, bloated- # long-lived workers, dashboard growth). Under observed pressure the- # dispatcher stops adding load: critical -> spawn nothing this tick;- # elevated -> at most one new worker. Reclaim/promotion above already- # ran, so board bookkeeping stays live either way, and deferred tasks- # simply wait for a later tick. "unknown" imposes no restriction.+ # Memory-pressure guard: a static cap can't see the host's actual state.+ # critical -> spawn nothing this tick; elevated -> at most one new worker.+ # Reclaim/promotion already ran, so bookkeeping stays live; deferred tasks+ # wait for a later tick. "unknown" imposes no restriction.pressure = _memory_pressure_level()if pressure == "critical":result.memory_pressure = pressure@@ -2071,8 +1834,8 @@ def _dispatch_once_locked("WHERE status = 'ready' AND claim_lock IS NULL ""ORDER BY priority DESC, created_at ASC").fetchall()- # Review rows are enumerated up front (not after the ready loop) so the- # budget split below can see whether review work exists at all.+ # Review rows are enumerated up front so the budget split can see whether+ # review work exists at all.review_rows = []if review_dispatch_enabled():review_rows = conn.execute(@@ -2080,21 +1843,18 @@ def _dispatch_once_locked("WHERE status = 'review' AND claim_lock IS NULL ""ORDER BY priority DESC, created_at ASC").fetchall()- # Review-lane reservation: the ready loop runs first and used to consume- # the ENTIRE shared budget, starving autonomous reviews under a sustained- # ready backlog. When spawnable review work exists and there is any- # budget, hold one slot back from the ready loop. Per-tick and- # self-releasing: no spawnable review work (or no cap) → full budget.- # "Spawnable" mirrors the review loop's own gate (assigned + real- # profile) so human-pulled control-plane lanes don't tax ready throughput.+ # Review-lane reservation: the ready loop runs first and would otherwise+ # consume the ENTIRE shared budget, starving reviews under a sustained ready+ # backlog. When spawnable review work exists and there is any budget, hold+ # one slot back. "Spawnable" mirrors the review loop's own gate so+ # human-pulled control-plane lanes don't tax ready throughput.def _any_spawnable_review() -> bool:if not review_rows:return Falsetry:from hermes_cli.profiles import profile_exists as _rpeexcept Exception:- # Profiles module unavailable (test stubs, exotic envs) —- # assume spawnable, matching the review loop's own fallback.+ # Assume spawnable, matching the review loop's own fallback.return any(row["assignee"] for row in review_rows)return any(row["assignee"] and _rpe(row["assignee"]) for row in review_rows@@ -2104,11 +1864,8 @@ def _dispatch_once_locked(if spawn_budget is not None and spawn_budget > 0 and _any_spawnable_review():ready_budget = max(spawn_budget - 1, 0)spawned = 0- # Per-profile concurrency cap: track in-flight workers per assignee and- # refuse spawns past the cap so a fan-out can't melt one profile's local- # model / API quota / browser pool. Deferred tasks go to- # skipped_per_profile_capped, not skipped_unassigned — "busy, retry- # later" is a different operator signal from "needs routing".+ # Per-profile cap. Deferred tasks go to skipped_per_profile_capped, not+ # skipped_unassigned — "busy, retry later" differs from "needs routing"._per_profile_cap = max_in_progress_per_profile if (isinstance(max_in_progress_per_profile, int)and max_in_progress_per_profile > 0@@ -2121,11 +1878,9 @@ def _dispatch_once_locked("GROUP BY assignee"):_per_profile_running[prow["assignee"]] = int(prow["n"])- # Normalize default_assignee once (empty → None) and resolve- # profile_exists once. When the profiles module isn't importable (test- # stubs, exotic envs) trust the operator's config: the downstream- # profile_exists check on the assigned row still buckets a missing- # profile as nonspawnable with the existing diagnostic.+ # When the profiles module isn't importable trust the operator's config:+ # the downstream profile_exists check still buckets a missing profile as+ # nonspawnable._default_assignee = (default_assignee or "").strip() or Noneif _default_assignee:try:@@ -2139,9 +1894,8 @@ def _dispatch_once_locked(breakrow_assignee = row["assignee"]if not row_assignee:- # Honour kanban.default_assignee so a task created without an- # assignee doesn't park in 'ready' forever when the operator's- # intent ("default") was clear.+ # Honour kanban.default_assignee so an unassigned task doesn't+ # park in 'ready' forever.if not _default_assignee or not _apply_default_assignee(conn, row["id"], _default_assignee, dry_run=dry_run,):@@ -2158,13 +1912,10 @@ def _dispatch_once_locked(spawned += 1# ---- review column dispatch ----- # A worker moved the task to 'review' after creating a PR; the dispatcher- # spawns a review agent (sdlc-review skill) that approves (→ done) or- # requests changes (→ ready/todo for the implementer). Review spawns share- # max_spawn with ready tasks so total running workers stay bounded; enabled- # by default, disable with ``kanban.review_dispatch`` for human-only boards.- # The review loop checks the FULL shared ``spawn_budget`` — the- # reservation above caps the ready lane, it grants no extra capacity here.+ # A review agent (sdlc-review) approves (→ done) or requests changes+ # (→ ready/todo). Review spawns share max_spawn with ready tasks. The loop+ # checks the FULL shared ``spawn_budget`` — the reservation above caps the+ # ready lane, it grants no extra capacity here.for row in review_rows:if spawn_budget is not None and spawned >= spawn_budget:break@@ -2191,10 +1942,8 @@ def _positive_int(value: Any, default: int, *, minimum: int = 1) -> int:def worker_log_rotation_config(kanban_cfg: Optional[dict] = None) -> tuple[int, int]:"""Return ``(rotate_bytes, backup_count)`` for worker log rotation.-- Defaults preserve the historical behavior: rotate at 2 MiB and keep one- backup generation (``.log.1``). Operators with long-running workers can- raise either value from ``config.yaml`` without changing dispatcher code.+ Defaults: rotate at 2 MiB, keep one backup (``.log.1``); both overridable+ from ``config.yaml``."""if kanban_cfg is None:try:@@ -2225,11 +1974,8 @@ def _rotate_worker_log(max_bytes: int,backup_count: int = DEFAULT_LOG_BACKUP_COUNT,) -> None:- """Rotate ``<log>`` when it exceeds ``max_bytes``.-- ``backup_count=1`` preserves the legacy single-generation behavior:- ``<log>`` moves to ``<log>.1`` and any previous ``.1`` is replaced.- Higher values shift older generations up to ``backup_count``.+ """Rotate ``<log>`` when it exceeds ``max_bytes``: ``<log>`` → ``<log>.1``,+ older generations shift up to ``backup_count``."""try:if not log_path.exists():@@ -2263,8 +2009,7 @@ def _rotate_worker_log(def _module_hermes_argv() -> list[str]:"""Return the interpreter-bound Hermes CLI invocation."""- # ``hermes_cli.main`` is the console-script target declared in- # pyproject.toml, NOT a top-level ``hermes`` package — there is no+ # ``hermes_cli.main`` is the console-script target — there is no top-level# ``hermes`` package to import.return [sys.executable, "-m", "hermes_cli.main"]@@ -2304,10 +2049,9 @@ def _path_search_names(command: str) -> list[str]:def _safe_which_no_cwd(command: str) -> Optional[str]:"""Resolve a bare command from PATH without implicit current-dir search.- ``shutil.which`` follows platform search behavior. On Windows that can- include the current directory before PATH for bare names, which is not a- safe dispatcher primitive. This resolver only considers explicit PATH- entries and skips empty / ``.`` entries.+ On Windows ``shutil.which`` may search the current directory before PATH+ for bare names — unsafe for a dispatcher. Only explicit PATH entries are+ considered; empty / ``.`` entries are skipped."""path_env = os.environ.get("PATH", "")for raw_dir in path_env.split(os.pathsep):@@ -2326,10 +2070,8 @@ def _safe_which_no_cwd(command: str) -> Optional[str]:def _hermes_path_argv(path: str) -> list[str]:"""Return argv for a resolved Hermes executable path.- Windows batch shims (`.cmd` / `.bat`) are not safe as argv[0] for- worker launches because the argument vector includes task-derived- values. Prefer the interpreter-bound module form whenever the resolved- executable is only a shell shim.+ Windows batch shims (`.cmd` / `.bat`) are unsafe as argv[0] because the+ argument vector includes task-derived values; prefer the module form."""if _kb._IS_WINDOWS and _is_windows_batch_shim(path):return _module_hermes_argv()@@ -2339,26 +2081,15 @@ def _hermes_path_argv(path: str) -> list[str]:def _resolve_hermes_argv() -> list[str]:"""Resolve the ``hermes`` invocation as argv parts for ``Popen``.- Tries in order:-- 1. ``$HERMES_BIN`` — explicit operator override. Path-like values are- normalized to absolute paths; bare command names keep normal PATH- semantics and never prefer a same-directory file before ``PATH``.- 2. ``shutil.which("hermes")`` — the console-script shim, normalized to- an absolute path. On Windows, ``which`` can return a relative- ``.\\hermes.CMD`` when the current directory is on ``PATH``; directly- launching batch shims is also unsafe with task-derived argv. The- dispatcher therefore falls back to the interpreter-bound module form- for implicit ``.cmd`` / ``.bat`` shims.- 3. ``sys.executable -m hermes_cli.main`` — fallback for setups where- Hermes is launched from a venv and the ``hermes`` shim is not on- the dispatcher's ``$PATH`` (cron, systemd ``User=`` services,- launchd jobs, detached processes, etc.). Goes through the running- interpreter so the result is independent of ``$PATH``.-- Mirrors ``gateway.run._resolve_hermes_bin`` for the same reason. Kept- local (not imported from gateway) because ``hermes_cli`` sits below- ``gateway`` in the dependency order.+ Tries in order: ``$HERMES_BIN`` (path-like values normalized to absolute;+ bare names keep PATH semantics, never a same-directory file first);+ ``shutil.which("hermes")`` normalized to absolute (on Windows ``which`` can+ return a relative ``.\\hermes.CMD`` when cwd is on PATH, and batch shims are+ unsafe with task-derived argv, so those fall back to the module form);+ ``sys.executable -m hermes_cli.main`` for setups where the shim is not on+ the dispatcher's ``$PATH`` (cron, systemd ``User=`` services, launchd).+ Mirrors ``gateway.run._resolve_hermes_bin``; kept local because+ ``hermes_cli`` sits below ``gateway`` in the dependency order."""import shutil@@ -2383,10 +2114,9 @@ def _worker_terminal_timeout_env() -> Optional[str]:"""Return a worker-scoped TERMINAL_TIMEOUT override, if needed.- Kanban's ``max_runtime_seconds`` bounds the whole worker attempt. The- terminal tool has its own default timeout via ``TERMINAL_TIMEOUT``; when- the worker runtime is longer, raise only the child process default so a- long command is not killed by the generic terminal default first.+ When ``max_runtime_seconds`` exceeds the terminal tool's default timeout,+ raise only the child's default so a long command isn't killed by the+ generic terminal default first."""if max_runtime_seconds is None:return None@@ -2410,13 +2140,11 @@ def _worker_terminal_timeout_env(def _resolve_worker_cli_toolsets(hermes_home: Optional[str]) -> Optional[list[str]]:"""Return the assigned profile's effective CLI toolsets for a worker.- Dispatcher-spawned workers are launched from a long-lived gateway process,- then the child re-enters the CLI with ``-p <assignee>``. Resolve the- assignee profile's CLI tool surface at dispatch time and pass it as an- explicit ``--toolsets`` pin so worker startup cannot fall back to a stale- root/active-profile config or a profile whose top-level ``toolsets`` entry- is only the kanban orchestrator surface. ``model_tools`` still appends the- task-scoped kanban lifecycle tools when ``HERMES_KANBAN_TASK`` is set.+ Resolved at dispatch time and passed as an explicit ``--toolsets`` pin so+ worker startup cannot fall back to a stale root/active-profile config or a+ profile whose top-level ``toolsets`` is only the kanban orchestrator+ surface. ``model_tools`` still appends the task-scoped kanban lifecycle+ tools when ``HERMES_KANBAN_TASK`` is set."""if not hermes_home:return None@@ -2447,10 +2175,10 @@ _retagged_workspace_roots: set[str] = set()def _retag_legacy_worker_sessions(workspaces_root_path: str) -> None:"""Reclaim pre-tag worker rows in state.db so they leave the session lists.- Best-effort and gated — the durable ``state_meta`` gate lives in- ``retag_kanban_worker_sessions``; the in-process set keeps a busy- dispatcher from reopening state.db on every spawn just to read it. A- dispatcher tick must never fail because a session DB was busy or missing.+ Best-effort: the durable gate is ``state_meta`` in+ ``retag_kanban_worker_sessions``; the in-process set avoids reopening+ state.db on every spawn. A tick must never fail because a session DB was+ busy or missing."""if workspaces_root_path in _retagged_workspace_roots:return@@ -2475,15 +2203,11 @@ def _default_spawn() -> Optional[int]:"""Fire-and-forget ``hermes -p <profile> chat -q ...`` subprocess.- Returns the spawned child's PID so the dispatcher can detect crashes- before the claim TTL expires. The child's completion is still observed- via the ``complete`` / ``block`` transitions the worker writes itself;- the PID check is a safety net for crashes, OOM kills, and Ctrl+C.-- ``board`` pins the child's kanban context to that board: the child's- ``HERMES_KANBAN_DB`` / ``HERMES_KANBAN_BOARD`` / workspaces_root env- vars all resolve to the same board the dispatcher claimed the task- from. Workers cannot accidentally see other boards.+ Returns the child's PID so the dispatcher can detect crashes before the+ claim TTL expires; completion is still observed via the worker's own+ ``complete`` / ``block`` transitions. ``board`` pins the child's+ ``HERMES_KANBAN_DB`` / ``HERMES_KANBAN_BOARD`` / workspaces_root to the+ board the task was claimed from, so workers cannot see other boards."""import subprocessif not task.assignee:@@ -2495,17 +2219,16 @@ def _default_spawn(prompt = f"work kanban task {task.id}"env = dict(os.environ)- # The dispatcher is detached from every conversation. Its worker must never- # inherit routing mirrored by a previous gateway turn, even before the first- # session binds ContextVars in this process.+ # The dispatcher is detached from every conversation; its worker must never+ # inherit routing mirrored by a previous gateway turn.from gateway.session_context import _VAR_MAPfor key in _VAR_MAP:env.pop(key, None)- # Inject HERMES_HOME so the worker reads the profile-scoped config.yaml- # (fallback_providers, toolsets, ...). Without it the child's- # get_hermes_home() falls back to the DEFAULT profile root because- # `hermes -p` applies its override before hermes_constants is imported.+ # Inject HERMES_HOME so the worker reads the profile-scoped config.yaml:+ # without it the child's get_hermes_home() falls back to the DEFAULT+ # profile root because `hermes -p` applies its override before+ # hermes_constants is imported.from hermes_cli.profiles import resolve_profile_envtry:env["HERMES_HOME"] = resolve_profile_env(profile_arg)@@ -2517,16 +2240,13 @@ def _default_spawn(env["HERMES_TENANT"] = task.tenantenv["HERMES_KANBAN_TASK"] = task.idenv["HERMES_KANBAN_WORKSPACE"] = workspace- # Tag the session as `kanban` (not an untitled `cli` row): a worker is a- # dispatcher-owned run read on the board / `hermes kanban log`, so every- # session-browsing surface filters it out by source instead of rendering- # one sidebar row per attempt.+ # Tag the session `kanban` so session-browsing surfaces filter it out by+ # source instead of rendering one sidebar row per attempt.env["HERMES_SESSION_SOURCE"] = "kanban"- # Pin TERMINAL_CWD to the workspace: it takes precedence over the process- # cwd in file_tools._resolve_base_dir and build_context_files_prompt, so- # without it relative writes land in the gateway user's home and workers- # load the gateway's AGENTS.md. Only a real absolute directory — file_tools- # rejects relative / sentinel values, so leave the inherited value otherwise.+ # TERMINAL_CWD takes precedence over process cwd in file_tools and+ # build_context_files_prompt; without it relative writes land in the gateway+ # user's home and workers load the gateway's AGENTS.md. file_tools rejects+ # relative / sentinel values, so only set a real absolute directory.if workspace and os.path.isabs(workspace) and os.path.isdir(workspace):env["TERMINAL_CWD"] = workspaceif task.branch_name:@@ -2535,9 +2255,8 @@ def _default_spawn(env["HERMES_KANBAN_RUN_ID"] = str(task.current_run_id)if task.claim_lock:env["HERMES_KANBAN_CLAIM_LOCK"] = task.claim_lock- # Goal-loop mode: the worker reads these and wraps its run in the- # Ralph-style /goal judge loop (see cli.py quiet-mode path). Only set- # when enabled so non-goal tasks keep a clean env.+ # Goal-loop mode (Ralph-style /goal judge loop in cli.py quiet-mode path).+ # Only set when enabled so non-goal tasks keep a clean env.if task.goal_mode:env["HERMES_KANBAN_GOAL_MODE"] = "1"if task.goal_max_turns is not None:@@ -2554,14 +2273,13 @@ def _default_spawn()if foreground_timeout is not None:env["TERMINAL_MAX_FOREGROUND_TIMEOUT"] = foreground_timeout- # Pin the board DB + workspaces root the dispatcher resolved so the- # worker's kanban paths still match after `hermes -p` rewrites- # HERMES_HOME (belt-and-braces for symlink / Docker layouts).+ # Pin the board DB + workspaces root so the worker's kanban paths still+ # match after `hermes -p` rewrites HERMES_HOME (symlink / Docker layouts).env["HERMES_KANBAN_DB"] = str(_kb.kanban_db_path(board=board))env["HERMES_KANBAN_WORKSPACES_ROOT"] = str(_kb.workspaces_root(board=board))_kb._retag_legacy_worker_sessions(env["HERMES_KANBAN_WORKSPACES_ROOT"])- # Board slug — final defense-in-depth pin if a path is ever resolved- # without the DB / workspaces env vars.+ # Board slug — defense-in-depth pin if a path is resolved without the+ # DB / workspaces env vars.resolved_board = _kb._normalize_board_slug(board) or _kb.get_current_board()env["HERMES_KANBAN_BOARD"] = resolved_board# kanban_comment reads HERMES_PROFILE for its default author; `-p` alone@@ -2578,32 +2296,25 @@ def _default_spawn(*_kb._resolve_hermes_argv(),"-p", profile_arg,"--cli",- # Worker subprocesses switch to a profile-scoped HERMES_HOME above,- # so they see that profile's shell-hook allowlist instead of the- # dispatcher's root allowlist. Pass --accept-hooks explicitly so- # profile-local worker sessions still register configured hooks.+ # Workers run under a profile-scoped HERMES_HOME and so see that+ # profile's shell-hook allowlist; pass --accept-hooks explicitly so+ # configured hooks still register."--accept-hooks",]- # Per-task force-loaded skills. Each name goes in its own- # `--skills X` pair rather than a single comma-joined arg: the CLI- # accepts both forms (action='append' + comma-split), but- # per-name pairs are easier to read in `ps` output and avoid any- # quoting ambiguity if a skill name ever contains unusual chars.+ # One `--skills X` pair per name: easier to read in `ps` and avoids quoting+ # ambiguity if a skill name contains unusual chars.if task.skills:for sk in task.skills:if sk:cmd.extend(["--skills", sk])if task.model_override:cmd.extend(["-m", task.model_override])- # Pin the provider too when the override names one, so the worker- # resolves the model against the intended backend instead of the- # profile's configured provider (mixing model X with provider Y is- # the classic mis-set that stalls a board).+ # Pin the provider too so the worker resolves the model against the+ # intended backend (model X with provider Y is the classic board-stall).if task.provider_override:cmd.extend(["--provider", task.provider_override])- # Per-task thinking depth. Independent of the model override — a task can- # run the profile's own model at a different depth — so this is its own- # branch, not a nested one.+ # Independent of the model override — a task can run the profile's own+ # model at a different depth.if task.reasoning_effort:cmd.extend(["--reasoning", task.reasoning_effort])worker_toolsets = _resolve_worker_cli_toolsets(env.get("HERMES_HOME"))@@ -2614,16 +2325,12 @@ def _default_spawn("-q", prompt,])if task.goal_mode:- # Goal-mode workers must take the fully-quiet single-query path:- # the kanban goal-loop hook (_run_kanban_goal_loop_q) only runs in- # cli.py's quiet branch. Without -Q the worker gets exactly one- # turn, prints text, exits rc=0, and the dispatcher records a- # protocol violation (incident 2026-06-09 t_d9cbe312).+ # The kanban goal-loop hook only runs in cli.py's fully-quiet branch.+ # Without -Q the worker gets one turn, prints text, exits rc=0, and the+ # dispatcher records a protocol violation.cmd.append("-Q")- # Redirect output to a per-task log under <board-root>/logs/.- # Anchored at the board root (not the shared kanban root), so- # `hermes kanban log` on a specific board reads its own file and- # logs don't collide across boards that happen to share task ids.+ # Per-task log anchored at the board root (not the shared kanban root) so+ # `hermes kanban log` reads its own file and boards sharing task ids don't collide.log_dir = _kb.worker_logs_dir(board=board)log_dir.mkdir(parents=True, exist_ok=True)log_path = log_dir / f"{task.id}.log"@@ -2649,11 +2356,8 @@ def _default_spawn("`hermes` executable not found on PATH. ""Install Hermes Agent or activate its venv before running the kanban dispatcher.")- # NOTE: we intentionally do NOT close log_f here — we want Popen's- # child process to keep writing after this function returns. The- # handle is kept alive by the child's inheritance. The parent's- # reference goes out of scope and is GC'd, but the OS-level FD stays- # open in the child until the child exits.+ # Intentionally NOT closing log_f: the child keeps writing after return;+ # the OS-level FD stays open in the child until it exits.return proc.pid@@ -2671,15 +2375,11 @@ def run_daemon() -> None:"""Run the dispatcher in a loop until interrupted.- Calls :func:`dispatch_once` every ``interval`` seconds. Exits cleanly- on SIGINT / SIGTERM so ``hermes kanban daemon`` is systemd-friendly.- ``stop_event`` (a :class:`threading.Event`) and ``on_tick`` (a- callable receiving the :class:`DispatchResult`) are test hooks.-- Each tick resolves ``kanban.max_in_progress`` (explicit config, else- the memory-derived default) exactly like the gateway-embedded- dispatcher and ``hermes kanban dispatch`` — the standalone daemon must- not be the one uncapped entry point (OOF-30).+ Calls :func:`dispatch_once` every ``interval`` seconds; exits cleanly on+ SIGINT / SIGTERM so it is systemd-friendly. ``stop_event`` and ``on_tick``+ are test hooks. Each tick resolves ``kanban.max_in_progress`` exactly like+ the gateway dispatcher and ``hermes kanban dispatch`` — the standalone+ daemon must not be the one uncapped entry point."""import signalimport threading@@ -2690,8 +2390,8 @@ def run_daemon(def _handle(_signum, _frame):stop_event.set()- # Install handlers only when running on the main thread — tests call- # this inline from worker threads and signal() would raise there.+ # Install handlers only on the main thread — tests call this inline from+ # worker threads and signal() would raise there.if threading.current_thread() is threading.main_thread():for sig_name in ("SIGINT", "SIGTERM"):sig = getattr(signal, sig_name, None)@@ -2701,14 +2401,8 @@ def run_daemon(while not stop_event.is_set():try:- # Resolve the global concurrency cap the same way the gateway- # dispatcher and `hermes kanban dispatch` do (OOF-30): explicit- # kanban.max_in_progress wins, otherwise the memory-derived- # default applies. The standalone daemon previously passed no- # cap at all — the shipped systemd path could still fan out an- # entire backlog in one tick even with the derived default in- # place everywhere else. Re-resolved every tick (config load is- # mtime-cached) so operator edits apply without a restart.+ # Re-resolved every tick (config load is mtime-cached) so operator+ # edits apply without a restart.max_in_progress = resolve_max_in_progress(_kb.configured_max_in_progress())diff --git a/hermes_cli/kanban_db_notify.py b/hermes_cli/kanban_db_notify.pyindex e969f2eb29b..7a5151fd0ce 100644--- a/hermes_cli/kanban_db_notify.py+++ b/hermes_cli/kanban_db_notify.py@@ -25,11 +25,8 @@ if TYPE_CHECKING:# Notification subscriptions (used by the gateway kanban-notifier)# ----------------------------------------------------------------------------# How the gateway kanban-notifier reacts to a terminal event for a-# subscription:-# "notify" -> passive ``adapter.send`` only (default)-# "notify+wake" -> passive send AND wake the destination gateway agent-# "wake" -> wake the agent only; no passive message is sent+# Notifier reaction to a terminal event: "notify" = passive adapter.send only+# (default); "notify+wake" = send AND wake the destination agent; "wake" = wake only._NOTIFY_DELIVERY_MODES = ("notify", "notify+wake", "wake")@@ -82,40 +79,26 @@ def add_notify_sub(delivery_mode: Optional[str] = None,delivery_metadata: Optional[Mapping[str, Any]] = None,) -> None:- """Register a gateway source that wants terminal-state notifications- for ``task_id``. Idempotent on (task, platform, chat, thread).-- ``user_id_alt`` records the originating source's platform-specific stable- alt ID (Signal UUID, Feishu union_id, ...) alongside ``user_id``. Active-wake- replay must reproduce it so the woken turn's ``build_session_key`` matches- the original event's — ``build_session_key`` prefers ``user_id_alt`` over- ``user_id`` (gateway/session.py), so replaying only ``user_id`` would key a- wake into a different session whenever the two diverge for this source.-- ``chat_type`` records the originating source's chat type; the active-wake- delivery modes replay it so the woken turn resolves the operator's real- channel. ``None`` keeps an existing row's value.-- ``delivery_mode`` (see ``_NOTIFY_DELIVERY_MODES``) selects how the- kanban-notifier reacts to a terminal event for this subscription. ``None``- leaves an existing row's mode untouched (and inserts the ``"notify"``- default for a fresh row); an explicit value is last-write-wins, so an- operator can intentionally re-subscribe to change the mode (e.g.- ``notify`` -> ``wake``). An unknown value falls back to ``"notify"``.- New subscriptions start "caught up": ``last_event_id`` snaps to the task's- current ``MAX(task_events.id)`` instead of the schema default 0, which made- the notifier replay every historical terminal event on its next tick (a- boot-time burst of 100+ messages with many stale subs). Subscribers only- want events AFTER they subscribe; auto-subscribe at task creation snapshots- 0 anyway.+ """Register a gateway source wanting terminal-state notifications for+ ``task_id``. Idempotent on (task, platform, chat, thread).++ ``user_id_alt`` (Signal UUID, Feishu union_id, ...) must be replayed on+ active wake: ``build_session_key`` prefers it over ``user_id``, so replaying+ only ``user_id`` would key the wake into a different session when they+ diverge. ``chat_type`` is likewise replayed so the woken turn resolves the+ operator's real channel; ``None`` keeps an existing row's value.++ ``delivery_mode`` (``_NOTIFY_DELIVERY_MODES``): ``None`` leaves an existing+ row untouched (fresh rows get ``"notify"``); an explicit value is+ last-write-wins so re-subscribing can change the mode; unknown values fall+ back to ``"notify"``. New subs start "caught up" (``last_event_id`` =+ current ``MAX(task_events.id)``, not 0) — otherwise the notifier replays+ every historical terminal event on its next tick (boot-time bursts)."""insert_mode = delivery_mode if delivery_mode in _NOTIFY_DELIVERY_MODES else (- # api_server is stateless: the adapter has no send() — the wake- # self-post IS the delivery on that path (see gateway/wake.py and- # test_kanban_notifier_apiserver_wake). A plain-'notify' default- # would leave those subscriptions with no delivery mechanism at- # all, regressing the pre-delivery_mode behavior where a task- # carrying a session_id always woke. Explicit modes still win.+ # api_server is stateless: the adapter has no send(), the wake self-post+ # IS the delivery. A plain 'notify' default would leave those subs with+ # no delivery mechanism at all. Explicit modes still win."notify+wake" if platform == "api_server" else "notify")insert_chat_type = chat_type or "dm"@@ -146,9 +129,8 @@ def add_notify_sub(task_id,),)- # Re-subscribe semantics per column: chat_type / delivery_mode /- # delivery_metadata are last-write-wins; user_id_alt and- # notifier_profile only self-heal legacy rows that never had one.+ # chat_type / delivery_mode / delivery_metadata are last-write-wins;+ # user_id_alt and notifier_profile only self-heal legacy rows lacking one.key = (task_id, platform, chat_id, thread_id or "")for column, value, fill_only in (("chat_type", chat_type, False),@@ -207,10 +189,9 @@ def list_notify_subs() -> list[dict]:"""List subscriptions, optionally restricted to notifier profile owners.- Passing no ``notifier_profiles`` preserves the historical all-subscriptions- result. Gateway notifier processes pass the profiles whose adapters they- own so they cannot claim another gateway's events. ``include_unowned`` is- used by the dispatch owner for legacy rows created before profile stamping.+ No ``notifier_profiles`` -> all subscriptions. Gateway notifiers pass the+ profiles they own so they cannot claim another gateway's events;+ ``include_unowned`` (dispatch owner) covers legacy rows without a stamp."""owner_where, owner_params = _notify_profile_filter(notifier_profiles, include_unowned=include_unowned,@@ -250,23 +231,15 @@ def count_notify_subs() -> int:"""Count ``kanban_notify_subs`` rows via a read-only connection.- Cheap probe for the gateway notifier's zero-subscription early exit:- unlike :func:`connect`, this never creates the DB file, never runs- schema init/migration, and never opens the database writable (no- write locks, no checkpoints — though a read-only open of a WAL- database may still create the ``-shm``/``-wal`` sidecars, it cannot- write table content). Rows in a not-yet-checkpointed WAL are- visible, so a freshly added subscription is never missed. A missing- DB, or a legacy DB that predates the subscriptions table, counts as- zero. When ``notifier_profiles`` is supplied, only subscriptions owned- by those profiles are counted; ``include_unowned`` also includes legacy- rows without an owner stamp. Optional platform/chat/thread filters narrow- the probe to one notification owner without changing the unfiltered count.- Platform matching is case-insensitive, matching notifier routing; chat and- thread identifiers are exact. Path resolution matches :func:`connect`- (explicit ``db_path``, else ``board`` via :func:`kanban_db_path`). Raises- :class:`sqlite3.Error` when the DB exists but cannot be read- (locked, corrupt); callers choose their own fallback.+ Cheap probe for the notifier's zero-subscription early exit: unlike+ :func:`connect` it never creates the DB file, runs schema init/migration,+ or opens writable (a read-only WAL open may still create ``-shm``/``-wal``+ sidecars but cannot write table content). Rows in a not-yet-checkpointed+ WAL are visible, so a fresh subscription is never missed. A missing DB or+ a legacy DB without the table counts as zero. Platform matching is+ case-insensitive (matching notifier routing); chat/thread are exact.+ Path resolution matches :func:`connect`. Raises :class:`sqlite3.Error`+ when the DB exists but cannot be read; callers choose their own fallback."""path = db_path if db_path is not None else _kb.kanban_db_path(board=board)if not path.exists():@@ -326,26 +299,17 @@ def purge_stale_done_notify_subs(*,max_age_days: int = 30,) -> int:- """Delete notify subscriptions whose task has sat in ``done`` or- ``blocked`` untouched for longer than ``max_age_days``.-- The notifier keeps subscriptions alive through ``done`` because a- completed task can be reopened (review corrections, continuation) and- the reopened cycle must still notify its origin session. On boards- that never archive, that retention would otherwise accumulate- subscription rows forever — each one scanned every notifier tick.- This GC bounds that: a task that has been ``done`` with no new events- for the retention window is treated as settled and its subscriptions- are purged. ``blocked`` tasks (circuit-breaker trips, dead workers)- are reaped on the same clock — they are abandoned, not idle, unlike a- ``backlog``/``ready`` card that is merely waiting for pickup (#100955).- Age is measured from the task's most recent event- (falling back to ``completed_at`` then ``created_at``), so ANY- activity — including a reopen, which also moves the task off- ``done`` — resets or exempts it.-- ``max_age_days <= 0`` disables the sweep entirely. Returns the number- of subscription rows deleted.+ """Delete notify subs whose task has sat in ``done``/``blocked`` untouched+ for longer than ``max_age_days``.++ Subs survive ``done`` because a completed task can be reopened and must+ still notify its origin; on never-archiving boards that would accumulate+ rows forever, each scanned every notifier tick. ``blocked`` tasks are+ reaped on the same clock — they are abandoned, not merely waiting like+ ``backlog``/``ready``. Age is measured from the most recent event+ (falling back to ``completed_at`` then ``created_at``), so ANY activity —+ including a reopen — resets or exempts it. ``max_age_days <= 0`` disables+ the sweep. Returns the number of rows deleted."""try:days = int(max_age_days)@@ -390,11 +354,8 @@ def unseen_events_for_sub(thread_id: Optional[str] = None,kinds: Optional[Iterable[str]] = None,) -> tuple[int, list[Event]]:- """Return ``(new_cursor, events)`` for a given subscription.-- Only events with ``id > last_event_id`` are returned. The subscription's- cursor is NOT advanced here; call :func:`advance_notify_cursor` after- the gateway has successfully delivered the notifications.+ """Return ``(new_cursor, events)`` with ``id > last_event_id``. The cursor+ is NOT advanced here; call :func:`advance_notify_cursor` after delivery."""cursor = _notify_cursor(conn, task_id, platform, chat_id, thread_id)if cursor is None:@@ -426,19 +387,14 @@ def claim_unseen_events_for_sub(thread_id: Optional[str] = None,kinds: Optional[Iterable[str]] = None,) -> tuple[int, int, list[Event]]:- """Atomically claim unseen notification events for one subscription.-- Returns ``(old_cursor, new_cursor, events)``. When events are returned,- ``kanban_notify_subs.last_event_id`` has already been advanced to- ``new_cursor`` inside a ``BEGIN IMMEDIATE`` transaction. That makes the- notifier's read/claim step single-owner across multiple gateway watcher- processes pointed at the same board DB: concurrent watchers serialize on- SQLite's writer lock, and only the first process sees and claims a given- event range.-- Callers should send the claimed events, then either leave the cursor at- ``new_cursor`` on success or call :func:`rewind_notify_cursor` if delivery- failed before any terminal unsubscribe removed the row.+ """Atomically claim unseen events for one subscription.++ Returns ``(old_cursor, new_cursor, events)``; when events are returned the+ row's ``last_event_id`` has already been advanced inside ``BEGIN IMMEDIATE``,+ so concurrent gateway watchers on the same board DB serialize on SQLite's+ writer lock and only the first claims a given event range. Callers send the+ events, then leave the cursor or call :func:`rewind_notify_cursor` on+ delivery failure."""with _kb.write_txn(conn):old_cursor = _notify_cursor(conn, task_id, platform, chat_id, thread_id)@@ -490,11 +446,8 @@ def rewind_notify_cursor(claimed_cursor: int,old_cursor: int,) -> bool:- """Undo a notification claim when delivery fails.-- The CAS guard only rewinds if no later notifier advanced the row after our- claim. This keeps retry behavior for transient send failures without- clobbering newer progress.+ """Undo a claim when delivery fails. The CAS guard only rewinds if no later+ notifier advanced the row, so retries never clobber newer progress."""with _kb.write_txn(conn):cur = conn.execute(diff --git a/hermes_cli/kanban_db_workspace.py b/hermes_cli/kanban_db_workspace.pyindex d18bec16d11..87ca776bd3b 100644--- a/hermes_cli/kanban_db_workspace.py+++ b/hermes_cli/kanban_db_workspace.py@@ -85,27 +85,17 @@ def _scratch_workspace(conn: sqlite3.Connection, task_id: str) -> Optional[Path]def _is_managed_scratch_path(p: Path) -> bool:"""Return True iff *p* is a strict descendant of a kanban-managed scratch root.- A managed root is exclusively a ``workspaces/`` directory — never the- broader kanban home, a board root, or sibling subtrees like ``logs/`` or- ``boards/<slug>/`` itself. Allowed roots:-- * ``HERMES_KANBAN_WORKSPACES_ROOT`` when set (worker-side override- injected by the dispatcher).- * ``<kanban_home>/kanban/workspaces`` — legacy default-board scratch root.- * ``<kanban_home>/kanban/boards/<slug>/workspaces`` for each board slug- that currently exists on disk.-- The check requires strict descendancy: a path equal to one of these- roots is NOT managed (deleting the workspaces root would wipe every- task's scratch dir at once), and a path that resolves to ``<kanban_home>- /kanban`` itself, ``<kanban_home>/kanban/logs``, or- ``<kanban_home>/kanban/boards/<slug>`` is rejected because those- subtrees hold Hermes' own DB, metadata, and logs, not task workspaces.-- Used by :func:`_cleanup_workspace` to refuse to ``shutil.rmtree`` paths- outside Hermes-managed storage. A board ``default_workdir`` pointing at a- real source tree can otherwise pair with ``workspace_kind='scratch'`` and- cause task completion to delete user data (#28818).+ A managed root is exclusively a ``workspaces/`` directory:+ ``HERMES_KANBAN_WORKSPACES_ROOT`` (dispatcher-injected worker override),+ ``<kanban_home>/kanban/workspaces`` (legacy default board), or+ ``<kanban_home>/kanban/boards/<slug>/workspaces`` per on-disk board.+ Strict descendancy: a path EQUAL to a root is not managed (deleting it+ would wipe every task's scratch dir), and ``<kanban_home>/kanban``,+ ``.../logs`` or ``.../boards/<slug>`` are rejected because they hold+ Hermes' own DB, metadata and logs. :func:`_cleanup_workspace` uses this to+ refuse ``shutil.rmtree`` outside managed storage — a board+ ``default_workdir`` pointing at a real source tree can otherwise pair with+ ``workspace_kind='scratch'`` and make task completion delete user data."""is_managed, _board = _managed_scratch_path_info(p)return is_managed@@ -113,13 +103,10 @@ def _is_managed_scratch_path(p: Path) -> bool:def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:"""Remove a task's scratch workspace dir and kill its stale tmux session.-- Called from :func:`complete_task` after the DB transaction commits.- Best-effort — any error is swallowed so cleanup never blocks task completion.- ``scratch`` workspaces are removed; ``worktree`` workspaces are removed only- when provably free of work (clean tree, every commit reachable from a- remote-tracking ref); ``dir`` workspaces are intentionally preserved.- """+ Called from :func:`complete_task` after the transaction commits; best-effort+ so cleanup never blocks completion. ``scratch`` is removed; ``worktree``+ only when provably free of work (clean tree, every commit reachable from a+ remote-tracking ref); ``dir`` is intentionally preserved."""try:row = conn.execute("SELECT workspace_kind, workspace_path, branch_name FROM tasks WHERE id = ?",@@ -130,14 +117,12 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:kind: Optional[str] = row["workspace_kind"]path: Optional[str] = row["workspace_path"]if kind not in ("scratch", "worktree") or not path:- # This task's own workspace isn't a removable scratch dir, but its- # completion may still unblock a deferred parent scratch cleanup- # (e.g. a 'dir' child whose scratch parent was waiting on it). #33774+ # Not removable itself, but completing may still unblock a deferred+ # parent scratch cleanup (e.g. a 'dir' child of a scratch parent)._try_cleanup_parent_workspaces(conn, task_id)return- # 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).+ # Defer while any child is not yet terminal so it can still read+ # handoff artifacts from this workspace._active_children = conn.execute("SELECT 1 FROM task_links l ""JOIN tasks t ON t.id = l.child_id "@@ -153,9 +138,8 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:)returnif kind == "worktree":- # Kill the (dead) tmux worker session BEFORE removing the- # worktree so a lingering worker never has its cwd deleted out- # from under it. Both steps stay best-effort.+ # Kill the (dead) tmux worker session BEFORE removing the worktree+ # so a lingering worker never has its cwd deleted from under it._cleanup_worker_tmux(conn, task_id)_cleanup_worktree_workspace(task_id, path, row["branch_name"])_try_cleanup_parent_workspaces(conn, task_id)@@ -163,11 +147,9 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:import shutilwp = Path(path)if wp.is_dir():- # Containment guard (#28818): a board's ``default_workdir`` can- # pair ``workspace_kind='scratch'`` with a user-supplied path- # pointing at a real source tree. Without this check, task- # completion would unconditionally ``shutil.rmtree`` that path- # and silently delete the user's source data.+ # Containment guard: a board's ``default_workdir`` can pair+ # ``workspace_kind='scratch'`` with a user path pointing at a real+ # source tree; without this, completion would rmtree the user's data.if _is_managed_scratch_path(wp):shutil.rmtree(wp, ignore_errors=True)_kb._log.debug("Removed scratch workspace: %s", wp)@@ -178,12 +160,9 @@ def _cleanup_workspace(conn: sqlite3.Connection, task_id: str) -> None:"kanban-managed workspaces root)",task_id, wp,)- # Also kill the tmux session for the worker that owned this task,- # if the tmux session is now dead (worker process exited).+ # Kill the owning worker's tmux session if it is now dead, then let any+ # parent whose children are all done run its deferred cleanup._cleanup_worker_tmux(conn, task_id)- # After cleaning up this task's workspace, check if any parent- # tasks now have all children done — their deferred cleanup can- # proceed (#33774)._try_cleanup_parent_workspaces(conn, task_id)except Exception:pass # best-effort — never block completion@@ -193,14 +172,11 @@ def _cleanup_worktree_workspace(task_id: str, path: str, branch_name: Optional[str] = None) -> None:"""Remove a finished task's linked git worktree when it holds no work.-- Mirrors the safety judgment of the CLI startup pruner- (``cli._prune_stale_worktrees``): removal requires a clean working tree- AND every commit reachable from a remote-tracking ref. Any doubt — dirty- files, unpushed commits, unresolvable repo, failing git — preserves the- worktree. The task's auto-generated ``wt/<task-id>`` branch is deleted- with it; custom branches are kept. Best-effort like the scratch path.- """+ Mirrors the CLI startup pruner (``cli._prune_stale_worktrees``): removal+ requires a clean tree AND every commit reachable from a remote-tracking+ ref; any doubt (dirty, unpushed, unresolvable repo, failing git) preserves+ it. The auto-generated ``wt/<task-id>`` branch is deleted with it; custom+ branches are kept. Best-effort."""try:from cli import _worktree_has_unpushed_commits, _worktree_is_dirtyexcept Exception:@@ -221,10 +197,8 @@ def _cleanup_worktree_workspace(task_id, wp,)return- # No --force: the dirty/unpushed checks above run before removal, so- # git's own dirty guard re-verifies at removal time. If the tree- # became dirty between our check and the removal (TOCTOU), removal- # fails safe and the worktree is preserved.+ # No --force: git's own dirty guard re-verifies at removal time, so if+ # the tree became dirty since our check (TOCTOU) removal fails safe.result = subprocess.run(["git", "-C", str(repo_root), "worktree", "remove", str(wp)],capture_output=True,@@ -253,13 +227,9 @@ def _cleanup_worktree_workspace(def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> None:- """Clean up parent scratch workspaces now that *task_id* completed.-- When a parent task's cleanup was deferred because it had active children,- this function is called after each child completes. If all children of a- parent are now done/archived/failed/cancelled, the parent's scratch- workspace is removed (#33774).- """+ """Run the deferred cleanup of any parent scratch/worktree workspace whose+ children are now all done/archived/failed/cancelled (called after each+ child completes)."""try:parents = conn.execute("SELECT parent_id FROM task_links WHERE child_id = ?",@@ -276,7 +246,6 @@ def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> Noor not row["workspace_path"]):continue- # Check if ALL children of this parent are terminalactive = conn.execute("SELECT 1 FROM task_links l ""JOIN tasks t ON t.id = l.child_id "@@ -286,7 +255,6 @@ def _try_cleanup_parent_workspaces(conn: sqlite3.Connection, task_id: str) -> No).fetchone()if active:continue # still has active children- # All children done — safe to clean up parent workspaceif row["workspace_kind"] == "worktree":_cleanup_worktree_workspace(parent_id, row["workspace_path"], row["branch_name"]@@ -312,7 +280,6 @@ def _cleanup_worker_tmux(conn: sqlite3.Connection, task_id: str) -> None:assignee: str = row["assignee"]# Workers named swarm1-12 use tmux sessions named swarm-swarm1 etc.session = f"swarm-{assignee}"- # Check if session exists and pane is dead before killingout = subprocess.run(["tmux", "list-panes", "-t", session, "-F", "#{pane_dead}"],capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5,@@ -343,9 +310,8 @@ def _scratch_tip_sentinel_path() -> Path:def _scratch_tip_shown() -> bool:- """True iff the scratch-workspace tip has already been emitted on this- install. Best-effort — any error means we re-emit, which is the safer- failure mode for a help message."""+ """True iff the scratch-workspace tip was already emitted on this install.+ Best-effort — any error re-emits, the safer failure mode for a help message."""try:return _scratch_tip_sentinel_path().exists()except OSError:@@ -353,11 +319,8 @@ def _scratch_tip_shown() -> bool:def _mark_scratch_tip_shown() -> None:- """Touch the sentinel so future scratch workspaces stay silent.-- Best-effort: a failure here just means the tip might appear once more,- which is preferable to crashing dispatch over a help message.- """+ """Touch the sentinel so future scratch workspaces stay silent. Best-effort:+ a failure means the tip may appear once more, preferable to crashing dispatch."""try:path = _scratch_tip_sentinel_path()path.parent.mkdir(parents=True, exist_ok=True)@@ -371,12 +334,9 @@ def _maybe_emit_scratch_tip(task_id: str,workspace_kind: Optional[str],) -> None:- """Emit the first-use scratch-workspace tip exactly once per install.-- Called from the dispatcher right after a scratch workspace is- materialized. No-op for ``worktree`` / ``dir`` workspaces (they're- preserved by design) and no-op after the sentinel exists.- """+ """Emit the first-use scratch-workspace tip once per install, right after a+ scratch workspace is materialized. No-op for ``worktree``/``dir`` (preserved+ by design) and once the sentinel exists."""if (workspace_kind or "scratch") != "scratch":returnif _scratch_tip_shown():@@ -497,21 +457,13 @@ def _ensure_git_worktree(repo_root: Path, target: Path, branch_name: str) -> Nondef _resolve_worktree_workspace(task: Task, *, board: Optional[str] = None) -> tuple[Path, str]:- """Resolve + materialize a linked git worktree for ``task``.-- When ``task.workspace_path`` is unset, the anchor is the board's- ``default_workdir`` (a persistent project checkout). This keeps every- worktree task under a meaningful, board-owned repo — ``<repo>/.worktrees/- <task-id>`` — instead of silently landing under the dispatcher's current- working directory (which is whatever directory the gateway happened to be- launched from, e.g. the Hermes checkout). If no anchor is configured- anywhere, we fail loudly rather than guess.- """+ """Resolve + materialize a linked git worktree for ``task``. With no+ ``task.workspace_path`` the anchor is the board's ``default_workdir`` so+ every worktree lands under a board-owned repo (``<repo>/.worktrees/<id>``)+ instead of the dispatcher's incidental CWD (whatever dir the gateway was+ launched from); with no anchor configured we fail loudly rather than guess."""branch_name = (task.branch_name or "").strip() or f"wt/{task.id}"if not task.workspace_path:- # Anchor on the board's configured default_workdir, not Path.cwd().- # The dispatcher's CWD is incidental (gateway launch dir) and using it- # scatters worktrees under whatever repo the gateway started in.board_slug = board if board else _kb.get_current_board()board_default = (_kb.read_board_metadata(board_slug).get("default_workdir") or "").strip()if not board_default:@@ -549,22 +501,19 @@ def _resolve_worktree_workspace(actual_branch = _git_current_branch(requested)if actual_branch == branch_name:return requested_resolved, actual_branch- # The requested path is an existing checkout of a DIFFERENT- # task's branch. Decompose children inherit the root's- # workspace_path verbatim, so siblings all point here; reusing- # the checkout as-is would run this task on the other task's- # branch — silent cross-task provenance corruption, and unsafe- # when siblings run concurrently. Fall back to a fresh worktree- # of our own under the same repo.+ # The requested path is an existing checkout of a DIFFERENT task's+ # branch (decompose children inherit the root's workspace_path+ # verbatim, so siblings all point here). Reusing it would run this task+ # on the other task's branch — silent cross-task provenance corruption,+ # unsafe under concurrency — so fall back to our own worktree.fallback_root = _repo_root_for_worktree_target(requested.parent)if fallback_root is not None:fallback = fallback_root / ".worktrees" / task.idif fallback.resolve(strict=False) != requested_resolved:_ensure_git_worktree(fallback_root, fallback, branch_name)return fallback.resolve(strict=False), branch_name- # No repo to anchor a fallback on (or the occupied path IS this- # task's own canonical worktree): keep the legacy reuse rather- # than failing dispatch.+ # No repo to anchor a fallback on (or the occupied path IS this task's+ # own canonical worktree): keep the legacy reuse rather than fail dispatch.return requested_resolved, actual_branch or branch_namerepo_root = _git_toplevel(requested)@@ -586,35 +535,25 @@ def _resolve_worktree_workspace(def resolve_workspace(task: Task, *, board: Optional[str] = None) -> Path:"""Resolve (and create if needed) the workspace for a task.- - ``scratch``: a fresh dir under ``<board-root>/workspaces/<id>/``,- where ``<board-root>`` is the active board's root. The path is the- same for the dispatcher and every profile worker, so handoff is+ - ``scratch``: fresh dir under ``<board-root>/workspaces/<id>/`` — the+ same path for the dispatcher and every profile worker, so handoff ispath-stable.- - ``dir:<path>``: the path stored in ``workspace_path``. Created- if missing. MUST be absolute — relative paths are rejected to- prevent confused-deputy traversal where ``../../../tmp/attacker``- resolves against the dispatcher's CWD instead of a meaningful- root. Users who want a kanban-root-relative workspace should- compute the absolute path themselves.- - ``worktree``: a real linked git worktree. If ``workspace_path`` names- a repo root, Hermes treats it as an anchor and materializes a linked- worktree at ``<repo>/.worktrees/<task-id>``. If ``workspace_path`` names- a concrete target path, Hermes creates/reuses that linked worktree. With- no ``workspace_path``, Hermes anchors on the board's ``default_workdir``- and materializes ``<repo>/.worktrees/<task-id>`` per task; if no- ``default_workdir`` is configured it raises rather than guessing from the- dispatcher's CWD. When ``branch_name`` is empty, Hermes uses- ``wt/<task-id>``.-- Persist the resolved path back to the task row via ``set_workspace_path``- so subsequent runs reuse the same directory.+ - ``dir:<path>``: ``workspace_path``, created if missing. MUST be absolute+ — relative paths are rejected to prevent confused-deputy traversal where+ ``../../../tmp/attacker`` resolves against the dispatcher's CWD.+ - ``worktree``: a real linked git worktree. A ``workspace_path`` naming a+ repo root is an anchor (materializes ``<repo>/.worktrees/<task-id>``);+ a concrete target path is created/reused; with none, the board's+ ``default_workdir`` anchors it and raises if unset rather than guessing+ from the dispatcher's CWD. Empty ``branch_name`` -> ``wt/<task-id>``.++ Persist the resolved path via ``set_workspace_path`` so later runs reuse it."""kind = task.workspace_kind or "scratch"if kind == "scratch":if task.workspace_path:- # Legacy scratch tasks that were set to an explicit path get the- # same absolute-path guard as dir: — consistent with the- # threat model.+ # Legacy explicit-path scratch tasks get the same absolute-path+ # guard as dir: — same threat model.p = Path(task.workspace_path).expanduser()if not p.is_absolute():raise ValueError(