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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(harness): settle service-initiated backend teardown as infrastructure interruption (#1209)
Qi Qib9c66d2235f8
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex 0a3203c21..ce4396b54 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -36,6 +36,7 @@ from core.message_output import ()from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocksfrom core.run_settlement import (+ SETTLED_BY_BACKEND_REFRESH,SETTLED_BY_STOPPED,SETTLED_BY_TERMINAL_RESULT,SETTLED_BY_TURN_ONLY_RESULT,@@ -228,7 +229,16 @@ async def _stream_chunk(# terminal STATUS is still first-writer-wins in the store, so a result whose row# write already landed keeps its ``succeeded`` — this only stops the reason from# silently disagreeing with what the user was told.- if sink.get("settled_by") != SETTLED_BY_STOPPED:+ #+ # A contained backend teardown is the same case for the same reason: the+ # service retired the runtime itself and the release already named that as+ # the settlement, so a straggler result must not relabel an infrastructure+ # interruption as a healthy terminal result. Only these two are protected --+ # NOT all of ``SETTLEMENTS_WITHOUT_RESULT`` -- because+ # ``SETTLED_BY_NO_TERMINAL_RESULT`` is the pessimistic default a fallback+ # releaser writes, and upgrading THAT when a real result lands is the whole+ # point of this line.+ if sink.get("settled_by") not in (SETTLED_BY_STOPPED, SETTLED_BY_BACKEND_REFRESH):sink["settled_by"] = SETTLED_BY_TERMINAL_RESULTdone = sink.get("done_event")if done is not None:@@ -1921,6 +1931,7 @@ class ConsolidatedMessageDispatcher:manager.on_terminal_result(context,is_error=is_error,+ settled_by=self._turn_release_settlement(output_semantics),terminal_evidence={"result_text": self._fold_footer(terminal_body, result_footer),"terminal_error": terminal_error,@@ -1954,13 +1965,28 @@ class ConsolidatedMessageDispatcher:"Activity output batch recovery is incomplete",delivered=False,)+ # This row is the IM turn's ONLY terminal boundary — an IM turn has+ # no durable execution owner, and ``list_turn_groups`` /+ # ``_latest_source_message_anchor`` both close a turn on it. So a+ # settlement that ends a turn without a result must still write one;+ # skipping it leaves the turn logically open, which renders as a+ # still-running activity card long after the runtime is gone. Only+ # ``stopped`` is exempt, and only because the stop path reports the+ # boundary itself. Passing the settlement lets the row say+ # ``canceled`` where ``is_error`` alone would have said ``failed`` —+ # a contained backend teardown gets a boundary that is honest about+ # being an interruption rather than a backend fault.if (mutates_turn_lifecycleand context.platform != "avibe"and self._turn_release_settlement(output_semantics)!= SETTLED_BY_STOPPED):- persist_silent_terminal(context, is_error=is_error)+ persist_silent_terminal(+ context,+ is_error=is_error,+ settled_by=self._turn_release_settlement(output_semantics),+ )if canonical_type == "result" and output_semantics.settles_run:# Run completion is independent from visible Message and Turn# completion cardinality. A detached/empty final output maydiff --git a/core/message_mirror.py b/core/message_mirror.pyindex 84ddad225..c45f80c61 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -29,6 +29,7 @@ from typing import Any, Optionalfrom sqlalchemy.exc import IntegrityError+from core.run_settlement import NON_COMPLETING_TURN_SETTLEMENTSfrom modules.im.base import MessageContextfrom storage import agent_events_service, messages_service, settings_servicefrom storage.db import get_cached_sqlite_engine@@ -472,12 +473,25 @@ def persist_agent_message(return None-def persist_silent_terminal(context: MessageContext, *, is_error: bool) -> None:+def persist_silent_terminal(+ context: MessageContext,+ *,+ is_error: bool,+ settled_by: str | None = None,+) -> None:"""Record reply-less IM terminal evidence outside the Message transcript.Durable Workbench turns settle through ``session_turns``. IM turns do not havethat execution owner, so their empty/silent terminal result is retained as anappend-only trace event for activity grouping and fork-boundary recovery.++ ``settled_by`` names the release when the turn ended without the backend+ producing a result, and it outranks ``is_error`` for the same reason it does on+ a durable Turn: a runtime the service retired on purpose ended ``canceled``,+ not ``failed``. Omitting the event entirely is NOT the alternative -- this row+ IS the IM turn's boundary, so dropping it leaves the turn's tool activity+ logically open, which ``list_turn_groups`` renders as a still-running card and+ ``_latest_source_message_anchor`` reads as no fork boundary at all."""session_id = (context.platform_specific or {}).get("agent_session_id")@@ -504,7 +518,10 @@ def persist_silent_terminal(context: MessageContext, *, is_error: bool) -> None:event_type="silent_terminal",visibility="trace",metadata={- "terminal_outcome": "failed" if is_error else "completed",+ "terminal_outcome": NON_COMPLETING_TURN_SETTLEMENTS.get(+ settled_by or "",+ "failed" if is_error else "completed",+ ),},agent_name=agent_name,backend=backend,diff --git a/core/message_output.py b/core/message_output.pyindex e5c754811..42eb046f4 100644--- a/core/message_output.py+++ b/core/message_output.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, field, replacefrom typing import Any, Mapping-from core.run_settlement import SETTLED_BY_STOPPED+from core.run_settlement import SETTLED_BY_BACKEND_REFRESH, SETTLED_BY_STOPPED# Every trigger kind whose dispatch created an ``agent_runs`` row. Scheduled# tasks, watches, webhooks, hooks and recovered Activities are all Harness runs@@ -177,3 +177,43 @@ def stop_output_for(request: Any) -> MessageOutput:completes_run=False,settled_by=SETTLED_BY_STOPPED,)+++def contained_teardown_output_for(request: Any) -> MessageOutput:+ """A service-initiated backend teardown's terminal result: infrastructure, not fault.++ The service killed this backend runtime itself -- idle eviction, duplicate reap,+ a rolling ``agents.*`` reconciliation. #1202 taught the Claude paths to recognize+ that signal and stop reporting it as a user-visible backend error or a Model Hub+ source-health failure. It did not change what the emit that follows still says:+ an ordinary ``result`` whose only lifecycle authority is the terminal-turn+ default, so the dispatcher terminalized an ``agent_runs`` row from an empty body+ and the durable Turn read ``failed`` -- indistinguishable from a backend that+ actually broke, while the bubble said nothing at all.++ Same shape as ``stop_output_for``, different reason. ``completes_run=False``+ keeps the empty body out of ``_record_agent_run_terminal_result``, and+ ``settled_by`` routes the release through the settlement lane instead, where+ ``SETTLEMENT_TERMINAL_STATUS`` already maps ``backend_refresh`` to ``failed``+ with ``interrupt_reason=backend_refresh``. That preserves invariant 2 of+ ``docs/plans/harness-run-reliability.md`` -- an infrastructure interruption is+ ``failed`` with a STRUCTURED cause, never silently swallowed -- while making the+ cause distinguishable from a backend that actually broke.++ ``backend_refresh`` rather than ``interrupted`` because it already names this+ exact boundary: a live Agent runtime retired inside an otherwise healthy+ service. The same name also drives the TURN-level surfaces through+ ``NON_COMPLETING_TURN_SETTLEMENTS``, which record it as ``canceled`` -- the word+ ``release_for_backend_refresh`` already uses when it retires a live Turn+ directly, so one teardown reads the same however it reached the row.++ Nothing here is Claude-specific. Any backend whose cleanup can classify its own+ teardown gets the same semantics by emitting through this factory.+ """++ return replace(+ terminal_output_for(request),+ completes_turn=True,+ completes_run=False,+ settled_by=SETTLED_BY_BACKEND_REFRESH,+ )diff --git a/core/run_settlement.py b/core/run_settlement.pyindex 4cd36f45d..7003f0ed9 100644--- a/core/run_settlement.py+++ b/core/run_settlement.py@@ -231,6 +231,31 @@ SETTLEMENT_TERMINAL_STATUS: Final = {SETTLED_BY_INTERRUPTED: "failed",}++# ----- which durable TURN outcome each settlement writes -------------------+#+# Separate from the map above because a Turn and a Run answer different+# questions. The Run asks "did this unit of work succeed" — an infrastructure+# interruption is a ``failed`` run with a structured cause. The Turn asks "how+# did this execution end", and a runtime the service retired on purpose ended+# ``canceled``, the same word ``release_for_backend_refresh`` writes when it+# retires a live Turn directly. Recording ``failed`` there instead would make the+# two paths for ONE teardown disagree depending on which reached the row first.+#+# Only settlements that end a Turn with no terminal result belong here; anything+# absent falls through to the ordinary ``is_error`` mapping. ``restarted`` is+# excluded on purpose — its call site forces ``failed`` before reaching the+# mapper, because a service shutdown is not a cancellation — as is+# ``no_terminal_result``, the pessimistic default a fallback releaser writes,+# which is a genuine failure to produce a result rather than a deliberate stop.+#: Shared by ``SessionTurnManager._durable_terminal_outcome`` (durable Workbench+#: Turns) and ``persist_silent_terminal`` (the IM trace that stands in for one),+#: so both surfaces describe the same settlement with the same word.+NON_COMPLETING_TURN_SETTLEMENTS: Final = {+ SETTLED_BY_STOPPED: "canceled",+ SETTLED_BY_BACKEND_REFRESH: "canceled",+}+def covered(test_node: str) -> tuple[str, str]:"""Declare the consuming test that proves one teardown matrix cell."""diff --git a/core/session_turns.py b/core/session_turns.pyindex 4494af113..58e025671 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -31,6 +31,7 @@ from core.web_push_notifications import WEB_PUSH_USER_KEY_METADATA, WEB_PUSH_USEfrom core.message_context import resolve_turn_sink_keyfrom core.native_dispatch_phase import backend_dispatch_attemptedfrom core.run_settlement import (+ NON_COMPLETING_TURN_SETTLEMENTS,SETTLEMENTS_WITHOUT_RESULT,SETTLED_BY_BACKEND_REFRESH,SETTLED_BY_NO_TERMINAL_RESULT,@@ -4258,9 +4259,17 @@ class SessionTurnManager:interruption == SETTLED_BY_STOPPEDand not cancel_defers_queue_resume)+ # Same map as every other Turn-outcome surface. This branch used+ # to hardcode ``stopped``, so a rolling refresh landed ``failed``+ # here while ``release_for_backend_refresh`` -- the very caller+ # that cancelled this runner -- wrote ``canceled`` for the durable+ # Turns it reached directly. One teardown, two outcomes, decided+ # by which writer won the race. ``restarted`` is absent from the+ # map and still falls through to ``failed``: a service shutdown+ # is not a cancellation.result = self._terminalize_durable_turn(turn_id,- "canceled" if interruption == SETTLED_BY_STOPPED else "failed",+ NON_COMPLETING_TURN_SETTLEMENTS.get(interruption, "failed"),settled_by=interruption,evidence_kind=("service_shutdown"@@ -6902,10 +6911,30 @@ class SessionTurnManager:@staticmethoddef _durable_terminal_outcome(*, is_error: bool, settled_by: str | None) -> str:+ """Map a release to the durable Turn outcome. The settlement wins.++ A named settlement in ``SETTLEMENTS_WITHOUT_RESULT`` says the Turn ended+ WITHOUT the backend producing a terminal result, so ``completed`` is never+ truthful for one -- yet only ``stopped`` used to be excluded, which left+ ``backend_refresh`` recording a retired runtime as a completed Turn. That is+ the same event ``release_for_backend_refresh`` writes as ``canceled``+ (``failed`` for a start it could not resolve), so the two paths for one+ service-initiated teardown disagreed depending on which reached the row+ first.++ ``canceled`` rather than ``failed`` because the Turn was retired, not broken;+ the RUN still settles ``failed`` with ``interrupt_reason=backend_refresh``+ through ``SETTLEMENT_TERMINAL_STATUS``, so invariant 2 of+ ``docs/plans/harness-run-reliability.md`` keeps its structured cause.+ ``restarted`` is deliberately absent -- its call site already forces+ ``failed`` before reaching here, and a service shutdown is not a cancellation.+ """++ non_completing = NON_COMPLETING_TURN_SETTLEMENTS.get(settled_by or "")+ if non_completing is not None:+ return non_completingif is_error:return "failed"- if settled_by == SETTLED_BY_STOPPED:- return "canceled"return "completed"def _finish_durable_terminal_result(@@ -6953,9 +6982,16 @@ class SessionTurnManager:context: "MessageContext",*,is_error: bool,+ settled_by: str | None = None,terminal_evidence: dict[str, Any] | None = None,) -> None:- """OUTBOUND turn chokepoint for the active terminal ``result``."""+ """OUTBOUND turn chokepoint for the active terminal ``result``.++ ``settled_by`` is the release's named settlement, latched alongside+ ``is_error`` so the post-delivery boundary can tell a Turn that ended+ WITHOUT a result on purpose from a backend that broke. Optional because a+ release may not name one; absent, the flag decides as before.+ """if self.controller is None:returnif not self.is_active_emit(context):@@ -6986,6 +7022,7 @@ class SessionTurnManager:"session_id": session_id,"logical_turn_id": logical_turn_id,"is_error": is_error,+ "settled_by": settled_by or None,"terminal_evidence": dict(terminal_evidence or {}),}context.platform_specific = payload@@ -7004,6 +7041,7 @@ class SessionTurnManager:session_id = str(latch.get("session_id") or "")logical_turn_id = str(latch.get("logical_turn_id") or "")is_error = bool(latch.get("is_error"))+ latched_settlement = str(latch.get("settled_by") or "")if not session_id:returndurable_turn_exists = False@@ -7019,9 +7057,23 @@ class SessionTurnManager:exc_info=True,)if not durable_turn_exists:+ # No durable Turn row owns this session's outcome (IM, CLI, legacy),+ # so this projection IS the session's terminal state. ``is_error``+ # alone would call every result-less release a failure -- including a+ # release whose settlement says the Turn was ended on purpose. A+ # service-initiated backend teardown is the case that matters: the+ # flag is honestly ``True`` (nothing answered) while the settlement+ # says infrastructure, not fault, and the sidebar has no third dot to+ # say so. ``idle`` is what the stop path already projects for the+ # other member of that map, so one deliberate non-completion no+ # longer reads two different ways depending on which one it was.self.controller.set_agent_status(session_id,- "failed" if is_error else "idle",+ (+ "failed"+ if is_error and latched_settlement not in NON_COMPLETING_TURN_SETTLEMENTS+ else "idle"+ ),)returncurrent = self.in_flight.get(session_id)diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex a99d42ae5..5764da6a7 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -2,7 +2,7 @@ import asyncioimport loggingimport osimport uuid-from typing import Callable, Optional+from typing import Any, Callable, Optionalfrom core.agent_auth_service import classify_auth_errorfrom core.backend_failure import backend_failure_notification_output, emit_backend_failure@@ -10,6 +10,7 @@ from core.message_dispatcher import ActivityOutputDeliveryErrorfrom core.message_output import (HARNESS_RUN_ID_TRIGGER_KINDS,MessageOutput,+ contained_teardown_output_for,stop_output_for,terminal_output_for,terminal_turn_output,@@ -266,6 +267,19 @@ class ClaudeAgent(BaseAgent):preserve_pending_request_state=True,)if not handled:+ # Third and last emit site that can be holding a claimed+ # Activity batch. The request is in the FIFO from the moment+ # it is queued, so a background Activity that completes while+ # ``client.query`` is in flight attaches its batch here; the+ # auth branch above already requeues for exactly that reason.+ # Both receiver paths hand the batch back before their+ # terminal emit, unconditionally -- do the same rather than+ # only for a contained teardown, because the non-contained+ # release is no better: it terminalizes those Runs from this+ # empty error body. Requeueing resets the request output to+ # the plain terminal shape, so the emit below carries no+ # provenance it can no longer honour.+ self._requeue_request_activity(request)contained = await self.session_handler.handle_session_error(runtime_session_key, context, e, client=client)@@ -300,14 +314,11 @@ class ClaudeAgent(BaseAgent):)# No async receiver result is coming. Auth recovery settles its# own failure; otherwise do that here without another bubble.- await self.controller.emit_agent_message(+ await self._emit_no_result_settlement(context,- "result",- "",- is_error=True,- level="silent",- output=terminal_output_for(request),- terminal_error=diagnostic,+ request,+ diagnostic,+ contained=contained is True,)finally:self._release_service_runtime_turn(context)@@ -331,6 +342,64 @@ class ClaudeAgent(BaseAgent):logger.debug("claude: teardown classification failed", exc_info=True)return False+ async def _emit_no_result_settlement(+ self,+ context: MessageContext,+ request: Any,+ diagnostic: Optional[str],+ *,+ contained: bool,+ ) -> None:+ """Settle a turn whose backend produced no terminal result.++ Three call sites reach this state -- a failed direct query, a receiver that+ hit EOF, and a receiver exception -- and all three must settle the turn+ through the one outbound chokepoint, because nothing else will.++ ``contained`` is #1202's classification: the service killed this Claude+ process itself. That branch is the whole point of the split. Emitting the+ ordinary shape for it recorded a FAILED Turn and an ``agent_runs`` row+ terminalized from an empty body -- provenance that contradicts the+ classification the caller already made, and which #1202 only hid the bubble+ for. ``contained_teardown_output_for`` routes the release through the+ settlement lane instead, where the run lands ``failed`` with+ ``interrupt_reason=backend_refresh``: still terminal, still visible to+ anything reading the reason, but no longer indistinguishable from a backend+ that actually broke.++ What does NOT change is ``is_error``. Inside the dispatcher's silent branch+ it feeds four things -- the collapsed status bubble's footer word, the+ durable Turn outcome, the IM silent-terminal trace, and (when no durable+ Turn owns the session) the sidebar status projection -- and for all four+ "no terminal result was produced" remains true no matter who killed the+ process. Clearing it would collapse the bubble to a green ``done`` for a+ turn that answered nothing.++ The three that must NOT read that as a backend fault are told so by the+ settlement, which outranks the flag: ``NON_COMPLETING_TURN_SETTLEMENTS``+ for the two Turn-outcome surfaces, and the same map's membership for the+ sidebar, which has no dot between ``idle`` and ``failed`` to spend on it.++ The one thing suppressed is ``terminal_error``: with the flag set and no+ diagnostic, the bubble reads ``stopped`` (an intentional silent end) rather+ than ``failed``, which is exactly what this is. The settlement supplies the+ machine-readable cause; the footer only has to stop claiming success.+ """++ await self.controller.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=(+ contained_teardown_output_for(request)+ if contained+ else terminal_output_for(request)+ ),+ terminal_error=None if contained else diagnostic,+ )+def _release_service_runtime_turn(self, context: MessageContext) -> None:service = getattr(self.controller, "agent_service", None)release = getattr(service, "release_runtime_turn", None)@@ -1931,6 +2000,13 @@ class ClaudeAgent(BaseAgent):client = self.claude_sessions.get(composite_key)returncode = get_claude_client_returncode(client)auth_handled = False+ # Only the ``handle_session_error`` branch below can classify this EOF as a+ # teardown the service performed itself. Every other way out of the branch+ # tree -- no returncode, no handler, auth recovery -- has no classification+ # to offer, and the settlement at the bottom is shared by all of them, so+ # the default has to be "not contained": an unclassified EOF is a real+ # failure and must keep saying so.+ contained = Falseif returncode is not None:eof_error = RuntimeError(terminal_error)error_notify = self._format_error_notify(eof_error, composite_key=composite_key)@@ -1968,13 +2044,16 @@ class ClaudeAgent(BaseAgent):self._requeue_request_activity(pending_request)handle_session_error = getattr(self.session_handler, "handle_session_error", None)if callable(handle_session_error):- contained = await handle_session_error(- composite_key, context, eof_error, client=client+ contained = (+ await handle_session_error(+ composite_key, context, eof_error, client=client+ )+ is True)# A teardown the service performed itself is already# explained in the log; do not leave a durable failure row# for the web Chat to render.- if contained is not True:+ if not contained:try:from core.message_mirror import persist_agent_message@@ -2018,14 +2097,11 @@ class ClaudeAgent(BaseAgent):preserve_pending_request_state=True,)try:- await self.controller.emit_agent_message(+ await self._emit_no_result_settlement(context,- "result",- "",- is_error=True,- level="silent",- output=terminal_output_for(pending_request),- terminal_error=diagnostic,+ pending_request,+ diagnostic,+ contained=contained,)finally:self._release_service_runtime_turn(context)@@ -2079,6 +2155,18 @@ class ClaudeAgent(BaseAgent):await self._clear_pending_reactions(composite_key, context)self._mark_session_idle_if_no_pending_requests(composite_key)else:+ # Give a claimed Activity batch back to the Registry BEFORE the+ # terminal emit, exactly as ``_handle_receiver_eof`` does. This+ # path only ever peeked at the FIFO head, so a request carrying+ # an ``activity_completion_output`` still owned that batch and+ # its ``run_ids`` when the receiver died. Emitting on it either+ # terminalizes those Runs from an empty body or -- once the+ # settlement stops completing the Run -- skips them entirely and+ # discards the claim with them. Requeueing resets the request's+ # output to the plain terminal shape, so the release below+ # carries no provenance it can no longer honour and the batch+ # stays deliverable by whoever claims it next.+ self._requeue_request_activity(pending_request)contained = await self.session_handler.handle_session_error(composite_key,context,@@ -2109,14 +2197,11 @@ class ClaudeAgent(BaseAgent):"claude: failed to persist terminal receiver-error row",exc_info=True,)- await self.controller.emit_agent_message(+ await self._emit_no_result_settlement(context,- "result",- "",- is_error=True,- level="silent",- output=terminal_output_for(pending_request),- terminal_error=diagnostic,+ pending_request,+ diagnostic,+ contained=contained is True,)self._release_service_runtime_turn(context)diff --git a/storage/agent_activity_service.py b/storage/agent_activity_service.pyindex 102d0c957..c406cd10f 100644--- a/storage/agent_activity_service.py+++ b/storage/agent_activity_service.py@@ -134,6 +134,23 @@ def _is_terminal(msg_type: Any, author: Any, metadata: Optional[dict]) -> bool:)+def _outcome_status(terminal_outcome: Any) -> str:+ """Render a stored terminal outcome as an activity-group status.++ One mapper for both boundary kinds — the durable Turn row and the IM+ ``silent_terminal`` trace that stands in for one — so a settlement never means+ two different things depending on which surface recorded it. A turn that was+ canceled or never written its outcome is ``interrupted``, not ``done``: it+ ended without producing an answer, and the group chip should say so.+ """++ if terminal_outcome == "failed":+ return "failed"+ if terminal_outcome in {"canceled", "not_written"}:+ return "interrupted"+ return "done"++def _terminal_status(msg_type: Any, metadata: Optional[dict] = None) -> str:"""done for a normal completion (result / silent marker); failed for an ``error``or a ``backend_failure`` notify."""@@ -310,9 +327,11 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"row_kind": "turn_terminal","text": None,"is_silent": True,- "terminal_status": (- "failed" if terminal_outcome == "failed" else "done"- ),+ # Same mapping as the durable-Turn branch below, because the+ # silent marker IS the IM stand-in for one: a turn the service+ # retired writes ``canceled`` here too, and rendering that as a+ # green ``done`` would claim an answer that was never produced.+ "terminal_status": _outcome_status(terminal_outcome),})continue@@ -358,13 +377,7 @@ def _timeline(conn, session_id: str, *, include_text: bool) -> list[dict[str, An"row_kind": "turn_terminal","text": None,"is_silent": True,- "terminal_status": (- "failed"- if turn["terminal_outcome"] == "failed"- else "interrupted"- if turn["terminal_outcome"] in {"canceled", "not_written"}- else "done"- ),+ "terminal_status": _outcome_status(turn["terminal_outcome"]),})# Sort by decoded emission microsecond (true cross-table order); the phase rankdiff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex ccb4b6791..516253de4 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -3,7 +3,7 @@ import sysimport unittestfrom pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import ANY, AsyncMock, MagicMock, patch+from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -13,6 +13,8 @@ from core.native_dispatch_phase import (backend_dispatch_attempted,set_dispatch_phase,)+from core.run_settlement import SETTLED_BY_BACKEND_REFRESH+from core.session_activities import SessionActivity, activity_completion_outputfrom core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequestfrom modules.agents.claude_agent import ClaudeAgentfrom modules.agents.service import AgentService@@ -1833,6 +1835,371 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):# The exact client whose returncode was read, not a fresh lookup.self.assertEqual(probed, [client])+ # --- contained teardown settlement (#1204) -------------------------------+ #+ # #1202 stopped a service-initiated teardown from being REPORTED as a backend+ # failure. The emit that follows still described it as one: an ordinary silent+ # ``result`` carrying only the terminal-turn default, so an ``agent_runs`` row+ # was terminalized from an empty body and the durable Turn read ``failed``.+ # These assert the settlement now matches the classification on all three paths+ # that can reach it, and — the point of the negative controls — that an ordinary+ # backend failure is untouched.++ def assert_contained_settlement(self, emitter):+ """The terminal emit routed a contained teardown through the settlement lane."""++ call = emitter.await_args+ self.assertEqual(call.args[1:3], ("result", ""))+ self.assertEqual(call.kwargs["level"], "silent")+ output = call.kwargs["output"]+ self.assertEqual(output.settled_by, SETTLED_BY_BACKEND_REFRESH)+ # ``settles_run`` False keeps the empty body out of+ # ``_record_agent_run_terminal_result``; the settlement lane owns the row.+ self.assertFalse(output.settles_run)+ self.assertTrue(output.completes_turn)+ # No terminal result was produced, and that stays true whoever killed the+ # process: clearing the flag would collapse the status bubble to a green+ # ``done`` for a turn that answered nothing.+ self.assertTrue(call.kwargs["is_error"])+ # Suppressing the DIAGNOSTIC is what separates this from a real failure —+ # the dispatcher reads the pair as an intentional silent end (``stopped``)+ # rather than a fault, and the settlement carries the machine-readable cause.+ self.assertIsNone(call.kwargs["terminal_error"])++ def assert_uncontained_settlement(self, emitter, diagnostic_fragment):+ """An ordinary backend failure still settles as one."""++ call = emitter.await_args+ self.assertEqual(call.args[1:3], ("result", ""))+ self.assertTrue(call.kwargs["is_error"])+ self.assertIn(diagnostic_fragment, call.kwargs["terminal_error"])+ self.assertIsNone(call.kwargs["output"].settled_by)+ self.assertTrue(call.kwargs["output"].settles_run)++ def _eof_agent(self, composite_key, *, contained, returncode=-9):+ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ controller._get_session_key = lambda context: "telegram::user::U1"+ agent = ClaudeAgent(controller)+ agent.record_model_hub_native_failure = AsyncMock()+ pending_request = SimpleNamespace(+ context=SimpleNamespace(+ platform_specific={+ "turn_token": "eof-turn",+ "agent_runtime_turn_token": "eof-runtime",+ }+ ),+ )+ agent._pending_requests[composite_key] = [pending_request]+ agent._remove_specific_pending_reaction = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent.session_handler = SimpleNamespace(+ handle_session_error=AsyncMock(return_value=contained),+ claude_teardown_is_intentional=lambda *_a, **_k: contained,+ cleanup_session=AsyncMock(),+ claude_error_diagnostic=lambda _key, _error: f"Claude process terminated: {returncode}",+ )+ controller.claude_sessions[composite_key] = SimpleNamespace(+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=returncode)),+ )+ controller.receiver_tasks[composite_key] = asyncio.current_task()+ return controller, agent, pending_request++ async def test_receiver_eof_contained_teardown_settles_as_backend_refresh(self):+ key = "session-eof-settle:/tmp/work"+ controller, agent, request = self._eof_agent(key, contained=True)++ await agent._handle_receiver_eof(key, request.context)++ self.assert_contained_settlement(controller.emit_agent_message)++ async def test_receiver_eof_real_failure_still_settles_as_a_backend_failure(self):+ """The negative control: only a CLASSIFIED teardown gets the new semantics."""++ key = "session-eof-real:/tmp/work"+ controller, agent, request = self._eof_agent(key, contained=False, returncode=-6)++ with patch("core.message_mirror.persist_agent_message"):+ await agent._handle_receiver_eof(key, request.context)++ self.assert_uncontained_settlement(controller.emit_agent_message, "-6")++ async def test_receiver_eof_without_a_returncode_settles_as_a_backend_failure(self):+ """A live process that merely stopped talking was never classified at all.++ This is the branch that skips ``handle_session_error`` entirely, so+ ``contained`` is only ever its initial value. If that default were True the+ most common EOF — no returncode, no explanation — would silently become an+ infrastructure interruption.+ """++ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ controller._get_session_key = lambda context: "telegram::user::U1"+ agent = ClaudeAgent(controller)+ agent.record_model_hub_native_failure = AsyncMock()+ key = "session-eof-alive:/tmp/work"+ request = SimpleNamespace(+ context=SimpleNamespace(+ platform_specific={+ "turn_token": "eof-turn",+ "agent_runtime_turn_token": "eof-runtime",+ }+ ),+ )+ agent._pending_requests[key] = [request]+ agent._remove_specific_pending_reaction = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent.session_handler = SimpleNamespace(cleanup_session=AsyncMock())+ controller.claude_sessions[key] = SimpleNamespace(+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=None)),+ )+ controller.receiver_tasks[key] = asyncio.current_task()++ await agent._handle_receiver_eof(key, request.context)++ self.assert_uncontained_settlement(+ controller.emit_agent_message,+ "Claude receiver ended without a terminal result",+ )++ def _receiver_exception_agent(self, composite_key, *, contained):+ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ controller._get_session_key = lambda context: "telegram::user::U1"+ agent = ClaudeAgent(controller)+ agent.record_model_hub_native_failure = AsyncMock()+ request = SimpleNamespace(+ context=SimpleNamespace(+ platform_specific={+ "turn_token": "exc-turn",+ "agent_runtime_turn_token": "exc-runtime",+ }+ ),+ )+ agent._pending_requests[composite_key] = [request]+ agent._clear_pending_reactions = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ agent.session_handler = SimpleNamespace(+ handle_session_error=AsyncMock(return_value=contained),+ claude_teardown_is_intentional=lambda *_a, **_k: contained,+ mark_session_idle=lambda _key: None,+ cleanup_session=AsyncMock(),+ claude_error_diagnostic=lambda _key, _error: "Claude process terminated: SIGTERM",+ )+ controller.claude_sessions[composite_key] = SimpleNamespace(+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-15)),+ )+ return controller, agent, request++ async def test_receiver_exception_contained_teardown_settles_as_backend_refresh(self):+ key = "session-exc-settle:/tmp/work"+ controller, agent, request = self._receiver_exception_agent(key, contained=True)++ await agent._handle_receiver_exception(+ key, request.context, RuntimeError("Cannot write to terminated process (exit code: -15)")+ )++ self.assert_contained_settlement(controller.emit_agent_message)++ async def test_receiver_exception_real_failure_still_settles_as_a_backend_failure(self):+ key = "session-exc-real:/tmp/work"+ controller, agent, request = self._receiver_exception_agent(key, contained=False)++ with patch("core.message_mirror.persist_agent_message"):+ await agent._handle_receiver_exception(+ key, request.context, RuntimeError("boom")+ )++ self.assert_uncontained_settlement(controller.emit_agent_message, "SIGTERM")++ async def test_receiver_exception_requeues_a_claimed_activity_batch(self):+ """A dying receiver must not take an Activity claim down with it.++ The EOF path already requeues before its terminal emit; this one only+ peeked at the FIFO head, so the request still owned the batch and the+ ``run_ids`` on its ``activity_completion_output``. With the contained+ settlement declining to complete the Run, emitting on that output would+ skip those Runs AND drop the claim -- the batch would be neither+ delivered nor redeliverable. Requeueing restores it and strips the+ provenance the release can no longer honour.+ """++ key = "session-exc-activity:/tmp/work"+ controller, agent, request = self._receiver_exception_agent(key, contained=True)+ activity = SessionActivity(+ id="activity-1",+ backend="claude",+ runtime_key=key,+ session_id="ses-1",+ kind="background_task",+ status="completed",+ run_id="run-1",+ )+ request.output_activities = [activity]+ request.output = activity_completion_output(+ activity,+ activities=[activity],+ detached=False,+ completes_turn=True,+ )+ registry = SimpleNamespace(requeue_completed_outputs=Mock())+ agent._activity_registry = lambda: registry++ await agent._handle_receiver_exception(+ key,+ request.context,+ RuntimeError("Cannot write to terminated process (exit code: -15)"),+ )++ registry.requeue_completed_outputs.assert_called_once_with([activity])+ self.assertEqual(request.output_activities, [])+ self.assert_contained_settlement(controller.emit_agent_message)+ released = controller.emit_agent_message.await_args.kwargs["output"]+ self.assertEqual(released.activity_ids, ())+ self.assertIsNone(released.activity_batch_id)+ self.assertEqual(released.run_ids, ())++ async def test_direct_query_contained_teardown_settles_as_backend_refresh(self):+ """The third path: the query itself fails, no receiver ever runs."""++ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ runtime_key = "wechat_o9:reviewer:/tmp/work"+ client = SimpleNamespace(+ query=AsyncMock(+ side_effect=RuntimeError("Cannot write to terminated process (exit code: -9)")+ ),+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)),+ _vibe_runtime_base_session_id="wechat_o9:reviewer",+ _vibe_runtime_session_key=runtime_key,+ )+ controller.session_handler = SimpleNamespace(+ get_or_create_claude_session=AsyncMock(return_value=client),+ mark_session_active=lambda _key: None,+ mark_session_idle=lambda _key: None,+ handle_session_error=AsyncMock(return_value=True),+ claude_teardown_is_intentional=lambda *_a, **_k: True,+ cleanup_session=AsyncMock(),+ capture_session_id=lambda *_: None,+ )+ agent = ClaudeAgent(controller)+ agent.record_model_hub_native_failure = AsyncMock()+ agent._prepare_message_with_files = lambda request: request.message+ agent._delete_ack = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ request = SimpleNamespace(+ context=SimpleNamespace(platform_specific={}),+ message="hello",+ working_path="/tmp/work",+ base_session_id="wechat_o9",+ composite_session_id="wechat_o9:/tmp/work",+ session_key="wechat-user",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ ack_message_id=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ files=None,+ )++ with patch("core.message_mirror.persist_agent_message") as persist:+ await agent.handle_message(request)++ agent.record_model_hub_native_failure.assert_not_awaited()+ persist.assert_not_called()+ self.assert_contained_settlement(controller.emit_agent_message)++ async def test_direct_query_requeues_a_claimed_activity_batch(self):+ """The same claim leak on the path where no receiver ever runs.++ The request joins the FIFO before ``client.query`` is awaited, so a+ background Activity that finishes while the query is in flight attaches+ its batch to exactly this request -- the race the auth branch above+ already requeues for. If the query then fails into a contained teardown,+ the release declines to complete the Run and drops the claim with it.+ Requeue like both receiver paths do.+ """++ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ runtime_key = "wechat_o9:activity:/tmp/work"+ activity = SessionActivity(+ id="activity-2",+ backend="claude",+ runtime_key=runtime_key,+ session_id="ses-2",+ kind="background_task",+ status="completed",+ run_id="run-2",+ )+ request = SimpleNamespace(+ context=SimpleNamespace(platform_specific={}),+ message="hello",+ working_path="/tmp/work",+ base_session_id="wechat_o9",+ composite_session_id="wechat_o9:/tmp/work",+ session_key="wechat-user",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ ack_message_id=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ files=None,+ )++ async def _query_after_activity_lands(*_args, **_kwargs):+ # The batch attaches to the queued request mid-query, then the+ # transport turns out to be gone.+ request.output_activities = [activity]+ request.output = activity_completion_output(+ activity,+ activities=[activity],+ detached=False,+ completes_turn=True,+ )+ raise RuntimeError("Cannot write to terminated process (exit code: -9)")++ client = SimpleNamespace(+ query=AsyncMock(side_effect=_query_after_activity_lands),+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-9)),+ _vibe_runtime_base_session_id="wechat_o9:activity",+ _vibe_runtime_session_key=runtime_key,+ )+ controller.session_handler = SimpleNamespace(+ get_or_create_claude_session=AsyncMock(return_value=client),+ mark_session_active=lambda _key: None,+ mark_session_idle=lambda _key: None,+ handle_session_error=AsyncMock(return_value=True),+ claude_teardown_is_intentional=lambda *_a, **_k: True,+ cleanup_session=AsyncMock(),+ capture_session_id=lambda *_: None,+ )+ agent = ClaudeAgent(controller)+ agent.record_model_hub_native_failure = AsyncMock()+ agent._prepare_message_with_files = lambda req: req.message+ agent._delete_ack = AsyncMock()+ agent._remove_ack_reaction = AsyncMock()+ registry = SimpleNamespace(+ requeue_completed_outputs=Mock(),+ has_active=lambda *_a, **_k: False,+ has_completed_output=lambda *_a, **_k: False,+ )+ agent._activity_registry = lambda: registry++ with patch("core.message_mirror.persist_agent_message"):+ await agent.handle_message(request)++ registry.requeue_completed_outputs.assert_called_once_with([activity])+ self.assertEqual(request.output_activities, [])+ self.assert_contained_settlement(controller.emit_agent_message)+ released = controller.emit_agent_message.await_args.kwargs["output"]+ self.assertEqual(released.activity_ids, ())+ self.assertIsNone(released.activity_batch_id)+ self.assertEqual(released.run_ids, ())+async def test_receiver_eof_terminated_auth_adopts_turn_before_recovery(self):controller = _StubController()controller._get_session_key = lambda context: "telegram::user::U1"diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.pyindex fe7969b18..c7d97461e 100644--- a/tests/test_dispatcher_stream_chunk.py+++ b/tests/test_dispatcher_stream_chunk.py@@ -21,7 +21,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core.message_context import build_context_turn_sink_keyfrom core.message_dispatcher import _stream_chunk-from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT+from core.run_settlement import (+ SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_NO_TERMINAL_RESULT,+ SETTLED_BY_STOPPED,+ SETTLED_BY_TERMINAL_RESULT,+)from modules.im import MessageContext@@ -109,6 +114,47 @@ def test_result_does_not_overwrite_an_acknowledged_stop_stamp():assert sink["settled_by"] == SETTLED_BY_STOPPED+def test_result_does_not_overwrite_a_contained_teardown_stamp():+ """#1204: the same window, the other protected reason.++ The service retired the runtime itself and the release named that settlement.+ A straggler result landing before the row is written would relabel an+ infrastructure interruption as a healthy terminal result — the exact+ disagreement invariant 2 of ``docs/plans/harness-run-reliability.md`` forbids.+ """++ controller = _ControllerDouble()+ done = asyncio.Event()+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done)+ sink = controller.get_turn_sink("avibe::C")+ sink["settled_by"] = SETTLED_BY_BACKEND_REFRESH+ done.set()++ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))++ assert sink["settled_by"] == SETTLED_BY_BACKEND_REFRESH+++def test_result_still_upgrades_the_pessimistic_no_result_stamp():+ """The guard protects two NAMED reasons, not every no-result settlement.++ ``no_terminal_result`` is what a fallback releaser writes when it gives up+ waiting. Upgrading it when a real result finally lands is the whole point of+ the line the two guards sit on — widening them to all of+ ``SETTLEMENTS_WITHOUT_RESULT`` would freeze that pessimistic guess forever.+ """++ controller = _ControllerDouble()+ done = asyncio.Event()+ controller.register_turn_sink("avibe::C", on_chunk=AsyncMock(), done_event=done)+ sink = controller.get_turn_sink("avibe::C")+ sink["settled_by"] = SETTLED_BY_NO_TERMINAL_RESULT++ asyncio.run(_stream_chunk(controller, _ctx(), text="final", message_id="m1", kind="result"))++ assert sink["settled_by"] == SETTLED_BY_TERMINAL_RESULT++def test_notify_kind_leaves_sink_unsettled():# Only a terminal result may claim the honest settlement.controller = _ControllerDouble()diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 8123dbf15..129727ed4 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -9,15 +9,23 @@ from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))from core.message_dispatcher import ConsolidatedMessageDispatcher-from core.message_output import MessageOutput, stop_output_for+from core.message_output import (+ MessageOutput,+ contained_teardown_output_for,+ stop_output_for,+)from core.run_settlement import (+ NON_COMPLETING_TURN_SETTLEMENTS,+ SETTLED_BY_BACKEND_REFRESH,SETTLED_BY_STOPPED,SETTLED_BY_TERMINAL_RESULT,SETTLED_BY_TURN_ONLY_RESULT,SETTLEMENT_TERMINAL_STATUS,SETTLEMENTS_WITHOUT_RESULT,)+from core.session_turns import SessionTurnManagerfrom modules.im import MessageContext+from storage.agent_activity_service import _outcome_statusclass _StubSettingsManager:@@ -261,6 +269,7 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):controller.session_turns.on_terminal_result.assert_called_once_with(context,is_error=False,+ settled_by=SETTLED_BY_TERMINAL_RESULT,terminal_evidence={"result_text": "final output","terminal_error": None,@@ -330,6 +339,7 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):controller.session_turns.on_terminal_result.assert_called_once_with(context,is_error=False,+ settled_by=SETTLED_BY_TERMINAL_RESULT,terminal_evidence={"result_text": "already delivered","terminal_error": None,@@ -444,7 +454,11 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):completes_run=False,)- persist.assert_called_once_with(context, is_error=False)+ persist.assert_called_once_with(+ context,+ is_error=False,+ settled_by=SETTLED_BY_TURN_ONLY_RESULT,+ )async def test_stop_output_release_names_the_stop_and_records_no_run_terminal(self):"""HFR-036: the synthetic result a user stop emits must NOT record the run.@@ -477,6 +491,94 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):dispatcher._record_agent_run_terminal_result.assert_not_called()persist.assert_not_called()+ async def test_contained_teardown_release_names_backend_refresh_and_records_no_run_terminal(+ self,+ ):+ """#1204: a teardown the service performed itself is an infrastructure+ interruption, not a backend result.++ #1202 stopped these from being SHOWN as backend errors; the emit that+ followed still terminalized an ``agent_runs`` row from an empty body. Same+ fix shape as the stop above: name the settlement so the lanes reach the+ writer that maps ``backend_refresh`` to ``failed`` with a structured cause+ (invariant 2 of ``docs/plans/harness-run-reliability.md``), and claim no run+ terminal so the empty body never becomes the result.++ The IM boundary is still written, unlike the stop above — an IM turn has no+ durable execution owner, so this row is the ONLY thing that closes it — but+ it is written with the settlement, so it records ``canceled`` rather than+ asserting a backend fault.+ """+ controller = self._terminal_lifecycle_controller()++ with mock.patch("core.message_dispatcher.persist_silent_terminal") as persist:+ dispatcher, context = await self._emit_silent_terminal(+ controller,+ completes_run=False,+ output=contained_teardown_output_for(None),+ )++ controller.mark_turn_complete.assert_called_once_with(+ context,+ settled_by=SETTLED_BY_BACKEND_REFRESH,+ )+ self.assertIn(SETTLED_BY_BACKEND_REFRESH, SETTLEMENTS_WITHOUT_RESULT)+ # Still terminal, still a failed RUN — the cause is what changed.+ self.assertEqual(SETTLEMENT_TERMINAL_STATUS[SETTLED_BY_BACKEND_REFRESH], "failed")+ # The TURN is canceled, not failed: retired, not broken.+ self.assertEqual(+ NON_COMPLETING_TURN_SETTLEMENTS[SETTLED_BY_BACKEND_REFRESH], "canceled"+ )+ dispatcher._record_agent_run_terminal_result.assert_not_called()+ persist.assert_called_once_with(+ context,+ is_error=False,+ settled_by=SETTLED_BY_BACKEND_REFRESH,+ )++ def test_durable_turn_outcome_never_completes_a_result_less_settlement(self):+ """The Turn-level half of #1204, at the mapper both surfaces share.++ ``_durable_terminal_outcome`` special-cased ``stopped`` only, so a+ ``backend_refresh`` release with no error flag recorded the durable Turn as+ ``completed`` — a retired runtime reported as a finished answer, and a+ straight contradiction of what ``release_for_backend_refresh`` writes for+ the very same event.+ """+ outcome = SessionTurnManager._durable_terminal_outcome++ self.assertEqual(+ outcome(is_error=False, settled_by=SETTLED_BY_BACKEND_REFRESH), "canceled"+ )+ # The settlement outranks the flag: how the turn ended is not a function of+ # whether a result was produced, and both agree it was retired.+ self.assertEqual(+ outcome(is_error=True, settled_by=SETTLED_BY_BACKEND_REFRESH), "canceled"+ )+ self.assertEqual(+ outcome(is_error=False, settled_by=SETTLED_BY_STOPPED), "canceled"+ )+ # Unnamed releases are unchanged — this must not become a blanket override.+ self.assertEqual(outcome(is_error=False, settled_by=None), "completed")+ self.assertEqual(outcome(is_error=True, settled_by=None), "failed")+ self.assertEqual(+ outcome(is_error=False, settled_by=SETTLED_BY_TERMINAL_RESULT), "completed"+ )++ def test_activity_group_status_renders_a_canceled_boundary_as_interrupted(self):+ """The IM trace and the durable Turn must not disagree on one settlement.++ ``list_turn_groups`` already rendered a ``canceled`` durable Turn as+ ``interrupted``; the silent marker that stands in for one on IM was mapped+ with a separate two-way test that could only say ``failed`` or ``done``, so+ the same teardown showed a green ``done`` chip there.+ """+ self.assertEqual(_outcome_status("canceled"), "interrupted")+ self.assertEqual(_outcome_status("not_written"), "interrupted")+ self.assertEqual(_outcome_status("failed"), "failed")+ self.assertEqual(_outcome_status("completed"), "done")+ self.assertEqual(_outcome_status(None), "done")+async def test_slack_result_uses_native_markdown_sender_when_available(self):im_client = _NativeMarkdownIMClient()controller = _StubController(platform="slack", im_client=im_client)@@ -1083,6 +1185,52 @@ class MessageDispatcherStatusChokepointTests(unittest.IsolatedAsyncioTestCase):controller.session_turns.on_terminal_delivery_complete(context)self.assertEqual(controller.status_calls, [("ses-1", "failed")])+ async def test_contained_teardown_does_not_project_a_failed_session(self):+ """The settlement outranks ``is_error`` for the sidebar too.++ No durable Turn owns this session, so this projection IS its terminal+ state. ``is_error`` is honestly ``True`` -- nothing answered -- but the+ service retired the runtime itself, and there is no dot between ``idle``+ and ``failed`` to say so. Without the settlement this read ``failed``,+ contradicting every other surface the same release writes.+ """++ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ dispatcher._collapse_status_bubble = mock.AsyncMock()+ context = _avibe_ctx()+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ output=contained_teardown_output_for(None),+ terminal_error=None,+ )+ controller.session_turns.on_terminal_delivery_complete(context)+ self.assertEqual(controller.status_calls, [("ses-1", "idle")])++ async def test_unnamed_silent_failure_still_projects_a_failed_session(self):+ """Negative control: only a NAMED non-completing settlement is exempt."""++ controller = _AvibeStatusController()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ dispatcher._collapse_status_bubble = mock.AsyncMock()+ context = _avibe_ctx()+ with mock.patch("core.message_dispatcher.persist_agent_message"):+ await dispatcher.emit_agent_message(+ context,+ "result",+ "",+ is_error=True,+ level="silent",+ terminal_error="provider unavailable",+ )+ controller.session_turns.on_terminal_delivery_complete(context)+ self.assertEqual(controller.status_calls, [("ses-1", "failed")])+async def test_silent_backend_failure_collapses_status_as_failed(self):controller = _AvibeStatusController()dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 5aec5105f..e950803dd 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -19,6 +19,8 @@ from core.native_dispatch_phase import (set_dispatch_phase,)from core.run_settlement import (+ SETTLED_BY_BACKEND_REFRESH,+ SETTLED_BY_NO_TERMINAL_RESULT,SETTLED_BY_RESTARTED,SETTLED_BY_STOPPED,SETTLED_BY_TERMINAL_RESULT,@@ -4550,6 +4552,53 @@ def test_canceled_shutdown_runner_preserves_deferred_queue(assert _row(engine, str(queued.delivery_id))["state"] == "queued"+ ("settled_by", "expected_outcome"),+ [+ (SETTLED_BY_BACKEND_REFRESH, "canceled"),+ (SETTLED_BY_RESTARTED, "failed"),+ (SETTLED_BY_NO_TERMINAL_RESULT, "failed"),+ ],+)+def test_cancelled_runner_release_writes_the_settlement_outcome(+ managers,+ settled_by: str,+ expected_outcome: str,+) -> None:+ """The cancellation branch reads the shared Turn-outcome map.++ ``release_for_backend_refresh`` cancels this runner AND terminalizes the+ durable Turns it can reach directly as ``canceled``. When the branch+ hardcoded ``stopped`` as the only non-failure, one rolling refresh landed two+ different outcomes depending on which writer won. ``restarted`` stays+ ``failed`` -- a service shutdown is not a cancellation -- as does the+ pessimistic default a releaser writes when it can name nothing.+ """++ manager, _other, engine, _engine_b, _starts = managers+ turn_id, _context_value = asyncio.run(_activate(manager))++ released = manager._reconcile_durable_runner_release(+ turn_id,+ cancelled=True,+ failed=False,+ prewrite_refused=False,+ definitive_prewrite_exit=False,+ settled_by=settled_by,+ terminal_is_error=True,+ cancel_defers_queue_resume=True,+ )++ assert released["changed"] is True+ with engine.connect() as conn:+ turn = delivery_store.get_turn(conn, turn_id)+ assert turn is not None+ assert turn["terminal_outcome"] == expected_outcome+ # Only a user stop releases the queue here; a refresh still defers it to the+ # post-refresh generation, so the outcome word must not move that lever.+ assert released["defer_queue_resume"] is True++def test_ambiguous_start_failure_defers_runner_queue_resume(managers) -> None:manager, _other, engine, _engine_b, starts = managersadmitted = asyncio.run(