The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(kanban): GC stale done-task notify subscriptions
Tekniumc69231270432
diff --git a/gateway/kanban_watchers.py b/gateway/kanban_watchers.pyindex a60caaf4bd7..f5018e18c0c 100644--- a/gateway/kanban_watchers.py+++ b/gateway/kanban_watchers.py@@ -255,8 +255,35 @@ class GatewayKanbanWatchersMixin:# Initial delay so the gateway can finish wiring adapters.await asyncio.sleep(5)+ # Stale done-sub GC cadence. Subscriptions survive ``done`` (it is+ # reversible), so boards that never archive would otherwise+ # accumulate rows scanned on every 5s tick forever. The sweep is a+ # single DELETE per board, gated to once per watcher startup and at+ # most once per hour thereafter — cheap relative to the tick's own+ # per-sub claims. Retention is kanban.done_sub_retention_days in+ # config.yaml (default 30; 0 disables), re-read at each sweep so a+ # config change applies without a restart.+ _GC_INTERVAL_SECONDS = 3600.0+ _gc_next_at = 0.0 # 0 → sweep on the first tick after startup+while self._running:try:+ _gc_due = time.monotonic() >= _gc_next_at+ _gc_retention_days = 30+ if _gc_due:+ _gc_next_at = time.monotonic() + _GC_INTERVAL_SECONDS+ try:+ from hermes_cli.config import load_config as _load_cfg++ _kanban_cfg = (_load_cfg() or {}).get("kanban") or {}+ _gc_retention_days = int(+ _kanban_cfg.get("done_sub_retention_days", 30)+ )+ except Exception:+ # Fail safe on the shipped default; the sweep itself+ # treats <= 0 as disabled.+ _gc_retention_days = 30+def _collect():deliveries: list[dict] = []include_unowned = self._owns_kanban_dispatcher_lock()@@ -346,6 +373,28 @@ class GatewayKanbanWatchersMixin:logger.debug("kanban notifier: cannot open board %s: %s", slug, exc)continuetry:+ if _gc_due:+ # Hourly (plus once at startup) stale-sub GC:+ # drop subscriptions for tasks that have been+ # ``done`` untouched past the retention+ # window. Best-effort — a failed sweep never+ # blocks delivery; the next hourly gate+ # retries it.+ 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-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,+ )# `connect()` runs the schema + idempotent migration# on first open per process, so an explicit# `init_db()` here would be redundant. Worse:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex e4a489b5ce1..584b10b36ad 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2436,6 +2436,14 @@ DEFAULT_CONFIG = {# to the TTL/crash/stale recovery paths. Set false to keep orphans# frozen for manual forensics."reconcile_orphans": True,+ # Notify subscriptions survive a task reaching ``done`` (completion+ # is reversible — controllers reopen done work for review+ # corrections), and are normally removed on archive. On boards that+ # never archive, the notifier GC purges subscriptions for tasks+ # that have been ``done`` with no new activity for this many days,+ # so stale rows don't accumulate and get scanned on every notifier+ # tick forever. Set 0 to disable the sweep.+ "done_sub_retention_days": 30,},# execute_code settings — controls the tool used for programmatic tool calls.diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.pyindex d770de2a838..05a1873c111 100644--- a/hermes_cli/kanban_db.py+++ b/hermes_cli/kanban_db.py@@ -11247,6 +11247,51 @@ def remove_notify_sub(return cur.rowcount > 0+def purge_stale_done_notify_subs(+ conn: sqlite3.Connection,+ *,+ max_age_days: int = 30,+) -> int:+ """Delete notify subscriptions whose task has sat in ``done`` 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. 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.+ """+ try:+ days = int(max_age_days)+ except (TypeError, ValueError):+ days = 30+ if days <= 0:+ return 0+ cutoff = int(time.time()) - days * 86400+ with write_txn(conn):+ cur = conn.execute(+ "DELETE FROM kanban_notify_subs WHERE task_id IN ("+ " SELECT t.id FROM tasks t"+ " WHERE t.status = 'done'"+ " AND COALESCE("+ " (SELECT MAX(e.created_at) FROM task_events e"+ " WHERE e.task_id = t.id),"+ " t.completed_at, t.created_at, 0"+ " ) < ?)",+ (cutoff,),+ )+ return int(cur.rowcount or 0)++def unseen_events_for_sub(conn: sqlite3.Connection,*,diff --git a/tests/hermes_cli/test_kanban_notify.py b/tests/hermes_cli/test_kanban_notify.pyindex 28299e3e5fb..ec01f5a5d34 100644--- a/tests/hermes_cli/test_kanban_notify.py+++ b/tests/hermes_cli/test_kanban_notify.py@@ -1011,3 +1011,122 @@ def test_create_with_parents_inherits_delivery_metadata(kanban_home):finally:conn.close()_assert_full_inherited_sub(subs)+++# ---------------------------------------------------------------------------+# Stale done-subscription GC (purge_stale_done_notify_subs)+# ---------------------------------------------------------------------------++def _make_done_task_with_sub(kb, conn, *, title, chat_id):+ tid = kb.create_task(conn, title=title, assignee="worker1")+ kb.add_notify_sub(+ conn, task_id=tid, platform="telegram", chat_id=chat_id,+ notifier_profile="default",+ )+ assert kb.complete_task(conn, tid, summary="done")+ return tid+++def _backdate_task(kb, conn, tid, *, days):+ """Push a task's entire event history + completion into the past."""+ past = int(__import__("time").time()) - days * 86400+ with kb.write_txn(conn):+ conn.execute(+ "UPDATE task_events SET created_at = ? WHERE task_id = ?",+ (past, tid),+ )+ conn.execute(+ "UPDATE tasks SET completed_at = ?, created_at = ? WHERE id = ?",+ (past, past, tid),+ )+++def test_gc_purges_stale_done_sub_keeps_fresh_one(kanban_home):+ import hermes_cli.kanban_db as kb++ conn = kb.connect()+ try:+ stale = _make_done_task_with_sub(kb, conn, title="old done", chat_id="c-stale")+ fresh = _make_done_task_with_sub(kb, conn, title="new done", chat_id="c-fresh")+ _backdate_task(kb, conn, stale, days=45)++ purged = kb.purge_stale_done_notify_subs(conn, max_age_days=30)++ assert purged == 1+ assert kb.list_notify_subs(conn, stale) == []+ # A done task inside the retention window keeps its subscription —+ # it may still be reopened for review corrections.+ assert len(kb.list_notify_subs(conn, fresh)) == 1+ finally:+ conn.close()+++def test_gc_honors_configured_retention_days(kanban_home):+ import hermes_cli.kanban_db as kb+ from hermes_cli.config_defaults import DEFAULT_CONFIG++ # The watcher reads kanban.done_sub_retention_days from config; the+ # shipped default must exist and drive the sweep when passed through.+ default_days = DEFAULT_CONFIG["kanban"]["done_sub_retention_days"]+ assert isinstance(default_days, int) and default_days > 0++ conn = kb.connect()+ try:+ tid = _make_done_task_with_sub(kb, conn, title="ten days old", chat_id="c-10d")+ _backdate_task(kb, conn, tid, days=10)++ # Under the shipped default (>= 30d) a 10-day-old done task is fresh.+ assert kb.purge_stale_done_notify_subs(conn, max_age_days=default_days) == 0+ assert len(kb.list_notify_subs(conn, tid)) == 1++ # A tighter user-configured retention purges the same row.+ assert kb.purge_stale_done_notify_subs(conn, max_age_days=7) == 1+ assert kb.list_notify_subs(conn, tid) == []++ # Zero (and below) disables the sweep entirely.+ tid2 = _make_done_task_with_sub(kb, conn, title="ancient", chat_id="c-anc")+ _backdate_task(kb, conn, tid2, days=3650)+ assert kb.purge_stale_done_notify_subs(conn, max_age_days=0) == 0+ assert len(kb.list_notify_subs(conn, tid2)) == 1+ finally:+ conn.close()+++def test_gc_spares_reopened_task_even_when_old(kanban_home):+ import hermes_cli.kanban_db as kb++ conn = kb.connect()+ try:+ tid = _make_done_task_with_sub(kb, conn, title="reopened", chat_id="c-reopen")+ _backdate_task(kb, conn, tid, days=90)+ # Reopen: the task leaves ``done``, so even with an ancient event+ # history the GC must not touch its subscription.+ with kb.write_txn(conn):+ conn.execute("UPDATE tasks SET status = 'ready' WHERE id = ?", (tid,))+ kb._append_event(conn, tid, "status", {"status": "ready"})+ # Backdate the reopen event too — status alone must protect it.+ _backdate_task(kb, conn, tid, days=90)++ assert kb.purge_stale_done_notify_subs(conn, max_age_days=30) == 0+ assert len(kb.list_notify_subs(conn, tid)) == 1+ finally:+ conn.close()+++def test_gc_archived_rows_already_removed_by_unsub(kanban_home):+ import hermes_cli.kanban_db as kb++ conn = kb.connect()+ try:+ tid = _make_done_task_with_sub(kb, conn, title="archived", chat_id="c-arch")+ assert kb.archive_task(conn, tid)+ # The notifier removes the sub at archive time; the GC targets only+ # ``done`` tasks, so an archived task contributes nothing to purge.+ kb.remove_notify_sub(+ conn, task_id=tid, platform="telegram", chat_id="c-arch",+ )+ _backdate_task(kb, conn, tid, days=365)+ assert kb.purge_stale_done_notify_subs(conn, max_age_days=30) == 0+ assert kb.list_notify_subs(conn, tid) == []+ finally:+ conn.close()diff --git a/website/docs/user-guide/features/kanban.md b/website/docs/user-guide/features/kanban.mdindex 88bcc392d91..b978f97c912 100644--- a/website/docs/user-guide/features/kanban.md+++ b/website/docs/user-guide/features/kanban.md@@ -614,6 +614,7 @@ Config knobs (all under `kanban:` in `~/.hermes/config.yaml`):| `orchestrator_profile` | `""` | Profile assigned to the root/orchestration task after decomposition. Empty = fall back to active default profile. || `default_assignee` | `""` | Where a child task lands when the LLM picks an unknown profile. Empty = fall back to active default. || `auto_subscribe_on_create` | `true` | When `kanban_create` runs inside a persistent gateway/TUI session, terminal events resume that originating agent with a synthetic status turn. Set to `false` for passive completion or to require explicit `kanban_notify-subscribe` calls. Independent of `auto_decompose`. |+| `done_sub_retention_days` | `30` | Notify subscriptions survive `done` (reopen-safe) and are removed on `archived`. The notifier GC purges subscriptions whose task has been `done` with no new events for this many days, bounding sub-table growth on boards that never archive. `0` disables the sweep. |And the two auxiliary LLM slots:@@ -886,7 +887,7 @@ bot> ✓ t_9fc1a3 completed by transcribertranscribed 42 minutes, saved to podcast/2026-05-04.md```-Subscriptions auto-remove themselves once the task reaches `done` or `archived`. If you script a create with `--json` (machine output) the auto-subscribe is skipped — the assumption is that scripted callers want to manage subscriptions explicitly via `/kanban notify-subscribe`.+Subscriptions survive a task reaching `done` — completion is reversible (a reviewer or controller can reopen a done task), so the origin session keeps getting notified through reopen cycles. They auto-remove on `archived` (the irreversible end state). On boards that never archive, a GC sweep purges subscriptions for tasks that have sat in `done` with no new activity for `kanban.done_sub_retention_days` days (default 30; set 0 to disable), so stale rows don't accumulate forever. If you script a create with `--json` (machine output) the auto-subscribe is skipped — the assumption is that scripted callers want to manage subscriptions explicitly via `/kanban notify-subscribe`.A chat-originated auto-subscribe is created in `notify+wake` mode: on a terminal event the destination agent both receives the passive message **and** takes a real turn, so it can read the board context and reply in its own voice. See [Delivery modes](#delivery-modes) below.