Skip to content

The agent that grows with you

fix(kanban): refuse to resume a Kanban-owned worker session as an untracked writer

Austin Pickettd53b1720e671
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index c365e68f17e..6ce8a4eda5a 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -787,6 +787,16 @@ class CLIAgentSetupMixin:
session_meta,
lambda rid: self._console_print(
f"[dim]{_escape(t('cli.resume.compressed_into', session_id=self.session_id, descendant=rid))}[/]"))
+ # A Kanban worker transcript resumes only through a dispatcher-owned run (#68779) —
+ # an ordinary CLI resume would be a live writer the board cannot observe. Refuse AND
+ # fall back to a fresh session id, so this process never appends to the worker row.
+ from hermes_cli.kanban_resume_guard import kanban_resume_refusal
+ if (kanban_refusal := kanban_resume_refusal(self._session_db, self.session_id)):
+ self._console_print(f"[bold red]{_escape(kanban_refusal)}[/]")
+ self._resumed = False
+ from hermes_state_ids import new_session_id
+ self.session_id = new_session_id(self.session_start)
+ return False
resume_limit_error = self._resume_history_limit_error()
if resume_limit_error:
self._resume_history_error = resume_limit_error
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index 49782c48019..5645b6690b9 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -998,6 +998,13 @@ class CLICommandsMixin(CLICommandsSessionToolsMixin):
if resolved is None:
return
target_id, session_meta = resolved
+ # A Kanban worker transcript must not become this chat's write-capable continuation
+ # (#68779): the resumed conversation would be a writer the Kanban board cannot
+ # observe, and unblocking the card could dispatch a competing worker. Keep the
+ # CURRENT session instead of switching.
+ from hermes_cli.kanban_resume_guard import kanban_resume_refusal
+ if (kanban_refusal := kanban_resume_refusal(self._session_db, target_id)):
+ return _cp(f" {kanban_refusal}")
if target_id == self.session_id:
return _cp(f" {_t('resume.already_on')}")
old_session_id = self.session_id
diff --git a/hermes_cli/kanban_resume_guard.py b/hermes_cli/kanban_resume_guard.py
new file mode 100644
index 00000000000..5323c246138
--- /dev/null
+++ b/hermes_cli/kanban_resume_guard.py
@@ -0,0 +1,69 @@
+"""Centralized resume-time guard for Kanban-owned sessions (#68779) — the ONE place that
+decides whether a Kanban worker transcript may resume as an ordinary session.
+
+A Kanban dispatcher worker transcript must never continue as a write-capable ordinary
+CLI / Desktop / TUI session: the resumed process carries none of the dispatcher-granted
+ownership env (``HERMES_KANBAN_TASK`` / ``HERMES_KANBAN_RUN_ID`` / ``HERMES_KANBAN_BOARD`` /
+``HERMES_KANBAN_CLAIM_LOCK``), so the board cannot observe or supervise it — and unblocking
+the card can then dispatch a second writer into the same workspace. Every surface that makes
+a resumed session WRITE-CAPABLE asks this guard before loading history:
+
+- interactive CLI ``--resume`` / ``-c`` (``HermesCLI._preload_resumed_session``),
+- mid-chat ``/resume`` / ``/sessions <id>`` (``_handle_resume_command``),
+- quiet one-shot resume (``hermes_cli/oneshot.py``),
+- gateway ``session.resume`` — Desktop session history and the TUI picker
+ (``tui_gateway/methods_session.py``).
+
+Detection is persisted provenance (``SessionDB.is_kanban_owned_session``: the session row's
+``kanban`` source, checked across the compression lineage a resume would materialize) plus
+dispatch-time env for the exemption: a process that itself holds ``HERMES_KANBAN_TASK`` is a
+dispatcher-owned run — the one legitimate supervised continuation — and may proceed.
+"""
+
+import logging
+import os
+
+logger = logging.getLogger(__name__)
+
+
+def _dispatcher_owned_run() -> bool:
+ """This process holds a dispatcher-granted Kanban task (``HERMES_KANBAN_TASK``, exactly
+ what ``_default_spawn`` injects into worker children). That is the grant boundary: only a
+ run the dispatcher owns — task, run id, claim, heartbeat — may continue a worker
+ transcript, so it is exempt from the guard."""
+ try:
+ from gateway.session_context import get_session_env
+ except ImportError: # no gateway context (plain CLI child) — read the process env
+ get_session_env = os.environ.get
+ return bool(str(get_session_env("HERMES_KANBAN_TASK", "") or "").strip())
+
+
+def kanban_resume_refusal(db, session_id: str):
+ """Human-readable refusal reason when ``session_id`` is a Kanban-owned session that must
+ NOT resume as an ordinary write-capable session, or ``None`` when the resume may proceed.
+
+ Fails open ONLY for a store that cannot classify at all (a probe error must never block
+ an ordinary session); a POSITIVE kanban-provenance match always refuses. Read failures
+ are logged, not surfaced to the user as success.
+ """
+ if not session_id:
+ return None
+ if _dispatcher_owned_run():
+ return None
+ probe = getattr(db, "is_kanban_owned_session", None)
+ if probe is None: # lightweight adaptor DB without the method — cannot classify
+ return None
+ try:
+ owned = probe(session_id)
+ except Exception:
+ # Deliberate fail-open boundary: an ordinary session must never be blocked by a
+ # broken probe, so classify as unknown and log the full traceback for diagnosis.
+ logger.warning("kanban resume probe failed for %s (proceeding unclassified)",
+ session_id, exc_info=True)
+ return None
+ # Strict True: SessionDB answers a real bool; anything else (a test double, an adaptor
+ # quirk) is treated as unclassified, keeping the guard open for every non-worker store.
+ if owned is not True:
+ return None
+ from agent.i18n import t
+ return t("cli.resume.kanban_owned", session_id=session_id)
diff --git a/hermes_cli/oneshot.py b/hermes_cli/oneshot.py
index b9eb2d48708..4ce668b1900 100644
--- a/hermes_cli/oneshot.py
+++ b/hermes_cli/oneshot.py
@@ -460,6 +460,11 @@ def _load_resume_target(session_db, resume: Optional[str]) -> tuple[Optional[str
session_meta = session_db.get_session(resolved)
if not session_meta:
raise RuntimeError(f"session not found: {resume}")
+ # A Kanban worker transcript resumes only through a dispatcher-owned run (#68779): a
+ # quiet one-shot resume would be a write-capable process the board cannot observe.
+ from hermes_cli.kanban_resume_guard import kanban_resume_refusal
+ if (kanban_refusal := kanban_resume_refusal(session_db, resolved)) is not None:
+ raise RuntimeError(f"cannot resume session {resume}: {kanban_refusal}")
session_db.assert_resume_safe(resolved, tip_only=True)
restored, _display = session_db.get_resume_conversations(resolved)
history = [m for m in restored if m.get("role") != "session_meta"]
diff --git a/hermes_state.py b/hermes_state.py
index 7ae87ae2ecd..d7867ade9ad 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -30,7 +30,8 @@ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar
from hermes_state_common import (
TITLE_SOURCE_DERIVED as _TITLE_SOURCE_DERIVED, TITLE_SOURCE_LLM as _TITLE_SOURCE_LLM,
TITLE_SOURCE_USER as _TITLE_SOURCE_USER,
- escape_like as _escape_like, stat_db_file_identity as _stat_db_file_identity,
+ escape_like as _escape_like, _placeholders,
+ stat_db_file_identity as _stat_db_file_identity,
)
from hermes_state_holders import read_only_db_uri
from hermes_state_pidns import holder_pid_checkable
@@ -1668,6 +1669,28 @@ class SessionDB(
return retagged
return self._execute_write(_do)
+ def is_kanban_owned_session(self, session_id: str) -> bool:
+ """True when this session — or any segment of the compression lineage a resume would
+ materialize — belongs to the Kanban dispatcher (``source``/``created_source`` =
+ ``'kanban'``): the transcript of a worker run, not a human conversation (#68779).
+
+ Both columns are checked: ``source`` is live routing state the dispatcher tags
+ (``HERMES_SESSION_SOURCE=kanban``) and the legacy retag rewrites, while immutable
+ ``created_source`` survives later surface flips. The lineage is the VERIFIED
+ compression chain (``_resume_lineage_ids``) — exactly the rows a resume loads — so a
+ worker transcript stays kanban-owned across rotations, while a delegate/branch child
+ of a worker (a DIFFERENT conversation) is not swept in. Plain classification, not a
+ gate: the resume-time guard (``hermes_cli/kanban_resume_guard.py``) owns the decision
+ and the dispatcher-owned exemption."""
+ lineage = self._resume_lineage_ids(session_id)
+ if not lineage:
+ return False
+ rows = self._read_all(
+ f"SELECT 1 FROM sessions WHERE id IN ({_placeholders(lineage)}) "
+ "AND (source = 'kanban' OR created_source = 'kanban') LIMIT 1",
+ tuple(lineage))
+ return bool(rows)
+
def list_meta_prefix(self, prefix: str) -> List[Tuple[str, str]]:
"""``[(key, value), ...]`` for state_meta keys starting with the literal
``prefix`` (LIKE wildcards escaped) — e.g. ``loop:<session_id>`` rows."""
diff --git a/locales/af.yaml b/locales/af.yaml
index a3e0e38350d..8ce322f8fe9 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Sessie nie gevind nie: {session_id}"
compressed_into: "Sessie {session_id} is in {descendant} saamgepers; die afstammeling word met jou transkripsie hervat."
cannot_resume: "Kan nie sessie hervat nie: {error}"
+ kanban_owned: "⛔ Sessie {session_id} is 'n Kanban-werker-transkripsie. Om dit hier te hervat sou 'n skrywer skep wat die Kanban-raad nie kan waarneem of toesien hou nie — probeer eerder die kaart op die raad weer of ontblok dit, sodat die dispatcher die volgende lopie besit."
cannot_resume_prefix: "Kan nie sessie hervat nie:"
resumed_session: "↻ Sessie hervat"
counts_one: "({count} gebruikersboodskap, {total} boodskappe altesaam)"
diff --git a/locales/ar.yaml b/locales/ar.yaml
index d04319da91e..998e1e7213b 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "الجلسة غير موجودة: {session_id}"
compressed_into: "ضُغطت الجلسة {session_id} في {descendant}؛ جارٍ استئناف الجلسة المتفرّعة مع نصّ محادثتك."
cannot_resume: "تعذّر استئناف الجلسة: {error}"
+ kanban_owned: "⛔ الجلسة {session_id} هي نص جلسة عامل Kanban. استئنافها هنا سينشئ كاتبًا لا يستطيع لوح Kanban مراقبته أو الإشراف عليه — بدلًا من ذلك أعد المحاولة أو ارفع الحظر عن البطاقة على اللوحة ليمتلك المُرسِل التشغيل التالي."
cannot_resume_prefix: "تعذّر استئناف الجلسة:"
resumed_session: "↻ استُؤنفت الجلسة"
counts_one: "({count} رسالة من المستخدم، {total} رسائل إجمالًا)"
diff --git a/locales/de.yaml b/locales/de.yaml
index 24065a26cf3..fca635ee1c5 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Sitzung nicht gefunden: {session_id}"
compressed_into: "Sitzung {session_id} wurde in {descendant} komprimiert; die Nachfolgesitzung wird mit Ihrem Transkript fortgesetzt."
cannot_resume: "Sitzung kann nicht fortgesetzt werden: {error}"
+ kanban_owned: "⛔ Sitzung {session_id} ist ein Kanban-Worker-Transkript. Das Fortsetzen würde hier einen Schreiber erzeugen, den das Kanban-Board weder beobachten noch überwachen kann — versuche stattdessen, die Karte auf dem Board erneut zu starten oder zu entblocken, damit der Dispatcher den nächsten Lauf besitzt."
cannot_resume_prefix: "Sitzung kann nicht fortgesetzt werden:"
resumed_session: "↻ Sitzung fortgesetzt"
counts_one: "({count} Benutzernachricht, {total} Nachrichten insgesamt)"
diff --git a/locales/en.yaml b/locales/en.yaml
index b72265e47e9..10c39f1e8f8 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -2493,6 +2493,7 @@ cli:
compressed_into: "Session {session_id} was compressed into {descendant}; resuming the descendant with your transcript."
cannot_resume: "Cannot resume session: {error}"
cannot_resume_prefix: "Cannot resume session:"
+ kanban_owned: "⛔ Session {session_id} is a Kanban worker transcript. Resuming it here would create a writer the Kanban board cannot observe or supervise — retry or unblock the card on the board instead, so the dispatcher owns the next run."
resumed_session: "↻ Resumed session"
counts_one: "({count} user message, {total} total messages)"
counts_other: "({count} user messages, {total} total messages)"
diff --git a/locales/es.yaml b/locales/es.yaml
index 10c07384d0d..a4f33506a4d 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Sesión no encontrada: {session_id}"
compressed_into: "La sesión {session_id} se comprimió en {descendant}; reanudando la descendiente con tu transcripción."
cannot_resume: "No se puede reanudar la sesión: {error}"
+ kanban_owned: "⛔ La sesión {session_id} es una transcripción de un worker de Kanban. Reanudarla aquí crearía un escritor que el tablero Kanban no puede observar ni supervisar — reintenta o desbloquea la tarjeta en el tablero para que el dispatcher sea dueño de la siguiente ejecución."
cannot_resume_prefix: "No se puede reanudar la sesión:"
resumed_session: "↻ Sesión reanudada"
counts_one: "({count} mensaje del usuario, {total} mensajes en total)"
diff --git a/locales/fr.yaml b/locales/fr.yaml
index f8db3779d0b..ae9be7f3527 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -2665,6 +2665,7 @@ cli:
session_not_found: "Session introuvable : {session_id}"
compressed_into: "La session {session_id} a été compressée dans {descendant} ; reprise de la session descendante avec votre transcription."
cannot_resume: "Impossible de reprendre la session : {error}"
+ kanban_owned: "⛔ La session {session_id} est la transcription d'un worker Kanban. La reprendre ici créerait un écrivain que le tableau Kanban ne peut ni observer ni superviser — relance ou débloque plutôt la carte sur le tableau, afin que le dispatcher possède la prochaine exécution."
cannot_resume_prefix: "Impossible de reprendre la session :"
resumed_session: "↻ Session reprise"
counts_one: "({count} message utilisateur, {total} messages au total)"
diff --git a/locales/ga.yaml b/locales/ga.yaml
index 4e8df6e69e1..c6fe0933816 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Seisiún gan a aimsiú: {session_id}"
compressed_into: "Dlúthaíodh an seisiún {session_id} isteach i {descendant}; ag atosú an tsleachta le do thraschríbhinn."
cannot_resume: "Ní féidir an seisiún a atosú: {error}"
+ kanban_owned: "⛔ Is tras-scríbhinn oibrithe Kanban é an seisiún {session_id}. Athfhachtóirí a chur ar bun anseo a dhéanfadh scríbhneoir nach féidir le clár Kanban a fheiceáil ná a mhaorú — ina áit sin, bain triail arís ar an gcárta ar an gclár nó díbhlocáil é, ionas go mbeidh an cláróir ina thine ar an rith chugainn."
cannot_resume_prefix: "Ní féidir an seisiún a atosú:"
resumed_session: "↻ Seisiún atosaithe"
counts_one: "({count} teachtaireacht úsáideora, {total} teachtaireacht san iomlán)"
diff --git a/locales/hu.yaml b/locales/hu.yaml
index f405844bada..ddc0282df49 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -2409,6 +2409,7 @@ cli:
session_not_found: "A munkamenet nem található: {session_id}"
compressed_into: "A(z) {session_id} munkamenet a(z) {descendant} munkamenetbe lett tömörítve; a leszármazottat folytatom az átiratoddal."
cannot_resume: "A munkamenet nem folytatható: {error}"
+ kanban_owned: "⛔ A(z) {session_id} munkamenet egy Kanban-worker átirata. Itt folytatva egy olyan írót hozna létre, amelyet a Kanban-tábla nem tud megfigyelni vagy felügyelni — ehelyett próbáld újra vagy oldd fel a kártyát a táblán, hogy a dispatcher legyen a következő futás tulajdonosa."
cannot_resume_prefix: "A munkamenet nem folytatható:"
resumed_session: "↻ Munkamenet folytatva"
counts_one: "({count} felhasználói üzenet, összesen {total} üzenet)"
diff --git a/locales/it.yaml b/locales/it.yaml
index 5d79381abf2..ba6744f319e 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Sessione non trovata: {session_id}"
compressed_into: "La sessione {session_id} è stata compressa in {descendant}; riprendo la sessione discendente con la tua trascrizione."
cannot_resume: "Impossibile riprendere la sessione: {error}"
+ kanban_owned: "⛔ La sessione {session_id} è la trascrizione di un worker Kanban. Riprenderla qui creerebbe uno scrittore che la board Kanban non può osservare né supervisionare — invece riprova o sblocca la card sulla board, così il dispatcher possiede la prossima esecuzione."
cannot_resume_prefix: "Impossibile riprendere la sessione:"
resumed_session: "↻ Sessione ripresa"
counts_one: "({count} messaggio utente, {total} messaggi in totale)"
diff --git a/locales/ja.yaml b/locales/ja.yaml
index 9bd259d76ab..9cbc8544674 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "セッションが見つかりません: {session_id}"
compressed_into: "セッション {session_id} は {descendant} に圧縮されました。トランスクリプトを引き継いで後続セッションを再開します。"
cannot_resume: "セッションを再開できません: {error}"
+ kanban_owned: "⛔ セッション {session_id} は Kanban ワーカーのトランスクリプトです。ここで再開すると、Kanban ボードが観察・監督できない書き込みプロセスが生じます。代わりにボード上でカードを再試行するかブロック解除し、次の実行はディスパッチャーに所有させてください。"
cannot_resume_prefix: "セッションを再開できません:"
resumed_session: "↻ セッションを再開しました"
counts_one: "(ユーザーメッセージ {count} 件、合計 {total} 件)"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index a878ff3afa0..08e658bb814 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "세션을 찾을 수 없어요: {session_id}"
compressed_into: "세션 {session_id}은(는) {descendant}(으)로 압축됐어요. 기록과 함께 후속 세션을 재개해요."
cannot_resume: "세션을 재개할 수 없어요: {error}"
+ kanban_owned: "⛔ 세션 {session_id}은(는) Kanban 워커의 기록입니다. 여기서 재개하면 Kanban 보드가 관찰하거나 감독할 수 없는 작성자가 생깁니다 — 대신 보드에서 카드를 재시도하거나 차단을 해제하여 디스패처가 다음 실행을 소유하도록 하세요."
cannot_resume_prefix: "세션을 재개할 수 없어요:"
resumed_session: "↻ 세션 재개됨"
counts_one: "(사용자 메시지 {count}개, 전체 메시지 {total}개)"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index c65687beb9e..d84eac8b7da 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Sessão não encontrada: {session_id}"
compressed_into: "A sessão {session_id} foi comprimida em {descendant}; retomando a descendente com sua transcrição."
cannot_resume: "Não foi possível retomar a sessão: {error}"
+ kanban_owned: "⛔ A sessão {session_id} é a transcrição de um worker do Kanban. Retomá-la aqui criaria um escritor que o quadro Kanban não consegue observar nem supervisionar — em vez disso, tente novamente ou desbloqueie o cartão no quadro, para que o dispatcher possua a próxima execução."
cannot_resume_prefix: "Não foi possível retomar a sessão:"
resumed_session: "↻ Sessão retomada"
counts_one: "({count} mensagem do usuário, {total} mensagens no total)"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index 4c4d7a675d3..68f30150c3f 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Сеанс не найден: {session_id}"
compressed_into: "Сеанс {session_id} был сжат в {descendant}; возобновляем сеанс-потомок с вашей расшифровкой."
cannot_resume: "Не удалось возобновить сеанс: {error}"
+ kanban_owned: "⛔ Сессия {session_id} — это стенограмма Kanban-воркера. Её возобновление здесь создало бы писателя, которого Kanban-доска не может наблюдать или контролировать — вместо этого повторите попытку или разблокируйте карточку на доске, чтобы диспетчер владел следующим запуском."
cannot_resume_prefix: "Не удалось возобновить сеанс:"
resumed_session: "↻ Сеанс возобновлён"
counts_one: "({count} сообщение пользователя, всего сообщений: {total})"
diff --git a/locales/tr.yaml b/locales/tr.yaml
index 5c8a4c6e1c6..f2833ee574f 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Oturum bulunamadı: {session_id}"
compressed_into: "{session_id} oturumu {descendant} içine sıkıştırıldı; transkriptinizle alt oturum sürdürülüyor."
cannot_resume: "Oturum sürdürülemiyor: {error}"
+ kanban_owned: "⛔ Oturum {session_id} bir Kanban çalışanı transkriptidir. Burada sürdürmek, Kanban panosunun gözlemleyip denetleyemeyeceği bir yazıcı oluşturur — bunun yerine kartı panoda yeniden deneyin veya engelini kaldırın, böylece bir sonraki çalışmayı dispatch sahibi olur."
cannot_resume_prefix: "Oturum sürdürülemiyor:"
resumed_session: "↻ Oturum sürdürüldü"
counts_one: "({count} kullanıcı mesajı, toplam {total} mesaj)"
diff --git a/locales/uk.yaml b/locales/uk.yaml
index 278a90dd0a8..978b0bd8378 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "Сеанс не знайдено: {session_id}"
compressed_into: "Сеанс {session_id} було стиснуто в {descendant}; відновлюємо нащадок із вашою стенограмою."
cannot_resume: "Не вдалося відновити сеанс: {error}"
+ kanban_owned: "⛔ Сесія {session_id} — це стенограма Kanban-воркера. Її відновлення тут створило б пишучого, якого Kanban-дошка не може спостерігати чи контролювати — замість цього повторіть спробу або розблокуйте картку на дошці, щоб dispatcher володів наступним запуском."
cannot_resume_prefix: "Не вдалося відновити сеанс:"
resumed_session: "↻ Сеанс відновлено"
counts_one: "({count} повідомлення користувача, усього повідомлень: {total})"
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index 4a576d40ad6..b9fbd75e94c 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "找不到工作階段:{session_id}"
compressed_into: "工作階段 {session_id} 已壓縮為 {descendant};將以你的對話紀錄恢復後續的工作階段。"
cannot_resume: "無法恢復工作階段:{error}"
+ kanban_owned: "⛔ 工作階段 {session_id} 是 Kanban 工作執行緒的記錄。在此恢復會建立一個 Kanban 看板無法觀察或監督的寫入者——請改為在看板上重試或解除卡片的封鎖,讓調度器擁有下一次執行。"
cannot_resume_prefix: "無法恢復工作階段:"
resumed_session: "↻ 已恢復工作階段"
counts_one: "({count} 則使用者訊息,共 {total} 則訊息)"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index 1b37a2d48ec..f9d044363d2 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -2392,6 +2392,7 @@ cli:
session_not_found: "未找到会话:{session_id}"
compressed_into: "会话 {session_id} 已被压缩进 {descendant};将使用你的记录恢复后继会话。"
cannot_resume: "无法恢复会话:{error}"
+ kanban_owned: "⛔ 会话 {session_id} 是 Kanban 工作线程的记录。在此恢复会创建一个 Kanban 看板无法观察或监督的写入者——请改为在看板上重试或解除卡片的阻塞,让调度器拥有下一次运行。"
cannot_resume_prefix: "无法恢复会话:"
resumed_session: "↻ 已恢复会话"
counts_one: "({count} 条用户消息,共 {total} 条消息)"
diff --git a/tests/hermes_cli/test_kanban_resume_guard.py b/tests/hermes_cli/test_kanban_resume_guard.py
new file mode 100644
index 00000000000..468bdb0b983
--- /dev/null
+++ b/tests/hermes_cli/test_kanban_resume_guard.py
@@ -0,0 +1,194 @@
+"""Kanban worker transcripts must not resume as ordinary write-capable sessions (#68779).
+
+Behaviour tests for the centralized guard (`hermes_cli/kanban_resume_guard.py`) and the three
+CLI resume surfaces it protects: startup `--resume` (`_preload_resumed_session`), mid-chat
+`/resume`, and the quiet one-shot resume (`oneshot._load_resume_target`). The gateway surface
+is covered in `tests/tui_gateway/test_kanban_resume_guard.py`.
+"""
+
+from io import StringIO
+from unittest.mock import patch
+
+import pytest
+
+from hermes_state import SessionDB
+
+
+def _db(tmp_path, *, source="cli", flip_source_to=None, parent=None, end_reason=None,
+ session_id="sess-plain", with_message=True):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session(session_id, source, parent_session_id=parent)
+ if flip_source_to: # simulate a later surface flipping live ``source`` (created_source stays)
+ db._execute_write(lambda conn: conn.execute(
+ "UPDATE sessions SET source = ? WHERE id = ?", (flip_source_to, session_id)))
+ if with_message:
+ db.append_message(session_id, "user", "hello")
+ db.append_message(session_id, "assistant", "hi")
+ if end_reason:
+ db.end_session(session_id, end_reason)
+ return db
+
+
+# ── SessionDB.is_kanban_owned_session ────────────────────────────────
+
+def test_kanban_source_row_is_kanban_owned(tmp_path):
+ db = _db(tmp_path, source="kanban", session_id="worker-1")
+ assert db.is_kanban_owned_session("worker-1") is True
+
+
+def test_cli_source_row_is_not_kanban_owned(tmp_path):
+ db = _db(tmp_path, source="cli", session_id="chat-1")
+ assert db.is_kanban_owned_session("chat-1") is False
+
+
+def test_created_source_survives_surface_flip(tmp_path):
+ """A worker row whose live ``source`` was flipped (e.g. by a later surface) stays
+ kanban-owned via immutable ``created_source``."""
+ db = _db(tmp_path, source="kanban", flip_source_to="cli", session_id="flipped-1")
+ assert db.is_kanban_owned_session("flipped-1") is True
+
+
+def test_compression_lineage_of_kanban_worker_is_owned(tmp_path):
+ """Resuming the compression child of a worker transcript is resuming the worker's
+ conversation — it must classify as kanban-owned."""
+ db = _db(tmp_path, source="kanban", session_id="worker-root", end_reason="compression")
+ db.create_session("worker-tip", "cli", parent_session_id="worker-root")
+ db.append_message("worker-tip", "user", "continued")
+ assert db.is_kanban_owned_session("worker-tip") is True
+
+
+def test_branch_child_of_kanban_worker_is_not_owned(tmp_path):
+ """A delegate/branch child is a DIFFERENT conversation — not swept into the guard."""
+ db = _db(tmp_path, source="kanban", session_id="worker-root", end_reason="blocked")
+ db.create_session("branch-child", "cli", parent_session_id="worker-root",
+ model_config={"_branched_from": "worker-root"})
+ assert db.is_kanban_owned_session("branch-child") is False
+
+
+# ── the centralized guard ────────────────────────────────────────────
+
+def _refusal(db, sid):
+ from hermes_cli.kanban_resume_guard import kanban_resume_refusal
+ return kanban_resume_refusal(db, sid)
+
+
+def test_guard_refuses_kanban_session_with_reason(tmp_path):
+ db = _db(tmp_path, source="kanban", session_id="worker-1")
+ refusal = _refusal(db, "worker-1")
+ assert refusal is not None
+ assert "worker-1" in refusal
+ assert "Kanban" in refusal
+
+
+def test_guard_allows_ordinary_session(tmp_path):
+ db = _db(tmp_path, source="cli", session_id="chat-1")
+ assert _refusal(db, "chat-1") is None
+
+
+def test_guard_exempts_dispatcher_owned_run(tmp_path, monkeypatch):
+ """A process holding HERMES_KANBAN_TASK is a dispatcher-owned run — the supervised
+ continuation — and may resume (env beats no other signal)."""
+ db = _db(tmp_path, source="kanban", session_id="worker-1")
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "task-42")
+ assert _refusal(db, "worker-1") is None
+
+
+def test_guard_fails_open_on_probe_error(tmp_path):
+ db = _db(tmp_path, source="cli", session_id="chat-1")
+
+ def boom(session_id):
+ raise RuntimeError("database is locked")
+
+ db.is_kanban_owned_session = boom
+ assert _refusal(db, "chat-1") is None
+
+
+# ── CLI startup --resume / -c ────────────────────────────────────────
+
+def _make_cli(resume=None):
+ from cli import HermesCLI
+ import cli as _cli_mod
+
+ _clean_config = {
+ "model": {"default": "anthropic/claude-opus-4.6", "base_url": "https://openrouter.ai/api/v1",
+ "provider": "auto"},
+ "display": {"compact": False, "tool_progress": "all", "resume_display": "full"},
+ "agent": {},
+ "terminal": {"env_type": "local"},
+ }
+ with (
+ patch("cli.get_tool_definitions", return_value=[]),
+ patch.dict("os.environ", {"LLM_MODEL": "", "HERMES_MAX_ITERATIONS": ""}, clear=False),
+ patch.dict(_cli_mod.__dict__, {"CLI_CONFIG": _clean_config}),
+ ):
+ return HermesCLI(resume=resume)
+
+
+def test_startup_resume_refuses_kanban_session_and_starts_fresh(tmp_path):
+ db = _db(tmp_path, source="kanban", session_id="worker-1")
+ reopened = []
+ orig_reopen = db.reopen_session
+ db.reopen_session = lambda session_id: reopened.append(session_id) or orig_reopen(session_id)
+
+ cli = _make_cli(resume="worker-1")
+ cli._session_db = db
+ buf = StringIO()
+ cli.console.file = buf
+
+ assert cli._preload_resumed_session() is False
+ assert "worker-1" in buf.getvalue()
+ assert "Kanban" in buf.getvalue()
+ # The worker row must never receive this process's writes: fresh id, no resume state.
+ assert cli._resumed is False
+ assert cli.session_id != "worker-1"
+ assert reopened == [], "the kanban worker row must not be reopened by an ordinary resume"
+
+
+def test_startup_resume_ordinary_session_still_works(tmp_path):
+ db = _db(tmp_path, source="cli", session_id="chat-1")
+ cli = _make_cli(resume="chat-1")
+ cli._session_db = db
+ buf = StringIO()
+ cli.console.file = buf
+
+ assert cli._preload_resumed_session() is True
+ assert len(cli.conversation_history) == 2
+ assert cli.session_id == "chat-1"
+
+
+# ── mid-chat /resume ─────────────────────────────────────────────────
+
+def test_midchat_resume_refuses_kanban_target(tmp_path):
+ db = _db(tmp_path, source="cli", session_id="chat-1")
+ db.create_session("worker-1", "kanban")
+ db.append_message("worker-1", "user", "task work")
+ cli = _make_cli(resume=None)
+ cli._session_db = db
+ cli.session_id = "chat-1"
+ cli.conversation_history = [{"role": "user", "content": "hi"}]
+ printed = []
+ with patch("cli._cprint", lambda line: printed.append(line)):
+ cli._handle_resume_command("/resume worker-1")
+
+ joined = "\n".join(str(p) for p in printed)
+ assert "Kanban" in joined
+ # The chat stays on its own session — no switch, no history swap.
+ assert cli.session_id == "chat-1"
+ assert cli.conversation_history == [{"role": "user", "content": "hi"}]
+
+
+# ── quiet one-shot resume ────────────────────────────────────────────
+
+def test_oneshot_resume_refuses_kanban_session(tmp_path):
+ from hermes_cli.oneshot import _load_resume_target
+ db = _db(tmp_path, source="kanban", session_id="worker-1")
+ with pytest.raises(RuntimeError, match="cannot resume session worker-1"):
+ _load_resume_target(db, "worker-1")
+
+
+def test_oneshot_resume_ordinary_session_still_works(tmp_path):
+ from hermes_cli.oneshot import _load_resume_target
+ db = _db(tmp_path, source="cli", session_id="chat-1")
+ sid, history, meta = _load_resume_target(db, "chat-1")
+ assert sid == "chat-1"
+ assert len(history) == 2
diff --git a/tests/tui_gateway/test_kanban_resume_guard.py b/tests/tui_gateway/test_kanban_resume_guard.py
new file mode 100644
index 00000000000..aeb9b7c3d3a
--- /dev/null
+++ b/tests/tui_gateway/test_kanban_resume_guard.py
@@ -0,0 +1,113 @@
+"""Gateway/desktop `session.resume` must refuse a Kanban worker transcript (#68779).
+
+The refusal happens in `_resume_guard`, before ANY history read, live-reuse, lazy watch or
+slash-worker build: a resumed Desktop/TUI session would be a write-capable writer with none
+of the dispatcher's ownership env, invisible to the Kanban board.
+"""
+
+import sys
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+_original_stdout = sys.stdout
+
+
[email protected](autouse=True)
+def _restore_stdout():
+ yield
+ sys.stdout = _original_stdout
+
+
+def server():
+ # Same import-window pattern as tests/tui_gateway/test_protocol.py: the mocks only need
+ # to cover the initial import of tui_gateway.server.
+ import tui_gateway.server_requests # noqa: F401
+ import tui_gateway.transport # noqa: F401
+ with patch.dict("sys.modules", {
+ "hermes_constants": MagicMock(get_hermes_home=MagicMock(return_value="/tmp/hermes_test")),
+ "hermes_cli.env_loader": MagicMock(),
+ "hermes_cli.banner": MagicMock(),
+ "hermes_state": MagicMock(),
+ }):
+ import importlib
+ mod = importlib.import_module("tui_gateway.server")
+
+ methods = dict(mod._methods)
+ real_stdout = mod._real_stdout
+ yield mod
+ mod._methods.clear()
+ mod._methods.update(methods)
+ mod._real_stdout = real_stdout
+ for sid in list(mod._sessions):
+ mod._close_session_by_id(sid, end_reason="test_cleanup")
+ from tui_gateway import server_requests
+ server_requests.reset_for_tests()
+ mod._live_transports.clear()
+
+
+class _KanbanDB:
+ """Fake profile session store: classifies `worker-1` as kanban-owned, `chat-1` not."""
+
+ def __init__(self):
+ self.reads = []
+
+ def get_session(self, session_id):
+ return {"id": session_id}
+
+ def get_session_by_title(self, _title):
+ return None
+
+ def resolve_resume_session_id(self, session_id):
+ return session_id
+
+ def is_kanban_owned_session(self, session_id):
+ self.reads.append(("kanban-probe", session_id))
+ return session_id == "worker-1"
+
+ def assert_resume_safe(self, _session_id, **_kwargs):
+ self.reads.append(("size-guard", _session_id))
+
+ def get_resume_conversations(self, _session_id):
+ self.reads.append(("lineage", _session_id))
+ return ([], [])
+
+ def get_messages_as_conversation(self, session_id, **_kwargs):
+ self.reads.append(("tip", session_id))
+ return []
+
+ def get_ancestor_display_prefix(self, _session_id):
+ return []
+
+
+def _resume(server, monkeypatch, db, session_id):
+ monkeypatch.setattr(server, "_get_db", lambda: db)
+ return server.handle_request({
+ "id": f"r-{session_id}",
+ "method": "session.resume",
+ "params": {"session_id": session_id, "omit_messages": True},
+ })
+
+
+def test_gateway_resume_refuses_kanban_worker_session(server, monkeypatch):
+ """A kanban-owned transcript is refused before any history read or session build."""
+ db = _KanbanDB()
+ response = _resume(server, monkeypatch, db, "worker-1")
+
+ err = response.get("error") or {}
+ assert err.get("code") == 4132, response
+ assert "Kanban" in err.get("message", "")
+ # No history read ran: the refusal fired before anything touched the transcript.
+ assert ("lineage", "worker-1") not in db.reads
+ assert ("tip", "worker-1") not in db.reads
+
+
+def test_gateway_resume_ordinary_session_unchanged(server, monkeypatch):
+ """A non-kanban session flows past the guard exactly as before."""
+ db = _KanbanDB()
+ response = _resume(server, monkeypatch, db, "chat-1")
+
+ assert "error" not in response, response
+ # omit_messages reads the tip segment — proof the guard was survived.
+ assert ("tip", "chat-1") in db.reads
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index fb989d37903..ead77bdaeeb 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -854,7 +854,16 @@ def _resume_follow_tip(ctx: _Resume) -> None:
def _resume_guard(ctx: _Resume) -> dict | None:
"""Refuse a runaway transcript before any history read (sessions.max_resume_messages). Deferred /
omit_messages / lazy paths load the TIP segment only and are guarded tip-only (a lineage count rejected
- exactly the well-compressed chats). Metadata fallback for lightweight adaptor DBs; fails OPEN on errors."""
+ exactly the well-compressed chats). Metadata fallback for lightweight adaptor DBs; fails OPEN on errors.
+
+ Kanban worker transcripts refuse FIRST and fail CLOSED on a positive match (#68779): a
+ resumed Desktop/TUI session would be a write-capable writer with none of the dispatcher
+ ownership env, invisible to the board while a re-dispatch can start a competing writer
+ in the same workspace. One guard for every resume shape below (cold / eager / deferred /
+ lazy / live-reuse) — no slash worker is ever built for a refused session."""
+ from hermes_cli.kanban_resume_guard import kanban_resume_refusal
+ if (kanban_refusal := kanban_resume_refusal(ctx.db, ctx.target)) is not None:
+ return _err(ctx.rid, 4132, kanban_refusal)
from hermes_state import SessionResumeTooLargeError, resolved_max_resume_messages
tip_only = ctx.lazy or ctx.omit_messages or (ctx.defer_history and not ctx.eager_build)
try: