Skip to content

The agent that grows with you

refactor(gateway): unify kanban watcher settings/lock helpers in kanban_watchers_common, split notifier board collection into phase helpers

Teknium7a1a36a12fb6
diff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.py
index 5929061f893..005d7e96b4c 100644
--- a/gateway/kanban_watchers.py
+++ b/gateway/kanban_watchers.py
@@ -3,19 +3,27 @@
Background loops that subscribe to kanban boards, deliver notifications and
artifacts, and drive the multi-agent dispatcher. They use only ``self`` state,
so they live on a mixin ``GatewayRunner`` inherits. Per-tick work lives in
-``kanban_watchers_notifier`` / ``kanban_watchers_dispatcher``.
+``kanban_watchers_notifier`` / ``kanban_watchers_dispatcher``; shared plumbing
+in ``kanban_watchers_common``.
"""
from __future__ import annotations
import asyncio
-import contextlib
import os
import time
from pathlib import Path
-from typing import Any, Callable, Optional
-
-from gateway.kanban_watchers_common import _to_thread_process_service, logger # noqa: F401 (tests import via origin)
+from typing import Any, Optional
+
+from gateway.kanban_watchers_common import ( # noqa: F401 (tests import via origin)
+ _acquire_singleton_lock,
+ _kanban_dispatch_allowed,
+ _release_singleton_lock,
+ _resolve_auto_decompose_settings,
+ _gc_retention_days,
+ _to_thread_process_service,
+ logger,
+)
from gateway.kanban_watchers_notifier import ( # noqa: F401 (_wake_scope_id: tests import via origin)
_KanbanNotification,
_notifier_collect,
@@ -27,100 +35,16 @@ from gateway.kanban_watchers_dispatcher import (
_resolve_dispatcher_settings,
)
-
-def _resolve_auto_decompose_settings(
- load_config: Callable[[], Any],
-) -> "tuple[bool, int]":
- """Resolve the live (enabled, per_tick) auto-decompose settings.
-
- Read fresh every dispatcher tick so flipping ``kanban.auto_decompose:
- false`` stops runaway fan-out on the next tick without a restart. Fails
- safe: a config read error returns ``(False, 3)`` rather than re-enabling
- a feature the user turned off. ``per_tick`` is clamped to ``>= 1``.
- """
- try:
- cfg = load_config()
- except Exception:
- return False, 3
- kcfg = cfg.get("kanban", {}) if isinstance(cfg, dict) else {}
- enabled = bool(kcfg.get("auto_decompose", True))
- try:
- per_tick = int(kcfg.get("auto_decompose_per_tick", 3) or 3)
- except (TypeError, ValueError):
- per_tick = 3
- return enabled, max(per_tick, 1)
-
-
-def _kanban_dispatch_allowed() -> bool:
- """Return False while the global emergency stop (`hermes pause`) is engaged.
-
- Checked every tick before spawning, so a pause applies on the next tick;
- in-flight workers are never touched. Fails open if estop is unimportable.
- """
- try:
- from agent.estop import check_paused
- except ImportError:
- return True
- return not check_paused("kanban", logger)
-
-
-def _acquire_singleton_lock(lock_path) -> "tuple[Optional[object], str]":
- """Take the exclusive, non-blocking advisory lock for the sole dispatcher.
-
- Only one gateway machine-wide may run the embedded dispatcher: concurrent
- dispatchers double reclaim frequency and claim events, and with
- ``wal_autocheckpoint=0`` concurrent manual checkpoints can corrupt index
- pages. ``dispatch_in_gateway`` is the primary control; this is the backstop.
-
- Returns ``(handle, "held")`` (caller must release via
- :func:`_release_singleton_lock`), ``(None, "contended")`` when another
- process holds it (caller must NOT dispatch), or ``(None, "unavailable")``
- when locking cannot be performed (caller falls back to config control).
- """
- try:
- from gateway.status import _try_acquire_file_lock # deferred; same package
- except ImportError:
- return None, "unavailable"
- try:
- Path(lock_path).parent.mkdir(parents=True, exist_ok=True)
- handle = open(str(lock_path), "a+", encoding="utf-8")
- except OSError:
- return None, "unavailable"
- if not _try_acquire_file_lock(handle):
- handle.close()
- return None, "contended"
- return handle, "held"
-
-
-def _release_singleton_lock(handle) -> None:
- """Release a lock acquired via :func:`_acquire_singleton_lock`."""
- if handle is None:
- return
- try:
- from gateway.status import _release_file_lock
- _release_file_lock(handle)
- except Exception:
- pass
- with contextlib.suppress(Exception):
- handle.close()
-
-
-def _gc_retention_days() -> int:
- """``kanban.done_sub_retention_days`` (default 30; 0 disables), re-read per sweep; fails safe to 30."""
- try:
- from hermes_cli.config import load_config as _load_cfg
-
- _kanban_cfg = (_load_cfg() or {}).get("kanban") or {}
- return int(_kanban_cfg.get("done_sub_retention_days", 30))
- except Exception:
- return 30
+_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp"}
+_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
+_GC_INTERVAL_SECONDS = 3600.0
+_HEALTH_WINDOW = 6
class GatewayKanbanWatchersMixin:
"""Kanban watcher / notifier / dispatcher loops for GatewayRunner."""
def _owns_kanban_dispatcher_lock(self) -> bool:
- """Return whether this gateway currently owns the singleton lock."""
return getattr(self, "_kanban_dispatcher_lock_handle", None) is not None
def _release_kanban_dispatcher_lock(self) -> None:
@@ -141,15 +65,12 @@ class GatewayKanbanWatchersMixin:
"""Poll ``kanban_notify_subs`` and deliver terminal events to users.
Per subscription, claims ``task_events`` newer than the stored cursor
- (kinds in TERMINAL_KINDS), sends one message per event to
- ``(platform, chat_id, thread_id)``, then advances the cursor. The
- subscription is removed only when the task is ``archived``: ``done``
- is reversible (review/continuation), so the cursor — not unsubscribing
- — is the dedup mechanism. Earlier unsub-on-terminal silently dropped
- users when the dispatcher respawned a crashed task.
-
- All SQLite work runs in a thread; one tick's failure never stops the
- next. Iterates every board on disk per tick.
+ (kinds in TERMINAL_KINDS), sends one message per event, then advances
+ the cursor. The subscription is removed only when the task is
+ ``archived``: ``done`` is reversible, so the cursor — not unsubscribing
+ — is the dedup mechanism (unsub-on-terminal dropped users when the
+ dispatcher respawned a crashed task). All SQLite work runs in a thread;
+ one tick's failure never stops the next.
"""
from gateway.config import Platform as _Platform
try:
@@ -158,9 +79,7 @@ class GatewayKanbanWatchersMixin:
logger.warning("kanban notifier: kanban_db not importable; notifier disabled")
return
- sub_fail_counts: dict[tuple, int] = getattr(
- self, "_kanban_sub_fail_counts", {}
- )
+ sub_fail_counts: dict[tuple, int] = getattr(self, "_kanban_sub_fail_counts", {})
self._kanban_sub_fail_counts = sub_fail_counts
notifier_profile = getattr(self, "_kanban_notifier_profile", None)
if not notifier_profile:
@@ -172,9 +91,8 @@ class GatewayKanbanWatchersMixin:
# Stale done-sub GC: subs survive ``done``, so boards that never
# archive would accumulate rows scanned every tick. One DELETE per
- # board, at startup and at most hourly.
- _GC_INTERVAL_SECONDS = 3600.0
- _gc_next_at = 0.0 # 0 → sweep on the first tick after startup
+ # board, at startup (0 → first tick) and at most hourly.
+ _gc_next_at = 0.0
while self._running:
try:
@@ -186,9 +104,7 @@ class GatewayKanbanWatchersMixin:
deliveries = await asyncio.to_thread(
_notifier_collect, self, _kb,
- notifier_profile=notifier_profile,
- gc_due=_gc_due,
- gc_retention_days=_retention,
+ notifier_profile=notifier_profile, gc_due=_gc_due, gc_retention_days=_retention,
)
for d in deliveries:
await _KanbanNotification(
@@ -204,47 +120,23 @@ class GatewayKanbanWatchersMixin:
conn = _kb.connect(board=board)
try:
getattr(_kb, op)(
- conn,
- task_id=sub["task_id"],
- platform=sub["platform"],
- chat_id=sub["chat_id"],
- thread_id=sub.get("thread_id") or "",
- **extra,
+ conn, task_id=sub["task_id"], platform=sub["platform"], chat_id=sub["chat_id"],
+ thread_id=sub.get("thread_id") or "", **extra,
)
finally:
conn.close()
- def _kanban_advance(
- self, sub: dict, cursor: int, board: Optional[str] = None,
- ) -> None:
- """Advance a subscription's cursor on the board that owns it."""
+ def _kanban_advance(self, sub: dict, cursor: int, board: Optional[str] = None) -> None:
self._kanban_sub_op(board, "advance_notify_cursor", sub, new_cursor=cursor)
def _kanban_unsub(self, sub: dict, board: Optional[str] = None) -> None:
self._kanban_sub_op(board, "remove_notify_sub", sub)
- def _kanban_rewind(
- self,
- sub: dict,
- claimed_cursor: int,
- old_cursor: int,
- board: Optional[str] = None,
- ) -> None:
+ def _kanban_rewind(self, sub: dict, claimed_cursor: int, old_cursor: int, board: Optional[str] = None) -> None:
"""Undo a claimed notification cursor after send failure."""
- self._kanban_sub_op(
- board, "rewind_notify_cursor", sub,
- claimed_cursor=claimed_cursor, old_cursor=old_cursor,
- )
-
- async def _deliver_kanban_artifacts(
- self,
- *,
- adapter,
- chat_id: str,
- metadata: dict,
- event_payload: Optional[dict],
- task,
- ) -> None:
+ self._kanban_sub_op(board, "rewind_notify_cursor", sub, claimed_cursor=claimed_cursor, old_cursor=old_cursor)
+
+ async def _deliver_kanban_artifacts(self, *, adapter, chat_id: str, metadata: dict, event_payload: Optional[dict], task) -> None:
"""Upload artifact files referenced by a completed kanban task.
Sources, in priority order: ``event_payload['artifacts']``,
@@ -270,18 +162,13 @@ class GatewayKanbanWatchersMixin:
for item in raw:
if isinstance(item, str):
_add(item)
-
summary = event_payload.get("summary")
if isinstance(summary, str) and summary:
- paths, _ = adapter.extract_local_files(summary)
- for p in paths:
+ for p in adapter.extract_local_files(summary)[0]:
_add(p)
-
if task is not None and getattr(task, "result", None):
- paths, _ = adapter.extract_local_files(str(task.result))
- for p in paths:
+ for p in adapter.extract_local_files(str(task.result))[0]:
_add(p)
-
if not candidates:
return
@@ -290,81 +177,56 @@ class GatewayKanbanWatchersMixin:
if not candidates:
return
- _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp"}
- _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
-
from urllib.parse import quote as _quote
# Images ride one send_multiple_images call (batch uploads on Signal/Slack).
image_paths = [p for p in candidates if Path(p).suffix.lower() in _IMAGE_EXTS]
other_paths = [p for p in candidates if Path(p).suffix.lower() not in _IMAGE_EXTS]
-
if image_paths:
try:
batch = [(f"file://{_quote(p)}", "") for p in image_paths]
- await adapter.send_multiple_images(
- chat_id=chat_id, images=batch, metadata=metadata,
- )
+ await adapter.send_multiple_images(chat_id=chat_id, images=batch, metadata=metadata)
except Exception as exc:
- logger.warning(
- "kanban notifier: image batch upload failed: %s", exc,
- )
-
+ logger.warning("kanban notifier: image batch upload failed: %s", exc)
for path in other_paths:
try:
if Path(path).suffix.lower() in _VIDEO_EXTS:
- await adapter.send_video(
- chat_id=chat_id, video_path=path, metadata=metadata,
- )
+ await adapter.send_video(chat_id=chat_id, video_path=path, metadata=metadata)
else:
- await adapter.send_document(
- chat_id=chat_id, file_path=path, metadata=metadata,
- )
+ await adapter.send_document(chat_id=chat_id, file_path=path, metadata=metadata)
except Exception as exc:
- logger.warning(
- "kanban notifier: artifact upload (%s) failed: %s",
- path, exc,
- )
+ logger.warning("kanban notifier: artifact upload (%s) failed: %s", path, exc)
- async def _kanban_dispatcher_watcher(self) -> None:
- """Embedded kanban dispatcher — one tick every `dispatch_interval_seconds`.
+ def _kanban_dispatcher_boot(self) -> Optional[tuple]:
+ """Resolve config, kanban_db and the singleton lock; None when the dispatcher must not run.
- Gated by `kanban.dispatch_in_gateway` (default True); when false the
- loop exits and an external `hermes kanban daemon` is expected. Each
- tick runs :func:`kanban_db.dispatch_once` in a thread; one tick's
- failure never stops the next. Shutdown: ``self._running`` is checked
- between ticks and the in-flight ``to_thread`` returns on its own.
+ Config is read once at boot (restart to apply), except the auto-decompose
+ toggle which is re-read every tick. The env var is an escape hatch to
+ disable without editing YAML.
"""
- # Config is read once at boot (restart to apply), except the
- # auto-decompose toggle which is re-read every tick. The env var is
- # an escape hatch to disable without editing YAML.
try:
from hermes_cli.config import load_config as _load_config
except Exception:
logger.warning("kanban dispatcher: config loader unavailable; disabled")
- return
+ return None
env_override = os.environ.get("HERMES_KANBAN_DISPATCH_IN_GATEWAY", "").strip().lower()
if env_override in {"0", "false", "no", "off"}:
logger.info("kanban dispatcher: disabled via HERMES_KANBAN_DISPATCH_IN_GATEWAY env")
- return
-
+ return None
try:
cfg = _load_config()
except Exception as exc:
logger.warning("kanban dispatcher: cannot load config (%s); disabled", exc)
- return
+ return None
kanban_cfg = cfg.get("kanban", {}) if isinstance(cfg, dict) else {}
if not kanban_cfg.get("dispatch_in_gateway", True):
- logger.info(
- "kanban dispatcher: disabled via config kanban.dispatch_in_gateway=false"
- )
- return
-
+ logger.info("kanban dispatcher: disabled via config kanban.dispatch_in_gateway=false")
+ return None
try:
from hermes_cli import kanban_db as _kb
except Exception:
logger.warning("kanban dispatcher: kanban_db not importable; dispatcher disabled")
- return
+ return None
# Single-dispatcher backstop (see _acquire_singleton_lock). The lock
# lives at the machine-global kanban root, so it serialises ALL gateways.
@@ -376,7 +238,7 @@ class GatewayKanbanWatchersMixin:
"kanban dispatcher: another gateway already holds the dispatcher "
"lock (%s); this gateway will NOT dispatch.", _lock_path,
)
- return
+ return None
if _lock_state == "held":
self._kanban_dispatcher_lock_handle = _lock_handle # hold for process lifetime
logger.info("kanban dispatcher: holding singleton dispatcher lock (%s)", _lock_path)
@@ -385,7 +247,21 @@ class GatewayKanbanWatchersMixin:
"kanban dispatcher: advisory lock unavailable at %s; proceeding "
"on config control alone.", _lock_path,
)
+ return _load_config, _kb, kanban_cfg
+ async def _kanban_dispatcher_watcher(self) -> None:
+ """Embedded kanban dispatcher — one tick every `dispatch_interval_seconds`.
+
+ Gated by `kanban.dispatch_in_gateway` (default True); when false the
+ loop exits and an external `hermes kanban daemon` is expected. Each
+ tick runs :func:`kanban_db.dispatch_once` in a thread; one tick's
+ failure never stops the next. Shutdown: ``self._running`` is checked
+ between ticks and the in-flight ``to_thread`` returns on its own.
+ """
+ boot = self._kanban_dispatcher_boot()
+ if boot is None:
+ return
+ _load_config, _kb, kanban_cfg = boot
settings = _resolve_dispatcher_settings(kanban_cfg, _kb)
interval = settings.interval
@@ -395,25 +271,18 @@ class GatewayKanbanWatchersMixin:
# Health telemetry (mirrors `_cmd_daemon`): warn when the ready queue
# is non-empty but spawns are 0 for N consecutive ticks — usually a
# broken PATH, missing venv, or credential loss.
- HEALTH_WINDOW = 6
bad_ticks = 0
last_warn_at = 0
dispatcher = _KanbanDispatcher(_kb, settings)
- logger.info(
- "kanban dispatcher: embedded in gateway (interval=%.1fs)", interval
- )
+ logger.info("kanban dispatcher: embedded in gateway (interval=%.1fs)", interval)
while self._running:
try:
# Reap zombies before per-board work so a board DB failure
# cannot block cleanup of unrelated workers.
pids = await _to_thread_process_service(_kb.reap_worker_zombies)
if pids:
- logger.info(
- "kanban dispatcher: reaped %d zombie worker(s), pids=%s",
- len(pids),
- pids,
- )
+ logger.info("kanban dispatcher: reaped %d zombie worker(s), pids=%s", len(pids), pids)
except Exception:
logger.exception("kanban dispatcher: zombie reaper failed")
@@ -430,10 +299,9 @@ class GatewayKanbanWatchersMixin:
await _to_thread_process_service(dispatcher.auto_decompose_tick, _ad_per_tick)
results = await _to_thread_process_service(dispatcher.tick_once)
any_spawned = _log_spawn_results(results)
- # Health telemetry (aggregate across boards)
ready_pending = await _to_thread_process_service(dispatcher.ready_nonempty)
bad_ticks = bad_ticks + 1 if ready_pending and not any_spawned else 0
- if bad_ticks >= HEALTH_WINDOW:
+ if bad_ticks >= _HEALTH_WINDOW:
now = int(time.time())
if now - last_warn_at >= 300:
logger.warning(
diff --git a/gateway/kanban_watchers_common.py b/gateway/kanban_watchers_common.py
index 22833575ee0..e9e9fdb1179 100644
--- a/gateway/kanban_watchers_common.py
+++ b/gateway/kanban_watchers_common.py
@@ -1,11 +1,18 @@
-"""Plumbing shared by the kanban notifier and dispatcher loops."""
+"""Plumbing shared by the kanban notifier and dispatcher loops.
+
+Thread offload, board enumeration, live-config coercers and the singleton
+dispatcher lock live here so the notifier, dispatcher and mixin modules read
+them from one place.
+"""
from __future__ import annotations
import asyncio
+import contextlib
import logging
from contextvars import Context
-from typing import Any, Callable
+from pathlib import Path
+from typing import Any, Callable, Optional
# Keep the logger name run.py used so extracted log records are unchanged.
logger = logging.getLogger("gateway.run")
@@ -33,3 +40,112 @@ def _list_boards(kb: Any) -> list:
return kb.list_boards(include_archived=False)
except Exception:
return [kb.read_board_metadata(kb.DEFAULT_BOARD)]
+
+
+def _board_slugs(kb: Any) -> list:
+ return [b.get("slug") or kb.DEFAULT_BOARD for b in _list_boards(kb)]
+
+
+def _kanban_cfg(load_config: Callable[[], Any]) -> Optional[dict]:
+ """``kanban`` section of the live config; ``None`` when the loader raises."""
+ try:
+ cfg = load_config()
+ except Exception:
+ return None
+ return cfg.get("kanban", {}) if isinstance(cfg, dict) else {}
+
+
+def _positive_int_setting(kanban_cfg: dict, key: str) -> Optional[int]:
+ """Parse an optional ``kanban.<key>`` int cap; None when unset or invalid (< 1 is invalid)."""
+ raw = kanban_cfg.get(key)
+ if raw is None:
+ return None
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ logger.warning("kanban dispatcher: invalid kanban.%s=%r; ignoring", key, raw)
+ return None
+ if value < 1:
+ logger.warning("kanban dispatcher: kanban.%s=%r is below 1; ignoring", key, raw)
+ return None
+ logger.info("kanban dispatcher: %s=%d", key, value)
+ return value
+
+
+def _resolve_auto_decompose_settings(load_config: Callable[[], Any]) -> "tuple[bool, int]":
+ """Live (enabled, per_tick) auto-decompose settings, re-read every dispatcher tick.
+
+ Fails safe: a config read error returns ``(False, 3)`` rather than
+ re-enabling a feature the user turned off. ``per_tick`` is clamped to ``>= 1``.
+ """
+ kcfg = _kanban_cfg(load_config)
+ if kcfg is None:
+ return False, 3
+ try:
+ per_tick = int(kcfg.get("auto_decompose_per_tick", 3) or 3)
+ except (TypeError, ValueError):
+ per_tick = 3
+ return bool(kcfg.get("auto_decompose", True)), max(per_tick, 1)
+
+
+def _gc_retention_days() -> int:
+ """``kanban.done_sub_retention_days`` (default 30; 0 disables), re-read per sweep; fails safe to 30."""
+ try:
+ from hermes_cli.config import load_config
+
+ return int(((load_config() or {}).get("kanban") or {}).get("done_sub_retention_days", 30))
+ except Exception:
+ return 30
+
+
+def _kanban_dispatch_allowed() -> bool:
+ """False while the global emergency stop (`hermes pause`) is engaged.
+
+ Checked every tick before spawning, so a pause applies on the next tick;
+ in-flight workers are never touched. Fails open if estop is unimportable.
+ """
+ try:
+ from agent.estop import check_paused
+ except ImportError:
+ return True
+ return not check_paused("kanban", logger)
+
+
+def _acquire_singleton_lock(lock_path) -> "tuple[Optional[object], str]":
+ """Take the exclusive, non-blocking advisory lock for the sole dispatcher.
+
+ Only one gateway machine-wide may run the embedded dispatcher: concurrent
+ dispatchers double reclaim frequency and claim events, and with
+ ``wal_autocheckpoint=0`` concurrent manual checkpoints can corrupt index
+ pages. ``dispatch_in_gateway`` is the primary control; this is the backstop.
+
+ Returns ``(handle, "held")`` (release via :func:`_release_singleton_lock`),
+ ``(None, "contended")`` when another process holds it (caller must NOT
+ dispatch), or ``(None, "unavailable")`` when locking cannot be performed
+ (caller falls back to config control).
+ """
+ try:
+ from gateway.status import _try_acquire_file_lock # deferred; same package
+ except ImportError:
+ return None, "unavailable"
+ try:
+ Path(lock_path).parent.mkdir(parents=True, exist_ok=True)
+ handle = open(str(lock_path), "a+", encoding="utf-8")
+ except OSError:
+ return None, "unavailable"
+ if not _try_acquire_file_lock(handle):
+ handle.close()
+ return None, "contended"
+ return handle, "held"
+
+
+def _release_singleton_lock(handle) -> None:
+ """Release a lock acquired via :func:`_acquire_singleton_lock`."""
+ if handle is None:
+ return
+ with contextlib.suppress(Exception):
+ from gateway.status import _release_file_lock
+
+ _release_file_lock(handle)
+ with contextlib.suppress(Exception):
+ handle.close()
diff --git a/gateway/kanban_watchers_dispatcher.py b/gateway/kanban_watchers_dispatcher.py
index b768906245f..fceba657e5e 100644
--- a/gateway/kanban_watchers_dispatcher.py
+++ b/gateway/kanban_watchers_dispatcher.py
@@ -14,7 +14,7 @@ import time
from dataclasses import dataclass
from typing import Any, Optional
-from gateway.kanban_watchers_common import _list_boards, logger
+from gateway.kanban_watchers_common import _board_slugs, _positive_int_setting, logger
_CORRUPT_DB_MARKERS = ("file is not a database", "database disk image is malformed")
@@ -33,23 +33,6 @@ class _DispatcherSettings:
max_in_progress_per_profile: Optional[int]
-def _positive_int_setting(kanban_cfg: dict, key: str) -> Optional[int]:
- """Parse an optional ``kanban.<key>`` int cap; None when unset or invalid (< 1 is invalid)."""
- raw = kanban_cfg.get(key)
- if raw is None:
- return None
- try:
- value = int(raw)
- except (TypeError, ValueError):
- logger.warning("kanban dispatcher: invalid kanban.%s=%r; ignoring", key, raw)
- return None
- if value < 1:
- logger.warning("kanban dispatcher: kanban.%s=%r is below 1; ignoring", key, raw)
- return None
- logger.info("kanban dispatcher: %s=%d", key, value)
- return value
-
-
def _resolve_dispatcher_settings(kanban_cfg: dict, kb: Any) -> _DispatcherSettings:
"""Parse and log the dispatcher settings in their established order."""
try:
@@ -66,10 +49,9 @@ def _resolve_dispatcher_settings(kanban_cfg: dict, kb: Any) -> _DispatcherSettin
if max_spawn is not None:
logger.info("kanban dispatcher: max_spawn=%s", max_spawn)
- # Cap simultaneously running tasks so slow workers don't pile up and
- # time out. Explicit config wins; otherwise a memory-derived default
- # (unbounded fan-out swap-thrashes small hosts), or None where total
- # memory can't be read.
+ # Cap simultaneously running tasks so slow workers don't pile up and time
+ # out. Explicit config wins; otherwise a memory-derived default (unbounded
+ # fan-out swap-thrashes small hosts), or None where total memory can't be read.
max_in_progress = _positive_int_setting(kanban_cfg, "max_in_progress")
effective_max_in_progress = kb.resolve_max_in_progress(max_in_progress)
if max_in_progress is None and effective_max_in_progress is not None:
@@ -86,15 +68,13 @@ def _resolve_dispatcher_settings(kanban_cfg: dict, kb: Any) -> _DispatcherSettin
except (TypeError, ValueError):
logger.warning(
"kanban dispatcher: invalid kanban.failure_limit=%r; using default %d",
- raw_failure_limit,
- kb.DEFAULT_FAILURE_LIMIT,
+ raw_failure_limit, kb.DEFAULT_FAILURE_LIMIT,
)
failure_limit = kb.DEFAULT_FAILURE_LIMIT
if failure_limit < 1:
logger.warning(
"kanban dispatcher: kanban.failure_limit=%r is below 1; using default %d",
- raw_failure_limit,
- kb.DEFAULT_FAILURE_LIMIT,
+ raw_failure_limit, kb.DEFAULT_FAILURE_LIMIT,
)
failure_limit = kb.DEFAULT_FAILURE_LIMIT
@@ -150,12 +130,10 @@ class _KanbanDispatcher:
def __init__(self, kb: Any, settings: _DispatcherSettings) -> None:
self.kb = kb
self.settings = settings
- self.disabled_corrupt_boards: dict[
- str, tuple[tuple[str, int | None, int | None], float]
- ] = {}
+ self.disabled_corrupt_boards: dict[str, tuple[tuple[str, int | None, int | None], float]] = {}
def _board_slugs(self) -> list:
- return [b.get("slug") or self.kb.DEFAULT_BOARD for b in _list_boards(self.kb)]
+ return _board_slugs(self.kb)
def board_db_fingerprint(self, slug: str) -> tuple[str, int | None, int | None]:
path = self.kb.kanban_db_path(slug)
@@ -191,14 +169,10 @@ class _KanbanDispatcher:
logger.info(
"kanban dispatcher: board %s database fingerprint unchanged "
"after %.0fs quarantine; retrying dispatch",
- slug,
- age,
+ slug, age,
)
else:
- logger.info(
- "kanban dispatcher: board %s database changed; retrying dispatch",
- slug,
- )
+ logger.info("kanban dispatcher: board %s database changed; retrying dispatch", slug)
self.disabled_corrupt_boards.pop(slug, None)
return True
@@ -218,12 +192,8 @@ class _KanbanDispatcher:
# process (see the matching note in the notifier collector).
conn = self.kb.connect(board=slug)
return self.kb.dispatch_once(
- conn,
- board=slug,
- max_spawn=s.max_spawn,
- max_in_progress=s.max_in_progress,
- failure_limit=s.failure_limit,
- stale_timeout_seconds=s.stale_timeout_seconds,
+ conn, board=slug, max_spawn=s.max_spawn, max_in_progress=s.max_in_progress,
+ failure_limit=s.failure_limit, stale_timeout_seconds=s.stale_timeout_seconds,
default_assignee=s.default_assignee,
max_in_progress_per_profile=s.max_in_progress_per_profile,
reconcile_orphans=s.reconcile_orphans,
@@ -237,8 +207,7 @@ class _KanbanDispatcher:
"the file changes, the gateway restarts, or the "
"quarantine timer expires. Move or restore the file, "
"then run `hermes kanban init` if you need a fresh board.",
- slug,
- fingerprint[0],
+ slug, fingerprint[0],
)
return None
logger.exception("kanban dispatcher: tick failed on board %s", slug)
@@ -253,14 +222,13 @@ class _KanbanDispatcher:
return [(slug, self.tick_once_for_board(slug)) for slug in self._board_slugs()]
def ready_nonempty(self) -> bool:
- """Is there a ready+assigned+unclaimed task on ANY board that the
- dispatcher would actually spawn for?
-
- Control-plane lanes (e.g. ``orion-cc``) are pulled by terminals
- via ``claim_task`` and never spawnable — a queue full of those is
- "correctly idle", not "stuck". The review column is probed only
- when review dispatch is on (same gate as the dispatcher): a task
- waiting for a human reviewer is idle, not stuck.
+ """Is there a ready+assigned+unclaimed task on ANY board the dispatcher would spawn for?
+
+ Control-plane lanes (e.g. ``orion-cc``) are pulled by terminals via
+ ``claim_task`` and never spawnable — a queue full of those is
+ "correctly idle", not "stuck". The review column is probed only when
+ review dispatch is on (same gate as the dispatcher): a task waiting
+ for a human reviewer is idle, not stuck.
"""
kb = self.kb
_review_probe = kb.review_dispatch_enabled()
@@ -268,9 +236,7 @@ class _KanbanDispatcher:
conn = None
try:
conn = kb.connect(board=slug)
- if kb.has_spawnable_ready(conn):
- return True
- if _review_probe and kb.has_spawnable_review(conn):
+ if kb.has_spawnable_ready(conn) or (_review_probe and kb.has_spawnable_review(conn)):
return True
except Exception:
continue
@@ -281,17 +247,15 @@ class _KanbanDispatcher:
return False
def auto_decompose_tick(self, auto_decompose_per_tick: int) -> int:
- """Auto-decompose up to N triage tasks across all boards into
- ready workgraphs before dispatch fans out; the per-tick cap keeps
- a bulk triage load from burst-spending the aux LLM. Returns the
- number decomposed/specified.
+ """Auto-decompose up to N triage tasks across all boards into ready workgraphs.
+
+ Runs before dispatch fans out; the per-tick cap keeps a bulk triage
+ load from burst-spending the aux LLM. Returns the number decomposed.
"""
try:
from hermes_cli import kanban_decompose as _decomp
except Exception as exc: # pragma: no cover
- logger.warning(
- "kanban auto-decompose: import failed (%s); skipping", exc,
- )
+ logger.warning("kanban auto-decompose: import failed (%s); skipping", exc)
return 0
attempted = 0
successes = 0
@@ -306,10 +270,7 @@ class _KanbanDispatcher:
try:
triage_ids = _decomp.list_triage_ids()
except Exception as exc:
- logger.debug(
- "kanban auto-decompose: list_triage_ids failed on board %s (%s)",
- slug, exc,
- )
+ logger.debug("kanban auto-decompose: list_triage_ids failed on board %s (%s)", slug, exc)
triage_ids = []
for tid in triage_ids:
if attempted >= auto_decompose_per_tick:
@@ -329,28 +290,16 @@ class _KanbanDispatcher:
try:
outcome = _decomp.decompose_task(tid, author="auto-decomposer")
except Exception:
- logger.exception(
- "kanban auto-decompose: decompose_task crashed on %s",
- tid,
- )
+ logger.exception("kanban auto-decompose: decompose_task crashed on %s", tid)
return 0
if not outcome.ok:
# Common no-op reasons (no aux client) must not spam logs every tick.
- logger.debug(
- "kanban auto-decompose [%s]: %s skipped: %s",
- slug, tid, outcome.reason,
- )
+ logger.debug("kanban auto-decompose [%s]: %s skipped: %s", slug, tid, outcome.reason)
return 0
if outcome.fanout and outcome.child_ids:
- logger.info(
- "kanban auto-decompose [%s]: %s → %d children",
- slug, tid, len(outcome.child_ids),
- )
+ logger.info("kanban auto-decompose [%s]: %s → %d children", slug, tid, len(outcome.child_ids))
else:
- logger.info(
- "kanban auto-decompose [%s]: %s → single task (no fanout)",
- slug, tid,
- )
+ logger.info("kanban auto-decompose [%s]: %s → single task (no fanout)", slug, tid)
return 1
@@ -364,9 +313,7 @@ def _log_spawn_results(results: Optional[list]) -> bool:
logger.info(
"kanban dispatcher [%s]: spawned=%d reclaimed=%d "
"crashed=%d timed_out=%d promoted=%d auto_blocked=%d",
- slug,
- len(res.spawned),
- res.reclaimed,
+ slug, len(res.spawned), res.reclaimed,
len(res.crashed) if hasattr(res.crashed, "__len__") else 0,
len(res.timed_out) if hasattr(res.timed_out, "__len__") else 0,
res.promoted,
diff --git a/gateway/kanban_watchers_notifier.py b/gateway/kanban_watchers_notifier.py
index 2abb00890e4..1c0b0c283f5 100644
--- a/gateway/kanban_watchers_notifier.py
+++ b/gateway/kanban_watchers_notifier.py
@@ -26,10 +26,9 @@ _WAKE_KINDS = (
"blocked", "review_requested", "changes_requested",
"block_loop_detected",
)
-# Consecutive send failures (adapter raised OR reported
-# SendResult(success=False)) before a sub is dropped as a dead chat.
-# 12 ≈ 60s at the 5s cadence: a transient API outage must not
-# permanently unsubscribe a live review-gate channel.
+# Consecutive send failures (adapter raised OR reported SendResult(success=False))
+# before a sub is dropped as a dead chat. 12 ≈ 60s at the 5s cadence: a transient
+# API outage must not permanently unsubscribe a live review-gate channel.
MAX_SEND_FAILURES = 12
_LOCAL_PATH_RE = re.compile(
@@ -42,13 +41,8 @@ def _safe_review_reason(value: Any, limit: int = 160) -> str:
"""Return a mobile-friendly review reason safe for external delivery."""
from agent.redact import redact_sensitive_text
- reason = redact_sensitive_text(
- "" if value is None else str(value),
- force=True,
- redact_url_credentials=True,
- )
- reason = _LOCAL_PATH_RE.sub("[local path]", reason)
- reason = " ".join(reason.split())
+ reason = redact_sensitive_text("" if value is None else str(value), force=True, redact_url_credentials=True)
+ reason = " ".join(_LOCAL_PATH_RE.sub("[local path]", reason).split())
if len(reason) > limit:
reason = reason[: limit - 1].rstrip() + "…"
return reason
@@ -76,10 +70,7 @@ def _wake_scope_id(adapter: Any, sub: dict) -> Optional[str]:
except Exception as exc:
# An adapter-side lookup failure yields no scope, never an error.
logger.debug(
- "kanban notifier: scope lookup failed for chat %s: %s",
- sub.get("chat_id"),
- exc,
- exc_info=True,
+ "kanban notifier: scope lookup failed for chat %s: %s", sub.get("chat_id"), exc, exc_info=True,
)
return None
if resolved:
@@ -92,19 +83,10 @@ def _platform_names(mapping: Any) -> set[str]:
return {getattr(platform, "value", str(platform)).lower() for platform in mapping}
-# ---------------------------------------------------------------------------
-# Collection (runs in a worker thread)
-# ---------------------------------------------------------------------------
+# --- Collection (runs in a worker thread) ---
-def _notifier_collect(
- runner: Any,
- kb: Any,
- *,
- notifier_profile: Optional[str],
- gc_due: bool,
- gc_retention_days: int,
-) -> list[dict]:
+def _notifier_collect(runner: Any, kb: Any, *, notifier_profile: Optional[str], gc_due: bool, gc_retention_days: int) -> list[dict]:
"""Claim unseen terminal events for every owned subscription on every board.
Each gateway polls only subscriptions owned by profiles whose adapters it
@@ -115,9 +97,7 @@ def _notifier_collect(
include_unowned = runner._owns_kanban_dispatcher_lock()
profile_adapters = getattr(runner, "_profile_adapters", {})
notifier_profiles = {notifier_profile}
- notifier_profiles.update(
- str(profile).strip() for profile in profile_adapters if str(profile).strip()
- )
+ notifier_profiles.update(str(profile).strip() for profile in profile_adapters if str(profile).strip())
active_platforms = _platform_names(runner.adapters)
# Include every platform any secondary profile has live. This is only a
# coarse pre-filter; the precise per-profile check (_authorization_adapter,
@@ -141,58 +121,88 @@ def _notifier_collect(
except Exception:
resolved_db_path = f"slug:{slug}"
if resolved_db_path in seen_db_paths:
- logger.debug(
- "kanban notifier: skipping duplicate board slug %s for DB %s",
- slug, resolved_db_path,
- )
+ logger.debug("kanban notifier: skipping duplicate board slug %s for DB %s", slug, resolved_db_path)
continue
seen_db_paths.add(resolved_db_path)
_notifier_collect_board(
kb, slug, deliveries,
- notifier_profile=notifier_profile,
- notifier_profiles=notifier_profiles,
- include_unowned=include_unowned,
- profile_adapters=profile_adapters,
- active_platforms=active_platforms,
- gc_due=gc_due,
- gc_retention_days=gc_retention_days,
+ notifier_profile=notifier_profile, notifier_profiles=notifier_profiles,
+ include_unowned=include_unowned, profile_adapters=profile_adapters,
+ active_platforms=active_platforms, gc_due=gc_due, gc_retention_days=gc_retention_days,
)
return deliveries
-def _notifier_collect_board(
- kb: Any,
- slug: str,
- deliveries: list[dict],
- *,
- notifier_profile: Optional[str],
- notifier_profiles: set,
- include_unowned: bool,
- profile_adapters: dict,
- active_platforms: set[str],
- gc_due: bool,
- gc_retention_days: int,
-) -> None:
- """Claim events on one board, appending delivery dicts to *deliveries*."""
- # Cheap read-only probe before the writable connect() (schema init, WAL
- # sidecars, checkpoints) — a board with no subscriptions has nothing to notify.
+def _board_has_subs(kb: Any, slug: str, notifier_profiles: set, include_unowned: bool) -> bool:
+ """Cheap read-only probe before the writable connect() (schema init, WAL
+ sidecars, checkpoints); a probe failure falls back to the writable open."""
try:
- if kb.count_notify_subs(
- board=slug,
- notifier_profiles=notifier_profiles,
- include_unowned=include_unowned,
- ) == 0:
+ if kb.count_notify_subs(board=slug, notifier_profiles=notifier_profiles, include_unowned=include_unowned) == 0:
logger.debug(
"kanban notifier: board %s has no subscriptions owned by %s; skipping open",
slug, sorted(notifier_profiles),
)
- return
+ return False
except Exception as exc:
logger.debug(
"kanban notifier: read-only subscription probe failed "
"for board %s (%s); falling back to writable open",
slug, exc,
)
+ return True
+
+
+def _gc_stale_subs(kb: Any, conn: Any, slug: str, gc_retention_days: int) -> None:
+ """Best-effort stale-sub sweep: a failed sweep never blocks delivery; the next hourly gate retries."""
+ try:
+ _purged = kb.purge_stale_done_notify_subs(conn, max_age_days=gc_retention_days)
+ if _purged:
+ logger.info(
+ "kanban notifier: purged %d stale done/blocked-task subscription(s) on board %s (retention %dd)",
+ _purged, slug, gc_retention_days,
+ )
+ except Exception as _gc_exc:
+ logger.debug("kanban notifier: stale-sub GC failed for board %s: %s", slug, _gc_exc)
+
+
+def _claim_for_sub(kb: Any, conn: Any, slug: str, sub: dict, *, notifier_profile: Optional[str], profile_adapters: dict, active_platforms: set[str]) -> Optional[dict]:
+ """Claim one subscription's unseen events; None when skipped or nothing new."""
+ owner_profile = sub.get("notifier_profile") or None
+ if owner_profile and owner_profile != notifier_profile and not profile_adapters.get(owner_profile):
+ logger.debug(
+ "kanban notifier: subscription for %s owned by profile %s; current profile %s has no adapter for it, skipping",
+ sub.get("task_id"), owner_profile, notifier_profile,
+ )
+ return None
+ platform = (sub.get("platform") or "").lower()
+ if platform not in active_platforms:
+ logger.debug(
+ "kanban notifier: subscription for %s on %s skipped; adapter not connected",
+ sub.get("task_id"), platform or "<missing>",
+ )
+ return None
+ old_cursor, cursor, events = kb.claim_unseen_events_for_sub(
+ conn, task_id=sub["task_id"], platform=sub["platform"], chat_id=sub["chat_id"],
+ thread_id=sub.get("thread_id") or "", kinds=TERMINAL_KINDS,
+ )
+ if not events:
+ return None
+ task = kb.get_task(conn, sub["task_id"])
+ logger.debug(
+ "kanban notifier: claimed %d event(s) for %s on board %s cursor %s→%s",
+ len(events), sub["task_id"], slug, old_cursor, cursor,
+ )
+ return {"sub": sub, "old_cursor": old_cursor, "cursor": cursor, "events": events, "task": task, "board": slug}
+
+
+def _notifier_collect_board(
+ kb: Any, slug: str, deliveries: list[dict], *,
+ notifier_profile: Optional[str], notifier_profiles: set, include_unowned: bool,
+ profile_adapters: dict, active_platforms: set[str], gc_due: bool, gc_retention_days: int,
+) -> None:
+ """Claim events on one board, appending delivery dicts to *deliveries*."""
+ if not _board_has_subs(kb, slug, notifier_profiles, include_unowned):
+ return
try:
conn = kb.connect(board=slug)
except Exception as exc:
@@ -200,69 +210,21 @@ def _notifier_collect_board(
return
try:
if gc_due:
- # Best-effort: a failed sweep never blocks delivery; the next
- # hourly gate retries.
- try:
- _purged = kb.purge_stale_done_notify_subs(conn, max_age_days=gc_retention_days)
- if _purged:
- logger.info(
- "kanban notifier: purged %d stale done/blocked-task subscription(s) on board %s (retention %dd)",
- _purged, slug, gc_retention_days,
- )
- except Exception as _gc_exc:
- logger.debug(
- "kanban notifier: stale-sub GC failed for board %s: %s",
- slug, _gc_exc,
- )
+ _gc_stale_subs(kb, conn, slug, gc_retention_days)
# No explicit init_db(): connect() already runs the migration once per
# process, and init_db() would re-run it on a second connection racing
# the first.
- subs = kb.list_notify_subs(
- conn,
- notifier_profiles=notifier_profiles,
- include_unowned=include_unowned,
- )
+ subs = kb.list_notify_subs(conn, notifier_profiles=notifier_profiles, include_unowned=include_unowned)
if not subs:
logger.debug("kanban notifier: board %s has no subscriptions", slug)
for sub in subs:
try:
- owner_profile = sub.get("notifier_profile") or None
- if owner_profile and owner_profile != notifier_profile and not profile_adapters.get(owner_profile):
- logger.debug(
- "kanban notifier: subscription for %s owned by profile %s; current profile %s has no adapter for it, skipping",
- sub.get("task_id"), owner_profile, notifier_profile,
- )
- continue
- platform = (sub.get("platform") or "").lower()
- if platform not in active_platforms:
- logger.debug(
- "kanban notifier: subscription for %s on %s skipped; adapter not connected",
- sub.get("task_id"), platform or "<missing>",
- )
- continue
- old_cursor, cursor, events = kb.claim_unseen_events_for_sub(
- conn,
- task_id=sub["task_id"],
- platform=sub["platform"],
- chat_id=sub["chat_id"],
- thread_id=sub.get("thread_id") or "",
- kinds=TERMINAL_KINDS,
+ claimed = _claim_for_sub(
+ kb, conn, slug, sub, notifier_profile=notifier_profile,
+ profile_adapters=profile_adapters, active_platforms=active_platforms,
)
- if not events:
- continue
- task = kb.get_task(conn, sub["task_id"])
- logger.debug(
- "kanban notifier: claimed %d event(s) for %s on board %s cursor %s→%s",
- len(events), sub["task_id"], slug, old_cursor, cursor,
- )
- deliveries.append({
- "sub": sub,
- "old_cursor": old_cursor,
- "cursor": cursor,
- "events": events,
- "task": task,
- "board": slug,
- })
+ if claimed is not None:
+ deliveries.append(claimed)
except Exception as sub_exc:
# One bad subscription must not block the rest of the tick.
logger.warning(
@@ -273,79 +235,60 @@ def _notifier_collect_board(
conn.close()
-# ---------------------------------------------------------------------------
-# Per-event message formatting: kind -> (msg, wake_handoff, wake_review_detail)
-# ---------------------------------------------------------------------------
-# ``None`` for handoff / review_detail leaves the accumulated wake value
-# untouched. ``_payload(ev, key)`` is the shared "payload present and truthy" read.
+# --- Per-event message formatting: kind -> (msg, wake_handoff, wake_review_detail) ---
+# ``None`` for handoff / review_detail leaves the accumulated wake value untouched.
def _payload(ev: Any, key: str) -> Any:
+ """Shared "payload present and truthy" read."""
return ev.payload.get(key) if ev.payload and ev.payload.get(key) else None
+def _clip(ev: Any, key: str, fmt: str, limit: int) -> str:
+ """``fmt`` applied to the truncated payload value, or ``""`` when absent."""
+ value = _payload(ev, key)
+ return fmt.format(str(value)[:limit]) if value else ""
+
+
def _first_line(text: str, limit: int) -> str:
lines = text.strip().splitlines()
return lines[0][:limit] if lines else text[:limit]
def _fmt_completed(ev, n) -> tuple:
- # Prefer the run summary from the event payload; fall back to
- # task.result for legacy rows.
- handoff = ""
+ # Prefer the run summary from the event payload; fall back to task.result for legacy rows.
wake_handoff = None
payload_summary = _payload(ev, "summary")
if payload_summary:
wake_handoff = _first_line(str(payload_summary), 200)
- handoff = f"\n{wake_handoff}"
elif n.task and n.task.result:
wake_handoff = _first_line(n.task.result, 160)
- handoff = f"\n{wake_handoff}"
- msg = (
- f"✔ {n.board_tag}{n.tag}Kanban {n.task_id} done"
- f" — {n.title}{handoff}"
- )
- return msg, wake_handoff, None
+ handoff = f"\n{wake_handoff}" if wake_handoff is not None else ""
+ return f"✔ {n.head} done — {n.title}{handoff}", wake_handoff, None
def _fmt_blocked(ev, n) -> tuple:
- reason = _payload(ev, "reason")
- reason = f": {str(reason)[:160]}" if reason else ""
- return f"⏸ {n.board_tag}{n.tag}Kanban {n.task_id} blocked{reason}", None, None
+ reason = _clip(ev, "reason", ": {}", 160)
+ return f"⏸ {n.head} blocked{reason}", None, None
def _fmt_gave_up(ev, n) -> tuple:
- err = _payload(ev, "error")
- err = f"\n{str(err)[:200]}" if err else ""
- msg = (
- f"✖ {n.board_tag}{n.tag}Kanban {n.task_id} gave up "
- f"after repeated spawn failures{err}"
- )
- return msg, None, None
+ err = _clip(ev, "error", "\n{}", 200)
+ return f"✖ {n.head} gave up after repeated spawn failures{err}", None, None
def _fmt_crashed(ev, n) -> tuple:
- msg = (
- f"✖ {n.board_tag}{n.tag}Kanban {n.task_id} worker crashed "
- f"(pid gone); dispatcher will retry"
- )
- return msg, None, None
+ return f"✖ {n.head} worker crashed (pid gone); dispatcher will retry", None, None
def _fmt_timed_out(ev, n) -> tuple:
limit = _payload(ev, "limit_seconds")
- limit = int(limit) if limit else 0
- msg = (
- f"⏱ {n.board_tag}{n.tag}Kanban {n.task_id} timed out "
- f"(max_runtime={limit}s); will retry"
- )
- return msg, None, None
+ return f"⏱ {n.head} timed out (max_runtime={int(limit) if limit else 0}s); will retry", None, None
def _fmt_status(ev, n) -> tuple:
new_status = _payload(ev, "status")
- new_status = str(new_status) if new_status else ""
- return f"🔄 {n.board_tag}{n.tag}Kanban {n.task_id} → {new_status}", None, None
+ return f"🔄 {n.head} → {str(new_status) if new_status else ''}", None, None
def _fmt_review_requested(ev, n) -> tuple:
@@ -358,11 +301,7 @@ def _fmt_review_requested(ev, n) -> tuple:
summary = str(summary)
handoff = f"\n{summary[:200]}"
wake_handoff = _first_line(summary, 200)
- msg = (
- f"👀 {n.board_tag}{n.tag}Kanban {n.task_id} ready for review"
- f" — {n.title}{handoff}"
- )
- return msg, wake_handoff, None
+ return f"👀 {n.head} ready for review — {n.title}{handoff}", wake_handoff, None
def _fmt_changes_requested(ev, n) -> tuple:
@@ -371,30 +310,20 @@ def _fmt_changes_requested(ev, n) -> tuple:
reviewer = _safe_review_reason(payload.get("reviewer"), 48)
implementer = _safe_review_reason(payload.get("implementer"), 48)
reason_text = reason or "reviewer feedback requires changes"
- provenance = ""
- if reviewer:
- provenance += f" — reviewer @{reviewer}"
+ provenance = f" — reviewer @{reviewer}" if reviewer else ""
if implementer:
provenance += f" → implementer @{implementer}"
- msg = (
- f"🛑 {n.board_tag}Kanban {n.task_id} review requested "
- f"changes/BLOCK: {reason_text}{provenance}"
- )
+ msg = f"🛑 {n.board_tag}Kanban {n.task_id} review requested changes/BLOCK: {reason_text}{provenance}"
return msg, None, reason_text
def _fmt_block_loop_detected(ev, n) -> tuple:
# Re-blocked for the same cause past the limit and routed to `triage`
# for a human. It emits no blocked/status event, so ping loudly here.
- reason = _payload(ev, "reason")
- reason = f": {str(reason)[:160]}" if reason else ""
- recurrences = ev.payload.get("recurrences") if ev.payload else None
+ recurrences = _payload(ev, "recurrences")
rc = f" (blocked {recurrences}x for the same cause)" if recurrences else ""
- msg = (
- f"🛑 {n.board_tag}{n.tag}Kanban {n.task_id} routed to TRIAGE"
- f" — needs a human decision{rc}{reason}"
- )
- return msg, None, None
+ reason = _clip(ev, "reason", ": {}", 160)
+ return f"🛑 {n.head} routed to TRIAGE — needs a human decision{rc}{reason}", None, None
# archived / unblocked are claimed (so the cursor advances past them) but
@@ -413,9 +342,7 @@ _EVENT_FORMATTERS: dict[str, Callable[[Any, "_KanbanNotification"], tuple]] = {
}
-# ---------------------------------------------------------------------------
-# Delivery of one claimed batch (one subscription, N events)
-# ---------------------------------------------------------------------------
+# --- Delivery of one claimed batch (one subscription, N events) ---
class _KanbanNotification:
@@ -445,6 +372,7 @@ class _KanbanNotification:
# Attribute the ping to the worker that did the work.
who = task.assignee if task and task.assignee else None
self.tag = f"@{who} " if who else ""
+ self.head = f"{self.board_tag}{self.tag}Kanban {self.task_id}"
# The wake self-post path needs the key even when every event was skipped.
self.sub_key = (sub["task_id"], sub["platform"], sub["chat_id"], sub.get("thread_id") or "")
mode = sub.get("delivery_mode") or "notify"
@@ -513,11 +441,7 @@ class _KanbanNotification:
def build_wake_text(self) -> None:
"""Set ``wake_kinds`` / ``session_key`` / ``synth`` for the wake paths."""
task, sub = self.task, self.sub
- self.wake_kinds = (
- {ev.kind for ev in self.d["events"] if ev.kind in _WAKE_KINDS}
- if self.wake_agent
- else set()
- )
+ self.wake_kinds = {ev.kind for ev in self.d["events"] if ev.kind in _WAKE_KINDS} if self.wake_agent else set()
if not self.wake_kinds:
return
if self.is_push_adapter:
@@ -532,11 +456,8 @@ class _KanbanNotification:
_status = t("gateway.kanban.wake.status_joiner").join(_parts) or t("gateway.kanban.wake.status_default")
synth = t(
"gateway.kanban.wake.message",
- task_id=sub["task_id"],
- status=_status,
- title=self.title,
- assignee=task.assignee if task else "",
- board=self.board_slug,
+ task_id=sub["task_id"], status=_status, title=self.title,
+ assignee=task.assignee if task else "", board=self.board_slug,
)
# Label as an automatic notification and carry the handoff so the
# creator inspects the board instead of re-decomposing.
@@ -557,26 +478,20 @@ class _KanbanNotification:
from gateway.session import SessionSource
from gateway.wake import deliver_wake
sub = self.sub
- # Rebuild the creator's real session scope from the persisted
- # chat_type: build_session_key() keys DMs differently from
- # group/thread, so a hardcoded "group" mis-routed DM/thread creators
- # into a fresh session. Legacy rows may carry chat_type in
- # delivery_metadata; last resort is "group". A mismatch only degrades
- # to a fresh session.
+ # Rebuild the creator's real session scope from the persisted chat_type:
+ # build_session_key() keys DMs differently from group/thread, so a
+ # hardcoded "group" mis-routed DM/thread creators into a fresh session.
+ # Legacy rows may carry chat_type in delivery_metadata; last resort is
+ # "group". A mismatch only degrades to a fresh session.
_chat_type = str(sub.get("chat_type") or "").strip()
if not _chat_type:
_delivery_meta = sub.get("delivery_metadata")
if isinstance(_delivery_meta, dict):
_chat_type = str(_delivery_meta.get("chat_type") or "").strip()
_source = SessionSource(
- platform=self.plat,
- chat_id=sub["chat_id"],
- chat_type=_chat_type or "group",
- thread_id=sub.get("thread_id") or None,
- user_id=sub.get("user_id"),
- user_id_alt=sub.get("user_id_alt"),
- profile=self.sub_profile or None,
- scope_id=_wake_scope_id(self.adapter, sub),
+ platform=self.plat, chat_id=sub["chat_id"], chat_type=_chat_type or "group",
+ thread_id=sub.get("thread_id") or None, user_id=sub.get("user_id"), user_id_alt=sub.get("user_id_alt"),
+ profile=self.sub_profile or None, scope_id=_wake_scope_id(self.adapter, sub),
)
await deliver_wake(self.adapter, text=self.synth, session_id=self.session_key, source=_source)
self._log_woke()
@@ -606,17 +521,11 @@ class _KanbanNotification:
if ev.kind == "completed":
try:
await self.runner._deliver_kanban_artifacts(
- adapter=adapter,
- chat_id=sub["chat_id"],
- metadata=metadata,
- event_payload=getattr(ev, "payload", None),
- task=self.task,
+ adapter=adapter, chat_id=sub["chat_id"], metadata=metadata,
+ event_payload=getattr(ev, "payload", None), task=self.task,
)
except Exception as art_exc:
- logger.debug(
- "kanban notifier: artifact delivery for %s failed: %s",
- self.task_id, art_exc,
- )
+ logger.debug("kanban notifier: artifact delivery for %s failed: %s", self.task_id, art_exc)
async def _send_pings(self) -> bool:
"""Send every text ping; False when a send failed (claim already rewound/dropped)."""
@@ -671,7 +580,7 @@ class _KanbanNotification:
await self.rewind()
return
self.adapter = adapter
- from gateway.wake import adapter_supports_push
+ from gateway.wake import adapter_supports_push, deliver_wake
self.is_push_adapter = adapter_supports_push(adapter)
if not await self._send_pings():
@@ -683,7 +592,6 @@ class _KanbanNotification:
if not is_push and wake_kinds and self.session_key:
# Self-post IS the delivery: must succeed BEFORE the cursor advances.
- from gateway.wake import deliver_wake
try:
await deliver_wake(adapter, text=self.synth, session_id=self.session_key)
self._log_woke()
@@ -713,10 +621,7 @@ class _KanbanNotification:
try:
await self.push_wake()
except Exception as _wk_err:
- logger.warning(
- "kanban notifier: wakeup injection failed for %s: %s",
- self.task_id, _wk_err, exc_info=True,
- )
+ logger.warning("kanban notifier: wakeup injection failed for %s: %s", self.task_id, _wk_err, exc_info=True)
# Unsubscribe only on archive; ``done`` is reversible.
if task_terminal:
await self.unsub()