Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(harness): make definition failures visible (PR6) (#1072)

Qi Qi915084b3a69a
diff --git a/config/platform_registry.py b/config/platform_registry.py
index 7572400e6..83a489c96 100644
--- a/config/platform_registry.py
+++ b/config/platform_registry.py
@@ -62,6 +62,19 @@ class PlatformDescriptor:
# same registry but is never a configurable IM platform. IM-only code paths
# should select via ``im_platform_descriptors()`` / ``im_platform_ids()``
# rather than re-deriving an ad-hoc workbench exclude.
+ #
+ # CONTRACT, load-bearing beyond that selection: ``kind`` is the axis of
+ # ``core/scheduled_tasks.py::LADDER_ACK_SOURCES``, where ("im", channel|user) is
+ # the one PERMISSIVE row — a failure notice sent there may be acknowledged on the
+ # id the send returned, with nothing persisted behind it. Declaring ``kind="im"``
+ # therefore asserts that this transport's send id was minted by a platform that
+ # actually reached a person. A transport that mints its own id locally (as
+ # ``AvibeBot.send_message`` does) must NOT be "im", or an owed notice can be
+ # marked delivered when nobody was told. The default stays for the sake of
+ # constructors outside the registry, but every descriptor IN ``PLATFORM_REGISTRY``
+ # states its kind, and ``test_every_registry_platform_declares_its_kind_explicitly``
+ # fails if a new one inherits it instead — a claim this strong should be made,
+ # not defaulted into.
kind: str = "im"
@property
@@ -148,6 +161,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {
client_class="SlackBot",
formatter_module="modules.im.formatters",
formatter_class="SlackFormatter",
+ kind="im",
credential_fields=("bot_token",),
runtime_reconcile_fields=("bot_token", "app_token", "proxy_url"),
capabilities=PlatformCapabilities(
@@ -172,6 +186,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {
client_class="DiscordBot",
formatter_module="modules.im.formatters",
formatter_class="DiscordFormatter",
+ kind="im",
credential_fields=("bot_token",),
runtime_reconcile_fields=("bot_token", "proxy_url"),
capabilities=PlatformCapabilities(
@@ -196,6 +211,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {
client_class="TelegramBot",
formatter_module="modules.im.formatters",
formatter_class="TelegramFormatter",
+ kind="im",
credential_fields=("bot_token",),
runtime_reconcile_fields=("bot_token", "use_webhook", "webhook_url", "webhook_secret_token", "proxy_url"),
capabilities=PlatformCapabilities(
@@ -221,6 +237,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {
client_class="FeishuBot",
formatter_module="modules.im.formatters",
formatter_class="FeishuFormatter",
+ kind="im",
credential_fields=("app_id", "app_secret"),
runtime_reconcile_fields=("app_id", "app_secret", "domain", "proxy_url"),
# NOTE: Feishu/Lark DOES support message deletion via the API
@@ -260,6 +277,7 @@ PLATFORM_REGISTRY: dict[str, PlatformDescriptor] = {
client_class="WeChatBot",
formatter_module="modules.im.formatters",
formatter_class="WeChatFormatter",
+ kind="im",
credential_fields=("bot_token",),
runtime_reconcile_fields=("bot_token", "base_url", "cdn_base_url", "proxy_url"),
capabilities=PlatformCapabilities(
diff --git a/core/backend_failure.py b/core/backend_failure.py
index c76f40c24..8c3aa9757 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import uuid
from typing import Any
+from core.delivery_evidence import DeliveryEvidence
from core.message_output import MessageOutput, terminal_output_for, terminal_turn_output
from vibe.message_types import spec_for
@@ -30,12 +31,46 @@ def _terminal_output(request: Any, output: MessageOutput | None) -> MessageOutpu
return terminal_turn_output()
+def _harness_run_identity(context: Any, request: Any) -> str:
+ """The run id a harness execution's failure notice is keyed by, if any."""
+
+ for source in (getattr(request, "context", None), context):
+ payload = getattr(source, "platform_specific", None) or {}
+ identity = str(payload.get("task_execution_id") or "").strip()
+ if identity:
+ return identity
+ return ""
+
+
def _failure_identity(
context: Any,
request: Any,
explicit_id: str | None,
+ *,
+ authoritative: bool = False,
) -> str:
identity = str(explicit_id or "").strip()
+ # An AUTHORITATIVE id is one the caller derived from the durable run row — the
+ # owed-notice drain's. It wins outright, which is what keeps a D1 interruption
+ # notice (``interrupt:{run}:{reason}``) from collapsing into the ordinary
+ # notice for the same execution.
+ if identity and authoritative:
+ return identity
+
+ # A harness execution is keyed by its RUN, whichever backend reported the
+ # failure. Codex and OpenCode pass their own turn/message/session id at five
+ # call sites, and preferring that over the run id meant the live notification
+ # and the drain's replay had different identities — so the drain could not see
+ # the message the live path had already persisted, and sent a duplicate. The
+ # run id is the one identity BOTH paths can derive, the live one from its
+ # context and the drain from the durable row.
+ #
+ # Non-harness contexts have no run to align to, so a backend's explicit id
+ # still wins there and that path is unchanged.
+ harness_identity = _harness_run_identity(context, request)
+ if harness_identity:
+ return harness_identity
+
if identity:
return identity
@@ -59,6 +94,19 @@ def _failure_identity(
return uuid.uuid4().hex
+def _failure_texts(backend_name: str, diagnostic: Any, display_text: Any) -> tuple[str, str]:
+ """The diagnostic and the user-visible body, for the live path and the replay.
+
+ Shared so a replayed notice cannot drift from the notice the live path would
+ have shown for the same failure: same fallback when a backend supplies no
+ display text, same fallback when it supplies no diagnostic either.
+ """
+
+ error = str(diagnostic or "").strip() or f"{backend_name} backend failed"
+ visible = str(display_text or "").strip() or error
+ return error, visible
+
+
def backend_failure_notification_output(
context: Any,
backend: str,
@@ -66,12 +114,15 @@ def backend_failure_notification_output(
request: Any = None,
output: MessageOutput | None = None,
failure_id: str | None = None,
+ failure_id_authoritative: bool = False,
) -> MessageOutput:
"""Build the durable, non-settling visible half of a backend failure."""
backend_name = str(backend or "backend").strip() or "backend"
terminal = _terminal_output(request, output)
- identity = _failure_identity(context, request, failure_id)
+ identity = _failure_identity(
+ context, request, failure_id, authoritative=failure_id_authoritative
+ )
metadata = dict(terminal.metadata)
metadata.update(
{
@@ -92,6 +143,77 @@ def backend_failure_notification_output(
)
+async def emit_replayed_backend_failure(
+ controller: Any,
+ context: Any,
+ backend: str,
+ diagnostic: str,
+ *,
+ failure_id: str,
+ display_text: str | None = None,
+ delivery: DeliveryEvidence | None = None,
+) -> None:
+ """Deliver the visible half of a failure that ALREADY ended. Settles nothing.
+
+ The owed-failure-notice drain replays a failure it read back from a durable
+ run row, hours after the run itself ended. That is a different act from
+ reporting a failure as it happens, and it used to be expressed as the live
+ ``emit_backend_failure`` with its live behaviour switched off piece by piece:
+ a non-settling ``output``, an auth-recovery bypass, an explicit identity. Four
+ review rounds found settlement, auth and identity defects in the gaps between
+ those switches, because the replay still entered the live lifecycle and every
+ new live behaviour had to be neutralized again by hand.
+
+ So the replay is its own emitter, and the neutralizations become facts of its
+ construction rather than arguments:
+
+ * ONE ``notify``. No ``result``, therefore no turn settlement, no status-bubble
+ teardown, no runtime-turn release. A replayed context describes a run that
+ ended long ago and carries no runtime-turn token, and
+ ``emit_matches_runtime_turn`` fails OPEN for a tokenless context —
+ deliberately, so a scheduled or watch run can settle its own turn — so a
+ settling replay was adopted by whatever turn happened to be live on the
+ target channel and finalized it. The run this notice is about is terminal by
+ construction: a notice is owed only once the row is settled.
+ * NO auth recovery. This is a report about a possibly hours-old 401, not an
+ interactive "reset OAuth" affordance about the backend's state right now, and
+ ``maybe_emit_auth_recovery_message`` cannot report into ``DeliveryEvidence``
+ anyway, so a notice delivered through it would read as unacknowledged and walk
+ on to the next delivery rung.
+ * The identity is AUTHORITATIVE, with no way to say otherwise. It comes from the
+ durable notice row, so two drain passes over that row produce one identity —
+ and an interruption's ``interrupt:{run}:{reason}`` survives instead of
+ collapsing into the ordinary notice for the same execution, which is what
+ happens when a context-derived run id is allowed to win.
+
+ ``delivery`` is filled in with what the notify attempt actually proved; the
+ drain acks its durable notice on that evidence, never on a clean return.
+ """
+
+ backend_name = str(backend or "backend").strip() or "backend"
+ _error, visible = _failure_texts(backend_name, diagnostic, display_text)
+ # Non-settling by construction: ``backend_failure_notification_output`` hardcodes
+ # ``completes_turn=False`` / ``completes_run=False``, and it is the only output
+ # this function emits.
+ notification = backend_failure_notification_output(
+ context,
+ backend_name,
+ failure_id=failure_id,
+ failure_id_authoritative=True,
+ )
+ # ``delivery`` is passed ONLY when a caller asked for it: controller-like objects
+ # that implement ``emit_agent_message`` without the keyword must keep working.
+ notify_kwargs: dict[str, Any] = {"output": notification}
+ if delivery is not None:
+ notify_kwargs["delivery"] = delivery
+ await controller.emit_agent_message(
+ context,
+ "notify",
+ visible,
+ **notify_kwargs,
+ )
+
+
async def emit_backend_failure(
controller: Any,
context: Any,
@@ -102,27 +224,29 @@ async def emit_backend_failure(
request: Any = None,
output: MessageOutput | None = None,
failure_id: str | None = None,
+ delivery: DeliveryEvidence | None = None,
) -> bool:
- """Notify once, then settle one terminal backend failure silently.
+ """Settle one terminal backend failure, notifying live only outside Harness.
Backend adapters own structured failure recognition. This helper owns the
shared representation and keeps visible delivery separate from lifecycle
- settlement. The return value is true when auth recovery supplied the visible
- notification.
+ settlement. Harness executions already own a durable owed-notice row whose drain
+ applies streak suppression, callback coordination, claims, and retry policy. For
+ those runs this emitter settles only; the drain is the single delivery owner.
+ Non-Harness callers retain immediate auth recovery and notification. The return
+ value is true when auth recovery supplied that immediate notification.
+
+ ``delivery``, when supplied, is filled in with what the notify attempt actually
+ proved. Nothing here can report that otherwise: this function DISCARDS the
+ result of ``emit_agent_message`` and returns normally whether or not the notify
+ was delivered, so a caller that owes a durable notice had no way to tell a
+ delivered notice from a lost one and would ack on a send that never happened.
+ Callers with nothing durable at stake pass nothing and are unaffected.
"""
backend_name = str(backend or "backend").strip() or "backend"
- error = str(diagnostic or "").strip() or f"{backend_name} backend failed"
- visible = str(display_text or "").strip() or error
+ error, visible = _failure_texts(backend_name, diagnostic, display_text)
terminal = _terminal_output(request, output)
- notification = backend_failure_notification_output(
- context,
- backend_name,
- request=request,
- output=terminal,
- failure_id=failure_id,
- )
-
async def settle_terminal_failure() -> None:
await controller.emit_agent_message(
context,
@@ -134,6 +258,32 @@ async def emit_backend_failure(
terminal_error=error,
)
+ # A Harness run is durable before the backend executes. Its terminal settlement
+ # stamps the owed notice atomically, and that notice drain is the only layer with
+ # enough definition history to suppress a recurring failure streak correctly.
+ # Sending here as well creates two competing delivery owners and lets every live
+ # failure bypass that policy before the drain can classify it.
+ if _harness_run_identity(context, request):
+ await settle_terminal_failure()
+ return False
+
+ notification = backend_failure_notification_output(
+ context,
+ backend_name,
+ request=request,
+ output=terminal,
+ failure_id=failure_id,
+ )
+
+ # Auth recovery is unconditional for non-Harness live callers, and there is no
+ # switch to turn it off. A real interactive 401 should offer its reset-OAuth
+ # affordance immediately; a Harness failure is reported by the durable drain.
+ #
+ # The one caller that must not do that — the owed-notice drain, replaying a
+ # possibly hours-old failure it read back from a durable row — does not call this
+ # function at all; see ``emit_replayed_backend_failure``. A bypass argument here
+ # was the previous shape, and it left the replay inside this lifecycle with its
+ # live behaviours switched off one at a time.
auth_service = getattr(controller, "agent_auth_service", None)
maybe_recover = getattr(auth_service, "maybe_emit_auth_recovery_message", None)
if callable(maybe_recover):
@@ -151,12 +301,19 @@ async def emit_backend_failure(
if handled_auth:
return True
+ # ``delivery`` is passed ONLY when a caller asked for it. Sending it
+ # unconditionally changed the call signature for every controller-like object
+ # that implements ``emit_agent_message`` without the new keyword, which is a
+ # breaking change for an optional diagnostic — three suites caught it.
+ notify_kwargs: dict[str, Any] = {"output": notification}
+ if delivery is not None:
+ notify_kwargs["delivery"] = delivery
try:
await controller.emit_agent_message(
context,
"notify",
visible,
- output=notification,
+ **notify_kwargs,
)
finally:
await settle_terminal_failure()
diff --git a/core/caller_context.py b/core/caller_context.py
index fc091ac20..309b7e9b2 100644
--- a/core/caller_context.py
+++ b/core/caller_context.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
import os
from typing import Mapping, Optional
@@ -11,17 +11,87 @@ AVIBE_RUN_ID_ENV = "AVIBE_RUN_ID"
AVIBE_CALLER_SOURCE_ENV = "AVIBE_CALLER_SOURCE"
AVIBE_CALLER_BACKEND_ENV = "AVIBE_CALLER_BACKEND"
AVIBE_NATIVE_SESSION_ID_ENV = "AVIBE_NATIVE_SESSION_ID"
+#: The CREATION ORIGIN half of the contract. Everything below travels the same
+#: subprocess hop as the ids above, because an IM-created definition is created by an
+#: Agent run executing ``vibe task add`` — the env is the only channel between the
+#: conversation that asked for the definition and the row that records who asked.
+AVIBE_CALLER_PLATFORM_ENV = "AVIBE_CALLER_PLATFORM"
+AVIBE_CALLER_USER_ID_ENV = "AVIBE_CALLER_USER_ID"
+AVIBE_CALLER_CHANNEL_ID_ENV = "AVIBE_CALLER_CHANNEL_ID"
+AVIBE_CALLER_SESSION_KEY_ENV = "AVIBE_CALLER_SESSION_KEY"
+AVIBE_CALLER_MESSAGE_ID_ENV = "AVIBE_CALLER_MESSAGE_ID"
+AVIBE_CALLER_WORKSPACE_ID_ENV = "AVIBE_CALLER_WORKSPACE_ID"
@dataclass(frozen=True)
class CallerContext:
- """Caller identity resolved from Avibe-owned execution context."""
+ """Caller identity resolved from Avibe-owned execution context.
+
+ The first five fields answer "which Avibe session/run made this call". The
+ ORIGIN fields below answer "where in the user's world was it made", which is a
+ different question and has to be captured separately: a failure notice is
+ context-free by construction (it may be delivered to an owner DM or to the
+ workspace inbox hours later), so it can only name the channel and thread the
+ definition came from if the creating turn wrote them down.
+
+ ``session_key`` and ``channel_id`` are BOTH kept, and are not redundant:
+
+ * ``session_key`` is the ADDRESS — the
+ ``<platform>::<channel|user>::<id>[::thread::<ts>]`` grammar
+ ``parse_session_key`` speaks, and the one a notice rung can be delivered to;
+ * ``channel_id`` is the LOCATION — what a message permalink needs. For a DM the
+ session key's scope id is the USER id, and a permalink built from it would be
+ fabricated (Slack DM permalinks are keyed by the ``D…`` conversation).
+
+ ``workspace_id`` is one generic field rather than one per platform: it holds a
+ Slack team id or a Discord guild id, both of which are the enclosing tenant a
+ deep link must name.
+ """
session_id: str
run_id: Optional[str] = None
source: Optional[str] = None
backend: Optional[str] = None
native_session_id: Optional[str] = None
+ platform: Optional[str] = None
+ user_id: Optional[str] = None
+ channel_id: Optional[str] = None
+ session_key: Optional[str] = None
+ message_id: Optional[str] = None
+ workspace_id: Optional[str] = None
+
+ def session_stable(self) -> "CallerContext":
+ """This context minus every origin field that changes from turn to turn.
+
+ For a backend whose caller env is written ONCE — the Claude SDK client is spawned
+ per session and its environment cannot be refreshed afterwards — the per-message
+ fields are not merely useless, they are dangerous in two different ways:
+
+ * ``message_id`` changes on every message, so keeping it in the comparison that
+ decides whether a cached client is still valid would tear down and respawn the
+ Agent on EVERY turn;
+ * ``user_id`` changes with the author, and a shared channel session is
+ deliberately shared across participants (pinned by
+ ``test_session_handler_reuses_cached_claude_client_when_system_prompt_is_unchanged``,
+ which also asserts the per-user id never reaches the system prompt). A baked-in
+ author id would attribute a definition created by one participant to whoever
+ happened to speak first — and the owner-DM rung would then notify the wrong
+ person, which is worse than not notifying anybody.
+
+ What survives is what the SESSION owns: platform, channel, session key,
+ workspace. So a Claude-created definition still names the conversation it came
+ from and still lights up rung (3); it gets no owner-DM rung and no deep link,
+ because a permalink needs the message id this deliberately drops. Codex and
+ OpenCode rewrite their caller env per turn (a ``BASH_ENV`` script and a binding
+ file respectively) and therefore keep the full origin.
+
+ A DM is the case where nothing is lost: its session key is
+ ``<platform>::user::<id>``, so the person is carried by the scope itself.
+ """
+
+ if not self.user_id and not self.message_id:
+ return self
+ return replace(self, user_id=None, message_id=None)
def to_env(self) -> dict[str, str]:
env = {AVIBE_SESSION_ID_ENV: self.session_id}
@@ -33,9 +103,30 @@ class CallerContext:
env[AVIBE_CALLER_BACKEND_ENV] = self.backend
if self.native_session_id:
env[AVIBE_NATIVE_SESSION_ID_ENV] = self.native_session_id
+ if self.platform:
+ env[AVIBE_CALLER_PLATFORM_ENV] = self.platform
+ if self.user_id:
+ env[AVIBE_CALLER_USER_ID_ENV] = self.user_id
+ if self.channel_id:
+ env[AVIBE_CALLER_CHANNEL_ID_ENV] = self.channel_id
+ if self.session_key:
+ env[AVIBE_CALLER_SESSION_KEY_ENV] = self.session_key
+ if self.message_id:
+ env[AVIBE_CALLER_MESSAGE_ID_ENV] = self.message_id
+ if self.workspace_id:
+ env[AVIBE_CALLER_WORKSPACE_ID_ENV] = self.workspace_id
return env
def to_metadata(self) -> dict[str, str]:
+ """The ``created_by.caller`` shape persisted with a definition.
+
+ The origin key NAMES are load-bearing: ``core/scheduled_tasks.py``'s failure
+ ladder has always read ``caller["session_key"]`` / ``caller["scope_id"]``
+ (rung 3) and ``caller["platform"]`` / ``caller["user_id"]`` (rung 4, the owner
+ DM) — fields nothing had ever written, so both rungs were dormant. Writing
+ them under any other name would leave them dormant.
+ """
+
metadata = {"session_id": self.session_id}
if self.run_id:
metadata["run_id"] = self.run_id
@@ -45,6 +136,26 @@ class CallerContext:
metadata["backend"] = self.backend
if self.native_session_id:
metadata["native_session_id"] = self.native_session_id
+ if self.platform:
+ metadata["platform"] = self.platform
+ if self.user_id:
+ metadata["user_id"] = self.user_id
+ if self.channel_id:
+ metadata["channel_id"] = self.channel_id
+ if self.session_key:
+ metadata["session_key"] = self.session_key
+ # ``scope_id`` only when it says something the session key does not: rung 3
+ # reads ``session_key or scope_id``, so a copy of the same value would be
+ # dead weight. A THREAD key's parent scope is the exception — it is the
+ # coarser address a consumer that cannot deliver into a thread still wants,
+ # and ``parse_scope_id`` cannot express the five-part form.
+ scope_id = _scope_id_from_session_key(self.session_key)
+ if scope_id:
+ metadata["scope_id"] = scope_id
+ if self.message_id:
+ metadata["message_id"] = self.message_id
+ if self.workspace_id:
+ metadata["workspace_id"] = self.workspace_id
return metadata
@@ -52,6 +163,94 @@ def _clean(value: object) -> str:
return str(value or "").strip()
+def _scope_id_from_session_key(session_key: str) -> Optional[str]:
+ parts = _clean(session_key).split("::")
+ if len(parts) != 5:
+ return None
+ return "::".join(parts[:3])
+
+
+def _origin_thread_id(
+ context_platform: str,
+ payload: Mapping[str, object] | None,
+ thread_id: object,
+ *,
+ is_dm: bool,
+) -> Optional[str]:
+ """The thread segment of the origin session key.
+
+ Mirrors ``build_session_key_for_context(..., include_thread=True)`` —
+ ``resolve_context_thread_id(context) or context.thread_id`` — which is pinned by
+ ``test_the_captured_origin_session_key_matches_the_canonical_builder`` rather than
+ imported, so this module keeps no dependency on ``modules.im`` and stays cheap
+ enough for the CLI to import.
+
+ *context_platform* is deliberately the platform WITHOUT the caller's fallback, which
+ is the one asymmetry in that mirror: ``build_session_key_for_context`` passes its
+ ``fallback_platform`` to ``resolve_context_platform`` for the key's prefix but calls
+ ``resolve_context_thread_id`` with no fallback at all. Applying the fallback here
+ would canonicalise a Telegram forum thread the canonical builder would have left
+ off, i.e. address rung (3) at a conversation the rest of the system does not believe
+ in. The asymmetry is invisible in production — the Telegram adapter always sets
+ ``context.platform``, and only Slack leaves it unset — but it is the exact case
+ ``test_the_captured_origin_session_key_matches_the_canonical_builder`` caught.
+ """
+
+ canonical: Optional[str] = None
+ if context_platform == "telegram" and not is_dm:
+ data = payload or {}
+ if _clean(thread_id):
+ canonical = _clean(thread_id)
+ elif data.get("is_forum") or data.get("is_topic_message"):
+ canonical = "1"
+ return canonical or (_clean(thread_id) or None)
+
+
+def _origin_session_key(
+ platform: str,
+ payload: Mapping[str, object] | None,
+ *,
+ context_platform: str,
+ user_id: str,
+ channel_id: str,
+ thread_id: object,
+) -> Optional[str]:
+ if not platform:
+ return None
+ is_dm = bool((payload or {}).get("is_dm", False))
+ scope_type = "user" if is_dm else "channel"
+ scope_id = user_id if is_dm else channel_id
+ if not scope_id:
+ return None
+ base = f"{platform}::{scope_type}::{scope_id}"
+ thread = _origin_thread_id(context_platform, payload, thread_id, is_dm=is_dm)
+ return f"{base}::thread::{thread}" if thread else base
+
+
+def _origin_workspace_id(platform: str, payload: Mapping[str, object] | None) -> Optional[str]:
+ """The enclosing tenant, read from whatever the adapter already put on the payload.
+
+ Defensive by design, and deliberately read-only: no ``modules/im`` adapter is
+ changed to feed this. Slack event payloads carry ``team_id``; a Discord payload
+ carries either the raw ``discord.Message`` or ``discord.Interaction``; both expose
+ ``guild``, which is ``None`` in a DM. Every other platform has no tenant id here,
+ which is a MISSING id, not an empty one — the deep-link builder must refuse rather
+ than invent one.
+ """
+
+ if not payload:
+ return None
+ if platform == "slack":
+ return _clean(payload.get("team_id")) or None
+ if platform == "discord":
+ origin = payload.get("message")
+ if origin is None:
+ origin = payload.get("interaction")
+ guild = getattr(origin, "guild", None)
+ return _clean(getattr(guild, "id", None)) or None
+ return None
+
+
def caller_context_from_env(env: Mapping[str, str] | None = None) -> Optional[CallerContext]:
"""Resolve caller context from process env.
@@ -70,14 +269,33 @@ def caller_context_from_env(env: Mapping[str, str] | None = None) -> Optional[Ca
source=_clean(source.get(AVIBE_CALLER_SOURCE_ENV)) or None,
backend=_clean(source.get(AVIBE_CALLER_BACKEND_ENV)) or None,
native_session_id=_clean(source.get(AVIBE_NATIVE_SESSION_ID_ENV)) or None,
+ platform=_clean(source.get(AVIBE_CALLER_PLATFORM_ENV)) or None,
+ user_id=_clean(source.get(AVIBE_CALLER_USER_ID_ENV)) or None,
+ channel_id=_clean(source.get(AVIBE_CALLER_CHANNEL_ID_ENV)) or None,
+ session_key=_clean(source.get(AVIBE_CALLER_SESSION_KEY_ENV)) or None,
+ message_id=_clean(source.get(AVIBE_CALLER_MESSAGE_ID_ENV)) or None,
+ workspace_id=_clean(source.get(AVIBE_CALLER_WORKSPACE_ID_ENV)) or None,
)
-def caller_context_from_platform_payload(payload: Mapping[str, object] | None) -> Optional[CallerContext]:
- """Resolve caller context from an Avibe message/turn payload."""
+def caller_context_from_platform_payload(
+ payload: Mapping[str, object] | None,
+ *,
+ message: object | None = None,
+ fallback_platform: object | None = None,
+) -> Optional[CallerContext]:
+ """Resolve caller context from an Avibe message/turn payload.
- if not payload:
+ *message* is the turn's typed ``MessageContext`` (duck-typed here so this module
+ stays importable by the CLI without pulling in ``modules.im``). Without it the
+ context carries identity only and NO origin — which is exactly right for a caller
+ that has no conversation behind it, and is why every existing caller keeps its
+ previous env and metadata byte for byte.
+ """
+
+ if not payload and message is None:
return None
+ payload = payload or {}
target = payload.get("agent_session_target")
session_id = ""
backend = ""
@@ -94,15 +312,65 @@ def caller_context_from_platform_payload(payload: Mapping[str, object] | None) -
trigger_kind = _clean(payload.get("task_trigger_kind"))
source = source_kind if source_kind == "callback" else trigger_kind or source_kind or "agent_turn"
backend = backend or _clean(payload.get("vibe_agent_backend"))
+
+ platform = ""
+ user_id = ""
+ channel_id = ""
+ message_id = ""
+ session_key: Optional[str] = None
+ workspace_id: Optional[str] = None
+ if message is not None:
+ context_platform = _clean(getattr(message, "platform", None)) or _clean(payload.get("platform"))
+ platform = context_platform or _clean(fallback_platform)
+ user_id = _clean(getattr(message, "user_id", None))
+ channel_id = _clean(getattr(message, "channel_id", None))
+ message_id = _clean(getattr(message, "message_id", None))
+ session_key = _origin_session_key(
+ platform,
+ payload,
+ context_platform=context_platform,
+ user_id=user_id,
+ channel_id=channel_id,
+ thread_id=getattr(message, "thread_id", None),
+ )
+ workspace_id = _origin_workspace_id(platform, payload)
+
return CallerContext(
session_id=session_id,
run_id=run_id or None,
source=source or None,
backend=backend or None,
native_session_id=native_session_id or None,
+ platform=platform or None,
+ user_id=user_id or None,
+ channel_id=channel_id or None,
+ session_key=session_key,
+ message_id=message_id or None,
+ workspace_id=workspace_id,
)
-def caller_env_for_platform_payload(payload: Mapping[str, object] | None) -> dict[str, str]:
- context = caller_context_from_platform_payload(payload)
- return context.to_env() if context else {}
+def caller_env_for_platform_payload(
+ payload: Mapping[str, object] | None,
+ *,
+ message: object | None = None,
+ fallback_platform: object | None = None,
+ session_stable_only: bool = False,
+) -> dict[str, str]:
+ """The caller env for an Agent subprocess.
+
+ Set *session_stable_only* when the env is written once for the whole session and
+ cannot be refreshed per turn — see ``CallerContext.session_stable`` for what that
+ drops and why keeping it would be worse than losing it.
+ """
+
+ context = caller_context_from_platform_payload(
+ payload,
+ message=message,
+ fallback_platform=fallback_platform,
+ )
+ if context is None:
+ return {}
+ if session_stable_only:
+ context = context.session_stable()
+ return context.to_env()
diff --git a/core/controller.py b/core/controller.py
index 1321417af..5ad245062 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -1403,6 +1403,7 @@ class Controller:
result_footer: Optional[str] = None,
output: MessageOutput | None = None,
terminal_error: Optional[str] = None,
+ delivery: Any = None,
):
"""Backward-compatible entrypoint; delegated to message dispatcher."""
try:
@@ -1417,6 +1418,12 @@ class Controller:
result_footer=result_footer,
output=output,
terminal_error=terminal_error,
+ # Forwarded ONLY when a caller asked for it, for the same reason
+ # ``emit_backend_failure`` does: ``message_dispatcher`` is a
+ # substitutable collaborator (six test suites replace it), so passing
+ # an optional diagnostic unconditionally would change the required
+ # signature of every stand-in.
+ **({"delivery": delivery} if delivery is not None else {}),
)
finally:
manager = getattr(self, "session_turns", None)
diff --git a/core/delivery_evidence.py b/core/delivery_evidence.py
new file mode 100644
index 000000000..72bf8ac22
--- /dev/null
+++ b/core/delivery_evidence.py
@@ -0,0 +1,99 @@
+"""What a notify delivery attempt actually proved, as one value.
+
+Dependency-free on purpose: the message dispatcher fills it, the message mirror
+contributes to it, and the owed-failure-notice drain branches on it, so it may not
+import any of them.
+
+Why a structured result rather than the message id alone. The notify branch's
+contract is ``Optional[str]``, and ``None`` is ambiguous three ways:
+
+* ``persist_agent_message`` swallows its own failures and returns ``None``, and the
+ notify branch discarded that return value entirely;
+* the branch's blanket ``except`` returned ``None`` for a send failure, a
+ persistence failure and a post-delivery stream failure alike.
+
+A drain that acked on "returned cleanly" would therefore mark a notice ``sent`` on
+a delivery that never happened — losing it permanently, which is the exact silent
+failure the durable notice exists to prevent. A drain that acked only on a
+persisted row could not tell "never delivered" from "delivered, bookkeeping
+failed", and would re-send a notice the user already has.
+
+So all three signals travel: what was delivered, what was persisted, and what
+went wrong where.
+
+And an id is not uniformly evidence, which is why ``ack_evidence`` distinguishes
+the two strengths rather than collapsing them into one boolean.
+``AvibeBot.send_message`` mints and returns a synthetic ``msg_<hex>`` id
+UNCONDITIONALLY — whether or not an SSE subscriber exists, and whether or not
+anything was persisted — so on that platform ``delivery_only`` proves nothing and
+only a receipt does. On a real IM platform the returned id came from the platform,
+so it does prove the user was told. Who may ack on what is the CALLER's policy,
+enumerated per target class in ``core.scheduled_tasks.LADDER_ACK_SOURCES`` and
+applied by ``ScheduledTaskService._rung_acknowledges``; this module only reports
+which of the two strengths it has.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Optional
+
+#: A persisted ``messages`` row. The strongest evidence: the row implies the send
+#: returned an id (or that the transport persists without delivering), and it is
+#: what later dedupes the identity.
+ACK_EVIDENCE_RECEIPT = "receipt"
+#: The transport returned an id but the row write failed. On a real IM platform that
+#: id came from the platform, so this is positive evidence the user was told,
+#: recorded explicitly rather than pretending a receipt exists — re-sending because
+#: a DB write failed would spam a notice that already arrived. On avibe the id is
+#: synthetic and this proves nothing; see the module docstring.
+ACK_EVIDENCE_DELIVERY_ONLY = "delivery_only"
+
+#: Where in the notify branch an error came from. ``stream`` is the one that must
+#: NOT read as a delivery failure: send and persist both succeeded and only the
+#: live SSE fan-out raised, so resending would duplicate a delivered notice.
+STAGE_SEND = "send"
+STAGE_PERSIST = "persist"
+STAGE_STREAM = "stream"
+
+
+@dataclass
+class DeliveryEvidence:
+ """Filled in by the notify branch; read by whoever owes the notice."""
+
+ delivered_id: Optional[str] = None
+ persisted_row: Optional[dict[str, Any]] = None
+ error: Optional[BaseException] = None
+ error_stage: Optional[str] = None
+ #: True once the send call returned without raising, whatever it returned —
+ #: distinguishing "the transport refused" from "the transport accepted and told
+ #: us nothing useful", which ``delivered_id`` alone cannot.
+ send_returned: bool = field(default=False)
+
+ @property
+ def ack_evidence(self) -> Optional[str]:
+ """How delivery was proved, or ``None`` when it was not."""
+
+ if self.persisted_row is not None:
+ return ACK_EVIDENCE_RECEIPT
+ if self.delivered_id is not None:
+ return ACK_EVIDENCE_DELIVERY_ONLY
+ return None
+
+ @property
+ def delivered(self) -> bool:
+ return self.ack_evidence is not None
+
+ @property
+ def error_text(self) -> Optional[str]:
+ """The failure's own message, for the dead letter to report.
+
+ The raised exception's text, never a generic string: a dead letter that
+ cannot say why is an actionable-failure requirement reduced to "something
+ went wrong".
+ """
+
+ if self.error is None:
+ return None
+ detail = str(self.error).strip() or type(self.error).__name__
+ return f"{self.error_stage or 'delivery'}: {detail}"
diff --git a/core/failure_notices.py b/core/failure_notices.py
new file mode 100644
index 000000000..4350c42b5
--- /dev/null
+++ b/core/failure_notices.py
@@ -0,0 +1,556 @@
+"""Who gets told about a failed harness run, and how often.
+
+The durable half — ``metadata.owed_failure_notice``, stamped by whichever UPDATE
+transitions a run to ``failed`` — lives in ``storage/background.py``. This module
+owns the POLICY over it, kept separate from the delivery plumbing in
+``core/scheduled_tasks.py`` so every branch is testable without a controller.
+
+Three lanes, and the asymmetries between them are the whole design:
+
+* **Failures** of a definition can recur *unboundedly* — every tick produces
+ another one — so without a scope the user gets a message per tick forever. They
+ share one **consecutive-failure streak** with a single canonical notice.
+* **Interruptions** (a deploy, an eviction, a lifetime cap, a user Stop) hit a run
+ **at most once**: the run is terminalized and never re-dispatched, so the notice
+ count is bounded by the number of runs. Per-run notices are self-bounding, and
+ there is nothing to suppress. Giving them a streak-shaped scope would silence
+ all but one of the several runs a single restart interrupts — and
+ ``create_per_run`` means there genuinely are several.
+* **Binding changes** are the odd one out twice over. They are the only notice a
+ SUCCEEDED run can owe — a ``create_once`` definition whose pinned session was
+ deleted rebinds, retries, and works — so no terminal transition stamps them and
+ ``core/scheduled_tasks.py`` writes them explicitly at the moment the transition
+ is recorded. And they arrive already scoped: ``SessionBindingChange.signature``
+ is "one broken binding, one notification", so they carry their own bound and are
+ delivered per-transition like an interruption rather than per-streak.
+
+Suppression is applied HERE, by the drain, not by the terminal writers. Three
+reasons. Every terminal transition stamps unconditionally, and a policy predicate
+inside each of five writers is five chances for them to disagree. A streak read at
+stamp time races with concurrent executions of the same definition, while at drain
+time one component reads it once. And definition-level notification policy does
+not belong in SQL UPDATE helpers.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Optional
+
+from storage.sqlite_semantics import sqlite_cast_integer
+
+from core.run_settlement import (
+ DISPATCH_FAILURE_REASONS,
+ INTERRUPT_REASON_DELIVERY_TARGET_MISSING,
+ INTERRUPT_REASON_EVICTED,
+ INTERRUPT_REASON_LIFETIME_TIMEOUT,
+ INTERRUPT_REASON_RESTARTED,
+ RUN_INTERRUPTION_REASONS,
+ SETTLED_BY_BACKEND_REFRESH,
+ SETTLED_BY_NO_TERMINAL_RESULT,
+ SETTLED_BY_REFUSED_CONCURRENT_TURN,
+ SETTLED_BY_STOPPED,
+ SETTLEMENT_I18N_KEYS,
+ SWEEP_I18N_KEYS,
+)
+
+#: What the drain decided to do with one owed notice this tick.
+ACTION_DELIVER = "deliver"
+#: Not delivered, no attempt consumed, no backoff burned — reconsidered next tick.
+#: Used both while an earlier run of the definition has not settled and while this
+#: streak's canonical notice is still trying.
+ACTION_DEFER = "defer"
+#: Terminal: the streak's notice was already delivered, so this row is a duplicate.
+ACTION_SKIP = "skip"
+
+#: Exponential backoff from the 2s tick, capped. The Nth FAILED attempt waits
+#: ``BACKOFF_SECONDS[N - 1]``, so the first failure waits the first declared interval
+#: and the sequence advances exactly once per consumed attempt. Running off the end is
+#: the dead letter.
+BACKOFF_SECONDS: tuple[float, ...] = (2.0, 8.0, 32.0, 128.0, 512.0)
+#: How many attempts a notice gets before it dead-letters to ``failed``. A visible
+#: dead letter, rather than a silent drop or an infinite loop.
+#:
+#: Derived, not chosen: N attempts are separated by N-1 waits, so one attempt per
+#: declared interval plus the attempt that finds no interval left is exactly
+#: ``len(BACKOFF_SECONDS) + 1``. Writing it as ``len(BACKOFF_SECONDS)`` made the
+#: sequence one rung shorter than it declared and pushed the whole mapping off by one.
+MAX_ATTEMPTS = len(BACKOFF_SECONDS) + 1
+
+#: How long a claimed notice is reserved to the owner performing its delivery.
+#:
+#: The drain's single-flight authority is a CLAIM taken before the external send: one
+#: guarded UPDATE consumes the attempt and pushes ``next_attempt_at`` this far out, so
+#: a second owner either loses that CAS or reads the lease and stands down. Without it
+#: both owners read ``pending``, both send, and only then does either write — a
+#: duplicate message that no database predicate can recall.
+#:
+#: This constant is therefore the RECOVERY BOUND for a claimant that dies mid-send:
+#: the lease is stored as an instant, not held as a lock, so a killed process releases
+#: it by expiry and the notice becomes eligible again with no operator action.
+#:
+#: Why 600 s, from both sides. It has to exceed the longest a live delivery can
+#: legitimately take, or a healthy claimant is overtaken while still sending and the
+#: duplicate comes back: a full ladder walk is five rungs, each able to sit on an
+#: adapter's HTTP timeout of roughly 30-60 s, so the worst case is a few minutes. And
+#: it has to exceed the retry ladder's own cap of ``BACKOFF_SECONDS[-1]`` (512 s), so a
+#: lease can never expire sooner than the backoff a failed attempt would have armed —
+#: otherwise the recovery path would become the faster retry and quietly replace the
+#: backoff it exists to respect.
+#:
+#: The cost is stated plainly: expiry-retry means the guarantee is AT LEAST ONCE, not
+#: exactly once. A claimant that died after the transport accepted its send but before
+#: its acknowledgement leaves a delivered message and an eligible row, and recovery
+#: sends again. ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` adds a second entrance to the same
+#: window rather than a new one: a claimant CANCELLED after the transport accepted its
+#: request is in exactly that state, having delivered without acknowledging. Closing it
+#: needs an idempotency key the transport itself honours; until then the residual is
+#: one duplicate per claimant death or cancel-after-accept inside that window. (Not
+#: "bounded by ``MAX_ATTEMPTS``": a claimant that dies on EVERY attempt never survives
+#: to write the dead letter, so claims keep consuming attempts past the ceiling — the
+#: bound is per death, not global.)
+CLAIM_LEASE_SECONDS: float = 600.0
+
+#: How long ONE delivery — the whole ladder walk, not one rung — may take before it is
+#: cancelled and its attempt treated as failed.
+#:
+#: The claim above buys single-flight against a competing owner and, through lease
+#: expiry, recovery from an owner that DIES. Neither covers an owner that never
+#: RETURNS: a transport that accepted the request and hung (a half-open socket, a
+#: platform that stopped answering, an adapter with no timeout of its own) leaves the
+#: pass suspended inside the send, the row ineligible for as long as the lease holds,
+#: and nothing anywhere reporting it — the drain is not crashed, it is stopped. The
+#: notice would be owed indefinitely, and so would every notice behind it.
+#:
+#: Why 300 s, from both sides, on the same arithmetic as the lease. The worst
+#: LEGITIMATE walk — five rungs, each able to sit on an adapter's HTTP timeout of
+#: roughly 30-60 s — comes to AT MOST this same 300 s, so the bound MATCHES the worst
+#: case rather than exceeding it: a walk that saturates every rung's timeout is
+#: cancelled at the line and consumed as an ordinary failed attempt, retried on the
+#: declared backoff, and any rung that had already persisted its receipt is absorbed
+#: by the duplicate short-circuit on the retry. That trade is deliberate — a rarely
+#: mislabelled slowest-possible walk costs one bounded retry, while a longer deadline
+#: would hold every notice behind a wedge for that much longer. And it has to stay
+#: strictly BELOW ``CLAIM_LEASE_SECONDS``, so a timed-out claimant is cancelled and
+#: its backoff durably written while its OWN lease still holds: a replacement claimant
+#: can never coexist with a transport coroutine that is still unwinding.
+#:
+#: What the deadline does to the claim is the load-bearing half: it CONSUMES it. The
+#: attempt was made durable by the claim before the send, so the timeout takes the
+#: ordinary retry path and arms ``BACKOFF_SECONDS[attempts - 1]``. Rewinding
+#: ``attempts`` instead would let a transport that hangs every time retry without bound
+#: and never dead-letter — the unbounded loop the raising-rung handler exists to
+#: prevent, reached by a different road.
+#:
+#: The stated assumption, because it is an assumption and not a proof: the bound holds
+#: only for a transport that HONOURS cancellation. ``asyncio.wait_for`` cancels the
+#: inner task and awaits that cancellation before raising, so our adapters — none of
+#: which swallow ``CancelledError`` — are cancelled rather than detached. One that
+#: swallowed it would hang the deadline too and re-wedge the drain; because the drain
+#: is dispatched off the store watch rather than awaited by it, that failure is
+#: confined to notice delivery instead of stopping every periodic pass.
+NOTICE_DELIVERY_TIMEOUT_SECONDS: float = 300.0
+
+#: How long ONE DRAIN PASS may keep pulling notices out of its batch.
+#:
+#: What this is NOT for, refuted first because the obvious diagnosis is wrong: a
+#: wedged batch does not re-select itself forever. ``list_owed_failure_notices``
+#: orders by ``next_attempt_at ASC`` — least-recently-deferred first — so the fresh
+#: backoff instants a slow pass just armed sort BEHIND a notice stamped while it was
+#: working, and the newcomer is picked up next pass. Starvation by re-selection is
+#: already closed by that ordering.
+#:
+#: What it IS for is the SERIAL cost of one pass. Deliveries within a pass run one at
+#: a time, and that is deliberate: row #2 of a streak only observes row #1's ``sent``
+#: because the passes are ordered, so parallelising them reopens the same-streak
+#: duplicate window that serialization closes. But a batch of ten, each legitimately
+#: sitting on ``NOTICE_DELIVERY_TIMEOUT_SECONDS``, is ten times that deadline before
+#: the pass so much as returns — and a notice stamped one second in waits behind all
+#: of it. So the fix is a BUDGET, not concurrency.
+#:
+#: Why twice the delivery deadline, from both sides. It has to be at least ONE full
+#: worst-case delivery, or a pass could spend its budget before finishing the notice
+#: it started and the drain would make no progress at all — the budget is checked
+#: BETWEEN notices and never cancels a delivery in flight, so anything smaller just
+#: means "one notice per pass" while a value below the deadline would additionally
+#: read as an attempt to bound a send it cannot bound. And it has to be small enough
+#: that a fresh notice's wait is a function of the budget rather than of the batch
+#: size: the worst wait becomes budget + one delivery instead of ten deliveries, and
+#: it stops growing when the batch limit does.
+#:
+#: What a budget-truncated pass costs the rows it did not reach: nothing. They were
+#: never claimed, so no attempt is consumed and no backoff is armed; they stay exactly
+#: as eligible as they were, and the ASC ordering puts the oldest of them first.
+NOTICE_DRAIN_PASS_BUDGET_SECONDS: float = 2 * NOTICE_DELIVERY_TIMEOUT_SECONDS
+
+#: How long the settled-prefix deferral waits on an earlier nonterminal run before
+#: treating it as settled. See ``earliest_unsettled_run_before``.
+DEFERRAL_STALE_AFTER_SECONDS = 3600.0
+
+#: What a notice is ABOUT. Absent means ``failure``, so every notice stamped
+#: before this field existed keeps its lane — the field is additive, and the
+#: eligibility index is expressed over ``state``/``next_attempt_at`` only, so
+#: adding it needs no migration.
+NOTICE_KIND_FAILURE = "failure"
+#: A pinned session binding was replaced under the user. Unlike a failure this can
+#: be reported by a run that SUCCEEDED, which is exactly why it needs its own kind:
+#: nothing in the failure lane stamps a succeeded row.
+NOTICE_KIND_BINDING_CHANGE = "binding_change"
+
+#: How long a DEFERRED notice steps aside before being reconsidered.
+#:
+#: Deferral has to be durable, not just a Python-side ``continue``. A deferred row
+#: that stays immediately-eligible is re-selected by every tick and keeps occupying
+#: the batch, so one definition with more than a batch worth of pending failures
+#: starves every other definition's notices — and interruptions — indefinitely,
+#: with no error and a drain that looks healthy because it is busy.
+#:
+#: Short enough to stay responsive once the blocker resolves (the canonical is sent
+#: or dead-letters, or the earlier run settles), long enough that the row is not
+#: back in the next tick. It consumes NO attempt: the row has not been tried.
+DEFERRAL_RECHECK_SECONDS = 30.0
+
+
+#: SHORT user-visible labels for the interruption lane's reasons.
+#:
+#: ``harness.notice.interrupted`` renders its ``reason=`` inside the sentence, so the
+#: value substituted there is product copy whether or not anyone treated it as such.
+#: The drain interpolated the WIRE value, and a Chinese user was told 被中断
+#: (backend_refresh): an internal identifier, untranslated, mid-sentence.
+#:
+#: Same construction as ``SETTLEMENT_I18N_KEYS`` / ``SWEEP_I18N_KEYS`` and for the same
+#: reason — an explicit map rather than ``f"harness.notice.reason.{reason}"`` — so the
+#: settlement vocabulary stays free to change without a renamed value silently
+#: degrading into a raw key in the middle of a translated sentence.
+#:
+#: These are LABELS, not the long explanations in ``harness.run.interrupted.*``. That
+#: family is the run's ``error`` column, read on its own; this one is a parenthetical
+#: inside a headline, so it has to be a phrase.
+#:
+#: The key set must equal ``RUN_INTERRUPTION_REASONS``, since that frozenset is what
+#: gates the interrupted branch; pinned by
+#: ``tests/test_i18n_backend_keys.py::test_notice_reason_i18n_map_covers_exactly_the_interruption_lane``.
+NOTICE_REASON_I18N_KEYS: dict[str, str] = {
+ SETTLED_BY_STOPPED: "harness.notice.reason.stopped",
+ SETTLED_BY_BACKEND_REFRESH: "harness.notice.reason.backendRefresh",
+ INTERRUPT_REASON_EVICTED: "harness.notice.reason.evicted",
+ INTERRUPT_REASON_RESTARTED: "harness.notice.reason.restarted",
+ INTERRUPT_REASON_LIFETIME_TIMEOUT: "harness.notice.reason.lifetimeTimeout",
+ # The sweep's "owner vanished" class, spelled as a literal exactly as
+ # ``RUN_INTERRUPTION_REASONS`` does — the constant itself lives in the store, and
+ # importing storage from core would invert the layering.
+ "orphaned": "harness.notice.reason.orphaned",
+}
+
+#: The label for a reason with no entry above — a LOCALIZED generic, never the wire
+#: value and never the dotted key path.
+#:
+#: ``NOTICE_REASON_I18N_KEYS.get(reason, reason)`` would be the obvious spelling and is
+#: the original defect again, reachable in precisely the window the drift test exists to
+#: close: between a reason being added to the lane and CI noticing it has no label.
+NOTICE_REASON_UNKNOWN_I18N_KEY = "harness.notice.reason.unknown"
+
+
+def notice_reason_i18n_key(reason: Optional[str]) -> str:
+ """The i18n key for one interruption reason's short label."""
+
+ return NOTICE_REASON_I18N_KEYS.get(
+ str(reason or "").strip(), NOTICE_REASON_UNKNOWN_I18N_KEY
+ )
+
+
+#: The ``interrupt_reason`` values that stay in the FAILED lane — the per-fire verdicts.
+#:
+#: DERIVED, not retyped: every reason the settlement, sweep and dispatch-failure
+#: vocabularies name, minus the ones ``RUN_INTERRUPTION_REASONS`` claims for the
+#: interrupted lane. That subtraction is the same discriminator ``is_interruption``
+#: applies, so the two cannot disagree about which lane a reason belongs to.
+#:
+#: ``DISPATCH_FAILURE_REASONS`` joined the union rather than being retyped into one of
+#: the other two, and that choice is load-bearing for this derivation's honesty. The
+#: obvious shortcut — declaring ``delivery_target_missing`` in ``SETTLEMENT_I18N_KEYS``
+#: with a ``harness.run.interrupted.*`` twin — would have made the drift pin pass while
+#: recording a dispatch failure as a waiter settlement AND shipping a long description
+#: no caller renders (``SETTLEMENT_I18N_KEYS`` is only ever consulted for a run whose
+#: turn actually existed). One vocabulary per origin, one union here.
+PER_FIRE_INTERRUPT_REASONS = frozenset(
+ (set(SETTLEMENT_I18N_KEYS) | set(SWEEP_I18N_KEYS) | set(DISPATCH_FAILURE_REASONS))
+ - set(RUN_INTERRUPTION_REASONS)
+)
+
+#: SHORT user-visible labels for the FAILED lane's classes — D5's "the error and its
+#: class", which the per-fire lane dropped entirely.
+#:
+#: WHY NOT ``NOTICE_REASON_I18N_KEYS``. Its key set is drift-pinned to
+#: ``RUN_INTERRUPTION_REASONS``, which is precisely the set this lane EXCLUDES: a reason
+#: with an entry there always takes the interrupted headline, so reusing that map here
+#: would render the localized generic ("for a reason outside the run itself") for every
+#: failed-lane notice — a sentence that is both uninformative and, on this lane, untrue.
+#: Same construction, second vocabulary.
+#:
+#: WHY NOT ``harness.run.interrupted.*`` either: that family is the run's ``error``
+#: column, already printed on its own line by ``harness.notice.error``, so reusing it
+#: would print the same sentence twice. These are parenthetical labels.
+#:
+#: Key set pinned to ``PER_FIRE_INTERRUPT_REASONS`` by
+#: ``tests/test_i18n_backend_keys.py::test_notice_failure_class_map_covers_exactly_the_per_fire_lane``.
+NOTICE_FAILURE_CLASS_I18N_KEYS: dict[str, str] = {
+ SETTLED_BY_NO_TERMINAL_RESULT: "harness.notice.class.noTerminalResult",
+ SETTLED_BY_REFUSED_CONCURRENT_TURN: "harness.notice.class.refusedConcurrentTurn",
+ # Sweep reasons, spelled as literals for the same layering reason
+ # ``NOTICE_REASON_I18N_KEYS`` spells ``orphaned`` as one.
+ "transport_unavailable": "harness.notice.class.transportUnavailable",
+ "queue_hold_expired": "harness.notice.class.queueHoldExpired",
+ # The dispatch lane. #1060's field case: the notice's ``error`` line already
+ # carries "agent session id not found: <id>", which is the exception's own text
+ # and names the session — but a raw id is not a diagnosis. The label is what turns
+ # it into one, and it is the only place the notice says the failure is about the
+ # DESTINATION rather than about the work.
+ INTERRUPT_REASON_DELIVERY_TARGET_MISSING: "harness.notice.class.deliveryTargetMissing",
+}
+
+
+def notice_failure_class_i18n_key(reason: Optional[str]) -> Optional[str]:
+ """The i18n key for a failed-lane class label, or ``None`` when there is none.
+
+ ``None`` rather than a generic, deliberately, and it is the opposite choice from
+ ``notice_reason_i18n_key``'s. There the reason is rendered INSIDE a sentence that is
+ printed either way, so a missing label has to degrade to something readable. Here the
+ label IS the line: with nothing real to name, the honest rendering is no line at all
+ rather than "Class: unknown" — copy about nothing, on the lane that already carries
+ the most lines.
+ """
+
+ return NOTICE_FAILURE_CLASS_I18N_KEYS.get(str(reason or "").strip())
+
+
+#: Display names for the platform a definition was CREATED on, keyed by the wire value
+#: ``PLATFORM_REGISTRY`` uses (note ``lark``, not ``feishu``). A CLOSED map for the same
+#: reason ``NOTICE_FAILURE_CLASS_I18N_KEYS`` is one: the origin line renders inside a
+#: translated sentence, so an unknown platform must take no line rather than
+#: interpolate a raw identifier into product copy. Drift-pinned against the registry by
+#: ``test_every_notice_origin_platform_label_resolves``.
+NOTICE_ORIGIN_PLATFORM_I18N_KEYS: dict[str, str] = {
+ "slack": "harness.notice.platform.slack",
+ "discord": "harness.notice.platform.discord",
+ "telegram": "harness.notice.platform.telegram",
+ "lark": "harness.notice.platform.lark",
+ "wechat": "harness.notice.platform.wechat",
+ "avibe": "harness.notice.platform.avibe",
+}
+
+
+def notice_origin_platform_i18n_key(platform: Optional[str]) -> Optional[str]:
+ """The i18n key for a creation-origin platform label, or ``None`` when unmapped."""
+
+ return NOTICE_ORIGIN_PLATFORM_I18N_KEYS.get(str(platform or "").strip())
+
+
+@dataclass(frozen=True)
+class NoticeDecision:
+ action: str
+ reason: str = ""
+
+
+def is_interruption(notice: Optional[dict[str, Any]]) -> bool:
+ """Whether this notice belongs to the per-run interruption lane.
+
+ Membership in a closed set, never ``interrupt_reason is not None``: master
+ stamps that field for ``no_terminal_result``, ``refused_concurrent_turn``,
+ ``transport_unavailable`` and ``queue_hold_expired`` too, all of which recur on
+ every fire and therefore belong in the suppressed failure lane. Reading
+ presence as "interrupted" would give the commonest failures an unsuppressed
+ notice per tick — the daily spam this scope exists to prevent.
+ """
+
+ reason = str((notice or {}).get("interrupt_reason") or "").strip()
+ return reason in RUN_INTERRUPTION_REASONS
+
+
+def notice_kind(notice: Optional[dict[str, Any]]) -> str:
+ """This notice's lane, defaulting to ``failure`` for rows stamped without one."""
+
+ return str((notice or {}).get("kind") or "").strip() or NOTICE_KIND_FAILURE
+
+
+def is_binding_change(notice: Optional[dict[str, Any]]) -> bool:
+ """Whether this notice reports a session binding that was replaced."""
+
+ return notice_kind(notice) == NOTICE_KIND_BINDING_CHANGE
+
+
+def bypasses_suppression(notice: Optional[dict[str, Any]]) -> bool:
+ """Whether this notice is delivered per-run, outside the failure streak.
+
+ Two lanes qualify, for the SAME reason and not by accident:
+
+ * an interruption hits a run at most once, so per-run notices are self-bounding;
+ * a binding change is already scoped by ``SessionBindingChange.signature`` — one
+ broken binding, one notification — so it carries its own bound and does not
+ need the streak's.
+
+ Asking this instead of ``is_interruption`` at the drain's streak gate matters
+ beyond taste: ``failure_streak_decision`` accepts a ``succeeded`` anchor, so
+ reading the streak for a binding notice on a successful rebind would sweep in the
+ definition's surrounding FAILURES and defer or skip the notice behind a canonical
+ row that has nothing to do with it — the notice would be stamped, durable, and
+ never sent.
+ """
+
+ return is_interruption(notice) or is_binding_change(notice)
+
+
+def decide(
+ *,
+ run_id: str,
+ definition_id: Optional[str],
+ notice: Optional[dict[str, Any]],
+ streak_facts: Optional[dict[str, Any]],
+ earlier_unsettled: Optional[dict[str, Any]],
+ callback_status: Optional[str] = None,
+) -> NoticeDecision:
+ """What to do with one pending owed notice.
+
+ ``streak_facts`` is ``SQLiteBackgroundTaskStore.failure_streak_decision``'s answer
+ — ``in_streak``, ``has_sent_elsewhere``, ``earliest_pending_id`` — or ``None`` when
+ no streak was read (the bypass lanes below return before it is consulted).
+ ``earlier_unsettled`` is an earlier-created execution of the same definition that
+ has not settled. ``callback_status`` is the run's effective callback delivery
+ state read FRESH at decision time (``run_callback_state``): a queued callback
+ child remains pending, only a succeeded child is sent, and a terminally failed
+ child releases the notice. ``None`` means the run has no callback.
+
+ Facts, not rows. This function used to receive the streak itself and rederive
+ "anyone sent?" and "who is canonical?" from it in Python, which is what made the
+ read cost the streak's length and let the three reads behind it disagree about
+ where the streak ENDED. Both questions are one indexed comparison each, so they
+ are answered where the rows are. The outcomes are unchanged, reason strings
+ included.
+ """
+
+ # A PENDING CALLBACK IS ALREADY A DELIVERY for the same transition (plan
+ # correction, 2026-07-29): a failed run carrying ``callback_session_id`` gets a
+ # user-visible result turn from ``_drain_callbacks``, so the notice lane firing
+ # too would give one failure two independently keyed messages. The stamp stayed
+ # unconditional for durability — the callback can still die — so the DRAIN
+ # resolves the race here, on the callback's own outcome: still ``pending`` →
+ # step aside without consuming an attempt; ``sent`` → this notice is a
+ # duplicate, acknowledged as delivered-by-callback; ``failed``/``skipped`` →
+ # the primary path is dead and the retry protocol below proceeds.
+ #
+ # Checked before every other lane — including the interruption lane, whose
+ # unconditional DELIVER is about suppression scope, not about a second
+ # messenger — with one exemption: a binding-change notice reports a different
+ # fact (the pinned session was replaced), which the callback's result turn
+ # never carries, so shielding it would silence the news entirely.
+ if callback_status and not is_binding_change(notice):
+ if callback_status == "pending":
+ return NoticeDecision(ACTION_DEFER, "callback_pending")
+ if callback_status == "sent":
+ return NoticeDecision(ACTION_SKIP, "delivered_by_callback")
+
+ if is_interruption(notice):
+ # Per-run, always, with no suppression scope and no deferral: the streak is
+ # irrelevant to a notice that can only happen once for this run, and
+ # deferring behind an unrelated run would delay a D1 notice for no gain.
+ return NoticeDecision(ACTION_DELIVER, "interruption")
+
+ if is_binding_change(notice):
+ # Same shape, different bound. The transition is already deduped on
+ # ``SessionBindingChange.signature`` before it is ever stamped, so there is
+ # nothing here for the streak to suppress — and the run this notice rides on
+ # may have SUCCEEDED, which no streak reasoning is written for.
+ return NoticeDecision(ACTION_DELIVER, "binding_change")
+
+ if not definition_id:
+ # A one-off or ad-hoc run has no definition, so it has no streak and is
+ # never suppressed. Every such failure is a first failure.
+ return NoticeDecision(ACTION_DELIVER, "no_definition")
+
+ if earlier_unsettled is not None:
+ # Classification is deferred while any earlier-created run of the same
+ # definition is nonterminal, so the streak is a function of a settled prefix
+ # and cannot be rewritten by a straggler. Cheap for every definition that
+ # holds an execution lock — those serialize, so the predicate never fires.
+ return NoticeDecision(ACTION_DEFER, f"earlier_run_unsettled:{earlier_unsettled['id']}")
+
+ facts = streak_facts or {}
+
+ # Evidence of delivery ANYWHERE in the streak settles it: this row is a
+ # duplicate. Note this is checked before the canonical is consulted, because a
+ # sent notice is not necessarily the earliest row.
+ if facts.get("has_sent_elsewhere"):
+ return NoticeDecision(ACTION_SKIP, "streak_already_notified")
+
+ # The canonical notice is the earliest still-trying row. ``failed`` (dead
+ # lettered) and ``skipped`` rows drop out, which is exactly how promotion
+ # works: a streak whose canonical exhausted its retries still owes the user the
+ # news, so the claim on delivery outlives any single row.
+ #
+ # ``None`` covers two cases that decide the same way and always did: this run
+ # belongs to no streak at all (``in_streak`` false — a one-off, an interruption,
+ # another definition's run), and a streak in which nothing is pending any more.
+ # Both mean nobody else has a claim on telling the user.
+ canonical_id = facts.get("earliest_pending_id")
+ if canonical_id is None or canonical_id == run_id:
+ return NoticeDecision(ACTION_DELIVER, "canonical")
+
+ # The canonical notice is still pending — by design, because it keeps retrying.
+ # Absence of an acknowledgement is NOT evidence that nothing is in flight, so
+ # this row waits rather than notifying. At most one notice per streak is ever in
+ # flight, which is the property "once, not daily" was asking for.
+ return NoticeDecision(ACTION_DEFER, f"canonical_pending:{canonical_id}")
+
+
+def _attempts_read(value: Any) -> int:
+ """``attempts`` as SQLite's CAS will read it — CAST semantics, not ``int()``.
+
+ The field lives in a JSON blob, so it can hold anything; what this policy and
+ the guarded write MUST share is the raw SQLite DECODE of the stored value —
+ diverge there and the claim can never match, so the row stays eligible and
+ unchanged on every drain pass: one of the ten batch slots occupied forever,
+ every notice behind it starved. Shared decode, not necessarily the same final
+ number: for a NEGATIVE decode the CAS expectation stays raw (asserting the row
+ as it is stored, so the claim still lands) while the policy consumer
+ (``next_attempt``) clamps its input to the ladder's start before incrementing,
+ so a hand-edited counter can never buy more than ``MAX_ATTEMPTS`` attempts.
+ The first version of this function degraded to 0 on any conversion
+ error, which agreed with SQLite for ``"abc"`` but diverged for every
+ numeric-PREFIX string (``"3x"`` reads 3 under ``CAST``, 0 under ``int()``),
+ for ``"1e100"`` (1 vs 0), and for out-of-range numbers (SQLite saturates at
+ the signed-64-bit bounds; ``int()`` does not) — exactly the split the round-18
+ review named. Both readers now consume one dependency-neutral model of
+ ``CAST(... AS INTEGER)`` (``storage.sqlite_semantics.sqlite_cast_integer``),
+ pinned by an executable parity oracle against real SQLite, so a drift fails
+ against the engine rather than surviving as an argument.
+ """
+
+ return sqlite_cast_integer(value)
+
+
+def next_attempt(notice: dict[str, Any]) -> tuple[int, Optional[float]]:
+ """The attempt number this delivery is, and how long to wait if it fails.
+
+ ``None`` for the delay means there is no attempt left: the notice dead-letters.
+
+ The index is off the attempt this delivery IS, minus one — the Nth failed attempt
+ arms ``BACKOFF_SECONDS[N - 1]``. Indexing on the incremented number instead skipped
+ the first declared interval entirely (a freshly stamped notice waited 8 s, never
+ 2 s) and shortened the ladder by one rung, so the declared cap was never armed and
+ ``CLAIM_LEASE_SECONDS``' "must exceed the retry cap" argument was about an interval
+ the code could not reach. One interval per consumed attempt, in order, then the
+ dead letter.
+ """
+
+ # The POLICY counter clamps a negative read to the start of the ladder; the CAS
+ # expectation deliberately does not (``notice_write_expectation`` asserts the raw
+ # stored value, so the guarded claim still matches the row as it is). CAST
+ # semantics can read a negative from an out-of-band value ("-3q" reads -3,
+ # INT64_MIN from a saturated number), and incrementing FROM it would grant the
+ # notice more than ``MAX_ATTEMPTS`` attempts — ~9.2 quintillion for the saturated
+ # case, each on the shortest backoff. Clamped, the first claim stamps attempt 1
+ # over the poison and the row is a normal notice again in one pass.
+ attempts = max(_attempts_read(notice.get("attempts")), 0) + 1
+ if attempts >= MAX_ATTEMPTS:
+ return attempts, None
+ return attempts, BACKOFF_SECONDS[attempts - 1]
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 620e778e0..b8959fc4f 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -228,7 +228,7 @@ class SessionHandler(BaseHandler):
)
return None
- caller_env = caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+ caller_env = self._caller_env_for_context(context)
if getattr(client, "_vibe_caller_env", {}) != caller_env:
logger.info(
"Recreating cached Claude SDK client for %s because caller context env changed",
@@ -296,7 +296,7 @@ class SessionHandler(BaseHandler):
agent_name="claude",
session_anchor=base_session_id,
)
- caller_env = caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+ caller_env = self._caller_env_for_context(context)
if getattr(client, "_vibe_caller_env", {}) != caller_env:
logger.info(
"Recreating cached Claude subagent SDK client for %s because caller context env changed",
@@ -425,6 +425,37 @@ class SessionHandler(BaseHandler):
or getattr(self.config, "platform", "slack")
)
+ def _caller_env_for_context(self, context: MessageContext) -> dict[str, str]:
+ """Caller identity AND creation origin for the Agent subprocess env.
+
+ The typed context is passed alongside the platform payload because an
+ IM-created Harness definition is created by an Agent run executing
+ ``vibe task add`` — this env is the only channel between the conversation that
+ asked for it and the ``created_by.caller`` row that records where it came from.
+ Dropping the ids here is what left the failure ladder's owner-DM rung dormant
+ and the notice unable to name its origin.
+
+ The platform is resolved through ``_get_context_platform`` rather than off the
+ context alone, so the captured origin agrees with the platform every other
+ session-scoped decision in this handler is made with (the Slack adapter sets
+ neither ``context.platform`` nor a payload ``platform``).
+
+ SESSION-STABLE ONLY, and that is not a shortcut. This env is baked into a Claude
+ SDK client at spawn and is also the value compared to decide whether a cached
+ client may be reused, so a field that changes per turn would respawn the Agent on
+ every message, and a field that changes per author would attribute one
+ participant's definition to another. ``CallerContext.session_stable`` documents
+ both, and what a Claude-created definition therefore keeps: the conversation, not
+ the author or the individual message.
+ """
+
+ return caller_env_for_platform_payload(
+ getattr(context, "platform_specific", None),
+ message=context,
+ fallback_platform=self._get_context_platform(context),
+ session_stable_only=True,
+ )
+
def should_allocate_scheduled_anchor(self, context: MessageContext, source: str = "human") -> bool:
if source != "scheduled" or context.thread_id:
return False
@@ -1057,7 +1088,7 @@ class SessionHandler(BaseHandler):
claude_env = build_claude_subprocess_env(getattr(self.config, "claude", None))
if model_hub_launch is not None:
claude_env = build_claude_hub_env(claude_env, model_hub_launch)
- claude_env.update(caller_env_for_platform_payload(getattr(context, "platform_specific", None)))
+ claude_env.update(self._caller_env_for_context(context))
prepend_vendored_git_to_path(
claude_env,
base_env=os.environ,
@@ -1124,7 +1155,7 @@ class SessionHandler(BaseHandler):
# Create new Claude client
client = ClaudeSDKClient(options=options)
- setattr(client, "_vibe_caller_env", caller_env_for_platform_payload(getattr(context, "platform_specific", None)))
+ setattr(client, "_vibe_caller_env", self._caller_env_for_context(context))
setattr(client, "_vibe_git_path_state", git_path_state)
setattr(
client,
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 037f36444..94fccc492 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -19,6 +19,7 @@ from config.platform_registry import get_platform_descriptor
from config.v2_config import DEFAULT_AGENT_PROGRESS_STYLE
from modules.im import MessageContext
from modules.im.formatters.base_formatter import to_status_label
+from core.delivery_evidence import STAGE_PERSIST, STAGE_SEND, STAGE_STREAM, DeliveryEvidence
from core.message_mirror import (
agent_message_exists,
persist_agent_message,
@@ -1386,6 +1387,7 @@ class ConsolidatedMessageDispatcher:
result_footer: Optional[str] = None,
output: MessageOutput | None = None,
terminal_error: Optional[str] = None,
+ delivery: DeliveryEvidence | None = None,
) -> Optional[str]:
"""Centralized dispatch for agent messages.
@@ -1555,6 +1557,26 @@ class ConsolidatedMessageDispatcher:
if native_output_id and agent_message_exists(target_context, native_output_id):
logger.info("Skipping duplicate agent output %s", native_output_id)
+ # An existing row is the STRONGEST receipt available — stronger than a
+ # send that returned an id, because it proves the write committed. Report
+ # it here or a caller holding a durable notice cannot distinguish "already
+ # delivered" from "never delivered": this branch returns ~112 lines above
+ # the notify branch's evidence assignment, and the drain reads the
+ # evidence, not the return value.
+ #
+ # That gap was reachable exactly where it hurts most — a crash between
+ # persisting the message and acknowledging the notice, which is the case
+ # the idempotency key exists for. The retry would find the row, decline to
+ # re-send, report nothing, and then either walk on to another delivery
+ # rung (a duplicate by another route) or exhaust its backoff and
+ # dead-letter a notice the user already has.
+ if delivery is not None:
+ delivery.send_returned = True
+ delivery.delivered_id = native_output_id
+ delivery.persisted_row = {
+ "native_message_id": native_output_id,
+ "evidence": "duplicate_short_circuit",
+ }
try:
if canonical_type == "result" and output_semantics.settles_run:
duplicate_result_text = self._fold_footer(
@@ -1679,24 +1701,54 @@ class ConsolidatedMessageDispatcher:
self._release_runtime_turn(context)
if canonical_type == "notify":
+ # Three steps, three error scopes — deliberately NOT one blanket ``try``.
+ #
+ # Under a single ``try`` a persistence failure returned ``None`` and
+ # DISCARDED the message id assigned on the line above, turning
+ # "delivered but unpersisted" into "looks like never delivered" and
+ # re-sending a notice the user already had. A post-delivery
+ # ``_stream_chunk`` failure did the same thing. Whoever owes a durable
+ # notice for this message has to be able to tell those apart from a send
+ # that genuinely failed, so each stage reports itself.
try:
message_id = await im_client.send_message(target_context, text, parse_mode=parse_mode)
- # Record only once delivered (avibe always, via SSE) so a failed
- # IM send isn't stored as if the user received it.
- if persists_without_delivery or message_id is not None:
- persist_agent_message(
- target_context,
- "notify",
- text,
- metadata=output_metadata,
- native_message_id=native_output_id,
- )
- # Live SSE turn stream for the web Chat page (no-op for IM/CLI).
+ except Exception as err:
+ logger.error("Failed to send notify message: %s", err, exc_info=True)
+ if delivery is not None:
+ delivery.error = err
+ delivery.error_stage = STAGE_SEND
+ return None
+ if delivery is not None:
+ delivery.send_returned = True
+ delivery.delivered_id = message_id
+ # Record only once delivered (avibe always, via SSE) so a failed
+ # IM send isn't stored as if the user received it.
+ if persists_without_delivery or message_id is not None:
+ persist_errors: list[BaseException] = []
+ persisted_notify = persist_agent_message(
+ target_context,
+ "notify",
+ text,
+ metadata=output_metadata,
+ native_message_id=native_output_id,
+ error_sink=persist_errors,
+ )
+ if delivery is not None:
+ delivery.persisted_row = persisted_notify
+ if persisted_notify is None and persist_errors:
+ delivery.error = persist_errors[0]
+ delivery.error_stage = STAGE_PERSIST
+ # Live SSE turn stream for the web Chat page (no-op for IM/CLI). Past
+ # this point the message is delivered; a failure here is recorded for
+ # diagnosis and must not be read as a delivery failure.
+ try:
await _stream_chunk(self.controller, context, text=text, message_id=message_id, kind="notify")
- return message_id
except Exception as err:
- logger.error("Failed to send notify message: %s", err)
- return None
+ logger.error("notify stream failed after delivery: %s", err, exc_info=True)
+ if delivery is not None:
+ delivery.error = err
+ delivery.error_stage = STAGE_STREAM
+ return message_id
if canonical_type == "result":
try:
@@ -1930,8 +1982,17 @@ class ConsolidatedMessageDispatcher:
# same body+footer without double-appending (persist_text is never
# mutated) and is a no-op when there is no footer.
persisted_result_text = self._fold_footer(persist_text, folded_footer)
+ run_provenance = output_semantics.provenance(context)
+ workbench_run_waits_for_persistence = (
+ target_context.platform == "avibe"
+ and output_semantics.settles_run
+ and bool(run_provenance.get("run_id") or run_provenance.get("run_ids"))
+ )
+ settlement_waits_for_persistence = (
+ output_semantics.requires_delivery_for_run_settlement or workbench_run_waits_for_persistence
+ )
- if not output_semantics.requires_delivery_for_run_settlement:
+ if not settlement_waits_for_persistence:
self._record_agent_run_terminal_result(
context,
persisted_result_text,
@@ -1980,10 +2041,20 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
)
- if output_semantics.requires_delivery_for_run_settlement:
- if persisted_output is None and not (
- native_output_id
- and agent_message_exists(target_context, native_output_id)
+ if settlement_waits_for_persistence:
+ durable_output_exists = bool(
+ persisted_output is not None
+ or (
+ native_output_id
+ and agent_message_exists(target_context, native_output_id)
+ )
+ )
+ if workbench_run_waits_for_persistence and not durable_output_exists:
+ raise RuntimeError("Workbench run output was not durably persisted")
+ if (
+ output_semantics.requires_delivery_for_run_settlement
+ and not workbench_run_waits_for_persistence
+ and not durable_output_exists
):
raise RuntimeError(
"Activity output was not durably persisted after delivery"
diff --git a/core/message_mirror.py b/core/message_mirror.py
index f8fb1d5eb..d88be5fff 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -323,6 +323,7 @@ def persist_agent_message(
quick_replies: Optional[list[str]] = None,
metadata: Optional[dict[str, Any]] = None,
native_message_id: Optional[str] = None,
+ error_sink: Optional[list] = None,
) -> Optional[dict]:
"""Persist one agent output into the workbench ``messages`` store.
@@ -487,8 +488,16 @@ def persist_agent_message(
except Exception:
logger.debug("web push notification scheduling failed", exc_info=True)
return appended_row
- except Exception:
+ except Exception as err:
logger.exception("persist_agent_message: failure on platform=%s", context.platform)
+ # Surfaced, not raised. A caller that owes a durable receipt needs to know
+ # WHY the row is missing — propagating only ``None`` says a receipt is
+ # absent and nothing about whether the message was delivered. Raising
+ # instead would be caught by the notify branch and discard the message id
+ # already in hand, which is the bug this channel exists to avoid.
+ # Optional so the eleven callers that ignore it are unaffected.
+ if error_sink is not None:
+ error_sink.append(err)
return None
diff --git a/core/origin_links.py b/core/origin_links.py
new file mode 100644
index 000000000..cadff5f36
--- /dev/null
+++ b/core/origin_links.py
@@ -0,0 +1,111 @@
+"""Deep links back to the message that created a Harness definition.
+
+One function, one rule: LINK OR ``None``, never a fabricated URL. A failure notice
+that offers a link the user cannot follow is worse than a notice that offers none —
+it moves the failure from "I do not know where this came from" to "Avibe told me
+where and it was wrong", and the second is the one that costs trust.
+
+So every branch below refuses unless it holds EVERY id that platform's permalink
+grammar requires, and the honesty table is the contract:
+
+============ ================================================ =====================
+platform link when ``None`` when
+============ ================================================ =====================
+``slack`` channel id + message ts either is missing
+``discord`` workspace (guild) id + channel id + message id any is missing —
+ notably a DM, which
+ has no guild
+``telegram`` a ``-100…`` supergroup/channel id + message id a private/basic-group
+ chat id, or no
+ message id
+``lark`` never always
+``wechat`` never always
+``avibe`` never always
+unknown never always
+============ ================================================ =====================
+
+The three refusals-by-design are refusals of DIFFERENT kinds and are spelled out
+rather than lumped together:
+
+* Feishu/Lark (wire value ``lark``) and WeChat have no stable public message
+ permalink an external notice can address, so there is nothing to build.
+* ``avibe`` is the Workbench itself. It HAS an addressable location, but the only URL
+ form is the local setup host — and a ``http://127.0.0.1:<port>/…`` link pasted into
+ a Slack DM or a phone push is not honestly reachable from where the notice is
+ read. The origin TEXT still names the Workbench; only the link is withheld.
+* An unrecognised platform is a wire value this module has never seen. Guessing a URL
+ shape for it is the fabrication this whole module exists to prevent.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+
+def _clean(value: object) -> str:
+ return str(value or "").strip()
+
+
+def _slack_link(channel_id: str, thread_id: str, message_id: str) -> Optional[str]:
+ if not channel_id or not message_id:
+ return None
+ # ``1710000000.000100`` → ``p1710000000000100``: Slack's archive path is the ts
+ # with the dot removed, and nothing else about it is transformed.
+ link = f"https://slack.com/archives/{channel_id}/p{message_id.replace('.', '')}"
+ if thread_id and thread_id != message_id:
+ # A REPLY. Without these params the link opens the parent channel at the
+ # message; with them it opens the thread the definition was actually created
+ # in. ``thread_id == message_id`` is Slack's own "not in a thread" encoding
+ # (the adapter defaults ``thread_id`` to the message's own ts), so it adds
+ # nothing there and is left off.
+ link = f"{link}?thread_ts={thread_id}&cid={channel_id}"
+ return link
+
+
+def _discord_link(workspace_id: str, channel_id: str, message_id: str) -> Optional[str]:
+ if not workspace_id or not channel_id or not message_id:
+ # NEVER ``@me``. That path is valid Discord syntax and resolves for the ONE
+ # user whose DM it is, so it would read as a working link while being
+ # unfollowable for anyone else — including the workspace inbox, which is not a
+ # person at all.
+ return None
+ return f"https://discord.com/channels/{workspace_id}/{channel_id}/{message_id}"
+
+
+def _telegram_link(channel_id: str, message_id: str) -> Optional[str]:
+ # ``t.me/c/<internal id>/<message id>`` exists only for supergroups and channels,
+ # whose ids Telegram prefixes with ``-100``. A private chat or a basic group has no
+ # such link at all, and stripping four characters off an id that does not carry
+ # that prefix would address an unrelated chat.
+ if not message_id or not channel_id.startswith("-100"):
+ return None
+ internal_id = channel_id[4:]
+ if not internal_id:
+ return None
+ return f"https://t.me/c/{internal_id}/{message_id}"
+
+
+def origin_link(
+ platform: object,
+ channel_id: object,
+ thread_id: object,
+ message_id: object,
+ workspace_id: object,
+) -> Optional[str]:
+ """A followable URL for the creating message, or ``None``.
+
+ Pure: no config, no network, no database. Every argument is an id captured at
+ definition-creation time (``CallerContext``'s origin fields), so this can be called
+ from a notice body, a test, or an ad-hoc probe with the same result.
+ """
+
+ resolved_platform = _clean(platform)
+ channel = _clean(channel_id)
+ message = _clean(message_id)
+ if resolved_platform == "slack":
+ return _slack_link(channel, _clean(thread_id), message)
+ if resolved_platform == "discord":
+ return _discord_link(_clean(workspace_id), channel, message)
+ if resolved_platform == "telegram":
+ return _telegram_link(channel, message)
+ return None
diff --git a/core/run_settlement.py b/core/run_settlement.py
index a14d56587..b61bc4832 100644
--- a/core/run_settlement.py
+++ b/core/run_settlement.py
@@ -89,6 +89,96 @@ INTERRUPT_REASON_STOPPED: Final = SETTLED_BY_STOPPED
INTERRUPT_REASON_REFUSED_CONCURRENT_TURN: Final = SETTLED_BY_REFUSED_CONCURRENT_TURN
INTERRUPT_REASON_BACKEND_REFRESH: Final = SETTLED_BY_BACKEND_REFRESH
+#: Reserved for ``docs/plans/harness-run-reliability.md`` (PR2 / PR4 / PR7). Named
+#: here now because the classification below has to be closed over them before
+#: they are written, or each PR would have to remember to widen it.
+INTERRUPT_REASON_EVICTED: Final = "evicted"
+INTERRUPT_REASON_RESTARTED: Final = "restarted"
+INTERRUPT_REASON_LIFETIME_TIMEOUT: Final = "lifetime_timeout"
+
+#: The run could not be dispatched at all because the session it delivers to no
+#: longer exists (``UnresolvableSessionTarget`` with ``reason == "missing"``).
+#:
+#: #1060's field evidence is the whole argument for naming this one. A watch pinned
+#: to a session that later ceased to exist failed three deliveries and stopped, and
+#: the only cause recorded anywhere was ``last_exit_code = 75`` — the user's own
+#: configured ``--retry-exit-code``, i.e. the waiter's HEALTHY "nothing new yet"
+#: signal. The reporter's second ask was literally "a cause field distinct from the
+#: last exit code": ``delivery_target_missing`` is not ``exited 75``, and anyone
+#: debugging from the exit code alone starts by investigating a working waiter.
+INTERRUPT_REASON_DELIVERY_TARGET_MISSING: Final = "delivery_target_missing"
+
+
+#: Per-fire failure classes recorded by the DISPATCH path itself.
+#:
+#: A third source vocabulary rather than an entry in ``SETTLEMENT_I18N_KEYS`` or
+#: ``SWEEP_I18N_KEYS``, because it has a third origin and the honest derivation
+#: downstream depends on saying so. Those two describe a run that WAS dispatched:
+#: a settlement is how a live turn's waiter was released, and a sweep reason is what
+#: a run's vanished owner left behind. This one is recorded BEFORE any turn exists —
+#: the executor could not resolve the target, so nothing was ever dispatched to
+#: release or to orphan.
+#:
+#: A frozenset and not a map, deliberately. ``SETTLEMENT_I18N_KEYS`` /
+#: ``SWEEP_I18N_KEYS`` exist because their reasons ARE the run's user-visible
+#: ``error`` column and therefore need a translated long description. A dispatch
+#: failure already has a better one: the exception's own text names the missing
+#: session id ("agent session id not found: sesd46nxp3cz5"), which is strictly more
+#: informative than any generic sentence this module could supply. Adding a
+#: ``harness.run.interrupted.*`` twin would be copy that never renders.
+#:
+#: What these values DO need is the short parenthetical LABEL for the notice body,
+#: which lives with the other labels in
+#: ``core.failure_notices.NOTICE_FAILURE_CLASS_I18N_KEYS``.
+DISPATCH_FAILURE_REASONS: Final = frozenset({INTERRUPT_REASON_DELIVERY_TARGET_MISSING})
+
+
+#: ``interrupt_reason`` values that terminate ONE run out of band and say nothing
+#: about whether its definition works.
+#:
+#: This set exists because ``interrupt_reason`` is NOT a synonym for "interrupted".
+#: It is the general marker for "terminalized by something other than its own
+#: backend result", and most of the values it carries are ordinary per-fire
+#: verdicts: a turn that ended without dispatching an agent
+#: (``no_terminal_result``), a refused concurrent turn, a run whose transport was
+#: never available, a queue hold that expired, a delivery target that no longer
+#: exists. Those recur on every fire, are exactly the failures P6 exists to surface,
+#: and must count toward a definition's health and share one suppression streak.
+#:
+#: ``delivery_target_missing`` is the sharpest case of that rule and is deliberately
+#: ABSENT below. A definition pinned to a deleted session fails on EVERY fire, so
+#: admitting it here would give it an unsuppressed notice per fire, mint an
+#: ``interrupt:{run}:{reason}`` identity the live path never uses, and take it out of
+#: the health window — reporting a permanently broken watch as healthy while
+#: notifying about it forever. It is a per-fire verdict about the definition, which
+#: is exactly what this set excludes.
+#:
+#: The values below are the opposite shape. Each terminates a specific run from
+#: outside — a deploy, an eviction, a lifetime cap, a supervisor whose process
+#: vanished, a user pressing Stop — at most once per run, and re-firing the
+#: definition is expected to work. So they:
+#:
+#: * stay OUT of the derived health window (they are not evidence about the
+#: definition), and
+#: * stay OUT of the consecutive-failure streak, notifying per run instead
+#: (bounded by the number of runs, so there is nothing to suppress).
+#:
+#: The discriminator has to be membership here rather than ``interrupt_reason IS
+#: NOT NULL``: nullness excludes the common failure population, which reports a
+#: permanently broken definition as healthy AND gives every one of its failures an
+#: unsuppressed notice — P6 and the daily spam it forbids, at the same time.
+RUN_INTERRUPTION_REASONS: Final = frozenset(
+ {
+ SETTLED_BY_STOPPED,
+ SETTLED_BY_BACKEND_REFRESH,
+ INTERRUPT_REASON_EVICTED,
+ INTERRUPT_REASON_RESTARTED,
+ INTERRUPT_REASON_LIFETIME_TIMEOUT,
+ # The sweep's "owner vanished" class: a process restart by another name.
+ "orphaned",
+ }
+)
+
# ----- user-visible reason text -------------------------------------------
#
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index bdc94100a..d361f6dfc 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -8,9 +8,10 @@ import logging
import tempfile
import time
from dataclasses import asdict, dataclass, field
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Dict, NamedTuple, Optional, Sequence
+from types import MappingProxyType
+from typing import Any, Dict, Mapping, NamedTuple, Optional, Sequence
from uuid import uuid4
from zoneinfo import ZoneInfo
@@ -21,6 +22,7 @@ from sqlalchemy import select
from sqlalchemy.exc import SQLAlchemyError
from config import paths
+from config.platform_registry import PLATFORM_REGISTRY
from config.v2_config import (
DEFAULT_HARNESS_RUN_HOLD_TTL_SECONDS,
DEFAULT_HARNESS_RUN_ORPHAN_GRACE_SECONDS,
@@ -34,8 +36,11 @@ from core.message_context import (
resolve_context_thread_id,
thread_id_from_session_anchor,
)
+from core.origin_links import origin_link
from core.reply_enhancer import strip_silent_blocks
from core.run_settlement import (
+ INTERRUPT_REASON_DELIVERY_TARGET_MISSING,
+ RUN_INTERRUPTION_REASONS,
SETTLEMENTS_WITHOUT_RESULT,
SETTLED_BY_NO_TERMINAL_RESULT,
SETTLEMENT_I18N_KEYS,
@@ -44,10 +49,27 @@ from core.run_settlement import (
)
from core.session_activities import activity_completion_output
from modules.im import MessageContext
+from storage.agent_session_rows import (
+ INBOX_SESSION_VISIBILITIES,
+ WORKSPACE_NOTICE_SESSION_ID,
+ session_is_runtime_owned,
+)
from storage.db import create_sqlite_engine, get_cached_sqlite_engine
+from core import failure_notices
+from core.backend_failure import emit_replayed_backend_failure
+from core.delivery_evidence import (
+ ACK_EVIDENCE_DELIVERY_ONLY,
+ ACK_EVIDENCE_RECEIPT,
+ STAGE_PERSIST,
+ DeliveryEvidence,
+)
from storage.background import (
DefinitionWriteConflict,
DefinitionWriteExpectation,
+ NOTICE_FAILED,
+ NOTICE_PENDING,
+ NOTICE_SENT,
+ NOTICE_SKIPPED,
SKIP_REASON_SESSION_BUSY,
SKIP_REASON_TRANSPORT_UNAVAILABLE,
SQLiteBackgroundTaskStore,
@@ -55,6 +77,9 @@ from storage.background import (
SWEEP_REASON_QUEUE_HOLD_EXPIRED,
SWEEP_REASON_TRANSPORT_UNAVAILABLE,
SweptRun,
+ compute_next_run_at,
+ notice_write_expectation,
+ owed_notice_eligible,
resolve_run_at,
)
from storage.models import agent_sessions, scope_settings, scopes
@@ -82,6 +107,24 @@ def _utc_now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def _adopt_delivery_evidence(target: DeliveryEvidence, source: DeliveryEvidence) -> None:
+ """Copy one ladder rung's evidence onto the object the caller holds.
+
+ The owed-notice drain hands ``_emit_failure_notice`` a single
+ ``DeliveryEvidence`` and then reads it back, but a LADDER needs one per rung:
+ ``delivered`` is a latch, so evidence shared across rungs cannot say which rung
+ proved what. The walk therefore builds its own per rung and copies the decisive
+ one out here, by field rather than by rebinding — the caller's reference is the
+ contract.
+ """
+
+ target.delivered_id = source.delivered_id
+ target.persisted_row = source.persisted_row
+ target.send_returned = source.send_returned
+ target.error = source.error
+ target.error_stage = source.error_stage
+
+
def _json_loads(value: str | None, default: Any) -> Any:
if not value:
return default
@@ -154,6 +197,20 @@ def _normalize_file_run_status(payload: dict[str, Any], state: str) -> str:
TERMINAL_RUN_STATUSES = {"succeeded", "failed", "canceled"}
+#: The scope types a SESSION KEY may name. A session key addresses a conversation,
+#: so it is narrower than a scope id on purpose.
+SESSION_KEY_SCOPE_TYPES = frozenset({"channel", "user"})
+#: The scope types a SCOPE ID may name — the same two plus the workbench's
+#: ``project``, which is not a conversation and cannot carry a thread.
+SCOPE_ID_SCOPE_TYPES = frozenset({"channel", "user", "project"})
+#: Every scope type a failure-notice delivery target can carry, because ``_add``
+#: builds every rung through exactly those two parsers and neither admits anything
+#: else. One of the two axes of ``LADDER_ACK_SOURCES`` below, named here rather
+#: than spelled inline in the parsers so the acknowledgement policy can be checked
+#: against the real vocabulary instead of a hand-copied echo of it.
+LADDER_SCOPE_TYPES = SESSION_KEY_SCOPE_TYPES | SCOPE_ID_SCOPE_TYPES
+
+
@dataclass(frozen=True)
class ParsedSessionKey:
platform: str
@@ -185,7 +242,7 @@ def parse_session_key(value: str) -> ParsedSessionKey:
platform, scope_type, scope_id = parts[:3]
if not platform or not scope_id:
raise ValueError("session key platform and scope id are required")
- if scope_type not in {"channel", "user"}:
+ if scope_type not in SESSION_KEY_SCOPE_TYPES:
raise ValueError("session key scope type must be 'channel' or 'user'")
thread_id: Optional[str] = None
@@ -211,7 +268,7 @@ def parse_scope_id(value: str) -> ParsedSessionKey:
platform, scope_type, native_id = parts
if not platform or not scope_type or not native_id:
raise ValueError("scope id platform, scope type, and native id are required")
- if scope_type not in {"channel", "user", "project"}:
+ if scope_type not in SCOPE_ID_SCOPE_TYPES:
raise ValueError("scope id scope type must be 'channel', 'user', or 'project'")
return ParsedSessionKey(
@@ -222,6 +279,127 @@ def parse_scope_id(value: str) -> ParsedSessionKey:
)
+# --- the failure-notice ladder's target x acknowledgement policy -------------
+#
+# WHICH evidence is allowed to acknowledge an owed failure notice depends on WHAT
+# was addressed, and getting that wrong in the permissive direction is the worst
+# outcome the drain has: a notice marked ``sent`` with nothing durable behind it is
+# lost forever, which is strictly worse than the visible dead letter it replaces.
+#
+# It was three separate review findings before it was a table — an ``avibe``
+# special case bolted onto a boolean, which answered for the target classes anyone
+# had thought about and fell through to the permissive branch for the rest. So the
+# policy is ENUMERATED over the two axes a target actually has, the lookup is
+# TOTAL, and the answer for a class nobody declared is the strict one.
+
+#: The transport returned an id that the PLATFORM minted, so the id itself is proof
+#: a person was told; re-sending because the bookkeeping write failed afterwards
+#: would spam a notice that already arrived. A persisted receipt is admitted too —
+#: it is the same claim, only stronger.
+ACK_SOURCE_NATIVE_DELIVERY_ID = "native_delivery_id"
+#: Only a durable ``messages`` row acknowledges. For the workbench that is not
+#: strictness for its own sake, it is what delivery MEANS: the inbox reads rows, an
+#: SSE fan-out with no browser attached reaches nobody, and
+#: ``AvibeBot.send_message`` mints and returns a synthetic ``msg_<hex>`` id
+#: unconditionally — no subscriber required and nothing persisted. Its id therefore
+#: proves nothing at all. Includes the dedup receipt: the duplicate short-circuit
+#: reports the row it FOUND (``persist_agent_message`` already committed it before
+#: the crash), which is the strongest receipt there is, so a crash-then-retry on a
+#: workbench rung acknowledges instead of re-sending forever.
+ACK_SOURCE_PERSISTED_RECEIPT = "persisted_receipt"
+
+#: Which ``DeliveryEvidence.ack_evidence`` values each source admits. Spelled as
+#: sets rather than as a comparison so a third evidence strength cannot be added
+#: without deciding, per source, whether it acknowledges.
+ACK_EVIDENCE_BY_ACK_SOURCE: Mapping[str, frozenset[str]] = MappingProxyType(
+ {
+ ACK_SOURCE_NATIVE_DELIVERY_ID: frozenset(
+ {ACK_EVIDENCE_RECEIPT, ACK_EVIDENCE_DELIVERY_ONLY}
+ ),
+ ACK_SOURCE_PERSISTED_RECEIPT: frozenset({ACK_EVIDENCE_RECEIPT}),
+ }
+)
+
+#: The platform-kind of a target naming a platform the registry does not know. A
+#: deliver key is a free string and ``parse_session_key`` does not check it against
+#: the registry, so this class is reachable and needs a name rather than an
+#: accident.
+LADDER_PLATFORM_KIND_UNREGISTERED = "unregistered"
+
+#: THE policy: one row per (platform kind, scope type) a ladder target can be.
+#: ``PLATFORM_REGISTRY``'s ``kind`` is the axis, not the platform id, so a new IM
+#: transport inherits the IM answer instead of needing a row of its own — and a new
+#: KIND (a transport that is neither, say a future cloud relay) does need one, and
+#: ``test_every_ladder_target_class_declares_its_acknowledgement_source`` fails
+#: until it gets one.
+#:
+#: THE TRUST BOUNDARY THAT MAKES THAT SAFE, stated because it is a premise this table
+#: cannot check for itself: ``kind == "im"`` means the id a send RETURNS was minted by
+#: a platform that reached a person. That is what entitles the two ``im`` conversation
+#: rows below to acknowledge on a delivery id alone. A transport that mints its own id
+#: locally does not qualify, however IM-shaped it looks — the workbench is exactly that
+#: case (``AvibeBot.send_message`` returns a synthetic ``msg_<hex>`` unconditionally),
+#: which is why it has a kind of its own rather than a platform-id exception here.
+#: ``PlatformDescriptor.kind`` DEFAULTS to ``"im"``, so a transport added to the
+#: registry without stating its kind would silently take the permissive rows and no
+#: structural test here would notice: the kind axis would be unchanged, the table would
+#: still be total. ``test_every_registry_platform_declares_its_kind_explicitly``
+#: guards that specific accident at the registry, where the claim is made.
+LADDER_ACK_SOURCES: Mapping[tuple[str, str], str] = MappingProxyType(
+ {
+ # A real IM conversation: the send id came from Slack/Discord/Telegram/
+ # Lark/WeChat, so it is evidence the user was told.
+ ("im", "channel"): ACK_SOURCE_NATIVE_DELIVERY_ID,
+ ("im", "user"): ACK_SOURCE_NATIVE_DELIVERY_ID,
+ # An IM platform with a ``project`` scope is not a conversation — the id is
+ # an internal scope row, not a native channel — so a returned id does not
+ # locate a person. Reachable through a hand-written ``deliver_key`` or
+ # creator scope, and receipt-gated rather than trusted.
+ ("im", "project"): ACK_SOURCE_PERSISTED_RECEIPT,
+ # The workbench, uniformly, for every scope type: the reason is the
+ # TRANSPORT (a synthetic id minted whether or not anything landed), not the
+ # scope shape, so ``avibe::user::…`` from a workbench creator's provenance
+ # is exactly as unproven as ``avibe::project::…``.
+ ("workbench", "channel"): ACK_SOURCE_PERSISTED_RECEIPT,
+ ("workbench", "user"): ACK_SOURCE_PERSISTED_RECEIPT,
+ ("workbench", "project"): ACK_SOURCE_PERSISTED_RECEIPT,
+ # A platform the registry has never heard of: nothing is known about what
+ # its send id means, so nothing is assumed.
+ (LADDER_PLATFORM_KIND_UNREGISTERED, "channel"): ACK_SOURCE_PERSISTED_RECEIPT,
+ (LADDER_PLATFORM_KIND_UNREGISTERED, "user"): ACK_SOURCE_PERSISTED_RECEIPT,
+ (LADDER_PLATFORM_KIND_UNREGISTERED, "project"): ACK_SOURCE_PERSISTED_RECEIPT,
+ }
+)
+
+#: The answer for a target class the table does not name. Deliberately the STRICT
+#: source: an undeclared class that acked on a send id would lose the notice
+#: permanently, while one that demands a receipt it cannot produce retries and then
+#: dead-letters — visibly, with ``last_error``, the health badge and
+#: ``vibe task show`` all still reporting the failure.
+UNDECLARED_LADDER_ACK_SOURCE = ACK_SOURCE_PERSISTED_RECEIPT
+
+
+def failure_notice_target_class(target: ParsedSessionKey) -> tuple[str, str]:
+ """Which enumerated class this ladder target belongs to.
+
+ Total by construction: an unregistered platform gets a named kind, and
+ ``scope_type`` comes from a parser whose vocabulary is ``LADDER_SCOPE_TYPES``.
+ """
+
+ descriptor = PLATFORM_REGISTRY.get(target.platform)
+ kind = descriptor.kind if descriptor is not None else LADDER_PLATFORM_KIND_UNREGISTERED
+ return (kind, target.scope_type)
+
+
+def failure_notice_ack_source(target: ParsedSessionKey) -> str:
+ """The one evidence source that may acknowledge a notice sent to *target*."""
+
+ return LADDER_ACK_SOURCES.get(
+ failure_notice_target_class(target),
+ UNDECLARED_LADDER_ACK_SOURCE,
+ )
+
+
def session_anchor_for_target(target: ParsedSessionKey) -> str:
if target.thread_id:
return build_thread_session_anchor(target.platform, target.scope_id, target.thread_id)
@@ -252,6 +430,7 @@ class TaskExecutionResult:
error: Optional[str]
session_key: str
session_id: Optional[str]
+ failure_code: Optional[str] = None
@dataclass(frozen=True)
@@ -273,6 +452,12 @@ class AgentRunExecutionResult:
#: once per cron minute.
BINDING_RECOVERY_METADATA_KEY = "binding_recovery"
+#: Stable terminal code written only after the target resolver has proved that
+#: a pinned Session cannot accept a turn. Human-readable error text is allowed
+#: to evolve; the three-failure auto-pause policy must never parse it.
+FAILURE_CODE_UNRESOLVABLE_TARGET = "unresolvable_target"
+UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES = 3
+
#: Durable definition-metadata flag: this definition deliberately pins NO Agent
#: of its own and follows whatever Agent its bound Session carries.
#:
@@ -351,6 +536,7 @@ class SessionBindingChange:
"""What the scheduler did about a pinned session that no longer exists."""
# "rebound" -- a replacement session was reserved AND stored
+ # "failing" -- a user-pinned binding failed below the auto-pause threshold
# "paused" -- the definition was user-pinned, so it was disabled instead
# "reclaimed" -- a replacement was reserved but the guarded write refused it, so
# nothing was stored and the fire did not run (HFR-268), AND the
@@ -419,6 +605,42 @@ def resolve_session_id_target(session_id: str, *, db_path: Optional[Path] = None
raise UnresolvableSessionTarget(
f"agent session id not found: {raw}", session_id=raw, reason="missing"
)
+ # A RUNTIME-OWNED session accepts no turn from anybody, so it is not a target.
+ #
+ # THE ROUTE-LOCAL GUARD WAS NOT ENOUGH (review thread 3678900318). Refusing the
+ # send in ``POST /api/sessions/<id>/messages`` closed the composer, which is the
+ # door a human finds; it left every OTHER turn entry point open, because they all
+ # come through HERE instead. ``vibe agent run --session-id ses-workspace-notices``
+ # (``cmd_agent_run`` resolves the pin at ``vibe/cli.py``'s ``session_policy in
+ # {"existing", "fork"}`` branch), a task or watch pinned with ``--session-id``, and
+ # ``enqueue_session_callback`` all resolve first and enqueue a real turn second. So
+ # the ownership check belongs in the SHARED resolver: one line, and every present
+ # and future backend entry point inherits the no-turn contract instead of having to
+ # remember it. Same reasoning as ``archive_session`` / ``update_session`` owning the
+ # write refusals rather than each caller.
+ #
+ # BEFORE the archived check, deliberately, even though the two barely overlap. The
+ # reserved row may not be archived at all (``archive_session`` refuses its id) and
+ # ``resolve_workspace_notice_session`` heals a corrupted ``archived`` status on the
+ # next notice, so the ordering only decides which refusal a CORRUPTED row reports
+ # in that window — and "reserved for the runtime" is both the more specific fact
+ # and the one that stays true after the heal. Existence still wins over both: a
+ # missing row is ``missing``, whatever its id claimed to be.
+ #
+ # ``reason="reserved"`` IS A NEW VALUE, not a reuse of the two above, and it is
+ # deliberately left OUT of the ``delivery_target_missing`` classification in
+ # ``_execute_claimed_request`` (which keys on ``missing`` alone). This row exists
+ # and is healthy; nothing about the DESTINATION is dead. Pointing a definition at
+ # it is a CONFIGURATION error, and labelling it as a vanished delivery target would
+ # send the reader looking for a session that is sitting right there in their inbox.
+ # The run still settles ``failed`` naming the reserved session, which is the
+ # visible outcome that matters.
+ if session_is_runtime_owned(session_id=raw, visibility=row["visibility"]):
+ raise UnresolvableSessionTarget(
+ f"agent session is reserved for the runtime and accepts no turn: {raw}",
+ session_id=raw,
+ reason="reserved",
+ )
# Archived sessions are terminal + inert. A task/watch/run that still targets
# one by id must NOT fire into it — treat it as an unresolvable target so the
# run is skipped (archive also reclaims bound definitions, so this is defense
@@ -561,6 +783,22 @@ def build_session_key_for_context(
)
+def _created_by_caller(task: Any, run_metadata: Any) -> Optional[dict[str, Any]]:
+ """The ``created_by.caller`` provenance a definition was created with, or ``None``.
+
+ Read from the DEFINITION's metadata when the definition row still exists and from
+ the run's own copy otherwise, so a deleted definition keeps whatever the run
+ recorded. Shared by the failure ladder (rungs 3 and 4, which ADDRESS the origin) and
+ the notice body (which NAMES it): the two must never disagree about who created a
+ definition, and before this they read the same nested shape from two places.
+ """
+
+ source = (getattr(task, "metadata", None) if task is not None else run_metadata) or {}
+ created_by = source.get("created_by") if isinstance(source, dict) else None
+ caller = created_by.get("caller") if isinstance(created_by, dict) else None
+ return caller if isinstance(caller, dict) else None
+
+
@dataclass
class ScheduledTask:
id: str
@@ -896,6 +1134,24 @@ class ScheduledTaskStore:
def get_task(self, task_id: str) -> Optional[ScheduledTask]:
return self._tasks.get(task_id)
+ def get_watch_definition(self, definition_id: str) -> Optional[Dict[str, Any]]:
+ """The watch row for *definition_id*, or ``None`` when it is not a watch.
+
+ ``get_task`` mirrors ``scheduled_task`` rows only, so a WATCH looked up
+ through it reads as "no definition at all": no name, and no signal that
+ ``vibe task …`` is the wrong vocabulary for it. Watches and tasks are both
+ ``run_definitions`` rows and this store already holds the backend that reads
+ them, so a caller that must describe whichever definition a run belongs to
+ (the owed-failure-notice copy) can resolve either one without a second store.
+
+ ``None`` on the file backend, which has no definition table to read.
+ """
+
+ identifier = str(definition_id or "").strip()
+ if not identifier or self._sqlite is None:
+ return None
+ return self._sqlite.get_watch(identifier)
+
@staticmethod
def _read_state(task: ScheduledTask) -> DefinitionWriteExpectation:
"""The guarded state a full-row payload for ``task`` is derived from.
@@ -1110,12 +1366,20 @@ class ScheduledTaskStore:
raise DefinitionWriteConflict(task_id, definition_type="scheduled task")
return task
- def record_binding_recovery(self, task_id: str, payload: dict[str, Any]) -> bool:
+ def record_binding_recovery(
+ self,
+ task_id: str,
+ payload: dict[str, Any],
+ *,
+ binding_notice: Optional[dict[str, Any]] = None,
+ ) -> bool:
"""Durably stamp what was done about a broken session binding.
Written through the store (not by mutating a task the next
``maybe_reload`` may replace) because it is what makes the notification
- once-per-transition instead of once-per-fire.
+ once-per-transition instead of once-per-fire. When a successful rebind
+ needs its own notice, both rows commit in one SQLite transaction: a failed
+ notice write therefore cannot leave a marker that suppresses every retry.
"""
self.maybe_reload()
@@ -1130,6 +1394,20 @@ class ScheduledTaskStore:
# A runtime stamp, not a user action: a lost write is reported by the return
# value (the caller already treats ``False`` as "nothing recorded") rather than
# by an exception through the fire path.
+ if self._sqlite is not None and binding_notice is not None:
+ try:
+ landed = self._sqlite.upsert_scheduled_task_with_binding_notice(
+ task.to_dict(),
+ expect=expect,
+ notice=binding_notice,
+ )
+ except Exception:
+ self._reload_after_lost_write(task.id)
+ raise
+ if landed:
+ return True
+ self.load()
+ return False
return self._write_task(task, expect)
def list_orphaned_reservations(self, task_id: str) -> list[dict[str, Any]]:
@@ -1520,6 +1798,43 @@ class TaskExecutionStore:
return self._sqlite.list_runs(status=status)
return self._list_file_runs(status=status)
+ def consecutive_definition_failures_with_code(
+ self,
+ definition_id: str,
+ failure_code: str,
+ *,
+ limit: int,
+ ) -> int:
+ """Count the newest consecutive failed verdicts carrying one stable code."""
+
+ if limit <= 0:
+ return 0
+ if self._sqlite is not None:
+ return self._sqlite.consecutive_definition_failures_with_code(
+ definition_id,
+ failure_code,
+ limit=limit,
+ )
+ verdicts = [
+ run
+ for run in self._list_file_runs()
+ if str(run.get("definition_id") or run.get("task_id") or "") == str(definition_id)
+ and (_normalize_requested_run_status(run.get("status")) or run.get("status")) in {"succeeded", "failed"}
+ and not (
+ isinstance(run.get("metadata"), dict)
+ and run["metadata"].get("interrupt_reason") in RUN_INTERRUPTION_REASONS
+ )
+ ]
+ count = 0
+ for run in reversed(verdicts[-limit:]):
+ if (_normalize_requested_run_status(run.get("status")) or run.get("status")) != "failed":
+ break
+ metadata = run.get("metadata")
+ if not isinstance(metadata, dict) or metadata.get("failure_code") != failure_code:
+ break
+ count += 1
+ return count
+
def list_pending_callbacks(self, *, limit: int = 20) -> list[dict[str, Any]]:
if self._sqlite is not None:
return self._sqlite.list_pending_callbacks(limit=limit)
@@ -1995,18 +2310,49 @@ class TaskExecutionStore:
task_id: Optional[str] = None,
session_key: Optional[str] = None,
session_id: Optional[str] = None,
+ interrupt_reason: Optional[str] = None,
+ failure_code: Optional[str] = None,
) -> None:
+ """Settle one claimed request.
+
+ ``interrupt_reason`` is the caller's structured CLASS for a failure that has
+ one — today only ``delivery_target_missing`` (see ``_execute_claimed_request``).
+ It rides the SAME statement as the terminal transition, because that statement
+ is also the one that stamps the owed failure notice: ``_merge_owed_failure_notice``
+ applies ``extra_metadata`` to the run's ``metadata_json`` BEFORE
+ ``_owed_failure_notice_for_transition`` reads ``interrupt_reason`` out of it, so
+ the notice is born already carrying its class. A second UPDATE afterwards would
+ be too late — the notice never overwrites an existing one, by design, so a class
+ written after the stamp would be recorded on the run and missing from the very
+ blob the drain renders from.
+
+ Named keywords rather than a general ``metadata`` dict, deliberately: these
+ arguments are merged verbatim into a run's metadata, and a wide-open
+ passthrough at a completion site is how an unrelated key comes to overwrite
+ ``interrupt_reason``, ``failure_code`` or the notice blob itself.
+ """
+
+ extra_metadata: dict[str, Any] = {"ok": ok}
+ if interrupt_reason:
+ extra_metadata["interrupt_reason"] = interrupt_reason
+ if failure_code:
+ extra_metadata["failure_code"] = failure_code
if self._sqlite is not None:
- self._sqlite.update_run_status(
+ # Guarded, NOT ``update_run_status``: that writer's UPDATE has no status
+ # predicate, so an ordinary completion rewrote a status another actor had
+ # already settled — a real terminal ``succeeded`` result became ``failed``
+ # whenever the claimed-request layer finished with an error. The identity
+ # columns are still written either way (see ``settle_run_terminal``), so
+ # routing through the guard costs nothing a caller depended on.
+ self._sqlite.settle_run_terminal(
request.id,
- status="succeeded" if ok else "failed",
+ terminal_status="succeeded" if ok else "failed",
error=error,
- completed_at=_utc_now_iso(),
updated_at=_utc_now_iso(),
task_id=task_id if task_id is not None else request.task_id,
session_key=session_key if session_key is not None else request.session_key,
session_id=session_id if session_id is not None else request.session_id,
- metadata={"ok": ok},
+ metadata=extra_metadata,
)
return
processing_path = self._request_path(request.id, state="processing")
@@ -2023,6 +2369,17 @@ class TaskExecutionStore:
"callback_session_id": request.callback_session_id,
}
)
+ if interrupt_reason or failure_code:
+ # The file backend has no owed-notice machinery at all, so this records the
+ # class where its only reader — an operator looking at the completed JSON —
+ # can see it, rather than dropping the one fact the caller went to the
+ # trouble of classifying.
+ existing = payload.get("metadata")
+ payload["metadata"] = {
+ **(existing if isinstance(existing, dict) else {}),
+ **({"interrupt_reason": interrupt_reason} if interrupt_reason else {}),
+ **({"failure_code": failure_code} if failure_code else {}),
+ }
with tempfile.NamedTemporaryFile(
mode="w",
dir=self.completed_dir,
@@ -2080,6 +2437,10 @@ class ScheduledTaskService:
self.request_store = request_store or TaskExecutionStore()
self.scheduler = AsyncIOScheduler(timezone="UTC")
self._reconcile_task: Optional[asyncio.Task] = None
+ # The owed-notice drain pass currently in flight, if any. It runs OUTSIDE the
+ # store watch (see ``_spawn_failure_notice_drain``), which means it also has to
+ # be torn down by name: cancelling the watch no longer stops it.
+ self._notice_drain_task: Optional["asyncio.Task[Any]"] = None
self._job_signatures: Dict[str, tuple[Any, ...]] = {}
self._running = False
self._watch_store_restart_count = 0
@@ -2367,6 +2728,12 @@ class ScheduledTaskService:
current_task = self._current_asyncio_task()
if cancel_reconcile and self._reconcile_task and self._reconcile_task is not current_task:
self._reconcile_task.cancel()
+ # Cancelled by name, and not gated on ``cancel_reconcile``: the notice drain is
+ # no longer part of the watch coroutine, so stopping the watch leaves it running
+ # — a delivery on behalf of a service this process no longer owns, or one that
+ # outlives shutdown. The identity check is the only exemption it needs.
+ if self._notice_drain_task and self._notice_drain_task is not current_task:
+ self._notice_drain_task.cancel()
for task in list(self._inflight_executions.values()):
if task is not current_task:
task.cancel()
@@ -2393,6 +2760,17 @@ class ScheduledTaskService:
except asyncio.CancelledError:
pass
self._reconcile_task = None
+ # And the dispatched notice drain, awaited rather than merely cancelled: a
+ # delivery suspended in a transport send has to be given the chance to unwind
+ # before the process leaves, or shutdown races a coroutine that is still
+ # writing to the notice row it claimed.
+ if self._notice_drain_task:
+ self._notice_drain_task.cancel()
+ try:
+ await self._notice_drain_task
+ except (asyncio.CancelledError, Exception):
+ pass
+ self._notice_drain_task = None
# Cancel any in-flight executions so shutdown is clean. Cancellation is
# caught by ``_execute_claimed_request``, which requeues the run, so it
# is picked up again on the next start (and ``recover_processing`` on
@@ -2426,6 +2804,11 @@ class ScheduledTaskService:
except Exception:
self._drain_dirty = True
raise
+ # A failed run emits no store change anyone else notices, so — like
+ # the vault and sweep passes below — only a periodic pass finds it.
+ # Cheap: one indexed lookup that no-ops when nothing is owed.
+ # DISPATCHED, not awaited: see ``_spawn_failure_notice_drain``.
+ self._spawn_failure_notice_drain()
# Vault requests resolve via the web/API layer, which emits no run-store change,
# so sweep for owed auto-resume callbacks every tick — a cheap indexed lookup that
# no-ops when nothing is pending.
@@ -2825,6 +3208,1346 @@ class ScheduledTaskService:
self.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)
self._drain_dirty = True
+ # --- the owed-failure-notice drain ---------------------------------------
+ #
+ # Rides the existing 2 s tick beside ``_drain_callbacks``, for the same reason:
+ # a failed run emits no store change anyone else notices, so only a periodic
+ # pass finds it. The durable notice is stamped by whichever UPDATE terminalizes
+ # the row, so a crash between the failure and the delivery loses nothing — which
+ # is the whole point of persisting it rather than notifying inline.
+
+ def _spawn_failure_notice_drain(self) -> None:
+ """Start the owed-notice drain OUTSIDE the store watch, one pass at a time.
+
+ ``_watch_store`` is a single coroutine running every periodic pass in sequence,
+ so awaiting the drain there puts external message delivery on the critical path
+ of the whole service tick. One notice whose delivery does not return stops
+ request draining, callbacks, vault callbacks, the stale-run sweep — and every
+ LATER notice, including the ones reporting the failures that wedge is a symptom
+ of. Nothing looks broken, because the loop is suspended rather than crashed.
+
+ ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` alone would only shorten that stall to the
+ deadline, and a deadline short enough to hold the tick would cancel legitimate
+ deliveries. So the two halves are both required: dispatch takes delivery off the
+ watch, and the deadline bounds the dispatched work.
+
+ SINGLE-FLIGHT is the other half of dispatching. A task per tick would replace a
+ stalled loop with a delivery attempt every 2 s — the durable claim would make
+ most of them stand down, but the pile of coroutines is unbounded and each one
+ re-reads and re-claims. One pass at a time, and a tick that finds the previous
+ pass still running simply skips: the drain is idempotent across ticks by
+ construction, since eligibility is re-read from the row every pass.
+ """
+
+ task = self._notice_drain_task
+ if task is not None and not task.done():
+ return
+ self._notice_drain_task = asyncio.create_task(self._drain_failure_notices())
+ self._notice_drain_task.add_done_callback(self._on_notice_drain_done)
+
+ @staticmethod
+ def _on_notice_drain_done(task: "asyncio.Task[Any]") -> None:
+ """Retrieve the dispatched pass's exception so it is logged, never swallowed.
+
+ The inline await propagated failures into the watch's own handler. A fire-and-
+ forget task has no such reader, and an unretrieved exception surfaces only as an
+ asyncio "never retrieved" warning at garbage-collection time — which is how a
+ drain that has been failing every tick for a week goes unnoticed.
+ """
+
+ if task.cancelled():
+ return
+ exc = task.exception()
+ if exc is not None:
+ logger.error("owed failure notice drain pass failed: %r", exc, exc_info=exc)
+
+ async def _drain_failure_notices(self) -> None:
+ if not self._owns_service_instance():
+ return
+ store = self.request_store._sqlite
+ if store is None:
+ return
+ try:
+ owed = store.list_owed_failure_notices(limit=10)
+ except Exception:
+ logger.exception("failed to list owed failure notices")
+ return
+ # THE FAIRNESS BUDGET, checked between notices and never against one in flight.
+ #
+ # Deliveries inside a pass are serial on purpose (see
+ # ``NOTICE_DRAIN_PASS_BUDGET_SECONDS``), so a batch of wedged rows costs
+ # batch x deadline before the pass returns and every notice stamped in the
+ # meantime waits behind it. Truncating the pass bounds that wait by the budget
+ # plus one delivery instead of by the batch size.
+ #
+ # Between, not during: cancelling a delivery already on the wire would trade a
+ # slow pass for a duplicate, and the walk already has its own deadline. So the
+ # pass always finishes what it started and only stops PULLING more.
+ #
+ # Rows left behind cost nothing — unclaimed, so no attempt consumed and no
+ # backoff armed — and ``list_owed_failure_notices`` orders by
+ # ``next_attempt_at ASC``, so the next pass starts with the oldest of them.
+ started = time.monotonic()
+ budget = failure_notices.NOTICE_DRAIN_PASS_BUDGET_SECONDS
+ for index, run in enumerate(owed):
+ if index and time.monotonic() - started > budget:
+ logger.info(
+ "owed failure notice pass stopped at its %ss budget with %d of %d "
+ "notices unattempted; they keep their attempts and stay eligible",
+ budget,
+ len(owed) - index,
+ len(owed),
+ )
+ break
+ run_id = str(run.get("id") or "")
+ if not run_id:
+ continue
+ try:
+ await self._deliver_one_failure_notice(store, run)
+ except Exception:
+ logger.exception("owed failure notice drain failed for run=%s", run_id)
+
+ async def _deliver_one_failure_notice(self, store: Any, run: dict[str, Any]) -> None:
+ run_id = str(run["id"])
+ definition_id = str(run.get("task_id") or run.get("definition_id") or "") or None
+ notice = store.owed_failure_notice(run_id)
+ # Re-read and re-check ELIGIBILITY, not merely the state. The batch was listed
+ # before this pass began and each row is then delivered one at a time, so by
+ # the time a row is reached another owner may already have claimed it — and a
+ # claim is expressed as ``pending`` plus a lease on ``next_attempt_at``, so a
+ # state-only check would read it as free and send a duplicate. This is the same
+ # predicate the listing query used, deliberately: whatever the claim writes has
+ # to be visible to every later reader through one shared definition of
+ # eligibility.
+ now = datetime.now(timezone.utc)
+ if not owed_notice_eligible(notice, now.isoformat()):
+ return
+ # Every write below re-asserts the notice this pass DECIDED FROM. Ownership is
+ # checked once, at the top of the pass, and then the pass awaits delivery — so a
+ # service-lock handoff can leave this coroutine writing behind the new owner's
+ # completed delivery. The expectation makes the loser a no-op instead.
+ expect = notice_write_expectation(notice)
+
+ streak_facts: Optional[dict[str, Any]] = None
+ earlier_unsettled = None
+ # ``bypasses_suppression``, not ``is_interruption``: a binding-change notice is
+ # already scoped by the transition's signature, and reading the streak for one
+ # would be actively wrong — the anchor run SUCCEEDED, so
+ # ``failure_streak_decision`` would sweep in the definition's surrounding
+ # failures and defer the notice behind a canonical row it has nothing to do
+ # with.
+ if definition_id and not failure_notices.bypasses_suppression(notice):
+ earlier_unsettled = store.earliest_unsettled_run_before(
+ definition_id,
+ created_at=str(run.get("created_at") or ""),
+ run_id=run_id,
+ stale_after_seconds=failure_notices.DEFERRAL_STALE_AFTER_SECONDS,
+ )
+ if earlier_unsettled is None:
+ # The DECISION facts, not the streak's rows. One statement, so the
+ # boundaries and the notice states inside them come from one SQLite
+ # read snapshot: read separately, a success settling between the
+ # boundary seek and the row read merges two streaks, and a ``sent``
+ # notice from the earlier outage then skips a live one.
+ streak_facts = store.failure_streak_decision(definition_id, run_id)
+
+ # The callback's status is read FRESH, not taken from the listed row: the
+ # batch predates this decision by up to a whole pass, and ``_drain_callbacks``
+ # runs on the same ticks — a stale ``pending`` here would defer a notice whose
+ # callback already landed, and a stale absence would deliver beside it. A
+ # read failure propagates to the drain loop's per-row handler and the row is
+ # retried later, which errs toward one message rather than two.
+ decision = failure_notices.decide(
+ run_id=run_id,
+ definition_id=definition_id,
+ notice=notice,
+ streak_facts=streak_facts,
+ earlier_unsettled=earlier_unsettled,
+ callback_status=store.run_callback_state(run_id),
+ )
+ if decision.action == failure_notices.ACTION_DEFER:
+ # No attempt consumed — this row has not been tried. But the deferral is
+ # written down rather than merely skipped: a row left immediately-eligible
+ # is re-selected by every tick and keeps occupying the batch, so one
+ # definition with more than a batch worth of pending failures starved
+ # every other definition's notices indefinitely.
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ next_attempt_at=(
+ datetime.now(timezone.utc)
+ + timedelta(seconds=failure_notices.DEFERRAL_RECHECK_SECONDS)
+ ).isoformat(),
+ defer_reason=decision.reason,
+ )
+ logger.debug("failure notice for %s deferred (%s)", run_id, decision.reason)
+ return
+ if decision.action == failure_notices.ACTION_SKIP:
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_SKIPPED,
+ skip_reason=decision.reason,
+ )
+ return
+
+ attempt, retry_after = failure_notices.next_attempt(notice)
+
+ # THE CLAIM, and it must precede the external side effect.
+ #
+ # This one guarded UPDATE does two things at once: it CONSUMES the attempt (so
+ # the number is durable before anything can go wrong with the send — the bound
+ # the raising-rung handler below exists to keep) and it arms a LEASE on
+ # ``next_attempt_at`` marking the row as somebody's until that instant.
+ #
+ # Why here and not after the send. Ownership is checked once per pass and then
+ # the pass AWAITS delivery, so two owners can both hold a listed row: they both
+ # read ``pending``, both walk the ladder, both send, and only then does either
+ # write. A predicate on the write catches the second WRITE and nothing else —
+ # the user already has two messages, and no database can recall one. Nothing
+ # downstream closes it either: ``emit_agent_message`` checks
+ # ``agent_message_exists`` BEFORE the send and persists AFTER it, so both owners
+ # pass that lookup while neither receipt exists. Single-flight has to be
+ # established before the irreversible act, which means before this line.
+ #
+ # The primitive is the CAS that is already here. SQLite evaluates ``expect`` in
+ # the writing statement under its single-writer lock, so a guarded transition
+ # from ``(pending, N)`` is atomic across connections and processes — exactly an
+ # atomic claim, just used earlier. An owner that read before this write loses
+ # the CAS; one that reads after it sees the lease and stands down at the
+ # eligibility check at the top of this method.
+ #
+ # And because the lease is an INSTANT rather than a held lock, a claimant that
+ # dies mid-send releases it by expiry: ``CLAIM_LEASE_SECONDS`` is the recovery
+ # bound, and the recovered pass consumes its own attempt rather than inheriting
+ # the dead one, so the retry ladder stays finite. The residual is at-least-once
+ # delivery, documented on that constant.
+ claimed = store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ attempts=attempt,
+ # Armed at CLAIM time, not from the instant the eligibility check read:
+ # the streak reads above sit between the two, and the lease has to bound
+ # the delivery that is about to start rather than one that already has.
+ next_attempt_at=(
+ datetime.now(timezone.utc)
+ + timedelta(seconds=failure_notices.CLAIM_LEASE_SECONDS)
+ ).isoformat(),
+ )
+ if claimed is None:
+ # Another owner moved this row between our read and our claim. Nothing to
+ # repair and nothing to report: the winner is delivering it, and this pass
+ # must not send. Silent for the same reason the losing write is — a lock
+ # handoff is normal, and an error here would be logged on every one.
+ logger.debug("failure notice for %s already claimed by another owner", run_id)
+ return
+ # Every write below re-asserts what the CLAIM left behind, not what was read
+ # before it.
+ expect = notice_write_expectation(claimed)
+
+ evidence = DeliveryEvidence()
+ # THE DEADLINE, over the whole ladder walk rather than one rung.
+ #
+ # The claim above makes a competing owner stand down for the lease, and lease
+ # expiry recovers a claimant that DIES. Neither covers one that never returns:
+ # a transport that accepted the request and hung leaves this coroutine
+ # suspended with the row ineligible and nothing reporting it, so the notice is
+ # owed indefinitely. See ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` for the two-sided
+ # argument for the value; what matters here is the scope and the disposal.
+ #
+ # Scope is the WALK, not the rung: a per-rung bound would let five slow rungs
+ # add up past the lease, and the thing being bounded is how long this claim can
+ # be held.
+ #
+ # Disposal: ``wait_for`` cancels the inner task and AWAITS that cancellation
+ # before raising, so the transport coroutine is dead — not detached to send
+ # behind a replacement claimant's back — by the time the handler below writes
+ # anything. ``asyncio.wait_for`` rather than ``asyncio.timeout`` because the
+ # package supports 3.10, where the latter does not exist.
+ # The ATTEMPT IS NOT THREADED INTO THE WALK, and it used to be. An earlier
+ # revision passed it down because the workspace rung's presence depended on the
+ # attempt number; that design is retired (see ``_failure_notice_targets``' WHEN
+ # block) and the ladder is now the same on every attempt, so the walk needs
+ # nothing from the counter. ``attempt`` still governs everything BELOW — the
+ # backoff instant, ``MAX_ATTEMPTS``, and the dead letter — because those are
+ # properties of the row, not of the address.
+ emit = asyncio.ensure_future(self._emit_failure_notice(run, notice, evidence))
+ try:
+ delivered = await asyncio.wait_for(
+ emit, timeout=failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS
+ )
+ except asyncio.TimeoutError as exc:
+ # WHOSE timeout, asked rather than assumed: from 3.11 ``asyncio.TimeoutError``
+ # is the builtin ``TimeoutError``, so an adapter's own HTTP timeout arrives
+ # here indistinguishable from the deadline. ``emit.cancelled()`` is the
+ # discriminator — only the deadline cancels the walk — and without it the
+ # notice would be stamped with a confident lie about which one happened.
+ delivered = False
+ if emit.cancelled():
+ logger.error(
+ "failure notice delivery timed out for run=%s after %ss; transport cancelled",
+ run_id,
+ failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS,
+ )
+ # The timeout CONSUMES the attempt the claim already made durable: the
+ # retry write below arms the ordinary backoff under the claim's own
+ # expectation, which cannot lose while this claimant's lease holds. A
+ # release (rewinding ``attempts``) would let a permanently hanging
+ # transport retry without bound and never dead-letter.
+ stamped: BaseException = TimeoutError(
+ "failure notice delivery timed out after "
+ f"{failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS}s; transport cancelled"
+ )
+ else:
+ # A rung's OWN timeout, reported as itself: it is an ordinary raising
+ # rung that happens to have picked this exception type.
+ logger.exception("failure notice delivery raised for run=%s", run_id)
+ stamped = exc
+ if evidence.error is None:
+ evidence.error = stamped
+ evidence.error_stage = "deliver"
+ except Exception as exc:
+ # A raising rung CONSUMES an attempt. Previously the exception escaped
+ # between computing the attempt number and persisting it, so the next
+ # 2 s tick recomputed the same number and raised again — an unbounded
+ # retry loop, which is exactly what the backoff exists to prevent. The
+ # bound has to hold for any rung, not just the one that was observed
+ # raising, so this catches rather than enumerating call sites.
+ logger.exception("failure notice delivery raised for run=%s", run_id)
+ delivered = False
+ if evidence.error is None:
+ evidence.error = exc
+ evidence.error_stage = "deliver"
+
+ if delivered and evidence.delivered:
+ # Acknowledged on a durable receipt or on a returned delivery id — never
+ # on a function return. ``emit_replayed_backend_failure`` discards the
+ # notify result and returns normally either way, so a returns-cleanly ack
+ # would flip a lost notice to ``sent`` permanently.
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_SENT,
+ # Re-asserting the attempt the CLAIM already consumed, deliberately
+ # rather than omitting it: this write is the one a reader reconstructs
+ # the delivery from, and it should say which attempt succeeded instead
+ # of leaving that to be inferred from an earlier row version.
+ attempts=attempt,
+ ack_evidence=evidence.ack_evidence,
+ # A post-delivery error (the SSE fan-out raised) is recorded for
+ # diagnosis and must NOT trigger a resend.
+ error=evidence.error_text,
+ )
+ self._drain_dirty = True
+ return
+
+ error_text = evidence.error_text or "failure notice delivery produced no evidence"
+ if retry_after is None:
+ # Dead letter, carrying the raised exception's own message rather than a
+ # generic string. Visible rather than silently retrying forever.
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_FAILED,
+ attempts=attempt,
+ error=error_text,
+ )
+ logger.error("failure notice for run %s dead-lettered: %s", run_id, error_text)
+ return
+ next_attempt_at = (
+ datetime.now(timezone.utc) + timedelta(seconds=retry_after)
+ ).isoformat()
+ store.update_owed_failure_notice(
+ run_id,
+ expect=expect,
+ state=NOTICE_PENDING,
+ attempts=attempt,
+ next_attempt_at=next_attempt_at,
+ error=error_text,
+ )
+
+ async def _emit_failure_notice(
+ self,
+ run: dict[str, Any],
+ notice: dict[str, Any],
+ evidence: "DeliveryEvidence",
+ ) -> bool:
+ """Walk D5's delivery ladder for one failed run. True once one rung emitted.
+
+ Evidence is per RUNG, then adopted into the caller's object. One shared
+ ``DeliveryEvidence`` cannot express a ladder: ``delivered`` latches true the
+ moment any rung records an id, so a rung whose ack is REJECTED (see
+ ``_rung_acknowledges``) would both stop the walk and hand the eventual
+ ack/dead-letter another rung's ``ack_evidence``. The caller ends up with the
+ winning rung's evidence, or — when no rung was accepted — the last one's, so
+ the dead letter reports what actually went wrong on the final attempt.
+
+ A rung that RAISES is an unusable rung, not the end of the walk. Every other
+ way a rung can fail to deliver already continues — ``_build_context`` raising,
+ a stale synthetic candidate, an un-acked send — so a delivery that throws
+ (a platform whose settings manager is gone, an adapter that fails before its
+ transport) has to continue too, or the notice spends every attempt on rung (1)
+ and dead-letters without rungs (2)…(5) ever being tried. ``Exception`` and not
+ ``BaseException``: the walk-level deadline cancels this coroutine, and
+ cancellation must unwind the walk rather than advance it past the bound it was
+ cancelled to respect.
+
+ The cost is real and is recorded rather than hidden. A rung that raises AFTER
+ its transport accepted the send, leaving no evidence behind, now delivers again
+ on the next rung. The adapters no longer manufacture that state — post-send
+ bookkeeping is guarded in every one of them, so an already-delivered id is not
+ destroyed on its way out — and what remains is the same at-least-once residual
+ documented on ``CLAIM_LEASE_SECONDS``, narrowed on the retry by the duplicate
+ short-circuit's persisted receipt.
+
+ THE WORKSPACE RUNG IS RESOLVED HERE, NOT WHERE THE LADDER IS BUILT, and that
+ split is the whole reason this method knows the reserved id at all.
+ ``_failure_notice_targets`` appends the reserved id as a CONSTANT — no database
+ access, no row minted — and the resolve-or-create-or-heal happens below, once
+ the walk has actually reached that rung. Two consequences, both wanted:
+
+ * an installation whose rung (1) always delivers never grows the reserved row,
+ even though every ladder it builds ends with the reserved id. The rung is
+ appended to every ladder unconditionally (the round-14 gate), so a
+ build-time resolve would create the row on the FIRST failure of every
+ install, which is the one surviving argument from the design this replaced;
+ * ``_failure_notice_targets`` stays a pure address computation. It is called
+ directly by tests and by ad-hoc inspection, and under a build-time resolve
+ each of those calls would be a write.
+
+ The cost is that the rung can turn out to be UNUSABLE mid-walk, when the
+ workbench database cannot be read or written. That is not a new state — every
+ other rung can be unusable too (``_build_context`` raising, a stale candidate,
+ a send that throws) — and it takes the same disposal: the rung is skipped, the
+ walk continues, and with nothing left to try the notice keeps its ``pending``
+ state and its backoff. It dead-letters visibly only if the database never
+ answers.
+ """
+
+ body = self._failure_notice_body(run, notice)
+ failure_id = str(notice.get("failure_id") or f"failure:{run['id']}")
+ last_rung: Optional[DeliveryEvidence] = None
+ first_raise: Optional[DeliveryEvidence] = None
+ try:
+ for target, session_id in self._failure_notice_targets(run):
+ if session_id == WORKSPACE_NOTICE_SESSION_ID:
+ # THE LAZY HALF of the reserved rung: resolve-or-create-or-heal now
+ # that the walk has reached it. ``resolve_workspace_notice_session``
+ # always answers with this same reserved id, so nothing about the
+ # target changes — the call is made for its WRITE (create the row,
+ # or repair one that was archived or hidden), not for its return.
+ if self._workspace_notice_session_id() is None:
+ # An unusable rung, disposed of like any other. Recorded only
+ # when no earlier rung left evidence: a preferred rung's own
+ # refusal ("returned send id … without a persisted receipt") is
+ # the more useful diagnosis, and this must not displace it.
+ logger.warning(
+ "failure notice rung unusable: the workspace-notifications "
+ "session could not be resolved for run=%s",
+ run["id"],
+ )
+ if last_rung is None:
+ unusable = DeliveryEvidence()
+ unusable.error = RuntimeError(
+ f"{target.to_key()} rung unusable: the "
+ "workspace-notifications session could not be resolved"
+ )
+ unusable.error_stage = "deliver"
+ last_rung = unusable
+ continue
+ try:
+ context = await self._build_context(
+ target,
+ delivery_target=target,
+ execution_id=str(run["id"]),
+ task_id=str(run.get("task_id") or "") or None,
+ trigger_kind=str(run.get("run_type") or "scheduled"),
+ session_id=session_id,
+ )
+ except Exception:
+ logger.debug("failure notice rung unusable: %s", target, exc_info=True)
+ continue
+ rung = DeliveryEvidence()
+ last_rung = rung
+ # The REPLAY emitter, not the live failure path. A notice is owed only for
+ # a run that is already settled, so this delivers one visible ``notify``
+ # and nothing else: no terminal result, no turn settlement, no auth
+ # prompt, and an identity taken from the durable row rather than from
+ # whatever ``task_execution_id`` this rebuilt context happens to supply.
+ # See ``emit_replayed_backend_failure`` for why each of those is a
+ # property of the emitter instead of an argument to the live one.
+ try:
+ await emit_replayed_backend_failure(
+ self.controller,
+ context,
+ str(run.get("agent_backend") or "harness"),
+ str(run.get("error") or "").strip() or body,
+ display_text=body,
+ failure_id=failure_id,
+ delivery=rung,
+ )
+ except Exception as exc:
+ # This rung is unusable; the ladder is not. See the docstring for
+ # why ``Exception`` and not ``BaseException``.
+ logger.warning(
+ "failure notice rung raised, continuing the walk: %s",
+ target.to_key(),
+ exc_info=True,
+ )
+ if rung.error is None:
+ rung.error = exc
+ rung.error_stage = "deliver"
+ if first_raise is None:
+ first_raise = rung
+ continue
+ if self._rung_acknowledges(target, rung):
+ return True
+ finally:
+ if last_rung is not None:
+ _adopt_delivery_evidence(evidence, last_rung)
+ if evidence.error is None and first_raise is not None:
+ # The winning rung carries no error of its own, so the skipped rung's
+ # does not compete with anything: it is recorded on the acknowledged
+ # row purely for diagnosis, the same way a post-delivery stream error
+ # is, and — like that one — must never be read as a delivery failure.
+ evidence.error = first_raise.error
+ evidence.error_stage = first_raise.error_stage
+ return False
+
+ @staticmethod
+ def _rung_acknowledges(target: ParsedSessionKey, rung: "DeliveryEvidence") -> bool:
+ """Whether THIS rung's evidence satisfies its target class's ack source.
+
+ One table lookup and one membership test, deliberately: the question "who may
+ ack on what" is answered once, declaratively, by ``LADDER_ACK_SOURCES`` — see
+ that table for why each class gets the source it does. A predicate that
+ special-cased platforms here is exactly how three review rounds each found a
+ different target class acking on evidence that proved nothing.
+
+ A rejected rung is not a silent one. When the send DID return an id and only
+ the durable receipt is missing, that is recorded on the rung so the eventual
+ retry or dead letter can say why, instead of reporting "produced no
+ evidence" about a send that in fact returned.
+ """
+
+ source = failure_notice_ack_source(target)
+ if rung.ack_evidence in ACK_EVIDENCE_BY_ACK_SOURCE[source]:
+ return True
+ if (
+ source == ACK_SOURCE_PERSISTED_RECEIPT
+ and rung.error is None
+ and rung.delivered_id is not None
+ ):
+ rung.error = RuntimeError(
+ f"{target.to_key()} rung returned send id {rung.delivered_id} "
+ "without a persisted receipt"
+ )
+ rung.error_stage = STAGE_PERSIST
+ return False
+
+ def _failure_notice_targets(
+ self,
+ run: dict[str, Any],
+ ) -> list[tuple[ParsedSessionKey, Optional[str]]]:
+ """D5's ladder, in order, skipping rungs this run cannot address.
+
+ (1) the definition's delivery key; (2) the bound session's scope while the
+ session is still alive; (3) the scope the definition was created from;
+ (4) a DM to the owner; (5) the workbench inbox.
+
+ Rung (5) carries the definitions no person is addressable for. For one
+ created by a plain ``vibe task add`` at a terminal there is no caller
+ provenance at all, so rungs (3) and (4) are both empty; an unscoped
+ ``create_per_run`` definition can also have no delivery key, and once its
+ per-run session is gone rung (2) goes with it.
+
+ What rung (5) does and does not guarantee, stated honestly because the
+ earlier "always resolves" claim was wrong. The distinction it turns on is
+ between a REAL PERSISTED project scope and a STALE SYNTHETIC project
+ candidate, and the key alone does not tell them apart: rung (5) is spelled
+ ``avibe::project::<session id>``, a candidate this method MANUFACTURES for
+ every run carrying a session id. It becomes a real scope only downstream,
+ where ``persist_agent_message`` looks the session's ``agent_sessions`` row up
+ and takes that row's ``scope_id``.
+
+ AN ARCHIVED OR BACKGROUND ROW IS NOT A DELIVERY SURFACE, and rung (5) is
+ rerouted when the run names one — see ``_rung_five_session_id``. The previous
+ revision claimed
+ the opposite ("the real difference between this rung and rung (2)": that
+ ``_session_row`` has no status filter while ``resolve_session_id_target``
+ refuses an archived session outright). The mechanism is real; the conclusion
+ was wrong, and it is the round-13 P1 on this method (review thread
+ 3676292667). ``persist_agent_message`` does write the row, which is the
+ workbench class's ack source, so the notice is stamped ``sent`` — while
+ ``list_inbox_sessions`` excludes archived and background sessions, so there
+ is no card, no
+ ``inbox.session.updated`` and no push, and the acked notice is never retried.
+ Same class as the round-12 reserved-session hole, opposite remedy: the
+ reserved row is HEALED because nobody may archive it, whereas an ordinary
+ session was archived by its owner ON PURPOSE. Resurrecting it would overrule
+ the user, so the fix is ROUTING.
+
+ With a hard-deleted row the candidate resolves to nothing and
+ ``persist_agent_message`` returns before writing — yet ``AvibeBot.send_message``
+ still hands back a synthetic ``msg_…`` id, so the rung LOOKS delivered. That is
+ why the workbench target class may only acknowledge on a persisted receipt (see
+ ``LADDER_ACK_SOURCES``): a stale candidate leaves the notice retryable instead
+ of marking it ``sent`` against a row that was never written. Pinned by
+ ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``.
+
+ AND EVERY LADDER ENDS WITH THE RESERVED WORKSPACE RUNG (plan :3193, :3215-3222;
+ round-14 gate, review comment 5121007240). One distinct
+ WORKSPACE-NOTIFICATIONS rung is appended after every person/context target, on
+ every attempt, whatever the four rungs above produced — see the WHEN block at
+ the end of this method for why that is unconditional and what it costs. It
+ resolves without a person to address because it is addressed to the workspace
+ instead.
+
+ This method takes NO attempt number and performs NO database access. The
+ reserved rung is appended as a CONSTANT (``WORKSPACE_NOTICE_SESSION_ID``); the
+ resolve-or-create-or-heal happens in ``_emit_failure_notice``, when the walk
+ actually reaches that rung. So the ladder is a pure address computation that is
+ safe to call from a test or an ad-hoc probe, and an installation whose rung (1)
+ always delivers never grows the reserved row even though every ladder it builds
+ names it.
+
+ The rung is therefore appended UNCONDITIONALLY but is not guaranteed USABLE, and
+ that distinction is stated here rather than left to be discovered because an
+ earlier revision's unqualified "always resolves" is the exact claim the plan's
+ own correction had to retract. ``_workspace_notice_session_id`` returns ``None``
+ when the workbench database cannot be read or written; the walk then skips the
+ rung. The consequence is a RETRY, not a loss: the notice keeps its ``pending``
+ state, arms its backoff, and delivers on a later pass once the database answers
+ — and only dead-letters if it never does. That is the same shape as any other
+ unusable rung, which is why it needs no special handling in the drain.
+ """
+
+ rungs: list[tuple[ParsedSessionKey, Optional[str]]] = []
+ seen: set[tuple[str, Optional[str]]] = set()
+
+ def _add(raw_key: Any, session_id: Optional[str]) -> None:
+ key = str(raw_key or "").strip()
+ if not key:
+ return
+ try:
+ parsed = parse_session_key(key)
+ except Exception:
+ # ``parse_session_key`` rejects every scope type outside
+ # ``{channel, user}``, and EVERY avibe rung is
+ # ``avibe::project::…`` — rung (2) for any workbench-bound session
+ # (``resolve_session_id_target`` hands back a ``project`` scope for
+ # one), rung (3) for a workbench-created definition, and rung (5)
+ # always. Swallowing that ``ValueError`` silently discarded all of
+ # them, so an Avibe-only definition had an entirely empty ladder.
+ #
+ # Only a bare three-part key falls back. A five-part
+ # ``::thread::`` key is a session key by construction and
+ # ``parse_scope_id`` cannot express one, so it stays on the strict
+ # parser rather than being downgraded to its scope prefix (which
+ # would silently retarget a thread notice at its parent channel).
+ if len(key.split("::")) != 3:
+ return
+ try:
+ parsed = parse_scope_id(key)
+ except Exception:
+ return
+ identity = (parsed.to_key(), session_id)
+ if identity in seen:
+ return
+ seen.add(identity)
+ rungs.append((parsed, session_id))
+
+ metadata = run.get("metadata") if isinstance(run.get("metadata"), dict) else {}
+ task = self.store.get_task(str(run.get("task_id") or "")) if run.get("task_id") else None
+
+ # (1) the definition's delivery key.
+ _add((task.deliver_key if task else None) or run.get("deliver_key"), None)
+
+ # (2) the bound session's scope, only while the session resolves to a visible
+ # delivery surface. Background sessions deliberately suppress delivery, so
+ # persisting and acknowledging a notice there would hide it permanently.
+ session_id = str((task.session_id if task else None) or run.get("session_id") or "").strip()
+ if session_id:
+ try:
+ resolved = resolve_session_id_target(session_id)
+ except Exception:
+ resolved = None
+ if resolved is not None and not resolved.suppress_delivery:
+ _add(resolved.session_key.to_key(), session_id)
+
+ # (3) caller provenance, written at definition creation.
+ caller = _created_by_caller(task, metadata)
+ if caller is not None:
+ _add(caller.get("session_key") or caller.get("scope_id"), None)
+
+ # (4) a DM to the owner, from the same provenance.
+ if caller is not None:
+ platform = str(caller.get("platform") or "").strip()
+ user_id = str(caller.get("user_id") or "").strip()
+ if platform and user_id:
+ _add(f"{platform}::user::{user_id}", None)
+
+ # (5) the workbench inbox, addressed through the run's own session — the rung
+ # that survives rung (2)'s refusal, because ``persist_agent_message`` resolves
+ # the avibe scope from ``_session_row`` (no status filter) where
+ # ``resolve_session_id_target`` demands a live, usable session.
+ #
+ # The key below is a CANDIDATE, not a resolved scope: the session id sits in
+ # the ``project`` slot and, for a MISSING row, nothing here checks that the row
+ # it names still exists. Whether it is real is settled downstream, by whether a
+ # durable ``messages`` row appears — which is exactly what the workbench class's
+ # receipt-only ack source measures, so a candidate for a deleted session
+ # cannot pass itself off as a delivery.
+ #
+ # An archived or background row is the case that measurement CANNOT catch,
+ # so it is caught here instead: see ``_rung_five_session_id``.
+ #
+ # So this rung covers every definition that has ever had a session — every
+ # ``create_once`` / ``create_per_run`` / session-bound definition — addressing
+ # the run's own session while that row is a surface a user can see, and the
+ # workspace inbox when it is not.
+ if session_id:
+ rung_five_session_id = self._rung_five_session_id(session_id)
+ _add(f"avibe::project::{rung_five_session_id}", rung_five_session_id)
+
+ # …AND THE LAST RUNG, for the definitions the four above cannot address at all
+ # (plan :3193, :3215-3222; PR6's own step list, :1256-1259).
+ #
+ # THE EARLIER POSITION HERE WAS WRONG, and the plan says so with a date. It read
+ # that ``persist_agent_message`` returns before writing when an avibe context
+ # resolves neither a scope nor a session row, therefore a session-less
+ # definition has nowhere to put the row, therefore the notice dead-letters
+ # VISIBLY and that is a declared Known-By-Design limitation under #1044. The
+ # first two clauses are still true; the conclusion was not. "Visible in
+ # ``last_error`` and the health badge" is visible to somebody who goes LOOKING,
+ # and D1's whole subject is the runs nobody is watching. A notice with nowhere
+ # to go is a notice that is never written.
+ #
+ # What was actually missing was a HOME, not a widened writer: the blocker is a
+ # session row, so the fix supplies one. ``_workspace_notice_session_id``
+ # resolves-or-creates a single reserved workspace-notifications session, and
+ # rung (5) then addresses it exactly like any other avibe session — the same
+ # ``avibe::project::<session id>`` candidate, satisfied by the same
+ # ``_session_row`` lookup, acked by the same receipt-only policy. Nothing
+ # downstream learns a new row shape.
+ #
+ # WHAT THAT ACTUALLY GETS THE USER, enumerated rather than waved at, because the
+ # previous revision's "the same inbox / unread / realtime / Web Push machinery"
+ # claimed three surfaces the row does not reach:
+ #
+ # * an INBOX CARD (``list_inbox_sessions`` accepts a terminal ``notify``) and the
+ # ``inbox.session.updated`` realtime event that patches an open browser — the
+ # two surfaces the plan's "readable inbox row" is about;
+ # * a LOCAL Web Push, via ``maybe_notify_inbox_message``.
+ #
+ # Residuals, all three properties of pre-existing policy rather than of this rung:
+ # the notice does NOT bump the unread badge (``notify`` carries no ``unread`` in
+ # ``vibe/message_types.json`` and the unread counts are ``result``-only, on purpose
+ # — a failure report is not an unread reply); it is NOT reachable by message
+ # search, which is also ``result``-scoped; and on a REMOTE-ACCESS install push can
+ # find no owner to address, because owner resolution falls back to the local user
+ # only while remote access is off (``core/web_push_notifications.py``). The inbox
+ # card and the realtime event are unaffected by all three.
+ #
+ # WHEN. UNCONDITIONALLY, ONCE, LAST. One distinct workspace-notifications rung
+ # after every person/context target, on every attempt, whether or not the four
+ # rungs above produced anything and whether or not what they produced is stale,
+ # unavailable, or failing delivery. This is the round-14 gate ruling (review
+ # comment 5121007240) and it is a settled decision, not a preference to be
+ # re-litigated by a later revision.
+ #
+ # TWO RETIRED DESIGNS, named so neither comes back:
+ #
+ # (i) round 12's "ONLY WHEN NOTHING ELSE RESOLVED" — the fallback fired only for
+ # an empty ladder. Too narrow by exactly the case #1060 reported (maintainer
+ # note 5120451508): a NON-EMPTY ladder is not a DELIVERABLE one. Rung (5)
+ # above is manufactured from the run's session id and nothing checks that the
+ # row it names still exists, and rungs (3)/(4) can point at the same dead
+ # session. A watch bound to a HARD-DELETED session therefore builds a ladder
+ # that can never persist a receipt: every attempt sends to a candidate that
+ # resolves to nothing, the receipt-only ack source correctly refuses it, the
+ # ``if not rungs`` gate never fires, all six attempts burn, and the notice
+ # dead-letters into ``NOTICE_FAILED`` with nothing written anywhere. That
+ # silent dead letter is the 3.5 hours of silence in #1060's field evidence,
+ # and "visible in ``last_error``" was refuted above for exactly this reason.
+ #
+ # (ii) round 13's FINAL-ATTEMPT fallback (commit ``ce695b42``) — appended last,
+ # but only on attempt ``MAX_ATTEMPTS``. It closed (i)'s hole and was
+ # overruled anyway. Its argument was that a workspace rung present from
+ # attempt 1 converts a TRANSIENT preferred-rung failure into a permanently
+ # workspace-routed notice, since the walk acks the FIRST rung that succeeds.
+ # That reading of the mechanism is correct; the gate weighed the trade and
+ # decided the other way, in terms that leave no conditional room:
+ # "Workspace fallback is mandatory rung 5. Append one distinct
+ # workspace-notifications target after every person/context target, even
+ # when earlier candidates exist but are stale, unavailable, or fail
+ # delivery. It cannot be conditional on rungs being empty."
+ #
+ # THE TRADE, RECORDED RATHER THAN LEFT SILENT, because it is a real behaviour
+ # change and the next reader deserves to find it stated: any walk in which every
+ # preferred rung fails to deliver now reaches this rung on THAT walk, delivers,
+ # and ACKS. So a preferred rung that failed TRANSIENTLY — a platform blip on
+ # attempt 1 — permanently routes that one notice to the workspace inbox; the
+ # notice is never retried to the preferred target, and the user's own channel
+ # does not receive a copy it would have received a minute later. Accepted
+ # explicitly by the maintainer in the ruling above ("…or fail delivery"), on the
+ # judgement that a misrouted notice a user can find beats a notice nobody
+ # receives. Scope of the residual: ONE notice, not the definition — the next
+ # failure builds a fresh ladder and the recovered preferred rung wins it again.
+ #
+ # WHAT KEEPS IT FROM BEING NOISY is the ORDER, which is the one property of
+ # round 12's argument that survives intact. The rung is appended STRICTLY LAST,
+ # after every preferred rung, and the walk returns on the first rung that
+ # acknowledges — so a HEALTHY preferred rung wins every walk and never produces a
+ # workspace card at all. Duplicate cards for a delivered notice's silent per-rung
+ # failures are therefore not reachable; only a walk where NOTHING preferred
+ # delivered gets here. Pinned by
+ # ``test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox``.
+ #
+ # AND ONCE. The reserved id is appended as a CONSTANT, so it collides by identity
+ # with rung (5)'s archived-session reroute (which returns the same constant) and
+ # the ``_add`` seen-set collapses the two into a single rung. An archived-session
+ # ladder holds exactly ONE workspace rung, not two — pinned by
+ # ``test_an_archived_session_ladder_holds_exactly_one_workspace_rung``.
+ #
+ # NO DATABASE ACCESS HERE. Appending the constant costs nothing; the
+ # resolve-or-create-or-heal is done by ``_emit_failure_notice`` when the walk
+ # reaches this rung. That is what keeps the reserved row from being minted on the
+ # first failure of an installation whose rung (1) always delivers — the only part
+ # of round 12's "would create the reserved row for installations that never need
+ # it" that is still load-bearing once the ordering argument above is granted.
+ #
+ # RESIDUAL: ``_workspace_notice_session_id`` returns ``None`` when the workbench
+ # database cannot be read or written, and the walk then SKIPS this rung on every
+ # attempt — so the notice dead-letters exactly as it did before, visibly, with the
+ # last rung's own refusal in ``error``. That path must stay reachable: a fallback
+ # that swallowed the dead letter when it could not itself deliver would replace
+ # one silence with a worse one.
+ _add(f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}", WORKSPACE_NOTICE_SESSION_ID)
+ return rungs
+
+ def _rung_five_session_id(self, session_id: str) -> str:
+ """Which session rung (5) may address: the run's own, or the workspace inbox.
+
+ THE INVISIBLE-SESSION REROUTE. An archived or background
+ ``agent_sessions`` row is WRITABLE but is not a VISIBLE delivery surface,
+ and the notice machinery reads those two as one thing:
+ ``persist_agent_message`` resolves the avibe scope through ``_session_row``,
+ which has no status filter, so the message persists; a persisted receipt is the
+ workbench class's ack source (``LADDER_ACK_SOURCES``), so the rung ACKS and the
+ notice is stamped ``sent`` and never retried; but ``list_inbox_sessions`` and
+ ``get_inbox_session`` exclude archived sessions, so there is no inbox card, no
+ ``inbox.session.updated`` patch for an open browser, and no Web Push. The user is
+ told nothing and the system believes it told them — the exact silence D1 exists
+ to close, and worse than a dead letter, which at least says so.
+
+ The receipt-only ack source CANNOT catch this one. It is the right measurement
+ for a MISSING row (nothing persists, so nothing acks — see
+ ``_failure_notice_targets``' rung-(5) comment and
+ ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``), and it is blind
+ here precisely because the write really does happen. So the check has to be a
+ read, and it has to be here, where the address is chosen.
+
+ WHY REROUTING RATHER THAN HEALING, which is what round 12 did for the same class
+ of hole (``2ceaa865``, the reserved workspace session). That row may never be
+ archived at all — ``archive_session`` refuses its id — so an archived one is
+ corruption and repairing it in place restores the invariant. An ORDINARY session
+ was archived by its owner deliberately. Un-archiving it to deliver a failure
+ notice would overrule a user decision to make a bookkeeping row visible, and it
+ would resurface the whole session, not the notice. The session is not broken; the
+ ADDRESS is. So the notice moves.
+
+ Three outcomes, and only the middle one changes anything:
+
+ * row ABSENT (hard-deleted, or the DB cannot be read): the caller's own
+ candidate, unchanged. Nothing persists, so nothing acks, and the appended
+ workspace rung plus the ``delivery_target_missing`` classification carry the
+ case on the SAME walk. The candidate is
+ also kept for what it documents: rung (5) is a candidate by construction, and
+ removing it here would hide the shape of the ladder from the ack policy that
+ depends on it.
+ * row ARCHIVED OR HIDDEN: the reserved workspace-notifications session, so the
+ notice lands somewhere ``list_inbox_sessions`` will show it. Returned as the
+ bare CONSTANT — this method does not resolve or create the reserved row, so
+ the reroute is a pure address change and the id it returns is identical to the
+ one ``_failure_notice_targets`` appends last, which is what lets the
+ ``_add`` seen-set collapse the two into ONE rung. Whether that row can
+ actually be written is settled later, by the walk. If it cannot, the rung is
+ skipped and the notice stays retryable rather than acking invisibly into the
+ archived row — which is what keeping the caller's candidate here used to do.
+ * an active row whose visibility is explicitly admitted by the inbox: the
+ caller's candidate. The visibility whitelist is shared with inbox queries,
+ so a future value stays hidden until both surfaces opt it in.
+
+ ONE READ, and the TOCTOU is real and bounded: a session archived or hidden
+ between this SELECT and ``persist_agent_message``'s write still acks there.
+ The residual is ONE notice, not a class — the next notice re-reads and reroutes —
+ and closing it would need the status check inside the persisting transaction,
+ which is a writer-side change of a different shape. Not worth trading a
+ per-notice window for a widened writer.
+ """
+
+ try:
+ with get_cached_sqlite_engine().begin() as conn:
+ row = conn.execute(
+ select(agent_sessions.c.status, agent_sessions.c.visibility).where(
+ agent_sessions.c.id == session_id
+ )
+ ).first()
+ except Exception:
+ logger.warning(
+ "failure notice: cannot read session %s status/visibility for rung (5)",
+ session_id,
+ exc_info=True,
+ )
+ return session_id
+ if row is None:
+ return session_id
+ status, visibility = row
+ if str(status) != "archived" and str(visibility) in INBOX_SESSION_VISIBILITIES:
+ return session_id
+ logger.info(
+ "failure notice: session %s is archived or hidden, rerouting rung (5) to the "
+ "workspace-notifications inbox",
+ session_id,
+ )
+ return WORKSPACE_NOTICE_SESSION_ID
+
+ def _workspace_notice_session_id(self) -> Optional[str]:
+ """The reserved workspace-notifications session id, created on first need.
+
+ Lazy on purpose: an installation whose definitions all have a delivery key or a
+ session never grows the row. See
+ ``storage.agent_session_rows.resolve_workspace_notice_session`` for why the
+ identity is a reserved primary key and why the row carries no Scope.
+
+ THREE MECHANISMS KEEP THE ROW USABLE, and they cover three different ways of
+ losing it — the first one alone was not enough:
+
+ * RECREATION covers REMOVAL. Nothing asks the ``/new`` clear path or session
+ eviction for an exemption; if the row is deleted the next notice makes it again.
+ * HEALING covers ARCHIVE and a flipped ``visibility``, which recreation cannot
+ see: the reserved primary key is still there, so nothing recreates, while the
+ row has stopped being a delivery surface. That state fails SILENTLY — the
+ notice still persists through ``_session_row`` (no status filter), still acks
+ on the receipt, and ``list_inbox_sessions`` shows nothing — so
+ ``resolve_workspace_notice_session`` repairs the row in place instead.
+ * THE ``archive_session`` AND ``update_session`` GUARDS cover the UI paths.
+ The row is ``visibility='system'`` — absent from ordinary session lists,
+ admitted by the inbox surfaces — so the remaining door to it is its own
+ inbox card, and ``storage.workbench_sessions_service`` refuses the id on
+ both archive and modify (403). The heal is still needed for a database
+ archived or re-flagged out of band, or before the guards existed.
+
+ Called from the WALK (``_emit_failure_notice``), not from the ladder build. The
+ ladder appends the reserved id as a constant, so this — the only part of the rung
+ that writes — runs exactly when the walk has actually reached it. An install
+ whose preferred rung always delivers therefore never grows the row.
+
+ Returns ``None`` rather than raising: this runs mid-walk for a failure that is
+ already recorded, and an unwritable workbench DB must leave the notice retryable
+ — the pre-existing behaviour — instead of turning one unusable rung into an
+ exception the drain has to classify.
+ """
+
+ try:
+ from storage.agent_session_rows import resolve_workspace_notice_session
+ from storage.db import get_cached_sqlite_engine
+
+ with get_cached_sqlite_engine().begin() as conn:
+ return resolve_workspace_notice_session(
+ conn,
+ # Named once, at CREATE time, by whoever's notice needed it first.
+ title=self._t("harness.notice.workspaceSession"),
+ )
+ except Exception:
+ logger.warning(
+ "failure notice: workspace-notifications session unavailable", exc_info=True
+ )
+ return None
+
+ def _origin_lines(self, caller: Optional[dict[str, Any]]) -> list[str]:
+ """The creation-origin line, plus a deep link when one can be built honestly.
+
+ Zero, one or two lines — never a placeholder. Three separate refusals, each of
+ which independently yields FEWER lines rather than vaguer ones:
+
+ * **No provenance at all.** Every definition created before the origin capture
+ landed, and every definition created from the CLI with no conversation behind
+ it. There is nothing to say, so nothing is said.
+ * **An unmapped platform.** The label is rendered inside a translated sentence,
+ so the wire value goes through ``NOTICE_ORIGIN_PLATFORM_I18N_KEYS`` — a closed
+ map — and never gets interpolated. Same call as
+ ``notice_failure_class_i18n_key``'s: ``None`` means no line, because "Created
+ in: mystery_platform" leaks an identifier into product copy for no benefit.
+ * **No followable link.** ``origin_link`` returns ``None`` for a Feishu/Lark or
+ WeChat origin, for a Workbench origin (a localhost URL is not reachable from
+ the IM notice this may be delivered to), and for any platform whose permalink
+ grammar needs an id that was not captured. The origin TEXT still renders; only
+ the second line is dropped.
+
+ The channel and thread are rendered from the CAPTURED ids — a raw ``C0123`` is
+ the identifier the user's own client shows in a URL, and inventing a display
+ name that was never captured would be a different kind of dishonesty from
+ inventing a link, but the same kind of mistake. The scope is read back out of
+ the same ``session_key`` that rung (3) is addressed to, so the notice cannot
+ name one conversation while the ladder targets another.
+ """
+
+ if not caller:
+ return []
+ platform = str(caller.get("platform") or "").strip()
+ platform_key = failure_notices.notice_origin_platform_i18n_key(platform)
+ if not platform_key:
+ return []
+ platform_label = self._t(platform_key)
+
+ parsed: Optional[ParsedSessionKey] = None
+ raw_key = str(caller.get("session_key") or caller.get("scope_id") or "").strip()
+ if raw_key:
+ for parser in (parse_session_key, parse_scope_id):
+ try:
+ parsed = parser(raw_key)
+ break
+ except Exception:
+ parsed = None
+ scope_type = parsed.scope_type if parsed is not None else ""
+ scope_id = parsed.scope_id if parsed is not None else ""
+ thread_id = parsed.thread_id if parsed is not None else None
+
+ if scope_type == "channel" and scope_id:
+ if thread_id:
+ origin = self._t(
+ "harness.notice.originChannelThread",
+ platform=platform_label,
+ channel=scope_id,
+ thread=thread_id,
+ )
+ else:
+ origin = self._t(
+ "harness.notice.originChannel",
+ platform=platform_label,
+ channel=scope_id,
+ )
+ elif scope_type == "user" and scope_id:
+ origin = self._t(
+ "harness.notice.originDirect",
+ platform=platform_label,
+ user=scope_id,
+ )
+ else:
+ # A known platform with no usable scope — a Workbench (``project``) origin,
+ # or a caller recorded before the session key could be resolved. The
+ # platform alone is still true and still narrows the search.
+ origin = platform_label
+
+ lines = [self._t("harness.notice.origin", origin=origin)]
+ link = origin_link(
+ platform,
+ caller.get("channel_id"),
+ thread_id,
+ caller.get("message_id"),
+ caller.get("workspace_id"),
+ )
+ if link:
+ lines.append(self._t("harness.notice.originLink", url=link))
+ return lines
+
+ def _failure_notice_body(self, run: dict[str, Any], notice: dict[str, Any]) -> str:
+ """Actionable copy: what failed, why, its state, and how to re-run.
+
+ A DM is context-free by construction and rung (5) is not attached to any
+ conversation, so the body has to carry its own context rather than relying on
+ where it happened to land.
+
+ Two classifications decide the copy, and BOTH are asked here by the same
+ predicate the rest of the system uses:
+
+ * the LANE — ``failure_notices.is_interruption``, i.e. membership in
+ ``RUN_INTERRUPTION_REASONS``. Asking by the mere presence of
+ ``interrupt_reason`` told a user "nothing is wrong with the definition
+ itself" for ``no_terminal_result`` / ``refused_concurrent_turn`` /
+ ``transport_unavailable`` / ``queue_hold_expired`` — the recurring per-fire
+ verdicts where the definition is exactly what IS wrong.
+ * the DEFINITION KIND. A watch is not a task: ``vibe task run`` /
+ ``vibe task show`` do not accept a watch id, and ``vibe watch run`` does not
+ exist at all, so a failed watch was handed commands it could not use and an
+ id in place of its name (``get_task`` mirrors scheduled tasks only).
+ """
+
+ definition_id = str(run.get("task_id") or "") or None
+ task = self.store.get_task(definition_id) if definition_id else None
+ # Only for a run whose definition is not a task: the run's own ``run_type``
+ # says so for a watch hook send (``watch``) and for the supervisor heartbeat
+ # (``watch_runtime``), and the definition row is the fallback for a row
+ # rebuilt without one.
+ watch = (
+ self.store.get_watch_definition(definition_id)
+ if task is None and definition_id
+ else None
+ )
+ is_watch = watch is not None or str(run.get("run_type") or "").strip().startswith("watch")
+ name = (
+ (task.name if task else None)
+ or (str((watch or {}).get("name") or "").strip() or None)
+ or definition_id
+ or str(run["id"])
+ )
+ run_id = str(run.get("id") or "").strip()
+ if failure_notices.is_binding_change(notice):
+ return self._binding_notice_body(
+ notice,
+ name=name,
+ definition_id=definition_id,
+ definition_exists=task is not None,
+ run_id=run_id,
+ )
+ reason = str(notice.get("interrupt_reason") or "").strip()
+ error = str(run.get("error") or "").strip() or self._t("harness.notice.unknownError")
+ if failure_notices.is_interruption(notice):
+ # The reason is rendered INSIDE a translated sentence, so it is copy: the
+ # wire value went through a closed label map, never interpolated raw. An
+ # unmapped reason takes the map's localized generic rather than leaking the
+ # identifier — see ``NOTICE_REASON_UNKNOWN_I18N_KEY``.
+ headline = self._t(
+ "harness.notice.interrupted",
+ name=name,
+ reason=self._t(failure_notices.notice_reason_i18n_key(reason)),
+ )
+ else:
+ headline = self._t("harness.notice.failed", name=name)
+ lines = [headline, self._t("harness.notice.error", error=error)]
+ if not failure_notices.is_interruption(notice):
+ # D5 asks for "the error and its CLASS", and on this lane the class was
+ # dropped: the interrupted headline was the only place any reason was
+ # rendered, while the per-fire verdicts — ``no_terminal_result``,
+ # ``refused_concurrent_turn``, ``transport_unavailable``,
+ # ``queue_hold_expired`` — stay in the FAILED lane by design and carry a
+ # reason all the same. Its own closed vocabulary, and ``None`` (no line)
+ # when there is no class to name: see ``notice_failure_class_i18n_key``.
+ class_key = failure_notices.notice_failure_class_i18n_key(reason)
+ if class_key:
+ lines.append(
+ self._t("harness.notice.failureClass", failureClass=self._t(class_key))
+ )
+ last_success = self._last_success_instant(definition_id)
+ if last_success:
+ # "When it last succeeded" — D5's own list. Omitted rather than rendered as
+ # "never" for a definition that has never succeeded: the notice already says
+ # this fire failed, and a line about the absence of history is noise.
+ lines.append(self._t("harness.notice.lastSucceeded", when=last_success))
+ # WHERE IT CAME FROM — the last item on D5's list, and the one a DM or a
+ # workspace card needs most, because neither is attached to the conversation
+ # that asked for the definition. Omitted whole when nothing was captured, which
+ # is EVERY definition created before this round: there is no backfill and no
+ # migration, because the ids were never recorded and inventing them is the one
+ # thing a provenance line may not do.
+ lines.extend(
+ self._origin_lines(
+ _created_by_caller(task, run.get("metadata") if isinstance(run.get("metadata"), dict) else {})
+ )
+ )
+ if definition_id:
+ lines.append(self._t("harness.notice.definition", id=definition_id))
+ if task is None and watch is None:
+ # The definition row is GONE while the run keeps its ``definition_id``
+ # forever, so EVERY definition-level command is a dead end — checked
+ # before the task/watch split because both halves of that split print
+ # one. ``vibe task run <deleted id>`` parses and then reports "not
+ # found", which is the same class of defect HFR-094 closed for
+ # watches: copy naming an action the user cannot take.
+ lines.extend(self._deleted_definition_lines(run_id))
+ elif is_watch:
+ if watch is not None and not watch.get("enabled", True):
+ # RETIRED IS NOT PAUSED, and the row already says which. A watch
+ # that ran out its ``once`` cycle carries ``retired_at``; a user who
+ # pressed pause leaves it null. Both land on ``enabled = 0``, which
+ # is exactly the ambiguity #1060 reported ("``enabled=0`` is carrying
+ # three meanings") — and printing the resume copy for a retired
+ # watch contradicts the lifecycle projection this same round makes
+ # authoritative: the definition reads FINISHED while its notice
+ # offers ``vibe watch resume``, an action that would arm a watch the
+ # user never paused.
+ #
+ # The distinction is read from the same column the projection's
+ # ``ended`` predicate uses, so the copy and the badge cannot
+ # disagree. A legacy row with no marker keeps the resume copy: its
+ # history genuinely cannot prove which of the two happened, and
+ # ``definition_lifecycle_expression`` makes the same call.
+ if str(watch.get("retired_at") or "").strip():
+ lines.append(self._t("harness.notice.watchRetired"))
+ else:
+ lines.append(self._t("harness.notice.watchPaused", id=definition_id))
+ # No re-run affordance, because there is no ``vibe watch run``: a watch
+ # fires when the thing it waits on happens. ``show`` is the action a
+ # user actually has.
+ lines.append(self._t("harness.notice.watchShow", id=definition_id))
+ else:
+ if task is not None and not task.enabled:
+ # FINISHED IS NOT PAUSED, the task-side twin of the watch branch
+ # above. A failed one-shot is disabled by ``mark_task_result``
+ # (``disable_one_shot``), so ``enabled = 0`` here carries two
+ # meanings — and the paused copy offers ``vibe task resume`` for
+ # a definition the canonical lifecycle projection reads as
+ # FINISHED, an action that re-arms nothing. The distinction is
+ # read from the projection ITSELF (``definition_lifecycle_state``
+ # evaluates the badge's own CASE for this row) rather than
+ # re-derived in Python, so the copy and the badge cannot
+ # disagree — not even in the window where a naive ``run_at`` in
+ # a non-UTC task timezone reads differently to
+ # ``compute_next_run_at`` and to SQLite's UTC clock. The
+ # explicit re-run affordance below stays either way: unlike a
+ # watch, ``vibe task run`` is real and is the honest next step.
+ lifecycle = self._task_lifecycle_state(definition_id, task)
+ if lifecycle == "finished":
+ lines.append(self._t("harness.notice.taskFinished"))
+ elif lifecycle == "paused":
+ lines.append(self._t("harness.notice.paused", id=definition_id))
+ # ``running`` (``vibe task run`` accepts a disabled one-shot, and
+ # an in-flight execution outranks the ended predicate) and
+ # ``waiting`` (a switch the mirror has not caught up with): no
+ # lifecycle line at all. Either copy would contradict the badge,
+ # and the re-run/show affordance below stands on its own.
+ elif task is not None:
+ next_run = compute_next_run_at(
+ enabled=task.enabled,
+ schedule_type=task.schedule_type,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ )
+ if next_run:
+ lines.append(self._t("harness.notice.nextRun", when=next_run))
+ lines.append(self._t("harness.notice.rerun", id=definition_id))
+ return "\n".join(lines)
+
+ def _task_lifecycle_state(self, definition_id: Optional[str], task: Any) -> str:
+ """The lifecycle state the badge shows for this task — asked of the badge.
+
+ The authoritative answer is ``definition_lifecycle_state``, the same SQL CASE
+ every list and count surface evaluates, so the notice copy and the badge share
+ one clock and one parse of ``run_at`` — and one priority order: an in-flight
+ execution outranks the ended predicate, so the caller sees ``running`` rather
+ than a boolean that flattened it into "not finished". The Python inference
+ below it is a FALLBACK for the file backend and for a row the read cannot
+ reach: there is no SQL badge in those worlds to disagree with, and the
+ inference asks the same question the projection encodes
+ (``compute_next_run_at`` returns ``None`` exactly when the named instant is
+ behind us, with ``enabled=True`` so the switch cannot mask the clock).
+ """
+
+ if definition_id:
+ store = getattr(self.request_store, "_sqlite", None)
+ if store is not None:
+ try:
+ state = store.definition_lifecycle_state(
+ definition_id, definition_type="task"
+ )
+ except Exception:
+ logger.debug(
+ "failure notice: lifecycle-state read failed", exc_info=True
+ )
+ state = None
+ if state is not None:
+ return state
+ if task.schedule_type == "at" and not compute_next_run_at(
+ enabled=True,
+ schedule_type=task.schedule_type,
+ cron=task.cron,
+ run_at=task.run_at,
+ timezone_name=task.timezone,
+ ):
+ return "finished"
+ return "paused"
+
+ def _last_success_instant(self, definition_id: Optional[str]) -> Optional[str]:
+ """When this definition last succeeded, for the body's own context.
+
+ Read through the request store's SQLite handle, which is where run history lives
+ (the task mirror holds definitions, not runs). ``None`` on the file backend, on a
+ run with no definition, and on any read error: this is one context line on a
+ notice that must still be delivered, so an unanswerable question drops the line
+ rather than the notice.
+ """
+
+ if not definition_id:
+ return None
+ store = getattr(self.request_store, "_sqlite", None)
+ if store is None:
+ return None
+ try:
+ return store.last_success_settled_at(definition_id)
+ except Exception:
+ logger.debug("failure notice: last-success read failed", exc_info=True)
+ return None
+
+ def _deleted_definition_lines(self, run_id: str) -> list[str]:
+ """The only recovery copy a definition that no longer exists can honestly print.
+
+ One place, because both bodies need it and both had the same hole. The run row
+ outlives its definition, so the RUN is what is left to inspect — and
+ ``vibe runs show`` is a real subcommand with an optional positional run id,
+ vetted against the real parser by
+ ``test_a_deleted_definition_notice_names_only_run_level_recovery``.
+
+ No run id (a body rendered from a row rebuilt without one) prints the
+ explanation alone rather than ``vibe runs show`` with nothing after it: an
+ incomplete command is the WI-2 failure mode again, one argument smaller.
+ """
+
+ lines = [self._t("harness.notice.definitionDeleted")]
+ if run_id:
+ lines.append(self._t("harness.notice.runInspect", id=run_id))
+ return lines
+
+ def _binding_notice_body(
+ self,
+ notice: dict[str, Any],
+ *,
+ name: str,
+ definition_id: Optional[str],
+ definition_exists: bool,
+ run_id: str,
+ ) -> str:
+ """Copy for "your pinned session was replaced", which is not a failure report.
+
+ Two things the failure body must not do here. It opens with "failed" and
+ always prints an ``Error:`` line — for a run that SUCCEEDED that reads as a
+ false alarm, and with ``error=None`` the line degrades to "no error text was
+ recorded", which is noise about nothing. And its call to action is ``vibe task
+ run``, whereas the action a user actually wants after an unrequested rebind is
+ to pin the session back or look at what the definition is bound to now.
+
+ Every command named below is a real subcommand (``vibe task update
+ --session-id``, ``vibe task show``); the WI-2 lesson is that invented copy
+ fails nothing but the user. ``definition_exists`` is the second half of that
+ lesson: a rebind notice can outlive its definition by the whole retry/backoff
+ window, and a command that names a row which no longer exists is invented copy
+ by a slower route — it parses, and then reports "not found".
+ """
+
+ binding = notice.get("binding") if isinstance(notice.get("binding"), dict) else {}
+ previous = str(binding.get("previous_session_id") or "").strip()
+ new = str(binding.get("new_session_id") or "").strip()
+ lines = [self._t("harness.notice.rebound", name=name)]
+ if previous and new:
+ lines.append(self._t("harness.notice.reboundSessions", previous=previous, new=new))
+ if binding.get("settings_preserved"):
+ lines.append(self._t("harness.notice.reboundSettingsPreserved"))
+ else:
+ lines.append(self._t("harness.notice.reboundSettingsReset"))
+ if definition_id:
+ lines.append(self._t("harness.notice.definition", id=definition_id))
+ if definition_exists:
+ lines.append(self._t("harness.notice.reboundRepin", id=definition_id))
+ lines.append(self._t("harness.notice.show", id=definition_id))
+ else:
+ # Nothing left to re-pin OR to show. The rebind itself still happened
+ # and the lines above still report it — the news is not suppressed,
+ # only the actions that no longer address anything.
+ lines.extend(self._deleted_definition_lines(run_id))
+ return "\n".join(lines)
+
def settle_activity_runs(self, activity: Any) -> list[str]:
"""Settle deferred Runs when a failed/stopped owned Activity is last."""
@@ -3129,6 +4852,11 @@ class ScheduledTaskService:
async def _execute_claimed_request(self, request: TaskExecutionRequest) -> None:
error: Optional[str] = None
+ #: The structured CLASS of this run's failure, when the failure has one. Kept
+ #: beside ``error`` rather than parsed back out of it: the text is a sentence
+ #: for a human, this is the value the notice's lane and label are chosen from.
+ interrupt_reason: Optional[str] = None
+ failure_code: Optional[str] = None
should_complete = True
settled_out_of_band = False
recover_queue_on_return = False
@@ -3153,6 +4881,7 @@ class ScheduledTaskService:
error = result.error
session_key = result.session_key
session_id = result.session_id
+ failure_code = result.failure_code
elif request.request_type in {"hook_send", "watch", "webhook"}:
if not request.prompt:
raise ValueError("hook request requires prompt")
@@ -3223,6 +4952,54 @@ class ScheduledTaskService:
self.request_store.requeue(request.id)
should_complete = False
raise
+ except UnresolvableSessionTarget as exc:
+ # THE RUN'S DELIVERY TARGET IS GONE, and that is a CLASS of failure rather
+ # than one more error string. #1060's field evidence is the case: a watch
+ # pinned to a session that ceased to exist failed three deliveries and
+ # stopped, and the only recorded cause anywhere was ``last_exit_code = 75``
+ # — the user's own ``--retry-exit-code``, i.e. the waiter's healthy
+ # "nothing new yet" signal. The error TEXT was already right here (it names
+ # the missing session id); what was missing was a structured class, so the
+ # notice could say the failure is about the DESTINATION and a reader could
+ # tell it apart from the work itself breaking.
+ #
+ # Placed at the top level, not nested around the hook branch, so a run type
+ # added later inherits the classification instead of having to remember it.
+ # It cannot over-reach: ``UnresolvableSessionTarget`` is a distinct type
+ # raised only by ``resolve_session_id_target``, never by a transient fault.
+ #
+ # Which branches actually arrive here. ``watch`` / ``hook_send`` / ``webhook``
+ # and ``agent_run`` do — none of them resolves the target before dispatch, so
+ # this is their first and only handler. ``task_run`` does NOT: ``_execute_task``
+ # catches the same type first, runs the binding recovery
+ # (``_recover_pinned_session_binding``), and absorbs a failed rebind retry in
+ # its own ``except``. That asymmetry is deliberate and predates this handler —
+ # a task has a definition to rebind or pause, and its recovery already stamps
+ # a ``binding_change`` notice of its own.
+ #
+ # ONLY ``reason == "missing"`` IS CLASSIFIED. ``archived`` is left
+ # unclassified on purpose: an archived session's row still exists, and the
+ # honest description of that failure is "the session is inert", not "it no
+ # longer exists". Its NOTICE is still deliverable — rung (5) reroutes an
+ # archived session to the workspace inbox rather than writing into a row
+ # ``list_inbox_sessions`` hides (see ``_rung_five_session_id``) — so the
+ # reader is not left with an unnamed failure they cannot see. A wrong class
+ # is worse than no class — the label is the one line in the notice a reader
+ # trusts about the shape of the failure — and
+ # ``notice_failure_class_i18n_key`` already renders NO line rather than a
+ # generic one when there is nothing to name. Same for ``unusable``.
+ error = str(exc)
+ failure_code = FAILURE_CODE_UNRESOLVABLE_TARGET
+ if exc.reason == "missing":
+ interrupt_reason = INTERRUPT_REASON_DELIVERY_TARGET_MISSING
+ logger.error(
+ "Task execution request %s cannot reach its delivery target: %s",
+ request.id,
+ exc,
+ exc_info=True,
+ )
+ should_complete = True
+ settled_out_of_band = False
except Exception as exc:
error = str(exc)
logger.error("Task execution request %s failed: %s", request.id, exc, exc_info=True)
@@ -3245,6 +5022,13 @@ class ScheduledTaskService:
task_id=task_id,
session_key=session_key,
session_id=session_id,
+ # ``None`` for every ordinary completion, so the settlement
+ # writer's metadata merge is a no-op exactly as before. Only
+ # ``complete`` carries it: ``complete_coalesced`` settles
+ # ``agent_run`` fan-outs, which reserve their own session per
+ # run and so cannot reach the branch above.
+ interrupt_reason=interrupt_reason,
+ failure_code=failure_code,
)
if should_complete or settled_out_of_band:
# An out-of-band settlement still made this run terminal, so it owes
@@ -3282,6 +5066,7 @@ class ScheduledTaskService:
disable_one_shot: bool,
) -> TaskExecutionResult:
error: Optional[str] = None
+ failure_code: Optional[str] = None
session_id = task.session_id
session_key = task.session_key
binding_change: Optional[SessionBindingChange] = None
@@ -3323,7 +5108,12 @@ class ScheduledTaskService:
logger.error("Scheduled task %s has an unresolvable session binding: %s", task.id, exc)
binding_change = self._recover_pinned_session_binding(task, exc)
error = binding_change.detail
+ failure_code = FAILURE_CODE_UNRESOLVABLE_TARGET
if binding_change.action == "rebound" and binding_change.new_session_id:
+ # The binding failure was repaired. Any error from the retried turn
+ # is a new backend/dispatch outcome, not another member of the
+ # unresolvable-target auto-pause streak.
+ failure_code = None
session_id = binding_change.new_session_id
session_key = ""
try:
@@ -3374,9 +5164,23 @@ class ScheduledTaskService:
if not error:
error = _TASK_RESULT_NOT_RECORDED_ERROR
if binding_change is not None:
- await self._emit_binding_change(binding_change)
+ # ``execution_id`` IS the run row's id on every path that reaches here
+ # (``_execute_claimed_request`` passes ``request.id``), and this runs
+ # BEFORE ``complete()`` settles the row — so a notice stamped now rides
+ # into the terminal write instead of racing it. ``run_error`` decides
+ # whether the binding news may take the notice slot at all: a rebind whose
+ # retry failed already owes an ordinary failure notice, and that one must
+ # not be displaced.
+ await self._emit_binding_change(
+ binding_change, run_id=execution_id, run_error=error
+ )
self.reconcile_jobs()
- return TaskExecutionResult(error=error, session_key=session_key, session_id=session_id)
+ return TaskExecutionResult(
+ error=error,
+ session_key=session_key,
+ session_id=session_id,
+ failure_code=failure_code if error else None,
+ )
async def _execute_agent_run(
self,
@@ -3819,17 +5623,37 @@ class ScheduledTaskService:
settings_preserved=settings_preserved,
)
+ prior_failures = self.request_store.consecutive_definition_failures_with_code(
+ task.id,
+ FAILURE_CODE_UNRESOLVABLE_TARGET,
+ limit=UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES - 1,
+ )
+ failure_number = prior_failures + 1
+ if failure_number < UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES:
+ return SessionBindingChange(
+ action="failing",
+ task_id=task.id,
+ reason=exc.reason,
+ previous_session_id=previous,
+ detail=self._t(
+ "harness.run.bindingUnresolvedRetry",
+ session=previous or "",
+ attempt=failure_number,
+ threshold=UNRESOLVABLE_TARGET_AUTO_PAUSE_FAILURES,
+ id=task.id,
+ ),
+ )
+
self._pause_task(task)
return SessionBindingChange(
action="paused",
task_id=task.id,
reason=exc.reason,
previous_session_id=previous,
- detail=(
- f"paused: {exc}. The bound agent session no longer exists, so this "
- "definition would fail on every run. Re-point it with "
- f"`vibe task update {task.id} --session-id <id>` and resume it with "
- f"`vibe task resume {task.id}`."
+ detail=self._t(
+ "harness.run.bindingUnresolvedPaused",
+ session=previous or "",
+ id=task.id,
),
)
@@ -3963,7 +5787,13 @@ class ScheduledTaskService:
# from this stale mirror would only restore what the teardown cleared.
logger.debug("Task %s was already reclaimed before it could be paused", task.id)
- async def _emit_binding_change(self, change: SessionBindingChange) -> None:
+ async def _emit_binding_change(
+ self,
+ change: SessionBindingChange,
+ *,
+ run_id: Optional[str] = None,
+ run_error: Optional[str] = None,
+ ) -> None:
"""Notify once per binding transition, never once per fire.
A daily cron on a dead session would otherwise notify every day. The
@@ -3986,28 +5816,58 @@ class ScheduledTaskService:
recorded = task.metadata.get(BINDING_RECOVERY_METADATA_KEY) if isinstance(task.metadata, dict) else None
if isinstance(recorded, dict) and recorded.get("signature") == change.signature:
return
- if not self.store.record_binding_recovery(
- change.task_id,
- {
+ recovery_payload = {
+ "signature": change.signature,
+ "action": change.action,
+ "reason": change.reason,
+ "previous_session_id": change.previous_session_id,
+ "new_session_id": change.new_session_id,
+ "settings_preserved": change.settings_preserved,
+ "at": _utc_now_iso(),
+ # Only on the HFR-276 branch, so the recorded shape of every other
+ # transition is unchanged.
+ **(
+ {
+ "orphaned_session_id": change.orphaned_session_id,
+ "orphan_tracked": change.orphan_tracked,
+ }
+ if change.orphaned_session_id
+ else {}
+ ),
+ }
+ binding_notice = None
+ if (
+ run_id
+ and change.action == "rebound"
+ and change.new_session_id
+ and not run_error
+ and self.store._sqlite is not None
+ ):
+ binding_notice = {
+ "run_id": run_id,
+ "task_id": change.task_id,
"signature": change.signature,
"action": change.action,
"reason": change.reason,
"previous_session_id": change.previous_session_id,
"new_session_id": change.new_session_id,
"settings_preserved": change.settings_preserved,
- "at": _utc_now_iso(),
- # Only on the HFR-276 branch, so the recorded shape of every other
- # transition is unchanged.
- **(
- {
- "orphaned_session_id": change.orphaned_session_id,
- "orphan_tracked": change.orphan_tracked,
- }
- if change.orphaned_session_id
- else {}
- ),
- },
- ):
+ }
+ try:
+ recorded_recovery = self.store.record_binding_recovery(
+ change.task_id,
+ recovery_payload,
+ binding_notice=binding_notice,
+ )
+ except Exception:
+ logger.exception(
+ "Not notifying the binding %s for task %s: its recovery marker and "
+ "notice could not be committed together",
+ change.action,
+ change.task_id,
+ )
+ return
+ if not recorded_recovery:
logger.warning(
"Not notifying the binding %s for task %s: the recovery record was "
"refused, so the definition was reclaimed, repointed or removed and "
@@ -4021,11 +5881,22 @@ class ScheduledTaskService:
async def _notify_binding_change(self, task: ScheduledTask, change: SessionBindingChange) -> None:
"""Single delivery seam for a binding change.
- Deliberately the only place that decides how the user hears about this. The
- durable half is already written (``last_error`` plus
- ``metadata.binding_recovery``), which the CLI and the Harness detail pane
- read today; the delivery ladder for definitions whose session is gone is
- built on top of this seam and is not this change's job.
+ Deliberately the only place that decides how the user hears about this.
+
+ The durable half was already written by the time we get here (``last_error``
+ plus ``metadata.binding_recovery``), and the run row's owed notice — which the
+ drain delivers through D5's ladder — carries the user-visible half. For
+ ``paused`` / ``reclaimed`` / ``orphaned`` that notice comes from the terminal
+ transition, because those fires end failed. For ``rebound`` the retry succeeds
+ and no transition owes anything, so ``record_binding_recovery`` commits the
+ marker and notice together before this log seam is reached.
+
+ Either way this seam does not deliver anything itself: doing so would produce
+ a SECOND message for one event, and it would be the un-retried one, since only
+ the owed notice has a receipt/backoff/dead-letter protocol behind it.
+
+ What it does own is the log line, which is the operator's view of a
+ transition that is per-BINDING rather than per-fire.
"""
logger.warning(
diff --git a/core/services/agent_graph.py b/core/services/agent_graph.py
index 61fcfc88d..cc5f0af49 100644
--- a/core/services/agent_graph.py
+++ b/core/services/agent_graph.py
@@ -674,6 +674,18 @@ def _filter_nodes(
else:
target = f"avibe::project::{project}"
result = [n for n in result if n["scope_id"] == target]
+ # A ``system`` session is the RUNTIME's own row (today: the workspace-notifications
+ # sink that harness failure notices fall back to — see
+ # ``storage.agent_session_rows.resolve_workspace_notice_session``). It is not agent
+ # work, has no backend and runs no turns, so it is not a node under EITHER toggle;
+ # ``include_background`` is a user preference about the user's own hidden sessions and
+ # does not mean "show me the runtime's". Excluded EXPLICITLY rather than left to the
+ # ``!= 'background'`` test below, which admits by default: today the row owns no runs
+ # so it never even becomes a candidate, but a single run pointing at it (a repaired
+ # ``session_id``, an imported row, a future self-heal run) would otherwise make it a
+ # History-view node counted as ``foreground``. Pinned by
+ # ``tests/test_workspace_system_session.py``.
+ result = [n for n in result if n.get("visibility") != "system"]
if not include_background:
result = [n for n in result if n.get("visibility") != "background"]
return result
@@ -719,6 +731,9 @@ def _prefilter_candidate_rows(
return r.get("status") == "archived" or archived_project
result = [r for r in rows if not _hidden(r)]
+ # Mirror _filter_nodes' unconditional ``system`` exclusion here too, so a runtime row
+ # cannot consume the run-load cap on its way to being dropped.
+ result = [r for r in result if (r.get("visibility") or "foreground") != "system"]
if not include_background:
result = [r for r in result if (r.get("visibility") or "foreground") != "background"]
if project and project != "all":
diff --git a/core/services/sessions.py b/core/services/sessions.py
index 2b3f84878..98cfe945f 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -37,6 +37,7 @@ from typing import Optional
from config import paths
from storage.workbench_sessions_service import (
+ ReservedSessionError,
SessionArchivedError,
SessionBackendLockedError,
archive_session,
@@ -58,6 +59,7 @@ from vibe.i18n import t as i18n_t
__all__ = [
"SESSION_ARCHIVED_I18N_KEY",
+ "ReservedSessionError",
"SessionArchivedError",
"SessionBackendLockedError",
"archive_session",
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index b98bf3ab8..737208b64 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -64,8 +64,21 @@ def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[s
return
if not _is_notifiable_message(message.get("type"), message.get("metadata")):
return
- if not message.get("session_id"):
- return
+
+ # ``session_id`` used to be a hard requirement, which made this the LAST rung of
+ # the failure-notification ladder to be empty rather than the one that always
+ # resolves. A definition created from a plain CLI invocation has no caller
+ # provenance at all (``_session_creation_metadata_from_caller`` returns ``{}``
+ # for a ``None`` caller), so it has no channel to fall back to and no user to DM;
+ # an unscoped ``create_per_run`` definition can have no delivery key either. For
+ # such a definition every earlier rung is empty, and a notice with nowhere to go
+ # is a notice that is never written — for exactly the runs nobody is watching.
+ #
+ # A workspace-addressed notice needs no session because it is addressed to the
+ # workspace. Where a session IS named the deep link still points at it.
+ session_id = message.get("session_id")
+ url = f"/chat/{session_id}" if session_id else "/harness"
+ tag = f"session:{session_id}" if session_id else "harness:failure"
# ``badge_count`` is the app-icon badge number, which is a single global
# value — not this one session's unread count. It is computed at send time
@@ -74,10 +87,10 @@ def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[s
payload = {
"title": inbox_row.get("title") or inbox_row.get("project_name") or "avibe",
"body": (message.get("text") or inbox_row.get("preview_text") or "").strip()[:240],
- "url": f"/chat/{message['session_id']}",
- "tag": f"session:{message['session_id']}",
+ "url": url,
+ "tag": tag,
"message_id": message.get("id"),
- "session_id": message.get("session_id"),
+ "session_id": session_id,
}
thread = threading.Thread(target=_send_to_enabled_subscriptions, args=(payload,), daemon=True)
thread.start()
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 9e5521919..a3e3a6666 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -1020,8 +1020,21 @@ class CodexAgent(BaseAgent):
# ------------------------------------------------------------------
def _caller_env_for_request(self, request: AgentRequest) -> dict[str, str]:
+ # The typed context carries the CREATION ORIGIN (platform, channel, thread,
+ # user, message id) that a Harness definition created by ``vibe task add`` in
+ # this turn's shell needs in order to record where it came from. This env is
+ # the only hop it can travel: the CLI runs as a subprocess of the Codex shell.
context = getattr(request, "context", None)
- return caller_env_for_platform_payload(getattr(context, "platform_specific", None))
+ return caller_env_for_platform_payload(
+ getattr(context, "platform_specific", None),
+ message=context,
+ # Defensively resolved: this is reached from payload-shaping helpers that
+ # are exercised (and legitimately used) without a fully wired controller,
+ # and a missing fallback costs an origin platform — never a raised turn.
+ fallback_platform=getattr(
+ getattr(getattr(self, "controller", None), "config", None), "platform", None
+ ),
+ )
def _caller_env_script_path(self, request: AgentRequest) -> Path:
caller_env = self._caller_env_for_request(request)
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 40a02e393..158f56287 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -805,6 +805,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
request.context.platform_specific or {},
base_env=os.environ,
working_dir=request.working_path,
+ # The creation origin travels with the identity: an OpenCode shell
+ # command running ``vibe task add`` sources this binding, and it is
+ # the only place the conversation behind the definition is visible.
+ message=request.context,
+ fallback_platform=platform,
)
except Exception:
logger.warning("Failed to bind OpenCode caller context for session %s", session_id, exc_info=True)
diff --git a/modules/agents/opencode/caller_context.py b/modules/agents/opencode/caller_context.py
index 1ce1f94b3..a37991021 100644
--- a/modules/agents/opencode/caller_context.py
+++ b/modules/agents/opencode/caller_context.py
@@ -144,13 +144,27 @@ def bind_session(
base_env: Mapping[str, str],
working_dir: Path | str | None,
ttl_hours: int = BINDING_TTL_HOURS,
+ message: object | None = None,
+ fallback_platform: object | None = None,
) -> bool:
+ """Persist the caller env an OpenCode shell command will source.
+
+ *message* is the turn's typed ``MessageContext``. Without it the binding carries
+ caller IDENTITY only; with it the binding also carries the CREATION ORIGIN, which is
+ what lets a Harness definition created by ``vibe task add`` inside this OpenCode
+ session record the conversation it came from.
+ """
+
from core.git_runtime import prepend_vendored_git_to_path
session_id = str(opencode_session_id or "").strip()
if not session_id:
return False
- caller = caller_context_from_platform_payload(platform_payload)
+ caller = caller_context_from_platform_payload(
+ platform_payload,
+ message=message,
+ fallback_platform=fallback_platform,
+ )
env = caller.to_env() if caller is not None else {}
prepend_vendored_git_to_path(
env,
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index eda663633..206d4982c 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -397,9 +397,17 @@ class FeishuBot(BaseIMClient):
root_id = context.thread_id or reply_to
if root_id:
message_id = await self._reply_message(root_id, text, subtext=subtext)
+ # Post-send bookkeeping: the message is ALREADY delivered, so a raise
+ # here must never destroy the native id on its way out. Callers such as
+ # the message dispatcher treat any exception from the adapter as a send
+ # failure with no delivery evidence, which would re-send an
+ # already-delivered message. Same guard as discord.py send_message.
if self.settings_manager:
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)
+ except Exception:
+ pass
return message_id
request = (
@@ -425,10 +433,15 @@ class FeishuBot(BaseIMClient):
raise RuntimeError(f"Feishu send_message failed: {response.msg}")
message_id = response.data.message_id
+ # Post-send bookkeeping must not destroy the delivered message id
+ # (see the thread-reply branch above).
if self.settings_manager and (context.thread_id or reply_to):
thread = context.thread_id or reply_to
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, thread)
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread)
+ except Exception:
+ pass
return message_id
async def _reply_message(self, parent_id: str, text: str, subtext: Optional[str] = None) -> str:
@@ -621,9 +634,14 @@ class FeishuBot(BaseIMClient):
if root_id:
message_id = await self._reply_message_with_card(root_id, card_json)
self._remember_message_text(message_id, text, subtext=subtext)
+ # Post-send bookkeeping must not destroy the delivered message id
+ # (see send_message); mirrors discord.py send_message_with_buttons.
if self.settings_manager:
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, root_id)
+ except Exception:
+ pass
return message_id
request = (
@@ -650,9 +668,14 @@ class FeishuBot(BaseIMClient):
message_id = response.data.message_id
self._remember_message_text(message_id, text, subtext=subtext)
+ # Post-send bookkeeping must not destroy the delivered message id
+ # (see send_message).
if self.settings_manager and context.thread_id:
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, context.thread_id)
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, context.thread_id)
+ except Exception:
+ pass
return message_id
async def _reply_message_with_card(self, parent_id: str, card_json: str) -> str:
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 73a290aad..aa3d22982 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -779,12 +779,20 @@ class SlackBot(BaseIMClient):
reply_to=reply_to,
)
- # Mark thread as active if we sent a message to a thread
+ # Mark thread as active if we sent a message to a thread. This is
+ # post-send bookkeeping: the message is ALREADY delivered, so a raise
+ # here must never destroy the native id on its way out. Callers such as
+ # the message dispatcher treat any exception from the adapter as a send
+ # failure with no delivery evidence, which would re-send an
+ # already-delivered message. Same guard as discord.py send_message.
if self.settings_manager and (context.thread_id or reply_to):
thread_ts = context.thread_id or reply_to
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
- logger.debug(f"Marked thread {thread_ts} as active after bot message")
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ logger.debug(f"Marked thread {thread_ts} as active after bot message")
+ except Exception:
+ pass
return response["ts"]
@@ -833,10 +841,15 @@ class SlackBot(BaseIMClient):
except SlackApiError as e:
logger.error(f"Error sending Slack status bubble: {e}")
raise
+ # Post-send bookkeeping must not destroy the delivered message id
+ # (see send_message).
if self.settings_manager and (context.thread_id or reply_to):
thread_ts = context.thread_id or reply_to
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ except Exception:
+ pass
return response["ts"]
async def send_markdown_message(
@@ -921,11 +934,16 @@ class SlackBot(BaseIMClient):
)
return await self.send_message(context, body, parse_mode="markdown", reply_to=reply_to)
+ # Post-send bookkeeping must not destroy the delivered message id
+ # (see send_message).
if self.settings_manager and (context.thread_id or reply_to):
thread_ts = context.thread_id or reply_to
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
- logger.debug(f"Marked thread {thread_ts} as active after bot native markdown message")
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ logger.debug(f"Marked thread {thread_ts} as active after bot native markdown message")
+ except Exception:
+ pass
return response["ts"]
@@ -1589,12 +1607,16 @@ class SlackBot(BaseIMClient):
log_label="message-with-buttons send",
)
- # Mark thread as active if we sent a message to a thread
+ # Post-send bookkeeping must not destroy the delivered message id
+ # (see send_message); mirrors discord.py send_message_with_buttons.
if self.settings_manager and (context.thread_id or reply_to):
thread_ts = context.thread_id or reply_to
- if self.sessions:
- self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
- logger.debug(f"Marked thread {thread_ts} as active after bot message with buttons")
+ try:
+ if self.sessions:
+ self.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ logger.debug(f"Marked thread {thread_ts} as active after bot message with buttons")
+ except Exception:
+ pass
return response["ts"]
diff --git a/storage/agent_session_rows.py b/storage/agent_session_rows.py
index 03ba9aad1..9991d3adc 100644
--- a/storage/agent_session_rows.py
+++ b/storage/agent_session_rows.py
@@ -17,7 +17,29 @@ from storage.session_reclaim import (
SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"
JSON_VALUE_PREFIX = "__json__:"
-SESSION_VISIBILITIES = frozenset({"foreground", "background"})
+
+#: ``agent_sessions.visibility`` — the STORAGE vocabulary, and the axis every session
+#: list and inbox surface already filters on (it is indexed: ``storage/models.py``
+#: ``ix_agent_sessions_visibility``). ``foreground`` = an ordinary chat; ``background``
+#: = a session that is hidden AND whose replies are not delivered; ``system`` = a row
+#: the RUNTIME owns, kept out of ordinary session lists while staying a first-class
+#: inbox/receipt destination (see ``WORKSPACE_NOTICE_SESSION_VISIBILITY``).
+#:
+#: There is no CHECK constraint on the column, so this set IS the vocabulary — every
+#: writer validates against it in Python.
+SESSION_VISIBILITIES = frozenset({"foreground", "background", "system"})
+
+#: The subset a CALLER may choose. ``system`` is deliberately excluded: it is a runtime
+#: classification, not a user preference, so ``PATCH /api/sessions/<id>`` and
+#: ``vibe session update`` cannot promote an ordinary chat into a system surface (which
+#: would hide it from every list while leaving it delivering). Only this module's own
+#: reserved-row create/heal writes ``system``.
+ASSIGNABLE_SESSION_VISIBILITIES = frozenset({"foreground", "background"})
+
+#: Visibilities the INBOX admits, i.e. the ones whose sessions can own a card, a
+#: realtime ``inbox.session.updated`` and a Web Push. Positive form on purpose: a
+#: future fourth value is hidden by default and has to opt in here explicitly.
+INBOX_SESSION_VISIBILITIES: tuple[str, ...] = ("foreground", "system")
PRIVATE_AGENT_RUN_SCOPE_TYPE = "private_agent_run"
@@ -173,6 +195,231 @@ def new_session_id(conn: Connection) -> str:
return candidate
+#: The reserved workspace-notifications Session — D5 rung (5) of the harness failure
+#: ladder (``docs/plans/harness-run-reliability.md:3193``, :3215-3222).
+#:
+#: SPELLED OUTSIDE ``SESSION_ID_ALPHABET``, which is the whole reason it is a literal
+#: rather than a generated id: the alphabet has no ``-``, so ``new_session_id`` can
+#: never mint this value and the reserved row can never collide with an ordinary
+#: session. That makes the PRIMARY KEY the idempotence key — two racing creators
+#: produce one row and the loser simply reads it back — with no marker search, no new
+#: column and no migration.
+WORKSPACE_NOTICE_SESSION_ID = "ses-workspace-notices"
+
+#: Its ``session_anchor``. Also outside the generated namespace, so the
+#: ``uq_agent_sessions_scope_anchor`` slot it occupies cannot be claimed by a thread.
+WORKSPACE_NOTICE_SESSION_ANCHOR = "avibe_workspace_notices"
+
+#: Metadata marker on the row, for an operator reading ``agent_sessions`` directly.
+#: NOT the lookup key — see ``WORKSPACE_NOTICE_SESSION_ID``.
+WORKSPACE_NOTICE_SESSION_METADATA_KEY = "workspace_notice_session"
+
+#: Its ``visibility``: a SYSTEM surface, which is what makes the row simultaneously
+#: invisible to ordinary session lists and a first-class inbox destination. See
+#: ``resolve_workspace_notice_session`` for why that pair needs a third value rather
+#: than either of the two that existed.
+WORKSPACE_NOTICE_SESSION_VISIBILITY = "system"
+
+
+def session_is_runtime_owned(*, session_id: Any, visibility: Any = None) -> bool:
+ """Whether the RUNTIME owns this session, i.e. it accepts no user turn.
+
+ ``resolve_workspace_notice_session`` creates its row with "no backend and no turns"
+ (``docs/plans/harness-run-reliability.md``): it exists only to hold workspace
+ failure notices. Everything that WRITES a session already refuses it —
+ ``archive_session`` and ``update_session`` raise ``ReservedSessionError`` — but
+ ``system`` visibility deliberately keeps the row in the inbox, so its card is a
+ clickable chat, and a chat's composer POSTs messages. Without this predicate that
+ was the one door left open: a user could type into the workspace-notifications card
+ and dispatch a real agent turn into a machine-owned row with an empty
+ ``agent_backend``, mixing conversation into the failure-notice transcript.
+
+ TWO TESTS, OR'd, because they fail in different directions:
+
+ * ``visibility == 'system'`` is the PROJECTION, and the axis every other surface
+ already filters on — so a future system-owned row inherits the refusal instead of
+ needing its own line here. It is also free at the call site: the payload
+ ``get_session`` already returns carries ``visibility``.
+ * the reserved IDENTITY covers the row in the states where the projection is
+ momentarily wrong. That row heals lazily — ``resolve_workspace_notice_session``
+ repairs an archived status, a drifted visibility or a vacated anchor on the NEXT
+ notice, not on read — so between an operator's ``UPDATE … SET
+ visibility='foreground'`` (or a round-12/13 development row) and that heal, a
+ visibility-only test would admit the turn. This is the same reason the archive and
+ update guards test identity rather than row state.
+
+ ``visibility`` is optional so a caller holding only an id (no row loaded) still gets
+ the identity half rather than a false ``False``.
+ """
+ if str(session_id or "").strip() == WORKSPACE_NOTICE_SESSION_ID:
+ return True
+ return str(visibility or "").strip() == WORKSPACE_NOTICE_SESSION_VISIBILITY
+
+
+def _workspace_notice_session_is_usable(conn: Connection) -> bool | None:
+ """``True`` usable, ``False`` present-but-unusable, ``None`` absent.
+
+ THREE answers, not two, because the caller's three actions are different: return it,
+ heal it, create it. Collapsing "unusable" into "absent" would make the create path
+ collide with the row's own primary key; collapsing it into "usable" is the silent
+ swallow this predicate exists to detect.
+
+ Usability is defined by what the DELIVERY SURFACE requires, not by what the row
+ looks like: ``list_inbox_sessions`` filters on ``status != 'archived'`` AND
+ ``visibility IN ('foreground', 'system')``, and the reserved anchor has to be back
+ in place for the row to be the one the identity names. Everything else about the
+ row — title, metadata, history — is somebody's record and no business of this check.
+
+ ``system`` is required EXACTLY, not merely accepted: a ``foreground`` row is
+ deliverable but is also a visible chat in every ordinary session list, which is the
+ projection this round removed. So a round-12/13 development row (or any row an
+ operator re-labelled) is repaired rather than left half-projected — which is also
+ why this needs no Alembic migration.
+ """
+
+ row = conn.execute(
+ select(
+ agent_sessions.c.status,
+ agent_sessions.c.visibility,
+ agent_sessions.c.session_anchor,
+ ).where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ ).mappings().first()
+ if row is None:
+ return None
+ return (
+ str(row["status"] or "") == "active"
+ and str(row["visibility"] or "") == WORKSPACE_NOTICE_SESSION_VISIBILITY
+ and str(row["session_anchor"] or "") == WORKSPACE_NOTICE_SESSION_ANCHOR
+ )
+
+
+def resolve_workspace_notice_session(
+ conn: Connection,
+ *,
+ title: str | None = None,
+ now: str | None = None,
+) -> str:
+ """Resolve — creating once — the Session that harness failure notices fall back to.
+
+ D5's ladder ends in a row addressed to the WORKSPACE rather than to a person,
+ because a definition created by a plain ``vibe task add`` has no caller provenance
+ (so rungs (3) and (4) are empty), may have no delivery key (rung (1)), and may have
+ no session binding at all (rung (2), and the session-derived rung (5) candidate).
+ Without this row every rung is empty and the notice can only dead-letter.
+
+ DURABILITY BY LAZY RECREATION, not by exemption. Nothing here asks ``/new``'s
+ clear path or session eviction for a special case: if some other machinery removes
+ this row, the next notice creates it again. That is why the identity has to be
+ STABLE and why it is the primary key that enforces uniqueness.
+
+ CONCURRENCY. Two notice-drain owners can race the create. The unlocked read is the
+ hot path (the row almost always exists); the create path reserves SQLite's writer
+ slot with ``reserve_write_lock`` FIRST and re-decides underneath it, which is the
+ same answer ``get_or_create_agent_session_row`` gives the first-turn INSERT — one
+ row, and no ``SQLITE_BUSY_SNAPSHOT`` for the loser to classify.
+
+ NO SCOPE, deliberately. Every ``avibe`` project scope is a row in
+ ``projects_service.list_projects``, so anchoring this session to a reserved project
+ would mint a fake project in the workbench sidebar. ``agent_sessions.scope_id`` is
+ nullable and already carries scope-less sessions (``reserve_standalone_agent_session``),
+ ``persist_agent_message``'s avibe branch writes on ``session_row is not None``
+ regardless of scope, and the inbox card falls back to ``'avibe'`` for a null
+ project — so a scope-less session is an existing shape rather than a new one.
+
+ A SYSTEM SURFACE, NOT A FOREGROUND CHAT (``visibility='system'``). The row has to be
+ two things at once, and the two visibility values that existed each gave exactly one
+ of them: ``foreground`` delivers but is also an ordinary chat in every session list
+ (a machine-owned row users cannot usefully talk to, offered as somewhere to talk);
+ ``background`` hides but is filtered OUT of ``list_inbox_sessions`` /
+ ``unread_counts_by_session``, i.e. it hides the notice itself, which is the one thing
+ rung (5) exists to show — and it additionally sets ``suppress_delivery``, so no
+ realtime event and no push either. ``system`` is the projection: kept out of the
+ ordinary session lists (which all filter POSITIVELY on ``== 'foreground'``, so they
+ exclude it with no change of theirs) and admitted to the inbox surfaces explicitly
+ (``INBOX_SESSION_VISIBILITIES``). Delivery is untouched — ``suppress_delivery`` keys
+ on ``== 'background'`` alone, so a system session delivers exactly like a foreground
+ one.
+
+ WHY A VALUE IN AN EXISTING COLUMN. ``visibility`` is precisely the axis every list
+ and inbox surface already filters on, and it is indexed
+ (``ix_agent_sessions_visibility``), so the projection costs one predicate on queries
+ that already carry one. A ``metadata_json`` flag would put JSON parsing into the hot
+ inbox/list queries; a dedicated column would be a migration for a single row. A
+ session class that some surfaces refuse is also not new here —
+ ``PRIVATE_AGENT_RUN_SCOPE_TYPE`` is deliberately kept off the chat surface the same
+ way. And because ``system`` is not in ``ASSIGNABLE_SESSION_VISIBILITIES``, no caller
+ can label an ordinary chat with it.
+
+ ``title`` is the localized display name, applied at CREATE time only: it is
+ persisted product copy, so a later language change does not rewrite it (the row is
+ named once, by whoever's notice created it).
+
+ AND IT HEALS, because recreation covers only REMOVAL. The states that matter are the
+ ones where the row still exists under its reserved primary key and is nonetheless
+ unusable — an ARCHIVED status, a non-``system`` visibility, a vacated
+ ``archived:<id>`` anchor — and each of them fails SILENTLY rather than loudly: the
+ notice still persists through ``_session_row`` (no status filter), still earns its
+ receipt, still acks, while ``list_inbox_sessions`` shows nothing (or shows it in the
+ wrong place). So a row that exists but is not usable is repaired in place, under the
+ same write lock the create takes, which also repairs a database archived before
+ ``archive_session`` learned to refuse this id — and converts a round-12/13
+ development row that predates ``system``, which is why this needs no migration: the
+ row exists in no release. The defences are independent on purpose: the
+ archive/update guards close the API doors, this closes every other one.
+ """
+
+ healthy = _workspace_notice_session_is_usable(conn)
+ if healthy is True:
+ return WORKSPACE_NOTICE_SESSION_ID
+
+ # BEFORE the re-read the INSERT rests on, for the reason ``reserve_write_lock``
+ # spells out: a competing creator committing between the read and the write leaves
+ # this transaction unable to write at all.
+ reserve_write_lock(conn)
+ healthy = _workspace_notice_session_is_usable(conn)
+ if healthy is True:
+ return WORKSPACE_NOTICE_SESSION_ID
+ if healthy is False:
+ # The row exists and is unusable. Repair exactly the columns that make it
+ # unusable and nothing else — its title, metadata and message history are
+ # somebody's record and are not this call's to rewrite.
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ .values(
+ status="active",
+ visibility=WORKSPACE_NOTICE_SESSION_VISIBILITY,
+ # ``archive_session`` re-anchors to ``archived:<id>`` to free the
+ # (scope, anchor) slot; restoring the reserved anchor cannot collide,
+ # because this row's ``scope_id`` is NULL and SQLite treats NULLs in a
+ # UNIQUE index as distinct.
+ session_anchor=WORKSPACE_NOTICE_SESSION_ANCHOR,
+ agent_status="idle",
+ updated_at=now or utc_now_iso(),
+ )
+ )
+ return WORKSPACE_NOTICE_SESSION_ID
+
+ return create_agent_session_row(
+ conn,
+ scope_id=None,
+ session_id=WORKSPACE_NOTICE_SESSION_ID,
+ session_anchor=WORKSPACE_NOTICE_SESSION_ANCHOR,
+ # No backend and no turns: nothing is ever dispatched into this session, it
+ # only holds notification rows. An empty backend is the honest value, and
+ # ``create_agent_session_row`` normalizes the variant to ``default``.
+ agent_backend="",
+ title=title,
+ visibility=WORKSPACE_NOTICE_SESSION_VISIBILITY,
+ metadata={WORKSPACE_NOTICE_SESSION_METADATA_KEY: True},
+ now=now,
+ # No Scope to snapshot a workdir from, and none is wanted: a workdir would
+ # imply a runtime, and creating a directory for a row that never runs anything
+ # is a filesystem side effect the notice path has no business taking.
+ require_workdir=False,
+ )
+
+
def create_agent_session_row(
conn: Connection,
*,
diff --git a/storage/alembic/versions/20260728_0039_agent_runs_settled_at_index.py b/storage/alembic/versions/20260728_0039_agent_runs_settled_at_index.py
new file mode 100644
index 000000000..08b2832d0
--- /dev/null
+++ b/storage/alembic/versions/20260728_0039_agent_runs_settled_at_index.py
@@ -0,0 +1,60 @@
+"""index agent_runs by definition and settlement time for derived health
+
+The health window scans one definition's verdicts ordered by
+``coalesce(completed_at, created_at) desc, id desc``. The existing
+``ix_agent_runs_definition_created`` is ``(definition_id, created_at)``, which
+serves the equality but NOT that ordering, so the sort was unindexed.
+
+Index-only: this adds no state. Health stays derived from ``agent_runs`` on every
+read — there is no counter, no column to keep in sync, and nothing to backfill.
+
+Raw SQL rather than ``op.create_index`` because the second key is an expression;
+SQLAlchemy cannot express it.
+
+Revision ID: 20260728_0039
+Revises: 20260727_0038
+Create Date: 2026-07-28
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260728_0039"
+down_revision = "20260727_0038"
+branch_labels = None
+depends_on = None
+
+_INDEX = "ix_agent_runs_definition_settled"
+# Exported so the head-schema repair path in ``storage/migrations.py`` executes THIS
+# statement rather than a second copy of it. ``_ensure_head_indexes`` promises a
+# head-shaped unversioned database every index head has, and a retyped copy is how an
+# index ends up built with a different definition than the one the planner was measured
+# against.
+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"
+CREATE_INDEX_SQL = (
+ f"create index {_INDEX} on agent_runs "
+ "(definition_id, coalesce(completed_at, created_at) desc, id desc)"
+)
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
+ bind.exec_driver_sql(CREATE_INDEX_SQL)
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
diff --git a/storage/alembic/versions/20260728_0040_agent_runs_owed_notice_index.py b/storage/alembic/versions/20260728_0040_agent_runs_owed_notice_index.py
new file mode 100644
index 000000000..90d174b87
--- /dev/null
+++ b/storage/alembic/versions/20260728_0040_agent_runs_owed_notice_index.py
@@ -0,0 +1,79 @@
+"""index the owed-failure-notice eligibility expression for the 2s drain tick
+
+The drain runs every two seconds and asks "is any notice eligible to deliver?".
+Filtering the notice state in SQL was not enough to bound that: the planner could
+only seek on ``status='failed'`` and then had to evaluate the unindexed
+``json_valid`` / ``json_extract`` terms on EVERY failed row before concluding
+nothing was eligible. Measured before this migration::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_status_created (status=?)
+ USE TEMP B-TREE FOR LAST TERM OF ORDER BY
+
+The temp sort is the second half of the problem: it defeats the ``LIMIT``'s early
+exit, because SQLite must order the whole failed set before it can return ten
+rows. So the steady-state cost of a tick grew with total failed-run history.
+
+Indexing the eligibility EXPRESSION makes it seekable and supplies the
+``(created_at, id)`` ordering, so the plan becomes a bounded seek with no temp
+sort. A *partial* index (``WHERE json_extract(...) = 'pending'``) was tried first
+and rejected: SQLite's partial-index implication analysis does not match these
+terms, and the planner silently ignored the index — verified with EXPLAIN QUERY
+PLAN on a 5000-row table both with and without ANALYZE.
+
+The ``CASE json_valid`` guard is load-bearing at WRITE time here, which it is not
+in the query. An index expression is evaluated on every INSERT and UPDATE, so a
+bare ``json_extract`` would raise ``malformed JSON`` and make a row with an
+unparseable blob UNWRITABLE — turning a read-side degradation into a write-side
+outage. CASE short-circuits, so the extract never runs on invalid JSON.
+
+The expression must stay byte-identical to the one
+``SQLiteBackgroundTaskStore.list_owed_failure_notices`` compiles, or the planner
+will not match it; ``tests/test_harness_failure_visibility.py`` asserts the query
+plan names this index, so a drift fails the suite rather than silently
+reintroducing the scan.
+
+Revision ID: 20260728_0040
+Revises: 20260728_0039
+Create Date: 2026-07-28
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260728_0040"
+down_revision = "20260728_0039"
+branch_labels = None
+depends_on = None
+
+_INDEX = "ix_agent_runs_owed_notice"
+# Unqualified column names: SQLite rejects the "." operator inside an index
+# expression. The planner still matches this against the query's qualified form.
+_STATE_EXPR = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_extract(metadata_json, '$.owed_failure_notice.state') END"
+)
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(f"drop index if exists {_INDEX}")
+ bind.exec_driver_sql(
+ f"create index {_INDEX} on agent_runs ({_STATE_EXPR}, created_at, id)"
+ )
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(f"drop index if exists {_INDEX}")
diff --git a/storage/alembic/versions/20260728_0041_agent_runs_owed_notice_backoff_index.py b/storage/alembic/versions/20260728_0041_agent_runs_owed_notice_backoff_index.py
new file mode 100644
index 000000000..6a8025219
--- /dev/null
+++ b/storage/alembic/versions/20260728_0041_agent_runs_owed_notice_backoff_index.py
@@ -0,0 +1,97 @@
+"""constrain the owed-notice backoff term in the index, not per row
+
+``20260728_0040`` indexed the eligibility STATE expression followed by
+``(created_at, id)``. That made SQLite report the index as used and skip the temp
+sort — which is exactly what the query-plan test asserted — while the backoff
+condition stayed unindexed, so the engine still walked EVERY pending-state entry
+evaluating it. With many notices waiting on retry and none eligible, the two-second
+tick was again unbounded in the number of pending notices.
+
+The plan before this migration, with 40 backed-off notices::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_owed_notice (<expr>=?)
+
+— one constrained term. After, with the backoff expression as the second index
+column::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_owed_notice (<expr>=? AND <expr><?)
+
+Measured on a 4000-row table where nothing is eligible, this is the difference
+between walking all 4000 entries and ~50 VM steps.
+
+Two things had to change together for the range term to be usable at all:
+
+* ``next_attempt_at`` is now always written as an instant, never ``NULL``. A
+ nullable column forces ``(x IS NULL OR x <= now)``, and a disjunction cannot be
+ an index range constraint.
+* the query orders on the index prefix, so the ordering is free and the ``LIMIT``
+ still short-circuits.
+
+The ``CASE json_valid`` guard is required on the new expression for the same
+write-time reason as the state expression: an index expression is evaluated on
+every INSERT/UPDATE, so a bare ``json_extract`` would make a row with an
+unparseable blob unwritable.
+
+Revision ID: 20260728_0041
+Revises: 20260728_0040
+Create Date: 2026-07-28
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260728_0041"
+down_revision = "20260728_0040"
+branch_labels = None
+depends_on = None
+
+_INDEX = "ix_agent_runs_owed_notice"
+# Unqualified column names: SQLite rejects the "." operator inside an index
+# expression. Must stay byte-identical to ``OWED_NOTICE_STATE_SQL`` /
+# ``OWED_NOTICE_NEXT_ATTEMPT_SQL`` in ``storage/background.py``, or the planner
+# silently declines to match and the scan comes back with no signal.
+_STATE_EXPR = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_extract(metadata_json, '$.owed_failure_notice.state') END"
+)
+# ``coalesce(..., '')`` is what makes this usable as a RANGE constraint: a null
+# next-attempt means "eligible now", and expressing that as a disjunction would
+# leave the term filtered per row while the plan still named the index.
+_NEXT_ATTEMPT_EXPR = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN coalesce(json_extract(metadata_json, '$.owed_failure_notice.next_attempt_at'), '') END"
+)
+# Exported so the head-schema repair path in ``storage/migrations.py`` executes THIS
+# statement rather than a second copy of it. Nowhere is that more load-bearing than
+# here: the planner matches an index EXPRESSION against a query expression by text, so a
+# retyped copy would build an index the owed-notice tick silently declines to use, which
+# is the exact failure 0040 and 0041 were each written to correct.
+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"
+CREATE_INDEX_SQL = (
+ f"create index {_INDEX} on agent_runs "
+ f"({_STATE_EXPR}, {_NEXT_ATTEMPT_EXPR}, created_at, id)"
+)
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
+ bind.exec_driver_sql(CREATE_INDEX_SQL)
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
+ bind.exec_driver_sql(f"create index {_INDEX} on agent_runs ({_STATE_EXPR}, created_at, id)")
diff --git a/storage/alembic/versions/20260729_0042_agent_runs_definition_streak_index.py b/storage/alembic/versions/20260729_0042_agent_runs_definition_streak_index.py
new file mode 100644
index 000000000..49fc3ed36
--- /dev/null
+++ b/storage/alembic/versions/20260729_0042_agent_runs_definition_streak_index.py
@@ -0,0 +1,80 @@
+"""index a definition's history by its (created_at, id) position
+
+``failure_streak`` runs once per pending owed notice, on the same two-second tick
+as the eligibility lookup. It used to materialise the definition's ENTIRE settled
+lifetime and slice the streak out in Python; it now finds the successes bracketing
+the run with two ``LIMIT 1`` seeks and reads only the rows between them.
+
+That rewrite needs an index this table did not have. The sequence key is
+``(created_at, id)`` — ``created_at`` alone is not a position, because several
+writers stamp a whole batch with one ISO string — so the seek asks for
+``(created_at, id) < (?, ?)``. With ``ix_agent_runs_definition_created``
+(``definition_id, created_at``) SQLite decomposes that row value into a weaker
+scalar range and then sorts to recover the tie-break::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_definition_created
+ (definition_id=? AND created_at<?)
+ USE TEMP B-TREE FOR LAST TERM OF ORDER BY
+
+— and a temp sort over one definition's whole history is the unbounded read the
+rewrite exists to remove, because it defeats the ``LIMIT 1``'s early exit. With
+``id`` as the third key the row value becomes a real index constraint and the sort
+disappears::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_definition_streak
+ (definition_id=? AND (created_at,id)<(?,?))
+
+``ix_agent_runs_definition_created`` is left in place even though this index is a
+strict superset of it: ``storage/migrations.py::_ensure_new_background_indexes``
+recreates that name unconditionally for legacy databases, so dropping it here
+would only make the resulting schema depend on which upgrade path a database took.
+
+Index-only: no new state, nothing to backfill, health and streaks stay derived
+from ``agent_runs`` on every read.
+
+Raw SQL rather than ``op.create_index`` for symmetry with ``20260728_0039``.
+
+Revision ID: 20260729_0042
+Revises: 20260728_0041
+Create Date: 2026-07-29
+"""
+
+from __future__ import annotations
+
+from alembic import op
+
+revision = "20260729_0042"
+down_revision = "20260728_0041"
+branch_labels = None
+depends_on = None
+
+_INDEX = "ix_agent_runs_definition_streak"
+# Exported so the head-schema repair path in ``storage/migrations.py`` executes THIS
+# statement rather than a second copy of it — the same reason ``20260728_0039`` and
+# ``20260728_0041`` export theirs. The note above about ``_ensure_new_background_indexes``
+# recreating ``ix_agent_runs_definition_created`` unconditionally still holds; that
+# helper now also installs this index, from this constant.
+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"
+CREATE_INDEX_SQL = f"create index {_INDEX} on agent_runs (definition_id, created_at, id)"
+
+
+def _tables(bind) -> set[str]:
+ return {
+ str(row[0])
+ for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")
+ }
+
+
+def upgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
+ bind.exec_driver_sql(CREATE_INDEX_SQL)
+
+
+def downgrade() -> None:
+ bind = op.get_bind()
+ if "agent_runs" not in _tables(bind):
+ return
+ bind.exec_driver_sql(DROP_INDEX_SQL)
diff --git a/storage/background.py b/storage/background.py
index 4431fa0d1..094edac36 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import json
import logging
-from contextlib import contextmanager
+from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -11,10 +11,27 @@ from zoneinfo import ZoneInfo
from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
-from sqlalchemy import and_, case, func, insert, or_, select, update
+from sqlalchemy import (
+ Integer,
+ Text,
+ and_,
+ case,
+ cast,
+ exists,
+ func,
+ insert,
+ literal,
+ literal_column,
+ or_,
+ select,
+ tuple_,
+ update,
+)
from config import paths
+from config.platform_registry import PLATFORM_REGISTRY
from storage.agent_session_rows import (
+ INBOX_SESSION_VISIBILITIES,
reserve_write_lock,
session_openable_in_chat,
unchanged_text,
@@ -22,11 +39,13 @@ from storage.agent_session_rows import (
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.migrations import (
background_tables_ready,
+ ensure_background_indexes,
guard_source_checkout_default_state_migration,
initialize_background_tables,
)
-from storage.models import agent_runs, agent_sessions, run_definitions, scopes
+from storage.models import agent_runs, agent_sessions, messages, run_definitions, scopes
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
+from storage.sqlite_semantics import sqlite_cast_integer
from storage.session_reclaim import SESSION_SETTINGS_SNAPSHOT_KEY
logger = logging.getLogger(__name__)
@@ -380,12 +399,17 @@ def definition_lifecycle_expression(definition_type: str):
# ``None`` exactly when the instant is behind us — so the state and the
# time printed beside it cannot contradict each other.
#
- # ``datetime()`` normalises offset-carrying timestamps before comparing
- # the scheduled instant with SQLite's current UTC clock.
+ # SQLite cannot resolve an IANA timezone and treats a naive timestamp as
+ # UTC. The connection UDF delegates that resolution to the same stdlib
+ # rule the scheduler uses, then compares two epoch values in UTC.
ended = and_(
run_definitions.c.schedule_type == "at",
run_definitions.c.run_at.is_not(None),
- func.datetime(run_definitions.c.run_at) <= func.datetime("now"),
+ func.avibe_run_at_epoch(
+ run_definitions.c.run_at,
+ run_definitions.c.timezone,
+ )
+ <= (func.julianday("now") - literal(2440587.5)) * literal(86400.0),
)
return case(
(in_flight, "running"),
@@ -671,6 +695,655 @@ SWEEP_REASON_ORPHANED = "orphaned"
SWEEP_REASON_TRANSPORT_UNAVAILABLE = "transport_unavailable"
SWEEP_REASON_QUEUE_HOLD_EXPIRED = "queue_hold_expired"
+#: ``agent_runs.metadata.owed_failure_notice`` — the durable record that a user
+#: still has to be told about one terminal failure.
+#:
+#: Stamped by whichever UPDATE actually transitions ``status`` to ``failed``, not
+#: by a list of call sites: that property is what makes a settlement path added
+#: later inherit the notice instead of having to remember it. The one exception is
+#: ``stamp_binding_change_notice``, and it is an exception precisely because there
+#: is no transition to ride — a rebind whose retry succeeds settles ``succeeded``
+#: and still owes the user the news. Guardedness is
+#: deliberately NOT part of the test — an ordinary synchronous failure
+#: terminalizes through the claimed-request completion, and excluding it would
+#: leave the most common failure of all with no notice to deliver.
+OWED_FAILURE_NOTICE_KEY = "owed_failure_notice"
+
+#: Expression index serving the drain's eligibility seek. Named here so the query,
+#: the migration and the query-plan test cannot drift apart.
+OWED_NOTICE_INDEX = "ix_agent_runs_owed_notice"
+
+#: The eligibility expressions, as literal SQL.
+#:
+#: Literal rather than composed with ``case()``/``func`` because SQLAlchemy renders
+#: the ``1`` and the JSON path as bound parameters, and SQLite will not match an
+#: index expression against a query expression containing binds — the index gets
+#: built and silently ignored.
+#:
+#: The ``CASE json_valid`` guard does two jobs. In the QUERY it stops one malformed
+#: blob from raising ``malformed JSON`` and failing the whole statement, which would
+#: silence every failure notification at once. In the INDEX it stops the same thing
+#: at WRITE time: an index expression is evaluated on every INSERT/UPDATE, so a bare
+#: ``json_extract`` would make a row with an unparseable blob unwritable.
+#:
+#: Columns are unqualified because SQLite rejects the "." operator inside an index
+#: expression. ``20260728_0040`` must keep these byte-identical.
+OWED_NOTICE_STATE_SQL = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_extract(metadata_json, '$.owed_failure_notice.state') END"
+)
+#: The notice kind is not part of the eligibility index: it only distinguishes the
+#: exceptional canceled binding-change row after the indexed pending/backoff seek.
+#: Keep the same malformed-JSON guard as the indexed expressions so one damaged row
+#: cannot stop every notification from draining.
+OWED_NOTICE_KIND_SQL = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_extract(metadata_json, '$.owed_failure_notice.kind') END"
+)
+#: ``coalesce(..., '')`` is what keeps this a RANGE term. A missing or null
+#: ``next_attempt_at`` means "eligible now", and expressing that as
+#: ``(x IS NULL OR x <= now)`` is a disjunction, which SQLite cannot use as an index
+#: constraint — the index would be named in the plan while the backoff was still
+#: filtered per row. The empty string sorts before every ISO instant, so a null
+#: reads as eligible through the same ``<=`` comparison.
+#:
+#: This also keeps notices stamped before the backoff column existed visible
+#: instead of silently unreachable forever.
+OWED_NOTICE_NEXT_ATTEMPT_SQL = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN coalesce(json_extract(metadata_json, '$.owed_failure_notice.next_attempt_at'), '') END"
+)
+
+#: The notice lifecycle, mirroring ``callback_status`` rather than inventing a
+#: second vocabulary: ``pending`` owes delivery, ``sent`` has evidence of it,
+#: ``skipped`` is a row the drain decided needs no user-visible notice (streak
+#: suppression), ``failed`` is a dead letter that exhausted its retries and stays
+#: visible instead of retrying forever.
+NOTICE_PENDING = "pending"
+NOTICE_SENT = "sent"
+NOTICE_SKIPPED = "skipped"
+NOTICE_FAILED = "failed"
+#: Terminal notice states: never delivered again, and no longer blocking a streak.
+NOTICE_TERMINAL_STATES = frozenset({NOTICE_SENT, NOTICE_SKIPPED, NOTICE_FAILED})
+
+
+class _UnstampableInstant(str):
+ """A ``next_attempt_at`` that is not JSON text, carried through an expectation.
+
+ A ``str`` subclass so the expectation stays a ``tuple[str, int, str]`` and every
+ caller that only passes it through, prints it or compares it keeps working, while
+ ``owed_notice_state_unchanged`` can recognize it by TYPE and re-assert the stored
+ value the only way SQLite makes reproducible: by its JSON type.
+
+ Why a JSON number cannot be re-asserted by its text. The guard compares
+ ``cast(json_extract(...) AS TEXT)`` against a Python string, and SQLite renders a
+ REAL with its own 15-significant-digit formatter: ``1e25`` reads back as
+ ``'1.0e+25'`` where Python's ``str`` gives ``'1e+25'``, and at the 15th digit the
+ two round differently (``-1.5063173670565552e-212`` -> ``...655`` in SQLite,
+ ``...656`` in Python). Guessing that text would refuse the write, and a refused
+ write on a row the listing ADMITS is the starvation this whole pair exists to
+ prevent: the row is selected first every tick — every numeric sorts before every
+ ISO instant — consumes a batch slot, and never transitions.
+
+ Asserting the TYPE is not a loosening of what the third element is FOR. It exists
+ to catch a concurrent DEFERRAL, which writes an ISO string
+ (``notice_write_expectation``'s docstring records why), so "still not text" catches
+ every deferral there can be. ``state`` and ``attempts`` are unchanged and still
+ carry single-flight: a competing claim consumes the attempt, so only one owner can
+ win regardless of how this element compares.
+ """
+
+ __slots__ = ()
+
+
+#: The expectation's ``next_attempt_at`` when the stored value is not JSON text — a
+#: shape no stamper writes, so it can only arrive from a hand-edited row or a foreign
+#: writer. Interned as one value so the guard has a single spelling to recognize.
+_NEXT_ATTEMPT_NOT_TEXT = _UnstampableInstant("<next_attempt_at:not-text>")
+
+
+def notice_write_expectation(notice: Optional[dict[str, Any]]) -> tuple[str, int, str]:
+ """The ``(state, attempts, next_attempt_at)`` an owed-notice write was decided from.
+
+ Pass the result as ``update_owed_failure_notice(..., expect=...)``: one function so
+ the reading side and the predicate side normalize identically and cannot drift.
+ Never raises — ``attempts`` is JSON and a malformed value must read the same for
+ both sides rather than turning a guarded write into an error.
+
+ ALL THREE FIELDS THE DECISION READ, not just the two that identify a delivery
+ attempt. Eligibility is a function of ``state`` and ``next_attempt_at``
+ (``owed_notice_eligible``) and of ``attempts`` (``core.failure_notices.next_attempt``),
+ so a predicate over two of them leaves one way for a write to land on a world that
+ moved: a DEFERRAL writes only ``next_attempt_at`` and ``defer_reason``, leaving
+ ``(state, attempts)`` untouched, so a claimant that read before a concurrent
+ owner's deferral still matched its own expectation, won, and erased the deferral —
+ a second notice for one outage in the stale-cutoff lane, and a
+ ``DEFERRAL_RECHECK_SECONDS`` that any stale claimant could cancel.
+
+ Why this field and not ``updated_at``, which ``DefinitionWriteExpectation``
+ deliberately refuses: a row-version marker refuses benign writes and a freshly
+ stamped notice does not carry one at all, whereas ``next_attempt_at`` is stamped
+ unconditionally by every stamper (``_owed_failure_notice_for_transition`` and
+ ``stamp_binding_change_notice``) and a legacy notice that predates the field reads
+ ``""`` identically on both sides — the same ``coalesce(..., '')`` that keeps
+ ``OWED_NOTICE_NEXT_ATTEMPT_SQL`` a range term.
+
+ One consequence is recorded rather than hidden: two owners deferring the same
+ notice from one read no longer BOTH land — the first moves the field the second
+ re-asserts. The refusal is correct, and observationally empty: the notice is
+ deferred either way, no attempt is consumed either way, and the two recheck
+ instants differ by the microseconds between two owners reading the clock. Pinned by
+ ``test_a_second_identical_deferral_loses_the_cas_without_changing_the_outcome``.
+ """
+
+ source = notice if isinstance(notice, dict) else {}
+ # CAST semantics, not int(): SQLite parses a numeric PREFIX ('3x' → 3,
+ # '1e100' → 1) and saturates at the i64 bounds, where int() raises or
+ # overflows past what the CAS will read back. A divergent read here is a
+ # claim that can never match — the row stays eligible and unchanged on every
+ # drain pass, occupying one of the ten batch slots forever.
+ attempts = sqlite_cast_integer(source.get("attempts"))
+ return (str(source.get("state") or ""), attempts, _expected_next_attempt_at(source))
+
+
+def _expected_next_attempt_at(source: dict[str, Any]) -> str:
+ """``next_attempt_at`` as SQLite will read it back for the guard's comparison.
+
+ Text is taken VERBATIM — not stripped, not re-formatted — because the guard
+ compares it against the stored blob through SQLite, which does neither; a stripped
+ copy would refuse a write over a padded instant that nobody raced. Missing and
+ null both read as ``""``, mirroring the ``coalesce(..., '')`` in
+ ``OWED_NOTICE_NEXT_ATTEMPT_SQL``.
+
+ Anything else — a JSON number, ``true``/``false``, an object, an array — is a shape
+ no stamper writes and whose SQLite text is not reproducible in Python, so it is
+ carried as ``_NEXT_ATTEMPT_NOT_TEXT`` and re-asserted by JSON type instead. Note
+ the falsiness traps this avoids by testing the raw value rather than ``or ""``:
+ a stored ``0`` is ``'0'`` to SQLite, not ``''``, and a stored ``true`` is ``'1'``,
+ not ``'True'`` — both of which read as an unraceable guard on the eligible row
+ they belong to.
+ """
+
+ raw = source.get("next_attempt_at")
+ if raw is None or raw == "":
+ return ""
+ if isinstance(raw, str):
+ return raw
+ return _NEXT_ATTEMPT_NOT_TEXT
+
+
+def owed_notice_eligible(notice: Optional[dict[str, Any]], now: str) -> bool:
+ """Whether this notice may be acted on at *now*: ``pending`` and out of its wait.
+
+ The Python twin of ``OWED_NOTICE_STATE_SQL`` / ``OWED_NOTICE_NEXT_ATTEMPT_SQL``,
+ and it has to agree with them value for value — same relationship, and same
+ hazard, as ``notice_write_expectation`` and ``owed_notice_state_unchanged``. The
+ listing query seeks on those two index expressions and then re-checks the decoded
+ blob (the index is over a JSON path, so a row whose blob changed between the seek
+ and the read is worth re-reading), and ``_deliver_one_failure_notice`` re-reads
+ the row again before claiming it. Three copies of "is this eligible" is three
+ chances to disagree; one function is none.
+
+ ``next_attempt_at`` missing, null or empty means ELIGIBLE NOW, mirroring the
+ ``coalesce(..., '')`` in ``OWED_NOTICE_NEXT_ATTEMPT_SQL`` — the empty string sorts
+ before every ISO instant, so both sides read an absent wait through the same
+ ``<=``. String comparison, for the same reason every other timestamp comparison
+ here is: ISO-8601 in UTC sorts lexicographically.
+
+ Agreement means agreeing with the comparison SQLITE makes, which for a value that
+ is not text is not the comparison Python makes. The indexed expression is compared
+ RAW, so SQLite compares STORAGE CLASSES: every INTEGER and REAL sorts before every
+ TEXT, making a numeric ``next_attempt_at`` eligible at every instant, and SQLite
+ never strips, so ``" 9999-01-01..."`` sorts before ``now`` on its leading space.
+ Reading those through ``str(...).strip() <= now`` said the opposite, and the
+ disagreement is not a difference of opinion the drain absorbs: the seek applies
+ ``LIMIT`` BEFORE this re-check, so such a row is selected, dropped without any
+ state transition, and selected again on the next tick forever — and because it
+ sorts FIRST, ten of them starve every valid notice behind them, silently, in a
+ drain that looks busy. So the shapes SQL admits are admitted here too, and the
+ drain ADVANCES them: the claim stamps a real instant over the unreadable one.
+ Degrade and advance, as ``notice_write_expectation`` does for ``attempts``.
+
+ THE WHOLE DOMAIN, decided explicitly rather than left to whichever of the two
+ languages happens to answer first. Only the first two rows are reachable through
+ this module's writers; the rest need a hand-edited row or a foreign writer, and are
+ given a stated treatment anyway because the failure mode of an unstated one is
+ silence:
+
+ ==================== ============ =============================================
+ stored value eligible? treatment
+ ==================== ============ =============================================
+ absent / null / ``""`` yes no wait ever armed — ``coalesce(..., '')``
+ text ``value <= now`` UNSTRIPPED lexicographic compare, both
+ sides, because SQLite does not strip: a padded
+ instant is EARLY (``" 9999-…"`` sorts on its
+ leading space), never late
+ integer / real / yes numeric storage class sorts below every text
+ ``true`` / ``false`` bound, so SQL admits it at every instant;
+ admitted here too and NORMALIZED BY THE CLAIM,
+ which stamps a real instant over it. Bounded
+ progress: one pass and the row is a normal
+ notice again
+ object / array NO reads back as JSON text beginning ``{``/``[``,
+ which sorts above every ISO instant, so the
+ SEEK never returns it: it occupies no batch
+ slot and starves nothing. It also never
+ delivers. Chosen over admitting it in Python
+ only, which is the divergence this function
+ exists to remove; the underlying failure stays
+ visible through the definition's ``last_error``
+ and ``definition_health`` (the run is still
+ ``failed``), so what is lost is the push, not
+ the record. Pinned by
+ ``test_a_container_retry_instant_is_ineligible_
+ on_both_sides_and_starves_nothing``
+ ==================== ============ =============================================
+
+ The field carries two things that are one thing to this predicate: the retry
+ BACKOFF after a failed attempt, and the LEASE a claimant arms before it performs
+ the external send (see ``core.failure_notices.CLAIM_LEASE_SECONDS``). Both mean
+ "not this owner, not yet", so both are expressed as a future instant rather than
+ as a second column — which is also what makes the claim expire on its own if the
+ claimant dies.
+ """
+
+ if not isinstance(notice, dict) or notice.get("state") != NOTICE_PENDING:
+ return False
+ raw = notice.get("next_attempt_at")
+ if raw is None or raw == "":
+ return True
+ if isinstance(raw, str):
+ return raw <= now
+ if isinstance(raw, (int, float)):
+ # Numeric storage class, so SQLite sorts it before every TEXT: eligible at any
+ # ``now``. ``bool`` is an ``int`` here and is one in SQLite too — ``json_extract``
+ # reads JSON ``true``/``false`` back as 1/0.
+ return True
+ # An object or an array reads back as its JSON TEXT, which begins with a brace or a
+ # bracket and therefore sorts above every ISO instant — ineligible on both sides,
+ # and spelled out as a comparison rather than hardcoded as ``False`` so the two
+ # sides stay one rule rather than two agreeing accidents.
+ return _json_dumps(raw) <= now
+
+
+#: ``attempts``, read in SQL. Unlike ``OWED_NOTICE_STATE_SQL`` this one is NOT pinned
+#: to an index expression and does not need to be: the guarded write is located by
+#: primary key, so this pair is a FILTER on one already-identified row rather than a
+#: seek term, and no plan depends on its text.
+#:
+#: It keeps the ``CASE json_valid`` shape for the WRITE-time reason that constant
+#: documents: a bare ``json_extract`` over a malformed blob raises ``malformed JSON``
+#: and fails the whole statement, which here would turn "this write lost a race" into
+#: an exception the drain logs on every pass.
+_OWED_NOTICE_ATTEMPTS_SQL = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_extract(metadata_json, '$.owed_failure_notice.attempts') END"
+)
+
+#: ``next_attempt_at``'s JSON TYPE, read in SQL. The only reproducible way to
+#: re-assert a stored value whose TEXT rendering is SQLite's own — see
+#: ``_UnstampableInstant``. Not index-pinned, for the reason
+#: ``_OWED_NOTICE_ATTEMPTS_SQL`` gives: this is a filter on a row already located by
+#: primary key, so no query plan depends on its text.
+#:
+#: Same ``CASE json_valid`` guard, same reason: ``json_type`` raises ``malformed JSON``
+#: on an unparseable blob and would fail the whole statement.
+_OWED_NOTICE_NEXT_ATTEMPT_TYPE_SQL = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_type(metadata_json, '$.owed_failure_notice.next_attempt_at') END"
+)
+
+
+def owed_notice_state_unchanged(expect: tuple[str, int, str]) -> list[Any]:
+ """Predicates re-asserting the ``(state, attempts, next_attempt_at)`` of a write.
+
+ The SQL twin of ``notice_write_expectation``, and normalized to agree with it
+ value for value — same relationship as ``reclaim_snapshot_marker`` and
+ ``_RECLAIM_SNAPSHOT_MARKER_SQL``, for the same reason: a predicate that read the
+ stored blob more strictly than the caller read it would refuse writes nobody
+ raced. ``coalesce`` because a missing/null key is 0 or ``""`` on the Python side
+ and would otherwise be NULL here, and NULL is not false — it would fail the guard
+ on every freshly stamped notice. ``CAST`` because JSON is untyped: ``"3"`` and
+ ``3.7`` are what ``int(...)`` makes of them.
+
+ Values a notice cannot legally hold (a state stored as a JSON number) may still
+ resolve differently on the two sides; when they do, SQL is the STRICTER one, so
+ the residue is a refused write and a retried notice, never a lost one.
+
+ THAT ARGUMENT DOES NOT EXTEND TO ``next_attempt_at``, and the exception is why the
+ third predicate has two forms. A refused write is harmless only for a row that is
+ also ineligible; a row this guard can never match while ``owed_notice_eligible``
+ keeps admitting it is selected first by every tick — every JSON number sorts before
+ every ISO instant — occupies a batch slot, and never transitions. So for a stored
+ value that is not JSON text, whose SQLite TEXT rendering is not reproducible in
+ Python, the guard re-asserts the JSON TYPE instead of the text. See
+ ``_UnstampableInstant`` for the rendering evidence and for why the type is a
+ faithful substitute here.
+
+ The text form reuses ``OWED_NOTICE_NEXT_ATTEMPT_SQL`` VERBATIM under the
+ same outer ``coalesce``/``CAST`` shape as the other two, for the reason
+ ``owed_notice_absent`` gives: this is a filter on a row located by primary key so
+ no plan depends on its text, but a divergent copy of an indexed expression is
+ exactly how the eligibility index was built and silently ignored twice.
+ """
+
+ state, attempts, next_attempt_at = expect
+ if isinstance(next_attempt_at, _UnstampableInstant):
+ # The stored value is not JSON text, so its TEXT rendering is SQLite's own and
+ # not reproducible here (see ``_UnstampableInstant``): re-assert the type
+ # instead. ``coalesce`` to ``'null'`` because an absent key and a malformed blob
+ # both read as NULL, and NULL is not false — either would pass a bare
+ # ``NOT IN`` and let this guard match a row the caller never read.
+ third: Any = cast(
+ func.coalesce(literal_column(_OWED_NOTICE_NEXT_ATTEMPT_TYPE_SQL), "null"), Text
+ ).notin_(["text", "null"])
+ else:
+ third = (
+ cast(func.coalesce(literal_column(OWED_NOTICE_NEXT_ATTEMPT_SQL), ""), Text)
+ == next_attempt_at
+ )
+ return [
+ cast(func.coalesce(literal_column(OWED_NOTICE_STATE_SQL), ""), Text) == state,
+ cast(func.coalesce(literal_column(_OWED_NOTICE_ATTEMPTS_SQL), 0), Integer) == attempts,
+ third,
+ ]
+
+
+def owed_notice_absent() -> list[Any]:
+ """Predicate for "this row owes no notice yet", evaluated by SQLite.
+
+ The SQL twin of the Python pre-check every STAMPING writer makes
+ (``_owed_failure_notice_for_transition`` and ``stamp_binding_change_notice``:
+ "an existing notice is never overwritten"), and normalized to agree with it —
+ ``coalesce`` because an absent key, a null state and a notice stored as
+ something other than an object all read as "no notice" on the Python side and
+ would be NULL here, and NULL is not false.
+
+ It exists for the writer that has no terminal transition to ride. A stamp folded
+ into the UPDATE that moves ``status`` to ``failed`` is already atomic with the
+ thing it depends on; ``stamp_binding_change_notice`` runs on a LIVE run, before
+ ``complete()``, so its "no existing notice" read and its write are two statements
+ and something else can terminalize in between. Same reason
+ ``owed_notice_state_unchanged`` exists, same fix.
+
+ Reuses ``OWED_NOTICE_STATE_SQL`` verbatim rather than spelling the JSON path
+ again: this is a FILTER on a row located by primary key, so no plan depends on
+ its text, but a divergent copy of that expression is exactly how the eligibility
+ index was built and silently ignored twice.
+ """
+
+ return [cast(func.coalesce(literal_column(OWED_NOTICE_STATE_SQL), ""), Text) == ""]
+
+
+#: Mirror of ``core.failure_notices.NOTICE_KIND_*``, spelled as literals for the
+#: same reason ``RUN_INTERRUPTION_REASONS`` is below: ``core`` imports ``storage``,
+#: not the other way round. ``tests/test_harness_failure_visibility.py`` asserts the
+#: two agree so they cannot drift.
+#:
+#: The field is ADDITIVE. A notice stamped before it existed carries no ``kind`` and
+#: reads as ``failure``, and neither eligibility expression mentions it, so no index
+#: and no migration is involved.
+NOTICE_KIND_FAILURE = "failure"
+NOTICE_KIND_BINDING_CHANGE = "binding_change"
+
+#: How the drain proved delivery. ``receipt`` is a persisted ``messages`` row;
+#: ``delivery_only`` is a transport that returned an id whose row write failed —
+#: positive evidence the user was told, recorded explicitly rather than pretending
+#: the receipt exists.
+ACK_EVIDENCE_RECEIPT = "receipt"
+ACK_EVIDENCE_DELIVERY_ONLY = "delivery_only"
+
+#: Mirror of ``core.run_settlement.RUN_INTERRUPTION_REASONS``, spelled as literals
+#: for the same reason ``SWEEP_I18N_KEYS`` mirrors this module's sweep reasons:
+#: ``core`` imports ``storage``, not the other way round, and this module must stay
+#: importable without pulling ``core`` in. ``tests/test_harness_failure_visibility.py``
+#: asserts the two sets are equal so they cannot drift.
+RUN_INTERRUPTION_REASONS = frozenset(
+ {
+ "stopped",
+ "backend_refresh",
+ "evicted",
+ "restarted",
+ "lifetime_timeout",
+ SWEEP_REASON_ORPHANED,
+ }
+)
+
+#: ``metadata.interrupt_reason``, as literal SQL. ONE spelling, shared by every
+#: query that has to keep interruptions out of a definition's history — the health
+#: window and the failure streak — because a divergent copy is silent: the results
+#: stay correct and the planner just declines to match, which is precisely how the
+#: eligibility index was built and ignored twice (see ``OWED_NOTICE_STATE_SQL``).
+#:
+#: Literal, and unqualified, for the same two reasons as the eligibility
+#: expressions: SQLAlchemy renders a composed ``case()`` with BOUND PARAMETERS,
+#: which no index expression can match, and SQLite rejects the "." operator inside
+#: one. Nothing indexes this expression today — the streak's bound comes from
+#: ``(definition_id, created_at, id)`` and the interruption filter is evaluated on
+#: the handful of rows that seek touches — but keeping it index-shaped is what
+#: makes indexing it later a migration rather than a rewrite.
+#:
+#: The ``CASE json_valid`` guard is not optional: ``json_extract`` raises
+#: ``malformed JSON`` and fails the whole STATEMENT, so one unparseable blob would
+#: take out health for every definition in a batch, or the streak read for the
+#: whole drain. CASE evaluates lazily, so a malformed row degrades to "no interrupt
+#: reason" — the same way this module's Python ``_json_loads`` idiom degrades.
+INTERRUPT_REASON_SQL = (
+ "CASE WHEN (json_valid(metadata_json) = 1) "
+ "THEN json_extract(metadata_json, '$.interrupt_reason') END"
+)
+
+
+def _not_an_out_of_band_interruption() -> Any:
+ """SQL for "this row is not an out-of-band interruption".
+
+ MEMBERSHIP in ``RUN_INTERRUPTION_REASONS``, never ``interrupt_reason IS NOT
+ NULL``. Nullness would also exclude ``no_terminal_result`` /
+ ``refused_concurrent_turn`` / ``transport_unavailable`` / ``queue_hold_expired``,
+ which are the ordinary per-fire failures this whole feature exists to surface.
+ """
+
+ reason = literal_column(INTERRUPT_REASON_SQL)
+ return or_(reason.is_(None), reason.notin_(sorted(RUN_INTERRUPTION_REASONS)))
+
+#: Derived health, per definition. No new state: both counters come from one
+#: indexed query over ``agent_runs``, so nothing has to be kept in sync or
+#: backfilled.
+HEALTH_FAILING = "failing"
+HEALTH_DEGRADED = "degraded"
+HEALTH_HEALTHY = "healthy"
+#: What a definition reads when its own history cannot be classified — a malformed
+#: ``metadata_json`` row, in practice. Distinct from ``healthy`` on purpose: a
+#: health signal that cannot be computed must not read as a clean bill.
+HEALTH_UNKNOWN = "unknown"
+
+#: The health window: the last N verdicts OR the last T hours, whichever is
+#: shorter. Both bounds live in the ``WHERE``/``LIMIT`` of one query rather than
+#: one of them in prose — bounded only by count, a definition that failed once and
+#: then stopped firing would read ``failing`` forever with no user action able to
+#: clear it.
+HEALTH_WINDOW_RUNS = 10
+HEALTH_WINDOW_HOURS = 72
+
+
+def _owed_failure_notice_for_transition(
+ run_id: str,
+ *,
+ status: Any,
+ metadata: dict[str, Any],
+ now: str,
+) -> Optional[dict[str, Any]]:
+ """The notice a terminal transition owes, or ``None`` when it owes nothing.
+
+ Only a ``failed`` transition owes one. ``succeeded`` has nothing to report, and
+ ``canceled`` is reserved for explicit user intent (``SETTLEMENT_TERMINAL_STATUS``
+ maps only ``stopped`` there, and the guarded writers map a ``cancel_requested``
+ row there) — telling a user their run failed because they stopped it is noise.
+
+ An existing notice is never overwritten. Re-stamping would reset ``attempts``
+ and resurrect a dead letter, so a row that already carries a notice keeps the
+ one it has whatever later writer touches it.
+ """
+
+ if normalize_run_status(status) != "failed":
+ return None
+ existing = metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(existing, dict) and str(existing.get("state") or "").strip():
+ return None
+ reason = str(metadata.get("interrupt_reason") or "").strip() or None
+ return {
+ "state": NOTICE_PENDING,
+ "attempts": 0,
+ # ALWAYS an instant, never ``None``. A nullable column forces the query into
+ # ``(x IS NULL OR x <= now)``, and a disjunction cannot be an index range
+ # term — which is how the backoff stayed unindexed while the plan still
+ # named the index. ``now`` means "eligible immediately".
+ "next_attempt_at": now,
+ # Run-derived so two drain passes over the same row produce ONE identity,
+ # and so the identity is available at drain time at all: deriving it from
+ # whatever context a pass happens to build would key it off a per-pass
+ # ``task_execution_id`` — or off ``uuid4`` when the rebuild supplies none —
+ # and re-send the notice every tick.
+ #
+ # WHICH run-derived form matters, and the two lanes need different ones.
+ #
+ # An ordinary failure reuses the bare run id, because that is exactly what
+ # the LIVE path's ``_failure_identity`` resolves to (it prefers
+ # ``task_execution_id``, which ``_build_context`` sets to the run id). A
+ # different spelling here would produce a different ``native_message_id``,
+ # so the drain's ``agent_message_exists`` lookup could not see a
+ # notification the live path had already delivered — and would send a
+ # second one for the same failure, defeating the dedup the whole receipt
+ # protocol rests on.
+ #
+ # An interruption must NOT collide with that. A run terminalized out of band
+ # may already carry an ordinary backend-failure notice against the same
+ # execution, and a shared identity would let the dedup silently swallow the
+ # D1 notice telling the user a deploy killed their run — the notices that
+ # matter most, lost to the mechanism meant to prevent duplicates.
+ #
+ # Which lane this is comes from MEMBERSHIP in ``RUN_INTERRUPTION_REASONS``,
+ # never from the presence of a reason. ``interrupt_reason`` is the general
+ # marker for "terminalized by something other than its own backend result",
+ # and its commonest values — ``no_terminal_result``,
+ # ``refused_concurrent_turn``, ``transport_unavailable``,
+ # ``queue_hold_expired`` — are ordinary per-fire verdicts that belong in the
+ # suppressed failure lane. Minting ``interrupt:{run}:{reason}`` for those gave
+ # them an identity the live path never uses, and since the drain's id is
+ # AUTHORITATIVE that is one duplicate notification per failure.
+ "failure_id": (
+ f"interrupt:{run_id}:{reason}"
+ if reason in RUN_INTERRUPTION_REASONS
+ else run_id
+ ),
+ # Optional, and only ever a copy selector. The lane a notice belongs to is
+ # decided from this value's membership in ``RUN_INTERRUPTION_REASONS``, not
+ # from its presence.
+ "interrupt_reason": reason,
+ "error": None,
+ "ack_evidence": None,
+ "stamped_at": now,
+ }
+
+
+def _callback_parent_owns_failure_notice(
+ conn: Any,
+ *,
+ source_kind: Any,
+ parent_run_id: Any,
+) -> bool:
+ """Whether a callback child's parent already owns the user-visible notice."""
+
+ if str(source_kind or "").strip() != "callback":
+ return False
+ parent_id = str(parent_run_id or "").strip()
+ if not parent_id:
+ return False
+ raw_metadata = conn.execute(
+ select(agent_runs.c.metadata_json).where(agent_runs.c.id == parent_id).limit(1)
+ ).scalar_one_or_none()
+ metadata = _json_loads(raw_metadata, {})
+ notice = metadata.get(OWED_FAILURE_NOTICE_KEY) if isinstance(metadata, dict) else None
+ return isinstance(notice, dict) and bool(str(notice.get("state") or "").strip())
+
+
+def _merge_owed_failure_notice(
+ values: dict[str, Any],
+ *,
+ conn: Any,
+ run_id: str,
+ status: Any,
+ source_kind: Any,
+ parent_run_id: Any,
+ row_metadata_json: Any,
+ extra_metadata: Optional[dict[str, Any]] = None,
+ now: str,
+) -> None:
+ """Fold the owed notice into the ``metadata_json`` an UPDATE is about to write.
+
+ In-place on ``values`` so the stamp rides the SAME statement that transitions
+ the status. A stamp written by a second UPDATE could be lost to a crash between
+ the two, which is the whole failure mode the durable notice exists to close.
+
+ Takes the RAW COLUMN, not a decoded dict, because the decode is a decision this
+ choke point has to make rather than inherit. Every caller used to hand it
+ ``_json_loads(row["metadata_json"], {})`` and the fallback here turned anything
+ that was not a dict into ``{}``, so settling a row whose blob is unparseable — or
+ valid JSON that is not an object — REPLACED the column with just the notice.
+ Whatever those bytes were is not this feature's to destroy.
+
+ So an unreadable blob is READ-ONLY here: empty or NULL is a fresh ``{}`` base as
+ before, and anything non-empty that will not decode to an object skips the
+ metadata write ENTIRELY while the caller's terminal status/error/completed_at
+ transition still commits. The same answer the three precedents on this path
+ already give — the binding stamp refuses malformed rows through ``json_valid``,
+ ``update_owed_failure_notice`` returns ``None`` when the metadata is not a dict,
+ and ``list_owed_failure_notices`` excludes them ("a row whose metadata will not
+ parse cannot hold a readable notice anyway").
+
+ RESIDUAL, stated rather than hidden: such a row settles ``failed`` and never owes
+ a notice, so its failure is visible in the run list and in derived health but is
+ never delivered as a message. That was ALREADY true — the eligibility query
+ excludes malformed rows, so a notice written here would have been durable and
+ unreachable — and it is the direction every other reader on this path chose.
+ """
+
+ if isinstance(row_metadata_json, (bytes, bytearray)):
+ row_metadata_json = bytes(row_metadata_json).decode("utf-8", "replace")
+ if row_metadata_json is None or (
+ isinstance(row_metadata_json, str) and not row_metadata_json.strip()
+ ):
+ merged: dict[str, Any] = {}
+ else:
+ decoded = _json_loads(row_metadata_json if isinstance(row_metadata_json, str) else None, None)
+ if not isinstance(decoded, dict):
+ logger.warning(
+ "run %s has unreadable metadata_json; settling it without touching the "
+ "column, so it records no owed failure notice",
+ run_id,
+ )
+ return
+ merged = decoded
+ if extra_metadata:
+ merged.update(extra_metadata)
+ notice = None
+ if not _callback_parent_owns_failure_notice(
+ conn,
+ source_kind=source_kind,
+ parent_run_id=parent_run_id,
+ ):
+ notice = _owed_failure_notice_for_transition(
+ run_id,
+ status=status,
+ metadata=merged,
+ now=now,
+ )
+ if notice is None and not extra_metadata:
+ return
+ if notice is not None:
+ merged[OWED_FAILURE_NOTICE_KEY] = notice
+ values["metadata_json"] = _json_dumps(merged)
+
def normalize_run_status(status: Any) -> str:
return RUN_STATUS_ALIASES.get(str(status or "").strip(), str(status or "").strip() or "queued")
@@ -687,6 +1360,21 @@ def _stronger_terminal_status(current: Any, incoming: Any) -> str:
return incoming_status
+#: When a run SETTLED, as one expression shared by every read that orders a
+#: definition's history by it — the health window and the last-success seek.
+#:
+#: ``COALESCE`` rather than bare ``completed_at``: master does not treat terminal and
+#: ``completed_at IS NOT NULL`` as the same condition (``list_pending_callbacks`` tests
+#: them separately), and ordering must not silently reorder a row on the day one
+#: terminal writer stops stamping it.
+#:
+#: ONE OBJECT, not two spellings, for the reason ``INTERRUPT_REASON_SQL`` is also
+#: shared by name: this is the second key of ``ix_agent_runs_definition_settled``
+#: (migration ``20260728_0039``), and a retyped copy that drifts is one the planner
+#: silently stops matching while the results stay correct.
+_SETTLED_AT = func.coalesce(agent_runs.c.completed_at, agent_runs.c.created_at)
+
+
def _status_query_values(status: str) -> list[str]:
normalized = normalize_run_status(status)
values = [raw for raw, public in RUN_STATUS_ALIASES.items() if public == normalized]
@@ -862,6 +1550,104 @@ def _coalesced_agent_run_metadata(rows: dict[str, Any], run_ids: list[str]) -> d
return metadata
+def cancel_not_requested() -> Any:
+ """SQL for "still nobody has asked to cancel this run", evaluated by SQLite.
+
+ The SQL twin of the Python read ``bool(row["cancel_requested"])`` that every
+ guarded terminal writer branches on, and normalized to agree with it —
+ ``coalesce`` because a NULL column reads as "not requested" on the Python side and
+ NULL is not false here, ``CAST`` because JSON-free but untyped storage means a
+ text ``'0'`` must not read as truthy. Same relationship, and the same reason, as
+ ``notice_write_expectation`` and ``owed_notice_state_unchanged``.
+
+ WHY IT BELONGS IN THE TERMINAL ``WHERE``. ``cancel_run`` is a separate
+ transaction. It can land between a guarded writer's snapshot SELECT and that
+ writer's UPDATE — pysqlite starts no transaction for the read, so the snapshot is
+ genuinely older than the write — and ``cancel_requested`` is the ONLY signal
+ distinguishing "this run failed" from "the user pressed Stop". A writer that reads
+ it in Python and then does not re-assert it overwrites the Stop with ``failed``
+ and, worse, stamps an owed failure notice: the user is told their task broke
+ because they cancelled it.
+
+ A FILTER on a row already located by primary key, so no query plan depends on its
+ text.
+ """
+
+ return cast(func.coalesce(agent_runs.c.cancel_requested, 0), Integer) == 0
+
+
+def _cancel_aware_terminal_status(
+ row: Any,
+ requested_status: Any,
+) -> tuple[str, list[Any]]:
+ """Decide one terminal status and return the CAS guards for that snapshot."""
+
+ status = normalize_run_status(requested_status)
+ cancel_requested = bool(row["cancel_requested"])
+ if cancel_requested and status == "failed":
+ status = "canceled"
+ guards = [
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ ]
+ if not cancel_requested:
+ guards.append(cancel_not_requested())
+ return status, guards
+
+
+def _coalesced_terminal_write(
+ conn: Any, row: Any, *, run_id: str, ok: bool, error: Optional[str], now: str
+) -> Optional[tuple[dict[str, Any], list[Any]]]:
+ """The values and the CAS predicates one coalesced run's settlement needs.
+
+ ``None`` means "write nothing": the row was already settled by another actor.
+ Without that skip the UPDATE rewrites a row wholesale — a ``record_run_output``
+ success that landed first becomes ``failed`` — because the write carries no status
+ predicate of its own.
+
+ The two branches guard DIFFERENTLY, and that asymmetry is the point:
+
+ * the ``canceled`` branch is reached because the snapshot ALREADY saw the cancel,
+ so it keeps ``canceled`` in its status list and falls through — a
+ cancel-requested row goes on being normalized to ``canceled`` exactly as before,
+ and a second cancel landing under it changes nothing it would write;
+ * the ``succeeded``/``failed`` branch is reached because the snapshot saw NO
+ cancel, so it re-asserts that (``cancel_not_requested``) and DROPS ``canceled``
+ from its status list. Both halves are needed: the status predicate stops the
+ write landing on a row already flipped to ``canceled`` by ``cancel_run`` (which
+ does that for a queued row), and the ``cancel_requested`` predicate stops it
+ landing on a RUNNING row where ``cancel_run`` set only the flag.
+ """
+
+ status = normalize_run_status(row["status"])
+ if status in TERMINAL_RUN_STATUSES and status != "canceled":
+ return None
+ values: dict[str, Any] = {"updated_at": now}
+ nonterminal = _status_query_values("queued") + _status_query_values("running")
+ if bool(row["cancel_requested"]) or status == "canceled":
+ values["status"] = "canceled"
+ values["completed_at"] = now
+ predicates = [agent_runs.c.status.in_(nonterminal + _status_query_values("canceled"))]
+ else:
+ values["status"] = "succeeded" if ok else "failed"
+ values["completed_at"] = now
+ if error is not None:
+ values["error"] = error
+ predicates = [agent_runs.c.status.in_(nonterminal), cancel_not_requested()]
+ _merge_owed_failure_notice(
+ values,
+ conn=conn,
+ run_id=run_id,
+ status=values["status"],
+ source_kind=row["source_kind"],
+ parent_run_id=row["parent_run_id"],
+ row_metadata_json=row["metadata_json"],
+ now=now,
+ )
+ return values, predicates
+
+
def complete_coalesced_agent_runs_for_workbench_in_connection(
conn: Any,
run_ids: list[str],
@@ -888,21 +1674,36 @@ def complete_coalesced_agent_runs_for_workbench_in_connection(
completed_ids: list[str] = []
for run_id in normalized_run_ids:
row = rows.get(run_id)
- if row is None:
- continue
- status = normalize_run_status(row["status"])
- values: dict[str, Any] = {"updated_at": now}
- if bool(row["cancel_requested"]) or status == "canceled":
- values["status"] = "canceled"
- values["completed_at"] = now
- else:
- values["status"] = "succeeded" if ok else "failed"
- values["completed_at"] = now
- if error is not None:
- values["error"] = error
- result = conn.execute(update(agent_runs).where(agent_runs.c.id == run_id).values(**values))
- if result.rowcount:
- completed_ids.append(run_id)
+ # ONE re-read on a refused write, never a loop. A refusal means the row moved
+ # under the batch snapshot, so the decision has to be made again from what the
+ # row NOW says — otherwise a run the user cancelled mid-flight is simply left
+ # ``running`` and nothing ever settles it, which trades a wrong status for a
+ # zombie. The retry is bounded at one because its own snapshot already sees the
+ # cancel: a second racing writer would have to land inside the retry itself,
+ # and this runs on the Workbench completion path where an unbounded retry is
+ # its own outage.
+ for final_attempt in (False, True):
+ if row is None:
+ break
+ plan = _coalesced_terminal_write(
+ conn, row, run_id=run_id, ok=ok, error=error, now=now
+ )
+ if plan is None:
+ break
+ values, predicates = plan
+ result = conn.execute(
+ update(agent_runs).where(agent_runs.c.id == run_id).where(*predicates).values(**values)
+ )
+ if result.rowcount:
+ completed_ids.append(run_id)
+ break
+ if final_attempt:
+ break
+ row = (
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1))
+ .mappings()
+ .first()
+ )
_defer_run_ids_updated_from_connection(conn, completed_ids)
return completed_ids
@@ -1348,6 +2149,7 @@ class SQLiteBackgroundTaskStore:
ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
if not background_tables_ready(self.db_path):
initialize_background_tables(self.db_path)
+ ensure_background_indexes(self.db_path)
self.engine = create_sqlite_engine(self.db_path)
self._probe = SqliteInvalidationProbe(self.engine)
@@ -1436,6 +2238,31 @@ class SQLiteBackgroundTaskStore:
self._scheduled_task_values(payload), expect=expect, definition_type="scheduled task"
)
+ def upsert_scheduled_task_with_binding_notice(
+ self,
+ payload: dict[str, Any],
+ *,
+ expect: DefinitionWriteExpectation,
+ notice: dict[str, Any],
+ ) -> bool:
+ """Commit a recovery marker and its owed notice as one durable effect."""
+
+ with self.engine.begin() as conn:
+ self.stamp_binding_change_notice(_conn=conn, **notice)
+ landed = upsert_definition_in_connection(
+ conn,
+ self._scheduled_task_values(payload),
+ expect=expect,
+ definition_type="scheduled task",
+ )
+ if not landed:
+ # A normal return from ``engine.begin()`` COMMITs. The notice was
+ # written earlier in this transaction, so an explicit rollback is
+ # what keeps a refused definition CAS from publishing stale news.
+ conn.rollback()
+ return False
+ return True
+
def remove_task(self, definition_id: str, *, deleted_at: Optional[str] = None) -> bool:
with self.engine.begin() as conn:
result = conn.execute(
@@ -2217,6 +3044,134 @@ class SQLiteBackgroundTaskStore:
)
_publish_run_rows_updated([row_to_publish])
+ def definition_lifecycle_state(
+ self, definition_id: str, *, definition_type: str = "task"
+ ) -> Optional[str]:
+ """One definition's canonical lifecycle state, from the shared expression.
+
+ ``definition_lifecycle_expression`` evaluated for a single row — the same
+ CASE every list and count surface reads, so a consumer rendering copy
+ beside the badge cannot reach a different answer by re-deriving the state
+ in Python. The expression resolves an offset-free ``run_at`` in the stored
+ IANA timezone through the same rule as ``compute_next_run_at``; the state
+ and the displayed next fire therefore cannot disagree during the zone's
+ UTC-offset interval. ``None`` when the definition row does not exist.
+ """
+
+ resolved = str(definition_id or "").strip()
+ if not resolved:
+ return None
+ statement = (
+ select(definition_lifecycle_expression(definition_type))
+ .select_from(run_definitions)
+ .where(run_definitions.c.id == resolved)
+ .limit(1)
+ )
+ with self.engine.connect() as conn:
+ row = conn.execute(statement).first()
+ return None if row is None else str(row[0])
+
+ def run_callback_state(self, run_id: str) -> Optional[str]:
+ """This run's effective callback delivery state, or ``None`` without one.
+
+ Read FRESH, at decision time, rather than trusted from the drain's listing:
+ the owed-notice batch is listed once per pass and each row is then decided
+ one at a time, so by the time a row is reached ``_drain_callbacks`` may
+ already have moved its callback from ``pending`` to ``sent`` — and the
+ notice decision keyed on the stale copy would defer a row whose blocker is
+ already resolved, or worse, deliver beside a callback that just landed.
+ A parent marked ``sent`` only proves that ``_drain_callbacks`` enqueued the
+ callback child. The user has the callback only after that child succeeds and
+ records delivery evidence. A persisted result row is evidence only while its
+ target Session is admitted by the Inbox; a recorded native send id for a real
+ IM conversation is transport evidence in its own right because it is returned
+ only after delivery. Archiving or deleting the local Session afterwards cannot
+ revoke that completed send. Workbench ids are synthetic and never qualify on
+ their own, while a receipt in suppressed background history proves persistence,
+ not visibility. This read joins the child and target Session and projects the
+ state the notice lane actually needs: queued/running is pending, succeeded with
+ effective delivery evidence is sent, and every other terminal outcome releases
+ the notice as failed. All three lookups are primary-key probes in one statement.
+
+ ``None`` means "no callback exists for this run" (no target session), which
+ is different from a callback whose status column is empty — a target with
+ no recorded status has never been armed, and the caller treats both as
+ no-shield.
+ """
+
+ parent = agent_runs.alias("callback_parent")
+ child = agent_runs.alias("callback_child")
+ callback_session = agent_sessions.alias("callback_session")
+ persisted_receipt = (
+ select(literal(1))
+ .select_from(messages)
+ .where(messages.c.session_id == child.c.session_id)
+ .where(messages.c.type == "result")
+ .where(func.json_valid(messages.c.metadata_json) == 1)
+ .where(
+ cast(func.json_extract(messages.c.metadata_json, "$.run_id"), Text)
+ == child.c.id
+ )
+ .correlate(child)
+ .exists()
+ )
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(
+ parent.c.callback_session_id,
+ parent.c.callback_status,
+ parent.c.callback_run_id,
+ child.c.status,
+ persisted_receipt,
+ callback_session.c.status,
+ callback_session.c.visibility,
+ child.c.legacy_session_key,
+ child.c.message_ids_json,
+ )
+ .select_from(
+ parent.outerjoin(child, child.c.id == parent.c.callback_run_id).outerjoin(
+ callback_session,
+ callback_session.c.id == child.c.session_id,
+ )
+ )
+ .where(parent.c.id == str(run_id))
+ .limit(1)
+ ).first()
+ if row is None or not str(row[0] or "").strip():
+ return None
+ callback_status = str(row[1] or "").strip() or None
+ callback_run_id = str(row[2] or "").strip()
+ if callback_status != "sent" or not callback_run_id:
+ return callback_status
+ child_status = normalize_run_status(row[3]) if row[3] is not None else ""
+ if child_status in {"queued", "running"}:
+ return "pending"
+ target_key_parts = self._parse_session_key(row[7])
+ message_ids = _json_loads(row[8], [])
+ descriptor = (
+ PLATFORM_REGISTRY.get(target_key_parts[0])
+ if target_key_parts is not None
+ else None
+ )
+ has_native_im_receipt = (
+ descriptor is not None
+ and descriptor.kind == "im"
+ and target_key_parts is not None
+ and target_key_parts[1] in {"channel", "user"}
+ and isinstance(message_ids, list)
+ and any(str(message_id or "").strip() for message_id in message_ids)
+ )
+ target_is_visible = (
+ str(row[5] or "").strip() != "archived"
+ and str(row[6] or "").strip() in INBOX_SESSION_VISIBILITIES
+ )
+ has_visible_persisted_receipt = bool(row[4]) and target_is_visible
+ if child_status == "succeeded" and (
+ has_native_im_receipt or has_visible_persisted_receipt
+ ):
+ return "sent"
+ return "failed"
+
def update_callback_status(
self,
run_id: str,
@@ -2444,28 +3399,57 @@ class SQLiteBackgroundTaskStore:
if deferred_result_text is not None
else visible_text
)
- terminal_values: dict[str, Any] = {
- "status": normalize_run_status(effective_terminal_status),
+ base_terminal_values: dict[str, Any] = {
# Structured outputs remain available in result_payload, but
# result_text is the one terminal result used by callbacks.
"result_text": terminal_result_text,
- "completed_at": now,
- "updated_at": now,
}
if effective_terminal_error is not None:
- terminal_values["error"] = str(effective_terminal_error)
- transition = conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .where(
- agent_runs.c.status.in_(
- _status_query_values("queued")
- + _status_query_values("running")
- )
+ base_terminal_values["error"] = str(effective_terminal_error)
+
+ # One bounded re-read mirrors ``settle_run_terminal``. A Stop on a
+ # running row changes only ``cancel_requested``; the first CAS loses,
+ # then the second decision sees the flag and settles canceled.
+ terminal_row = row
+ for final_attempt in (False, True):
+ if normalize_run_status(terminal_row["status"]) in TERMINAL_RUN_STATUSES:
+ break
+ status, guards = _cancel_aware_terminal_status(
+ terminal_row, effective_terminal_status
)
- .values(**terminal_values)
- )
- terminal_transition = bool(transition.rowcount)
+ terminal_values = {
+ **base_terminal_values,
+ "status": status,
+ "completed_at": now,
+ "updated_at": now,
+ }
+ _merge_owed_failure_notice(
+ terminal_values,
+ conn=conn,
+ run_id=run_id,
+ status=status,
+ source_kind=terminal_row["source_kind"],
+ parent_run_id=terminal_row["parent_run_id"],
+ row_metadata_json=terminal_row["metadata_json"],
+ now=now,
+ )
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(*guards)
+ .values(**terminal_values)
+ )
+ if transition.rowcount:
+ terminal_transition = True
+ break
+ if final_attempt:
+ break
+ terminal_row = (
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1))
+ .mappings()
+ .one()
+ )
+ row = terminal_row
if not terminal_transition:
# The row was already terminal, so the guarded UPDATE above
# matched nothing and ``result_text`` -- the one terminal
@@ -2547,6 +3531,9 @@ class SQLiteBackgroundTaskStore:
result_text: Optional[str] = None,
metadata: Optional[dict[str, Any]] = None,
updated_at: Optional[str] = None,
+ task_id: Optional[str] = None,
+ session_key: Optional[str] = None,
+ session_id: Optional[str] = None,
) -> Optional[str]:
"""Terminalize a non-terminal run in one guarded write.
@@ -2562,6 +3549,14 @@ class SQLiteBackgroundTaskStore:
write. Rows carrying a deferred terminal intent are left alone — the Activity
lifecycle owns those.
+ ``task_id`` / ``session_key`` / ``session_id`` are the identity columns the
+ claimed-request completion resolves late (a ``scheduled`` row learns its real
+ target only once the task definition has been read). They are facts about
+ WHICH conversation the run belongs to, not claims about its outcome, so they
+ are written whether or not the status transition lands — otherwise routing
+ the completion through this guarded writer would lose them on exactly the
+ rows another actor settled first.
+
Returns the terminal status actually written, or ``None`` when nothing was
written (already terminal, deferred, or missing).
"""
@@ -2573,46 +3568,77 @@ class SQLiteBackgroundTaskStore:
row = conn.execute(
select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
).mappings().first()
- if not row or normalize_run_status(row["status"]) in TERMINAL_RUN_STATUSES:
- return None
- result_payload = _json_loads(row["result_payload_json"], {})
- if isinstance(result_payload, dict) and result_payload.get("deferred_terminal_status"):
- # The Activity lifecycle already owns this row's terminal state.
+ if not row:
return None
- status = normalize_run_status(terminal_status)
- if row["cancel_requested"] and status == "failed":
- status = "canceled"
- values: dict[str, Any] = {
- "status": status,
- "completed_at": now,
- "updated_at": now,
- }
- if error is not None:
- values["error"] = str(error)
- if result_text is not None:
- values["result_text"] = str(result_text)
- if metadata:
- merged = _json_loads(row["metadata_json"], {})
- if not isinstance(merged, dict):
- merged = {}
- merged.update(metadata)
- values["metadata_json"] = _json_dumps(merged)
- transition = conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .where(
- agent_runs.c.status.in_(
- _status_query_values("queued") + _status_query_values("running")
- )
+ identity: dict[str, Any] = {}
+ if task_id is not None:
+ identity["definition_id"] = task_id
+ if session_key is not None:
+ identity["legacy_session_key"] = session_key
+ if session_id is not None:
+ identity["session_id"] = session_id
+ if identity:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(**identity, updated_at=now)
)
- .values(**values)
- )
- if transition.rowcount:
- written_status = status
- row_to_publish = dict(
- conn.execute(
- select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
- ).mappings().one()
+ # ONE re-read on a refused write, never a loop, for the reason
+ # ``cancel_not_requested`` gives: refusing the write is only half the fix,
+ # because a run left ``running`` with nothing to settle it is the zombie
+ # this writer exists to prevent. The second pass re-decides from the row as
+ # it now stands, which is where the cancel is visible, so it writes
+ # ``canceled`` rather than being refused again.
+ for final_attempt in (False, True):
+ if row is None:
+ break
+ if normalize_run_status(row["status"]) in TERMINAL_RUN_STATUSES:
+ return None
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if isinstance(result_payload, dict) and result_payload.get("deferred_terminal_status"):
+ # The Activity lifecycle already owns this row's terminal state.
+ return None
+ status, guards = _cancel_aware_terminal_status(row, terminal_status)
+ values: dict[str, Any] = {
+ "status": status,
+ "completed_at": now,
+ "updated_at": now,
+ }
+ if error is not None:
+ values["error"] = str(error)
+ if result_text is not None:
+ values["result_text"] = str(result_text)
+ _merge_owed_failure_notice(
+ values,
+ conn=conn,
+ run_id=run_id,
+ status=status,
+ source_kind=row["source_kind"],
+ parent_run_id=row["parent_run_id"],
+ row_metadata_json=row["metadata_json"],
+ extra_metadata=metadata or None,
+ now=now,
+ )
+ # ``_cancel_aware_terminal_status`` re-asserts the cancellation fact
+ # this branch read. A running cancel changes only the flag, so a status
+ # predicate alone cannot stop a stale failure from overwriting Stop.
+ transition = conn.execute(
+ update(agent_runs).where(agent_runs.c.id == run_id).where(*guards).values(**values)
+ )
+ if transition.rowcount:
+ written_status = status
+ row_to_publish = dict(
+ conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().one()
+ )
+ break
+ if final_attempt:
+ break
+ row = (
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1))
+ .mappings()
+ .first()
)
_publish_run_rows_updated([row_to_publish])
return written_status
@@ -2696,63 +3722,89 @@ class SQLiteBackgroundTaskStore:
).mappings().first()
if not row:
return False
- result_payload = _json_loads(row["result_payload_json"], {})
- if not isinstance(result_payload, dict):
- return False
- deferred_status = str(result_payload.get("deferred_terminal_status") or "").strip()
- if not deferred_status:
- return False
- result_payload.pop("deferred_terminal_status", None)
- deferred_error = result_payload.pop("deferred_terminal_error", None)
- deferred_result_text = result_payload.pop("deferred_terminal_result_text", None)
- status = (
- _stronger_terminal_status(deferred_status, terminal_status)
- if terminal_status
- else normalize_run_status(deferred_status)
- )
- values: dict[str, Any] = {
- "status": status,
- "completed_at": now,
- "updated_at": now,
- "result_payload_json": _json_dumps(result_payload),
- }
- effective_error = deferred_error if deferred_error is not None else error
- if effective_error is not None:
- values["error"] = str(effective_error)
- if deferred_result_text is not None:
- values["result_text"] = str(deferred_result_text)
- transition = conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .where(
- agent_runs.c.status.in_(
- _status_query_values("queued")
- + _status_query_values("running")
- )
+ # A deferred failure is still subordinate to Stop. Re-decide once when
+ # the cancellation CAS loses so a running row becomes canceled instead
+ # of remaining a zombie or receiving a false failure notice.
+ for final_attempt in (False, True):
+ if normalize_run_status(row["status"]) in TERMINAL_RUN_STATUSES:
+ break
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if not isinstance(result_payload, dict):
+ break
+ deferred_status = str(
+ result_payload.get("deferred_terminal_status") or ""
+ ).strip()
+ if not deferred_status:
+ break
+ result_payload.pop("deferred_terminal_status", None)
+ deferred_error = result_payload.pop("deferred_terminal_error", None)
+ deferred_result_text = result_payload.pop(
+ "deferred_terminal_result_text", None
)
- .values(**values)
- )
- transitioned = bool(transition.rowcount)
- if transitioned:
- row_to_publish = dict(
- conn.execute(
- select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
- ).mappings().one()
+ requested_status = (
+ _stronger_terminal_status(deferred_status, terminal_status)
+ if terminal_status
+ else normalize_run_status(deferred_status)
)
- _publish_run_rows_updated([row_to_publish])
- return transitioned
-
- def find_callback_run(
- self,
- *,
- parent_run_id: str,
- source_actor: str,
- ) -> Optional[dict[str, Any]]:
- """Return the callback Run for one parent callback identity."""
-
- with self.engine.connect() as conn:
- row = conn.execute(
- select(agent_runs)
+ status, guards = _cancel_aware_terminal_status(row, requested_status)
+ values: dict[str, Any] = {
+ "status": status,
+ "completed_at": now,
+ "updated_at": now,
+ "result_payload_json": _json_dumps(result_payload),
+ }
+ effective_error = deferred_error if deferred_error is not None else error
+ if effective_error is not None:
+ values["error"] = str(effective_error)
+ if deferred_result_text is not None:
+ values["result_text"] = str(deferred_result_text)
+ _merge_owed_failure_notice(
+ values,
+ conn=conn,
+ run_id=run_id,
+ status=status,
+ source_kind=row["source_kind"],
+ parent_run_id=row["parent_run_id"],
+ row_metadata_json=row["metadata_json"],
+ now=now,
+ )
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(*guards)
+ .values(**values)
+ )
+ if transition.rowcount:
+ transitioned = True
+ row_to_publish = dict(
+ conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().one()
+ )
+ break
+ if final_attempt:
+ break
+ row = (
+ conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1))
+ .mappings()
+ .first()
+ )
+ if row is None:
+ break
+ _publish_run_rows_updated([row_to_publish])
+ return transitioned
+
+ def find_callback_run(
+ self,
+ *,
+ parent_run_id: str,
+ source_actor: str,
+ ) -> Optional[dict[str, Any]]:
+ """Return the callback Run for one parent callback identity."""
+
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agent_runs)
.where(agent_runs.c.run_type == "agent_run")
.where(agent_runs.c.source_kind == "callback")
.where(agent_runs.c.parent_run_id == parent_run_id)
@@ -2813,27 +3865,37 @@ class SQLiteBackgroundTaskStore:
Returns ``True`` when a write actually happened.
"""
+ instant = at or _utc_now_iso()
+ raw_metadata = func.coalesce(agent_runs.c.metadata_json, "{}")
+ metadata = case(
+ (func.json_valid(raw_metadata) == 1, raw_metadata),
+ else_=literal("{}"),
+ )
with self.engine.begin() as conn:
- row = conn.execute(
- select(agent_runs.c.status, agent_runs.c.metadata_json)
- .where(agent_runs.c.id == run_id)
- .limit(1)
- ).mappings().first()
- if not row or normalize_run_status(row["status"]) != "queued":
- return False
- metadata = _json_loads(row["metadata_json"], {})
- if not isinstance(metadata, dict):
- metadata = {}
- if metadata.get("last_skip_reason") == reason:
- return False
- metadata["last_skip_reason"] = reason
- metadata["last_skip_at"] = at or _utc_now_iso()
- conn.execute(
+ result = conn.execute(
update(agent_runs)
.where(agent_runs.c.id == run_id)
- .values(metadata_json=_json_dumps(metadata))
+ .where(agent_runs.c.status.in_(_status_query_values("queued")))
+ .where(
+ cast(
+ func.coalesce(
+ func.json_extract(metadata, "$.last_skip_reason"), ""
+ ),
+ Text,
+ )
+ != reason
+ )
+ .values(
+ metadata_json=func.json_set(
+ metadata,
+ "$.last_skip_reason",
+ reason,
+ "$.last_skip_at",
+ instant,
+ )
+ )
)
- return True
+ return bool(result.rowcount)
def _clear_transport_skip_evidence(self, run_ids: set[str]) -> int:
"""Forget a ``transport_unavailable`` stamp whose outage has demonstrably ended.
@@ -2849,29 +3911,32 @@ class SQLiteBackgroundTaskStore:
it will be reconsidered, with a fresh ``last_skip_at``, next sweep.
"""
- cleared = 0
+ normalized_ids = sorted({str(run_id) for run_id in run_ids if str(run_id).strip()})
+ if not normalized_ids:
+ return 0
+ raw_metadata = func.coalesce(agent_runs.c.metadata_json, "{}")
+ metadata = case(
+ (func.json_valid(raw_metadata) == 1, raw_metadata),
+ else_=literal("{}"),
+ )
with self.engine.begin() as conn:
- for run_id in sorted(run_ids):
- row = conn.execute(
- select(agent_runs.c.status, agent_runs.c.metadata_json)
- .where(agent_runs.c.id == run_id)
- .limit(1)
- ).mappings().first()
- if not row or normalize_run_status(row["status"]) != "queued":
- continue
- metadata = _json_loads(row["metadata_json"], {})
- if not isinstance(metadata, dict):
- continue
- if metadata.get("last_skip_reason") != SKIP_REASON_TRANSPORT_UNAVAILABLE:
- continue
- metadata.pop("last_skip_reason", None)
- metadata.pop("last_skip_at", None)
- conn.execute(
- update(agent_runs)
- .where(agent_runs.c.id == run_id)
- .values(metadata_json=_json_dumps(metadata))
+ result = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id.in_(normalized_ids))
+ .where(agent_runs.c.status.in_(_status_query_values("queued")))
+ .where(
+ cast(func.json_extract(metadata, "$.last_skip_reason"), Text)
+ == SKIP_REASON_TRANSPORT_UNAVAILABLE
+ )
+ .values(
+ metadata_json=func.json_remove(
+ metadata,
+ "$.last_skip_reason",
+ "$.last_skip_at",
+ )
)
- cleared += 1
+ )
+ cleared = int(result.rowcount or 0)
if cleared:
logger.debug("Cleared recovered transport skip evidence on %s harness run(s)", cleared)
return cleared
@@ -3070,6 +4135,1147 @@ class SQLiteBackgroundTaskStore:
)
return swept
+ # --- owed failure notices -------------------------------------------------
+
+ def list_owed_failure_notices(self, *, limit: int = 20, now: Optional[str] = None) -> list[dict[str, Any]]:
+ """Runs owing a user-visible failure notice whose backoff has elapsed.
+
+ Ordered by ``(created_at, id)`` so the drain sees a streak's earliest row
+ first and the canonical choice is deterministic.
+
+ **Eligibility is decided in SQL, before the limit.** An earlier revision
+ filtered the notice state in Python and argued there was no filter-after-LIMIT
+ hazard because the limit applied after ordering. That was right about
+ correctness and silent about cost, which is the part that mattered: with no
+ state predicate and no SQL ``LIMIT``, the steady state — every historical
+ failure already ``sent``/``skipped``/``failed`` — made this tick scan and
+ JSON-decode the ENTIRE failed-run history every two seconds to return an empty
+ list, at a cost growing without bound over the database's lifetime.
+
+ ``json_valid`` guards the extraction inside a ``CASE``, for the same reason as
+ the health window and with a sharper consequence: ``json_extract`` raises
+ ``malformed JSON`` and fails the whole STATEMENT, so one unparseable blob would
+ stop the drain finding ANY owed notice — every failure notification in the
+ system silenced by a single bad row. A row whose metadata will not parse cannot
+ hold a readable notice anyway, so it is excluded rather than rescued.
+
+ The Python re-check below is kept as a second layer: it tolerates a notice
+ stored as something other than a dict, and it is now cheap because only
+ eligible rows reach it. It may only re-decide rows whose BLOB CHANGED between
+ the seek and the read — it may never be narrower than the predicate above.
+ Narrower means a row that is selected inside the limit and dropped outside it,
+ with no state transition to stop it being selected again: a permanent hole in
+ the batch. ``owed_notice_eligible`` is therefore normalized to the comparison
+ SQLite makes here, storage classes and all.
+ """
+
+ instant = now or _utc_now_iso()
+ owed: list[dict[str, Any]] = []
+ # Literal SQL, NOT a composed ``case(...)``: SQLAlchemy renders the ``1`` and
+ # the JSON path as BOUND PARAMETERS, and SQLite cannot match an index
+ # expression against a query expression containing binds. The composed form
+ # produced a correct result and silently kept the full scan — the index was
+ # built, ignored, and nothing said so.
+ #
+ # These strings must stay byte-identical to the migration's; the query-plan
+ # test fails if they drift, which is what keeps the duplication honest.
+ notice_state = literal_column(OWED_NOTICE_STATE_SQL)
+ notice_kind = literal_column(OWED_NOTICE_KIND_SQL)
+ next_attempt_at = literal_column(OWED_NOTICE_NEXT_ATTEMPT_SQL)
+ stmt = (
+ # Both ordinary terminal VERDICTS, not just ``failed``. A binding-change notice is
+ # stamped on the run that recovered the binding, and when the rebound
+ # retry works that run settles ``succeeded`` — filtering on ``failed``
+ # made the notice durable and permanently unreachable, which is the
+ # silent-replacement bug this widening exists to close.
+ #
+ # ``canceled`` is admitted only for that same notice kind. Stop can land
+ # AFTER the rebind and its notice commit but before terminal settlement;
+ # the rebind still happened, its durable marker prevents a later restamp,
+ # and excluding the row would strand the pending notice forever. Ordinary
+ # canceled runs still owe nothing and remain outside the drain.
+ #
+ # Free of cost and of plan risk: ``ix_agent_runs_owed_notice`` indexes
+ # ``(state, next_attempt_at, created_at, id)`` and NOT ``status``, so the
+ # seek is on the notice state either way and ``status``/``kind`` stay a
+ # post-filter over the handful of rows that actually own a pending notice.
+ select(agent_runs)
+ .where(
+ or_(
+ agent_runs.c.status.in_(
+ [*_status_query_values("failed"), *_status_query_values("succeeded")]
+ ),
+ and_(
+ agent_runs.c.status.in_(_status_query_values("canceled")),
+ notice_kind == NOTICE_KIND_BINDING_CHANGE,
+ ),
+ )
+ )
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(notice_state == NOTICE_PENDING)
+ # A pure range term, so the index can CONSTRAIN it instead of the engine
+ # filtering every pending entry per row. ISO-8601 in UTC sorts
+ # lexicographically, which every other timestamp comparison here relies on.
+ .where(next_attempt_at <= instant)
+ # Ordered on the index prefix, so there is no temp sort AND the LIMIT can
+ # short-circuit. Batch order is not load-bearing for correctness — the
+ # canonical notice is chosen by ``failure_streak_decision``, not by arrival
+ # order — and least-recently-deferred-first is the fairer sequence anyway.
+ .order_by(next_attempt_at, agent_runs.c.created_at, agent_runs.c.id)
+ .limit(max(1, limit))
+ )
+ with self.engine.connect() as conn:
+ for row in conn.execute(stmt).mappings():
+ notice = _json_loads(row["metadata_json"], {})
+ notice = notice.get(OWED_FAILURE_NOTICE_KEY) if isinstance(notice, dict) else None
+ # The same predicate the delivery pass re-checks before it claims, so
+ # the listing and the claim cannot disagree about what "eligible" is.
+ # A row whose wait has not elapsed is skipped rather than delivered,
+ # which is what keeps a failing transport from firing every 2 s — and,
+ # since a claimant's lease is written to the same field, what keeps a
+ # second owner out of a delivery already in flight.
+ if not owed_notice_eligible(notice, instant):
+ continue
+ owed.append(self._run_from_row(row))
+ if len(owed) >= max(1, limit):
+ break
+ return owed
+
+ def stamp_binding_change_notice(
+ self,
+ run_id: str,
+ *,
+ task_id: str,
+ signature: str,
+ action: str,
+ reason: str,
+ previous_session_id: Optional[str],
+ new_session_id: Optional[str],
+ settings_preserved: bool,
+ now: Optional[str] = None,
+ _conn: Any = None,
+ ) -> Optional[dict[str, Any]]:
+ """Owe the user a notice about a session binding that was replaced.
+
+ The one notice a TERMINAL TRANSITION cannot stamp. Every other owed notice is
+ folded into the UPDATE that moves a run to ``failed``
+ (``_merge_owed_failure_notice``), which is what makes a settlement path added
+ later inherit it for free. A rebind whose retry SUCCEEDS produces no failed
+ transition at all — ``error`` is ``None`` and the row settles ``succeeded`` —
+ so the news that the user's pinned session was swapped had no writer and no
+ reader. This is that writer, and it is deliberately the only one. The normal
+ caller commits this notice and the definition's durable dedup marker in the
+ same transaction, so neither effect can survive without the other.
+
+ Everything downstream is unchanged. The blob has the same shape as a failure
+ notice plus an additive ``kind``/``binding``, so the drain's receipt, backoff
+ and dead-letter protocol carries it without a parallel path.
+
+ Identity is ``binding:{task_id}:{signature}`` — the transition's own key, not
+ the run's. A rebind that somehow re-stamps against a later run therefore
+ collides on the notification the user already has, rather than sending a
+ second one; and it can never collide with the bare run id an ordinary backend
+ failure uses for the SAME run, which is the mistake the interruption lane
+ already had to be taught (see ``_owed_failure_notice_for_transition``).
+
+ Never over an existing notice: a genuine failure notice on this row outranks
+ the binding news, and re-stamping would reset ``attempts`` and resurrect a
+ dead letter.
+
+ And never onto a run something else TERMINALIZED in the meantime. This is the
+ one owed-notice writer with no terminal transition to ride — it runs on a live
+ run, before ``complete()`` — so its read and its write are two statements, and
+ under pysqlite ``engine.begin()`` holds no lock across the first (no ``BEGIN``
+ is emitted for a bare SELECT; see ``upsert_definition_in_connection`` and
+ ``update_owed_failure_notice``). Round 7 audited this stamp and excused it as
+ "a pre-read stamp", which was right about the ORDER and wrong about the
+ CONNECTION: a second one can settle the row in that gap, and there are three
+ damage directions — two the CAS must refuse, and one it must NOT.
+
+ * The terminal writer settles ``failed`` and stamps its OWN failure notice in
+ the same UPDATE (``_merge_owed_failure_notice``), and the whole-blob write
+ this used to issue put the binding blob over the top — the user told their
+ session was swapped and never told the run failed.
+ * The row settles ``canceled`` before this CAS, so the stamp is refused: a Stop
+ that already won outranks binding news. This is distinct from Stop landing
+ AFTER the stamp committed. In that later ordering the rebind already happened
+ and its marker prevents a restamp, so ``list_owed_failure_notices`` admits
+ canceled rows carrying this specific notice kind.
+ * The row settles ``succeeded`` — the ORDINARY outcome of the rebind this
+ notice exists for — and a status CAS that refuses here loses the notice
+ PERMANENTLY rather than deferring it. A successful settlement writes no
+ notice of its own, so the slot is left empty. The store-level method also
+ remains correct when called outside the combined marker transaction: refusing
+ this direction would silently lose the news that the pinned session changed.
+
+ So the read is re-asserted in the WHERE clause — the status the SELECT saw,
+ verbatim, no cancellation request, plus ``owed_notice_absent()`` — and the
+ loss is read off ``rowcount``, the ``DefinitionWriteExpectation`` idiom
+ ``update_owed_failure_notice`` already follows. ``json_set`` rather than a
+ composed blob for the same atomicity reason one level down: the run is LIVE
+ here, so sibling metadata
+ keys are being written concurrently (the sweep's ``interrupt_reason``, the
+ settler's ``ok`` marker), and a status+notice CAS over a whole-blob write
+ would still clobber whichever of those landed in the gap. Only the one key
+ this method owns is written.
+
+ A lost CAS then re-reads the row ONCE and decides on the WINNER's status. The
+ policy is TOTAL over the terminal statuses, so no outcome falls through to an
+ accidental default:
+
+ ================ ==================================================
+ winner outcome
+ ================ ==================================================
+ ``failed`` refuse — its own failure notice owns the slot and
+ outranks this news
+ ``canceled`` refuse — the user's Stop won before this stamp;
+ only a binding notice committed before a later
+ Stop is admitted by the drain
+ ``succeeded`` STAMP — no other writer owes anything, the slot is
+ legitimately owed, and
+ ``list_owed_failure_notices`` selects ``succeeded``
+ precisely to carry it
+ anything else refuse — still live (nothing terminalized, so the
+ loss was the notice slot or a malformed blob),
+ slot occupied, or unreadable metadata
+ ================ ==================================================
+
+ EXACTLY ONE retry, and the reason is CONVERGENCE rather than luck. It is NOT
+ that the first no-op UPDATE holds a write lock — an UPDATE that matches zero
+ rows may never escalate to RESERVED, so nothing here can be argued from lock
+ acquisition. It is that ``succeeded`` is TERMINAL to every GUARDED writer:
+ ``settle_run_terminal`` and the rest of the terminal set are conditioned on a
+ non-terminal status, so none of them can move the row once the re-read sees
+ ``succeeded``, and the retry's status predicate cannot go stale a second time.
+ The notice slot is equally settled: another stamp on this run sees the occupied
+ slot, and no terminal transition remains to stamp a failure notice.
+ The remaining writer that can touch this row is a sibling-key ``json_set`` (the
+ sweep's ``interrupt_reason``), which changes neither the status nor the slot and
+ so cannot make the retry lose.
+
+ Not claimed: that the status is IMMUTABLE. ``update_run_status`` writes by id
+ with no status predicate, and the cancel-bookkeeping and requeue paths reach it
+ (``mark_run_canceled``, ``requeue``); on an already-terminal row that is a
+ caller bug, but it is reachable prose-wise and the argument must not pretend
+ otherwise. It is harmless HERE either way: such a write inside this window
+ moves the status off the re-read value, the retry's CAS matches zero rows, and
+ the method returns ``None``. The failure mode of a broken invariant is a lost
+ notice, never a notice mis-stamped onto a row that moved — so a second failure
+ would mean something upstream is wrong, not that a third attempt would help.
+ """
+
+ instant = now or _utc_now_iso()
+ transaction = nullcontext(_conn) if _conn is not None else self.engine.begin()
+ with transaction as conn:
+ row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().first()
+ if not row:
+ return None
+ if bool(row["cancel_requested"]) or normalize_run_status(row["status"]) == "canceled":
+ return None
+ metadata = _json_loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict):
+ return None
+ existing = metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if isinstance(existing, dict) and str(existing.get("state") or "").strip():
+ return None
+ notice = {
+ "state": NOTICE_PENDING,
+ "attempts": 0,
+ # Always an instant, never ``None`` — see the eligibility expressions.
+ "next_attempt_at": instant,
+ "failure_id": f"binding:{task_id}:{signature}",
+ "kind": NOTICE_KIND_BINDING_CHANGE,
+ # No interruption: the lane is decided by ``kind``, and leaving this
+ # ``None`` keeps ``is_interruption`` answering the same question it
+ # always did rather than becoming a two-meaning field.
+ "interrupt_reason": None,
+ "binding": {
+ "task_id": task_id,
+ "action": action,
+ "reason": reason,
+ "previous_session_id": previous_session_id,
+ "new_session_id": new_session_id,
+ "settings_preserved": bool(settings_preserved),
+ },
+ "error": None,
+ "ack_evidence": None,
+ "stamped_at": instant,
+ }
+ # ``coalesce`` so a row that has never carried metadata is stamped rather
+ # than refused: ``json_set(NULL, …)`` is NULL, which would erase the column.
+ # ``json_valid`` over the SAME expression so a MALFORMED blob is refused
+ # instead of raising ``malformed JSON`` out of the rebind path — the write-time
+ # half of the discipline ``OWED_NOTICE_STATE_SQL`` documents (HFR-084). Refused
+ # rather than repaired: the previous whole-blob write silently replaced an
+ # unreadable blob with a fresh one, discarding whatever else was in it.
+ metadata_source = func.coalesce(agent_runs.c.metadata_json, "{}")
+
+ def _stamp_against(observed_status: Any) -> int:
+ """The guarded write, conditioned on status and no explicit Stop."""
+
+ return conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ # The status the SELECT read, verbatim rather than normalized:
+ # this is a compare-and-swap on the value that was actually seen,
+ # and widening it through ``_status_query_values`` would let an
+ # alias transition slip past the guard.
+ .where(agent_runs.c.status == observed_status)
+ # An explicit Stop outranks binding-recovery news. This closes
+ # both shapes: queued Stop already changed the status to canceled;
+ # running Stop changed only cancel_requested.
+ .where(cancel_not_requested())
+ .where(*owed_notice_absent())
+ .where(func.json_valid(metadata_source) == 1)
+ .values(
+ metadata_json=func.json_set(
+ metadata_source,
+ f"$.{OWED_FAILURE_NOTICE_KEY}",
+ func.json(_json_dumps(notice)),
+ ),
+ updated_at=instant,
+ )
+ ).rowcount
+
+ if _stamp_against(row["status"]):
+ return notice
+
+ # The CAS lost. Re-read ONCE and decide on the winner: see the policy
+ # table above. Only a ``succeeded`` winner is retried, because it is the
+ # only terminal status that writes no notice of its own and so leaves a
+ # slot this method legitimately owes.
+ settled = (
+ conn.execute(
+ select(agent_runs.c.status, agent_runs.c.metadata_json)
+ .where(agent_runs.c.id == run_id)
+ .limit(1)
+ )
+ .mappings()
+ .first()
+ )
+ winner = normalize_run_status(settled["status"]) if settled else None
+ if winner == "succeeded":
+ later = _json_loads(settled["metadata_json"], {})
+ occupant = later.get(OWED_FAILURE_NOTICE_KEY) if isinstance(later, dict) else None
+ slot_is_empty = isinstance(later, dict) and not (
+ isinstance(occupant, dict) and str(occupant.get("state") or "").strip()
+ )
+ # The retry re-asserts the RE-READ status, not the original one, and
+ # keeps ``owed_notice_absent()``/``json_valid`` unchanged — so it is
+ # the same compare-and-swap over a fresher observation, never a
+ # weakened one. Terminal status plus single-stamper marker is what
+ # makes one attempt sufficient; there is no loop.
+ if slot_is_empty and _stamp_against(settled["status"]):
+ return notice
+
+ # NOTHING was written. Reporting ``None`` rather than the composed notice
+ # matters for the same reason it does in ``update_owed_failure_notice``:
+ # the caller must not treat its own view as what the row now says.
+ logger.debug(
+ "binding notice for %s not stamped: read status %r, settled as %r, "
+ "and that outcome either owns the notice slot or reserves it",
+ run_id,
+ row["status"],
+ None if settled is None else settled["status"],
+ )
+ return None
+
+ def update_owed_failure_notice(
+ self,
+ run_id: str,
+ *,
+ expect: Optional[tuple[str, int, str]] = None,
+ **fields: Any,
+ ) -> Optional[dict[str, Any]]:
+ """Merge fields into one run's owed notice, in a single guarded write.
+
+ Guarded on the notice still EXISTING rather than on the run's status: the run
+ is already terminal by construction, and the thing that must not be clobbered
+ is a notice another pass resolved.
+
+ ``expect`` adds the second half of that: the ``(state, attempts,
+ next_attempt_at)`` the caller DECIDED FROM, as ``notice_write_expectation`` read
+ it, re-asserted here so a write cannot land behind a newer one. Existence alone is not enough for the
+ drain, which checks service ownership ONCE at the top of a pass and then
+ AWAITS delivery: a lock handoff can lapse the outgoing owner's lease while its
+ coroutine is still suspended in that send, so the incoming owner reads the same
+ pending notice, delivers it and acknowledges, and the resumed pass then writes
+ its stale ``pending`` retry or ``failed`` dead letter over the ``sent``. The
+ ``failed`` direction is the one that hurts: it is terminal, so a receipt the
+ user already has is buried for good.
+
+ The predicate goes in the UPDATE's WHERE clause, not in Python, for the reason
+ ``upsert_definition_in_connection`` spells out: the SELECT below reserves
+ nothing — pysqlite emits no ``BEGIN`` for a bare SELECT, so the write lock is
+ first taken by the UPDATE — and a comparison made in the gap between them is a
+ check-then-act that two passes can both pass. Evaluated by SQLite in the
+ writing statement, the loser matches zero rows and is detected by ``rowcount``.
+ ``attempts`` is part of the predicate so two passes that both read attempt N
+ cannot both consume it. DELIBERATELY NOT ``updated_at`` — see
+ ``DefinitionWriteExpectation``: a row-version guard refuses benign writes, and
+ a freshly stamped notice carries no such marker at all.
+
+ The loser SILENTLY no-ops (``None``, nothing written) instead of raising. It has
+ nothing to repair — the next 2 s tick re-reads whatever the winner settled — and
+ an exception would be caught by the drain's per-row handler and logged on every
+ handoff. ``expect=None`` keeps the unguarded merge for the stamp/rewind callers,
+ which write no predicate and so behave exactly as before.
+
+ ``expect`` is keyword-only AND declared before ``**fields`` on purpose:
+ ``fields`` is merged verbatim into the notice blob, so a positional or
+ trailing spelling would silently persist the expectation as notice content.
+ """
+
+ now = _utc_now_iso()
+ with self.engine.begin() as conn:
+ row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().first()
+ if not row:
+ return None
+ metadata = _json_loads(row["metadata_json"], {})
+ if not isinstance(metadata, dict):
+ return None
+ notice = metadata.get(OWED_FAILURE_NOTICE_KEY)
+ if not isinstance(notice, dict):
+ return None
+ merged = dict(notice)
+ merged.update(fields)
+ merged["updated_at"] = now
+ metadata[OWED_FAILURE_NOTICE_KEY] = merged
+ stmt = update(agent_runs).where(agent_runs.c.id == run_id)
+ if expect is not None:
+ stmt = stmt.where(*owed_notice_state_unchanged(expect))
+ result = conn.execute(
+ stmt.values(metadata_json=_json_dumps(metadata), updated_at=now)
+ )
+ if expect is not None and not result.rowcount:
+ # LOST, and nothing was written. Reporting ``None`` rather than the
+ # payload matters: the caller must not treat its own merged view as
+ # what the row now says.
+ logger.debug(
+ "owed failure notice for %s moved from %s; stale write dropped",
+ run_id,
+ expect,
+ )
+ return None
+ return merged
+
+ def owed_failure_notice(self, run_id: str) -> Optional[dict[str, Any]]:
+ run = self.get_run(run_id)
+ notice = (run or {}).get("metadata") or {}
+ notice = notice.get(OWED_FAILURE_NOTICE_KEY) if isinstance(notice, dict) else None
+ return notice if isinstance(notice, dict) else None
+
+ def _definition_history_scope(self, definition_id: str, *columns: Any) -> Any:
+ """One definition's history, minus every row class that is not a verdict.
+
+ Same exclusions as the health window and for the same reasons — most
+ sharply, the watch supervisor heartbeat flips its predecessor to
+ ``succeeded`` on every write, and a ``succeeded`` row bearing the watch's
+ ``definition_id`` sitting between two failures CLOSES the streak, so every
+ watch failure would read as a first failure and notify. Fixing only the
+ deferral predicate would trade a permanent silence for daily spam.
+
+ Interruptions are dropped HERE, in SQL, rather than while classifying: they
+ are transparent to a streak — neither joining one nor closing one — so a row
+ the classifier would skip must never reach it, exactly as the health window
+ argues. Letting one join would absorb a D1 notice into an unrelated streak
+ and skip it as a duplicate.
+ """
+
+ return (
+ select(*columns)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(_not_an_out_of_band_interruption())
+ )
+
+ def consecutive_definition_failures_with_code(
+ self,
+ definition_id: str,
+ failure_code: str,
+ *,
+ limit: int,
+ ) -> int:
+ """Count a bounded suffix of failed verdicts carrying ``failure_code``.
+
+ The current run is still ``running`` when binding recovery asks, so this
+ reads only prior terminal verdicts. A success or a differently-classified
+ failure closes the suffix; canceled and out-of-band interruption rows are
+ transparent through ``_definition_history_scope``.
+ """
+
+ if limit <= 0:
+ return 0
+ statement = (
+ self._definition_history_scope(
+ str(definition_id),
+ agent_runs.c.status,
+ agent_runs.c.metadata_json,
+ )
+ .where(agent_runs.c.status.in_(_status_query_values("succeeded") + _status_query_values("failed")))
+ .order_by(agent_runs.c.created_at.desc(), agent_runs.c.id.desc())
+ .limit(limit)
+ )
+ with self.engine.connect() as conn:
+ rows = conn.execute(statement).all()
+ count = 0
+ for status, metadata_json in rows:
+ if normalize_run_status(status) != "failed":
+ break
+ metadata = _json_loads(metadata_json, {})
+ if not isinstance(metadata, dict) or metadata.get("failure_code") != failure_code:
+ break
+ count += 1
+ return count
+
+ def failure_streak_decision(self, definition_id: str, run_id: str) -> dict[str, Any]:
+ """The three facts ``core.failure_notices.decide`` needs, in ONE statement.
+
+ Not the streak. The drain never wanted a streak — it wanted to know whether
+ this run belongs to one, whether anybody in it has already told the user, and
+ which row is the one still trying. Returning the rows themselves was what made
+ the read cost the streak's LENGTH and forced the caller to redo the
+ classification in Python.
+
+ ``in_streak``
+ ``run_id`` is a verdict of this definition — not an interruption, not a
+ heartbeat, not another definition's run, not nonterminal. When it is
+ ``False`` the other two facts are ``False``/``None`` BY CONSTRUCTION
+ rather than by a Python guard: the window predicates carry an
+ anchor-membership term, so a run that belongs to no streak yields an empty
+ window instead of the definition's whole history.
+ ``has_sent_elsewhere``
+ some OTHER row of the same streak has notice state ``sent``. Evidence of
+ delivery anywhere in the streak makes this row a duplicate.
+ ``earliest_pending_id``
+ the earliest still-``pending`` row of the streak by ``(created_at, id)``:
+ the canonical notice. ``failed`` (dead-lettered) and ``skipped`` rows drop
+ out, which is how promotion works — a streak whose canonical exhausted its
+ retries still owes the user the news.
+
+ The streak is still exactly what it was: the run of verdicts strictly between
+ the two ``succeeded`` rows bracketing this one, so a success on either side
+ closes it and the next failure after a recovery notifies again.
+
+ WHY ONE STATEMENT, and this is the whole point of the shape (two reasons, both
+ load-bearing):
+
+ 1. ONE SNAPSHOT. pysqlite does not open a transaction for reads, so three bare
+ ``SELECT``s saw three different databases. A success settling between the
+ "following success" seek and the range query MERGES two streaks: the later
+ streak's rows are then read as members of the earlier one, and a ``sent``
+ notice belonging to the earlier outage makes ``decide`` answer SKIP for a
+ LIVE one. That is a lost notice — the D1 direction, not the duplicate
+ direction. The previous docstring argued the reads were safe because "every
+ row they read is already SETTLED", which is true of each row individually
+ and says nothing about which rows the WINDOW contains; the boundaries are
+ what moves. One statement is one SQLite read snapshot, so the boundaries and
+ the rows inside them are read from the same database.
+ 2. A BOUNDED READ. The range query materialised every row of the streak and
+ JSON-decoded each one. For a definition that has never succeeded the streak
+ IS the lifetime, and ``2 * len(streak) + 2`` decodes is O(lifetime) — the
+ bound HFR-095 claimed was a bound on the answer, which is only a bound when
+ the answer is small. Three scalars cross into Python now and NO metadata
+ blob is decoded here at all: the notice states are compared inside SQLite
+ through ``OWED_NOTICE_STATE_SQL``.
+
+ Every term is a seek on ``ix_agent_runs_definition_streak``
+ (``(definition_id, created_at, id)``, migration ``20260729_0042``): the same
+ two row-value boundary seeks as before, then the window itself constrained on
+ BOTH ends — ``(definition_id=? AND (created_at,id)>(?,?) AND
+ (created_at,id)<(?,?))``.
+ """
+
+ succeeded = _status_query_values("succeeded")
+ verdicts = succeeded + _status_query_values("failed")
+ # The sequence key, as a ROW VALUE. ``created_at`` alone is not a position:
+ # these are application-written ISO strings and several writers stamp a whole
+ # batch with one value, so a bare ``created_at <`` both loses rows tied with a
+ # boundary and can leave a SUCCESS inside the window — which silently merges
+ # two streaks into one and skips the second one's notice as a duplicate. A row
+ # value keeps the tie-break IN the comparison, and SQLite can constrain
+ # ``(created_at, id) < (?, ?)`` with an index instead of sorting.
+ position = tuple_(agent_runs.c.created_at, agent_runs.c.id)
+
+ # The anchor's position, as a SUBQUERY rather than a value fetched first. That
+ # is the difference between one statement and two, and therefore between one
+ # snapshot and two.
+ anchor_created = (
+ self._definition_history_scope(definition_id, agent_runs.c.created_at)
+ .where(agent_runs.c.id == run_id)
+ .where(agent_runs.c.status.in_(verdicts))
+ .limit(1)
+ .scalar_subquery()
+ )
+ here = tuple_(anchor_created, literal(str(run_id)))
+
+ def _closing_success(column: Any, before: bool) -> Any:
+ """One element of the nearest bracketing success's position."""
+
+ stmt = self._definition_history_scope(definition_id, column).where(
+ agent_runs.c.status.in_(succeeded)
+ )
+ if before:
+ stmt = stmt.where(position < here).order_by(
+ agent_runs.c.created_at.desc(), agent_runs.c.id.desc()
+ )
+ else:
+ stmt = stmt.where(position > here).order_by(
+ agent_runs.c.created_at, agent_runs.c.id
+ )
+ return stmt.limit(1).scalar_subquery()
+
+ # AN ABSENT BOUNDARY IS A SENTINEL, NOT A DROPPED PREDICATE. The three-statement
+ # form knew at build time whether each seek had found anything and simply
+ # omitted the term when it had not; a single statement cannot, and expressing
+ # it as ``(boundary IS NULL OR position > boundary)`` would make the term a
+ # DISJUNCTION, which SQLite cannot use as an index constraint — the plan would
+ # name the index while the range stayed a per-row filter, which is the exact
+ # failure ``20260728_0040`` shipped and HFR-086 pinned.
+ #
+ # Below every position: the empty string, which sorts at or below every value
+ # of both keys. The one position it excludes is ``('', '')`` itself — a row
+ # with an empty primary key AND an empty ``created_at``, which no writer can
+ # produce (``enqueue_run`` stamps an id and an ISO instant on every row).
+ #
+ # Above every position: the definition's own LAST ``created_at`` with a
+ # character appended. This is derived rather than a magic high constant because
+ # a constant would have to out-sort every possible ``created_at`` byte string
+ # and nothing guarantees that, while ``X < X || 'x'`` holds for every ``X``
+ # under BINARY collation (``X`` is a strictly shorter prefix). It is found by
+ # the same ``LIMIT 1`` index seek as the boundaries, not by a ``max()`` over
+ # the definition.
+ above_every_position = func.coalesce(
+ select(agent_runs.c.created_at)
+ .where(agent_runs.c.definition_id == definition_id)
+ .order_by(agent_runs.c.created_at.desc(), agent_runs.c.id.desc())
+ .limit(1)
+ .scalar_subquery(),
+ "",
+ ) + literal("x")
+ opened = tuple_(
+ func.coalesce(_closing_success(agent_runs.c.created_at, True), ""),
+ func.coalesce(_closing_success(agent_runs.c.id, True), ""),
+ )
+ closed = tuple_(
+ func.coalesce(_closing_success(agent_runs.c.created_at, False), above_every_position),
+ func.coalesce(_closing_success(agent_runs.c.id, False), ""),
+ )
+
+ # The notice state, read by SQLite. ``OWED_NOTICE_STATE_SQL`` referenced rather
+ # than retyped, under the same ``coalesce``/``CAST`` shape
+ # ``owed_notice_state_unchanged`` uses and normalized to agree with the Python
+ # side value for value: a notice that is not an object, a state stored as a
+ # number, and a malformed blob all read as "not this state" on both sides.
+ notice_state = cast(func.coalesce(literal_column(OWED_NOTICE_STATE_SQL), ""), Text)
+
+ def _window(*columns: Any) -> Any:
+ return (
+ self._definition_history_scope(definition_id, *columns)
+ .where(agent_runs.c.status.in_(verdicts))
+ # ANCHOR MEMBERSHIP, as a window term. Without it a ``run_id`` that is
+ # not a verdict of this definition leaves both boundaries NULL, both
+ # sentinels apply, and the "window" becomes the definition's ENTIRE
+ # history — unbounded, and answering about a streak the run is not in.
+ # The old form got this from an early ``return []``; a single statement
+ # has to say it in SQL. It is an uncorrelated term, so SQLite evaluates
+ # it once and skips the subquery outright when it is false.
+ .where(anchor_created.isnot(None))
+ .where(position > opened)
+ .where(position < closed)
+ )
+
+ statement = select(
+ exists(
+ self._definition_history_scope(definition_id, literal(1))
+ .where(agent_runs.c.id == run_id)
+ .where(agent_runs.c.status.in_(verdicts))
+ ).label("in_streak"),
+ # ``id != run_id``: evidence of delivery by SOMEBODY ELSE. This row's own
+ # ``sent`` state is not evidence that it is a duplicate.
+ exists(
+ _window(literal(1))
+ .where(agent_runs.c.id != run_id)
+ .where(notice_state == NOTICE_SENT)
+ ).label("has_sent_elsewhere"),
+ _window(agent_runs.c.id)
+ .where(notice_state == NOTICE_PENDING)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ .scalar_subquery()
+ .label("earliest_pending_id"),
+ )
+
+ with self.engine.connect() as conn:
+ row = conn.execute(statement).mappings().first()
+ earliest = (row or {}).get("earliest_pending_id")
+ return {
+ "in_streak": bool((row or {}).get("in_streak")),
+ "has_sent_elsewhere": bool((row or {}).get("has_sent_elsewhere")),
+ "earliest_pending_id": str(earliest) if earliest is not None else None,
+ }
+
+ def earliest_unsettled_run_before(
+ self,
+ definition_id: str,
+ *,
+ created_at: str,
+ run_id: str,
+ stale_after_seconds: Optional[float] = None,
+ now: Optional[str] = None,
+ ) -> Optional[dict[str, Any]]:
+ """An earlier-created execution of this definition that has not settled.
+
+ The streak is only computable over a settled PREFIX. ``create_per_run``
+ definitions hold no execution lock, so executions genuinely overlap and
+ completion order need not follow ``created_at``: a later-created run can fail
+ first, become canonical and send, and then an earlier-created run fails and
+ becomes the new earliest — a second notice for one outage.
+
+ ``watch_runtime`` is excluded, and that exclusion is load-bearing in the
+ opposite direction from the streak's: the heartbeat is earlier-created and
+ permanently nonterminal, so every failed watch run would defer behind its own
+ supervisor forever and never deliver a notice at all.
+
+ ``stale_after_seconds`` bounds the wait. The plan's argument for an unbounded
+ wait is that "settling every nonterminal run is precisely what PR1/PR2/PR7
+ guarantee" — but PR2/PR4/PR7 are not landed, so on the current tree a queued
+ row for a paused definition can sit nonterminal indefinitely and the notice
+ would never be delivered. Past the cap the row is treated as settled, which
+ risks a duplicate notice rather than a lost one; the plan chooses that
+ direction explicitly ("a duplicated notice is a papercut, a lost one is the
+ D1 violation"). Remove the cap once those PRs land.
+
+ Both filters are SQL TERMS, not a Python ``continue``. This runs once per
+ pending owed notice on the two-second drain tick, exactly like the eligibility
+ lookup and the streak read, and it was the last read in that path deciding in
+ Python what the index could decide for it: selecting every queued/running row
+ for the definition made a definition holding a large nonterminal backlog — a
+ paused ``create_per_run`` task, a queue drained slower than it fills — pay that
+ whole backlog per notice per tick to answer a question whose answer is at most
+ one row. ``ORDER BY created_at, id LIMIT 1`` over ``ix_agent_runs_definition_streak``
+ (``(definition_id, created_at, id)``, migration ``20260729_0042``) is the same
+ answer as the first row the loop accepted.
+ """
+
+ instant = _parse_iso_instant(now) or datetime.now(timezone.utc)
+ # The anchor position as a ROW VALUE, for the reason ``failure_streak_decision``
+ # spells out: ``created_at`` alone is not a position, because several writers stamp
+ # a whole batch with one value, and a row value keeps the tie-break IN the
+ # comparison where SQLite can constrain it with the index.
+ position = tuple_(agent_runs.c.created_at, agent_runs.c.id)
+ here = tuple_(literal(str(created_at)), literal(str(run_id)))
+ stmt = (
+ select(agent_runs.c.id, agent_runs.c.created_at, agent_runs.c.status)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
+ .where(position < here)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ )
+ if stale_after_seconds is not None:
+ # ONE DOCUMENTED DIVERGENCE from the Python filter this replaces. That one
+ # asked ``_parse_iso_instant`` and SKIPPED the staleness test when the
+ # answer was ``None``, so a row whose ``created_at`` cannot be parsed read
+ # as fresh and blocked the notice for as long as it stayed nonterminal —
+ # which, for an unparseable timestamp, is a wait nothing can bound. A
+ # lexicographic cutoff has no such escape and may class the same value as
+ # stale, treating it as settled. That is the duplicate-not-lost direction
+ # the cap itself already chose, so it is the acceptable side to land on.
+ # Pinned by ``test_an_unparseable_created_at_reads_as_stale_rather_than_as_a_blocker``.
+ #
+ # ``>=`` because the Python test skipped on ``> stale_after_seconds``: a row
+ # exactly at the cap was kept, and it still is.
+ cutoff = (instant - timedelta(seconds=stale_after_seconds)).isoformat()
+ stmt = stmt.where(agent_runs.c.created_at >= cutoff)
+ with self.engine.connect() as conn:
+ row = conn.execute(stmt).mappings().first()
+ if row is None:
+ return None
+ return {"id": row["id"], "created_at": row["created_at"], "status": row["status"]}
+
+ # --- derived definition health -------------------------------------------
+ #
+ # ONE STATEMENT, and per definition a BOUNDED SEEK. Those two requirements pull
+ # in opposite directions and both are load-bearing, so the shape is not a matter
+ # of taste:
+ #
+ # * one statement, because ``_enrich_definitions`` resolves the whole page here
+ # (see the ``definition health`` lookup: "Derived health for the whole page in
+ # one query") and ``test_a_page_costs_a_fixed_number_of_queries`` pins a page's
+ # statement count at a fixed budget this read holds exactly one slot in. That
+ # budget is #1033's invariant: the per-row enrichment it replaced issued a query
+ # per row, and a 30-row page paid it thirty times over. A statement per
+ # definition here would put it straight back.
+ # * a bounded seek, because ``HEALTH_WINDOW_RUNS`` advertises ten verdicts and the
+ # window-function form it replaced had to rank the definition's ENTIRE 72 h
+ # window before ``position <= 10`` could discard anything. On a definition firing
+ # every minute that is thousands of rows examined per list row, and the
+ # settled-time index cannot stop early because ``row_number()`` needs them all.
+ #
+ # The one shape that does both, SQLite having no ``LATERAL``: iterate the id list
+ # as a virtual table (``json_each``) and answer each id with a CORRELATED scalar
+ # subquery that seeks ``(definition_id, settled DESC, id DESC)`` and stops at
+ # ``LIMIT HEALTH_WINDOW_RUNS``, aggregated into one JSON blob per definition. The
+ # measured plan is a bounded ``SEARCH`` with no ``SCAN agent_runs`` and no temp
+ # B-tree; the residual ``SCAN d`` walks the id list and ``SCAN recent`` walks the
+ # already-limited ten-row co-routine. There is no ranking step left, which is the
+ # literal ask: the limit is applied before anything ranks.
+ #
+ # The honest framing of the trade: the budget invariant counts STATEMENTS because
+ # statement dispatch was the per-row cost #1033 removed. N bounded seeks are the
+ # irreducible work of answering N health questions — what changed is that each is
+ # now a ten-row early exit instead of a full-window rank, paid inside one dispatch.
+ #
+ # ORDER IS RE-ESTABLISHED IN PYTHON. ``json_group_array`` makes no promise about
+ # the order it aggregates in — the inner ``ORDER BY`` is what bounds the seek, not
+ # what orders the array — so the blob is sorted by ``(settled, id)`` descending
+ # after decoding. Ten entries per definition, so it costs nothing, and relying on
+ # the aggregate's incidental order would be a badge that flips between reads with
+ # no write in between.
+ #
+ # ``agent_runs`` filtered to one definition is a history of ROWS, and health is
+ # a function of settled OUTCOMES only. Four row classes therefore have to be
+ # excluded, and every one of them by predicate rather than while classifying,
+ # because the ``LIMIT`` is applied to whatever the predicates let through —
+ # anything the classifier would ignore must never reach it:
+ #
+ # 1. the watch supervisor heartbeat (``run_type = watch_runtime``), which shares
+ # the watch's ``definition_id``, is refreshed to the waiter's ``started_at``
+ # on every restart, and flips its predecessor to ``succeeded`` — so it both
+ # presents as the newest "run" and closes a failure streak;
+ # 2. nonterminal executions: a failing recurring definition's next fire is the
+ # newest row for the definition and is not an outcome, so reading "the latest
+ # run failed" off it reports an actively failing definition as healthy for the
+ # whole duration of its next attempt;
+ # 3. ``canceled``: a cancellation is the absence of an outcome, so N cancelled
+ # retries would displace the failure they are supposed to be transparent to;
+ # 4. out-of-band interruptions — but by MEMBERSHIP in ``RUN_INTERRUPTION_REASONS``,
+ # never by ``interrupt_reason IS NOT NULL``. Nullness would also exclude
+ # ``no_terminal_result`` / ``refused_concurrent_turn`` / ``transport_unavailable``
+ # / ``queue_hold_expired``, which are the ordinary per-fire failures this
+ # whole feature exists to surface.
+
+ def last_success_settled_at(
+ self,
+ definition_id: str,
+ *,
+ conn: Any = None,
+ ) -> Optional[str]:
+ """When this definition last SUCCEEDED, or ``None`` if it never has.
+
+ D5 requires the failure notice's body to say "when it last succeeded", and no
+ read for it existed. This is that read and nothing more: ONE instant, so ONE
+ row.
+
+ The seek is the ``_health_rows`` seek with the window predicates removed —
+ ``ix_agent_runs_definition_settled`` (``(definition_id, coalesce(completed_at,
+ created_at) desc, id desc)``, migration ``20260728_0039``) supplies both the
+ equality and the order, so ``LIMIT 1`` early-exits on the index with nothing
+ sorted. Every filter is a SQL TERM rather than a Python ``continue``: this runs
+ once per notice on the two-second drain tick, and a definition with a long
+ history must not pay for it (the HFR-068 lesson).
+
+ THREE SPELLINGS SHARED BY NAME, never retyped — ``_SETTLED_AT`` (the index's own
+ second key), ``_status_query_values("succeeded")`` (the column holds legacy
+ spellings alongside canonical ones, so a literal ``'succeeded'`` would miss every
+ row written as ``completed``) and the ``settled DESC, id DESC`` tie-break (these
+ timestamps are application-written ISO strings and several writers stamp a whole
+ batch with one value, so without the secondary key "the last success" is whichever
+ row SQLite happens to return first).
+
+ ``watch_runtime`` is excluded for the same reason the health window excludes it:
+ the supervisor heartbeat is not the definition succeeding, and it flips to
+ ``succeeded`` on every restart — so without this term a permanently broken watch
+ would report a fresh "last succeeded" instant on every service restart.
+ """
+
+ statement = (
+ select(_SETTLED_AT)
+ .where(agent_runs.c.definition_id == str(definition_id))
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(agent_runs.c.status.in_(_status_query_values("succeeded")))
+ .order_by(_SETTLED_AT.desc(), agent_runs.c.id.desc())
+ .limit(1)
+ )
+ if conn is not None:
+ value = conn.execute(statement).scalar_one_or_none()
+ else:
+ with self.engine.connect() as active:
+ value = active.execute(statement).scalar_one_or_none()
+ text_value = str(value or "").strip()
+ return text_value or None
+
+ def _health_rows(
+ self,
+ definition_ids: Sequence[str],
+ *,
+ now: Optional[str] = None,
+ conn: Any = None,
+ ) -> dict[str, list[Optional[str]]]:
+ """Each definition's last N verdicts within T hours, newest first.
+
+ ``None`` in place of a verdict means the row is UNREADABLE — its
+ ``metadata_json`` will not parse — so nothing about it can be classified and
+ ``_classify_health`` degrades the whole definition to ``HEALTH_UNKNOWN``. It is
+ carried as a value rather than raised, because the window is per definition and
+ one bad row must not take the page down (HFR-072).
+ """
+
+ ids = [str(value or "").strip() for value in definition_ids]
+ ids = [value for value in dict.fromkeys(ids) if value]
+ if not ids:
+ return {}
+ instant = _parse_iso_instant(now) or datetime.now(timezone.utc)
+ cutoff = (instant - timedelta(hours=HEALTH_WINDOW_HOURS)).isoformat()
+
+ settled_at = _SETTLED_AT
+ # Not a literal ``('succeeded', 'failed')``: the column holds legacy
+ # spellings alongside canonical ones, so a literal list would miss every row
+ # written as ``completed`` and report a healthy definition as failing.
+ verdicts = _status_query_values("succeeded") + _status_query_values("failed")
+
+ # The id list travels as ONE json parameter and is iterated as a virtual
+ # table, so the bound-parameter count is constant in the number of definitions
+ # — which is what lets the unpaged harness list stay a single statement where
+ # an ``IN`` list had to be chunked by ``_id_batches``.
+ id_list = func.json_each(_json_dumps(ids)).table_valued("value").alias("d")
+ # READABILITY, selected alongside the verdict rather than read separately — see
+ # the note on ``json_array`` below for why it belongs in this statement.
+ #
+ # A NULL or empty column is VALID: an absent blob is not an unreadable one, and
+ # ``json_valid(NULL)`` is NULL while ``json_valid('')`` is 0, both of which would
+ # otherwise mark every metadata-free run unreadable.
+ #
+ # Valid is NOT enough: ``json_valid('[]')`` and ``json_valid('"value"')`` are 1,
+ # but the metadata SCHEMA — an object with keys — cannot be read out of a
+ # top-level array, string, number, boolean, or JSON null, so those rows are
+ # exactly as unclassifiable as a malformed blob and get the same treatment.
+ # The type check sits in a CASE branch BEHIND the validity check, deliberately:
+ # ``json_type`` on malformed input raises and would fail the whole statement —
+ # the very failure mode the ``json_valid`` guards exist to prevent (HFR-072) —
+ # and SQLite evaluates CASE branches lazily, so the invalid arm never reaches it.
+ _metadata_blob = func.coalesce(func.nullif(agent_runs.c.metadata_json, ""), "{}")
+ readable = case(
+ (func.json_valid(_metadata_blob) == 1, func.json_type(_metadata_blob) == "object"),
+ else_=literal(False),
+ )
+ recent = (
+ select(
+ settled_at.label("settled"),
+ agent_runs.c.id.label("id"),
+ agent_runs.c.status.label("status"),
+ readable.label("readable"),
+ )
+ # Correlated to the id currently being iterated, which is what makes the
+ # LIMIT below per-definition rather than per-batch.
+ .where(agent_runs.c.definition_id == id_list.c.value)
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(agent_runs.c.status.in_(verdicts))
+ .where(settled_at >= cutoff)
+ # The same expression the streak read excludes interruptions with, shared
+ # by NAME rather than retyped: two copies of a JSON extract drift
+ # silently, and the copy that drifts is the one the planner stops
+ # matching. Its ``CASE json_valid`` guard is also what keeps one
+ # unparseable blob from failing the whole statement (HFR-072).
+ .where(_not_an_out_of_band_interruption())
+ # ``id DESC`` is a required tie-break, not tidiness: these timestamps are
+ # application-written ISO strings and several writers stamp a whole batch
+ # with ONE value, so without a secondary key "the newest run" is whichever
+ # row SQLite happens to return first and the badge can flip between reads
+ # with no write in between. ``list_pending_callbacks`` already orders this
+ # way one screen away — and both keys are the index's own, so the order is
+ # free and the LIMIT early-exits on it.
+ .order_by(settled_at.desc(), agent_runs.c.id.desc())
+ .limit(HEALTH_WINDOW_RUNS)
+ # Explicit: the inner seek must NOT put the id list in its own FROM, or
+ # every definition would answer with every definition's runs.
+ .correlate(id_list)
+ .subquery("recent")
+ )
+ # ``settled`` and ``id`` are carried out of SQL, not dropped, because the sort
+ # has to be redone in Python — see the block comment: ``json_group_array``
+ # promises no order.
+ #
+ # READABILITY IS THE FOURTH ELEMENT, and it travels inside the SAME statement
+ # rather than as a second read, because the page budget invariant holds this
+ # lookup to one statement and the window predicates are pinned byte-identical by
+ # the round-10/11 plan tests. ``INTERRUPT_REASON_SQL``'s ``CASE json_valid``
+ # guard keeps ONE bad blob from failing the whole statement (HFR-072) — it was
+ # never a claim that the row is classifiable, and a NULL extract passes
+ # ``reason IS NULL``, so without this element a malformed row was counted as an
+ # ordinary verdict and a definition whose history could not be read got a
+ # confident ``healthy`` or ``failing``. ``HEALTH_UNKNOWN``'s own docstring
+ # promises unknown for exactly this row.
+ blob = select(
+ func.json_group_array(
+ func.json_array(recent.c.settled, recent.c.id, recent.c.status, recent.c.readable)
+ )
+ ).scalar_subquery()
+ statement = select(id_list.c.value.label("definition_id"), blob.label("verdicts"))
+
+ verdicts_by_definition: dict[str, list[Optional[str]]] = {}
+
+ def _collect(active: Any) -> None:
+ for row in active.execute(statement):
+ entries = _json_loads(row[1], [])
+ if not isinstance(entries, list) or not entries:
+ # A definition with no verdicts is ABSENT from the mapping rather
+ # than mapped to an empty list, exactly as the batched form was:
+ # ``_classify_health`` already defaults a missing id to no
+ # verdicts, and inventing a key here would change what
+ # ``definition_health_batch`` reports for a never-run definition.
+ continue
+ rows = [entry for entry in entries if isinstance(entry, list) and len(entry) == 4]
+ rows.sort(key=lambda entry: (str(entry[0] or ""), str(entry[1] or "")), reverse=True)
+ verdicts_by_definition[str(row[0])] = [
+ # Raw column values, so the legacy spellings ``_status_query_values``
+ # deliberately matched have to be normalized here — the batched form
+ # did the same one line down. An unreadable row carries ``None``
+ # instead of a verdict it has no standing to report.
+ normalize_run_status(entry[2]) if entry[3] else None
+ for entry in rows
+ ]
+
+ if conn is not None:
+ _collect(conn)
+ else:
+ with self.engine.connect() as owned:
+ _collect(owned)
+ return verdicts_by_definition
+
+ @staticmethod
+ def _classify_health(verdicts: list[Optional[str]]) -> dict[str, Any]:
+ """Health from one definition's verdicts, newest first.
+
+ ``failing`` when the latest verdict failed, ``degraded`` when the latest
+ succeeded but a failure is still inside the window, ``healthy`` otherwise.
+ Deliberately weaker than acknowledgment: it answers "has this been unhealthy
+ recently", not "has a human seen it". A single success downgrades ``failing``
+ to ``degraded`` rather than erasing it, which is the P6 bug, and the window
+ ages out on its own so nothing has to be dismissed.
+
+ A ``None`` verdict is an UNREADABLE row (``_health_rows``), and ONE of them
+ anywhere in the window degrades the whole definition to ``HEALTH_UNKNOWN``
+ rather than being skipped. Skipping is not the conservative choice it looks
+ like: both answers this function can give are claims over the WHOLE window —
+ ``failing`` reads the newest verdict and ``healthy`` asserts the absence of a
+ failure across all of them — so a window with a hole in it cannot support
+ either. The counters go out as ``(0, 0)``, the same shape
+ ``definition_health_batch`` reports when the read itself fails, so a caller
+ rendering "N consecutive failures" beside an unknown badge cannot print a
+ number that was never computed.
+ """
+
+ if any(status is None for status in verdicts):
+ return {
+ "health": HEALTH_UNKNOWN,
+ "consecutive_failures": 0,
+ "recent_failures": 0,
+ }
+
+ consecutive = 0
+ for status in verdicts:
+ if status != "failed":
+ break
+ consecutive += 1
+ recent = sum(1 for status in verdicts if status == "failed")
+ if consecutive:
+ health = HEALTH_FAILING
+ elif recent:
+ health = HEALTH_DEGRADED
+ else:
+ health = HEALTH_HEALTHY
+ return {
+ "health": health,
+ "consecutive_failures": consecutive,
+ "recent_failures": recent,
+ }
+
+ def definition_health_batch(
+ self,
+ definition_ids: Sequence[str],
+ *,
+ now: Optional[str] = None,
+ conn: Any = None,
+ ) -> dict[str, dict[str, Any]]:
+ """Derived health for many definitions in one indexed query.
+
+ A read failure degrades to ``unknown`` for every definition rather than
+ propagating: the health badge must not be the only thing standing between a
+ bad row and an empty Harness list, and ``last_error`` renders independently
+ of it.
+ """
+
+ ids = [str(value or "").strip() for value in definition_ids]
+ ids = [value for value in dict.fromkeys(ids) if value]
+ if not ids:
+ return {}
+ try:
+ verdicts_by_definition = self._health_rows(ids, now=now, conn=conn)
+ except Exception:
+ logger.warning("definition health lookup failed; reporting unknown", exc_info=True)
+ return {
+ definition_id: {
+ "health": HEALTH_UNKNOWN,
+ "consecutive_failures": 0,
+ "recent_failures": 0,
+ }
+ for definition_id in ids
+ }
+ return {
+ definition_id: self._classify_health(verdicts_by_definition.get(definition_id, []))
+ for definition_id in ids
+ }
+
+ def definition_health(
+ self,
+ definition_id: str,
+ *,
+ now: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Derived health for one definition."""
+
+ batch = self.definition_health_batch([definition_id], now=now)
+ return batch.get(
+ str(definition_id or "").strip(),
+ {"health": HEALTH_HEALTHY, "consecutive_failures": 0, "recent_failures": 0},
+ )
+
def write_watch_runtime(self, payload: dict[str, Any], *, updated_at: str) -> None:
watches = payload.get("watches", {}) if isinstance(payload, dict) else {}
with self.engine.begin() as conn:
@@ -3443,6 +5649,18 @@ class SQLiteBackgroundTaskStore:
"watch runtimes",
lambda: self._watch_runtimes(conn, [row.get("id") for row in rows]),
)
+ # Derived health for the whole page in one query. It goes here rather than in
+ # a per-surface payload builder because this is the only chokepoint the CLI,
+ # the list endpoint and the detail pane all pass through — and the Harness
+ # detail pane has no fetch of its own, it re-renders the row the list
+ # returned, so a field that is not on the row cannot reach it.
+ health = _lookup(
+ "definition health",
+ lambda: self.definition_health_batch(
+ [row.get("id") for row in rows if row.get("id")],
+ conn=conn,
+ ),
+ )
if any(row.get("lifecycle_state") == "running" for row in rows):
started = _lookup(
"in-flight run starts",
@@ -3465,6 +5683,14 @@ class SQLiteBackgroundTaskStore:
else [key_summaries.get(row.get(field) or "") for field in _DEFINITION_SESSION_KEY_FIELDS],
)
)
+ row_health = health.get(row.get("id") or "") or {
+ "health": HEALTH_UNKNOWN,
+ "consecutive_failures": 0,
+ "recent_failures": 0,
+ }
+ row["health"] = row_health["health"]
+ row["consecutive_failures"] = row_health["consecutive_failures"]
+ row["recent_failures"] = row_health["recent_failures"]
state = row.get("lifecycle_state")
row["lifecycle_detail"] = definition_lifecycle_detail(
lifecycle_state=state,
diff --git a/storage/db.py b/storage/db.py
index 5c896cb04..c5fe9cd90 100644
--- a/storage/db.py
+++ b/storage/db.py
@@ -7,6 +7,7 @@ from sqlalchemy import Engine, create_engine, event
from sqlalchemy.engine import URL
from config import paths
+from storage.sqlite_semantics import sqlite_run_at_epoch
def escape_sql_like(value: str) -> str:
@@ -36,6 +37,12 @@ def create_sqlite_engine(db_path: Path | None = None) -> Engine:
@event.listens_for(engine, "connect")
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
+ dbapi_connection.create_function(
+ "avibe_run_at_epoch",
+ 2,
+ sqlite_run_at_epoch,
+ deterministic=True,
+ )
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode = WAL")
cursor.execute("PRAGMA foreign_keys = ON")
diff --git a/storage/messages_service.py b/storage/messages_service.py
index d052bb1c3..6315f87b7 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -20,6 +20,7 @@ from typing import Any, Iterable, Optional
from sqlalchemy import and_, case, delete, func, or_, select, update
from sqlalchemy.engine import Connection
+from storage.agent_session_rows import INBOX_SESSION_VISIBILITIES
from storage.db import escape_sql_like
from storage.models import (
agent_runs,
@@ -331,6 +332,15 @@ def search_messages(
# Archived sessions are soft-deleted — never surface their messages
# unless the caller explicitly opted in via ``include_archived``.
.where(*archived_session_filters)
+ # DELIBERATELY ``foreground`` ALONE, i.e. narrower than the inbox
+ # (``INBOX_SESSION_VISIBILITIES``, which also admits ``system``). Search
+ # returns RESULTS a user goes on to open and read in context, and the only
+ # system session is the runtime's workspace-notifications row: machine-authored
+ # failure notices, already surfaced as inbox cards, with no conversation around
+ # a hit to read. Admitting it would put runtime bookkeeping into every user text
+ # search for no reachable next action. (Today's notices are additionally not
+ # ``searchable`` by TYPE — this predicate is the one that stays true if that
+ # ever changes.)
.where(agent_sessions.c.visibility == "foreground")
# Archived PROJECTS are modelled as scope_settings.enabled = 0 (the
# sessions stay active), so exclude a disabled scope's messages too. A
@@ -1120,7 +1130,12 @@ def unread_counts(
select(agent_sessions.c.id).where(
or_(
agent_sessions.c.status == "archived",
- agent_sessions.c.visibility != "foreground",
+ # NEGATIVE form, so it has to name every visibility the
+ # inbox admits or the badge would disagree with the feed
+ # it is supposed to count. Spelling it as "not one of the
+ # admitted values" also keeps a future fourth visibility
+ # hidden by default rather than silently badged.
+ agent_sessions.c.visibility.notin_(INBOX_SESSION_VISIBILITIES),
)
)
),
@@ -1161,7 +1176,9 @@ def unread_counts_by_session(
select(agent_sessions.c.id).where(
or_(
agent_sessions.c.status == "archived",
- agent_sessions.c.visibility != "foreground",
+ # See ``unread_counts``: negative form, so it names the
+ # admitted set rather than one value.
+ agent_sessions.c.visibility.notin_(INBOX_SESSION_VISIBILITIES),
)
)
)
@@ -1301,9 +1318,15 @@ def list_inbox_sessions(
)
)
# Archived sessions are hidden everywhere — keep them out of the inbox feed too.
+ # Visibility is the ADMISSION list, not "foreground": the runtime's
+ # workspace-notifications row is ``system`` — deliberately absent from every
+ # ordinary session list — and the inbox is the surface it is delivered on, so
+ # excluding it here would hide the notice this session exists to show while the
+ # notice was still recorded as sent. ``background`` remains excluded (it also
+ # sets ``suppress_delivery``).
session_rows = session_rows.where(
agent_sessions.c.status != "archived",
- agent_sessions.c.visibility == "foreground",
+ agent_sessions.c.visibility.in_(INBOX_SESSION_VISIBILITIES),
)
if only_session:
session_rows = session_rows.where(agent_sessions.c.id == only_session)
diff --git a/storage/migrations.py b/storage/migrations.py
index ce3028a51..00a26c6c7 100644
--- a/storage/migrations.py
+++ b/storage/migrations.py
@@ -25,6 +25,11 @@ logger = logging.getLogger(__name__)
_MIGRATION_LOCK = threading.RLock()
INITIAL_REVISION = "20260501_0001"
+# Stamp FLOOR for head-shaped unversioned databases, deliberately NOT head: after
+# `_stamp_existing_initial_schema` stamps it, `_run_migrations_locked` upgrades to head,
+# so every revision after this one replays on a schema that already looks like head.
+# Each such migration must therefore stay idempotent/replay-safe against head shape
+# (e.g. `drop index if exists` before `create index`) rather than assume a virgin table.
LATEST_SCHEMA_REVISION = "20260622_0023"
REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"
ALLOW_DEV_STATE_MIGRATION_ENV = "AVIBE_ALLOW_DEV_STATE_MIGRATION"
@@ -217,6 +222,26 @@ def initialize_background_tables(db_path: Path | None = None) -> None:
run_migrations(target_db)
+def ensure_background_indexes(db_path: Path | None = None) -> None:
+ """Repair head indexes even when the tables already pass readiness checks.
+
+ ``metadata.create_all`` can produce every required table and column without
+ the expression indexes owned by migrations 0039/0041/0042. Such a database
+ correctly skips schema migration, so store construction must still enter the
+ index repair path. Correct expression indexes are detected byte-for-byte
+ against their owning migration DDL and are not rebuilt on ordinary opens.
+ """
+
+ target_db = (db_path or paths.get_sqlite_state_path()).expanduser().resolve()
+ if not target_db.exists():
+ return
+ with sqlite3.connect(target_db) as conn:
+ tables = _table_names(conn)
+ if {"run_definitions", "agent_runs"}.issubset(tables) and not _agent_runs_expression_indexes_ready(conn):
+ _ensure_agent_runs_expression_indexes(conn)
+ conn.commit()
+
+
def guard_source_checkout_default_state_migration(db_path: Path) -> None:
if _env_flag_enabled(ALLOW_DEV_STATE_MIGRATION_ENV):
return
@@ -628,6 +653,78 @@ def _ensure_new_background_indexes(conn: sqlite3.Connection) -> None:
conn.execute('create index if not exists ix_agent_runs_agent_created on agent_runs (agent_name, created_at)')
conn.execute('create index if not exists ix_agent_runs_callback_status on agent_runs (callback_status, completed_at)')
conn.execute('create index if not exists ix_agent_runs_updated on agent_runs (updated_at)')
+ if not _agent_runs_expression_indexes_ready(conn):
+ _ensure_agent_runs_expression_indexes(conn)
+
+
+#: The ``agent_runs`` index migrations whose DDL the head-schema repair path must also
+#: install, oldest first. 0040 is deliberately absent: 0041 drops the index 0040 created
+#: and recreates it under its own two-expression definition, so 0040's shape is never a
+#: valid end state and replaying it here would only build an index 0041 has to replace.
+_AGENT_RUNS_INDEX_REVISION_MODULES = (
+ "storage.alembic.versions.20260728_0039_agent_runs_settled_at_index",
+ "storage.alembic.versions.20260728_0041_agent_runs_owed_notice_backoff_index",
+ "storage.alembic.versions.20260729_0042_agent_runs_definition_streak_index",
+)
+#: Columns the three index expressions read. A head-shaped database has all of them, but
+#: this helper is also reached from ``_repair_head_required_columns`` on older drifted
+#: shapes, and ``create index`` on a missing column raises rather than skipping.
+_AGENT_RUNS_INDEX_COLUMNS = frozenset({"definition_id", "created_at", "completed_at", "metadata_json"})
+
+
+def _normalized_index_sql(value: object) -> str:
+ return " ".join(str(value or "").split()).casefold()
+
+
+def _agent_runs_expression_indexes_ready(conn: sqlite3.Connection) -> bool:
+ if not _AGENT_RUNS_INDEX_COLUMNS.issubset(_column_names(conn, "agent_runs")):
+ return True
+ for module_name in _AGENT_RUNS_INDEX_REVISION_MODULES:
+ revision_module = import_module(module_name)
+ row = conn.execute(
+ "select sql from sqlite_master where type = 'index' and name = ?",
+ (revision_module._INDEX,),
+ ).fetchone()
+ if row is None or _normalized_index_sql(row[0]) != _normalized_index_sql(revision_module.CREATE_INDEX_SQL):
+ return False
+ return True
+
+
+def _ensure_agent_runs_expression_indexes(conn: sqlite3.Connection) -> None:
+ """Install the 0039/0041/0042 ``agent_runs`` indexes on a head-shaped database.
+
+ ``_ensure_head_indexes`` promises that a head-shaped unversioned database ends up
+ with every index head has, and until now it silently lagged head by these three.
+ Two lanes make that gap reachable without any migration ever running: a database
+ born from ``metadata.create_all`` satisfies ``background_tables_ready`` (tables and
+ columns only — never indexes), so ``SQLiteBackgroundTaskStore`` accepts it as ready
+ and never calls ``initialize_background_tables``; and the day
+ ``LATEST_SCHEMA_REVISION`` moves past 0038 the stamp floor stops replaying them for
+ everyone. Both leave the two-second owed-notice tick, the health window and the
+ streak read scanning run history with nothing to repair them.
+
+ The DDL is IMPORTED from the revision that owns it, never retyped. The owed-notice
+ index is an expression index and SQLite matches an index expression against a query
+ expression by text, so a second copy of that string is an index that gets built and
+ silently ignored — the failure 0040 and 0041 were each written to correct. Importing
+ the revision module is the same technique ``_run_remove_legacy_default_agent_migration``
+ already uses; ``storage.background`` (which holds the query-side twins) cannot be
+ imported here because it imports this module.
+
+ Drop-then-create rather than ``create index if not exists``: a database carrying the
+ superseded 0040 shape of ``ix_agent_runs_owed_notice`` has the NAME already taken by
+ an index missing the backoff expression, and ``if not exists`` would leave that
+ weaker definition in place. Recreating unconditionally also makes the resulting
+ ``sqlite_master`` SQL byte-identical to the migration's, whichever route a database
+ took to head.
+ """
+
+ if not _AGENT_RUNS_INDEX_COLUMNS.issubset(_column_names(conn, "agent_runs")):
+ return
+ for module_name in _AGENT_RUNS_INDEX_REVISION_MODULES:
+ revision_module = import_module(module_name)
+ conn.execute(revision_module.DROP_INDEX_SQL)
+ conn.execute(revision_module.CREATE_INDEX_SQL)
def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -> None:
diff --git a/storage/sqlite_semantics.py b/storage/sqlite_semantics.py
new file mode 100644
index 000000000..758308b66
--- /dev/null
+++ b/storage/sqlite_semantics.py
@@ -0,0 +1,87 @@
+"""Pure models of SQLite value semantics, shared by both sides of a CAS.
+
+Stdlib-only on purpose ("dependency-neutral"): ``storage`` must never import
+``core``, and ``core.failure_notices`` keeps its imports light, so a normalizer
+consumed by BOTH — the policy reader that decides an increment/dead-letter and
+the storage predicate the guarded write asserts — has to live in a leaf module
+with no dependencies of its own. One function, two importers, zero drift.
+"""
+
+from __future__ import annotations
+
+import re
+from datetime import datetime
+from typing import Any
+from zoneinfo import ZoneInfo
+
+_INT64_MAX = 2**63 - 1
+_INT64_MIN = -(2**63)
+
+#: SQLite's CAST skips only ASCII whitespace before an optional sign and digits.
+#: Python's ``\s`` also matches unicode spaces, which SQLite reads as 0 — so the
+#: class is spelled out. Digits are ASCII only: ``CAST('٣' AS INTEGER)`` is 0.
+_CAST_INTEGER_PREFIX = re.compile(r"[ \t\n\r\f\v]*([+-]?)([0-9]*)")
+
+
+def sqlite_cast_integer(raw: Any) -> int:
+ """``CAST(<json_extract result> AS INTEGER)``, modelled exactly.
+
+ ``raw`` is what ``json_extract`` hands back for the stored JSON value —
+ ``None`` for null/absent (callers pair this with ``coalesce(..., 0)``), a
+ ``bool``/``int``/``float`` for scalars, a ``str`` for JSON text, and a
+ ``list``/``dict`` for containers (whose extract is their JSON text, first
+ byte ``[``/``{`` — no numeric prefix, so CAST reads 0).
+
+ The semantics that differ from Python's ``int()`` and that this exists for
+ (empirically traced against SQLite, and pinned by the executable-oracle
+ parity test rather than by this table):
+
+ * numeric-PREFIX parsing: ``'3x'`` → 3, ``'1e100'`` → 1 (the ``e`` ends the
+ digits), ``' +7x'`` → 7, ``'- 5'`` → 0 (space after the sign ends it);
+ * truncation toward zero for reals: ``3.9`` → 3, ``-3.9`` → -3;
+ * saturation at the signed-64-bit bounds for anything beyond them, in every
+ lane — huge JSON integers, ``±1e100``, and digit strings alike.
+ """
+
+ if raw is None:
+ return 0
+ if isinstance(raw, bool):
+ return 1 if raw else 0
+ if isinstance(raw, int):
+ return min(max(raw, _INT64_MIN), _INT64_MAX)
+ if isinstance(raw, float):
+ if raw != raw: # NaN — unreachable through JSON, guarded anyway.
+ return 0
+ if raw >= float(2**63):
+ return _INT64_MAX
+ if raw < float(_INT64_MIN):
+ return _INT64_MIN
+ return int(raw) # int() truncates toward zero, exactly like CAST.
+ if isinstance(raw, (list, dict)):
+ return 0
+ match = _CAST_INTEGER_PREFIX.match(str(raw))
+ if match is None or not match.group(2):
+ return 0
+ return min(max(int(match.group(1) + match.group(2)), _INT64_MIN), _INT64_MAX)
+
+
+def sqlite_run_at_epoch(run_at: Any, timezone_name: Any) -> float | None:
+ """Resolve a one-shot wall clock exactly like the scheduler does.
+
+ SQLite's ``datetime()`` treats an offset-free timestamp as UTC and cannot
+ resolve IANA timezone names. Scheduled tasks do carry an IANA timezone, so
+ lifecycle queries use this connection-local function instead of silently
+ reading the same ``run_at`` as a different instant than APScheduler.
+
+ ``None`` is the SQL-friendly invalid-input result: it makes the lifecycle
+ predicate false and leaves the row visible rather than retiring a schedule
+ whose instant cannot be proved.
+ """
+
+ try:
+ zone = ZoneInfo(str(timezone_name or "UTC"))
+ instant = datetime.fromisoformat(str(run_at))
+ resolved = instant.replace(tzinfo=zone) if instant.tzinfo is None else instant.astimezone(zone)
+ return resolved.timestamp()
+ except (KeyError, OSError, TypeError, ValueError, OverflowError):
+ return None
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index d17e1a3de..3984c4ba8 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -25,7 +25,8 @@ from sqlalchemy.engine import Connection
from config import paths
from storage.agent_session_rows import (
- SESSION_VISIBILITIES,
+ ASSIGNABLE_SESSION_VISIBILITIES,
+ WORKSPACE_NOTICE_SESSION_ID,
create_agent_session_row,
new_session_id,
)
@@ -137,6 +138,12 @@ def list_sessions(
``title_query`` powers the chat composer ``#``-mention global search: a
case-insensitive title LIKE match (LIKE metacharacters escaped).
+
+ The visibility predicate is POSITIVE (``== 'foreground'``), which is why the runtime's
+ ``system`` sessions need no exclusion of their own here: an ordinary session list
+ shows ordinary sessions, and anything the runtime owns has to opt IN to a surface
+ rather than be remembered as an exception. ``tests/test_workspace_system_session.py``
+ pins that, so it stays a property rather than an assumption.
"""
query = select(agent_sessions).where(agent_sessions.c.visibility == "foreground")
@@ -245,6 +252,9 @@ def list_sessions_page(
``<platform>::`` ``scope_id`` prefix (no join needed; see ``make_scope_id``).
Fetches ``limit + 1`` rows so the caller learns whether a next page exists
without a second COUNT query.
+
+ ``visibility == 'foreground'`` is positive for the reason ``list_sessions`` spells
+ out: runtime-owned ``system`` sessions are excluded without naming them.
"""
request = PageRequest(page=max(int(page), 1), limit=max(int(limit), 1))
query = select(agent_sessions).where(
@@ -371,6 +381,30 @@ def create_session(
return get_session(conn, session_id)
+class ReservedSessionError(PermissionError):
+ """Raised when a caller tries to tear down or edit a session the runtime reserves.
+
+ ``PermissionError`` by inheritance, deliberately: the session routes in
+ ``vibe/ui_server.py`` already map that to a refusal response, so a route that has
+ not learned this class yet answers a refusal rather than 500. ``code`` is the
+ machine half; the user-visible sentence is rendered at the HTTP boundary from
+ ``vibe/i18n``, because this layer has no way to know the caller's language (the
+ configured language lives in ``core.services.settings``, and importing core from
+ storage would invert the layering).
+
+ Raised from ``archive_session`` (teardown) and ``update_session`` (edit), both on
+ identity rather than row state — see each for why.
+ """
+
+ code = "reserved_session"
+
+ def __init__(self, session_id: str):
+ self.session_id = session_id
+ super().__init__(
+ f"Session {session_id} is reserved by the runtime and cannot be archived or modified"
+ )
+
+
class SessionBackendLockedError(Exception):
"""Raised when a caller tries to switch the backend of a session that already
has a native conversation (pinned for life: the native can only be resumed by
@@ -423,6 +457,24 @@ def update_session(
pinned: Any = _UNSET,
scope_id: Any = _UNSET,
) -> dict[str, Any]:
+ """Apply a caller's edits to one session row.
+
+ THE RESERVED WORKSPACE-NOTICE SESSION IS REFUSED HERE TOO, for the same reason
+ ``archive_session`` refuses it and on the same IDENTITY test (so the answer does not
+ depend on whether the lazily-created row exists yet). That row is D5 rung (5)'s home
+ and its ``system`` visibility IS the projection: hidden from ordinary session lists,
+ admitted to the inbox. An unguarded write could move it off that value — ``visibility
+ = 'background'`` mutes the notice outright, ``foreground`` re-materializes a
+ machine-owned chat in every user's session list — and also ``scope_id``, which would
+ mint a fake project row and put the session inside a scoped clear's reach. Each of
+ those is silent until the next notice's heal, so an ack could be earned against a
+ surface showing nothing in between.
+
+ ``system`` itself is not assignable in the other direction either: see the
+ ``visibility`` branch below.
+ """
+ if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
+ raise ReservedSessionError(str(session_id))
existing = conn.execute(
select(
agent_sessions.c.id,
@@ -517,7 +569,11 @@ def update_session(
values["reasoning_effort"] = reasoning_effort or None
if visibility is not _UNSET:
visibility_value = str(visibility or "").strip()
- if visibility_value not in SESSION_VISIBILITIES:
+ # ASSIGNABLE, not the full storage vocabulary: ``system`` is a runtime
+ # classification of a runtime-owned row, so no caller may label an ordinary
+ # chat with it (that would hide the chat from every session list while leaving
+ # it delivering into the inbox — a session the user can no longer reach).
+ if visibility_value not in ASSIGNABLE_SESSION_VISIBILITIES:
raise ValueError(f"invalid session visibility: {visibility!r}")
values["visibility"] = visibility_value
if pinned is not _UNSET:
@@ -997,7 +1053,26 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:
Returns the archived session payload plus a ``reclaimed`` summary
(``{tasks, watches, runs}``) for the confirm-dialog / post-archive notice.
+
+ THE RESERVED WORKSPACE-NOTICE SESSION IS REFUSED, and the refusal is on IDENTITY
+ rather than on row state, so a race that removes the row cannot turn it into a
+ 404-and-then-archive. That row is D5 rung (5)'s home (see
+ ``storage.agent_session_rows.resolve_workspace_notice_session``); it is ``system``,
+ so it is NOT one click from a session list any more — but it is still one ``DELETE
+ /api/sessions/ses-workspace-notices`` from anyone holding the id (the inbox card
+ carries it), and archiving it fails SILENTLY. Everything downstream disagrees about
+ what archived means: ``_session_row`` has no status filter so a later notice still
+ persists and still earns its receipt — the notice is stamped ``sent`` — while
+ ``list_inbox_sessions`` excludes archived sessions, so no card, no realtime event and
+ no push. Every subsequent caller-less failure would be recorded as delivered into a
+ surface nothing displays. Hiding the row from the lists narrows the blast radius; it
+ does not replace this guard, which is why both exist.
+
+ Checked BEFORE the existence lookup so the answer is the same on every install,
+ whether or not the lazily-created row exists yet.
"""
+ if str(session_id) == WORKSPACE_NOTICE_SESSION_ID:
+ raise ReservedSessionError(str(session_id))
existing = conn.execute(
select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)
).scalar_one_or_none()
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 72cb5acd2..2385c120e 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -427,6 +427,1895 @@ scenarios:
layer: contract
backend: shared
test: tests/test_sqlite_sessions_store.py::test_prefix_clear_does_not_delete_a_superseded_row
+ # PR6 — P6 make failure visible. Range HFR-060…074 reserved in the plan's §10.7
+ # after PR1 and PR5 collided by picking ranges independently.
+ - id: HFR-060
+ name: an ordinary completion does not clobber an already-settled success
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_complete_does_not_clobber_an_already_terminal_run
+ - id: HFR-061
+ name: the coalesced completer does not clobber an already-settled success
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # PR6 review round 12 (#1072). THE DELIBERATE FALL-THROUGH THIS ID ESTABLISHED IS
+ # ALSO A HOLE. HFR-061 stopped the coalesced completer clobbering an already-SETTLED
+ # row by skipping terminal statuses, but it deliberately let ``canceled`` fall through
+ # so a cancel-requested row keeps being normalized. That exemption read
+ # ``cancel_requested`` from a batch snapshot and never re-asserted it, and ``cancel_run``
+ # is a separate transaction: pysqlite starts no transaction for the read, so the
+ # snapshot is genuinely older than the write and a Stop landing in the gap is
+ # overwritten by a ``failed`` the writer decided on BEFORE the user pressed it.
+ # ``settle_run_terminal`` has the reachable half of the same defect from the other
+ # side: it scopes its UPDATE to ``queued|running``, which catches a cancel of a QUEUED
+ # row because ``cancel_run`` flips that status directly -- but on a RUNNING row
+ # ``cancel_run`` sets only the flag, the status predicate still matches, and the write
+ # lands ``failed`` over the Stop. A running turn is what a user actually presses Stop
+ # on.
+ # THE DAMAGE IS TWO-LAYERED, and the second layer is why this belongs to PR6 rather
+ # than to the settlement lane alone: the run reads ``failed`` when the user cancelled
+ # it, so the Stop silently did nothing; AND a ``failed`` transition stamps an owed
+ # failure notice, so the drain then tells the user their task is broken because they
+ # cancelled it -- "a notice nobody can act on, in the lane this whole feature exists
+ # to make trustworthy."
+ # FIX: ``cancel_requested`` joins the terminal CAS as ``cancel_not_requested()``, a
+ # module-level SQL helper under the same ``coalesce``/``CAST`` shape
+ # ``owed_notice_state_unchanged`` uses -- ``coalesce`` because a NULL column reads as
+ # "not requested" on the Python side and NULL is not false in SQL, ``CAST`` because
+ # untyped storage means a text ``'0'`` must not read as truthy. The asymmetry IS the
+ # fix: the ``canceled`` branch keeps ``canceled`` in its status list and falls through,
+ # while the ``succeeded``/``failed`` branch re-asserts ``cancel_not_requested()`` and
+ # DROPS ``canceled`` from its list. Both halves are needed -- the status predicate stops
+ # the write landing on a row already flipped to ``canceled``, the flag predicate stops
+ # it landing on a running row where only the flag moved.
+ # ONE RE-READ ON A REFUSED WRITE, NEVER A LOOP, and the reason one suffices is not
+ # lock acquisition: a refusal means the row moved under the snapshot, so the decision
+ # is remade from what the row NOW says -- "otherwise a run the user cancelled
+ # mid-flight is simply left ``running`` and nothing ever settles it, which trades a
+ # wrong status for a zombie." The retry's own snapshot already sees the cancel, and
+ # this runs on the Workbench completion path where an unbounded retry is its own
+ # outage. ``settle_run_terminal`` now also RETURNS what it actually wrote rather than
+ # what it first decided.
+ # Three subordinate tests carry this id, one per writer plus the control. The cancel
+ # goes through the production ``cancel_run`` on a second store over the same file, not
+ # a hand-written UPDATE, "so what the test races against is what the Stop button
+ # does", and each asserts the race actually fired before judging the outcome.
+ # ``test_a_cancel_landing_under_the_coalesced_completer_is_not_overwritten`` and
+ # ``test_a_cancel_landing_under_settle_run_terminal_is_not_overwritten`` require
+ # ``canceled`` AND no stamped notice; red on ``a2829d3b`` for both writers, where the
+ # row ends ``failed`` with a notice attached.
+ # ``test_the_cancel_cas_does_not_leave_an_uncancelled_run_unsettled`` is the negative
+ # control, and it is not optional: "a ``cancel_requested`` predicate is the kind of
+ # guard that quietly refuses writes nobody raced -- and here that would mean a failed
+ # turn never settling and never owing its notice, which is a D1 loss dressed as a
+ # safety fix."
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_complete_coalesced_does_not_clobber_an_already_succeeded_run
+ - id: HFR-062
+ name: one success does not erase recent failure history in the CLI
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # The locator named ``test_task_last_status_does_not_report_succeeded_while_failures_are_in_window``,
+ # which no longer exists: #1061 demoted ``last_status`` to a compatibility field
+ # that never determines lifecycle, so the test was rewritten onto the
+ # ``health``/``recent_failures`` axis and renamed with it, and this line was left
+ # pointing at the old name -- a scenario id that collects nothing is an id nobody
+ # is testing. Repointed at the node that carries the assertion (its docstring
+ # self-identifies as HFR-062) rather than renaming the test back.
+ test: tests/test_harness_failure_visibility.py::test_definition_health_reaches_the_cli_list_after_a_success
+ - id: HFR-063
+ name: the brief task list carries the error that says why a task failed
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_brief_task_payload_carries_last_error
+ - id: HFR-064
+ name: the interruption-class vocabulary cannot drift between core and storage
+ status: covered
+ kind: safety
+ layer: unit
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_storage_interruption_reasons_mirror_the_settlement_vocabulary
+ - id: HFR-065
+ name: a dead-lettered canonical notice promotes the next pending row
+ status: covered
+ kind: failure
+ layer: unit
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_dead_lettered_canonical_notice_promotes_the_next_pending_row
+ - id: HFR-066
+ name: derived health survives a success after repeated failures
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_one_success_does_not_erase_recent_failure_history
+ - id: HFR-067
+ name: a result-less settlement still counts toward definition health
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_result_less_settlement_still_counts_toward_health
+ - id: HFR-068
+ name: cancellations do not bury a failure in the bounded health window
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # PR6 review round 10 (#1072). The window this id is named for was advertised and
+ # not ENFORCED. ``HEALTH_WINDOW_RUNS`` promises "the last ten verdicts", but
+ # ``_health_rows`` made SQLite assign ``row_number()`` to every verdict in the
+ # definition's entire 72 h window before the outer ``position <= HEALTH_WINDOW_RUNS``
+ # could discard any of them: the settled-time index narrows by time and cannot stop
+ # early, because the window function needs every row to rank. Measured on a 400-run
+ # history the plan was ``SEARCH agent_runs USING INDEX ix_agent_runs_definition_settled
+ # (definition_id=? AND <expr>>?)`` -- the seek is there -- followed by
+ # ``SCAN (subquery-3)``, ``SCAN anon_1`` and ``USE TEMP B-TREE FOR ORDER BY``, with no
+ # ``LIMIT`` anywhere to stop it. So a high-frequency definition walked its whole
+ # recent history to return ten rows.
+ # WHERE IT IS PAID, stated correctly because the first framing of this finding was
+ # wrong about it: NOT the 2 s drain tick, which does not read health at all. It is
+ # every Harness list, show and mutation enriched read -- the surfaces HFR-097/098
+ # collapsed onto ``_enrich_definitions`` -- so the cost lands on interactive reads
+ # once per page rather than on a background loop.
+ # THE OBVIOUS FIX WAS REVERTED, AND THE REVERT IS THE INTERESTING PART. A
+ # per-definition seek in a loop bounds the work perfectly and reintroduces exactly
+ # the per-row query #1033 removed; the master-owned page-budget invariant
+ # ``test_a_page_costs_a_fixed_number_of_queries``
+ # (``tests/test_harness_definition_lifecycle.py``, #1033) caught it, which is the
+ # invariant doing its job on a change that had every appearance of being an
+ # optimization. One statement per page and a bounded seek per definition pull in
+ # opposite directions, and both are load-bearing.
+ # FIX: the one shape that satisfies both, SQLite having no ``LATERAL``. The id list
+ # travels as ONE json parameter iterated as a ``json_each`` virtual table, and each
+ # id is answered by a CORRELATED scalar subquery that seeks
+ # ``ix_agent_runs_definition_settled (definition_id=? AND <expr>>?)`` in
+ # ``(settled DESC, id DESC)`` -- the index's own order, so it early-exits -- with
+ # ``LIMIT HEALTH_WINDOW_RUNS`` applied BEFORE anything ranks. There is no ranking
+ # step left at all, which is the literal ask. Results are aggregated with
+ # ``json_group_array`` and RE-SORTED IN PYTHON, because that aggregate promises no
+ # order: the inner ``ORDER BY`` is what bounds the seek, not what orders the array,
+ # and relying on its incidental order is a badge that flips between reads with no
+ # write in between. Ten entries per definition, so the sort is free. Bound parameters
+ # are now CONSTANT in the number of definitions, so the unpaged harness list also
+ # collapses to a single statement where an ``IN`` list previously had to be chunked
+ # one statement per 400 ids by ``_id_batches``.
+ # THE HONEST FRAMING OF THE TRADE, since N seeks remain: the budget invariant counts
+ # STATEMENTS because statement dispatch was the per-row cost #1033 removed. N bounded
+ # seeks are the irreducible work of answering N health questions -- what changed is
+ # that each is a <=10-row early exit instead of a full-window rank, paid inside one
+ # dispatch.
+ # Two subordinate tests carry this same id.
+ # ``test_the_health_read_is_bounded_before_it_is_ranked`` asserts BOTH properties,
+ # and would be wrong without either: one statement for three definitions, and a
+ # plan with a ``LIMIT``, no ``TEMP B-TREE``, no ``SCAN agent_runs``, and both index
+ # terms constrained. Asserted on the CONSTRAINED TERMS rather than an index name,
+ # which is the HFR-086/095 lesson -- a plan can name the index while the term that
+ # matters stays a per-row filter. The two residual SCANs are named and excused in
+ # place (the ``json_each`` id list, and the already-limited ten-row co-routine),
+ # because a bare ``SCAN`` assertion would have been unsatisfiable in this shape.
+ # Red on b3986fde with ``assert 'LIMIT' in ...`` over the windowed statement.
+ # ``test_the_bounded_health_read_matches_the_ranked_health_read`` is a randomized
+ # parity oracle keeping the replaced algorithm in the test module, the HFR-096
+ # pattern: the bounded read must return the SAME ten verdicts. It is GREEN ON BOTH
+ # SIDES by construction -- at b3986fde it compares the ranked form against its own
+ # reference -- so it is a no-regression oracle for the rewrite, not a detector of
+ # the defect.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 11 (#1072). The round-10 paragraph named the parity oracle's own
+ # blind spot and then relied on it anyway: the 72 h boundary. Parity is the wrong
+ # instrument for the window predicate, and the reason is now pinned rather than
+ # asserted. Measured both ways: flipping the product's ``settled >= cutoff`` to ``>``
+ # leaves the parity test GREEN even though the oracle keeps its own ``>=`` -- because
+ # the randomised fixture straddles the cutoff without ever landing ON it (its
+ # arithmetic floors the day, and ``now - 72 h`` is midnight), so no row exercises the
+ # comparison; and flipping BOTH lanes leaves it green for the second reason, that the
+ # two readers move together. Either way a definition whose only verdict settled
+ # exactly on the boundary would silently report as never-run.
+ # ``test_the_health_window_includes_a_verdict_settled_on_the_cutoff`` therefore
+ # asserts ABSOLUTELY, against a literal expected mapping, with two definitions of one
+ # row each: one settled at exactly ``now - HEALTH_WINDOW_HOURS`` (computed from the
+ # same ``now`` the read is given, so it cannot drift from the constant) which must be
+ # PRESENT, and one a single second older which must be ABSENT -- so an over-wide
+ # comparison or a cutoff with the wrong sign fails too. It also guards its own
+ # fixture, which is what stops it becoming a tautology: the boundary instant is
+ # asserted to survive the write byte-for-byte (a normalizing writer added later would
+ # otherwise move the row off the boundary silently), the ISO shape is checked because
+ # the comparison is lexicographic in SQLite, and a wider ``now`` proves the exclusion
+ # is a WINDOW exclusion rather than an unreadable row. Parity is kept only as the
+ # weaker second witness. Red by mutation (``>=`` -> ``>``), which is the honest label:
+ # the predicate was already correct, so this is a pin, not a fix.
+ # The plan test above also grew a LEXICAL bound on the LIMIT, and that is a real
+ # tightening rather than tidying: "a LIMIT exists" is satisfied by an OUTER
+ # ``LIMIT 10`` over the whole batched result, which would answer the page with ten
+ # rows TOTAL instead of ten per definition -- silently wrong health for every
+ # definition after the first. It now requires exactly one ``LIMIT``, closing inside
+ # the correlated per-definition subquery, and rendering before the ``FROM`` over the
+ # id list.
+ # And the parity fixture's own coverage claims were made true first, because three of
+ # them were false and each one silently removed a row class from the oracle: the
+ # legacy ``completed`` spelling was normalized to ``succeeded`` by ``enqueue_run`` on
+ # the way in (so the legacy lane both readers exist to honour was never exercised --
+ # it is now written past the front door and asserted to survive in the column), the
+ # ``watch_runtime`` heartbeat was written without the ``watches`` wrapper
+ # ``write_watch_runtime`` reads and so wrote NOTHING, and the docstring's claim to
+ # cover rows sitting on the cutoff was untrue -- corrected to say it straddles the
+ # cutoff but never lands on it, and to defer the boundary to the absolute test above.
+ # A fixture that claims coverage it does not have is worse than one that claims less,
+ # because the claim is what stops the next reviewer looking.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header) -- see the round-11
+ # note under HFR-099 for the re-drawn allocation.
+ test: tests/test_harness_failure_visibility.py::test_cancellations_do_not_bury_a_failure_in_the_bounded_window
+ - id: HFR-069
+ name: the watch supervisor heartbeat does not reset consecutive failures
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_watch_runtime_heartbeat_does_not_reset_consecutive_failures
+ - id: HFR-070
+ name: a nonterminal execution does not displace the newest verdict
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_nonterminal_execution_does_not_displace_the_newest_verdict
+ - id: HFR-071
+ name: the health window ages out on its own after the time bound
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_health_window_ages_out_after_the_time_bound
+ - id: HFR-072
+ name: one malformed metadata row does not blank health for every definition
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # PR6 review round 12 (#1072). THE GUARD THIS ID ESTABLISHED WAS BEING READ AS A
+ # CLAIM IT NEVER MADE. ``INTERRUPT_REASON_SQL``'s ``CASE json_valid`` wrapper exists
+ # to stop ONE bad blob failing the whole statement -- "it was never a claim that the
+ # row is classifiable". But a malformed blob makes that CASE yield NULL, and
+ # ``_not_an_out_of_band_interruption`` admits NULL, so an unreadable row was admitted
+ # to the health window as an ORDINARY VERDICT and counted as whatever its ``status``
+ # column happened to say. A definition whose history could not be read got a confident
+ # ``failing`` or ``healthy`` badge -- and a wrongly-CLEAN bill is the failure mode this
+ # whole capability exists to remove, contradicting ``HEALTH_UNKNOWN``'s own docstring
+ # ("a health signal that cannot be computed must not read as a clean bill").
+ # FIX: readability travels as a fourth element of the SAME correlated statement -- not
+ # as a second read, because the page-budget invariant holds this lookup to one
+ # statement and the round-10/11 plan tests pin the window predicates byte-identical.
+ # The expression is ``json_valid(coalesce(nullif(metadata_json, ''), '{}'))``, and the
+ # wrapper is load-bearing rather than defensive: a NULL or empty column is VALID -- an
+ # absent blob is not an unreadable one -- while ``json_valid(NULL)`` is NULL and
+ # ``json_valid('')`` is 0, either of which would otherwise mark every metadata-free run
+ # unreadable. It is carried as a VALUE rather than raised, because the window is per
+ # definition and one bad row must not take the page down, which is this id's own rule.
+ # ONE UNREADABLE ROW ANYWHERE IN THE WINDOW DEGRADES THE WHOLE DEFINITION TO
+ # ``HEALTH_UNKNOWN`` rather than being skipped, and the reasoning is worth keeping
+ # because skipping looks like the conservative choice and is not: "both answers this
+ # function can give are claims over the WHOLE window -- ``failing`` reads the newest
+ # verdict and ``healthy`` asserts the absence of a failure across all of them -- so a
+ # window with a hole in it cannot support either." The counters go out as ``(0, 0)``,
+ # the same shape ``definition_health_batch`` already reports when the read itself
+ # raises, so a caller rendering "N consecutive failures" beside an unknown badge cannot
+ # print a number that was never computed. The degrade is scoped to the WINDOW, not the
+ # lifetime -- otherwise one ancient bad blob would blank a definition's badge forever.
+ # THE ASSERTION ON THIS ID'S OWN TEST WAS ALSO TIGHTENED, and the loosening it
+ # replaces is instructive: it read ``health in {"failing", "unknown"}``, a disjunction
+ # that was green on the broken code. It is now an equality on ``unknown``, so this
+ # entry's semantics strengthen without its locator moving.
+ # One subordinate test carries this id --
+ # ``test_a_malformed_history_row_reports_unknown_rather_than_a_verdict`` -- with three
+ # definitions: the unreadable row newest (so "the latest run failed" is unknowable),
+ # inside the window but not newest (so ``degraded`` is not answerable either), and aged
+ # out of the window by eleven later successes, which must still read ``healthy`` and is
+ # the negative control for the scoping claim.
+ # It takes no id of its own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_one_malformed_metadata_row_does_not_blank_health_for_every_definition
+ - id: HFR-073
+ name: a second failure in one streak is skipped rather than notified
+ status: covered
+ kind: failure
+ layer: unit
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_second_failure_in_streak_is_skipped_not_notified
+ - id: HFR-074
+ name: a second failure defers while the streak's first notice is still pending
+ status: covered
+ kind: failure
+ layer: unit
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_second_failure_defers_while_first_notice_is_still_pending
+ # PR6 review round 2 (#1072). PR6's reserved range ends at HFR-074, which the
+ # entries above consume in full, so these four BORROW from PR2's HFR-075…089
+ # block. Flagged rather than taken silently — §10.7 exists because PR1 and PR5
+ # picked ranges independently. PR2 must start at HFR-079, or the plan should
+ # extend PR6's range to 078 and PR2's block move up.
+ - id: HFR-075
+ name: the duplicate short-circuit reports its receipt as delivery evidence
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # PR6 review round 7 (#1072). A subordinate test carries this same id --
+ # ``test_the_duplicate_short_circuit_receipt_acks_a_workbench_rung`` -- because
+ # once the workbench target class may acknowledge ONLY on a persisted receipt,
+ # "which evidence does the dedup path report" stops being a bookkeeping detail
+ # and becomes the difference between a redelivery loop and a correct ack. The
+ # short-circuit fires when ``agent_message_exists`` already sees the notice's
+ # idempotency key: nothing is re-sent, so if that path reported ``delivery_only``
+ # an avibe notice whose row is already durable would be refused on every pass,
+ # burn its attempts and dead-letter a receipt the user demonstrably has.
+ # NO PRODUCT FIX WAS NEEDED: the short-circuit already fills
+ # ``DeliveryEvidence.persisted_row`` with a ``duplicate_short_circuit`` receipt,
+ # so it classifies as ``receipt`` and satisfies the strict source. The test pins
+ # that in the terms the policy is written in -- it asserts the target's declared
+ # ack source IS the receipt-only one and that ``_rung_acknowledges`` accepts the
+ # evidence -- so a later refactor of the dedup branch cannot silently downgrade
+ # it. Verified red by dropping the ``persisted_row`` assignment: both this and the
+ # original test then fail on ``'delivery_only' == 'receipt'``.
+ # It takes no id of its own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_the_duplicate_short_circuit_reports_its_receipt
+ - id: HFR-076
+ name: a raising delivery rung consumes an attempt instead of retrying forever
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # PR6 review round 6 (#1072), F8. A second, subordinate test carries this same
+ # id -- ``test_a_stale_drain_pass_cannot_overwrite_a_newer_acknowledgement`` --
+ # the same bound attacked from the other side of the clock. During a service-lock
+ # handoff an old drain can stay suspended in the awaited send while the new owner
+ # reads the same pending notice and delivers it; the late pass's
+ # read/modify/write was keyed by run id alone and guarded only on the notice
+ # still EXISTING, so it could rewrite ``sent`` back to ``pending`` -- re-sending
+ # a delivered notice -- or forward to ``failed``, a dead letter burying a real
+ # receipt. Ownership is checked once at the top of the pass and never re-checked
+ # across the await, which is the check-then-act gap.
+ # FIX: every drain write re-asserts the ``(state, attempts)`` it was decided
+ # from inside ``update_owed_failure_notice`` (as a Python comparison in this round;
+ # see round 8 below, which moved it into the UPDATE's WHERE clause) -- the
+ # same write-re-asserts-its-read idiom as ``DefinitionWriteExpectation``, without
+ # reusing the class, whose predicate is over ``run_definitions`` lifecycle
+ # columns rather than a blob in ``agent_runs.metadata_json``. ``attempts`` is in
+ # the predicate so two passes reading the same value cannot both consume the
+ # increment, and ``updated_at`` deliberately is NOT: a fresh stamp does not carry
+ # it, which would make the guard refuse every write. The losing pass no-ops
+ # silently rather than raising, because it has nothing to repair and the next 2 s
+ # tick reads the winner's state; raising would log an exception on every handoff.
+ # It takes no id of its own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 7 (#1072) audited that guard for TOTALITY rather than for the
+ # one write the finding named, because a CAS that covers four of five writes
+ # protects nothing. Every production transition of a notice AFTER the drain's read
+ # now passes the expectation: the deferral (backoff + ``defer_reason``), the skip,
+ # the ack, the dead letter and the retry -- five call sites, one read, one
+ # ``expect``. The deferral is the easy one to miss, since it consumes no attempt,
+ # but it does move ``next_attempt_at`` and would have shadowed a newer pass's ack
+ # behind a fresh backoff. Two neighbouring writers were audited and deliberately
+ # left unguarded: ``_merge_owed_failure_notice``'s four call sites are terminal
+ # STAMPS folded into the same UPDATE that transitions ``agent_runs.status``, and
+ # ``_owed_failure_notice_for_transition`` refuses to overwrite an existing notice
+ # at all. That half still holds: both ride the transition itself, so there is no gap
+ # and an expectation there would have nothing to compare against. The remaining
+ # unguarded calls are test-only backoff rewinds.
+ # CORRECTED IN ROUND 9. The same audit also excused ``stamp_binding_change_notice``
+ # as "likewise a pre-read stamp inside its own guarded read/modify/write ... not a
+ # post-read transition, so an expectation there would have nothing to compare
+ # against". That was right about the ORDER and wrong about the CONNECTION: the
+ # excuse only covers a competing pass on the same statement, and cyhhao
+ # demonstrated it fails across connections. The stamp reads a LIVE run and runs
+ # before ``complete()``, so a second connection can settle that row -- ``failed``
+ # (stamping its own notice) or ``canceled`` -- between its SELECT and its UPDATE,
+ # exactly the gap this id's own guard was moved into SQL to close.
+ # FIX: the stamp now carries a CAS of its own in the UPDATE's WHERE clause -- the
+ # status the SELECT saw, verbatim, plus ``owed_notice_absent()`` plus ``json_valid``
+ # over the same expression -- and writes through ``json_set`` rather than a composed
+ # blob. See HFR-099's round-9 paragraph for both damage directions and the tests.
+ # PR6 review round 8 (#1072) found the guard itself was a CHECK-THEN-ACT: it read
+ # the row, compared ``(state, attempts)`` in Python, then issued its UPDATE, and
+ # under pysqlite a bare SELECT emits no ``BEGIN`` (the same fact
+ # ``upsert_definition_in_connection`` documents), so no lock spans that gap and the
+ # write lock is first taken by the UPDATE. Two passes could both read
+ # ``(pending, N)``, both pass the comparison, and both write -- the round-6 guard
+ # narrowed the window from a whole awaited send to sub-millisecond without closing
+ # it, and the losing write is the terminal ``failed`` dead letter.
+ # FIX: the predicate moved into the UPDATE's WHERE clause
+ # (``owed_notice_state_unchanged``), evaluated by SQLite in the same statement that
+ # writes, with the loss read off ``rowcount`` -- the ``DefinitionWriteExpectation``
+ # idiom now in full, not just in shape. Two subordinate tests carry this same id:
+ # ``test_a_notice_write_refuses_a_race_settled_after_its_own_read`` commits the
+ # winner from a second connection INSIDE that gap (a
+ # ``before_cursor_execute`` hook on the loser's UPDATE), which only an SQL-level
+ # predicate survives, and
+ # ``test_the_notice_expectation_reads_the_same_in_python_and_in_sql`` pins the cost
+ # of the move -- ``notice_write_expectation`` and its new SQL twin must normalize a
+ # missing/null/string/non-integer ``attempts`` identically, or the guard would
+ # refuse writes nobody raced.
+ # They take no id of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 8 (#1072), SECOND FINDING: that CAS is a write guard, and the
+ # duplicate it prevents is a duplicate ROW, not a duplicate MESSAGE. It correctly
+ # stops a stale pass from overwriting a newer acknowledgement, but it does not
+ # stop the stale pass from DELIVERING. Both owners can read ``pending``, both then
+ # await ``_emit_failure_notice``, and only after the external send does either
+ # attempt the CAS -- so the loser is refused at the database having already spoken
+ # to the user. ``MessageDispatcher.emit_agent_message`` checks
+ # ``agent_message_exists`` before ``send_message`` and persists after it, so two
+ # concurrent drain owners both pass the pre-send lookup and both send before
+ # either receipt exists; the unique persisted ``(platform, native_message_id)``
+ # row resolves only the later database race and cannot recall the duplicate
+ # message already delivered.
+ # FIX: the attempt is CONSUMED BEFORE the external send, as a guarded claim
+ # through the existing CAS (``expect=(pending, N)`` evaluated by SQLite in the
+ # UPDATE's WHERE clause), so exactly one of any number of passes that read
+ # ``(pending, N)`` wins and every loser returns WITHOUT SENDING.
+ # ``next_attempt_at`` doubles as the recovery lease
+ # (``CLAIM_LEASE_SECONDS = 600.0``, chosen above both the worst-case five-rung
+ # ladder walk at ~30-60 s adapter HTTP timeouts and the 512 s backoff cap), so a
+ # claimant that dies mid-send is reclaimed after a bounded delay instead of
+ # stalling forever -- no SQL text change and no migration, since the lease rides
+ # the column the eligibility index already ranges on. The post-read guard in
+ # ``_deliver_one_failure_notice`` widens from a bare ``state == pending`` check to
+ # full eligibility (``owed_notice_eligible``, factored in ``storage/background.py``
+ # and shared with ``list_owed_failure_notices``' own Python re-check so the two
+ # copies cannot drift). That half is not optional: the claim ALONE is insufficient,
+ # because an owner that listed before the claim would re-read ``(pending, 1)`` and
+ # send a duplicate anyway.
+ # Two further subordinate tests carry this same id.
+ # ``test_two_owners_reading_one_pending_notice_deliver_it_exactly_once`` runs two
+ # services over one SQLite file on two connections, suspends the first exactly at
+ # the IM adapter's send boundary, lets the second take ownership and run to
+ # completion, and asserts exactly one outbound send and one durable receipt --
+ # red on 93c1b379 with "got 2".
+ # ``test_a_dead_claimants_lease_expires_into_exactly_one_recovered_delivery``
+ # cancels the claimant while it holds the lease, rewinds the lease, and requires
+ # recovery to deliver once while consuming its OWN claim, so ``attempts == 2``.
+ # THE RESIDUAL IS AT-LEAST-ONCE DELIVERY, AND MUST NEVER BE DESCRIBED AS
+ # EXACTLY-ONCE. A duplicate now requires the claimant to die (or stall past the
+ # lease) AFTER the transport accepted the send and BEFORE
+ # ``persist_agent_message`` committed; a crash after the receipt persisted is
+ # absorbed by the HFR-075 duplicate short-circuit, which reports the found row as
+ # a receipt and acks. Before this fix duplicate delivery was SYSTEMATIC -- every
+ # concurrent-owner race duplicated, with a window the full width of a send and no
+ # crash required. What remains is irreducible without a transport-honoured
+ # idempotency key, which Slack/Discord/Telegram plain sends do not offer.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 9 (#1072). The claim bounds a competing owner, and by lease
+ # expiry it bounds an owner that DIES. Neither bounds an owner that never RETURNS. A
+ # transport that accepted the request and hung -- a half-open socket, a platform that
+ # stopped answering, an adapter with no timeout of its own -- leaves the pass
+ # suspended inside the send, the row ineligible for as long as the lease holds, and
+ # nothing anywhere reporting it: the drain is not crashed, it is STOPPED, so this
+ # notice and every notice behind it are owed indefinitely.
+ # FIX, in two halves that are both required.
+ # (a) ``NOTICE_DELIVERY_TIMEOUT_SECONDS = 300.0`` bounds ONE delivery -- the whole
+ # ladder walk, not one rung. The worst legitimate five-rung walk (each rung able to
+ # sit on an adapter's 30-60 s HTTP timeout) comes to AT MOST this same 300 s, so
+ # the bound MATCHES the worst case rather than exceeding it: a walk that saturates
+ # every rung's timeout is consumed as an ordinary failed attempt, retried on the
+ # declared backoff, and a rung that had already persisted its receipt is absorbed
+ # by the duplicate short-circuit on the retry. The deadline also stays strictly
+ # BELOW ``CLAIM_LEASE_SECONDS``' 600 s, so a timed-out claimant is cancelled and its
+ # backoff durably written while its OWN lease still holds and a replacement claimant
+ # can never coexist with a transport coroutine that is still unwinding. The deadline
+ # CONSUMES the claim rather than rewinding it: the attempt was already made durable
+ # before the send, so the timeout takes the ordinary retry path under the claim's own
+ # ``expect`` and arms the declared interval. Rewinding ``attempts`` instead would let
+ # a transport that hangs every time retry without bound and never dead-letter --
+ # precisely the unbounded loop this id exists to prevent, reached by a different
+ # road. ``asyncio.wait_for`` cancels the inner task and AWAITS that cancellation
+ # before raising, so no detached transport coroutine survives the deadline.
+ # (b) The drain is no longer awaited by ``_watch_store``; it is dispatched as a
+ # SINGLE-FLIGHT background task. The deadline alone would only shorten the stall to
+ # 300 s, and a deadline short enough to hold a 2 s tick would cancel legitimate
+ # deliveries -- and the watch is one coroutine running every periodic pass in
+ # sequence, so a wedged notice stalled request draining, callbacks, vault callbacks
+ # and the stale-run sweep too. Single-flight rather than a task per tick, which would
+ # replace a stalled loop with an unbounded pile of coroutines each re-reading and
+ # re-claiming: a tick that finds the previous pass still running simply skips, since
+ # eligibility is re-read from the row every pass. The dispatched task's exception is
+ # retrieved in a done callback, because a fire-and-forget pass has no reader and a
+ # drain that has been failing every tick for a week would otherwise surface only as
+ # an asyncio "never retrieved" warning at collection time.
+ # SAME ROUND, THE SEQUENCE ITSELF WAS OFF BY ONE. ``BACKOFF_SECONDS`` declares five
+ # intervals, and the arming indexed on the INCREMENTED attempt number: the first
+ # failed attempt armed ``BACKOFF_SECONDS[1]``, so the 2 s rung was never used, the
+ # 512 s cap was never reachable, and the ladder ran 8/32/128/512 and dead-lettered a
+ # rung early. Not cosmetic -- ``CLAIM_LEASE_SECONDS`` is justified as exceeding
+ # ``BACKOFF_SECONDS[-1]``, an invariant about an interval the code could not arm.
+ # FIX: the Nth failed attempt arms ``BACKOFF_SECONDS[N - 1]``, one interval per
+ # consumed attempt in order, and ``MAX_ATTEMPTS`` is DERIVED as
+ # ``len(BACKOFF_SECONDS) + 1`` rather than chosen, because N attempts are separated
+ # by N-1 waits plus the attempt that finds no interval left. Total ladder time moves
+ # 680 s to 682 s.
+ # Four subordinate tests carry this same id.
+ # ``test_a_wedged_delivery_times_out_into_one_durably_retryable_claim`` wedges the
+ # send, requires the delivery to RETURN, and asserts the row comes back as ONE
+ # durably retryable claim: the attempt consumed, the declared interval armed, no
+ # second send.
+ # ``test_a_wedged_notice_delivery_does_not_stall_the_store_watch`` wedges one notice
+ # and requires an unrelated periodic pass to keep ticking -- red on 93c1b379 by
+ # hanging until the test's own deadline, which IS the defect.
+ # ``test_backoff_spaces_attempts_and_terminates_in_a_dead_letter`` is strengthened
+ # from "the spacing increases" to the exact sequence, plus both exhaustion edges:
+ # every declared interval armed exactly once in order, and the attempt that finds
+ # none left dead-letters. Red on 93c1b379 with ``[8, 32, 128, 512] != [2, 8, 32,
+ # 128, 512]``.
+ # ``test_the_notice_timing_constants_bound_each_other_as_documented`` pins the
+ # arithmetic both prose arguments rest on, so retuning one constant cannot silently
+ # invalidate the other's justification.
+ # THE RESIDUAL IS UNCHANGED, AND MUST STILL NEVER BE DESCRIBED AS EXACTLY-ONCE.
+ # Cancel-after-transport-accept is a SECOND ENTRANCE to the at-least-once window
+ # ``CLAIM_LEASE_SECONDS`` already documents, not a new one: a claimant cancelled
+ # after the transport accepted its request has delivered without acknowledging,
+ # which is the state a dying claimant leaves. And the deadline's bound is a STATED
+ # ASSUMPTION about our adapters rather than a proof -- none of them swallow
+ # ``CancelledError``, but one that did would hang the deadline too and re-wedge the
+ # dispatched drain task, though no longer the store watch. That is what half (b) buys
+ # on top of half (a): it confines the failure to notice delivery instead of stopping
+ # every periodic pass.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 12 (#1072), THREE FINDINGS on this id.
+ # (D) THE CAS WAS INCOMPLETE, AND THE ROUND-8 PARAGRAPH ABOVE DESCRIBES IT AS
+ # ``(state, attempts)`` BECAUSE THAT IS WHAT IT WAS. Eligibility is decided from THREE
+ # fields -- ``owed_notice_eligible`` reads ``state`` and ``next_attempt_at``,
+ # ``next_attempt`` reads ``attempts`` -- and the one left out is the only field a
+ # DEFERRAL writes. A deferral touches neither ``state`` nor ``attempts``, so a claimant
+ # that read before a concurrent owner's deferral still matched its own expectation, won
+ # the CAS, and ERASED the deferral: two notices per streak in the stale-cutoff lane, and
+ # a ``DEFERRAL_RECHECK_SECONDS`` that any stale claimant could cancel -- which is the
+ # starvation the durable deferral exists to prevent.
+ # FIX: ``notice_write_expectation`` returns ``(state, attempts, next_attempt_at)`` and
+ # ``owed_notice_state_unchanged`` gains the third predicate, reusing
+ # ``OWED_NOTICE_NEXT_ATTEMPT_SQL`` verbatim rather than retyping it -- "a divergent copy
+ # of an indexed expression is exactly how the eligibility index was built and silently
+ # ignored twice." ``next_attempt_at`` and NOT ``updated_at``, which
+ # ``DefinitionWriteExpectation`` deliberately refuses: a row-version marker refuses
+ # benign writes and a freshly stamped notice carries none, whereas ``next_attempt_at`` is
+ # stamped unconditionally by every stamper and a legacy notice predating the field reads
+ # ``""`` identically on both sides. Deliberately NOT stripped on the Python side, unlike
+ # ``owed_notice_eligible``, because SQLite does not strip and stripping here would refuse
+ # a write over a padded instant nobody raced. A completion of round 8's value-CAS to the
+ # decision's full read-set, not a reversal of it.
+ # THE ROUND-8 KNOWN-BY-DESIGN SENTENCE IS RETRACTED. Round 8 recorded, as a deliberate
+ # non-guarantee, that two owners deferring one notice from the same read BOTH land. They
+ # no longer do: the first moves the field the second re-asserts, so the second LOSES.
+ # That is correct under the new contract rather than a benign-refusal regression, and the
+ # distinction is the observable state -- "the refused write was refused because the world
+ # had already moved to the state it was trying to establish". The outcome is
+ # observationally identical: the notice is deferred either way, no attempt is consumed
+ # either way, and the two recheck instants differ by the microseconds between two owners
+ # reading the clock. Pinned by
+ # ``test_a_second_identical_deferral_loses_the_cas_without_changing_the_outcome``, beside
+ # ``test_a_stale_claim_cannot_overwrite_a_concurrent_deferral``. Two pre-existing tests
+ # were widened in place rather than renamed: the race test now asserts ``expect[:2]``
+ # plus the live instant rather than a literal that would pin a wall clock, and the
+ # Python/SQL parity test grows five ``next_attempt_at`` shapes and a third "wrong
+ # neighbour" tuple, "because a predicate that silently ignored the third element would
+ # pass every other assertion in this test".
+ # (F) A MALFORMED ``attempts`` WEDGED THE BATCH INSTEAD OF DEGRADING. ``next_attempt``
+ # did ``int(notice.get("attempts") or 0)``, which raises on a nonnumeric string or a
+ # container. Nothing crashes -- the drain's per-row handler catches it -- "and that is
+ # precisely what makes it bad": the exception escapes BEFORE the claim, so it writes NO
+ # state, the row keeps its malformed value, stays eligible, and re-occupies a slot in the
+ # batch of ten on every 2 s tick. Every notice behind it starved, with a log line per
+ # tick and a drain that looks busy rather than broken. FIX: ``_attempts_read`` degrades
+ # to 0. Not a fresh choice -- ``notice_write_expectation`` already normalizes this field
+ # the same way for the CAS predicate, and SQLite's
+ # ``CAST(coalesce(json_extract(...), 0) AS INTEGER)`` reads a nonnumeric value as 0 too,
+ # so all three readings agree, "which is what lets the guarded write MATCH and the row
+ # advance through claim, backoff and -- if it keeps failing -- the visible dead letter. A
+ # different degraded value here would refuse the claim on every pass and reach the same
+ # wedge by a quieter road." Three subordinate tests:
+ # ``test_a_malformed_attempts_value_degrades_instead_of_raising`` over six shapes,
+ # ``test_the_python_and_sql_readings_of_a_malformed_attempts_agree`` for the three-way
+ # agreement, and ``test_a_malformed_attempts_row_advances_instead_of_occupying_the_batch``
+ # for the consuming outcome -- the batch slot released, not re-occupied forever.
+ # (L) ONE PASS COULD HOLD THE WHOLE BACKLOG -- and the obvious diagnosis is REFUTED
+ # FIRST, which is why this paragraph is worth reading twice. A wedged batch does NOT
+ # re-select itself forever: ``list_owed_failure_notices`` orders by ``next_attempt_at
+ # ASC``, least-recently-deferred first, so the fresh backoff instants a slow pass just
+ # armed sort BEHIND a notice stamped while it was working, and the newcomer is picked up
+ # next pass. Starvation by re-selection was already closed by that ordering. What IS the
+ # defect is the SERIAL COST of one pass: deliveries within a pass run one at a time
+ # deliberately -- row #2 of a streak only observes row #1's ``sent`` because the passes
+ # are ordered, so parallelising them reopens the same-streak duplicate window that
+ # serialization closes -- but a batch of ten each legitimately sitting on
+ # ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` is 3000 s, fifty minutes, before the pass so much
+ # as returns, and a notice stamped one second in waits behind all of it. So the fix is a
+ # BUDGET, not concurrency: ``NOTICE_DRAIN_PASS_BUDGET_SECONDS``, declared derivationally
+ # as ``2 * NOTICE_DELIVERY_TIMEOUT_SECONDS`` rather than as a literal 600.
+ # Two-sided, like every other constant on this id: at least ONE full worst-case delivery,
+ # or a pass could spend its budget before finishing the notice it started and make no
+ # progress at all; and small enough that a fresh notice's wait is a function of the
+ # budget rather than of the batch size -- worst wait becomes budget plus one delivery
+ # instead of ten deliveries, and stops growing when the batch limit does. Checked BETWEEN
+ # notices and never mid-delivery: "cancelling a delivery already on the wire would trade
+ # a slow pass for a duplicate, and the walk already has its own deadline." A truncated
+ # pass costs the rows it did not reach NOTHING -- never claimed, no attempt consumed, no
+ # backoff armed, and the ASC ordering puts the oldest of them first. Two subordinate
+ # tests: ``test_one_pass_stops_at_its_fairness_budget_instead_of_holding_the_backlog``
+ # and ``test_the_pass_budget_admits_one_full_worst_case_delivery``, the lower side of the
+ # argument as an assertion.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_a_raising_delivery_consumes_an_attempt_instead_of_retrying_forever
+ - id: HFR-077
+ name: a drained failure notice does not become a live auth prompt
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_the_drain_does_not_turn_an_owed_notice_into_a_live_auth_prompt
+ - id: HFR-078
+ name: the owed-notice lookup is bounded in SQL and does not scan settled history
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # PR6 review round 12 (#1072). The eligibility lookup was bounded here, and HFR-095
+ # bounded the streak read, but ONE read on the same 2 s tick was still deciding in
+ # Python what the index could decide for it: ``earliest_unsettled_run_before``
+ # selected every ``queued``/``running`` row for the definition and applied both the
+ # anchor position and the staleness cap as a Python ``continue``. So a definition
+ # holding a large nonterminal backlog -- a paused ``create_per_run`` task, a queue
+ # drained slower than it fills -- paid that whole backlog per notice per tick "to
+ # answer a question whose answer is at most one row".
+ # FIX: both filters become SQL TERMS. The anchor is a ROW VALUE
+ # (``(created_at, id) < (?, ?)``) for the reason ``failure_streak_decision`` spells
+ # out -- ``created_at`` alone is not a position, because several writers stamp a whole
+ # batch with one value, and a row value keeps the tie-break IN the comparison where
+ # SQLite can constrain it with the index. The staleness cap becomes a lexicographic
+ # ``created_at >= cutoff``, and ``LIMIT 1`` states in the statement what the docstring
+ # already claimed. Served by ``ix_agent_runs_definition_streak``
+ # (``definition_id, created_at, id``): under the older two-column index SQLite
+ # decomposes the row value into a weaker scalar range and recovers the tie-break with
+ # ``USE TEMP B-TREE FOR LAST TERM OF ORDER BY``, which defeats the ``LIMIT 1``'s early
+ # exit -- so the third key is what makes the bound real, not tidiness.
+ # ONE DIVERGENCE IS DOCUMENTED RATHER THAN HIDDEN, and it is a deliberate behaviour
+ # change: the Python filter asked ``_parse_iso_instant`` and SKIPPED the staleness test
+ # when the answer was ``None``, so a row whose ``created_at`` cannot be parsed read as
+ # fresh and blocked the notice for as long as it stayed nonterminal -- "a wait nothing
+ # can bound". A lexicographic cutoff has no such escape and may class the same value as
+ # stale, treating it as settled. That is the duplicate-not-lost direction the cap
+ # itself already chose, so it is the acceptable side to land on. The boundary is
+ # preserved exactly: ``>=``, because the Python test skipped on
+ # ``> stale_after_seconds`` and a row exactly at the cap was kept.
+ # Three subordinate tests carry this id.
+ # ``test_the_predecessor_read_is_bounded_and_seeks_rather_than_scans`` asserts the
+ # RESULT-SET SIZE separately from the plan, which is the reusable lesson: "a read that
+ # filters in Python passes both a statement-count budget and a plan that names an
+ # index while still materialising an unbounded population."
+ # ``test_the_sql_predecessor_read_matches_the_python_filtered_one`` is the parity
+ # oracle against ``_python_earliest_unsettled_before``, byte-for-byte the production
+ # algorithm as of ``3578f2b6``.
+ # ``test_an_unparseable_created_at_reads_as_stale_rather_than_as_a_blocker`` pins the
+ # divergence above as intended rather than accidental.
+ # A fourth names the two cases the randomised fixture only SAMPLES --
+ # ``test_the_predecessor_read_breaks_created_at_ties_by_id_and_stays_bounded_on_no_match``
+ # -- because "reproducible is not the same as named": nothing in a seeded fixture fails
+ # if the tie-break regresses for a reason its row pool stops generating. It pins both
+ # failure directions of the tie (a scalar ``<`` drops the whole tied group and loses a
+ # real blocker, the duplicate direction; a scalar ``<=`` admits the anchor itself and
+ # defers every notice behind its own run forever) and requires the ``None`` answer to
+ # stay bounded too, since ``None`` is what RELEASES the notice and is the common case
+ # on a healthy definition. Red on ``b43837f7``: the no-match read handed Python 2 rows.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_the_owed_notice_lookup_does_not_scan_settled_history
+ # PR6 review round 5 (#1072). HFR-079 was the one id left unused when the round-3
+ # block started at 080; the block is PR6's up to 099, so it is taken here rather
+ # than skipped.
+ - id: HFR-079
+ name: a replayed failure notice reaches the user without touching the live lifecycle
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The drain replayed a historical failure through the LIVE emitter and then
+ # neutralized its live behaviour one argument at a time: a non-settling output,
+ # an auth-recovery bypass, an explicit failure id. ``settle_terminal_failure``
+ # still ran in a ``finally``, so the replay stayed inside the live turn
+ # lifecycle with a defused payload — and four review rounds found a settlement,
+ # an auth and an identity defect in the gaps between those switches.
+ # FIX: ``core/backend_failure.py::emit_replayed_backend_failure`` — one visible
+ # ``notify`` built from ``backend_failure_notification_output`` and nothing else.
+ # No ``result``, so no turn settlement, no status-bubble teardown and no
+ # runtime-turn release can be reached at all; no auth recovery; an identity that
+ # is authoritative by construction. The run is terminal by construction too: a
+ # notice is owed only once the row is settled.
+ # Asserted at both ends over a real dispatcher and a migrated state DB: the user
+ # gets the persisted notify row and the notice acks on that receipt, AND the live
+ # emitter is unreachable (patched to raise under both module spellings, with the
+ # drain's import proven absent), exactly one emission and it is the notify, the
+ # output settles neither turn nor run, no live-turn hook fires, and the
+ # controller's auth service raises on any attribute read.
+ # PR6 review round 6 (#1072), F7. Two further subordinate tests carry this same
+ # id -- ``test_a_workbench_addressed_notice_lands_as_a_durable_inbox_row`` and
+ # ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id`` -- because "reaches
+ # the user" never held for a workbench-addressed rung. This test set
+ # ``deliver_key="slack::channel::C123"`` and so only ever exercised rung (1);
+ # every ``avibe::project::...`` target -- the bound session's scope, the creator
+ # scope, and rung (5) itself -- was parsed with ``parse_session_key``, which
+ # rejects the ``project`` scope type, and ``_add`` swallowed the error. For an
+ # Avibe-only definition the ENTIRE ladder was empty, so its failures exhausted
+ # their retries and dead-lettered instead of notifying.
+ # FIX: ``_add`` falls back to ``parse_scope_id`` for three-part scope ids -- five
+ # part ``::thread::`` keys stay on the strict parser, which is the only one that
+ # can express a thread -- and an avibe rung acknowledges on the persisted
+ # ``messages`` receipt ONLY. That second half is not optional:
+ # ``AvibeBot.send_message`` mints a synthetic id whether or not anything durable
+ # landed, so a ``delivery_only`` ack would have flipped "nowhere to write the
+ # row" from a visible dead letter into a permanent false ``sent`` -- strictly
+ # worse than the bug. Receipt-gating one platform in turn forces PER-RUNG
+ # evidence, since a single ``DeliveryEvidence`` latches ``delivered`` on the
+ # first ``delivered_id`` and one rejected rung would otherwise vouch for every
+ # later one.
+ # The delta rung (5) really buys is an ARCHIVED session: ``_session_row`` has no
+ # status filter where ``resolve_session_id_target`` refuses archived, so rung (2)
+ # is gone and rung (5) still delivers. A run whose session row is gone entirely,
+ # and a definition that never had one, still dead-letter VISIBLY -- the
+ # workspace-level inbox scope that would close that is product surface, not a bug
+ # fix. They take no ids of their own because PR6's block is full at 099 and 100+
+ # is contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # RETRACTED IN ROUND 12 -- and it is the sentence directly above that is wrong, so
+ # read it as history rather than as contract. "A run whose session row is gone
+ # entirely, and a definition that never had one, still dead-letter VISIBLY" was
+ # recorded as Known-By-Design across four rounds, on the reasoning that the
+ # workspace-level inbox scope which would close it "is product surface, not a bug
+ # fix". THE PLAN DISAGREES, IN WRITING AND BY NAME. #1044 merged carrying two dated
+ # corrections that assign exactly this to PR6:
+ # "Rung (5) is mandatory, not an implementation check (corrected 2026-07-27)" --
+ # which names the earlier conditional framing as "a way to ship PR6 with the failure
+ # still silent" -- and "'Widen the push helper' was not a mechanism (corrected
+ # 2026-07-29, review)", which specifies the synthetic workspace-notifications session
+ # and says outright "This is in PR6's scope, not a follow-up, because without it rung
+ # (5) is as empty as the four above it" (docs/plans/harness-run-reliability.md
+ # :3170-3174, :3196-3222, with the D5 body requirement at :3165-3168).
+ # THE POPULATION THIS WAS LOSING is not exotic: a definition created by a plain
+ # ``vibe task add`` records no caller provenance at all
+ # (``_definition_creation_metadata_from_caller`` returns ``{}`` for a null caller
+ # context), so rungs (3) and (4) are empty; with no deliver key and no session
+ # binding, rungs (1), (2) and the session-derived rung (5) candidate are empty too.
+ # EVERY rung empty meant the notice could only dead-letter -- visible to somebody who
+ # goes looking, which is precisely the population D1 is about.
+ # FIX (round 12): the blocker was a missing HOME, not a missing writer.
+ # ``persist_agent_message`` declines to write only when an avibe context resolves
+ # neither a scope nor a session row, so rung (5) now resolves-or-creates ONE reserved
+ # workspace-notifications session (``resolve_workspace_notice_session`` in
+ # ``storage/agent_session_rows.py``) and addresses it exactly like any other avibe
+ # session: the same ``avibe::project::<session id>`` candidate, the same
+ # ``_session_row`` lookup, the same receipt-only ack policy the paragraph above
+ # forced, and the same inbox / unread / realtime / Web Push machinery. Nothing
+ # downstream learns a new row shape, which is the whole point -- the rejected
+ # alternative was a sessionless inbox row, and the plan's own correction records why
+ # that fails: the inbox is per-session by construction at four layers, so widening
+ # the push helper alone "creates nothing -- there is no row to notify about".
+ # THREE IMPLEMENTATION CHOICES DIVERGE FROM THE PLAN'S SKETCH, each for a reason
+ # worth keeping, because the plan asked for a row "hidden from ordinary session
+ # lists, exempt from ``/new`` clears and eviction".
+ # * NOT hidden. ``visibility='background'`` is filtered out of
+ # ``list_inbox_sessions``, so hiding the row would hide the inbox card rung (5)
+ # exists to show -- the plan's own requirement defeats itself. The row is
+ # ``foreground`` and named through ``vibe/i18n`` instead
+ # (``harness.notice.workspaceSession``).
+ # * NOT exempt. Durability is by lazy RECREATION rather than by exemption, so no
+ # ``/new`` clear path and no eviction code learns a special case (no PR5 file is
+ # touched); if the row is removed, the next notice simply makes it again.
+ # * Idempotence rests on the PRIMARY KEY, not on a lock alone:
+ # ``WORKSPACE_NOTICE_SESSION_ID`` is spelled outside ``SESSION_ID_ALPHABET``, so
+ # ``new_session_id`` can never mint it, and the create re-decides under
+ # ``reserve_write_lock`` so two racing drain owners produce one row. The row
+ # carries NO scope, because every avibe project scope is a row in
+ # ``list_projects`` and a reserved one would mint a fake sidebar project.
+ # The old pin is INVERTED rather than deleted --
+ # ``test_a_session_less_definition_dead_letters_rather_than_going_silent`` is now
+ # ``test_a_session_less_definition_now_reaches_the_workspace_inbox`` -- and the
+ # plan's two owed tests exist by name:
+ # ``test_a_caller_less_cli_definition_still_delivers_its_failure_notice``, built with
+ # ``caller_context=None`` so the emptiness is STRUCTURAL rather than mocked, and
+ # ``test_workspace_notification_session_is_created_once_and_reused``.
+ # RESIDUALS, three, stated because none of them is closed: the session appears in
+ # ordinary session lists (the direct cost of choosing foreground over hidden); its
+ # ``agent_backend`` is empty, since it has no backend and no turns; and D5's
+ # remaining body item -- the creation channel/thread with a deep link -- is NOT
+ # implemented, only the failure class and last-success lines are (see HFR-094's
+ # round-12 paragraph). That half awaits the plan's numbered-deferral mechanism rather
+ # than being claimed here.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header) -- and the offer to
+ # take §10.7's re-drawn HFR-280...319 block is WITHDRAWN as of round 14, for two
+ # independent reasons. The first is a ruling: cyhhao declined to consume an id for this
+ # round, so the subordinate tests documented throughout this file stay subordinate by
+ # DECISION, not merely because the block was full. The second is stronger and outlives
+ # the ruling: THAT BLOCK IS ALREADY DEAD. Master landed HFR-280 in ``807d1eee``
+ # (``feat(search): opt-in include-archived``) -- an unrelated PR that took the first id
+ # of the block §10.7 had just re-drawn for PR6 -- and §10.7's own rule is explicit:
+ # "an overflow block is dead the moment a landed catalog occupies any of it; reassign
+ # from above the highest landed ID, never reuse or straddle." So this is the THIRD
+ # occurrence of the exact failure §10.7 was written to prevent (after PR1/PR5 both
+ # claiming 041...048, and PR5's overflow landing across blocks promised to
+ # PR6/PR2/PR3), and it arrived the same way each previous one did: silently, visible
+ # only on comparing branches by hand. Any future assignment for these tests must be
+ # re-drawn above the highest landed id rather than taken from 280...319. Round 11's
+ # note under HFR-099 should be read with both facts attached.
+ # RETRACTED IN ROUND 14, THREE CLAIMS, and two of them are claims this block made
+ # about its own fix rather than about the code it replaced -- so read the marked
+ # sentences above as history.
+ # (a) "The delta rung (5) really buys is an ARCHIVED session: ``_session_row`` has no
+ # status filter where ``resolve_session_id_target`` refuses archived, so rung (2) is
+ # gone and rung (5) still delivers." REVERSED (round-13 P1, review thread
+ # 3676292667). The mechanism is real and still is; the CONCLUSION was wrong. An
+ # archived ``agent_sessions`` row is "a WRITABLE row that is not a VISIBLE surface":
+ # ``persist_agent_message`` resolves the scope through ``_session_row``, which has no
+ # status filter, so the write lands; a persisted receipt is the workbench class's ack
+ # source, so the rung ACKS and the notice is stamped ``sent`` and never retried; but
+ # ``list_inbox_sessions`` and ``get_inbox_session`` exclude archived sessions, so
+ # there is no inbox card, no ``inbox.session.updated`` patch for an open browser, and
+ # no Web Push. "The user is told nothing and the system believes it told them --
+ # worse than a dead letter, which at least says so." And the receipt-only ack policy
+ # this same block introduced CANNOT catch it: it is blind here precisely because the
+ # write really does happen.
+ # FIX: ``_rung_five_session_id`` reads the row's status and REROUTES rung (5) to
+ # ``WORKSPACE_NOTICE_SESSION_ID`` when it is ``archived``, keyed on that single
+ # literal "not on a whitelist of good ones, so a new status is treated as deliverable
+ # until somebody teaches the read paths otherwise", and failing OPEN (an unreadable
+ # DB returns the original id rather than hijacking the notice). ROUTING, NOT HEALING,
+ # and the asymmetry with round 12 is deliberate: the reserved row may never be
+ # archived at all, so an archived one is corruption and repairing it in place restores
+ # the invariant -- whereas an ordinary session was archived by its owner ON PURPOSE.
+ # "The session is not broken; the ADDRESS is. So the notice moves." Pinned by
+ # ``test_an_archived_ordinary_session_is_rerouted_instead_of_acked_into``, which
+ # asserts the ACK FIRST -- "it passes either way, which is what makes the bug silent"
+ # -- then the surface it claims to have reached, and which also requires the archived
+ # row to stay archived: delivering a notice may not un-archive a session the user
+ # archived deliberately, and the ``failure_id`` stays the bare run id because
+ # rerouting changes the address, never the identity.
+ # (c) "NOT hidden ... The row is ``foreground``" and the reasoning that a hidden row
+ # "would need a schema change this round does not take". SUPERSEDED. The impasse was
+ # real and was mis-diagnosed as a schema problem: ordinary session lists filter
+ # POSITIVELY on ``visibility == 'foreground'``, and so did the inbox -- which is why
+ # ``background`` hid the card as well as the row. The resolution is a THIRD value,
+ # ``visibility='system'``, and a vocabulary split rather than a migration:
+ # ``SESSION_VISIBILITIES`` widens to what may be STORED while
+ # ``ASSIGNABLE_SESSION_VISIBILITIES`` (foreground/background) stays what a CALLER may
+ # choose, and ``INBOX_SESSION_VISIBILITIES = ("foreground", "system")`` admits the row
+ # to ``list_inbox_sessions`` explicitly. The session lists needed NO change at all --
+ # a positive equality filter excludes an unrecognized value for free -- and
+ # ``suppress_delivery`` keys on ``== 'background'`` alone, so realtime and Web Push
+ # are untouched. ``unread_counts_by_session`` had to be edited even though its answer
+ # is the same shape, because its predicate is the NEGATIVE form and "has to name every
+ # visibility the inbox admits or the badge would disagree with the feed it is supposed
+ # to count". Message search deliberately keeps ``== 'foreground'``, narrower than the
+ # inbox. The Agents run graph is excluded EXPLICITLY, because its own filter was
+ # ``!= 'background'``, which admits by default.
+ # NO ALEMBIC MIGRATION, and the reason is worth keeping because it is unusual: "this
+ # row exists in no release (this PR created it), so there is nothing deployed to
+ # migrate." ``_workspace_notice_session_is_usable`` now requires ``system`` EXACTLY
+ # rather than accepting either value, so a round-12/13 development row is converted in
+ # place by the next notice, under the same write lock the create takes -- "the heal is
+ # also the migration". The naive alternative is kept as a PERMANENT REFUTATION rather
+ # than a comment: ``test_background_would_hide_the_card_which_is_why_system_exists``
+ # flips the row to ``background`` by direct SQL and asserts both halves of the cost in
+ # one failure -- the card disappears while the notice row is still persisted and still
+ # stamped ``sent``, and the badge stops counting it.
+ # (d) THE RESIDUALS ARE NOW TWO, NOT THREE. "The session appears in ordinary session
+ # lists" is closed by (c). "D5's remaining body item -- the creation channel/thread
+ # with a deep link -- is NOT implemented" is closed by round 14's origin contract; see
+ # HFR-094's round-14 paragraph, which also retracts the matching sentence there. What
+ # remains: the row's ``agent_backend`` is empty, since it has no backend and no turns;
+ # and it is still one ``DELETE /api/sessions/ses-workspace-notices`` from anyone
+ # holding the id, which the inbox card carries -- "hiding the row from the lists
+ # narrows the blast radius; it does not replace this guard, which is why both exist",
+ # and a delete HEALS on the next notice rather than being exempted.
+ # The system-surface behaviour has its own file, ``tests/test_workspace_system_session.py``,
+ # so only the doctrine is recorded here.
+ # THE ALWAYS-APPEND DOCTRINE (round 14, gate item 2; review thread 3676292675). Round
+ # 12's rule was that the workspace rung fires only for an otherwise-empty ladder, and
+ # that rule was "too narrow by exactly the case #1060 reported (maintainer note
+ # 5120451508): a NON-EMPTY ladder is not a DELIVERABLE one." A watch bound to a
+ # HARD-DELETED session builds a ladder whose every candidate resolves to nothing: each
+ # attempt sends, the receipt-only ack source correctly refuses it, the ``if not rungs``
+ # gate NEVER FIRES, all six attempts burn, and the notice dead-letters with nothing
+ # written anywhere. That silent dead letter is the 3.5 hours of silence in #1060's
+ # field evidence.
+ # TWO DESIGNS ARE RETIRED, named so neither comes back. (i) Round 12's "only when
+ # nothing else resolved". (ii) Round 13's FINAL-ATTEMPT fallback (``ce695b42``), which
+ # appended the same rung last but only on attempt ``MAX_ATTEMPTS``; it closed (i)'s
+ # hole and was overruled anyway -- "correct about the mechanism and overruled on the
+ # trade". It never shipped: the history was rebuilt and that commit is not an ancestor
+ # of the branch, so the catalog never documented it as landed and should not now.
+ # FIX: the workspace rung is appended UNCONDITIONALLY, once, last. "What survives of
+ # round 12's argument is ORDER, and it does the work a condition used to" -- a healthy
+ # preferred rung wins every walk because it comes first, not because a gate suppressed
+ # the fallback. The reviewer's ruling is quoted verbatim in the code rather than
+ # paraphrased: "Append one distinct workspace-notifications target after every
+ # person/context target, even when earlier candidates exist but are stale, unavailable,
+ # or fail delivery. It cannot be conditional on rungs being empty."
+ # THE REROUTE AND THE APPEND COLLAPSE TO ONE RUNG, and that is a property of the
+ # ``_add`` seen-set rather than of a special case: ``_rung_five_session_id`` returns the
+ # bare ``WORKSPACE_NOTICE_SESSION_ID`` constant, so an archived row's rerouted rung (5)
+ # and the unconditional append are byte-identical ``(parsed key, session id)`` tuples
+ # and dedupe for free. Pinned ladder-only by
+ # ``test_an_archived_session_ladder_holds_exactly_one_workspace_rung``, with a live
+ # rung (1) present so it covers POSITION as well as count.
+ # THE TRADE IS RECORDED, WITH ITS ACCEPTANCE, because it is a real behaviour change:
+ # any walk in which every preferred rung fails to deliver now reaches this rung on THAT
+ # walk, delivers, and acks -- so a preferred rung that failed TRANSIENTLY (a platform
+ # blip on attempt 1) permanently routes that one notice to the workspace inbox, and the
+ # user's own channel never receives the copy it would have got a minute later. Accepted
+ # explicitly by the maintainer in the ruling above ("...or fail delivery"), "on the
+ # judgement that a misrouted notice a user can find beats a notice nobody receives".
+ # Scope of the residual is ONE notice, not the definition: the next failure builds a
+ # fresh ladder and the recovered preferred rung wins it again.
+ # THE RESERVED ROW IS NOT MINTED ON HEALTHY INSTALLS, which is the cost the append
+ # would otherwise carry. The rung is appended at ladder-build time but RESOLVED at the
+ # walk, so ``_workspace_notice_session_id`` is only called when the walk actually
+ # reaches it -- the call is made "for its WRITE, not for its return".
+ # ``test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox`` is the negative
+ # pin nothing else in the file carried: one live rung (1) wins, no workspace
+ # ``messages`` row exists, and no reserved session row is created at all.
+ # The unwritable-DB residual MOVED rather than disappeared: from "nothing to append" to
+ # "the rung is skipped", with the walk logging it and preserving a preferred rung's own
+ # refusal rather than overwriting it with the resolve failure. Still a visible dead
+ # letter, pinned by ``test_an_unwritable_workspace_inbox_still_dead_letters_visibly``.
+ # Two further subordinate tests, both renamed from the retired design so no locator
+ # points at a name that never shipped:
+ # ``test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox`` (was
+ # ``test_the_final_attempt_falls_back_to_the_workspace_inbox``) pins the ladder before
+ # any send, the send ORDER, exactly one workspace row, and the round-14 delta --
+ # ``attempts == 1`` on ONE drain pass, where the retired design needed six; and
+ # ``test_replaying_the_workspace_walk_reuses_the_persisted_receipt`` (was
+ # ``test_replaying_the_final_walk_reuses_the_persisted_workspace_receipt``), which is
+ # explicitly a pin rather than a red-first case -- HFR-075's machinery already makes it
+ # green, and its red half is the mutation at the end: delete the persisted row and the
+ # same replay delivers again.
+ # ``attempt`` is no longer threaded into the walk. It used to be, only because the
+ # workspace rung's presence depended on the attempt number; with the rung unconditional
+ # the parameter had no other reader, and ``MAX_ATTEMPTS``, the backoff ladder and
+ # ``LADDER_ACK_SOURCES`` are untouched by all of this.
+ # PR6 review round 7 (#1072) closed the CLASS instead of the third symptom of it.
+ # Three rounds had each found one more target acking on evidence that proved
+ # nothing, because "who may ack on what" lived as a predicate reading a platform
+ # name -- so every new rung, platform or scope type inherited a permissive answer
+ # by default and nothing failed until a user lost a notice.
+ # FIX: ``core/scheduled_tasks.py`` states the policy DECLARATIVELY, as
+ # ``LADDER_ACK_SOURCES``: a total table over (platform kind, scope type) -> the one
+ # evidence source that may acknowledge there. External IM conversations may ack on
+ # their native delivery id; every workbench class, the ``project`` scope type and
+ # any UNREGISTERED platform require a persisted receipt, and
+ # ``UNDECLARED_LADDER_ACK_SOURCE`` makes receipt-only the default an undeclared
+ # class would fall back to, so the unsafe direction is never the implicit one.
+ # ``_rung_acknowledges`` is now one lookup plus one membership test.
+ # A third subordinate test carries this id --
+ # ``test_every_ladder_target_class_declares_its_acknowledgement_source`` -- and it
+ # is STRUCTURAL: it derives both axes from the code (the ``kind`` of every
+ # ``PLATFORM_REGISTRY`` descriptor; the scope-type vocabularies the two ladder
+ # parsers actually enforce, asserted parseable rather than hand-copied) and
+ # requires the table's domain to equal their product exactly -- no missing class,
+ # no stale one. A future rung introducing a platform kind or a scope type cannot
+ # ship without declaring its acknowledgement source. Verified red both ways: adding
+ # a ``workspace`` scope type reports the three missing classes, and renaming a
+ # platform kind reports the stale ones.
+ # The two consuming directions are now both asserted end to end. Direction 1 (the
+ # workbench inbox row) also proves the notice never enters the LIVE
+ # ``emit_backend_failure`` lifecycle, by the same technique as the replay guard
+ # above -- patched to raise under both module spellings, with the drain's import
+ # proven absent from a ``hasattr`` snapshot taken BEFORE the ``raising=False``
+ # patch would have created it -- plus one emission, no turn or run settlement, no
+ # live-turn hook and an auth service that raises on any read. Direction 2 (the
+ # synthetic send id) is driven through TWO drain passes: with the bound session row
+ # DELETED both rungs send and neither persists, so the notice stays ``pending``
+ # with no ``ack_evidence``, one attempt consumed and an error naming the missing
+ # receipt rather than "produced no evidence"; then, with the row restored ARCHIVED
+ # and the backoff rewound, the same still-owed notice is delivered by rung (5),
+ # receipts, and acks with the attempt count carried forward. That second pass is
+ # what makes "walks on and stays retryable" an assertion instead of a claim.
+ # CORRECTED IN ROUND 14: pass 2's SUBJECT changed, though its shape did not. It was
+ # written in round 9 to assert that rung (5) delivers INTO the archived row, on the
+ # premise that an archived row is a valid delivery surface; the premise was wrong (see
+ # the round-14 retraction (a) above), so the test's own docstring now records the
+ # reversal and pass 2 pins the REROUTE instead: the still-owed notice is delivered to
+ # the workspace-notifications session, receipts there, and acks with the attempt count
+ # carried forward. What survives of the round-9 claim is narrower and still worth
+ # having -- "the surviving delta rung (5) buys over rung (2) is a DELIVERY at all, not
+ # a delivery into that particular row" -- and pass 1 additionally has to SUPPRESS the
+ # now-mandatory workspace rung to keep testing what it was written to test.
+ # PR6 review round 8 (#1072) named the ONE premise that table cannot check for
+ # itself, since totality over an axis says nothing about the axis VALUE being
+ # right: ``kind == "im"`` is a claim that the id a send returns was minted by a
+ # platform that reached a person, and it is what entitles ("im", channel|user) to
+ # the permissive rows. ``PlatformDescriptor.kind`` DEFAULTS to ``"im"``, so a
+ # transport added to ``PLATFORM_REGISTRY`` without stating its kind would inherit
+ # that entitlement silently -- and the structural test above would stay green,
+ # because no new kind appeared. If such a transport minted its own id the way
+ # ``AvibeBot.send_message`` does, this whole finding class would reopen with
+ # nothing failing.
+ # FIX (no product behaviour change): the premise is now WRITTEN DOWN where the
+ # claim is made -- a contract comment on ``PlatformDescriptor.kind`` and one beside
+ # ``LADDER_ACK_SOURCES`` -- all five IM descriptors state ``kind="im"`` explicitly
+ # instead of inheriting it, and a fourth subordinate test carries this id:
+ # ``test_every_registry_platform_declares_its_kind_explicitly``. It reads the
+ # registry's AST, because at RUNTIME a defaulted ``kind`` and an explicit
+ # ``kind="im"`` are the same object; it also asserts the parsed ids equal the live
+ # registry's keys, so a registry the AST can no longer read fails rather than
+ # silently passing over nothing. The dataclass default is deliberately KEPT --
+ # ``PlatformDescriptor`` is constructed outside the registry too -- so the
+ # enforcement sits at the registry, not on the shared constructor.
+ # It takes no id of its own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 12 (#1072), TWO COUPLED FINDINGS -- and the coupling is the point:
+ # they ship in one round because each one alone would make the other worse.
+ # (G) A RAISING RUNG KILLED THE WALK. The per-rung ``try/except`` covered
+ # ``_build_context`` alone; the ``emit_replayed_backend_failure`` call one line below was
+ # unwrapped, so any raise from a rung's delivery -- a platform whose settings manager is
+ # gone, a client lookup that fails, an adapter that throws before the transport --
+ # escaped the ``for`` body, unwound through the walk's ``finally``, and landed in the
+ # handler that consumes the attempt and arms the backoff. The next pass restarted the
+ # SAME ladder at rung (1) and raised again, so the notice burned every attempt on one
+ # broken rung and dead-lettered WITHOUT EVER TRYING rung (2). The inconsistency is what
+ # makes it a defect: every other way a rung can fail to deliver already continues --
+ # ``_build_context`` raising, a stale synthetic candidate, an un-acked send -- and round
+ # 7's accepted contract is that an unresolvable or stale candidate continues the walk.
+ # "A raising one is the same class of unusable and must be treated the same way."
+ # FIX: the delivery call is wrapped, the rung records ``error_stage = "deliver"``, the
+ # walk ``continue``s, and the first raising rung's error is copied onto the aggregate
+ # evidence when the winning rung carries none -- recorded purely for diagnosis, "the same
+ # way a post-delivery stream error is, and -- like that one -- must never be read as a
+ # delivery failure". ``Exception`` and deliberately NOT ``BaseException``: the walk-level
+ # deadline cancels this coroutine, and cancellation must unwind the walk rather than
+ # advance it past the bound it was cancelled to respect. Pinned both ways --
+ # ``test_a_raising_ladder_rung_does_not_abandon_the_rest_of_the_walk`` requires the later
+ # rung to be attempted, to ack on its receipt, to consume ONE attempt, and to carry the
+ # skipped rung's error for diagnosis; ``test_the_walk_deadline_still_cancels_through_a_rung``
+ # pins the one-letter distinction, and its assertion is that rung (2) is NEVER attempted,
+ # "which is what distinguishes cancellation from the raise above".
+ # THE HONEST RESIDUAL, and it is why (B) is in the same round: a rung that raises AFTER
+ # its transport accepted the send, leaving no evidence behind, now delivers again on the
+ # next rung. That is a duplicate this fix introduces, and it is only acceptable because
+ # the state that manufactures it is being removed at the source in the same round.
+ # (B) THE ADAPTERS WERE MANUFACTURING EXACTLY THAT STATE. Threaded Slack and Feishu sends
+ # ran ``sessions.mark_thread_active`` AFTER the transport call but BEFORE returning the
+ # native message id, unguarded -- and "the transport call is the point of no return: once
+ # it succeeds the user HAS the message." A raise there REPLACED the return value, so the
+ # dispatcher's blanket handler recorded a send failure with no delivery evidence for a
+ # message the user already had, and the fallback ladder re-sent it. "That is a systematic
+ # duplicate per bookkeeping failure, not the crash-only at-least-once residual" this id's
+ # family documents elsewhere.
+ # FIX AT THE ADAPTER, and the layer is forced rather than chosen: ``modules/im/discord.py``
+ # already wrapped the identical call, so Slack (four send paths) and Feishu (two) now
+ # match its shape exactly. It "cannot be papered over in ``core/message_dispatcher.py``:
+ # the id is destroyed inside the adapter before it can ever escape." Slack's inbound event
+ # handlers keep their unguarded calls deliberately -- they return no native id and are not
+ # send paths. Behaviour-preserving on the success path; only the already-delivered failure
+ # path changes. Red-first: six adapter cases fail without the change.
+ # THE NOTICE-LEVEL CONSUMER IS PINNED SEPARATELY, because adapter and dispatcher coverage
+ # do not answer the question this id asks -- whether the DRAIN's ack/retry decision comes
+ # out right for an adapter whose transport succeeded and whose bookkeeping blew up.
+ # ``test_a_notice_acks_when_the_adapters_post_send_bookkeeping_raises`` drives a real
+ # ``SlackBot`` with only the HTTP call stubbed ("real adapter and not a shaped stub,
+ # because the subject IS the adapter's own ordering: transport, bookkeeping, return")
+ # through the real drain, and requires the notice to ACK rather than resend. It is GREEN
+ # FROM BIRTH, since the fix landed in the same round, so the red half lives in the same
+ # file: ``test_the_pre_guard_adapter_shape_resends_an_already_delivered_notice``
+ # reintroduces the pre-fix shape and asserts BOTH consequences, "because either alone
+ # would understate the defect" -- the notice is not acknowledged AND, now that a raising
+ # rung continues the walk, the same body is pushed onto the next rung.
+ # ``test_a_real_send_failure_is_still_undelivered`` is the negative control that keeps the
+ # guard honest: it only ever runs after the transport returned, "otherwise the guard would
+ # have converted every failed send into a silent success, which is the failure mode the
+ # whole durable notice exists to prevent."
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header). The adapter-level cases
+ # live in ``tests/test_im_post_send_bookkeeping.py`` and the dispatcher-level ones in
+ # ``tests/test_message_dispatcher_scheduled.py`` as platform unit pins, which is why only
+ # the notice-level consumer is documented here.
+ test: tests/test_harness_failure_visibility.py::test_a_replayed_notice_reaches_the_user_without_touching_the_live_lifecycle
+ # PR6 review round 3 (#1072). Range extended to HFR-084 by the maintainer; PR2
+ # moves to 085. This block is now full — do not go past 084 without extending.
+ # SUPERSEDED (round 11): both numbers above are historical. The plan merged as #1044
+ # records the range being widened again, 15 -> 20 -> 25 -> 40, so PR6's main block is
+ # HFR-060...099 and PR2 starts at 100, not 085
+ # (docs/plans/harness-run-reliability.md §10.7). The "do not go past 084" instruction
+ # was overtaken by later review rounds and is left in place only as the record of what
+ # was true when it was written.
+ - id: HFR-080
+ name: a replayed failure notice does not finalize a live unrelated turn
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_a_replayed_notice_does_not_finalize_a_live_unrelated_turn
+ - id: HFR-081
+ name: the drain reuses the identity the live failure path would have used
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_the_drain_reuses_the_identity_the_live_path_would_have_used
+ - id: HFR-082
+ name: an interruption notice keeps an identity distinct from an ordinary failure
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_an_interruption_keeps_an_identity_distinct_from_an_ordinary_failure
+ - id: HFR-083
+ name: the owed-notice lookup seeks on an index rather than scanning failed history
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_the_owed_notice_lookup_seeks_rather_than_scans
+ - id: HFR-084
+ name: a malformed metadata row stays writable under the eligibility index
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # PR6 review round 12 (#1072). "STILL WRITABLE" WAS TRUE AND NOT ENOUGH: the four
+ # terminal writers were writable over a malformed row by DESTROYING it.
+ # ``_merge_owed_failure_notice`` took a pre-DECODED dict and fell back to ``{}`` for
+ # anything that was not one, and every terminal writer handed it
+ # ``_json_loads(row["metadata_json"], {})`` -- so settling a row whose blob is
+ # unparseable, or valid JSON that is not an object, REPLACED the column with just the
+ # notice. Whatever those bytes were (a truncated write, a value another component owns,
+ # the context an operator would need to diagnose it) "is not this feature's to
+ # destroy", and it went on all four writers.
+ # WHAT MAKES IT A DEFECT RATHER THAN A POLICY is that it was already inconsistent with
+ # every other reader on this head: the binding stamp refuses malformed rows through
+ # ``json_valid`` (round 9), ``update_owed_failure_notice`` returns ``None`` when the
+ # metadata is not a dict, and ``list_owed_failure_notices`` excludes them outright. One
+ # writer out of four chose repair-by-replacement while three chose refusal.
+ # FIX: the parameter becomes ``row_metadata_json`` and takes the RAW COLUMN, "because
+ # the decode is a decision this choke point has to make rather than inherit". An
+ # undecodable or non-object blob logs and RETURNS EARLY without setting
+ # ``metadata_json``, so the caller's ``status``/``error``/``completed_at`` UPDATE still
+ # commits -- the run settles, only the column is left alone. This completes the
+ # refuse-don't-repair rule the binding stamp adopted in round 9: it is now TOTAL across
+ # all four terminal writers rather than true of one.
+ # RESIDUAL, stated rather than hidden: such a row settles ``failed`` and never owes a
+ # notice, so its failure is visible in the run list and in derived health but is never
+ # delivered as a message. That was ALREADY true -- the eligibility query excludes
+ # malformed rows, so a notice written here would have been durable and unreachable --
+ # and it is the direction every other reader on this path chose.
+ # One subordinate test carries this id --
+ # ``test_a_terminal_writer_never_rewrites_unparseable_metadata`` -- a matrix over four
+ # blob shapes and all four writers, asserting the raw column byte-identical while the
+ # run still settles ``failed`` with its error. The ``settle_run_terminal`` leg passes a
+ # caller-supplied ``interrupt_reason`` on purpose: a sibling field must not be the lever
+ # that rewrites the column either.
+ # It takes no id of its own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_a_malformed_metadata_row_is_still_writable_under_the_expression_index
+ # PR6 review round 4 (#1072). Block widened to HFR-099 by the maintainer; PR2
+ # moves to 100+.
+ - id: HFR-085
+ name: a backed-off streak does not starve other definitions' failure notices
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_one_backed_off_definition_does_not_starve_every_other_notice
+ - id: HFR-086
+ name: the eligibility lookup stays bounded when every notice is backed off
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_the_eligibility_lookup_is_bounded_when_everything_is_backed_off
+ - id: HFR-087
+ name: a backend-supplied failure id and the drain agree for harness runs
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_the_drain_and_a_backend_supplied_identity_agree_for_harness_runs
+ - id: HFR-088
+ name: the eligibility index migration and the query use identical expressions
+ status: covered
+ kind: safety
+ layer: unit
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_the_index_migration_and_the_query_use_the_same_expressions
+ - id: HFR-089
+ name: a notice with no backoff field is still reachable by the drain
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_a_notice_stamped_without_a_backoff_field_is_still_reachable
+ # Rebase onto #1061's definition read projection.
+ - id: HFR-090
+ name: a watch reports derived health on the same terms as a task
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ test: tests/test_harness_failure_visibility.py::test_a_watch_reports_health_on_the_same_terms_as_a_task
+ - id: HFR-091
+ name: the drain preserves an authoritative interruption identity
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # ``_failure_identity`` honours an explicit id outright only when the caller says
+ # it is AUTHORITATIVE; otherwise the harness run-id override wins, which is what
+ # aligns a backend's own turn id with the drain's replay (HFR-087). The drain
+ # passed its explicit ``failure_id`` WITHOUT that flag, so the interruption
+ # identity ``interrupt:{run}:{reason}`` — stamped precisely so a D1 interruption
+ # cannot be swallowed by the dedup for an ordinary failure on the same execution
+ # — collapsed back to the bare run id at the one call site that reads it off a
+ # durable row. HFR-082 and HFR-087 both call
+ # ``backend_failure_notification_output`` directly and so could not see it.
+ # FIX: ``emit_replayed_backend_failure`` passes
+ # ``failure_id_authoritative=True`` unconditionally and exposes no way to say
+ # otherwise, so the authority is a property of the emitter rather than an
+ # argument a call site can forget. Driven through the REAL drain and asserted on
+ # the durable ``messages`` row's ``native_message_id`` and metadata, which is
+ # what the dedup lookup actually reads.
+ test: tests/test_harness_failure_visibility.py::test_the_drain_preserves_an_authoritative_interruption_identity
+ - id: HFR-092
+ name: a suppressed-lane reason never takes the interruption identity or copy
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # ``interrupt_reason`` is the general marker for "terminalized by something other
+ # than its own backend result", and its commonest values are ordinary per-fire
+ # verdicts that belong in the SUPPRESSED failure lane: ``no_terminal_result``,
+ # ``refused_concurrent_turn``, ``transport_unavailable``, ``queue_hold_expired``.
+ # The lane is membership in ``RUN_INTERRUPTION_REASONS``
+ # (``failure_notices.is_interruption``), but two places asked by PRESENCE: the
+ # stamp minted ``interrupt:{run}:{reason}`` for any non-empty reason, and the
+ # notice copy rendered the "was interrupted, nothing is wrong with the definition
+ # itself" headline for any non-empty reason. The first is a duplicate
+ # notification per failure once the drain's id is authoritative (HFR-091); the
+ # second tells a user their definition is fine when the definition is the problem.
+ # FIX: both gate on membership, and the reason stays recorded as the copy selector
+ # it is.
+ test: tests/test_harness_failure_visibility.py::test_a_suppressed_lane_reason_never_takes_the_interruption_identity_or_copy
+ - id: HFR-093
+ name: the drain and the live path agree for a suppressed-lane reason
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # The HFR-091 × HFR-092 interaction, pinned where it bites the user. With the
+ # drain's stamped ``failure_id`` authoritative and the stamp keyed by presence, a
+ # ``no_terminal_result`` failure is stamped
+ # ``interrupt:{run}:no_terminal_result`` while the live path keys the same failure
+ # by the run id — so ``agent_message_exists`` cannot see the notification the live
+ # path already persisted and the user is told twice. Neither HFR-081 (identity
+ # equality, computed directly) nor HFR-091 (interruption identity survives) can
+ # see it: one never runs the drain, the other uses a reason that IS in the
+ # interruption set. Drives BOTH paths over one real failure and counts the durable
+ # ``messages`` rows.
+ test: tests/test_harness_failure_visibility.py::test_the_drain_and_the_live_path_agree_for_a_suppressed_lane_reason
+ - id: HFR-094
+ name: a failed watch notice renders watch commands
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # ``_failure_notice_body`` resolved the definition through
+ # ``ScheduledTaskStore.get_task`` ALONE — the scheduled-task mirror — and then
+ # appended ``vibe task run {id}`` / ``vibe task show {id}`` for every definition.
+ # A watch is in neither: it got named by its raw id and handed two commands that
+ # cannot address it, and there is no ``vibe task run`` for a definition that is
+ # not scheduled at all. FIX: discriminate on ``run_type`` / the watch definition
+ # row, resolve the name through the watch read path
+ # (``get_watch_definition``), and render watch copy
+ # (``harness.notice.watchPaused`` / ``harness.notice.watchShow`` →
+ # ``vibe watch resume`` / ``vibe watch show``). Asserted through the REAL
+ # translator, because the defect is in the command strings a user reads.
+ # PR6 review round 9 (#1072). That discrimination still assumed the definition
+ # EXISTS. A run outlives its definition -- the notice is stamped by the terminal
+ # transition and drained later, and the retry ladder above makes that window minutes
+ # wide -- and the archetypal case is ordinary: a user deletes a task whose last fire
+ # failed and has not been reported yet. Both bodies then named commands that resolve
+ # to nothing. The failure body appended ``harness.notice.rerun`` unconditionally
+ # ("Re-run it now with: ``vibe task run <id>``") and ``harness.notice.show``; the
+ # binding body offered ``vibe task update <id> --session-id ...`` to pin back a row
+ # that cannot be pinned. Each PARSES and then fails at runtime with "not found",
+ # which is this id's own defect one noun over: copy naming an action the user cannot
+ # take, and worse than silence because it reads as a working recovery path.
+ # FIX: when neither read path resolves the definition (``get_task`` and
+ # ``get_watch_definition`` both empty), the body says the definition is gone
+ # (``harness.notice.definitionDeleted``) and names only RUN-LEVEL recovery --
+ # ``vibe runs show <run id>``, the one row that does still exist -- dropping the
+ # definition-scoped pair entirely. The binding body got the same treatment and keeps
+ # the news itself: the old and new session ids are still reported, because "your
+ # pinned session was replaced" is true whether or not the definition survived.
+ # Validated by parsing EVERY command the body prints through the real
+ # ``build_parser()``, which is the HFR-099 copy-test discipline, because a
+ # hand-written expectation drifts with the CLI.
+ # Two subordinate tests carry this same id:
+ # ``test_a_deleted_definition_notice_names_only_run_level_recovery`` and
+ # ``test_a_deleted_definition_binding_notice_drops_the_repin_command``.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 12 (#1072), TWO FINDINGS on this copy family.
+ # FIRST: AN INTERRUPTION REASON IS A WIRE VALUE, NOT USER-VISIBLE COPY.
+ # ``harness.notice.interrupted`` renders its ``reason=`` INSIDE the sentence, so
+ # whatever is substituted there is product copy whether or not anyone treated it as
+ # such -- and the drain interpolated the wire value. A Chinese user was told
+ # ``被中断(backend_refresh)``: an internal identifier, untranslated, mid-sentence, for
+ # every one of the six reasons in ``RUN_INTERRUPTION_REASONS``. FIX:
+ # ``NOTICE_REASON_I18N_KEYS`` maps each lane reason to a label key, with
+ # ``NOTICE_REASON_UNKNOWN_I18N_KEY`` as the fallback, both locales filled.
+ # An EXPLICIT MAP rather than an f-string key, "so the settlement vocabulary stays free
+ # to change without a renamed value silently degrading into a raw key in the middle of
+ # a translated sentence" -- and the obvious ``.get(reason, reason)`` spelling is called
+ # out as the original defect again, reachable in exactly the window between a reason
+ # joining the lane and CI noticing it has no label. These are LABELS, deliberately not
+ # the long-form ``harness.run.interrupted.*`` family, which is the run's ``error``
+ # column printed on its own line.
+ # Four subordinate tests: ``test_an_interruption_notice_never_prints_the_raw_wire_reason``
+ # loops the whole lane through the REAL translator (a ``_t`` that echoes keys reports
+ # which key was chosen, not what the user reads);
+ # ``test_an_unmapped_interruption_reason_renders_a_localized_fallback`` empties the map
+ # rather than inventing a reason, because ``is_interruption`` gates the branch on lane
+ # membership so an unmapped reason is only reachable as a map/lane disagreement; and two
+ # drift guards in ``tests/test_i18n_backend_keys.py`` require the map's key set to equal
+ # the lane exactly and every label to resolve in every supported language -- "if that
+ # key were missing the notice would print the dotted path instead, a worse leak than the
+ # raw reason it replaced."
+ # SECOND: the D5 body requirement, PARTIALLY. Two of the plan's named body items were
+ # missing on the per-fire FAILED lane, and the diagnosis corrects a conflation:
+ # ``interrupt_reason`` is NOT a synonym for "interrupted" -- master stamps it for
+ # ``no_terminal_result`` / ``refused_concurrent_turn`` / ``transport_unavailable`` /
+ # ``queue_hold_expired``, which recur on every fire and so stay in the failure lane by
+ # design. But the interrupted HEADLINE was the only place any reason was rendered, so on
+ # the failed lane the class was dropped and the user saw only whatever text the ``error``
+ # column held. The last success had no read at all, on any lane.
+ # FIX: ``PER_FIRE_INTERRUPT_REASONS`` is DERIVED by subtracting the interruption lane
+ # from the settlement and sweep vocabularies -- "that subtraction is the same
+ # discriminator ``is_interruption`` applies, so the two cannot disagree about which lane
+ # a reason belongs to" -- and ``NOTICE_FAILURE_CLASS_I18N_KEYS`` labels exactly that set,
+ # asserted DISJOINT from the interruption map: one reason, one lane, one label. The last
+ # success comes from ``last_success_settled_at``, one bounded indexed seek sharing
+ # ``_SETTLED_AT``, the succeeded status vocabulary and the ``settled DESC, id DESC``
+ # tie-break BY NAME rather than retyped, with ``watch_runtime`` excluded -- without that
+ # term a permanently broken watch would report a fresh "last succeeded" instant on every
+ # service restart.
+ # THE TWO OMISSION CHOICES ARE OPPOSITE ON PURPOSE, and this is the part worth keeping:
+ # ``notice_failure_class_i18n_key`` returns ``None`` rather than a generic, "the opposite
+ # choice from ``notice_reason_i18n_key``'s. There the reason is rendered INSIDE a
+ # sentence that is printed either way, so a missing label has to degrade to something
+ # readable. Here the label IS the line: with nothing real to name, the honest rendering
+ # is no line at all rather than 'Class: unknown'." The last-success line is likewise
+ # omitted rather than rendered as "never" for a definition that has never succeeded.
+ # Three subordinate tests, plus two more drift guards:
+ # ``test_the_failed_lane_names_its_class_and_when_it_last_succeeded`` runs both locales
+ # through the real translator and requires the LATEST success rather than the earliest;
+ # ``test_a_failed_lane_body_omits_both_lines_when_neither_is_real``; and
+ # ``test_the_last_success_read_is_one_bounded_indexed_seek``, asserted on the CONSTRAINED
+ # TERMS rather than only the index name, which is the HFR-086/095 lesson.
+ # NOT IMPLEMENTED, AND NOT CLAIMED: D5's remaining body item -- where the task was
+ # created, channel/thread with a deep link (plan :3165-3168). Only the failure class and
+ # last-success lines landed this round. No i18n key for a creation location or deep link
+ # exists, and the commits state no reason for the omission, so this is recorded as an
+ # open gap against the plan rather than as a documented deferral.
+ # CLOSED IN ROUND 14 (gate item 3). The gap above is the last item of D5 and it is now
+ # implemented end to end, so the paragraph stands only as the record of what was open.
+ # THE DEFECT, precisely: a failure notice "is context-free by construction -- an owner
+ # DM or a workspace card, delivered hours after the fire -- so the conversation that
+ # asked for the definition was unrecoverable from the notice." And the reason it could
+ # not simply be rendered: the ids had never been captured, and no permalink builder
+ # existed anywhere in the codebase.
+ # CAPTURE. ``CallerContext`` gains six fields -- ``platform``, ``user_id``,
+ # ``channel_id``, ``session_key``, ``message_id``, ``workspace_id`` -- each with its own
+ # ``AVIBE_CALLER_*`` env var, because the subprocess env is the ONLY channel available:
+ # an IM-created definition is created by an Agent run executing ``vibe task add``, so
+ # the env is the only hop between the conversation that asked and the row that records
+ # it. ``channel_id`` and ``session_key`` are both kept and are not redundant --
+ # ``session_key`` is the ADDRESS in the grammar ``parse_session_key`` speaks, while
+ # ``channel_id`` is the LOCATION a permalink needs; for a DM the session key's scope id
+ # is the USER id, and a permalink built from it would be fabricated.
+ # THE KEY NAMES ARE LOAD-BEARING, and this is the part that lights up the ladder:
+ # ``to_metadata`` writes exactly the names the ladder has always read --
+ # ``caller["session_key"]`` / ``caller["scope_id"]`` for rung (3) and
+ # ``caller["platform"]`` / ``caller["user_id"]`` for rung (4), the owner DM. "Writing
+ # them under any other name would leave them dormant." So rungs (3) and (4) become
+ # reachable for NEW definitions and D5's designed ladder shape finally exists in
+ # practice. The reading logic was never broken -- verified at ``3578f2b6``, where the
+ # rungs resolve fine from hand-written metadata; "nothing ever wrote it."
+ # THE HONESTY TABLE, in the new ``core/origin_links.py``: one public function,
+ # ``origin_link``, and "one rule: LINK OR ``None``, never a fabricated URL. A failure
+ # notice that offers a link the user cannot follow is worse than a notice that offers
+ # none -- it moves the failure from 'I do not know where this came from' to 'Avibe told
+ # me where and it was wrong', and the second is the one that costs trust." Linkable only
+ # when every id that platform's permalink grammar requires is present: ``slack``
+ # (channel + ts), ``discord`` (guild + channel + message -- and NEVER ``@me``, which
+ # "would read as a working link while being unfollowable for anyone else, including the
+ # workspace inbox, which is not a person at all"), ``telegram`` (a ``-100`` supergroup id
+ # + message). Named but never linked: ``lark`` and ``wechat`` have no stable public
+ # message permalink, and ``avibe`` has an addressable location whose only URL form is the
+ # local setup host -- "a ``http://127.0.0.1:<port>/...`` link pasted into a Slack DM or a
+ # phone push is not honestly reachable from where the notice is read." An unrecognised
+ # platform gets nothing, because "guessing a URL shape for it is the fabrication this
+ # whole module exists to prevent." Matching is exact on the wire value, and the wire
+ # value is ``lark`` rather than ``feishu`` -- keying the map on the product name would
+ # have made every Feishu origin unnameable.
+ # THREE INDEPENDENT REFUSALS, each yielding FEWER lines rather than vaguer ones: no
+ # provenance at all (every definition created before this round) takes no line and there
+ # is "no backfill and no migration, because the ids were never recorded and inventing
+ # them is the one thing a provenance line may not do"; an unmapped platform takes no
+ # line rather than leaking its wire value; and an unlinkable origin still renders the
+ # TEXT and drops only the link. The omission rule is the same judgement
+ # ``notice_failure_class_i18n_key`` already made -- "'Created in: unknown' would be copy
+ # about nothing on the lane that already carries the most lines."
+ # THE CLAUDE-PATH RESIDUAL, stated as a residual because it is one.
+ # ``SessionHandler`` is the sole caller passing ``session_stable_only=True``, and it is
+ # not a shortcut: that env "is baked into a Claude SDK client at spawn and is also the
+ # value compared to decide whether a cached client may be reused", so ``message_id``
+ # would respawn the Agent on every turn, and ``user_id`` -- which changes with the author
+ # on a deliberately shared channel session -- "would attribute a definition created by
+ # one participant to whoever happened to speak first, and the owner-DM rung would then
+ # notify the wrong person, which is worse than not notifying anybody." What survives is
+ # what the SESSION owns, so a Claude-created definition names its conversation and lights
+ # rung (3) but gets no owner-DM rung and no deep link: "an omission, not a wrong URL."
+ # Codex and OpenCode rewrite their caller env per turn and keep the full origin; a DM
+ # loses nothing either way, since its session key carries the person in the scope itself.
+ # Subordinate tests, none taking an id. The body half is
+ # ``test_the_notice_names_where_the_definition_was_created_and_links_to_it`` (both
+ # locales, red at ``3578f2b6`` where the body was four lines with no channel, no thread
+ # and no URL), with ``test_a_definition_with_no_captured_origin_gets_no_origin_line``,
+ # ``test_an_origin_that_cannot_be_linked_is_still_named`` and
+ # ``test_an_unmappable_origin_platform_takes_no_line_rather_than_leaking_itself`` for the
+ # three refusals. The capture half is
+ # ``test_the_creation_origin_survives_the_env_hop_into_created_by_caller``, also red at
+ # ``3578f2b6``. ``test_a_captured_origin_lights_up_the_scope_and_owner_dm_rungs`` has NO
+ # red of its own and says so -- overlaid at ``3578f2b6`` the ladder already resolved
+ # those rungs from hand-written metadata, which is the evidence for "the reading logic
+ # was never dead". ``test_the_workspace_card_carries_the_creation_origin`` is red at
+ # ``d2c3bf31`` rather than at ``3578f2b6``, a deliberately SPLIT baseline: it imports
+ # round-12+ symbols, and an ``ImportError`` is not evidence of a defect. The new
+ # ``tests/test_origin_links.py`` states the same discipline for itself -- "There is
+ # deliberately no red baseline for this file. It characterises a new pure module, so at
+ # any earlier commit it would only raise ``ImportError``."
+ # PR6 review round 14 (#1072), #1060's FIELD CASE, CONSUMED. A dead delivery target had
+ # no name of its own: a ``once`` watch pinned with ``--session-id`` to a session that
+ # later ceased to exist failed its follow-up delivery, retired, and "the only cause
+ # recorded anywhere was ``last_exit_code = 75`` -- the user's own ``--retry-exit-code``,
+ # i.e. the waiter's HEALTHY 'nothing new yet' signal", so "anyone debugging from exit 75
+ # starts by investigating a working waiter". The reporter's ask was literally "a cause
+ # field distinct from the last exit code".
+ # FIX: ``INTERRUPT_REASON_DELIVERY_TARGET_MISSING = "delivery_target_missing"``, grouped
+ # in a THIRD source vocabulary ``DISPATCH_FAILURE_REASONS`` "because it has a third
+ # origin", labelled ``harness.notice.class.deliveryTargetMissing`` in both locales, and
+ # threaded from ``_execute_claimed_request``'s ``UnresolvableSessionTarget`` handler into
+ # ``complete(interrupt_reason=...)`` -- as ONE named keyword rather than a general
+ # metadata dict, because "a wide-open passthrough at a completion site is how an
+ # unrelated key comes to overwrite ``interrupt_reason`` or the notice blob itself". The
+ # ordering is load-bearing: ``extra_metadata`` is applied BEFORE
+ # ``_owed_failure_notice_for_transition`` reads the reason, "so the notice is born
+ # already carrying its class. A second UPDATE afterwards would be too late."
+ # ONLY ``reason == "missing"`` IS CLASSIFIED, and the restraint is the interesting part:
+ # ``archived`` is left unclassified on purpose, because "an archived session's row still
+ # exists, and the honest description of that failure is 'the session is inert', not 'it
+ # no longer exists' ... A wrong class is worse than no class" -- and its notice is
+ # deliverable anyway, via the reroute in retraction (a) above.
+ # IT IS ON THE PER-FIRE LANE AND DELIBERATELY NOT AN INTERRUPTION, which is a routing
+ # decision with three consequences the docstring spells out: a definition pinned to a
+ # deleted session fails on EVERY fire, so admitting it to ``RUN_INTERRUPTION_REASONS``
+ # would give it an unsuppressed notice per fire, mint an ``interrupt:{run}:{reason}``
+ # identity the live path never uses, and take it out of the health window -- "reporting a
+ # permanently broken watch as healthy while notifying about it forever". Because it stays
+ # out of that set, ``failure_id`` remains the bare run id, the live path's dedup finds it,
+ # the streak collapses to one canonical notice, and derived health still reads
+ # ``failing``. Drift-pinned by a DIRECTION test rather than by the existing equality --
+ # ``test_a_dispatch_failure_class_joins_the_per_fire_lane_and_not_the_interrupted_one`` --
+ # because "the pin above is an equality between two sets that both grow, so it stays
+ # green for a reason added correctly AND for one added to the wrong source vocabulary".
+ # RETIRED IS NOT PAUSED. ``_failure_notice_body`` rendered the resume affordance for
+ # every disabled watch, so a retired one read FINISHED in the lifecycle projection while
+ # its notice offered ``vibe watch resume`` -- "an action that would arm a watch nobody
+ # paused". Root cause is that ``enabled=0`` carries three meanings. FIX: the copy branches
+ # on the ``retired_at`` column -- "the same column the projection's ``ended`` predicate
+ # uses, so the copy and the badge cannot disagree" -- with a new parameterless
+ # ``harness.notice.watchRetired``. A legacy row with no marker keeps the resume copy,
+ # because "its history genuinely cannot prove which of the two happened".
+ # THE FIELD CASE IS DRIVEN END TO END, which no previous test did: every existing layer
+ # test stubbed one of the four steps. ``test_a_watch_that_outlives_its_delivery_target_dies_visibly``
+ # asserts the maintainer note's five outcomes in labelled blocks -- (a) the terminal row
+ # is not indistinguishable from a pause or a retirement, checked through the real CLI
+ # payload; (b) the recorded cause is the delivery failure, never the retry sentinel, with
+ # the negative asserted on the definition too; (c) the terminal timestamps are coherent,
+ # re-read from a fresh store for durability; (d) exactly ONE actionable notice, in the
+ # workspace inbox, reachable only via the mandatory rung because every preferred rung
+ # names a session row that no longer exists; (e) a replay through a THIRD owner may
+ # neither duplicate nor erase it. ``test_a_forever_watch_repeating_the_field_failure_notifies_once``
+ # takes the repetition half with a real waiter subprocess exiting 75/0/0/75 "so the LAST
+ # recorded cycle is the sentinel -- the state #1060's row was actually read in", and pins
+ # that the sentinel never retires the watch, the projection reads ``waiting`` while health
+ # reads ``failing``, and the streak still collapses to one notice.
+ # WHAT WAS FOUND ALREADY COHERENT IS RECORDED TOO, "because the plan predicted
+ # otherwise": ``mark_cycle_result`` already writes ``retired_at``,
+ # ``last_finished_at`` and ``last_event_at`` in one guarded stamp, so (c) and half of (a)
+ # needed no change in ``core/watches.py`` at all -- #1060's row predates that stamp. They
+ # are asserted anyway, "the preconditions the rest of the case rests on, and a regression
+ # in them reopens the field bug by a different road".
+ # A third subordinate test,
+ # ``test_a_disabled_watchs_notice_copy_distinguishes_retired_from_paused``, covers the
+ # copy half in both locales through the real translator. All three are consuming tests
+ # for the fix in the preceding commit, so they are green at this head and were red before
+ # it; the honest framing is that they consume a fix rather than drive one.
+ # They take no ids of their own because PR6's block is full at 099, 100+ is contracted to
+ # PR2 by the merged plan, and cyhhao declined to consume an id from §10.7's HFR-280...319
+ # block for this round.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_a_failed_watch_notice_renders_watch_commands
+ - id: HFR-095
+ name: the streak read is bounded by the streak, not by the definition's lifetime
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # ``failure_streak`` is asked once per pending owed notice on the same 2 s tick
+ # HFR-078/083/086 bounded the eligibility lookup for — and it was the last read
+ # in that path that was still unbounded. ``_definition_verdict_rows`` selected a
+ # definition's ENTIRE settled lifetime ordered by ``(created_at, id)``,
+ # materialised every row and JSON-decoded each one to drop interruptions, then
+ # sliced out a streak that is almost always two or three rows. Measured on a
+ # 5000-row history: 5000 metadata blobs decoded to return 6 rows, under
+ # ``SEARCH ... ix_agent_runs_definition_created (definition_id=?)`` plus
+ # ``USE TEMP B-TREE FOR LAST TERM OF ORDER BY``.
+ # FIX: two ``LIMIT 1`` seeks for the successes bracketing the run by
+ # ``(created_at, id)``, then only the rows between them —
+ # ``SEARCH ... ix_agent_runs_definition_streak
+ # (definition_id=? AND (created_at,id)>(?,?) AND (created_at,id)<(?,?))``, 6
+ # blobs decoded. Asserted on the plan's CONSTRAINED TERMS rather than on an
+ # index name, which is the HFR-086 lesson: a plan can name an index while the
+ # term that matters stays a per-row filter.
+ # PR6 review round 12 (#1072). BOTH CLAIMS ABOVE ARE SUPERSEDED, one on cost and one
+ # on correctness, and the second is the serious one.
+ # THE BOUND WAS ON THE ANSWER, NOT ON THE WORK. The seek-based replacement fixed the
+ # plan and kept HANDING THE STREAK'S ROWS BACK; its decode budget was written as
+ # ``2 * len(streak) + 2``, which is a bound on the ANSWER and therefore only a bound
+ # when the answer is small. On a definition that has never succeeded the streak IS
+ # its lifetime, and that is not a corner case -- it is every definition that has been
+ # failing since it was created. Measured on a 1500-run never-succeeded history: 4
+ # statements, 1500 rows into Python, 1500 blobs decoded, per pending notice, per 2 s
+ # tick. So the "6 blobs decoded" figure above describes a bracketed history only; it
+ # was never the worst case. Now 1 statement, 1 row, 0 blobs -- on both shapes.
+ # THE THREE READS SAW A MOVING HISTORY, and the previous paragraph's safety argument
+ # was the wrong argument. It reasoned that three statements are not three snapshots
+ # "because every row they read is already SETTLED" -- true of each row individually,
+ # and silent about which rows the WINDOW contains. The boundaries are what moves.
+ # pysqlite opens no transaction for reads, so the boundaries were seeked at one
+ # instant and the rows read at a later one; a success settling in that gap left the
+ # boundary saying "no success before this run", the row read swept in the PREVIOUS
+ # outage, and that outage's ``sent`` notice made ``decide`` answer SKIP for a live
+ # one. ``skipped`` is durable and nothing revisits it, so the outage is never
+ # reported: a lost notice, the D1 direction. The old conclusion that holding the
+ # write lock "would buy nothing" is retired too -- the fix takes one snapshot without
+ # taking any lock.
+ # FIX: ``failure_streak_decision`` replaces ``failure_streak``, which is DELETED
+ # rather than deprecated (no production callers remain). It answers the three facts
+ # ``decide`` actually needs -- ``in_streak``, ``has_sent_elsewhere``,
+ # ``earliest_pending_id`` -- in ONE statement, which is one SQLite read snapshot, so
+ # the boundaries and the rows inside them come from the same database. The drain never
+ # wanted a streak: returning the rows is what made the read cost the streak's LENGTH
+ # and forced the caller to redo the classification in Python. The notice state is
+ # compared INSIDE SQLite (``OWED_NOTICE_STATE_SQL`` referenced, never retyped), which
+ # is why zero blobs are decoded, and ``id != run_id`` on the ``has_sent_elsewhere``
+ # term keeps it evidence of delivery by SOMEBODY ELSE -- this row's own ``sent`` state
+ # is not evidence that it is a duplicate.
+ # AN ABSENT BOUNDARY IS A DERIVED SENTINEL, NOT A DROPPED PREDICATE, and this is the
+ # subtle part. The three-statement form knew at build time whether a seek had found
+ # anything and omitted the term when it had not; one statement cannot, and spelling it
+ # ``(boundary IS NULL OR position > boundary)`` would make the term a DISJUNCTION,
+ # which SQLite cannot use as an index constraint -- the plan would name the index
+ # while the range stayed a per-row filter, which is the exact failure ``20260728_0040``
+ # shipped and HFR-086 pinned. Below every position is the empty string; above every
+ # position is the definition's own last ``created_at`` with ``'x'`` appended, DERIVED
+ # by the same ``LIMIT 1`` seek rather than a magic high constant, "because a constant
+ # would have to out-sort every possible ``created_at`` byte string and nothing
+ # guarantees that, while ``X < X || 'x'`` holds for every ``X`` under BINARY
+ # collation". Anchor membership is itself a window term, because without it a
+ # ``run_id`` that is not a verdict of this definition leaves both boundaries NULL,
+ # both sentinels apply, and the "window" becomes the definition's entire history.
+ # Two subordinate tests carry this id. The locator above is repointed at
+ # ``failure_streak_decision`` and now pins ONE statement, ZERO blobs on BOTH shapes
+ # (bracketed and never-succeeded), and the plan's constrained terms with both
+ # row-value boundary seeks -- allowing ``SCAN CONSTANT ROW`` deliberately, since the
+ # outer projection has no FROM at all.
+ # ``test_a_success_settling_mid_read_cannot_merge_two_streaks`` is the correctness
+ # half: a second connection commits the recovery from the third ``agent_runs`` SELECT
+ # onward, which is a point a multi-statement read reaches with its boundaries already
+ # taken and its rows not yet read -- and a one-statement read never reaches at all.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_the_streak_read_is_bounded_and_seeks_rather_than_scans
+ - id: HFR-096
+ name: the bounded streak read is the same streak the materialized one computed
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # Parity for HFR-095 against the algorithm it replaces, kept in the test module
+ # as an oracle. Randomised histories carry every row class that decides the
+ # answer: verdicts and non-verdicts, interruptions inside and outside
+ # ``RUN_INTERRUPTION_REASONS``, ``watch_runtime`` heartbeats, and runs sharing a
+ # ``created_at`` so the ``id`` tie-break decides ordering — and every run in the
+ # history is asked for, not just the failures. The first cut compared boundaries
+ # on ``created_at`` alone and this caught it immediately: a bare scalar range
+ # both drops rows tied with the boundary and can leave a SUCCESS inside the
+ # window, which merges two streaks and skips the second one's notice as a
+ # duplicate. The comparison is a ROW VALUE for that reason.
+ # PR6 review round 12 (#1072). REPOINTED, and the oracle is now a COMPOSITION. The
+ # locator above named ``test_the_sql_streak_matches_the_materialized_streak``, which
+ # no longer exists: the read it checked stopped returning a streak, so the test was
+ # renamed with it. The parity claim is stronger than a rename suggests.
+ # ``_materialized_streak`` survives unchanged -- still byte-for-byte the pre-SQL
+ # production algorithm -- and a new ``_facts`` helper is byte-for-byte the derivation
+ # ``decide`` used to perform inline on the rows it was handed. Their COMPOSITION is
+ # the full old behaviour end to end, and that is what the one-statement read is
+ # checked against: "a parity test against a reimplementation of the new code would
+ # prove nothing." Six seeded histories of 40 runs, every run asked for plus the
+ # literal ``run-does-not-exist``, because a missing anchor is the case that could turn
+ # the window into the definition's whole history.
+ # A second subordinate test carries this id --
+ # ``test_the_facts_decide_exactly_what_the_streak_rows_decided`` -- which pins the
+ # CONSUMER against ``_legacy_decide`` (``decide`` as of ``467b7c80``, taking rows)
+ # over an asserted 1100-case matrix, comparing ``(action, reason)`` rather than
+ # action alone: the reasons are written into the row as ``skip_reason`` /
+ # ``defer_reason`` and read back by operators, and ``canonical_pending:<id>`` names a
+ # specific run. Moving a derivation into SQL is only safe if no outcome moved with
+ # it, and that is a claim about the OLD code, so the old code has to be present to
+ # check against.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ test: tests/test_harness_failure_visibility.py::test_the_sql_streak_facts_match_the_materialized_streak
+ # Collapse the CLI's second health read model into the one projection.
+ - id: HFR-097
+ name: the CLI is a projection consumer, not a second health read model
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # This change's own first draft added _task_health_map/_task_health to vibe/cli.py
+ # and a ScheduledTaskStore.definition_health_batch delegator that existed for no
+ # other caller: a SECOND read model over agent_runs beside _enrich_definitions,
+ # which every list, show and Workbench read already passes through. Two read models
+ # over one table is how the same definition comes to have two answers, and it did --
+ # task mutations answered from the CLI-side query, watch mutations (which never grew
+ # one) answered with no health at all.
+ # FIX: delete both helpers and the delegator; mutations read the row back through
+ # get_scheduled_task / get_watch. Guarded two ways, because either alone is
+ # escapable: the source of vibe/cli.py and core/scheduled_tasks.py may not mention
+ # definition_health_batch or _task_health, AND every definition_health_batch call
+ # made while task add / pause / update run must have _enrich_definitions on its
+ # stack -- so the query cannot be reintroduced under a different name.
+ test: tests/test_harness_health_projection.py::test_the_cli_is_a_projection_consumer_not_a_second_health_read_model
+ - id: HFR-098
+ name: task and watch mutations answer with the enriched projection
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # The consuming end of HFR-097. A create/pause/resume/update response is the first --
+ # and for an agent, often the only -- thing anyone sees, so a definition that is
+ # already failing has to say so there. Watch mutations carried no health, no
+ # lifecycle_state and no failure counts at all; task mutations carried a separately
+ # queried copy of health and still no lifecycle fields.
+ # FIX: all seven mutation responses (task add / set_enabled / update, watch add /
+ # set_enabled / update, and the watch startup-failure details) build their payload
+ # from the row read back through _enrich_definitions. Asserted by seeding a real
+ # two-run failure streak in agent_runs and comparing each response against the
+ # show that immediately follows it -- immediately, because lifecycle_state
+ # legitimately changes with each pause and resume.
+ test: tests/test_harness_health_projection.py::test_task_and_watch_mutations_return_the_enriched_projection
+ - id: HFR-099
+ name: a successful rebind is delivered through the retried notice path
+ status: covered
+ kind: failure
+ layer: contract
+ backend: shared
+ # The one binding transition nobody hears about. A create_once definition whose
+ # pinned session is hard-deleted rebinds and retries; when the retry SUCCEEDS the
+ # run settles succeeded with error=None, so _owed_failure_notice_for_transition
+ # stamps nothing (it stamps only on failed) and _notify_binding_change is a
+ # log-only seam. The user's pinned session was replaced -- possibly onto different
+ # Agent/model settings -- and the only trace was a logger.warning.
+ # FIX: _emit_binding_change stamps a durable notice on the succeeded run row, once
+ # per transition (immediately after the binding_recovery marker lands, and only for
+ # action == "rebound" with a run that did not fail, so a rebind whose retry failed
+ # keeps its ordinary failure notice). Identity is binding:{task_id}:{signature} --
+ # SessionBindingChange's own "one broken binding, one notification" key -- and the
+ # kind/binding fields are additive, so no migration and no change to the
+ # eligibility index expressions HFR-088/089 pin. failure_notices.decide grows a
+ # deliver-always lane beside is_interruption, and the drain asks
+ # bypasses_suppression rather than is_interruption at the streak gate: reading the
+ # streak off a SUCCEEDED anchor would sweep in the definition's surrounding
+ # failures and defer the notice forever. list_owed_failure_notices widens its
+ # status predicate to both terminal verdicts (free: the index covers state and
+ # next_attempt_at, never status).
+ # Asserted on the real path end to end -- one SQLite file for the fire, the drain
+ # and the messages receipt -- and the second half is the point: the first delivery
+ # is killed, which must consume an attempt and arm the backoff rather than
+ # re-firing, and the next eligible tick delivers with a receipt. A one-shot emit
+ # beside the log line would satisfy "a message appeared" and fail that half.
+ # A second, subordinate test carries this same id --
+ # ``test_the_binding_notice_copy_only_names_commands_the_cli_has`` -- which parses
+ # every command the binding copy prints with the REAL ``build_parser()`` in both
+ # locales. It takes no id of its own because the PR6 overflow range this block was
+ # written against (250-274) was already occupied by #1064's landed HFR-240...279.
+ # Re-truthed in round 11: the plan merged as #1044 re-drew that allocation
+ # (docs/plans/harness-run-reliability.md §10.7, "Re-drawn 2026-07-29 against the
+ # merged catalog"), so PR6's overflow is now HFR-280...319 -- see the round-11 note
+ # under HFR-099 for why these subordinate ids are still unassigned.
+ # PR6 review round 9 (#1072). ``stamp_binding_change_notice`` is the ONE owed-notice
+ # writer with no terminal transition to ride: it runs on a LIVE run, before
+ # ``complete()``, so its read and its write are two statements with no lock across
+ # the gap -- pysqlite emits no ``BEGIN`` for a bare SELECT, the fact
+ # ``update_owed_failure_notice`` and ``upsert_definition_in_connection`` both
+ # document. Round 7 (see HFR-076) audited this writer and excused it as "a pre-read
+ # stamp"; right about the order, wrong about the connection, and there were two
+ # damage directions, both user-visible.
+ # * A second connection settles the row ``failed`` and stamps its OWN failure notice
+ # in the same UPDATE (``_merge_owed_failure_notice``). The whole-blob write put the
+ # binding blob over the top, so the user was told their session was swapped and
+ # NEVER told the run failed -- the notice this whole capability exists to deliver,
+ # overwritten by the one added last.
+ # * The row settles ``canceled``. A ``pending`` notice then sat on a status
+ # ``list_owed_failure_notices`` excludes by design: durable and undeliverable
+ # forever, the silent-drop shape HFR-088/089 exist to prevent. ``canceled`` is
+ # reserved for explicit stop semantics, so the correct outcome is NO notice at all
+ # rather than a deferred one -- a user who pressed Stop outranks the rebind news.
+ # FIX: the SELECT's status is re-asserted VERBATIM in the UPDATE's WHERE clause
+ # beside ``owed_notice_absent()``, with the loss read off ``rowcount`` -- the
+ # ``DefinitionWriteExpectation`` idiom, the same one HFR-076 moved the drain's guard
+ # into. The write is a ``json_set`` of the single key this method owns rather than a
+ # composed blob, for the atomicity reason one level down: the run is LIVE, so sibling
+ # metadata keys are being written concurrently (the sweep's ``interrupt_reason``, the
+ # settler's ``ok`` marker), and a status+notice CAS over a whole-blob write would
+ # still clobber whichever of those landed in the gap. ``json_valid`` over the same
+ # ``coalesce``d expression makes a MALFORMED blob a refusal-and-log rather than a
+ # ``malformed JSON`` raised out of the rebind path -- refused, never
+ # repaired-by-replacement, which is exactly what the old whole-blob write did to an
+ # unreadable blob.
+ # Four subordinate tests carry this same id.
+ # ``test_a_binding_stamp_refuses_a_failure_terminalized_inside_its_gap`` commits the
+ # terminal failure from a SECOND connection inside the gap (the loser's UPDATE
+ # hooked, as HFR-076's round-8 test does) and asserts the stamp reports it wrote
+ # nothing while the failure's own notice survives BYTE-INTACT.
+ # ``test_a_binding_stamp_never_lands_on_a_run_canceled_inside_its_gap`` does the same
+ # with a cancel and requires no notice at all.
+ # ``test_a_binding_stamp_on_a_malformed_metadata_row_is_refused_not_raised`` and
+ # ``test_a_binding_stamp_writes_only_its_own_metadata_key`` pin the two costs of the
+ # move: an unreadable blob is left alone rather than replaced, and a sibling live-run
+ # metadata key written in the gap survives.
+ # They take no ids of their own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 10 (#1072). That CAS had a THIRD damage direction, and its two
+ # tests could not see it because both raced the stamp against a status the guard is
+ # RIGHT to refuse. The winner can also terminalize ``succeeded`` -- which is not an
+ # edge case but the ORDINARY outcome of the rebind this notice exists for, a
+ # create_once definition whose pinned session was hard-deleted, rebound, and retried
+ # successfully. Refusing there is not a deferral, it is a PERMANENT SILENT LOSS, for
+ # two reasons that compound: a successful settlement writes no notice of its own, so
+ # nothing else ever fills the slot; and ``_emit_binding_change`` has already
+ # persisted the ``binding_recovery`` dedup marker through
+ # ``record_binding_recovery`` BEFORE it calls the stamp, so every later fire
+ # short-circuits on that marker and no retry is ever attempted. The user's pinned
+ # session was replaced, possibly onto different Agent/model settings, and the only
+ # trace is a logger.warning -- which is verbatim the bug THIS ID WAS OPENED TO
+ # CLOSE, reintroduced by the guard added to protect it. ``succeeded`` is also
+ # precisely why ``list_owed_failure_notices`` was widened to both terminal verdicts
+ # above: this catalog's own words, "the one notice a succeeded run can owe". The
+ # slot is not merely empty, it is legitimately owed and deliverable.
+ # FIX: a lost CAS re-reads the row ONCE, inside the same transaction, and retries
+ # the stamp exactly once when the winner normalizes to ``succeeded``, the metadata
+ # parses, and the notice slot is still empty. The retry re-asserts the RE-READ
+ # status and keeps ``owed_notice_absent()``/``json_valid`` unchanged, so it is the
+ # same compare-and-swap over a fresher observation rather than a weakened one. The
+ # other directions are unchanged and now stated as a total policy over terminal
+ # statuses: ``failed`` refuses (its own failure notice owns the slot and outranks
+ # this news), ``canceled`` refuses (Stop outranks the rebind news, and the drain
+ # excludes the status so a notice there would be durable and undeliverable), and
+ # anything else refuses (still live, slot occupied, or unreadable). No outcome falls
+ # through to an accidental default, which is the round-7 lesson about auditing a
+ # guard for TOTALITY rather than for the one case a finding named.
+ # EXACTLY ONE RETRY, AND THE REASON IS CONVERGENCE RATHER THAN LUCK -- explicitly
+ # NOT an argument from lock acquisition, since an UPDATE matching zero rows may
+ # never escalate to RESERVED. ``succeeded`` is terminal and every terminal writer in
+ # the module is guarded on a non-terminal status, so once the re-read sees it the
+ # status can never move again and the retry's predicate cannot go stale a second
+ # time. The slot is equally settled: ``record_binding_recovery`` is a guarded write
+ # admitting a single stamper per transition, so no second binding stamp exists to
+ # race and no terminal transition remains to stamp a failure notice. The only writer
+ # that can still touch the row is a sibling-key ``json_set`` (the sweep's
+ # ``interrupt_reason``), which moves neither the status nor the slot. A second loss
+ # would mean an invariant broke, not that a third attempt would help -- so there is
+ # no loop.
+ # One subordinate test carries this same id:
+ # ``test_a_binding_stamp_survives_a_success_settled_inside_its_gap`` reuses the
+ # round-9 failed-race interleaving with a SUCCESSFUL settlement as the racing write,
+ # and asserts ``interleaved`` first so a stamp that simply never raced cannot pass.
+ # Red on b3986fde with ``stamped is None``. The round-9 failed/canceled/malformed/
+ # sibling-key tests are untouched and still green, which is what makes this an
+ # ADDITION to the policy rather than a relaxation of it.
+ # It takes no id of its own because PR6's block is full at 099 and 100+ is
+ # contracted to PR2 by the merged plan (docs/plans/harness-run-reliability.md
+ # §10.7; landed in #1044, PR2 not started per its status header).
+ # PR6 review round 11 (#1072). The round-10 retry answered "is the notice LOST?" and
+ # was silent on "is it DUPLICATED?", which is the obligation a retry incurs. The
+ # follow-up asked for proof that exactly one durable binding notice reaches the user
+ # and that later fires do not add another, and no test carried it: the success-race
+ # test stops at store level and never calls ``_emit_binding_change``, so the
+ # ``binding_recovery`` marker that gates every later fire does not exist in its
+ # world -- and that marker is exactly what the round-10 second stamp attempt runs
+ # against.
+ # ``test_one_rebind_that_wins_its_race_still_notifies_exactly_once`` closes it end to
+ # end on one store, in three steps: the race driven THROUGH ``_emit_binding_change``
+ # so the marker is persisted before the stamp as in production; a later fire of the
+ # same definition against the same signature, on a REAL second ``agent_runs`` row
+ # (reusing the first would be refused by the occupied slot and would prove the wrong
+ # layer), which must not reach the store at all -- asserted on every stamp ATTEMPT,
+ # since the store's contents cannot distinguish a short-circuit from a refused
+ # attempt; and the drain through the real dispatcher landing exactly ONE durable
+ # message, with a second pass landing nothing.
+ # A GREEN-FROM-BIRTH PIN, said plainly: both dedup layers already existed and are
+ # each exercised elsewhere, so nothing here is a red-first fix -- what was missing
+ # was putting them together on the path round 10 touched. RED BY MUTATION instead:
+ # neutering the signature short-circuit makes the later fire stamp a second notice,
+ # and the attempt list comes back with the same signature twice.
+ # It takes no id of its own for the reason above -- but the allocation itself has
+ # moved, and this is the note the other blocks point at. The plan merged as #1044
+ # RE-DREW §10.7 against the merged catalog ("an overflow block is dead the moment a
+ # landed catalog occupies any of it"), and PR6's overflow is now HFR-280...319, with
+ # PR2 at HFR-100...129. §10.7 says so explicitly: "#1072 currently carries
+ # review-round tests that took no ID because its block was full and its old overflow
+ # was occupied -- the 280...319 block above is where they belong." So the ~20
+ # subordinate tests documented throughout this file now HAVE a home, and assigning
+ # them is real outstanding work rather than a documentation nicety. It is left
+ # undone here deliberately: it changes the catalog's id SET, which is the one
+ # property every round of this review has verified as unchanged, so it is a scoped
+ # follow-up for the plan owner and not a close-out edit.
+ test: tests/test_harness_failure_visibility.py::test_a_successful_rebind_is_delivered_through_the_retried_notice_path
- id: HFR-240
name: the backend-wide clear does not delete a superseded row
status: covered
diff --git a/tests/test_caller_context.py b/tests/test_caller_context.py
index 71689a405..c702019b8 100644
--- a/tests/test_caller_context.py
+++ b/tests/test_caller_context.py
@@ -1,8 +1,16 @@
from __future__ import annotations
+import pytest
+
from core.caller_context import (
AVIBE_CALLER_BACKEND_ENV,
+ AVIBE_CALLER_CHANNEL_ID_ENV,
+ AVIBE_CALLER_MESSAGE_ID_ENV,
+ AVIBE_CALLER_PLATFORM_ENV,
+ AVIBE_CALLER_SESSION_KEY_ENV,
AVIBE_CALLER_SOURCE_ENV,
+ AVIBE_CALLER_USER_ID_ENV,
+ AVIBE_CALLER_WORKSPACE_ID_ENV,
AVIBE_NATIVE_SESSION_ID_ENV,
AVIBE_RUN_ID_ENV,
AVIBE_SESSION_ID_ENV,
@@ -76,3 +84,383 @@ def test_caller_context_from_platform_payload_preserves_callback_source() -> Non
assert context is not None
assert context.source == "callback"
+
+
+# --- the creation origin ---------------------------------------------------
+#
+# Subordinate to HFR-094's notice-body family (round 14 gate item 3, review comment
+# 5121007240) — no new scenario id. These fields exist so a failure notice can name the
+# conversation a definition was created in; the copy that renders them is covered in
+# ``tests/test_harness_failure_visibility.py``.
+
+
+def _slack_channel_context():
+ """A Slack channel message, shaped exactly as ``modules/im/slack.py`` builds it.
+
+ Note what the adapter does NOT set: ``platform`` is absent from both the typed
+ context and ``platform_specific``, which is why every capture call site has to pass
+ a ``fallback_platform`` resolved the same way the rest of the handler resolves it.
+ """
+
+ from modules.im import MessageContext
+
+ return MessageContext(
+ user_id="U0AUTHOR",
+ channel_id="C0123",
+ thread_id="1710000000.000100",
+ message_id="1710000000.000100",
+ platform_specific={"team_id": "T0999", "is_dm": False, "event": {}},
+ )
+
+
+def _agent_turn_payload(extra: dict | None = None) -> dict:
+ payload = {
+ "agent_session_id": "ses123",
+ "task_execution_id": "run456",
+ "task_trigger_kind": "agent_turn",
+ }
+ payload.update(extra or {})
+ return payload
+
+
+def test_the_creation_origin_survives_the_env_hop_into_created_by_caller() -> None:
+ """The whole contract in one pass: IM turn → env → subprocess → persisted metadata.
+
+ THE DEFECT this pins. An IM-created Harness definition is created by an Agent run
+ executing ``vibe task add``, so the ONLY channel between the conversation that asked
+ for it and the ``created_by.caller`` row that records it is the subprocess env. The
+ capture dropped every IM id on the floor: ``CallerContext`` carried session/run/
+ source/backend ids and nothing about where the request came from. Two consequences,
+ both closed here — the failure ladder's rungs (3) and (4) read
+ ``caller["session_key"]`` / ``caller["platform"]`` / ``caller["user_id"]``, fields
+ nothing had ever written, so the owner-DM rung was dead code; and the notice body
+ had no origin to name.
+
+ RED at 3578f2b6 (round 11) as an overlay spelling the env vars as string literals
+ rather than importing the new constants — an ``ImportError`` is not a red. There the
+ metadata came back as ``{'session_id': 'ses123', 'run_id': 'run456', 'source':
+ 'agent_turn'}``: no ``platform``, no ``user_id``, no ``session_key``, no
+ ``channel_id``, no ``message_id``, no ``workspace_id``.
+
+ The env is asserted as the MIDDLE of the hop, not as the destination: values are
+ read back through ``caller_context_from_env`` and only then compared, because a
+ field that serialises but does not deserialise is exactly as broken as one that was
+ never captured.
+ """
+
+ from vibe.cli import _definition_creation_metadata_from_caller
+
+ captured = caller_context_from_platform_payload(
+ _agent_turn_payload({"team_id": "T0999", "is_dm": False, "event": {}}),
+ message=_slack_channel_context(),
+ fallback_platform="slack",
+ )
+ assert captured is not None
+
+ env = captured.to_env()
+ assert env[AVIBE_CALLER_PLATFORM_ENV] == "slack"
+ assert env[AVIBE_CALLER_USER_ID_ENV] == "U0AUTHOR"
+ assert env[AVIBE_CALLER_CHANNEL_ID_ENV] == "C0123"
+ assert env[AVIBE_CALLER_SESSION_KEY_ENV] == "slack::channel::C0123::thread::1710000000.000100"
+ assert env[AVIBE_CALLER_MESSAGE_ID_ENV] == "1710000000.000100"
+ assert env[AVIBE_CALLER_WORKSPACE_ID_ENV] == "T0999"
+
+ # The subprocess hop: a fresh process sees only this mapping.
+ rehydrated = caller_context_from_env(env)
+ assert rehydrated is not None
+ assert rehydrated == captured, (
+ "every origin field has to round-trip; one that serialises without "
+ "deserialising is as broken as one never captured"
+ )
+
+ # And the REAL writer — the function ``vibe task add`` uses to build the row.
+ metadata = _definition_creation_metadata_from_caller(rehydrated)
+ caller = metadata["created_by"]["caller"]
+ assert caller["platform"] == "slack", "rung (4) reads exactly this key"
+ assert caller["user_id"] == "U0AUTHOR", "and exactly this one"
+ assert caller["session_key"] == "slack::channel::C0123::thread::1710000000.000100", (
+ "rung (3) reads exactly this key"
+ )
+ assert caller["scope_id"] == "slack::channel::C0123", (
+ "the thread key's parent scope, which rung (3) falls back to and "
+ "``parse_scope_id`` cannot express from the five-part form"
+ )
+ assert caller["channel_id"] == "C0123"
+ assert caller["message_id"] == "1710000000.000100"
+ assert caller["workspace_id"] == "T0999"
+
+
+def test_a_non_thread_session_key_records_no_redundant_scope_id() -> None:
+ """``scope_id`` is written only when it says something ``session_key`` does not.
+
+ Rung (3) reads ``session_key or scope_id``, so a copy of the same value would be
+ dead weight in every persisted definition. The three-part form IS its own scope.
+ """
+
+ from modules.im import MessageContext
+
+ captured = caller_context_from_platform_payload(
+ _agent_turn_payload({"is_dm": False}),
+ message=MessageContext(user_id="U1", channel_id="C1", platform="discord"),
+ )
+ assert captured is not None
+ assert captured.session_key == "discord::channel::C1"
+ assert "scope_id" not in captured.to_metadata()
+
+
+ "platform,payload_extra,kwargs,why",
+ [
+ (
+ "slack",
+ {"team_id": "T0999", "is_dm": False},
+ {"thread_id": "1710000000.000100"},
+ "a Slack channel message, thread ts included",
+ ),
+ (
+ "slack",
+ {"is_dm": True},
+ {"channel_id": "D0123", "thread_id": "1710000000.000100"},
+ "a Slack DM, whose scope id is the USER not the D-channel",
+ ),
+ (
+ "telegram",
+ {"is_dm": False, "is_forum": True},
+ {"platform": "telegram", "channel_id": "-1001234567890", "thread_id": None},
+ "a Telegram forum with no explicit topic id, which canonicalises to '1'",
+ ),
+ (
+ "telegram",
+ {"is_dm": False, "is_topic_message": True},
+ {"platform": "telegram", "channel_id": "-1001234567890", "thread_id": "77"},
+ "a Telegram topic message with an explicit topic id",
+ ),
+ (
+ "telegram",
+ {"is_dm": True},
+ {"platform": "telegram", "channel_id": "42", "thread_id": None},
+ "a Telegram DM, which has no thread segment at all",
+ ),
+ (
+ # The asymmetry the mirror has to reproduce rather than improve on:
+ # ``build_session_key_for_context`` applies ``fallback_platform`` to the
+ # key's PREFIX but calls ``resolve_context_thread_id`` without it, so a
+ # forum flag on a context whose own ``platform`` is unset yields NO thread
+ # segment. Unreachable in production (the Telegram adapter always sets
+ # ``platform``), and the case that caught this implementation canonicalising
+ # a thread the rest of the system would not have addressed.
+ "telegram",
+ {"is_dm": False, "is_forum": True},
+ {"channel_id": "-1001234567890", "thread_id": None},
+ "a forum flag with no platform on the context itself",
+ ),
+ (
+ "discord",
+ {"is_dm": False},
+ {"platform": "discord", "channel_id": "555", "thread_id": "778"},
+ "a Discord thread",
+ ),
+ (
+ "lark",
+ {"is_dm": False},
+ {"platform": "lark", "channel_id": "oc_abc", "thread_id": None},
+ "a Lark group, whose origin is nameable even though it is not linkable",
+ ),
+ ],
+)
+def test_the_captured_origin_session_key_matches_the_canonical_builder(
+ platform: str,
+ payload_extra: dict,
+ kwargs: dict,
+ why: str,
+) -> None:
+ """Drift pin for the one piece of logic this module reimplements.
+
+ The origin session key has to be the SAME grammar ``build_session_key_for_context``
+ produces, because rung (3) delivers to it — a notice addressed to a key the rest of
+ the system would not have built is a notice sent to the wrong conversation. The rule
+ is reimplemented rather than imported so ``core/caller_context.py`` keeps no
+ dependency on ``modules.im`` (the CLI imports it on every invocation), and this test
+ is what makes the duplication safe. If ``build_session_key_for_context`` changes,
+ this fails.
+ """
+
+ from core.scheduled_tasks import build_session_key_for_context
+ from modules.im import MessageContext
+
+ context = MessageContext(
+ user_id=kwargs.get("user_id", "U0AUTHOR"),
+ channel_id=kwargs.get("channel_id", "C0123"),
+ platform=kwargs.get("platform"),
+ thread_id=kwargs.get("thread_id"),
+ message_id="m1",
+ platform_specific=dict(payload_extra),
+ )
+ canonical = build_session_key_for_context(
+ context,
+ include_thread=True,
+ fallback_platform=platform,
+ ).to_key()
+
+ captured = caller_context_from_platform_payload(
+ _agent_turn_payload(payload_extra),
+ message=context,
+ fallback_platform=platform,
+ )
+ assert captured is not None
+ assert captured.session_key == canonical, f"drift on {why}"
+
+
+def test_a_discord_dm_captures_no_workspace_id() -> None:
+ """``message.guild`` is ``None`` in a DM, and a missing tenant must stay missing.
+
+ Read defensively off whatever the adapter already put on the payload — no
+ ``modules/im`` change feeds this — and the absence is what makes
+ ``origin_link`` refuse rather than fall back to Discord's ``@me`` path.
+ """
+
+ from types import SimpleNamespace
+
+ from modules.im import MessageContext
+
+ guild_message = SimpleNamespace(guild=SimpleNamespace(id=999))
+ in_guild = caller_context_from_platform_payload(
+ _agent_turn_payload({"message": guild_message, "is_dm": False}),
+ message=MessageContext(user_id="U1", channel_id="555", platform="discord"),
+ )
+ assert in_guild is not None
+ assert in_guild.workspace_id == "999", "an int guild id is captured as its string form"
+
+ in_dm = caller_context_from_platform_payload(
+ _agent_turn_payload({"message": SimpleNamespace(guild=None), "is_dm": True}),
+ message=MessageContext(user_id="U1", channel_id="U1", platform="discord"),
+ )
+ assert in_dm is not None
+ assert in_dm.workspace_id is None
+
+
+def test_a_discord_interaction_captures_its_guild_as_the_workspace() -> None:
+ """Button and quick-reply turns store ``interaction``, not ``message``."""
+
+ from types import SimpleNamespace
+
+ from modules.im import MessageContext
+
+ captured = caller_context_from_platform_payload(
+ _agent_turn_payload(
+ {
+ "interaction": SimpleNamespace(guild=SimpleNamespace(id=777)),
+ "is_dm": False,
+ }
+ ),
+ message=MessageContext(
+ user_id="U1",
+ channel_id="555",
+ platform="discord",
+ message_id="888",
+ ),
+ )
+
+ assert captured is not None
+ assert captured.workspace_id == "777"
+
+
+def test_a_caller_with_no_message_context_captures_no_origin() -> None:
+ """The CLI-only caller, unchanged.
+
+ ``vibe task add`` run by hand has no conversation behind it, so it must keep
+ producing exactly the pre-origin env and metadata — not empty origin fields, which
+ would render an origin line about nothing.
+ """
+
+ context = caller_context_from_platform_payload(_agent_turn_payload())
+ assert context is not None
+ assert context.to_metadata() == {
+ "session_id": "ses123",
+ "run_id": "run456",
+ "source": "agent_turn",
+ }
+ assert set(context.to_env()) == {
+ AVIBE_SESSION_ID_ENV,
+ AVIBE_RUN_ID_ENV,
+ AVIBE_CALLER_SOURCE_ENV,
+ }
+
+
+def test_a_session_scoped_caller_env_drops_only_the_per_turn_origin() -> None:
+ """The asymmetry between backends that CAN refresh their caller env and one that cannot.
+
+ The Claude SDK client is spawned once per session with a fixed environment, and that
+ same environment is the value compared to decide whether a cached client may be
+ reused. Two fields make that combination unsafe, for two different reasons, and both
+ are worse than the information they carry:
+
+ * ``message_id`` changes every turn, so leaving it in would respawn the Agent on
+ every single message;
+ * ``user_id`` changes with the author, and a channel session is deliberately shared
+ across participants — baking in the first speaker would later attribute another
+ participant's definition to them, and the owner-DM rung would notify the wrong
+ person.
+
+ Everything the SESSION owns survives, so a Claude-created definition still names its
+ conversation and still lights up rung (3). It gets no deep link, because every
+ permalink grammar needs the message id — an omission, not a wrong URL. Codex
+ (``BASH_ENV`` script) and OpenCode (binding file) rewrite their env per turn and keep
+ the full origin, which is why this is a per-call-site flag and not a global policy.
+ """
+
+ captured = caller_context_from_platform_payload(
+ _agent_turn_payload({"team_id": "T0999", "is_dm": False, "event": {}}),
+ message=_slack_channel_context(),
+ fallback_platform="slack",
+ )
+ assert captured is not None
+
+ stable = captured.session_stable()
+ assert stable.user_id is None and stable.message_id is None
+ assert (stable.platform, stable.channel_id, stable.workspace_id) == ("slack", "C0123", "T0999")
+ assert stable.session_key == "slack::channel::C0123::thread::1710000000.000100", (
+ "the conversation is session-owned and must survive"
+ )
+ assert stable.session_id == captured.session_id
+
+ assert AVIBE_CALLER_USER_ID_ENV not in stable.to_env()
+ assert AVIBE_CALLER_MESSAGE_ID_ENV not in stable.to_env()
+ assert AVIBE_CALLER_SESSION_KEY_ENV in stable.to_env()
+
+ from core.caller_context import caller_env_for_platform_payload
+
+ payload = _agent_turn_payload({"team_id": "T0999", "is_dm": False})
+ full = caller_env_for_platform_payload(
+ payload, message=_slack_channel_context(), fallback_platform="slack"
+ )
+ scoped = caller_env_for_platform_payload(
+ payload,
+ message=_slack_channel_context(),
+ fallback_platform="slack",
+ session_stable_only=True,
+ )
+ assert set(full) - set(scoped) == {AVIBE_CALLER_USER_ID_ENV, AVIBE_CALLER_MESSAGE_ID_ENV}
+
+
+def test_a_dm_loses_nothing_to_the_session_scoped_form() -> None:
+ """The case where the person IS the scope.
+
+ A DM's session key is ``<platform>::user::<id>``, so dropping ``user_id`` costs the
+ owner-DM rung nothing: rung (3) already addresses that same person. The stable form
+ is only lossy for a SHARED conversation, which is exactly where sharing is correct.
+ """
+
+ from modules.im import MessageContext
+
+ captured = caller_context_from_platform_payload(
+ _agent_turn_payload({"is_dm": True}),
+ message=MessageContext(
+ user_id="U0AUTHOR",
+ channel_id="D0123",
+ platform="slack",
+ message_id="1710000000.000200",
+ ),
+ )
+ assert captured is not None
+ assert captured.session_stable().session_key == "slack::user::U0AUTHOR"
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index c0705088c..de9cae2db 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -617,6 +617,87 @@ def test_session_handler_injects_caller_context_env(monkeypatch, tmp_path: Path)
assert env["AVIBE_NATIVE_SESSION_ID"] == "claude-native"
+def test_session_handler_injects_only_session_stable_creation_origin(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """The creation origin a Claude session may carry, and the two ids it may not.
+
+ Round 14 gate item 3 (review comment 5121007240): a Harness definition created by
+ ``vibe task add`` inside an Agent turn has to record the conversation it came from,
+ and this env is the only hop those ids can travel. But a Claude SDK client is spawned
+ ONCE per session with a fixed environment, and that same environment is what
+ ``_reuse_cached_claude_session_if_available`` compares to decide whether the cached
+ client is still valid. So:
+
+ * the session-owned ids (platform, channel, session key, workspace) are baked in —
+ that is what makes the notice able to name the conversation and rung (3) able to
+ address it;
+ * ``AVIBE_CALLER_USER_ID`` and ``AVIBE_CALLER_MESSAGE_ID`` are NOT. The message id
+ changes every turn, so including it would respawn Claude on every message; the
+ author changes per speaker in a shared channel, and
+ ``test_session_handler_reuses_cached_claude_client_when_system_prompt_is_unchanged``
+ pins that a channel session is shared across participants — so a baked-in author
+ would later attribute another participant's definition to them and DM the wrong
+ person.
+
+ The visible cost is a Claude-created definition having no deep link (every permalink
+ grammar needs the message id). Codex and OpenCode rewrite their caller env per turn
+ and keep the full origin; that asymmetry is the unit-level
+ ``test_a_session_scoped_caller_env_drops_only_the_per_turn_origin``.
+ """
+
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ # Keep the base session anchor at ``slack_C123`` (this file's session stub asserts
+ # it): without this the message id would become the anchor, which is a different
+ # decision from the one under test.
+ controller.im_client.should_use_message_id_for_channel_session = lambda _context=None: False
+ handler = SessionHandler(controller)
+ context = MessageContext(
+ user_id="U123",
+ channel_id="C123",
+ message_id="1710000000.000200",
+ platform_specific={
+ "team_id": "T0999",
+ "is_dm": False,
+ "agent_session_target": {
+ "id": "ses-parent",
+ "agent_backend": "claude",
+ "native_session_id": "claude-native",
+ },
+ },
+ )
+
+ _run_session(handler, context)
+
+ env = captured["options"].env
+ # The Slack adapter sets neither ``context.platform`` nor a payload ``platform``, so
+ # the handler's own resolver is what supplies it — captured here as well, because a
+ # missing platform would make the whole origin unnameable.
+ assert env["AVIBE_CALLER_PLATFORM"] == "slack"
+ assert env["AVIBE_CALLER_CHANNEL_ID"] == "C123"
+ assert env["AVIBE_CALLER_SESSION_KEY"] == "slack::channel::C123"
+ assert env["AVIBE_CALLER_WORKSPACE_ID"] == "T0999"
+
+ assert "AVIBE_CALLER_USER_ID" not in env, (
+ "a shared channel session must not bake in whichever participant spoke first"
+ )
+ assert "AVIBE_CALLER_MESSAGE_ID" not in env, (
+ "a per-message id here would respawn the Claude client on every turn"
+ )
+
+
def test_session_handler_coalesces_concurrent_claude_client_creates(
monkeypatch, tmp_path: Path
) -> None:
diff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.py
index 75971bfd1..3f1ea1571 100644
--- a/tests/test_cli_task_command.py
+++ b/tests/test_cli_task_command.py
@@ -3308,3 +3308,328 @@ def test_task_update_refuses_to_undo_a_reclaim_committed_after_its_read(tmp_path
f"enabled={None if live is None else live.enabled!r} while the row says "
f"name={stored.name!r} enabled={stored.enabled!r}"
)
+
+
+# --- the reserved workspace-notifications Session is not an admission target --
+#
+# Round-16 review thread 3678900318, confirmed blocking as comment 5124692513. The
+# reserved row (``ses-workspace-notices``) exists to HOLD failure notices and accepts no
+# turn: no backend, no dispatch. A round-15 guard closed the Web composer
+# (``POST /api/sessions/<id>/messages``); every CLI door reaches the runtime through
+# ``resolve_session_id_target`` instead, and that resolver refused only ARCHIVED rows
+# while this one is deliberately kept ACTIVE.
+#
+# The maintainer's evidence contract is ZERO SIDE EFFECTS at each door, not merely a
+# non-zero exit: no definition row, no queued Run, no ``messages`` row, nothing
+# dispatched. Each test below therefore asserts the absences explicitly rather than
+# trusting the return code, and each carries a POSITIVE CONTROL in the same test so a
+# guard that simply refused everything could not pass it.
+#
+# Subordinate coverage under HFR-094; no new scenario id.
+
+
+def _capture_stderr_text(func, *args) -> tuple[int, str]:
+ """Like ``_capture_stderr_json``, but WITHOUT parsing.
+
+ The refusal tests below have to assert the EXIT CODE before they touch the payload.
+ Against ``d00bc038`` the command succeeds, writes its success payload to stdout and
+ leaves stderr empty — so a helper that parses first turns the real regression signal
+ ("this was admitted") into a ``JSONDecodeError`` about an empty string, which names
+ neither the lane nor the defect.
+ """
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ result = func(*args)
+ return result, stderr.getvalue()
+
+
+def _no_caller_context(monkeypatch) -> None:
+ """Run the command as a BARE terminal invocation.
+
+ ``caller_context_from_env`` keys off ``AVIBE_SESSION_ID``, which is set inside every
+ Avibe-hosted Agent shell — including the one a coding agent runs these tests from. Left
+ alone it changes the command under test (it defaults the target Session and relaxes the
+ session-policy validation) and stamps the caller into ``metadata.created_by``, so the
+ same test exercises a different path locally than it does in CI. Deleted rather than
+ replaced: the lane being pinned is a human typing the command.
+ """
+ monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)
+
+
+def _reserved_session_cli_db(tmp_path: Path):
+ """A migrated CLI state DB holding the reserved row plus one ordinary session.
+
+ Both rows in ONE database because the point is DISCRIMINATION: the same command,
+ the same store and the same resolver must refuse one id and accept the other, which
+ a test with only the reserved row cannot show.
+
+ Returns ``(db_path, agent_store, ordinary_session_id)``.
+ """
+ from storage.agent_session_rows import resolve_workspace_notice_session
+ from storage.importer import ensure_sqlite_state
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
+
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ assert resolve_workspace_notice_session(conn, title="Workspace notifications") == (
+ "ses-workspace-notices"
+ )
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ ordinary = service.bind_agent_session(
+ scope_key="slack::channel::C900",
+ agent_name="worker",
+ session_anchor="slack_C900",
+ native_session_id="native-C900",
+ )
+ finally:
+ service.close()
+ assert ordinary
+ return db_path, agent_store, ordinary
+
+
+ ("language", "expected_hint"),
+ [
+ (
+ "en",
+ "This session only receives Avibe's workspace failure notifications — it does not accept messages.",
+ ),
+ (
+ "zh",
+ "该会话只接收 Avibe 的工作区失败通知,不接受发送消息。",
+ ),
+ ],
+)
+def test_reserved_session_cli_hint_uses_the_configured_backend_locale(
+ language: str,
+ expected_hint: str,
+) -> None:
+ exc = cli.UnresolvableSessionTarget(
+ "reserved",
+ session_id="ses-workspace-notices",
+ reason="reserved",
+ )
+ with patch.object(
+ cli.V2Config,
+ "load",
+ return_value=SimpleNamespace(language=language),
+ ):
+ error = cli._reserved_session_cli_error(exc)
+
+ assert error.hint == expected_hint
+
+
+def _message_rows(db_path: Path, session_id: str) -> list[tuple]:
+ from sqlalchemy import text as sa_text
+
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ return [
+ tuple(row)
+ for row in conn.execute(
+ sa_text(
+ "SELECT author, type, content_text FROM messages "
+ "WHERE session_id = :sid ORDER BY created_at, id"
+ ),
+ {"sid": session_id},
+ )
+ ]
+
+
+def test_task_add_refuses_the_reserved_session_with_no_side_effects(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """``vibe task add --session-id ses-workspace-notices`` is refused at ADMISSION.
+
+ The definition is the durable half of the hole: once persisted, every future fire
+ re-resolves the same pin, so a definition that got in would have to be discovered
+ and paused rather than simply never accepted. ``cmd_task_add`` reaches
+ ``_resolve_agent_for_target`` — and through it ``resolve_session_id_target`` —
+ BEFORE it writes anything, so the shared resolver guard closes this door with no
+ CLI-local exception of its own. That is the mechanism the maintainer asked for: one
+ shared-target fix, not another route-local special case.
+
+ Zero side effects, asserted as absences (comment 5124692513): no definition in the
+ store, no queued Run, and the reserved transcript untouched.
+
+ POSITIVE CONTROL in the same test: the ordinary session id, through the identical
+ command and store, IS accepted. A guard that refused every ``--session-id`` would
+ fail here.
+ """
+ _no_caller_context(monkeypatch)
+ db_path, agent_store, ordinary = _reserved_session_cli_db(tmp_path)
+ store = cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_task_add(
+ ["--session-id", "ses-workspace-notices", "--cron", "0 * * * *", "--message", "hello"]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ ):
+ result, stderr_text = _capture_stderr_text(cli.cmd_task_add, args)
+
+ assert result == 1, (
+ "``vibe task add --session-id ses-workspace-notices`` was ADMITTED. The reserved "
+ "row accepts no turn, so every future fire of this definition would resolve a "
+ f"target that cannot take one. stdout={capsys.readouterr().out!r}"
+ )
+ payload = json.loads(stderr_text)
+ assert payload["ok"] is False
+ assert payload["code"] == "reserved_session", (
+ "the refusal must be TYPED, not swallowed by the broad handler's generic "
+ "``task_command_failed``. ``reserved_session`` is the same token the Web surface "
+ "already answers with, so one client vocabulary covers both: "
+ f"{payload}"
+ )
+ assert "reserved for the runtime" in payload["error"], (
+ f"the refusal has to say WHY, in the diagnostic the resolver owns: {payload}"
+ )
+ assert "ses-workspace-notices" in payload["error"], (
+ f"and it has to name the session that was refused: {payload}"
+ )
+ assert payload["details"] == {
+ "session_id": "ses-workspace-notices",
+ "reason": "reserved",
+ }, f"and it must carry the machine-readable subject and reason: {payload}"
+
+ # --- zero side effects --------------------------------------------------
+ assert cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json").list_tasks() == [], (
+ "a definition pinned to a row that takes no turns must never be PERSISTED: "
+ "every later fire would re-resolve the same pin"
+ )
+ assert store.list_tasks() == [], "and the live store the command used must agree"
+ assert request_store.list_pending() == [], (
+ "creation does not fire, and a refused creation may not queue anything either"
+ )
+ assert _message_rows(db_path, "ses-workspace-notices") == [], (
+ "nothing may be written into the runtime's own row"
+ )
+
+ # --- positive control: the ordinary session is accepted -----------------
+ ok_args = _parse_task_add(
+ ["--session-id", ordinary, "--cron", "0 * * * *", "--message", "hello"]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_store", return_value=store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ ):
+ assert cli.cmd_task_add(ok_args) == 0
+ accepted = json.loads(capsys.readouterr().out)
+ assert accepted["ok"] is True
+ assert accepted["definition"]["session_id"] == ordinary, (
+ "the guard must not have narrowed ordinary session targeting: "
+ f"{accepted['definition']}"
+ )
+ assert [task.session_id for task in store.list_tasks()] == [ordinary]
+
+
+def test_agent_run_refuses_the_reserved_session_with_no_side_effects(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """The direct lane named in the finding, as a test rather than a hand probe.
+
+ ``vibe agent run --session-id ses-workspace-notices --message … --no-callback`` is
+ the exact command quoted in review thread 3678900318. Against ``d00bc038`` it
+ returned ``ok: true`` with EXIT 0 and left a QUEUED ``agent_run`` request whose
+ ``session_id`` was the reserved row — a real turn on its way into a machine-owned
+ session with an empty ``agent_backend``, which is what "accepts no turn" was
+ supposed to forbid.
+
+ ``--no-callback`` is load-bearing, not noise: without it the command stops earlier
+ on ``missing_async_callback``, which would let this test pass on a tree with the hole
+ wide open. The flag is what makes the run reach admission.
+
+ Zero side effects: no queued Run (the durable artifact the scheduler would have
+ picked up) and no ``messages`` row. Positive control: the ordinary session queues.
+ """
+ _no_caller_context(monkeypatch)
+ db_path, agent_store, ordinary = _reserved_session_cli_db(tmp_path)
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ "--async",
+ "--no-callback",
+ "--session-id",
+ "ses-workspace-notices",
+ "--message",
+ "hello",
+ ]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ result, stderr_text = _capture_stderr_text(cli.cmd_agent_run, args)
+
+ assert result == 1, (
+ "``vibe agent run --session-id ses-workspace-notices --message … --no-callback`` "
+ "returned success — the exact command from review thread 3678900318, admitted. "
+ f"stdout={capsys.readouterr().out!r} pending="
+ f"{[r.session_id for r in request_store.list_pending()]}"
+ )
+ payload = json.loads(stderr_text)
+ assert payload["ok"] is False
+ assert payload["code"] == "reserved_session", (
+ "the gate's remaining ask (comment 5124964406): direct Agent admission fell "
+ "through ``cmd_agent_run``'s broad ``except Exception`` and reported "
+ "``task_command_failed``, so a caller had only prose to branch on. The refusal "
+ f"must stay typed and coded at the consuming CLI surface: {payload}"
+ )
+ assert "reserved for the runtime" in payload["error"], (
+ f"the resolver's own diagnostic has to reach the caller: {payload}"
+ )
+ assert "ses-workspace-notices" in payload["error"]
+ assert payload["details"] == {
+ "session_id": "ses-workspace-notices",
+ "reason": "reserved",
+ }, f"and it must carry the machine-readable subject and reason: {payload}"
+
+ # --- zero side effects --------------------------------------------------
+ assert request_store.list_pending() == [], (
+ "against d00bc038 this held one queued agent_run for the reserved session; a "
+ "queued Run is the artifact the scheduler would dispatch"
+ )
+ assert cli.TaskExecutionStore(tmp_path / "task_requests").list_pending() == [], (
+ "and durably so, not only in the store instance the command happened to hold"
+ )
+ assert _message_rows(db_path, "ses-workspace-notices") == [], (
+ "no turn side effect of any kind lands in the runtime's own row"
+ )
+
+ # --- positive control: the ordinary session still runs ------------------
+ ok_args = _parse_agent_run(
+ ["--async", "--no-callback", "--session-id", ordinary, "--message", "hello"]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ ):
+ assert cli.cmd_agent_run(ok_args) == 0
+ accepted = json.loads(capsys.readouterr().out)
+ assert accepted["ok"] is True
+ assert [request.session_id for request in request_store.list_pending()] == [ordinary], (
+ "an ordinary Session must still be able to take a direct Agent Run: "
+ f"{[r.session_id for r in request_store.list_pending()]}"
+ )
diff --git a/tests/test_cli_watch_command.py b/tests/test_cli_watch_command.py
index 2261aaa6d..808dda5fe 100644
--- a/tests/test_cli_watch_command.py
+++ b/tests/test_cli_watch_command.py
@@ -1683,3 +1683,198 @@ def test_watch_update_refuses_to_undo_a_reclaim_committed_after_its_read(tmp_pat
f"enabled={None if live is None else live.enabled!r} while the row says "
f"name={stored.name!r} enabled={stored.enabled!r}"
)
+
+
+# --- the reserved workspace-notifications Session is not a Watch target -------
+#
+# Round-16 review thread 3678900318 (blocking, comment 5124692513), the Watch half of
+# the same admission contract the Task and direct Agent Run lanes carry in
+# ``tests/test_cli_task_command.py``. A watch is the WORST lane to leave open: it is
+# long-lived and self-firing, so one accepted definition dispatches a turn into the
+# runtime's own notice row on every event, not once.
+#
+# Subordinate coverage under HFR-094; no new scenario id.
+
+
+def _capture_stderr_text(func, *args) -> tuple[int, str]:
+ """Like ``_capture_stderr_json``, but WITHOUT parsing.
+
+ The refusal test below asserts the EXIT CODE before it touches the payload. Against
+ ``d00bc038`` the command succeeds, writes to stdout and leaves stderr empty, so a
+ helper that parses first reports a ``JSONDecodeError`` about an empty string instead
+ of the real regression ("this watch was admitted").
+ """
+ stderr = io.StringIO()
+ with redirect_stderr(stderr):
+ result = func(*args)
+ return result, stderr.getvalue()
+
+
+def _no_caller_context(monkeypatch) -> None:
+ """Run the command as a BARE terminal invocation.
+
+ ``caller_context_from_env`` keys off ``AVIBE_SESSION_ID``, which is set inside every
+ Avibe-hosted Agent shell — including the one a coding agent runs these tests from.
+ Left alone it defaults the target Session and relaxes session-policy validation, so the
+ same test would exercise a different path locally than in CI.
+ """
+ monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)
+
+
+def _reserved_session_cli_db(tmp_path: Path):
+ """A migrated CLI state DB holding the reserved row plus one ordinary session.
+
+ Both rows in ONE database: the point is DISCRIMINATION — the same command and store
+ must refuse one id and accept the other.
+
+ Returns ``(db_path, agent_store, ordinary_session_id)``.
+ """
+ from storage.agent_session_rows import resolve_workspace_notice_session
+ from storage.importer import ensure_sqlite_state
+ from storage.sessions_service import SQLiteSessionsService
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ ensure_sqlite_state(db_path=db_path, primary_platform="slack")
+
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ assert resolve_workspace_notice_session(conn, title="Workspace notifications") == (
+ "ses-workspace-notices"
+ )
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ ordinary = service.bind_agent_session(
+ scope_key="slack::channel::C900",
+ agent_name="worker",
+ session_anchor="slack_C900",
+ native_session_id="native-C900",
+ )
+ finally:
+ service.close()
+ assert ordinary
+ return db_path, agent_store, ordinary
+
+
+def _message_rows(db_path: Path, session_id: str) -> list[tuple]:
+ from sqlalchemy import text as sa_text
+
+ with cli.create_sqlite_engine(db_path).begin() as conn:
+ return [
+ tuple(row)
+ for row in conn.execute(
+ sa_text(
+ "SELECT author, type, content_text FROM messages "
+ "WHERE session_id = :sid ORDER BY created_at, id"
+ ),
+ {"sid": session_id},
+ )
+ ]
+
+
+def test_watch_add_refuses_the_reserved_session_with_no_side_effects(
+ tmp_path: Path, capsys, monkeypatch
+) -> None:
+ """``vibe watch add --session-id ses-workspace-notices`` is refused at ADMISSION.
+
+ ``cmd_watch_add`` resolves the pin through ``_resolve_agent_for_target`` — and so
+ through the shared ``resolve_session_id_target`` — before it stores the definition or
+ starts a waiter, so the resolver guard closes this door with no watch-local
+ exception. Zero side effects, per comment 5124692513: no watch row, no waiter
+ started, nothing written into the reserved transcript.
+
+ ``_wait_for_watch_startup`` is patched to a spy that MUST NOT be called: on this lane
+ the absence of a dispatch is the claim, and a startup that fired would mean a real
+ waiter subprocess was launched against a definition that should never have existed.
+
+ POSITIVE CONTROL in the same test: the ordinary session id, same command, same store,
+ is accepted and does start.
+ """
+ _no_caller_context(monkeypatch)
+ db_path, agent_store, ordinary = _reserved_session_cli_db(tmp_path)
+ store = ManagedWatchStore(tmp_path / "watches.json")
+ runtime_store = WatchRuntimeStateStore(tmp_path / "watch_runtime.json")
+ started: list[str] = []
+
+ def _spy_startup(*args, **kwargs):
+ started.append(args[2])
+ return _startup_ok(store, runtime_store, args[2])
+
+ args = _parse_watch_add(
+ ["--session-id", "ses-workspace-notices", "--shell", "python3 scripts/wait.py"]
+ )
+
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=_spy_startup),
+ ):
+ result, stderr_text = _capture_stderr_text(cli.cmd_watch_add, args)
+
+ assert result == 1, (
+ "``vibe watch add --session-id ses-workspace-notices`` was ADMITTED. A watch is "
+ "long-lived and self-firing, so this definition would dispatch a turn into the "
+ f"runtime's own notice row on every event. stdout={capsys.readouterr().out!r} "
+ f"started={started}"
+ )
+ payload = json.loads(stderr_text)
+ assert payload["ok"] is False
+ assert payload["code"] == "reserved_session", (
+ "the refusal must be TYPED here too, with the same token the Web surface and the "
+ f"other two admission doors use — one contract, every surface: {payload}"
+ )
+ assert "reserved for the runtime" in payload["error"], (
+ f"the refusal has to say WHY, in the resolver's own diagnostic: {payload}"
+ )
+ assert "ses-workspace-notices" in payload["error"], (
+ f"and it has to name the session that was refused: {payload}"
+ )
+ assert payload["details"] == {
+ "session_id": "ses-workspace-notices",
+ "reason": "reserved",
+ }, f"and it must carry the machine-readable subject and reason: {payload}"
+
+ # --- zero side effects --------------------------------------------------
+ assert ManagedWatchStore(tmp_path / "watches.json").list_watches() == [], (
+ "a watch pinned to a row that takes no turns must never be PERSISTED: it would "
+ "dispatch a turn into the runtime's notice row on every event, not once"
+ )
+ assert store.list_watches() == [], "and the live store the command used must agree"
+ assert started == [], (
+ f"no waiter may be started for a definition that was never admitted: {started}"
+ )
+ assert runtime_store.load().get("watches", {}) == {}, (
+ "and no runtime state may be recorded for it"
+ )
+ assert _message_rows(db_path, "ses-workspace-notices") == [], (
+ "nothing may be written into the runtime's own row"
+ )
+
+ # --- positive control: the ordinary session is accepted -----------------
+ ok_args = _parse_watch_add(
+ ["--session-id", ordinary, "--shell", "python3 scripts/wait.py"]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),
+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._watch_store", return_value=store),
+ patch("vibe.cli._watch_runtime_store", return_value=runtime_store),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=_spy_startup),
+ ):
+ assert cli.cmd_watch_add(ok_args) == 0
+ accepted = json.loads(capsys.readouterr().out)
+ assert accepted["ok"] is True
+ assert accepted["definition"]["session_id"] == ordinary, (
+ f"the guard must not have narrowed ordinary Watch targeting: {accepted['definition']}"
+ )
+ assert [watch.session_id for watch in store.list_watches()] == [ordinary]
+ assert started == [accepted["definition"]["id"]], (
+ f"and an admitted watch really does start: {started}"
+ )
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 66a9fd7c8..7083d5a04 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -89,6 +89,10 @@ def test_public_surface_is_stable():
"SessionArchivedError",
# Localized user-facing copy for that guard's 409 body:
"session_archived_message",
+ # Reserved-row guard raised by archive_session for the workspace-notifications
+ # session (D5 rung (5)'s home): archive is terminal, and archiving that row
+ # would silently swallow every later caller-less failure notice.
+ "ReservedSessionError",
}
assert set(sessions_service.__all__) == expected | {"SESSION_ARCHIVED_I18N_KEY"}
for name in expected:
diff --git a/tests/test_harness_definition_lifecycle.py b/tests/test_harness_definition_lifecycle.py
index a66617f0e..44755e412 100644
--- a/tests/test_harness_definition_lifecycle.py
+++ b/tests/test_harness_definition_lifecycle.py
@@ -804,6 +804,40 @@ def test_one_shot_states_and_counts_agree_on_the_clock(store) -> None:
assert (counts["waiting"], counts["finished"], counts["paused"]) == (1, 1, 1)
+def test_naive_one_shot_uses_its_task_timezone_in_rows_counts_and_next_fire(store) -> None:
+ """Offset-free ``run_at`` has one meaning across SQL and the scheduler."""
+
+ now_utc = datetime.now(timezone.utc)
+ los_angeles = ZoneInfo("America/Los_Angeles")
+ shanghai = ZoneInfo("Asia/Shanghai")
+ ahead = (now_utc.astimezone(los_angeles) + timedelta(hours=1)).replace(tzinfo=None)
+ behind = (now_utc.astimezone(shanghai) - timedelta(hours=1)).replace(tzinfo=None)
+
+ _task(
+ store,
+ "naive-ahead",
+ schedule_type="at",
+ run_at=ahead.isoformat(),
+ timezone="America/Los_Angeles",
+ )
+ _task(
+ store,
+ "naive-behind",
+ schedule_type="at",
+ run_at=behind.isoformat(),
+ timezone="Asia/Shanghai",
+ )
+
+ rows = {row["id"]: row for row in store.list_scheduled_tasks()}
+ assert rows["naive-ahead"]["lifecycle_state"] == "waiting"
+ assert rows["naive-behind"]["lifecycle_state"] == "finished"
+ assert rows["naive-ahead"]["next_run_at"] is not None
+ assert rows["naive-behind"]["next_run_at"] is None
+
+ counts = store.count_scheduled_tasks()
+ assert (counts["waiting"], counts["finished"]) == (1, 1)
+
+
def test_mark_cycle_result_stamps_a_finish_only_when_it_retires_the_watch(tmp_path: Path) -> None:
"""Only the cycle that changes enabled -> disabled owns retirement state."""
from core.watches import ManagedWatchStore
diff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.py
new file mode 100644
index 000000000..388eca2b3
--- /dev/null
+++ b/tests/test_harness_failure_visibility.py
@@ -0,0 +1,12262 @@
+"""PR6 — make harness failure visible.
+
+Scenarios HFR-060 … HFR-090 (``tests/scenarios/harness_failure_recovery``).
+
+Three groups, in the order the plan builds them:
+
+1. the terminal-writer set — every UPDATE that transitions ``agent_runs.status``
+ to a terminal value is guarded and stamps an owed failure notice;
+2. the owed-notice drain — receipt/ack/backoff/dead-letter, streak suppression,
+ settled-prefix deferral;
+3. derived health — the counters the CLI/UI badge reads, and the row classes that
+ must not reach them.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import pytest
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from sqlalchemy import event, select
+
+from core.scheduled_tasks import TaskExecutionStore
+from storage.background import (
+ NOTICE_KIND_BINDING_CHANGE,
+ NOTICE_KIND_FAILURE,
+ NOTICE_PENDING,
+ NOTICE_SENT,
+ OWED_FAILURE_NOTICE_KEY,
+ OWED_NOTICE_INDEX,
+ RUN_INTERRUPTION_REASONS,
+ SQLiteBackgroundTaskStore,
+ owed_notice_eligible,
+)
+
+
+def _store(tmp_path: Path) -> tuple[SQLiteBackgroundTaskStore, TaskExecutionStore]:
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ requests = TaskExecutionStore(tmp_path / "task_requests")
+ requests._sqlite = sqlite
+ return sqlite, requests
+
+
+_EPOCH = "2026-07-01T00:00:00+00:00"
+
+
+def _task(sqlite: SQLiteBackgroundTaskStore, definition_id: str, **overrides) -> None:
+ payload = {
+ "id": definition_id,
+ "name": definition_id,
+ "prompt": "go",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "created_at": _EPOCH,
+ "updated_at": _EPOCH,
+ }
+ payload.update(overrides)
+ sqlite.upsert_scheduled_task(payload)
+
+
+def _watch(sqlite: SQLiteBackgroundTaskStore, definition_id: str, **overrides) -> None:
+ payload = {
+ "id": definition_id,
+ "name": definition_id,
+ "prompt": "check",
+ "command": ["true"],
+ "enabled": True,
+ "created_at": _EPOCH,
+ "updated_at": _EPOCH,
+ }
+ payload.update(overrides)
+ sqlite.upsert_watch(payload)
+
+
+# --- group 1: the terminal writer set -------------------------------------
+
+
+def test_complete_does_not_clobber_an_already_terminal_run(tmp_path: Path) -> None:
+ """HFR-060 — ``complete()`` must not rewrite a status another actor settled.
+
+ ``TaskExecutionStore.complete`` terminalizes through the UNGUARDED
+ ``update_run_status``, whose UPDATE has no status predicate. A run whose real
+ terminal result already landed ``succeeded`` is rewritten to ``failed`` when
+ the claimed-request layer completes with an error, so the user is shown a
+ failure for a run that worked.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ request = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="hi")
+ claimed = requests.claim(request.id)
+ assert claimed is not None
+
+ # The backend's own terminal result lands first, through a guarded writer.
+ sqlite.record_run_output(
+ request.id,
+ output_id="out-1",
+ text="the report",
+ terminal_status="succeeded",
+ )
+ assert sqlite.get_run(request.id)["status"] == "succeeded"
+
+ # The claimed-request layer then completes the same row with an error.
+ requests.complete(claimed, ok=False, error="backend blew up")
+
+ saved = sqlite.get_run(request.id)
+ assert saved["status"] == "succeeded", "a settled success must not be rewritten to failed"
+ assert saved["result_text"] == "the report"
+
+
+def test_complete_coalesced_does_not_clobber_an_already_succeeded_run(tmp_path: Path) -> None:
+ """HFR-061 — the coalesced completer must skip already-terminal rows.
+
+ ``complete_coalesced_agent_runs_for_workbench_in_connection`` honors
+ ``cancel_requested`` but has no ``queued|running`` predicate and no
+ already-terminal skip, so it rewrites a settled row wholesale.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ request = requests.enqueue_agent_run(
+ session_key="slack::channel::C1",
+ message="hi",
+ agent_name=None,
+ )
+ claimed = requests.claim(request.id)
+ assert claimed is not None
+ sqlite.record_run_output(
+ request.id,
+ output_id="out-1",
+ text="done",
+ terminal_status="succeeded",
+ )
+
+ requests.complete_coalesced(claimed, [request.id], ok=False, error="turn died")
+
+ saved = sqlite.get_run(request.id)
+ assert saved["status"] == "succeeded", "a settled success must not be rewritten to failed"
+
+
+def _cancel_mid_write(sqlite_store, run_id: str, *, fire_on: str):
+ """A ``cancel_run`` from a SECOND connection, fired between snapshot and UPDATE.
+
+ Returns a listener to register on ``before_cursor_execute``. It fires once, on the
+ first statement whose SQL contains ``fire_on`` — for a terminal writer that is its
+ own UPDATE, so the cancel is committed after the writer has read the row and
+ decided what to write, and before the write lands. That gap is not hypothetical:
+ pysqlite starts no transaction for a SELECT, so a guarded writer's snapshot really
+ is older than its own UPDATE, and ``cancel_run`` really is a separate transaction.
+
+ The cancel goes through the production ``cancel_run`` on a second store over the
+ same file, not through a hand-written UPDATE, so what the test races against is
+ what the Stop button does.
+ """
+
+ fired: list[int] = []
+
+ def _listener(conn, cursor, statement, parameters, context, executemany):
+ if fired or fire_on not in statement:
+ return
+ fired.append(1)
+ other = SQLiteBackgroundTaskStore(sqlite_store.db_path)
+ try:
+ other.cancel_run(run_id)
+ finally:
+ other.close()
+
+ return _listener, fired
+
+
+def test_a_cancel_landing_under_the_coalesced_completer_is_not_overwritten(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-060/061 — Stop must outrank a stale terminal snapshot.
+
+ HFR-061 stopped the coalesced completer clobbering an already-SETTLED row by
+ skipping terminal statuses, but it deliberately let ``canceled`` fall through so a
+ cancel-requested row keeps being normalized. That fall-through is also a hole: the
+ row's ``cancel_requested`` is read from a batch snapshot and never re-asserted, so
+ a ``cancel_run`` landing between the snapshot and the UPDATE is overwritten by a
+ ``failed`` the writer decided on before the user pressed Stop.
+
+ Two consequences, and the second is the one that makes this a P6 scenario rather
+ than a cosmetic status bug:
+
+ * the run reads ``failed`` when the user cancelled it, so the Stop silently did
+ nothing;
+ * a ``failed`` transition STAMPS AN OWED FAILURE NOTICE, so the drain then tells
+ the user their task is broken — because they cancelled it. A notice nobody can
+ act on, in the lane this whole feature exists to make trustworthy.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ request = requests.enqueue_agent_run(
+ session_key="slack::channel::C1",
+ message="hi",
+ agent_name=None,
+ )
+ claimed = requests.claim(request.id)
+ assert claimed is not None
+ assert sqlite.get_run(request.id)["status"] == "running"
+
+ listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="UPDATE agent_runs")
+ event.listen(sqlite.engine, "before_cursor_execute", listener)
+ try:
+ requests.complete_coalesced(claimed, [request.id], ok=False, error="turn died")
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", listener)
+
+ assert fired, "the interleaved cancel never fired; the race was not exercised"
+
+ saved = sqlite.get_run(request.id)
+ assert saved["status"] == "canceled", (
+ f"the user's Stop was overwritten by a stale terminal snapshot; row is {saved['status']!r}"
+ )
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None, (
+ "a cancelled run owes no failure notice — the drain would tell the user their "
+ "task broke because they stopped it"
+ )
+
+
+def test_a_cancel_landing_under_settle_run_terminal_is_not_overwritten(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-060/061 — the same hole in the zombie-settlement writer.
+
+ ``settle_run_terminal`` scopes its UPDATE to ``queued|running``, which catches a
+ cancel of a QUEUED row because ``cancel_run`` flips that one straight to
+ ``canceled``. On a RUNNING row ``cancel_run`` sets only ``cancel_requested``, the
+ status predicate still matches, and the write lands ``failed`` over the Stop with
+ an owed notice attached. A running turn is precisely what a user presses Stop on,
+ so this is the reachable half of the same defect.
+
+ The refusal alone would not be a fix: a run left ``running`` with nothing to settle
+ it is the zombie this writer exists to prevent. So the write is re-decided ONCE
+ from the row as it then stands, and lands ``canceled``.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ request = requests.enqueue_agent_run(
+ session_key="slack::channel::C2",
+ message="hi",
+ agent_name=None,
+ )
+ claimed = requests.claim(request.id)
+ assert claimed is not None
+ assert sqlite.get_run(request.id)["status"] == "running"
+
+ listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="UPDATE agent_runs")
+ event.listen(sqlite.engine, "before_cursor_execute", listener)
+ try:
+ written = sqlite.settle_run_terminal(
+ request.id, terminal_status="failed", error="no terminal result"
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", listener)
+
+ assert fired, "the interleaved cancel never fired; the race was not exercised"
+
+ saved = sqlite.get_run(request.id)
+ assert saved["status"] == "canceled", (
+ f"the user's Stop was overwritten by a stale snapshot; row is {saved['status']!r}"
+ )
+ assert written == "canceled", (
+ f"the writer must report what it actually wrote, not what it first decided; got {written!r}"
+ )
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None, (
+ "a cancelled run owes no failure notice"
+ )
+
+
+def test_a_cancel_landing_under_record_run_output_is_not_overwritten(
+ tmp_path: Path,
+) -> None:
+ """The backend output writer must re-decide a failed turn after Stop wins."""
+
+ sqlite, requests = _store(tmp_path)
+ request = requests.enqueue_agent_run(
+ session_key="slack::channel::C6",
+ message="hi",
+ agent_name=None,
+ )
+ assert requests.claim(request.id) is not None
+
+ listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="UPDATE agent_runs")
+ event.listen(sqlite.engine, "before_cursor_execute", listener)
+ try:
+ result = sqlite.record_run_output(
+ request.id,
+ output_id="failed-output",
+ text="backend failed",
+ terminal_status="failed",
+ error="backend failed",
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", listener)
+
+ assert fired, "the interleaved cancel never fired; the race was not exercised"
+ saved = sqlite.get_run(request.id)
+ assert result["terminal_transition"] is True
+ assert saved["status"] == "canceled"
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None
+
+
+def test_a_cancel_landing_under_settle_deferred_run_is_not_overwritten(
+ tmp_path: Path,
+) -> None:
+ """An Activity's deferred failure remains subordinate to a concurrent Stop."""
+
+ sqlite, requests = _store(tmp_path)
+ request = requests.enqueue_agent_run(
+ session_key="slack::channel::C7",
+ message="hi",
+ agent_name=None,
+ )
+ assert requests.claim(request.id) is not None
+ assert sqlite.defer_run_terminal(
+ request.id,
+ terminal_status="failed",
+ error="deferred failure",
+ result_text="backend failed",
+ )
+
+ listener, fired = _cancel_mid_write(sqlite, request.id, fire_on="UPDATE agent_runs")
+ event.listen(sqlite.engine, "before_cursor_execute", listener)
+ try:
+ transitioned = sqlite.settle_deferred_run(request.id)
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", listener)
+
+ assert fired, "the interleaved cancel never fired; the race was not exercised"
+ saved = sqlite.get_run(request.id)
+ assert transitioned is True
+ assert saved["status"] == "canceled"
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None
+ assert "deferred_terminal_status" not in (saved.get("result_payload") or {})
+
+
+def test_the_cancel_cas_does_not_leave_an_uncancelled_run_unsettled(tmp_path: Path) -> None:
+ """Subordinate to HFR-060/061 — the guard must not cost an ordinary settlement.
+
+ The negative control for the two races above. A ``cancel_requested`` predicate is
+ the kind of guard that quietly refuses writes nobody raced — the failure mode
+ ``owed_notice_state_unchanged`` calls out — and here that would mean a failed turn
+ never settling and never owing its notice, which is a D1 loss dressed as a safety
+ fix. So: no interleaved cancel, and both writers must settle ``failed`` and stamp
+ the notice exactly as before.
+ """
+
+ sqlite, requests = _store(tmp_path)
+
+ coalesced = requests.enqueue_agent_run(
+ session_key="slack::channel::C3", message="hi", agent_name=None
+ )
+ claimed = requests.claim(coalesced.id)
+ assert claimed is not None
+ requests.complete_coalesced(claimed, [coalesced.id], ok=False, error="turn died")
+ saved = sqlite.get_run(coalesced.id)
+ assert saved["status"] == "failed"
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is not None
+
+ settled = requests.enqueue_agent_run(
+ session_key="slack::channel::C4", message="hi", agent_name=None
+ )
+ assert requests.claim(settled.id) is not None
+ assert sqlite.settle_run_terminal(settled.id, terminal_status="failed", error="boom") == "failed"
+ saved = sqlite.get_run(settled.id)
+ assert saved["status"] == "failed"
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is not None
+
+ # ...and a cancel the writer's OWN snapshot saw still normalizes to ``canceled``
+ # through the fall-through branch, which the CAS must not have closed.
+ requested = requests.enqueue_agent_run(
+ session_key="slack::channel::C5", message="hi", agent_name=None
+ )
+ claimed = requests.claim(requested.id)
+ assert claimed is not None
+ sqlite.cancel_run(requested.id)
+ requests.complete_coalesced(claimed, [requested.id], ok=False, error="turn died")
+ saved = sqlite.get_run(requested.id)
+ assert saved["status"] == "canceled"
+ assert (saved.get("metadata") or {}).get(OWED_FAILURE_NOTICE_KEY) is None
+
+
+# --- group 2: the owed-notice drain ---------------------------------------
+#
+# The policy decisions are tested against ``core.failure_notices.decide`` directly:
+# it is a pure function of (notice, streak facts, earlier-unsettled), so every branch
+# is reachable without a controller, an event loop or an IM transport. The delivery
+# protocol (receipt/ack/backoff/dead-letter) is tested against the store, since
+# what has to survive a crash is the row, not the call.
+
+
+def _notice(state: str = "pending", **fields) -> dict:
+ payload = {"state": state, "attempts": 0, "next_attempt_at": None}
+ payload.update(fields)
+ return payload
+
+
+def _streak_row(run_id: str, status: str = "failed", notice: dict | None = None) -> dict:
+ return {"id": run_id, "created_at": f"2026-07-27T00:00:{run_id[-2:]}", "status": status, "notice": notice}
+
+
+def _facts(streak: list[dict], run_id: str) -> dict:
+ """``failure_streak_decision``'s three facts, derived from a streak's ROWS.
+
+ This is byte-for-byte the derivation ``decide`` used to perform inline on the
+ streak it was handed, and it stays in the test module for two jobs:
+
+ * these policy scenarios keep reading as streaks — "a sent row and a pending row"
+ is what the policy is about, and stating it as ``has_sent_elsewhere=True``
+ instead would assert the answer as the question;
+ * it is the ORACLE. ``test_the_sql_streak_facts_match_the_materialized_streak``
+ composes it with ``_materialized_streak`` to check the SQL facts, and
+ ``test_the_facts_decide_exactly_what_the_streak_rows_decided`` uses it to check
+ that moving the derivation into SQL did not move any outcome.
+ """
+
+ others = [row for row in streak if row["id"] != run_id]
+ return {
+ "in_streak": any(row["id"] == run_id for row in streak),
+ "has_sent_elsewhere": any(
+ (row.get("notice") or {}).get("state") == "sent" for row in others
+ ),
+ "earliest_pending_id": next(
+ (row["id"] for row in streak if (row.get("notice") or {}).get("state") == "pending"),
+ None,
+ ),
+ }
+
+
+def test_second_failure_in_streak_is_skipped_not_notified() -> None:
+ """HFR-073 — "notify on the 1st failure (once, not daily)".
+
+ Each execution of a recurring definition is a new run, so without a scope every
+ consecutive failure is a distinct unacknowledged notice and the drain notifies on
+ every fire — the daily spam the policy forbids.
+ """
+
+ from core.failure_notices import ACTION_SKIP, decide
+
+ first = _streak_row("run-01", notice=_notice("sent", ack_evidence="receipt"))
+ second = _streak_row("run-02", notice=_notice("pending"))
+
+ decision = decide(
+ run_id="run-02",
+ definition_id="task-1",
+ notice=second["notice"],
+ streak_facts=_facts([first, second], "run-02"),
+ earlier_unsettled=None,
+ )
+
+ assert decision.action == ACTION_SKIP
+
+
+def test_second_failure_defers_while_first_notice_is_still_pending() -> None:
+ """HFR-074 — absence of an acknowledgement is not evidence nothing is in flight.
+
+ Suppressing only once an earlier notice is ACKNOWLEDGED leaves the window that
+ matters open: if the streak's first notice fails its transport attempt and a
+ second execution fails before the retry lands, nothing is acknowledged, so the
+ second row would pass the predicate and notify — while the first is still
+ ``pending`` BY DESIGN because it is deliberately still retrying. One streak,
+ two notices, produced by the interaction of two fixes rather than either alone.
+ """
+
+ from core.failure_notices import ACTION_DEFER, decide
+
+ first = _streak_row("run-01", notice=_notice("pending", attempts=2, error="send: nope"))
+ second = _streak_row("run-02", notice=_notice("pending"))
+
+ decision = decide(
+ run_id="run-02",
+ definition_id="task-1",
+ notice=second["notice"],
+ streak_facts=_facts([first, second], "run-02"),
+ earlier_unsettled=None,
+ )
+
+ assert decision.action == ACTION_DEFER
+ assert "run-01" in decision.reason
+
+
+def test_dead_lettered_canonical_notice_promotes_the_next_pending_row() -> None:
+ """HFR-065 — a streak's claim on delivery outlives any single row.
+
+ A streak whose canonical notice exhausted its retries still owes the user the
+ news that the task is broken, so the earliest remaining ``pending`` row is
+ promoted rather than deferring behind a dead letter forever.
+ """
+
+ from core.failure_notices import ACTION_DELIVER, decide
+
+ first = _streak_row("run-01", notice=_notice("failed", attempts=5, error="send: nope"))
+ second = _streak_row("run-02", notice=_notice("pending"))
+
+ decision = decide(
+ run_id="run-02",
+ definition_id="task-1",
+ notice=second["notice"],
+ streak_facts=_facts([first, second], "run-02"),
+ earlier_unsettled=None,
+ )
+
+ assert decision.action == ACTION_DELIVER
+
+
+def test_failure_after_a_success_notifies_again() -> None:
+ """A ``succeeded`` verdict closes the streak, so recovery re-arms notification."""
+
+ from core.failure_notices import ACTION_DELIVER, decide
+
+ # ``failure_streak_decision`` answers only about the streak CONTAINING this run,
+ # so a success before it is already excluded — the streak here is this row alone.
+ row = _streak_row("run-03", notice=_notice("pending"))
+
+ decision = decide(
+ run_id="run-03",
+ definition_id="task-1",
+ notice=row["notice"],
+ streak_facts=_facts([row], "run-03"),
+ earlier_unsettled=None,
+ )
+
+ assert decision.action == ACTION_DELIVER
+
+
+def test_run_without_definition_id_is_never_suppressed() -> None:
+ """``definition_id`` is nullable; an ad-hoc run has no streak to be absorbed into."""
+
+ from core.failure_notices import ACTION_DELIVER, decide
+
+ decision = decide(
+ run_id="run-adhoc",
+ definition_id=None,
+ notice=_notice("pending"),
+ streak_facts=None,
+ earlier_unsettled=None,
+ )
+
+ assert decision.action == ACTION_DELIVER
+
+
+def test_classification_defers_while_an_earlier_run_is_still_running() -> None:
+ """The streak is only computable over a settled prefix.
+
+ ``create_per_run`` holds no execution lock, so executions overlap and completion
+ order need not follow ``created_at``. A later-created run that fails first would
+ become canonical and send; the earlier one then fails, becomes the new earliest,
+ and the streak emits a second notice for the same outage.
+ """
+
+ from core.failure_notices import ACTION_DEFER, decide
+
+ decision = decide(
+ run_id="run-02",
+ definition_id="task-1",
+ notice=_notice("pending"),
+ streak_facts=None,
+ earlier_unsettled={"id": "run-01", "created_at": "2026-07-27T00:00:00+00:00", "status": "running"},
+ )
+
+ assert decision.action == ACTION_DEFER
+ assert "run-01" in decision.reason
+
+
+def test_one_restart_interrupting_overlapping_runs_notifies_for_every_run() -> None:
+ """An interruption notice is per-run, always, with no suppression scope.
+
+ A single restart interrupts EVERY in-flight execution of a definition at once,
+ and ``create_per_run`` means there can be several. Giving interruptions a
+ streak-shaped scope (consecutive interruptions of D sharing one
+ ``interrupt_reason``) would derive one notice from one arbitrary run and skip the
+ rest — and each skipped run is a distinct turn with its own session, prompt and
+ rerun path whose user is told nothing.
+
+ Asserts the COUNT equals the number of interrupted runs, not merely that a
+ notice was sent — which is the assertion the broken version would have passed.
+ """
+
+ from core.failure_notices import ACTION_DELIVER, decide
+
+ interrupted = ["run-01", "run-02", "run-03"]
+ streak = [_streak_row(rid, notice=_notice("pending", interrupt_reason="restarted")) for rid in interrupted]
+
+ delivered = [
+ run_id
+ for run_id in interrupted
+ if decide(
+ run_id=run_id,
+ definition_id="task-1",
+ notice=_notice("pending", interrupt_reason="restarted"),
+ streak_facts=_facts(streak, run_id),
+ earlier_unsettled=None,
+ ).action
+ == ACTION_DELIVER
+ ]
+
+ assert delivered == interrupted
+
+
+def test_an_ordinary_result_less_failure_is_not_treated_as_an_interruption() -> None:
+ """The lane split is membership, not ``interrupt_reason`` presence.
+
+ ``no_terminal_result`` is stamped on the commonest harness failure of all. Read
+ as an interruption it would get an unsuppressed notice on every fire, which is
+ the daily spam the streak exists to prevent — the mirror image of the health bug
+ the same wrong predicate causes.
+ """
+
+ from core.failure_notices import ACTION_SKIP, decide, is_interruption
+
+ assert is_interruption({"interrupt_reason": "restarted"}) is True
+ assert is_interruption({"interrupt_reason": "no_terminal_result"}) is False
+
+ first = _streak_row("run-01", notice=_notice("sent", ack_evidence="receipt"))
+ second = _streak_row("run-02", notice=_notice("pending", interrupt_reason="no_terminal_result"))
+
+ decision = decide(
+ run_id="run-02",
+ definition_id="task-1",
+ notice=second["notice"],
+ streak_facts=_facts([first, second], "run-02"),
+ earlier_unsettled=None,
+ )
+
+ assert decision.action == ACTION_SKIP
+
+
+def test_watch_runtime_heartbeat_does_not_close_a_failure_streak(tmp_path: Path) -> None:
+ """The heartbeat shares the watch's ``definition_id`` and goes ``succeeded``.
+
+ ``write_watch_runtime`` flips every prior heartbeat to ``succeeded`` on each
+ write, so an unfiltered streak query finds a success between any two watch
+ failures. Every watch failure would then read as a first failure and notify —
+ trading the permanent silence of the deferral bug for exactly the daily spam
+ this sub-step exists to prevent.
+
+ Asserted through the CONSEQUENCE rather than through a list of ids: the first
+ failure carries a ``sent`` notice, so if the heartbeat splits the streak the
+ second failure no longer sees it, ``has_sent_elsewhere`` goes false and the drain
+ notifies again. That is the spam, stated as the thing that produces it.
+ """
+
+ from core.failure_notices import ACTION_SKIP, decide
+
+ sqlite, _ = _store(tmp_path)
+ _watch(sqlite, "watch-streak")
+ for index in (1, 2):
+ sqlite.enqueue_run(
+ {
+ "id": f"run-w{index}",
+ "request_type": "watch",
+ "status": "failed",
+ "definition_id": "watch-streak",
+ "error": "hook blew up",
+ "created_at": f"2026-07-27T0{index}:00:00+00:00",
+ "completed_at": f"2026-07-27T0{index}:01:00+00:00",
+ # The first failure already told the user; the second is the one whose
+ # fate the heartbeat must not change.
+ "metadata": {
+ OWED_FAILURE_NOTICE_KEY: {
+ "state": "sent" if index == 1 else "pending",
+ "attempts": 1,
+ }
+ },
+ }
+ )
+ # A heartbeat write lands between the two failures, flipping the previous
+ # runtime row to ``succeeded``.
+ sqlite.write_watch_runtime(
+ {"watches": {"watch-streak": {"running": True, "started_at": f"2026-07-27T0{index}:30:00+00:00"}}},
+ updated_at=f"2026-07-27T0{index}:30:00+00:00",
+ )
+
+ facts = sqlite.failure_streak_decision("watch-streak", "run-w2")
+
+ assert facts["in_streak"] is True
+ assert facts["has_sent_elsewhere"] is True, (
+ "the heartbeat must not split the streak; the earlier failure's sent notice "
+ f"has to stay visible to run-w2, got {facts}"
+ )
+ assert (
+ decide(
+ run_id="run-w2",
+ definition_id="watch-streak",
+ notice=_notice("pending"),
+ streak_facts=facts,
+ earlier_unsettled=None,
+ ).action
+ == ACTION_SKIP
+ )
+
+
+def test_watch_runtime_heartbeat_does_not_defer_a_failed_watch_run(tmp_path: Path) -> None:
+ """The heartbeat is earlier-created and permanently nonterminal.
+
+ Unfiltered, every failed watch run defers behind its own supervisor forever and
+ a long-running watch never delivers a failure notice — P6 for watches,
+ reintroduced by the mechanism written to guarantee notification.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _watch(sqlite, "watch-defer")
+ sqlite.write_watch_runtime(
+ {"watches": {"watch-defer": {"running": True, "started_at": "2026-07-27T00:00:00+00:00"}}},
+ updated_at="2026-07-27T00:00:00+00:00",
+ )
+ sqlite.enqueue_run(
+ {
+ "id": "run-wd",
+ "request_type": "watch",
+ "status": "failed",
+ "definition_id": "watch-defer",
+ "error": "hook blew up",
+ "created_at": "2026-07-27T02:00:00+00:00",
+ "completed_at": "2026-07-27T02:01:00+00:00",
+ }
+ )
+ # The heartbeat row is still ``running`` and was created two hours earlier.
+ assert sqlite.get_run("runtime:watch-defer")["status"] == "running"
+
+ blocker = sqlite.earliest_unsettled_run_before(
+ "watch-defer",
+ created_at="2026-07-27T02:00:00+00:00",
+ run_id="run-wd",
+ now="2026-07-27T02:05:00+00:00",
+ )
+
+ assert blocker is None, "the supervisor heartbeat is not an execution to wait for"
+
+
+def test_out_of_order_completion_does_not_resend_for_one_streak(tmp_path: Path) -> None:
+ """An earlier-created run that has not settled blocks classification."""
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-overlap", session_policy="create_per_run")
+ sqlite.enqueue_run(
+ {
+ "id": "run-early",
+ "request_type": "scheduled",
+ "status": "running",
+ "definition_id": "task-overlap",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ }
+ )
+ sqlite.enqueue_run(
+ {
+ "id": "run-late",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-overlap",
+ "error": "boom",
+ "created_at": "2026-07-27T02:00:00+00:00",
+ "completed_at": "2026-07-27T02:01:00+00:00",
+ }
+ )
+
+ blocker = sqlite.earliest_unsettled_run_before(
+ "task-overlap",
+ created_at="2026-07-27T02:00:00+00:00",
+ run_id="run-late",
+ now="2026-07-27T02:05:00+00:00",
+ )
+
+ assert blocker is not None and blocker["id"] == "run-early"
+
+
+def test_a_stale_nonterminal_predecessor_stops_blocking_the_notice(tmp_path: Path) -> None:
+ """The deferral is bounded, which the plan's own argument leaves open.
+
+ The plan justifies an unbounded wait with "settling every nonterminal run is
+ precisely what PR1/PR2/PR7 guarantee". PR2/PR4/PR7 are NOT landed, so on the
+ current tree a queued row for a paused definition sits nonterminal indefinitely
+ and the notice would never be delivered — a deferral without a bound, which this
+ plan itself calls a deletion. Past the cap the predecessor is treated as
+ settled, risking a duplicate notice rather than a lost one, which is the
+ direction the plan chooses explicitly.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-stale-pred", session_policy="create_per_run")
+ sqlite.enqueue_run(
+ {
+ "id": "run-wedged",
+ "request_type": "scheduled",
+ "status": "running",
+ "definition_id": "task-stale-pred",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ }
+ )
+
+ blocker = sqlite.earliest_unsettled_run_before(
+ "task-stale-pred",
+ created_at="2026-07-27T02:00:00+00:00",
+ run_id="run-late",
+ stale_after_seconds=3600.0,
+ now="2026-07-29T00:00:00+00:00",
+ )
+
+ assert blocker is None
+
+
+def _python_earliest_unsettled_before(
+ sqlite_store: SQLiteBackgroundTaskStore,
+ definition_id: str,
+ *,
+ created_at: str,
+ run_id: str,
+ stale_after_seconds: float | None,
+ now: str,
+) -> dict | None:
+ """The pre-SQL predecessor read, computed by filtering in Python.
+
+ Byte-for-byte the production algorithm as of ``3578f2b6`` — the whole
+ queued/running population for the definition ordered by ``(created_at, id)``,
+ then a Python loop that ``continue``s past rows at or after the anchor position
+ and past rows older than the staleness cap. It is the specification the SQL has
+ to reproduce, including its edge cases.
+ """
+
+ from datetime import datetime, timezone
+
+ from sqlalchemy import or_ as sa_or, select as sa_select
+
+ from storage.background import (
+ _WATCH_RUNTIME_RUN_TYPE,
+ _parse_iso_instant,
+ _status_query_values,
+ )
+ from storage.models import agent_runs
+
+ instant = _parse_iso_instant(now) or datetime.now(timezone.utc)
+ stmt = (
+ sa_select(agent_runs.c.id, agent_runs.c.created_at, agent_runs.c.status)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(
+ sa_or(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued") + _status_query_values("running")
+ )
+ )
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ )
+ with sqlite_store.engine.connect() as conn:
+ for row in conn.execute(stmt).mappings():
+ if (str(row["created_at"]), str(row["id"])) >= (str(created_at), str(run_id)):
+ continue
+ if stale_after_seconds is not None:
+ started = _parse_iso_instant(row["created_at"])
+ if started is not None and (instant - started).total_seconds() > stale_after_seconds:
+ continue
+ return {"id": row["id"], "created_at": row["created_at"], "status": row["status"]}
+ return None
+
+
+def test_the_predecessor_read_is_bounded_and_seeks_rather_than_scans(tmp_path: Path) -> None:
+ """Subordinate to HFR-078 — the predecessor read runs on the same 2 s tick.
+
+ ``earliest_unsettled_run_before`` is asked once per pending owed notice, exactly
+ like the eligibility lookup HFR-078 bounded and the streak read HFR-095 bounded —
+ and it was the last read in that path that was not. It selected EVERY
+ queued/running row for the definition and then decided in Python which ones were
+ before the anchor and which had gone stale, so a definition holding a large
+ nonterminal backlog paid the whole backlog per notice per tick to answer a
+ question whose answer is at most one row.
+
+ Asserted on two things, because either alone is satisfiable by an unbounded read:
+ the CONSTRAINED TERMS of the plan (naming an index proves nothing — HFR-086 is
+ that lesson) and the SIZE of the result set the statement hands back, which is
+ the work the tick actually pays.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-pred-plan", session_policy="create_per_run")
+ backlog = 1200
+ for index in range(backlog):
+ sqlite.enqueue_run(
+ {
+ "id": f"run-backlog-{index:05d}",
+ "request_type": "scheduled",
+ "status": "queued" if index % 2 else "running",
+ "definition_id": "task-pred-plan",
+ # Well before the staleness cap, so every one of them is treated as
+ # settled and the honest answer is ``None`` on both sides.
+ "created_at": f"2026-07-01T{index // 3600:02d}:{(index // 60) % 60:02d}:{index % 60:02d}+00:00",
+ }
+ )
+
+ anchor_created = "2026-07-29T00:00:00+00:00"
+ now = "2026-07-29T00:05:00+00:00"
+
+ def _read():
+ return sqlite.earliest_unsettled_run_before(
+ "task-pred-plan",
+ created_at=anchor_created,
+ run_id="run-anchor",
+ stale_after_seconds=3600.0,
+ now=now,
+ )
+
+ assert _read() is None, "every predecessor is past the staleness cap"
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ sizes = _agent_run_query_result_sizes(sqlite, db_path, _read)
+ assert sizes, "the predecessor read issued no agent_runs query"
+ assert max(sizes) <= 1, (
+ f"the predecessor read handed Python {max(sizes)} rows out of a {backlog}-row "
+ "nonterminal backlog to answer a question whose answer is at most one row"
+ )
+
+ plans = _agent_run_query_plans(sqlite, db_path, _read)
+ rendered = "\n".join(line for _statement, plan in plans for line in plan)
+ compact = rendered.replace(" ", "")
+ assert "SCAN" not in rendered, (
+ f"the predecessor read must never scan a definition's backlog; plans were:\n{rendered}"
+ )
+ assert "TEMPB-TREE" not in compact, (
+ f"the (created_at, id) order must come from an index, not a sort; plans were:\n{rendered}"
+ )
+ assert "(created_at,id)<(?,?)" in compact, (
+ "the anchor position must bound the seek in SQL, not in a Python ``continue``; "
+ f"plans were:\n{rendered}"
+ )
+
+ # ...and a predecessor inside the cap is still found, so the bound above is not a
+ # read that answers ``None`` to everything.
+ sqlite.enqueue_run(
+ {
+ "id": "run-fresh",
+ "request_type": "scheduled",
+ "status": "running",
+ "definition_id": "task-pred-plan",
+ "created_at": "2026-07-28T23:59:00+00:00",
+ }
+ )
+ blocker = _read()
+ assert blocker is not None and blocker["id"] == "run-fresh"
+
+
+def test_the_predecessor_read_breaks_created_at_ties_by_id_and_stays_bounded_on_no_match(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-078 — the two cases the randomised parity fixture only samples.
+
+ The parity test above reaches ties and empty answers through a seeded RNG, which
+ makes them reproducible but not NAMED: nothing in it fails if the tie-break or the
+ empty case regresses for a reason the fixture's row pool happens to stop
+ generating. Both are pinned here as fixed, hand-built histories.
+
+ TIES, because ``created_at`` is not a position. Several writers stamp a whole
+ batch with ONE value, so "the earliest unsettled predecessor" is only well defined
+ with ``id`` inside the comparison. Two things follow and both are asserted: among
+ predecessors sharing an instant the SMALLEST id wins, and a row sharing the
+ ANCHOR's instant is a predecessor only when its id sorts below the anchor's — a
+ scalar ``created_at <`` would drop the whole tied group (losing a real blocker,
+ the duplicate-notice direction) and a scalar ``<=`` would admit the anchor itself
+ and defer every notice behind its own run forever.
+
+ THE NO-MATCH EDGE, because ``None`` is the answer the drain acts on: it is what
+ releases the notice to send. It has to stay bounded too — an unbounded read that
+ materialises the backlog and then finds nothing pays the same cost per tick as one
+ that finds something, and ``None`` is the common case on a healthy definition.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-pred-tie", session_policy="create_per_run")
+
+ # Well inside the staleness cap, so the cap plays no part in either case: this
+ # test is about position, and a tied group that answered ``None`` because it had
+ # aged out would pass the tie assertions for the wrong reason.
+ tied = "2026-07-28T12:59:00+00:00"
+ anchor_created = "2026-07-28T13:00:00+00:00"
+ now = "2026-07-28T13:00:30+00:00"
+
+ def _enqueue(run_id: str, status: str, created_at: str) -> None:
+ sqlite.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": status,
+ "definition_id": "task-pred-tie",
+ "created_at": created_at,
+ }
+ )
+
+ def _read(created_at: str, run_id: str):
+ return sqlite.earliest_unsettled_run_before(
+ "task-pred-tie",
+ created_at=created_at,
+ run_id=run_id,
+ stale_after_seconds=3600.0,
+ now=now,
+ )
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+
+ # THE NO-MATCH EDGE FIRST, while the only nonterminal rows sit at or after the
+ # anchor position: there is no predecessor, and finding that out must still cost
+ # at most one row.
+ _enqueue("run-later", "queued", "2026-07-28T14:00:00+00:00")
+ _enqueue("run-anchor", "running", anchor_created)
+ assert _read(anchor_created, "run-anchor") is None
+ sizes = _agent_run_query_result_sizes(sqlite, db_path, lambda: _read(anchor_created, "run-anchor"))
+ assert sizes and max(sizes) <= 1, (
+ f"the no-match answer must be bounded too; the read handed Python {sizes} rows"
+ )
+
+ # TIES AMONG PREDECESSORS: three rows on one instant, inserted so that neither
+ # insertion order nor rowid order matches id order.
+ for run_id in ("run-tie-c", "run-tie-a", "run-tie-b"):
+ _enqueue(run_id, "queued", tied)
+ blocker = _read(anchor_created, "run-anchor")
+ assert blocker is not None and blocker["id"] == "run-tie-a", (
+ f"the smallest id in a tied group is the earliest predecessor; got {blocker}"
+ )
+
+ # A TIE WITH THE ANCHOR ITSELF: asked from an anchor on the tied instant, the
+ # answer is the tied row whose id sorts BELOW it, and never the anchor.
+ blocker = _read(tied, "run-tie-b")
+ assert blocker is not None and blocker["id"] == "run-tie-a", (
+ f"a row tied with the anchor is a predecessor when its id sorts below; got {blocker}"
+ )
+ # ...and from the lowest id in the group there is no predecessor at all — the
+ # anchor must not find itself.
+ assert _read(tied, "run-tie-a") is None, "the anchor must never be its own blocker"
+
+
+def test_the_sql_predecessor_read_matches_the_python_filtered_one(tmp_path: Path) -> None:
+ """Subordinate to HFR-078 — the bounded read has to be the SAME predecessor.
+
+ Parity against ``_python_earliest_unsettled_before``, the algorithm this
+ replaces, over randomised WELL-FORMED histories containing every row class that
+ decides the answer: queued and running rows on both sides of the anchor
+ position, terminal rows that are not predecessors at all, ``watch_runtime``
+ heartbeats (excluded, or every failed watch run would defer behind its own
+ supervisor forever), rows sharing one ``created_at`` so the ``id`` tie-break
+ decides which is earliest, and rows straddling the staleness cap. Asked with and
+ without the cap, and from several anchors per history.
+
+ WELL-FORMED is the caveat, and it is the one documented divergence. Python read
+ an UNPARSEABLE ``created_at`` as fresh — ``_parse_iso_instant`` returned ``None``
+ and the staleness test was skipped — while the SQL cutoff is a lexicographic
+ string comparison that may class the same value as stale. That direction risks a
+ duplicated notice rather than a lost one, which is the direction the 1 h cap
+ itself already chose; it is asserted explicitly below rather than left to a
+ fixture that never produces such a row.
+ """
+
+ import random
+
+ sqlite, _ = _store(tmp_path)
+ for seed in range(6):
+ rng = random.Random(seed)
+ definition_id = f"task-pred-parity-{seed}"
+ _task(sqlite, definition_id, session_policy="create_per_run")
+ ids: list[str] = []
+ for index in range(30):
+ run_id = f"run-{seed}-{index:03d}"
+ ids.append(run_id)
+ # A small pool of instants, some inside the cap and some well outside it,
+ # with ties so the ``id`` tie-break decides the sequence.
+ day = rng.choice([27, 27, 28, 29, 29])
+ instant = f"2026-07-{day:02d}T{rng.randrange(4):02d}:00:00+00:00"
+ status = rng.choice(["queued", "running", "running", "failed", "succeeded", "canceled"])
+ request_type = "watch_runtime" if rng.random() < 0.15 else "scheduled"
+ sqlite.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": request_type,
+ "status": status,
+ "definition_id": definition_id,
+ "created_at": instant,
+ "completed_at": instant if status in {"failed", "succeeded", "canceled"} else None,
+ }
+ )
+
+ now = "2026-07-29T04:00:00+00:00"
+ anchors = [
+ ("2026-07-29T03:00:00+00:00", "run-anchor"),
+ ("2026-07-27T00:00:00+00:00", "run-anchor"),
+ ("2026-07-28T02:00:00+00:00", f"run-{seed}-015"),
+ *[
+ (f"2026-07-{rng.choice([27, 28, 29]):02d}T{rng.randrange(4):02d}:00:00+00:00", rng.choice(ids))
+ for _ in range(6)
+ ],
+ ]
+ for created_at, run_id in anchors:
+ for cap in (None, 3600.0, 86400.0, 0.0):
+ expected = _python_earliest_unsettled_before(
+ sqlite,
+ definition_id,
+ created_at=created_at,
+ run_id=run_id,
+ stale_after_seconds=cap,
+ now=now,
+ )
+ actual = sqlite.earliest_unsettled_run_before(
+ definition_id,
+ created_at=created_at,
+ run_id=run_id,
+ stale_after_seconds=cap,
+ now=now,
+ )
+ assert actual == expected, (
+ f"seed {seed}, anchor ({created_at}, {run_id}), cap {cap}: the SQL "
+ f"predecessor disagrees with the Python-filtered one\n"
+ f" expected {expected}\n actual {actual}"
+ )
+
+
+def test_an_unparseable_created_at_reads_as_stale_rather_than_as_a_blocker(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-078 — the one divergence the SQL cutoff introduces.
+
+ The Python filter asked ``_parse_iso_instant`` and skipped the staleness test
+ when it answered ``None``, so a row whose ``created_at`` cannot be parsed BLOCKED
+ the notice for as long as it stayed nonterminal — which, for an unparseable
+ timestamp, is a wait nothing can bound. A lexicographic cutoff classes the same
+ row as stale and treats it as settled.
+
+ That is the duplicate-not-lost direction the cap already chose ("a duplicated
+ notice is a papercut, a lost one is the D1 violation"), so it is pinned here as
+ the intended behaviour rather than tolerated as an accident.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-pred-garbage", session_policy="create_per_run")
+ sqlite.enqueue_run(
+ {
+ "id": "run-garbage",
+ "request_type": "scheduled",
+ "status": "running",
+ "definition_id": "task-pred-garbage",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ }
+ )
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == "run-garbage")
+ .values(created_at="0000-13-45T99:99:99+00:00")
+ )
+
+ blocker = sqlite.earliest_unsettled_run_before(
+ "task-pred-garbage",
+ created_at="2026-07-29T00:00:00+00:00",
+ run_id="run-late",
+ stale_after_seconds=3600.0,
+ now="2026-07-29T00:05:00+00:00",
+ )
+
+ assert blocker is None, (
+ "a row whose created_at cannot be read must not block a notice forever"
+ )
+ # Without a cap there is no cutoff to compare against, so the row is still a
+ # predecessor: the divergence is confined to the staleness test, and the anchor
+ # position comparison — a string comparison on both sides all along — is
+ # unchanged.
+ assert (
+ sqlite.earliest_unsettled_run_before(
+ "task-pred-garbage",
+ created_at="2026-07-29T00:00:00+00:00",
+ run_id="run-late",
+ now="2026-07-29T00:05:00+00:00",
+ )
+ or {}
+ ).get("id") == "run-garbage"
+
+
+# --- group 2b: the delivery protocol --------------------------------------
+
+
+def test_every_terminal_failure_transition_stamps_an_owed_notice(tmp_path: Path) -> None:
+ """All five terminal writers, including the unguarded-until-now pair.
+
+ The stamp is keyed on the PROPERTY "this UPDATE sets status to a terminal
+ failure", not on a list of call sites, so a settlement path added later inherits
+ it. Guardedness is deliberately not part of the test: the commonest failure of
+ all terminalizes through the claimed-request completion.
+ """
+
+ sqlite, requests = _store(tmp_path)
+
+ # 1. record_run_output
+ first = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="a")
+ requests.claim(first.id)
+ sqlite.record_run_output(first.id, output_id="o1", text="bad", terminal_status="failed")
+
+ # 2. settle_run_terminal, via the claimed-request completion
+ second = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="b")
+ claimed = requests.claim(second.id)
+ requests.complete(claimed, ok=False, error="boom")
+
+ # 3. settle_deferred_run
+ third = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="c")
+ requests.claim(third.id)
+ sqlite.defer_run_terminal(third.id, terminal_status="failed", error="deferred boom")
+ sqlite.settle_deferred_run(third.id)
+
+ # 4. the coalesced completer
+ fourth = requests.enqueue_agent_run(session_key="slack::channel::C1", message="d", agent_name=None)
+ claimed_fourth = requests.claim(fourth.id)
+ requests.complete_coalesced(claimed_fourth, [fourth.id], ok=False, error="coalesced boom")
+
+ for run_id in (first.id, second.id, third.id, fourth.id):
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice is not None, f"{run_id} owes no notice"
+ assert notice["state"] == "pending"
+ # The bare run id, which is exactly what the LIVE path's ``_failure_identity``
+ # resolves to. Asserted as the identity rather than as a format so a future
+ # spelling change has to keep the dedup working rather than just keep a shape.
+ assert notice["failure_id"] == run_id
+
+
+def _raw_metadata_json(sqlite: SQLiteBackgroundTaskStore, run_id: str) -> Any:
+ """The ``metadata_json`` COLUMN, undecoded — what a clobber would rewrite."""
+
+ from storage.models import agent_runs
+
+ with sqlite.engine.connect() as conn:
+ return conn.execute(
+ select(agent_runs.c.metadata_json).where(agent_runs.c.id == run_id)
+ ).scalar_one()
+
+
+def _write_raw_metadata_json(sqlite: SQLiteBackgroundTaskStore, run_id: str, blob: str) -> None:
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs).where(agent_runs.c.id == run_id).values(metadata_json=blob)
+ )
+ assert _raw_metadata_json(sqlite, run_id) == blob, "the fixture blob must survive the write"
+
+
+def test_a_terminal_writer_never_rewrites_unparseable_metadata(tmp_path: Path) -> None:
+ """Subordinate to HFR-084/HFR-072 — malformed metadata is READ-ONLY to the stamp.
+
+ ``_merge_owed_failure_notice`` decoded the column with ``_json_loads(..., {})``
+ and then fell back to ``{}`` for anything that was not a dict, so settling a row
+ whose ``metadata_json`` is unparseable — or valid JSON that is not an object —
+ REPLACED the raw column with ``{"owed_failure_notice": …}``. Whatever the blob
+ held (a truncated write, a value another component owns, the bytes an operator
+ would need to diagnose it) was destroyed by the notification feature, on all four
+ terminal writers.
+
+ Inconsistent with all three accepted precedents on this head, which is what makes
+ it a defect rather than a policy: the binding stamp refuses a malformed row
+ through ``json_valid`` (HFR-084), ``update_owed_failure_notice`` returns ``None``
+ when the metadata is not a dict, and ``list_owed_failure_notices`` excludes
+ malformed rows outright — "a row whose metadata will not parse cannot hold a
+ readable notice anyway".
+
+ So the choke point refuses the METADATA write while the terminal transition still
+ commits: the run settles ``failed`` with its ``error`` recorded and the column is
+ byte-identical. The residual is stated rather than hidden — a malformed row
+ settles failed but never owes a notice, which was already true at the read side.
+ """
+
+ blobs = ("{broken", "[1]", '"5"', "not json at all")
+ for blob in blobs:
+ for writer in ("record_run_output", "settle_run_terminal", "settle_deferred_run", "coalesced"):
+ # ``[1]`` and ``"5"`` — valid JSON that is not an object — are only
+ # exercised on one writer; the truncated blob is exercised on all four.
+ if blob != "{broken" and writer != "record_run_output":
+ continue
+ sqlite, requests = _store(tmp_path / f"{writer}-{blobs.index(blob)}")
+ if writer == "coalesced":
+ run = requests.enqueue_agent_run(
+ session_key="slack::channel::C1", message="d", agent_name=None
+ )
+ else:
+ run = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="a")
+ claimed = requests.claim(run.id)
+ if writer == "settle_deferred_run":
+ sqlite.defer_run_terminal(run.id, terminal_status="failed", error="boom")
+
+ _write_raw_metadata_json(sqlite, run.id, blob)
+
+ if writer == "record_run_output":
+ sqlite.record_run_output(
+ run.id, output_id="o1", text="bad", terminal_status="failed", error="boom"
+ )
+ elif writer == "settle_run_terminal":
+ # ``extra_metadata`` too: a caller-supplied sibling field must not be
+ # the lever that rewrites the column either.
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="boom",
+ metadata={"interrupt_reason": "evicted"},
+ )
+ elif writer == "settle_deferred_run":
+ sqlite.settle_deferred_run(run.id)
+ else:
+ requests.complete_coalesced(claimed, [run.id], ok=False, error="boom")
+
+ saved = sqlite.get_run(run.id)
+ assert _raw_metadata_json(sqlite, run.id) == blob, (
+ f"{writer} rewrote an unparseable metadata column instead of leaving it "
+ f"alone: {_raw_metadata_json(sqlite, run.id)!r}"
+ )
+ assert saved["status"] == "failed", (
+ f"{writer} must still commit the terminal transition, got {saved['status']!r}"
+ )
+ assert "boom" in str(saved["error"] or ""), (
+ f"{writer} must still record the error, got {saved['error']!r}"
+ )
+ # The stated residual, pinned so it is a decision and not a surprise.
+ assert sqlite.owed_failure_notice(run.id) is None
+ assert sqlite.list_owed_failure_notices() == []
+
+
+def test_a_succeeded_or_canceled_transition_owes_no_notice(tmp_path: Path) -> None:
+ """Only a failure owes a notice.
+
+ ``canceled`` is reserved for explicit user intent, so telling a user their run
+ failed because they stopped it is noise — and a cancellation is the absence of an
+ outcome everywhere else in this feature too.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ ok_run = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="a")
+ claimed = requests.claim(ok_run.id)
+ requests.complete(claimed, ok=True)
+
+ stopped = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="b")
+ requests.claim(stopped.id)
+ sqlite.cancel_run(stopped.id)
+ sqlite.settle_run_terminal(stopped.id, terminal_status="failed", error="stopped")
+
+ assert sqlite.get_run(stopped.id)["status"] == "canceled"
+ assert sqlite.owed_failure_notice(ok_run.id) is None
+ assert sqlite.owed_failure_notice(stopped.id) is None
+
+
+def test_a_later_writer_never_resets_an_in_flight_notice(tmp_path: Path) -> None:
+ """Re-stamping would reset ``attempts`` and resurrect a dead letter."""
+
+ sqlite, requests = _store(tmp_path)
+ run = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="a")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom")
+ sqlite.update_owed_failure_notice(run.id, state="failed", attempts=5, error="send: nope")
+
+ # Another writer touches the same already-terminal row.
+ sqlite.settle_run_terminal(run.id, terminal_status="failed", error="boom again")
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == "failed"
+ assert notice["attempts"] == 5
+
+
+def test_backoff_spaces_attempts_and_terminates_in_a_dead_letter() -> None:
+ """Bounded retry: spaced, then a visible dead letter — not every tick forever.
+
+ There is no attempt counter or backoff anywhere in the scheduler today, so this
+ is new machinery and the bound is the part worth pinning.
+
+ Subordinate to HFR-076 — and the SHAPE is not enough, which is why the value
+ assertions below were added. This test used to check only that the delays rose,
+ were unique, and ran out at ``MAX_ATTEMPTS``. All three held while
+ ``next_attempt`` indexed ``BACKOFF_SECONDS[attempts]`` after incrementing, so a
+ freshly stamped notice's first failure armed 8 s: the declared 2 s interval at
+ index 0 was unreachable, the ladder was one rung shorter than it declared, and
+ ``CLAIM_LEASE_SECONDS``' "must exceed the retry cap" argument was reasoning
+ about an interval the code could not arm. The mapping is therefore pinned by
+ VALUE: the Nth failed attempt arms ``BACKOFF_SECONDS[N - 1]``, and the attempt
+ that finds no interval left dead-letters instead.
+ """
+
+ from core.failure_notices import BACKOFF_SECONDS, MAX_ATTEMPTS, next_attempt
+
+ delays = []
+ notice = {"attempts": 0}
+ while True:
+ attempt, retry_after = next_attempt(notice)
+ notice["attempts"] = attempt
+ if retry_after is None:
+ break
+ delays.append(retry_after)
+ assert attempt < MAX_ATTEMPTS
+
+ assert delays == sorted(delays) and len(set(delays)) == len(delays), "must back off, not fire every tick"
+ assert notice["attempts"] == MAX_ATTEMPTS
+
+ # The full declared sequence, in order, each interval used exactly once —
+ # starting at the first one.
+ assert delays == list(BACKOFF_SECONDS), (
+ f"every declared interval must be armed exactly once, in order: {delays}"
+ )
+ assert delays[0] == 2.0, (
+ f"the first failed attempt must wait the declared first interval, not {delays[0]}"
+ )
+
+ # The exhaustion edge, from both sides: one attempt per declared interval, plus
+ # the one that finds none left. The terminal bound is a consequence of the
+ # sequence's length rather than an independently chosen number.
+ assert MAX_ATTEMPTS == len(BACKOFF_SECONDS) + 1
+ assert next_attempt({"attempts": len(BACKOFF_SECONDS) - 1}) == (
+ len(BACKOFF_SECONDS),
+ BACKOFF_SECONDS[-1],
+ ), "the last declared interval must be reachable, or the cap is decoration"
+ assert next_attempt({"attempts": len(BACKOFF_SECONDS)}) == (MAX_ATTEMPTS, None), (
+ "the attempt after the last interval has nowhere to go and must dead-letter"
+ )
+
+
+def test_the_notice_timing_constants_bound_each_other_as_documented() -> None:
+ """Subordinate to HFR-076 — the ordering the docstrings ARGUE, asserted.
+
+ Three constants have to be ordered for the claim/retry state machine to hold, and
+ each argument currently lives only in prose that nothing checks:
+
+ * ``NOTICE_DELIVERY_TIMEOUT_SECONDS < CLAIM_LEASE_SECONDS`` — a claimant whose
+ delivery is timed out must still hold its own lease when it writes the retry,
+ or its ``expect``-guarded write races a replacement claimant that has already
+ taken the row;
+ * ``CLAIM_LEASE_SECONDS > BACKOFF_SECONDS[-1]`` — a lease may never expire sooner
+ than the backoff a failed attempt would have armed, or expiry-recovery quietly
+ becomes the faster retry path and replaces the backoff it exists to respect;
+ * ``MAX_ATTEMPTS == len(BACKOFF_SECONDS) + 1`` — the terminal bound is one
+ attempt per declared interval plus the attempt that finds none left, so N
+ attempts are separated by exactly N-1 intervals.
+
+ Cheap, and it fails the moment someone retunes one number without the others.
+ """
+
+ from core import failure_notices
+
+ assert failure_notices.NOTICE_DELIVERY_TIMEOUT_SECONDS < failure_notices.CLAIM_LEASE_SECONDS, (
+ "a timed-out claimant must be cancelled while its own lease still holds"
+ )
+ assert failure_notices.CLAIM_LEASE_SECONDS > failure_notices.BACKOFF_SECONDS[-1], (
+ "lease expiry must never undercut the longest backoff it can be racing"
+ )
+ assert failure_notices.MAX_ATTEMPTS == len(failure_notices.BACKOFF_SECONDS) + 1
+
+
+def test_a_notice_whose_backoff_has_not_elapsed_is_not_listed(tmp_path: Path) -> None:
+ """The drain skips a notice still inside its backoff window."""
+
+ sqlite, requests = _store(tmp_path)
+ run = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="a")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom")
+ sqlite.update_owed_failure_notice(
+ run.id,
+ attempts=1,
+ next_attempt_at="2026-07-27T12:00:00+00:00",
+ )
+
+ assert sqlite.list_owed_failure_notices(now="2026-07-27T11:00:00+00:00") == []
+ ready = sqlite.list_owed_failure_notices(now="2026-07-27T13:00:00+00:00")
+ assert [item["id"] for item in ready] == [run.id]
+
+
+def test_a_sent_notice_is_not_listed_again(tmp_path: Path) -> None:
+ """A crash between delivery and the ack must not re-send.
+
+ The ack is the durable half: once the row records evidence of delivery, the next
+ drain pass simply does not see it. Combined with the run-derived ``failure_id``
+ (which dedupes on ``(platform, native_message_id)``), that is at-least-once
+ delivery with a bounded duplicate window — NOT exactly-once, because a crash
+ between ``send_message`` returning and the row being written leaves nothing to
+ deduplicate against.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ run = requests.enqueue_hook_send(session_key="slack::channel::C1", prompt="a")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom")
+ assert [item["id"] for item in sqlite.list_owed_failure_notices()] == [run.id]
+
+ sqlite.update_owed_failure_notice(run.id, state="sent", ack_evidence="receipt")
+
+ assert sqlite.list_owed_failure_notices() == []
+
+
+def test_a_session_less_definition_now_reaches_the_workspace_inbox(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The INVERSION of a pin this branch used to carry, kept so the reversal is legible.
+
+ It read ``test_a_session_less_definition_dead_letters_rather_than_going_silent``,
+ and it asserted ``_failure_notice_targets(run) == []`` for a definition with no
+ session and no provenance, then hand-drove the attempt counter to a ``failed`` dead
+ letter, on the argument that a truly session-less workspace surface was a declared
+ Known-By-Design limitation under #1044's still-open plan contract.
+
+ THE PLAN REFUTED THAT WITH TWO DATED CORRECTIONS (``docs/plans/harness-run-reliability.md``
+ :3170-3174 and :3196-3222). The mechanism it names is a reserved
+ workspace-notifications session created lazily on first need — not a widened
+ session-less writer, which really is unreachable — and it puts that session in
+ PR6's scope explicitly, "because without it rung (5) is as empty as the four above
+ it". A dead letter is visible to somebody who goes looking; D1's subject is the
+ runs nobody is watching.
+
+ So the same setup now DELIVERS, and the half of the old pin that was never wrong is
+ kept: the failure is still visible on the definition itself.
+ """
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _no_background_web_push(monkeypatch)
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-no-session")
+ run = requests.enqueue_task_run("task-no-session")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="unresolvable target", task_id="task-no-session")
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None and notice["state"] == "pending"
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [target.to_key() for target, _ in rungs] == [
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}"
+ ], f"the ladder's last rung must resolve where the four above it cannot: {rungs}"
+
+ asyncio.run(service._drain_failure_notices())
+
+ settled = sqlite.owed_failure_notice(run.id)
+ assert settled["state"] == NOTICE_SENT, (
+ f"a session-less definition must no longer dead-letter: {settled}"
+ )
+ assert settled["attempts"] == 1, "and it must not spend the backoff getting there"
+ assert [row["session_id"] for row in _persisted_messages()] == [
+ WORKSPACE_NOTICE_SESSION_ID
+ ], "the notice has to be durable, not merely attempted"
+ # The half of the old pin that was never wrong: the definition still reports the
+ # failure, so the push and the badge agree rather than substituting for each other.
+ assert sqlite.definition_health("task-no-session")["health"] == "failing"
+
+
+def test_the_drain_delivers_an_ordinary_failure_once_and_acks_it(tmp_path: Path, monkeypatch) -> None:
+ """The whole path, end to end, through the real wiring.
+
+ Every other test in this group isolates one layer. This one runs the tick's
+ actual entry point over a real store so the parts are proven to be connected:
+ an ordinary claimed-request failure stamps a notice, the drain walks D5's
+ ladder to the definition's delivery key, the notice acks on the receipt, and a
+ SECOND pass sends nothing.
+
+ The second pass is the point. It is the crash-between-delivery-and-ack case:
+ whatever happens after the row records evidence of delivery, the next drain
+ simply does not see it.
+ """
+
+ import asyncio
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-e2e", name="daily report", deliver_key="slack::channel::C1")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ run = requests.enqueue_task_run("task-e2e")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-e2e")
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+
+ emitted: list[dict] = []
+
+ async def _fake_emit(controller, context, backend, diagnostic, **kwargs):
+ emitted.append(
+ {
+ "platform": context.platform,
+ "channel_id": context.channel_id,
+ "body": kwargs.get("display_text"),
+ "failure_id": kwargs.get("failure_id"),
+ }
+ )
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.delivered_id = "1717.42"
+ evidence.persisted_row = {"id": "msg-1"}
+ return False
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _fake_emit)
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert len(emitted) == 1
+ # Rung (1): the definition's own delivery key.
+ assert (emitted[0]["platform"], emitted[0]["channel_id"]) == ("slack", "C1")
+ # Run-derived, so two passes cannot mint two identities — and identical to what
+ # the live path would have used, so the drain cannot duplicate a notification the
+ # live path already delivered.
+ assert emitted[0]["failure_id"] == run.id
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == "sent"
+ assert notice["ack_evidence"] == "receipt"
+ assert notice["attempts"] == 1
+
+ emitted.clear()
+ asyncio.run(service._drain_failure_notices())
+ assert emitted == [], "an acknowledged notice must never be delivered twice"
+
+
+def test_the_drain_body_names_what_failed_and_how_to_re_run(tmp_path: Path) -> None:
+ """D5 requires the body to carry its own context.
+
+ A DM is context-free by construction and the workbench rung is attached to no
+ conversation, so "your task failed" delivered somewhere the user cannot trace
+ is not actionable.
+ """
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-body", name="daily report")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._t = lambda key, **kwargs: f"{key}({','.join(f'{k}={v}' for k, v in kwargs.items())})"
+
+ body = service._failure_notice_body(
+ {"id": "run-1", "task_id": "task-body", "error": "backend exploded"},
+ {"failure_id": "failure:run-1", "interrupt_reason": None},
+ )
+
+ assert "name=daily report" in body
+ assert "error=backend exploded" in body
+ assert "id=task-body" in body
+ assert "harness.notice.rerun" in body
+
+
+def test_a_failed_watch_notice_renders_watch_commands(tmp_path: Path) -> None:
+ """HFR-094 — a watch is not a task, and the copy has to know it.
+
+ ``_failure_notice_body`` resolved the definition through
+ ``ScheduledTaskStore.get_task`` ALONE and then appended
+ ``harness.notice.rerun`` — ``vibe task run {id}`` / ``vibe task show {id}`` — for
+ every definition it rendered. A watch definition is not in the task mirror, so a
+ failed watch got both halves wrong: named by its raw id, and handed two commands
+ that cannot address it. ``vibe task show <watch-id>`` reports "not found", and
+ there is no ``vibe task run`` for a definition that is not scheduled at all —
+ the only surface telling a user their watch died pointed at the wrong noun.
+
+ Watches have their own verbs (``vibe watch show`` / ``vibe watch resume``), so
+ this is a copy and read-path defect, not a missing feature.
+
+ Asserted through the REAL translator: the defect is in the rendered command
+ strings a user reads, not in which key was selected.
+ """
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _watch(sqlite, "watch-ci", name="ci waiter", deliver_key="slack::channel::C1")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ assert store.get_task("watch-ci") is None, "a watch is not in the task mirror"
+
+ run = requests.enqueue_hook_send(
+ session_key="slack::channel::C1",
+ prompt="the waiter finished",
+ run_type="watch",
+ definition_id="watch-ci",
+ )
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="hook delivery failed", task_id="watch-ci")
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ # No ``config`` on the controller, so the real ``_t`` renders English out of the
+ # shipped catalog instead of echoing keys.
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None
+ body = service._failure_notice_body(sqlite.get_run(run.id), notice)
+
+ assert "vibe watch" in body, f"a failed watch must be given watch commands: {body}"
+ assert "vibe task" not in body, f"a watch cannot be addressed as a task: {body}"
+ assert "ci waiter" in body, f"the watch's own name must survive the lookup: {body}"
+
+
+def test_a_failed_one_shot_notice_says_finished_not_paused(tmp_path: Path) -> None:
+ """The task-side twin of the retired-watch copy fix — FINISHED IS NOT PAUSED.
+
+ A failed ``at`` task is disabled by ``mark_task_result(disable_one_shot=True)``
+ before its notice renders, so the generic disabled branch told the user the task
+ was PAUSED and offered ``vibe task resume`` — while the canonical lifecycle
+ projection (``definition_lifecycle_expression``) classifies a past one-shot as
+ FINISHED and the CLI reads the same combination as a failed one-shot. One
+ surface's copy contradicted every other surface and named a lifecycle action
+ that re-arms nothing.
+
+ The distinction is read through the projection's own question —
+ ``compute_next_run_at`` returns ``None`` exactly when the named instant is
+ behind us — so the copy and the badge cannot disagree. The explicit re-run
+ affordance is retained: ``vibe task run`` is real and is the honest next step
+ for a failed one-shot.
+
+ The control is a paused CRON task: a cron task cannot retire itself, so its
+ disabled copy must keep naming resume.
+ """
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ # The instant is named and behind us; ``mark_task_result`` left the switch off.
+ _task(
+ sqlite,
+ "task-once",
+ name="one shot",
+ schedule_type="at",
+ cron=None,
+ run_at="2026-07-20T00:00:00+00:00",
+ enabled=False,
+ )
+ _task(sqlite, "task-paused", name="paused cron", enabled=False)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ # No ``config`` on the controller, so the real ``_t`` renders English out of
+ # the shipped catalog: the defect is in the command strings a user reads.
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ body = service._failure_notice_body(
+ {"id": "run-once", "task_id": "task-once", "error": "boom"},
+ {"failure_id": "failure:run-once", "interrupt_reason": None},
+ )
+ assert i18n_t("harness.notice.taskFinished", "en") in body, (
+ f"a finished one-shot's copy has to say it finished: {body!r}"
+ )
+ assert "vibe task resume" not in body, (
+ "and must NOT offer resume for a definition the lifecycle projection reads "
+ f"as FINISHED: {body!r}"
+ )
+ assert "vibe task run task-once" in body, (
+ f"the explicit re-run affordance is retained for a failed one-shot: {body!r}"
+ )
+
+ control = service._failure_notice_body(
+ {"id": "run-paused", "task_id": "task-paused", "error": "boom"},
+ {"failure_id": "failure:run-paused", "interrupt_reason": None},
+ )
+ assert "vibe task resume task-paused" in control, (
+ f"a genuinely paused cron task keeps the resume copy: {control!r}"
+ )
+
+ # A naive ``run_at`` is resolved in the task's own timezone by both the SQL
+ # lifecycle projection and ``compute_next_run_at``. This Shanghai wall clock
+ # is one hour in the past there but seven hours ahead if misread as UTC, so it
+ # consumes the exact disagreement the SQLite connection UDF closes.
+ from datetime import datetime, timedelta, timezone
+ from zoneinfo import ZoneInfo
+
+ naive_past_shanghai = (
+ (
+ datetime.now(timezone.utc).astimezone(ZoneInfo("Asia/Shanghai"))
+ - timedelta(hours=1)
+ )
+ .replace(tzinfo=None)
+ .isoformat()
+ )
+ _task(
+ sqlite,
+ "task-tz",
+ name="tz one shot",
+ schedule_type="at",
+ cron=None,
+ run_at=naive_past_shanghai,
+ timezone="Asia/Shanghai",
+ enabled=False,
+ )
+ store.load()
+ assert sqlite.definition_lifecycle_state("task-tz", definition_type="task") == "finished"
+ from storage.background import compute_next_run_at as _next_run
+
+ assert (
+ _next_run(
+ enabled=True,
+ schedule_type="at",
+ cron=None,
+ run_at=naive_past_shanghai,
+ timezone_name="Asia/Shanghai",
+ )
+ is None
+ )
+
+ tz_body = service._failure_notice_body(
+ {"id": "run-tz", "task_id": "task-tz", "error": "boom"},
+ {"failure_id": "failure:run-tz", "interrupt_reason": None},
+ )
+ assert i18n_t("harness.notice.taskFinished", "en") in tz_body, (
+ f"the copy and badge must both read the task-zone instant as FINISHED: {tz_body!r}"
+ )
+ assert "vibe task resume task-tz" not in tz_body, f"a finished task must not offer resume: {tz_body!r}"
+
+ # THE IN-FLIGHT SPLIT: ``vibe task run`` accepts a disabled one-shot, and an
+ # in-flight execution outranks the ended predicate in the canonical CASE — the
+ # badge says RUNNING. Flattening every non-finished state to "paused" printed
+ # resume copy beside that badge. With a rerun in flight the notice prints NO
+ # lifecycle line: either claim would contradict the badge, and the re-run/show
+ # affordance stands on its own.
+ _task(
+ sqlite,
+ "task-running",
+ name="rerun in flight",
+ schedule_type="at",
+ cron=None,
+ run_at="2026-07-20T00:00:00+00:00",
+ enabled=False,
+ )
+ sqlite.enqueue_run(
+ {
+ "id": "run-manual-rerun",
+ "request_type": "scheduled",
+ "status": "queued",
+ "definition_id": "task-running",
+ "created_at": "2026-07-29T00:00:00+00:00",
+ }
+ )
+ store.load()
+ assert (
+ sqlite.definition_lifecycle_state("task-running", definition_type="task")
+ == "running"
+ ), "the premise: an in-flight execution outranks the ended predicate"
+
+ running_body = service._failure_notice_body(
+ {"id": "run-earlier", "task_id": "task-running", "error": "boom"},
+ {"failure_id": "failure:run-earlier", "interrupt_reason": None},
+ )
+ assert "vibe task resume task-running" not in running_body, (
+ f"the copy must not say PAUSED while the badge says RUNNING: {running_body!r}"
+ )
+ assert i18n_t("harness.notice.taskFinished", "en") not in running_body, (
+ f"nor FINISHED while an execution is in flight: {running_body!r}"
+ )
+ assert "vibe task run task-running" in running_body, (
+ f"the re-run affordance stands on its own: {running_body!r}"
+ )
+
+
+# --- group 2d: crash/exception ordering in the delivery protocol -----------
+#
+# All three of these are ordering bugs, not happy-path gaps: the delivery
+# succeeds, or the delivery raises, and the protocol draws the wrong conclusion
+# because of WHERE in the sequence it looked.
+
+
+def test_the_duplicate_short_circuit_reports_its_receipt(tmp_path: Path) -> None:
+ """HFR-075 — a found row is the strongest receipt there is, and it was dropped.
+
+ Crash after ``persist_agent_message`` commits but before the owed notice is
+ acknowledged, and the retry hits the duplicate short-circuit
+ (``agent_message_exists`` → ``return native_output_id``) which sits ~112 lines
+ ABOVE the notify branch's evidence assignment and touches ``delivery`` nowhere.
+
+ ``_emit_failure_notice`` discards the return value and inspects only
+ ``DeliveryEvidence``, so a notice that IS delivered and IS persisted reads as
+ unacknowledged — and then either walks on to another ladder rung and sends a
+ duplicate, or burns its backoff and dead-letters a notice that already has a
+ receipt.
+ """
+
+ from unittest.mock import patch
+
+ import core.message_dispatcher as dispatcher_module
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT, DeliveryEvidence
+ from core.message_output import MessageOutput
+ from modules.im import MessageContext
+
+ from tests.test_message_dispatcher_scheduled import _StubController
+
+ controller = _StubController()
+ dispatcher = dispatcher_module.ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={"task_trigger_kind": "scheduled", "task_execution_id": "run-1"},
+ )
+ evidence = DeliveryEvidence()
+
+ # The row from the pre-crash attempt is already in ``messages``.
+ with patch.object(dispatcher_module, "agent_message_exists", return_value=True):
+ returned = asyncio.run(
+ dispatcher.emit_agent_message(
+ context,
+ "notify",
+ "your task failed",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="backend-failure:failure:run-1",
+ ),
+ delivery=evidence,
+ )
+ )
+
+ # The short-circuit returns the stable identity and re-sends nothing: that half
+ # already worked. The defect is that it says so ONLY through a return value the
+ # notice drain does not read.
+ assert returned and "backend-failure:failure:run-1" in returned
+ assert controller.im_client.sent == []
+ # ...and it must SAY so, or the drain cannot tell this from a lost notice.
+ assert evidence.delivered is True, "a persisted row is evidence of delivery"
+ assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
+
+
+def test_the_duplicate_short_circuit_receipt_acks_a_workbench_rung() -> None:
+ """HFR-075 — the dedup receipt has to satisfy the STRICTEST ack source there is.
+
+ The receipt above is the general claim; this is the one consumer for which it is
+ load-bearing rather than convenient. A workbench rung may acknowledge on a
+ durable persisted receipt and on nothing else (``LADDER_ACK_SOURCES``), so if the
+ duplicate short-circuit reported its found row as anything weaker than
+ ``receipt`` — a bare ``delivered_id``, say — then the exact case the idempotency
+ key exists for would be unserviceable on avibe: a crash between persisting the
+ message and acknowledging the notice would find the row, decline to re-send,
+ report nothing the policy accepts, and then re-send forever on other rungs or
+ dead-letter a notice the user demonstrably already has.
+
+ Driven through the real dispatcher against an avibe context, then handed to the
+ real predicate, because the claim spans the two modules: what the short-circuit
+ fills in, and what the ladder is willing to ack on.
+ """
+
+ from unittest.mock import patch
+
+ import core.message_dispatcher as dispatcher_module
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT, DeliveryEvidence
+ from core.message_output import MessageOutput
+ from core.scheduled_tasks import (
+ ACK_SOURCE_PERSISTED_RECEIPT,
+ ScheduledTaskService,
+ failure_notice_ack_source,
+ parse_scope_id,
+ )
+ from modules.im import MessageContext
+
+ from tests.test_message_dispatcher_scheduled import _StubController
+
+ controller = _StubController()
+ dispatcher = dispatcher_module.ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="proj-notice",
+ platform="avibe",
+ platform_specific={
+ "platform": "avibe",
+ "agent_session_id": "sesDup",
+ "task_trigger_kind": "scheduled",
+ "task_execution_id": "run-dup",
+ },
+ )
+ evidence = DeliveryEvidence()
+
+ with patch.object(dispatcher_module, "agent_message_exists", return_value=True):
+ returned = asyncio.run(
+ dispatcher.emit_agent_message(
+ context,
+ "notify",
+ "your task failed",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ idempotency_key="backend-failure:failure:run-dup",
+ ),
+ delivery=evidence,
+ )
+ )
+
+ assert returned and "backend-failure:failure:run-dup" in returned
+ assert controller.im_client.sent == [], "the row already exists; nothing may be re-sent"
+
+ target = parse_scope_id("avibe::project::proj-notice")
+ assert failure_notice_ack_source(target) == ACK_SOURCE_PERSISTED_RECEIPT, (
+ "the premise: this target class accepts nothing but a receipt"
+ )
+ assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
+ assert ScheduledTaskService._rung_acknowledges(target, evidence) is True, (
+ "a found row must acknowledge a workbench rung, or a crash-then-retry there "
+ "can never settle"
+ )
+ # And the rejection annotation stays off a rung that was accepted: an ack that
+ # also carried a "no persisted receipt" error would report a lie on the notice.
+ assert evidence.error is None
+
+
+def test_a_raising_delivery_consumes_an_attempt_instead_of_retrying_forever(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-076 — an exception must not escape before ``attempts`` is persisted.
+
+ ``_deliver_one_failure_notice`` computed the attempt number, then awaited
+ delivery, then wrote the result. An exception from any ladder rung escaped
+ between the second and third step, so nothing was persisted and the next 2 s
+ tick recomputed the SAME attempt number and raised again — an unbounded retry
+ loop, which is precisely what the backoff exists to prevent.
+
+ The live case is auth recovery (see the bypass test below), but the bound has
+ to hold for ANY raising rung, so this test raises directly.
+ """
+
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-raise", deliver_key="slack::channel::C1")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ run = requests.enqueue_task_run("task-raise")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-raise")
+
+ async def _raising_emit(controller, context, backend, diagnostic, **kwargs):
+ raise RuntimeError("auth prompt exploded")
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _raising_emit)
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+
+ seen = []
+ for _ in range(8):
+ asyncio.run(service._drain_failure_notices())
+ current = dict(sqlite.owed_failure_notice(run.id))
+ seen.append(current)
+ if current["state"] == "pending":
+ # Let the backoff elapse without sleeping. Rewinding rather than waiting
+ # keeps the test deterministic while still driving the real retry path —
+ # and the fact that this is NEEDED is itself the backoff working, since
+ # against the old code every tick fired regardless.
+ sqlite.update_owed_failure_notice(run.id, next_attempt_at=None)
+
+ attempts = [entry["attempts"] for entry in seen]
+ assert attempts[0] == 1, f"a raising delivery must consume an attempt, got {attempts}"
+ assert attempts == sorted(attempts), "attempts must advance monotonically"
+ assert seen[-1]["state"] == "failed", "a persistently raising rung must dead-letter"
+ assert "auth prompt exploded" in (seen[-1]["error"] or ""), "the dead letter must say why"
+
+
+def test_a_stale_drain_pass_cannot_overwrite_a_newer_acknowledgement(tmp_path: Path) -> None:
+ """HFR-076, the concurrency half of the same bound — a handoff must not undo an ack.
+
+ Scope, stated because the obvious reading of the title is wider than the proof:
+ this is about stale WRITE rejection only. The winner here is substituted with a
+ direct store update, so what is demonstrated is that the loser's ``pending`` retry
+ and its ``failed`` dead letter both land on nothing. It says nothing about whether
+ the loser DELIVERED — its send is stubbed out entirely, and in the real drain the
+ send happens before any of these writes. The no-redelivery consuming outcome is
+ ``test_two_owners_reading_one_pending_notice_deliver_it_exactly_once``, which
+ counts outbound sends at the IM adapter with two real connections; the durable
+ single-flight claim it pins is what makes the two owners here mutually exclusive
+ in the first place.
+
+ ``_owns_service_instance`` is consulted ONCE at the top of a drain pass and then
+ the pass AWAITS delivery. Ownership is a live flock check, so during a
+ service-lock handoff the outgoing process's lease can lapse while its coroutine
+ is still suspended in that send, and the incoming owner reads the SAME pending
+ notice, delivers it and acknowledges. The old pass then resumes and performs its
+ own write — and ``update_owed_failure_notice`` was keyed on the run id alone,
+ guarded only on "a notice still exists", so the loser's stale ``pending`` retry or
+ ``failed`` dead letter overwrote the winner's ``sent``. Both directions produce
+ another delivery; the ``failed`` one also permanently buries a receipt the user
+ already has, which is the worse half.
+
+ The fix is the ``DefinitionWriteExpectation`` idiom applied to the notice blob: a
+ write re-asserts the ``(state, attempts)`` it was decided from, and the losing
+ pass silently no-ops rather than raising — it has nothing to repair, and the next
+ tick re-reads the winner's state. ``attempts`` is in the predicate so two passes
+ that both read attempt N cannot both consume it.
+ """
+
+ from types import SimpleNamespace
+
+ from core.failure_notices import MAX_ATTEMPTS
+
+ sqlite, requests = _store(tmp_path)
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+
+ def _owed_run(definition_id: str, *, attempts: int = 0):
+ _task(sqlite, definition_id, deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="boom", task_id=definition_id)
+ if attempts:
+ sqlite.update_owed_failure_notice(run.id, attempts=attempts)
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+ return run
+
+ def _overtaken_pass(run_id: str, *, winner_attempts: int) -> dict[str, Any]:
+ """One drain pass, overtaken by the new lock owner while its send is in flight."""
+
+ async def _emit_while_the_new_owner_wins(*args, **kwargs):
+ # Suspended exactly where the old pass sits when its flock lapses: after
+ # its own read of the pending notice, inside the awaited send. The new
+ # owner's pass — which read the same pending notice — runs to completion
+ # here, ack included.
+ await asyncio.sleep(0)
+ sqlite.update_owed_failure_notice(
+ run_id,
+ state=NOTICE_SENT,
+ attempts=winner_attempts,
+ ack_evidence="receipt",
+ )
+ # ...and the resumed old pass finds nothing acknowledging ITS send.
+ return False
+
+ service._emit_failure_notice = _emit_while_the_new_owner_wins
+ asyncio.run(service._drain_failure_notices())
+ return dict(sqlite.owed_failure_notice(run_id))
+
+ # Direction 1: the loser still has attempts left, so its stale write is a
+ # ``pending`` retry. Self-healing at best — the resend hits the duplicate
+ # short-circuit — and a visible duplicate whenever the winner acked on a
+ # delivery id with no persisted row to find.
+ retry = _owed_run("task-stale-retry")
+ after_retry = _overtaken_pass(retry.id, winner_attempts=1)
+ assert after_retry["state"] == NOTICE_SENT, (
+ "a stale retry must not reopen a notice the new owner already acknowledged, "
+ f"got {after_retry['state']}"
+ )
+ assert after_retry["attempts"] == 1, "the winner's consumed attempt must stand"
+ assert after_retry["ack_evidence"] == "receipt", "the winner's receipt must survive"
+ assert not after_retry["error"], "the loser's error text must not land on a sent notice"
+
+ # Direction 2: the loser is on its last attempt, so its stale write is the dead
+ # letter — the damaging one, because ``failed`` is terminal and hides the receipt
+ # for good.
+ dead = _owed_run("task-stale-dead-letter", attempts=MAX_ATTEMPTS - 1)
+ after_dead = _overtaken_pass(dead.id, winner_attempts=MAX_ATTEMPTS)
+ assert after_dead["state"] == NOTICE_SENT, (
+ "a stale dead letter must not bury a delivered notice, "
+ f"got {after_dead['state']}"
+ )
+ assert after_dead["attempts"] == MAX_ATTEMPTS
+ assert after_dead["ack_evidence"] == "receipt", "the winner's receipt must survive"
+ assert not after_dead["error"], "a sent notice must not carry the loser's dead-letter reason"
+
+
+def test_a_notice_write_refuses_a_race_settled_after_its_own_read(tmp_path: Path) -> None:
+ """Subordinate to HFR-076 — the expectation must be evaluated by SQLITE, not Python.
+
+ The test above proves the guard catches a winner that landed BEFORE the losing
+ write was issued. That is the wide window (a whole awaited send) but not the only
+ one: the guard itself was a check-then-act. ``update_owed_failure_notice`` read
+ the row, compared ``(state, attempts)`` in Python, and only then issued its
+ UPDATE — and under pysqlite a bare SELECT emits no ``BEGIN`` (the reason
+ ``upsert_definition_in_connection`` puts its own predicate in the WHERE clause),
+ so no lock is held across that gap and the write lock is first taken by the
+ UPDATE. Two passes could both read ``(pending, N)``, both pass the comparison,
+ and both write.
+
+ So the winner is committed HERE, from another connection, in exactly that gap:
+ after the loser's SELECT, before the loser's UPDATE reaches the driver. Only a
+ predicate SQLite evaluates in the writing statement survives it; a Python
+ comparison has already been made against a snapshot the winner invalidated.
+
+ The window is sub-millisecond, which is why this is a property test rather than a
+ reported defect — but the losing write is the ``failed`` dead letter, which is
+ terminal and buries a receipt the user already has, so "narrow" is not the same
+ as "closed".
+ """
+
+ from sqlalchemy import event
+
+ from storage.background import NOTICE_FAILED, notice_write_expectation
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cas", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-cas")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="boom", task_id="task-cas")
+
+ # What the losing pass decided from, read exactly as the drain reads it. The
+ # expectation is the TRIPLE, so the freshly stamped ``next_attempt_at`` is part of
+ # it — asserted on the first two elements plus "the third is the stamped instant"
+ # rather than on a literal, which would pin a wall clock.
+ expect = notice_write_expectation(sqlite.owed_failure_notice(run.id))
+ assert expect[:2] == ("pending", 0)
+ assert expect[2] == sqlite.owed_failure_notice(run.id)["next_attempt_at"]
+
+ interleaved: list[str] = []
+
+ def _win_the_race_inside_the_gap(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ # The new lock owner's pass — which read the same pending notice — delivers
+ # and acknowledges, and COMMITS, on its own connection. The loser's read is
+ # already stale; its UPDATE has not been sent yet.
+ sqlite.update_owed_failure_notice(
+ run.id,
+ expect=expect,
+ state=NOTICE_SENT,
+ attempts=1,
+ ack_evidence="receipt",
+ )
+
+ event.listen(sqlite.engine, "before_cursor_execute", _win_the_race_inside_the_gap)
+ try:
+ lost = sqlite.update_owed_failure_notice(
+ run.id,
+ expect=expect,
+ state=NOTICE_FAILED,
+ attempts=5,
+ error="stale dead letter",
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _win_the_race_inside_the_gap)
+
+ assert interleaved, "the winner never got into the gap — this test proves nothing"
+ assert lost is None, (
+ "a write whose expectation was invalidated between its read and its UPDATE "
+ f"must report that it wrote nothing, got {lost}"
+ )
+
+ settled = sqlite.owed_failure_notice(run.id)
+ assert settled["state"] == NOTICE_SENT, (
+ "the ack committed inside the loser's read/write gap must stand, "
+ f"got {settled['state']}"
+ )
+ assert settled["attempts"] == 1, "the winner's consumed attempt must stand"
+ assert settled["ack_evidence"] == "receipt", "the winner's receipt must survive"
+ assert not settled["error"], "the loser's dead-letter reason must not land at all"
+
+
+def _owed_notice_run(sqlite, requests, definition_id: str):
+ """A settled failure of ``definition_id`` owing a freshly stamped notice."""
+
+ _task(sqlite, definition_id, deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="boom", task_id=definition_id)
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+ return run
+
+
+def test_a_stale_claim_cannot_overwrite_a_concurrent_deferral(tmp_path: Path) -> None:
+ """HFR-076 — the value-CAS has to cover every field eligibility is decided from.
+
+ Round 8 put ``(state, attempts)`` in the claim's WHERE clause. Eligibility is
+ decided from THREE fields, not two: ``owed_notice_eligible`` reads ``state`` and
+ ``next_attempt_at``, and ``next_attempt`` reads ``attempts``. The one the claim did
+ not re-assert is the one a DEFERRAL writes — a deferral moves ``next_attempt_at``
+ and ``defer_reason`` and leaves ``(state, attempts)`` exactly as they were — so a
+ claimant that read before a concurrent owner's deferral still matched its own
+ expectation, won the CAS, and overwrote the deferral.
+
+ Two consequences, and neither is theoretical. In the stale-cutoff lane the
+ predecessor deferral is what stops a second notice going out for one outage, so
+ erasing it sends two. And ``DEFERRAL_RECHECK_SECONDS`` becomes advisory rather
+ than durable: any stale claimant can pull a deferred row straight back into the
+ batch it was deferred out of, which is the starvation the durable deferral exists
+ to prevent.
+
+ Round 8's reason for keeping ``updated_at`` OUT of the predicate does not extend
+ to this field, which is why this is a completion rather than a reversal: a
+ row-version guard refuses benign writes and a freshly stamped notice carries no
+ such marker at all, whereas ``next_attempt_at`` is stamped unconditionally by
+ every stamper and a legacy notice that lacks it reads ``""`` identically on both
+ sides (the same ``coalesce(..., '')`` that keeps the eligibility index a range
+ term).
+ """
+
+ from storage.background import notice_write_expectation
+
+ sqlite, requests = _store(tmp_path)
+ run = _owed_notice_run(sqlite, requests, "task-defer-race")
+
+ # Owner A reads the notice and decides to CLAIM it.
+ expect_a = notice_write_expectation(sqlite.owed_failure_notice(run.id))
+
+ # Owner B is a second process, so a second engine over the same file. It reads the
+ # same notice and DEFERS it behind the streak's canonical row.
+ other = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ deferred_until = "2026-07-29T00:00:30+00:00"
+ assert (
+ other.update_owed_failure_notice(
+ run.id,
+ expect=notice_write_expectation(other.owed_failure_notice(run.id)),
+ next_attempt_at=deferred_until,
+ defer_reason="canonical_pending:run-canonical",
+ )
+ is not None
+ ), "the deferral itself must land"
+
+ # A's claim was decided from a world that no longer exists.
+ lost = sqlite.update_owed_failure_notice(
+ run.id,
+ expect=expect_a,
+ attempts=1,
+ next_attempt_at="2026-07-29T00:10:00+00:00",
+ )
+
+ assert lost is None, (
+ "a claim decided before a concurrent deferral must report that it wrote "
+ f"nothing, got {lost}"
+ )
+ settled = sqlite.owed_failure_notice(run.id)
+ assert settled["next_attempt_at"] == deferred_until, (
+ "the durable deferral must stand, or DEFERRAL_RECHECK_SECONDS is advisory; "
+ f"got {settled['next_attempt_at']!r}"
+ )
+ assert settled["attempts"] == 0, "no attempt may be consumed by a losing claim"
+ assert settled["defer_reason"] == "canonical_pending:run-canonical"
+
+
+def test_a_second_identical_deferral_loses_the_cas_without_changing_the_outcome(
+ tmp_path: Path,
+) -> None:
+ """HFR-076 — and the Known-By-Design sentence round 8 wrote has to be updated.
+
+ Round 8 recorded, as a deliberate non-guarantee, that two owners deferring one
+ notice from the same read BOTH land: the deferral touches neither ``state`` nor
+ ``attempts``, so neither write lost the ``(state, attempts)`` CAS. Adding
+ ``next_attempt_at`` to the expectation changes that — the first deferral MOVES the
+ field the second one's expectation carries, so the second now loses.
+
+ That is the correct outcome under the new contract, not a benign-refusal
+ regression, and the distinction is the OBSERVABLE state: the refused write was
+ refused because the world had already moved to the state it was trying to
+ establish. The notice is deferred either way, no attempt is consumed either way,
+ and the recheck instant differs only by the microseconds between two owners
+ computing ``now`` — so nothing a user or a later drain pass can observe differs.
+ Asserted here, rather than argued, because "the loser's write was redundant" is
+ exactly the claim a reviewer should not have to take on trust.
+ """
+
+ from storage.background import NOTICE_PENDING, notice_write_expectation
+
+ sqlite, requests = _store(tmp_path)
+ run = _owed_notice_run(sqlite, requests, "task-double-defer")
+
+ read_together = notice_write_expectation(sqlite.owed_failure_notice(run.id))
+ other = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+
+ first = other.update_owed_failure_notice(
+ run.id,
+ expect=read_together,
+ next_attempt_at="2026-07-29T00:00:30+00:00",
+ defer_reason="canonical_pending:run-canonical",
+ )
+ second = sqlite.update_owed_failure_notice(
+ run.id,
+ expect=read_together,
+ next_attempt_at="2026-07-29T00:00:30.000001+00:00",
+ defer_reason="canonical_pending:run-canonical",
+ )
+
+ assert first is not None, "the first deferral lands"
+ assert second is None, (
+ "the second deferral is decided from a superseded read and must report that it "
+ "wrote nothing"
+ )
+
+ # And the OUTCOME is the one both owners were trying to establish.
+ settled = sqlite.owed_failure_notice(run.id)
+ assert settled["state"] == NOTICE_PENDING, "still owed, and still not tried"
+ assert settled["attempts"] == 0, "a deferral consumes no attempt, from either owner"
+ assert settled["defer_reason"] == "canonical_pending:run-canonical"
+ assert settled["next_attempt_at"] == "2026-07-29T00:00:30+00:00"
+ # Deferred out of the immediately-eligible batch, which is the property the
+ # durable deferral exists for — the starvation bound, not the exact instant.
+ assert sqlite.list_owed_failure_notices(now="2026-07-29T00:00:00+00:00") == []
+ assert [
+ item["id"]
+ for item in sqlite.list_owed_failure_notices(now="2026-07-29T00:01:00+00:00")
+ ] == [run.id]
+
+
+def test_the_notice_expectation_reads_the_same_in_python_and_in_sql(tmp_path: Path) -> None:
+ """Subordinate to HFR-076 — the guard's two normalizations may not drift.
+
+ Moving the predicate into the WHERE clause buys atomicity at the cost of a twin:
+ ``notice_write_expectation`` normalizes the value the CALLER decided from, and
+ ``owed_notice_state_unchanged`` has to normalize the stored blob identically or
+ the guard refuses writes nobody raced. Same shape, and same hazard, as
+ ``reclaim_snapshot_marker`` and its ``_RECLAIM_SNAPSHOT_MARKER_SQL`` twin, so it
+ gets the same treatment: drive both sides over the values a notice can actually
+ hold and require the same answer.
+
+ The interesting rows are the ones where Python is lenient — a missing
+ ``attempts``, a null, a JSON string, a non-integer, an ABSENT
+ ``next_attempt_at`` — because each is a way for ``expect`` to say 0 or ``""``
+ while SQL says NULL, which would fail every guarded write on a freshly stamped
+ notice.
+
+ The expectation is the TRIPLE ``(state, attempts, next_attempt_at)``: eligibility
+ is decided from all three (``owed_notice_eligible`` reads state and
+ ``next_attempt_at``, ``next_attempt`` reads ``attempts``), so all three have to be
+ re-asserted or a write can land on a world that moved in the one field it did not
+ check — a deferral written by a concurrent owner, overwritten by a stale claim.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.background import notice_write_expectation, owed_notice_state_unchanged
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-twin")
+ run = requests.enqueue_task_run("task-twin")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-twin")
+
+ notices: list[dict[str, Any]] = [
+ {"state": "pending", "attempts": 0},
+ {"state": "pending"},
+ {"state": "pending", "attempts": None},
+ {"state": "pending", "attempts": 3},
+ {"state": "pending", "attempts": "3"},
+ {"state": "pending", "attempts": "not-a-number"},
+ {"state": "pending", "attempts": 3.7},
+ {"state": "sent", "attempts": 1},
+ {"state": "failed", "attempts": 5},
+ {"state": "skipped", "attempts": 0},
+ {"state": None, "attempts": 2},
+ {"attempts": 2},
+ # ``next_attempt_at`` in every shape a notice can hold it: absent (a notice
+ # stamped before the backoff field existed), explicitly null, empty, a real
+ # instant, and a non-string.
+ {"state": "pending", "attempts": 1, "next_attempt_at": None},
+ {"state": "pending", "attempts": 1, "next_attempt_at": ""},
+ {"state": "pending", "attempts": 1, "next_attempt_at": "2026-07-29T00:00:30+00:00"},
+ {"state": "pending", "attempts": "not-a-number", "next_attempt_at": "2026-07-29T00:00:30+00:00"},
+ {"state": "sent", "attempts": 2, "next_attempt_at": "2026-07-29T00:10:00+00:00"},
+ {"state": "pending", "attempts": 1, "next_attempt_at": " 9999-01-01T00:00:00+00:00"},
+ # ...and every JSON type it cannot legally hold. These are not curiosities: the
+ # eligibility predicate ADMITS all of them (SQLite sorts every number before
+ # every ISO instant), so an expectation SQL cannot match is a row the drain
+ # reads and can never write — a batch slot held for good. ``0`` and ``false``
+ # are the ones an ``or ""`` read got wrong, and the reals are the ones whose
+ # SQLite text cannot be reproduced in Python at all.
+ {"state": "pending", "attempts": 1, "next_attempt_at": 5},
+ {"state": "pending", "attempts": 1, "next_attempt_at": 0},
+ {"state": "pending", "attempts": 1, "next_attempt_at": True},
+ {"state": "pending", "attempts": 1, "next_attempt_at": False},
+ {"state": "pending", "attempts": 1, "next_attempt_at": 3.5},
+ {"state": "pending", "attempts": 1, "next_attempt_at": 1e25},
+ {"state": "pending", "attempts": 1, "next_attempt_at": -1.5063173670565552e-212},
+ {"state": "pending", "attempts": 1, "next_attempt_at": {"a": 1}},
+ {"state": "pending", "attempts": 1, "next_attempt_at": [1]},
+ # ``attempts`` in the shapes where SQLite's CAST diverges from ``int()`` — the
+ # round-19 finding. CAST parses a numeric PREFIX and saturates at the i64
+ # bounds, so each of these is a row the listing admits whose claim could never
+ # match under an ``int()``-based expectation: eligible, unchanged, and holding
+ # a batch slot on every pass.
+ {"state": "pending", "attempts": "3x"},
+ {"state": "pending", "attempts": "1e100"},
+ {"state": "pending", "attempts": " 5 "},
+ {"state": "pending", "attempts": " +7x"},
+ {"state": "pending", "attempts": "-3q"},
+ {"state": "pending", "attempts": "3.9"},
+ {"state": "pending", "attempts": 9223372036854775808},
+ {"state": "pending", "attempts": 1e100},
+ {"state": "pending", "attempts": True},
+ {"state": "pending", "attempts": [2]},
+ {"state": "pending", "attempts": {"n": 2}},
+ ]
+
+ import json as _json
+
+ for stored in notices:
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .values(metadata_json=_json.dumps({OWED_FAILURE_NOTICE_KEY: stored}))
+ )
+ expect = notice_write_expectation(stored)
+ with sqlite.engine.connect() as conn:
+ matched = conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .where(*owed_notice_state_unchanged(expect))
+ .values(updated_at="2026-07-01T00:00:00+00:00")
+ ).rowcount
+ assert matched == 1, (
+ f"SQL disagreed with notice_write_expectation({stored!r}) == {expect!r}; "
+ "a guarded write would be refused with no race at all"
+ )
+ # ...and the same predicate rejects the neighbouring expectations, so the
+ # agreement above is not a predicate that matches everything. One neighbour per
+ # field, INCLUDING ``next_attempt_at`` — a predicate that silently ignored the
+ # third element would pass every other assertion in this test.
+ # The wrong-attempts neighbour steps DOWN at the saturation bound: +1 there
+ # cannot bind as an SQLite integer parameter at all (OverflowError), and a
+ # CAST-saturated expectation is exactly the shape that sits on the bound.
+ wrong_attempts = expect[1] + 1 if expect[1] < 2**63 - 1 else expect[1] - 1
+ for wrong in (
+ (expect[0], wrong_attempts, expect[2]),
+ (expect[0] + "x", expect[1], expect[2]),
+ (expect[0], expect[1], expect[2] + "x"),
+ ):
+ with sqlite.engine.connect() as conn:
+ assert (
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .where(*owed_notice_state_unchanged(wrong))
+ .values(updated_at="2026-07-01T00:00:00+00:00")
+ ).rowcount
+ == 0
+ ), f"{wrong!r} must not match a notice whose expectation is {expect!r}"
+
+ # The non-text branch asserts a TYPE, so it needs its own negative control: an
+ # expectation read from a numeric instant must not match a row that now holds a
+ # real one. That transition is exactly what the third element exists to catch — a
+ # concurrent DEFERRAL writes an ISO string — so a guard that ignored it would let a
+ # stale claim erase the deferral it never saw.
+ numeric = {"state": "pending", "attempts": 1, "next_attempt_at": 5}
+ from_numeric = notice_write_expectation(numeric)
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .values(
+ metadata_json=_json.dumps(
+ {
+ OWED_FAILURE_NOTICE_KEY: {
+ "state": "pending",
+ "attempts": 1,
+ "next_attempt_at": "2026-07-29T00:00:30+00:00",
+ }
+ }
+ )
+ )
+ )
+ with sqlite.engine.connect() as conn:
+ assert (
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .where(*owed_notice_state_unchanged(from_numeric))
+ .values(updated_at="2026-07-01T00:00:00+00:00")
+ ).rowcount
+ == 0
+ ), (
+ f"{from_numeric!r} matched a row whose retry instant became TEXT; a "
+ "concurrent deferral would be erased by a claim that never saw it"
+ )
+
+
+def test_the_eligibility_predicate_reads_the_same_in_python_and_in_sql(tmp_path: Path) -> None:
+ """Subordinate to HFR-076 — the eligibility twins may not drift over ANY JSON shape.
+
+ ``owed_notice_eligible`` is the Python twin of the two expressions
+ ``list_owed_failure_notices`` seeks on, and the seek applies ``LIMIT`` BEFORE the
+ Python re-check runs. So a shape SQL admits and Python rejects is not a harmless
+ difference of opinion: the row consumes one of the ten slots, is dropped with no
+ state transition, and is selected again on the next tick forever. Ten of them
+ starve every valid notice behind them — silently, in a drain that looks busy and
+ healthy. Same defect class as HFR-085 and as the malformed ``attempts`` that
+ ``notice_write_expectation`` degrades instead of wedging.
+
+ ``next_attempt_at`` is stamped only by this module's own writers, always as an ISO
+ string, so the shapes below need a foreign writer or a hand-edited row to arrive.
+ That is exactly the argument that made the earlier drift invisible for two rounds,
+ so the predicate is pinned over every JSON type instead: null, text, integer, real,
+ true/false, object and array, and the paddings that make a string sort against
+ ``now`` differently before and after a ``strip()``.
+
+ The comparison SQLite makes is a STORAGE CLASS comparison, and this test exists
+ because that is not the comparison Python makes: every INTEGER and REAL sorts
+ before every TEXT in SQLite, so a numeric ``next_attempt_at`` is ``<= now`` for
+ any instant, while ``str(9999) <= "2026-..."`` is false. And SQLite does not strip,
+ so ``" 9999-01-01..."`` sorts before ``now`` on the leading space while a stripped
+ copy sorts after it.
+ """
+
+ from sqlalchemy import and_, literal_column
+ from sqlalchemy import select as sa_select
+ from sqlalchemy import update as sa_update
+
+ from storage.background import (
+ NOTICE_PENDING,
+ OWED_NOTICE_NEXT_ATTEMPT_SQL,
+ OWED_NOTICE_STATE_SQL,
+ )
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-eligible-twin")
+ run = requests.enqueue_task_run("task-eligible-twin")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-eligible-twin")
+
+ now = "2026-07-29T00:00:00+00:00"
+ # The two expressions VERBATIM, combined exactly as the listing query combines
+ # them, so this compares against the predicate that actually applies the limit.
+ in_sql = and_(
+ literal_column(OWED_NOTICE_STATE_SQL) == NOTICE_PENDING,
+ literal_column(OWED_NOTICE_NEXT_ATTEMPT_SQL) <= now,
+ )
+
+ shapes: list[Any] = [
+ # ``next_attempt_at`` as TEXT, which is the only shape a stamper writes.
+ {"state": "pending"},
+ {"state": "pending", "next_attempt_at": None},
+ {"state": "pending", "next_attempt_at": ""},
+ {"state": "pending", "next_attempt_at": "2026-07-28T23:59:59+00:00"},
+ {"state": "pending", "next_attempt_at": "2099-01-01T00:00:00+00:00"},
+ {"state": "pending", "next_attempt_at": " 2020-01-01T00:00:00+00:00"},
+ {"state": "pending", "next_attempt_at": " 9999-01-01T00:00:00+00:00"},
+ {"state": "pending", "next_attempt_at": "2026-07-28T23:59:59+00:00 "},
+ # ...and a numeric-looking STRING, which is still text and still compares as
+ # text on both sides — the negative control for the numeric rows below.
+ {"state": "pending", "next_attempt_at": "9999"},
+ # Every other JSON type.
+ {"state": "pending", "next_attempt_at": 0},
+ {"state": "pending", "next_attempt_at": 1},
+ {"state": "pending", "next_attempt_at": 3},
+ {"state": "pending", "next_attempt_at": 9999},
+ {"state": "pending", "next_attempt_at": -5},
+ {"state": "pending", "next_attempt_at": 1.5},
+ {"state": "pending", "next_attempt_at": 3.5},
+ {"state": "pending", "next_attempt_at": 1e25},
+ {"state": "pending", "next_attempt_at": True},
+ {"state": "pending", "next_attempt_at": False},
+ {"state": "pending", "next_attempt_at": {"a": 1}},
+ {"state": "pending", "next_attempt_at": [1]},
+ # The state half of the predicate, including the shapes that make the notice
+ # unreadable rather than merely ineligible.
+ {"state": "sent", "next_attempt_at": None},
+ {"state": "skipped"},
+ {"state": "failed"},
+ {"state": "PENDING"},
+ {"state": None},
+ {},
+ None,
+ "pending",
+ 5,
+ ]
+
+ import json as _json
+
+ answers: list[bool] = []
+ drift: list[str] = []
+ for stored in shapes:
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .values(metadata_json=_json.dumps({OWED_FAILURE_NOTICE_KEY: stored}))
+ )
+ with sqlite.engine.connect() as conn:
+ listed = bool(
+ conn.execute(
+ sa_select(in_sql).select_from(agent_runs).where(agent_runs.c.id == run.id)
+ ).scalar()
+ )
+ answers.append(listed)
+ if owed_notice_eligible(stored, now) is not listed:
+ drift.append(f"{stored!r}: SQL={listed} python={not listed}")
+ # Reported as one list rather than one failure: the shapes that drift are the
+ # inventory of ways a row can hold a batch slot forever, and seeing them together
+ # is what makes the normalization rule obvious.
+ assert not drift, (
+ "owed_notice_eligible disagreed with the SQL the LIMIT is applied to for "
+ + str(len(drift))
+ + " shape(s); each is a row SQL admits and Python drops, which holds one of "
+ "the ten batch slots forever with no state transition:\n "
+ + "\n ".join(drift)
+ )
+
+ # A predicate that answered the same thing to everything would satisfy the loop
+ # above without pinning anything.
+ assert any(answers) and not all(answers), "the shapes must exercise both answers"
+
+
+def test_the_drain_does_not_turn_an_owed_notice_into_a_live_auth_prompt(
+ tmp_path: Path,
+) -> None:
+ """HFR-077 — a drained notice cannot become an interactive auth prompt.
+
+ ``maybe_emit_auth_recovery_message`` cannot fill a ``DeliveryEvidence`` — its
+ signature has no such parameter — so a notice delivered through it reads as
+ unacknowledged and walks on to the next ladder rung.
+
+ Not plumbing evidence through it is a product answer, not a shortcut: an owed
+ notice is a report about a run that failed in the past, possibly hours ago and
+ possibly already retried, whereas the auth prompt is an interactive remediation
+ affordance about the state of the backend RIGHT NOW. Those are different
+ messages.
+
+ Asserted on the drain's OBSERVABLE behaviour against a real controller whose
+ auth service refuses to be read at all, rather than on an argument the drain
+ passes. The bypass used to be an ``allow_auth_recovery=False`` on the live
+ emitter, so this test could only check that the drain remembered to pass it; the
+ drain now has its own emitter that cannot reach auth recovery, and the way to
+ prove that is to make any access fail.
+ """
+
+ _migrated_state_db()
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ controller.agent_auth_service = _ForbiddenAuthService()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-auth", deliver_key="slack::channel::C123")
+ run = requests.enqueue_task_run("task-auth")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="401 unauthorized", task_id="task-auth")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_SENT
+ # ...and what the user got is the notice, not an OAuth prompt.
+ assert len(controller.im_client.sent) == 1
+ assert "harness.notice" in controller.im_client.sent[0][2]
+
+
+def test_auth_recovery_stays_on_for_every_other_caller() -> None:
+ """Interactive callers keep auth recovery; Harness delivery stays durable.
+
+ Auth recovery is where a real interactive 401 gets its reset-OAuth button. A
+ Harness run instead settles into its owed-notice row and lets that drain own the
+ single visible delivery, including recurring-streak suppression.
+ """
+
+ import inspect
+ from types import SimpleNamespace
+
+ from core.backend_failure import emit_backend_failure, emit_replayed_backend_failure
+ from modules.im import MessageContext
+
+ live_params = inspect.signature(emit_backend_failure).parameters
+ assert "allow_auth_recovery" not in live_params, (
+ "a bypass argument on the live path is one a caller can pass by mistake"
+ )
+ replay_params = inspect.signature(emit_replayed_backend_failure).parameters
+ assert "allow_auth_recovery" not in replay_params
+
+ # The interactive live path really does consult it.
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ consulted: list[str] = []
+
+ async def _maybe_recover(context, backend, visible, **kwargs):
+ consulted.append(backend)
+ return True
+
+ controller.agent_auth_service = SimpleNamespace(
+ maybe_emit_auth_recovery_message=_maybe_recover
+ )
+ context = MessageContext(
+ user_id="u1", channel_id="C123", platform="slack", platform_specific={"turn_token": "t"}
+ )
+
+ handled = asyncio.run(emit_backend_failure(controller, context, "codex", "401 unauthorized"))
+
+ assert handled is True and consulted == ["codex"]
+
+ harness_context = MessageContext(
+ user_id="u1",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_execution_id": "run-harness-auth",
+ "task_trigger_kind": "scheduled",
+ },
+ )
+ handled = asyncio.run(
+ emit_backend_failure(controller, harness_context, "codex", "401 unauthorized")
+ )
+ assert handled is False
+ assert consulted == ["codex"], "Harness failures must not bypass the durable notice policy"
+
+
+def test_the_owed_notice_lookup_does_not_scan_settled_history(tmp_path: Path) -> None:
+ """HFR-078 — the 2 s lookup must be bounded in SQL, not in Python.
+
+ The query selected every ``failed`` run with no predicate on notice state or
+ backoff and no SQL ``LIMIT``; the Python limit applied only once a PENDING
+ notice was found. Once historical failures are all ``sent``/``skipped``/
+ ``failed`` — the steady state — every tick scanned and JSON-decoded the entire
+ failed-run history to return an empty list, at a cost growing without bound
+ over the database's lifetime.
+
+ Asserted on the work done, not on wall-clock time: the number of metadata rows
+ the store decodes in Python.
+ """
+
+ from unittest.mock import patch
+
+ import storage.background as background
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-history")
+
+ settled = 40
+ for index in range(settled):
+ run_id = f"run-old-{index:03d}"
+ sqlite.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-history",
+ "error": "boom",
+ "created_at": f"2026-07-01T00:{index:02d}:00+00:00",
+ "completed_at": f"2026-07-01T00:{index:02d}:30+00:00",
+ "metadata": {
+ "owed_failure_notice": {
+ "state": "sent",
+ "attempts": 1,
+ "ack_evidence": "receipt",
+ "failure_id": f"failure:{run_id}",
+ }
+ },
+ }
+ )
+
+ decoded: list[int] = []
+ real_json_loads = background._json_loads
+
+ def _counting_json_loads(value, default):
+ decoded.append(1)
+ return real_json_loads(value, default)
+
+ with patch.object(background, "_json_loads", _counting_json_loads):
+ assert sqlite.list_owed_failure_notices() == []
+
+ assert len(decoded) < settled, (
+ f"decoded {len(decoded)} metadata blobs for {settled} settled rows — "
+ "the eligibility predicate must run in SQL, before the limit"
+ )
+
+ # And pin the bound on the statement itself, so the behaviour above cannot be
+ # satisfied later by some Python-side shortcut that leaves the scan in place.
+ from sqlalchemy import event
+
+ statements: list[tuple[str, Any]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ statements.append((statement, parameters))
+
+ event.listen(sqlite.engine, "before_cursor_execute", _capture)
+ try:
+ sqlite.list_owed_failure_notices(limit=7, now="2026-07-27T12:00:00+00:00")
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _capture)
+
+ statement, parameters = statements[-1]
+ rendered = f"{statement} {parameters}"
+ assert "LIMIT" in statement.upper(), "the query must be bounded in SQL"
+ assert "json_valid" in statement, "one malformed row must not fail the statement"
+ assert f"$.{OWED_FAILURE_NOTICE_KEY}.state" in rendered
+ assert f"$.{OWED_FAILURE_NOTICE_KEY}.next_attempt_at" in rendered
+
+
+def test_the_owed_notice_lookup_survives_one_malformed_metadata_row(tmp_path: Path) -> None:
+ """The SQL predicate needs the same ``json_valid`` guard as the health window.
+
+ ``json_extract`` raises ``malformed JSON`` and fails the whole STATEMENT, so
+ without the guard one bad row stops the drain finding ANY owed notice — every
+ failure notification in the system, silenced by a single unparseable blob.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-malformed")
+
+ good = requests.enqueue_task_run("task-malformed")
+ claimed = requests.claim(good.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-malformed")
+
+ sqlite.enqueue_run(
+ {
+ "id": "run-bad-json",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-malformed",
+ "error": "boom",
+ "created_at": "2026-07-01T00:00:00+00:00",
+ }
+ )
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs).where(agent_runs.c.id == "run-bad-json").values(metadata_json="{not json")
+ )
+
+ owed = sqlite.list_owed_failure_notices()
+
+ assert [item["id"] for item in owed] == [good.id]
+
+
+# --- group 2e: the replay must not disturb the present ---------------------
+
+
+def _live_turn_dispatcher():
+ """A dispatcher whose target channel has a turn in progress.
+
+ ``emit_matches_runtime_turn`` fails OPEN when a context carries no runtime-turn
+ key — deliberately, because a scheduled or watch run legitimately has none and
+ its own terminal result must still settle. That assumption holds while the
+ emitter IS the run's live execution. For a REPLAY of a run that ended hours ago
+ it is exactly backwards: the tokenless context is adopted by whatever turn is
+ currently live on that channel.
+ """
+
+ from types import SimpleNamespace
+
+ import core.message_dispatcher as dispatcher_module
+
+ from tests.test_message_dispatcher_scheduled import _StubController
+
+ controller = _StubController()
+ # No runtime-turn key on the replay context, so this returns True (fail-open) —
+ # the dispatcher believes the emit belongs to the channel's current turn.
+ controller.agent_service = SimpleNamespace(
+ emit_matches_runtime_turn=lambda context: True,
+ activities=SimpleNamespace(has_blocking_run_activity=lambda run_id: False),
+ release_runtime_turn=lambda context: None,
+ )
+ dispatcher = dispatcher_module.ConsolidatedMessageDispatcher(controller)
+
+ touched: list[str] = []
+
+ async def _collapse(*args, **kwargs):
+ touched.append("collapse_status_bubble")
+
+ async def _clear(*args, **kwargs):
+ touched.append("clear_consolidated_state")
+
+ def _signal(*args, **kwargs):
+ touched.append("signal_turn_complete")
+
+ async def _finish(*args, **kwargs):
+ touched.append("finish_processing_indicator_turn")
+
+ def _release(*args, **kwargs):
+ touched.append("release_runtime_turn")
+
+ dispatcher._collapse_status_bubble = _collapse
+ dispatcher._clear_consolidated_state = _clear
+ dispatcher._signal_turn_complete = _signal
+ dispatcher._finish_processing_indicator_turn = _finish
+ dispatcher._release_runtime_turn = _release
+
+ controller.emit_agent_message = dispatcher.emit_agent_message
+ return controller, dispatcher, touched
+
+
+class _ForbiddenAuthService:
+ """Any attribute read at all is a failure.
+
+ The replay may not consult auth recovery, and the check has to be on ACCESS
+ rather than on invocation: ``emit_backend_failure`` reads
+ ``maybe_emit_auth_recovery_message`` off this service and only then decides
+ whether to await it, so a spy that records calls alone would pass for a replay
+ that had walked back into the live path.
+ """
+
+ def __getattr__(self, name: str): # pragma: no cover - the assertion is the point
+ raise AssertionError(f"the replay path reached auth recovery: {name}")
+
+
+def _migrated_state_db() -> Path:
+ """The isolated home's workbench state DB, with the real schema applied.
+
+ Without the schema ``persist_agent_message`` cannot upsert a scope, swallows the
+ "no such table" error and returns ``None``. The notice then acks on the send id
+ alone and no ``messages`` row is written — so every assertion about the notice a
+ user can actually read back, and about the identity that row is keyed by, needs
+ the real schema rather than a stub.
+
+ The one-time JSON → SQLite import is settled here too. Any default-path
+ ``SQLiteBackgroundTaskStore()`` runs ``ensure_sqlite_state`` lazily from its
+ constructor, and on an unmarked DB that CLEARS every imported table — including
+ ``messages``. The live result path builds such a store
+ (``_record_agent_run_terminal_result``), so a test that persists a notification
+ and then drives a live settlement had its row silently wiped mid-test. Priming
+ the marker up front makes the import a fact of setup rather than a hazard of
+ whichever path happens to construct a store first.
+ """
+
+ from config import paths
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+ from storage.migrations import run_migrations
+
+ path = paths.get_sqlite_state_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ run_migrations(path)
+ ensure_sqlite_state(
+ primary_platform=resolve_primary_platform_from_config(paths.get_state_dir())
+ )
+ return path
+
+
+def _persisted_messages() -> list[dict]:
+ from sqlalchemy import text as sa_text
+
+ from storage.db import get_cached_sqlite_engine
+
+ with get_cached_sqlite_engine().begin() as conn:
+ rows = conn.execute(sa_text("SELECT * FROM messages ORDER BY created_at, id")).mappings()
+ return [dict(row) for row in rows]
+
+
+def _drain_service(tmp_path: Path, controller, sqlite, requests):
+ """A ``ScheduledTaskService`` wired to drain one real store through *controller*."""
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ controller.platform_settings_managers = {}
+ controller.session_turn_gate = None
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ # The notice drain is dispatched from the watch rather than awaited by it, so a
+ # service built without ``__init__`` still needs the handle the dispatcher keys its
+ # single-flight check on.
+ service._notice_drain_task = None
+ service.controller = controller
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+ return service
+
+
+def _spy_emissions(controller) -> list[dict[str, Any]]:
+ """Record every ``emit_agent_message`` the drain makes, then pass it through."""
+
+ seen: list[dict[str, Any]] = []
+ inner = controller.emit_agent_message
+
+ async def _spy(context, message_type, text, *args, **kwargs):
+ seen.append(
+ {
+ "type": message_type,
+ "text": text,
+ "level": kwargs.get("level"),
+ "output": kwargs.get("output"),
+ }
+ )
+ return await inner(context, message_type, text, *args, **kwargs)
+
+ controller.emit_agent_message = _spy
+ return seen
+
+
+def test_a_replayed_notice_reaches_the_user_without_touching_the_live_lifecycle(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-079 — the replay is its own emitter, not the live path with switches off.
+
+ The drain used to replay a historical failure through ``emit_backend_failure``
+ and then neutralize the live behaviour one argument at a time: a non-settling
+ ``output``, an auth-recovery bypass, an explicit identity. The terminal
+ ``result`` was still emitted (``settle_terminal_failure`` runs in a ``finally``),
+ so the replay stayed inside the live turn lifecycle with a defused payload —
+ and four review rounds found a settlement, an auth and an identity defect in
+ the gaps between those switches.
+
+ Two halves, and the guard is the load-bearing one:
+
+ * the consuming end — a user actually gets the notice, persisted and acked;
+ * the structural guard — the live emitter is UNREACHABLE from the drain, no
+ ``result`` is emitted at all, auth recovery is not even looked at, and no
+ turn settlement, status-bubble teardown or runtime-turn release happens.
+
+ The run is terminal by construction: a notice is owed only once the row is
+ settled, so there is nothing here for a lifecycle emit to settle.
+ """
+
+ import core.backend_failure as backend_failure_module
+ import core.scheduled_tasks as scheduled_tasks
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+
+ _migrated_state_db()
+ controller, _dispatcher, touched = _live_turn_dispatcher()
+ controller.agent_auth_service = _ForbiddenAuthService()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-replay", name="daily report", deliver_key="slack::channel::C123")
+ run = requests.enqueue_task_run("task-replay")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-replay")
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+
+ async def _forbidden_live_emit(*args, **kwargs):
+ raise AssertionError("the drain called the LIVE backend-failure emitter")
+
+ # Snapshot BEFORE patching: ``raising=False`` below would otherwise CREATE the
+ # attribute and make the structural check trivially true.
+ drain_imports_live_emitter = hasattr(scheduled_tasks, "emit_backend_failure")
+
+ # Both spellings, because patching only the definition would leave the drain's
+ # own module-level reference — the one it actually calls — untouched.
+ monkeypatch.setattr(backend_failure_module, "emit_backend_failure", _forbidden_live_emit)
+ monkeypatch.setattr(
+ scheduled_tasks, "emit_backend_failure", _forbidden_live_emit, raising=False
+ )
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ emissions = _spy_emissions(controller)
+
+ asyncio.run(service._drain_failure_notices())
+
+ # --- the guard ---------------------------------------------------------
+ assert [item["type"] for item in emissions] == ["notify"], (
+ f"the replay must emit exactly one visible notify and nothing else: {emissions}"
+ )
+ assert touched == [], f"the replay mutated live turn state: {touched}"
+ output = emissions[0]["output"]
+ assert output.completes_turn is False and output.settles_run is False, (
+ "a receipt about an already-terminal run may not settle a turn or a run"
+ )
+ assert not drain_imports_live_emitter, (
+ "the drain must not so much as import the live failure emitter"
+ )
+
+ # --- the consuming end -------------------------------------------------
+ assert controller.im_client.sent, "the notice must still reach the user"
+ channel, _thread, sent_text = controller.im_client.sent[0]
+ assert channel == "C123"
+ assert sent_text == emissions[0]["text"]
+ assert "harness.notice.rerun" in sent_text
+
+ rows = _persisted_messages()
+ assert [row["type"] for row in rows] == ["notify"], (
+ f"exactly one durable row, the visible one: {rows}"
+ )
+ assert rows[0]["content_text"] == sent_text
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == NOTICE_SENT
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT
+ assert notice["attempts"] == 1
+
+
+# --- group 2f: single-flight BEFORE the external side effect ----------------
+
+
+def _second_owner_store(tmp_path: Path) -> tuple[SQLiteBackgroundTaskStore, TaskExecutionStore]:
+ """A genuinely separate store pair over the SAME database file.
+
+ Not ``_store``'s objects passed twice: the race these tests exist for is between
+ two OS processes, so the two owners must not be able to coordinate through shared
+ Python state — no shared engine, no shared connection, no shared identity map. Two
+ ``SQLiteBackgroundTaskStore`` instances over one file is the closest single-process
+ approximation, and it is faithful where it matters: the guarded UPDATE is evaluated
+ by SQLite under its single-writer lock, which is the same primitive across
+ connections and across processes.
+ """
+
+ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")
+ requests = TaskExecutionStore(tmp_path / "task_requests")
+ requests._sqlite = sqlite
+ return sqlite, requests
+
+
+def _owed_slack_notice(sqlite, requests, definition_id: str) -> str:
+ """One failed run owing one pending notice, addressed at a Slack channel rung."""
+
+ from storage.background import NOTICE_PENDING
+
+ _task(sqlite, definition_id, name="daily report", deliver_key="slack::channel::C123")
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id=definition_id)
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_PENDING
+ return run.id
+
+
+def test_two_owners_reading_one_pending_notice_deliver_it_exactly_once(
+ tmp_path: Path,
+) -> None:
+ """HFR-076, subordinate — the consuming outcome: single-flight before the external send.
+
+ The ``(state, attempts)`` expectation on the notice write stops a stale pass from
+ OVERWRITING a newer acknowledgement. It does not stop that pass from DELIVERING,
+ because it is only reached after the send has already happened: both owners read
+ ``pending``, both walk the ladder, both await ``_emit_failure_notice``, and only
+ then does either attempt its CAS. The loser's write is rejected — and the user has
+ two identical messages, which no database predicate can recall.
+
+ Nothing downstream closes it either. ``MessageDispatcher.emit_agent_message``
+ checks ``agent_message_exists`` BEFORE ``send_message`` and persists AFTER it, so
+ two owners both pass the pre-send lookup while neither receipt exists yet. The
+ unique ``(platform, native_message_id)`` row resolves the later database race
+ only: it keeps the transcript honest, one row for two sends, which is precisely
+ why the count has to be taken further out.
+
+ So the count is taken at the IM adapter's ``send_message`` — the last hop before
+ the platform. Not at the drain's intent (a pass that stood down never had one) and
+ not at the persisted rows (they dedupe, and would report success for a duplicate
+ the user can see). Everything between the drain and that hop runs for real: the
+ ladder, the replay emitter, ``agent_message_exists``, ``persist_agent_message`` and
+ the guarded write. Only the transport is stubbed, as it is throughout this file.
+
+ Handing owner B a run dict listed BEFORE anything was written is load-bearing: an
+ implementation that only tightened the SQL listing would otherwise pass, while the
+ real drain reads its batch and then awaits deliveries one at a time.
+
+ The fix has to be a durable claim taken BEFORE the side effect — the attempt
+ consumed and a lease armed in one guarded UPDATE — so the second owner either
+ loses that CAS or sees the lease and stands down. A process-local lock cannot do
+ it (two processes), and neither can a post-send CAS.
+ """
+
+ _migrated_state_db()
+
+ sqlite_a, requests_a = _store(tmp_path)
+ sqlite_b, requests_b = _second_owner_store(tmp_path)
+ assert sqlite_a.engine is not sqlite_b.engine, "two owners, two connections"
+
+ run_id = _owed_slack_notice(sqlite_a, requests_a, "task-race")
+
+ sends: list[tuple[str, str, str]] = []
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ from tests.test_message_dispatcher_scheduled import _StubIMClient
+
+ class _GatedIMClient(_StubIMClient):
+ """Owner A, suspended with its request already on the wire."""
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ sends.append(("A", context.channel_id, text))
+ entered.set()
+ await release.wait()
+ return "slack-msg-A"
+
+ class _SecondOwnerIMClient(_StubIMClient):
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ sends.append(("B", context.channel_id, text))
+ return "slack-msg-B"
+
+ controller_a, _dispatcher_a, _touched_a = _live_turn_dispatcher()
+ controller_a.im_client = _GatedIMClient()
+ controller_b, _dispatcher_b, _touched_b = _live_turn_dispatcher()
+ controller_b.im_client = _SecondOwnerIMClient()
+
+ service_a = _drain_service(tmp_path, controller_a, sqlite_a, requests_a)
+ service_b = _drain_service(tmp_path, controller_b, sqlite_b, requests_b)
+
+ # Both owners load the same pending notice, each on its own connection, BEFORE
+ # either has written anything at all.
+ run_a = sqlite_a.list_owed_failure_notices()[0]
+ run_b = sqlite_b.list_owed_failure_notices()[0]
+ assert run_a["id"] == run_b["id"] == run_id
+
+ async def scenario() -> None:
+ task_a = asyncio.create_task(service_a._deliver_one_failure_notice(sqlite_a, run_a))
+ await asyncio.wait_for(entered.wait(), timeout=30)
+ # The second owner takes over and runs to completion while A is still in
+ # flight — the handoff the ownership check cannot see, because it was
+ # consulted once, before the await.
+ await service_b._deliver_one_failure_notice(sqlite_b, run_b)
+ release.set()
+ await task_a
+
+ asyncio.run(scenario())
+
+ assert len(sends) == 1, (
+ f"exactly one outbound IM send may leave for one owed notice, got {len(sends)}: {sends}"
+ )
+ rows = _persisted_messages()
+ assert [row["type"] for row in rows] == ["notify"]
+ notice = sqlite_a.owed_failure_notice(run_a["id"])
+ assert notice["state"] == NOTICE_SENT
+ assert notice["attempts"] == 1
+ assert not notice["error"]
+
+
+def test_a_dead_claimants_lease_expires_into_exactly_one_recovered_delivery(
+ tmp_path: Path,
+) -> None:
+ """HFR-076, subordinate — the bounded-recovery half of the same claim.
+
+ A claim taken before the send buys single-flight at the price of a new way to
+ lose a notice: the claimant can die holding it. A process killed inside the send
+ leaves ``pending`` with an armed lease and no owner, and if that lease never
+ expired the notice would be owed forever with nothing reporting it — a worse
+ outcome than the duplicate the claim exists to prevent.
+
+ So the lease is a BOUND, not a lock: once it elapses the row is eligible again,
+ any owner may re-claim it, and the recovered delivery consumes its OWN attempt
+ rather than riding the dead one. That is what keeps the retry ladder finite —
+ a claim that could be inherited for free would let a repeatedly-dying claimant
+ retry without limit and never dead-letter.
+
+ The claimant dies with ``Task.cancel``, which is faithful twice over: the drain's
+ ``except Exception`` deliberately does not swallow ``CancelledError``, so nothing
+ is written on the way out, and the send is abandoned BEFORE the adapter records
+ it — the transport never accepted the request, so no user has this notice yet.
+ The lease is elapsed by rewinding it rather than by sleeping, exactly as the
+ raising-rung test elapses the backoff.
+ """
+
+ _migrated_state_db()
+
+ sqlite_a, requests_a = _store(tmp_path)
+ sqlite_b, requests_b = _second_owner_store(tmp_path)
+
+ run_id = _owed_slack_notice(sqlite_a, requests_a, "task-lease")
+
+ sends: list[tuple[str, str, str]] = []
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ from tests.test_message_dispatcher_scheduled import _StubIMClient
+
+ class _DyingIMClient(_StubIMClient):
+ """Owner A, killed before the transport ever accepted the request."""
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ entered.set()
+ await release.wait()
+ sends.append(("A", context.channel_id, text)) # pragma: no cover
+ return "slack-msg-A" # pragma: no cover
+
+ class _RecoveringIMClient(_StubIMClient):
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ sends.append(("B", context.channel_id, text))
+ return "slack-msg-B"
+
+ controller_a, _dispatcher_a, _touched_a = _live_turn_dispatcher()
+ controller_a.im_client = _DyingIMClient()
+ controller_b, _dispatcher_b, _touched_b = _live_turn_dispatcher()
+ controller_b.im_client = _RecoveringIMClient()
+
+ service_a = _drain_service(tmp_path, controller_a, sqlite_a, requests_a)
+ service_b = _drain_service(tmp_path, controller_b, sqlite_b, requests_b)
+
+ run_a = sqlite_a.list_owed_failure_notices()[0]
+
+ async def scenario() -> None:
+ task_a = asyncio.create_task(service_a._deliver_one_failure_notice(sqlite_a, run_a))
+ await asyncio.wait_for(entered.wait(), timeout=30)
+ task_a.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task_a
+
+ # The lease elapses, with no claimant left to renew or release it.
+ sqlite_b.update_owed_failure_notice(run_id, next_attempt_at=None)
+
+ owed = sqlite_b.list_owed_failure_notices()
+ assert [item["id"] for item in owed] == [run_id], (
+ "an expired claim must make the row eligible again, or a claimant that "
+ f"died mid-send owes the user a notice forever: {owed}"
+ )
+ await service_b._deliver_one_failure_notice(sqlite_b, owed[0])
+
+ asyncio.run(scenario())
+
+ assert [entry[0] for entry in sends] == ["B"], (
+ f"recovery must deliver exactly once, and only the survivor: {sends}"
+ )
+ rows = _persisted_messages()
+ assert [row["type"] for row in rows] == ["notify"]
+ notice = sqlite_a.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_SENT
+ assert notice["attempts"] == 2, (
+ "the recovered delivery must consume its OWN attempt rather than riding the "
+ f"dead claimant's, or a dying claimant retries without bound: {notice}"
+ )
+
+
+def test_a_wedged_delivery_times_out_into_one_durably_retryable_claim(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-076, subordinate — the claim must be bounded in TIME, not just in owners.
+
+ The claim taken before the send makes a second owner stand down for
+ ``CLAIM_LEASE_SECONDS``. That is the right trade for a claimant that DIES, and the
+ wrong one for a claimant that never returns: a transport that accepted the request
+ and hung (no timeout, a half-open socket, a platform that stopped answering) leaves
+ the pass suspended inside ``_emit_failure_notice`` forever. Nothing recovers it —
+ the row is not eligible while the lease holds, and the coroutine holding it is not
+ going to fail — so the notice is owed indefinitely with no error anywhere.
+
+ So the ladder walk gets a deadline of its own, and the interesting part is what the
+ deadline does to the CLAIM. It CONSUMES it, it does not release it: the attempt was
+ already made durable by the claim before the send, so the timeout writes the
+ ordinary retry — ``(pending, attempts=1)`` with the declared first backoff armed —
+ under the expectation the claim left behind. Releasing it instead (rewinding
+ ``attempts``) would let a transport that hangs every time retry without bound and
+ never dead-letter.
+
+ Two properties beyond "it returned", both of which a naive ``asyncio.wait_for``
+ around the wrong scope would break:
+
+ * the hung transport is CANCELLED and observed to be cancelled, so no detached
+ coroutine survives to send behind a replacement claimant's back;
+ * the row's armed retry is the declared FIRST interval, which is the item-7
+ indexing fix showing up where a user would feel it.
+
+ The send is recorded only when the stub COMPLETES, mirroring the wedge being
+ modelled: an HTTP call still sitting on the wire never reached the platform, so the
+ one message the user eventually gets is the recovered owner's.
+
+ Honest residual, stated because the timeout cannot remove it: a transport that
+ accepted the request and is cancelled after that acceptance leaves a delivered
+ message and a retryable row — the same at-least-once window
+ ``CLAIM_LEASE_SECONDS`` documents for a claimant that dies there. And the bound
+ itself assumes the transport honours cancellation; one that swallowed
+ ``CancelledError`` would hang the deadline too.
+ """
+
+ from datetime import datetime, timezone
+
+ from core import failure_notices
+ from storage.background import NOTICE_PENDING
+
+ _migrated_state_db()
+
+ sqlite_a, requests_a = _store(tmp_path)
+ sqlite_b, requests_b = _second_owner_store(tmp_path)
+
+ run_id = _owed_slack_notice(sqlite_a, requests_a, "task-wedge")
+
+ sends: list[tuple[str, str, str]] = []
+ entered = asyncio.Event()
+ never_returns = asyncio.Event()
+ cancelled: list[str] = []
+
+ from tests.test_message_dispatcher_scheduled import _StubIMClient
+
+ class _WedgedIMClient(_StubIMClient):
+ """A transport that took the call and never came back."""
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ entered.set()
+ try:
+ await never_returns.wait()
+ except asyncio.CancelledError:
+ cancelled.append("A")
+ raise
+ sends.append(("A", context.channel_id, text)) # pragma: no cover
+ return "slack-msg-A" # pragma: no cover
+
+ class _RecoveringIMClient(_StubIMClient):
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ sends.append(("B", context.channel_id, text))
+ return "slack-msg-B"
+
+ controller_a, _dispatcher_a, _touched_a = _live_turn_dispatcher()
+ controller_a.im_client = _WedgedIMClient()
+ controller_b, _dispatcher_b, _touched_b = _live_turn_dispatcher()
+ controller_b.im_client = _RecoveringIMClient()
+
+ service_a = _drain_service(tmp_path, controller_a, sqlite_a, requests_a)
+ service_b = _drain_service(tmp_path, controller_b, sqlite_b, requests_b)
+
+ # ``raising=False`` is load-bearing rather than defensive: this test has to be
+ # runnable against the tree where no such bound exists, and the missing constant
+ # IS the defect. With ``raising=True`` the red would be a fixture error.
+ monkeypatch.setattr(
+ failure_notices, "NOTICE_DELIVERY_TIMEOUT_SECONDS", 0.05, raising=False
+ )
+
+ run_a = sqlite_a.list_owed_failure_notices()[0]
+ assert run_a["id"] == run_id
+
+ async def scenario() -> None:
+ armed_from = datetime.now(timezone.utc)
+ # The outer bound is what makes the red a clean failure instead of a hung
+ # pytest: against an unbounded await this pass never returns at all.
+ await asyncio.wait_for(service_a._deliver_one_failure_notice(sqlite_a, run_a), 5.0)
+
+ assert entered.is_set(), "the wedge must have reached the transport"
+ assert cancelled == ["A"], (
+ "a timed-out delivery must CANCEL its transport, not detach it to send "
+ f"later behind a replacement claimant: {cancelled}"
+ )
+
+ timed_out = dict(sqlite_a.owed_failure_notice(run_id))
+ assert timed_out["state"] == NOTICE_PENDING, (
+ f"a timed-out delivery must stay retryable, got {timed_out['state']}"
+ )
+ assert timed_out["attempts"] == 1, (
+ "the timeout must consume the claim's attempt rather than release it, or "
+ f"a permanently hanging transport never dead-letters: {timed_out}"
+ )
+ assert "timed out" in (timed_out["error"] or "").lower(), (
+ f"the stamped error must say what happened: {timed_out['error']!r}"
+ )
+ armed = datetime.fromisoformat(timed_out["next_attempt_at"])
+ delay = (armed - armed_from).total_seconds()
+ assert 2.0 <= delay <= 3.5, (
+ "a first failed attempt must arm the declared FIRST backoff interval "
+ f"(2 s), got {delay:.2f}s"
+ )
+
+ # Durably retryable by a DIFFERENT owner on its own connection. The armed
+ # backoff is rewound rather than slept through, exactly as the raising-rung
+ # and dead-claimant tests elapse theirs.
+ sqlite_b.update_owed_failure_notice(run_id, next_attempt_at=None)
+ owed = sqlite_b.list_owed_failure_notices()
+ assert [item["id"] for item in owed] == [run_id], (
+ f"a timed-out claim must return the row to the eligible set: {owed}"
+ )
+ await service_b._deliver_one_failure_notice(sqlite_b, owed[0])
+
+ asyncio.run(scenario())
+
+ assert [entry[0] for entry in sends] == ["B"], (
+ f"one owed notice may produce one completed send, by the survivor: {sends}"
+ )
+ rows = _persisted_messages()
+ assert [row["type"] for row in rows] == ["notify"]
+ notice = sqlite_a.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_SENT
+ assert notice["attempts"] == 2, (
+ "the recovered delivery must consume its own attempt, not the wedged one's: "
+ f"{notice}"
+ )
+
+
+def test_a_wedged_notice_delivery_does_not_stall_the_store_watch(tmp_path: Path) -> None:
+ """HFR-076, subordinate — the drain may not be on the serial watch's critical path.
+
+ ``_watch_store`` is ONE coroutine doing every periodic pass in sequence, and it
+ awaited ``_drain_failure_notices`` inline. A single notice whose delivery does not
+ return therefore stops the entire tick: request draining, callbacks, vault
+ callbacks, the stale-run sweep, and — the recursive part — every LATER notice,
+ including the ones that would have reported the failures this wedge is a symptom
+ of. The service stays "healthy" the whole time, because the loop is not crashed,
+ it is suspended.
+
+ A per-notice deadline alone does not fix this: it bounds the stall at the deadline
+ instead of removing it, and a deadline long enough to be safe for a legitimate
+ ladder walk is far too long to hold the tick. So the drain is DISPATCHED from the
+ watch rather than awaited by it, and the deadline bounds the dispatched work.
+
+ Single-flight is asserted alongside liveness, because the cheap version of this
+ fix — spawn a task every tick — trades a stalled loop for a notice delivered once
+ per 2 s tick. One entry into the transport across several ticks is the property.
+
+ The watch is driven for real; only the periodic passes that are not the subject
+ are stubbed, and the sweep and vault passes are counted because they sit AFTER the
+ notice drain in the tick and so are exactly what a wedge starves.
+ """
+
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ _owed_slack_notice(sqlite, requests, "task-watch-wedge")
+
+ entries: list[str] = []
+ entered = asyncio.Event()
+ never_returns = asyncio.Event()
+
+ from tests.test_message_dispatcher_scheduled import _StubIMClient
+
+ class _WedgedIMClient(_StubIMClient):
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ entries.append(context.channel_id)
+ entered.set()
+ await never_returns.wait()
+ return "slack-msg" # pragma: no cover
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ controller.im_client = _WedgedIMClient()
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ counts = {"sweeps": 0, "vault": 0}
+ ticked = asyncio.Event()
+
+ def _sweep() -> None:
+ counts["sweeps"] += 1
+ if counts["sweeps"] >= 2 and counts["vault"] >= 2:
+ ticked.set()
+
+ async def _vault() -> None:
+ counts["vault"] += 1
+
+ async def _recovered_outputs() -> None:
+ return None
+
+ service._running = True
+ service._notice_drain_task = None
+ service._drain_recovered_activity_outputs = _recovered_outputs
+ # Held steady so the tick's conditional half (reconcile, request/callback drains)
+ # stays out of the way: the subject is the UNCONDITIONAL passes after the drain.
+ service.store.maybe_reload = lambda: False
+ service.request_store.maybe_reload = lambda: False
+ service._drain_vault_callbacks = _vault
+ service._sweep_stale_runs = _sweep
+
+ async def scenario() -> None:
+ watch = asyncio.create_task(service._watch_store())
+ try:
+ await asyncio.wait_for(entered.wait(), timeout=5.0)
+ # Two ticks is one real 2 s sleep. The generous bound is for a loaded
+ # machine, not for the behaviour: against an inline await this never
+ # advances at all.
+ await asyncio.wait_for(ticked.wait(), timeout=15.0)
+ assert not never_returns.is_set(), (
+ "the point is that the watch advanced while the delivery was STILL wedged"
+ )
+ assert entries == ["C123"], (
+ "the wedged notice must be delivered once, not re-dispatched every "
+ f"tick: {entries}"
+ )
+ finally:
+ service._running = False
+ watch.cancel()
+ drain = service._notice_drain_task
+ if drain is not None:
+ drain.cancel()
+ for task in (watch, drain):
+ if task is None:
+ continue
+ try:
+ await task
+ except (asyncio.CancelledError, Exception):
+ pass
+
+ asyncio.run(scenario())
+
+ assert counts["sweeps"] >= 2 and counts["vault"] >= 2, (
+ "a wedged notice delivery must not stop the store watch's later passes: "
+ f"{counts}"
+ )
+
+
+def _workbench_session(
+ session_id: str,
+ *,
+ project: str,
+ status: str = "active",
+ visibility: str = "foreground",
+) -> str:
+ """One avibe project scope + one session row, in the MIGRATED WORKBENCH DB.
+
+ Two databases are in play in every drain test and they are NOT the same file.
+ The run/notice store is its own sqlite under ``tmp_path`` (``_store``), while
+ ``resolve_session_id_target`` reads ``paths.get_sqlite_state_path()`` and
+ ``persist_agent_message`` writes through ``get_cached_sqlite_engine()``. An
+ avibe rung resolves and persists ONLY from the latter, so a session row written
+ into the ``_store`` DB leaves rungs (2) and (5) silently unusable — and a test
+ built that way passes or fails for the wrong reason.
+
+ Returns the ``scopes.id`` the persisted row must be keyed to.
+ """
+
+ from storage.db import get_cached_sqlite_engine
+ from storage.models import agent_sessions
+ from storage.settings_service import upsert_scope
+
+ _migrated_state_db()
+ now = "2026-07-01T00:00:00+00:00"
+ with get_cached_sqlite_engine().begin() as conn:
+ scope_id = upsert_scope(conn, "avibe", "project", project, now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_name="codex",
+ agent_variant="default",
+ session_anchor=f"avibe_{project}:{session_id}",
+ native_session_id=f"native-{session_id}",
+ status=status,
+ visibility=visibility,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return scope_id
+
+
+def _no_background_web_push(monkeypatch) -> list[dict]:
+ """Keep the Web Push fan-out off the DAEMON THREAD, on the calling thread's DB.
+
+ Persisting an avibe inbox row schedules ``_send_to_enabled_subscriptions`` on a
+ daemon thread that sleeps ``WEB_PUSH_NOTIFICATION_DELAY_SECONDS`` and only then
+ opens its own connection — long after the test's isolated home is gone, so it
+ raises ``no such table: messages`` into an unhandled-thread warning attributable
+ to no test. Scheduling is still exercised; only the delayed send is stubbed.
+
+ Returns the payloads that WOULD have been pushed.
+ """
+
+ import core.web_push_notifications as web_push_notifications
+
+ pushed: list[dict] = []
+ monkeypatch.setattr(
+ web_push_notifications, "_send_to_enabled_subscriptions", pushed.append
+ )
+ return pushed
+
+
+def test_a_workbench_addressed_notice_lands_as_a_durable_inbox_row(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-079 — the workbench rungs of D5's ladder were never reachable at all.
+
+ ``_failure_notice_targets._add`` parsed EVERY rung with ``parse_session_key``,
+ which rejects any scope type outside ``{channel, user}``. Every avibe rung is
+ ``avibe::project::…``: rung (2) for any workbench-bound session (
+ ``resolve_session_id_target`` returns a ``project`` scope for one), rung (3) for
+ a workbench-created definition, and rung (5) always. ``_add`` swallowed the
+ ``ValueError`` and returned, so for an Avibe-only definition the ENTIRE ladder
+ was empty and its notice could only ever dead-letter.
+
+ Driven through the real drain against the real workbench DB, because the payoff
+ is the durable row: the workbench notice is delivered by being PERSISTED (the
+ inbox reads rows, and an SSE fan-out with no browser attached reaches nobody),
+ so "one visible avibe rung" and "one ``messages`` row the user can read back
+ later" are the same claim.
+
+ The REPLAY guard is asserted here too, not only in
+ ``test_a_replayed_notice_reaches_the_user_without_touching_the_live_lifecycle``.
+ That test pins it for rung (1), a Slack channel; a project rung reaches the
+ dispatcher on the one platform where a terminal ``result`` also drives the
+ workbench sidebar dot and the SSE turn stream, so "the drain never enters the
+ live ``emit_backend_failure`` lifecycle" is a distinct claim on this path rather
+ than a restatement of that one.
+ """
+
+ import core.backend_failure as backend_failure_module
+ import core.scheduled_tasks as scheduled_tasks
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ pushed = _no_background_web_push(monkeypatch)
+ controller, _dispatcher, touched = _live_turn_dispatcher()
+ controller.agent_auth_service = _ForbiddenAuthService()
+ scope_id = _workbench_session("sesWork", project="proj-notice")
+
+ async def _forbidden_live_emit(*args, **kwargs):
+ raise AssertionError("the drain called the LIVE backend-failure emitter")
+
+ # Snapshot BEFORE patching: ``raising=False`` below CREATES the attribute, which
+ # would make the structural check below trivially true forever after.
+ drain_imports_live_emitter = hasattr(scheduled_tasks, "emit_backend_failure")
+
+ # Both spellings — patching only the definition leaves the drain's own
+ # module-level reference, the one it would actually call, untouched.
+ monkeypatch.setattr(backend_failure_module, "emit_backend_failure", _forbidden_live_emit)
+ monkeypatch.setattr(
+ scheduled_tasks, "emit_backend_failure", _forbidden_live_emit, raising=False
+ )
+
+ sqlite, requests = _store(tmp_path)
+ # No delivery key and no caller provenance: rungs (1), (3) and (4) are empty by
+ # construction, so only the workbench-addressed rungs can carry this notice.
+ _task(sqlite, "task-workbench", name="nightly report", session_id="sesWork")
+ run = requests.enqueue_task_run("task-workbench")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-workbench")
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ emissions = _spy_emissions(controller)
+
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [target.to_key() for target, _ in rungs] == [
+ "avibe::project::proj-notice",
+ "avibe::project::sesWork",
+ # The mandatory workspace rung, appended after every person/context target
+ # (round-14 gate). It is present on every ladder and is NOT what delivers here:
+ # rung (2) resolves a live scope and acks first, which the single persisted row
+ # below is the proof of.
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ ], f"a project-scoped rung must survive parsing: {rungs}"
+
+ asyncio.run(service._drain_failure_notices())
+
+ # --- the replay guard, on the workbench path -----------------------------
+ assert [item["type"] for item in emissions] == ["notify"], (
+ f"a workbench notice must be exactly one visible notify and nothing else: {emissions}"
+ )
+ output = emissions[0]["output"]
+ assert output.completes_turn is False and output.settles_run is False, (
+ "a receipt about an already-terminal run may not settle a turn or a run"
+ )
+ assert touched == [], f"the workbench replay mutated live turn state: {touched}"
+ assert not drain_imports_live_emitter, (
+ "the drain must not so much as import the live failure emitter"
+ )
+
+ rows = _persisted_messages()
+ assert [(row["platform"], row["type"]) for row in rows] == [("avibe", "notify")], (
+ f"the workbench notice must exist as one durable row: {rows}"
+ )
+ assert rows[0]["scope_id"] == scope_id, "the row must land in the session's project scope"
+ assert rows[0]["session_id"] == "sesWork"
+ assert rows[0]["content_text"], "an empty notice is not a notice"
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == NOTICE_SENT
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT, (
+ "a workbench rung may only ack on the persisted receipt"
+ )
+ assert notice["attempts"] == 1
+
+ # The row is inbox-visible, so it is also push-notifiable — the notice reaches a
+ # user who is not looking at the tab, not just the transcript.
+ assert [payload["session_id"] for payload in pushed] == ["sesWork"], (
+ f"the workbench notice must be pushed, not only stored: {pushed}"
+ )
+
+
+def test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-079 — the trap a bare parser swap walks straight into.
+
+ ``AvibeBot.send_message`` mints and returns a synthetic ``msg_<hex>`` id
+ unconditionally — with no SSE subscriber, and whether or not anything was
+ persisted. The dispatcher records that as ``delivered_id``, and
+ ``DeliveryEvidence.delivered`` is true on ``delivered_id`` ALONE
+ (``delivery_only``). So merely admitting project rungs into the ladder would
+ convert today's visible dead letter into a permanent, FALSE ``sent`` for any
+ avibe rung that persisted nothing: ``persist_agent_message``'s avibe branch
+ returns before writing when it can resolve neither a scope nor a session row.
+
+ The worst shape of that is a definition whose bound Session row has been
+ DELETED, which is what this drives. Rung (5) is still BUILT — it is keyed on the
+ run's session id, not on the row's existence — so it addresses a project
+ candidate that resolves to nothing: ``AvibeBot.send_message`` still returns an
+ id, ``persist_agent_message`` still returns before writing, and an ack on that
+ id would mark the notice ``sent`` forever with no row, no push and no dead
+ letter. That is strictly worse than the gap the drain exists to close.
+
+ Two phases, because "does not ack" is only half a contract. A rung that must not
+ acknowledge must also not CONSUME the notice:
+
+ * pass 1 — a stale project candidate on every rung. Both rungs send, neither
+ persists, so nothing acks: the notice stays ``pending``, records no
+ ``ack_evidence``, and carries the reason a receipt was missing.
+ * pass 2 — the same notice, still owed, after the Session row exists again as an
+ ARCHIVED row. It now delivers and acks on a receipt, with the attempt count
+ carried forward from the pass that walked on — but the receipt is in the
+ WORKSPACE-NOTIFICATIONS session, not in the archived row.
+
+ THE MANDATORY WORKSPACE RUNG IS SUPPRESSED IN PASS 1, and that is deliberate
+ isolation rather than a workaround. Since the round-14 gate the ladder ends with a
+ workspace rung on EVERY attempt, so a pass 1 with it enabled would DELIVER — which
+ is correct product behaviour and would leave nothing to say about the synthetic send
+ id, the subject of this test. ``_workspace_notice_session_id`` returning ``None``
+ (the unwritable-workbench-DB path, pinned in its own right by
+ ``test_an_unwritable_workspace_inbox_still_dead_letters_visibly``) makes the walk
+ skip that rung, so pass 1 sees exactly the two stale project candidates and nothing
+ else. Pass 2 restores it, and what it then pins is the archived REROUTE.
+
+ DOCTRINE REVERSAL IN PASS 2 (round-13 P1, review thread 3676292667). This test
+ was written in round 9 to assert the opposite: that rung (5) delivers INTO the
+ archived row, on the premise that "an archived row is a valid delivery surface"
+ because ``_session_row`` has no status filter where rung (2)'s
+ ``resolve_session_id_target`` refuses an archived session outright. The mechanism
+ is real and still is; the premise was wrong. An archived row is WRITABLE but not
+ VISIBLE: the write happens, the receipt exists, so the workbench class's
+ receipt-only ack source marks the notice ``sent`` and it is never retried — while
+ ``list_inbox_sessions`` / ``get_inbox_session`` exclude archived sessions, so there
+ is no inbox card, no ``inbox.session.updated`` and no Web Push. That is the ack
+ source's blind spot, and it is blind precisely because the write is genuine, which
+ is why the check had to move UPSTREAM into the address (``_rung_five_session_id``).
+
+ Not healed, unlike the reserved workspace session's own archive
+ (``test_an_archived_workspace_notice_session_heals_instead_of_swallowing_the_notice``):
+ the user archived THIS session on purpose. So the notice is rerouted instead, and
+ what pass 2 now pins is that the surviving delta rung (5) buys over rung (2) is a
+ DELIVERY at all, not a delivery into that particular row.
+
+ Pass 1 also pins the per-rung evidence: one shared ``DeliveryEvidence`` latches
+ ``delivered`` true forever once any rung sets an id, so the first rejected rung
+ would both stop the walk and hand the eventual ack/dead letter another rung's
+ ``ack_evidence``.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.background import NOTICE_PENDING
+ from storage.db import get_cached_sqlite_engine
+ from storage.messages_service import get_inbox_session
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ # The schema, but deliberately NO session row for ``sesGone`` yet: the binding
+ # points at a session that has been deleted.
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-avibe-ack",
+ name="nightly report",
+ session_id="sesGone",
+ metadata={"created_by": {"caller": {"scope_id": "avibe::project::proj-gone"}}},
+ )
+ run = requests.enqueue_task_run("task-avibe-ack")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-avibe-ack")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [target.to_key() for target, _ in rungs] == [
+ "avibe::project::proj-gone",
+ "avibe::project::sesGone",
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ ], f"a deleted session loses rung (2) and still BUILDS rung (5): {rungs}"
+
+ # --- pass 1: nothing durable, so nothing acknowledges -------------------
+ #
+ # With the mandatory workspace rung SKIPPED (see the docstring), so the only rungs
+ # the walk can act on are the two stale project candidates this pass is about.
+ workspace_enabled = service._workspace_notice_session_id
+ service._workspace_notice_session_id = lambda: None
+ asyncio.run(service._drain_failure_notices())
+
+ channels = [channel for channel, _thread, _text in controller.im_client.sent]
+ assert channels == ["proj-gone", "sesGone"], (
+ "a synthetic send id must not end the walk; the next rung has to be tried: "
+ f"{channels}"
+ )
+ assert _persisted_messages() == [], (
+ "neither candidate resolves a scope or a session row, so nothing can persist"
+ )
+
+ notice = dict(sqlite.owed_failure_notice(run.id))
+ assert notice["state"] == NOTICE_PENDING, (
+ "a stale project candidate may not mark the notice sent: "
+ f"{notice['state']} / {notice.get('ack_evidence')}"
+ )
+ assert not notice.get("ack_evidence"), (
+ f"a synthetic send id is not an acknowledgement: {notice.get('ack_evidence')}"
+ )
+ assert notice["attempts"] == 1, "the pass consumed exactly one attempt"
+ assert "without a persisted receipt" in (notice["error"] or ""), (
+ f"the retry must say why the rung was refused, not 'no evidence': {notice['error']}"
+ )
+ # Still RETRYABLE rather than dead-lettered: a backoff instant, not a terminal state.
+ assert notice["next_attempt_at"], "a refused rung must leave the notice schedulable"
+
+ # --- pass 2: the same owed notice, REROUTED off the archived row ----------
+ service._workspace_notice_session_id = workspace_enabled
+ archived_scope_id = _workbench_session("sesGone", project="proj-live", status="archived")
+ # Let the backoff elapse without sleeping (the same rewind the retry tests use).
+ sqlite.update_owed_failure_notice(run.id, next_attempt_at=None)
+ assert [row["id"] for row in sqlite.list_owed_failure_notices(limit=10)] == [run.id], (
+ "the notice has to still be OWED for a later rung to be able to deliver it"
+ )
+
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [target.to_key() for target, _ in rungs] == [
+ "avibe::project::proj-gone",
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ ], (
+ "rung (5) must address a surface the user can SEE. The archived row is writable "
+ f"and invisible, so the candidate is the workspace inbox instead: {rungs}"
+ )
+ assert [target.to_key() for target, _ in rungs].count(
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}"
+ ) == 1, (
+ "and it collapses with the MANDATORY appended workspace rung rather than "
+ f"appearing twice — the reroute returns the same reserved id: {rungs}"
+ )
+
+ asyncio.run(service._drain_failure_notices())
+
+ rows = _persisted_messages()
+ assert [row["session_id"] for row in rows] == [WORKSPACE_NOTICE_SESSION_ID], (
+ "only the rung that persisted anything counts as delivered — and the row it "
+ f"persisted has to be one the inbox displays: {rows}"
+ )
+ assert rows[0]["scope_id"] != archived_scope_id, (
+ f"nothing may be written into the archived session's scope: {rows}"
+ )
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == NOTICE_SENT
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT, (
+ "the ack must carry the WINNING rung's evidence, not the rejected rung's"
+ )
+ assert notice["attempts"] == 2, (
+ "the attempt the refused pass consumed is carried forward, not reset"
+ )
+
+ # THE REVERSAL, asserted on the SURFACE rather than on the notice state, because the
+ # notice state is exactly where the old doctrine and the new one look identical: an
+ # ack into the archived row reads ``sent`` just the same.
+ with get_cached_sqlite_engine().begin() as conn:
+ assert get_inbox_session(conn, "sesGone") is None, (
+ "the premise of the reversal: an archived session shows no inbox card, so a "
+ "notice acked into it was never seen by anybody"
+ )
+ assert get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None, (
+ "and the session it was rerouted to does show one"
+ )
+
+
+def test_a_background_session_notice_is_rerouted_to_the_workspace_inbox(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A hidden bound session cannot acknowledge a user-visible failure notice."""
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.background import NOTICE_SENT
+ from storage.db import get_cached_sqlite_engine
+ from storage.messages_service import get_inbox_session
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _workbench_session(
+ "sesBackgroundNotice",
+ project="proj-background-notice",
+ visibility="background",
+ )
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-background-notice", session_id="sesBackgroundNotice")
+ run = requests.enqueue_task_run("task-background-notice")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(
+ claimed,
+ ok=False,
+ error="backend exploded",
+ task_id="task-background-notice",
+ )
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [(target.to_key(), session_id) for target, session_id in rungs] == [
+ (
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ WORKSPACE_NOTICE_SESSION_ID,
+ )
+ ], f"a background session must be omitted from both session-derived rungs: {rungs}"
+
+ asyncio.run(service._drain_failure_notices())
+
+ rows = _persisted_messages()
+ assert [row["session_id"] for row in rows] == [WORKSPACE_NOTICE_SESSION_ID], rows
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_SENT
+ with get_cached_sqlite_engine().begin() as conn:
+ assert get_inbox_session(conn, "sesBackgroundNotice") is None
+ assert get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+
+
+def _workspace_notice_session_rows() -> list[dict]:
+ """Every ``agent_sessions`` row holding the reserved workspace-notice identity."""
+
+ from sqlalchemy import select as sa_select
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.db import get_cached_sqlite_engine
+ from storage.models import agent_sessions
+
+ with get_cached_sqlite_engine().begin() as conn:
+ rows = conn.execute(
+ sa_select(agent_sessions).where(
+ agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID
+ )
+ ).mappings()
+ return [dict(row) for row in rows]
+
+
+def test_a_caller_less_cli_definition_still_delivers_its_failure_notice(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """D5 rung (5), owed by name at plan ``docs/plans/harness-run-reliability.md:3216``.
+
+ Subordinate coverage under §D5's rung-(5) requirement (plan :3193, :3215-3222);
+ no new scenario id this round — the §10.7 HFR-280…319 assignment is offered to
+ the maintainer as a follow-up.
+
+ THE EMPTINESS IS STRUCTURAL, not mocked. ``vibe task add`` typed at a terminal
+ reaches ``_definition_creation_metadata_from_caller(None)``, whose first line is
+ ``if caller_context is None: return {}`` — so there is no ``created_by``, hence no
+ rung (3) and no rung (4); no ``deliver_key``, hence no rung (1); and no session
+ binding, hence neither rung (2) nor the session-derived rung (5) candidate. The
+ test builds the definition's metadata by CALLING that helper rather than by
+ asserting a hand-written ``{}``, so the premise cannot drift away from the
+ product path it stands for.
+
+ Before this change every rung was empty and the notice could only dead-letter
+ (``_failure_notice_targets(run) == []``): a failure notice with nowhere to go is a
+ failure notice that is never written, which is D1 unmet for exactly the runs
+ nobody is watching. Rung (5) is now unconditional — a reserved
+ workspace-notifications session, resolved-or-created lazily, addressed as
+ ``avibe::project::<reserved session id>``.
+
+ Asserted at the CONSUMING end, because "the ladder was walked" is not delivery:
+ the notice has to exist as one durable ``messages`` row in that session, be
+ inbox-readable, be push-notifiable, and ack on the persisted receipt (the
+ workbench target class may not ack on ``AvibeBot``'s synthetic send id — see
+ ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``).
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from vibe.cli import _definition_creation_metadata_from_caller
+
+ pushed = _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ # The real workbench schema, and deliberately NO session row and NO project
+ # scope of any kind: the workspace session must be created by the notice path.
+ _migrated_state_db()
+ assert _workspace_notice_session_rows() == [], (
+ "the reserved session must not pre-exist; the drain is what creates it"
+ )
+
+ sqlite, requests = _store(tmp_path)
+ caller_metadata = _definition_creation_metadata_from_caller(None)
+ assert caller_metadata == {}, (
+ "the premise: a plain CLI invocation records no caller provenance at all"
+ )
+ _task(sqlite, "task-cli-only", name="nightly report", metadata=caller_metadata)
+ run = requests.enqueue_task_run("task-cli-only")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-cli-only")
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ # The REAL translator: the claim is about copy a user reads back out of the inbox,
+ # so a ``_t`` that echoes keys would assert the wrong thing on both the notice body
+ # and the workspace session's name.
+ from core.scheduled_tasks import ScheduledTaskService
+
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [target.to_key() for target, _ in rungs] == [
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}"
+ ], f"rung (5) must resolve for a definition with no caller and no session: {rungs}"
+ assert [session_id for _target, session_id in rungs] == [WORKSPACE_NOTICE_SESSION_ID], (
+ "the rung has to carry the session id, or ``persist_agent_message`` has no row "
+ "to resolve the message against"
+ )
+
+ asyncio.run(service._drain_failure_notices())
+
+ rows = _persisted_messages()
+ assert [(row["platform"], row["type"], row["session_id"]) for row in rows] == [
+ ("avibe", "notify", WORKSPACE_NOTICE_SESSION_ID)
+ ], f"the notice must land as exactly one durable row in the workspace session: {rows}"
+ assert rows[0]["content_text"], "an empty notice is not a notice"
+ assert "nightly report" in rows[0]["content_text"], (
+ f"and it must name what failed: {rows[0]['content_text']!r}"
+ )
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == NOTICE_SENT
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT, (
+ "the workbench class acks on the persisted receipt, never on a send id"
+ )
+ assert notice["attempts"] == 1, "one rung, one attempt — no retry, no dead letter"
+
+ # READABLE, not merely stored: the inbox feed is the surface D5 promises, and it
+ # filters on ``visibility = 'foreground'`` — so a session hidden by that flag
+ # would store the row and show the user nothing.
+ from storage.db import get_cached_sqlite_engine
+ from storage.messages_service import get_inbox_session
+
+ with get_cached_sqlite_engine().begin() as conn:
+ card = get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID)
+ assert card is not None, "the workspace notice must be an inbox-readable card"
+ assert "nightly report" in str(card["preview_text"]), (
+ f"the card must preview the notice a user has to read: {card}"
+ )
+ # A CLEAR name rather than a bare reserved id: the row is a ``system`` surface
+ # hidden from ordinary session lists, but its inbox card still leads with the
+ # title, so an unnamed card would read as a bug.
+ assert str(card["title"] or "").strip(), f"the workspace session must be named: {card}"
+
+ # And push-notifiable, so it reaches a user who is not looking at the tab.
+ assert [payload["session_id"] for payload in pushed] == [WORKSPACE_NOTICE_SESSION_ID], (
+ f"the workspace notice must be pushed, not only stored: {pushed}"
+ )
+
+
+def test_workspace_notification_session_is_created_once_and_reused(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The second owed test at plan ``docs/plans/harness-run-reliability.md:3222``.
+
+ Subordinate coverage under §D5's rung-(5) requirement (plan :3193, :3215-3222);
+ no new scenario id this round — the §10.7 HFR-280…319 assignment is offered to
+ the maintainer as a follow-up.
+
+ Rung (5) resolves-or-CREATES, so the identity has to do the deduplication. Two
+ caller-less definitions fail and are drained in two separate passes; exactly ONE
+ ``agent_sessions`` row may exist afterwards and BOTH notices must land in it.
+
+ Idempotence rests on the PRIMARY KEY, not on a marker search: the reserved id is
+ spelled outside ``SESSION_ID_ALPHABET`` (which has no ``-``), so
+ ``new_session_id`` can never mint it and the reserved row cannot collide with an
+ ordinary session. The create re-decides under SQLite's write lock
+ (``reserve_write_lock``), which is the same answer ``get_or_create_agent_session_row``
+ already gives the first-turn INSERT — so two drain owners racing the creation
+ produce one row, not an ``IntegrityError``.
+
+ DURABILITY BY RECREATION, deliberately, rather than by exempting the row from
+ ``/new`` clears and eviction: nothing here asks the session-clear or reclaim
+ machinery for a special case. The third phase deletes the row outright and drains
+ a third failure — the next notice simply recreates it, which is why an exemption
+ is not needed at all.
+ """
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.db import get_cached_sqlite_engine
+ from storage.models import agent_sessions
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ def _fail(definition_id: str) -> str:
+ _task(sqlite, definition_id, name=definition_id)
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="boom", task_id=definition_id)
+ return run.id
+
+ first = _fail("task-cli-a")
+ asyncio.run(service._drain_failure_notices())
+ created_at = _workspace_notice_session_rows()[0]["created_at"]
+
+ second = _fail("task-cli-b")
+ asyncio.run(service._drain_failure_notices())
+
+ rows = _workspace_notice_session_rows()
+ assert len(rows) == 1, f"the reserved session must be created once, not per notice: {rows}"
+ assert rows[0]["created_at"] == created_at, (
+ "the second notice must REUSE the row, not replace it"
+ )
+
+ messages = _persisted_messages()
+ assert [row["session_id"] for row in messages] == [
+ WORKSPACE_NOTICE_SESSION_ID,
+ WORKSPACE_NOTICE_SESSION_ID,
+ ], f"both notices must land in the one workspace session: {messages}"
+ for run_id in (first, second):
+ assert sqlite.owed_failure_notice(run_id)["state"] == NOTICE_SENT
+
+ # --- durability by recreation, not by exemption -------------------------
+ with get_cached_sqlite_engine().begin() as conn:
+ conn.execute(
+ agent_sessions.delete().where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ )
+ assert _workspace_notice_session_rows() == []
+
+ third = _fail("task-cli-c")
+ asyncio.run(service._drain_failure_notices())
+
+ assert len(_workspace_notice_session_rows()) == 1, (
+ "a cleared workspace session is recreated by the next notice"
+ )
+ assert sqlite.owed_failure_notice(third)["state"] == NOTICE_SENT, (
+ "so a clear cannot make a later notice unsendable"
+ )
+
+
+def test_an_archived_workspace_notice_session_heals_instead_of_swallowing_the_notice(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The one state "lazy recreation" does NOT cover, and it fails SILENTLY.
+
+ Recreation is keyed on the row being GONE. An archive leaves the reserved primary
+ key in place, so nothing recreates — and every downstream half of the delivery
+ disagrees about what archived means:
+
+ * ``persist_agent_message`` resolves the session through ``_session_row``, which has
+ NO status filter, so the message still persists;
+ * a persisted row is the workbench class's ack source, so the rung ACKS and the
+ notice is stamped ``sent``;
+ * but ``list_inbox_sessions`` / ``get_inbox_session`` exclude archived sessions, so
+ there is no card, no ``inbox.session.updated`` and no Web Push.
+
+ So every later caller-less failure is recorded as DELIVERED into a surface nothing
+ displays — strictly worse than the dead letter this branch replaced, because a dead
+ letter at least says so. Asserted on the INBOX SURFACE rather than on the notice
+ state, which is exactly where the two disagree.
+
+ The heal runs under the same ``reserve_write_lock`` re-read as the create, so it
+ also repairs a row archived before the ``archive_session`` guard existed. The
+ archive here is driven by DIRECT SQL on purpose: the guard
+ (``tests/test_session_archive.py::test_the_reserved_workspace_notice_session_cannot_be_archived``)
+ now refuses the ordinary path, and a test that could only reach this state through a
+ door that is closed would prove nothing about a database that is already in it.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.agent_session_rows import (
+ WORKSPACE_NOTICE_SESSION_ANCHOR,
+ WORKSPACE_NOTICE_SESSION_ID,
+ )
+ from storage.db import get_cached_sqlite_engine
+ from storage.messages_service import get_inbox_session
+ from storage.models import agent_sessions
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ def _fail(definition_id: str) -> str:
+ _task(sqlite, definition_id, name=definition_id)
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="boom", task_id=definition_id)
+ return run.id
+
+ _fail("task-heal-a")
+ asyncio.run(service._drain_failure_notices())
+ with get_cached_sqlite_engine().begin() as conn:
+ assert get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+
+ # --- the state the guard now forbids, reached out of band -----------------
+ with get_cached_sqlite_engine().begin() as conn:
+ conn.execute(
+ sa_update(agent_sessions)
+ .where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ .values(
+ status="archived",
+ # ``archive_session`` vacates the thread anchor too, so the heal has to
+ # restore that as well or the row keeps an anchor nothing resolves.
+ session_anchor=f"archived:{WORKSPACE_NOTICE_SESSION_ID}",
+ )
+ )
+ with get_cached_sqlite_engine().begin() as conn:
+ assert get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is None, (
+ "the premise: an archived session shows no inbox card"
+ )
+
+ second = _fail("task-heal-b")
+ asyncio.run(service._drain_failure_notices())
+
+ with get_cached_sqlite_engine().begin() as conn:
+ row = dict(
+ conn.execute(
+ select(agent_sessions).where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ ).mappings().first()
+ )
+ card = get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID)
+
+ # THE DEFECT, asserted in the order it happens. The notice acks either way — that
+ # is what makes the failure silent — so the ack is checked FIRST and then the
+ # surface it claims to have reached. On the unhealed code the ack passes and the
+ # card is ``None``.
+ assert sqlite.owed_failure_notice(second)["state"] == NOTICE_SENT, (
+ "the premise: this rung acks on the persisted row, archived or not"
+ )
+ assert card is not None, (
+ "an acked notice with no inbox card is worse than the dead letter this "
+ "branch replaced — a dead letter at least says so"
+ )
+ assert row["status"] == "active", f"the notice must heal the row it needs: {row}"
+ assert row["session_anchor"] == WORKSPACE_NOTICE_SESSION_ANCHOR, (
+ f"including the reserved anchor the archive vacated: {row}"
+ )
+ assert row["visibility"] == "system", (
+ "and the system visibility the inbox feed admits while ordinary session "
+ f"lists exclude: {row}"
+ )
+ assert [row["session_id"] for row in _persisted_messages()] == [
+ WORKSPACE_NOTICE_SESSION_ID,
+ WORKSPACE_NOTICE_SESSION_ID,
+ ]
+ assert len(_workspace_notice_session_rows()) == 1, (
+ "healing repairs the reserved row; it never mints a second one"
+ )
+
+
+def test_an_archived_ordinary_session_is_rerouted_instead_of_acked_into(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-079, subordinate — the SAME hole for an ordinary session, opposite remedy.
+
+ Round-13 P1, review thread 3676292667: "an archived-session receipt is acked as
+ delivery but is invisible". The heal above closes this for the RESERVED workspace
+ session; a run pinned to an ordinary session that its owner later archived reaches
+ the identical disagreement by a different door — ``persist_agent_message`` resolves
+ through ``_session_row`` (no status filter) and writes, the receipt is the workbench
+ class's ack source so the notice is stamped ``sent`` and never retried, and
+ ``list_inbox_sessions`` / ``get_inbox_session`` exclude archived sessions so no card,
+ no realtime patch and no push is produced.
+
+ WHY THIS ONE IS NOT HEALED. The reserved row may not be archived at all
+ (``archive_session`` refuses its id), so an archived one is corruption and repairing
+ it restores an invariant. An ordinary session was archived by its owner ON PURPOSE.
+ Un-archiving it to deliver a failure notice would overrule that decision and
+ resurface the whole session, not the notice. The session is not broken; the ADDRESS
+ is. So the fix is routing (``_rung_five_session_id``), and this test asserts routing
+ — the candidate itself, before any send — rather than a repaired row.
+
+ Nor is the ack policy the place to fix it. The receipt-only source is the right
+ measurement for a MISSING row (nothing persists, so nothing acks — see
+ ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id`` pass 1) and it is blind
+ here precisely because the write is genuine.
+
+ RED ON THE PRE-FIX HEAD, in the order the failure happens: the notice acks ``sent``
+ with its receipt inside the archived session and the inbox shows nothing. The ack is
+ therefore asserted FIRST — it passes either way, which is what makes the bug silent
+ — and then the surface it claims to have reached.
+
+ Deliberately a SESSION-ONLY definition: no ``deliver_key`` and no ``created_by``, so
+ rungs (1), (3) and (4) are empty and rung (5) is the only rung. A definition with a
+ live preferred rung would let that rung win the walk and prove nothing about which
+ session rung (5) named.
+
+ WHAT THE MANDATORY WORKSPACE RUNG DOES AND DOES NOT ACCOUNT FOR HERE. Since the
+ round-14 gate every ladder ends with a workspace rung, so "the notice reached the
+ workspace inbox" no longer distinguishes routing from fallback on its own. The claim
+ this test carries is therefore the NEGATIVE one, asserted on the ladder before any
+ send: ``avibe::project::sesArchived`` is ABSENT. Without the reroute it would be
+ there and would be walked FIRST, persist into the archived row, and ack — so the
+ appended rung would never be reached and the notice would be invisible. The ladder
+ assertion below is what separates the two mechanisms; ``…_holds_exactly_one_workspace_rung``
+ pins that they collapse into one rung rather than two.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.db import get_cached_sqlite_engine
+ from storage.messages_service import get_inbox_session
+ from storage.models import agent_sessions
+
+ pushed = _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ archived_scope_id = _workbench_session(
+ "sesArchived", project="proj-archived", status="archived"
+ )
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-archived", name="nightly report", session_id="sesArchived")
+ run = requests.enqueue_task_run("task-archived")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-archived")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ # --- the routing decision, asserted before anything is sent --------------
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+ assert [target.to_key() for target, _ in rungs] == [
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}"
+ ], (
+ "rung (2) refuses an archived session, and rung (5) must not quietly deliver "
+ f"into it either — the only visible surface left is the workspace inbox: {rungs}"
+ )
+ assert [session_id for _target, session_id in rungs] == [WORKSPACE_NOTICE_SESSION_ID], (
+ f"the session the context is built with has to be rerouted too: {rungs}"
+ )
+
+ asyncio.run(service._drain_failure_notices())
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == NOTICE_SENT, (
+ f"the premise: this rung acks on a persisted receipt either way: {notice}"
+ )
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT
+ assert notice["attempts"] == 1, "one visible delivery, on the first attempt"
+
+ rows = _persisted_messages()
+ assert [(row["platform"], row["type"], row["session_id"]) for row in rows] == [
+ ("avibe", "notify", WORKSPACE_NOTICE_SESSION_ID)
+ ], f"one notice, in the session the inbox displays: {rows}"
+ assert rows[0]["scope_id"] != archived_scope_id, (
+ f"and nothing at all in the archived session's scope: {rows}"
+ )
+ assert str(rows[0]["content_text"] or "").strip(), f"an empty notice is not a notice: {rows}"
+ assert f'"failure_id": "{run.id}"' in str(rows[0]["metadata_json"] or ""), (
+ "and it is still THIS run's notice — rerouting changes the address, never the "
+ f"identity the live path's dedup looks up: {rows}"
+ )
+
+ with get_cached_sqlite_engine().begin() as conn:
+ assert get_inbox_session(conn, "sesArchived") is None, (
+ "the premise of the finding: an archived session has no inbox card, so an "
+ "acked notice inside it is invisible and — being acked — never retried"
+ )
+ card = get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID)
+ assert card is not None, "the rerouted notice must produce a card a user can see"
+
+ # And the push fan-out, which is the surface for a user who is not looking at the
+ # tab — the third thing the archived row silently withheld.
+ assert [payload["session_id"] for payload in pushed] == [WORKSPACE_NOTICE_SESSION_ID], (
+ f"the rerouted notice must be pushed, not only stored: {pushed}"
+ )
+
+ # The archived session is left exactly as its owner left it. This is the line that
+ # separates this remedy from the reserved session's heal.
+ with get_cached_sqlite_engine().begin() as conn:
+ status = conn.execute(
+ select(agent_sessions.c.status).where(agent_sessions.c.id == "sesArchived")
+ ).scalar_one_or_none()
+ assert status == "archived", (
+ "delivering a failure notice may not un-archive a session the user archived on "
+ f"purpose: {status}"
+ )
+
+
+def test_every_ladder_target_class_declares_its_acknowledgement_source() -> None:
+ """HFR-079 — a ladder target may not inherit an acknowledgement by accident.
+
+ The three findings in this class were all the same shape: a target whose
+ acknowledgement source nobody had decided, silently answered by whichever
+ branch the predicate happened to fall through to. Fixing them one platform at a
+ time leaves the NEXT target — a new platform kind, a new scope type, a new rung
+ — to rediscover the trap, and the failure mode is invisible: an undeclared
+ target that acks on a send id turns a visible dead letter into a permanent false
+ ``sent``.
+
+ So the policy is a TABLE (``LADDER_ACK_SOURCES``) keyed by target class, and
+ this test asserts the table is total over what the ladder can produce. Both axes
+ are read out of the code that produces them and never listed here — that is the
+ whole point:
+
+ * the platform-kind axis from ``PLATFORM_REGISTRY``, whose ``kind`` field is the
+ structural distinction between a real IM transport and the workbench, plus the
+ one kind the registry cannot supply — an unregistered platform, which a
+ free-string ``deliver_key`` makes reachable;
+ * the scope-type axis from the two parsers ``_add`` builds every rung with,
+ driven here so the constants are proven to be what the parsers enforce rather
+ than a second copy of it.
+
+ Add a platform kind or a scope type without declaring its acknowledgement
+ source and this fails. At RUNTIME the same omission is safe rather than
+ permissive — the lookup falls back to the receipt — but silent, which is why the
+ enumeration is checked here.
+ """
+
+ from config.platform_registry import PLATFORM_REGISTRY
+ from core.scheduled_tasks import (
+ ACK_EVIDENCE_BY_ACK_SOURCE,
+ ACK_SOURCE_NATIVE_DELIVERY_ID,
+ ACK_SOURCE_PERSISTED_RECEIPT,
+ LADDER_ACK_SOURCES,
+ LADDER_PLATFORM_KIND_UNREGISTERED,
+ LADDER_SCOPE_TYPES,
+ SCOPE_ID_SCOPE_TYPES,
+ SESSION_KEY_SCOPE_TYPES,
+ UNDECLARED_LADDER_ACK_SOURCE,
+ ParsedSessionKey,
+ failure_notice_ack_source,
+ failure_notice_target_class,
+ parse_scope_id,
+ parse_session_key,
+ )
+
+ # --- axis 1: the scope types, proven against the parsers themselves -----
+ for scope_type in SESSION_KEY_SCOPE_TYPES:
+ assert parse_session_key(f"slack::{scope_type}::X").scope_type == scope_type
+ for scope_type in SCOPE_ID_SCOPE_TYPES:
+ assert parse_scope_id(f"slack::{scope_type}::X").scope_type == scope_type
+ scope_types = SESSION_KEY_SCOPE_TYPES | SCOPE_ID_SCOPE_TYPES
+ assert scope_types == LADDER_SCOPE_TYPES
+
+ # A scope type outside that vocabulary cannot reach the ladder at all: both
+ # parsers refuse it, so ``_add`` drops the rung rather than handing the policy a
+ # class it has never heard of. This is what bounds the axis to the union above.
+ for parser in (parse_session_key, parse_scope_id):
+ with pytest.raises(ValueError):
+ parser("slack::not-a-scope-type::W1")
+
+ # --- axis 2: the platform kinds, from the registry ----------------------
+ registered_kinds = {descriptor.kind for descriptor in PLATFORM_REGISTRY.values()}
+ assert registered_kinds, "the registry is the platform-kind axis; an empty one proves nothing"
+ platform_kinds = registered_kinds | {LADDER_PLATFORM_KIND_UNREGISTERED}
+ assert LADDER_PLATFORM_KIND_UNREGISTERED not in registered_kinds, (
+ "the unregistered kind must stay distinct from every registered one"
+ )
+
+ # --- the table is total over the product of the two ---------------------
+ declared = set(LADDER_ACK_SOURCES)
+ expected = {(kind, scope_type) for kind in platform_kinds for scope_type in scope_types}
+ assert declared == expected, (
+ "every (platform kind, scope type) the ladder can produce must declare its "
+ f"acknowledgement source: missing {sorted(expected - declared)}, "
+ f"stale {sorted(declared - expected)}"
+ )
+
+ # ...and the classifier's whole RANGE is inside that domain — every registered
+ # platform AND an unregistered one — so no target the ladder can build today
+ # resolves by fallback. The fallback stays load-bearing for the case this test
+ # is here to catch: a scope type added to a parser without a row.
+ for platform in list(PLATFORM_REGISTRY) + ["brandnew"]:
+ for scope_type in scope_types:
+ target = ParsedSessionKey(platform=platform, scope_type=scope_type, scope_id="X")
+ assert failure_notice_target_class(target) in LADDER_ACK_SOURCES, (
+ f"{target.to_key()} resolves by fallback rather than by declaration"
+ )
+
+ # --- every source is interpretable, and the undeclared one is the SAFE one ---
+ for source in set(LADDER_ACK_SOURCES.values()) | {UNDECLARED_LADDER_ACK_SOURCE}:
+ assert source in ACK_EVIDENCE_BY_ACK_SOURCE, (
+ f"acknowledgement source {source!r} admits no stated evidence"
+ )
+ assert UNDECLARED_LADDER_ACK_SOURCE == ACK_SOURCE_PERSISTED_RECEIPT, (
+ "an undeclared target must default to the STRICTER source, never the permissive one"
+ )
+ # An unregistered platform takes the same strict answer, through its declared
+ # row: a deliver key can name any platform string, and ``parse_session_key`` does
+ # not check it against the registry.
+ assert (
+ failure_notice_ack_source(parse_session_key("brandnew::channel::C1"))
+ == ACK_SOURCE_PERSISTED_RECEIPT
+ )
+ # The two named classes, spot-checked at the call site's own granularity so the
+ # table cannot be reshuffled without one of these moving.
+ assert (
+ failure_notice_ack_source(parse_session_key("slack::channel::C1"))
+ == ACK_SOURCE_NATIVE_DELIVERY_ID
+ )
+ assert (
+ failure_notice_ack_source(parse_scope_id("avibe::project::proj-1"))
+ == ACK_SOURCE_PERSISTED_RECEIPT
+ )
+
+
+def test_every_registry_platform_declares_its_kind_explicitly() -> None:
+ """Subordinate to HFR-075/079 — the ack policy's permissive row rests on a default.
+
+ The test above proves ``LADDER_ACK_SOURCES`` is TOTAL over the axes; it cannot
+ prove the axis value is right, and for ``kind`` that value is the whole trust
+ boundary. ``("im", channel|user)`` are the permissive rows — a notice sent there
+ acks on the id the send returned — and the premise is that such an id was minted
+ by a platform that reached a person. ``PlatformDescriptor.kind`` DEFAULTS to
+ ``"im"``, so a transport added to the registry without stating its kind inherits
+ the permissive answer, and the totality test above stays green because no new
+ kind appeared. If that transport mints its own id the way ``AvibeBot.send_message``
+ does, every defect in this class reopens with nothing failing.
+
+ Checked in the SOURCE rather than at runtime because at runtime the two cases are
+ indistinguishable: a defaulted ``kind`` and an explicit ``kind="im"`` produce the
+ same object. The registry is a module-level dict literal of direct constructor
+ calls, so the AST answers the question exactly — and the assertion that the
+ parsed ids equal ``PLATFORM_REGISTRY``'s own keys is what keeps this honest if
+ that ever stops being true: a registry the AST can no longer read fails here
+ instead of silently passing over nothing.
+ """
+
+ import ast
+ import dataclasses
+ import inspect
+
+ from config import platform_registry
+ from config.platform_registry import PLATFORM_REGISTRY, PlatformDescriptor
+
+ # The default is real — this test is not asserting a hypothetical.
+ kind_field = next(
+ field for field in dataclasses.fields(PlatformDescriptor) if field.name == "kind"
+ )
+ assert kind_field.default == "im", (
+ "if kind is mandatory now, this test is obsolete rather than merely passing"
+ )
+
+ tree = ast.parse(inspect.getsource(platform_registry))
+ registry_literal = None
+ for node in ast.walk(tree):
+ # The registry is an annotated assignment today; accept both spellings so a
+ # dropped annotation does not read as a missing registry.
+ targets = (
+ [node.target]
+ if isinstance(node, ast.AnnAssign)
+ else node.targets
+ if isinstance(node, ast.Assign)
+ else []
+ )
+ if any(
+ isinstance(target, ast.Name) and target.id == "PLATFORM_REGISTRY"
+ for target in targets
+ ):
+ registry_literal = node.value
+ assert isinstance(registry_literal, ast.Dict), (
+ "PLATFORM_REGISTRY is no longer a dict literal; this guard must be rewritten "
+ "rather than deleted — the kind axis is still a trust boundary"
+ )
+
+ undeclared: list[str] = []
+ parsed_ids: list[str] = []
+ for key, value in zip(registry_literal.keys, registry_literal.values):
+ assert isinstance(key, ast.Constant), "every registry key must be a literal id"
+ parsed_ids.append(str(key.value))
+ assert isinstance(value, ast.Call) and getattr(value.func, "id", "") == (
+ "PlatformDescriptor"
+ ), f"{key.value} is not a direct PlatformDescriptor(...) call; rewrite this guard"
+ if not any(keyword.arg == "kind" for keyword in value.keywords):
+ undeclared.append(str(key.value))
+
+ assert set(parsed_ids) == set(PLATFORM_REGISTRY), (
+ "the AST did not read the live registry, so it proves nothing: parsed "
+ f"{sorted(set(parsed_ids))}, registered {sorted(PLATFORM_REGISTRY)}"
+ )
+ assert not undeclared, (
+ f"{undeclared} inherit PlatformDescriptor.kind's default of 'im', which grants "
+ "them LADDER_ACK_SOURCES' permissive rows — a failure notice may be marked "
+ "delivered on the id their send returns. State kind= explicitly, and if the "
+ "transport mints that id itself, it is not 'im'."
+ )
+
+
+def test_a_replayed_notice_does_not_finalize_a_live_unrelated_turn(tmp_path: Path) -> None:
+ """HFR-080 — a receipt about an old run must not mutate the current turn.
+
+ ``emit_backend_failure`` sends the notice and then emits its usual TERMINAL
+ result (``terminal_turn_output()`` → ``completes_turn=True``). For a replayed
+ notice the context describes a run that ended hours ago and carries no
+ runtime-turn token, so the fail-open guard adopts the channel's CURRENT turn:
+ delivering the notice collapses a live status bubble, clears consolidated
+ state, signals turn-complete and releases the runtime turn — in a conversation
+ that has nothing to do with the failed run.
+
+ That is strictly worse than the gap PR6 exists to close: it trades a silent
+ failure for a visible one in someone else's turn.
+
+ Driven through the DRAIN rather than through ``emit_backend_failure``, because
+ the mechanism to avoid this already exists — ``emit_backend_failure`` honours an
+ explicit non-settling ``output``. The defect is that the drain never supplied
+ one, so that is what the test exercises.
+ """
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ controller, _dispatcher, touched = _live_turn_dispatcher()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-live", deliver_key="slack::channel::C123")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ run = requests.enqueue_task_run("task-live")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-live")
+
+ controller.platform_settings_managers = {}
+ controller.session_turn_gate = None
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = controller
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert touched == [], f"a replayed notice mutated the live turn: {touched}"
+ # The notice itself must still have been delivered — this is not a fix by silence.
+ assert controller.im_client.sent, "the notice must still reach the user"
+
+
+def test_a_live_failure_still_settles_its_own_turn() -> None:
+ """The non-settling output is opt-in, so the live failure path is unchanged.
+
+ Only the replay declines to settle. A backend failure reported as it happens
+ still owns its turn, or every real 401 would leave a spinner running forever.
+ """
+
+ from core.backend_failure import emit_backend_failure
+ from modules.im import MessageContext
+
+ controller, _dispatcher, touched = _live_turn_dispatcher()
+ live_context = MessageContext(
+ user_id="u1",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={"turn_token": "tok-1"},
+ )
+
+ asyncio.run(
+ emit_backend_failure(controller, live_context, "codex", "boom", display_text="it broke")
+ )
+
+ assert "signal_turn_complete" in touched, "the live path must still settle its turn"
+
+
+def test_the_drain_reuses_the_identity_the_live_path_would_have_used(tmp_path: Path) -> None:
+ """HFR-081 — a stamped notice must dedupe against the live notification.
+
+ The live path keys its failure notification through ``_failure_identity``, which
+ prefers ``task_execution_id`` — and ``_build_context`` sets that to the run id.
+ Stamping ``failure:{run_id}`` instead produced a DIFFERENT
+ ``native_message_id``, so the drain's ``agent_message_exists`` lookup could not
+ see the message the live path had already persisted and sent a second
+ notification for the same failure.
+
+ This is the mirror of the duplicate-short-circuit defect: there the drain could
+ not see its OWN receipt, here it cannot see the live path's.
+ """
+
+ from core.backend_failure import backend_failure_notification_output
+ from modules.im import MessageContext
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-dedup", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-dedup")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-dedup")
+
+ # What the LIVE path produces, from a context built the way ``_build_context``
+ # builds one for this run.
+ live_context = MessageContext(
+ user_id="scheduled",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={"task_execution_id": run.id, "task_trigger_kind": "scheduled"},
+ )
+ live_identity = backend_failure_notification_output(live_context, "harness").idempotency_key
+
+ # What the DRAIN stamped on the durable row.
+ notice = sqlite.owed_failure_notice(run.id)
+ drained_context = MessageContext(user_id="scheduled", channel_id="C1", platform="slack")
+ drained_identity = backend_failure_notification_output(
+ drained_context, "harness", failure_id=notice["failure_id"]
+ ).idempotency_key
+
+ assert drained_identity == live_identity, (
+ "the drain would post a second notification for a failure already delivered"
+ )
+
+
+def test_an_interruption_keeps_an_identity_distinct_from_an_ordinary_failure(
+ tmp_path: Path,
+) -> None:
+ """HFR-082 — the interruption notice must NOT collide with the ordinary one.
+
+ Reusing the live identity is right for an ordinary failure, and wrong for an
+ interruption: a run terminalized out of band may already have an ordinary
+ backend-failure notice against ``task_execution_id``, and a colliding identity
+ would let the dedup silently swallow the D1 notice that a deploy killed the run.
+ """
+
+ from core.backend_failure import backend_failure_notification_output
+ from modules.im import MessageContext
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-interrupt")
+ run = requests.enqueue_task_run("task-interrupt")
+ requests.claim(run.id)
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="interrupted by a restart",
+ metadata={"interrupt_reason": "restarted"},
+ )
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["interrupt_reason"] == "restarted"
+
+ context = MessageContext(user_id="scheduled", channel_id="C1", platform="slack")
+ interrupt_identity = backend_failure_notification_output(
+ context, "harness", failure_id=notice["failure_id"]
+ ).idempotency_key
+ ordinary_identity = backend_failure_notification_output(
+ context, "harness", failure_id=run.id
+ ).idempotency_key
+
+ assert interrupt_identity != ordinary_identity
+ assert run.id in notice["failure_id"] and "restarted" in notice["failure_id"], (
+ "the identity must stay derivable from the durable run row"
+ )
+
+
+def test_the_owed_notice_lookup_seeks_rather_than_scans(tmp_path: Path) -> None:
+ """HFR-083 — the SQL bound must actually bound the work.
+
+ ``LIMIT`` plus in-SQL predicates moved the JSON decoding from Python into SQLite
+ without bounding it: the planner still had to seek only on ``status='failed'``
+ and then evaluate the unindexed ``json_valid``/``json_extract`` terms on every
+ failed row before concluding that no eligible rows exist. Measured on the
+ previous revision, the plan was::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_status_created (status=?)
+ USE TEMP B-TREE FOR LAST TERM OF ORDER BY
+
+ — and the temp sort is the second half of the problem, because it defeats the
+ ``LIMIT``'s early exit: SQLite must order the whole failed set before returning
+ ten rows.
+
+ Asserted on the query plan, which is what "bounded" actually means here, rather
+ than on wall-clock time.
+ """
+
+ import sqlite3
+
+ from sqlalchemy import event
+
+ sqlite_store, requests = _store(tmp_path)
+ _task(sqlite_store, "task-plan")
+ run = requests.enqueue_task_run("task-plan")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-plan")
+
+ captured: list[tuple[str, Any]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ captured.append((statement, parameters))
+
+ event.listen(sqlite_store.engine, "before_cursor_execute", _capture)
+ try:
+ sqlite_store.list_owed_failure_notices(limit=10, now="2026-07-27T12:00:00+00:00")
+ finally:
+ event.remove(sqlite_store.engine, "before_cursor_execute", _capture)
+
+ statement, parameters = captured[-1]
+ raw = sqlite3.connect(str(tmp_path / "state" / "vibe.sqlite"))
+ try:
+ plan = [row[-1] for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters)]
+ finally:
+ raw.close()
+
+ rendered = "\n".join(plan)
+ assert OWED_NOTICE_INDEX in rendered, (
+ f"the eligibility lookup must seek on {OWED_NOTICE_INDEX}; plan was:\n{rendered}"
+ )
+ assert "SCAN" not in rendered, f"the lookup must not scan agent_runs; plan was:\n{rendered}"
+ # The index also supplies (created_at, id) order, so the LIMIT can short-circuit
+ # instead of sorting the whole failed history first.
+ assert "TEMP B-TREE" not in rendered, (
+ f"the ORDER BY must be served by the index, not a temp sort; plan was:\n{rendered}"
+ )
+
+
+def test_a_malformed_metadata_row_is_still_writable_under_the_expression_index(
+ tmp_path: Path,
+) -> None:
+ """HFR-084 — the index expression must not reject rows at write time.
+
+ A bare ``json_extract`` in an index expression is evaluated on every INSERT and
+ UPDATE, so one malformed blob would make the row UNWRITABLE — converting a
+ read-side degradation into a write-side outage. The ``CASE json_valid`` guard
+ short-circuits, so the expression is never evaluated on invalid JSON.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite_store, requests = _store(tmp_path)
+ _task(sqlite_store, "task-badjson")
+ run = requests.enqueue_task_run("task-badjson")
+ claimed = requests.claim(run.id)
+ requests.complete(claimed, ok=False, error="boom", task_id="task-badjson")
+
+ # Must not raise.
+ with sqlite_store.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs).where(agent_runs.c.id == run.id).values(metadata_json="{not json")
+ )
+
+ assert sqlite_store.get_run(run.id)["status"] == "failed"
+ assert sqlite_store.list_owed_failure_notices() == []
+
+
+# --- group 2f: fairness and boundedness of the drain batch -----------------
+
+
+def _pending_failure(sqlite_store, run_id: str, definition_id: str, *, created_at: str, notice: dict) -> None:
+ """A settled failure row carrying a hand-built owed notice."""
+
+ sqlite_store.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": definition_id,
+ "error": "boom",
+ "created_at": created_at,
+ "completed_at": created_at,
+ "metadata": {"owed_failure_notice": notice},
+ }
+ )
+
+
+def test_one_backed_off_definition_does_not_starve_every_other_notice(tmp_path: Path) -> None:
+ """HFR-085 — a deferred streak must not occupy the global batch forever.
+
+ When one definition has more than ten pending failures and its canonical notice
+ is in backoff, the canonical is excluded by the ``next_attempt_at`` predicate
+ while its LATER streak rows fill the limit of ten. Those rows are deferred
+ without being changed, so every two-second tick selects the same ten rows again
+ and never reaches another definition's notice — or an interruption's.
+
+ A definition whose delivery ladder never works repeats this through each
+ promoted canonical, starving unrelated notices indefinitely. This is the worst
+ shape of defect for this PR: it makes an arbitrary subset of failures
+ permanently invisible, with no error, no log, and a drain that looks healthy
+ because it is busy.
+ """
+
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-noisy", deliver_key="slack::channel::C1")
+ _task(sqlite, "task-quiet", deliver_key="slack::channel::C2")
+
+ # The noisy definition's canonical is mid-backoff and therefore not eligible.
+ _pending_failure(
+ sqlite,
+ "run-noisy-canonical",
+ "task-noisy",
+ created_at="2026-07-27T00:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 2,
+ "next_attempt_at": "2099-01-01T00:00:00+00:00",
+ "failure_id": "run-noisy-canonical",
+ },
+ )
+ # ...and it is followed by more than one batch worth of streak rows.
+ for index in range(15):
+ _pending_failure(
+ sqlite,
+ f"run-noisy-{index:02d}",
+ "task-noisy",
+ created_at=f"2026-07-27T01:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": f"run-noisy-{index:02d}",
+ },
+ )
+ # A completely unrelated definition owes exactly one notice.
+ _pending_failure(
+ sqlite,
+ "run-quiet",
+ "task-quiet",
+ created_at="2026-07-27T02:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": "run-quiet",
+ },
+ )
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ delivered: list[str] = []
+
+ async def _spy_emit(controller, context, backend, diagnostic, **kwargs):
+ delivered.append(str(kwargs.get("failure_id")))
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _spy_emit)
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+ # A handful of ticks — far more than the one the quiet notice should need.
+ for _ in range(4):
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice("run-quiet")["state"] == "sent", (
+ "an unrelated definition's notice was starved by a deferred streak; "
+ f"delivered={delivered}"
+ )
+
+
+def test_ten_unstampable_retry_instants_do_not_starve_the_notice_behind_them(
+ tmp_path: Path,
+) -> None:
+ """HFR-085 — a row the SQL admits and Python drops must not hold a batch slot.
+
+ The same starvation as the test above, reached through the OTHER half of the
+ eligibility contract. ``list_owed_failure_notices`` seeks and LIMITS in SQL and
+ then re-checks the decoded blob in Python, so a ``next_attempt_at`` the two sides
+ read differently is a row that is selected, dropped, and never written — the one
+ thing that guarantees it is selected again next tick.
+
+ A JSON number is the sharpest shape: SQLite compares storage classes, so every
+ INTEGER sorts before every TEXT and the row is both ELIGIBLE and FIRST in
+ ``ORDER BY next_attempt_at``. Ten of them therefore fill the batch of ten ahead of
+ every legitimately eligible notice, on every tick, forever.
+
+ The fix is not to make the drain skip them harder: it is that a row admitted by
+ the listing must be advanced by the pass that reads it. Degrade and advance, as
+ ``notice_write_expectation`` already does for a malformed ``attempts`` — the claim
+ stamps a real ISO instant over the unreadable one, so the poisoned row leaves the
+ front of the queue by being HANDLED rather than by being avoided.
+
+ MORE POISONED ROWS THAN THE BATCH LIMIT, and every off-domain shape among them:
+ twelve numerics (which sort ahead of the valid notice), padded instants (text, so
+ they sort behind it), and containers (never eligible on either side, so they are
+ never listed at all — the domain table in ``owed_notice_eligible`` states that
+ treatment, and this test pins that it starves nothing).
+ """
+
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-poisoned", deliver_key="slack::channel::C1")
+ _task(sqlite, "task-behind", deliver_key="slack::channel::C2")
+
+ # MORE than one batch worth of rows whose retry instant is a JSON number. Every one
+ # is ``<= now`` in SQL and sorts ahead of every ISO instant and ahead of the empty
+ # string a freshly stamped notice reads as, so all twelve are ahead of the valid
+ # notice below.
+ for index in range(12):
+ _pending_failure(
+ sqlite,
+ f"run-poisoned-{index:02d}",
+ "task-poisoned",
+ created_at=f"2026-07-27T00:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": 30000 + index,
+ "failure_id": f"run-poisoned-{index:02d}",
+ },
+ )
+ # Padded instants: still TEXT, so they sort behind the valid notice, and eligible on
+ # both sides only because neither side strips.
+ for index in range(3):
+ _pending_failure(
+ sqlite,
+ f"run-padded-{index:02d}",
+ "task-poisoned",
+ created_at=f"2026-07-27T01:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": " 9999-01-01T00:00:00+00:00",
+ "failure_id": f"run-padded-{index:02d}",
+ },
+ )
+ # Containers: ineligible on BOTH sides, so the seek never returns them. They occupy
+ # no slot and starve nothing — the other half of the domain's explicit treatment.
+ for index, value in enumerate(({"at": "2020-01-01T00:00:00+00:00"}, [1], [])):
+ _pending_failure(
+ sqlite,
+ f"run-container-{index:02d}",
+ "task-poisoned",
+ created_at=f"2026-07-27T00:00:0{index}+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": value,
+ "failure_id": f"run-container-{index:02d}",
+ },
+ )
+ # ...and one ordinary notice behind them, eligible now.
+ _pending_failure(
+ sqlite,
+ "run-behind",
+ "task-behind",
+ created_at="2026-07-27T02:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": "run-behind",
+ },
+ )
+
+ # The batch the SQL LIMIT filled must not arrive HOLLOW. Ten rows were admitted
+ # before the limit; if the Python re-check drops them afterwards the drain gets an
+ # empty pass while nineteen notices are owed, and gets the same empty pass forever.
+ listed = [item["id"] for item in sqlite.list_owed_failure_notices(limit=10)]
+ assert len(listed) == 10, (
+ "the limited batch came back short while nineteen notices were owed: the rows SQL "
+ "admitted were dropped by the Python re-check AFTER the limit, so the batch is a "
+ f"hole rather than a queue (listed={listed})"
+ )
+ assert not [run_id for run_id in listed if run_id.startswith("run-container-")], (
+ "a container-valued retry instant was listed; it is ineligible on both sides "
+ f"and must never consume a slot (listed={listed})"
+ )
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ delivered: list[str] = []
+
+ async def _spy_emit(controller, context, backend, diagnostic, **kwargs):
+ delivered.append(str(kwargs.get("failure_id")))
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _spy_emit)
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+ for _ in range(4):
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice("run-behind")["state"] == "sent", (
+ "a notice was starved by ten rows the listing admitted and the drain dropped; "
+ f"delivered={delivered}"
+ )
+ # ...and every poisoned row was ADVANCED rather than skipped over: settled, or
+ # deferred to a real instant. None of them is still immediately eligible, so none
+ # can re-occupy the front of the queue on the next tick. That — not the field's
+ # final value — is the anti-starvation property, and it is asserted through the
+ # very predicate the listing seeks on.
+ from datetime import datetime, timezone
+
+ later = datetime.now(timezone.utc).isoformat()
+ admitted = [f"run-poisoned-{index:02d}" for index in range(12)]
+ admitted += [f"run-padded-{index:02d}" for index in range(3)]
+ stuck = {run_id: sqlite.owed_failure_notice(run_id) for run_id in admitted}
+ stuck = {
+ run_id: notice for run_id, notice in stuck.items() if owed_notice_eligible(notice, later)
+ }
+ assert not stuck, (
+ "rows the listing admitted are still immediately eligible after being read by "
+ f"four passes; each holds a batch slot for good: {stuck}"
+ )
+ # The containers made no progress, which is the stated treatment rather than an
+ # oversight: they are ineligible on both sides, so no pass ever reads them. What
+ # they must not do is hold a slot — proved by the valid notice above having been
+ # delivered while they sat there.
+ for index in range(3):
+ container = sqlite.owed_failure_notice(f"run-container-{index:02d}")
+ assert container["state"] == "pending" and not owed_notice_eligible(container, later), (
+ "a container-valued retry instant changed the domain's answer: it is "
+ f"ineligible and undelivered by design ({container})"
+ )
+
+
+ "attempts",
+ ["-3q", -3, -(2**63), -1e100],
+ ids=["negative-prefix-string", "negative-int", "int64-min", "saturated-real"],
+)
+def test_a_negative_attempt_counter_starts_the_ladder_instead_of_counting_up(
+ attempts,
+) -> None:
+ """Subordinate to HFR-076 — the round-20 finding: clamp the POLICY, not the CAS.
+
+ CAST semantics can read a negative counter from an out-of-band value ("-3q"
+ reads -3; a saturated number reads INT64_MIN), and a policy that increments
+ FROM it grants the notice more than ``MAX_ATTEMPTS`` attempts — roughly 9.2
+ quintillion for the saturated case, each armed with the shortest backoff.
+ The split is deliberate and directional: ``notice_write_expectation`` keeps
+ asserting the RAW stored value (the CAS must match the row as it is, or the
+ claim never lands at all), while ``next_attempt`` clamps the policy read to
+ the start of the ladder — so the first claim stamps attempt 1 over the poison
+ and the row is a normal notice again in one pass.
+ """
+
+ from core.failure_notices import BACKOFF_SECONDS, next_attempt
+
+ assert next_attempt({"state": "pending", "attempts": attempts}) == (
+ 1,
+ BACKOFF_SECONDS[0],
+ ), "a negative counter must start the retry ladder, not extend it downward"
+
+
+def test_twelve_cast_divergent_attempt_counters_do_not_starve_the_notice_behind_them(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-076 — the round-19 finding: the OTHER field's CAST split.
+
+ Same starvation as the retry-instant test above, reached through ``attempts``.
+ The listing admits a pending notice regardless of its counter, but the claim
+ asserts the counter through SQLite's ``CAST(... AS INTEGER)`` — which parses a
+ numeric PREFIX (``"3x"`` reads 3, ``"1e100"`` reads 1) and saturates at the
+ signed-64-bit bounds, where Python's ``int()`` raises and the old reader
+ degraded to 0. An expectation of 0 against a stored ``"3x"`` is a claim that
+ can never match: the row is selected, refused, and unchanged on every pass,
+ holding a batch slot forever, with every notice behind it starved.
+
+ Both readers (``core.failure_notices._attempts_read`` and
+ ``storage.background.notice_write_expectation``) now consume ONE model of the
+ CAST (``storage.sqlite_semantics.sqlite_cast_integer``) for the DECODE, so the
+ claim's expectation matches the stored value and the write lands. The two final
+ numbers are deliberately NOT identical for every shape: for a NEGATIVE decode
+ the CAS asserts the raw stored value while the policy clamps to the ladder's
+ start before incrementing (round 20 — an unclamped increment from INT64_MIN
+ would grant ~9.2 quintillion attempts). For every nonnegative shape they are
+ the same number. Either way the claim lands, stamps a real integer over the
+ malformed counter, and the row advances through the ordinary backoff toward
+ delivery or the visible dead letter. Bounded progress, not a broad retry and
+ not a widened batch.
+ """
+
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cast", deliver_key="slack::channel::C1")
+ _task(sqlite, "task-cast-behind", deliver_key="slack::channel::C2")
+
+ # MORE divergent counters than the batch limit, in every shape the finding
+ # names: numeric-prefix strings, scientific-notation prefixes, padded digits,
+ # signed prefixes, reals-as-text, and out-of-range numbers. Each reads as a
+ # different integer under CAST than under the old int()-or-0 read.
+ divergent = ["3x", "1e100", " 5 ", " +7x", "-3q", "3.9", "2x", "4y",
+ 9223372036854775808, 1e100, "1e19", "8 8"]
+ for index, counter in enumerate(divergent):
+ _pending_failure(
+ sqlite,
+ f"run-cast-{index:02d}",
+ "task-cast",
+ created_at=f"2026-07-27T00:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": counter,
+ "next_attempt_at": None,
+ "failure_id": f"run-cast-{index:02d}",
+ },
+ )
+ _pending_failure(
+ sqlite,
+ "run-cast-behind",
+ "task-cast-behind",
+ created_at="2026-07-27T02:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": "run-cast-behind",
+ },
+ )
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ delivered: list[str] = []
+
+ async def _spy_emit(controller, context, backend, diagnostic, **kwargs):
+ delivered.append(str(kwargs.get("failure_id")))
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _spy_emit)
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+ for _ in range(4):
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice("run-cast-behind")["state"] == "sent", (
+ "a valid notice was starved by rows whose attempt counter the claim could "
+ f"never re-assert; delivered={delivered}"
+ )
+ # And the divergent rows made bounded progress under the guarded claim: none is
+ # still holding a malformed counter AND immediately eligible. Each was either
+ # delivered, dead-lettered on running off the ladder (counters that CAST past
+ # MAX_ATTEMPTS dead-letter on their first read — the '1e100'-as-number and
+ # out-of-range shapes), or advanced onto a real integer with a real backoff.
+ from datetime import datetime, timezone
+
+ later = datetime.now(timezone.utc).isoformat()
+ stuck = {}
+ for index in range(len(divergent)):
+ notice = sqlite.owed_failure_notice(f"run-cast-{index:02d}")
+ # A REAL nonnegative integer — ``-2`` from an unclamped negative increment
+ # would have satisfied a bare isinstance check (the round-20 gate's point).
+ attempts_now = notice.get("attempts")
+ if notice["state"] == "pending" and not (
+ isinstance(attempts_now, int) and not isinstance(attempts_now, bool) and attempts_now >= 1
+ ):
+ stuck[f"run-cast-{index:02d}"] = notice
+ assert not stuck, (
+ "rows with CAST-divergent counters were read by four passes and never "
+ f"advanced onto a real nonnegative attempt — each holds a batch slot for good: {stuck}"
+ )
+
+
+def test_negative_attempt_counters_claim_at_the_raw_value_and_dead_letter_on_schedule(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-076 — the round-20 clamp, proven at the consuming end.
+
+ The direct policy test pins ``next_attempt``'s answer; this one proves the
+ machine: for a NEGATIVE stored counter (a ``"-3q"`` hand-edit, a negative JSON
+ scalar, the i64 floor a saturated number decodes to) the real guarded claim
+ matches the RAW negative value — that is what the CAS asserts, deliberately
+ unclamped — and persists attempt exactly 1 with the first declared backoff
+ armed. The same rows then follow the ordinary retry schedule to the ordinary
+ dead letter in the normal bounded attempt count.
+
+ MORE negative rows than the drain's batch limit sit ahead of a valid due
+ notice, so the batch BOUNDARY is exercised, not just batch ordering: pass 1
+ claims exactly the first batch and leaves the remainder untouched (unclaimed
+ — no attempt consumed, no backoff armed); pass 2, inside the first batch's
+ backoff, must advance PAST those backed-off rows to the remaining negatives
+ and the valid notice rather than reselecting the first batch forever.
+
+ Red on the pre-clamp head: the first claim persisted the negative increment
+ (``-2`` from ``"-3q"``; ``INT64_MIN + 1`` from the floor), never attempt 1,
+ and the floor row could not dead-letter in any bounded number of passes.
+ """
+
+ from datetime import datetime, timedelta, timezone
+ from types import SimpleNamespace
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.failure_notices import BACKOFF_SECONDS, MAX_ATTEMPTS
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+ from storage.background import notice_write_expectation
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-negative-behind", deliver_key="slack::channel::C2")
+
+ # One DEFINITION per negative row: rows of one definition share a streak, so
+ # only the canonical would be claimed per pass and the rest would defer —
+ # correct suppression, but it would hide the per-row claim this test exists
+ # to prove. Separate definitions make every row its own canonical.
+ #
+ # THIRTEEN rows — more than the drain's batch limit of 10 — with all three
+ # required shapes (negative-prefix text, negative scalar, i64 floor) present
+ # in the first batch AND in the remainder past the boundary. The listing
+ # orders by ``(created_at, id)``, so indexes 0-9 are the first batch.
+ negatives: list[Any] = [
+ "-3q", -3, -(2**63), "-1x", -1, -1e100, "-7q", -5, -(2**63), " -2x",
+ # Past the batch boundary:
+ "-9z", -4, -(2**63),
+ ]
+ for index, counter in enumerate(negatives):
+ _task(sqlite, f"task-neg-{index:02d}", deliver_key="slack::channel::C1")
+ _pending_failure(
+ sqlite,
+ f"run-neg-{index:02d}",
+ f"task-neg-{index:02d}",
+ created_at=f"2026-07-27T00:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": counter,
+ "next_attempt_at": None,
+ "failure_id": f"run-neg-{index:02d}",
+ },
+ )
+ # The premise, asserted before any pass runs: the CAS expectation reads the
+ # RAW negative — the clamp is policy-side only. If the expectation clamped
+ # too, the claim would assert a value the row does not hold and never land.
+ expectation = notice_write_expectation(sqlite.owed_failure_notice(f"run-neg-{index:02d}"))
+ assert expectation[1] < 0, (
+ f"the CAS must assert the stored negative as-is, got {expectation!r} for {counter!r}"
+ )
+ _pending_failure(
+ sqlite,
+ "run-neg-behind",
+ "task-negative-behind",
+ created_at="2026-07-27T02:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": "run-neg-behind",
+ },
+ )
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ async def _spy_emit(controller, context, backend, diagnostic, **kwargs):
+ # The valid notice behind the negatives delivers; the negative rows'
+ # deliveries FAIL every time, so they must walk the declared retry
+ # schedule to the ordinary dead letter.
+ failure_id = str(kwargs.get("failure_id"))
+ evidence = kwargs.get("delivery")
+ if failure_id == "run-neg-behind" and evidence is not None:
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ import pytest as _pytest
+
+ import storage.background as storage_background
+
+ # ONE FROZEN INSTANT for every clock the consuming path reads, so pass-two
+ # eligibility is deterministic BY CONSTRUCTION: the listing's default ``now``
+ # (``storage.background._utc_now_iso``) and every eligibility/claim/retry
+ # calculation in ``core.scheduled_tasks`` (its module ``datetime``). The
+ # production 2-second first rung stays UNCHANGED — pass 1 stamps
+ # ``frozen + BACKOFF_SECONDS[0]`` and pass 2 lists at ``frozen``, which is
+ # provably inside the backoff no matter how long the process is suspended
+ # between the passes; there is no wall-clock read left for preemption to
+ # advance. Stored deadlines are then asserted EXACTLY from the frozen
+ # instant. (The drain's pass budget uses ``time.monotonic`` and is not
+ # frozen; with the spy emitter it never truncates.)
+ frozen = datetime(2026, 7, 28, 12, 0, 0, tzinfo=timezone.utc)
+
+ class _FrozenDatetime(datetime):
+ @classmethod
+ def now(cls, tz=None): # noqa: ANN001 - datetime API shape
+ return frozen.astimezone(tz) if tz is not None else frozen.replace(tzinfo=None)
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _spy_emit)
+ patch.setattr(scheduled_tasks, "datetime", _FrozenDatetime)
+ patch.setattr(storage_background, "_utc_now_iso", lambda: frozen.isoformat())
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+
+ # PASS 1 claims exactly the first batch. Snapshot the boundary between the
+ # passes — pass 2 runs inside the (widened) first backoff to prove the
+ # batch does not get reselected.
+ # PASS 1 claims exactly the first batch; the boundary is snapshotted
+ # between the passes.
+ first_batch = list(range(10))
+ remainder = list(range(10, len(negatives)))
+ asyncio.run(service._drain_failure_notices())
+ remainder_after_pass_one = {
+ index: sqlite.owed_failure_notice(f"run-neg-{index:02d}") for index in remainder
+ }
+ valid_after_pass_one = sqlite.owed_failure_notice("run-neg-behind")["state"]
+
+ # PASS 2, at the SAME frozen instant: the first batch is backed off by
+ # construction, so the bounded drain must advance PAST it to the
+ # remaining negatives and the valid notice.
+ asyncio.run(service._drain_failure_notices())
+
+ # The boundary, as pass 1 left it: rows past the limit were simply not
+ # pulled — unclaimed, so no attempt consumed and no backoff armed, and the
+ # CAS expectation still reads their RAW negative. The valid notice, last in
+ # ``(created_at, id)`` order, was outside the first batch too.
+ for index, snapshot in remainder_after_pass_one.items():
+ assert snapshot["state"] == "pending" and snapshot.get("next_attempt_at") is None, (
+ f"pass 1 must leave the row past the batch boundary unclaimed, got {snapshot!r}"
+ )
+ assert notice_write_expectation(snapshot)[1] < 0, (
+ f"an unclaimed remainder row must still hold its raw negative, got {snapshot!r}"
+ )
+ assert valid_after_pass_one == "pending", (
+ "the valid notice sorts after thirteen negatives — pass 1's batch of 10 "
+ "must not have reached it"
+ )
+
+ # PASS 1's claims: the guarded claim matched the raw negative and persisted
+ # exactly attempt 1, with the FIRST declared interval armed — the clamp
+ # starting the ladder rather than extending it downward. Still attempt 1
+ # after pass 2: the backoff excluded the first batch from reselection.
+ for index in first_batch:
+ notice = sqlite.owed_failure_notice(f"run-neg-{index:02d}")
+ assert notice["attempts"] == 1, (
+ f"the first claim over {negatives[index]!r} must persist attempt exactly 1 "
+ f"and pass 2 must not reselect the backed-off batch, "
+ f"got {notice['attempts']!r} (state={notice['state']!r})"
+ )
+ assert notice["state"] == "pending"
+ # EXACT, from the frozen instant: the retry stamp is
+ # ``frozen + BACKOFF_SECONDS[0]`` to the microsecond — rung 1, not
+ # rung 2 and not the claim lease, with no timing tolerance at all.
+ armed = datetime.fromisoformat(notice["next_attempt_at"])
+ assert armed == frozen + timedelta(seconds=BACKOFF_SECONDS[0]), (
+ f"the first backoff must be exactly the ladder's FIRST rung from the "
+ f"frozen instant, got {notice['next_attempt_at']!r}"
+ )
+ # PASS 2's claims: the remainder crossed the boundary on the very next
+ # bounded pass — attempt exactly 1, first interval armed — and the valid
+ # due notice behind every negative row delivered instead of starving.
+ for index in remainder:
+ notice = sqlite.owed_failure_notice(f"run-neg-{index:02d}")
+ assert notice["attempts"] == 1, (
+ f"pass 2 must claim the remainder row {negatives[index]!r} at attempt 1, "
+ f"got {notice['attempts']!r} (state={notice['state']!r})"
+ )
+ assert notice["state"] == "pending"
+ armed = datetime.fromisoformat(notice["next_attempt_at"])
+ assert armed == frozen + timedelta(seconds=BACKOFF_SECONDS[0]), (
+ f"the remainder's first backoff must be exactly the ladder's FIRST rung "
+ f"from the frozen instant, got {notice['next_attempt_at']!r}"
+ )
+ assert sqlite.owed_failure_notice("run-neg-behind")["state"] == "sent", (
+ "thirteen negative rows ahead of it must not starve the valid due notice "
+ "past the second pass"
+ )
+
+ # PASSES 3..N: rewind the backoff between passes and let the schedule run
+ # out. Every negative row must reach the ordinary dead letter at exactly
+ # the declared bound — MAX_ATTEMPTS — never more. The bound: 13 rows need
+ # 5 more claims each and a pass claims at most 10, with ``(created_at,
+ # id)`` order letting the first batch monopolize passes until it dead-
+ # letters — 5 passes for the first ten, then 5 for the remainder, so
+ # 2 * (MAX_ATTEMPTS + 1) passes is enough with slack.
+ for _ in range(2 * (MAX_ATTEMPTS + 1)):
+ pending = [
+ index
+ for index in range(len(negatives))
+ if sqlite.owed_failure_notice(f"run-neg-{index:02d}")["state"] == "pending"
+ ]
+ if not pending:
+ break
+ for index in pending:
+ sqlite.update_owed_failure_notice(f"run-neg-{index:02d}", next_attempt_at=None)
+ asyncio.run(service._drain_failure_notices())
+
+ for index in range(len(negatives)):
+ notice = sqlite.owed_failure_notice(f"run-neg-{index:02d}")
+ assert notice["state"] == "failed", (
+ f"a negative counter must reach the ordinary dead letter, got {notice['state']!r} "
+ f"for {negatives[index]!r} at attempts={notice['attempts']!r}"
+ )
+ assert notice["attempts"] == MAX_ATTEMPTS, (
+ "the dead letter must arrive at the declared bound, not before or after: "
+ f"{notice['attempts']!r} != {MAX_ATTEMPTS} for {negatives[index]!r}"
+ )
+
+
+def _callback_run(sqlite_store, run_id: str, definition_id: str, *, status: str) -> None:
+ """A settled failure owing a notice, whose run also carries a callback."""
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ _pending_failure(
+ sqlite_store,
+ run_id,
+ definition_id,
+ created_at="2026-07-27T00:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": run_id,
+ },
+ )
+ with sqlite_store.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(callback_session_id="ses-callback-target", callback_status=status)
+ )
+
+
+def _callback_session(
+ sqlite_store,
+ *,
+ visibility: str = "foreground",
+ status: str = "active",
+) -> None:
+ """The callback target row whose visibility decides whether a receipt is visible."""
+
+ from storage.models import agent_sessions
+
+ now = "2026-07-27T00:00:00+00:00"
+ with sqlite_store.engine.begin() as conn:
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses-callback-target",
+ scope_id=None,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="callback-target",
+ native_session_id="native-callback-target",
+ status=status,
+ visibility=visibility,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
+def _persist_callback_result(sqlite_store, run_id: str, *, text: str) -> None:
+ """Materialize the durable message receipt that a callback success requires."""
+
+ from storage import messages_service
+
+ with sqlite_store.engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id="ses-callback-target",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text=text,
+ metadata={"run_id": run_id},
+ )
+
+
+def _notice_drain_service(tmp_path: Path, sqlite_store, requests) -> tuple[Any, list[str]]:
+ """A detached drain service whose emitter records and acks every delivery."""
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite_store
+ store.load()
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service._drain_dirty = False
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._owns_service_instance = lambda: True
+ service.validate_platform = lambda platform: None
+ service._t = lambda key, **kwargs: key
+ delivered: list[str] = []
+
+ async def _spy_emit(controller, context, backend, diagnostic, **kwargs):
+ delivered.append(str(kwargs.get("failure_id")))
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ service._spy_emit = _spy_emit # kept referenced for the caller's MonkeyPatch
+ return service, delivered
+
+
+def test_failed_run_with_callback_delivers_exactly_one_message(tmp_path: Path) -> None:
+ """Owed by the plan (corrected 2026-07-29): a pending callback IS the delivery.
+
+ A failed run carrying ``callback_session_id`` gets a user-visible result turn
+ from ``_drain_callbacks`` — the path the plan treats as sufficient notification
+ — while terminalization stamps ``owed_failure_notice`` unconditionally for
+ durability. Without coordination the two drains both fire and one failure
+ produces two independently keyed messages.
+
+ The notice drain must resolve on the callback's outcome: defer while it is
+ ``pending`` (no attempt consumed — the row has not been tried), and acknowledge
+ the notice as delivered-by-callback (``skipped``) once it is ``sent``. The
+ fallback is proven live by the companion test
+ ``test_owed_notice_takes_over_when_the_callback_dead_letters``.
+ """
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.failure_notices import DEFERRAL_RECHECK_SECONDS
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cb", deliver_key="slack::channel::C1")
+ _callback_session(sqlite)
+ _callback_run(sqlite, "run-cb", "task-cb", status="pending")
+ callback = requests.enqueue_agent_run(
+ message="deliver the callback",
+ source_kind="callback",
+ parent_run_id="run-cb",
+ session_id="ses-callback-target",
+ )
+ sqlite.update_callback_status("run-cb", status="sent", callback_run_id=callback.id)
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+
+ # PASS 1: the parent has enqueued the callback child, but that child is still
+ # queued. Enqueue is not delivery, so the notice steps aside — no
+ # message, no attempt consumed, and the deferral is durable (a real backoff
+ # instant, so the row does not occupy the batch on every tick).
+ asyncio.run(service._drain_failure_notices())
+ assert delivered == [], "the notice lane must not fire beside a pending callback"
+ notice = sqlite.owed_failure_notice("run-cb")
+ assert notice["state"] == "pending"
+ assert not notice.get("attempts"), (
+ f"a deferral consumes no attempt, got {notice.get('attempts')!r}"
+ )
+ assert notice.get("defer_reason") == "callback_pending", f"got {notice!r}"
+ from datetime import datetime
+
+ armed = datetime.fromisoformat(notice["next_attempt_at"])
+ assert armed is not None # a durable step-aside, not a Python-side continue
+ assert DEFERRAL_RECHECK_SECONDS > 0
+
+ # The callback child succeeds. Only now is the notice a duplicate of a
+ # message the user has, and it must settle terminally.
+ claimed_callback = requests.claim(callback.id)
+ assert claimed_callback is not None
+ delivered_callback = sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="callback delivered",
+ message_id="callback-message-1",
+ terminal_status="succeeded",
+ )
+ assert delivered_callback["terminal_transition"]
+ _persist_callback_result(sqlite, callback.id, text="callback delivered")
+ sqlite.update_owed_failure_notice("run-cb", next_attempt_at=None)
+ asyncio.run(service._drain_failure_notices())
+ notice = sqlite.owed_failure_notice("run-cb")
+ assert notice["state"] == "skipped", f"got {notice!r}"
+ assert notice.get("skip_reason") == "delivered_by_callback", f"got {notice!r}"
+ assert delivered == [], (
+ "exactly one message for the transition — the callback's; the notice "
+ f"lane emitted {delivered!r}"
+ )
+
+ # And the skip is terminal: a later pass does not resurrect it.
+ asyncio.run(service._drain_failure_notices())
+ assert delivered == []
+ assert sqlite.owed_failure_notice("run-cb")["state"] == "skipped"
+
+
+def test_owed_notice_takes_over_when_the_callback_dead_letters(tmp_path: Path) -> None:
+ """Owed by the plan (corrected 2026-07-29): the fallback exists the moment the
+ primary path dies.
+
+ Same transition as the companion test, but the callback delivery FAILED. The
+ parent's unconditional fallback must become deliverable and walk the ordinary
+ retry protocol, while the callback child never stamps a second notice for the
+ delivery mechanism itself.
+
+ The control is a binding-change notice riding a run whose callback is still
+ ``pending``: it reports a fact (the pinned session was replaced) the callback's
+ result turn never carries, so the shield must not silence it.
+ """
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cb-dead", deliver_key="slack::channel::C1")
+ _callback_run(sqlite, "run-cb-dead", "task-cb-dead", status="pending")
+ dead_callback = requests.enqueue_agent_run(
+ message="deliver the callback",
+ source_kind="callback",
+ parent_run_id="run-cb-dead",
+ session_id="ses-callback-target",
+ )
+ sqlite.update_callback_status(
+ "run-cb-dead", status="sent", callback_run_id=dead_callback.id
+ )
+ claimed_callback = requests.claim(dead_callback.id)
+ assert claimed_callback is not None
+ failed_callback = sqlite.record_run_output(
+ dead_callback.id,
+ output_id="terminal",
+ text="callback delivery failed",
+ terminal_status="failed",
+ updated_at="2026-07-27T00:00:01+00:00",
+ error="callback delivery failed",
+ )
+ assert failed_callback["terminal_transition"]
+ assert sqlite.owed_failure_notice(dead_callback.id) is None
+
+ _task(sqlite, "task-cb-binding", deliver_key="slack::channel::C2")
+ _callback_run(sqlite, "run-cb-binding", "task-cb-binding", status="pending")
+ sqlite.update_owed_failure_notice("run-cb-binding", kind="binding_change")
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert sorted(delivered) == ["run-cb-binding", "run-cb-dead"], (
+ "a dead-lettered callback hands the transition back to the notice lane, and "
+ "a binding-change notice is never shielded by an unrelated callback; got "
+ f"{delivered!r}"
+ )
+ assert sqlite.owed_failure_notice("run-cb-dead")["state"] == "sent"
+ assert sqlite.owed_failure_notice("run-cb-binding")["state"] == "sent"
+
+
+def test_failed_callback_owns_notice_when_successful_parent_has_no_fallback(
+ tmp_path: Path,
+) -> None:
+ """A callback delivery failure stays visible when its parent did not fail."""
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _callback_session(sqlite)
+ parent = requests.enqueue_agent_run(
+ message="produce a successful result",
+ session_id="ses-callback-target",
+ )
+ claimed_parent = requests.claim(parent.id)
+ assert claimed_parent is not None
+ parent_result = sqlite.record_run_output(
+ parent.id,
+ output_id="terminal",
+ text="result ready",
+ terminal_status="succeeded",
+ )
+ assert parent_result["terminal_transition"]
+ assert sqlite.owed_failure_notice(parent.id) is None
+
+ callback = requests.enqueue_agent_run(
+ message="deliver the successful result",
+ source_kind="callback",
+ parent_run_id=parent.id,
+ session_id="ses-callback-target",
+ )
+ sqlite.update_callback_status(parent.id, status="sent", callback_run_id=callback.id)
+ claimed_callback = requests.claim(callback.id)
+ assert claimed_callback is not None
+ callback_result = sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="callback delivery failed",
+ terminal_status="failed",
+ error="callback delivery failed",
+ )
+ assert callback_result["terminal_transition"]
+ assert sqlite.owed_failure_notice(callback.id)["state"] == "pending"
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == [callback.id]
+ assert sqlite.owed_failure_notice(callback.id)["state"] == "sent"
+
+
+def test_owed_notice_takes_over_when_callback_success_has_no_delivery_receipt(
+ tmp_path: Path,
+) -> None:
+ """A child outcome is not proof that the callback reached its user.
+
+ Ordinary result settlement is intentionally allowed after every IM send failed,
+ and Avibe creates a synthetic send id before persistence, so neither
+ ``status='succeeded'`` nor a Workbench ``message_ids_json`` entry can suppress
+ the durable fallback. Only a real ``messages`` row carrying this child run's
+ provenance is a Workbench receipt.
+ """
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cb-no-receipt", deliver_key="slack::channel::C1")
+ _callback_session(sqlite)
+ _callback_run(sqlite, "run-cb-no-receipt", "task-cb-no-receipt", status="pending")
+ callback = requests.enqueue_agent_run(
+ message="try the callback",
+ source_kind="callback",
+ parent_run_id="run-cb-no-receipt",
+ session_id="ses-callback-target",
+ session_key="avibe::project::proj_callback",
+ )
+ sqlite.update_callback_status(
+ "run-cb-no-receipt", status="sent", callback_run_id=callback.id
+ )
+ claimed = requests.claim(callback.id)
+ assert claimed is not None
+ recorded = sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="callback looked delivered",
+ message_id="msg_synthetic_only",
+ terminal_status="succeeded",
+ )
+ assert recorded["terminal_transition"]
+ assert sqlite.get_run(callback.id)["message_ids"] == ["msg_synthetic_only"]
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == ["run-cb-no-receipt"]
+ assert sqlite.owed_failure_notice("run-cb-no-receipt")["state"] == "sent"
+
+
[email protected]("session_teardown", ["none", "archived", "deleted"])
+def test_callback_native_im_delivery_id_prevents_duplicate_failure_notice(
+ tmp_path: Path,
+ session_teardown: str,
+) -> None:
+ """A real IM send stays delivered after transcript or local-session loss."""
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cb-native-receipt", deliver_key="slack::channel::C1")
+ _callback_session(sqlite)
+ _callback_run(
+ sqlite,
+ "run-cb-native-receipt",
+ "task-cb-native-receipt",
+ status="pending",
+ )
+ callback = requests.enqueue_agent_run(
+ message="deliver through Slack",
+ source_kind="callback",
+ parent_run_id="run-cb-native-receipt",
+ session_id="ses-callback-target",
+ session_key="slack::channel::C1",
+ )
+ sqlite.update_callback_status(
+ "run-cb-native-receipt", status="sent", callback_run_id=callback.id
+ )
+ claimed = requests.claim(callback.id)
+ assert claimed is not None
+ recorded = sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="callback reached Slack",
+ message_id="native-slack-message-id",
+ terminal_status="succeeded",
+ )
+ assert recorded["terminal_transition"]
+
+ from storage.models import agent_sessions
+
+ with sqlite.engine.begin() as conn:
+ if session_teardown == "archived":
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == "ses-callback-target")
+ .values(status="archived")
+ )
+ elif session_teardown == "deleted":
+ conn.execute(
+ agent_sessions.delete().where(
+ agent_sessions.c.id == "ses-callback-target"
+ )
+ )
+ assert sqlite.run_callback_state("run-cb-native-receipt") == "sent"
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == []
+ notice = sqlite.owed_failure_notice("run-cb-native-receipt")
+ assert notice["state"] == "skipped"
+ assert notice["skip_reason"] == "delivered_by_callback"
+
+
+def test_owed_notice_takes_over_when_callback_receipt_is_in_a_hidden_session(
+ tmp_path: Path,
+) -> None:
+ """A persisted background-history row is not a user-visible callback receipt."""
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-cb-hidden", deliver_key="slack::channel::C1")
+ _callback_session(sqlite, visibility="background")
+ _callback_run(sqlite, "run-cb-hidden", "task-cb-hidden", status="pending")
+ callback = requests.enqueue_agent_run(
+ message="persist only in hidden history",
+ source_kind="callback",
+ parent_run_id="run-cb-hidden",
+ session_id="ses-callback-target",
+ )
+ sqlite.update_callback_status(
+ "run-cb-hidden", status="sent", callback_run_id=callback.id
+ )
+ claimed = requests.claim(callback.id)
+ assert claimed is not None
+ recorded = sqlite.record_run_output(
+ callback.id,
+ output_id="terminal",
+ text="hidden callback body",
+ message_id="hidden-history-row",
+ terminal_status="succeeded",
+ )
+ assert recorded["terminal_transition"]
+ _persist_callback_result(sqlite, callback.id, text="hidden callback body")
+ assert sqlite.run_callback_state("run-cb-hidden") == "failed"
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ import pytest as _pytest
+
+ with _pytest.MonkeyPatch.context() as patch:
+ patch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == ["run-cb-hidden"]
+ assert sqlite.owed_failure_notice("run-cb-hidden")["state"] == "sent"
+
+
+def test_skip_reason_writer_cannot_erase_a_terminal_notice_from_its_write_gap(
+ tmp_path: Path,
+) -> None:
+ """A queued diagnostic must not overwrite a terminal owner's metadata."""
+
+ from sqlalchemy import event
+
+ sqlite, requests = _store(tmp_path)
+ run = requests.enqueue_agent_run(message="run later", source_kind="agent")
+ interleaved: list[str] = []
+
+ def _terminalize_before_skip_update(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ assert sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="backend failed before dispatch",
+ ) == "failed"
+
+ event.listen(sqlite.engine, "before_cursor_execute", _terminalize_before_skip_update)
+ try:
+ written = sqlite.record_run_skip_reason(
+ run.id,
+ reason="transport_unavailable",
+ at="2026-07-31T00:00:00+00:00",
+ )
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _terminalize_before_skip_update)
+
+ assert interleaved, "the terminal owner never entered the write gap"
+ assert written is False, "the queued-only writer must lose after terminal settlement"
+ assert sqlite.get_run(run.id)["status"] == "failed"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None and notice["failure_id"] == run.id
+ assert notice["state"] == "pending"
+
+
+def test_skip_recovery_clear_cannot_erase_a_terminal_notice_from_its_write_gap(
+ tmp_path: Path,
+) -> None:
+ """Recovery clears only its JSON keys and only while the row stays queued."""
+
+ from sqlalchemy import event
+
+ sqlite, requests = _store(tmp_path)
+ run = requests.enqueue_agent_run(message="run later", source_kind="agent")
+ assert sqlite.record_run_skip_reason(
+ run.id,
+ reason="transport_unavailable",
+ at="2026-07-31T00:00:00+00:00",
+ )
+ interleaved: list[str] = []
+
+ def _terminalize_before_clear_update(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ assert sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="backend failed during recovery",
+ ) == "failed"
+
+ event.listen(sqlite.engine, "before_cursor_execute", _terminalize_before_clear_update)
+ try:
+ cleared = sqlite._clear_transport_skip_evidence({run.id})
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _terminalize_before_clear_update)
+
+ assert interleaved, "the terminal owner never entered the write gap"
+ assert cleared == 0, "the queued-only clear must lose after terminal settlement"
+ assert sqlite.get_run(run.id)["status"] == "failed"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None and notice["failure_id"] == run.id
+ assert notice["state"] == "pending"
+
+
+def test_the_eligibility_lookup_is_bounded_when_everything_is_backed_off(
+ tmp_path: Path,
+) -> None:
+ """HFR-086 — the backoff term must be CONSTRAINED by the index, not filtered.
+
+ The previous index was the state expression followed by ``(created_at, id)``, so
+ SQLite reported the index as used and avoided the temp sort — satisfying the
+ plan test exactly — while still walking every pending-state entry to evaluate
+ the unindexed future-backoff condition. With many notices waiting on retry and
+ none eligible, the tick was again unbounded in the number of pending notices.
+
+ The plan test is therefore strengthened to assert the backoff term is
+ constrained, not merely that an index is named. ``EXPLAIN QUERY PLAN`` reports
+ constrained terms explicitly — ``(<expr>=? AND <expr><?)`` — so this is
+ assertable directly rather than through a proxy.
+ """
+
+ import sqlite3
+
+ from sqlalchemy import event
+
+ sqlite_store, _requests = _store(tmp_path)
+ _task(sqlite_store, "task-backoff")
+ for index in range(40):
+ _pending_failure(
+ sqlite_store,
+ f"run-backoff-{index:03d}",
+ "task-backoff",
+ created_at=f"2026-07-27T00:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 3,
+ "next_attempt_at": "2099-01-01T00:00:00+00:00",
+ "failure_id": f"run-backoff-{index:03d}",
+ },
+ )
+
+ captured: list[tuple[str, Any]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ captured.append((statement, parameters))
+
+ event.listen(sqlite_store.engine, "before_cursor_execute", _capture)
+ try:
+ assert sqlite_store.list_owed_failure_notices(now="2026-07-27T12:00:00+00:00") == []
+ finally:
+ event.remove(sqlite_store.engine, "before_cursor_execute", _capture)
+
+ statement, parameters = captured[-1]
+ raw = sqlite3.connect(str(tmp_path / "state" / "vibe.sqlite"))
+ try:
+ plan = [row[-1] for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters)]
+ finally:
+ raw.close()
+ rendered = "\n".join(plan)
+
+ assert OWED_NOTICE_INDEX in rendered, f"plan was:\n{rendered}"
+ # TWO constrained terms. The previous index produced ``(<expr>=?)`` — state
+ # only — which is what let the backoff walk stay unbounded while every other
+ # assertion in the old test still held.
+ assert "AND" in rendered.split(OWED_NOTICE_INDEX, 1)[1].split("\n")[0], (
+ f"the backoff term must be constrained by the index, not filtered per row; plan was:\n{rendered}"
+ )
+
+
+def test_the_eligibility_seek_still_constrains_both_terms_with_off_domain_rows(
+ tmp_path: Path,
+) -> None:
+ """HFR-086 — the plan must survive the values the domain normalization admits.
+
+ A PIN, not a repair: HFR-086 above proves the seek constrains both terms over
+ text-only rows, and the eligibility domain now admits values that are not text at
+ all. Whether an index over a JSON expression still yields a two-term range
+ constraint when the indexed values span several STORAGE CLASSES is a property of
+ SQLite, not of this code — so it is asserted rather than argued.
+
+ The reasoning it replaces: a numeric key sorts below every text key, so the
+ ``<= now`` upper bound still bounds it and the range stays a range; a container key
+ sorts above every ISO instant, so it falls outside the bound and is never visited.
+ Both are conclusions about the b-tree, and the way to keep a conclusion true is to
+ fail the build when it stops being.
+
+ Stronger than HFR-086 on the two failure modes that make the tick unbounded again:
+ no ``TEMP B-TREE`` (the ``ORDER BY`` must still be served by the index) and no
+ ``SCAN`` of ``agent_runs`` (one off-domain row must not cost a full walk).
+ """
+
+ import sqlite3
+
+ from sqlalchemy import event
+
+ sqlite_store, _requests = _store(tmp_path)
+ _task(sqlite_store, "task-mixed")
+ # Text rows, all in backoff: the population HFR-086 pins.
+ for index in range(40):
+ _pending_failure(
+ sqlite_store,
+ f"run-text-{index:03d}",
+ "task-mixed",
+ created_at=f"2026-07-27T00:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 3,
+ "next_attempt_at": "2099-01-01T00:00:00+00:00",
+ "failure_id": f"run-text-{index:03d}",
+ },
+ )
+ # ...and every off-domain shape, interleaved through the same index: numerics and
+ # booleans (below the bound, so INSIDE the range), padded instants (text, early),
+ # and containers (above every instant, so outside the range).
+ off_domain: list[Any] = [
+ 30000,
+ 30001,
+ -5,
+ 0,
+ 3.5,
+ 1e25,
+ True,
+ False,
+ " 9999-01-01T00:00:00+00:00",
+ " 2020-01-01T00:00:00+00:00",
+ {"a": 1},
+ [1],
+ ]
+ for index, value in enumerate(off_domain):
+ _pending_failure(
+ sqlite_store,
+ f"run-offdomain-{index:03d}",
+ "task-mixed",
+ created_at=f"2026-07-26T00:{index:02d}:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": value,
+ "failure_id": f"run-offdomain-{index:03d}",
+ },
+ )
+
+ captured: list[tuple[str, Any]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ captured.append((statement, parameters))
+
+ event.listen(sqlite_store.engine, "before_cursor_execute", _capture)
+ try:
+ listed = sqlite_store.list_owed_failure_notices(now="2026-07-27T12:00:00+00:00")
+ finally:
+ event.remove(sqlite_store.engine, "before_cursor_execute", _capture)
+
+ # The rows the domain admits came back, and nothing the domain excludes did — the
+ # plan below is a plan for the query that actually answers this population.
+ ids = {str(item["id"]) for item in listed}
+ assert ids and all(run_id.startswith("run-offdomain-") for run_id in ids), (
+ f"the seek returned rows outside the admitted domain: {sorted(ids)}"
+ )
+
+ statement, parameters = captured[-1]
+ raw = sqlite3.connect(str(tmp_path / "state" / "vibe.sqlite"))
+ try:
+ plan = [row[-1] for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters)]
+ finally:
+ raw.close()
+ rendered = "\n".join(plan)
+
+ assert OWED_NOTICE_INDEX in rendered, f"plan was:\n{rendered}"
+ assert "AND" in rendered.split(OWED_NOTICE_INDEX, 1)[1].split("\n")[0], (
+ "both the state and the next-attempt terms must stay CONSTRAINED with "
+ f"off-domain values in the index; plan was:\n{rendered}"
+ )
+ assert "TEMP B-TREE" not in rendered.upper(), (
+ f"the ORDER BY fell back to a temp sort; plan was:\n{rendered}"
+ )
+ assert "SCAN" not in rendered.upper(), (
+ f"one off-domain row cost a full table walk; plan was:\n{rendered}"
+ )
+
+
+def test_the_drain_and_a_backend_supplied_identity_agree_for_harness_runs(
+ tmp_path: Path,
+) -> None:
+ """HFR-087 — the ordinary/interruption split still collided on a third path.
+
+ Codex and OpenCode pass an explicit ``failure_id`` (the Codex ``turn_id``, an
+ OpenCode message/session id) at five call sites, and ``_failure_identity``
+ prioritises an explicit value over ``task_execution_id``. For a scheduled run on
+ those backends the live notification is keyed by the backend's id while the
+ drain stamps the run id, so the drain cannot find the already-persisted live
+ notification and the user gets a duplicate.
+
+ Aligning them cannot simply mean "explicit always wins" either, because the
+ drain's own ``interrupt:{run}:{reason}`` is an explicit id that MUST stay
+ distinct from the ordinary one.
+ """
+
+ from core.backend_failure import backend_failure_notification_output
+ from modules.im import MessageContext
+
+ harness_context = MessageContext(
+ user_id="scheduled",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={"task_execution_id": "run-abc", "task_trigger_kind": "scheduled"},
+ )
+
+ # What Codex produces live for a SCHEDULED run: an explicit backend turn id.
+ live = backend_failure_notification_output(
+ harness_context, "codex", failure_id="codex-turn-77"
+ ).idempotency_key
+ # What the drain stamps and replays.
+ replay = backend_failure_notification_output(
+ harness_context, "codex", failure_id="run-abc", failure_id_authoritative=True
+ ).idempotency_key
+
+ assert live == replay, "the drain would duplicate a notification Codex already sent"
+
+ # A non-harness context has no run to align to, so the backend's id still wins.
+ plain_context = MessageContext(user_id="u", channel_id="C1", platform="slack")
+ plain = backend_failure_notification_output(
+ plain_context, "codex", failure_id="codex-turn-77"
+ ).idempotency_key
+ assert "codex-turn-77" in plain
+
+ # And an interruption stays distinct from the ordinary identity for the same run.
+ interrupt = backend_failure_notification_output(
+ harness_context,
+ "codex",
+ failure_id="interrupt:run-abc:restarted",
+ failure_id_authoritative=True,
+ ).idempotency_key
+ assert interrupt != live
+
+
+def test_the_drain_preserves_an_authoritative_interruption_identity(tmp_path: Path) -> None:
+ """HFR-091 — HFR-087's alignment must not eat the interruption identity.
+
+ ``_failure_identity`` honours an explicit id outright only when the caller says
+ it is AUTHORITATIVE; otherwise the harness run-id override wins, which is what
+ aligns a backend's own turn id with the drain's replay (HFR-087). The drain
+ passed its explicit ``failure_id`` without that flag, so ``interrupt:{run}:{reason}``
+ — stamped precisely so a D1 interruption cannot be swallowed by the dedup for an
+ ordinary failure on the same execution — collapsed back to the bare run id at
+ the one call site that reads it off a durable row.
+
+ HFR-082 asserts the two identities differ when the flag is set, and HFR-087 that
+ the ordinary lane still aligns. Neither could see this, because both call
+ ``backend_failure_notification_output`` directly. This one drives the REAL drain
+ and reads the identity off the row a user keeps, which is why the authority is
+ now a property of ``emit_replayed_backend_failure`` rather than an argument any
+ call site can forget.
+ """
+
+ _migrated_state_db()
+ controller, _dispatcher, touched = _live_turn_dispatcher()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-interrupt-drain", deliver_key="slack::channel::C123")
+ run = requests.enqueue_task_run("task-interrupt-drain")
+ requests.claim(run.id)
+ assert "restarted" in RUN_INTERRUPTION_REASONS
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="interrupted by a restart",
+ metadata={"interrupt_reason": "restarted"},
+ )
+
+ expected_failure_id = f"interrupt:{run.id}:restarted"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["failure_id"] == expected_failure_id
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ emissions = _spy_emissions(controller)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_SENT
+ visible = [item for item in emissions if item["type"] == "notify"]
+ assert len(visible) == 1
+ assert visible[0]["output"].idempotency_key == f"backend-failure:{expected_failure_id}", (
+ "the drain's interruption identity collapsed into the ordinary failure's"
+ )
+
+ # And on the durable row, which is what the dedup lookup and the D1 notice's
+ # survival actually depend on.
+ rows = _persisted_messages()
+ assert len(rows) == 1
+ assert rows[0]["native_message_id"].endswith(f"backend-failure:{expected_failure_id}")
+ assert f'"failure_id": "{expected_failure_id}"' in rows[0]["metadata_json"]
+ assert touched == []
+
+
+def test_a_suppressed_lane_reason_never_takes_the_interruption_identity_or_copy(
+ tmp_path: Path,
+) -> None:
+ """HFR-092 — ``interrupt_reason`` presence is not the interruption lane.
+
+ ``interrupt_reason`` is the general marker for "terminalized by something other
+ than its own backend result", and most values it carries are ordinary per-fire
+ verdicts: ``no_terminal_result``, ``refused_concurrent_turn``,
+ ``transport_unavailable``, ``queue_hold_expired``. Those recur on every fire and
+ belong in the SUPPRESSED failure lane — which is exactly what
+ ``failure_notices.is_interruption`` says, by membership in
+ ``RUN_INTERRUPTION_REASONS``.
+
+ Two other places asked the question by PRESENCE instead:
+
+ * the stamp (``_owed_failure_notice_for_transition``) minted
+ ``interrupt:{run}:{reason}`` for any non-empty reason, and
+ * the copy (``_failure_notice_body``) rendered the "was interrupted, nothing is
+ wrong with the definition itself" headline for any non-empty reason.
+
+ Both are wrong for the commonest failures, and the identity half is now
+ load-bearing: the drain's ``failure_id`` is AUTHORITATIVE (HFR-091), so an id
+ the live path never used is an id the dedup cannot match — one duplicate
+ notification per suppressed-lane failure. The copy half tells the user their
+ definition is fine when it is the definition that is broken.
+ """
+
+ from types import SimpleNamespace
+
+ from core import failure_notices
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-suppressed", name="daily report", deliver_key="slack::channel::C1")
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+
+ run = requests.enqueue_task_run("task-suppressed")
+ requests.claim(run.id)
+ assert "no_terminal_result" not in RUN_INTERRUPTION_REASONS
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="the turn ended without dispatching an agent",
+ metadata={"interrupt_reason": "no_terminal_result"},
+ )
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["interrupt_reason"] == "no_terminal_result", (
+ "the reason itself is still recorded — it is a copy selector, not a lane"
+ )
+ # The lane, from the one predicate that decides it.
+ assert failure_notices.is_interruption(notice) is False
+ assert notice["failure_id"] == run.id, (
+ "a suppressed-lane failure must carry the identity the live path uses, or the "
+ "authoritative replay duplicates a notification already delivered"
+ )
+
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._t = lambda key, **kwargs: key
+
+ body = service._failure_notice_body(sqlite.get_run(run.id), notice)
+ assert "harness.notice.failed" in body
+ assert "harness.notice.interrupted" not in body, (
+ "a recurring per-fire verdict must not be reported as an out-of-band interruption"
+ )
+
+
+def test_the_drain_and_the_live_path_agree_for_a_suppressed_lane_reason(
+ tmp_path: Path,
+) -> None:
+ """HFR-093 — recurring live failures enter the durable policy before delivery.
+
+ Two consecutive executions fail for the same definition. Each backend reports
+ its failure live, but that path owns settlement only; the owed-notice drain owns
+ visible delivery and can therefore send the first failure while suppressing the
+ rest of the streak. Delivering before settlement would produce two rows before
+ the drain had any opportunity to classify the streak.
+ """
+
+ from core.backend_failure import emit_backend_failure
+ from core.scheduled_tasks import parse_session_key
+
+ _migrated_state_db()
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-suppressed-dedup", deliver_key="slack::channel::C123")
+ runs = []
+ for _index in range(2):
+ run = requests.enqueue_task_run("task-suppressed-dedup")
+ requests.claim(run.id)
+ sqlite.settle_run_terminal(
+ run.id,
+ terminal_status="failed",
+ error="backend failed",
+ )
+ assert sqlite.owed_failure_notice(run.id)["state"] == "pending"
+ runs.append(run)
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ target = parse_session_key("slack::channel::C123")
+ for run in runs:
+ live_context = asyncio.run(
+ service._build_context(
+ target,
+ delivery_target=target,
+ execution_id=run.id,
+ task_id="task-suppressed-dedup",
+ trigger_kind="scheduled",
+ )
+ )
+ asyncio.run(
+ emit_backend_failure(
+ controller,
+ live_context,
+ "harness",
+ "backend failed",
+ display_text="the live notice",
+ )
+ )
+ live_rows = [
+ row for row in _persisted_messages() if "backend-failure:" in (row["native_message_id"] or "")
+ ]
+ assert live_rows == [], (
+ "Harness live emitters settle only; visible delivery belongs to the durable "
+ f"notice policy: {live_rows}"
+ )
+
+ asyncio.run(service._drain_failure_notices())
+
+ rows = [
+ row for row in _persisted_messages() if "backend-failure:" in (row["native_message_id"] or "")
+ ]
+ assert len(rows) == 1, (
+ "one recurring failure streak must produce one durable notification, got "
+ f"{[row['native_message_id'] for row in rows]}"
+ )
+ assert rows[0]["native_message_id"].endswith(f"backend-failure:{runs[0].id}")
+ assert sqlite.owed_failure_notice(runs[0].id)["state"] == "sent"
+ assert sqlite.owed_failure_notice(runs[1].id)["state"] == "skipped"
+
+
+def test_the_index_migration_and_the_query_use_the_same_expressions(tmp_path: Path) -> None:
+ """HFR-088 — index/query drift is silent, so it needs its own assertion.
+
+ The planner matches an index expression to a query expression by structure. A
+ one-character difference makes it decline, and nothing reports that: the index
+ is built, ignored, and the query keeps returning correct results at scan cost.
+ That happened twice while fixing this — once from bound parameters, once from
+ editing only one of the two copies.
+
+ The migration cannot import the store (migrations must stay stable against a
+ moving codebase), so the strings are duplicated on purpose and pinned here —
+ the same mirror discipline ``SWEEP_I18N_KEYS`` already uses.
+ """
+
+ from importlib import import_module
+
+ from storage.background import OWED_NOTICE_NEXT_ATTEMPT_SQL, OWED_NOTICE_STATE_SQL
+
+ migration = import_module(
+ "storage.alembic.versions.20260728_0041_agent_runs_owed_notice_backoff_index"
+ )
+
+ assert migration._STATE_EXPR == OWED_NOTICE_STATE_SQL
+ assert migration._NEXT_ATTEMPT_EXPR == OWED_NOTICE_NEXT_ATTEMPT_SQL
+
+
+def test_a_notice_stamped_without_a_backoff_field_is_still_reachable(tmp_path: Path) -> None:
+ """HFR-089 — a null backoff must read as "eligible now", not as unreachable.
+
+ Making the backoff a pure ``<= now`` range term is what lets the index constrain
+ it, but a NULL never satisfies ``<=``. Any notice stamped before that field
+ existed — or by any writer that leaves it unset — would silently drop out of the
+ drain forever. ``coalesce(..., '')`` inside the indexed expression keeps it a
+ range term AND keeps those rows visible, because the empty string sorts before
+ every ISO instant.
+ """
+
+ sqlite_store, _requests = _store(tmp_path)
+ _task(sqlite_store, "task-legacy")
+ _pending_failure(
+ sqlite_store,
+ "run-legacy",
+ "task-legacy",
+ created_at="2026-07-27T00:00:00+00:00",
+ notice={"state": "pending", "attempts": 0, "next_attempt_at": None, "failure_id": "run-legacy"},
+ )
+
+ owed = sqlite_store.list_owed_failure_notices(now="2026-07-27T12:00:00+00:00")
+
+ assert [item["id"] for item in owed] == ["run-legacy"]
+
+
+# --- group 2g: the streak read itself --------------------------------------
+#
+# ``failure_streak`` runs once per pending notice on the same two-second tick as
+# the eligibility lookup, so it is under the same bound — and it was the last read
+# in this path that was not. The oracle below is the algorithm it used to be:
+# ``_definition_verdict_rows`` materialised a definition's ENTIRE settled lifetime
+# and sliced the streak out of it in Python. Kept here rather than deleted so the
+# SQL replacement has something to be equal to.
+
+
+def _materialized_streak(
+ sqlite_store: SQLiteBackgroundTaskStore, definition_id: str, run_id: str
+) -> list[dict]:
+ """The pre-SQL streak, computed by materialising the whole definition.
+
+ Byte-for-byte the production algorithm as of ``4558fc35`` — the lifetime
+ ``SELECT`` ordered by ``(created_at, id)``, the per-row ``interrupt_reason``
+ decode, and the two Python scans outward from the run. It is the specification
+ the SQL has to reproduce, including its edge cases.
+ """
+
+ import storage.background as background
+ from sqlalchemy import or_ as sa_or, select as sa_select
+ from storage.background import (
+ OWED_FAILURE_NOTICE_KEY as NOTICE_KEY,
+ _status_query_values,
+ normalize_run_status,
+ )
+ from storage.models import agent_runs
+
+ verdicts = _status_query_values("succeeded") + _status_query_values("failed")
+ stmt = (
+ sa_select(agent_runs)
+ .where(agent_runs.c.definition_id == definition_id)
+ .where(sa_or(agent_runs.c.run_type.is_(None), agent_runs.c.run_type != "watch_runtime"))
+ .where(agent_runs.c.status.in_(verdicts))
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ )
+ rows: list[dict] = []
+ with sqlite_store.engine.connect() as conn:
+ for row in conn.execute(stmt).mappings():
+ metadata = background._json_loads(row["metadata_json"], {})
+ metadata = metadata if isinstance(metadata, dict) else {}
+ reason = str(metadata.get("interrupt_reason") or "").strip()
+ if reason in RUN_INTERRUPTION_REASONS:
+ continue
+ rows.append(
+ {
+ "id": row["id"],
+ "created_at": row["created_at"],
+ "status": normalize_run_status(row["status"]),
+ "notice": metadata.get(NOTICE_KEY)
+ if isinstance(metadata.get(NOTICE_KEY), dict)
+ else None,
+ }
+ )
+ index = next((position for position, row in enumerate(rows) if row["id"] == run_id), None)
+ if index is None:
+ return []
+ start = index
+ while start > 0 and rows[start - 1]["status"] == "failed":
+ start -= 1
+ end = index
+ while end + 1 < len(rows) and rows[end + 1]["status"] == "failed":
+ end += 1
+ return rows[start : end + 1]
+
+
+def _agent_run_query_plans(sqlite_store, db_path: Path, call) -> list[tuple[str, list[str]]]:
+ """Every ``agent_runs`` SELECT one call issues, with its query plan."""
+
+ import sqlite3
+
+ from sqlalchemy import event
+
+ captured: list[tuple[str, Any]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ captured.append((statement, parameters))
+
+ event.listen(sqlite_store.engine, "before_cursor_execute", _capture)
+ try:
+ call()
+ finally:
+ event.remove(sqlite_store.engine, "before_cursor_execute", _capture)
+
+ plans: list[tuple[str, list[str]]] = []
+ raw = sqlite3.connect(str(db_path))
+ try:
+ for statement, parameters in captured:
+ plans.append(
+ (statement, [str(row[-1]) for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters)])
+ )
+ finally:
+ raw.close()
+ return plans
+
+
+def _agent_run_statements(sqlite_store, call) -> list[tuple[str, Any]]:
+ """Every ``agent_runs`` SELECT one call issues, with its bound parameters."""
+
+ from sqlalchemy import event
+
+ captured: list[tuple[str, Any]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ captured.append((statement, parameters))
+
+ event.listen(sqlite_store.engine, "before_cursor_execute", _capture)
+ try:
+ call()
+ finally:
+ event.remove(sqlite_store.engine, "before_cursor_execute", _capture)
+ return captured
+
+
+def _agent_run_query_result_sizes(sqlite_store, db_path: Path, call) -> list[int]:
+ """How many rows each ``agent_runs`` SELECT one call hands back.
+
+ The statement count says how many round trips a read costs; this says how much
+ of the table each round trip drags into Python. A read that filters in Python
+ passes both a statement-count budget and a plan that names an index while still
+ materialising an unbounded population, so the size of the result set is asserted
+ separately.
+ """
+
+ import sqlite3
+
+ raw = sqlite3.connect(str(db_path))
+ try:
+ return [
+ len(raw.execute(statement, parameters).fetchall())
+ for statement, parameters in _agent_run_statements(sqlite_store, call)
+ ]
+ finally:
+ raw.close()
+
+
+def _seed_streak_history(
+ sqlite_store, definition_id: str, total: int, *, ever_succeeded: bool = True
+) -> None:
+ """A long settled history whose failures sit in short, closed streaks.
+
+ ``ever_succeeded=False`` is the OPPOSITE case and it is the one that matters most:
+ a definition with no success anywhere has ONE streak as long as its lifetime, so
+ every bound expressed in terms of "the streak" is vacuous there. That is the shape
+ the old ``2 * len(streak) + 2`` decode budget could not constrain.
+ """
+
+ _task(sqlite_store, definition_id)
+ for index in range(total):
+ # Successes every seventh run, so the streak containing any given failure is
+ # at most six rows long while the lifetime is ``total``.
+ status = "succeeded" if ever_succeeded and index % 7 == 0 else "failed"
+ instant = f"2026-07-01T{index // 3600:02d}:{(index // 60) % 60:02d}:{index % 60:02d}+00:00"
+ sqlite_store.enqueue_run(
+ {
+ "id": f"run-{index:05d}",
+ "request_type": "scheduled",
+ "status": status,
+ "definition_id": definition_id,
+ "error": "boom" if status == "failed" else None,
+ "created_at": instant,
+ "completed_at": instant,
+ "metadata": {"owed_failure_notice": {"state": "pending", "attempts": 0}},
+ }
+ )
+
+
+def test_the_streak_read_is_bounded_and_seeks_rather_than_scans(tmp_path: Path) -> None:
+ """HFR-095 — the streak decision read runs on the 2 s tick and must be bounded.
+
+ Repointed at ``failure_streak_decision``, which is what the drain asks now. The
+ original scenario removed a lifetime ``SELECT`` ordered by ``(created_at, id)``
+ whose plan was::
+
+ SEARCH agent_runs USING INDEX ix_agent_runs_definition_created (definition_id=?)
+ USE TEMP B-TREE FOR LAST TERM OF ORDER BY
+
+ — one constrained term, an unindexed sort of the whole definition, and 5000
+ metadata blobs decoded to return one row. The seek-based replacement fixed the
+ plan but kept HANDING THE STREAK'S ROWS BACK, and its decode budget was written
+ as ``2 * len(streak) + 2``: a bound on the ANSWER, which is only a bound when the
+ answer is small. On a definition that has never succeeded the streak IS the
+ lifetime, so that budget permitted decoding the whole history — the same cost,
+ per pending notice, per tick.
+
+ Three properties, and the test would be incomplete without any of them:
+
+ * ONE STATEMENT. Also the correctness property, not just a cost one: one
+ statement is one SQLite read snapshot, which is what stops a success settling
+ mid-read from merging two streaks (see
+ ``test_a_success_settling_mid_read_cannot_merge_two_streaks``).
+ * ZERO metadata blobs decoded in Python, on BOTH shapes. Not "few" — the notice
+ states are compared inside SQLite through ``OWED_NOTICE_STATE_SQL``, so the
+ honest number is zero and any nonzero number means rows are crossing back into
+ Python again.
+ * The plan's CONSTRAINED TERMS, not the index name (HFR-086's lesson: a plan can
+ name an index while the term that matters stays a per-row filter). Both boundary
+ seeks, and the window seek constrained on BOTH ends.
+ """
+
+ import storage.background as background
+ from unittest.mock import patch
+
+ sqlite_store, _requests = _store(tmp_path)
+ lifetime = 5000
+ _seed_streak_history(sqlite_store, "task-streak-plan", lifetime)
+ # A failure late in the history whose streak is closed by a success on BOTH
+ # sides, so both boundary seeks have something to find.
+ target = "run-04997"
+ # The never-succeeded definition: one streak, `lifetime` rows long.
+ unbroken = 1500
+ _seed_streak_history(sqlite_store, "task-never-succeeded", unbroken, ever_succeeded=False)
+
+ def _decode_count(call) -> tuple[int, Any]:
+ decoded: list[int] = []
+ real_json_loads = background._json_loads
+
+ def _counting_json_loads(value, default):
+ decoded.append(1)
+ return real_json_loads(value, default)
+
+ with patch.object(background, "_json_loads", _counting_json_loads):
+ answer = call()
+ return len(decoded), answer
+
+ # 1. THE BRACKETED STREAK. run-04992 is the earliest pending row between the
+ # successes at 4991 and 4998, so it is the canonical notice.
+ decoded, facts = _decode_count(
+ lambda: sqlite_store.failure_streak_decision("task-streak-plan", target)
+ )
+ assert facts == {
+ "in_streak": True,
+ "has_sent_elsewhere": False,
+ "earliest_pending_id": "run-04992",
+ }, facts
+ assert decoded == 0, (
+ f"decoded {decoded} metadata blobs out of {lifetime} rows — the notice states are "
+ "compared in SQL, so nothing should be decoded in Python at all"
+ )
+
+ # 2. THE NEVER-SUCCEEDED DEFINITION, where "bounded by the streak" is no bound.
+ decoded, facts = _decode_count(
+ lambda: sqlite_store.failure_streak_decision("task-never-succeeded", "run-01499")
+ )
+ assert facts == {
+ "in_streak": True,
+ "has_sent_elsewhere": False,
+ "earliest_pending_id": "run-00000",
+ }, facts
+ assert decoded == 0, (
+ f"decoded {decoded} metadata blobs for a definition whose streak is its whole "
+ f"{unbroken}-run lifetime — this is the case the old O(streak) budget could not "
+ "constrain"
+ )
+
+ # 3. ONE STATEMENT, and one row back from it.
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ statements = _agent_run_statements(
+ sqlite_store, lambda: sqlite_store.failure_streak_decision("task-streak-plan", target)
+ )
+ assert len(statements) == 1, (
+ f"the streak decision must be ONE statement — one read snapshot — but issued "
+ f"{len(statements)}"
+ )
+ sizes = _agent_run_query_result_sizes(
+ sqlite_store, db_path, lambda: sqlite_store.failure_streak_decision("task-streak-plan", target)
+ )
+ assert sizes == [1], f"the decision is three scalars on one row; the read returned {sizes}"
+
+ # 4. THE PLAN.
+ plans = _agent_run_query_plans(
+ sqlite_store,
+ db_path,
+ lambda: sqlite_store.failure_streak_decision("task-streak-plan", target),
+ )
+ assert plans, "the streak decision read issued no agent_runs query"
+ lines = [line for _statement, plan in plans for line in plan]
+ rendered = "\n".join(lines)
+ compact = rendered.replace(" ", "")
+
+ # ``SCAN agent_runs`` is the property, and it is asserted as such rather than as
+ # ``"SCAN" not in ...``: the outer projection has no FROM at all, so SQLite reports
+ # a ``SCAN CONSTANT ROW`` for it. That is the single zero-table row the three
+ # scalars are projected onto, and pinning the allowed set keeps the assertion from
+ # being weakened into "no scan of agent_runs, probably".
+ assert {line for line in lines if "SCAN" in line} <= {"SCAN CONSTANT ROW"}, (
+ f"the streak decision must never scan a definition's history; plans were:\n{rendered}"
+ )
+ assert "TEMP B-TREE" not in rendered, (
+ f"the (created_at, id) order must come from an index, not a sort; plans were:\n{rendered}"
+ )
+ # The two boundary seeks, by their constrained terms. A plan that constrains only
+ # ``definition_id`` is the unbounded read this scenario exists to remove, and it
+ # would satisfy every assertion above once the sort is indexed away.
+ assert "(created_at,id)<(?,?)" in compact, (
+ f"the preceding success must be found by an indexed seek; plans were:\n{rendered}"
+ )
+ assert "(created_at,id)>(?,?)" in compact, (
+ f"the following success must be found by an indexed seek; plans were:\n{rendered}"
+ )
+ # ...and the window itself, constrained on BOTH ends by the boundaries above. This
+ # is the term the sentinel ``coalesce`` exists to preserve: spelled as
+ # ``(boundary IS NULL OR position > boundary)`` it would be a disjunction, and
+ # SQLite cannot use a disjunction as an index constraint.
+ assert "(definition_id=?AND(created_at,id)>(?,?)AND(created_at,id)<(?,?))" in compact, (
+ f"the streak window must be an indexed range on both ends; plans were:\n{rendered}"
+ )
+
+
+def test_the_sql_streak_facts_match_the_materialized_streak(tmp_path: Path) -> None:
+ """HFR-096 — the one-statement decision must decide what the streak's rows decided.
+
+ Repointed at ``failure_streak_decision``, and the oracle is COMPOSED rather than
+ replaced: ``_materialized_streak`` still computes the streak the pre-SQL algorithm
+ computed, and ``_facts`` still derives from those rows exactly what ``decide`` used
+ to derive inline. Their composition is therefore the full old behaviour end to end,
+ and it is what the new statement is checked against — a parity test against a
+ reimplementation of the new code would prove nothing.
+
+ Randomised histories carry every row class that decides the answer: successes and
+ failures, ``canceled``/``queued`` rows that are not verdicts at all, interruptions
+ whose reason IS in ``RUN_INTERRUPTION_REASONS`` (transparent: skipped, and neither
+ joining nor closing a streak), interruptions whose reason is NOT
+ (``no_terminal_result`` and friends — ordinary failures that DO join),
+ ``watch_runtime`` heartbeats, notices in all four states, and runs sharing one
+ ``created_at`` so the ``id`` tie-break decides ordering.
+
+ Every run in the history is asked for, not just failures: the streak is defined
+ relative to the run it is given, and a caller that hands it a succeeded or
+ excluded row must get the same answer it got before. ``run-does-not-exist`` is
+ asked too, because that is the case where a missing anchor could turn the window
+ into the definition's whole history.
+ """
+
+ import random
+
+ outside_the_lane = ["no_terminal_result", "refused_concurrent_turn", "queue_hold_expired"]
+ inside_the_lane = sorted(RUN_INTERRUPTION_REASONS)
+
+ sqlite_store, _requests = _store(tmp_path)
+ for seed in range(6):
+ rng = random.Random(seed)
+ definition_id = f"task-parity-{seed}"
+ _task(sqlite_store, definition_id)
+ ids: list[str] = []
+ for index in range(40):
+ run_id = f"run-{seed}-{index:03d}"
+ ids.append(run_id)
+ # A small pool of instants, so identical timestamps are common and the
+ # ``id`` tie-break decides the sequence.
+ instant = f"2026-07-27T00:{rng.randrange(6):02d}:00+00:00"
+ status = rng.choice(["failed", "failed", "failed", "succeeded", "canceled", "queued"])
+ metadata: dict[str, Any] = {}
+ roll = rng.random()
+ if roll < 0.2:
+ metadata["interrupt_reason"] = rng.choice(inside_the_lane)
+ elif roll < 0.4:
+ metadata["interrupt_reason"] = rng.choice(outside_the_lane)
+ if rng.random() < 0.2:
+ metadata[OWED_FAILURE_NOTICE_KEY] = {
+ "state": rng.choice(["pending", "sent", "skipped", "failed"]),
+ "attempts": 1,
+ }
+ request_type = "watch_runtime" if rng.random() < 0.1 else "scheduled"
+ sqlite_store.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": request_type,
+ "status": status,
+ "definition_id": definition_id,
+ "error": "boom" if status == "failed" else None,
+ "created_at": instant,
+ "completed_at": instant,
+ "metadata": metadata,
+ }
+ )
+
+ for run_id in [*ids, "run-does-not-exist"]:
+ streak = _materialized_streak(sqlite_store, definition_id, run_id)
+ expected = _facts(streak, run_id)
+ actual = sqlite_store.failure_streak_decision(definition_id, run_id)
+ assert actual == expected, (
+ f"seed {seed}, run {run_id}: the SQL streak facts disagree with the ones "
+ f"derived from the materialized streak\n"
+ f" streak {[(row['id'], row['status'], (row.get('notice') or {}).get('state')) for row in streak]}\n"
+ f" expected {expected}\n"
+ f" actual {actual}"
+ )
+
+
+def _legacy_decide(
+ *,
+ run_id: str,
+ definition_id: str | None,
+ notice: dict | None,
+ streak: list[dict],
+ earlier_unsettled: dict | None,
+):
+ """``core.failure_notices.decide`` as of ``467b7c80``, taking the streak's ROWS.
+
+ Byte-for-byte the branch order and reason strings of the version that derived
+ "anyone sent?" and "who is canonical?" in Python. Kept as the oracle for
+ ``test_the_facts_decide_exactly_what_the_streak_rows_decided``: moving a
+ derivation into SQL is only safe if no outcome moved with it, and that is a claim
+ about the OLD code, so the old code has to be present to check it against.
+ """
+
+ from core.failure_notices import (
+ ACTION_DEFER,
+ ACTION_DELIVER,
+ ACTION_SKIP,
+ NoticeDecision,
+ is_binding_change,
+ is_interruption,
+ )
+
+ if is_interruption(notice):
+ return NoticeDecision(ACTION_DELIVER, "interruption")
+ if is_binding_change(notice):
+ return NoticeDecision(ACTION_DELIVER, "binding_change")
+ if not definition_id:
+ return NoticeDecision(ACTION_DELIVER, "no_definition")
+ if earlier_unsettled is not None:
+ return NoticeDecision(ACTION_DEFER, f"earlier_run_unsettled:{earlier_unsettled['id']}")
+ others = [row for row in streak if row["id"] != run_id]
+ if any((row.get("notice") or {}).get("state") == "sent" for row in others):
+ return NoticeDecision(ACTION_SKIP, "streak_already_notified")
+ canonical = next(
+ (row for row in streak if (row.get("notice") or {}).get("state") == "pending"),
+ None,
+ )
+ if canonical is None or canonical["id"] == run_id:
+ return NoticeDecision(ACTION_DELIVER, "canonical")
+ return NoticeDecision(ACTION_DEFER, f"canonical_pending:{canonical['id']}")
+
+
+def test_the_facts_decide_exactly_what_the_streak_rows_decided() -> None:
+ """Subordinate to HFR-096 — the rewrite must not move a single outcome.
+
+ ``decide`` stopped receiving the streak and started receiving three facts about
+ it. Parity for the SQL that produces those facts is
+ ``test_the_sql_streak_facts_match_the_materialized_streak``; this is parity for the
+ CONSUMER, against ``_legacy_decide`` — the version that took the rows.
+
+ The matrix is exhaustive over what the branches read, not sampled: every notice
+ lane (ordinary failure, each interruption reason in and out of the lane, binding
+ change), present and absent ``definition_id``, present and absent
+ ``earlier_unsettled``, and every streak shape that can change the answer —
+ empty, this row alone, this row with earlier/later rows in each of the four
+ notice states, this row not pending itself, and a streak this row is not in.
+
+ ``reason`` is compared, not just ``action``: the reasons are written into the row
+ as ``skip_reason``/``defer_reason`` and read back by operators, and
+ ``canonical_pending:<id>`` names a specific run.
+ """
+
+ from core.failure_notices import decide
+
+ states = [None, "pending", "sent", "skipped", "failed"]
+
+ def _row(run_id: str, state: str | None) -> dict:
+ return _streak_row(run_id, notice=None if state is None else _notice(state))
+
+ run_id = "run-02"
+ streaks: list[list[dict]] = [
+ [],
+ [_row("run-02", "pending")],
+ [_row("run-02", "sent")],
+ [_row("run-02", None)],
+ # A streak this row is not a member of at all — the shape a non-verdict anchor
+ # produced as ``[]`` before, and which must still deliver.
+ [_row("run-01", "pending"), _row("run-03", "sent")],
+ ]
+ for earlier in states:
+ for later in states:
+ streaks.append(
+ [_row("run-01", earlier), _row("run-02", "pending"), _row("run-03", later)]
+ )
+ # ...and the same with THIS row not pending, which decides whether the
+ # canonical can be a row other than the one being asked about.
+ streaks.append(
+ [_row("run-01", earlier), _row("run-02", "failed"), _row("run-03", later)]
+ )
+
+ notices: list[dict] = [
+ _notice("pending"),
+ _notice("pending", kind="binding_change"),
+ _notice("pending", interrupt_reason="restarted"),
+ _notice("pending", interrupt_reason="no_terminal_result"),
+ _notice("pending", interrupt_reason=""),
+ ]
+ unsettled = [None, {"id": "run-00", "created_at": "2026-07-27T00:00:00+00:00", "status": "queued"}]
+
+ checked = 0
+ for streak in streaks:
+ for notice in notices:
+ for definition_id in ("task-1", None):
+ for earlier_unsettled in unsettled:
+ expected = _legacy_decide(
+ run_id=run_id,
+ definition_id=definition_id,
+ notice=notice,
+ streak=streak,
+ earlier_unsettled=earlier_unsettled,
+ )
+ actual = decide(
+ run_id=run_id,
+ definition_id=definition_id,
+ notice=notice,
+ streak_facts=_facts(streak, run_id),
+ earlier_unsettled=earlier_unsettled,
+ )
+ assert (actual.action, actual.reason) == (expected.action, expected.reason), (
+ f"streak {[(row['id'], (row.get('notice') or {}).get('state')) for row in streak]}, "
+ f"notice {notice}, definition {definition_id}, unsettled {earlier_unsettled}: "
+ f"expected {expected}, got {actual}"
+ )
+ checked += 1
+
+ # The matrix is worth stating: a silently-shrinking parity sweep is how a rewrite
+ # gets declared equivalent against three cases.
+ assert checked == len(streaks) * len(notices) * 2 * 2 == 1100
+
+
+def test_a_success_settling_mid_read_cannot_merge_two_streaks(tmp_path: Path) -> None:
+ """Subordinate to HFR-095 — the decision must describe ONE state of the database.
+
+ pysqlite opens no transaction for reads, so a multi-statement read is several
+ snapshots. The streak's boundaries were seeked by one statement and its rows read
+ by a later one, and a success settling in that gap made the read describe a
+ history that had already stopped existing: the boundary said "no success before
+ this run", so the row read swept in the PREVIOUS outage's rows, and that outage's
+ ``sent`` notice made ``decide`` answer SKIP for a live one.
+
+ That answer is written DURABLY (``state='skipped'``), which is what makes it a
+ lost notice rather than a late one: nothing revisits a skipped row, so the outage
+ is never reported at all. D1 direction.
+
+ The invariant asserted is the one that matters and it is stated without reference
+ to statement counts: the facts the drain is about to write must match the database
+ it is writing about, computed independently by ``_materialized_streak`` AFTER the
+ read returns. A concurrent writer is scheduled at the point where a multi-statement
+ read is exposed — partway through. A one-statement read has no partway, which is
+ the property, and it is why the writer never fires against it.
+ """
+
+ import sqlite3
+
+ from sqlalchemy import event
+
+ sqlite_store, _requests = _store(tmp_path)
+ _task(sqlite_store, "task-torn")
+
+ def _run(run_id: str, status: str, instant: str, state: str | None) -> None:
+ sqlite_store.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": status,
+ "definition_id": "task-torn",
+ "error": "boom" if status == "failed" else None,
+ "created_at": instant,
+ "completed_at": instant if status != "running" else None,
+ "metadata": {} if state is None else {OWED_FAILURE_NOTICE_KEY: {"state": state, "attempts": 1}},
+ }
+ )
+
+ # The PREVIOUS outage, already reported.
+ _run("run-a", "failed", "2026-07-27T01:00:00+00:00", "sent")
+ # The recovery that closes it — still RUNNING when the read starts, which is why
+ # the boundary seek cannot see it yet.
+ _run("run-s", "running", "2026-07-27T02:00:00+00:00", None)
+ # The LIVE outage. Alone in its own streak once run-s settles, so the user must be
+ # told about it.
+ _run("run-b", "failed", "2026-07-27T03:00:00+00:00", "pending")
+
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ seen: list[int] = []
+
+ def _settle_the_recovery(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" not in statement or not statement.strip().upper().startswith(("SELECT", "WITH")):
+ return
+ seen.append(1)
+ # From the THIRD statement onward: a multi-statement read has taken its
+ # boundaries by then and has not yet read its rows, which is exactly the gap.
+ # A one-statement read never reaches this point.
+ if len(seen) < 3:
+ return
+ other = sqlite3.connect(str(db_path))
+ try:
+ other.execute(
+ "update agent_runs set status = 'succeeded', completed_at = ? where id = 'run-s'",
+ ("2026-07-27T02:30:00+00:00",),
+ )
+ other.commit()
+ finally:
+ other.close()
+
+ event.listen(sqlite_store.engine, "before_cursor_execute", _settle_the_recovery)
+ try:
+ facts = sqlite_store.failure_streak_decision("task-torn", "run-b")
+ finally:
+ event.remove(sqlite_store.engine, "before_cursor_execute", _settle_the_recovery)
+
+ # The database AS IT NOW STANDS, read independently of the decision.
+ truth = _facts(_materialized_streak(sqlite_store, "task-torn", "run-b"), "run-b")
+ assert facts == truth, (
+ "the streak decision describes a history that no longer exists: it was written "
+ f"from {facts} while the database says {truth}"
+ )
+
+ # ...and the consequence, so a future reader can see what the mismatch costs.
+ from core.failure_notices import ACTION_SKIP, decide
+
+ action = decide(
+ run_id="run-b",
+ definition_id="task-torn",
+ notice=_notice("pending"),
+ streak_facts=facts,
+ earlier_unsettled=None,
+ ).action
+ expected_action = decide(
+ run_id="run-b",
+ definition_id="task-torn",
+ notice=_notice("pending"),
+ streak_facts=truth,
+ earlier_unsettled=None,
+ ).action
+ assert action == expected_action, (
+ f"the live outage on run-b is decided {action} from a stale window while the "
+ f"database says {expected_action}"
+ )
+ if action == ACTION_SKIP:
+ assert truth["has_sent_elsewhere"], (
+ "run-b was skipped as a duplicate, so a sent notice really has to be in its "
+ "streak — a skip is durable and nothing revisits it"
+ )
+
+# --- group 2c: delivery evidence ------------------------------------------
+
+
+def test_delivered_but_unpersisted_acks_on_the_delivery_id() -> None:
+ """A returned message id is positive evidence the user was told.
+
+ Re-sending because the DB write failed would spam a notice that already arrived.
+ The ack records ``delivery_only`` rather than pretending a receipt exists.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_DELIVERY_ONLY, STAGE_PERSIST, DeliveryEvidence
+
+ evidence = DeliveryEvidence(
+ delivered_id="1717.42",
+ persisted_row=None,
+ error=RuntimeError("disk is full"),
+ error_stage=STAGE_PERSIST,
+ )
+
+ assert evidence.delivered is True
+ assert evidence.ack_evidence == ACK_EVIDENCE_DELIVERY_ONLY
+ # The persistence exception's OWN message, not a generic string.
+ assert "disk is full" in evidence.error_text
+
+
+def test_a_send_that_returned_no_id_is_not_evidence_of_delivery() -> None:
+ """The notice must stay pending and be retried, never marked sent."""
+
+ from core.delivery_evidence import STAGE_SEND, DeliveryEvidence
+
+ evidence = DeliveryEvidence(error=ConnectionError("slack is down"), error_stage=STAGE_SEND)
+
+ assert evidence.delivered is False
+ assert evidence.ack_evidence is None
+ assert "slack is down" in evidence.error_text
+
+
+def test_a_post_delivery_error_is_not_a_delivery_failure() -> None:
+ """Send and persist succeeded; only the SSE fan-out raised.
+
+ Under the old single ``try`` this returned ``None`` — indistinguishable from a
+ failed send — so the drain would have re-sent a notice the user already had.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT, STAGE_STREAM, DeliveryEvidence
+
+ evidence = DeliveryEvidence(
+ delivered_id="1717.42",
+ persisted_row={"id": "msg-1"},
+ error=RuntimeError("sink closed"),
+ error_stage=STAGE_STREAM,
+ )
+
+ assert evidence.delivered is True
+ assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
+
+
+def test_an_avibe_send_returning_none_still_acks_on_its_receipt() -> None:
+ """avibe delivers over SSE, so the happy path returns ``None``.
+
+ A drain acking on "the function returned an id" would never acknowledge a
+ Workbench-targeted notice at all, and would re-send it every tick.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT, DeliveryEvidence
+
+ evidence = DeliveryEvidence(delivered_id=None, persisted_row={"id": "msg-1"}, send_returned=True)
+
+ assert evidence.delivered is True
+ assert evidence.ack_evidence == ACK_EVIDENCE_RECEIPT
+
+
+def test_persist_agent_message_surfaces_its_caught_exception() -> None:
+ """The error channel exists, and does NOT raise through the notify branch.
+
+ Letting it raise would be caught by the branch's blanket ``except`` and discard
+ the message id assigned on the line above, turning delivered-but-unpersisted
+ into looks-like-never-delivered.
+ """
+
+ from unittest.mock import patch
+
+ from core import message_mirror
+ from modules.im import MessageContext
+
+ context = MessageContext(user_id="u", channel_id="C1", platform="slack", platform_specific={"platform": "slack"})
+ sink: list = []
+ with patch.object(message_mirror, "get_cached_sqlite_engine", side_effect=RuntimeError("db is gone")):
+ result = message_mirror.persist_agent_message(context, "notify", "boom", error_sink=sink)
+
+ assert result is None
+ assert len(sink) == 1 and "db is gone" in str(sink[0])
+
+
+# --- group 3: derived health ----------------------------------------------
+
+
+def test_definition_health_reaches_the_cli_list_after_a_success(capsys) -> None:
+ """HFR-062 — one success must not erase days of failure on the CLI surface.
+
+ ``last_run_at``/``last_error`` are both overwritten on every fire, so a task
+ that failed three days running and then succeeded once reported a clean
+ ``succeeded`` and nothing else.
+
+ Asserted on ``health``/``recent_failures`` rather than on ``last_status``.
+ #1061 demoted ``last_status`` to a compatibility field that never determines
+ lifecycle, so an earlier revision of this test — which asserted
+ ``last_status == "degraded"`` — was pinning new semantics onto a field the
+ canonical projection is not supposed to read. Health is its own axis now.
+ """
+
+ import json
+ from datetime import datetime, timedelta, timezone
+
+ from storage.background import SQLiteBackgroundTaskStore
+ from storage.pagination import PageRequest
+ from vibe import cli
+
+ # Seeded RELATIVE to the wall clock, because the CLI path computes health
+ # from ``datetime.now`` — a fixed calendar date here was a time bomb that
+ # started aging runs out of the 72 h window three days after it was written.
+ def _instant(hours_ago: float) -> str:
+ return (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat()
+
+ store = SQLiteBackgroundTaskStore()
+ try:
+ _task(store, "task-cli")
+ for index in range(3):
+ store.enqueue_run(
+ {
+ "id": f"run-cli-fail-{index}",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-cli",
+ "error": "boom",
+ "created_at": _instant(8 - index),
+ "completed_at": _instant(7.5 - index),
+ }
+ )
+ store.enqueue_run(
+ {
+ "id": "run-cli-ok",
+ "request_type": "scheduled",
+ "status": "succeeded",
+ "definition_id": "task-cli",
+ "created_at": _instant(4),
+ "completed_at": _instant(3.5),
+ }
+ )
+ # What ``mark_task_result`` leaves behind after that final success.
+ store.upsert_scheduled_task(
+ {
+ "id": "task-cli",
+ "name": "task-cli",
+ "prompt": "go",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "created_at": _EPOCH,
+ "updated_at": _EPOCH,
+ "last_run_at": _instant(3.5),
+ "last_error": None,
+ }
+ )
+
+ assert cli.cmd_task_list(page_request=PageRequest(limit=20)) == 0
+ finally:
+ store.close()
+
+ entry = json.loads(capsys.readouterr().out)["definitions"][0]
+ assert entry["recent_failures"] == 3, "a success downgrades, it does not erase"
+ assert entry["health"] == "degraded"
+ # And the demoted compatibility field keeps #1061's three-valued vocabulary.
+ assert entry["last_status"] in {"failed", "succeeded", "never_run"}
+
+
+def test_brief_task_payload_carries_last_error(capsys) -> None:
+ """HFR-063 — ``vibe task list`` dropped ``last_error`` entirely.
+
+ The brief payload is an explicit allowlist, so the one field that says WHY a
+ task is failing never reached the list a user actually runs. It is forwarded
+ with the health fields now, since it answers the question the badge raises.
+ """
+
+ import json
+
+ from storage.background import SQLiteBackgroundTaskStore
+ from storage.pagination import PageRequest
+ from vibe import cli
+
+ store = SQLiteBackgroundTaskStore()
+ try:
+ _task(store, "task-broken", last_error="unresolvable session binding", last_run_at=_EPOCH)
+ assert cli.cmd_task_list(page_request=PageRequest(limit=20)) == 0
+ finally:
+ store.close()
+
+ entry = json.loads(capsys.readouterr().out)["definitions"][0]
+ assert entry["last_error"] == "unresolvable session binding"
+
+
+def test_a_watch_reports_health_on_the_same_terms_as_a_task(capsys) -> None:
+ """HFR-090 — a watch whose hook fails nightly is as invisible as a task.
+
+ ``_enrich_definitions`` computes health for both definition types, so the only
+ thing that decided whether it reached a surface was the projection allowlist.
+ """
+
+ import json
+ from datetime import datetime, timedelta, timezone
+
+ from storage.background import SQLiteBackgroundTaskStore
+ from storage.pagination import PageRequest
+ from vibe import cli
+
+ # Seeded RELATIVE to the wall clock, for the same reason HFR-062's sibling was
+ # (``c57ce4b8``): the CLI path computes health from ``datetime.now``, so a fixed
+ # calendar date here was a time bomb that started aging the run out of the 72 h
+ # window three days after it was written. This one was missed by that commit and
+ # went red on 2026-07-30 — the health it asserts is ``failing`` read ``healthy``
+ # once the seeded failure fell outside the window.
+ def _instant(hours_ago: float) -> str:
+ return (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat()
+
+ store = SQLiteBackgroundTaskStore()
+ try:
+ _watch(store, "watch-health")
+ store.enqueue_run(
+ {
+ "id": "run-watch-health",
+ "request_type": "watch",
+ "status": "failed",
+ "definition_id": "watch-health",
+ "error": "hook blew up",
+ "created_at": _instant(2),
+ "completed_at": _instant(1.98),
+ }
+ )
+ assert cli.cmd_watch_list(page_request=PageRequest(limit=20)) == 0
+ finally:
+ store.close()
+
+ entry = json.loads(capsys.readouterr().out)["definitions"][0]
+ assert entry["health"] == "failing"
+ assert entry["consecutive_failures"] == 1
+
+
+def test_storage_interruption_reasons_mirror_the_settlement_vocabulary() -> None:
+ """HFR-064 — the two spellings of the interruption class may not drift.
+
+ ``storage`` cannot import ``core``, so the set is declared in
+ ``core.run_settlement`` and mirrored as literals in ``storage.background``,
+ exactly as ``SWEEP_I18N_KEYS`` mirrors the sweep reasons. This is the test that
+ keeps the mirror honest.
+ """
+
+ from core.run_settlement import RUN_INTERRUPTION_REASONS as core_reasons
+ from storage.background import RUN_INTERRUPTION_REASONS as storage_reasons
+
+ assert set(core_reasons) == set(storage_reasons)
+
+
+def test_one_success_does_not_erase_recent_failure_history(tmp_path: Path) -> None:
+ """HFR-066 — P6 itself: ``last_run_at``/``last_error`` are overwritten every fire.
+
+ Three failed fires then one success leaves the definition indistinguishable
+ from one that has never failed, because both source fields are single-valued.
+ Health has to be derived from ``agent_runs``, which still holds all four rows.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-health")
+
+ for index in range(3):
+ sqlite.enqueue_run(
+ {
+ "id": f"run-fail-{index}",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-health",
+ "error": "boom",
+ "created_at": f"2026-07-27T0{index}:00:00+00:00",
+ "completed_at": f"2026-07-27T0{index}:30:00+00:00",
+ }
+ )
+ sqlite.enqueue_run(
+ {
+ "id": "run-ok",
+ "request_type": "scheduled",
+ "status": "succeeded",
+ "definition_id": "task-health",
+ "created_at": "2026-07-27T04:00:00+00:00",
+ "completed_at": "2026-07-27T04:30:00+00:00",
+ }
+ )
+
+ health = sqlite.definition_health("task-health", now="2026-07-27T05:00:00+00:00")
+
+ assert health["recent_failures"] == 3
+ assert health["consecutive_failures"] == 0
+ assert health["health"] == "degraded", "one success must downgrade, not erase"
+
+
+def test_result_less_settlement_still_counts_toward_health(tmp_path: Path) -> None:
+ """HFR-067 — an ``interrupt_reason`` is not by itself a D1 interruption.
+
+ ``metadata.interrupt_reason`` is master's general marker for "terminalized by
+ something other than its own backend result": ``_settle_agent_run_without_result``
+ writes ``no_terminal_result`` / ``refused_concurrent_turn`` / ``backend_refresh``
+ and ``sweep_stale_runs`` writes ``orphaned`` / ``transport_unavailable`` /
+ ``queue_hold_expired``. Only the last group is out-of-band interruption; the
+ rest are ordinary per-fire verdicts and are the COMMON P6 failure. A health
+ predicate keyed on ``interrupt_reason IS NULL`` excludes all of them and
+ reports a permanently broken definition as healthy.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-resultless")
+ sqlite.enqueue_run(
+ {
+ "id": "run-resultless",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-resultless",
+ "error": "the turn ended without a terminal result",
+ "created_at": "2026-07-27T03:00:00+00:00",
+ "completed_at": "2026-07-27T03:01:00+00:00",
+ "metadata": {"interrupt_reason": "no_terminal_result"},
+ }
+ )
+
+ health = sqlite.definition_health("task-resultless", now="2026-07-27T04:00:00+00:00")
+
+ assert health["consecutive_failures"] == 1
+ assert health["health"] == "failing"
+
+
+def test_cancellations_do_not_bury_a_failure_in_the_bounded_window(tmp_path: Path) -> None:
+ """HFR-068 — ``canceled`` is transparent, and by predicate rather than classifier.
+
+ A cancellation is the absence of an outcome. Skipping it while classifying
+ cannot make it transparent, because ``LIMIT N`` is applied first: N cancelled
+ retries after one failure fill the whole window and displace the failure, so
+ the definition reads healthy although nothing ever succeeded.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-cancel")
+ sqlite.enqueue_run(
+ {
+ "id": "run-failed",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-cancel",
+ "error": "boom",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ "completed_at": "2026-07-27T01:01:00+00:00",
+ }
+ )
+ for index in range(12):
+ sqlite.enqueue_run(
+ {
+ "id": f"run-cancel-{index}",
+ "request_type": "scheduled",
+ "status": "canceled",
+ "definition_id": "task-cancel",
+ "created_at": f"2026-07-27T02:{index:02d}:00+00:00",
+ "completed_at": f"2026-07-27T02:{index:02d}:30+00:00",
+ }
+ )
+
+ health = sqlite.definition_health("task-cancel", now="2026-07-27T03:00:00+00:00")
+
+ assert health["consecutive_failures"] == 1, "cancellations must not displace the failure"
+ assert health["health"] == "failing"
+
+
+def test_watch_runtime_heartbeat_does_not_reset_consecutive_failures(tmp_path: Path) -> None:
+ """HFR-069 — the supervisor heartbeat shares the watch's ``definition_id``.
+
+ ``write_watch_runtime`` stores ``runtime:<watch_id>`` with
+ ``definition_id = watch_id`` and flips the previous heartbeat to
+ ``succeeded`` on every write, so an unfiltered history has a success between
+ any two real failures and the watch reads healthy.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _watch(sqlite, "watch-1")
+ sqlite.enqueue_run(
+ {
+ "id": "run-watch-fail",
+ "request_type": "watch",
+ "status": "failed",
+ "definition_id": "watch-1",
+ "error": "hook blew up",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ "completed_at": "2026-07-27T01:01:00+00:00",
+ }
+ )
+ # The supervisor heartbeat, written after the failure and therefore newest.
+ sqlite.write_watch_runtime(
+ {"watches": {"watch-1": {"running": True, "started_at": "2026-07-27T02:00:00+00:00"}}},
+ updated_at="2026-07-27T02:00:00+00:00",
+ )
+
+ health = sqlite.definition_health("watch-1", now="2026-07-27T03:00:00+00:00")
+
+ assert health["consecutive_failures"] == 1, "the heartbeat is not an execution"
+ assert health["health"] == "failing"
+
+
+def test_nonterminal_execution_does_not_displace_the_newest_verdict(tmp_path: Path) -> None:
+ """HFR-070 — health is a function of settled outcomes only.
+
+ A failing recurring definition fires again on schedule; the fresh
+ ``queued``/``running`` row is the newest entry for the definition. It is not
+ an outcome, so reading "the latest run failed" off it reports a definition
+ that is actively failing as healthy for the whole duration of its next
+ attempt — and every fire re-arms that.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-inflight")
+ sqlite.enqueue_run(
+ {
+ "id": "run-old-fail",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-inflight",
+ "error": "boom",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ "completed_at": "2026-07-27T01:01:00+00:00",
+ }
+ )
+ sqlite.enqueue_run(
+ {
+ "id": "run-inflight",
+ "request_type": "scheduled",
+ "status": "running",
+ "definition_id": "task-inflight",
+ "created_at": "2026-07-27T02:00:00+00:00",
+ }
+ )
+
+ health = sqlite.definition_health("task-inflight", now="2026-07-27T02:30:00+00:00")
+
+ assert health["consecutive_failures"] == 1
+ assert health["health"] == "failing"
+
+
+def test_health_window_ages_out_after_the_time_bound(tmp_path: Path) -> None:
+ """HFR-071 — the window is count AND time bounded, in the WHERE clause.
+
+ Bounded only by ``LIMIT N``, a definition that fails once and then stops
+ firing keeps that failure as its newest verdict forever and reads ``failing``
+ indefinitely, with no user action able to clear it.
+ """
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-stale", schedule_type="at", run_at="2026-07-01T00:00:00+00:00", cron=None, enabled=False)
+ sqlite.enqueue_run(
+ {
+ "id": "run-ancient",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-stale",
+ "error": "boom",
+ "created_at": "2026-07-01T00:00:00+00:00",
+ "completed_at": "2026-07-01T00:01:00+00:00",
+ }
+ )
+
+ health = sqlite.definition_health("task-stale", now="2026-07-27T00:00:00+00:00")
+
+ assert health["recent_failures"] == 0, "a failure older than the window is aged out"
+ assert health["health"] == "healthy"
+
+
+def test_one_malformed_metadata_row_does_not_blank_health_for_every_definition(
+ tmp_path: Path,
+) -> None:
+ """HFR-072 — a ``json_extract`` predicate aborts the statement on one bad row.
+
+ Master filters ``metadata_json`` in Python through the defensive
+ ``_json_loads``, so a single unparseable row costs one misclassified run.
+ SQLite raises ``malformed JSON`` and fails the whole statement, which would
+ take the health badge down for every definition in the list rather than for
+ the row that is broken.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, _ = _store(tmp_path)
+ for definition_id in ("task-a", "task-b"):
+ _task(sqlite, definition_id)
+ sqlite.enqueue_run(
+ {
+ "id": f"run-{definition_id}",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": definition_id,
+ "error": "boom",
+ "created_at": "2026-07-27T01:00:00+00:00",
+ "completed_at": "2026-07-27T01:01:00+00:00",
+ }
+ )
+
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == "run-task-a")
+ .values(metadata_json="{not json")
+ )
+
+ healths = sqlite.definition_health_batch(
+ ["task-a", "task-b"],
+ now="2026-07-27T02:00:00+00:00",
+ )
+
+ # task-b is unaffected by task-a's bad row.
+ assert healths["task-b"]["health"] == "failing"
+ # task-a degrades to unknown rather than taking the list down. Asserted exactly,
+ # not as a disjunction: ``HEALTH_UNKNOWN`` is what its own docstring promises for
+ # this row ("a health signal that cannot be computed must not read as a clean bill
+ # of health"), and a read that answers ``failing`` here is answering from a window
+ # it could not classify.
+ assert healths["task-a"]["health"] == "unknown"
+
+
+def test_a_malformed_history_row_reports_unknown_rather_than_a_verdict(
+ tmp_path: Path,
+) -> None:
+ """HFR-072 — an unreadable row in the window is not evidence of anything.
+
+ ``_health_rows``' predicates let a malformed row through as an ORDINARY verdict:
+ ``INTERRUPT_REASON_SQL``'s ``CASE json_valid`` guard degrades the extract to NULL,
+ which passes ``reason IS NULL``, so the row is counted as whatever ``status``
+ happens to say. That guard exists to stop one bad blob failing the whole statement
+ — it was never a claim that the row is classifiable — and the result contradicts
+ ``HEALTH_UNKNOWN``'s own docstring, which promises unknown for exactly this row.
+
+ The consequence is directional, which is why it is worth a scenario rather than a
+ note: the badge reads ``healthy`` or ``failing`` with equal confidence off a
+ history it could not read, and a wrongly-clean bill is the failure mode this whole
+ feature exists to remove.
+
+ The negative control is the third definition: a malformed row OUTSIDE the window
+ must not make health unknown, or one ancient bad blob would blank a definition's
+ badge forever. Unknown is scoped to the window the verdict is read from, which is
+ the same scope the counters use.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, _ = _store(tmp_path)
+
+ def _run(definition_id: str, index: int, status: str, hour: int) -> str:
+ run_id = f"run-{definition_id}-{index:03d}"
+ instant = f"2026-07-28T{hour:02d}:00:00+00:00"
+ sqlite.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": status,
+ "definition_id": definition_id,
+ "error": "boom" if status == "failed" else None,
+ "created_at": instant,
+ "completed_at": instant,
+ }
+ )
+ return run_id
+
+ def _break(run_id: str, payload: str = "{broken") -> None:
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs).where(agent_runs.c.id == run_id).values(metadata_json=payload)
+ )
+
+ # 1. the NEWEST verdict is unreadable, so "the latest run failed" is unknowable.
+ _task(sqlite, "task-newest-bad")
+ _run("task-newest-bad", 0, "succeeded", 1)
+ _break(_run("task-newest-bad", 1, "failed", 2))
+
+ # 2. an unreadable row INSIDE the window but not newest: the failure count over the
+ # window is unknowable too, so ``degraded`` is not answerable either.
+ _task(sqlite, "task-inner-bad")
+ _break(_run("task-inner-bad", 0, "failed", 1))
+ _run("task-inner-bad", 1, "succeeded", 2)
+
+ # 3. the negative control: unreadable, but displaced out of the window by ten
+ # later verdicts.
+ _task(sqlite, "task-aged-bad")
+ _break(_run("task-aged-bad", 0, "failed", 1))
+ for index in range(1, 12):
+ _run("task-aged-bad", index, "succeeded", 1 + index)
+
+ # 4. VALID JSON that is not an OBJECT is just as unreadable as malformed JSON:
+ # ``json_valid('[]')`` is 1, so a validity-only readability signal admits the
+ # row, ``INTERRUPT_REASON_SQL``'s extract degrades to NULL (passing
+ # ``reason IS NULL``), and the badge answers confidently off a metadata
+ # schema that cannot be read. Every non-object type SQLite's ``json_type``
+ # can report at the top level is covered.
+ for suffix, payload in (
+ ("array", "[]"),
+ ("text", '"value"'),
+ ("number", "3"),
+ ("null", "null"),
+ ("boolean", "true"),
+ ):
+ _task(sqlite, f"task-{suffix}-bad")
+ _run(f"task-{suffix}-bad", 0, "succeeded", 1)
+ _break(_run(f"task-{suffix}-bad", 1, "failed", 2), payload)
+
+ non_object = tuple(
+ f"task-{suffix}-bad" for suffix in ("array", "text", "number", "null", "boolean")
+ )
+ healths = sqlite.definition_health_batch(
+ ["task-newest-bad", "task-inner-bad", "task-aged-bad", *non_object],
+ now="2026-07-29T00:00:00+00:00",
+ )
+
+ for definition_id in ("task-newest-bad", "task-inner-bad", *non_object):
+ assert healths[definition_id]["health"] == "unknown", (
+ f"{definition_id} has an unreadable row in its window and must report "
+ f"unknown, not {healths[definition_id]['health']!r}"
+ )
+ # The same counter shape the batch-degrade path reports, so a caller rendering
+ # "N consecutive failures" beside an unknown badge cannot read a number that
+ # was never computed.
+ assert healths[definition_id]["consecutive_failures"] == 0
+ assert healths[definition_id]["recent_failures"] == 0
+
+ assert healths["task-aged-bad"]["health"] == "healthy", (
+ "an unreadable row outside the window must not blank the badge forever; got "
+ f"{healths['task-aged-bad']}"
+ )
+
+
+def _ranked_health_rows(sqlite_store, definition_ids, *, now: str) -> dict[str, list[str]]:
+ """The WINDOW-FUNCTION health read, kept as the oracle for the bounded one.
+
+ Byte-for-byte the implementation ``_health_rows`` had before the correlated seek
+ replaced it: ``row_number()`` over the whole 72 h window per definition, then
+ ``position <= HEALTH_WINDOW_RUNS`` on the outside. It is the SEMANTICS that are
+ being preserved — the cost is what changed — so the old shape stays here as an
+ executable specification rather than as prose in a docstring (HFR-096's pattern:
+ ``_materialized_streak`` does the same job for the streak read).
+ """
+
+ from datetime import datetime, timedelta, timezone
+
+ from sqlalchemy import func, or_
+
+ from storage.background import (
+ HEALTH_WINDOW_HOURS,
+ HEALTH_WINDOW_RUNS,
+ _id_batches,
+ _not_an_out_of_band_interruption,
+ _parse_iso_instant,
+ _status_query_values,
+ _WATCH_RUNTIME_RUN_TYPE,
+ normalize_run_status,
+ )
+ from storage.models import agent_runs
+
+ ids = [str(value or "").strip() for value in definition_ids]
+ ids = [value for value in dict.fromkeys(ids) if value]
+ if not ids:
+ return {}
+ instant = _parse_iso_instant(now) or datetime.now(timezone.utc)
+ cutoff = (instant - timedelta(hours=HEALTH_WINDOW_HOURS)).isoformat()
+ settled_at = func.coalesce(agent_runs.c.completed_at, agent_runs.c.created_at)
+ verdicts = _status_query_values("succeeded") + _status_query_values("failed")
+
+ def _statement(batch):
+ ranked = (
+ select(
+ agent_runs.c.definition_id.label("definition_id"),
+ agent_runs.c.status.label("status"),
+ func.row_number()
+ .over(
+ partition_by=agent_runs.c.definition_id,
+ order_by=[settled_at.desc(), agent_runs.c.id.desc()],
+ )
+ .label("position"),
+ )
+ .where(agent_runs.c.definition_id.in_(batch))
+ .where(
+ or_(
+ agent_runs.c.run_type.is_(None),
+ agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,
+ )
+ )
+ .where(agent_runs.c.status.in_(verdicts))
+ .where(settled_at >= cutoff)
+ .where(_not_an_out_of_band_interruption())
+ .subquery()
+ )
+ return (
+ select(ranked.c.definition_id, ranked.c.status)
+ .where(ranked.c.position <= HEALTH_WINDOW_RUNS)
+ .order_by(ranked.c.definition_id, ranked.c.position)
+ )
+
+ out: dict[str, list[str]] = {}
+ with sqlite_store.engine.connect() as conn:
+ for batch in _id_batches(ids):
+ for row in conn.execute(_statement(batch)):
+ out.setdefault(str(row[0]), []).append(normalize_run_status(row[1]))
+ return out
+
+
+def test_the_health_read_is_bounded_before_it_is_ranked(tmp_path: Path) -> None:
+ """Subordinate to HFR-068 — the advertised 10-run bound must bound the DB work.
+
+ ``HEALTH_WINDOW_RUNS`` says "the last ten verdicts", and the windowed form made
+ SQLite assign ``row_number()`` to EVERY verdict in the 72 h window before the outer
+ ``position <= 10`` could discard any of them. The settled-time index narrows by
+ time and cannot stop after ten entries, so a high-frequency definition made every
+ Harness list, show and mutation read walk its entire recent history to return ten
+ rows. Measured on this history, the plan was::
+
+ CO-ROUTINE anon_1
+ CO-ROUTINE (subquery-3)
+ SEARCH agent_runs USING INDEX ix_agent_runs_definition_settled (definition_id=? AND <expr>>?)
+ SCAN (subquery-3)
+ SCAN anon_1
+ USE TEMP B-TREE FOR ORDER BY
+
+ — the seek is there, and then the whole result is scanned twice and sorted, with no
+ ``LIMIT`` anywhere to stop it.
+
+ TWO properties, and the test would be wrong without either. The bound has to be in
+ the DATABASE (``LIMIT`` inside the per-definition seek, an indexed order so it can
+ early-exit), and it has to be reached in ONE statement, because
+ ``test_a_page_costs_a_fixed_number_of_queries`` in
+ ``tests/test_harness_definition_lifecycle.py`` pins a page's statement count at a
+ fixed budget that the health read holds exactly one slot in. A per-definition
+ statement loop satisfies the bound and reintroduces the per-row query that #1033
+ removed; a batched window function satisfies the budget and walks the window. Only
+ a batched statement whose per-definition work is a bounded correlated seek does
+ both.
+
+ Asserted on the CONSTRAINED TERMS, never on an index name: HFR-095 and HFR-086 are
+ the same lesson — a plan can name the index while the term stays a per-row filter.
+ """
+
+ import re
+
+ sqlite, _ = _store(tmp_path)
+ # Far more than ten verdicts inside the window, which is the only case where the
+ # ranking cost differs from the bound.
+ for definition_id in ("task-hot-a", "task-hot-b", "task-hot-c"):
+ _task(sqlite, definition_id)
+ for index in range(400):
+ instant = f"2026-07-27T{index // 60:02d}:{index % 60:02d}:00+00:00"
+ sqlite.enqueue_run(
+ {
+ "id": f"run-{definition_id}-{index:04d}",
+ "request_type": "scheduled",
+ "status": "failed" if index % 4 else "succeeded",
+ "definition_id": definition_id,
+ "error": "boom" if index % 4 else None,
+ "created_at": instant,
+ "completed_at": instant,
+ }
+ )
+
+ plans = _agent_run_query_plans(
+ sqlite,
+ tmp_path / "state" / "vibe.sqlite",
+ lambda: sqlite._health_rows(
+ ["task-hot-a", "task-hot-b", "task-hot-c"], now="2026-07-27T12:00:00+00:00"
+ ),
+ )
+ assert len(plans) == 1, (
+ "three definitions must cost ONE statement: the page-budget invariant in "
+ "test_a_page_costs_a_fixed_number_of_queries gives this read a single slot, so "
+ f"a statement per definition breaks it; issued {len(plans)}"
+ )
+ statement, plan = plans[0]
+ rendered = "\n".join(plan)
+ compact = rendered.replace(" ", "")
+
+ assert "LIMIT" in statement.upper(), (
+ "without a LIMIT inside the per-definition seek the bound is applied after the "
+ f"read, and the whole window is still walked: {statement}"
+ )
+ # And the LIMIT is the PER-DEFINITION one, asserted on statement STRUCTURE. The
+ # direct measurement — rows examined per statement — is not available: pysqlite
+ # binds no ``sqlite3_stmt_status`` accessor, so there is no row counter to read, and
+ # the plan text says a seek is used without saying where the bound sits. Structure
+ # plus the plan shape is therefore the proportionate evidence, and it is what rules
+ # out the one rewrite the assertions above would wave through: a statement-level
+ # ``LIMIT 10`` over the whole batched result satisfies "a LIMIT exists" and answers
+ # a different question — ten rows TOTAL, so every definition after the first loses
+ # its verdicts. The LIMIT must therefore close INSIDE the correlated scalar
+ # subquery, i.e. before its ``) AS verdicts`` and before the outer ``FROM
+ # json_each`` over the id list.
+ assert len(re.findall(r"\bLIMIT\b", statement, re.IGNORECASE)) == 1, (
+ "exactly one LIMIT is expected, and it has to be the per-definition one: "
+ f"{statement}"
+ )
+ assert re.search(
+ r"\bLIMIT\b[^)]*\)\s*AS\s+recent\s*\)\s*AS\s+verdicts",
+ statement,
+ re.IGNORECASE | re.DOTALL,
+ ), (
+ "the LIMIT must belong lexically to the correlated per-definition subquery, "
+ f"closing before the scalar subquery does: {statement}"
+ )
+ assert re.search(r"\bLIMIT\b.*\bFROM\s+json_each\b", statement, re.IGNORECASE | re.DOTALL), (
+ "an outer LIMIT would render AFTER the FROM over the id list, so a bound that "
+ f"appears before it is the statement's own rather than the seek's: {statement}"
+ )
+ assert "TEMP B-TREE" not in rendered, (
+ f"the newest-first order must come from an index, not a sort; plan was:\n{rendered}"
+ )
+ # ``SCAN agent_runs``, not bare ``SCAN``. Two residual SCANs are correct and
+ # unavoidable in this shape: ``SCAN d VIRTUAL TABLE INDEX 1`` walks the ``json_each``
+ # id list, which is bounded by the page, and ``SCAN (subquery-1)`` walks the
+ # already-LIMITed <=10-row co-routine. Neither touches the table. A ``SCAN
+ # agent_runs`` would be the unbounded history read this scenario exists to remove.
+ assert "SCAN agent_runs" not in rendered, (
+ f"the health read must never scan a definition's history; plan was:\n{rendered}"
+ )
+ assert "(definition_id=?AND<expr>>?)" in compact, (
+ "the per-definition window must be an indexed seek on (definition_id, settled) "
+ f"— both terms constrained, not one plus a filter; plan was:\n{rendered}"
+ )
+
+
+def test_the_bounded_health_read_matches_the_ranked_health_read(tmp_path: Path) -> None:
+ """Subordinate to HFR-068 — the bounded read has to be the SAME ten verdicts.
+
+ Parity against ``_ranked_health_rows``, the window-function form this replaces,
+ over randomised histories containing every row class that decides the answer:
+ verdicts and non-verdicts (``canceled``, ``queued``, ``running``),
+ interruptions whose reason IS in ``RUN_INTERRUPTION_REASONS`` (excluded) and whose
+ reason is not (an ordinary per-fire failure, counted), ``watch_runtime`` heartbeats
+ sharing the definition id, rows sharing one ``created_at`` so the ``id`` tie-break
+ decides the order, more than ten verdicts inside the window, rows straddling the
+ 72 h cutoff on both sides, a definition with NO rows at all — the ranked form
+ omits that key entirely rather than mapping it to an empty list, so the bounded
+ form has to skip its empty result instead of returning one — and the LEGACY
+ ``completed`` spelling that a literal ``('succeeded','failed')`` would drop.
+
+ That last one has to be written PAST ``enqueue_run``, which normalizes ``status``
+ on the way in (``_run_values`` -> ``normalize_run_status``): a fixture row asking
+ for ``completed`` lands as ``succeeded``, so going through the front door would
+ leave ``_status_query_values``' legacy lane — the reason neither reader may use a
+ literal status list — entirely unexercised while appearing to cover it.
+
+ Green on BOTH sides of the change by construction — that is the point. The plan
+ test above is the one that goes red; this one exists so the plan test cannot be
+ satisfied by a query that answers a different question, in particular by a LIMIT
+ applied to a population the interruption predicate had not yet filtered, or by a
+ result whose order comes from an aggregate that does not promise one.
+ """
+
+ import random
+
+ sqlite, _ = _store(tmp_path)
+ rng = random.Random(20260729)
+ now = "2026-07-29T00:00:00+00:00"
+ # No ``completed`` here on purpose: ``enqueue_run`` would normalize it to
+ # ``succeeded`` on write, so it would add a status the fixture already has while
+ # looking like legacy coverage. The real legacy row is written raw further down.
+ statuses = ["succeeded", "failed", "canceled", "queued", "running"]
+ reasons = [None, None, *sorted(RUN_INTERRUPTION_REASONS)[:3], "transport_unavailable"]
+ definition_ids = [f"task-parity-{index}" for index in range(6)]
+
+ for definition_id in definition_ids:
+ _task(sqlite, definition_id)
+ # Enough rows that at least one definition reaches the ten-verdict bound after
+ # the non-verdict, interruption and cutoff filters have taken their share —
+ # asserted below, because a fixture that never fills the window never tests the
+ # LIMIT at all.
+ for index in range(rng.randint(0, 60)):
+ # Hours spread across and beyond the 72 h window, so rows land on both
+ # sides of the cutoff. NOT on it: the arithmetic below floors the day and
+ # subtracts the remainder from hour 23, so no ``hours`` value can produce
+ # the cutoff INSTANT (``now - 72 h`` is midnight, and every row here lands
+ # at hour 23 - hours % 24). The boundary itself is covered absolutely by
+ # ``test_the_health_window_includes_a_verdict_settled_on_the_cutoff``, for
+ # the reason spelled out there: both readers share the ``>=`` predicate, so
+ # parity can never see a boundary regression.
+ hours = rng.choice([0, 1, 12, 12, 40, 40, 71, 71, 72, 73, 100])
+ day = 29 - (hours // 24)
+ hour = 23 - (hours % 24)
+ # Some rows deliberately SHARE a timestamp, which is when ``id`` decides.
+ minute = rng.choice([0, 0, 0, index % 60])
+ instant = f"2026-07-{day:02d}T{hour:02d}:{minute:02d}:00+00:00"
+ reason = rng.choice(reasons)
+ sqlite.enqueue_run(
+ {
+ "id": f"run-{definition_id}-{index:03d}",
+ "request_type": "scheduled",
+ "status": rng.choice(statuses),
+ "definition_id": definition_id,
+ "error": "boom",
+ "created_at": instant,
+ # Sometimes unset, so ``coalesce`` has to fall back.
+ "completed_at": instant if rng.random() < 0.8 else None,
+ "metadata": {"interrupt_reason": reason} if reason else {},
+ }
+ )
+ # A supervisor heartbeat under the same definition id. The ``watches`` wrapper
+ # is load-bearing: ``write_watch_runtime`` reads ``payload["watches"]``, so a
+ # bare ``{definition_id: …}`` writes NOTHING and this coverage claim would be
+ # false.
+ if rng.random() < 0.5:
+ sqlite.write_watch_runtime(
+ {
+ "watches": {
+ definition_id: {
+ "running": True,
+ "started_at": "2026-07-28T23:59:00+00:00",
+ }
+ }
+ },
+ updated_at="2026-07-28T23:59:00+00:00",
+ )
+
+ # A definition that exists and has never run, asked for alongside the rest.
+ _task(sqlite, "task-parity-empty")
+
+ # And one whose ONLY verdict carries the legacy ``completed`` spelling, written
+ # straight to the column because ``enqueue_run`` would normalize it away. One row,
+ # inside the window, no interruption — so if either reader dropped the legacy
+ # spelling this definition would vanish from the mapping entirely.
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ _task(sqlite, "task-parity-legacy")
+ sqlite.enqueue_run(
+ {
+ "id": "run-parity-legacy",
+ "request_type": "scheduled",
+ "status": "succeeded",
+ "definition_id": "task-parity-legacy",
+ "created_at": "2026-07-28T12:00:00+00:00",
+ "completed_at": "2026-07-28T12:00:00+00:00",
+ }
+ )
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == "run-parity-legacy")
+ .values(status="completed")
+ )
+ assert (
+ conn.execute(
+ select(agent_runs.c.status).where(agent_runs.c.id == "run-parity-legacy")
+ ).scalar_one()
+ == "completed"
+ ), "the legacy spelling must survive in the column, or this row proves nothing"
+
+ asked = [*definition_ids, "task-parity-empty", "task-parity-legacy"]
+
+ live = sqlite._health_rows(asked, now=now)
+ oracle = _ranked_health_rows(sqlite, asked, now=now)
+
+ assert live == oracle, (
+ "the bounded correlated seek must return the same verdicts, in the same order, "
+ f"as the ranked read:\nlive {live}\noracle {oracle}"
+ )
+ assert "task-parity-empty" not in live, (
+ "a definition with no verdicts must be ABSENT from the mapping, not present "
+ f"with an empty list: {live}"
+ )
+ assert live.get("task-parity-legacy") == ["succeeded"], (
+ "the legacy ``completed`` row must be SELECTED as a verdict and normalized on "
+ f"the way out; got {live.get('task-parity-legacy')!r}"
+ )
+ # And the fixture actually exercised the interesting case.
+ assert any(len(values) >= 5 for values in oracle.values()), (
+ f"the randomised history produced almost no verdicts: {oracle}"
+ )
+ assert any(len(values) == 10 for values in oracle.values()), (
+ f"no definition reached the 10-verdict bound, so the LIMIT was never tested: {oracle}"
+ )
+
+
+def test_the_health_window_includes_a_verdict_settled_on_the_cutoff(tmp_path: Path) -> None:
+ """Subordinate to HFR-068 — the 72 h boundary is INCLUSIVE, pinned absolutely.
+
+ ``_health_rows`` admits a row with ``settled >= cutoff``, where ``cutoff`` is
+ ``now - HEALTH_WINDOW_HOURS``. The test above cannot defend that ``>=``: it is
+ PARITY against ``_ranked_health_rows``, and both readers spell the boundary the
+ same way, so flipping ``>=`` to ``>`` moves both lanes together and parity stays
+ green while a definition whose only verdict settled exactly on the boundary
+ silently reports as never-run. Parity is the wrong instrument for a predicate the
+ oracle shares — the assertion here is therefore ABSOLUTE, against literal expected
+ verdicts, and the parity check is kept only as a second, weaker witness.
+
+ Two definitions, one row each, so the expected mapping is a literal and either
+ direction of the bug is visible in it:
+
+ * one settled at EXACTLY the cutoff instant, computed from the same ``now`` the
+ read is given rather than hand-written, so it cannot drift from
+ ``HEALTH_WINDOW_HOURS``. It must be PRESENT.
+ * one settled one second earlier — the smallest step outside — which must be
+ ABSENT, so an over-wide ``>`` -> ``>=`` on the wrong side of the comparison, or
+ a cutoff computed with the wrong sign, does not pass either.
+
+ The comparison happens in SQLite against the stored ISO TEXT, so the boundary row
+ only proves anything if the string it was written with is the string the cutoff is
+ rendered as. That is asserted on the raw column below rather than assumed:
+ ``_run_values`` passes ``completed_at`` through verbatim today, and a normalizing
+ writer added later would turn this test into a tautology without failing.
+ """
+
+ import re
+ from datetime import timedelta
+
+ from storage.background import HEALTH_WINDOW_HOURS, _parse_iso_instant
+ from storage.models import agent_runs
+
+ sqlite, _ = _store(tmp_path)
+ now = "2026-07-29T00:00:00+00:00"
+ # The cutoff exactly as ``_health_rows`` computes it, from the same ``now``.
+ instant = _parse_iso_instant(now)
+ assert instant is not None
+ cutoff = (instant - timedelta(hours=HEALTH_WINDOW_HOURS)).isoformat()
+ just_outside = (instant - timedelta(hours=HEALTH_WINDOW_HOURS, seconds=1)).isoformat()
+ # Not the assertion, a guard on the fixture: a lexicographic comparison is only
+ # an instant comparison while both strings are the same fixed-width ISO shape.
+ assert re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+00:00", cutoff), cutoff
+ assert just_outside < cutoff
+
+ # Distinct statuses, so the literal expected list below says WHICH row survived
+ # the predicate rather than only how many did.
+ _task(sqlite, "task-on-the-cutoff")
+ sqlite.enqueue_run(
+ {
+ "id": "run-on-the-cutoff",
+ "request_type": "scheduled",
+ "status": "succeeded",
+ "definition_id": "task-on-the-cutoff",
+ "created_at": cutoff,
+ "completed_at": cutoff,
+ }
+ )
+ _task(sqlite, "task-outside-the-cutoff")
+ sqlite.enqueue_run(
+ {
+ "id": "run-outside-the-cutoff",
+ "request_type": "scheduled",
+ "status": "failed",
+ "definition_id": "task-outside-the-cutoff",
+ "error": "boom",
+ "created_at": just_outside,
+ "completed_at": just_outside,
+ }
+ )
+
+ with sqlite.engine.connect() as conn:
+ stored = dict(
+ conn.execute(
+ select(agent_runs.c.id, agent_runs.c.completed_at).where(
+ agent_runs.c.definition_id.in_(
+ ["task-on-the-cutoff", "task-outside-the-cutoff"]
+ )
+ )
+ ).all()
+ )
+ assert stored == {"run-on-the-cutoff": cutoff, "run-outside-the-cutoff": just_outside}, (
+ "the fixture's instants must survive the write byte-for-byte, or the boundary "
+ f"row is not on the boundary the read compares against: {stored}"
+ )
+
+ asked = ["task-on-the-cutoff", "task-outside-the-cutoff"]
+ live = sqlite._health_rows(asked, now=now)
+
+ assert live == {"task-on-the-cutoff": ["succeeded"]}, (
+ "the 72 h window is inclusive of its own edge and exclusive one second past it: "
+ "a verdict settled exactly at now - 72 h must still count toward health, and a "
+ f"definition whose only verdict is older must be absent; got {live}"
+ )
+ # Kept, but explicitly the weaker witness: it would pass with the predicate broken
+ # in both lanes at once.
+ assert live == _ranked_health_rows(sqlite, asked, now=now), (
+ "the bounded read and the ranked oracle must also agree on the boundary"
+ )
+ # And the boundary really is decided by the window rather than by the row being
+ # unreadable for some other reason: one hour later, both rows are inside.
+ wider = sqlite._health_rows(asked, now="2026-07-28T23:00:00+00:00")
+ assert wider == {
+ "task-on-the-cutoff": ["succeeded"],
+ "task-outside-the-cutoff": ["failed"],
+ }, f"the excluded row must be a WINDOW exclusion, not an unreadable row: {wider}"
+
+
+# --- group 4: a binding change is a notice, not just a log line ------------
+#
+# The rebind lane is the one transition where the run SUCCEEDS and the user still
+# has to be told: ``create_once`` re-reserves a session, the retry works, and the
+# only trace is a ``logger.warning``. Everything below rides the same owed-notice
+# protocol as a failure, because "the user was told" needs a receipt whichever lane
+# produced the message.
+
+
+def _rebound_run(tmp_path: Path, monkeypatch):
+ """Drive one real ``create_once`` fire whose pinned session is gone.
+
+ One SQLite file serves all three halves of HFR-099: ``_binding_env`` and
+ ``_store`` both resolve to ``tmp_path/state/vibe.sqlite``, so the execution that
+ rebinds, the drain that delivers, and the ``messages`` row the receipt is read
+ back from are the same database rather than three that agree by construction.
+ """
+
+ from core.scheduled_tasks import ScheduledTaskStore
+
+ from tests.test_scheduled_tasks import _binding_env, _binding_service
+
+ db_path = _binding_env(tmp_path, monkeypatch)
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ task = store.add_task(
+ name="daily digest",
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+
+ calls: list = []
+ service = _binding_service(tmp_path, store, calls)
+ # The SQLite-backed request store, so the fire produces a real ``agent_runs``
+ # row for the notice to be stamped on and the drain to find.
+ service.request_store = requests
+
+ queued = requests.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ claimed = requests.claim(queued.id)
+ assert claimed is not None
+ asyncio.run(service._execute_claimed_request(claimed))
+
+ return db_path, sqlite, requests, store, task, queued.id, calls
+
+
+def test_a_successful_rebind_is_delivered_through_the_retried_notice_path(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-099 — a silently replaced session binding owes the user a notice.
+
+ ``create_once`` whose pinned session was hard-deleted re-reserves one and
+ retries the fire. When the retry SUCCEEDS the run settles ``succeeded`` with
+ ``error=None``, so ``_owed_failure_notice_for_transition`` stamps nothing — it
+ stamps only on ``failed`` — and ``_notify_binding_change`` is a log-only seam
+ whose docstring claimed "the run row's own owed notice carries the user-visible
+ half". False in exactly this case: the user's pinned session was replaced,
+ possibly with different settings, and nothing ever said so.
+
+ Two halves, and the second is the point of the finding:
+
+ * the notice EXISTS, is keyed by the binding transition rather than by the run,
+ and names old → new session;
+ * it is DURABLE and RETRIED — killing the first delivery consumes an attempt,
+ arms the backoff, and the next eligible tick delivers it with a receipt. A
+ one-shot ``emit`` next to the log line would satisfy "a message appeared" and
+ fail this half, which is why the notice rides the owed-notice protocol
+ instead of a parallel path.
+ """
+
+ import core.failure_notices as failure_notices
+ import core.scheduled_tasks as scheduled_tasks
+ import storage.background as background
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from storage.background import NOTICE_PENDING
+ from vibe.i18n import t as i18n_t
+
+ _db_path, sqlite, requests, store, task, run_id, calls = _rebound_run(
+ tmp_path, monkeypatch
+ )
+
+ # The fire itself worked: rebound, retried, and settled as a success.
+ updated = store.get_task(task.id)
+ assert updated is not None and updated.enabled is True
+ assert updated.session_id and updated.session_id != "sesdoesnotexist"
+ assert calls == ["send digest"], "the rebound run never executed"
+ assert sqlite.get_run(run_id)["status"] == "succeeded"
+
+ # --- half 1: the stamp -------------------------------------------------
+ notice = sqlite.owed_failure_notice(run_id)
+ assert isinstance(notice, dict), (
+ "a successful rebind left NO durable notice: the pinned session was "
+ "replaced and only a log line said so"
+ )
+ assert notice["state"] == NOTICE_PENDING
+ assert notice["kind"] == failure_notices.NOTICE_KIND_BINDING_CHANGE
+ # The storage mirror and the core vocabulary must agree, for the same reason
+ # ``RUN_INTERRUPTION_REASONS`` is mirrored: ``core`` imports ``storage``, never
+ # the reverse, so the constant is spelled twice and pinned once.
+ assert background.NOTICE_KIND_BINDING_CHANGE == failure_notices.NOTICE_KIND_BINDING_CHANGE
+ assert background.NOTICE_KIND_FAILURE == failure_notices.NOTICE_KIND_FAILURE
+ recorded = (store.get_task(task.id).metadata or {}).get("binding_recovery") or {}
+ assert notice["failure_id"] == f"binding:{task.id}:{recorded['signature']}", (
+ "the identity must be the binding transition's own dedup key, so one broken "
+ "binding is one notification however many times it fires"
+ )
+ binding = notice["binding"]
+ assert binding["action"] == "rebound"
+ assert binding["previous_session_id"] == "sesdoesnotexist"
+ assert binding["new_session_id"] == updated.session_id
+ assert binding["settings_preserved"] is False
+
+ # --- half 2: delivery is retried, not fire-and-forget ------------------
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ service._t = lambda key, **kwargs: i18n_t(key, "en", **kwargs)
+ emissions = _spy_emissions(controller)
+
+ real_emit = scheduled_tasks.emit_replayed_backend_failure
+
+ async def _raising_emit(*args, **kwargs):
+ raise RuntimeError("transport down")
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _raising_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ after_failure = sqlite.owed_failure_notice(run_id)
+ assert after_failure["state"] == NOTICE_PENDING, "a killed delivery must stay owed"
+ assert after_failure["attempts"] == 1, "the failed attempt must be persisted"
+ assert str(after_failure["next_attempt_at"] or "") > str(after_failure["stamped_at"]), (
+ "the backoff must be armed rather than re-firing on the next 2 s tick"
+ )
+ assert not controller.im_client.sent
+
+ # The armed backoff really holds: an immediate second tick is a no-op.
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", real_emit)
+ asyncio.run(service._drain_failure_notices())
+ assert sqlite.owed_failure_notice(run_id)["attempts"] == 1
+ assert not controller.im_client.sent
+
+ # Let the backoff elapse without sleeping, exactly as HFR-076 does.
+ sqlite.update_owed_failure_notice(run_id, next_attempt_at=None)
+ asyncio.run(service._drain_failure_notices())
+
+ settled = sqlite.owed_failure_notice(run_id)
+ assert settled["state"] == NOTICE_SENT, "the retry must deliver the notice"
+ assert settled["attempts"] == 2, "the retry is the SECOND attempt, not the first"
+ assert settled["ack_evidence"] == ACK_EVIDENCE_RECEIPT
+
+ assert [item["type"] for item in emissions] == ["notify"]
+ channel, _thread, sent_text = controller.im_client.sent[0]
+ assert channel == "C123"
+ assert "sesdoesnotexist" in sent_text and updated.session_id in sent_text, (
+ f"the notice must name old -> new session: {sent_text!r}"
+ )
+ assert "daily digest" in sent_text
+ assert i18n_t("harness.notice.unknownError", "en") not in sent_text, (
+ "a run that SUCCEEDED must not be reported with an error line"
+ )
+
+ rows = _persisted_messages()
+ assert [row["type"] for row in rows] == ["notify"]
+ assert rows[0]["content_text"] == sent_text
+
+
+#: Every ``vibe`` command the binding-change copy is allowed to print, with the
+#: argv the CLI must accept for it. Placeholders are rendered as uppercase tokens so
+#: the scan below cannot mistake an id for a subcommand.
+_BINDING_NOTICE_COMMANDS = {
+ "vibe task update ID --session-id <session-id>": [
+ "task",
+ "update",
+ "ID",
+ "--session-id",
+ "<session-id>",
+ ],
+ "vibe task show ID": ["task", "show", "ID"],
+ # The one command a definition that no longer exists can still offer. The run row
+ # outlives its definition, and ``runs show`` takes an optional positional run id.
+ "vibe runs show ID": ["runs", "show", "ID"],
+}
+
+#: The keys the binding-change body is built from, in both languages — including the
+#: deleted-definition pair, which replaces the repin/show commands rather than adding
+#: to them, and so has to clear the same bar.
+_BINDING_NOTICE_KEYS = (
+ "harness.notice.rebound",
+ "harness.notice.reboundSessions",
+ "harness.notice.reboundSettingsPreserved",
+ "harness.notice.reboundSettingsReset",
+ "harness.notice.reboundRepin",
+ "harness.notice.show",
+ "harness.notice.definitionDeleted",
+ "harness.notice.runInspect",
+)
+
+
+def test_the_binding_notice_copy_only_names_commands_the_cli_has() -> None:
+ """HFR-099 — every command the binding copy prints must really parse.
+
+ The same trap WI-2 hit with ``vibe watch run``: copy is the one place a command
+ can be invented with nothing failing, and a user handed a command that does not
+ parse is worse off than one handed none. Two directions, because either alone
+ passes trivially: the allowed commands are checked against the REAL parser, and
+ the rendered copy is checked to mention no ``vibe`` command outside that set.
+ """
+
+ import re
+
+ from vibe.cli import build_parser
+ from vibe.i18n import t as i18n_t
+
+ parser = build_parser()
+ for spelling, argv in _BINDING_NOTICE_COMMANDS.items():
+ try:
+ parser.parse_args(argv)
+ except SystemExit: # pragma: no cover - the assertion is the point
+ raise AssertionError(f"the binding copy prints {spelling!r}, which the CLI cannot parse")
+
+ for lang in ("en", "zh"):
+ for key in _BINDING_NOTICE_KEYS:
+ rendered = i18n_t(
+ key,
+ lang,
+ name="NAME",
+ id="ID",
+ previous="PREVIOUS",
+ new="NEW",
+ )
+ assert rendered != key, f"{key} is missing from {lang}.json"
+ # A left word boundary, so the ``[Avibe Harness]`` brand prefix is
+ # not read as an invocation of a ``vibe Harness]`` subcommand.
+ for match in re.finditer(r"(?<![A-Za-z])vibe ", rendered):
+ tail = rendered[match.start():]
+ assert any(tail.startswith(spelling) for spelling in _BINDING_NOTICE_COMMANDS), (
+ f"{lang}/{key} prints an unvetted command: {tail!r}"
+ )
+
+
+# --- round 9, gate item 3: the binding stamp's terminal CAS ------------------
+
+
+def _binding_stamp(sqlite, run_id: str, *, task_id: str, signature: str = "sig-1"):
+ """``stamp_binding_change_notice`` with the one transition shape that stamps."""
+
+ return sqlite.stamp_binding_change_notice(
+ run_id,
+ task_id=task_id,
+ signature=signature,
+ action="rebound",
+ reason="session_missing",
+ previous_session_id="ses-gone",
+ new_session_id="ses-fresh",
+ settings_preserved=True,
+ )
+
+
+def test_binding_marker_rolls_back_when_its_notice_write_faults(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A transient notice fault must leave the transition retryable."""
+
+ from core.scheduled_tasks import BINDING_RECOVERY_METADATA_KEY, SessionBindingChange
+ from tests.test_scheduled_tasks import _binding_env
+
+ _binding_env(tmp_path, monkeypatch)
+ sqlite, requests = _store(tmp_path)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ task = service.store.add_task(
+ name="daily digest",
+ session_key="",
+ session_id="ses-fresh",
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ run = requests.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ assert requests.claim(run.id) is not None
+ change = SessionBindingChange(
+ action="rebound",
+ task_id=task.id,
+ reason="session_missing",
+ previous_session_id="ses-gone",
+ detail="the pinned session was replaced",
+ new_session_id="ses-fresh",
+ settings_preserved=True,
+ )
+
+ real_stamp = sqlite.stamp_binding_change_notice
+
+ def _fault(*args, **kwargs):
+ raise OSError("transient sqlite write fault")
+
+ monkeypatch.setattr(sqlite, "stamp_binding_change_notice", _fault)
+ asyncio.run(service._emit_binding_change(change, run_id=run.id, run_error=None))
+
+ after_fault = service.store.get_task(task.id)
+ assert after_fault is not None
+ assert BINDING_RECOVERY_METADATA_KEY not in (after_fault.metadata or {})
+ assert sqlite.owed_failure_notice(run.id) is None
+
+ monkeypatch.setattr(sqlite, "stamp_binding_change_notice", real_stamp)
+ asyncio.run(service._emit_binding_change(change, run_id=run.id, run_error=None))
+
+ recovered = service.store.get_task(task.id)
+ marker = (recovered.metadata or {}).get(BINDING_RECOVERY_METADATA_KEY)
+ assert isinstance(marker, dict) and marker["signature"] == change.signature
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None
+ assert notice["failure_id"] == f"binding:{task.id}:{change.signature}"
+
+
+def test_binding_notice_rolls_back_when_the_definition_marker_cas_loses(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A refused marker must not commit the notice written earlier in its transaction."""
+
+ from sqlalchemy import update as sa_update
+
+ from core.scheduled_tasks import BINDING_RECOVERY_METADATA_KEY, SessionBindingChange
+ from storage.models import run_definitions
+ from tests.test_scheduled_tasks import _binding_env
+
+ _binding_env(tmp_path, monkeypatch)
+ sqlite, requests = _store(tmp_path)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ task = service.store.add_task(
+ name="daily digest",
+ session_key="",
+ session_id="ses-fresh",
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ run = requests.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ assert requests.claim(run.id) is not None
+ change = SessionBindingChange(
+ action="rebound",
+ task_id=task.id,
+ reason="session_missing",
+ previous_session_id="ses-gone",
+ detail="the pinned session was replaced",
+ new_session_id="ses-fresh",
+ settings_preserved=True,
+ )
+
+ real_atomic_write = sqlite.upsert_scheduled_task_with_binding_notice
+
+ def _repoint_before_atomic_write(payload, *, expect, notice):
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(run_definitions)
+ .where(run_definitions.c.id == task.id)
+ .values(session_id="ses-concurrently-repointed")
+ )
+ return real_atomic_write(payload, expect=expect, notice=notice)
+
+ monkeypatch.setattr(
+ sqlite,
+ "upsert_scheduled_task_with_binding_notice",
+ _repoint_before_atomic_write,
+ )
+ asyncio.run(service._emit_binding_change(change, run_id=run.id, run_error=None))
+
+ stored = service.store.get_task(task.id)
+ assert stored is not None and stored.session_id == "ses-concurrently-repointed"
+ assert BINDING_RECOVERY_METADATA_KEY not in (stored.metadata or {})
+ assert sqlite.owed_failure_notice(run.id) is None
+
+
+def test_a_binding_stamp_refuses_a_failure_terminalized_inside_its_gap(tmp_path: Path) -> None:
+ """Subordinate to HFR-099 — the binding stamp must re-assert what it read.
+
+ ``stamp_binding_change_notice`` is the one owed-notice writer that does not ride a
+ terminal transition: it runs on a LIVE run, before ``complete()``. Round 7 audited
+ it and excused it — "a pre-read stamp inside its own guarded read/modify/write" —
+ on the assumption that being gated on "no existing notice" was enough. It is not,
+ for the reason round 8 established one function over:
+ pysqlite emits no ``BEGIN`` for a bare SELECT, so ``engine.begin()`` holds no lock
+ across the read, and the write lock is first taken by the UPDATE.
+
+ So the terminal writer is committed HERE, from another connection, in exactly that
+ gap. It stamps its OWN failure notice as part of the same UPDATE that moves the row
+ to ``failed`` (``_merge_owed_failure_notice``), and the binding stamp then wrote
+ the whole ``metadata_json`` blob it had composed from the pre-transition snapshot
+ over the top: the failure the user needs to hear about replaced by the news that a
+ session was swapped, with the run reporting ``failed`` and no failure notice
+ anywhere.
+ """
+
+ from sqlalchemy import event
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-cas", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-binding-cas")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+
+ interleaved: list[str] = []
+
+ def _terminalize_inside_the_gap(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ # The backend result lands and the run settles ``failed``, stamping the
+ # failure notice, on its own connection and committed. The stamp's snapshot
+ # is now stale; its UPDATE has not reached the driver yet.
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-binding-cas")
+
+ event.listen(sqlite.engine, "before_cursor_execute", _terminalize_inside_the_gap)
+ try:
+ lost = _binding_stamp(sqlite, run.id, task_id="task-binding-cas")
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _terminalize_inside_the_gap)
+
+ assert interleaved, "the terminal writer never got into the gap — this test proves nothing"
+ assert lost is None, (
+ "a binding stamp whose run terminalized between its read and its UPDATE must "
+ f"report that it wrote nothing, got {lost}"
+ )
+
+ assert sqlite.get_run(run.id)["status"] == "failed"
+ settled = sqlite.owed_failure_notice(run.id)
+ assert settled is not None, "the terminal verdict's own notice must still be there"
+ assert settled["failure_id"] == run.id, (
+ "the FAILURE notice must survive byte-intact; the binding blob keys it "
+ f"``binding:…`` and this one reads {settled['failure_id']!r}"
+ )
+ assert settled.get("kind") in (None, NOTICE_KIND_FAILURE), (
+ f"a binding notice replaced the failure notice: {settled!r}"
+ )
+ assert settled.get("binding") is None, f"the binding payload must not be here: {settled!r}"
+ assert settled["state"] == "pending", "the failure is still owed to the user"
+ # And it is deliverable, which is the whole point of it surviving.
+ assert [row["id"] for row in sqlite.list_owed_failure_notices()] == [run.id]
+
+
+def test_a_binding_stamp_never_lands_on_a_run_canceled_inside_its_gap(tmp_path: Path) -> None:
+ """Subordinate to HFR-099 — ``canceled`` is reserved for explicit stop semantics.
+
+ The other damage direction, and the durable one. ``canceled`` owes no notice by
+ design (``_owed_failure_notice_for_transition``: telling a user their run failed
+ because they stopped it is noise), and ``list_owed_failure_notices`` selects only
+ ``failed``/``succeeded``. So a binding notice stamped onto a row that another
+ actor canceled in the read/write gap is written, is ``pending``, and is
+ PERMANENTLY unreachable: excluded from every drain batch, retried never,
+ dead-lettered never.
+
+ The user's explicit Stop also outranks the rebind news on its own terms, so the
+ correct outcome is not "deliver it later" but "never stamp it".
+ """
+
+ from sqlalchemy import event
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-cancel", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-binding-cancel")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ interleaved: list[str] = []
+
+ def _cancel_inside_the_gap(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ # Stop lands after the stamp's snapshot. It first sets cancel_requested, then
+ # the terminal owner maps the failed result to canceled before the stale stamp
+ # reaches its UPDATE.
+ assert sqlite.cancel_run(run.id)
+ requests.complete(claimed, ok=False, error="stopped", task_id="task-binding-cancel")
+
+ event.listen(sqlite.engine, "before_cursor_execute", _cancel_inside_the_gap)
+ try:
+ lost = _binding_stamp(sqlite, run.id, task_id="task-binding-cancel")
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _cancel_inside_the_gap)
+
+ assert interleaved, "the canceller never got into the gap — this test proves nothing"
+ assert sqlite.get_run(run.id)["status"] == "canceled", "the stop must have won"
+ assert lost is None, (
+ f"a binding stamp must report that it wrote nothing onto a canceled run, got {lost}"
+ )
+ assert sqlite.owed_failure_notice(run.id) is None, (
+ "a canceled run must carry NO owed notice: the drain excludes ``canceled``, so "
+ "one written here is durable and undeliverable forever"
+ )
+ assert sqlite.list_owed_failure_notices() == []
+
+
+def test_a_binding_notice_committed_before_stop_remains_deliverable(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """A later Stop cannot strand news about a rebind that already committed."""
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-cancel-after-stamp", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-binding-cancel-after-stamp")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+
+ stamped = _binding_stamp(sqlite, run.id, task_id="task-binding-cancel-after-stamp")
+ assert stamped is not None
+ assert sqlite.cancel_run(run.id)
+ requests.complete(
+ claimed,
+ ok=False,
+ error="stopped",
+ task_id="task-binding-cancel-after-stamp",
+ )
+
+ assert sqlite.get_run(run.id)["status"] == "canceled"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None and notice["kind"] == NOTICE_KIND_BINDING_CHANGE
+ assert notice["state"] == NOTICE_PENDING
+ assert [row["id"] for row in sqlite.list_owed_failure_notices()] == [run.id]
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ service, delivered = _notice_drain_service(tmp_path, sqlite, requests)
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", service._spy_emit)
+ asyncio.run(service._drain_failure_notices())
+
+ assert delivered == [notice["failure_id"]]
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_SENT
+ assert sqlite.list_owed_failure_notices() == []
+
+
+def test_a_binding_stamp_refuses_a_stop_already_visible_in_its_snapshot(tmp_path: Path) -> None:
+ """Both Stop shapes outrank binding news before the first CAS.
+
+ A queued Stop writes ``status='canceled'`` immediately; a running Stop leaves the
+ status running and writes ``cancel_requested`` for the terminal owner. Either row
+ would make a binding notice permanently unreachable after cancellation settles.
+ """
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-stopped")
+
+ queued = requests.enqueue_task_run("task-binding-stopped")
+ assert sqlite.cancel_run(queued.id)
+ assert sqlite.get_run(queued.id)["status"] == "canceled"
+
+ running = requests.enqueue_task_run("task-binding-stopped")
+ assert requests.claim(running.id) is not None
+ assert sqlite.cancel_run(running.id)
+ running_row = sqlite.get_run(running.id)
+ assert running_row["status"] == "running"
+ assert running_row["cancel_requested"] is True
+
+ for run in (queued, running):
+ assert _binding_stamp(sqlite, run.id, task_id="task-binding-stopped") is None
+ assert sqlite.owed_failure_notice(run.id) is None
+
+
+def test_a_binding_stamp_on_a_malformed_metadata_row_is_refused_not_raised(
+ tmp_path: Path,
+) -> None:
+ """Subordinate to HFR-084 — the stamp degrades, it does not take the fire down.
+
+ Moving the write from a whole-blob overwrite to ``json_set`` means SQLite now
+ parses ``metadata_json`` at WRITE time, and ``json_set`` over an unparseable blob
+ raises ``malformed JSON`` — which would turn one bad row into an exception on the
+ rebind path. The same ``CASE json_valid`` discipline the eligibility expressions
+ document applies here: the row is refused, reported as "wrote nothing", and left
+ exactly as it was.
+ """
+
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-badjson")
+ run = requests.enqueue_task_run("task-binding-badjson")
+ assert requests.claim(run.id) is not None
+ with sqlite.engine.begin() as conn:
+ conn.execute(
+ sa_update(agent_runs).where(agent_runs.c.id == run.id).values(metadata_json="{not json")
+ )
+
+ # Must not raise, and must not write.
+ assert _binding_stamp(sqlite, run.id, task_id="task-binding-badjson") is None
+ with sqlite.engine.connect() as conn:
+ stored = conn.execute(
+ select(agent_runs.c.metadata_json).where(agent_runs.c.id == run.id)
+ ).scalar_one()
+ assert stored == "{not json", "the malformed blob must be left exactly as it was"
+
+
+def test_a_binding_stamp_writes_only_its_own_metadata_key(tmp_path: Path) -> None:
+ """Subordinate to HFR-099 — a status CAS alone would not have been enough.
+
+ The run this stamps on is LIVE, and live rows take concurrent metadata writes: the
+ sweep records ``interrupt_reason``, the settler merges its ``ok`` marker. A
+ compare-and-swap on ``(status, no notice)`` makes the notice slot safe and says
+ nothing about the rest of the blob — a whole-``metadata_json`` write composed from
+ the pre-read snapshot would still erase whichever sibling key landed in the gap,
+ and erase it with the guard SATISFIED, which is the worst kind of pass.
+
+ ``json_set`` addresses one path, so this asserts on the one thing that makes the
+ guard total: a sibling written after the stamp's read survives it.
+ """
+
+ from sqlalchemy import event
+ from sqlalchemy import update as sa_update
+
+ from storage.models import agent_runs
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-siblings")
+ run = requests.enqueue_task_run("task-binding-siblings")
+ assert requests.claim(run.id) is not None
+
+ interleaved: list[str] = []
+
+ def _write_a_sibling_inside_the_gap(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ # Not a terminal transition, so the status CAS still passes — exactly the
+ # interleaving a status-only guard would wave through.
+ with sqlite.engine.begin() as other:
+ other.execute(
+ sa_update(agent_runs)
+ .where(agent_runs.c.id == run.id)
+ .values(metadata_json='{"interrupt_reason": "transport_unavailable"}')
+ )
+
+ event.listen(sqlite.engine, "before_cursor_execute", _write_a_sibling_inside_the_gap)
+ try:
+ stamped = _binding_stamp(sqlite, run.id, task_id="task-binding-siblings")
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _write_a_sibling_inside_the_gap)
+
+ assert interleaved, "the sibling write never got into the gap — this test proves nothing"
+ assert stamped is not None, "a non-terminal sibling write must not refuse the stamp"
+
+ metadata = sqlite.get_run(run.id)["metadata"]
+ assert metadata["interrupt_reason"] == "transport_unavailable", (
+ f"the stamp must write only its own key, not the whole blob: {metadata!r}"
+ )
+ assert metadata[OWED_FAILURE_NOTICE_KEY]["failure_id"] == "binding:task-binding-siblings:sig-1"
+
+
+def test_a_binding_stamp_survives_a_success_settled_inside_its_gap(tmp_path: Path) -> None:
+ """Subordinate to HFR-099 — the third damage direction: a LOST notice.
+
+ The round-9 CAS closed two directions and opened one. ``failed`` and ``canceled``
+ both have a legitimate reason to refuse — the failure notice outranks the binding
+ news, and a Stop outranks it too — but ``succeeded`` has none. A successful
+ settlement writes NO notice at all, so refusing leaves the slot empty; and the
+ refusal is PERMANENT, not deferred, because ``_emit_binding_change`` persists the
+ ``binding_recovery`` dedup marker BEFORE it calls the stamp, so every later fire
+ short-circuits on that marker and never retries. The user's pinned session was
+ replaced and nothing ever tells them.
+
+ ``list_owed_failure_notices`` was widened to failed+succeeded for exactly this
+ row — "the one notice a succeeded run can owe" — so the slot is not merely empty,
+ it is legitimately owed and deliverable. The store therefore re-reads the row once
+ after a lost CAS and stamps when the winner is ``succeeded`` and the slot is still
+ empty.
+
+ The interleaving is the failed-race test's, with a SUCCESSFUL settlement as the
+ racing write.
+ """
+
+ from sqlalchemy import event
+
+ from storage.background import NOTICE_KIND_BINDING_CHANGE
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-binding-success", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-binding-success")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+
+ interleaved: list[str] = []
+
+ def _settle_successfully_inside_the_gap(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ # The rebound retry's result lands and the run settles ``succeeded`` — no
+ # error, so no failure notice, so the notice slot stays empty. The stamp's
+ # status snapshot (``running``) is now stale; its UPDATE has not reached the
+ # driver yet.
+ requests.complete(claimed, ok=True, task_id="task-binding-success")
+
+ event.listen(sqlite.engine, "before_cursor_execute", _settle_successfully_inside_the_gap)
+ try:
+ stamped = _binding_stamp(sqlite, run.id, task_id="task-binding-success")
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _settle_successfully_inside_the_gap)
+
+ assert interleaved, "the successful settler never got into the gap — this test proves nothing"
+ assert stamped is not None, (
+ "a successful settlement writes no notice, so refusing the binding stamp loses "
+ "it forever: the dedup marker is already durable and no later fire retries"
+ )
+
+ assert sqlite.get_run(run.id)["status"] == "succeeded"
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None, "the binding notice must be on the row, not just returned"
+ assert notice["failure_id"] == "binding:task-binding-success:sig-1"
+ assert notice["kind"] == NOTICE_KIND_BINDING_CHANGE
+ assert notice["state"] == "pending"
+ # And it is DELIVERABLE — the reason ``list_owed_failure_notices`` selects
+ # ``succeeded`` alongside ``failed`` at all.
+ assert [row["id"] for row in sqlite.list_owed_failure_notices()] == [run.id]
+
+
+def test_one_rebind_that_wins_its_race_still_notifies_exactly_once(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Subordinate to HFR-099 — the race fix must not turn one rebind into two notices.
+
+ A GREEN-FROM-BIRTH PIN, said plainly: nothing here is a red-first fix. Both dedup
+ layers already exist and are each exercised elsewhere — the ``binding_recovery``
+ signature short-circuit at the top of ``_emit_binding_change``
+ (``tests/test_scheduled_tasks.py`` covers "one broken binding, one notification")
+ and the slot-occupied refusal inside ``stamp_binding_change_notice`` (the CAS tests
+ just above). What no test did was put them TOGETHER on the path the round-10 change
+ touched, and that omission was load-bearing: the success-race test above stops at
+ store level and never calls ``_emit_binding_change`` at all, so the marker that
+ gates every later fire does not exist in its world. It therefore proves the notice
+ is not LOST and says nothing about it being DUPLICATED — and the retry the round-10
+ change added is precisely a second stamp attempt against a row whose transition
+ marker is already durable.
+
+ The three steps are the whole claim, end to end on one store:
+
+ 1. the race, driven THROUGH ``_emit_binding_change`` so the marker is persisted
+ before the stamp exactly as in production, resolves with one pending notice;
+ 2. a LATER FIRE of the same definition against the same binding — a real second
+ ``agent_runs`` row, because reusing the first would be dedup'd by the occupied
+ slot and would prove the wrong layer — reaches the stamp NOT AT ALL, and leaves
+ exactly one owed row;
+ 3. the drain, through the real dispatcher, lands exactly ONE durable message, and a
+ second pass lands nothing.
+
+ Red-by-mutation evidence, since the test cannot go red against HEAD: neutering the
+ signature short-circuit in ``_emit_binding_change`` makes step 2 stamp a second
+ notice onto the later run, and both of its assertions fail.
+ """
+
+ from sqlalchemy import event
+
+ from core.scheduled_tasks import SessionBindingChange
+ from storage.background import NOTICE_KIND_BINDING_CHANGE, NOTICE_PENDING
+ from vibe.i18n import t as i18n_t
+
+ from tests.test_scheduled_tasks import _binding_env
+
+ # One DB for the execution, the drain and the ``messages`` receipt, exactly as
+ # ``_rebound_run`` arranges it for the HFR-099 delivery test.
+ _binding_env(tmp_path, monkeypatch)
+ _migrated_state_db()
+ sqlite, requests = _store(tmp_path)
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ service._t = lambda key, **kwargs: i18n_t(key, "en", **kwargs)
+
+ task = service.store.add_task(
+ name="daily digest",
+ session_key="",
+ session_id="ses-fresh",
+ session_policy="create_once",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ metadata={"session_scope_id": "slack::channel::C123"},
+ )
+ change = SessionBindingChange(
+ action="rebound",
+ task_id=task.id,
+ reason="session_missing",
+ previous_session_id="sesdoesnotexist",
+ detail="the pinned session was replaced",
+ new_session_id="ses-fresh",
+ settings_preserved=False,
+ )
+
+ # Every stamp ATTEMPT, not just every stamp that landed: the claim in step 2 is that
+ # the later fire short-circuits before the store is asked, which a check on the
+ # store's contents alone cannot distinguish from a refused attempt.
+ attempts: list[tuple[str, str]] = []
+ real_stamp = sqlite.stamp_binding_change_notice
+
+ def _recording_stamp(run_id, **kwargs):
+ attempts.append((run_id, str(kwargs.get("signature"))))
+ return real_stamp(run_id, **kwargs)
+
+ monkeypatch.setattr(sqlite, "stamp_binding_change_notice", _recording_stamp)
+
+ # --- step 1: the race, through the real emitter -------------------------
+ first = requests.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ claimed = requests.claim(first.id)
+ assert claimed is not None
+
+ interleaved: list[str] = []
+
+ def _settle_successfully_inside_the_gap(
+ conn, cursor, statement, parameters, context, executemany
+ ) -> None:
+ if interleaved or not statement.lstrip().upper().startswith("UPDATE AGENT_RUNS"):
+ return
+ interleaved.append(statement)
+ requests.complete(claimed, ok=True, task_id=task.id)
+
+ event.listen(sqlite.engine, "before_cursor_execute", _settle_successfully_inside_the_gap)
+ try:
+ asyncio.run(service._emit_binding_change(change, run_id=first.id, run_error=None))
+ finally:
+ event.remove(sqlite.engine, "before_cursor_execute", _settle_successfully_inside_the_gap)
+
+ assert interleaved, "the successful settler never got into the gap — this test proves nothing"
+ # The marker really is durable BEFORE the stamp, which is what makes step 2's
+ # short-circuit the only thing standing between one notice and one per fire.
+ recorded = (service.store.get_task(task.id).metadata or {}).get("binding_recovery") or {}
+ assert recorded.get("signature") == change.signature, (
+ f"the dedup marker must be persisted by the emitter: {recorded!r}"
+ )
+ assert sqlite.get_run(first.id)["status"] == "succeeded"
+ assert attempts == [(first.id, change.signature)]
+
+ notice = sqlite.owed_failure_notice(first.id)
+ assert notice is not None, "the rebind notice was lost to the race"
+ assert notice["kind"] == NOTICE_KIND_BINDING_CHANGE
+ assert notice["state"] == NOTICE_PENDING
+ assert notice["failure_id"] == f"binding:{task.id}:{change.signature}"
+ assert [row["id"] for row in sqlite.list_owed_failure_notices()] == [first.id]
+
+ # --- step 2: a later fire against the same binding ----------------------
+ # A fresh run row, settled ``succeeded`` like the first: a duplicate stamped here
+ # would be selected by ``list_owed_failure_notices`` and delivered, which is the
+ # damage this step exists to exclude. Reusing ``first`` would instead be refused by
+ # the occupied notice slot and would prove a different guard.
+ later = requests.enqueue_task_run(task.id, source_kind="scheduler", task=task)
+ claimed_later = requests.claim(later.id)
+ assert claimed_later is not None
+ asyncio.run(service._emit_binding_change(change, run_id=later.id, run_error=None))
+ requests.complete(claimed_later, ok=True, task_id=task.id)
+ assert sqlite.get_run(later.id)["status"] == "succeeded"
+
+ assert attempts == [(first.id, change.signature)], (
+ "a later fire against the SAME binding must not reach the store at all: the "
+ f"transition marker is the dedup key, not the run; attempts were {attempts}"
+ )
+ assert sqlite.owed_failure_notice(later.id) is None, (
+ "the later fire must owe nothing — one broken binding is one notification"
+ )
+ assert [row["id"] for row in sqlite.list_owed_failure_notices()] == [first.id], (
+ "exactly one row may be owed for this transition, however often it fires"
+ )
+
+ # --- step 3: exactly one durable message reaches the user ---------------
+ emissions = _spy_emissions(controller)
+ asyncio.run(service._drain_failure_notices())
+
+ settled = sqlite.owed_failure_notice(first.id)
+ assert settled["state"] == NOTICE_SENT
+ assert [item["type"] for item in emissions] == ["notify"]
+ assert len(controller.im_client.sent) == 1, (
+ f"one transition must produce ONE message: {controller.im_client.sent}"
+ )
+ channel, _thread, sent_text = controller.im_client.sent[0]
+ assert channel == "C123"
+ assert "sesdoesnotexist" in sent_text and "ses-fresh" in sent_text, (
+ f"the one message must name old -> new session: {sent_text!r}"
+ )
+ delivered = _persisted_messages()
+ assert [row["type"] for row in delivered] == ["notify"]
+ assert delivered[0]["content_text"] == sent_text
+
+ # A second pass delivers NOTHING: the notice is sent and acked, so it is no longer
+ # owed — the drain is idempotent rather than merely first-wins.
+ asyncio.run(service._drain_failure_notices())
+ assert not sqlite.list_owed_failure_notices()
+ assert len(controller.im_client.sent) == 1
+ assert [item["type"] for item in emissions] == ["notify"]
+ assert _persisted_messages() == delivered
+
+
+# --- round 9, gate item 5: copy for a definition that no longer exists -------
+
+
+def _copy_service(tmp_path: Path, sqlite, requests):
+ """A service wired for body rendering only, with the REAL translator."""
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore
+
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.store = store
+ service.request_store = requests
+ service.controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+ return service
+
+
+def _every_vibe_command(body: str) -> list[list[str]]:
+ """Every ``vibe …`` invocation the copy prints, as argv.
+
+ A left word boundary so the ``[Avibe Harness]`` brand prefix is not read as an
+ invocation, and one command per line because that is how the body is built.
+ """
+
+ import re
+ import shlex
+
+ commands: list[list[str]] = []
+ for line in body.splitlines():
+ for match in re.finditer(r"(?<![A-Za-z])vibe ", line):
+ commands.append(shlex.split(line[match.end():].strip()))
+ return commands
+
+
+def test_a_deleted_definition_notice_names_only_run_level_recovery(tmp_path: Path) -> None:
+ """Subordinate to HFR-094 — parser-validated copy, for a definition that is gone.
+
+ ``get_task`` returns ``None`` once the definition row is deleted while the run row
+ keeps its ``definition_id`` forever, and the failure body still appended
+ ``harness.notice.rerun`` unconditionally: "Re-run it now with: vibe task run
+ <id>". That command parses and then fails at runtime with "not found", which is
+ the exact defect HFR-094 exists for one noun over — copy that names an action the
+ user cannot take.
+
+ A deleted definition has no rerun, no resume and no ``show``. What it does have is
+ the run record, so the copy offers ``vibe runs show`` and says plainly that the
+ definition is gone.
+ """
+
+ from vibe.cli import build_parser
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-deleted", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-deleted")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-deleted")
+
+ service = _copy_service(tmp_path, sqlite, requests)
+ # The definition is removed AFTER the run settled, which is the ordinary case: a
+ # user archives a task whose last fire failed and has not been told yet.
+ assert service.store.remove_task("task-deleted")
+ assert service.store.get_task("task-deleted") is None
+ assert service.store.get_watch_definition("task-deleted") is None
+
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice is not None
+ body = service._failure_notice_body(sqlite.get_run(run.id), notice)
+
+ assert "vibe task" not in body, f"a deleted task cannot be addressed as a task: {body}"
+ assert "vibe watch" not in body, f"a deleted definition is not a watch either: {body}"
+ assert run.id in body, f"the run is the only thing left to inspect: {body}"
+
+ parser = build_parser()
+ printed = _every_vibe_command(body)
+ assert printed, f"the copy must still offer the user something: {body}"
+ for argv in printed:
+ try:
+ parser.parse_args(argv)
+ except SystemExit: # pragma: no cover - the assertion is the point
+ raise AssertionError(f"the copy prints {argv!r}, which the CLI cannot parse: {body}")
+
+
+def test_a_deleted_definition_binding_notice_drops_the_repin_command(tmp_path: Path) -> None:
+ """Subordinate to HFR-094 — the same hole on the binding-change body.
+
+ ``_binding_notice_body`` renders ``vibe task update <id> --session-id …`` and
+ ``vibe task show <id>`` against a definition it never checked the existence of.
+ A rebind notice can outlive its definition by the whole retry/backoff window, so
+ "pin it back" is offered for a row that cannot be pinned.
+ """
+
+ from vibe.cli import build_parser
+ from storage.background import NOTICE_KIND_BINDING_CHANGE
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-rebound-deleted", deliver_key="slack::channel::C1")
+ run = requests.enqueue_task_run("task-rebound-deleted")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ stamped = _binding_stamp(sqlite, run.id, task_id="task-rebound-deleted")
+ assert stamped is not None and stamped["kind"] == NOTICE_KIND_BINDING_CHANGE
+ requests.complete(claimed, ok=True, task_id="task-rebound-deleted")
+
+ service = _copy_service(tmp_path, sqlite, requests)
+ assert service.store.remove_task("task-rebound-deleted")
+ assert service.store.get_task("task-rebound-deleted") is None
+
+ body = service._failure_notice_body(
+ sqlite.get_run(run.id), sqlite.owed_failure_notice(run.id)
+ )
+
+ assert "vibe task" not in body, f"a deleted task cannot be re-pinned or shown: {body}"
+ assert "vibe watch" not in body, f"a rebound task is not a watch: {body}"
+ assert run.id in body, f"the run is the only thing left to inspect: {body}"
+ # The news itself must survive: this is still "your session was replaced".
+ assert "ses-fresh" in body and "ses-gone" in body, f"the rebind must still be reported: {body}"
+
+ parser = build_parser()
+ for argv in _every_vibe_command(body):
+ try:
+ parser.parse_args(argv)
+ except SystemExit: # pragma: no cover - the assertion is the point
+ raise AssertionError(f"the copy prints {argv!r}, which the CLI cannot parse: {body}")
+
+
+# =============================================================================
+# round 12: drain semantics and interruption copy
+# =============================================================================
+#
+# Four defects and one consuming-path pin, all in the owed-notice drain's own
+# control flow rather than in the store:
+#
+# * T-1 (G) a rung that RAISES must not kill the ladder walk;
+# * T-2 (L) one pass may not hold the whole backlog for batch x timeout;
+# * T-3 (E) an interruption reason is a wire value, not user-visible copy;
+# * T-4 (F) a nonnumeric ``attempts`` must degrade, not wedge the batch;
+# * T-5 (B) the consuming-path pin for the adapter bookkeeping guard.
+#
+# Appended as one block on purpose: several rounds run in parallel worktrees and
+# a single trailing section is the cheapest thing to cherry-pick.
+
+
+def _ladder_task(
+ sqlite,
+ definition_id: str,
+ *,
+ first: str,
+ second: str,
+) -> None:
+ """A definition whose ladder has exactly TWO rungs, in a known order.
+
+ Rung (1) is the delivery key and rung (3) is caller provenance; the caller
+ carries a ``session_key`` and NOTHING else, because a ``platform`` +
+ ``user_id`` pair would add rung (4) and make "the walk continued" ambiguous
+ about which later rung it reached.
+ """
+
+ _task(
+ sqlite,
+ definition_id,
+ name="daily report",
+ deliver_key=first,
+ metadata={"created_by": {"caller": {"session_key": second}}},
+ )
+
+
+def test_a_raising_ladder_rung_does_not_abandon_the_rest_of_the_walk(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-079, subordinate — a rung that raises is an UNUSABLE rung, not a dead walk.
+
+ The per-rung ``try/except`` covered ``_build_context`` alone. The
+ ``emit_replayed_backend_failure`` call one line below it was unwrapped, so any
+ raise from a rung's delivery — a platform whose settings manager is gone, a
+ client lookup that fails, an adapter that throws before the transport — escaped
+ the ``for`` body entirely, unwound through the walk's ``finally`` and landed in
+ ``_deliver_one_failure_notice``'s handler, which consumed the attempt and armed
+ the backoff. The next pass then started the SAME ladder from rung (1) and raised
+ again, so the notice burned every attempt on one broken rung and dead-lettered
+ without ever trying rung (2) — even though the walk already CONTINUES for a rung
+ whose send is un-acked (``_rung_acknowledges`` returning False), which is the
+ weaker version of the same condition.
+
+ Round 7's accepted contract is that an unresolvable or stale candidate continues
+ the walk. A raising one is the same class of unusable and must be treated the
+ same way.
+
+ The cost, stated rather than hidden: a rung that raises AFTER its transport
+ accepted the send, without leaving evidence, now duplicates onto the next rung.
+ That is exactly the class finding B's adapter guard (0ebf4c55, shipped in this
+ same round) closes at the source — an already-delivered id is no longer destroyed
+ by post-send bookkeeping — and what remains is covered by the duplicate
+ short-circuit on the retry plus the at-least-once residual documented on
+ ``CLAIM_LEASE_SECONDS``.
+ """
+
+ import core.scheduled_tasks as scheduled_tasks
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+
+ sqlite, requests = _store(tmp_path)
+ _ladder_task(
+ sqlite,
+ "task-raising-rung",
+ first="slack::channel::C-FIRST",
+ second="slack::channel::C-SECOND",
+ )
+ run = requests.enqueue_task_run("task-raising-rung")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-raising-rung")
+
+ attempted: list[str] = []
+
+ async def _first_rung_raises(controller, context, backend, diagnostic, **kwargs):
+ attempted.append(context.channel_id)
+ if context.channel_id == "C-FIRST":
+ raise RuntimeError("no settings manager for slack")
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.send_returned = True
+ evidence.delivered_id = "ts-second"
+ evidence.persisted_row = {"id": "msg-second"}
+ return False
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _first_rung_raises)
+
+ from types import SimpleNamespace
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ assert attempted == ["C-FIRST", "C-SECOND"], (
+ "a raising rung must be skipped, not end the walk; attempted=" f"{attempted}"
+ )
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == NOTICE_SENT, f"the second rung delivered it: {notice}"
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT
+ assert notice["attempts"] == 1, "one pass, one attempt"
+ # The skipped rung is recorded rather than swallowed: the aggregate evidence
+ # carries the first raise so an operator can see WHY rung (1) was passed over,
+ # on a row that is nonetheless acknowledged and will never be resent.
+ assert "no settings manager for slack" in (notice["error"] or ""), (
+ f"the skipped rung's own error must survive for diagnosis: {notice}"
+ )
+
+
+def test_the_walk_deadline_still_cancels_through_a_rung(tmp_path: Path, monkeypatch) -> None:
+ """HFR-079, subordinate — the per-rung handler may not eat ``CancelledError``.
+
+ The fix above catches ``Exception``, deliberately and not ``BaseException``: the
+ walk-level deadline (``NOTICE_DELIVERY_TIMEOUT_SECONDS``) cancels the delivery
+ task, and cancellation has to unwind the whole walk rather than being converted
+ into "this rung was unusable, try the next one". A handler one letter wider would
+ turn one wedged rung into a walk that keeps going past its own deadline, holding
+ the claim beyond the lease it was cancelled to respect.
+
+ Rung (2) never being attempted is the assertion: it is what distinguishes
+ cancellation from the raise above.
+ """
+
+ import core.failure_notices as failure_notices
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _ladder_task(
+ sqlite,
+ "task-cancel-rung",
+ first="slack::channel::C-HANG",
+ second="slack::channel::C-NEVER",
+ )
+ run = requests.enqueue_task_run("task-cancel-rung")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-cancel-rung")
+
+ attempted: list[str] = []
+
+ async def _first_rung_hangs(controller, context, backend, diagnostic, **kwargs):
+ attempted.append(context.channel_id)
+ await asyncio.Event().wait()
+ return False # pragma: no cover - the wait never returns
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _first_rung_hangs)
+ monkeypatch.setattr(failure_notices, "NOTICE_DELIVERY_TIMEOUT_SECONDS", 0.05)
+
+ from types import SimpleNamespace
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ assert attempted == ["C-HANG"], (
+ "the deadline must unwind the whole walk, not advance it to the next rung: "
+ f"{attempted}"
+ )
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == "pending", f"a timed-out delivery stays retryable: {notice}"
+ assert notice["attempts"] == 1, "the claim's attempt is consumed by the timeout"
+ assert "timed out" in (notice["error"] or ""), f"the timeout must say so: {notice}"
+
+
+def test_one_pass_stops_at_its_fairness_budget_instead_of_holding_the_backlog(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-076, subordinate — a pass is bounded by a budget, not by batch x timeout.
+
+ What is NOT the defect, refuted first because the obvious reading is wrong:
+ a wedged batch does not re-select itself forever. ``list_owed_failure_notices``
+ orders by ``next_attempt_at ASC`` (least-recently-deferred first), so a notice
+ stamped while ten rows were being delivered sorts AHEAD of the fresh backoff
+ instants those ten just armed and is picked up on the next pass.
+
+ What IS real is the SERIAL cost. One pass delivers its batch one notice at a
+ time — single-flight, accepted in round 9, because row #2 only sees row #1's
+ ``sent`` when the passes are ordered — and each delivery may legitimately sit on
+ ``NOTICE_DELIVERY_TIMEOUT_SECONDS``. Ten wedged rows is ten times that before the
+ pass even returns, and a freshly stamped notice waits behind all of it. The cure
+ is NOT concurrency: parallel deliveries reopen the same-streak duplicate window
+ that serialization closes.
+
+ So the pass takes a fairness budget instead, checked BETWEEN notices and never
+ against a delivery already in flight: once it is spent the pass logs what is left
+ and stops pulling work. Untouched rows consumed no attempt, kept their backoff,
+ and stay eligible — and the ASC ordering already puts the oldest of them first
+ next pass.
+ """
+
+ import core.failure_notices as failure_notices
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ for index in range(3):
+ definition_id = f"task-budget-{index}"
+ _task(sqlite, definition_id, deliver_key=f"slack::channel::C{index}")
+ _pending_failure(
+ sqlite,
+ f"run-budget-{index}",
+ definition_id,
+ created_at=f"2026-07-27T0{index}:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": 0,
+ "next_attempt_at": None,
+ "failure_id": f"run-budget-{index}",
+ },
+ )
+
+ delivered: list[str] = []
+
+ async def _slow_emit(controller, context, backend, diagnostic, **kwargs):
+ # Slower than the budget, so the pass is over the line after the FIRST one.
+ await asyncio.sleep(0.05)
+ delivered.append(str(kwargs.get("failure_id")))
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.send_returned = True
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _slow_emit)
+ # ``raising=False``: the constant does not exist before this fix, and the test has
+ # to be runnable at that head to be red evidence rather than an import error.
+ monkeypatch.setattr(
+ failure_notices, "NOTICE_DRAIN_PASS_BUDGET_SECONDS", 0.01, raising=False
+ )
+
+ from types import SimpleNamespace
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ assert len(delivered) == 1, (
+ "the pass must stop pulling work once its budget is spent, and must still "
+ f"make progress on one notice: {delivered}"
+ )
+ # The in-flight delivery was never cancelled: the one notice the pass started is
+ # acknowledged, not left half-done.
+ started = delivered[0]
+ assert sqlite.owed_failure_notice(started)["state"] == NOTICE_SENT
+
+ now = "2099-01-01T00:00:00+00:00"
+ for index in range(3):
+ run_id = f"run-budget-{index}"
+ if run_id == started:
+ continue
+ untouched = sqlite.owed_failure_notice(run_id)
+ assert untouched["attempts"] == 0, (
+ f"a row the pass never reached must not consume an attempt: {untouched}"
+ )
+ assert owed_notice_eligible(untouched, now), (
+ f"a row the pass never reached must stay eligible: {untouched}"
+ )
+ listed = {str(row["id"]) for row in sqlite.list_owed_failure_notices(limit=10)}
+ assert listed == {f"run-budget-{i}" for i in range(3)} - {started}, (
+ f"the deferred remainder is exactly what the next pass picks up: {listed}"
+ )
+
+
+def test_the_pass_budget_admits_one_full_worst_case_delivery() -> None:
+ """The lower side of the budget's two-sided argument, as an assertion.
+
+ A budget below ``NOTICE_DELIVERY_TIMEOUT_SECONDS`` would be spent before the
+ notice the pass STARTED could finish, which reads as "bound the send" — a job the
+ walk deadline already owns and this constant cannot do, since it is only ever
+ checked between notices. At or above one deadline, a pass always makes progress on
+ at least one notice no matter how slow that notice is.
+ """
+
+ from core.failure_notices import (
+ NOTICE_DELIVERY_TIMEOUT_SECONDS,
+ NOTICE_DRAIN_PASS_BUDGET_SECONDS,
+ )
+
+ assert NOTICE_DRAIN_PASS_BUDGET_SECONDS >= NOTICE_DELIVERY_TIMEOUT_SECONDS, (
+ "a pass must be able to contain one full worst-case delivery"
+ )
+
+
+def _zh_body_service(tmp_path: Path, sqlite, requests):
+ """A service whose ``_t`` is the REAL translator, in Chinese.
+
+ Copy defects are only visible through the real catalog: a ``_t`` that echoes keys
+ reports which key was chosen, not what the user reads, and the whole point here is
+ that an untranslated fragment survives translation.
+ """
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ service.controller.config = SimpleNamespace(language="zh", platform="slack")
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+ return service
+
+
+def test_an_interruption_notice_never_prints_the_raw_wire_reason(tmp_path: Path) -> None:
+ """HFR-094's family — an ``interrupt_reason`` is a wire value, not product copy.
+
+ ``harness.notice.interrupted`` takes ``reason=`` and renders it INSIDE the
+ sentence, and the drain passed the stored value straight through. So a Chinese
+ user was told 后台任务「daily report」被中断(backend_refresh) — an internal
+ identifier, untranslated, in the middle of a translated sentence, for every one of
+ the six reasons in ``RUN_INTERRUPTION_REASONS``.
+
+ Same shape and same fix as ``SWEEP_I18N_KEYS``: a closed map from wire value to
+ label key, drift-pinned against the lane's own frozenset in
+ ``tests/test_i18n_backend_keys.py`` so a new reason cannot ship unlabelled.
+ """
+
+ from core.run_settlement import RUN_INTERRUPTION_REASONS as REASONS
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-zh-reason", name="daily report")
+ service = _zh_body_service(tmp_path, sqlite, requests)
+
+ for reason in sorted(REASONS):
+ body = service._failure_notice_body(
+ {"id": "run-zh", "task_id": "task-zh-reason", "error": "boom"},
+ {"failure_id": "run-zh", "interrupt_reason": reason},
+ )
+ assert reason not in body, (
+ f"the raw wire reason {reason!r} leaked into user-visible copy: {body}"
+ )
+ assert "被中断" in body, f"the interrupted headline must still render: {body}"
+
+
+def test_an_unmapped_interruption_reason_renders_a_localized_fallback(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The closed map needs a closed FALLBACK, or the leak comes back by another door.
+
+ ``KEYS.get(reason, reason)`` would be the obvious spelling and it is the defect
+ again: a reason present in ``RUN_INTERRUPTION_REASONS`` but missing from the label
+ map — exactly what the drift test in ``tests/test_i18n_backend_keys.py`` exists to
+ catch, which means exactly what could reach a user between someone adding a reason
+ and CI failing — would print the identifier. The fallback is therefore a
+ TRANSLATED generic label, never the wire value and never the dotted key path.
+
+ Driven by emptying the map rather than by inventing a reason, because
+ ``is_interruption`` gates the branch on lane membership: an unmapped reason is
+ reachable only as a map/lane disagreement, so that is what the test creates.
+ """
+
+ import core.failure_notices as failure_notices
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-zh-unmapped", name="daily report")
+ service = _zh_body_service(tmp_path, sqlite, requests)
+
+ monkeypatch.setattr(failure_notices, "NOTICE_REASON_I18N_KEYS", {})
+
+ body = service._failure_notice_body(
+ {"id": "run-zh", "task_id": "task-zh-unmapped", "error": "boom"},
+ {"failure_id": "run-zh", "interrupt_reason": "backend_refresh"},
+ )
+
+ fallback = i18n_t(failure_notices.NOTICE_REASON_UNKNOWN_I18N_KEY, "zh")
+ assert fallback in body, f"an unmapped reason must render the localized label: {body}"
+ assert "backend_refresh" not in body, f"and never the wire value: {body}"
+ assert failure_notices.NOTICE_REASON_UNKNOWN_I18N_KEY not in body, (
+ f"nor the dotted key path: {body}"
+ )
+
+
+def _settled_run(sqlite, definition_id: str, run_id: str, *, status: str, at: str) -> None:
+ """One already-settled run of *definition_id*, stamped at *at*."""
+
+ sqlite.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": status,
+ "definition_id": definition_id,
+ "error": "boom" if status == "failed" else None,
+ "created_at": at,
+ "completed_at": at,
+ }
+ )
+
+
[email protected]("language", ["en", "zh"])
+def test_the_failed_lane_names_its_class_and_when_it_last_succeeded(
+ tmp_path: Path,
+ language: str,
+) -> None:
+ """D5's body contract, two of whose named items the failed lane never printed.
+
+ Subordinate coverage under §D5's body requirement (plan
+ ``docs/plans/harness-run-reliability.md``:3167-3169 — "the error and its class …
+ when it last succeeded"); no new scenario id this round, the §10.7 HFR-280…319
+ assignment is offered to the maintainer as a follow-up.
+
+ TWO GAPS, both in the per-fire FAILED lane specifically:
+
+ * **The class.** ``interrupt_reason`` is not a synonym for "interrupted": master
+ stamps it for ``no_terminal_result`` / ``refused_concurrent_turn`` /
+ ``transport_unavailable`` / ``queue_hold_expired`` too, and those recur on every
+ fire, so ``is_interruption`` correctly keeps them in the failure lane. But the
+ interrupted HEADLINE was the only place any reason was rendered, so on the failed
+ lane the class was dropped entirely and the user saw only whatever text the
+ ``error`` column happened to hold. ``NOTICE_REASON_I18N_KEYS`` cannot supply the
+ label: its key set is drift-pinned to ``RUN_INTERRUPTION_REASONS``, which is
+ exactly the set this lane excludes.
+ * **The last success.** No read for it existed at all, on any lane.
+
+ Asserted through the REAL translator in BOTH languages, because the defect is in
+ rendered copy: a ``_t`` that echoes keys would report which key was chosen and say
+ nothing about whether the sentence a user reads is translated. The wire value must
+ never appear, which is HFR-094's lesson applied to a second call site.
+ """
+
+ from types import SimpleNamespace
+
+ import core.failure_notices as failure_notices
+ from core.scheduled_tasks import ScheduledTaskService
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-class", name="daily report")
+ # A success, then a later success, then the failure being reported: the line has to
+ # name the LATEST success, not the first one found.
+ _settled_run(sqlite, "task-class", "run-ok-1", status="succeeded", at="2026-07-20T03:00:00+00:00")
+ _settled_run(sqlite, "task-class", "run-ok-2", status="succeeded", at="2026-07-26T03:00:00+00:00")
+ _settled_run(sqlite, "task-class", "run-bad", status="failed", at="2026-07-27T03:00:00+00:00")
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ service.controller.config = SimpleNamespace(language=language, platform="slack")
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ reason = "no_terminal_result"
+ assert reason not in failure_notices.RUN_INTERRUPTION_REASONS, (
+ "the premise: this reason belongs to the FAILED lane, not the interrupted one"
+ )
+ notice = {"failure_id": "run-bad", "interrupt_reason": reason}
+ assert not failure_notices.is_interruption(notice)
+
+ body = service._failure_notice_body(sqlite.get_run("run-bad"), notice)
+
+ # --- the class line ------------------------------------------------------
+ label = i18n_t(failure_notices.notice_failure_class_i18n_key(reason), language)
+ assert label in body, f"the failed lane must name its class: {body}"
+ assert reason not in body, f"and never the raw wire reason: {body}"
+ assert "harness.notice." not in body, f"nor a dotted key path: {body}"
+
+ # --- the last-success line ----------------------------------------------
+ assert "2026-07-26T03:00:00+00:00" in body, (
+ f"the body must say when the definition last succeeded: {body}"
+ )
+ assert "2026-07-20T03:00:00+00:00" not in body, (
+ f"and it must be the LATEST success, not the earliest: {body}"
+ )
+ assert i18n_t("harness.notice.lastSucceeded", language).split("{")[0].strip() in body, (
+ f"rendered through the localized sentence, not bare: {body}"
+ )
+
+
+def test_a_failed_lane_body_omits_both_lines_when_neither_is_real(tmp_path: Path) -> None:
+ """The other half of the contract: render only what exists.
+
+ A definition with no prior success has no last-success line, and a failure with no
+ ``interrupt_reason`` has no class line. Rendering "Last succeeded: never" or
+ "Class: unknown" would be the ``harness.notice.unknownError`` mistake again — copy
+ about nothing, on the lane that already carries the most lines.
+ """
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-fresh", name="daily report")
+ _settled_run(sqlite, "task-fresh", "run-bad", status="failed", at="2026-07-27T03:00:00+00:00")
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ service.controller.config = SimpleNamespace(language="en", platform="slack")
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ body = service._failure_notice_body(
+ sqlite.get_run("run-bad"), {"failure_id": "run-bad", "interrupt_reason": None}
+ )
+
+ from vibe.i18n import t as i18n_t
+
+ assert i18n_t("harness.notice.lastSucceeded", "en").split("{")[0].strip() not in body, (
+ f"a definition that has never succeeded gets no last-success line: {body}"
+ )
+ assert i18n_t("harness.notice.failureClass", "en").split("{")[0].strip() not in body, (
+ f"a failure with no recorded class gets no class line: {body}"
+ )
+
+
+def test_the_last_success_read_is_one_bounded_indexed_seek(tmp_path: Path) -> None:
+ """Subordinate to HFR-068's family — this read runs per notice on the 2s tick.
+
+ The body renders one instant, so the STORE must return one row: an indexed seek on
+ ``ix_agent_runs_definition_settled`` with ``LIMIT 1`` and the filters as SQL terms,
+ not a definition's whole success history filtered in Python. Asserted on the
+ CONSTRAINED TERMS rather than only on the index name, which is the HFR-095 /
+ HFR-086 lesson: a plan can name an index while the term stays a per-row filter.
+
+ The expression and tie-break are shared BY NAME with ``_health_rows`` rather than
+ retyped — two copies of ``coalesce(completed_at, created_at)`` drift silently, and
+ the copy that drifts is the one the planner stops matching.
+ """
+
+ import re
+
+ sqlite, _ = _store(tmp_path)
+ _task(sqlite, "task-hot")
+ for index in range(400):
+ instant = f"2026-07-27T{index // 60:02d}:{index % 60:02d}:00+00:00"
+ _settled_run(
+ sqlite,
+ "task-hot",
+ f"run-{index:04d}",
+ status="failed" if index % 4 else "succeeded",
+ at=instant,
+ )
+
+ plans = _agent_run_query_plans(
+ sqlite,
+ tmp_path / "state" / "vibe.sqlite",
+ lambda: sqlite.last_success_settled_at("task-hot"),
+ )
+ assert len(plans) == 1, f"one instant must cost one statement: {plans}"
+ statement, plan = plans[0]
+ flat = " ".join(plan)
+ assert "ix_agent_runs_definition_settled" in flat, (
+ f"the seek must ride the settled-time index: {plan}"
+ )
+ assert "SCAN agent_runs" not in flat, f"and must not scan the table: {plan}"
+ assert "TEMP B-TREE" not in flat, (
+ f"the index supplies the order, so nothing may be sorted: {plan}"
+ )
+ normalized = re.sub(r"\s+", " ", statement).upper()
+ # The bound travels as a PARAMETER, exactly as ``_health_rows``' does, so the
+ # value is asserted from the parameters rather than from the SQL text.
+ assert "LIMIT ?" in normalized, f"the bound has to be in the DATABASE: {statement}"
+ statements = _agent_run_statements(sqlite, lambda: sqlite.last_success_settled_at("task-hot"))
+ assert len(statements) == 1
+ assert 1 in tuple(statements[0][1]), (
+ f"and the bound has to be ONE row, not a page: {statements[0][1]}"
+ )
+ assert "DEFINITION_ID = ?" in normalized, f"the definition is an equality term: {statement}"
+ assert "STATUS IN" in normalized, f"the verdict filter is a SQL term: {statement}"
+ assert "RUN_TYPE !=" in normalized, (
+ f"the watch-supervisor exclusion is a SQL term too: {statement}"
+ )
+
+ # And the answer is the real one: the newest succeeded row in the history above.
+ assert sqlite.last_success_settled_at("task-hot") == "2026-07-27T06:36:00+00:00"
+ # A definition with no success at all answers None rather than an empty string, so
+ # the body can decide by presence.
+ assert sqlite.last_success_settled_at("task-absent") is None
+
+
+ "attempts,expected_attempt",
+ [("x", 1), ("", 1), ("3.5", 4), (["1"], 1), ({"n": 1}, 1), (None, 1)],
+ ids=["nonnumeric", "blank", "float-string", "list", "dict", "null"],
+)
+def test_a_malformed_attempts_value_degrades_instead_of_raising(
+ attempts, expected_attempt
+) -> None:
+ """HFR-076, subordinate — ``attempts`` is JSON, so it can be anything.
+
+ ``int(notice.get("attempts") or 0)`` raises ``ValueError`` on a nonnumeric string
+ and ``TypeError`` on a container. Nothing crashes — the drain's per-row handler
+ catches it — and that is precisely what makes it bad: the exception escapes BEFORE
+ the claim, so no state is written at all. The row keeps its malformed value, stays
+ eligible, is re-selected by the next 2 s tick, raises again, and occupies a slot in
+ the batch of ten forever. Starvation of every notice behind it, with a log line per
+ tick and a drain that looks busy rather than broken.
+
+ CORRECTED IN ROUND 19: the round-12 version degraded EVERYTHING unreadable to 0,
+ which agreed with SQLite for these shapes except one — ``"3.5"`` reads 3 under
+ ``CAST(... AS INTEGER)``'s numeric-prefix parse, not 0 — so the expected pair here
+ was pinning a Python-only answer the CAS would refuse forever. Both readers now
+ consume one model of the CAST (``storage.sqlite_semantics.sqlite_cast_integer``),
+ so the float-string row expects the CAST's answer: attempt 4, not attempt 1. The
+ truly nonnumeric shapes still read 0 on both sides.
+ """
+
+ from core.failure_notices import BACKOFF_SECONDS, next_attempt
+
+ assert next_attempt({"state": "pending", "attempts": attempts}) == (
+ expected_attempt,
+ BACKOFF_SECONDS[expected_attempt - 1],
+ )
+
+
+def test_the_python_and_sql_readings_of_a_malformed_attempts_agree(tmp_path: Path) -> None:
+ """The agreement itself, asserted rather than asserted-about.
+
+ ``next_attempt`` picks the backoff, ``notice_write_expectation`` builds the CAS
+ predicate, and ``OWED_NOTICE_ATTEMPTS_SQL`` evaluates it inside SQLite. If any one
+ of the three read a malformed ``attempts`` differently the claim would be refused
+ every pass — the same wedge as raising, reached by a guarded write that can never
+ match.
+ """
+
+ from storage.background import notice_write_expectation
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-bad-attempts", deliver_key="slack::channel::C1")
+ _pending_failure(
+ sqlite,
+ "run-bad-attempts",
+ "task-bad-attempts",
+ created_at="2026-07-27T00:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": "not-a-number",
+ "next_attempt_at": None,
+ "failure_id": "run-bad-attempts",
+ },
+ )
+
+ notice = sqlite.owed_failure_notice("run-bad-attempts")
+ assert notice_write_expectation(notice)[1] == 0, "the CAS side reads 0"
+ claimed = sqlite.update_owed_failure_notice(
+ "run-bad-attempts",
+ expect=notice_write_expectation(notice),
+ attempts=1,
+ )
+ assert claimed is not None, "so SQL must agree and let the claim through"
+ assert claimed["attempts"] == 1
+
+
+def test_a_malformed_attempts_row_advances_instead_of_occupying_the_batch(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The consuming outcome: the batch slot is released, not re-occupied forever."""
+
+ import core.scheduled_tasks as scheduled_tasks
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-bad-attempts", deliver_key="slack::channel::C1")
+ _pending_failure(
+ sqlite,
+ "run-bad-attempts",
+ "task-bad-attempts",
+ created_at="2026-07-27T00:00:00+00:00",
+ notice={
+ "state": "pending",
+ "attempts": ["1"],
+ "next_attempt_at": None,
+ "failure_id": "run-bad-attempts",
+ },
+ )
+
+ delivered: list[str] = []
+
+ async def _emit(controller, context, backend, diagnostic, **kwargs):
+ delivered.append(str(kwargs.get("failure_id")))
+ evidence = kwargs.get("delivery")
+ if evidence is not None:
+ evidence.send_returned = True
+ evidence.delivered_id = "m1"
+ evidence.persisted_row = {"id": "m1"}
+ return False
+
+ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _emit)
+
+ from types import SimpleNamespace
+
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+
+ notice = sqlite.owed_failure_notice("run-bad-attempts")
+ assert notice["attempts"] == 1, f"the claim must consume an attempt: {notice}"
+ assert notice["state"] == NOTICE_SENT, f"and the delivery must be reached: {notice}"
+ assert delivered == ["run-bad-attempts"]
+ assert sqlite.list_owed_failure_notices(limit=10) == [], (
+ "a settled row must free its slot in the batch"
+ )
+
+
+# =============================================================================
+# round 13: #1060's field case — the watch that died with its delivery target
+# =============================================================================
+#
+# The maintainer's acceptance note (PR #1072 comment 5120451508) asks this round to
+# absorb the field evidence filed on #1060 (comment 5097759698) rather than argue
+# from the plan: a real watch (``lane-b-pr5``) was created with ``--session-id``, the
+# session later ceased to exist, three follow-up deliveries failed four minutes
+# apart, the watch flipped to ``enabled=0``, and NOBODY WAS TOLD FOR 3.5 HOURS. A P1
+# review finding sat unattended in that window, because the watch was the only thing
+# that would have surfaced it.
+#
+# Five outcomes are owed, and the two tests below consume them end to end rather
+# than one layer at a time — the note's ask is field realism, so nothing here stubs
+# ``resolve_session_id_target``, the waiter subprocess, or settlement:
+#
+# (a) the terminal row is NOT indistinguishable from a pause or a retirement;
+# (b) the RECORDED CAUSE is the delivery failure, never the waiter's retry
+# sentinel (#1060's first complaint: the row blamed exit 75, the configured
+# ``--retry-exit-code``, i.e. the "nothing new yet" signal);
+# (c) the terminal timestamps are COHERENT (its second: ``last_started_at`` after
+# ``last_event_at`` with a null ``last_finished_at`` on a terminal row);
+# (d) exactly one actionable notice reaches the workspace inbox — via the mandatory
+# workspace rung, since every preferred rung here names a session row that no
+# longer exists (its third complaint and the whole cost: "a monitor that fails
+# silently is worse than no monitor");
+# (e) a restart or replay can neither duplicate nor erase that notice.
+#
+# What this round found ALREADY COHERENT, recorded because the plan predicted
+# otherwise: ``mark_cycle_result`` writes ``retired_at``, ``last_finished_at`` and
+# ``last_event_at`` in ONE guarded stamp on the cycle that disables the watch, so
+# (c) and the ``enabled=0``/``retired_at IS NULL`` half of (a) need no change in
+# ``core/watches.py`` at all — #1060's row predates that stamp. They are asserted
+# here anyway: they are the preconditions the rest of the case rests on, and a
+# regression in them reopens the field bug by a different road.
+#
+# No new scenario id. The §10.7 HFR-280… block is unassigned and cyhhao declined to
+# consume one for this round; both cases are subordinate coverage under HFR-094.
+
+
+def _default_home_store_pair() -> tuple[Any, Any]:
+ """A store pair over the ISOLATED HOME's database, as a fresh owner would open it.
+
+ Not ``_store`` / ``_second_owner_store``: those point at ``tmp_path/state``, while a
+ real watch supervisor, the claimed-request executor and the notice drain all reach
+ the default ``paths.get_sqlite_state_path()`` — the same file
+ ``resolve_session_id_target`` and ``persist_agent_message`` read. A test that split
+ those two databases would exercise a shape no install has.
+
+ Each call builds NEW objects with their own engines, which is what makes the
+ second/third owner in (d) and (e) a genuine second reader rather than the same
+ identity map answering twice.
+ """
+
+ from core.scheduled_tasks import TaskExecutionStore as _Requests
+
+ requests = _Requests()
+ sqlite = requests.sqlite_backend
+ assert sqlite is not None, "the default-path store must be SQLite-backed"
+ return sqlite, requests
+
+
+def _delete_agent_session_row(session_id: str) -> None:
+ """Hard-delete one ``agent_sessions`` row, the way #1060's session ceased to exist.
+
+ Not an archive: ``resolve_session_id_target`` refuses an archived session with
+ ``reason="archived"``, and an archived row still gives rung (5) a real scope to
+ persist into. The field case is the harder one — the row is GONE, so the notice's
+ own delivery target is missing too, which is why (d) has to land somewhere else.
+ """
+
+ from sqlalchemy import delete as sa_delete
+
+ from storage.db import get_cached_sqlite_engine
+ from storage.models import agent_sessions
+
+ with get_cached_sqlite_engine().begin() as conn:
+ conn.execute(sa_delete(agent_sessions).where(agent_sessions.c.id == session_id))
+
+
+def _watch_hook_runs(requests) -> list[Any]:
+ return [row for row in requests.list_pending() if row.request_type == "watch"]
+
+
+async def _drive_watch_service(service, watch_id: str, *, until, limit: int = 400) -> None:
+ """Run the REAL supervisor until *until* holds, then stop it.
+
+ The waiter is a real subprocess and the stamps are real guarded writes, so the
+ loop polls rather than counting cycles: the point of using the live service is
+ that the ordering between the cycle stamp, the queued hook and the disable is the
+ thing under test.
+ """
+
+ from tests.test_watches import _start_watch_service
+
+ await _start_watch_service(service)
+ try:
+ for _ in range(limit):
+ if until():
+ break
+ if watch_id not in service._active_tasks:
+ break
+ await asyncio.sleep(0.05)
+ finally:
+ await service.stop()
+
+
+def _execution_service(tmp_path: Path, controller, sqlite, requests):
+ """``_drain_service``, plus the real translator — the bodies here are read copy."""
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ service.controller.config = SimpleNamespace(language="en", platform="slack")
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+ return service
+
+
+def test_a_watch_that_outlives_its_delivery_target_dies_visibly(
+ tmp_path: Path,
+ monkeypatch,
+ capsys,
+) -> None:
+ """HFR-094, subordinate — #1060's four-step terminal case, driven end to end.
+
+ Maintainer acceptance note: PR #1072 comment 5120451508 ("absorb the field
+ evidence"). Field evidence: #1060 comment 5097759698 — a ``once`` watch pinned to
+ a session that ceased to exist, whose follow-up delivery failed and which then
+ stopped with no notification of any kind for 3.5 hours.
+
+ Everything real, deliberately, because the note asks for field realism and each
+ stub would remove one of the four steps: a migrated workbench DB, a real
+ ``agent_sessions`` row that is then hard-deleted, the real ``ManagedWatchService``
+ with a real waiter subprocess, the real claimed-request executor (so
+ ``resolve_session_id_target`` raises for the real reason), the real settlement
+ writer, and the real notice drain.
+
+ The four steps, asserted in the order the failure happens:
+
+ (c) the terminal timestamps agree with each other and survive a fresh read;
+ (a) the row reads FINISHED, never paused, and its health says failing on both the
+ projection and the CLI payload a coding agent actually parses;
+ (b) the run settled ``failed`` naming the delivery failure, the notice carries the
+ structured class ``delivery_target_missing``, and the DEFINITION's
+ ``last_error``/``last_exit_code`` still describe the healthy waiter — the
+ retry sentinel is never blamed;
+ (d) exactly one actionable notice reaches the workspace inbox, through the mandatory
+ workspace rung;
+ (e) a third owner replaying the same row neither duplicates nor erases it.
+ """
+
+ import json
+ import sys as _sys
+ from types import SimpleNamespace
+
+ import core.failure_notices as failure_notices
+ from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.background import NOTICE_PENDING
+ from vibe import cli
+ from vibe.i18n import t as i18n_t
+
+ _no_background_web_push(monkeypatch)
+ _migrated_state_db()
+ _workbench_session("sesd46nxp3cz5", project="proj-lane-b")
+
+ watch_store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
+ sqlite, requests = _default_home_store_pair()
+
+ watch = watch_store.add_watch(
+ name="lane-b-pr5",
+ session_key="",
+ command=[_sys.executable, "-c", "print('event')"],
+ shell_command=None,
+ prefix="The waiter finished.",
+ cwd=None,
+ mode="once",
+ timeout_seconds=30,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ session_id="sesd46nxp3cz5",
+ session_policy="existing",
+ )
+
+ # "That session later ceased to exist." Between creating the watch and its first
+ # event, which is exactly the order the field case ran in.
+ _delete_agent_session_row("sesd46nxp3cz5")
+
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=watch_store,
+ request_store=requests,
+ runtime_store=runtime_store,
+ )
+ asyncio.run(
+ _drive_watch_service(
+ service,
+ watch.id,
+ until=lambda: watch_store.get_watch(watch.id) is not None
+ and not watch_store.get_watch(watch.id).enabled,
+ )
+ )
+
+ saved = watch_store.get_watch(watch.id)
+ assert saved is not None and saved.enabled is False, (
+ f"the premise: a ``once`` watch retires itself after its event: {saved}"
+ )
+ hooks = _watch_hook_runs(requests)
+ assert len(hooks) == 1, f"the retiring cycle owes exactly one completion hook: {hooks}"
+
+ # --- (c) coherent terminal history --------------------------------------
+ assert saved.retired_at, f"a retired watch must record WHEN it retired: {saved}"
+ assert saved.last_finished_at, (
+ f"and a terminal row may not claim a cycle that never finished: {saved}"
+ )
+ assert saved.last_started_at and saved.last_started_at <= saved.last_finished_at, (
+ "#1060's row started a cycle three hours after the watch stopped: "
+ f"{saved.last_started_at} > {saved.last_finished_at}"
+ )
+ assert saved.last_event_at and saved.last_event_at <= saved.last_finished_at, (
+ f"the event it caught cannot postdate the cycle that caught it: {saved}"
+ )
+ reread = ManagedWatchStore().get_watch(watch.id)
+ assert (reread.retired_at, reread.last_finished_at, reread.last_event_at) == (
+ saved.retired_at,
+ saved.last_finished_at,
+ saved.last_event_at,
+ ), "the stamp has to be durable, not an artifact of the writer's in-memory row"
+
+ # --- the delivery that fails, exactly as it did in the field -------------
+ claimed = requests.claim(hooks[0].id)
+ assert claimed is not None
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ executor = _execution_service(tmp_path, controller, sqlite, requests)
+ asyncio.run(executor._execute_claimed_request(claimed))
+
+ # --- (a) not indistinguishable from a pause or a retirement -------------
+ projected = sqlite.get_watch(watch.id)
+ assert projected["lifecycle_state"] == "finished", (
+ "#1060 predicted this row would surface as PAUSED, which is what a user does "
+ f"deliberately: {projected}"
+ )
+ assert not (projected["enabled"] is False and projected.get("retired_at") in (None, "")), (
+ f"``enabled=0`` with no retirement marker is the ambiguous state: {projected}"
+ )
+ assert projected["health"] == "failing", (
+ f"a watch whose only delivery failed is not healthy: {projected}"
+ )
+ # The CLI payload too, not only the store projection: a coding agent driving this
+ # runtime reads ``vibe watch show``, and #1060 was discovered by a human running
+ # ``vibe watch list`` for an unrelated reason. The two must agree.
+ assert cli.cmd_watch_show(watch.id) == 0
+ shown = json.loads(capsys.readouterr().out)["definition"]
+ assert (shown["health"], shown["lifecycle_state"]) == ("failing", "finished"), (
+ f"the CLI payload must carry the same verdict as the projection: {shown}"
+ )
+
+ # --- (b) the recorded cause is the delivery failure ---------------------
+ run = sqlite.get_run(claimed.id)
+ assert run["status"] == "failed", f"the failed delivery must settle the run: {run}"
+ assert "agent session id not found" in str(run.get("error") or ""), (
+ f"and its error must name what actually broke: {run}"
+ )
+ notice = sqlite.owed_failure_notice(claimed.id)
+ assert notice is not None, "a failed run owes a notice"
+ assert notice["interrupt_reason"] == "delivery_target_missing", (
+ "#1060's second ask — 'a cause field distinct from the last exit code'. "
+ f"``delivery_target_missing`` is not ``exited 75``: {notice}"
+ )
+ assert not failure_notices.is_interruption(notice), (
+ "the class must NOT join the interruption lane: that would change the notice's "
+ f"headline and its identity, and defeat streak collapse: {notice}"
+ )
+ assert notice["failure_id"] == claimed.id, (
+ f"so the identity stays the bare run id, not ``interrupt:…``: {notice}"
+ )
+ after = ManagedWatchStore().get_watch(watch.id)
+ assert after.last_error is None and after.last_exit_code == 0, (
+ "the WAITER was healthy — it detected its event and exited 0. #1060's row "
+ f"blamed the retry sentinel instead, which sends the operator upstream: {after}"
+ )
+
+ # --- (d) exactly one actionable notice, in the workspace inbox ----------
+ #
+ # This half consumes the MANDATORY workspace rung (the other half of this round).
+ # Without it the ladder here holds one unusable rung: rung (5) manufactures
+ # ``avibe::project::sesd46nxp3cz5`` for a row that no longer exists, so
+ # ``persist_agent_message`` writes nothing, no receipt appears, and the receipt-only
+ # ack source correctly refuses the synthetic send id. Under round 12's
+ # only-when-nothing-resolved gate the fallback never fired (``rungs`` is not empty),
+ # all six attempts burned, and the notice dead-lettered with nothing written
+ # anywhere. That silent dead letter is #1060's 3.5 hours, reached through the notice
+ # layer instead of the definition row.
+ #
+ # The loop below is deliberately written to the WEAKER claim — drain until the notice
+ # leaves ``pending``, up to the full attempt budget — so it holds under both the
+ # retired final-attempt design and the round-14 rung, and it is not the assertion.
+ # Which attempt actually delivers is pinned by
+ # ``test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox``
+ # (the first one); what THIS case owns is that the real four-step field failure ends
+ # with one readable card rather than silence.
+ #
+ # AT LEAST ONCE, not exactly once: the contract is that no scripted run of this
+ # ladder may produce two messages, which is what "exactly one" below asserts. The
+ # residual duplicate window (a claimant that dies after the transport accepted) is
+ # documented on ``CLAIM_LEASE_SECONDS`` and is out of this case's reach.
+ sqlite_b, requests_b = _default_home_store_pair()
+ drain = _execution_service(tmp_path, _live_turn_dispatcher()[0], sqlite_b, requests_b)
+ for _ in range(failure_notices.MAX_ATTEMPTS + 2):
+ state = str((sqlite_b.owed_failure_notice(claimed.id) or {}).get("state") or "")
+ if state not in {"", NOTICE_PENDING}:
+ break
+ # Rewind the backoff rather than sleeping through it, as every other retry
+ # test in this file does.
+ sqlite_b.update_owed_failure_notice(claimed.id, next_attempt_at=None)
+ asyncio.run(drain._drain_failure_notices())
+
+ rows = _persisted_messages()
+ assert [(row["platform"], row["type"], row["session_id"]) for row in rows] == [
+ ("avibe", "notify", WORKSPACE_NOTICE_SESSION_ID)
+ ], f"exactly one actionable notice, in the workspace inbox: {rows}"
+ body = str(rows[0]["content_text"])
+ assert "lane-b-pr5" in body, f"the notice must name the watch that died: {body!r}"
+ assert i18n_t("harness.notice.class.deliveryTargetMissing", "en") in body, (
+ f"and name the class, not only the raw error line: {body!r}"
+ )
+ assert i18n_t("harness.notice.watchRetired", "en") in body, (
+ f"a retired watch's copy has to say it finished: {body!r}"
+ )
+ assert i18n_t("harness.notice.watchPaused", "en").split("{")[0].strip() not in body, (
+ "and must NOT offer ``vibe watch resume`` for a watch that retired — that is "
+ f"the same contradiction (a) closes, restated as copy: {body!r}"
+ )
+ settled = sqlite_b.owed_failure_notice(claimed.id)
+ assert settled["state"] == NOTICE_SENT, f"the notice must be marked delivered: {settled}"
+
+ # --- (e) a replay may neither duplicate nor erase it -------------------
+ sqlite_c, requests_c = _default_home_store_pair()
+ replay = _execution_service(tmp_path, _live_turn_dispatcher()[0], sqlite_c, requests_c)
+ sqlite_c.update_owed_failure_notice(claimed.id, next_attempt_at=None)
+ asyncio.run(replay._drain_failure_notices())
+ asyncio.run(replay._drain_failure_notices())
+
+ assert _persisted_messages() == rows, (
+ "a restart must not re-send a notice the user already has, and must not "
+ "rewrite the row that proves they have it"
+ )
+ replayed = sqlite_c.owed_failure_notice(claimed.id)
+ assert replayed["state"] == NOTICE_SENT
+ assert replayed["attempts"] == settled["attempts"], (
+ f"a replay consumes no attempt against a settled notice: {replayed}"
+ )
+ assert replayed["interrupt_reason"] == "delivery_target_missing", (
+ f"and the structured cause survives the replay: {replayed}"
+ )
+
+
+def test_a_forever_watch_repeating_the_field_failure_notifies_once(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-094, subordinate — #1060's REPETITION pattern, which is the other half.
+
+ Maintainer acceptance note: PR #1072 comment 5120451508. Field evidence: #1060
+ comment 5097759698, whose log is three failures four minutes apart, not one.
+
+ The ``once`` case above proves a terminal watch is visible. A ``forever`` watch is
+ where the two lanes of #1060's report pull against each other, and both directions
+ have to hold at the same time:
+
+ * the retry sentinel (exit 75, "nothing new yet") must NOT disable the watch or
+ look like a failure — it is the configured healthy signal;
+ * the real delivery failures repeat on every event, so they must collapse to ONE
+ canonical notice rather than one message per event — the streak lane, which is
+ only reachable because ``delivery_target_missing`` stays OUT of
+ ``RUN_INTERRUPTION_REASONS``;
+ * and the definition's ``last_error`` legitimately holds the sentinel string for
+ its last cycle, so the notice must not present that as the failure's cause.
+ This is #1060's first complaint in its exact shape: the sentinel is a true fact
+ about the waiter and a false explanation of the death.
+
+ The waiter is a real subprocess whose exit code walks a marker file: 75 first,
+ then 0 twice (two events, two follow-up deliveries, two failures), then 75 again
+ so the LAST recorded cycle is the sentinel — the state #1060's row was actually
+ read in.
+ """
+
+ import sys as _sys
+ from types import SimpleNamespace
+
+ import core.failure_notices as failure_notices
+ from core.watches import ManagedWatchService, ManagedWatchStore, WatchRuntimeStateStore
+
+ _no_background_web_push(monkeypatch)
+ _migrated_state_db()
+ _workbench_session("sesGoneForever", project="proj-forever")
+
+ marker = tmp_path / "waiter-cycles.txt"
+ waiter = tmp_path / "waiter.py"
+ waiter.write_text(
+ "import pathlib, sys\n"
+ f"marker = pathlib.Path(r{str(marker)!r})\n"
+ "n = (int(marker.read_text() or 0) if marker.exists() else 0) + 1\n"
+ "marker.write_text(str(n))\n"
+ "if n in (2, 3):\n"
+ " print('event %d' % n)\n"
+ " sys.exit(0)\n"
+ "sys.exit(75)\n",
+ encoding="utf-8",
+ )
+
+ watch_store = ManagedWatchStore()
+ runtime_store = WatchRuntimeStateStore()
+ sqlite, requests = _default_home_store_pair()
+
+ watch = watch_store.add_watch(
+ name="lane-b-forever",
+ session_key="",
+ command=[_sys.executable, str(waiter)],
+ shell_command=None,
+ prefix="The waiter finished.",
+ cwd=None,
+ mode="forever",
+ timeout_seconds=30,
+ lifetime_timeout_seconds=0,
+ retry_exit_codes=[75],
+ retry_delay_seconds=0,
+ post_to=None,
+ deliver_key=None,
+ session_id="sesGoneForever",
+ session_policy="existing",
+ )
+ _delete_agent_session_row("sesGoneForever")
+
+ service = ManagedWatchService(
+ controller=SimpleNamespace(),
+ store=watch_store,
+ request_store=requests,
+ runtime_store=runtime_store,
+ )
+
+ def _ready() -> bool:
+ row = watch_store.get_watch(watch.id)
+ return (
+ len(_watch_hook_runs(requests)) >= 2
+ and row is not None
+ and row.last_exit_code == 75
+ )
+
+ asyncio.run(_drive_watch_service(service, watch.id, until=_ready, limit=800))
+
+ hooks = sorted(_watch_hook_runs(requests), key=lambda row: (row.created_at, row.id))
+ assert len(hooks) == 2, f"two events must queue two follow-up deliveries: {hooks}"
+
+ saved = watch_store.get_watch(watch.id)
+ assert saved.enabled is True, (
+ "a configured retry exit code is the HEALTHY 'nothing new yet' signal; it may "
+ f"never retire the watch: {saved}"
+ )
+ assert saved.retired_at is None and saved.last_finished_at is None, (
+ f"nor stamp a retirement on a watch that is still running: {saved}"
+ )
+ sentinel = "watch command exited with status 75"
+ assert saved.last_error == sentinel and saved.last_exit_code == 75, (
+ f"the premise for the last assertion below — the last cycle was a retry: {saved}"
+ )
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ executor = _execution_service(tmp_path, controller, sqlite, requests)
+ for hook in hooks:
+ claimed = requests.claim(hook.id)
+ assert claimed is not None
+ asyncio.run(executor._execute_claimed_request(claimed))
+
+ for hook in hooks:
+ run = sqlite.get_run(hook.id)
+ assert run["status"] == "failed", f"both deliveries fail the same way: {run}"
+ assert "agent session id not found" in str(run.get("error") or "")
+
+ projected = sqlite.get_watch(watch.id)
+ assert projected["lifecycle_state"] == "waiting", (
+ f"the watch is still armed, so it is not finished: {projected}"
+ )
+ assert projected["health"] == "failing", (
+ "…and still failing: a repeating delivery failure is exactly the history the "
+ f"health badge exists to report: {projected}"
+ )
+
+ # ONE canonical notice for the streak, keyed to the FIRST failed run.
+ first = sqlite.owed_failure_notice(hooks[0].id)
+ second = sqlite.owed_failure_notice(hooks[1].id)
+ for notice in (first, second):
+ assert notice["interrupt_reason"] == "delivery_target_missing", notice
+ assert not failure_notices.is_interruption(notice), (
+ "in the interruption lane each run would notify separately — one message "
+ f"per event, which is the spam the streak exists to prevent: {notice}"
+ )
+ assert first["failure_id"] == hooks[0].id and second["failure_id"] == hooks[1].id, (
+ "the per-fire lane keeps the bare run id as its identity, which is what lets "
+ "the live path's dedup see a notification it already delivered"
+ )
+ decision = failure_notices.decide(
+ run_id=hooks[1].id,
+ definition_id=watch.id,
+ notice=second,
+ streak_facts=sqlite.failure_streak_decision(watch.id, hooks[1].id),
+ earlier_unsettled=None,
+ )
+ assert decision.action in {failure_notices.ACTION_DEFER, failure_notices.ACTION_SKIP}, (
+ f"the second failure of one streak must not notify on its own: {decision}"
+ )
+ canonical = failure_notices.decide(
+ run_id=hooks[0].id,
+ definition_id=watch.id,
+ notice=first,
+ streak_facts=sqlite.failure_streak_decision(watch.id, hooks[0].id),
+ earlier_unsettled=None,
+ )
+ assert canonical.action == failure_notices.ACTION_DELIVER, (
+ f"and the canonical one is the earliest failed run of the streak: {canonical}"
+ )
+
+ body = executor._failure_notice_body(sqlite.get_run(hooks[0].id), first)
+ assert sentinel not in body, (
+ "the definition's ``last_error`` is a true fact about the waiter's LAST cycle "
+ "and a false explanation of this failure. #1060: 'anyone debugging this starts "
+ f"by investigating a healthy waiter.': {body!r}"
+ )
+ assert "agent session id not found" in body, f"the real cause has to be there: {body!r}"
+
+
+# --- the reserved session is not a run target either -------------------------
+#
+# Round-16 review thread 3678900318, and the same class as the two cases above one
+# session row over: a definition whose ``--session-id`` names a row that CANNOT take a
+# turn must fail VISIBLY instead of dispatching one.
+#
+# The previous round closed the composer (``POST /api/sessions/<id>/messages``). That is
+# the door a human finds; the backend entry points come through
+# ``resolve_session_id_target`` instead, and it refused only ARCHIVED rows while the
+# reserved workspace-notifications row is deliberately kept ACTIVE. The two tests below
+# consume the resolver's new ``reason="reserved"`` from the two lanes that dispatch
+# differently, because their handlers are different code:
+#
+# * ``agent_run`` — the ``vibe agent run --session-id`` lane named in the finding —
+# lands in ``_execute_claimed_request``'s ``UnresolvableSessionTarget`` handler;
+# * ``task_run`` — a definition pinned with ``vibe task add --session-id`` — is caught
+# one level lower by ``_execute_task``, which runs the BINDING RECOVERY. That lane is
+# the one that could do real damage on a new reason (a rebind would silently
+# re-point a user's definition), so it is pinned rather than assumed.
+#
+# No new scenario id: both are subordinate coverage under HFR-094, like the #1060 cases
+# above them.
+
+
+def _reserved_notice_session() -> str:
+ """The reserved row in the DEFAULT-HOME workbench DB, with one notice in it.
+
+ The notice matters: it makes the transcript NON-EMPTY, so "no turn was dispatched"
+ is asserted as "the transcript is unchanged and still notices-only" rather than as
+ "there is nothing there", which an empty table would satisfy for the wrong reason.
+ """
+
+ from storage import messages_service
+ from storage.agent_session_rows import (
+ WORKSPACE_NOTICE_SESSION_ID,
+ resolve_workspace_notice_session,
+ )
+ from storage.db import get_cached_sqlite_engine
+
+ with get_cached_sqlite_engine().begin() as conn:
+ session_id = resolve_workspace_notice_session(conn, title="Workspace notifications")
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type="notify",
+ text="Scheduled task 'nightly' failed: backend exploded",
+ )
+ assert session_id == WORKSPACE_NOTICE_SESSION_ID
+ return session_id
+
+
+def _session_transcript(session_id: str) -> list[tuple[str, str]]:
+ """``(author, type)`` for every persisted row in one session, in order."""
+
+ return [
+ (str(row["author"]), str(row["type"]))
+ for row in _persisted_messages()
+ if str(row["session_id"] or "") == session_id
+ ]
+
+
+def test_an_agent_run_pinned_to_the_reserved_session_dispatches_no_turn(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-094, subordinate — the CLI lane the composer guard could not reach.
+
+ ``vibe agent run --session-id ses-workspace-notices --agent <enabled> --message …``
+ resolves the pin through ``resolve_session_id_target`` and enqueues an ``agent_run``.
+ Before the resolver owned the ownership check, that resolve SUCCEEDED — the row is
+ active, so only the archived branch could have stopped it — and the run went on to
+ dispatch a real turn into a machine-owned row with an empty ``agent_backend``,
+ mixing conversation into the failure-notice transcript.
+
+ Everything real: the migrated workbench DB the resolver actually reads, the real
+ request store, the real claimed-request executor and the real settlement writer.
+
+ Three outcomes:
+
+ * the run settles ``failed`` NAMING the reserved session — the visible result, and
+ the reason a run failure is the right disposal rather than a silent skip;
+ * the notice is NOT classified ``delivery_target_missing``. The row exists and is
+ healthy; this is a configuration error, and that label would send the reader
+ hunting for a session sitting in their own inbox;
+ * the reserved transcript is UNCHANGED and still notices-only — no ``user`` turn,
+ no assistant reply.
+ """
+
+ _no_background_web_push(monkeypatch)
+ _migrated_state_db()
+ reserved = _reserved_notice_session()
+ before = _session_transcript(reserved)
+ assert before == [("agent", "notify")], f"the premise: one notice, no turns: {before}"
+
+ sqlite, requests = _default_home_store_pair()
+ queued = requests.enqueue_agent_run(
+ message="summarise today's failures",
+ session_id=reserved,
+ session_policy="existing",
+ source_kind="cli",
+ source_actor="cli",
+ )
+ claimed = requests.claim(queued.id)
+ assert claimed is not None
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ executor = _execution_service(tmp_path, controller, sqlite, requests)
+ asyncio.run(executor._execute_claimed_request(claimed))
+
+ run = sqlite.get_run(claimed.id)
+ assert run["status"] == "failed", f"a turn that may not be dispatched is a failure: {run}"
+ error = str(run.get("error") or "")
+ assert reserved in error and "reserved" in error, (
+ f"and the recorded cause has to name the reserved session: {error!r}"
+ )
+
+ notice = sqlite.owed_failure_notice(claimed.id)
+ assert notice is not None, "a failed run owes a notice"
+ assert notice["interrupt_reason"] != "delivery_target_missing", (
+ "``delivery_target_missing`` means the destination CEASED TO EXIST. This one is "
+ f"alive and in the inbox — a wrong class is worse than no class: {notice}"
+ )
+
+ assert _session_transcript(reserved) == before, (
+ "NO turn may be dispatched into the runtime's own row: its transcript has to be "
+ f"byte-identical to the notices it held before the run: {_session_transcript(reserved)}"
+ )
+ assert requests.list_pending() == [], (
+ "and the refused run leaves NOTHING queued — not a requeue, not a retry. A "
+ "settled-failed row that is still pending would fire again on the next drain, "
+ f"which is the same hole one tick later: {requests.list_pending()}"
+ )
+
+
+def test_a_task_pinned_to_the_reserved_session_is_paused_never_rebound(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-094, subordinate — the binding-recovery lane must not "repair" this one.
+
+ ``task_run`` does not reach ``_execute_claimed_request``'s handler: ``_execute_task``
+ catches ``UnresolvableSessionTarget`` first and runs ``_recover_pinned_session_binding``,
+ which for some definitions RESERVES A REPLACEMENT SESSION and re-points the
+ definition at it. Auditing the new reason meant proving that cannot happen here,
+ because a silent rebind would answer "you pointed this at a row that takes no turns"
+ by pointing it somewhere it does — and then dispatching the turn.
+
+ It cannot, and the reason is structural rather than a reason check: only
+ ``create_once`` is ever rebound, and a ``create_once`` definition reserved its own
+ session from ``SESSION_ID_ALPHABET``, which contains no ``-`` and therefore can
+ never mint ``ses-workspace-notices``. Reaching the reserved id at all takes a
+ user-pinned ``existing`` binding, and ``existing`` is never rebound. Its first
+ classified failure is visible and the third consecutive classified failure pauses
+ it; transient failures carry no such code and never advance this policy.
+
+ Pinned here so the structural argument has a test behind it: still enabled for the
+ first two failures, paused on the third, no replacement session, and no turn handed
+ to the message handler.
+ """
+
+ from core.scheduled_tasks import ScheduledTaskStore
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ from tests.test_scheduled_tasks import _binding_env, _binding_service
+
+ _no_background_web_push(monkeypatch)
+ _binding_env(tmp_path, monkeypatch)
+ _migrated_state_db()
+ reserved = _reserved_notice_session()
+ before = _session_transcript(reserved)
+ assert before == [("agent", "notify")], f"the premise: one notice, no turns: {before}"
+
+ sqlite, requests = _store(tmp_path)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ store._sqlite = sqlite
+ store.load()
+ task = store.add_task(
+ name="daily digest",
+ session_key="",
+ session_id=reserved,
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ )
+
+ dispatched: list = []
+ service = _binding_service(tmp_path, store, dispatched)
+ service.request_store = requests
+
+ claimed_ids: list[str] = []
+ for attempt in range(1, 4):
+ current = store.get_task(task.id)
+ assert current is not None
+ queued = requests.enqueue_task_run(task.id, source_kind="scheduler", task=current)
+ claimed = requests.claim(queued.id)
+ assert claimed is not None
+ claimed_ids.append(claimed.id)
+ asyncio.run(service._execute_claimed_request(claimed))
+ saved = store.get_task(task.id)
+ assert saved is not None
+ assert saved.enabled is (attempt < 3)
+
+ saved = store.get_task(task.id)
+ assert saved is not None
+ assert saved.enabled is False, (
+ f"a definition that can never fire again must not keep firing: {saved}"
+ )
+ assert saved.session_id == WORKSPACE_NOTICE_SESSION_ID, (
+ "and the user's own pin must still be there to re-point — a rebind here would "
+ f"silently answer a configuration error with a different session: {saved}"
+ )
+ assert dispatched == [], (
+ f"no prompt may reach the message handler on this fire: {dispatched}"
+ )
+
+ run = sqlite.get_run(claimed_ids[-1])
+ assert run["status"] == "failed", f"the fire that could not run is a failure: {run}"
+ assert "paused" in str(run.get("error") or ""), (
+ f"and its recorded detail is the recovery's own verdict: {run}"
+ )
+ assert reserved in str(run.get("error") or ""), (
+ f"which still names the session the user pinned: {run}"
+ )
+ assert {
+ (sqlite.get_run(run_id).get("metadata") or {}).get("failure_code")
+ for run_id in claimed_ids
+ } == {"unresolvable_target"}
+ assert sqlite.owed_failure_notice(claimed_ids[0]) is not None, (
+ "the first classified failure must be visible before the third failure pauses"
+ )
+ assert _session_transcript(reserved) == before, (
+ f"the runtime's own row stays notices-only: {_session_transcript(reserved)}"
+ )
+
+
[email protected]("language", ["en", "zh"])
+def test_a_disabled_watchs_notice_copy_distinguishes_retired_from_paused(
+ tmp_path: Path,
+ language: str,
+) -> None:
+ """The copy half of outcome (a), asserted on the rendered sentence in both languages.
+
+ Maintainer acceptance note: PR #1072 comment 5120451508. Field evidence: #1060
+ comment 5097759698 — "``enabled=0`` with ``retired_at=null`` reads as *paused*, not
+ *broken*… ``enabled=0`` is carrying three meanings."
+
+ The body used to render the resume copy for EVERY disabled watch. For a retired one
+ that is a self-contradiction the round otherwise closes: the lifecycle projection
+ calls the row FINISHED while its notice offers ``vibe watch resume``, an action that
+ would arm a watch nobody paused. So the two states get two sentences, chosen from
+ the same ``retired_at`` column the projection's ``ended`` predicate reads.
+
+ Through the REAL translator, because the defect is in copy: a ``_t`` that echoes
+ keys would report which branch ran and nothing about what the user reads. And in
+ BOTH languages, because ``harness.notice.watchPaused`` was translated and its
+ replacement has to be too — a missing zh string degrades to English mid-sentence.
+ """
+
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ service = _drain_service(tmp_path, SimpleNamespace(), sqlite, requests)
+ service.controller.config = SimpleNamespace(language=language, platform="slack")
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+
+ retired_copy = i18n_t("harness.notice.watchRetired", language)
+ # The command, not the whole sentence: that is the part a user could act on, and
+ # the part that must not appear for a watch nobody paused.
+ resume_command = "vibe watch resume"
+
+ def _body(definition_id: str, **watch_fields) -> str:
+ _watch(sqlite, definition_id, enabled=False, **watch_fields)
+ _settled_run(
+ sqlite,
+ definition_id,
+ f"run-{definition_id}",
+ status="failed",
+ at="2026-07-27T03:00:00+00:00",
+ )
+ return service._failure_notice_body(
+ sqlite.get_run(f"run-{definition_id}"),
+ {"failure_id": f"run-{definition_id}", "interrupt_reason": None},
+ )
+
+ retired = _body("watch-retired", retired_at="2026-07-27T03:00:00+00:00", mode="once")
+ assert retired_copy in retired, f"a retired watch must say it finished: {retired!r}"
+ assert resume_command not in retired, (
+ "and must not offer to resume something that was never paused — the copy has to "
+ f"agree with the FINISHED lifecycle state: {retired!r}"
+ )
+
+ paused = _body("watch-paused", mode="forever")
+ assert resume_command in paused, (
+ f"a genuinely paused watch still needs its resume affordance: {paused!r}"
+ )
+ assert retired_copy not in paused, (
+ f"and must not be told it has finished when it has not: {paused!r}"
+ )
+
+
+# --- round 12: the consuming-path pin for the adapter bookkeeping guard -------
+#
+# GREEN FROM BIRTH. The fix these three cases consume landed as 0ebf4c55 in this
+# same round (``modules/im/slack.py`` / ``modules/im/feishu.py``, matching the guard
+# ``modules/im/discord.py`` already had); the adapter-level and dispatcher-level
+# coverage landed with it. What was missing was the NOTICE-level consumer: proof
+# that the drain's ack/retry decision comes out right for an adapter whose transport
+# succeeded and whose post-send bookkeeping blew up.
+#
+# Red-by-mutation, since there is no head at which the production code is wrong any
+# more: ``_PreGuardSlackBot`` below reintroduces the pre-0ebf4c55 shape — the same
+# transport call, the same bookkeeping call, unguarded — and is asserted to produce
+# the old outcome. That is the red half, run in the same file as the green one.
+
+
+def _threaded_slack_notice(sqlite, requests, definition_id: str) -> str:
+ """One owed notice whose only rung is a THREADED Slack channel.
+
+ The thread segment is load-bearing: every adapter's post-send bookkeeping is
+ ``if settings_manager and (thread_id or reply_to): sessions.mark_thread_active(...)``,
+ so an unthreaded target never reaches the line under test.
+ """
+
+ from storage.background import NOTICE_PENDING
+
+ _task(
+ sqlite,
+ definition_id,
+ name="daily report",
+ deliver_key="slack::channel::C123::thread::1710000000.000100",
+ )
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id=definition_id)
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_PENDING
+ return run.id
+
+
+class _RaisingSessions:
+ """``sessions.mark_thread_active`` as a locked SQLite / dead session store."""
+
+ def __init__(self) -> None:
+ self.calls: list[tuple] = []
+
+ def mark_thread_active(self, *args) -> None:
+ self.calls.append(args)
+ raise RuntimeError("session store unavailable")
+
+
+def _slack_bot_with_broken_bookkeeping(*, transport_fails: bool = False):
+ """A REAL ``SlackBot``, transport stubbed, bookkeeping guaranteed to raise.
+
+ Real adapter and not a shaped stub, because the subject IS the adapter's own
+ ordering: transport, bookkeeping, return. Only the HTTP call is replaced.
+ """
+
+ from config.v2_config import SlackConfig
+ from modules.im.slack import SlackBot
+
+ bot = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ bot._ensure_clients = lambda: None # type: ignore[method-assign]
+ bot.settings_manager = object()
+ bot.sessions = _RaisingSessions()
+ accepted: list[str] = []
+
+ async def _prepared(context, text, parse_mode=None, reply_to=None):
+ if transport_fails:
+ # BEFORE the point of no return: the platform never took the payload.
+ raise RuntimeError("slack rejected the payload")
+ accepted.append(text)
+ return {"ts": f"ts-{len(accepted)}"}
+
+ bot._send_prepared_text_message = _prepared # type: ignore[method-assign]
+ return bot, accepted
+
+
+class _PreGuardSlackBot:
+ """The pre-0ebf4c55 send path, reproduced to make the mutation red.
+
+ Delegates to a real ``SlackBot`` for the transport and then runs the bookkeeping
+ call UNGUARDED, exactly as ``send_message`` did before the fix — so the delivered
+ ``ts`` is destroyed by the exception on its way out.
+ """
+
+ def __init__(self, inner) -> None:
+ self._inner = inner
+ self.accepted: list[str] = []
+
+ def should_use_thread_for_reply(self) -> bool:
+ return self._inner.should_use_thread_for_reply()
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ response = await self._inner._send_prepared_text_message(
+ context, text, parse_mode=parse_mode, reply_to=reply_to
+ )
+ self.accepted.append(text)
+ thread_ts = context.thread_id or reply_to
+ if self._inner.settings_manager and thread_ts:
+ self._inner.sessions.mark_thread_active(context.user_id, context.channel_id, thread_ts)
+ return response["ts"]
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+
+def test_a_notice_acks_when_the_adapters_post_send_bookkeeping_raises(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """HFR-079, subordinate — delivered-but-unbookkept must ack, not resend.
+
+ The consuming end of finding B, through the real drain: claim, ladder walk, replay
+ emitter, dispatcher, and a real ``SlackBot`` whose transport accepted the message
+ and whose ``sessions.mark_thread_active`` then raised. The user HAS the notice, so
+ the only correct outcome is one send and an acknowledged row.
+
+ Green from birth — see the section header. The red half is
+ ``test_the_pre_guard_adapter_shape_resends_an_already_delivered_notice`` below,
+ which runs the pre-fix adapter body against this same wiring.
+
+ Feishu's threaded reply paths have the identical shape and the identical guard;
+ they are pinned at adapter level in ``tests/test_im_post_send_bookkeeping.py``
+ rather than duplicated here, because the notice-level consumer is
+ platform-agnostic once the adapter returns its id.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_DELIVERY_ONLY, ACK_EVIDENCE_RECEIPT
+
+ _migrated_state_db()
+ sqlite, requests = _store(tmp_path)
+ run_id = _threaded_slack_notice(sqlite, requests, "task-bookkeeping")
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ bot, accepted = _slack_bot_with_broken_bookkeeping()
+ controller.im_client = bot
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert len(accepted) == 1, f"exactly one send reached the transport: {accepted}"
+ assert bot.sessions.calls, "the bookkeeping call must actually have been attempted"
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_SENT, (
+ f"a delivered message whose bookkeeping failed is still delivered: {notice}"
+ )
+ assert notice["ack_evidence"] in {ACK_EVIDENCE_RECEIPT, ACK_EVIDENCE_DELIVERY_ONLY}
+ assert notice["attempts"] == 1
+
+ # And the retry that a lost id would have caused does not happen.
+ asyncio.run(service._drain_failure_notices())
+ assert len(accepted) == 1, f"an acknowledged notice must never be resent: {accepted}"
+
+
+def test_the_pre_guard_adapter_shape_resends_an_already_delivered_notice(
+ tmp_path: Path,
+) -> None:
+ """The red half of the pin: the pre-0ebf4c55 body, same wiring, old outcome.
+
+ With the bookkeeping call unguarded the exception replaces the returned ``ts``, so
+ the drain sees a rung that raised. Both consequences are asserted, because either
+ alone would understate the defect: the notice is NOT acknowledged (it retries and
+ will eventually dead-letter a message the user already has), and — now that a
+ raising rung continues the walk rather than ending it — the SAME body is pushed
+ again onto the next rung. That second half is why finding B's adapter fix and
+ finding G's ladder fix ship in one round.
+
+ THE MANDATORY WORKSPACE RUNG IS SUPPRESSED, for isolation. Since the round-14 gate
+ every ladder ends with it, and here it would DELIVER — the two Slack rungs raise, the
+ walk reaches the workspace rung, ``persist_agent_message`` writes a real row and the
+ notice acks on that receipt. Which is the gate's intent working exactly as designed,
+ and it would make this test say "the notice was rescued" instead of "the adapter
+ destroyed a delivered id". The subject here is the adapter's ordering, so the rescue
+ is switched off the same way ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``
+ switches it off for its pass 1. What the rescue itself buys is pinned by
+ ``test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox``.
+ """
+
+ _migrated_state_db()
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-preguard",
+ name="daily report",
+ deliver_key="slack::channel::C123::thread::1710000000.000100",
+ metadata={
+ "created_by": {"caller": {"session_key": "slack::channel::C999::thread::1710000000.000200"}}
+ },
+ )
+ run = requests.enqueue_task_run("task-preguard")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-preguard")
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ inner, _accepted = _slack_bot_with_broken_bookkeeping()
+ bot = _PreGuardSlackBot(inner)
+ controller.im_client = bot
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ service._workspace_notice_session_id = lambda: None
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert len(bot.accepted) == 2, (
+ "the pre-guard shape destroys the delivered id, so the walk pushes the same "
+ f"notice onto the next rung: {bot.accepted}"
+ )
+ notice = sqlite.owed_failure_notice(run.id)
+ assert notice["state"] == "pending", (
+ f"and the row is left owing a notice the user already received: {notice}"
+ )
+ assert notice["attempts"] == 1
+ assert "session store unavailable" in (notice["error"] or "")
+
+
+def test_a_real_send_failure_is_still_undelivered(tmp_path: Path) -> None:
+ """The control, so the guard above cannot be read as "ack on anything".
+
+ The bookkeeping guard only ever runs AFTER the transport returned. A transport
+ that raises BEFORE it returns an id never delivered, and must still leave the
+ notice unacknowledged with its retry armed — otherwise the guard would have
+ converted every failed send into a silent success, which is the failure mode the
+ whole durable notice exists to prevent.
+ """
+
+ _migrated_state_db()
+ sqlite, requests = _store(tmp_path)
+ run_id = _threaded_slack_notice(sqlite, requests, "task-send-failure")
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ bot, accepted = _slack_bot_with_broken_bookkeeping(transport_fails=True)
+ controller.im_client = bot
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert accepted == [], "nothing reached the platform"
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice["state"] == "pending", f"an undelivered notice stays owed: {notice}"
+ assert notice["ack_evidence"] in {None, ""}, f"and acks on nothing: {notice}"
+ assert notice["attempts"] == 1, "one attempt consumed by the claim"
+ assert str(notice["next_attempt_at"] or ""), "with a retry armed"
+
+
+# =============================================================================
+# --- round 14: the MANDATORY workspace rung, on every walk -------------------
+# =============================================================================
+#
+# Subordinate to HFR-079's ladder family (``test_a_workbench_addressed_notice_lands_as_a_durable_inbox_row``,
+# ``test_an_avibe_rung_does_not_ack_on_a_synthetic_send_id``,
+# ``test_a_caller_less_cli_definition_still_delivers_its_failure_notice``). NO new
+# scenario id: the subject is the same ladder those three already own.
+#
+# WHAT ROUND 12 LEFT OPEN, and it is the #1060 field evidence rather than a
+# hypothetical (maintainer note 5120451508). Round 12 gave the ladder a last rung —
+# the reserved workspace-notifications session — but gated it on ``if not rungs``,
+# "ONLY WHEN NOTHING ELSE RESOLVED", to keep a definition that already has an address
+# from collecting a duplicate card. That gate answers the duplicate question and
+# leaves the ORTHOGONAL one open: a ladder can be non-empty and yet contain no rung
+# that can deliver anything. A watch or task bound to a HARD-DELETED session is
+# exactly that shape — rung (5) is manufactured unconditionally from the run's session
+# id and nothing checks that the row it names still exists — so every attempt sends to
+# a candidate that resolves to nothing, no rung can persist a receipt, and the notice
+# burns all six attempts into a silent dead letter. That silence is the 3.5 hours in
+# #1060.
+#
+# ROUND 13 CLOSED THAT WITH A FINAL-ATTEMPT FALLBACK (commit ``ce695b42``): appended
+# last, but only on attempt ``MAX_ATTEMPTS``, on the argument that an always-present
+# workspace rung converts a TRANSIENT preferred-rung failure into a permanently
+# workspace-routed notice. THE ROUND-14 GATE OVERRULED THAT (review comment
+# 5121007240): "Workspace fallback is mandatory rung 5. Append one distinct
+# workspace-notifications target after every person/context target, even when earlier
+# candidates exist but are stale, unavailable, or fail delivery. It cannot be
+# conditional on rungs being empty." The transient-misroute trade is accepted
+# explicitly by that ruling ("…or fail delivery").
+#
+# THE RULE THE TESTS BELOW PIN, then, is three claims and not one:
+#
+# * UNCONDITIONAL — the rung is on every ladder on every attempt, so a walk whose
+# preferred rungs all fail delivers on THAT walk rather than on the sixth
+# (``test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox``);
+# * LAST — a healthy preferred rung still wins every walk and produces no workspace
+# card at all, which is what keeps the unconditional rung from being noise
+# (``test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox``);
+# * ONCE — the archived-session reroute names the same reserved id, so the two
+# mechanisms collapse into a single rung
+# (``test_an_archived_session_ladder_holds_exactly_one_workspace_rung``).
+
+
+def _dead_binding_notice(sqlite, requests, definition_id: str, *, session_id: str = "sesGone"):
+ """One owed notice whose ONLY preferred rung names a session row that does not exist.
+
+ No ``deliver_key`` (rung 1 empty), no ``created_by`` provenance (rungs 3 and 4
+ empty), and a ``session_id`` whose ``agent_sessions`` row was never written — so
+ ``resolve_session_id_target`` refuses it (rung 2 empty) while rung (5) is still
+ MANUFACTURED from the same id. A non-empty ladder with zero DELIVERABLE preferred
+ rungs: the precondition round 12's ``if not rungs`` fallback could not see.
+ """
+
+ from storage.background import NOTICE_PENDING
+
+ _task(sqlite, definition_id, name="nightly report", session_id=session_id)
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id=definition_id)
+ assert sqlite.owed_failure_notice(run.id)["state"] == NOTICE_PENDING
+ return run.id
+
+
+def _rewind_notice_backoff(sqlite, run_id: str) -> None:
+ """Let the armed backoff elapse without sleeping (the rewind the retry tests use)."""
+
+ sqlite.update_owed_failure_notice(run_id, next_attempt_at=None)
+ assert [row["id"] for row in sqlite.list_owed_failure_notices(limit=10)] == [run_id], (
+ "the notice has to still be OWED for the next attempt to be able to run"
+ )
+
+
+def _avibe_sends(controller) -> list[str]:
+ return [channel for channel, _thread, _text in controller.im_client.sent]
+
+
+def test_a_walk_whose_preferred_rungs_all_fail_lands_in_the_workspace_inbox(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Subordinate to HFR-079 — a non-empty ladder of undeliverable rungs must not
+ dead-letter in silence, and must not wait six attempts to say so.
+
+ THE DEFECT, traced end to end (maintainer note 5120451508, #1060's field
+ evidence). The definition is bound to a session whose row is gone, so the preferred
+ ladder is ``["avibe::project::sesGone"]`` — non-empty, because rung (5) is built from
+ the run's session id and "nothing here checks that the row it names still exists".
+ The rung sends (``AvibeBot.send_message`` mints a synthetic id unconditionally),
+ persists nothing (``persist_agent_message`` returns before writing with neither a
+ scope nor a session row), and is therefore refused by the workbench class's
+ receipt-only ack source. Correct so far, and correctly retryable — but under round
+ 12's ``if not rungs`` gate the ladder contained nothing else, so all six attempts
+ refused and the sixth dead-lettered a notice nobody will ever read.
+
+ THE ATTEMPT THIS LANDS ON IS THE POINT, and it is attempt ONE. Round 13 appended the
+ workspace rung on the final attempt only; the round-14 gate (review comment
+ 5121007240) made it unconditional — "it cannot be conditional on rungs being empty"
+ — so the FIRST walk whose preferred rungs all fail delivers and acks. One drain
+ pass, ``attempts == 1``, one durable row. The five backoff attempts an undeliverable
+ ladder used to burn in silence are gone, not merely made visible at the end.
+
+ THE PREFERRED RUNG IS STILL WALKED FIRST, which is the ordering half: the sends are
+ ``[sesGone, workspace]`` in that order, so the workspace rung is a LAST resort inside
+ one walk rather than a replacement for the definition's own addressing. That it does
+ not fire at all when the preferred rung is healthy is
+ ``test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox``.
+
+ Exactly ONE row for this scripted run — not a claim of exactly-once delivery. The
+ contract remains at-least-once (see ``CLAIM_LEASE_SECONDS``); what is asserted here
+ is that one uninterrupted walk produces one card.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ # The real schema, and deliberately NO row for ``sesGone`` and no reserved
+ # workspace session: both absences are the premise.
+ _migrated_state_db()
+ assert _workspace_notice_session_rows() == [], (
+ "the reserved session must not pre-exist; the walk is what creates it"
+ )
+
+ sqlite, requests = _store(tmp_path)
+ run_id = _dead_binding_notice(sqlite, requests, "task-dead-binding")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ run_row = sqlite.get_run(run_id)
+ # The ladder shape, asserted before any send, so the behaviour below is attributable
+ # to the rung ORDER rather than to a lucky walk: the undeliverable preferred rung
+ # first, the mandatory workspace rung appended strictly after it.
+ assert [
+ (target.to_key(), session_id)
+ for target, session_id in service._failure_notice_targets(run_row)
+ ] == [
+ ("avibe::project::sesGone", "sesGone"),
+ (
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ WORKSPACE_NOTICE_SESSION_ID,
+ ),
+ ], "the premise: an undeliverable preferred rung, then the mandatory workspace rung"
+
+ # --- ONE drain pass, and the notice is delivered -------------------------
+ asyncio.run(service._drain_failure_notices())
+
+ assert _avibe_sends(controller) == ["sesGone", WORKSPACE_NOTICE_SESSION_ID], (
+ "the preferred rung must still be tried FIRST; the workspace rung is the last "
+ f"resort within the same walk, not a replacement: {_avibe_sends(controller)}"
+ )
+
+ rows = _persisted_messages()
+ assert [(row["platform"], row["type"], row["session_id"]) for row in rows] == [
+ ("avibe", "notify", WORKSPACE_NOTICE_SESSION_ID)
+ ], f"the workspace rung must receive exactly one actionable notice: {rows}"
+ assert rows[0]["content_text"], "an empty notice is not a notice"
+ assert len(_workspace_notice_session_rows()) == 1, (
+ "and the reserved row is created lazily, by the walk that reached the rung"
+ )
+
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_SENT, (
+ f"an undeliverable ladder may not be silent: {notice['state']} / {notice.get('error')}"
+ )
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT, (
+ "the workbench class acks on the durable receipt and on nothing weaker"
+ )
+ assert notice["attempts"] == 1, (
+ "THE ROUND-14 DELTA: the notice lands on the FIRST walk, not after five silent "
+ f"backoff attempts: {notice}"
+ )
+ # And it is genuinely settled, not merely stamped: a second pass sends nothing.
+ asyncio.run(service._drain_failure_notices())
+ assert _avibe_sends(controller) == ["sesGone", WORKSPACE_NOTICE_SESSION_ID], (
+ f"an acknowledged notice must never be walked again: {_avibe_sends(controller)}"
+ )
+ assert len(_persisted_messages()) == 1, "and must not grow a second card"
+
+
+def test_a_healthy_preferred_rung_never_reaches_the_workspace_inbox(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The ORDERING property, which is what makes the mandatory rung safe to make
+ mandatory.
+
+ The round-14 gate appends a workspace rung to EVERY ladder, and round 12's objection
+ to that was duplicate cards: a delivered notice's silent per-rung failures turning
+ into a second copy in the workspace inbox, plus a reserved row minted on
+ installations that never need one. Both are answered by POSITION rather than by a
+ condition — the rung is appended strictly LAST and the walk returns on the first rung
+ that acknowledges — and this test is the pin for that answer, because nothing else in
+ the file asserts the NEGATIVE.
+
+ Two claims, and the second is why the ``_emit_failure_notice`` half of the design is
+ lazy:
+
+ * no workspace SEND and no workspace ``messages`` row. The definition's own delivery
+ key acks first, so the appended rung is never walked;
+ * no reserved ``agent_sessions`` ROW AT ALL. ``_failure_notice_targets`` appends the
+ reserved id as a constant and performs no database access; the
+ resolve-or-create-or-heal lives in the walk. A build-time resolve would create the
+ row on the first failure of every install even though nothing here ever addresses
+ it.
+
+ The ladder is asserted too, so this cannot be mistaken for evidence that the rung is
+ conditional: it IS on the ladder — the gate says it must be — and it simply loses the
+ walk.
+ """
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ _no_background_web_push(monkeypatch)
+ _migrated_state_db()
+ assert _workspace_notice_session_rows() == [], "the premise: no reserved row yet"
+
+ sqlite, requests = _store(tmp_path)
+ run_id = _threaded_slack_notice(sqlite, requests, "task-healthy-rung")
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+
+ rungs = service._failure_notice_targets(sqlite.get_run(run_id))
+ assert [target.to_key() for target, _ in rungs] == [
+ "slack::channel::C123::thread::1710000000.000100",
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ ], f"the mandatory rung is present, and it is LAST: {rungs}"
+
+ asyncio.run(service._drain_failure_notices())
+
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_SENT, f"the premise: rung (1) delivered: {notice}"
+
+ # --- the negative, which is the whole point ------------------------------
+ assert _avibe_sends(controller) == ["C123"], (
+ "the walk must return on the acknowledged rung; a healthy delivery may not "
+ f"also push a workspace card: {_avibe_sends(controller)}"
+ )
+ assert WORKSPACE_NOTICE_SESSION_ID not in [
+ row["session_id"] for row in _persisted_messages()
+ ], (
+ "and nothing may be written into the workspace inbox: "
+ f"{_persisted_messages()}"
+ )
+ assert _workspace_notice_session_rows() == [], (
+ "nor may the reserved row be MINTED for an install whose rung (1) always "
+ "delivers — the ladder names it as a constant and only the WALK resolves it"
+ )
+
+
+def test_an_archived_session_ladder_holds_exactly_one_workspace_rung(
+ tmp_path: Path,
+) -> None:
+ """The COMPOSITION of round 14's two halves, asserted on the address alone.
+
+ Two independent mechanisms now name the reserved workspace session:
+
+ * rung (5)'s archived-session REROUTE (``_rung_five_session_id``), because an
+ archived row is writable but invisible and must not be addressed;
+ * the MANDATORY appended rung, which is on every ladder unconditionally.
+
+ Both return the same reserved id, so ``_add``'s seen-set — keyed on
+ ``(parsed key, session id)`` — collapses them. Without that the ladder would hold TWO
+ identical workspace rungs, the walk would deliver on the first and the second would
+ be dead weight the ack policy still had to reason about; if the reroute had instead
+ returned a resolved-but-different id the ladder would be internally inconsistent.
+
+ Driven with a LIVE preferred rung present as well, so the assertion covers POSITION
+ and not only the count: the surviving workspace rung has to sit after the definition's
+ own delivery key, not in rung (5)'s slot ahead of nothing.
+
+ Ladder-only, deliberately. Delivery through the rerouted rung is
+ ``test_an_archived_ordinary_session_is_rerouted_instead_of_acked_into``; what is
+ unasserted anywhere else is the SHAPE, and a drain pass would settle on rung (1) here
+ and never inspect it.
+ """
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _workbench_session("sesArchivedDup", project="proj-archived-dup", status="archived")
+
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-archived-dup",
+ name="nightly report",
+ deliver_key="slack::channel::C123::thread::1710000000.000100",
+ session_id="sesArchivedDup",
+ )
+ run = requests.enqueue_task_run("task-archived-dup")
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id="task-archived-dup")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ rungs = service._failure_notice_targets(sqlite.get_run(run.id))
+
+ assert [(target.to_key(), session_id) for target, session_id in rungs] == [
+ ("slack::channel::C123::thread::1710000000.000100", None),
+ (
+ f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}",
+ WORKSPACE_NOTICE_SESSION_ID,
+ ),
+ ], (
+ "the reroute and the mandatory append must collapse into ONE rung, positioned "
+ f"last: {rungs}"
+ )
+ assert "avibe::project::sesArchivedDup" not in [
+ target.to_key() for target, _ in rungs
+ ], f"and the archived row may not be addressed at all: {rungs}"
+
+
+def test_replaying_the_workspace_walk_reuses_the_persisted_receipt(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Subordinate to HFR-079/HFR-075 — restart cannot duplicate the workspace card.
+
+ The maintainer's "restart/replay cannot duplicate that notice", applied to the
+ mandatory rung: crash between ``persist_agent_message`` committing the workspace row
+ and the owed notice being acknowledged, then re-drive the walk on a fresh service
+ instance. The dispatcher's duplicate short-circuit finds the row by its run-derived
+ identity, declines to re-send, and reports the found row as a ``receipt``
+ (HFR-075) — which is precisely what the workbench class's ack source accepts, so the
+ replay settles instead of writing a second card.
+
+ ATTEMPT 1 THROUGHOUT, since round 14. The rung is on every ladder, so the walk that
+ persists the row is the FIRST one and the crash rewind puts the notice back to zero
+ consumed attempts rather than to ``MAX_ATTEMPTS - 1``. Under the retired
+ final-attempt design that rewind had to reconstruct the sixth attempt, because it was
+ the only interleaving in which the rung existed at all.
+
+ A PIN, not a red-first case: HFR-075's machinery already makes this green, and the
+ rung inherits it because it is an ordinary ``avibe::project::…`` rung with an
+ ordinary run-derived ``failure_id``. The red half is the mutation at the end —
+ delete the persisted row and the same replay delivers again, which is what the
+ short-circuit is being credited with preventing.
+ """
+
+ from core.delivery_evidence import ACK_EVIDENCE_RECEIPT
+ from sqlalchemy import text as sa_text
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.background import NOTICE_PENDING
+ from storage.db import get_cached_sqlite_engine
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ run_id = _dead_binding_notice(sqlite, requests, "task-dead-binding-replay")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ asyncio.run(service._drain_failure_notices())
+ rows = _persisted_messages()
+ assert [row["session_id"] for row in rows] == [WORKSPACE_NOTICE_SESSION_ID], (
+ f"the premise: the first walk already persisted the workspace row: {rows}"
+ )
+ persisted_identity = rows[0]["native_message_id"]
+
+ def _crash_between_persist_and_ack() -> None:
+ """The row is committed; the notice never learned about it.
+
+ ``attempts=0`` so the recovered pass claims attempt 1 — the same attempt the
+ crashed pass was walking, which is now every attempt's shape.
+ """
+
+ sqlite.update_owed_failure_notice(
+ run_id,
+ state=NOTICE_PENDING,
+ attempts=0,
+ next_attempt_at=None,
+ ack_evidence=None,
+ error=None,
+ )
+
+ _crash_between_persist_and_ack()
+
+ # A FRESH service and dispatcher: the recovery is a different process, so nothing
+ # in-memory from the crashed pass may be what settles it.
+ replay_controller, _replay_dispatcher, _replay_touched = _live_turn_dispatcher()
+ replay_service = _drain_service(tmp_path, replay_controller, sqlite, requests)
+ asyncio.run(replay_service._drain_failure_notices())
+
+ assert [row["native_message_id"] for row in _persisted_messages()] == [
+ persisted_identity
+ ], "the replay must reuse the committed row, not write a second one"
+ assert WORKSPACE_NOTICE_SESSION_ID not in _avibe_sends(replay_controller), (
+ "the duplicate short-circuit must run BEFORE the send: "
+ f"{_avibe_sends(replay_controller)}"
+ )
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_SENT, f"a found row settles the notice: {notice}"
+ assert notice["ack_evidence"] == ACK_EVIDENCE_RECEIPT, (
+ "the found row is the receipt the workbench class requires"
+ )
+ assert notice["attempts"] == 1
+
+ # --- red by mutation: without the committed row, the replay DOES deliver --
+ with get_cached_sqlite_engine().begin() as conn:
+ conn.execute(
+ sa_text("DELETE FROM messages WHERE native_message_id = :identity"),
+ {"identity": persisted_identity},
+ )
+ _crash_between_persist_and_ack()
+ mutation_controller, _mutation_dispatcher, _mutation_touched = _live_turn_dispatcher()
+ mutation_service = _drain_service(tmp_path, mutation_controller, sqlite, requests)
+ asyncio.run(mutation_service._drain_failure_notices())
+
+ assert [row["session_id"] for row in _persisted_messages()] == [
+ WORKSPACE_NOTICE_SESSION_ID
+ ], "with the row gone there is nothing to short-circuit on, so it is written again"
+ assert WORKSPACE_NOTICE_SESSION_ID in _avibe_sends(mutation_controller), (
+ "and the send happens too — which is exactly what the receipt above prevented"
+ )
+
+
+def test_an_unwritable_workspace_inbox_still_dead_letters_visibly(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """Subordinate to HFR-079 — the residual, asserted rather than described.
+
+ ``_workspace_notice_session_id`` returns ``None`` when the workbench database cannot
+ be read or written. The rung is still APPENDED — the round-14 gate makes that
+ unconditional and the ladder never touches the database — so the residual now lives in
+ the WALK: ``_emit_failure_notice`` skips the rung on every attempt, the notice spends
+ its full backoff on the undeliverable preferred rung, and the sixth attempt
+ dead-letters exactly as it did before this change: ``failed``, carrying the reason the
+ last usable rung was refused ("without a persisted receipt", not the skipped rung's
+ own complaint).
+
+ That path has to stay reachable — a fallback that swallowed the dead letter when it
+ could not itself deliver would replace one silence with a worse one. It is also the
+ reason ``MAX_ATTEMPTS`` and the backoff survive round 14 untouched: making the rung
+ mandatory removes the retry ladder from the cases where it delivers, and leaves it
+ exactly where it is still the only thing standing between an unusable workbench DB
+ and an unbounded retry loop.
+ """
+
+ from core import failure_notices
+ from storage.background import NOTICE_FAILED, NOTICE_PENDING
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ run_id = _dead_binding_notice(sqlite, requests, "task-dead-binding-unwritable")
+
+ service = _drain_service(tmp_path, controller, sqlite, requests)
+ service._workspace_notice_session_id = lambda: None
+
+ for attempt in range(1, failure_notices.MAX_ATTEMPTS):
+ asyncio.run(service._drain_failure_notices())
+ assert sqlite.owed_failure_notice(run_id)["state"] == NOTICE_PENDING
+ _rewind_notice_backoff(sqlite, run_id)
+
+ asyncio.run(service._drain_failure_notices())
+
+ assert _persisted_messages() == [], "there was nowhere to write it"
+ notice = sqlite.owed_failure_notice(run_id)
+ assert notice["state"] == NOTICE_FAILED, (
+ f"an unwritable workbench DB must still dead-letter VISIBLY: {notice}"
+ )
+ assert notice["attempts"] == failure_notices.MAX_ATTEMPTS
+ assert "without a persisted receipt" in (notice["error"] or ""), (
+ f"and it must say why the last rung was refused: {notice['error']}"
+ )
+ # The definition-level surface is unchanged either way, so the dead letter is
+ # still discoverable by somebody who goes looking.
+ assert sqlite.definition_health("task-dead-binding-unwritable")["health"] == "failing"
+
+
+# --- group N: the creation origin the notice names -------------------------
+#
+# Round 14, gate item 3 (review comment 5121007240): "capture the stable creation origin
+# needed to render the channel/thread and deep link, then include origin/deep link … in
+# owner-DM and workspace notices". Subordinate to HFR-094's notice-body family for the
+# copy and to HFR-079's ladder family for the rungs the capture lights up; no new
+# scenario id.
+
+
+_SLACK_ORIGIN_CALLER = {
+ "session_id": "sesAgent",
+ "run_id": "runAgent",
+ "source": "agent_turn",
+ "platform": "slack",
+ "user_id": "U0AUTHOR",
+ "channel_id": "C0123",
+ "session_key": "slack::channel::C0123::thread::1710000000.000100",
+ "scope_id": "slack::channel::C0123",
+ "message_id": "1710000000.000200",
+ "workspace_id": "T0999",
+}
+
+_SLACK_ORIGIN_PERMALINK = (
+ "https://slack.com/archives/C0123/p1710000000000200"
+ "?thread_ts=1710000000.000100&cid=C0123"
+)
+
+
+def _StubShell():
+ """A bare controller stand-in for the body-only tests (no drain, no delivery)."""
+
+ from types import SimpleNamespace
+
+ return SimpleNamespace()
+
+
+def _origin_metadata(caller: dict) -> dict:
+ """The ``created_by`` envelope ``vibe task add`` writes, verbatim."""
+
+ return {"created_by": {"kind": "caller_context", "caller": dict(caller)}}
+
+
+def _failed_run(sqlite, requests, definition_id: str) -> str:
+ run = requests.enqueue_task_run(definition_id)
+ claimed = requests.claim(run.id)
+ assert claimed is not None
+ requests.complete(claimed, ok=False, error="backend exploded", task_id=definition_id)
+ return run.id
+
+
+def _real_translator(service, language: str):
+ from types import SimpleNamespace
+
+ from core.scheduled_tasks import ScheduledTaskService
+
+ service.controller.config = SimpleNamespace(language=language, platform="slack")
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+ return service
+
+
[email protected]("language", ["en", "zh"])
+def test_the_notice_names_where_the_definition_was_created_and_links_to_it(
+ tmp_path: Path,
+ language: str,
+) -> None:
+ """The last item on D5's body list, and the one a DM needs most.
+
+ A failure notice is CONTEXT-FREE by construction: it may be delivered to an owner DM
+ or to the workspace inbox hours after the fire, neither of which is attached to the
+ conversation that asked for the definition. So "which Slack thread did I create this
+ in" was unanswerable from the notice — the ids were never captured, and no permalink
+ builder existed anywhere in the codebase.
+
+ RED at 3578f2b6 (round 11), overlaid with its own local ``_failed_run`` helper so it
+ imports nothing newer than that commit: the body was
+
+ ``[Avibe Harness] Scheduled work "nightly report" failed.``
+ ``Error: backend exploded``
+ ``Definition: task-origin``
+ ``Re-run it now with: vibe task run task-origin …``
+
+ — verbatim, in both languages, with no line naming ``C0123``, no thread ts, and no
+ URL. (The overlay spells the origin metadata as a literal dict, which round 11
+ accepts and ignores: ``run_definitions.metadata_json`` is free-form JSON.)
+
+ Asserted through the REAL translator in BOTH languages because the defect is in
+ rendered copy — and the raw platform value must never appear, which is HFR-094's
+ lesson applied to a third call site: ``slack`` goes through a closed label map and
+ comes out as ``Slack``.
+ """
+
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-origin",
+ name="nightly report",
+ metadata=_origin_metadata(_SLACK_ORIGIN_CALLER),
+ )
+ run_id = _failed_run(sqlite, requests, "task-origin")
+
+ service = _real_translator(_drain_service(tmp_path, _StubShell(), sqlite, requests), language)
+ body = service._failure_notice_body(sqlite.get_run(run_id), {"failure_id": run_id})
+
+ # --- the origin line ----------------------------------------------------
+ assert i18n_t("harness.notice.origin", language).split("{")[0].strip() in body, (
+ f"the body must say where the definition was created: {body}"
+ )
+ assert i18n_t("harness.notice.platform.slack", language) in body
+ assert "C0123" in body, f"named by the captured channel id: {body}"
+ assert "1710000000.000100" in body, f"and by the captured thread: {body}"
+
+ # --- the deep link ------------------------------------------------------
+ assert _SLACK_ORIGIN_PERMALINK in body, f"with a followable permalink: {body}"
+ assert i18n_t("harness.notice.originLink", language).split("{")[0].strip() in body
+
+ # --- and nothing leaked -------------------------------------------------
+ assert "harness.notice." not in body, f"no dotted key path: {body}"
+ for wire_value in ("slack", "session_key", "workspace_id"):
+ assert wire_value not in body.replace(_SLACK_ORIGIN_PERMALINK, ""), (
+ f"{wire_value!r} is a wire value, not product copy: {body}"
+ )
+
+
+def test_a_definition_with_no_captured_origin_gets_no_origin_line(tmp_path: Path) -> None:
+ """The backfill answer is OMIT, and this is what that costs and what it buys.
+
+ EVERY definition created before the capture landed has no origin — the ids were never
+ recorded, and there is no migration that could invent them. A definition created from
+ the CLI by hand has none either, legitimately and forever: there is no conversation
+ behind it. Both take NO line, which is the same call
+ ``notice_failure_class_i18n_key`` makes for a class it cannot name and the same call
+ the last-success line makes for a definition that has never succeeded. "Created in:
+ unknown" would be copy about nothing on the lane that already carries the most lines.
+ """
+
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ # A pre-origin definition: metadata exists (round 12 writes a ``created_by`` for CLI
+ # callers) but carries no origin fields at all.
+ _task(
+ sqlite,
+ "task-legacy",
+ name="nightly report",
+ metadata=_origin_metadata({"session_id": "sesAgent", "source": "agent_turn"}),
+ )
+ run_id = _failed_run(sqlite, requests, "task-legacy")
+
+ service = _real_translator(_drain_service(tmp_path, _StubShell(), sqlite, requests), "en")
+ body = service._failure_notice_body(sqlite.get_run(run_id), {"failure_id": run_id})
+
+ assert i18n_t("harness.notice.origin", "en").split("{")[0].strip() not in body, (
+ f"no captured origin means no origin line: {body}"
+ )
+ assert i18n_t("harness.notice.originLink", "en").split("{")[0].strip() not in body
+
+ # And a definition with NO metadata whatsoever behaves identically.
+ _task(sqlite, "task-bare", name="nightly report")
+ bare_run = _failed_run(sqlite, requests, "task-bare")
+ bare_body = service._failure_notice_body(sqlite.get_run(bare_run), {"failure_id": bare_run})
+ assert i18n_t("harness.notice.origin", "en").split("{")[0].strip() not in bare_body
+
+
+ "caller,expects_link,why",
+ [
+ (
+ {
+ "platform": "lark",
+ "user_id": "ou_1",
+ "channel_id": "oc_abc",
+ "session_key": "lark::channel::oc_abc",
+ "message_id": "om_abc",
+ },
+ False,
+ "Feishu/Lark has no public message permalink, so the text stands alone",
+ ),
+ (
+ {
+ "platform": "avibe",
+ "session_key": "avibe::project::proj-1",
+ "channel_id": "proj-1",
+ "message_id": "msg-1",
+ },
+ False,
+ "a Workbench origin is addressable only as a localhost URL, which is not "
+ "reachable from wherever this notice is read",
+ ),
+ (
+ {
+ "platform": "discord",
+ "user_id": "111",
+ "channel_id": "555",
+ "session_key": "discord::user::111",
+ "message_id": "777",
+ },
+ False,
+ "a Discord DM has no guild, and ``@me`` would resolve for one user only",
+ ),
+ (
+ {
+ "platform": "telegram",
+ "user_id": "42",
+ "channel_id": "-1001234567890",
+ "session_key": "telegram::channel::-1001234567890::thread::7",
+ "message_id": "99",
+ },
+ True,
+ "a Telegram supergroup does have a t.me/c link",
+ ),
+ ],
+)
+def test_an_origin_that_cannot_be_linked_is_still_named(
+ tmp_path: Path,
+ caller: dict,
+ expects_link: bool,
+ why: str,
+) -> None:
+ """Two independent decisions, and the second failing must not suppress the first.
+
+ ``origin_link`` refuses for three different reasons (no permalink grammar exists; the
+ only URL is not reachable from where the notice is read; a required id was not
+ captured), and in all three the origin TEXT is still true and still narrows the
+ search. Collapsing them — dropping the whole origin because there is no link — would
+ make Feishu, WeChat and Workbench definitions permanently anonymous.
+ """
+
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _task(sqlite, "task-origin-nolink", name="nightly report", metadata=_origin_metadata(caller))
+ run_id = _failed_run(sqlite, requests, "task-origin-nolink")
+
+ service = _real_translator(_drain_service(tmp_path, _StubShell(), sqlite, requests), "en")
+ body = service._failure_notice_body(sqlite.get_run(run_id), {"failure_id": run_id})
+
+ assert i18n_t("harness.notice.origin", "en").split("{")[0].strip() in body, (
+ f"the origin is named regardless of linkability ({why}): {body}"
+ )
+ assert i18n_t(f"harness.notice.platform.{caller['platform']}", "en") in body
+ link_line = i18n_t("harness.notice.originLink", "en").split("{")[0].strip()
+ assert (link_line in body) is expects_link, f"{why}: {body}"
+ if not expects_link:
+ assert "http" not in body, f"a refused link must not leak a partial URL: {body}"
+
+
+def test_an_unmappable_origin_platform_takes_no_line_rather_than_leaking_itself(
+ tmp_path: Path,
+) -> None:
+ """A wire value from a platform this build has never heard of.
+
+ The label is rendered INSIDE a translated sentence, so the only two options are a
+ closed map or interpolation — and "Created in: mystery_platform channel X" puts an
+ identifier into product copy for no benefit. Same choice, same reasoning, as
+ ``notice_failure_class_i18n_key`` returning ``None``.
+ """
+
+ from vibe.i18n import t as i18n_t
+
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-origin-unknown",
+ name="nightly report",
+ metadata=_origin_metadata(
+ {
+ "platform": "mystery_platform",
+ "user_id": "U1",
+ "channel_id": "C1",
+ "session_key": "mystery_platform::channel::C1",
+ "message_id": "m1",
+ }
+ ),
+ )
+ run_id = _failed_run(sqlite, requests, "task-origin-unknown")
+
+ service = _real_translator(_drain_service(tmp_path, _StubShell(), sqlite, requests), "en")
+ body = service._failure_notice_body(sqlite.get_run(run_id), {"failure_id": run_id})
+
+ assert "mystery_platform" not in body, f"the wire value must not reach copy: {body}"
+ assert i18n_t("harness.notice.origin", "en").split("{")[0].strip() not in body, (
+ f"and an unnameable platform takes no line at all: {body}"
+ )
+
+
+def test_a_captured_origin_lights_up_the_scope_and_owner_dm_rungs(tmp_path: Path) -> None:
+ """D5's designed ladder shape, finally REACHABLE.
+
+ Rungs (3) and (4) have always read ``caller["session_key"]`` / ``caller["scope_id"]``
+ and ``caller["platform"]`` / ``caller["user_id"]`` — fields NOTHING in the codebase
+ had ever written. They were dead code: every ladder skipped straight from the bound
+ session to the workbench rung, and the owner DM the plan specifies had never once
+ fired. The origin capture is what lights them up, and this is the consequence to own
+ loudly rather than discover in the field: for newly created definitions an owner DM
+ is now a real delivery attempt.
+
+ NO RED OF ITS OWN, stated plainly because the honest answer is more useful than a
+ manufactured one. Overlaid at 3578f2b6 (round 11) with the same hand-written
+ ``created_by`` metadata, the ladder came back as
+
+ ``[('slack::channel::C999', None),
+ ('slack::channel::C0123::thread::1710000000.000100', None),
+ ('slack::user::U0AUTHOR', None)]``
+
+ — rungs (3) and (4) already resolved correctly. The reading logic was never the
+ defect; nothing in the product ever WROTE those fields, which is what
+ ``tests/test_caller_context.py``'s capture test is red on at that same commit. The
+ only assertion below that would fail at 3578f2b6 is the trailing workspace rung, and
+ that belongs to round 14's always-append change, not to this one. So this is a
+ consequence test: it pins that the capture makes D5's designed shape REACHABLE, and
+ it is the test that will fail if a future change to the origin key set silently
+ unlights the owner DM again.
+
+ ORDER is asserted, not just membership: the definition's own delivery key first, then
+ the creating conversation, then the owner DM, then the workbench rung, and the
+ reserved workspace rung last on every ladder (round-14 always-append). A DM that
+ preceded the definition's own channel would move a routine failure notice out of the
+ shared conversation the team watches and into one person's inbox.
+ """
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-origin-ladder",
+ name="nightly report",
+ deliver_key="slack::channel::C999",
+ metadata=_origin_metadata(_SLACK_ORIGIN_CALLER),
+ )
+ run_id = _failed_run(sqlite, requests, "task-origin-ladder")
+
+ service = _drain_service(tmp_path, _StubShell(), sqlite, requests)
+ rungs = [
+ (target.to_key(), session_id)
+ for target, session_id in service._failure_notice_targets(sqlite.get_run(run_id))
+ ]
+
+ assert rungs == [
+ ("slack::channel::C999", None),
+ ("slack::channel::C0123::thread::1710000000.000100", None),
+ ("slack::user::U0AUTHOR", None),
+ (f"avibe::project::{WORKSPACE_NOTICE_SESSION_ID}", WORKSPACE_NOTICE_SESSION_ID),
+ ], f"the captured origin must produce rungs (3) and (4), in that order: {rungs}"
+
+ # The five-part origin key is delivered to as a THREAD, not downgraded to its parent
+ # channel — ``scope_id`` is present in the same caller and is deliberately NOT the
+ # one rung (3) prefers, because retargeting a thread notice at its channel would
+ # broadcast it to everyone in the channel instead.
+ assert "slack::channel::C0123" not in [key for key, _ in rungs]
+
+
+def test_the_workspace_card_carries_the_creation_origin(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ """The half of the gate that is about the WORKSPACE notice, not the owner DM.
+
+ RED at the CURRENT HEAD (d2c3bf31), pre-change — not at 3578f2b6, because the
+ workspace-notifications rung, its reserved session and its receipt-only ack policy are
+ all round-12-and-later symbols this test imports. At HEAD the card was persisted with
+ a body that named no origin and carried no URL; the red is the absence of the origin
+ line in ``content_text``, and it is the same absence the ``_failure_notice_body``
+ tests above prove against the older baseline.
+
+ THE SCENARIO IS THE POINT, and it is the one where the origin matters most: a
+ definition created in a Slack thread, in an install whose Slack transport is no longer
+ configured. ``validate_platform`` refuses, so ``_build_context`` raises and BOTH origin
+ rungs are unusable — the disposal every unusable rung gets. The workspace card is then
+ the only place the failure surfaces, and it is the only place the user can learn which
+ Slack thread to go look at. Without the origin the card names a definition id and a
+ dead end.
+ """
+
+ from storage.agent_session_rows import WORKSPACE_NOTICE_SESSION_ID
+ from storage.background import NOTICE_SENT
+ from vibe.i18n import t as i18n_t
+
+ _no_background_web_push(monkeypatch)
+ controller, _dispatcher, _touched = _live_turn_dispatcher()
+ _migrated_state_db()
+
+ sqlite, requests = _store(tmp_path)
+ _task(
+ sqlite,
+ "task-origin-workspace",
+ name="nightly report",
+ deliver_key="slack::channel::C0123::thread::1710000000.000100",
+ metadata=_origin_metadata(_SLACK_ORIGIN_CALLER),
+ )
+ run_id = _failed_run(sqlite, requests, "task-origin-workspace")
+
+ service = _real_translator(_drain_service(tmp_path, controller, sqlite, requests), "en")
+
+ def _no_slack_transport(platform: str) -> None:
+ if platform == "slack":
+ raise ValueError("unsupported task platform: slack")
+
+ service.validate_platform = _no_slack_transport
+
+ asyncio.run(service._drain_failure_notices())
+
+ rows = _persisted_messages()
+ assert [(row["type"], row["session_id"]) for row in rows] == [
+ ("notify", WORKSPACE_NOTICE_SESSION_ID)
+ ], f"the premise: only the workspace rung could be delivered to: {rows}"
+ assert sqlite.owed_failure_notice(run_id)["state"] == NOTICE_SENT
+
+ card = rows[0]["content_text"]
+ assert i18n_t("harness.notice.origin", "en").split("{")[0].strip() in card, (
+ f"the workspace card must name the conversation it came from: {card}"
+ )
+ assert "C0123" in card and "1710000000.000100" in card
+ assert _SLACK_ORIGIN_PERMALINK in card, (
+ f"and give the user a way back to it: {card}"
+ )
diff --git a/tests/test_harness_health_projection.py b/tests/test_harness_health_projection.py
new file mode 100644
index 000000000..6b9484cf5
--- /dev/null
+++ b/tests/test_harness_health_projection.py
@@ -0,0 +1,273 @@
+"""HFR-097 / HFR-098 — the CLI consumes the definition health projection.
+
+``_enrich_definitions`` is the one place a definition's derived health is
+computed, and every list, show and Workbench read already passes through it.
+PR6 added a *second* read model beside it: ``vibe/cli.py`` grew its own
+``_task_health_map`` / ``_task_health`` pair that queried ``agent_runs`` again
+through a ``ScheduledTaskStore.definition_health_batch`` delegator that existed
+for no other caller. Two read models over the same table is how the same
+definition comes to have two different answers on two surfaces — and it did:
+task mutations answered from the CLI-side query while watch mutations, which
+never grew one, answered with no health at all.
+
+These two scenarios pin the direction of the dependency rather than the values:
+the CLI is a projection consumer (HFR-097), and every mutation answers with the
+same projected row the following ``show`` prints (HFR-098).
+"""
+
+from __future__ import annotations
+
+import inspect
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core import scheduled_tasks as scheduled_tasks_module
+from core.watches import ManagedWatchStore, WatchRuntimeStateStore
+from storage.background import SQLiteBackgroundTaskStore
+from vibe import cli
+
+#: The fields ``_enrich_definitions`` derives that a mutation response must not
+#: answer for itself. ``lifecycle_*`` rides along because health and lifecycle
+#: are orthogonal axes of the same projected row: a response that carried one
+#: without the other would still be reading two sources.
+PROJECTED_FIELDS = (
+ "health",
+ "consecutive_failures",
+ "recent_failures",
+ "lifecycle_state",
+ "lifecycle_detail",
+)
+
+
+def _configured_v2():
+ return SimpleNamespace(
+ slack=SimpleNamespace(bot_token="x", app_token="y"),
+ discord=SimpleNamespace(bot_token=""),
+ lark=SimpleNamespace(app_id="", app_secret=""),
+ wechat=SimpleNamespace(enable=False),
+ enabled_platforms=lambda: ["slack"],
+ )
+
+
+def _parse(argv: list[str]):
+ return cli.build_parser().parse_args(argv)
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _seed_failed_runs(definition_id: str, *, request_type: str, count: int = 2) -> None:
+ """Give a definition a real failure streak in ``agent_runs``.
+
+ Health is a fact about run history, never about the write that just
+ happened, so it has to be seeded where the projection actually reads it.
+ """
+
+ store = SQLiteBackgroundTaskStore()
+ try:
+ for index in range(count):
+ store.enqueue_run(
+ {
+ "id": f"run-{definition_id}-{index}",
+ "request_type": request_type,
+ "status": "failed",
+ "definition_id": definition_id,
+ "error": "boom",
+ "created_at": _now(),
+ "completed_at": _now(),
+ }
+ )
+ finally:
+ store.close()
+
+
+def _definition(capsys) -> dict:
+ return json.loads(capsys.readouterr().out)["definition"]
+
+
+def _projected(payload: dict) -> dict:
+ return {field: payload.get(field) for field in PROJECTED_FIELDS}
+
+
+class _FailureSeedingTaskStore(cli.ScheduledTaskStore):
+ """A task store whose new row already has failure history when it returns.
+
+ Not a contrivance: an ``--at`` task whose time has already passed can be
+ claimed, fail, and be recorded before the create command has printed
+ anything. The response is built after that, so it must read the row rather
+ than assume a write it just made is healthy.
+ """
+
+ def add_task(self, *args, **kwargs):
+ task = super().add_task(*args, **kwargs)
+ _seed_failed_runs(task.id, request_type="scheduled")
+ return task
+
+
+def test_the_cli_is_a_projection_consumer_not_a_second_health_read_model(
+ monkeypatch, capsys
+) -> None:
+ """HFR-097 — no CLI-side health query may exist, structurally or at runtime.
+
+ Two halves, because either alone is escapable. The source half says the
+ symbols are gone; the behavioural half says nothing reintroduced the query
+ under another name, by asserting that every ``definition_health_batch`` call
+ made while three task mutations run is one ``_enrich_definitions`` made.
+ """
+
+ # Snapshot before any patching: ``monkeypatch.setattr(..., raising=False)``
+ # CREATES a missing attribute, so a later absence assertion would pass for
+ # the wrong reason.
+ assert not hasattr(cli.ScheduledTaskStore, "definition_health_batch"), (
+ "the ScheduledTaskStore delegator existed only to feed the CLI-side query"
+ )
+
+ cli_source = Path(cli.__file__).read_text(encoding="utf-8")
+ assert "definition_health_batch" not in cli_source
+ assert "_task_health" not in cli_source
+ store_source = Path(scheduled_tasks_module.__file__).read_text(encoding="utf-8")
+ assert "definition_health_batch" not in store_source
+
+ unprojected: list[list[str]] = []
+ original = SQLiteBackgroundTaskStore.definition_health_batch
+
+ def guarded(self, definition_ids, **kwargs):
+ stack = [frame.function for frame in inspect.stack()]
+ if "_enrich_definitions" not in stack:
+ unprojected.append(stack[:6])
+ return original(self, definition_ids, **kwargs)
+
+ monkeypatch.setattr(SQLiteBackgroundTaskStore, "definition_health_batch", guarded)
+
+ store = cli.ScheduledTaskStore()
+ add_args = _parse(
+ [
+ "task",
+ "add",
+ "--session-key",
+ "slack::channel::C123",
+ "--cron",
+ "0 * * * *",
+ "--message",
+ "hello",
+ ]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2()),
+ patch("vibe.cli._task_store", return_value=store),
+ ):
+ assert cli.cmd_task_add(add_args) == 0
+ task_id = _definition(capsys)["id"]
+ assert cli.cmd_task_set_enabled(task_id, False) == 0
+ capsys.readouterr()
+ assert cli.cmd_task_update(_parse(["task", "update", task_id, "--name", "renamed"])) == 0
+ capsys.readouterr()
+
+ assert unprojected == [], (
+ "health was queried outside _enrich_definitions: " f"{unprojected}"
+ )
+
+
+def test_task_and_watch_mutations_return_the_enriched_projection(capsys) -> None:
+ """HFR-098 — every mutation answers with the row the next ``show`` prints.
+
+ A create/pause/resume/update response is the only thing an agent sees before
+ it reports back, so a definition that is already failing has to say so
+ there. Watch mutations carried no health at all; task mutations carried a
+ separately-queried copy of it. Both are asserted against ``show``, which
+ reads the canonical projection, so the two can no longer disagree.
+ """
+
+ def _assert_matches_show(label: str, payload: dict, show, definition_id: str) -> None:
+ """A mutation response, checked against the very next ``show``.
+
+ Immediately after, not once at the end: ``lifecycle_state`` legitimately
+ changes with each pause and resume, and comparing every response to one
+ final snapshot would test the wrong thing.
+ """
+
+ assert show(definition_id) == 0
+ shown = _definition(capsys)
+ assert shown["health"] == "failing", f"{label}: the seeded streak is not visible at all"
+ assert _projected(payload) == _projected(shown), f"{label} disagrees with show"
+ assert payload["consecutive_failures"] == 2, f"{label} lost the streak"
+
+ task_store = _FailureSeedingTaskStore()
+ add_args = _parse(
+ [
+ "task",
+ "add",
+ "--session-key",
+ "slack::channel::C123",
+ "--cron",
+ "0 * * * *",
+ "--message",
+ "hello",
+ ]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2()),
+ patch("vibe.cli._task_store", return_value=task_store),
+ ):
+ assert cli.cmd_task_add(add_args) == 0
+ created = _definition(capsys)
+ task_id = created["id"]
+ _assert_matches_show("task add", created, cli.cmd_task_show, task_id)
+
+ assert cli.cmd_task_set_enabled(task_id, False) == 0
+ _assert_matches_show("task pause", _definition(capsys), cli.cmd_task_show, task_id)
+
+ assert cli.cmd_task_set_enabled(task_id, True) == 0
+ _assert_matches_show("task resume", _definition(capsys), cli.cmd_task_show, task_id)
+
+ assert cli.cmd_task_update(_parse(["task", "update", task_id, "--name", "renamed"])) == 0
+ _assert_matches_show("task update", _definition(capsys), cli.cmd_task_show, task_id)
+
+ watch_store = ManagedWatchStore()
+ watch_runtime = WatchRuntimeStateStore()
+
+ def _startup(store, runtime_store, watch_id, **kwargs):
+ # A ``once`` watch can complete — and fail — while the create command is
+ # still confirming startup, which is exactly when this row's health
+ # stops being the default.
+ _seed_failed_runs(watch_id, request_type="watch")
+ return store.get_watch(watch_id), runtime_store.load().get("watches", {}).get(watch_id)
+
+ watch_add_args = _parse(
+ [
+ "watch",
+ "add",
+ "--session-key",
+ "slack::channel::C123",
+ "--name",
+ "Wait for export",
+ "--shell",
+ "true",
+ ]
+ )
+ with (
+ patch("vibe.cli._ensure_config", return_value=_configured_v2()),
+ patch("vibe.cli._watch_store", return_value=watch_store),
+ patch("vibe.cli._watch_runtime_store", return_value=watch_runtime),
+ patch("vibe.cli._wait_for_watch_startup", side_effect=_startup),
+ ):
+ assert cli.cmd_watch_add(watch_add_args) == 0
+ watch_created = _definition(capsys)
+ watch_id = watch_created["id"]
+ _assert_matches_show("watch add", watch_created, cli.cmd_watch_show, watch_id)
+
+ assert cli.cmd_watch_set_enabled(watch_id, False) == 0
+ _assert_matches_show("watch pause", _definition(capsys), cli.cmd_watch_show, watch_id)
+
+ assert cli.cmd_watch_set_enabled(watch_id, True) == 0
+ _assert_matches_show("watch resume", _definition(capsys), cli.cmd_watch_show, watch_id)
+
+ assert cli.cmd_watch_update(_parse(["watch", "update", watch_id, "--name", "renamed"])) == 0
+ _assert_matches_show("watch update", _definition(capsys), cli.cmd_watch_show, watch_id)
diff --git a/tests/test_i18n_backend_keys.py b/tests/test_i18n_backend_keys.py
index b43a81e34..59c6ceebc 100644
--- a/tests/test_i18n_backend_keys.py
+++ b/tests/test_i18n_backend_keys.py
@@ -16,7 +16,18 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from core.run_settlement import SETTLEMENT_I18N_KEYS, SWEEP_I18N_KEYS
+from core.failure_notices import (
+ NOTICE_FAILURE_CLASS_I18N_KEYS,
+ NOTICE_ORIGIN_PLATFORM_I18N_KEYS,
+ NOTICE_REASON_I18N_KEYS,
+ NOTICE_REASON_UNKNOWN_I18N_KEY,
+ PER_FIRE_INTERRUPT_REASONS,
+)
+from core.run_settlement import (
+ RUN_INTERRUPTION_REASONS,
+ SETTLEMENT_I18N_KEYS,
+ SWEEP_I18N_KEYS,
+)
from core.services.sessions import SESSION_ARCHIVED_I18N_KEY, session_archived_message
from core.show_session_events import SHOW_EVENT_ERROR_I18N_KEYS
from storage.background import (
@@ -105,3 +116,161 @@ def test_session_archived_message_resolves_in_every_language() -> None:
assert resolved != SESSION_ARCHIVED_I18N_KEY, f"{SESSION_ARCHIVED_I18N_KEY} is not translated in {lang}"
assert resolved.strip()
assert resolved == t(SESSION_ARCHIVED_I18N_KEY, lang)
+
+
+def test_notice_reason_i18n_map_covers_exactly_the_interruption_lane() -> None:
+ # ``harness.notice.interrupted`` renders the reason INTO the sentence a user
+ # reads, so an unmapped reason is a wire identifier leaking into product copy —
+ # "was interrupted (backend_refresh)". Same drift guard as ``SWEEP_I18N_KEYS``
+ # above: the map has to track ``RUN_INTERRUPTION_REASONS`` exactly, since that
+ # frozenset is what gates the interrupted branch. A reason added there without a
+ # label would silently fall back to the generic string and lose its explanation.
+ assert set(NOTICE_REASON_I18N_KEYS) == set(RUN_INTERRUPTION_REASONS), (
+ "unlabelled: "
+ f"{sorted(set(RUN_INTERRUPTION_REASONS) - set(NOTICE_REASON_I18N_KEYS))}; "
+ "stale: "
+ f"{sorted(set(NOTICE_REASON_I18N_KEYS) - set(RUN_INTERRUPTION_REASONS))}"
+ )
+
+
+ "reason,key",
+ sorted(NOTICE_REASON_I18N_KEYS.items()) + [("<unmapped>", NOTICE_REASON_UNKNOWN_I18N_KEY)],
+)
+def test_every_notice_reason_label_resolves(reason: str, key: str) -> None:
+ # Including the fallback: an unknown reason must render a LOCALIZED generic
+ # label, so if that key were missing the notice would print the dotted path
+ # instead — a worse leak than the raw reason it replaced.
+ for lang in get_supported_languages():
+ resolved = t(key, lang)
+ assert resolved != key, f"{key} is not translated in {lang} (reason={reason})"
+ assert resolved.strip()
+
+
+def test_notice_failure_class_map_covers_exactly_the_per_fire_lane() -> None:
+ # The FAILED lane's own vocabulary, drift-pinned the same way the interrupted
+ # lane's is — and against a DERIVED set, so the two maps cannot both claim a
+ # reason or both drop one. ``PER_FIRE_INTERRUPT_REASONS`` is the settlement and
+ # sweep vocabularies minus ``RUN_INTERRUPTION_REASONS``, i.e. exactly the
+ # discriminator ``is_interruption`` applies, so a reason moved between lanes
+ # fails here instead of silently losing its label.
+ assert set(NOTICE_FAILURE_CLASS_I18N_KEYS) == set(PER_FIRE_INTERRUPT_REASONS), (
+ "unlabelled: "
+ f"{sorted(set(PER_FIRE_INTERRUPT_REASONS) - set(NOTICE_FAILURE_CLASS_I18N_KEYS))}; "
+ "stale: "
+ f"{sorted(set(NOTICE_FAILURE_CLASS_I18N_KEYS) - set(PER_FIRE_INTERRUPT_REASONS))}"
+ )
+ # And the two maps are disjoint: one reason, one lane, one label.
+ assert not set(NOTICE_FAILURE_CLASS_I18N_KEYS) & set(NOTICE_REASON_I18N_KEYS)
+
+
+def test_a_dispatch_failure_class_joins_the_per_fire_lane_and_not_the_interrupted_one() -> None:
+ """#1060's class has to land in the FAILED lane, and the derivation has to say why.
+
+ The pin above is an equality between two sets that both grow, so it stays green for
+ a reason added correctly AND for one added to the wrong source vocabulary. This is
+ the direction pin for ``delivery_target_missing`` specifically, and each clause is a
+ thing that would silently break if it were placed in the interrupted lane instead:
+
+ * ``failure_id`` would become ``interrupt:{run}:{reason}`` rather than the bare run
+ id the live path's dedup looks up, so the notice would be re-sent;
+ * every fire of a permanently broken definition would notify separately, since the
+ interruption lane bypasses streak suppression;
+ * the definition would read HEALTHY, because the health window excludes
+ out-of-band interruptions.
+
+ All three are the opposite of what #1060 asked for. It is a per-fire verdict about
+ the definition, so it belongs where the per-fire verdicts are.
+ """
+
+ from core.run_settlement import (
+ DISPATCH_FAILURE_REASONS,
+ INTERRUPT_REASON_DELIVERY_TARGET_MISSING,
+ )
+
+ assert INTERRUPT_REASON_DELIVERY_TARGET_MISSING in DISPATCH_FAILURE_REASONS
+ assert INTERRUPT_REASON_DELIVERY_TARGET_MISSING not in RUN_INTERRUPTION_REASONS, (
+ "the interrupted lane would change the notice's identity, unsuppress it, and "
+ "take it out of derived health"
+ )
+ assert INTERRUPT_REASON_DELIVERY_TARGET_MISSING in PER_FIRE_INTERRUPT_REASONS, (
+ "so the derived per-fire set has to admit it, or its label has nowhere to live"
+ )
+ assert INTERRUPT_REASON_DELIVERY_TARGET_MISSING in NOTICE_FAILURE_CLASS_I18N_KEYS
+
+ # And it is NOT a settlement or a sweep reason: those vocabularies describe a run
+ # that was dispatched, and a run whose target could not be resolved never was. A
+ # ``harness.run.interrupted.*`` twin would also be copy no caller renders, because
+ # the run's ``error`` column already holds the exception's own text.
+ assert INTERRUPT_REASON_DELIVERY_TARGET_MISSING not in SETTLEMENT_I18N_KEYS
+ assert INTERRUPT_REASON_DELIVERY_TARGET_MISSING not in SWEEP_I18N_KEYS
+
+
[email protected]("reason,key", sorted(NOTICE_FAILURE_CLASS_I18N_KEYS.items()))
+def test_every_notice_failure_class_label_resolves(reason: str, key: str) -> None:
+ # No generic fallback here by design (``notice_failure_class_i18n_key`` returns
+ # ``None`` and the line is omitted), so every mapped label has to be real in
+ # every language or the class line prints a dotted path.
+ for lang in get_supported_languages():
+ resolved = t(key, lang)
+ assert resolved != key, f"{key} is not translated in {lang} (reason={reason})"
+ assert resolved.strip()
+ assert reason not in resolved, (
+ f"{key} leaks the wire value {reason!r} into product copy in {lang}"
+ )
+
+
[email protected]("platform,key", sorted(NOTICE_ORIGIN_PLATFORM_I18N_KEYS.items()))
+def test_every_notice_origin_platform_label_resolves(platform: str, key: str) -> None:
+ # The origin line renders the platform INSIDE a translated sentence, so an
+ # unresolved key would print a dotted path where a product name belongs. Same
+ # contract as the failure-class labels, and the same reason the map is closed: an
+ # unmapped platform takes no line rather than leaking its wire value.
+ for lang in get_supported_languages():
+ resolved = t(key, lang)
+ assert resolved != key, f"{key} is not translated in {lang} (platform={platform})"
+ assert resolved.strip()
+
+
+def test_the_origin_platform_map_covers_every_registered_platform() -> None:
+ """Drift pin against the platform registry, in BOTH directions.
+
+ A platform Avibe can run on but cannot name has no origin line at all, which is a
+ silent hole rather than a visible one. A label for a platform that does not exist is
+ copy no caller can reach. Note the wire value is ``lark``, not ``feishu``:
+ ``modules/im/feishu.py`` builds its contexts with ``platform="lark"``, and keying the
+ map on the product name would have made every Feishu origin unnameable.
+ """
+
+ from config.platform_registry import PLATFORM_REGISTRY
+
+ assert set(NOTICE_ORIGIN_PLATFORM_I18N_KEYS) == set(PLATFORM_REGISTRY), (
+ "missing labels: "
+ f"{sorted(set(PLATFORM_REGISTRY) - set(NOTICE_ORIGIN_PLATFORM_I18N_KEYS))}; "
+ "labels for unknown platforms: "
+ f"{sorted(set(NOTICE_ORIGIN_PLATFORM_I18N_KEYS) - set(PLATFORM_REGISTRY))}"
+ )
+
+
+def test_the_origin_lines_keep_their_placeholders_in_both_languages() -> None:
+ """Every origin sentence has to carry the ids it exists to render.
+
+ A translation that drops ``{channel}`` or ``{url}`` silently renders a notice that
+ names no conversation and offers no link — the exact hole this round closes, but
+ reintroduced in one bundle only, which is the failure mode ``vibe/i18n``'s
+ English fallback hides.
+ """
+
+ expected = {
+ "harness.notice.origin": {"{origin}"},
+ "harness.notice.originLink": {"{url}"},
+ "harness.notice.originChannel": {"{platform}", "{channel}"},
+ "harness.notice.originChannelThread": {"{platform}", "{channel}", "{thread}"},
+ "harness.notice.originDirect": {"{platform}", "{user}"},
+ }
+ for lang in ("en", "zh"):
+ bundle = _bundle(lang)
+ for key, placeholders in expected.items():
+ assert key in bundle, f"{key} missing from {lang}"
+ missing = [name for name in placeholders if name not in bundle[key]]
+ assert not missing, f"{lang} {key} dropped {missing}: {bundle[key]!r}"
diff --git a/tests/test_im_post_send_bookkeeping.py b/tests/test_im_post_send_bookkeeping.py
new file mode 100644
index 000000000..31b097b4d
--- /dev/null
+++ b/tests/test_im_post_send_bookkeeping.py
@@ -0,0 +1,190 @@
+"""Post-send bookkeeping must never destroy an already-delivered message id.
+
+Every IM adapter send path does the same three things in order: hand the payload
+to the platform transport, run local bookkeeping (``sessions.mark_thread_active``
+for threaded targets), then return the native message id. The transport call is
+the point of no return -- once it succeeds the user HAS the message.
+
+If the bookkeeping step is allowed to raise, the exception replaces the return
+value and reaches the caller's blanket handler
+(``core/message_dispatcher.py`` notify/result send stages), which records a send
+failure with NO delivery evidence. Anything that owes a durable notice for that
+message then sees "never delivered" and re-sends it: a systematic duplicate on
+every bookkeeping failure, not the crash-only at-least-once residual.
+
+``modules/im/discord.py`` (``send_message`` / ``send_message_with_buttons``)
+already guards the call with ``try/except Exception: pass``. These tests pin the
+same invariant for Slack and Feishu, which were missed. Platform clients are
+stubbed, so nothing touches the network.
+
+Subordinate context: this is the ack/delivery lane that HFR-079's family covers
+at the dispatcher/notice level; these cases are adapter-level unit pins and
+introduce no new scenario id.
+"""
+
+from __future__ import annotations
+
+import sys
+import types
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from config.v2_config import LarkConfig, SlackConfig
+from modules.im.base import InlineButton, InlineKeyboard, MessageContext
+from modules.im.feishu import FeishuBot
+from modules.im.slack import SlackBot
+
+
+class _Boom(RuntimeError):
+ """Whatever the session store can raise (locked SQLite, IO error, ...)."""
+
+
+def _raising_sessions() -> SimpleNamespace:
+ return SimpleNamespace(mark_thread_active=Mock(side_effect=_Boom("session store unavailable")))
+
+
+class SlackPostSendBookkeepingTests(unittest.IsolatedAsyncioTestCase):
+ """Slack: every send path returning a ``ts`` survives a bookkeeping raise."""
+
+ def _bot(self) -> SlackBot:
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ slack._ensure_clients = lambda: None # type: ignore[method-assign]
+ slack.settings_manager = object()
+ slack.sessions = _raising_sessions()
+ return slack
+
+ @staticmethod
+ def _threaded_context() -> MessageContext:
+ return MessageContext(user_id="U1", channel_id="C1", thread_id="1710000000.000100", platform="slack")
+
+ async def test_send_message_returns_ts_when_bookkeeping_raises(self):
+ slack = self._bot()
+ sent = []
+
+ async def fake_prepared(context, text, parse_mode=None, reply_to=None):
+ sent.append(text)
+ return {"ts": "ts-plain"}
+
+ slack._send_prepared_text_message = fake_prepared # type: ignore[method-assign]
+
+ message_id = await slack.send_message(self._threaded_context(), "delivered body")
+
+ self.assertEqual(sent, ["delivered body"])
+ self.assertEqual(message_id, "ts-plain")
+ slack.sessions.mark_thread_active.assert_called_once()
+
+ async def test_status_bubble_returns_ts_when_bookkeeping_raises(self):
+ slack = self._bot()
+ sent = []
+
+ async def fake_post(context, kwargs, log_label=None):
+ sent.append(kwargs)
+ return {"ts": "ts-bubble"}
+
+ slack._post_message_with_dm_recovery = fake_post # type: ignore[method-assign]
+
+ # A ``subtext`` routes send_message through _send_status_message.
+ message_id = await slack.send_message(self._threaded_context(), "body", subtext="⏳ 5s")
+
+ self.assertEqual(len(sent), 1)
+ self.assertEqual(message_id, "ts-bubble")
+ slack.sessions.mark_thread_active.assert_called_once()
+
+ async def test_markdown_message_returns_ts_when_bookkeeping_raises(self):
+ slack = self._bot()
+ sent = []
+
+ async def fake_post(context, kwargs, log_label=None):
+ sent.append(kwargs)
+ return {"ts": "ts-markdown"}
+
+ slack._post_message_with_dm_recovery = fake_post # type: ignore[method-assign]
+
+ message_id = await slack.send_markdown_message(self._threaded_context(), "# Result")
+
+ self.assertEqual(len(sent), 1)
+ self.assertEqual(message_id, "ts-markdown")
+ slack.sessions.mark_thread_active.assert_called_once()
+
+ async def test_message_with_buttons_returns_ts_when_bookkeeping_raises(self):
+ slack = self._bot()
+ sent = []
+
+ async def fake_post(context, kwargs, log_label=None):
+ sent.append(kwargs)
+ return {"ts": "ts-buttons"}
+
+ slack._post_message_with_dm_recovery = fake_post # type: ignore[method-assign]
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Stop", callback_data="stop")]])
+
+ message_id = await slack.send_message_with_buttons(self._threaded_context(), "pick one", keyboard)
+
+ self.assertEqual(len(sent), 1)
+ self.assertEqual(message_id, "ts-buttons")
+ slack.sessions.mark_thread_active.assert_called_once()
+
+
+class _FakeLarkResponse:
+ def __init__(self, message_id: str) -> None:
+ self.data = types.SimpleNamespace(message_id=message_id, chat_id="oc_chat")
+ self.code = 0
+ self.msg = "ok"
+
+ def success(self) -> bool:
+ return True
+
+
+class FeishuPostSendBookkeepingTests(unittest.IsolatedAsyncioTestCase):
+ """Feishu: the threaded reply paths survive a bookkeeping raise.
+
+ Only the ``root_id`` branches are covered because the trailing
+ ``mark_thread_active`` blocks in ``send_message`` / ``send_message_with_buttons``
+ sit after the early ``return`` taken whenever a thread target exists, so no
+ caller can reach them; they are wrapped for parity, not for a live path.
+ """
+
+ def _bot(self, message_id: str) -> tuple[FeishuBot, types.SimpleNamespace]:
+ bot = FeishuBot(LarkConfig(app_id="app-id", app_secret="app-secret"))
+ bot._ensure_client = lambda: None # type: ignore[method-assign]
+ message = types.SimpleNamespace(
+ acreate=AsyncMock(return_value=_FakeLarkResponse(message_id)),
+ areply=AsyncMock(return_value=_FakeLarkResponse(message_id)),
+ )
+ bot._lark_client = types.SimpleNamespace(
+ im=types.SimpleNamespace(v1=types.SimpleNamespace(message=message))
+ )
+ bot.settings_manager = object()
+ bot.sessions = _raising_sessions()
+ return bot, message
+
+ @staticmethod
+ def _threaded_context() -> MessageContext:
+ return MessageContext(user_id="ou_1", channel_id="oc_chat", thread_id="om_root", platform="lark")
+
+ async def test_thread_reply_returns_message_id_when_bookkeeping_raises(self):
+ bot, message = self._bot("om_reply")
+
+ result = await bot.send_message(self._threaded_context(), "delivered body")
+
+ message.areply.assert_awaited_once()
+ self.assertEqual(result, "om_reply")
+ bot.sessions.mark_thread_active.assert_called_once()
+
+ async def test_thread_card_reply_returns_message_id_when_bookkeeping_raises(self):
+ bot, message = self._bot("om_card")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Stop", callback_data="stop")]])
+
+ result = await bot.send_message_with_buttons(self._threaded_context(), "pick one", keyboard)
+
+ message.areply.assert_awaited_once()
+ self.assertEqual(result, "om_card")
+ bot.sessions.mark_thread_active.assert_called_once()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 6561bbc63..d6cf83c9c 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -611,6 +611,110 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn("[✅ Yes]", persist.call_args.args[2])
self.assertIn("Pick one", persist.call_args.args[2])
+ async def test_workbench_run_settles_only_after_result_persistence(self):
+ """A callback child stays pending until its Workbench receipt exists."""
+
+ controller = _StubController(platform="avibe")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._record_agent_run_terminal_result = mock.Mock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="ses-1",
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": "ses-1",
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "callback-run",
+ },
+ )
+
+ def _persist(*_args, **_kwargs):
+ dispatcher._record_agent_run_terminal_result.assert_not_called()
+ return {"id": "persisted-result"}
+
+ with mock.patch("core.message_dispatcher.persist_agent_message", side_effect=_persist):
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "callback complete",
+ output=MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ run_id="callback-run",
+ ),
+ )
+
+ dispatcher._record_agent_run_terminal_result.assert_called_once()
+
+ async def test_workbench_persistence_failure_does_not_settle_the_run(self):
+ controller = _StubController(platform="avibe")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._record_agent_run_terminal_result = mock.Mock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="ses-1",
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": "ses-1",
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "callback-run",
+ },
+ )
+
+ with mock.patch(
+ "core.message_dispatcher.persist_agent_message",
+ side_effect=RuntimeError("write failed"),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "write failed"):
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "callback complete",
+ output=MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ run_id="callback-run",
+ ),
+ )
+
+ dispatcher._record_agent_run_terminal_result.assert_not_called()
+
+ async def test_workbench_duplicate_persistence_receipt_can_settle_the_run(self):
+ controller = _StubController(platform="avibe")
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._record_agent_run_terminal_result = mock.Mock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="ses-1",
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": "ses-1",
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "callback-run",
+ },
+ )
+
+ with (
+ mock.patch("core.message_dispatcher.persist_agent_message", return_value=None),
+ mock.patch(
+ "core.message_dispatcher.agent_message_exists",
+ side_effect=[False, True],
+ ),
+ ):
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "callback complete",
+ output=MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ run_id="callback-run",
+ idempotency_key="stable-output",
+ ),
+ )
+
+ dispatcher._record_agent_run_terminal_result.assert_called_once()
+
async def test_suppressed_delivery_is_persisted_without_platform_send(self):
controller = _StubController(platform="slack")
dispatcher = ConsolidatedMessageDispatcher(controller)
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index ba8c493c6..7ebdbe6af 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -1558,3 +1558,98 @@ class HarnessRunResultTextTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(settled["result_text"], "recovered background result")
self.assertEqual(settled["status"], "succeeded")
self.assertIsNone(store.get_run(f"activity:claude:{activity.id}"))
+
+
+class _AdapterShapedIMClient(_StubIMClient):
+ """An IM client shaped like a real adapter: transport, bookkeeping, return id.
+
+ ``swallow_bookkeeping_error`` selects the pre-fix vs post-fix adapter shape.
+ """
+
+ def __init__(self, *, swallow_bookkeeping_error: bool):
+ super().__init__()
+ self.swallow_bookkeeping_error = swallow_bookkeeping_error
+ self.delivered = []
+
+ async def send_message(self, context, text, parse_mode=None, reply_to=None):
+ # Point of no return: the platform accepted the payload, the user HAS it.
+ message_id = f"bot-msg-{self._next_id}"
+ self._next_id += 1
+ self.delivered.append(message_id)
+ # Post-send local bookkeeping (sessions.mark_thread_active) blows up.
+ try:
+ raise RuntimeError("session store unavailable")
+ except RuntimeError:
+ if not self.swallow_bookkeeping_error:
+ raise
+ return message_id
+
+
+class PostSendBookkeepingDeliveryEvidenceTests(unittest.IsolatedAsyncioTestCase):
+ """The dispatcher cannot tell a bookkeeping raise from a failed send.
+
+ ``emit_agent_message`` only sees the adapter's return value or its exception,
+ so an adapter that lets post-send bookkeeping escape converts "delivered but
+ unbookkept" into "never delivered": the run is recorded with ``message_id
+ None`` even though the transport handed the message to the user, and whoever
+ owes a durable notice for it re-sends a duplicate.
+
+ That is why the fix has to live in the adapter (``modules/im/discord.py``
+ already guards it; Slack and Feishu now match) and cannot be papered over in
+ ``core/message_dispatcher.py``: the id is destroyed before it can escape.
+ Adapter-level coverage lives in ``tests/test_im_post_send_bookkeeping.py``;
+ these two cases pin the dispatcher-side consequence of each shape.
+
+ Subordinate context: ack/delivery lane, HFR-079's family. No new scenario id.
+ """
+
+ def _run(self, client):
+ controller = _StubController()
+ controller.im_client = client
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-bookkeeping",
+ },
+ )
+ calls = []
+
+ class _Store:
+ def record_run_message(self, run_id, *, text, message_id=None, terminal_status=None):
+ calls.append(("record", run_id, text, message_id, terminal_status))
+
+ def close(self):
+ pass
+
+ return dispatcher, context, calls, _Store
+
+ async def test_escaping_bookkeeping_error_loses_evidence_for_a_delivered_message(self):
+ client = _AdapterShapedIMClient(swallow_bookkeeping_error=False)
+ dispatcher, context, calls, store_cls = self._run(client)
+
+ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=store_cls()):
+ message_id = await dispatcher.emit_agent_message(context, "result", "delivered body")
+
+ # The transport delivered on the very first call, but because the id never
+ # escaped the adapter the dispatcher read it as a failed send and walked its
+ # fallback ladder, pushing the SAME logical message to the user again. One
+ # bookkeeping failure, several user-visible copies, and no evidence at all.
+ self.assertEqual(client.delivered[0], "bot-msg-1")
+ self.assertGreater(len(client.delivered), 1)
+ self.assertIsNone(message_id)
+ self.assertEqual(calls, [("record", "run-bookkeeping", "delivered body", None, "succeeded")])
+
+ async def test_swallowed_bookkeeping_error_keeps_evidence_for_a_delivered_message(self):
+ client = _AdapterShapedIMClient(swallow_bookkeeping_error=True)
+ dispatcher, context, calls, store_cls = self._run(client)
+
+ with patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=store_cls()):
+ message_id = await dispatcher.emit_agent_message(context, "result", "delivered body")
+
+ self.assertEqual(client.delivered, ["bot-msg-1"])
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertEqual(calls, [("record", "run-bookkeeping", "delivered body", "bot-msg-1", "succeeded")])
diff --git a/tests/test_message_type_catalog.py b/tests/test_message_type_catalog.py
index 5d3094a74..a0f30f3cc 100644
--- a/tests/test_message_type_catalog.py
+++ b/tests/test_message_type_catalog.py
@@ -46,11 +46,31 @@ def _catalog_types() -> tuple[str, ...]:
return tuple(_catalog_document()["types"])
-def _sequence_params(statement: Any) -> set[tuple[str, ...]]:
+def _message_type_sequences(statement: Any) -> set[tuple[str, ...]]:
+ """Every message-TYPE set a query binds, i.e. each expanding IN/NOT IN over
+ ``messages.c.type``.
+
+ Scoped to that column by bound-parameter NAME: SQLAlchemy names an expanding
+ parameter after the column it compares, so ``messages.c.type.in_(...)`` binds
+ ``type_1``, ``type_2``, … and no other column in these queries compiles to that
+ prefix. The scoping is the point — this module's contract is the message-type
+ catalog, and these queries also bind sequences over OTHER columns whose contents
+ are somebody else's decision:
+
+ ``list_inbox_sessions`` / ``unread_counts`` / ``unread_counts_by_session`` now also
+ bind ``agent_sessions.c.visibility`` (``INBOX_SESSION_VISIBILITIES`` ==
+ ``('foreground', 'system')``) since the reserved workspace-notifications row became
+ a ``system`` surface — a session-projection decision pinned by
+ ``tests/test_workspace_system_session.py``. Collecting every sequence indiscriminately
+ made that legitimate change fail three catalog assertions, which says the filter
+ belongs here rather than in the expectations: adding the visibility tuple to each
+ expected set would have this module re-pin a contract it does not own (and go red
+ again on the next non-type IN-list).
+ """
return {
tuple(value)
- for value in statement.compile().params.values()
- if isinstance(value, (list, tuple))
+ for name, value in statement.compile().params.items()
+ if isinstance(value, (list, tuple)) and (name == "type" or name.startswith("type_"))
}
@@ -78,7 +98,7 @@ def test_searchable_types_match_current_default_query() -> None:
expected = ("user", "harness", "annotation", "result")
assert types_with("searchable") == expected
- assert _sequence_params(connection.statements[-1]) == {expected}
+ assert _message_type_sequences(connection.statements[-1]) == {expected}
def test_inbox_activity_types_match_current_constant() -> None:
@@ -90,7 +110,7 @@ def test_inbox_activity_types_match_current_constant() -> None:
def test_inbox_preview_and_settlement_types_match_current_query() -> None:
connection = _CaptureConnection()
messages_service.list_inbox_sessions(connection)
- current_query_sets = _sequence_params(connection.statements[-1])
+ current_query_sets = _message_type_sequences(connection.statements[-1])
expected_preview = ("result", "notify", "error")
expected_settlement = ("result", "notify", "error", "silent")
@@ -116,7 +136,7 @@ def test_unread_types_match_current_queries(query: Any) -> None:
expected = ("result",)
assert types_with("unread") == expected
- assert _sequence_params(connection.statements[-1]) == {expected}
+ assert _message_type_sequences(connection.statements[-1]) == {expected}
def test_input_turn_pairs_match_current_constant() -> None:
diff --git a/tests/test_origin_links.py b/tests/test_origin_links.py
new file mode 100644
index 000000000..458c687c4
--- /dev/null
+++ b/tests/test_origin_links.py
@@ -0,0 +1,175 @@
+"""The honesty table for creation-origin deep links (``core/origin_links.py``).
+
+Subordinate to HFR-094's notice-body family — no new scenario id this round; the
+localized notice-context contract these links serve is round 14's gate item 3 (review
+comment 5121007240).
+
+ONE RULE, and every test below is a case of it: a link is offered only when every id
+that platform's permalink grammar requires was actually captured. The failure mode this
+guards is not a missing link — it is a PRESENT one that does not resolve, which converts
+"I cannot tell where this came from" into "Avibe told me where and it was wrong".
+
+There is deliberately no red baseline for this file. It characterises a new pure
+module, so at any earlier commit it would only raise ``ImportError``, and an
+``ImportError`` is not evidence of a defect. The reds that ARE evidence live with the
+capture round-trip (``tests/test_caller_context.py``) and the rendered body
+(``tests/test_harness_failure_visibility.py``).
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.failure_notices import NOTICE_ORIGIN_PLATFORM_I18N_KEYS
+from core.origin_links import origin_link
+
+SLACK_TS = "1710000000.000100"
+SLACK_PARENT_TS = "1709999999.000900"
+
+
+def test_a_slack_channel_message_links_to_its_archive_path() -> None:
+ """The ts loses its dot and nothing else about it is transformed."""
+
+ assert origin_link("slack", "C0123", SLACK_TS, SLACK_TS, "T0999") == (
+ "https://slack.com/archives/C0123/p1710000000000100"
+ )
+
+
+def test_a_slack_thread_reply_links_into_the_thread_not_the_channel() -> None:
+ """``thread_ts``/``cid`` are what make the link open the thread it was created in.
+
+ The Slack adapter defaults a non-threaded message's ``thread_id`` to the message's
+ own ts, so ``thread_id != message_id`` is the platform's own encoding of "this is a
+ reply" — and the query params are added on exactly that condition rather than
+ whenever a thread id happens to be present.
+ """
+
+ link = origin_link("slack", "C0123", SLACK_PARENT_TS, SLACK_TS, "T0999")
+ assert link == (
+ "https://slack.com/archives/C0123/p1710000000000100"
+ f"?thread_ts={SLACK_PARENT_TS}&cid=C0123"
+ )
+
+ assert "?" not in str(origin_link("slack", "C0123", SLACK_TS, SLACK_TS, "T0999")), (
+ "a top-level message must not be dressed up as a thread reply"
+ )
+
+
+ "channel_id,message_id,missing",
+ [
+ ("", SLACK_TS, "the channel"),
+ ("C0123", "", "the message ts"),
+ ("", "", "both ids"),
+ ],
+)
+def test_slack_refuses_without_both_ids(channel_id: str, message_id: str, missing: str) -> None:
+ assert origin_link("slack", channel_id, None, message_id, "T0999") is None, (
+ f"a Slack archive path cannot be built without {missing}"
+ )
+
+
+def test_a_discord_guild_message_links_to_the_three_part_channel_path() -> None:
+ assert origin_link("discord", "555", None, "777", "999") == (
+ "https://discord.com/channels/999/555/777"
+ )
+
+
+def test_discord_refuses_a_dm_rather_than_addressing_it_as_me() -> None:
+ """``@me`` is valid Discord syntax and is exactly why it must not be used.
+
+ A ``channels/@me/<c>/<m>`` path resolves for the one user whose DM it is, so it
+ would read as a working link while being unfollowable for anybody else — including
+ the workspace inbox, which is not a person at all. A DM has no guild
+ (``message.guild is None``), so the honest answer is no link.
+ """
+
+ link = origin_link("discord", "555", None, "777", None)
+ assert link is None, f"a guild-less Discord origin gets no link: {link}"
+ assert "@me" not in str(link)
+
+
+ "channel_id,message_id",
+ [("", "777"), ("555", "")],
+)
+def test_discord_refuses_without_channel_and_message(channel_id: str, message_id: str) -> None:
+ assert origin_link("discord", channel_id, None, message_id, "999") is None
+
+
+def test_a_telegram_supergroup_message_links_through_the_internal_id() -> None:
+ """``t.me/c/<id without the -100 prefix>/<message id>``."""
+
+ assert origin_link("telegram", "-1001234567890", None, "42", None) == (
+ "https://t.me/c/1234567890/42"
+ )
+
+
+ "channel_id,why",
+ [
+ ("123456789", "a private chat id has no t.me/c form at all"),
+ ("-123456789", "a basic group id is not a -100 supergroup id"),
+ ("-100", "the prefix alone leaves no internal id"),
+ ("", "no chat id was captured"),
+ ],
+)
+def test_telegram_refuses_any_chat_without_the_supergroup_prefix(channel_id: str, why: str) -> None:
+ """Stripping four characters off an id that never carried the prefix would address
+ an UNRELATED chat, which is the worst outcome available here."""
+
+ assert origin_link("telegram", channel_id, None, "42", None) is None, why
+
+
+def test_telegram_refuses_without_a_message_id() -> None:
+ assert origin_link("telegram", "-1001234567890", None, "", None) is None
+
+
[email protected]("platform", ["lark", "wechat"])
+def test_platforms_with_no_public_permalink_get_no_link(platform: str) -> None:
+ """Feishu/Lark and WeChat expose no stable message permalink an external notice can
+ address, so there is nothing to build — the origin TEXT still names them."""
+
+ assert origin_link(platform, "oc_abc", None, "om_abc", "tenant") is None
+
+
+def test_a_workbench_origin_gets_no_link_even_though_it_has_a_location() -> None:
+ """The refusal that is about REACHABILITY rather than about a missing id.
+
+ An ``avibe`` origin is the Workbench, which is addressable — but only as the local
+ setup host, and a ``http://127.0.0.1:<port>/…`` URL pasted into a Slack DM or a
+ phone push notification is not honestly followable from where the notice is read.
+ """
+
+ assert origin_link("avibe", "proj-1", None, "msg-1", None) is None
+
+
[email protected]("platform", ["", None, "mystery_platform", "SLACK"])
+def test_an_unrecognised_platform_never_gets_a_guessed_url(platform) -> None:
+ """Including the case-mismatched value: wire values are matched exactly, because a
+ permalink grammar is not something to infer from a near-miss."""
+
+ assert origin_link(platform, "C0123", None, SLACK_TS, "T0999") is None
+
+
+def test_every_linkable_platform_is_a_platform_the_notice_can_also_name() -> None:
+ """Drift pin between the two closed maps.
+
+ A platform that produces a link but has no display label would render a bare URL
+ with no sentence around it; a label with no link is fine and expected (Lark, WeChat,
+ the Workbench). So the link builder's vocabulary must be a SUBSET of the notice's.
+ """
+
+ linkable = {"slack", "discord", "telegram"}
+ assert linkable <= set(NOTICE_ORIGIN_PLATFORM_I18N_KEYS), (
+ "a platform that can be linked must also be nameable in the notice copy"
+ )
+ for platform in linkable:
+ assert origin_link(platform, "c", None, "m", "w") is not None or platform == "telegram", (
+ f"{platform} must be able to produce a link given a full id set"
+ )
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 41f8fc3a5..5a3df0dbd 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import json
+import sqlite3
import sys
from contextlib import suppress
from datetime import datetime, timedelta, timezone
@@ -7875,13 +7876,20 @@ def _binding_env(tmp_path: Path, monkeypatch, *, backends=("claude", "codex"), d
return db_path
-def _binding_service(tmp_path: Path, store: ScheduledTaskStore, calls: list) -> ScheduledTaskService:
+def _binding_service(
+ tmp_path: Path,
+ store: ScheduledTaskStore,
+ calls: list,
+ *,
+ language: str = "en",
+) -> ScheduledTaskService:
async def _handle_scheduled_message(context, message, parsed_session_key=None):
calls.append(message)
return None
settings_manager = SimpleNamespace(get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_kw: None))
controller = SimpleNamespace(
+ config=SimpleNamespace(language=language),
platform_settings_managers={"slack": settings_manager},
message_handler=SimpleNamespace(handle_scheduled_message=_handle_scheduled_message),
)
@@ -8096,14 +8104,14 @@ def _spy_binding_notices(service: ScheduledTaskService) -> list:
return notices
-def test_execute_task_pauses_and_notifies_when_pinned_session_is_missing(
+def test_execute_task_notifies_then_pauses_after_three_unresolvable_failures(
tmp_path: Path, monkeypatch
) -> None:
"""HFR-054 — an unresolvable pinned session must not fire forever.
``resolve_session_id_target`` raises, ``_execute_task`` records the error and
- leaves ``enabled=1``, so the definition re-fires and re-fails on every cron
- minute with nobody told. The backstop pauses it and notifies once.
+ leaves ``enabled=1``, so the first failure must be visible while the stable
+ failure code drives the three-consecutive-failure auto-pause policy.
"""
_binding_env(tmp_path, monkeypatch)
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
@@ -8121,7 +8129,11 @@ def test_execute_task_pauses_and_notifies_when_pinned_session_is_missing(
service = _binding_service(tmp_path, store, calls)
notices = _spy_binding_notices(service)
- asyncio.run(service._run_task(task.id))
+ for attempt in range(1, 4):
+ asyncio.run(service._run_task(task.id))
+ current = store.get_task(task.id)
+ assert current is not None
+ assert current.enabled is (attempt < 3)
updated = store.get_task(task.id)
assert updated is not None
@@ -8129,8 +8141,52 @@ def test_execute_task_pauses_and_notifies_when_pinned_session_is_missing(
assert updated.last_error
assert "sesdoesnotexist" in updated.last_error
assert not calls
- assert len(notices) == 1
- assert notices[0].action == "paused"
+ assert [notice.action for notice in notices] == ["failing", "paused"]
+ failed_runs = service.request_store.list_runs(status="failed")
+ assert len(failed_runs) == 3
+ assert {(run.get("metadata") or {}).get("failure_code") for run in failed_runs} == {"unresolvable_target"}
+
+
+ ("language", "retry_copy", "paused_copy"),
+ [
+ ("en", "cannot accept a turn (1/3)", "paused: pinned agent session"),
+ ("zh", "无法接收请求(1/3)", "已暂停:绑定的 Agent 会话"),
+ ],
+)
+def test_unresolvable_target_errors_follow_the_configured_language(
+ tmp_path: Path,
+ monkeypatch,
+ language: str,
+ retry_copy: str,
+ paused_copy: str,
+) -> None:
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ service = _binding_service(tmp_path, store, [], language=language)
+
+ asyncio.run(service._run_task(task.id))
+ retry_error = store.get_task(task.id).last_error
+ assert retry_copy in retry_error
+ assert "sesdoesnotexist" in retry_error
+ assert f"vibe task update {task.id} --session-id <id>" in retry_error
+
+ asyncio.run(service._run_task(task.id))
+ asyncio.run(service._run_task(task.id))
+ paused_error = store.get_task(task.id).last_error
+ assert paused_copy in paused_error
+ assert "sesdoesnotexist" in paused_error
+ assert f"vibe task resume {task.id}" in paused_error
def test_existing_policy_never_rebinds(tmp_path: Path, monkeypatch) -> None:
@@ -8154,7 +8210,8 @@ def test_existing_policy_never_rebinds(tmp_path: Path, monkeypatch) -> None:
)
service = _binding_service(tmp_path, store, [])
- asyncio.run(service._run_task(task.id))
+ for _ in range(3):
+ asyncio.run(service._run_task(task.id))
updated = store.get_task(task.id)
assert updated is not None
@@ -8198,12 +8255,11 @@ def test_create_once_rebinds_when_session_deleted(tmp_path: Path, monkeypatch) -
assert notices[0].action == "rebound"
-def test_repeated_failures_do_not_notify_twice(tmp_path: Path, monkeypatch) -> None:
- """HFR-054 — one broken binding is one notification, not one per fire.
+def test_repeated_binding_failures_notify_only_on_state_transitions(tmp_path: Path, monkeypatch) -> None:
+ """HFR-054 — one broken binding is not one notification per fire.
- A daily cron on a dead session would otherwise notify daily. The dedup is
- keyed on the failure signature, so re-firing the same unresolved binding
- (a resumed-but-still-broken definition) stays quiet.
+ The first failing transition and the eventual pause are distinct; the middle
+ identical failure is deduplicated.
"""
_binding_env(tmp_path, monkeypatch)
store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
@@ -8220,13 +8276,88 @@ def test_repeated_failures_do_not_notify_twice(tmp_path: Path, monkeypatch) -> N
service = _binding_service(tmp_path, store, [])
notices = _spy_binding_notices(service)
+ for _ in range(3):
+ asyncio.run(service._run_task(task.id))
+
+ assert [notice.action for notice in notices] == ["failing", "paused"]
+
+
+def test_transient_resolver_errors_do_not_auto_pause_a_definition(tmp_path: Path, monkeypatch) -> None:
+ """Only the persisted unresolvable-target code drives auto-pause."""
+
+ from sqlalchemy.exc import OperationalError
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ service = _binding_service(tmp_path, store, [])
+
+ async def _transient_failure(**_kwargs):
+ raise OperationalError(
+ "SELECT agent_sessions.id ...",
+ {},
+ sqlite3.OperationalError("database is locked"),
+ )
+
+ service._execute_request = _transient_failure # type: ignore[method-assign]
+ for _ in range(3):
+ asyncio.run(service._run_task(task.id))
+
+ saved = store.get_task(task.id)
+ assert saved is not None and saved.enabled is True
+ assert all(
+ not (run.get("metadata") or {}).get("failure_code") for run in service.request_store.list_runs(status="failed")
+ )
+
+
+def test_a_success_resets_the_unresolvable_target_auto_pause_streak(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """The policy counts consecutive classified failures, not lifetime failures."""
+
+ _binding_env(tmp_path, monkeypatch)
+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")
+ task = store.add_task(
+ session_key="",
+ session_id="sesdoesnotexist",
+ session_policy="existing",
+ prompt="send digest",
+ schedule_type="cron",
+ cron="0 * * * *",
+ timezone_name="UTC",
+ deliver_key="slack::channel::C123",
+ )
+ service = _binding_service(tmp_path, store, [])
+
for _ in range(2):
- store.set_enabled(task.id, True)
- current = store.get_task(task.id)
- assert current is not None
- asyncio.run(service._execute_task(current, execution_id="exec-1", disable_one_shot=False))
+ asyncio.run(service._run_task(task.id))
- assert len(notices) == 1
+ current = store.get_task(task.id)
+ assert current is not None
+ queued = service.request_store.enqueue_task_run(
+ task.id,
+ source_kind="scheduler",
+ task=current,
+ )
+ claimed = service.request_store.claim(queued.id)
+ assert claimed is not None
+ service.request_store.complete(claimed, ok=True, task_id=task.id)
+
+ asyncio.run(service._run_task(task.id))
+
+ saved = store.get_task(task.id)
+ assert saved is not None and saved.enabled is True
+ latest = service.request_store.list_runs(status="failed")[-1]
+ assert "(1/3)" in str(latest.get("error") or "")
def test_rebind_preserves_model_of_the_deleted_session(tmp_path: Path, monkeypatch) -> None:
diff --git a/tests/test_session_archive.py b/tests/test_session_archive.py
index c967d38b1..8fa28ea14 100644
--- a/tests/test_session_archive.py
+++ b/tests/test_session_archive.py
@@ -478,6 +478,64 @@ def test_archived_session_excluded_from_inbox(monkeypatch, tmp_path: Path) -> No
assert sid not in messages_service.unread_counts_by_session(conn, platform="avibe")
+def test_the_reserved_workspace_notice_session_cannot_be_archived(tmp_path: Path) -> None:
+ """Archive is terminal, so it must not be reachable for the notice fallback row.
+
+ D5 rung (5) resolves to a reserved workspace-notifications session
+ (``storage.agent_session_rows.resolve_workspace_notice_session``). That row is
+ ``foreground`` on purpose — ``background`` is filtered out of
+ ``list_inbox_sessions``, which would hide the very notice the rung exists to show
+ — so it appears in ordinary session lists and is ONE CLICK from this function.
+
+ Archiving it is the worst reachable outcome in the whole ladder, and it is silent:
+ ``persist_agent_message``'s ``_session_row`` has no status filter, so a later
+ notice still WRITES its row and still earns its persisted receipt, so the rung
+ ACKS and the notice is marked ``sent`` — while ``list_inbox_sessions`` excludes
+ archived sessions, so there is no card, no ``inbox.session.updated`` and no push.
+ Every subsequent caller-less failure would be recorded as delivered into a surface
+ nothing displays, permanently. That is D1 broken again by D1's own fix.
+
+ Two independent defences, and this is the first: refuse at the door. The second is
+ ``resolve_workspace_notice_session``'s heal, pinned by
+ ``test_an_archived_workspace_notice_session_heals_instead_of_swallowing_the_notice``,
+ which covers a row archived out of band or before this guard existed.
+ """
+ from storage.agent_session_rows import (
+ WORKSPACE_NOTICE_SESSION_ID,
+ resolve_workspace_notice_session,
+ )
+
+ db_path = tmp_path / "vibe.sqlite"
+ engine = create_sqlite_engine(db_path)
+ SQLiteSessionsService(db_path).close() # create_all
+ with engine.begin() as conn:
+ reserved = resolve_workspace_notice_session(conn, title="Workspace notifications")
+ assert reserved == WORKSPACE_NOTICE_SESSION_ID
+
+ with engine.begin() as conn:
+ with pytest.raises(PermissionError) as exc:
+ wss.archive_session(conn, reserved)
+ # A machine code, because the localized copy lives in ``vibe/i18n`` at the HTTP
+ # boundary where the language is known — storage carries no user-facing text.
+ assert getattr(exc.value, "code", None) == "reserved_session"
+
+ with engine.connect() as conn:
+ assert wss.is_session_archived(conn, reserved) is False, (
+ "the refusal has to leave the row usable, not half-torn-down"
+ )
+ # And an ordinary session is unaffected: the guard is keyed on the reserved
+ # identity, not on "looks like a notification session".
+ service = SQLiteSessionsService(db_path)
+ try:
+ ordinary = _bind_session(service, channel="C9", anchor="slack_C9", native="nat1")
+ finally:
+ service.close()
+ with engine.begin() as conn:
+ wss.archive_session(conn, ordinary)
+ with engine.connect() as conn:
+ assert wss.is_session_archived(conn, ordinary) is True
+
+
def test_is_session_archived_flag(tmp_path: Path) -> None:
"""The shared write-guard accessor flips with the session's status."""
db_path = tmp_path / "vibe.sqlite"
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index d48289331..5216ad8fe 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -19,13 +19,14 @@ from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState,
from storage.db import SqliteInvalidationProbe, create_sqlite_engine
from storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state
from storage import migrations
+from storage.background import SQLiteBackgroundTaskStore
from storage.migrations import UnsafeDefaultStateMigrationError, background_tables_ready, run_migrations
from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
from vibe.message_types import build_partial_index_predicate
-HEAD_REVISION = "20260727_0038"
+HEAD_REVISION = "20260729_0042"
MESSAGE_PARTIAL_INDEX_PREDICATES = {
"ix_messages_inbox_activity": (
"session_id is not null and type not in "
@@ -1095,6 +1096,393 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path
assert "ix_agent_sessions_scope_status_activity" in agent_session_indexes
+#: The three ``agent_runs`` index migrations a head-shaped database must end up with,
+#: whichever route it took there. Named by module so the DDL is only ever read from the
+#: migration that owns it — the owed-notice index is an EXPRESSION index and SQLite only
+#: matches an index expression against a byte-identical query expression, so a retyped
+#: copy is an index that is built and silently ignored.
+AGENT_RUNS_INDEX_MIGRATION_MODULES = (
+ "storage.alembic.versions.20260728_0039_agent_runs_settled_at_index",
+ "storage.alembic.versions.20260728_0041_agent_runs_owed_notice_backoff_index",
+ "storage.alembic.versions.20260729_0042_agent_runs_definition_streak_index",
+)
+#: The superseded 0040 shape of ``ix_agent_runs_owed_notice``: same NAME, one fewer
+#: indexed expression. Read from its own module for the same no-retyping reason.
+SUPERSEDED_OWED_NOTICE_MIGRATION_MODULE = (
+ "storage.alembic.versions.20260728_0040_agent_runs_owed_notice_index"
+)
+_LIVE_QUERY_NOW = "2026-07-27T12:00:00+00:00"
+_LIVE_QUERY_DEFINITION = "task-repair"
+#: The middle failure of the seeded streak: bracketed by a success on both sides, so
+#: both of ``failure_streak_decision``'s boundary seeks have something to find.
+_LIVE_QUERY_RUN = "run-0002"
+
+
+def _agent_runs_index_names() -> tuple[str, str, str]:
+ """``(settled, owed_notice, streak)`` index names, from the migrations themselves."""
+
+ settled, owed_notice, streak = (
+ import_module(module)._INDEX for module in AGENT_RUNS_INDEX_MIGRATION_MODULES
+ )
+ return settled, owed_notice, streak
+
+
+def _assert_agent_runs_indexes_present(db_path: Path, *, route: str) -> None:
+ names = _agent_runs_index_names()
+ with sqlite3.connect(db_path) as conn:
+ present = {
+ row[0]
+ for row in conn.execute(
+ "select name from sqlite_master where type = 'index' and name in (?, ?, ?)",
+ names,
+ )
+ }
+ assert present == set(names), (
+ f"{route} left the agent_runs expression indexes missing: {sorted(set(names) - present)}"
+ )
+
+
+def _seed_settled_history(db_path: Path) -> None:
+ """A realistic settled history for the three live two-second-tick reads.
+
+ A failure streak closed by a success on either side, the earlier failure owing a
+ pending notice, so the eligibility lookup, the health window and the streak read
+ all have something to seek for. Written through the store rather than by hand so
+ every column the real writers populate is populated here too.
+ """
+
+ from storage.background import SQLiteBackgroundTaskStore
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ store.upsert_scheduled_task(
+ {
+ "id": _LIVE_QUERY_DEFINITION,
+ "name": _LIVE_QUERY_DEFINITION,
+ "prompt": "go",
+ "schedule_type": "cron",
+ "cron": "0 * * * *",
+ "enabled": True,
+ "created_at": "2026-07-27T00:00:00+00:00",
+ "updated_at": "2026-07-27T00:00:00+00:00",
+ }
+ )
+ history = (
+ ("run-0001", "succeeded"),
+ (_LIVE_QUERY_RUN, "failed"),
+ ("run-0003", "failed"),
+ ("run-0004", "succeeded"),
+ )
+ for position, (run_id, status) in enumerate(history):
+ instant = f"2026-07-27T{position + 1:02d}:00:00+00:00"
+ store.enqueue_run(
+ {
+ "id": run_id,
+ "request_type": "scheduled",
+ "status": status,
+ "definition_id": _LIVE_QUERY_DEFINITION,
+ "error": "boom" if status == "failed" else None,
+ "created_at": instant,
+ "completed_at": instant,
+ "metadata": (
+ {"owed_failure_notice": {"state": "pending", "attempts": 0}}
+ if run_id == _LIVE_QUERY_RUN
+ else {}
+ ),
+ }
+ )
+ finally:
+ store.close()
+
+
+def _agent_runs_query_plan(store, db_path: Path, call) -> str:
+ """Every ``agent_runs`` SELECT one call issues, with its plan, as one text."""
+
+ from sqlalchemy import event
+
+ captured: list[tuple[str, object]] = []
+
+ def _capture(conn, cursor, statement, parameters, context, executemany):
+ if "agent_runs" in statement and statement.strip().upper().startswith("SELECT"):
+ captured.append((statement, parameters))
+
+ event.listen(store.engine, "before_cursor_execute", _capture)
+ try:
+ call()
+ finally:
+ event.remove(store.engine, "before_cursor_execute", _capture)
+ assert captured, "the read issued no agent_runs SELECT"
+
+ raw = sqlite3.connect(str(db_path))
+ try:
+ return "\n".join(
+ str(row[-1])
+ for statement, parameters in captured
+ for row in raw.execute("EXPLAIN QUERY PLAN " + statement, parameters)
+ )
+ finally:
+ raw.close()
+
+
+def _assert_live_reads_seek_agent_runs_indexes(db_path: Path, *, route: str) -> None:
+ """The three live reads must SEEK these indexes on THIS database.
+
+ Index existence is not the property that matters — the property is that the
+ owed-notice drain, the health window and the streak read stop scanning run
+ history. So this asserts the CONSTRAINED TERMS of the plan, not just the index
+ name: a plan can name an index while the term stays a per-row filter (which is
+ exactly what 0040 shipped and 0041 fixed).
+ """
+
+ from storage.background import SQLiteBackgroundTaskStore
+
+ settled_index, owed_notice_index, streak_index = _agent_runs_index_names()
+ store = SQLiteBackgroundTaskStore(db_path)
+ try:
+ owed_plan = _agent_runs_query_plan(
+ store,
+ db_path,
+ lambda: store.list_owed_failure_notices(limit=10, now=_LIVE_QUERY_NOW),
+ )
+ health_plan = _agent_runs_query_plan(
+ store,
+ db_path,
+ lambda: store._health_rows([_LIVE_QUERY_DEFINITION], now=_LIVE_QUERY_NOW),
+ )
+ streak_plan = _agent_runs_query_plan(
+ store,
+ db_path,
+ lambda: store.failure_streak_decision(_LIVE_QUERY_DEFINITION, _LIVE_QUERY_RUN),
+ )
+ finally:
+ store.close()
+
+ # The owed-notice eligibility seek: both expression terms constrained, and the
+ # (created_at, id) order taken from the index so the LIMIT can short-circuit.
+ assert f"USING INDEX {owed_notice_index} (<expr>=? AND <expr><?)" in owed_plan, (
+ f"{route}: the owed-notice tick must seek {owed_notice_index} on both expression "
+ f"terms; plan was:\n{owed_plan}"
+ )
+ assert "SCAN agent_runs" not in owed_plan, (
+ f"{route}: the owed-notice tick must not scan run history; plan was:\n{owed_plan}"
+ )
+ assert "TEMP B-TREE" not in owed_plan, (
+ f"{route}: the owed-notice order must come from the index; plan was:\n{owed_plan}"
+ )
+
+ # The health window: the per-definition seek is bounded by (definition_id, settled).
+ assert f"USING INDEX {settled_index} (definition_id=? AND <expr>>?)" in health_plan, (
+ f"{route}: the health window must seek {settled_index} on both terms; plan was:"
+ f"\n{health_plan}"
+ )
+ assert "SCAN agent_runs" not in health_plan, (
+ f"{route}: the health window must not scan run history; plan was:\n{health_plan}"
+ )
+ assert "TEMP B-TREE" not in health_plan, (
+ f"{route}: the health window's newest-first order must come from the index; plan "
+ f"was:\n{health_plan}"
+ )
+
+ # The streak's boundary seeks: the (created_at, id) row value has to be a real
+ # index constraint, which only the streak index's third key can make it.
+ compact_streak = streak_plan.replace(" ", "")
+ assert streak_index in streak_plan, (
+ f"{route}: the streak read must seek {streak_index}; plan was:\n{streak_plan}"
+ )
+ assert f"{streak_index}(definition_id=?AND(created_at,id)<(?,?))" in compact_streak, (
+ f"{route}: the preceding success must be an indexed row-value seek; plan was:"
+ f"\n{streak_plan}"
+ )
+ assert f"{streak_index}(definition_id=?AND(created_at,id)>(?,?))" in compact_streak, (
+ f"{route}: the following success must be an indexed row-value seek; plan was:"
+ f"\n{streak_plan}"
+ )
+ assert "SCAN agent_runs" not in streak_plan, (
+ f"{route}: the streak read must not scan a definition's history; plan was:"
+ f"\n{streak_plan}"
+ )
+ assert "TEMP B-TREE" not in streak_plan, (
+ f"{route}: the streak's (created_at, id) order must come from the index; plan was:"
+ f"\n{streak_plan}"
+ )
+
+
+def _head_shaped_unversioned_db(tmp_path: Path, name: str = "vibe.sqlite") -> Path:
+ """A models-born database: head tables and columns, no ``alembic_version``.
+
+ This is the shape ``metadata.create_all`` produces, which is what every
+ ``background_tables_ready`` consumer accepts as ready — and it lacks all three
+ ``agent_runs`` expression indexes, because ``storage/models.py`` cannot express
+ them.
+ """
+
+ db_path = tmp_path / name
+ engine = create_sqlite_engine(db_path)
+ try:
+ metadata.create_all(engine)
+ finally:
+ engine.dispose()
+
+ with sqlite3.connect(db_path) as conn:
+ for index_name in _agent_runs_index_names():
+ conn.execute(f"drop index if exists {index_name}")
+ conn.commit()
+ assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None
+ assert not {
+ row[0]
+ for row in conn.execute(
+ "select name from sqlite_master where type = 'index' and name in (?, ?, ?)",
+ _agent_runs_index_names(),
+ )
+ }
+ return db_path
+
+
+def _reference_agent_runs_index_sql(tmp_path: Path) -> dict[str, str]:
+ """The three indexes as a full 0001-to-head replay writes them, byte for byte."""
+
+ reference_db = tmp_path / "reference.sqlite"
+ run_migrations(reference_db)
+ with sqlite3.connect(reference_db) as conn:
+ return {name: _index_sql(conn, name) for name in _agent_runs_index_names()}
+
+
+def test_head_shaped_stamp_replays_agent_runs_expression_indexes(tmp_path: Path) -> None:
+ """The migration ENTRYPOINT leaves a head-shaped database with the 0039-0042 indexes.
+
+ This test is GREEN FROM BIRTH — it is a refutation pin, not a fix; red-first does
+ not apply. The refuted premise was that ``_stamp_existing_initial_schema`` stamps a
+ head-shaped database "directly at ``LATEST_SCHEMA_REVISION``" and therefore never
+ executes the owed-notice / settlement / streak index migrations, leaving the
+ two-second owed-notice tick scanning run history. ``LATEST_SCHEMA_REVISION`` is
+ ``20260622_0023``, which is the stamp FLOOR, not head: after that stamp
+ ``_run_migrations_locked`` runs ``command.upgrade(cfg, "head")``, so 0024 through
+ 0042 — including all four index migrations — replay on exactly this path.
+
+ That refutation is about the MECHANISM, not about the class. Two lanes reach a
+ head-shaped database with no expression indexes and never come back through this
+ entrypoint: any ``metadata.create_all`` consumer satisfies
+ ``background_tables_ready`` (which checks tables and columns, never indexes), and
+ the day ``LATEST_SCHEMA_REVISION`` moves past 0038 the stamp really would skip
+ them. So ``_ensure_new_background_indexes`` now installs the same three indexes,
+ sourced by import from the migrations that own the DDL rather than retyped — see
+ ``test_head_schema_repair_installs_agent_runs_expression_indexes``, which drives the
+ repair path alone. This test owns the REPLAY route, that one owns the REPAIR route,
+ and both compare byte-for-byte against the same full-replay reference, so the two
+ routes cannot converge on different SQL.
+ """
+ owed_notice_migration = import_module(AGENT_RUNS_INDEX_MIGRATION_MODULES[1])
+ replayed_indexes = _agent_runs_index_names()
+
+ # Reference: an empty path replays 0001 -> head with no stamping shortcut at all.
+ reference_sql = _reference_agent_runs_index_sql(tmp_path)
+
+ db_path = _head_shaped_unversioned_db(tmp_path)
+ _seed_settled_history(db_path)
+
+ run_migrations(db_path)
+
+ with sqlite3.connect(db_path) as conn:
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ upgraded_sql = {name: _index_sql(conn, name) for name in replayed_indexes}
+
+ assert version == (HEAD_REVISION,)
+ assert upgraded_sql == reference_sql
+ # The owed-notice eligibility and backoff expressions must be the migration's own,
+ # never a retyped copy: the planner only matches byte-identical expression text.
+ owed_notice_sql = upgraded_sql[owed_notice_migration._INDEX]
+ assert owed_notice_migration._STATE_EXPR in owed_notice_sql
+ assert owed_notice_migration._NEXT_ATTEMPT_EXPR in owed_notice_sql
+ # Existing SQL is not the claim; a bounded read is. Proven on the database the
+ # entrypoint actually produced.
+ _assert_live_reads_seek_agent_runs_indexes(db_path, route="the migration entrypoint")
+
+
+def test_head_schema_repair_installs_agent_runs_expression_indexes(tmp_path: Path) -> None:
+ """The head-schema REPAIR path installs the 0039-0042 indexes by itself.
+
+ ``_ensure_head_indexes`` promises a head-shaped database every index head has, and
+ it silently lagged head by three: the settlement index, the owed-notice
+ eligibility/backoff expression index and the definition-streak index were only ever
+ created by their migrations. Two lanes make that a real gap. A database born from
+ ``metadata.create_all`` satisfies ``background_tables_ready`` — tables and columns
+ only, never indexes — so ``SQLiteBackgroundTaskStore`` accepts it as ready and
+ ``initialize_background_tables`` never runs; and if ``LATEST_SCHEMA_REVISION`` ever
+ moves past 0038, the stamp floor stops replaying them for everyone.
+
+ Driven through ``_stamp_existing_initial_schema`` rather than through
+ ``run_migrations``, and that choice is the whole point of the test: it is the only
+ production caller that reaches ``_ensure_head_indexes`` on a head-shaped database,
+ and it RETURNS after stamping the floor, leaving the database repaired-but-not-yet
+ -upgraded. ``run_migrations`` would immediately replay 0024-0042 over the result and
+ the assertions below could not tell which route created the indexes;
+ ``_repair_head_required_columns`` reaches the same helper but only as a side effect
+ of a column repair, so it would prove less about the index promise. The stamped
+ revision is asserted to still be the FLOOR, which is what proves no upgrade ran.
+ """
+ settled_index, owed_notice_index, streak_index = _agent_runs_index_names()
+ superseded = import_module(SUPERSEDED_OWED_NOTICE_MIGRATION_MODULE)
+ reference_sql = _reference_agent_runs_index_sql(tmp_path)
+
+ db_path = _head_shaped_unversioned_db(tmp_path)
+ _seed_settled_history(db_path)
+ # A survivor of the 0040 shape: same index NAME, one fewer indexed expression, so
+ # the backoff term would stay a per-row filter. Repairing has to REBUILD it, not
+ # leave it because the name is taken.
+ with sqlite3.connect(db_path) as conn:
+ # Seeding uses the production store, which now repairs the already-ready
+ # schema on construction. Replace just this index afterwards to exercise
+ # the lower-level head-schema repair route this test owns.
+ conn.execute(f"drop index if exists {superseded._INDEX}")
+ conn.execute(
+ f"create index {superseded._INDEX} on agent_runs "
+ f"({superseded._STATE_EXPR}, created_at, id)"
+ )
+ conn.commit()
+
+ migrations._stamp_existing_initial_schema(db_path, migrations.alembic_config(db_path))
+
+ with sqlite3.connect(db_path) as conn:
+ version = conn.execute("select version_num from alembic_version").fetchone()
+ assert version == (migrations.LATEST_SCHEMA_REVISION,), (
+ "this test is only about the repair path: a database stamped past the floor has "
+ f"had migrations replayed over it, so it proves nothing; got {version}"
+ )
+ assert version != (HEAD_REVISION,)
+
+ _assert_agent_runs_indexes_present(db_path, route="the head-schema repair path")
+ with sqlite3.connect(db_path) as conn:
+ repaired_sql = {
+ name: _index_sql(conn, name)
+ for name in (settled_index, owed_notice_index, streak_index)
+ }
+ # Byte-equal to the full replay, because the repair path executes the migrations'
+ # own DDL rather than a copy of it. The owed-notice index in particular must be the
+ # 0041 shape — the 0040 survivor seeded above has to be gone.
+ assert repaired_sql == reference_sql
+ _assert_live_reads_seek_agent_runs_indexes(db_path, route="the head-schema repair path")
+
+
+def test_background_store_repairs_indexes_on_an_already_ready_schema(tmp_path: Path) -> None:
+ """Store construction reaches index repair even when no migration is needed."""
+
+ reference_sql = _reference_agent_runs_index_sql(tmp_path)
+ db_path = _head_shaped_unversioned_db(tmp_path, "store-ready.sqlite")
+ assert background_tables_ready(db_path)
+
+ store = SQLiteBackgroundTaskStore(db_path)
+ store.close()
+
+ with sqlite3.connect(db_path) as conn:
+ repaired_sql = {name: _index_sql(conn, name) for name in _agent_runs_index_names()}
+ assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None
+ assert repaired_sql == reference_sql
+ _assert_live_reads_seek_agent_runs_indexes(
+ db_path,
+ route="already-ready background store construction",
+ )
+
+
def test_run_migrations_adds_agent_events_from_previous_head(tmp_path: Path) -> None:
db_path = tmp_path / "vibe.sqlite"
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 2f4e302e4..9fd277293 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -298,6 +298,20 @@ def _machine_coded_error_builders():
# Round 5d: terminal archive vs retryable lock, on the same route. A client can
# only tell them apart if BOTH codes survive.
("backend_locked", lambda: ui_server._backend_locked_response(locked), "backend_locked", 409),
+ # The runtime-reserved workspace-notifications row: one code, three verbs, so the
+ # per-verb sentence is the only thing that varies and BOTH must keep the code.
+ (
+ "reserved_session_protected",
+ lambda: ui_server._reserved_session_response(ui_server.RESERVED_SESSION_PROTECTED_I18N_KEY),
+ "reserved_session",
+ 403,
+ ),
+ (
+ "reserved_session_read_only",
+ lambda: ui_server._reserved_session_response(ui_server.RESERVED_SESSION_READ_ONLY_I18N_KEY),
+ "reserved_session",
+ 403,
+ ),
# Fork — every branch, since they share one body builder (this round's finding).
(
"fork_archived",
@@ -561,6 +575,135 @@ def test_sessions_patch_archived_message_follows_configured_language(monkeypatch
assert body["error"]["message"] == body["message"]
+def test_messages_post_into_the_reserved_system_session_dispatches_nothing(monkeypatch, tmp_path):
+ """The workspace-notifications row accepts NO turn — the third and last door.
+
+ ``visibility='system'`` deliberately keeps the reserved row in the Inbox, so its card
+ is a clickable chat (``ui/src/components/workbench/InboxPage.tsx``) — while
+ ``archive_session`` / ``update_session`` are the only writes that refused it. That
+ left ``POST /api/sessions/ses-workspace-notices/messages``, which checked archived
+ status only: a user could type into the workspace-notifications card and dispatch a
+ real agent turn into a machine-owned row whose ``agent_backend`` is empty, mixing
+ their conversation into the failure-notice transcript and breaking the accepted
+ plan's "no backend and no turns" contract
+ (``docs/plans/harness-run-reliability.md``).
+
+ Pinned by what the CONTROLLER saw, not just by the status code: the refusal has to
+ happen before dispatch and before the row is reserved, so the assertions are
+ ``dispatch_async`` await count plus an unchanged message count. The ordinary session
+ is the positive control — the guard must not make every send a 403.
+ """
+ from unittest.mock import AsyncMock, patch
+
+ from sqlalchemy import func, select
+
+ from storage.agent_session_rows import (
+ WORKSPACE_NOTICE_SESSION_ID,
+ resolve_workspace_notice_session,
+ )
+ from storage.db import create_sqlite_engine
+ from storage.models import messages as messages_table
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import create_session
+ from vibe.i18n import t as i18n_t
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ ordinary = create_session(
+ conn, scope_id=project["scope_id"], agent_backend="claude", title="Live"
+ )["id"]
+ assert resolve_workspace_notice_session(conn, title="Workspace notifications") == (
+ WORKSPACE_NOTICE_SESSION_ID
+ )
+
+ def _message_count(session_id: str) -> int:
+ with engine.connect() as conn:
+ return conn.execute(
+ select(func.count())
+ .select_from(messages_table)
+ .where(messages_table.c.session_id == session_id)
+ ).scalar_one()
+
+ assert _message_count(WORKSPACE_NOTICE_SESSION_ID) == 0
+ client = app.test_client()
+ headers = csrf_headers(client)
+ dispatch = AsyncMock(return_value={"status_code": 202, "body": {}})
+
+ with patch("vibe.internal_client.dispatch_async", dispatch):
+ blocked = client.post(
+ f"/api/sessions/{WORKSPACE_NOTICE_SESSION_ID}/messages",
+ json={"text": "hello?"},
+ headers=headers,
+ )
+ # Positive control: an ordinary session still dispatches its turn.
+ accepted = client.post(
+ f"/api/sessions/{ordinary}/messages",
+ json={"text": "hello?"},
+ headers=headers,
+ )
+
+ assert blocked.status_code == 403
+ body = blocked.get_json()
+ # The code the Web UI resolves ``errors.reserved_session`` from, in BOTH the nested
+ # object the shared parser reads and the flat field the CLI reads.
+ assert _ui_error_code(body) == "reserved_session"
+ assert body["code"] == "reserved_session"
+ assert not isinstance(body["error"], str)
+ # Copy from ``vibe/i18n``, and the SEND-specific sentence rather than the
+ # archive/edit one ("cannot be archived or modified" answers a different question).
+ expected = i18n_t(ui_server.RESERVED_SESSION_READ_ONLY_I18N_KEY, "en")
+ assert expected != ui_server.RESERVED_SESSION_READ_ONLY_I18N_KEY # the key resolves
+ assert body["message"] == body["error"]["message"] == expected
+ assert expected != i18n_t(ui_server.RESERVED_SESSION_PROTECTED_I18N_KEY, "en")
+ # Refused BEFORE the reservation and BEFORE the controller: no row, no turn.
+ assert _message_count(WORKSPACE_NOTICE_SESSION_ID) == 0
+ assert dispatch.await_count == 1
+ assert accepted.status_code == 201
+ assert _message_count(ordinary) == 1
+
+
+def test_messages_post_reserved_refusal_follows_configured_language(monkeypatch, tmp_path):
+ """The 403 ``message`` is localized, like the archived 409's.
+
+ A direct API/CLI consumer reads it verbatim, and a Web UI client without the
+ ``errors.reserved_session`` key falls back to it — so a hardwired ``lang="en"`` in the
+ shared ``_reserved_session_response`` would ship English into a Chinese install.
+ """
+ from config import paths
+ from core.services.settings import default_config
+ from storage.agent_session_rows import (
+ WORKSPACE_NOTICE_SESSION_ID,
+ resolve_workspace_notice_session,
+ )
+ from storage.db import create_sqlite_engine
+ from vibe.i18n import t as i18n_t
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ config = default_config()
+ config.language = "zh"
+ config.save(paths.get_config_path())
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ resolve_workspace_notice_session(conn, title="工作区通知")
+
+ client = app.test_client()
+ blocked = client.post(
+ f"/api/sessions/{WORKSPACE_NOTICE_SESSION_ID}/messages",
+ json={"text": "hello?"},
+ headers=csrf_headers(client),
+ )
+ assert blocked.status_code == 403
+ key = ui_server.RESERVED_SESSION_READ_ONLY_I18N_KEY
+ assert blocked.get_json()["message"] == i18n_t(key, "zh") != i18n_t(key, "en")
+
+
def test_sessions_patch_archived_outranks_the_backend_lock_preflight(monkeypatch, tmp_path):
"""Archive is TERMINAL, so it must win over the transient backend lock.
diff --git a/tests/test_workspace_system_session.py b/tests/test_workspace_system_session.py
new file mode 100644
index 000000000..e8926ea94
--- /dev/null
+++ b/tests/test_workspace_system_session.py
@@ -0,0 +1,771 @@
+"""The reserved workspace-notifications Session is a SYSTEM surface, not an ordinary chat.
+
+D5 rung (5) of the harness failure ladder needs one row that is TWO things at once: a
+destination the runtime can always deliver a caller-less failure notice to, and NOT a
+chat that shows up in a user's session lists (nothing can be usefully said to it — no
+backend, no turns).
+
+The two ``agent_sessions.visibility`` values that existed each gave exactly one half:
+
+* ``foreground`` delivers, and is an ordinary session in every list.
+* ``background`` hides, and is filtered OUT of ``list_inbox_sessions`` /
+ ``unread_counts_by_session`` — so it hides the notice itself — and additionally sets
+ ``suppress_delivery`` (``core/internal_server.py``, ``core/scheduled_tasks.py``), so
+ no realtime ``inbox.session.updated`` and no Web Push either.
+
+``visibility='system'`` is the projection that satisfies both, and this module pins each
+half plus the refutation of the ``background`` alternative, so nobody "simplifies" the
+fix back into the impasse. See
+``storage.agent_session_rows.resolve_workspace_notice_session``.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select, text
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from config import paths
+from storage import messages_service
+from storage import workbench_sessions_service as wss
+from storage.agent_session_rows import (
+ ASSIGNABLE_SESSION_VISIBILITIES,
+ INBOX_SESSION_VISIBILITIES,
+ SESSION_VISIBILITIES,
+ WORKSPACE_NOTICE_SESSION_ANCHOR,
+ WORKSPACE_NOTICE_SESSION_ID,
+ WORKSPACE_NOTICE_SESSION_VISIBILITY,
+ resolve_workspace_notice_session,
+)
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions
+from storage.sessions_service import SQLiteSessionsService
+
+# The notice rows the harness actually writes into this session are agent ``notify``
+# messages: an inbox PREVIEW type (so they raise a card) but not an ``unread`` type (a
+# failure notify is not an unread reply and must not bump the badge).
+NOTICE_TYPE = "notify"
+
+
+def _migrated_db(monkeypatch, tmp_path: Path) -> Path:
+ """A real migrated state DB, not ``metadata.create_all``.
+
+ The projection is enforced by indexed predicates over columns whose defaults live in
+ the Alembic revisions, so the tests run against the schema an install actually has.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ return paths.get_sqlite_state_path()
+
+
+def _reserved_with_one_notice(db_path: Path):
+ """Create the reserved row and give it one notice, so it is inbox-eligible."""
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ session_id = resolve_workspace_notice_session(conn, title="Workspace notifications")
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id=session_id,
+ platform="avibe",
+ author="agent",
+ message_type=NOTICE_TYPE,
+ text="Scheduled task 'nightly' failed: delivery target missing",
+ )
+ assert session_id == WORKSPACE_NOTICE_SESSION_ID
+ return engine
+
+
+def _ordinary_session(db_path: Path, *, channel: str) -> tuple[str, str]:
+ service = SQLiteSessionsService(db_path)
+ try:
+ sid = service.bind_agent_session(
+ scope_key=f"slack::channel::{channel}",
+ agent_name="claude",
+ session_anchor=f"slack_{channel}",
+ native_session_id=f"native-{channel}",
+ )
+ assert sid is not None
+ return sid, service.get_agent_session_by_id(sid)["scope_id"]
+ finally:
+ service.close()
+
+
+def _list_ids(conn) -> list[str]:
+ return [row["id"] for row in wss.list_sessions(conn, limit=100)["sessions"]]
+
+
+def _paged_ids(conn) -> list[str]:
+ return [row["id"] for row in wss.list_sessions_page(conn, limit=100).items]
+
+
+def _inbox_ids(conn) -> list[str]:
+ return [row["session_id"] for row in messages_service.list_inbox_sessions(conn, platform="avibe")["sessions"]]
+
+
+# ── the vocabulary itself ────────────────────────────────────────────────────
+
+
+def test_system_is_a_storage_visibility_that_no_caller_can_assign() -> None:
+ """Third value in the closed vocabulary, and NOT in the caller-assignable subset.
+
+ Why a value in ``visibility`` at all: it is exactly the axis every session-list and
+ inbox surface already filters on, and it is indexed
+ (``ix_agent_sessions_visibility``, ``storage/models.py``), so the projection costs one
+ predicate on queries that already carry one. A ``metadata_json`` flag would push JSON
+ parsing into those hot queries; a dedicated column would be a migration for a single
+ row. The split matters as much as the value: ``system`` classifies a row the RUNTIME
+ owns, so a caller must not be able to label an ordinary chat with it.
+ """
+ assert WORKSPACE_NOTICE_SESSION_VISIBILITY == "system"
+ assert SESSION_VISIBILITIES == {"foreground", "background", "system"}
+ assert ASSIGNABLE_SESSION_VISIBILITIES == {"foreground", "background"}
+ assert "system" not in ASSIGNABLE_SESSION_VISIBILITIES
+ # Positive admission list: a future fourth visibility is hidden by default.
+ assert set(INBOX_SESSION_VISIBILITIES) == {"foreground", "system"}
+
+
+def test_the_reserved_row_is_created_and_healed_as_system(monkeypatch, tmp_path: Path) -> None:
+ """Both write paths (create, heal) land on ``system``.
+
+ The heal is also the migration: this row exists in no release, so a round-12/13
+ development row created as ``foreground`` is converted by the next notice rather than
+ by an Alembic revision.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ resolve_workspace_notice_session(conn, title="Workspace notifications")
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions.c.visibility, agent_sessions.c.agent_backend, agent_sessions.c.scope_id)
+ .where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ ).mappings().one()
+ assert row["visibility"] == "system"
+ # No backend and no turn: nothing is ever dispatched into it.
+ assert row["agent_backend"] == ""
+ assert row["scope_id"] is None
+
+ # A pre-``system`` row (exactly what a round-12/13 dev database holds) is repaired.
+ with engine.begin() as conn:
+ conn.execute(
+ text("UPDATE agent_sessions SET visibility = 'foreground' WHERE id = :sid"),
+ {"sid": WORKSPACE_NOTICE_SESSION_ID},
+ )
+ with engine.begin() as conn:
+ assert resolve_workspace_notice_session(conn) == WORKSPACE_NOTICE_SESSION_ID
+ with engine.connect() as conn:
+ assert _visibility(conn) == "system"
+ # The heal repairs only what makes the row unusable — the title it was named
+ # with is somebody's record.
+ title = conn.execute(
+ select(agent_sessions.c.title).where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ ).scalar_one()
+ assert title == "Workspace notifications"
+
+
+def _visibility(conn) -> str:
+ return conn.execute(
+ select(agent_sessions.c.visibility).where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ ).scalar_one()
+
+
+# ── half one: hidden from ordinary Session lists ─────────────────────────────
+
+
+def test_reserved_session_is_absent_from_both_ordinary_session_list_surfaces(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """RED before ``system``: the row was ``foreground`` and appeared in both lists.
+
+ Two surfaces, because they are two queries with two filters: the workbench
+ ``list_sessions`` (unscoped — the case a project filter would have masked) and the
+ offset-paginated ``list_sessions_page`` behind ``vibe session list``. Both filter
+ POSITIVELY on ``visibility == 'foreground'``, so ``system`` is excluded with no
+ change of theirs; this test is what makes that a pinned property instead of an
+ assumption about code neither this round nor the next one touches.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ ordinary, _ = _ordinary_session(db_path, channel="C700")
+
+ with engine.connect() as conn:
+ listed = _list_ids(conn)
+ paged = _paged_ids(conn)
+ assert WORKSPACE_NOTICE_SESSION_ID not in listed, (
+ f"reserved system row leaked into the workbench session list: {listed}"
+ )
+ assert WORKSPACE_NOTICE_SESSION_ID not in paged, (
+ f"reserved system row leaked into the paged CLI session list: {paged}"
+ )
+ # The filter is a projection, not a general blackout: ordinary sessions still list.
+ assert ordinary in listed
+ assert ordinary in paged
+
+
+def test_reserved_session_is_absent_from_the_mention_title_search(monkeypatch, tmp_path: Path) -> None:
+ """``#``-mention picker rides ``list_sessions``, so the same filter covers it."""
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.connect() as conn:
+ hits = [row["id"] for row in wss.list_sessions(conn, limit=100, title_query="workspace")["sessions"]]
+ assert hits == [], f"the reserved row is mentionable in the composer: {hits}"
+
+
+def test_reserved_session_messages_stay_out_of_message_search(monkeypatch, tmp_path: Path) -> None:
+ """DELIBERATE non-change: search keeps ``== 'foreground'``, narrower than the inbox.
+
+ Search returns results a user opens and reads IN CONTEXT. The only system session
+ holds machine-authored notices that are already surfaced as inbox cards, with no
+ conversation around a hit to read — so admitting it would put runtime bookkeeping into
+ every text search for no reachable next action. Pinned so the asymmetry with
+ ``INBOX_SESSION_VISIBILITIES`` reads as a decision, not an oversight.
+
+ Exercised with a ``result`` row on purpose: ``notify`` is not in
+ ``types_with('searchable')``, so the type filter alone would make this test pass
+ without saying anything about visibility. Both layers hold, and this asserts the one
+ the round changed.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id=WORKSPACE_NOTICE_SESSION_ID,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="unmistakable-needle-in-a-system-session",
+ )
+ with engine.connect() as conn:
+ found = messages_service.search_messages(conn, platform="avibe", query="unmistakable-needle")
+ # Control: the same predicate does find an ordinary session's result.
+ ordinary, scope_id = _ordinary_session(db_path, channel="C703")
+ with engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=ordinary,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="unmistakable-needle-in-an-ordinary-session",
+ )
+ with engine.connect() as conn:
+ control = messages_service.search_messages(conn, platform="avibe", query="unmistakable-needle")
+ assert found["sessions"] == [], f"system-session text is searchable: {found}"
+ assert [s["session_id"] for s in control["sessions"]] == [ordinary]
+
+
+# ── half two: still consumable through the ordinary inbox machinery ──────────
+
+
+def test_reserved_session_is_admitted_to_the_inbox_projection(monkeypatch, tmp_path: Path) -> None:
+ """The card, and therefore the SSE event and the push, survive being hidden.
+
+ ``get_inbox_session`` returning a row is the actual gate for both realtime paths in
+ ``core/message_mirror.py`` (``bus.publish('inbox.session.updated', inbox_row)`` and
+ ``maybe_notify_inbox_message``), so this assertion is the delivery contract and not
+ just a list membership.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.connect() as conn:
+ feed = _inbox_ids(conn)
+ card = messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID)
+ assert WORKSPACE_NOTICE_SESSION_ID in feed
+ assert card is not None
+ assert "delivery target missing" in (card["preview_text"] or "")
+ # No project placement (scope_id is NULL, deliberately — a reserved scope would mint
+ # a fake project in the sidebar), and the card renders anyway.
+ assert card["scope_id"] is None
+
+
+def test_unread_results_in_a_system_session_are_counted_like_any_other(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """The unread subselects use the NEGATIVE form, so they must name the admitted set.
+
+ Today's notices are ``notify``, which is not an unread type at all — so this test
+ writes a ``result`` to exercise the predicate directly. The point is agreement: the
+ badge counts what the feed shows. Left as ``!= 'foreground'``, a system session would
+ sit in the feed with its unread never counted, which is the same class of silent
+ disagreement the whole ladder keeps producing.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id=WORKSPACE_NOTICE_SESSION_ID,
+ platform="avibe",
+ author="agent",
+ message_type="result",
+ text="ack",
+ )
+ with engine.connect() as conn:
+ per_session = messages_service.unread_counts_by_session(conn, platform="avibe")
+ total = messages_service.total_unread(conn, platform="avibe")
+ assert per_session.get(WORKSPACE_NOTICE_SESSION_ID) == 1
+ assert total == 1
+
+
+def test_a_failure_notify_alone_never_badges_the_system_session(monkeypatch, tmp_path: Path) -> None:
+ """The projection did not turn failure notices into unread replies.
+
+ ``notify`` is an inbox PREVIEW type but not an ``unread`` type, so admitting the
+ session to the inbox raises a card without inflating the nav/PWA badge — which is the
+ pre-existing rule for every failed turn, kept intact here.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.connect() as conn:
+ assert WORKSPACE_NOTICE_SESSION_ID in _inbox_ids(conn)
+ assert messages_service.unread_counts_by_session(conn, platform="avibe") == {}
+ assert messages_service.total_unread(conn, platform="avibe") == 0
+
+
+def test_background_would_hide_the_card_which_is_why_system_exists(monkeypatch, tmp_path: Path) -> None:
+ """RED for the naive alternative: ``background`` satisfies only the hidden half.
+
+ Kept as a permanent refutation. Anyone reducing the third value back to
+ ``background`` gets both halves of the cost in one failure: the inbox card
+ disappears (so the notice the rung exists to show is gone, while the notice row is
+ still persisted and still stamped ``sent``), and the badge stops counting it.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ text("UPDATE agent_sessions SET visibility = 'background' WHERE id = :sid"),
+ {"sid": WORKSPACE_NOTICE_SESSION_ID},
+ )
+ with engine.connect() as conn:
+ assert WORKSPACE_NOTICE_SESSION_ID not in _list_ids(conn), "background does hide it"
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is None, (
+ "if this now returns a row, 'background' has become inbox-visible and the "
+ "reason 'system' exists has been lost"
+ )
+ assert _inbox_ids(conn) == []
+ # ``system`` restores the card without restoring the list entry: the next notice's
+ # heal is what an install actually relies on.
+ with engine.begin() as conn:
+ resolve_workspace_notice_session(conn)
+ with engine.connect() as conn:
+ assert _visibility(conn) == "system"
+ assert WORKSPACE_NOTICE_SESSION_ID not in _list_ids(conn)
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+
+
+def test_inbox_reads_see_a_system_row_written_on_another_connection(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """Two store instances over one file: the drain writes, a UI read must see the card.
+
+ The notice drain and the request that renders the inbox are different processes in
+ production, so they are different connections here — the projection must be a
+ property of the DATABASE, not of one open transaction's snapshot. Nothing in it is
+ connection-local (no temp view, no session pragma), and this is what says so.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ writer = create_sqlite_engine(db_path)
+ reader = create_sqlite_engine(db_path)
+ try:
+ with writer.begin() as conn:
+ resolve_workspace_notice_session(conn, title="Workspace notifications")
+ messages_service.append(
+ conn,
+ scope_id=None,
+ session_id=WORKSPACE_NOTICE_SESSION_ID,
+ platform="avibe",
+ author="agent",
+ message_type=NOTICE_TYPE,
+ text="watch 'ci' failed",
+ )
+ with reader.connect() as conn:
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+ assert WORKSPACE_NOTICE_SESSION_ID in _inbox_ids(conn)
+ assert WORKSPACE_NOTICE_SESSION_ID not in _list_ids(conn)
+ assert WORKSPACE_NOTICE_SESSION_ID not in _paged_ids(conn)
+ finally:
+ writer.dispose()
+ reader.dispose()
+
+
+# ── narrow protection: archive, update, scoped clear, delete ─────────────────
+
+
+def test_update_session_refuses_the_reserved_id(monkeypatch, tmp_path: Path) -> None:
+ """An unguarded PATCH could un-project the row until the next notice healed it.
+
+ ``visibility='background'`` mutes the notice; ``'foreground'`` re-materializes a
+ machine-owned chat in every session list; a ``scope_id`` mints a fake project AND
+ puts the row inside a scoped clear's reach. All three are silent in between, so the
+ refusal is on IDENTITY — before the existence read, so the answer does not depend on
+ whether the lazily-created row exists yet.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = create_sqlite_engine(db_path)
+
+ # Before the row exists at all.
+ with engine.begin() as conn:
+ with pytest.raises(PermissionError) as exc:
+ wss.update_session(conn, WORKSPACE_NOTICE_SESSION_ID, visibility="foreground")
+ assert getattr(exc.value, "code", None) == "reserved_session"
+
+ with engine.begin() as conn:
+ resolve_workspace_notice_session(conn, title="Workspace notifications")
+ for kwargs in (
+ {"visibility": "background"},
+ {"visibility": "foreground"},
+ {"title": "Chat with me"},
+ {"scope_id": None},
+ {"pinned": True},
+ ):
+ with engine.begin() as conn:
+ with pytest.raises(PermissionError) as exc:
+ wss.update_session(conn, WORKSPACE_NOTICE_SESSION_ID, **kwargs)
+ assert getattr(exc.value, "code", None) == "reserved_session", kwargs
+ # The refusal leaves the projection exactly as it was.
+ with engine.connect() as conn:
+ assert _visibility(conn) == "system"
+ assert WORKSPACE_NOTICE_SESSION_ID not in _list_ids(conn)
+
+
+def test_no_caller_can_promote_an_ordinary_session_to_system(monkeypatch, tmp_path: Path) -> None:
+ """The other direction of the same guard: ``system`` is not user-assignable.
+
+ Without this, ``PATCH /api/sessions/<id> {"visibility": "system"}`` would hide any
+ chat from every session list while leaving it delivering into the inbox — a session
+ the user can see notifications from and can no longer open from a list.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ ordinary, _ = _ordinary_session(db_path, channel="C701")
+ engine = create_sqlite_engine(db_path)
+ with engine.begin() as conn:
+ with pytest.raises(ValueError, match="invalid session visibility"):
+ wss.update_session(conn, ordinary, visibility="system")
+ # The two assignable values still work.
+ with engine.begin() as conn:
+ assert wss.update_session(conn, ordinary, visibility="background")["visibility"] == "background"
+ assert wss.update_session(conn, ordinary, visibility="foreground")["visibility"] == "foreground"
+
+
+def test_archive_still_refuses_the_reserved_id(monkeypatch, tmp_path: Path) -> None:
+ """The projection narrows the blast radius; it does not replace the archive guard.
+
+ The row is no longer one click from a session list, but the inbox card carries its
+ id, so ``DELETE /api/sessions/ses-workspace-notices`` is still reachable by anyone
+ holding it — and an archived row keeps earning receipts while showing no card.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.begin() as conn:
+ with pytest.raises(PermissionError) as exc:
+ wss.archive_session(conn, WORKSPACE_NOTICE_SESSION_ID)
+ assert getattr(exc.value, "code", None) == "reserved_session"
+ with engine.connect() as conn:
+ assert wss.is_session_archived(conn, WORKSPACE_NOTICE_SESSION_ID) is False
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+
+
+def test_the_row_accepts_no_turn_by_identity_or_by_projection(monkeypatch, tmp_path: Path) -> None:
+ """``system`` keeps the row in the inbox, so its card is a clickable chat — and a
+ chat has a composer. ``session_is_runtime_owned`` is the fact both the chat surface
+ and ``POST /api/sessions/<id>/messages`` read to refuse that send (the plan's "no
+ backend and no turns").
+
+ Both halves of the OR are pinned because they cover different failures:
+
+ * the PROJECTION half generalizes — a future ``system`` row is refused without a
+ second line — and is what the loaded session payload can answer for free;
+ * the IDENTITY half covers the window the heal has not reached yet. The row is
+ repaired LAZILY (on the next notice), so between a drifted
+ ``visibility='foreground'`` and that repair a projection-only test would admit a
+ turn into the machine's row. Same reason the archive/update guards test identity.
+
+ And an ordinary session must be untouched, or the guard breaks every send.
+ """
+ from storage.agent_session_rows import session_is_runtime_owned
+
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+
+ with engine.connect() as conn:
+ reserved = wss.get_session(conn, WORKSPACE_NOTICE_SESSION_ID)
+ assert reserved["visibility"] == WORKSPACE_NOTICE_SESSION_VISIBILITY
+ assert session_is_runtime_owned(
+ session_id=reserved["id"], visibility=reserved["visibility"]
+ ) is True
+ # Identity alone, i.e. a caller holding only the id (no row loaded) and a row whose
+ # visibility drifted and has not been healed back yet.
+ assert session_is_runtime_owned(session_id=WORKSPACE_NOTICE_SESSION_ID) is True
+ assert session_is_runtime_owned(
+ session_id=WORKSPACE_NOTICE_SESSION_ID, visibility="foreground"
+ ) is True
+ # Projection alone: a hypothetical second system-owned row inherits the refusal.
+ assert session_is_runtime_owned(
+ session_id="ses_some_other_system_row",
+ visibility=WORKSPACE_NOTICE_SESSION_VISIBILITY,
+ ) is True
+
+ ordinary, _ = _ordinary_session(db_path, channel="C703")
+ with engine.connect() as conn:
+ row = wss.get_session(conn, ordinary)
+ assert row["visibility"] == "foreground"
+ assert session_is_runtime_owned(session_id=row["id"], visibility=row["visibility"]) is False
+ for visibility in ("foreground", "background", None, ""):
+ assert session_is_runtime_owned(session_id=ordinary, visibility=visibility) is False
+
+
+def test_the_shared_target_resolver_refuses_the_reserved_row(monkeypatch, tmp_path: Path) -> None:
+ """The composer is one door; ``resolve_session_id_target`` is all the others.
+
+ Round-16 review thread 3678900318. The previous round refused the send inside
+ ``POST /api/sessions/<id>/messages``, which is the door a HUMAN finds. Every other
+ turn entry point reaches the runtime through the shared resolver instead —
+ ``vibe agent run --session-id ses-workspace-notices`` (``cmd_agent_run`` resolves
+ the pin on its ``session_policy in {"existing", "fork"}`` branch),
+ ``vibe task/watch add --session-id``, and ``enqueue_session_callback`` — and that
+ resolver refused only ARCHIVED rows. The reserved row is deliberately kept ACTIVE
+ (``archive_session`` refuses its id), so it sailed straight through and one CLI line
+ could enqueue a real turn into the machine's row, whose ``agent_backend`` is empty.
+
+ ``reason="reserved"``, a NEW value rather than a reuse of ``archived`` or
+ ``missing``: the row exists and is healthy, so nothing about the destination is
+ dead. ``missing`` in particular is the one reason ``_execute_claimed_request``
+ classifies as ``delivery_target_missing``, which here would send a reader hunting
+ for a session sitting in their own inbox.
+
+ Both halves of ``session_is_runtime_owned`` again, for the same two directions the
+ composer guard needed them in — the IDENTITY half covers the window before the lazy
+ heal, the ``system`` PROJECTION generalizes to a future runtime-owned row — and an
+ ordinary session must still resolve, or the guard breaks every pinned definition.
+ """
+ from core.scheduled_tasks import UnresolvableSessionTarget, resolve_session_id_target
+
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+
+ with pytest.raises(UnresolvableSessionTarget) as exc:
+ resolve_session_id_target(WORKSPACE_NOTICE_SESSION_ID, db_path=db_path)
+ assert exc.value.session_id == WORKSPACE_NOTICE_SESSION_ID
+ assert exc.value.reason == "reserved", (
+ "a distinct reason, so no consumer of the other two mistakes this for one of "
+ f"them: {exc.value.reason}"
+ )
+ assert exc.value.reason != "missing", (
+ "``missing`` is the ``delivery_target_missing`` classifier — this row is right "
+ "there in the inbox, so that label would be a lie"
+ )
+ assert WORKSPACE_NOTICE_SESSION_ID in str(exc.value), (
+ f"the message a failed run settles with has to name the session: {exc.value}"
+ )
+ # Still a ValueError, so every pre-existing ``except ValueError`` caller (CLI, API,
+ # watches) keeps refusing rather than crashing.
+ assert isinstance(exc.value, ValueError)
+
+ # The IDENTITY half: a drifted ``visibility`` the lazy heal has not reached yet.
+ with engine.begin() as conn:
+ conn.execute(
+ text("UPDATE agent_sessions SET visibility = 'foreground' WHERE id = :sid"),
+ {"sid": WORKSPACE_NOTICE_SESSION_ID},
+ )
+ with pytest.raises(UnresolvableSessionTarget) as drifted:
+ resolve_session_id_target(WORKSPACE_NOTICE_SESSION_ID, db_path=db_path)
+ assert drifted.value.reason == "reserved"
+
+ # ORDINARY SESSIONS ARE UNCHANGED, in BOTH of the two caller-assignable
+ # visibilities — the control cyhhao asked for by name (comment 5124692513). The
+ # guard's whole risk is over-reach: ``session_is_runtime_owned`` ORs an identity
+ # test with a projection test, and a projection widened by one value would refuse
+ # every ``background`` session, i.e. every ``create_once`` / ``create_per_run``
+ # definition and every ``vibe agent run --create-session`` on the install. So both
+ # are resolved here and their whole target is compared, not just the fact that no
+ # exception was raised: ``suppress_delivery`` is DERIVED from ``visibility``
+ # (``background`` suppresses), which is exactly the field a mis-widened predicate
+ # would take out with it.
+ ordinary, _scope_id = _ordinary_session(db_path, channel="C704")
+ resolved = resolve_session_id_target(ordinary, db_path=db_path)
+ assert resolved.session_id == ordinary
+ assert resolved.session_key.to_key() == "slack::channel::C704"
+ assert resolved.visibility == "foreground"
+ assert resolved.suppress_delivery is False
+
+ with engine.begin() as conn:
+ assert wss.update_session(conn, ordinary, visibility="background")["visibility"] == "background"
+ backgrounded = resolve_session_id_target(ordinary, db_path=db_path)
+ assert backgrounded.session_id == ordinary, (
+ "a BACKGROUND session is the ordinary shape of every reserved harness session — "
+ "refusing it here would break every ``create_once`` definition on the install"
+ )
+ assert backgrounded.session_key.to_key() == "slack::channel::C704"
+ assert backgrounded.visibility == "background"
+ assert backgrounded.suppress_delivery is True, (
+ "and its delivery suppression still derives from the same visibility the guard "
+ "reads, so the two readings of that column cannot drift apart"
+ )
+ with engine.begin() as conn:
+ wss.update_session(conn, ordinary, visibility="foreground")
+
+ # The PROJECTION half: a hypothetical second runtime-owned row inherits the refusal
+ # by visibility alone, with no second line here. Written by raw SQL because
+ # ``system`` is not in ``ASSIGNABLE_SESSION_VISIBILITIES``.
+ with engine.begin() as conn:
+ conn.execute(
+ text("UPDATE agent_sessions SET visibility = 'system' WHERE id = :sid"),
+ {"sid": ordinary},
+ )
+ with pytest.raises(UnresolvableSessionTarget) as projected:
+ resolve_session_id_target(ordinary, db_path=db_path)
+ assert projected.value.reason == "reserved"
+
+
+def test_an_absent_row_still_reads_as_missing_not_reserved(monkeypatch, tmp_path: Path) -> None:
+ """Existence is decided FIRST, so the reserved id does not shadow ``missing``.
+
+ ``session_is_runtime_owned`` answers on the id alone, so a check placed before the
+ existence test would relabel "the reserved row has been deleted and no notice has
+ recreated it yet" as ``reserved`` — and ``missing`` is the reason the delivery
+ classification and the binding recovery are both written against. Ordering, not a
+ special case.
+ """
+ from core.scheduled_tasks import UnresolvableSessionTarget, resolve_session_id_target
+
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ with pytest.raises(UnresolvableSessionTarget) as exc:
+ resolve_session_id_target(WORKSPACE_NOTICE_SESSION_ID, db_path=db_path)
+ assert exc.value.reason == "missing"
+
+
+def test_a_scoped_clear_cannot_reach_the_reserved_row(monkeypatch, tmp_path: Path) -> None:
+ """``scope_id IS NULL`` is what keeps ``/new`` and per-scope teardown off this row.
+
+ ``delete_agent_sessions`` always narrows to one resolved ``scope_id``, and SQL
+ equality never matches NULL — so the reserved row is unreachable by construction
+ rather than by an exemption list. That is the same property that made a scope-less
+ row the right shape in the first place (no fake project in the sidebar).
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ _ordinary_session(db_path, channel="C702")
+
+ service = SQLiteSessionsService(db_path)
+ try:
+ removed = service.delete_agent_sessions(scope_key="slack::channel::C702")
+ finally:
+ service.close()
+ assert removed >= 1, "the clear has to actually clear the scope it names"
+ with engine.connect() as conn:
+ assert _visibility(conn) == "system"
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+
+
+def test_a_deleted_reserved_row_heals_back_to_system(monkeypatch, tmp_path: Path) -> None:
+ """Round-12 doctrine: DURABILITY BY LAZY RECREATION, not by a delete exemption.
+
+ No new guard is added for raw deletes. If any machinery removes the row, the next
+ notice recreates it — under its reserved primary key, its reserved anchor, and now
+ ``system``, so the recreated row is projected exactly like the original.
+ """
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ text("DELETE FROM agent_sessions WHERE id = :sid"), {"sid": WORKSPACE_NOTICE_SESSION_ID}
+ )
+ with engine.begin() as conn:
+ assert resolve_workspace_notice_session(conn, title="Workspace notifications") == (
+ WORKSPACE_NOTICE_SESSION_ID
+ )
+ with engine.connect() as conn:
+ row = conn.execute(
+ select(agent_sessions.c.visibility, agent_sessions.c.session_anchor, agent_sessions.c.status)
+ .where(agent_sessions.c.id == WORKSPACE_NOTICE_SESSION_ID)
+ ).mappings().one()
+ assert row["visibility"] == "system"
+ assert row["session_anchor"] == WORKSPACE_NOTICE_SESSION_ANCHOR
+ assert row["status"] == "active"
+
+
+def test_an_archived_reserved_row_heals_back_to_system(monkeypatch, tmp_path: Path) -> None:
+ """The heal covers the states recreation cannot: the row exists and is unusable."""
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "UPDATE agent_sessions SET status = 'archived', visibility = 'background', "
+ "session_anchor = 'archived:' || id WHERE id = :sid"
+ ),
+ {"sid": WORKSPACE_NOTICE_SESSION_ID},
+ )
+ with engine.connect() as conn:
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is None
+ with engine.begin() as conn:
+ resolve_workspace_notice_session(conn)
+ with engine.connect() as conn:
+ assert _visibility(conn) == "system"
+ assert WORKSPACE_NOTICE_SESSION_ID not in _list_ids(conn)
+ assert messages_service.get_inbox_session(conn, WORKSPACE_NOTICE_SESSION_ID) is not None
+
+
+# ── the Agents run graph ─────────────────────────────────────────────────────
+
+
+def test_reserved_session_is_not_a_node_in_the_agents_graph(monkeypatch, tmp_path: Path) -> None:
+ """The Agents graph is an ordinary session surface too, so ``system`` is not a node.
+
+ ``build_graph``'s candidate set is the live sessions plus the sessions any ``agent_runs``
+ row references. The reserved session runs nothing, so TODAY it is never a candidate —
+ but that is an invariant of the notice path, not of the graph, and the graph's own
+ visibility test is ``!= 'background'``, which ADMITS an unrecognized value. A single
+ run pointing at the row (a repaired ``session_id``, imported state, a future self-heal
+ run) put it in the History view as a node counted under ``foreground``. So the
+ exclusion is explicit, and this test forces the candidate case rather than relying on
+ the absence of runs: the synthetic run below is exactly what made the leak visible.
+ """
+ from core.services import agent_graph
+ from storage.models import agent_runs
+
+ db_path = _migrated_db(monkeypatch, tmp_path)
+ engine = _reserved_with_one_notice(db_path)
+ now = "2026-07-01T00:00:00+00:00"
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ agent_runs.insert().values(
+ id="run-into-the-system-session",
+ run_type="task",
+ status="succeeded",
+ session_id=WORKSPACE_NOTICE_SESSION_ID,
+ created_at=now,
+ updated_at=now,
+ completed_at=now,
+ cancel_requested=0,
+ metadata_json="{}",
+ )
+ )
+ for include_ended in (True, False):
+ for include_background in (True, False):
+ graph = agent_graph.build_graph(
+ live_agents=[],
+ include_ended=include_ended,
+ include_background=include_background,
+ engine=engine,
+ )
+ ids = [node["session_id"] for node in graph["nodes"]]
+ assert WORKSPACE_NOTICE_SESSION_ID not in ids, (
+ f"include_ended={include_ended} include_background={include_background}: "
+ f"reserved system row became a graph node: {ids}"
+ )
+ assert graph["counts"]["foreground"] == 0
+ finally:
+ engine.dispose()
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
index f4d65e8c1..2becc017c 100644
--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -6,6 +6,8 @@ import { MemoryRouter } from 'react-router-dom';
import { describe, expect, it } from 'vitest';
import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import { selectApiErrorFields } from '../../context/ApiContext';
import type { VaultRequest, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { ToastProvider } from '../../context/ToastContext';
import { isVoiceControlDisabled } from '../../lib/voiceRecording';
@@ -18,8 +20,10 @@ import {
isSessionReadOnly,
isShowPageActive,
markSessionArchived,
+ sessionReadOnlyReason,
showPageControlActions,
transcriptSelectionActions,
+ WORKSPACE_NOTICE_SESSION_ID,
} from './sessionArchived';
import { SecretRequestCard } from '../ui/secret-request-card';
@@ -275,7 +279,7 @@ describe('read-only header withdraws the Show Page controls', () => {
disable: () => undefined,
setMode: () => undefined,
}}
- readOnly
+ readOnlyReason="archived"
/>,
);
// The header did render (so the absences below are not a blank component).
@@ -411,7 +415,7 @@ describe('archived conflicts converge whatever the verb', () => {
disable: () => undefined,
setMode: () => undefined,
}}
- readOnly
+ readOnlyReason="archived"
/>,
);
expect(markup).toContain('Model Hub');
@@ -428,6 +432,177 @@ describe('archived conflicts converge whatever the verb', () => {
});
});
+// ── Codex review round 15 (storage/messages_service.py:1207) ──────────────────
+// The reserved workspace-notifications session is ``visibility === 'system'``, which
+// admits it to the Inbox on purpose — so its card is a clickable chat. Archive was the
+// only read-only reason the chat surface knew, so that card opened a fully writable
+// composer into a row the runtime owns ("no backend and no turns"): typing into it
+// dispatched a real agent turn and mixed conversation into the failure-notice
+// transcript. The server now answers ``403 reserved_session`` there; this pins the
+// client half — the affordances go, and the copy does NOT claim the row is archived.
+describe('a runtime-owned system session is read-only for its own reason', () => {
+ const systemSession = () => session({ visibility: 'system', agent_name: null, agent_backend: '' });
+
+ it('reads read-only from the visibility projection, not from the status', () => {
+ expect(sessionReadOnlyReason(session())).toBeNull();
+ expect(isSessionReadOnly(session())).toBe(false);
+
+ const owned = systemSession();
+ expect(owned.status).toBe('active'); // NOT archived — the point of the reason
+ expect(sessionReadOnlyReason(owned)).toBe('system');
+ expect(isSessionReadOnly(owned)).toBe(true);
+
+ // The two assignable visibilities stay ordinary chats. ``background`` is hidden
+ // from lists but is still the USER's session and still accepts turns.
+ expect(sessionReadOnlyReason(session({ visibility: 'background' }))).toBeNull();
+ expect(sessionReadOnlyReason(session({ visibility: 'foreground' }))).toBeNull();
+ // A payload from an older client that predates the field is not read-only.
+ expect(sessionReadOnlyReason(session({ visibility: undefined }))).toBeNull();
+ expect(sessionReadOnlyReason(null)).toBeNull();
+ // Terminal lifecycle outranks ownership when a system row is somehow archived.
+ expect(sessionReadOnlyReason(session({ visibility: 'system', status: 'archived' }))).toBe('archived');
+ });
+
+ it('recognizes the reserved session by IDENTITY when its visibility has drifted', () => {
+ // The server's ``session_is_runtime_owned`` is two tests OR'd: the visibility
+ // projection AND the reserved identity, because the reserved row heals its
+ // visibility only lazily — on the next notice. Between an out-of-band update
+ // and that heal, the Inbox (which admits foreground) still reaches the row as
+ // ``foreground``; a visibility-only client predicate would render the
+ // composer, route picker and fork controls just to collect
+ // ``403 reserved_session`` on every one. Identity must lock it alone.
+ const drifted = session({
+ id: WORKSPACE_NOTICE_SESSION_ID,
+ visibility: 'foreground',
+ agent_name: null,
+ agent_backend: '',
+ });
+ expect(drifted.status).toBe('active');
+ expect(sessionReadOnlyReason(drifted)).toBe('system');
+ expect(isSessionReadOnly(drifted)).toBe(true);
+ // And the identity constant mirrors the server's, character for character —
+ // a drifted copy of THIS string is the whole point of the check.
+ expect(WORKSPACE_NOTICE_SESSION_ID).toBe('ses-workspace-notices');
+ // An ordinary foreground session with an ordinary id stays writable.
+ expect(sessionReadOnlyReason(session({ id: 'sesordinary01', visibility: 'foreground' }))).toBeNull();
+ });
+
+ it('withdraws every session write the same way archive does', () => {
+ // One reason feeds all of them, so the transcript/Show Page/header affordances
+ // cannot diverge per reason — this is what makes the new reason safe by
+ // construction rather than by auditing each site.
+ const readOnly = isSessionReadOnly(systemSession());
+ expect(readOnly).toBe(true);
+ expect(transcriptSelectionActions(systemSession(), readOnly)).toEqual({
+ quote: false,
+ askInNew: false,
+ });
+ expect(showPageControlActions(readOnly, true)).toEqual({
+ visualize: false,
+ share: false,
+ annotate: false,
+ });
+ expect(isShowPageActive(readOnly, true)).toBe(false);
+ });
+
+ it('renders a System badge and no invented agent route', () => {
+ const markup = render(
+ <ChatHeaderBar
+ session={systemSession()}
+ agents={[]}
+ defaultAgentName="claude"
+ onPatch={async () => undefined}
+ onBack={() => undefined}
+ working={false}
+ showPageMode={false}
+ showPageBusy={false}
+ onToggleShowPage={() => undefined}
+ annotation={{
+ state: null,
+ iframeRef: { current: null },
+ handleIframeLoad: () => undefined,
+ enable: () => undefined,
+ disable: () => undefined,
+ setMode: () => undefined,
+ }}
+ readOnlyReason="system"
+ />,
+ );
+ expect(markup).toContain('Model Hub'); // the header did render
+ expect(markup).toContain(en.common.systemSession);
+ // It is not archived, so it must not say so...
+ expect(markup).not.toContain(en.common.archived);
+ // ...and it has no backend, so the default agent's name must not be borrowed as
+ // this session's route (the archived header's fallback would have printed it).
+ expect(markup).not.toContain('claude');
+ expect(markup).not.toContain(en.newSession.defaultAgent);
+ // Same withdrawn cluster as the archived header: Back only.
+ expect(countButtons(markup)).toBe(1);
+ expect(markup).not.toContain('Visualize');
+ expect(markup).not.toContain('Share');
+ });
+
+ it('tells the composer what this session receives instead of calling it archived', () => {
+ const markup = render(
+ <Composer
+ onSend={() => undefined}
+ onStop={() => undefined}
+ disabled
+ placeholder={en.chat.compose.placeholderSystem}
+ />,
+ );
+ expect(markup).toContain(en.chat.compose.placeholderSystem);
+ expect(markup).not.toContain(en.chat.compose.placeholderArchived);
+ // Inert, exactly like the archived composer.
+ expect(countDisabledButtons(markup)).toBe(countButtons(markup));
+ });
+
+ it('reports the coded 403 as a sentence, not as "[object Object]"', () => {
+ // The composer is inert, so this body is only reachable from a client whose loaded
+ // payload predates ``visibility`` (the field is optional for exactly that reason) —
+ // which is precisely the case that must not render an object cast to a string. The
+ // send path uses a RAW apiFetch, so ``handleApiError`` never runs and the branch has
+ // to apply the shared selector itself.
+ const coded = {
+ ok: false,
+ code: 'reserved_session',
+ message: 'This session only receives Avibe’s workspace failure notifications.',
+ error: {
+ code: 'reserved_session',
+ message: 'This session only receives Avibe’s workspace failure notifications.',
+ },
+ };
+ const parsed = selectApiErrorFields(coded, 'HTTP 403');
+ expect(parsed?.code).toBe('reserved_session');
+ expect(parsed?.fallback).toBe(coded.message);
+ expect(String(parsed?.fallback)).not.toBe('[object Object]');
+ // The pre-fix expression, kept as the refutation.
+ expect(String(coded.error)).toBe('[object Object]');
+ // A flat legacy body still resolves to its sentence, so the branch is unchanged
+ // for every route that has not adopted the coded shape.
+ expect(selectApiErrorFields({ error: 'text or content is required' }, 'HTTP 400')?.fallback).toBe(
+ 'text or content is required',
+ );
+ });
+
+ it('has its own copy in both bundles, distinct from the archived wording', () => {
+ // A read-only reason with borrowed copy is the defect this reason exists to avoid:
+ // "This session is archived" is false on a row that was never archived.
+ for (const bundle of [en, zh]) {
+ expect(bundle.chat.compose.placeholderSystem).toBeTruthy();
+ expect(bundle.chat.compose.placeholderSystem).not.toBe(bundle.chat.compose.placeholderArchived);
+ expect(bundle.common.systemSession).toBeTruthy();
+ expect(bundle.common.systemSession).not.toBe(bundle.common.archived);
+ // The machine code the server's 403 carries, for a client that surfaces it
+ // through the shared ``errors.<code>`` resolution.
+ expect(bundle.errors.reserved_session).toBeTruthy();
+ }
+ // en/zh parity: the Chinese bundle must not be the English string.
+ expect(zh.chat.compose.placeholderSystem).not.toBe(en.chat.compose.placeholderSystem);
+ expect(zh.common.systemSession).not.toBe(en.common.systemSession);
+ });
+});
+
// ── Codex review #5b (ChatPage.tsx:3257) ──────────────────────────────────────
// Round 3 classified this "safe" because the write is a MACHINE-scoped vault secret
// the server accepts. That missed the point: archiving expired the session's
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index f3e382e53..729e6cf41 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -5,7 +5,7 @@ import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown,
import type { LucideIcon } from 'lucide-react';
import clsx from 'clsx';
-import { useApi } from '../../context/ApiContext';
+import { selectApiErrorFields, useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';
@@ -54,8 +54,10 @@ import {
isSessionReadOnly,
isShowPageActive,
markSessionArchived,
+ sessionReadOnlyReason,
showPageControlActions,
transcriptSelectionActions,
+ type SessionReadOnlyReason,
} from './sessionArchived';
import { InstallHint } from '../InstallHint';
import { Badge } from '../ui/badge';
@@ -172,6 +174,13 @@ export const ChatPage: React.FC = () => {
// re-route, no transcript control that would write to the session, and no Show
// Page controls (archive takes the page offline and refuses to create one, so
// Visualize and Share could only fail; see showPageControlActions).
+ //
+ // A ``visibility === 'system'`` session is read-only for a DIFFERENT reason and to
+ // the same depth: the runtime owns the row (the workspace-notifications session the
+ // Inbox links to) and the messages POST answers 403 ``reserved_session``. The reason
+ // is carried alongside because only the COPY differs — nothing here may call such a
+ // session archived.
+ const readOnlyReason = sessionReadOnlyReason(session);
const readOnly = isSessionReadOnly(session);
// Chat-page-wide drag-and-drop: dropping files anywhere over the chat surface
@@ -1341,10 +1350,23 @@ export const ChatPage: React.FC = () => {
}
if (!response.ok) {
setWorking(false);
- // Routes answer ``{"error": ...}``; ``detail`` is only FastAPI's own
- // validation shape. Try both before the bare status code.
+ // Routes answer either the flat ``{"error": "<sentence>"}`` or the shared
+ // CODED shape (``{"error": {code, message}, code, message}``) — the
+ // runtime-owned session's ``403 reserved_session`` is the latter, and
+ // ``String(body.error)`` renders that object as literal "[object Object]".
+ // This is a raw ``apiFetch``, so ``handleApiError`` never runs; reuse its own
+ // selector instead of re-deriving the precedence, and localize by code the
+ // same way, so a coded refusal reads as a sentence here too. ``detail`` is
+ // only FastAPI's own validation shape.
+ const parsed = body ? selectApiErrorFields(body, `HTTP ${response.status}`) : null;
throw new Error(
- body?.error ? String(body.error) : body?.detail ? String(body.detail) : `HTTP ${response.status}`,
+ parsed
+ ? parsed.code
+ ? t(`errors.${parsed.code}`, { defaultValue: parsed.fallback })
+ : parsed.fallback
+ : body?.detail
+ ? String(body.detail)
+ : `HTTP ${response.status}`,
);
}
if (body?.already_answered) {
@@ -2017,7 +2039,7 @@ export const ChatPage: React.FC = () => {
onShareOpenChange={setShareOpen}
annotation={annotation}
onAnnotateOpenChange={setAnnotateOpen}
- readOnly={readOnly}
+ readOnlyReason={readOnlyReason}
/>
{showPageActive && showPageUrl && (
@@ -2139,7 +2161,7 @@ export const ChatPage: React.FC = () => {
onDraftChange={onDraftChange}
onSearchAgents={searchAgents}
onSearchSessions={searchSessions}
- readOnly={readOnly}
+ readOnlyReason={readOnlyReason}
/>
</div>
</div>
@@ -2507,12 +2529,15 @@ interface ComposeProps {
onDraftChange: (text: string) => void;
onSearchAgents: ComposerProps['onSearchAgents'];
onSearchSessions: ComposerProps['onSearchSessions'];
- // Archived session: the composer is inert and explains why.
- readOnly: boolean;
+ // Read-only session: the composer is inert and explains why — which is the reason
+ // this is the REASON and not a boolean. "Archived, read-only" is the wrong sentence
+ // on a runtime-owned row that was never archived.
+ readOnlyReason: SessionReadOnlyReason | null;
}
-const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions, readOnly }) => {
+const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions, readOnlyReason }) => {
const { t } = useTranslation();
+ const readOnly = readOnlyReason !== null;
return (
// shrink-0 pins the bar at the bottom of the fixed-height chat container; the
// gradient fades the transcript out behind it (no opaque band / hard border)
@@ -2541,7 +2566,16 @@ const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, se
// chat and lets this placeholder win. autoFocus is dropped so opening an
// archived chat doesn't pop the keyboard on an inert box.
disabled={readOnly}
- placeholder={readOnly ? t('chat.compose.placeholderArchived') : undefined}
+ placeholder={
+ readOnlyReason === 'system'
+ ? // A runtime-owned row (the workspace-notifications session): the server
+ // answers ``403 reserved_session`` here, so say what it receives rather
+ // than "archived", which it is not.
+ t('chat.compose.placeholderSystem')
+ : readOnlyReason === 'archived'
+ ? t('chat.compose.placeholderArchived')
+ : undefined
+ }
autoFocus={!readOnly}
/>
</div>
@@ -2565,18 +2599,20 @@ interface ChatHeaderBarProps {
onShareOpenChange?: (open: boolean) => void;
annotation: AnnotationBridge;
onAnnotateOpenChange?: (open: boolean) => void;
- // Archived session: the title and the agent route render as static text — the
- // server refuses both edits with 409 — and the Show Page action cluster is
- // withdrawn entirely (see showPageControlActions).
- readOnly: boolean;
+ // Read-only session: the title and the agent route render as static text — the
+ // server refuses both edits (409 archived / 403 reserved) — and the Show Page action
+ // cluster is withdrawn entirely (see showPageControlActions). The REASON, not a
+ // boolean, because it also picks the badge: a runtime-owned row is not "Archived".
+ readOnlyReason: SessionReadOnlyReason | null;
}
// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),
// which renders the header alone rather than mounting the whole page. Note the
// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the
// read-only rendering is reachable without an ApiProvider.
-export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnly }) => {
+export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason }) => {
const { t } = useTranslation();
+ const readOnly = readOnlyReason !== null;
const showPageActions = showPageControlActions(readOnly, showPageMode);
const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;
// Backend locks once a NATIVE conversation exists — a native can only be
@@ -2633,15 +2669,20 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
</Button>
<TitleField key={session.id} title={session.title} onCommit={(title) => onPatch({ title })} readOnly={readOnly} />
{/* Hidden while the Show Page is open so the view gets the full width.
- On an archived session the route is frozen, so show it as static text
- plus an Archived badge instead of an interactive picker. */}
+ On a read-only session the route is frozen, so show it as static text
+ plus a badge naming WHY instead of an interactive picker. A runtime-owned
+ row has no backend at all (``agent_backend`` is empty by design), so the
+ agent name — which would fall back to the default agent's, naming a route
+ this session will never run — is omitted there rather than invented. */}
{!showPageMode && readOnly && (
<div className="flex min-w-0 shrink-0 items-center gap-1.5">
- <span className="truncate text-[12px] font-medium text-muted">
- {session.agent_name || (defaultAgent ? defaultAgent.name : t('newSession.defaultAgent'))}
- </span>
+ {readOnlyReason === 'archived' && (
+ <span className="truncate text-[12px] font-medium text-muted">
+ {session.agent_name || (defaultAgent ? defaultAgent.name : t('newSession.defaultAgent'))}
+ </span>
+ )}
<Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px] font-bold">
- {t('common.archived')}
+ {readOnlyReason === 'system' ? t('common.systemSession') : t('common.archived')}
</Badge>
</div>
)}
diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsx
index f5f23c236..1b1f6571d 100644
--- a/ui/src/components/workbench/HarnessPage.test.tsx
+++ b/ui/src/components/workbench/HarnessPage.test.tsx
@@ -9,6 +9,7 @@ import en from '../../i18n/en.json';
import type { HarnessRun, HarnessSessionSummary, HarnessWatch } from '../../context/ApiContext';
import {
DetailSession,
+ HealthBadge,
RunDetail,
RunTriggerChip,
WatchDetail,
@@ -289,6 +290,50 @@ describe('DetailSession', () => {
});
});
+describe('HealthBadge', () => {
+ // The projection contract: ``unknown`` means health could not be computed, and
+ // must not read as a clean bill of health. Rendering it as nothing gave the
+ // operator a spotless Harness list at exactly the moment the failure signal
+ // was unavailable.
+ it('names an unknown health instead of dropping it', () => {
+ const label = i18n.t('harness.health.unknown');
+ expect(label).not.toBe('harness.health.unknown');
+
+ const html = render(<HealthBadge row={watch({ health: 'unknown', consecutive_failures: 3, recent_failures: 7 })} />);
+
+ expect(html).toContain(`>${label}<`);
+ // Muted, not pink or amber: a fault in the reporting path is not a verdict
+ // that the definition itself is failing.
+ expect(html).toContain('text-muted');
+ expect(html).not.toContain('text-pink');
+ expect(html).not.toContain('text-amber');
+ });
+
+ it('shows no count on an unknown row', () => {
+ // The counters come from the same unreadable history, so printing them
+ // would put a number on a row whose runs could not be read at all.
+ const label = i18n.t('harness.health.unknown');
+ const html = render(<HealthBadge row={watch({ health: 'unknown', consecutive_failures: 3, recent_failures: 7 })} />);
+
+ expect(html).toContain(`>${label}<`);
+ expect(html).not.toContain(`${label} 3`);
+ expect(html).not.toContain(`${label} 7`);
+ });
+
+ it('renders nothing for a healthy row', () => {
+ // A badge on every passing row is noise; silence here is what makes the
+ // unknown badge above worth looking at.
+ expect(render(<HealthBadge row={watch({ health: 'healthy', consecutive_failures: 0, recent_failures: 0 })} />)).toBe('');
+ });
+
+ it('still counts a failing row', () => {
+ const html = render(<HealthBadge row={watch({ health: 'failing', consecutive_failures: 4, recent_failures: 4 })} />);
+
+ expect(html).toContain(`>${i18n.t('harness.health.failing')} 4<`);
+ expect(html).toContain('text-pink');
+ });
+});
+
describe('WatchDetail runtime', () => {
it.each([
[
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index c0524c02b..f64e3767f 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -62,6 +62,7 @@ import {
DEFINITION_STATUS_FILTERS,
definitionActiveCount,
definitionChipLabel,
+ definitionHealth,
definitionRowLine,
definitionRowTitle,
definitionStatusCount,
@@ -997,6 +998,51 @@ const ALERT_CLASS: Record<HarnessRowAlert, string> = {
// not an error the store recorded — it is the absence of one, which is
// exactly why nothing used to show it.
dead: 'text-pink',
+ // Recovered but not clean: the newest verdict succeeded while a failure is
+ // still in the window. Amber rather than pink — it is a "look at this", not a
+ // "this is broken right now".
+ degraded: 'text-amber',
+ // Health could not be read at all. Muted, because the fault is in the
+ // reporting path rather than in the definition — but present, because the
+ // alternative is a row that looks like it passed.
+ unknown: 'text-muted',
+};
+
+// Derived health, on the LIST row rather than only in the detail pane. A cron
+// task failing every night used to render identically to one succeeding every
+// night: the only failure signal was ``last_error``, which lives behind a click,
+// and the row's alert channel was driven by ``lifecycle_detail`` — null unless the
+// row is ``finished``, which a recurring definition never is.
+//
+// ``healthy`` renders nothing — a badge on every passing row is noise, and the
+// silence is what makes the other three worth looking at.
+//
+// ``unknown`` does render. The server emits it when the health read failed or
+// the stored metadata was malformed, so it is a rare fault state, not a noisy
+// one; rendering it as nothing produced a spotless Harness list at precisely the
+// moment the failure signal could not be computed, which is the opposite of what
+// the projection contract promises. Muted rather than pink or amber, because
+// what is broken is the reporting path, not necessarily the definition.
+export const HealthBadge: React.FC<{ row: HarnessTask | HarnessWatch }> = ({ row }) => {
+ const { t } = useTranslation();
+ const health = definitionHealth(row);
+ if (health !== 'failing' && health !== 'degraded' && health !== 'unknown') return null;
+ // No count on ``unknown``: both counters come from the same run history this
+ // row could not read, so printing one would put a number on nothing.
+ const count = health === 'unknown' ? 0 : health === 'failing' ? row.consecutive_failures : row.recent_failures;
+ return (
+ <Badge
+ variant="secondary"
+ className={clsx(
+ 'shrink-0 font-mono text-[9px] uppercase',
+ health === 'failing' ? 'text-pink' : health === 'degraded' ? 'text-amber' : 'text-muted',
+ )}
+ title={row.last_error || undefined}
+ >
+ {t(`harness.health.${health}`)}
+ {count > 1 ? ` ${count}` : ''}
+ </Badge>
+ );
};
interface DefinitionRowProps {
@@ -1048,6 +1094,7 @@ const DefinitionRow: React.FC<DefinitionRowProps> = ({
{chip}
</Badge>
)}
+ <HealthBadge row={row} />
</div>
<div className="flex min-w-0 items-center gap-2 text-[11px] text-muted">
{line.alert && <AlertTriangle className={clsx('size-3 shrink-0', ALERT_CLASS[line.alert])} />}
@@ -1186,11 +1233,17 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, p
{task.last_run_at && (
<DetailField label={t('harness.detail.lastRun')}>
<span className="font-mono text-[11px] text-muted">{formatLocalDateTime(task.last_run_at)}</span>
- {task.last_error && (
- <div className="mt-1 rounded-md border border-destructive/40 bg-destructive/[0.06] px-2 py-1 text-[11px] text-destructive">
- {task.last_error}
- </div>
- )}
+ </DetailField>
+ )}
+ {/* Its own field, and no longer nested inside ``last_run_at``: a task can
+ carry a ``last_error`` with no ``last_run_at`` (a fire that failed before
+ it ever ran), and that case rendered nothing at all. ``harness.detail.lastError``
+ already existed and was used only by the watch pane. */}
+ {task.last_error && (
+ <DetailField label={t('harness.detail.lastError')}>
+ <pre className="max-h-32 overflow-auto whitespace-pre-wrap rounded-md border border-destructive/40 bg-destructive/[0.06] p-2 font-mono text-[11px] text-destructive">
+ {task.last_error}
+ </pre>
</DetailField>
)}
<DetailField label={t('harness.detail.id')}>
diff --git a/ui/src/components/workbench/harnessLifecycle.test.ts b/ui/src/components/workbench/harnessLifecycle.test.ts
index 3652c8127..62bec5246 100644
--- a/ui/src/components/workbench/harnessLifecycle.test.ts
+++ b/ui/src/components/workbench/harnessLifecycle.test.ts
@@ -654,6 +654,27 @@ describe('definitionRowLine', () => {
expect(unstated.alert).toBe('dead');
});
+ it('warns on a health it could not compute, without dressing it up as a failure', () => {
+ // The backend returns ``unknown`` when the health query itself failed or the
+ // stored metadata was malformed. Mapping it to ``null`` renders the row
+ // exactly like a passing one — a clean-looking list precisely when the
+ // failure signal could not be computed, which is the defect, not the fix.
+ const waiting = { lifecycle_state: 'waiting' as const, next_run_at: at(HOUR) };
+
+ expect(definitionRowLine({ ...waiting, health: 'unknown' }, 'task', key, NOW).alert).toBe('unknown');
+ // Healthy is the only value that stays silent.
+ expect(definitionRowLine({ ...waiting, health: 'healthy' }, 'task', key, NOW).alert).toBeNull();
+ // And the two real failure verdicts keep their own, louder alerts.
+ expect(definitionRowLine({ ...waiting, health: 'failing' }, 'task', key, NOW).alert).toBe('error');
+ expect(definitionRowLine({ ...waiting, health: 'degraded' }, 'task', key, NOW).alert).toBe('degraded');
+ });
+
+ it('has copy behind every health verdict a row can show', () => {
+ // ``healthy`` has no badge and so needs no copy; every value that renders
+ // does, in both languages.
+ expectCopy('harness.health', ['failing', 'degraded', 'unknown']);
+ });
+
it('has copy behind every row phrase it can produce', () => {
expectCopy('harness.row', [
'modeOnce',
diff --git a/ui/src/components/workbench/harnessLifecycle.ts b/ui/src/components/workbench/harnessLifecycle.ts
index 851425c7f..eb8e933f0 100644
--- a/ui/src/components/workbench/harnessLifecycle.ts
+++ b/ui/src/components/workbench/harnessLifecycle.ts
@@ -322,9 +322,28 @@ export type HarnessDefinitionFacts = {
last_run_at?: string | null;
last_started_at?: string | null;
last_finished_at?: string | null;
+ last_error?: string | null;
updated_at?: string | null;
+ // Derived server-side from the definition's own run history, because
+ // ``last_run_at``/``last_error`` are overwritten on every fire and one success
+ // therefore erased days of failure.
+ health?: HarnessDefinitionHealth | string | null;
+ consecutive_failures?: number | null;
+ recent_failures?: number | null;
};
+// ``failing`` = the newest verdict failed; ``degraded`` = the newest succeeded but
+// a failure is still in the window; ``unknown`` = health could not be computed,
+// which is deliberately not the same as ``healthy``.
+export const HARNESS_HEALTH_STATES = ['failing', 'degraded', 'healthy', 'unknown'] as const;
+export type HarnessDefinitionHealth = (typeof HARNESS_HEALTH_STATES)[number];
+const HEALTH_STATES = new Set<string>(HARNESS_HEALTH_STATES);
+
+export function definitionHealth(row: HarnessDefinitionFacts): HarnessDefinitionHealth | null {
+ const value = row.health;
+ return value && HEALTH_STATES.has(value) ? (value as HarnessDefinitionHealth) : null;
+}
+
const WHITESPACE_RUN = /\s+/g;
// One uniform row title for a task or a watch (§4.3): its name, else the first
@@ -431,11 +450,13 @@ export function definitionChipLabel(
return row.schedule_type || t('harness.unknownSchedule');
}
-// What the row warns about, if anything: how a finished row ended, or a waiter
-// whose process is gone while the row still claims to be armed. ``null`` when
-// there is nothing to warn about — including when liveness is simply unknown,
-// which must not be dressed up as "dead".
-export type HarnessRowAlert = 'error' | 'timeout' | 'dead';
+// What the row warns about, if anything: how a finished row ended, a waiter
+// whose process is gone while the row still claims to be armed, or a health
+// verdict the server could not compute. ``null`` is reserved for rows with
+// nothing to report — which includes unknown *liveness* (never dressed up as
+// "dead") but not unknown *health*, because a health the projection failed to
+// read is the one thing that must not render as a passing row.
+export type HarnessRowAlert = 'error' | 'timeout' | 'dead' | 'degraded' | 'unknown';
export type HarnessDefinitionLine = {
primary: string;
@@ -475,13 +496,31 @@ export function definitionRowLine(
const liveness = kind === 'watch' ? livenessLabel(row, t) : null;
const dead =
kind === 'watch' && row.process_alive === false && waiterExpectedAlive(row) ? ('dead' as const) : null;
+ // A recurring definition that fails every night is ``waiting`` between fires,
+ // and every non-finished branch below used to return ``alert: null`` — so the
+ // one state a broken cron actually sits in was the one state that could not warn.
+ // ``finished`` keeps reporting how it ended; the health alert is what the other
+ // states gain.
+ // ``healthy`` is the only verdict that stays silent. ``unknown`` gets its own
+ // alert rather than falling through to ``null``: the server emits it when the
+ // health read itself failed, and collapsing that into "nothing to report"
+ // hands the operator a clean list exactly when the failure signal is missing.
+ const health = definitionHealth(row);
+ const unhealthy: HarnessRowAlert | null =
+ health === 'failing'
+ ? 'error'
+ : health === 'degraded'
+ ? 'degraded'
+ : health === 'unknown'
+ ? 'unknown'
+ : null;
if (state === 'finished') {
const detail = row.lifecycle_detail;
return {
primary: lifecycleLabel('finished', detail, t),
secondary: humanizeTime(since, t, now),
- alert: detail === 'error' || detail === 'timeout' ? detail : null,
+ alert: detail === 'error' || detail === 'timeout' ? detail : unhealthy,
};
}
@@ -490,7 +529,7 @@ export function definitionRowLine(
return {
primary: duration ? t('harness.row.runningFor', { duration }) : t('harness.lifecycle.running'),
secondary: liveness,
- alert: dead,
+ alert: dead ?? unhealthy,
};
}
@@ -503,7 +542,7 @@ export function definitionRowLine(
row.mode === 'forever' && row.last_event_at
? t('harness.row.lastEvent', { when: humanizeTime(row.last_event_at, t, now) })
: t('harness.row.waitingFor', { duration: humanizeGap(since, now, t) ?? '—' });
- return { primary, secondary: liveness, alert: dead };
+ return { primary, secondary: liveness, alert: dead ?? unhealthy };
}
if (row.next_run_at) {
const gap = humanizeGap(row.next_run_at, now, t);
@@ -516,19 +555,19 @@ export function definitionRowLine(
return {
primary: gap && isFuture ? t('harness.row.nextIn', { duration: gap }) : when,
secondary: when,
- alert: null,
+ alert: unhealthy,
};
}
return {
primary: t('harness.row.nextAt', { when }),
secondary: row.last_run_at ? t('harness.row.lastRun', { when: humanizeTime(row.last_run_at, t, now) }) : null,
- alert: null,
+ alert: unhealthy,
};
}
return {
primary: t('harness.row.waitingFor', { duration: humanizeGap(since, now, t) ?? '—' }),
secondary: row.last_run_at ? t('harness.row.lastRun', { when: humanizeTime(row.last_run_at, t, now) }) : null,
- alert: null,
+ alert: unhealthy,
};
}
@@ -537,6 +576,6 @@ export function definitionRowLine(
return {
primary: lifecycleLabel(state ?? 'paused', null, t),
secondary: since ? humanizeTime(since, t, now) : null,
- alert: null,
+ alert: unhealthy,
};
}
diff --git a/ui/src/components/workbench/sessionArchived.ts b/ui/src/components/workbench/sessionArchived.ts
index 6f79cdc85..23625f8ea 100644
--- a/ui/src/components/workbench/sessionArchived.ts
+++ b/ui/src/components/workbench/sessionArchived.ts
@@ -9,16 +9,60 @@
// transcript must stay fully readable while every mutating affordance is
// withdrawn — hidden, not left clickable-and-erroring.
//
+// Archive is no longer the ONLY read-only reason: a ``visibility === 'system'``
+// session is a row the RUNTIME owns (today the workspace-notifications session
+// that harness failure notices fall back to — "no backend and no turns"). It is
+// admitted to the Inbox on purpose, so its card is a clickable chat, and
+// ``POST /api/sessions/<id>/messages`` answers ``403 {"code":
+// "reserved_session"}`` there. Same shape as archive, different sentence — hence
+// a read-only REASON rather than a second boolean.
+//
// These live beside ChatPage rather than inside it (the harnessRuns.ts pattern)
// so the decisions are unit-tested without mounting a 3000-line component — the
// page just reads the answers.
import type { WorkbenchSession } from '../../context/ApiContext';
+/** The reserved workspace-notifications session's id — the server's
+ * ``WORKSPACE_NOTICE_SESSION_ID`` (``storage/agent_session_rows.py``), whose primary
+ * key is deliberately outside ``SESSION_ID_ALPHABET`` so no ordinary session can ever
+ * collide with it. Mirrored here because the server's ``session_is_runtime_owned``
+ * refuses this row by IDENTITY as well as by visibility, and the UI must reach the
+ * same answer from the same two tests. */
+export const WORKSPACE_NOTICE_SESSION_ID = 'ses-workspace-notices';
+
+/** Why the chat surface is read-only, or ``null`` when it is writable.
+ *
+ * ``archived`` is checked FIRST: it is the terminal lifecycle state, so it wins over
+ * ownership if a system row is ever also archived (the reserved row heals itself back
+ * out of that, but only on the next notice).
+ *
+ * ``system`` is TWO TESTS, OR'd, mirroring the server's
+ * ``session_is_runtime_owned``: the ``visibility`` projection (so a future
+ * system-owned row inherits the lock), and the reserved IDENTITY — which covers the
+ * states where the projection is momentarily wrong. The reserved row heals lazily,
+ * on the next notice, so a drifted ``foreground`` copy of it stays reachable through
+ * the Inbox in the meantime; without the identity half the composer, route picker
+ * and fork controls would render there just to collect ``403 reserved_session``. */
+export type SessionReadOnlyReason = 'archived' | 'system';
+
+export const sessionReadOnlyReason = (
+ session: WorkbenchSession | null,
+): SessionReadOnlyReason | null => {
+ if (!session) return null;
+ if (session.status === 'archived') return 'archived';
+ if (session.visibility === 'system' || session.id === WORKSPACE_NOTICE_SESSION_ID) {
+ return 'system';
+ }
+ return null;
+};
+
/** One predicate owns "this session can never accept another write", so the
* composer, header, transcript, queue strip and vault cards all derive the same
- * fact instead of each site re-deriving it. */
+ * fact instead of each site re-deriving it. Derived from the reason so a new reason
+ * locks every one of those affordances by construction, and only the COPY has to
+ * learn about it. */
export const isSessionReadOnly = (session: WorkbenchSession | null): boolean =>
- session?.status === 'archived';
+ sessionReadOnlyReason(session) !== null;
/** A ``409 {"code": "session_archived"}`` from any session-scoped write is the
* server stating this row is archived. Same shape for the messages POST and the
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 6545a0a2a..e18e0ca46 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -771,6 +771,13 @@ export type WorkbenchSession = {
model: string | null;
reasoning_effort: string | null;
status: string;
+ /** Storage projection, not a user preference: ``foreground`` = an ordinary chat,
+ * ``background`` = hidden and undelivered, ``system`` = a row the RUNTIME owns
+ * (kept out of session lists, still an Inbox destination — today the
+ * workspace-notifications session, which accepts no turn, see
+ * ``sessionReadOnlyReason``). Optional because payloads cached by an older client
+ * predate the field; the server always sends it. */
+ visibility?: 'foreground' | 'background' | 'system';
pinned: boolean;
/** Live agent-runtime status driving the sidebar dot: idle (gray) /
* running (green) / failed (red). Distinct from the lifecycle ``status``. */
@@ -1199,6 +1206,7 @@ export type HarnessSessionSummary = {
// ``lifecycle_detail`` is set only on ``finished`` rows and says how they ended.
export type HarnessLifecycleState = 'running' | 'waiting' | 'paused' | 'finished';
export type HarnessLifecycleDetail = 'normal' | 'timeout' | 'error';
+export type HarnessDefinitionHealth = 'failing' | 'degraded' | 'healthy' | 'unknown';
// The fields every task/watch row reads to describe its state.
export type HarnessDefinitionState = {
@@ -1214,6 +1222,20 @@ export type HarnessDefinitionState = {
// "how long has this been running" must come from the run that is running,
// not from whenever the row last did anything.
running_since: string | null;
+ // Derived from this definition's own settled run outcomes, never from
+ // ``last_run_at``/``last_error``: those are overwritten on every fire, so one
+ // success used to erase days of failure and a daily-failing cron rendered
+ // identically to a daily-succeeding one.
+ //
+ // ``failing`` = the newest verdict failed. ``degraded`` = the newest succeeded
+ // but a failure is still inside the window — a success downgrades, it does not
+ // clear. ``unknown`` = health could not be computed, which must not read as a
+ // clean bill of health.
+ health: HarnessDefinitionHealth | null;
+ // How many verdicts back the failure run reaches, and how many failures are in
+ // the window at all. Both age out on their own; neither is acknowledgment state.
+ consecutive_failures: number;
+ recent_failures: number;
};
export type HarnessTask = HarnessSessionSummary & HarnessDefinitionState & {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index fb885ce0f..9d0f6aefd 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -53,6 +53,7 @@
"disable": "Disable",
"disabled": "Disabled",
"archived": "Archived",
+ "systemSession": "System",
"default": "Default",
"running": "Running",
"stopped": "Stopped",
@@ -1186,6 +1187,7 @@
"missing_share_id": "Enter a custom link first.",
"not_public": "Make the Show Page public first to change its link.",
"session_archived": "This session is archived, so its Show Page can't be changed.",
+ "reserved_session": "Avibe owns this session — it only receives workspace notifications.",
"invalid_icon_type": "The icon must be an SVG, PNG, ICO, JPEG, or WebP image.",
"icon_too_large": "That icon is too large. Use an image up to 2 MiB.",
"icon_required": "Choose an icon file to upload.",
@@ -2923,6 +2925,11 @@
"run": {
"definitionDeleted": "(deleted)"
},
+ "health": {
+ "failing": "failing",
+ "degraded": "degraded",
+ "unknown": "health unknown"
+ },
"lifecycle": {
"running": "Running",
"waiting": "Waiting",
@@ -3070,6 +3077,7 @@
"placeholder": "Type a message…",
"placeholderBusy": "Type to queue while the agent works…",
"placeholderArchived": "This session is archived — read-only",
+ "placeholderSystem": "Avibe posts workspace notifications here — this session does not accept messages",
"hint": "Enter to send",
"send": "Send",
"queueSend": "Send to queue",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index dc8fec7b6..308dbda12 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -53,6 +53,7 @@
"disable": "禁用",
"disabled": "已禁用",
"archived": "已归档",
+ "systemSession": "系统",
"default": "默认",
"running": "运行中",
"stopped": "已停止",
@@ -1186,6 +1187,7 @@
"missing_share_id": "请先输入自定义链接。",
"not_public": "请先把展示页面设为公开,再修改链接。",
"session_archived": "该会话已归档,无法修改它的展示页面。",
+ "reserved_session": "该会话由 Avibe 管理,只接收工作区通知。",
"invalid_icon_type": "图标必须是 SVG、PNG、ICO、JPEG 或 WebP 图片。",
"icon_too_large": "图标太大了,请使用不超过 2 MiB 的图片。",
"icon_required": "请选择要上传的图标文件。",
@@ -2923,6 +2925,11 @@
"run": {
"definitionDeleted": "(已删除)"
},
+ "health": {
+ "failing": "连续失败",
+ "degraded": "近期失败",
+ "unknown": "状态未知"
+ },
"lifecycle": {
"running": "运行中",
"waiting": "等待中",
@@ -3070,6 +3077,7 @@
"placeholder": "输入消息…",
"placeholderBusy": "Agent 处理中,输入将排队…",
"placeholderArchived": "会话已归档,仅可查看",
+ "placeholderSystem": "Avibe 在这里发布工作区通知,该会话不接受发送消息",
"hint": "Enter 发送",
"send": "发送",
"queueSend": "排队发送",
diff --git a/vibe/cli.py b/vibe/cli.py
index 56daaad88..3249ea276 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -24,7 +24,7 @@ import urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
from textwrap import dedent
-from typing import Mapping, NamedTuple, Optional
+from typing import Any, Callable, Mapping, NamedTuple, Optional
from uuid import uuid4
from zoneinfo import ZoneInfo
@@ -40,6 +40,7 @@ from core.scheduled_tasks import (
BINDING_FOLLOWS_SESSION_METADATA_KEY,
ScheduledTaskStore,
TaskExecutionStore,
+ UnresolvableSessionTarget,
parse_scope_id,
parse_session_key,
resolve_session_id_target,
@@ -55,6 +56,7 @@ from core.watches import (
WatchRuntimeStateStore,
)
from vibe import __version__, api, runtime
+from vibe.i18n import t as i18n_t
from vibe.restart_supervisor import schedule_restart
from vibe.screenshot import ScreenshotError, capture_screenshot
from vibe.upgrade import (
@@ -185,7 +187,65 @@ class _LocalShowEventsTarget(NamedTuple):
verify_ui_pid: int | None = None
+#: The reserved workspace-notifications session, refused at a CLI admission door.
+#:
+#: ONE CODE ACROSS TWO SURFACES. ``reserved_session`` is not new vocabulary invented for
+#: the CLI: ``storage.workbench_sessions_service`` already raises it as
+#: ``ReservedSessionError.code``, ``vibe/ui_server.py`` answers ``403 reserved_session``
+#: for the DELETE, the PATCH and the messages POST, and ``ui/src/i18n`` renders one
+#: ``errors.reserved_session`` entry for it. A coding agent driving ``vibe`` and a browser
+#: driving the API now branch on the SAME token, which is the whole point of coding it:
+#: the round-16 hole was reachable from the CLI precisely because the two surfaces did not
+#: share a contract.
+#:
+#: ONLY ``reserved`` IS TYPED HERE, and the other three ``UnresolvableSessionTarget``
+#: reasons deliberately stay on the generic path. The breadth was checked against the
+#: vocabulary that actually exists rather than assumed:
+#:
+#: * ``session_archived`` does not exist in this CLI at all — it lives only on the Show
+#: and HTTP surfaces (``core/show_pages.py``, ``vibe/api.py``, ``vibe/ui_server.py``).
+#: Adding it here would be new vocabulary, not mirroring.
+#: * ``session_not_found`` DOES exist here (``vibe session get`` / ``vibe session
+#: update``) but means something narrower: a ``LookupError`` from
+#: ``sessions_service.get_active_session``, which by its own comment folds ARCHIVED into
+#: not-found. Reusing it for ``reason == "missing"`` would give one token two
+#: incompatible meanings depending on which command emitted it — worse than a generic
+#: code, because a client cannot tell which one it got.
+#: * this exception class already HAS a typed CLI code, ``invalid_session_id``, on the
+#: paths that route through ``_validate_session_id_target`` /
+#: ``_validate_callback_session_id``. Re-coding ``missing`` / ``archived`` / ``unusable``
+#: here would make a THIRD vocabulary for one class. Unifying those three is a real
+#: cleanup with its own blast radius; it is not this finding, and doing it silently
+#: inside a review round would be the larger change.
+RESERVED_SESSION_CLI_CODE = "reserved_session"
+
+
+def _reserved_session_cli_error(exc: "UnresolvableSessionTarget") -> TaskCliError:
+ """Re-type the resolver refusal and localize its user-facing guidance."""
+
+ try:
+ lang = V2Config.load().language
+ except Exception:
+ lang = "en"
+ return TaskCliError(
+ str(exc),
+ code=RESERVED_SESSION_CLI_CODE,
+ hint=i18n_t("harness.notice.workspaceSessionReadOnly", lang),
+ details={"session_id": exc.session_id, "reason": exc.reason},
+ )
+
+
def _print_task_error(exc: Exception, *, help_command: str | None = None) -> None:
+ # Re-typed BEFORE the ``TaskCliError`` branch, and here rather than in each command's
+ # own ``except``, because this is the one printer every CLI admission door funnels its
+ # broad handler through. ``cmd_agent_run``, ``cmd_task_add`` and ``cmd_watch_add`` all
+ # reached ``resolve_session_id_target`` via ``_resolve_agent_for_target``, which does
+ # not wrap — so all three reported ``task_command_failed`` and a client had nothing but
+ # a prose string to branch on. Fixing it at the printer means a command added later
+ # inherits the code instead of having to remember it, and adds no third copy of the
+ # payload builder below.
+ if isinstance(exc, UnresolvableSessionTarget) and exc.reason == "reserved":
+ exc = _reserved_session_cli_error(exc)
if isinstance(exc, TaskCliError):
payload = {
"schema_version": 1,
@@ -1549,6 +1609,16 @@ def _task_state(task) -> str:
def _task_last_status(task) -> str:
+ """Historical compatibility field; never used to determine lifecycle.
+
+ Deliberately three-valued and identical to ``_task_projection_last_status``.
+ An earlier revision of this change added a fourth value, ``degraded``, here —
+ before #1061 demoted the field. Keeping that would have put new semantics on a
+ field declared compatibility-only AND made the two spellings of ``last_status``
+ disagree about their own vocabulary. Health is reported in its own fields,
+ computed once in ``_enrich_definitions`` and read back by everything else.
+ """
+
if task.last_run_at and task.last_error:
return "failed"
if task.last_run_at:
@@ -1583,6 +1653,16 @@ def _task_schedule_summary(task) -> str:
def _task_payload(task, *, brief: bool = False):
+ """The stored row alone, for the one case that has no projection to read.
+
+ Carries no health: derived health is a fact about ``agent_runs`` that only
+ ``_enrich_definitions`` computes, and a payload builder that answered it from
+ a second query of its own is how the CLI came to disagree with every other
+ surface. Callers reach this only when the read-back finds nothing — the
+ file-backed store has no run history at all — where degrading to the stored
+ fields beats inventing a badge.
+ """
+
derived = {
"display_name": _task_display_name(task),
"message_preview": _task_message_preview(task.prompt),
@@ -1598,6 +1678,9 @@ def _task_payload(task, *, brief: bool = False):
"display_name": derived["display_name"],
"state": derived["state"],
"last_status": derived["last_status"],
+ # ``last_error`` used to be dropped here, which left the list a user
+ # actually runs unable to say WHY anything was failing.
+ "last_error": task.last_error,
"next_run_at": derived["next_run_at"],
"schedule_type": task.schedule_type,
"schedule_summary": derived["schedule_summary"],
@@ -1622,6 +1705,33 @@ _CANONICAL_DEFINITION_FIELDS = (
"running_since",
)
+#: Derived failure health, forwarded verbatim beside the canonical lifecycle
+#: fields — NOT folded into ``lifecycle_state`` and NOT smuggled into
+#: ``last_status``.
+#:
+#: Health and lifecycle are ORTHOGONAL axes. A cron that fails every night is
+#: ``waiting`` between fires and ``failing`` the whole time; that combination is
+#: precisely the case this exists to surface. Folding health into
+#: ``lifecycle_state`` would need a fifth value in a closed four-value vocabulary
+#: the Workbench switches on three ways (icon, pill class, i18n key), or would lose
+#: one of the two axes.
+#:
+#: ``last_status`` is the other wrong home: it is explicitly a compatibility field
+#: that never determines lifecycle, so putting new semantics there would leave the
+#: canonical projection unable to see that a definition is broken — which is the
+#: original defect one layer up.
+#:
+#: These ride the same store row as the canonical fields, because the health query
+#: is computed in ``_enrich_definitions`` — the one chokepoint every list, show and
+#: Workbench read already passes through.
+_DEFINITION_FAILURE_FIELDS = (
+ "health",
+ "consecutive_failures",
+ "recent_failures",
+ # The one field that says WHY, dropped from the brief list payload before.
+ "last_error",
+)
+
def _task_projection_state(task: Mapping[str, object]) -> str:
"""Compatibility ``state`` derived from the canonical lifecycle fields."""
@@ -1674,6 +1784,7 @@ def _task_projection_payload(task: Mapping[str, object], *, brief: bool = False)
"enabled": task.get("enabled"),
}
payload.update({field: task.get(field) for field in _CANONICAL_DEFINITION_FIELDS})
+ payload.update({field: task.get(field) for field in _DEFINITION_FAILURE_FIELDS})
return payload
payload = dict(task)
payload.update(derived)
@@ -1686,7 +1797,7 @@ def _task_store() -> ScheduledTaskStore:
@contextlib.contextmanager
def _definition_read_store():
- """Own the canonical read projection store used by CLI list/show commands."""
+ """Own the canonical read projection store used by CLI read commands."""
store = SQLiteBackgroundTaskStore()
try:
@@ -1695,6 +1806,43 @@ def _definition_read_store():
store.close()
+def _read_definition_projection(
+ read: Callable[[SQLiteBackgroundTaskStore], Optional[dict[str, Any]]],
+) -> Optional[dict[str, Any]]:
+ """Read one definition back through ``_enrich_definitions``, or ``None``.
+
+ Never raises: a mutation that succeeded must still report the row it wrote
+ even if the projection cannot be read, so callers degrade to the stored
+ fields instead of turning a completed write into a failed command.
+ """
+
+ try:
+ with _definition_read_store() as store:
+ return read(store)
+ except Exception:
+ logger.debug("definition projection read-back failed", exc_info=True)
+ return None
+
+
+def _task_mutation_payload(task) -> dict:
+ """The projected row a task mutation just wrote.
+
+ Create / pause / resume / update answer with exactly what ``vibe task show``
+ prints next, because they read the same enriched row rather than deriving
+ anything themselves. That is the whole contract: the mutation response is the
+ first — and for an agent, often the only — thing anyone sees, so a definition
+ that is already failing has to say so there in the same words.
+
+ ``None`` means there is no projection to read (the file-backed store keeps no
+ ``agent_runs`` history), which degrades to the stored row.
+ """
+
+ projected = _read_definition_projection(lambda store: store.get_scheduled_task(task.id))
+ if projected is None:
+ return _task_payload(task)
+ return _task_projection_payload(projected)
+
+
def _task_request_store() -> TaskExecutionStore:
return TaskExecutionStore()
@@ -2546,12 +2694,36 @@ def _watch_projection_payload(watch: Mapping[str, object], *, brief: bool = Fals
"process_alive": watch.get("process_alive"),
}
payload.update({field: watch.get(field) for field in _CANONICAL_DEFINITION_FIELDS})
+ # Watches get health on the same terms as tasks: ``_enrich_definitions``
+ # computes it for both, and a watch whose hook fails nightly is exactly as
+ # invisible as a task that does.
+ payload.update({field: watch.get(field) for field in _DEFINITION_FAILURE_FIELDS})
return payload
payload = dict(watch)
payload.update(derived)
return payload
+def _watch_mutation_payload(watch, runtime_entry: Optional[dict[str, object]]) -> dict:
+ """The projected row a watch mutation just wrote.
+
+ The twin of ``_task_mutation_payload``, and the reason watches needed one:
+ they never had a health lookup of their own, so every create / pause /
+ resume / update answered with no health at all while the same watch showed
+ ``failing`` in ``vibe watch list``. Reading the projection back gives both
+ definition types the one answer instead of one answer each.
+
+ ``runtime_entry`` remains the fallback's liveness source; the projected row
+ carries its own ``runtime`` and ``process_alive`` from the same heartbeat
+ rows the Workbench reads.
+ """
+
+ projected = _read_definition_projection(lambda store: store.get_watch(watch.id))
+ if projected is None:
+ return _watch_payload(watch, runtime_entry)
+ return _watch_projection_payload(projected)
+
+
def _agent_payload(agent, *, brief: bool = False) -> dict:
payload = agent.to_dict()
if brief:
@@ -2671,7 +2843,7 @@ def _wait_for_watch_startup(
hint="Inspect the stored watch error, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.",
example=inspect_command,
help_command=inspect_command,
- details={"watch": _watch_payload(watch, runtime_entry)},
+ details={"watch": _watch_mutation_payload(watch, runtime_entry)},
)
if watch.mode == "once" and watch.last_finished_at and not watch.last_error and watch.last_exit_code == 0:
return watch, runtime_entry
@@ -2691,7 +2863,7 @@ def _wait_for_watch_startup(
hint="Inspect the stored watch error, fix the waiter or its dependencies, then recreate the watch if monitoring should continue.",
example=inspect_command,
help_command=inspect_command,
- details={"watch": _watch_payload(watch, runtime_entry)},
+ details={"watch": _watch_mutation_payload(watch, runtime_entry)},
)
raise TaskCliError(
f"watch '{watch_id}' was created but startup was not confirmed within {timeout_seconds:.0f} second(s)",
@@ -2699,7 +2871,7 @@ def _wait_for_watch_startup(
hint="Confirm that the Avibe service is running, then inspect the watch state before reporting that monitoring is active.",
example=inspect_command,
help_command=inspect_command,
- details={"watch": _watch_payload(watch, runtime_entry) if watch is not None else {"id": watch_id}},
+ details={"watch": _watch_mutation_payload(watch, runtime_entry) if watch is not None else {"id": watch_id}},
)
@@ -2828,7 +3000,7 @@ def cmd_task_add(args):
metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),
)
warnings = _collect_target_warnings(session_target, delivery_target)
- task_payload = _task_payload(task)
+ task_payload = _task_mutation_payload(task)
payload_fields = {
"warnings": warnings,
}
@@ -2912,7 +3084,7 @@ def cmd_task_set_enabled(task_id: str, enabled: bool):
)
)
return 1
- task_payload = _task_payload(updated)
+ task_payload = _task_mutation_payload(updated)
_print_definition_payload(task_payload)
return 0
@@ -3287,7 +3459,7 @@ def cmd_task_update(args):
metadata=metadata,
)
warnings = _collect_target_warnings(session_target, delivery_target)
- task_payload = _task_payload(updated)
+ task_payload = _task_mutation_payload(updated)
_print_definition_payload(task_payload, warnings=warnings)
return 0
except DefinitionWriteConflict as exc:
@@ -8296,7 +8468,7 @@ def cmd_watch_add(args):
runtime_store = _watch_runtime_store()
watch, runtime_entry = _wait_for_watch_startup(store, runtime_store, watch.id)
warnings = _collect_target_warnings(session_target, delivery_target)
- watch_payload = _watch_payload(watch, runtime_entry)
+ watch_payload = _watch_mutation_payload(watch, runtime_entry)
payload_fields = {
"warnings": warnings,
}
@@ -8378,7 +8550,7 @@ def cmd_watch_set_enabled(watch_id: str, enabled: bool):
)
return 1
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
- watch_payload = _watch_payload(updated, runtime_entry)
+ watch_payload = _watch_mutation_payload(updated, runtime_entry)
_print_definition_payload(watch_payload)
return 0
@@ -8700,7 +8872,7 @@ def cmd_watch_update(args):
updated = store.update_watch(args.watch_id, **changes)
runtime_entry = _watch_runtime_store().load().get("watches", {}).get(updated.id)
warnings = _collect_target_warnings(session_target, delivery_target)
- watch_payload = _watch_payload(updated, runtime_entry)
+ watch_payload = _watch_mutation_payload(updated, runtime_entry)
_print_definition_payload(watch_payload, warnings=warnings)
return 0
except DefinitionWriteConflict as exc:
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index a25cebd13..4ae3cad3e 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -51,6 +51,64 @@
"fallbackResult": {
"canceled": "The run was canceled before producing a result.",
"failed": "The run failed before producing a result."
+ },
+ "bindingUnresolvedRetry": "Pinned agent session {session} cannot accept a turn ({attempt}/{threshold}). This definition will be paused after {threshold} consecutive unresolvable-target failures. Re-point it with: vibe task update {id} --session-id <id>.",
+ "bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}."
+ },
+ "notice": {
+ "failed": "[Avibe Harness] Scheduled work \"{name}\" failed.",
+ "interrupted": "[Avibe Harness] Scheduled work \"{name}\" was interrupted ({reason}). Nothing is wrong with the definition itself.",
+ "error": "Error: {error}",
+ "unknownError": "no error text was recorded",
+ "definition": "Definition: {id}",
+ "paused": "It is currently PAUSED and will not fire again until you resume it: vibe task resume {id}",
+ "taskFinished": "This one-shot task has already finished and will not fire again.",
+ "nextRun": "Next scheduled run: {when}",
+ "rerun": "Re-run it now with: vibe task run {id} — or inspect it with: vibe task show {id}",
+ "watchPaused": "It is currently PAUSED and will not watch again until you resume it: vibe watch resume {id}",
+ "watchRetired": "This watch has already finished and will not watch again.",
+ "watchShow": "Inspect it with: vibe watch show {id}",
+ "rebound": "[Avibe Harness] Scheduled work \"{name}\" lost the agent session it was pinned to, so it was reconnected to a new one and kept running.",
+ "reboundSessions": "Previous session: {previous} → new session: {new}",
+ "reboundSettingsPreserved": "The previous session's workdir, Agent and model were preserved.",
+ "reboundSettingsReset": "The previous session's settings could not be recovered, so this work now runs on the scope defaults.",
+ "reboundRepin": "Pin it to a different session with: vibe task update {id} --session-id <session-id>",
+ "show": "Inspect it with: vibe task show {id}",
+ "definitionDeleted": "This definition no longer exists, so it cannot be re-run, resumed or re-pinned — only this run's record remains.",
+ "runInspect": "Inspect the run with: vibe runs show {id}",
+ "workspaceSession": "Workspace notifications",
+ "workspaceSessionProtected": "This session receives Avibe's workspace failure notifications and cannot be archived or modified.",
+ "workspaceSessionReadOnly": "This session only receives Avibe's workspace failure notifications — it does not accept messages.",
+ "failureClass": "Failure class: {failureClass}",
+ "lastSucceeded": "Last succeeded: {when}",
+ "origin": "Created in: {origin}",
+ "originLink": "Open the message that created it: {url}",
+ "originChannel": "{platform} channel {channel}",
+ "originChannelThread": "{platform} channel {channel} (thread {thread})",
+ "originDirect": "a {platform} direct message with {user}",
+ "platform": {
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "lark": "Feishu/Lark",
+ "wechat": "WeChat",
+ "avibe": "the Avibe Workbench"
+ },
+ "class": {
+ "noTerminalResult": "the turn ended without the agent returning a result",
+ "refusedConcurrentTurn": "another turn was already running in its session",
+ "transportUnavailable": "the platform it delivers to was unreachable",
+ "queueHoldExpired": "it waited in the queue until its hold expired",
+ "deliveryTargetMissing": "the agent session it delivers to no longer exists"
+ },
+ "reason": {
+ "stopped": "it was stopped manually",
+ "backendRefresh": "its Agent runtime was refreshed",
+ "evicted": "its session was evicted",
+ "restarted": "the service restarted",
+ "lifetimeTimeout": "its session reached its lifetime limit",
+ "orphaned": "it was left running with nothing executing it",
+ "unknown": "for a reason outside the run itself"
}
}
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 2a1ceab2d..e2808d141 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -51,6 +51,64 @@
"fallbackResult": {
"canceled": "本次 run 在产出结果前被取消,因此没有结果。",
"failed": "本次 run 在产出结果前失败,因此没有结果。"
+ },
+ "bindingUnresolvedRetry": "绑定的 Agent 会话 {session} 无法接收请求({attempt}/{threshold})。连续 {threshold} 次出现目标会话不可用后,该定义将自动暂停。请用以下命令重新绑定:vibe task update {id} --session-id <id>。",
+ "bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。"
+ },
+ "notice": {
+ "failed": "[Avibe Harness] 后台任务「{name}」执行失败。",
+ "interrupted": "[Avibe Harness] 后台任务「{name}」被中断({reason}),任务本身没有问题。",
+ "error": "错误:{error}",
+ "unknownError": "未记录错误信息",
+ "definition": "任务 ID:{id}",
+ "paused": "该任务当前已暂停,恢复前不会再次触发:vibe task resume {id}",
+ "taskFinished": "这个一次性任务已经结束,不会再次触发。",
+ "nextRun": "下次运行时间:{when}",
+ "rerun": "立即重跑:vibe task run {id};查看详情:vibe task show {id}",
+ "watchPaused": "该监视当前已暂停,恢复前不会再次监视:vibe watch resume {id}",
+ "watchRetired": "该监视已经结束,不会再次监视。",
+ "watchShow": "查看详情:vibe watch show {id}",
+ "rebound": "[Avibe Harness] 后台任务「{name}」绑定的 Agent 会话已不存在,已自动重新绑定到新会话并继续运行。",
+ "reboundSessions": "原会话:{previous} → 新会话:{new}",
+ "reboundSettingsPreserved": "已保留原会话的工作目录、Agent 与模型设置。",
+ "reboundSettingsReset": "无法恢复原会话的设置,该任务现在使用当前作用域的默认配置。",
+ "reboundRepin": "如需改绑到其他会话:vibe task update {id} --session-id <session-id>",
+ "show": "查看详情:vibe task show {id}",
+ "definitionDeleted": "该定义已不存在,无法重跑、恢复或改绑,只保留这次运行的记录。",
+ "runInspect": "查看这次运行:vibe runs show {id}",
+ "workspaceSession": "工作区通知",
+ "workspaceSessionProtected": "该会话用于接收 Avibe 的工作区失败通知,无法归档或修改。",
+ "workspaceSessionReadOnly": "该会话只接收 Avibe 的工作区失败通知,不接受发送消息。",
+ "failureClass": "失败类型:{failureClass}",
+ "lastSucceeded": "上次成功时间:{when}",
+ "origin": "创建位置:{origin}",
+ "originLink": "打开创建它的那条消息:{url}",
+ "originChannel": "{platform} 频道 {channel}",
+ "originChannelThread": "{platform} 频道 {channel}(话题 {thread})",
+ "originDirect": "{platform} 上与 {user} 的私聊",
+ "platform": {
+ "slack": "Slack",
+ "discord": "Discord",
+ "telegram": "Telegram",
+ "lark": "飞书/Lark",
+ "wechat": "微信",
+ "avibe": "Avibe 工作台"
+ },
+ "class": {
+ "noTerminalResult": "本轮结束时 Agent 没有返回任何结果",
+ "refusedConcurrentTurn": "所属会话中已有另一轮在执行",
+ "transportUnavailable": "投递目标平台不可达",
+ "queueHoldExpired": "在队列中等待超时",
+ "deliveryTargetMissing": "它要投递的 Agent 会话已不存在"
+ },
+ "reason": {
+ "stopped": "被手动停止",
+ "backendRefresh": "所用的 Agent 运行时被刷新",
+ "evicted": "所属会话被回收",
+ "restarted": "服务重启",
+ "lifetimeTimeout": "所属会话达到生命周期上限",
+ "orphaned": "已无任何执行在推进它",
+ "unknown": "原因在这次运行之外"
}
}
},
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index b74337bab..556179247 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -6595,6 +6595,35 @@ def _session_archived_response():
return _coded_error_response("session_archived", workbench_sessions_service.session_archived_message(), 409)
+#: The archive/edit refusal's copy: the row exists to receive notices and cannot be
+#: torn down or re-labelled. Used by the DELETE and PATCH guards.
+RESERVED_SESSION_PROTECTED_I18N_KEY = "harness.notice.workspaceSessionProtected"
+#: The send refusal's copy. A SEPARATE key on purpose: "cannot be archived or modified"
+#: is not an answer to "why did my message not send", and the composer's own inert-state
+#: notice has to say the same thing this body says.
+RESERVED_SESSION_READ_ONLY_I18N_KEY = "harness.notice.workspaceSessionReadOnly"
+
+
+def _reserved_session_response(i18n_key: str, *, code: str = "reserved_session"):
+ """Shared 403 payload for a write refused because the RUNTIME reserves the session.
+
+ Third instance of the same three lines (DELETE teardown, PATCH edit, and now the
+ messages POST), so it is extracted rather than copied again. The refusal is 403 and
+ not the archive's 409: this is not a lifecycle state the caller could wait out, it is
+ a row the caller does not own.
+
+ One ``code`` for all three (``reserved_session``) so a Web UI client resolves one
+ ``errors.*`` entry, with the per-verb sentence chosen by ``i18n_key`` — the same split
+ the archived refusal uses (global ``errors.session_archived`` plus per-verb
+ ``chat.archived.*`` copy). ``storage`` raises the machine ``code`` and carries no
+ user-facing text, because the configured language is only resolvable up here.
+ """
+ from core.services import settings as settings_service
+
+ lang = settings_service.load_config_or_default().language
+ return _coded_error_response(code, t(i18n_key, lang), 403)
+
+
def _backend_locked_response(err):
"""Shared 409 payload for a rejected cross-backend session change.
@@ -6772,6 +6801,15 @@ async def sessions_update(session_id: str):
# session archived BETWEEN that read and this write, and keeps the service
# guard authoritative rather than trusting the route's preflight.
return _session_archived_response()
+ except workbench_sessions_service.ReservedSessionError as err:
+ # The reserved workspace-notifications session refuses modification the
+ # same way it refuses archive: a flipped visibility or title would
+ # un-project the system surface until the next heal. Mirror the DELETE
+ # route's 403 + localized copy so the two guards read as one contract.
+ return _reserved_session_response(
+ RESERVED_SESSION_PROTECTED_I18N_KEY,
+ code=getattr(err, "code", "reserved_session"),
+ )
except (ValueError, PermissionError) as err:
return jsonify({"error": str(err)}), 400
except workbench_sessions_service.SessionBackendLockedError as err:
@@ -6893,6 +6931,14 @@ async def sessions_archive(session_id: str):
session = workbench_sessions_service.archive_session(conn, session_id)
except LookupError as err:
return jsonify({"error": str(err)}), 404
+ except PermissionError as err:
+ # A session the runtime reserves (today: the workspace-notifications row that
+ # is D5 rung (5)'s home). ``storage`` raises a machine ``code`` and carries no
+ # user-facing text, because the configured language is only resolvable up here.
+ code = getattr(err, "code", "forbidden")
+ if code == "reserved_session":
+ return _reserved_session_response(RESERVED_SESSION_PROTECTED_I18N_KEY, code=code)
+ return _coded_error_response(code, str(err), 403)
revoked_vault_scopes = session.pop("revoked_vault_grant_scopes", [])
@@ -8012,6 +8058,7 @@ async def sessions_messages_create(session_id: str):
from core.services import sessions as workbench_sessions_service
from storage import messages_service
+ from storage.agent_session_rows import session_is_runtime_owned
from vibe import internal_client
payload = request.json or {}
@@ -8032,6 +8079,17 @@ async def sessions_messages_create(session_id: str):
# list, so this only fires on a leftover tab or a hand-crafted call).
if session.get("status") == "archived":
return _session_archived_response()
+ # A runtime-owned session accepts NO turn. The reserved workspace-notifications
+ # row is ``visibility='system'``, which keeps it in the inbox on purpose — so
+ # its card links into this chat, and a chat's composer POSTs here. Archive and
+ # PATCH already refuse that row; this is the third door, and the only one that
+ # could put a real agent turn (against an empty ``agent_backend``) and a user's
+ # conversation into the machine's failure-notice transcript. The UI hides the
+ # composer for the same fact (``sessionReadOnlyReason``); this guard is what
+ # makes it true for a hand-crafted call. Free here — the payload just loaded
+ # carries ``visibility``.
+ if session_is_runtime_owned(session_id=session_id, visibility=session.get("visibility")):
+ return _reserved_session_response(RESERVED_SESSION_READ_ONLY_I18N_KEY)
# Idempotency: a stale or duplicate quick-reply submit (a second tab, or
# one that missed the message.new event) must not start a second turn
# for an already-answered group. The answer lives on the agent message.