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(vibey): resume failed loops without visible retries (#2689)
Call White7154be7e837d
diff --git a/core/agent_core/agent/README.md b/core/agent_core/agent/README.mdindex 9e3ec117b..7421a28d4 100644--- a/core/agent_core/agent/README.md+++ b/core/agent_core/agent/README.md@@ -21,11 +21,26 @@ agent = Agent(agent.set_tools(build_tools(jobs=agent.jobs))async for event in agent.run(AgentInput(message_id, rendered_input), turn_id=turn_id):await deliver(event)+# Continue from committed context without writing another input row.+async for event in agent.resume(+ AgentInput(message_id, rendered_input),+ turn_id=turn_id,+ turn_inputs=source_turn_input_sequences,+):+ await deliver(event)# Return accepted but unconsumed inputs after an early end, abort, or error.pending = await agent.take_pending_inputs()```-C-9 is on when the adapter passes `context=ContextConfig(host=..., scratch_dir=...)`+`resume(input, turn_id=..., turn_inputs=...)` reruns the loop from the committed+transcript without consuming `input`; the input is only provided to `before_run`+for setup compatibility. A fresh Agent should pass the source Turn's committed+input sequence numbers in `turn_inputs` so context compaction pins only that Turn;+an Agent continuing its own run may omit it and preserves its in-memory set.+It is subject to the same one-active-run and pending-input ownership rules as+`run`. The adapter decides whether a failed run is safe to resume and owns any+retry budget.+(`harness/context.py`); in v1 such an Agent takes no user hooks (a configurationerror). Every conversation request then goes through one pipeline: projection,`budget()` on that request, the C-9 stage (stop, clear, checkpoint at T, overflowdiff --git a/core/agent_core/agent/events.py b/core/agent_core/agent/events.pyindex 3811eeb07..313db4f8c 100644--- a/core/agent_core/agent/events.py+++ b/core/agent_core/agent/events.py@@ -164,6 +164,10 @@ class AgentError:kind: strmessage: strorigin: ErrorOrigin+ #: Provider permissions survive the loop unchanged; local/protocol errors grant neither by default.+ retryable: bool = False+ continuable: bool = False+ retry_after_s: Optional[float] = NoneAgentEvent = Union[diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex cef57b3cf..591f9d2ff 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -406,23 +406,57 @@ class Agent:def run(self, input: AgentInput, *, turn_id: str) -> AsyncIterator[AgentEvent]:input = deepcopy(input)- return self._pump(turn_id, lambda emit: self._drive(emit, input))+ return self._pump(turn_id, lambda emit: self._drive(emit, input, consume=True))++ def resume(+ self,+ input: AgentInput,+ *,+ turn_id: str,+ turn_inputs: Iterable[int] | None = None,+ ) -> AsyncIterator[AgentEvent]:+ """Continue from the committed transcript without consuming another input row.++ The input is still passed to ``before_run`` so existing hook setup remains+ unchanged; it is a control value, not a second transcript message. A fresh+ Agent can provide the source Turn's input sequence numbers so compaction+ pins only that Turn's inputs. Within the same Turn, newly admitted inputs+ extend the existing pins rather than replacing them.+ """+ input = deepcopy(input)+ resume_turn_inputs = None if turn_inputs is None else set(turn_inputs)+ return self._pump(+ turn_id,+ lambda emit: self._drive(emit, input, consume=False),+ preserve_turn_inputs=True,+ resume_turn_inputs=resume_turn_inputs,+ )async def _pump(- self, turn_id: str, drive: Callable[[Callable[..., Awaitable[None]]], Awaitable[None]]+ self,+ turn_id: str,+ drive: Callable[[Callable[..., Awaitable[None]]], Awaitable[None]],+ *,+ preserve_turn_inputs: bool = False,+ resume_turn_inputs: set[int] | None = None,) -> AsyncIterator[AgentEvent]:+ previous_turn_inputs = set(self._turn_inputs)+ previous_seq = self._seqasync with self._lock:if self._running:raise RuntimeError("this Agent already has an active run")if self._steers or self._follow_ups:raise RuntimeError("return unconsumed inputs with take_pending_inputs() before starting another run")+ continuing_turn = preserve_turn_inputs and self._ctx.turn_id == turn_idself._running = Trueself._open = Trueself._consumer_closed = Falseself._ctx = RunContext(self.session_id, turn_id, CancelToken())self._scope = RunScope(self._ctx.cancel)self._outcome = OutcomeOwner()- self._seq = 0+ self._seq = previous_seq if continuing_turn else 0+ if preserve_turn_inputs:+ self._turn_inputs = (previous_turn_inputs if continuing_turn else set()) | set(resume_turn_inputs or ())# Bounded delivery applies backpressure to provider streaming. No emit# awaits this queue while holding the input-admission lock.@@ -552,8 +586,14 @@ class Agent:self._rows.append(row)return row- async def _drive(self, emit: Callable[..., Awaitable[None]], input: AgentInput) -> None:- """One run of ``input``."""+ async def _drive(+ self,+ emit: Callable[..., Awaitable[None]],+ input: AgentInput,+ *,+ consume: bool,+ ) -> None:+ """One run of ``input`` or one transcript-only continuation."""loaded = Falsetry:try:@@ -568,10 +608,12 @@ class Agent:self._committed_state_json = state_representation(self._ctx.state)self._committed_state = deepcopy(self._ctx.state)self._unproductive = 0- self._turn_inputs = set()+ if consume:+ self._turn_inputs = set()self._attempts = []self._refusals = _Refusals()- self._generated_images = []+ if consume:+ self._generated_images = []loaded = Truesystem = self.systemself._run_tools = dict(self._tools)@@ -585,7 +627,8 @@ class Agent:if len(names) != len(set(names)):raise ValueError("tool names must be unique")self._run_tools = dict(zip(names, setup.tools))- await self._consume(input)+ if consume:+ await self._consume(input)self._outcome.primary(await self._loop(system, emit, selected))except _Ended:self._outcome.primary("ended_by_hook")@@ -625,14 +668,20 @@ class Agent:await emit(RunEnded, reason=self._outcome.reason, cause=self._outcome.cause)async def _error(- self, emit: Callable[..., Awaitable[Any]], kind: str, message: str, origin: ErrorOrigin, *, cause: bool+ self, emit: Callable[..., Awaitable[Any]], kind: str, message: str, origin: ErrorOrigin, *, cause: bool,+ provider_error: Optional[ProviderError] = None,) -> None:"""The one place the loop announces an error: ``origin`` as its caller states it, where the error is raised.``cause``: the error decided the run's outcome (``OutcomeOwner.primary``), so ``RunEnded`` names it; adiagnostic never does."""- event = await emit(AgentError, kind=kind, message=message, origin=origin)+ event = await emit(+ AgentError, kind=kind, message=message, origin=origin,+ retryable=provider_error.retryable if provider_error is not None else False,+ continuable=provider_error.continuable if provider_error is not None else False,+ retry_after_s=provider_error.retry_after_s if provider_error is not None else None,+ )if cause:self._outcome.cause = event@@ -994,7 +1043,9 @@ class Agent:# ``aborted`` is the loop's own cancellation and ``overflow`` says our request was too large;# every other provider error is the source's.origin = "local" if terminal.kind in {"aborted", "overflow"} else "source"- await self._error(emit, terminal.kind, terminal.message, origin, cause=decided)+ await self._error(+ emit, terminal.kind, terminal.message, origin, cause=decided, provider_error=terminal+ )if terminal.partial is not None:row = await self._response(terminal.partial, final=False)await emit(MessageCommitted, message_id=row.row_id, context_seq=row.context_seq, final=False)diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex 37635a6b3..f9f666d2d 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -1181,11 +1181,12 @@ class StreamAssembler:kind=kind,message=message,retryable=kind in RETRYABLE_ERROR_KINDS and not self.streamed,+ continuable=kind in RETRYABLE_ERROR_KINDS,retry_after_s=parse_retry_after((headers or {}).get("retry-after")),status=status,partial=partial,)- return error+ return self._after_thinking(error, allow_unknown=True)error = classify_error(body=message,code=code,@@ -1195,7 +1196,7 @@ class StreamAssembler:partial=partial,protocol=self.protocol,)- return error+ return self._after_thinking(error, allow_unknown=True)def exception(self,@@ -1211,7 +1212,7 @@ class StreamAssembler:streamed=self.streamed,partial=self.partial() if self.streamed or self.usage is not None else None,)- return error+ return self._after_thinking(error)def aborted(self, reason: str | None = None) -> ProviderError:return ProviderError(@@ -1233,13 +1234,23 @@ class StreamAssembler:if self._terminal_seen:return Noneif isinstance(event, ProviderError):- event = _bounded_partial_error(self._sanitize_error(_partial_with_error(self._after_thinking(event))))+ event = _bounded_partial_error(self._sanitize_error(_partial_with_error(event)))self._terminal_seen = Truereturn event- def _after_thinking(self, error: ProviderError) -> ProviderError:- """A response that dropped after streaming thinking alone may be retried once (``provider.md``)."""- if self._emitted_output and not self._emitted_visible and error.kind in THINKING_DROP_RETRY_KINDS:+ def _after_thinking(self, error: ProviderError, *, allow_unknown: bool = False) -> ProviderError:+ """The producer alone grants thinking-drop replay, never terminal sanitization or error kind alone.++ Unknown wire failures retain their one request retry; an unknown local exception does not. Neither+ recovery exhaustion nor a refusal can regain permissions just because it names a transient kind.+ """+ if (+ self._emitted_output+ and not self._emitted_visible+ and error.refusal is None+ and error.kind in THINKING_DROP_RETRY_KINDS+ and (error.continuable or (allow_unknown and error.kind == "unknown"))+ ):return replace(error, retryable=True, after_thinking=True)return error@@ -1677,7 +1688,7 @@ def pin_refusal(assembler: StreamAssembler, endpoint: ModelEndpoint, handed_backrefusal = Refusal("pin_unavailable", endpoint.source_id, endpoint.source_identity, handed_back.tool, handed_back.aspect)- return replace(error, retryable=False, refusal=refusal)+ return replace(error, retryable=False, continuable=False, after_thinking=False, refusal=refusal)def portable_endpoint(endpoint: ModelEndpoint) -> ModelEndpoint:@@ -1870,7 +1881,9 @@ async def drive_sse_stream(# A replayed ciphertext this account cannot read, refused before any output: the# loop renders the request again without that identity's opaque payloads (§3.5).refusal = Refusal("opaque_refused", endpoint.source_id, endpoint.source_identity)- candidate = replace(candidate, retryable=False, refusal=refusal)+ candidate = replace(+ candidate, retryable=False, continuable=False, after_thinking=False, refusal=refusal+ )else:resolved_origin = await resolve_served_origin(endpoint,@@ -2097,8 +2110,11 @@ async def prepare_messages(retryable=False,)except Exception as exc:- return classify_error(- body=f"request preparation failed: {type(exc).__name__}: {exc}",+ # Preparation is local: diagnostic text resembling a transient upstream error grants no permission.+ return replace(+ classify_error(body=f"request preparation failed: {type(exc).__name__}: {exc}"),+ retryable=False,+ continuable=False,)return transformed.messages, loaded_imagesdiff --git a/core/agent_core/ai/errors.py b/core/agent_core/ai/errors.pyindex 8f1c9de8d..1fbed40f1 100644--- a/core/agent_core/ai/errors.py+++ b/core/agent_core/ai/errors.py@@ -169,6 +169,7 @@ def classify_error(kind=kind,message=message,retryable=retryable,+ continuable=kind in RETRYABLE_ERROR_KINDS,retry_after_s=retry_after,status=status,partial=partial,diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex e90a5b215..c83dab814 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -221,6 +221,9 @@ class ProviderError:#: A refusal before any output, which the loop answers by rendering the request again (``vibey-hosted-tools.md``#: §3.5), never by the generic retry.refusal: Optional["Refusal"] = None+ #: Permission to continue from the committed transcript, not replay this request. False by default:+ #: only a classified transient failure grants it, even when streaming makes ``retryable`` false.+ continuable: bool = False@dataclass(frozen=True)diff --git a/core/backend_failure_retry.py b/core/backend_failure_retry.pyindex 3f3d62123..52c859471 100644--- a/core/backend_failure_retry.py+++ b/core/backend_failure_retry.py@@ -156,6 +156,10 @@ def reserve_retry(and source_turn["terminal_outcome"] == "not_written"else [])+ backend = conn.execute(+ select(agent_sessions.c.agent_backend).where(agent_sessions.c.id == session_id)+ ).scalar_one_or_none()+ vibey_resume = backend == "vibey" and not originalturn = _validate_boundary(conn, notice, exclude_ids={row["id"] for row in original})delivery_id = str(turn["initial_delivery_id"]) if original else deliveries.new_delivery_id()binding = {@@ -177,14 +181,42 @@ def reserve_retry(if saved is None:raise RuntimeError("retry retained input claim lost")else:+ retry_snapshot = dict(snapshot)+ dispatch_text = "continue"+ if vibey_resume:+ # Vibey resumes its committed transcript. Keep the Delivery as the+ # durable ownership record, but do not create a visible user input.+ retry_snapshot.update(+ {+ "author": "harness",+ "source": "harness",+ "type": "agent_initiated",+ "content_text": None,+ "content_json": "{}",+ }+ )+ metadata = json.loads(str(retry_snapshot.get("metadata_json") or "{}"))+ if not isinstance(metadata, dict):+ metadata = {}+ metadata.update(+ {+ deliveries.VIBEY_RESUME_METADATA_KEY: True,+ "retry_notice_id": notice_id,+ deliveries.VIBEY_SOURCE_TURN_METADATA_KEY: turn["id"],+ }+ )+ retry_snapshot["metadata_json"] = json.dumps(+ metadata, ensure_ascii=False, sort_keys=True, separators=(",", ":")+ )+ dispatch_text = ""deliveries.insert_delivery(conn,delivery_id=delivery_id,session_id=session_id,priority="p3",state="reserved",- snapshot=snapshot,- dispatch_text="continue",+ snapshot=retry_snapshot,+ dispatch_text=dispatch_text,history_event=binding,)content = dict(notice["content"])diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 2e9368da0..d4b029571 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -199,7 +199,10 @@ class MessageHandler(BaseHandler):# If message is empty AND no files attached (e.g., user just @mentioned bot without text),# trigger the /start command instead of sending empty message to agenthas_files = bool(context.files)- if (not message or not message.strip()) and not has_files:+ internal_vibey_resume = bool(+ (context.platform_specific or {}).get("vibey_resume") is True+ )+ if (not message or not message.strip()) and not has_files and not internal_vibey_resume:if is_human:await self.controller.command_handler.handle_start(context, "")return Nonediff --git a/core/internal_server.py b/core/internal_server.pyindex 66852d5e0..ebffd6cf0 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1248,6 +1248,9 @@ def create_app("text": str(delivery.get("dispatch_text") or ""),"files": attachment_specs,"platform": delivery_payload.get("platform"),+ "type": delivery_payload.get("type"),+ "author": delivery_payload.get("author"),+ "source": delivery_payload.get("source"),"user_id": delivery_payload.get("author_id"),"message_id": delivery_payload.get("native_message_id") or delivery_id,"thread_id": delivery_payload.get("parent_native_message_id"),@@ -1877,12 +1880,13 @@ async def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, Messageif not isinstance(session_id, str) or not session_id.strip():raise ValueError("session_id is required")- # A turn may be text-only, attachments-only (the agent reads the files), or- # both. ``files`` are already-local web uploads resolved from media tokens.+ # Text/files or a hidden control Delivery, whose entire provenance the+ # endpoint restored from storage above (never from the wake-up request).from core.workbench_media import file_attachments_from_specs+ from storage.message_deliveries import is_vibey_resume_payloadfiles = file_attachments_from_specs(payload.get("files"))- if not text.strip() and not files:+ if not text.strip() and not files and not is_vibey_resume_payload(payload):raise ValueError("text or files is required")context = await asyncio.to_thread(diff --git a/core/session_turns.py b/core/session_turns.pyindex 0f79e8b10..e9ba9be98 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -2001,6 +2001,21 @@ class SessionTurnManager:raise RuntimeError("runtime-rejected Delivery queue fallback lost")return None+ # Admission can claim an older queued segment, and FIFO may resolve its+ # runtime only after inspecting input. Gate the actual claimed backend+ # here as well, using each durable row rather than the waking request.+ incompatible_resumes = [+ delivery for delivery in deliveries+ if backend != "vibey"+ and delivery_store.is_vibey_resume_payload(delivery_store.delivery_payload(delivery))+ ]+ if incompatible_resumes:+ for delivery in incompatible_resumes:+ cls._retire_delivery_not_written(+ conn, session_id, str(delivery["id"]), reason="backend_changed"+ )+ return None+denied_remote = [(delivery, reason)for delivery in deliveries@@ -2434,6 +2449,14 @@ class SessionTurnManager:{"delivery_id": str(delivery["id"]),"delivery_source": payload.get("source"),+ "vibey_resume": delivery_store.is_vibey_resume_payload(payload),+ "vibey_source_turn_id": (+ (payload.get("metadata") or {}).get(+ delivery_store.VIBEY_SOURCE_TURN_METADATA_KEY+ )+ if delivery_store.is_vibey_resume_payload(payload)+ else None+ ),"scope_id": payload.get("scope_id"),"display_text": payload.get("text") or "","message_content": dict(payload.get("content") or {}),@@ -2484,12 +2507,14 @@ class SessionTurnManager:return raw_session_idreturn session_id- @staticmethoddef _has_resolvable_delivery_input(+ self,conn: Connection,delivery: dict[str, Any],) -> bool:payload = delivery_store.delivery_payload(delivery)+ if delivery_store.is_vibey_resume_payload(payload):+ return Truefrom core.workbench_media import resolve_attachment_specsspecs = resolve_attachment_specs(@@ -2836,7 +2861,19 @@ class SessionTurnManager:if not content_present and request.content == "":request = replace(request, content=None)if request.priority == "p3" and not content_present:- raise ValueError("P3 requires content")+ delivery = None+ if request.delivery_id:+ with self._sqlite_engine().connect() as conn:+ delivery = delivery_store.get_delivery(conn, request.delivery_id)+ # submit() is a wake-up, not the producer of hidden retry provenance.+ # Neither its default user fields nor caller-supplied markers decide+ # whether an empty Delivery is an authorized continuation.+ if not (+ delivery is not None+ and delivery["session_id"] == request.session_id+ and delivery_store.is_vibey_resume_payload(delivery_store.delivery_payload(delivery))+ ):+ raise ValueError("P3 requires content")backend, resolved_context = self._delivery_backend(request.session_id,context,@@ -2885,6 +2922,24 @@ class SessionTurnManager:priority="p3",state="queued",)+ if (+ delivery_store.is_vibey_resume_payload(delivery_store.delivery_payload(delivery))+ and backend != "vibey"+ and delivery["state"] in {"queued", "reserved"}+ ):+ self._retire_delivery_not_written(+ conn,+ request.session_id,+ str(delivery["id"]),+ reason="backend_changed",+ )+ delivery = delivery_store.get_delivery(conn, str(delivery["id"])) or delivery+ return DeliveryResult(+ str(delivery["id"]),+ str(delivery.get("message_id") or "") or None,+ "retired",+ reason="backend_changed",+ )if delivery["state"] not in {"queued", "reserved"}:return DeliveryResult(str(delivery["id"]),@@ -4316,6 +4371,13 @@ class SessionTurnManager:for row in deliveriesif not self._has_resolvable_delivery_input(conn, row)}+ # The final routing context is rebuilt after claim. Both that route+ # and the bound Turn must still support the hidden control input.+ if str(turn["backend"]) != "vibey" or self._context_backend(resolved) != "vibey":+ invalid_delivery_ids.update(+ str(row["id"]) for row in deliveries+ if delivery_store.is_vibey_resume_payload(delivery_store.delivery_payload(row))+ )remote_authorization_denials = {str(row["id"]): reasonfor row in deliveriesdiff --git a/docs/plans/agent-core-contracts/agent-event.schema.json b/docs/plans/agent-core-contracts/agent-event.schema.jsonindex 5e61c7451..8a4111c92 100644--- a/docs/plans/agent-core-contracts/agent-event.schema.json+++ b/docs/plans/agent-core-contracts/agent-event.schema.json@@ -377,6 +377,9 @@"message": {"type": "string"},+ "retryable": { "type": "boolean", "default": false },+ "continuable": { "type": "boolean", "default": false },+ "retry_after_s": { "type": ["number", "null"], "minimum": 0 },"origin": {"enum": ["source",@@ -409,6 +412,9 @@"message": {"type": "string"},+ "retryable": { "type": "boolean", "default": false },+ "continuable": { "type": "boolean", "default": false },+ "retry_after_s": { "type": ["number", "null"], "minimum": 0 },"origin": {"description": "source: the served model produced the failure (a provider error other than an overflow, an answer the loop rejected, a response the transcript cannot hold); local: everything else (a Stop, an overflow or context exhaustion, a hook, tool, or store error).","enum": [diff --git a/docs/plans/agent-core-contracts/loop-control.md b/docs/plans/agent-core-contracts/loop-control.mdindex 8d99133ec..6b9c859ea 100644--- a/docs/plans/agent-core-contracts/loop-control.md+++ b/docs/plans/agent-core-contracts/loop-control.md@@ -12,6 +12,7 @@ class Agent:context: ContextConfig | None = None) -> None: ... # C-9; excludes hooks in v1 (§3)def run(self, input: Input, *, turn_id: str) -> AsyncIterator[AgentEvent]: ... # one Avibe Turn+ def resume(self, input: Input, *, turn_id: str, turn_inputs: Iterable[int] | None = None) -> AsyncIterator[AgentEvent]: ...def steer(self, input: Input) -> bool: ... # False: not accepted, the adapter keeps ownershipdef follow_up(self, input: Input) -> bool: ...def abort(self, reason: str) -> None: ...@@ -26,7 +27,23 @@ class Agent:wraps the given `JobHost` (`Agent.jobs`) to track foreground jobs for `abort`; tools are constructed with thatwrapper.-## 2. One run+A transcript-only `resume` uses the same loop and cleanup path as `run`, but skips+input consumption. It may be used only after the previous run has closed; the+adapter supplies an existing input to `before_run` for hook setup but does not+write a second `input` row. A fresh Agent passes the source Turn's committed input+sequence numbers through `turn_inputs`; an Agent continuing its own run preserves+its in-memory Turn-input set when the argument is omitted. Retry eligibility and+retry budgets are adapter policy, not loop policy.++A provider-caused `AgentError` preserves `retryable`, `continuable`, and `retry_after_s`; other errors default+to false/false/None. Vibey continues only a source error explicitly marked `continuable`, with no committed final+and no Stop. It permits at most five additional runs on the same Agent, with exponential backoff bounded by the+loop's delay settings and Retry-After as a floor. One elapsed window (the loop policy's `max_elapsed_s`, at most+120 seconds) starts at the first eligible failed run and includes all subsequent recovery work, waits, and runs;+it is not restarted by `resume`. A delay that does not fit denies another continuation. Expiry prevents new+continuations without interrupting a run already doing useful work. Stop wakes backoff immediately and settles+the Turn as stopped without another provider request or a failure notice.+```textcommit input → loop:diff --git a/docs/plans/agent-core-contracts/provider-event.schema.json b/docs/plans/agent-core-contracts/provider-event.schema.jsonindex ac5ed48f8..468b7cda0 100644--- a/docs/plans/agent-core-contracts/provider-event.schema.json+++ b/docs/plans/agent-core-contracts/provider-event.schema.json@@ -42,6 +42,7 @@"type": { "const": "error" },"kind": { "enum": ["overflow", "rate_limit", "overloaded", "network", "stalled", "server", "interrupted", "auth", "invalid_request", "aborted", "unknown"] },"retryable": { "type": "boolean" },+ "continuable": { "type": "boolean", "default": false, "description": "Explicit permission to continue from committed context, separate from same-request replay. Classified transient failures allow it; recovery exhaustion, refusals, permanent and local failures do not." },"retry_after_s": { "type": "number", "minimum": 0 },"after_thinking": { "type": "boolean", "description": "The response streamed thinking and nothing else before this transient or unknown error; the loop retries it at most once per request (provider.md)." },"status": { "type": "integer", "description": "HTTP status, when there was one." },diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex e6f75786d..931823f77 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -117,6 +117,17 @@ opaque payload of an unknown vendor can ever be replayed. A block without a signError classification is part of the contract because the loop branches on it:+`retryable` permits replay of the same request. `continuable` (default false) separately permits a new run+from the committed transcript after the failed run closes. Classified transient errors grant continuation even+when streamed output forbids replay. Model Hub's `model_hub_recovery_exhausted` ending, explicit pin/opaque+refusals, permanent/protocol errors, unclassified failures, and local preparation errors grant no continuation.+Neither the terminal sanitizer nor a downstream consumer may infer permission from `kind` alone. In particular,+a recovery-exhausted error naming `server` stays non-retryable and non-continuable after thinking, too.++The loop carries both permissions and `retry_after_s` into the terminal `AgentError` unchanged. These fields do+not grant permission to replay committed tools or manufacture user input; Vibey uses `Agent.resume` under its+own bounded continuation policy (`loop-control.md`).+| `kind` | Meaning | Loop action || --- | --- | --- || `overflow` | the request exceeded the model's context (Pi's overflow patterns and Anthropic's refusal of input plus `max_tokens` over the window, HTTP 413, `context_length_exceeded`) | overflow recovery (plan §5.2) |@@ -132,7 +143,8 @@ most once per request, inside the same count and time budget; a second drop endssome prompts drop at the same point every time. The dropped attempt's thinking is never context: it stays in theattempt ledger and its audit (C-9 `context.md` §10, invariant 4), and the retry resends the original request.A refusal or safety stop is a response, not an error, and `auth`, `invalid_request`, `overflow`, and `rate_limit`-after thinking stay terminal.+after thinking stay terminal. The unknown-wire exception grants one request replay only, not transcript+continuation; an unknown local exception does not acquire the thinking-drop exception.A `ProviderError` whose `partial` is committed (a response that failed after output) carries the error's text as thatpartial's `error_message`, redacted like the error itself and bounded to 1,000 characters, so the transcript row saysdiff --git a/docs/plans/agent-core-contracts/transcript.md b/docs/plans/agent-core-contracts/transcript.mdindex 0b005a90b..94e5d39f1 100644--- a/docs/plans/agent-core-contracts/transcript.md+++ b/docs/plans/agent-core-contracts/transcript.md@@ -48,6 +48,10 @@ and usage) or- Inputs already exist as rows when they are submitted. The loop sets `context_seq` and `content_json.model` on thatrow when it consumes the input. Each entry is its own transaction; an input accepted by `steer` but not yetconsumed when a crash happens is admitted into the context by the adapter at resume (`recovery.md` T3).+- The adapter binds live writes to the durable Turn ID independently of input consumption. A transcript-only+ retry therefore writes tool results, context edits, state, and audits against its new retry Turn, not the last+ consumed input's Turn. Response metadata records that Turn ID at commit time; T2 recovery and job handover use+ the response's identity after restart. Legacy responses without it retain the input-order fallback.- A response row is inserted at `message_end` with both `content_json.model` and its commit-time display`content_text`.- A tool result row is inserted at `tool_finished`. The `tool_call` trace row is inserted at tool start without adiff --git a/docs/plans/backend-failure-retry.md b/docs/plans/backend-failure-retry.mdindex e478b4c96..334355fb5 100644--- a/docs/plans/backend-failure-retry.md+++ b/docs/plans/backend-failure-retry.md@@ -3,7 +3,8 @@## ContractThe retry button is a user action on one authoritative backend-failure notice,-not a new backend retry protocol or an automatic retry policy.+not a new backend retry protocol. Vibey's bounded automatic continuation is an+adapter-local policy over the same committed transcript.- Only an attached `notify` with `event=backend_failure`, a `failure_id`, and adurable `turn_id` can offer the action. Ordinary notifications, detached@@ -36,8 +37,15 @@ not a new backend retry protocol or an automatic retry policy.rechecks access, archive/read-only status, current Turn, and pending input.A newer task, another live owner, or an unresolved native start blocks it.- A normal failed Turn continues through the existing P3 Delivery admission- with the literal backend input `continue`. It does not roll back history,- replay already attempted tools, or pretend to resume an arbitrary native Turn.+ with the literal backend input `continue`. Vibey is the deliberate exception:+ an accepted Vibey Turn retries from its committed transcript through a hidden+ `agent_initiated` Delivery, so no visible `continue` Message is created. It+ also performs up to five additional transcript continuations automatically+ for transient provider failures before emitting the failure notice. The hidden+ ownership row is excluded from Vibey's T3 unconsumed-input recovery, and a+ backend change before admission retires the Vibey-specific Delivery rather+ than sending an empty prompt to a native backend. Neither path rolls back+ transcript history or replays a committed tool call.- A proven `not_written` Turn reuses its retained, unaccepted initial Deliveryand the normal queue/admission path, preserving its prompt and attachments.Unknown native acceptance is not proof that replay is safe.@@ -47,8 +55,9 @@ not a new backend retry protocol or an automatic retry policy.- Retry is independent of the composer draft. The original error remainsvisible; the button reports that retry was requested. Accepted continuationinput remains in the ordinary transcript for truthful history.-- There is no implicit model switch, auth reset, service restart, automatic- retry loop, native history truncation, or new storage table.+- There is no backend-wide automatic retry loop, implicit model switch, auth reset,+ service restart, native history truncation, or new storage table. Vibey's bounded+ continuation is the adapter-local exception described above.## Interfaces and ownership@@ -71,7 +80,9 @@ unaccepted continuations can be reserved again only while the failed-Turnboundary still holds. Server-owned `backend_failure_retry` Delivery historybinds the notice, source Turn, and exact retained batch for admission and queuedrain checks. Once a native start is claimed, subsequent recovery stays owned-by the existing Turn state machine.+by the existing Turn state machine. For Vibey, the continuation marker is kept+in the hidden Delivery snapshot and the Agent loop resumes without consuming a+new user input row.A retained original may already be queued before the click. Its action projects`reserved` until the controller records this action's P3 admission or claims a@@ -84,9 +95,11 @@ message reads derive the same action state from durable storage.The Web notification renderer uses the existing design-system Button withlocalized labels (`重试` / `Retry`, `已请求重试` / `Retry requested`). It exposesno action on read-only Sessions and cannot invoke a retry twice while submitting.-This first change targets the external Web conversation surface. All three-backend adapters benefit from the shared admission path without separate retry-implementations; IM-specific notification button rendering is not added here.+This first change targets the external Web conversation surface. Native backend+adapters retain the shared admission path and literal `continue` behavior;+Vibey additionally uses its loop resume path for accepted retries and automatic+transient-failure continuations. IM-specific notification button rendering is+not added here.## Validation@@ -96,8 +109,8 @@ implementations; IM-specific notification button rendering is not added here.- Real storage/admission tests: same-notice concurrency and duplicate delivery,pre-write prompt/attachment preservation, failed submission recovery, andcomposer draft preservation.-- Web route tests: access checks, canonical server-generated payload, source- notice update, and reloading persisted action state.+- Agent-core and Vibey adapter tests: transcript-only resume, bounded automatic+ continuation, hidden Vibey Retry input, and committed tool-result reuse.- UI tests: eligible notification, ineligible/read-only rows, pending/acceptedfeedback, failure recovery, and draft-independent action; mounted ChatPagepreservation of newer Activity/thinking after replayed notices, with ordinary@@ -109,6 +122,41 @@ Scenario contracts: `MESSAGE-DELIVERY-026` through `MESSAGE-DELIVERY-028`.Restart notification binding and continuation: `MESSAGE-DELIVERY-030`.Harness-owned notification binding and continuation: `MESSAGE-DELIVERY-320`.+## Review-boundary correction contract++The second findings-bearing head exposed the same ownership class in new paths:+resume is control-plane work, not another model input. The orchestrator stops+path-by-path patching and retains the existing Delivery/Turn/Agent model, with+these complete boundary fixes (no new retry service or state machine):++- Internal dispatch derives resume permission only from the durable Delivery's+ `type`, `author`, `source`, and server marker. Admission, FIFO claim, and final+ dispatch must reject that control Delivery on any resolved non-Vibey backend.+- Provider errors distinguish replay permission (`retryable`) from transcript+ continuation permission (`continuable`, default false). Transient streamed+ failures can allow continuation without request replay; Model Hub recovery+ exhaustion, explicit refusals, permanent errors, and local errors allow neither.+ AgentError preserves these permissions and Retry-After. Automatic continuation+ honors the delay and one bounded elapsed budget across all five continuations.+- The adapter supplies the active durable Turn ID to transcript writes, separately+ from input consumption. T2 recovery keeps the originating failed call's Turn;+ retry execution writes new events against the retry Turn.+- Resume pins include every accepted input of the failed task, including returned+ steers and inputs inherited through retry ancestry. Automatic resume unions+ newly admitted sequence numbers with the same Agent's current pins.+- Hidden control rows stay out of model context and out of the indexed population+ of recoverable inputs. Recovery must not resolve attachments or fetch Delivery+ snapshots for historical hidden rows. Recovery seeks Messages first, then+ their Deliveries by indexed `message_id`, and Turns by primary key; tests+ reject historical scans at every join, not only the Message table. Migration+ upgrade, downgrade, and head-schema repair preserve those indexes.++Validation uses real Web-to-internal dispatch, FIFO backend changes, provider+classification through continuation, returned steers, repeated user retries,+event attribution, and recovery query plans. The existing CI failure in+`tests/test_vibey_agent_context.py` reproduces the lost provider permission and+must pass without weakening its source-failure attribution assertions.+## Known by designNative backend APIs do not provide one verified retry operation for all terminaldiff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 2205c32f8..9d10faeb1 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -37,7 +37,7 @@ from types import SimpleNamespacefrom typing import Any, AsyncIterator, Callable, Mapping, Optional, Sequenceimport httpx-from sqlalchemy import and_, select+from sqlalchemy import and_, select, text as sql_textfrom sqlalchemy.engine import Enginefrom config import paths@@ -117,6 +117,7 @@ from storage.agent_transcript import ()from storage.db import get_cached_sqlite_enginefrom storage.models import agent_events, agent_sessions, message_deliveries, messages, session_turns+from storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATEfrom vibe.i18n import t as i18n_tlogger = logging.getLogger(__name__)@@ -125,6 +126,7 @@ BACKEND = "vibey"# Final responses whose empty text is explained by the stop itself (loop-control.md section 2)._EXPLAINED_STOPS = ("length", "refusal", "safety")_COMPLETED = ("completed", "ended_by_hook")+_MAX_AUTO_CONTINUATIONS = 5_JOB_PRUNE_INTERVAL_S = 3600.0@@ -200,7 +202,13 @@ class _Run:reply_images: dict[str, tuple[HostedImage, ...]] = field(default_factory=dict)# Steer attempts ``Agent.steer`` accepted into this run: reconcile's in-process evidence.accepted_steers: set[str] = field(default_factory=set)+ # Automatic transcript-only continuations already spent by this Turn. The+ # initial model call is not counted; the limit is five additional attempts.+ continuations: int = 0+ # One elapsed window from the first continuable failure, shared by every outer continuation.+ continuation_started_at: Optional[float] = Nonestop_requested: bool = False+ stop_event: asyncio.Event = field(default_factory=asyncio.Event)# When each tool call started (monotonic), for a proxied hosted call's duration.tool_started: dict[str, float] = field(default_factory=dict)# Images the run's hosted calls generated, as (path, label), attached to its final reply.@@ -318,7 +326,7 @@ class VibeyAgent(BaseAgent):context = request.context# Rows this Turn writes are the Turn's Agent's, from its request snapshot, even if the# Session's selected Agent changes while it runs.- self.store.bind_agent(session_id, request.vibe_agent_name)+ self.store.bind_agent(session_id, request.vibe_agent_name, turn_id=turn.turn_id)await self._resume(runtime)if turn.stop_requested:return await self._settle_stopped(turn)@@ -352,20 +360,126 @@ class VibeyAgent(BaseAgent):await indicator.delete_ack_message(request)accept_catalog(self.controller, context, skill_catalog, backend=BACKEND)agent_input: Optional[AgentInput] = AgentInput(input_id, message)+ platform_specific = context.platform_specific or {}+ transcript_resume = platform_specific.get("vibey_resume") is True+ resume_turn_inputs = (+ await asyncio.to_thread(+ self._resume_turn_inputs, session_id, platform_specific.get("vibey_source_turn_id")+ )+ if transcript_resume+ else None+ )while agent_input is not None:if turn.stop_requested:# A Stop acknowledged before this run could abort: no run starts. An input# left unconsumed is admitted at the Session's next resume (T3).turn.reason = "aborted"break- async for event in turn.agent.run(agent_input, turn_id=turn.turn_id):+ stream = (+ turn.agent.resume(+ agent_input,+ turn_id=turn.turn_id,+ turn_inputs=resume_turn_inputs,+ )+ if transcript_resume+ else turn.agent.run(agent_input, turn_id=turn.turn_id)+ )+ transcript_resume = False+ resume_turn_inputs = None+ async for event in stream:await self._on_event(turn, event)+ if self._can_auto_continue(turn) and turn.continuations < _MAX_AUTO_CONTINUATIONS:+ if turn.continuation_started_at is None:+ turn.continuation_started_at = time.monotonic()+ # Finish T2 before asking the same Agent to build its next request.+ # Accepted P1 inputs are admitted into the transcript, but never+ # become an implicit user-visible continuation message.+ await self._settle_left_open(runtime)+ resume_turn_inputs = await self._admit_returned_inputs(turn)+ if await self._wait_auto_continue(turn):+ turn.continuations += 1+ turn.reason = None+ turn.cause = None+ turn.final_row = None+ transcript_resume = True+ continueagent_input = await self._continuing_input(turn)if turn.reason not in _COMPLETED:await self._settle_left_open(runtime)await self._settle(turn)self._maybe_backfill_session_title(request, session_id)+ def _resume_turn_inputs(self, session_id: str, source_turn_id: Any) -> tuple[int, ...]:+ """Committed inputs of the failed task, including steers across its retry ancestry."""+ if not isinstance(source_turn_id, str) or not source_turn_id:+ return ()+ pins: set[int] = set()+ visited: set[str] = set()+ with self._engine.connect() as conn:+ while source_turn_id and source_turn_id not in visited:+ visited.add(source_turn_id)+ turn = delivery_store.get_turn(conn, source_turn_id)+ if turn is None or turn["session_id"] != session_id or turn["backend"] != BACKEND:+ break+ pins.update(conn.execute(+ select(messages.c.context_seq)+ .select_from(message_deliveries.join(messages, message_deliveries.c.message_id == messages.c.id))+ .where(+ message_deliveries.c.turn_id == source_turn_id,+ messages.c.session_id == session_id,+ messages.c.context_seq.is_not(None),+ messages.c.type.in_(INPUT_TYPES),+ )+ ).scalars())+ initial = delivery_store.get_delivery(conn, turn["initial_delivery_id"])+ payload = delivery_store.execution_delivery_payload(conn, initial) if initial else {}+ if not delivery_store.is_vibey_resume_payload(payload):+ break+ source_turn_id = payload["metadata"].get(delivery_store.VIBEY_SOURCE_TURN_METADATA_KEY)+ if not isinstance(source_turn_id, str):+ break+ return tuple(sorted(pins))++ @staticmethod+ def _can_auto_continue(run: _Run) -> bool:+ """Whether the failed request can safely be retried from committed context."""++ cause = run.cause+ return bool(+ not run.stop_requested+ and run.reason == "error"+ and not run.final_row+ and cause is not None+ and cause.origin == "source"+ and cause.continuable+ )++ async def _wait_auto_continue(self, run: _Run) -> bool:+ """Honor the provider's delay floor and one elapsed budget, with Stop owning the wait.++ The initial run is not in this window. Subsequent runs and recovery work spend it, not just backoff.+ Expiry prevents another continuation, but never interrupts a run already doing useful work.+ """+ if run.stop_requested:+ run.reason = "aborted"+ return False+ if not self._can_auto_continue(run):+ return False+ policy = run.agent.retry+ elapsed = time.monotonic() - run.continuation_started_at+ backoff = min(policy.max_delay_s, policy.initial_delay_s * 2**run.continuations)+ delay = max(backoff, run.cause.retry_after_s or 0.0)+ if elapsed + delay >= policy.max_elapsed_s:+ return False+ try:+ await asyncio.wait_for(run.stop_event.wait(), timeout=delay)+ except asyncio.TimeoutError:+ pass+ if run.stop_requested:+ run.reason = "aborted"+ return False+ return time.monotonic() - run.continuation_started_at < policy.max_elapsed_s+async def _settle_stopped(self, turn: _Run) -> None:"""A Stop before the loop started: the Turn settles as stopped, nothing dispatched."""turn.reason = "aborted"@@ -377,6 +491,7 @@ class VibeyAgent(BaseAgent):request.stop_failure_reason = "not_active"return Falserun.stop_requested = True+ run.stop_event.set()if run.agent is not None:run.agent.abort("stopped by user")return True@@ -403,6 +518,7 @@ class VibeyAgent(BaseAgent):run = runtime.runif run is not None and run.request.session_key == session_key:run.stop_requested = True+ run.stop_event.set()if run.agent is not None:run.agent.abort("session cleared")cleared += 1@@ -789,23 +905,26 @@ class VibeyAgent(BaseAgent):run.reason = Nonereturn pending[-1]- async def _admit_returned_inputs(self, run: _Run) -> None:+ async def _admit_returned_inputs(self, run: _Run) -> tuple[int, ...]:"""Inputs a stopped or failed run accepted but did not consume enter the context (T3).They belong to the Turn that accepted them and share its outcome, as a messagemerged into another backend's stopped or failed turn does; the next Turnanswers them with the full context."""+ consumed: list[int] = []if run.agent is None:- return+ return ()try:for item in await run.agent.take_pending_inputs():- await self.store.consume_input(run.session_id, item.message_id, item.message)+ entry = await self.store.consume_input(run.session_id, item.message_id, item.message)+ consumed.append(entry.context_seq)except Exception:# The rows stay accepted and unconsumed: the recovery owner admits them (T3)# without waiting for the Session's next message.logger.exception("Vibey could not admit returned inputs for Session %s", run.session_id)self._schedule_recovery()+ return tuple(consumed)# --- resume (recovery.md T2, T3) -------------------------------------------@@ -875,8 +994,8 @@ class VibeyAgent(BaseAgent):# A tool result is the Agent's that made the call: its owning response's author, not# the Turn writing it now (or none, at startup) or the Session's current selection.# Only the last response can hold open calls, so they share one owner.- owner_agent = await asyncio.to_thread(self._author_of, open_calls[0][0].row_id)- with self.store.writing_as(session_id, owner_agent):+ owner_agent, owner_turn = await asyncio.to_thread(self._response_owner, open_calls[0][0].row_id)+ with self.store.writing_as(session_id, owner_agent, turn_id=owner_turn):await settle_open_calls(session_id=session_id,store=self.store,@@ -885,9 +1004,14 @@ class VibeyAgent(BaseAgent):render_result=suite.render_recovered,)- def _author_of(self, row_id: str) -> Optional[str]:+ def _response_owner(self, row_id: str) -> tuple[Optional[str], Optional[str]]:with self._engine.connect() as conn:- return conn.execute(select(messages.c.author_name).where(messages.c.id == row_id)).scalar()+ row = conn.execute(+ select(messages.c.author_name, messages.c.metadata_json).where(messages.c.id == row_id)+ ).first()+ if row is None:+ return None, None+ return row.author_name, _json_object(row.metadata_json).get("turn_id")def _job_route(self, meta: Mapping[str, Any]) -> dict[str, Any]:"""A job Watch's Agent and authorization, from the job's owning Turn (fail closed).@@ -912,13 +1036,15 @@ class VibeyAgent(BaseAgent):session_id = call.session_idwith self._engine.connect() as conn:owner = conn.execute(- select(messages.c.author_name).where(+ select(messages.c.author_name, messages.c.metadata_json).where(messages.c.id == call.response_id,messages.c.session_id == session_id,messages.c.context_seq == call.response_seq,)).first()- origin = self._turn_initial_input(conn, session_id, call.response_seq) if owner else None+ origin = self._turn_initial_input(+ conn, session_id, call.response_seq, turn_id=_json_object(owner.metadata_json).get("turn_id")+ ) if owner else Noneif owner is None or origin is None:return {"unverifiable_remote": True}route: dict[str, Any] = {"agent_name": owner.author_name} if owner.author_name else {}@@ -945,8 +1071,20 @@ class VibeyAgent(BaseAgent):return {**route, "user_context": context}@staticmethod- def _turn_initial_input(conn: Any, session_id: str, before_seq: int) -> Optional[dict]:- """The initial input row of the Turn whose input precedes ``before_seq``."""+ def _turn_initial_input(+ conn: Any, session_id: str, before_seq: int, *, turn_id: Optional[str] = None+ ) -> Optional[dict]:+ """The response's durable Turn input; legacy responses use context order."""+ if turn_id is not None:+ row = conn.execute(+ select(messages.c.platform, messages.c.author_id, messages.c.metadata_json)+ .select_from(+ session_turns.join(message_deliveries, message_deliveries.c.id == session_turns.c.initial_delivery_id)+ .join(messages, messages.c.id == message_deliveries.c.message_id)+ )+ .where(session_turns.c.id == turn_id, session_turns.c.session_id == session_id)+ ).mappings().first()+ return dict(row) if row is not None else Nonelatest = conn.execute(select(messages.c.id).where(@@ -990,30 +1128,23 @@ class VibeyAgent(BaseAgent):from core.workbench_media import file_attachments_from_specs, resolve_attachment_specswith self._engine.connect() as conn:+ # CROSS JOIN fixes SQLite's loop order: start with indexed live+ # inputs, then seek their Deliveries/Turns. A materialized CTE alone+ # still lets the planner scan all historical accepted Deliveries.rows = conn.execute(- select(- messages.c.id,- messages.c.content_text,- messages.c.content_json,- message_deliveries.c.id.label("delivery_id"),- message_deliveries.c.turn_role,- session_turns.c.dispatch_text.label("turn_dispatch_text"),- )- .select_from(- messages.join(message_deliveries, message_deliveries.c.message_id == messages.c.id).join(- session_turns, session_turns.c.id == message_deliveries.c.turn_id- )- )- .where(- and_(- messages.c.session_id == session_id,- messages.c.context_seq.is_(None),- messages.c.type.in_(INPUT_TYPES),- message_deliveries.c.state == "accepted",- session_turns.c.backend == BACKEND,- )- )- .order_by(message_deliveries.c.materialized_at, message_deliveries.c.turn_position, messages.c.id)+ sql_text(+ "select messages.id, messages.content_text, messages.content_json, "+ "message_deliveries.id as delivery_id, message_deliveries.turn_role, "+ "session_turns.dispatch_text as turn_dispatch_text "+ "from messages cross join message_deliveries "+ "on message_deliveries.message_id = messages.id "+ "cross join session_turns on session_turns.id = message_deliveries.turn_id "+ f"where {VIBEY_RECOVERY_INPUT_PREDICATE} "+ "and messages.session_id = :session_id "+ "and message_deliveries.state = 'accepted' and session_turns.backend = :backend "+ "order by message_deliveries.materialized_at, message_deliveries.turn_position, messages.id"+ ),+ {"session_id": session_id, "backend": BACKEND},).mappings().all()inputs = []seen: set[str] = set()@@ -1026,6 +1157,8 @@ class VibeyAgent(BaseAgent):conn, session_id=session_id, attachments=list(content.get("attachments") or []))delivery = delivery_store.get_delivery(conn, row["delivery_id"])+ if delivery is None:+ continue# A Turn's initial input is sent as the Turn's dispatch text, which the Turn owner# derived from its Delivery batch (attachment notes, merged scheduled inputs) and# keeps after acceptance; the row's display text omits that.@@ -1608,24 +1741,18 @@ class VibeyAgent(BaseAgent):def _sessions_with_unconsumed_inputs(self) -> list[str]:"""Sessions with inputs accepted into a ``vibey`` Turn that no run consumed (T3)."""with self._engine.connect() as conn:- return sorted(- conn.execute(- select(messages.c.session_id)- .select_from(- messages.join(message_deliveries, message_deliveries.c.message_id == messages.c.id).join(- session_turns, session_turns.c.id == message_deliveries.c.turn_id- )- )- .where(- messages.c.session_id.is_not(None),- messages.c.context_seq.is_(None),- messages.c.type.in_(INPUT_TYPES),- message_deliveries.c.state == "accepted",- session_turns.c.backend == BACKEND,- )- .distinct()- ).scalars()- )+ rows = conn.execute(+ sql_text(+ "select messages.session_id from messages "+ "cross join message_deliveries on message_deliveries.message_id = messages.id "+ "cross join session_turns on session_turns.id = message_deliveries.turn_id "+ f"where {VIBEY_RECOVERY_INPUT_PREDICATE} "+ "and messages.session_id is not null "+ "and message_deliveries.state = 'accepted' and session_turns.backend = :backend"+ ),+ {"backend": BACKEND},+ ).scalars()+ return sorted({str(session_id) for session_id in rows if session_id is not None})def _session_workdir(self, session_id: str) -> str:with self._engine.connect() as conn:diff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.pyindex 438c206e6..b9081f2b3 100644--- a/modules/agents/vibey/store.py+++ b/modules/agents/vibey/store.py@@ -75,28 +75,37 @@ class AdapterTranscriptStore:# Per Session, the Agent of the Turn writing it (its request snapshot), so a# mid-Turn change of the Session's selected Agent never re-attributes its rows.self._agents: dict[str, str] = {}+ self._turns: dict[str, str] = {}- def bind_agent(self, session_id: str, agent_name: Optional[str]) -> None:+ def bind_agent(self, session_id: str, agent_name: Optional[str], *, turn_id: Optional[str] = None) -> None:"""Attribute the Session's next writes to the running Turn's Agent."""if agent_name:self._agents[session_id] = agent_nameelse:self._agents.pop(session_id, None)+ if turn_id:+ self._turns[session_id] = turn_id+ else:+ self._turns.pop(session_id, None)@contextmanager- def writing_as(self, session_id: str, agent_name: Optional[str]) -> Iterator[None]:- """Attribute the Session's writes inside the block to ``agent_name``; restore after."""+ def writing_as(+ self, session_id: str, agent_name: Optional[str], *, turn_id: Optional[str] = None+ ) -> Iterator[None]:+ """Use the owning response's identity for recovery writes; restore the active Turn after."""previous = self._agents.get(session_id)- self.bind_agent(session_id, agent_name or previous)+ previous_turn = self._turns.get(session_id)+ self.bind_agent(session_id, agent_name or previous, turn_id=turn_id)try:yieldfinally:- self.bind_agent(session_id, previous)+ self.bind_agent(session_id, previous, turn_id=previous_turn)def forget(self, session_id: str) -> None:"""Drop per-Session state; the next consumption reads the environment from the rows again."""self._env_state.pop(session_id, None)self._agents.pop(session_id, None)+ self._turns.pop(session_id, None)self._store.forget(session_id)# --- TranscriptStore -----------------------------------------------------@@ -140,6 +149,7 @@ class AdapterTranscriptStore:replied=replied,images=images,agent_name=self._agents.get(session_id),+ turn_id=self._turns.get(session_id),)self._on_response(session_id, entry.row_id, message, replied, tuple(images))return entry@@ -148,20 +158,25 @@ class AdapterTranscriptStore:self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]) -> ContextEntry:return await self._store.append_tool_result(- session_id, message, details=details, agent_name=self._agents.get(session_id)+ session_id, message, details=details, agent_name=self._agents.get(session_id),+ turn_id=self._turns.get(session_id),)async def append_payload(self, session_id: str, kind: Literal["compaction", "context_edit", "agent_state"], payload: Mapping[str, Any]) -> ContextEntry:- return await self._store.append_payload(session_id, kind, payload, agent_name=self._agents.get(session_id))+ return await self._store.append_payload(+ session_id, kind, payload, agent_name=self._agents.get(session_id), turn_id=self._turns.get(session_id)+ )async def append_payloads(self,session_id: str,entries: Sequence[tuple[Literal["compaction", "context_edit", "agent_state"], Mapping[str, Any]]],) -> Sequence[ContextEntry]:- committed = await self._store.append_payloads(session_id, entries, agent_name=self._agents.get(session_id))+ committed = await self._store.append_payloads(+ session_id, entries, agent_name=self._agents.get(session_id), turn_id=self._turns.get(session_id)+ )if any(kind == "compaction" for kind, _ in entries):self._env_state.pop(session_id, None) # the summarized inputs' environment is no longer seenreturn committed@@ -169,7 +184,9 @@ class AdapterTranscriptStore:async def append_audit(self, session_id: str, kind: Literal["attempt", "fork_turn"], payload: Mapping[str, Any]) -> str:- return await self._store.append_audit(session_id, kind, payload, agent_name=self._agents.get(session_id))+ return await self._store.append_audit(+ session_id, kind, payload, agent_name=self._agents.get(session_id), turn_id=self._turns.get(session_id)+ )# --- implementation ------------------------------------------------------diff --git a/storage/agent_transcript.py b/storage/agent_transcript.pyindex dbe3045c4..b506acc4a 100644--- a/storage/agent_transcript.py+++ b/storage/agent_transcript.py@@ -90,6 +90,7 @@ from storage import agent_events_service, media_service, messages_servicefrom storage.agent_session_rows import reserve_write_lockfrom storage.message_deliveries import TURN_OWNER_STATESfrom storage.models import agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns+from storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATEINPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")# A final response is ``result``, or ``error`` when ``final_outcome`` says it failed:@@ -262,6 +263,7 @@ class SQLiteTranscriptStore:replied: Optional[bool] = None,images: Sequence[HostedImage] = (),agent_name: Optional[str] = None,+ turn_id: Optional[str] = None,) -> ContextEntry:if not isinstance(message, AssistantMessage):raise TypeError("append_response takes an AssistantMessage")@@ -274,7 +276,7 @@ class SQLiteTranscriptStore:display_text = self._render(message, final=final, replied=replied, images=tuple(images))def work(conn: Connection) -> ContextEntry:- origin = _turn_origin(conn, session_id, agent_name)+ origin = _turn_origin(conn, session_id, agent_name, turn_id)seq = _next_context_seq(conn, session_id)row = messages_service.append(conn,@@ -287,6 +289,7 @@ class SQLiteTranscriptStore:message_type=_response_type(message, final=final, display_text=display_text, replied=replied),text=display_text,content={"model": model},+ metadata={"turn_id": origin.turn_id} if origin.turn_id else None,)conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))_register_images(conn, origin.scope_id, session_id, message)@@ -303,6 +306,7 @@ class SQLiteTranscriptStore:*,details: Mapping[str, Any],agent_name: Optional[str] = None,+ turn_id: Optional[str] = None,) -> ContextEntry:if not isinstance(message, ToolResultMessage):raise TypeError("append_tool_result takes a ToolResultMessage")@@ -318,14 +322,17 @@ class SQLiteTranscriptStore:settled = _settled_result(conn, session_id, message.tool_call_id)if settled is not None:return settled- return self._append_event(conn, session_id, "tool_result", payload, message, agent_name)+ return self._append_event(conn, session_id, "tool_result", payload, message, agent_name, turn_id)return await self._write(session_id, work)async def append_payload(- self, session_id: str, kind: PayloadKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None+ self, session_id: str, kind: PayloadKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None,+ turn_id: Optional[str] = None,) -> ContextEntry:- return (await self.append_payloads(session_id, [(kind, payload)], agent_name=agent_name))[0]+ return (await self.append_payloads(+ session_id, [(kind, payload)], agent_name=agent_name, turn_id=turn_id+ ))[0]async def append_payloads(self,@@ -333,17 +340,19 @@ class SQLiteTranscriptStore:entries: Sequence[tuple[PayloadKind, Mapping[str, Any]]],*,agent_name: Optional[str] = None,+ turn_id: Optional[str] = None,) -> list[ContextEntry]:"""Several payload rows in order, in one transaction: all of them or none (C-9 section 10)."""rows = [(kind, _payload(kind, payload)) for kind, payload in entries]def work(conn: Connection) -> list[ContextEntry]:- return [self._append_event(conn, session_id, kind, data, None, agent_name) for kind, data in rows]+ return [self._append_event(conn, session_id, kind, data, None, agent_name, turn_id) for kind, data in rows]return await self._write(session_id, work)async def append_audit(- self, session_id: str, kind: AuditKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None+ self, session_id: str, kind: AuditKind, payload: Mapping[str, Any], *, agent_name: Optional[str] = None,+ turn_id: Optional[str] = None,) -> str:"""A non-context audit row (C-9 ``ModelAttempt`` or C-10 ``ForkTurn``); its id. Never loaded as context."""if kind not in _AUDIT_EVENT_TYPE:@@ -351,7 +360,7 @@ class SQLiteTranscriptStore:data = _canonical(dict(payload), f"{kind} audit")def work(conn: Connection) -> str:- origin = _turn_origin(conn, session_id, agent_name)+ origin = _turn_origin(conn, session_id, agent_name, turn_id)row = agent_events_service.append(conn,scope_id=origin.scope_id,@@ -394,8 +403,9 @@ class SQLiteTranscriptStore:payload: dict[str, Any],message: Optional[ToolResultMessage],agent_name: Optional[str] = None,+ turn_id: Optional[str] = None,) -> ContextEntry:- origin = _turn_origin(conn, session_id, agent_name)+ origin = _turn_origin(conn, session_id, agent_name, turn_id)seq = _next_context_seq(conn, session_id)row = agent_events_service.append(conn,@@ -481,18 +491,33 @@ def _next_context_seq(conn: Connection, session_id: str) -> int:return top + 1-def _turn_origin(conn: Connection, session_id: str, agent_name: Optional[str] = None) -> _TurnOrigin:+def _turn_origin(+ conn: Connection, session_id: str, agent_name: Optional[str] = None, turn_id: Optional[str] = None+) -> _TurnOrigin:"""Where an inserted row belongs, and the Agent that wrote it.``agent_name`` is the running Turn's Agent (its request snapshot): the Session'sselected Agent may change mid-Turn, so the Session row is only the fallback for a- write outside a Turn (startup recovery).+ write outside a Turn (startup recovery). ``turn_id`` is explicit for live writes:+ a transcript-only retry owns a new Turn without consuming another input."""session = conn.execute(select(agent_sessions.c.agent_name).where(agent_sessions.c.id == session_id)).first()if session is None:raise TranscriptError(f"Session {session_id} does not exist")+ if turn_id is not None:+ initial = conn.execute(+ select(messages.c.platform, messages.c.scope_id)+ .select_from(+ session_turns.join(message_deliveries, message_deliveries.c.id == session_turns.c.initial_delivery_id)+ .join(messages, messages.c.id == message_deliveries.c.message_id)+ )+ .where(session_turns.c.id == turn_id, session_turns.c.session_id == session_id)+ ).first()+ if initial is None:+ raise TranscriptError(f"Turn {turn_id} has no accepted input in Session {session_id}")+ return _TurnOrigin(initial.platform, initial.scope_id, turn_id, agent_name or session.agent_name, CONTEXT_WRITER)latest = conn.execute(select(messages.c.id, messages.c.platform, messages.c.scope_id).where(@@ -580,14 +605,13 @@ def _unended_input_seq(conn: Connection, session_id: str, entries: Sequence[Cont).all()awaiting_input = set(conn.execute(- select(message_deliveries.c.turn_id)- .select_from(message_deliveries.join(messages, messages.c.id == message_deliveries.c.message_id))- .where(- messages.c.session_id == session_id,- messages.c.context_seq.is_(None),- messages.c.type.in_(INPUT_TYPES),- message_deliveries.c.state == "accepted",- )+ text(+ "select message_deliveries.turn_id from messages "+ "cross join message_deliveries on message_deliveries.message_id = messages.id "+ f"where {VIBEY_RECOVERY_INPUT_PREDICATE} "+ "and messages.session_id = :session_id and message_deliveries.state = 'accepted'"+ ),+ {"session_id": session_id},).scalars())inputs = sorted(seq for _, _, seq in turns if seq is not None)diff --git a/storage/alembic/versions/20261016_0067_vibey_recovery_input_index.py b/storage/alembic/versions/20261016_0067_vibey_recovery_input_index.pynew file mode 100644index 000000000..c73549a73--- /dev/null+++ b/storage/alembic/versions/20261016_0067_vibey_recovery_input_index.py@@ -0,0 +1,77 @@+"""bound Vibey recovery to real unconsumed inputs++Vibey's T3 recovery looks for accepted input Messages whose ``context_seq`` is+still null. Hidden ``agent_initiated`` harness resume rows are durable control+ownership, not model inputs, and remain null forever. Filtering those rows in+Python made every resume walk and hydrate the whole retry history.++The partial index contains only real recovery candidates. Its predicate is+shared with ``storage.models`` and the three recovery queries so SQLite can+seek the growing Message table by ``context_seq`` and, for a Session query, by+``session_id``. A companion Delivery ``message_id`` index bounds the next join+by each live candidate rather than scanning accepted Delivery history.++Revision ID: 20261016_0067+Revises: 20261015_0066+Create Date: 2026-10-16+"""++from __future__ import annotations++from alembic import op++revision = "20261016_0067"+down_revision = "20261015_0066"+branch_labels = None+depends_on = None+MIGRATION_SAFETY = "additive"++_INDEX = "ix_messages_vibey_recovery_input"+# Frozen migration history: do not import the runtime predicate here. A later+# recovery-shape change must be a new migration, not a rewrite of this DDL.+_RECOVERY_INPUT_PREDICATE = (+ "context_seq is null and type in "+ "('user', 'harness', 'agent_initiated', 'annotation') "+ "and not (author is 'harness' and type is 'agent_initiated' "+ "and source is 'harness' and json_type("+ "case when json_valid(metadata_json) = 1 then metadata_json else '{}' end, "+ "'$.vibey_resume') is 'true')"+)+# Head-schema repair reuses this exact DDL; SQLite's partial-index matcher is+# syntax-sensitive.+DROP_INDEX_SQL = f"drop index if exists {_INDEX}"+CREATE_INDEX_SQL = (+ f"create index {_INDEX} on messages (context_seq, session_id, id) "+ f"where {_RECOVERY_INPUT_PREDICATE}"+)+++_DELIVERY_INDEX = "ix_message_deliveries_message"+DROP_DELIVERY_INDEX_SQL = f"drop index if exists {_DELIVERY_INDEX}"+CREATE_DELIVERY_INDEX_SQL = (+ f"create index {_DELIVERY_INDEX} on message_deliveries (message_id) where message_id is not null"+)+++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()+ tables = _tables(bind)+ if "messages" in tables:+ bind.exec_driver_sql(DROP_INDEX_SQL)+ bind.exec_driver_sql(CREATE_INDEX_SQL)+ if "message_deliveries" in tables:+ bind.exec_driver_sql(DROP_DELIVERY_INDEX_SQL)+ bind.exec_driver_sql(CREATE_DELIVERY_INDEX_SQL)+++def downgrade() -> None:+ bind = op.get_bind()+ bind.exec_driver_sql(DROP_DELIVERY_INDEX_SQL)+ bind.exec_driver_sql(DROP_INDEX_SQL)diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex b623a8adc..ca0577b49 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -39,6 +39,20 @@ FAILURE_RETRY_HISTORY_KIND = "backend_failure_retry"WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"WEB_PUSH_AUTHORIZATION_CONTEXTS_METADATA = "_web_push_authorization_contexts"+VIBEY_RESUME_METADATA_KEY = "vibey_resume"+VIBEY_SOURCE_TURN_METADATA_KEY = "vibey_source_turn_id"+++def is_vibey_resume_payload(payload: Mapping[str, Any]) -> bool:+ """Return whether a Delivery carries the server-owned Vibey resume marker."""+ metadata = payload.get("metadata")+ return bool(+ payload.get("type") == "agent_initiated"+ and payload.get("author") == "harness"+ and payload.get("source") == "harness"+ and isinstance(metadata, Mapping)+ and metadata.get(VIBEY_RESUME_METADATA_KEY) is True+ )def legacy_admitted_user_id(metadata: object) -> str | None:diff --git a/storage/migrations.py b/storage/migrations.pyindex 95de40c60..25cbd4c87 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -931,20 +931,27 @@ def _ensure_messages_query_indexes(conn: sqlite3.Connection, tables: set[str]) -):conn.execute(transcript_index.DROP_INDEX_SQL)conn.execute(transcript_index.CREATE_INDEX_SQL)- # The turn-id expression index, from the revision that owns its DDL: the- # planner matches an index expression by text, so a retyped copy is ignored.- turn_id_index = import_module(- "storage.alembic.versions.20261012_0064_messages_turn_id_index"- )- turn_id_row = conn.execute(- "select sql from sqlite_master where type = 'index' and name = ?",- (turn_id_index._INDEX,),- ).fetchone()- if turn_id_row is None or _normalized_index_sql(turn_id_row[0]) != _normalized_index_sql(- turn_id_index.CREATE_INDEX_SQL- ):- conn.execute(turn_id_index.DROP_INDEX_SQL)- conn.execute(turn_id_index.CREATE_INDEX_SQL)+ # Read expression/partial-index DDL from its owning revision: SQLite matches+ # these predicates syntactically, so a retyped copy may be silently ignored.+ turn_index = import_module("storage.alembic.versions.20261012_0064_messages_turn_id_index")+ recovery_index = import_module("storage.alembic.versions.20261016_0067_vibey_recovery_input_index")+ indexes = [+ (turn_index._INDEX, turn_index.DROP_INDEX_SQL, turn_index.CREATE_INDEX_SQL),+ (recovery_index._INDEX, recovery_index.DROP_INDEX_SQL, recovery_index.CREATE_INDEX_SQL),+ ]+ if "message_deliveries" in tables:+ indexes.append((+ recovery_index._DELIVERY_INDEX,+ recovery_index.DROP_DELIVERY_INDEX_SQL,+ recovery_index.CREATE_DELIVERY_INDEX_SQL,+ ))+ for index_name, drop_sql, create_sql in indexes:+ row = conn.execute(+ "select sql from sqlite_master where type = 'index' and name = ?", (index_name,)+ ).fetchone()+ if row is None or _normalized_index_sql(row[0]) != _normalized_index_sql(create_sql):+ conn.execute(drop_sql)+ conn.execute(create_sql)conn.execute('create index if not exists ix_messages_session_created_id on messages (session_id, created_at, id)')conn.execute('create index if not exists ix_messages_session_type_created_id on messages (session_id, type, created_at, id)')conn.execute('create index if not exists ix_messages_platform_session_created_id on messages (platform, session_id, created_at, id)')diff --git a/storage/models.py b/storage/models.pyindex 4478ecc03..52ad07763 100644--- a/storage/models.py+++ b/storage/models.py@@ -20,6 +20,7 @@ from sqlalchemy import ()from storage.delivery_states import DELIVERY_STATES+from storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATEfrom vibe.message_types import build_partial_index_predicatemetadata = MetaData()@@ -704,6 +705,16 @@ messages = Table(unique=True,sqlite_where=text("context_seq is not null"),),+ # T3 recovery only needs inputs that can still be consumed. The hidden+ # Vibey retry ownership row stays durable with a null context_seq but is+ # deliberately outside this growing population.+ Index(+ "ix_messages_vibey_recovery_input",+ "context_seq",+ "session_id",+ "id",+ sqlite_where=text(VIBEY_RECOVERY_INPUT_PREDICATE),+ ),Index("ix_messages_session_created", "session_id", "created_at"),Index("ix_messages_session_created_id", "session_id", "created_at", "id"),Index("ix_messages_session_type_created_id", "session_id", "type", "created_at", "id"),@@ -1069,6 +1080,11 @@ message_deliveries = Table(),),Index("ix_message_deliveries_session_state", "session_id", "state", "submitted_at", "id"),+ Index(+ "ix_message_deliveries_message",+ "message_id",+ sqlite_where=text("message_id is not null"),+ ),Index("ix_message_deliveries_turn", "turn_id", "turn_position"),Index("uq_message_deliveries_turn_position",diff --git a/storage/vibey_recovery.py b/storage/vibey_recovery.pynew file mode 100644index 000000000..c893e8272--- /dev/null+++ b/storage/vibey_recovery.py@@ -0,0 +1,30 @@+"""Shared SQL for Vibey's bounded unconsumed-input recovery queries.++The predicate mirrors ``message_deliveries.is_vibey_resume_payload`` at the+materialized Message boundary. Hidden Vibey retry rows are control ownership,+not model inputs: they remain durable rows with a null ``context_seq`` but must+not enter the growing recovery population.++Keep this expression byte-identical between the model metadata, Alembic DDL,+and recovery queries. The literal input values and marker expression are+intentional: SQLite partial-index matching is syntax-sensitive, and a bound+``IN`` list or a Python-side marker check would either miss the index or scan+hidden retry history first.+"""++from __future__ import annotations+++# Unqualified column names are required by SQLite inside a partial-index WHERE+# clause. The same clause is used in the joined recovery SELECTs, where these+# names are unambiguous because only ``messages`` has them.+VIBEY_RECOVERY_INPUT_PREDICATE = (+ "context_seq is null and type in "+ "('user', 'harness', 'agent_initiated', 'annotation') "+ "and not (author is 'harness' and type is 'agent_initiated' "+ "and source is 'harness' and json_type("+ "case when json_valid(metadata_json) = 1 then metadata_json else '{}' end, "+ "'$.vibey_resume') is 'true')"+)++__all__ = ["VIBEY_RECOVERY_INPUT_PREDICATE"]diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.pyindex 1a4c6057e..e65da0ddd 100644--- a/tests/agent_core/agent/test_loop.py+++ b/tests/agent_core/agent/test_loop.py@@ -95,11 +95,97 @@ def make_agent(provider, *, store=None, session_id="session", tools=(), hooks=()async def collect(agent, row_id="input", value="hello", turn_id="turn"):return [event async for event in agent.run(input_row(row_id, value), turn_id=turn_id)]-def user_texts(request):return [message.content[0].text for message in request.messages if isinstance(message, UserMessage)]+async def test_resume_reuses_the_committed_transcript_without_consuming_an_input():+ provider = ScriptedProvider(+ [+ [ProviderError("server", "temporary upstream failure", False)],+ [Done(assistant("recovered"))],+ ]+ )+ agent = make_agent(provider)+ original = input_row("input", "hello")++ first = [event async for event in agent.run(original, turn_id="turn")]+ second = [event async for event in agent.resume(original, turn_id="turn")]++ assert first[-1].reason == "error"+ assert second[-1].reason == "completed"+ assert [row.row_id for row in await agent.store.load("session") if row.kind == "input"] == ["input"]+ assert [row.message.content[0].text for row in await agent.store.load("session") if row.kind == "response"] == [+ "recovered"+ ]+ assert len(provider.requests) == 2+ assert second[0].seq == first[-1].seq + 1+++async def test_resume_uses_only_explicit_source_turn_inputs_for_a_fresh_agent():+ store = InMemoryTranscriptStore()+ first = await store.consume_input("session", "first", user("first"))+ await store.consume_input("session", "other", user("other"))+ provider = ScriptedProvider([[Done(assistant("recovered"))]])+ agent = make_agent(provider, store=store)++ events = [+ event+ async for event in agent.resume(+ input_row("retry", "ignored"),+ turn_id="retry-turn",+ turn_inputs={first.context_seq},+ )+ ]++ assert events[-1].reason == "completed"+ assert agent._turn_inputs == {first.context_seq}+++async def test_resume_merges_newly_admitted_inputs_into_same_turn_pins():+ provider = ScriptedProvider([+ [ProviderError("invalid_request", "failed", False)],+ [Done(assistant("recovered"))],+ ])+ agent = make_agent(provider)+ await collect(agent)+ [initial] = [row for row in await agent.store.load("session") if row.kind == "input"]+ returned = await agent.store.consume_input("session", "returned-steer", user("不要删文件"))++ events = [event async for event in agent.resume(+ input_row("retry", "ignored"), turn_id="turn", turn_inputs={returned.context_seq}+ )]++ assert events[-1].reason == "completed"+ assert agent._turn_inputs == {initial.context_seq, returned.context_seq}+ assert user_texts(provider.requests[-1]) == ["hello", "不要删文件"]+++async def test_resume_preserves_images_committed_by_an_earlier_tool_call():+ from core.agent_core.messages import HostedResult, ProxyExecution++ hosted = HostedResult(+ HostedRecord(status="completed", images=(HostedImage(path="/media/winner.png", mime="image/png"),)),+ ProxyExecution(ORIGIN, "src_executor01", "metered", mode="direct"),+ )+ tool = FakeTool("image_generate", result=ToolResult((text("saved"),), hosted=hosted))+ provider = ScriptedProvider(+ [+ [Done(assistant("", calls=[ToolCallBlock("call_img", "image_generate", {})]))],+ [ProviderError("server", "temporary upstream failure", False)],+ [Done(assistant("recovered"))],+ ]+ )+ agent = make_agent(provider, tools=[tool])++ first_events = await collect(agent, value="make an image")+ second_events = [event async for event in agent.resume(input_row("retry", "ignored"), turn_id="turn")]++ assert first_events[-1].reason == "error"+ assert second_events[-1].reason == "completed"+ assert agent._generated_images == [HostedImage(path="/media/winner.png", mime="image/png")]++async def test_C1_tool_set_is_captured_per_request_and_unavailable_calls_are_errors():old, new = FakeTool("old"), FakeTool("new")entered, release = asyncio.Event(), asyncio.Event()@@ -639,6 +725,27 @@ async def test_retry_obeys_provider_flag_and_allows_usage_only_partial(streamed,assert events[-1].reason == "completed"[email protected]("failure", ["before output", "after output", "recovery exhausted"])+async def test_provider_permissions_and_delay_reach_the_terminal_cause(failure):+ """C-3: consumers need the producer's decision, which the old kind/message-only event dropped."""+ from core.agent_core.ai.errors import classify_error++ error = classify_error(+ status=424 if failure == "recovery exhausted" else 429,+ body='{"error":{"code":"model_hub_recovery_exhausted","cause":"rate_limited"}}'+ if failure == "recovery exhausted" else "busy",+ headers={"retry-after": "17"},+ streamed=failure == "after output",+ )+ agent = make_agent(ScriptedProvider([[error]]), retry=RetryPolicy(max_retries=0))+ events = await collect(agent)+ [announced] = [event for event in events if isinstance(event, AgentError)]+ assert events[-1].cause == announced+ assert (announced.kind, announced.origin, announced.retryable, announced.continuable, announced.retry_after_s) == (+ "rate_limit", "source", failure == "before output", failure != "recovery exhausted", 17.0+ )++# OpenAI Responses streams, as the real adapter reads them: reasoning, then how the response ended._REASONING = ('data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'diff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.pyindex 5a13f7751..b180bebee 100644--- a/tests/agent_core/ai/test_provider_adapters.py+++ b/tests/agent_core/ai/test_provider_adapters.py@@ -2964,8 +2964,10 @@ class _FailingLoader(MediaLoader):@pytest.mark.asyncio-async def test_media_loader_failure_is_a_provider_error() -> None:- message = UserMessage((ImageBlock("image/png", "missing", "missing.png"),))[email protected]("token,kind", [("missing", "unknown"), ("rate limit", "rate_limit"), ("server error", "server")])+async def test_media_loader_failure_is_a_provider_error(token, kind) -> None:+ # Local preparation must not acquire replay/continuation permission from upstream-looking diagnostic text.+ message = UserMessage((ImageBlock("image/png", token, "missing.png"),))adapter = OpenAIChatAdapter(httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(500))),media_loader=_FailingLoader(),@@ -2977,7 +2979,8 @@ async def test_media_loader_failure_is_a_provider_error() -> None:)assert isinstance(events[-1], ProviderError)- assert events[-1].kind == "unknown"+ assert events[-1].kind == kind+ assert not events[-1].retryable and not events[-1].continuable@pytest.mark.asyncio@@ -4717,7 +4720,7 @@ async def test_model_hubs_recovery_exhausted_ending_names_its_cause(adapter_typeerror = events[-1]assert isinstance(error, ProviderError)- assert (error.kind, error.retryable) == (kind, False)+ assert (error.kind, error.retryable, error.continuable) == (kind, False, False)# CLIProxyAPI nests the class under `error`; OpenAI's reference carries it at the root.@@ -4766,6 +4769,61 @@ async def test_only_a_drop_after_thinking_alone_is_marked_after_thinking(assert error.after_thinking is flagged# Before any output a server error was always retryable; after text it never is.assert error.retryable is (flagged or not streamed)+ assert error.continuable is True++[email protected]("output", ["none", "thinking", "text"])+ "failure,continuable",+ [+ ("classified transient", True),+ ("explicit transient", True),+ ("eof", True),+ ("stalled", True),+ ("recovery exhausted", False),+ ("pin refusal", False),+ ("malformed", False),+ ("unknown wire", False),+ ("local exception", False),+ ],+)+def test_stream_error_producers_preserve_continuation_permission(output, failure, continuable):+ """C-2: terminal sanitization must not resurrect exhausted/refused/local failures after thinking.++ Prior tests covered kinds and replay only, so the outer adapter could undo their decision.+ """+ from core.agent_core.ai._common import PinUnavailable, pin_refusal+ from core.agent_core.ai.errors import ProviderStalled++ endpoint = _request("openai_responses").endpoint+ assembler = StreamAssembler(origin=Origin("test", "openai_responses", "model"), protocol="openai_responses")+ if output == "thinking":+ assembler.thinking_delta(0, "reasoning")+ elif output == "text":+ assembler.text_delta(0, "partial")+ if failure == "classified transient":+ error = assembler.error("busy", status=503)+ elif failure == "explicit transient":+ error = assembler.error("busy", kind="server")+ elif failure == "eof":+ error = assembler.incomplete()+ elif failure == "stalled":+ error = assembler.exception(ProviderStalled(600))+ elif failure == "recovery exhausted":+ error = assembler.error(json.dumps({"error": {"code": "model_hub_recovery_exhausted", "cause": "server_error"}}))+ elif failure == "pin refusal":+ error = pin_refusal(assembler, endpoint, PinUnavailable())+ elif failure == "malformed":+ error = assembler.error("bad wire shape", kind="invalid_request")+ elif failure == "unknown wire":+ error = assembler.error("unclassified failure")+ else:+ error = assembler.exception(RuntimeError("local failure"))+ terminal = assembler.terminal(error)+ assert terminal.continuable is continuable+ expected_retry = (continuable and output != "text") or (failure == "unknown wire" and output == "thinking")+ assert terminal.retryable is expected_retry+ assert terminal.after_thinking is (expected_retry and output == "thinking")@pytest.mark.asyncio@@ -4901,6 +4959,7 @@ async def test_eof_without_protocol_terminal_is_not_success(assert isinstance(events[-1], ProviderError)assert events[-1].retryable is False+ assert events[-1].continuable is Trueassert events[-1].partial is not Noneassert not any(isinstance(event, Done) for event in events)diff --git a/tests/test_agent_context_seq_migration.py b/tests/test_agent_context_seq_migration.pyindex a1d95f612..d51c14443 100644--- a/tests/test_agent_context_seq_migration.py+++ b/tests/test_agent_context_seq_migration.py@@ -56,7 +56,7 @@ def test_context_seq_upgrade_and_downgrade_keep_released_rows(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261015_0066",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0067",)assert_released_rows_unchanged(conn)assert _index_sql(conn, "ix_agent_events_turn_sequence_id") is not Nonefor table, (first, same_session, other_session) in _IDS.items():diff --git a/tests/test_backend_failure_retry.py b/tests/test_backend_failure_retry.pyindex 4b244f468..398f9670a 100644--- a/tests/test_backend_failure_retry.py+++ b/tests/test_backend_failure_retry.py@@ -13,7 +13,7 @@ from modules.agents.catalog import AGENT_BACKENDSfrom storage import message_deliveries, messages_servicefrom storage.agent_session_rows import reserve_write_lockfrom storage.db import create_sqlite_engine-from storage.models import messages, session_turns+from storage.models import agent_sessions, messages, session_turnsfrom tests.backend_failure_retry_helpers import reserve_failure_retry, seed_failed_noticefrom tests.test_session_delivery_fsm import _context, _fsm_schema_template, managers # noqa: F401from tests.test_ui_session_stream import _accepted_dispatch, _make_session, isolated_state # noqa: F401@@ -306,8 +306,11 @@ def test_failure_retry_canonical_continue_and_draft(isolated_state, tmp_path, ba)assert response.status_code == 201body = response.get_json()- assert body["text"] == "continue"- assert body["draft_advanced"] is False+ expected_text = "" if backend == "vibey" else "continue"+ assert body["text"] == expected_text+ if backend == "vibey":+ assert body["type"] == "agent_initiated"+ assert body["metadata"]["vibey_resume"] is Trueassert body["draft"] == draftassert body["retry_notice"]["content"]["failure_retry"]["state"] == "accepted"assert dispatch.await_args.args[0]["files"] == []@@ -511,23 +514,30 @@ def test_failure_retry_unwritten_original_batch(managers, texts):assert "continue" not in starts[0][1][email protected]("backend", AGENT_BACKENDS)@pytest.mark.parametrize("not_written", [False, True])-def test_failure_retry_web_controller_round_trip(isolated_state, tmp_path, monkeypatch, not_written):- """MESSAGE-DELIVERY-026: Web -> real admission -> native boundary -> replay."""+def test_failure_retry_web_controller_round_trip(isolated_state, tmp_path, monkeypatch, not_written, backend):+ """MESSAGE-DELIVERY-026: include hidden resume across both real HTTP consumers.++ A mocked internal client misses empty-input rejection and loss of durable+ provenance when submit constructs a user DeliveryRequest.+ """import httpxfrom core import internal_serverfrom tests.test_internal_server import _bind_test_native_start, _build_controller_doublefrom vibe import ui_server- session_id, notice, _turn, _inputs = _retry_notice(tmp_path, not_written=not_written)+ session_id, notice, _turn, _inputs = _retry_notice(tmp_path, backend=backend, not_written=not_written)engine = create_sqlite_engine()controller = _build_controller_double()internal_app = internal_server.create_app(controller)manager = controller.session_turnsstarts = []+ contexts = []async def capture_run(sid, context, text, *, logical_turn_id=None, **kwargs):starts.append((sid, text))+ contexts.append(context)_bind_test_native_start(engine, context)manager._terminalize_durable_turn(logical_turn_id,@@ -548,30 +558,71 @@ def test_failure_retry_web_controller_round_trip(isolated_state, tmp_path, monkeclient = ui_server.app.test_client()headers = csrf_headers(client)url = f"/api/sessions/{session_id}/messages"- first = client.post(url, json={"retry_for": notice["id"]}, headers=headers)+ first = client.post(+ url, json={"retry_for": notice["id"], "text": "不要重放工具调用", "metadata": {"vibey_resume": False}},+ headers=headers,+ )duplicate = client.post(url, json={"retry_for": notice["id"]}, headers=headers)assert first.status_code == duplicate.status_code == 201assert first.get_json()["id"] == duplicate.get_json()["id"]- assert starts == [(session_id, "检查这张图" if not_written else "continue")]+ resume = backend == "vibey" and not not_written+ assert starts == [(session_id, "检查这张图" if not_written else "" if resume else "continue")]+ assert contexts[0].platform_specific["vibey_resume"] is resume+ assert contexts[0].platform_specific["vibey_source_turn_id"] == (_turn["id"] if resume else None)+ with engine.connect() as conn:+ accepted = messages_service.get_message(conn, first.get_json()["id"])+ retry = message_deliveries.get_delivery(conn, first.get_json()["id"])+ assert retry["state"] == "accepted"+ assert accepted["type"] == ("agent_initiated" if resume else "user")-def test_failure_retry_queue_drain_rechecks_the_boundary(managers):- """MESSAGE-DELIVERY-028: a deferred retry cannot overtake newer work."""[email protected]("change", ["newer_turn", "backend_after_unwritten_start"])+def test_failure_retry_queue_drain_rechecks_the_boundary(managers, change):+ """MESSAGE-DELIVERY-028: revalidate a real retry after its queue wait.++ Once a start was claimed, no-write recovery belongs to the Turn FSM rather+ than the notice's unclaimed-retry guard. That path still must not dispatch a+ hidden resume to a newly selected native backend.+ """manager, _other, engine, _engine_b, starts = managers+ backend = "codex" if change == "newer_turn" else "vibey"++ def context(sid):+ value = _context(sid)+ value.platform_specific["agent_session_target"]["agent_backend"] = backend+ return value++ manager.bind_context(context)with engine.begin() as conn:- notice, _turn, _inputs = seed_failed_notice(conn, session_id="ses_fsm")+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(agent_backend=backend))+ notice, _turn, _inputs = seed_failed_notice(conn, session_id="ses_fsm", backend=backend)retry = reserve_failure_retry(conn, notice)async def queue_then_drain():- manager.begin_backend_drain("codex")- queued = await manager.deliver(- DeliveryRequest(session_id="ses_fsm", priority="p3", content="continue", delivery_id=retry["id"]),- context=_context(),- )- assert queued.state == "queued"- with engine.begin() as conn:- seed_failed_notice(conn, session_id="ses_fsm")- await manager.end_backend_drain("codex")+ nonlocal backend+ if change == "newer_turn":+ manager.begin_backend_drain(backend)+ admitted = await manager.deliver(manager._request_from_delivery(retry), context=context("ses_fsm"))+ if change == "newer_turn":+ assert admitted.state == "queued"+ with engine.begin() as conn:+ seed_failed_notice(conn, session_id="ses_fsm")+ await manager.end_backend_drain(backend)+ else:+ assert admitted.state == "claimed"+ assert [text for _turn, text in starts] == [""]+ manager._terminalize_durable_turn(+ admitted.turn_id, "not_written", settled_by="pre_write_failure",+ evidence_kind="definitive_prewrite_failure",+ )+ starts.clear()+ backend = "opencode"+ with engine.begin() as conn:+ queued = message_deliveries.get_delivery(conn, retry["id"])+ assert queued["state"] == "queued"+ assert message_deliveries.failure_retry_binding(queued, unclaimed_only=True) is None+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(agent_backend=backend))+ await manager.drain_delivery_queue("ses_fsm")asyncio.run(queue_then_drain())with engine.connect() as conn:diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex bec483d2b..02c8fb7c9 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -931,6 +931,57 @@ def test_dispatch_rejects_missing_text():assert "text" in payload["error"][email protected]("text", ["", "保留这条用户输入"])[email protected]("untrusted_field", ["type", "author", "source", "metadata"])+def test_dispatch_resume_permission_comes_only_from_durable_provenance(+ monkeypatch, tmp_path, text, untrusted_field,+):+ """Caller-forged resume fields cannot admit empty input or suppress real input.++ Adapter-only tests do not exercise the internal HTTP validator, which must+ replace every provenance field rather than merge a caller's claimed trust.+ """+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session = _create_test_session(tmp_path, native_id="resume_authority", backend="vibey")+ provenance = {+ "type": "agent_initiated", "author": "harness", "source": "harness",+ "metadata": {"vibey_resume": True},+ }+ provenance[untrusted_field] = {} if untrusted_field == "metadata" else "user"+ with engine.begin() as conn:+ reserved = _reserve_submission(+ conn, scope_id=session["scope_id"], session_id=session["id"], text=text,+ message_type=provenance["type"], author=provenance["author"],+ source=provenance["source"], metadata=provenance["metadata"],+ )+ observed = []+ controller = _build_controller_double()+ app = internal_server.create_app(controller)++ async def capture_run(_sid, context, dispatched, **_kwargs):+ observed.append((dispatched, context.platform_specific["vibey_resume"]))+ _bind_test_native_start(engine, context)++ controller.session_turns._run = capture_run++ async def dispatch():+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:+ return await client.post("/internal/dispatch_async", json={+ "session_id": session["id"], "user_message_id": reserved["id"],+ "text": "", "type": "agent_initiated", "author": "harness", "source": "harness",+ "vibey_resume": True, "metadata": {"vibey_resume": True},+ })++ response = asyncio.run(dispatch())+ if text:+ assert response.status_code == 202+ assert observed == [(text, False)]+ else:+ assert response.status_code == 400+ assert response.json()["error"] == "text or files is required"+ assert observed == []++def test_dispatch_rejects_missing_session_id():resp = asyncio.run(_dispatch_round_trip({"text": "hi"}))assert resp.status_code == 400diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex e9ad20dcf..564b70c7c 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -8048,9 +8048,91 @@ async def test_agent_initiated_continuation_materializes_as_hidden_turn_input(}[email protected]("backend", ["vibey", "claude", "codex", "opencode"])[email protected]("boundary", ["admission", "fifo", "admission_fifo", "dispatch"])+async def test_vibey_resume_delivery_is_retired_if_the_resolved_backend_changes(+ managers, monkeypatch, backend, boundary,+) -> None:+ """A hidden control Delivery may execute only on the resolved Vibey backend.++ Admission-only coverage missed later FIFO claims (including a new input+ driving the old queue) and routing rebuilt between claim and dispatch.+ At admission the request omits trusted fields: only the stored row owns them.+ """+ manager, _other, engine, _engine_b, starts = managers+ delivery_id = delivery_store.new_delivery_id()+ metadata = {+ delivery_store.VIBEY_RESUME_METADATA_KEY: True,+ delivery_store.VIBEY_SOURCE_TURN_METADATA_KEY: "source-turn",+ }++ def context(session_id):+ value = _context(session_id)+ with engine.connect() as conn:+ value.platform_specific["agent_session_target"]["agent_backend"] = conn.execute(+ select(agent_sessions.c.agent_backend).where(agent_sessions.c.id == session_id)+ ).scalar_one()+ return value++ manager.bind_context(context)+ with engine.begin() as conn:+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(agent_backend="vibey"))+ delivery_store.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id="ses_fsm",+ priority="p3",+ state="reserved",+ snapshot=delivery_store.message_snapshot(+ scope_id=None,+ session_id="ses_fsm",+ platform="avibe",+ author="harness",+ source="harness",+ message_type="agent_initiated",+ text="",+ metadata=metadata,+ ),+ dispatch_text="",+ )++ request = DeliveryRequest(+ session_id="ses_fsm", priority="p3", content="", has_content=False,+ delivery_id=delivery_id, admission_only=boundary in {"fifo", "admission_fifo"},+ **({"author": "harness", "source": "harness", "message_type": "agent_initiated", "metadata": metadata}+ if boundary != "admission" else {}),+ )+ start_persisted_turn = manager._start_persisted_turn+ if boundary == "dispatch":+ monkeypatch.setattr(manager, "_start_persisted_turn", AsyncMock(return_value=False))+ if boundary != "admission":+ queued = await manager.deliver(request, context=context("ses_fsm"))+ assert queued.state == ("claimed" if boundary == "dispatch" else "queued")+ assert starts == []+ with engine.begin() as conn:+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(agent_backend=backend))+ if boundary == "admission":+ result = await manager.deliver(request, context=context("ses_fsm"))+ if backend != "vibey":+ assert result.reason == "backend_changed"+ elif boundary == "fifo":+ await manager.drain_delivery_queue("ses_fsm")+ elif boundary == "admission_fifo":+ await manager.deliver(DeliveryRequest(session_id="ses_fsm", priority="p3", content="新的用户任务"))+ else:+ monkeypatch.setattr(manager, "_start_persisted_turn", start_persisted_turn)+ await manager._start_persisted_turn(queued.turn_id)++ with engine.connect() as conn:+ stored = delivery_store.get_delivery(conn, delivery_id)+ assert stored["state"] == ("claimed" if backend == "vibey" else "retired")+ expected = [""] if backend == "vibey" else ["新的用户任务"] if boundary == "admission_fifo" else []+ assert [text for _turn, text in starts] == expected++@pytest.mark.anyioasync def test_failed_session_lifecycle_preserves_sampled_epoch(managers) -> None:- """A failed reset preserves an in-flight turn epoch."""manager, _other, _engine, _engine_b, _starts = managerssampled_snapshot = manager.snapshot_session_lifecycle("ses_fsm")diff --git a/tests/test_skill_observability_migration.py b/tests/test_skill_observability_migration.pyindex e3b862d18..797c9a5ce 100644--- a/tests/test_skill_observability_migration.py+++ b/tests/test_skill_observability_migration.py@@ -35,7 +35,7 @@ def test_skill_schema_upgrade_downgrade_preserves_existing_events(tmp_path):migrations.run_migrations(path)with sqlite3.connect(path) as conn:assert conn.execute(f"SELECT {columns} FROM agent_events ORDER BY id").fetchall() == original- assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261015_0066",)+ assert conn.execute("SELECT version_num FROM alembic_version").fetchone() == ("20261016_0067",)assert conn.execute("SELECT count(*) FROM skill_usage_daily").fetchone() == (0,)assert {row[2] for row in conn.execute("PRAGMA foreign_key_list(skill_usage_daily)")} == {"scopes",diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 4c73d6131..a9691d4eb 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -38,7 +38,7 @@ from vibe.message_types import build_partial_index_predicatepytestmark = pytest.mark.no_sqlite_template-HEAD_REVISION = "20261015_0066"+HEAD_REVISION = "20261016_0067"# ``storage.models`` builds a bare ``MetaData()``, so its foreign keys are unnamed and# Alembic cannot re-emit them when batch mode recreates a table. Every migration that# rebuilds one therefore passes this convention; the rebuild simulated below has to pass@@ -3602,6 +3602,8 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Pathengine.dispose()with sqlite3.connect(db_path) as conn:+ conn.execute("drop index if exists ix_messages_vibey_recovery_input")+ conn.execute("drop index if exists ix_message_deliveries_message")conn.execute("drop index if exists ix_agent_sessions_scope_status_activity")conn.execute("drop index if exists ix_messages_session_created_id")conn.execute("drop index if exists ix_messages_session_type_created_id")@@ -3614,6 +3616,13 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Pathconn.commit()assert conn.execute("select name from sqlite_master where name = 'alembic_version'").fetchone() is None+ # Check repair before the normal upgrade can hide an omitted index by+ # replaying its migration from the schema-stamp floor.+ migrations._stamp_existing_initial_schema(db_path, migrations.alembic_config(db_path))+ with sqlite3.connect(db_path) as conn:+ assert "context_seq is null" in _index_sql(conn, "ix_messages_vibey_recovery_input")+ assert "message_id is not null" in _index_sql(conn, "ix_message_deliveries_message")+run_migrations(db_path)with sqlite3.connect(db_path) as conn:@@ -3631,6 +3640,7 @@ def test_run_migrations_repairs_head_indexes_before_stamping_head(tmp_path: Path)}assert version == (HEAD_REVISION,)+ assert "ix_messages_vibey_recovery_input" in message_indexesassert "ix_messages_session_created_id" in message_indexesassert "ix_messages_session_type_created_id" in message_indexesassert "ix_messages_platform_session_created_id" in message_indexesdiff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex b2dc91eaa..a8ac795e9 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -1239,6 +1239,326 @@ async def test_output_limited_final_is_a_failed_row_with_length_cause(assert "kind=length" in caplog.text+def continuation_policy(monkeypatch):+ """Configure the real loop's existing retry policy, without replacing continuation behavior."""+ from functools import partial++ from core.agent_core.agent.loop import Agent+ from core.agent_core.agent.models import RetryPolicy++ def configure(**settings):+ monkeypatch.setattr("modules.agents.vibey.agent.Agent", partial(Agent, retry=RetryPolicy(**settings)))++ return configure+++async def test_a_transient_failure_continues_from_the_same_transcript_without_a_notice(+ engine, session, tmp_path, published, continuation_policy+) -> None:+ from core.agent_core.ai.provider import ProviderError++ continuation_policy(initial_delay_s=0)+ failure = ProviderError("server", "temporary upstream failure", False, continuable=True)+ harness = _Harness(+ engine,+ tmp_path,+ "telegram",+ [[failure]] * 5 + [[Done(assistant("recovered"))]],+ )++ await harness.agent.handle_message(harness.request("finish the task"))++ assert len(harness.provider.requests) == 6+ assert harness.rows("notify") == []+ assert harness.controller.im_client.sent == ["recovered"]+ assert harness.controller.terminals[-1]["is_error"] is False+++async def test_a_continuation_reuses_a_committed_tool_result_without_rerunning_the_tool(+ engine, session, tmp_path, published+) -> None:+ from core.agent_core.ai.provider import ProviderError++ call = ToolCallBlock(id="call_1", name="echo", arguments={})+ tool = FakeTool("echo")+ harness = _Harness(+ engine,+ tmp_path,+ "telegram",+ [+ [Done(assistant("", calls=(call,)))],+ [ProviderError("server", "temporary upstream failure", False, continuable=True)],+ [Done(assistant("done"))],+ ],+ tools=[tool],+ )++ await harness.agent.handle_message(harness.request("run the tool"))++ assert len(tool.calls) == 1+ assert len(harness.provider.requests) == 3+ assert harness.rows("notify") == []+ assert harness.controller.im_client.sent == ["🔧 echo {}", "done"]+++async def test_vibey_retry_resumes_the_existing_transcript_without_a_continue_message(+ engine, session, tmp_path, published+) -> None:+ from core.agent_core.ai.provider import ProviderError+ from storage import messages_service+ from tests.backend_failure_retry_helpers import reserve_failure_retry++ first_failure = ProviderError("invalid_request", "request rejected", False)+ harness = _Harness(+ engine,+ tmp_path,+ "avibe",+ [[first_failure], [Done(assistant("recovered"))]],+ )+ first = harness.request("finish the task")+ await harness.agent.handle_message(first)+ with engine.begin() as conn:+ message_deliveries.terminalize_turn(+ conn,+ _turn(first.context),+ outcome="failed",+ settled_by="terminal_result",+ evidence_kind="terminal_result",+ )++ with engine.connect() as conn:+ notice = next(+ row+ for row in messages_service.list_session_messages(conn, session_id=SESSION)["messages"]+ if row["type"] == "notify"+ )+ with engine.begin() as conn:+ retry = reserve_failure_retry(conn, notice)+ turn_id = message_deliveries.new_turn_id()+ claimed = message_deliveries.claim_start_batch(+ conn,+ turn_id=turn_id,+ session_id=SESSION,+ backend="vibey",+ deliveries=[retry],+ dispatch_text="",+ )+ retry_delivery = claimed["deliveries"][0]++ retry_context = _context("avibe", SESSION, turn_id=turn_id, delivery_id=retry_delivery["id"])+ retry_context.platform_specific["vibey_resume"] = True+ retry_context.platform_specific["vibey_source_turn_id"] = _turn(first.context)+ retry_context.message_id = retry_delivery["id"]+ with engine.begin() as conn:+ current_turn = message_deliveries.get_turn(conn, turn_id)+ assert message_deliveries.bind_native_start(+ conn,+ turn_id,+ expected_version=int(current_turn["version"]),+ runtime_key="runtime",+ runtime_turn_id=turn_id,+ native_turn_id=f"vibey:{harness.agent._instance}:{turn_id}",+ )+ assert message_deliveries.materialize_start_acceptance(+ conn,+ turn_id=turn_id,+ evidence={"kind": "test_acceptance"},+ )+ retry_request = AgentRequest(+ **{+ **first.__dict__,+ "context": retry_context,+ "message": "",+ "user_message": "",+ }+ )++ await harness.agent.handle_message(retry_request)++ assert harness.controller.im_client.sent[-1] == "recovered"+ assert len(harness.rows("user")) == 1+ [resume_row] = harness.rows("agent_initiated")+ assert resume_row["context_seq"] is None+ assert harness.agent._sessions_with_unconsumed_inputs() == []+ assert "continue" not in [row["content_text"] or "" for row in harness.rows("user")]+++async def test_user_metadata_cannot_trigger_vibey_resume(+ engine, session, tmp_path, published+) -> None:+ harness = _Harness(+ engine,+ tmp_path,+ "avibe",+ [[Done(assistant("answered"))]],+ )+ request = harness.request("real input")+ request.context.platform_specific["message_metadata"] = {"vibey_resume": True}++ await harness.agent.handle_message(request)++ [user_row] = harness.rows("user")+ assert "real input" in (user_row["content_text"] or "")+ assert harness.controller.im_client.sent[-1] == "answered"+++async def test_a_transient_failure_shows_one_notice_after_five_continuations(+ engine, session, tmp_path, published, continuation_policy+) -> None:+ from core.agent_core.ai.provider import ProviderError++ continuation_policy(initial_delay_s=0)+ failure = ProviderError("server", "temporary upstream failure", False, continuable=True)+ harness = _Harness(engine, tmp_path, "telegram", [[failure]] * 6)++ await harness.agent.handle_message(harness.request("finish the task"))++ assert len(harness.provider.requests) == 6+ assert len(harness.rows("notify")) == 1+ assert harness.controller.im_client.sent == [f"❌ {i18n_t('vibeyAgent.error.server', 'en')}"]+ assert harness.controller.terminals[-1]["is_error"] is True+++ "failure,continues",+ [+ ("streamed server", True),+ ("streamed eof", True),+ ("streamed rate limit", True),+ ("rate limit past budget", False),+ ("recovery exhausted", False),+ ("recovery exhausted after thinking", False),+ ("unknown", False),+ ("malformed", False),+ ],+)+async def test_provider_continuation_decision_reaches_vibey(+ engine, session, tmp_path, published, continuation_policy, failure, continues+):+ """Classification -> loop -> adapter: neither an exhausted Hub nor a permanent stream fault may be retried.++ Kind-only scripted tests missed real producers and erased Retry-After before the consumer saw it.+ """+ import httpx++ from modules.agents.vibey.models import registry_providers++ continuation_policy(initial_delay_s=0)+ text_prefix = (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"Working"}\n\n'+ )+ thinking_prefix = (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n'+ 'data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"Thinking"}\n\n'+ )+ exhausted = {"code": "model_hub_recovery_exhausted", "cause": "server_error", "message": "recovery ended"}+ sent = []++ def gateway(request):+ sent.append(json.loads(request.content))+ if len(sent) > 1:+ return httpx.Response(200, text=_TEXT_STREAMS["openai_responses"][1])+ if failure == "rate limit past budget":+ return httpx.Response(429, headers={"retry-after": "121"}, json={"error": {"message": "busy"}})+ if failure == "recovery exhausted":+ return httpx.Response(424, json={"error": exhausted})+ if failure == "recovery exhausted after thinking":+ body = thinking_prefix + "data: " + json.dumps({"type": "error", "error": exhausted}) + "\n\n"+ elif failure == "streamed eof":+ body = text_prefix+ elif failure == "malformed":+ body = text_prefix + 'data: {"type":"response.output_text.delta","output_index":0,"delta":[]}\n\n'+ else:+ code = {"streamed server": "server_error", "streamed rate limit": "rate_limit_error"}.get(failure, "new_code")+ body = text_prefix + "data: " + json.dumps({"type": "error", "code": code, "message": "failed"}) + "\n\n"+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ harness = _Harness(engine, tmp_path, "avibe", [], providers=registry_providers(media_loader=None, client=client))+ harness.controller.hub_protocol = "openai_responses"+ await harness.agent.handle_message(harness.request("finish the task"))++ assert len(sent) == (2 if continues else 1)+ assert harness.controller.terminals[-1]["is_error"] is not continues+ assert len(harness.rows("notify")) == (0 if continues else 1)+ assert len(harness.rows("user")) == 1++[email protected]("stop", [False, True])+async def test_continuation_honors_retry_after_without_delaying_stop(+ engine, session, tmp_path, published, continuation_policy, stop+):+ """The outer wait must honor the provider's floor; a Stop during it must settle without another request."""+ from core.agent_core.ai.errors import classify_error++ continuation_policy(initial_delay_s=0)+ failed = asyncio.Event()+ times = []++ async def fail(request, cancel):+ times.append(time.monotonic())+ failed.set()+ yield classify_error(status=429, streamed=True, headers={"retry-after": "30" if stop else "0.15"})++ async def recover(request, cancel):+ times.append(time.monotonic())+ yield Done(assistant("recovered"))++ harness = _Harness(engine, tmp_path, "avibe", [fail, recover])+ request = harness.request("finish the task")+ task = asyncio.create_task(harness.agent.handle_message(request))+ try:+ await asyncio.wait_for(failed.wait(), timeout=2)+ if stop:+ await _until(+ lambda: harness.agent._runtimes[SESSION].run.continuation_started_at is not None,+ "the run never reached continuation backoff",+ )+ assert await harness.agent.handle_stop(request)+ await asyncio.wait_for(task, timeout=2)+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++ assert harness.rows("notify") == []+ if stop:+ assert len(times) == 1+ assert harness.controller.terminals[-1]["settled_by"] == "stopped"+ else:+ assert len(times) == 2 and times[1] - times[0] >= 0.15+ assert harness.controller.terminals[-1]["is_error"] is False++[email protected]("retry_after", [None, "61"])+async def test_continuations_share_one_elapsed_budget(+ engine, session, tmp_path, published, continuation_policy, monkeypatch, retry_after+):+ """Run time, not just backoff, spends the outer budget; restarting Agent.resume must not reset it."""+ from core.agent_core.ai.errors import ProviderStalled, classify_error++ continuation_policy(initial_delay_s=0)+ now = [0.0]+ monkeypatch.setattr("modules.agents.vibey.agent.time", SimpleNamespace(monotonic=lambda: now[0]))++ async def fail(request, cancel):+ # The initial stall is allowed to continue, but two 60s failed continuations spend the 120s window.+ now[0] += 60+ yield classify_error(+ exc=ProviderStalled(600), streamed=True,+ headers={"retry-after": retry_after} if retry_after and now[0] > 60 else None,+ )++ harness = _Harness(engine, tmp_path, "avibe", [fail] * 6)+ await harness.agent.handle_message(harness.request("finish the task"))+ assert len(harness.provider.requests) == (2 if retry_after else 3)+ assert len(harness.rows("notify")) == 1+ assert harness.controller.terminals[-1]["is_error"] is True+ assert json.loads(harness.rows("notify")[0]["metadata_json"])["error_kind"] == "stalled"++@pytest.mark.parametrize("language", ["en", "zh"])async def test_a_provider_stall_is_not_shown_as_a_connection_failure(engine, session, tmp_path, published, language@@ -3226,11 +3546,10 @@ _THINKING_DROPS = {@pytest.mark.parametrize("drop", sorted(_THINKING_DROPS))@pytest.mark.parametrize("drops", [1, 2])-async def test_a_stream_that_drops_after_thinking_alone_gets_one_retry_then_its_own_copy(+async def test_a_stream_that_drops_after_thinking_alone_gets_provider_retry_then_transcript_continuation(engine, session, tmp_path, published, drops, drop) -> None:- """Owner decision 2026-10-11: one retry after a stream that carried only thinking; a second drop shows the- drop's own copy, never the generic line."""+ """A thinking-only provider drop is retried by the request loop, then by Vibey's transcript continuation."""import httpxfrom modules.agents.vibey.models import registry_providers@@ -3239,7 +3558,7 @@ async def test_a_stream_that_drops_after_thinking_alone_gets_one_retry_then_its_{"provider": "upstream", "api": "openai_responses", "model": "served-model", "source": "src_upstream01"},separators=(",", ":"),)- ending, copy = _THINKING_DROPS[drop]+ ending, _copy = _THINKING_DROPS[drop]thinking_then_cut = ('data: {"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1"}}\n\n''data: {"type":"response.reasoning_summary_text.delta","output_index":0,"delta":"**Checking the catalog**"}\n\n'@@ -3261,11 +3580,9 @@ async def test_a_stream_that_drops_after_thinking_alone_gets_one_retry_then_its_harness.controller.hub_protocol = "openai_responses"await harness.agent.handle_message(harness.request("hello"))- assert len(sent) == 2 and sent[1]["input"] == sent[0]["input"]- if drops == 1:- assert harness.controller.im_client.sent == ["hi"]- else:- assert harness.controller.im_client.sent == [f"❌ {i18n_t(f'vibeyAgent.error.{copy}', 'en')}"]+ assert len(sent) == drops + 1+ assert all(request["input"] == sent[0]["input"] for request in sent[1:])+ assert harness.controller.im_client.sent == ["hi"]async def test_a_turn_runs_bash_through_the_real_job_host(engine, session, tmp_path, published) -> None:diff --git a/tests/test_vibey_resume_ownership.py b/tests/test_vibey_resume_ownership.pynew file mode 100644index 000000000..c77a4a5fb--- /dev/null+++ b/tests/test_vibey_resume_ownership.py@@ -0,0 +1,220 @@+"""Retry ownership and compaction pins through the real adapter and durable Delivery rows.++The ordinary resume tests do not cover a returned P1 input, multiple retry Turns,+or process recovery while a transcript-only retry owns a tool call.+"""++from __future__ import annotations++import asyncio+from dataclasses import replace+import json++from sqlalchemy import select++from core.agent_core.ai.errors import classify_error+from core.agent_core.ai.provider import Done, ProviderError+from core.agent_core.harness.context import compaction_payload+from core.agent_core.harness.projection import context_view+from core.agent_core.messages import ToolCallBlock, text+from core.agent_core.tools.jobs import JobStatus+from core.agent_core.tools.base import ToolResult+from core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequest+from modules.agents.vibey.tools import ToolSuite+from storage import message_deliveries, messages_service+from storage.models import agent_events+from tests.agent_core.fakes import FakeJobHost, FakeTool, assistant+from tests.backend_failure_retry_helpers import reserve_failure_retry+from tests.test_vibey_agent import ( # noqa: F401 (fixtures)+ SESSION, _Harness, _context, _turn, engine, published, session,+)+++def _retry_request(harness, failed):+ source_turn = _turn(failed.context)+ with harness.engine.begin() as conn:+ message_deliveries.terminalize_turn(+ conn, source_turn, outcome="failed", settled_by="terminal_result", evidence_kind="terminal_result"+ )+ notice = next(row for row in messages_service.list_session_messages(conn, session_id=SESSION)["messages"]+ if row["type"] == "notify" and row["metadata"].get("turn_id") == source_turn)+ retry = reserve_failure_retry(conn, notice)+ turn_id = message_deliveries.new_turn_id()+ message_deliveries.claim_start_batch(+ conn, turn_id=turn_id, session_id=SESSION, backend="vibey", deliveries=[retry], dispatch_text=""+ )+ payload = message_deliveries.delivery_payload(retry)+ context = _context("avibe", SESSION, turn_id=turn_id, delivery_id=retry["id"])+ context.platform_specific.update({+ "vibey_resume": message_deliveries.is_vibey_resume_payload(payload),+ "vibey_source_turn_id": payload["metadata"][message_deliveries.VIBEY_SOURCE_TURN_METADATA_KEY],+ })+ return replace(failed, context=context, message="", user_message="")+++async def _accepted_steer(harness, request, value):+ turn_id = _turn(request.context)+ native = harness.controller.started[-1]+ delivery_id, attempt_id = harness.open_steer(value, turn_id, native)+ receipt = await harness.agent.steer_active_turn(+ SteerRequest(SESSION, turn_id, native, value, attempt_id=attempt_id),+ ActiveSteerTarget("runtime", turn_id, request.context, request, harness.agent),+ )+ assert receipt.outcome is SteerOutcome.ACCEPTED+ harness.accept_steer(delivery_id, attempt_id, turn_id)+ return delivery_id+++def _record_agents(monkeypatch, harness):+ agents = []+ start = harness.agent._start_agent++ def recording(turn, *args, **kwargs):+ start(turn, *args, **kwargs)+ agents.append(turn.agent)++ monkeypatch.setattr(harness.agent, "_start_agent", recording)+ return agents+++def _kept_after_cut(entries, pins):+ """The actual compaction writer must retain each pinned input across a cut."""+ view = context_view(entries)+ return compaction_payload(+ view, len(view.units) - 1, mode="normal", reason="threshold", checkpoint="task checkpoint",+ state=[], earlier_record=None, tokens_before=30_000, threshold=20_000, window=32_000,+ summarizer=None, usage=None, turn_inputs=pins,+ )["kept_inputs"]+++async def test_returned_steer_is_pinned_when_the_failed_request_auto_continues(+ engine, session, tmp_path, published, monkeypatch+):+ entered, release = asyncio.Event(), asyncio.Event()++ async def fail(request, cancel):+ entered.set()+ await release.wait()+ yield classify_error(status=503, body="temporary streaming failure", streamed=True)++ harness = _Harness(engine, tmp_path, "avibe", [fail, [Done(assistant("recovered"))]])+ agents = _record_agents(monkeypatch, harness)+ request = harness.request("修复问题但保留数据")+ running = asyncio.create_task(harness.agent.handle_message(request))+ await entered.wait()+ try:+ steer_id = await _accepted_steer(harness, request, "不要删除凭据")+ finally:+ release.set()+ await running++ entries = await harness.context_rows()+ pins = {row.context_seq for row in entries if row.kind == "input"}+ assert any(row.row_id == steer_id for row in entries)+ assert agents[-1]._turn_inputs == pins+ assert set(_kept_after_cut(entries, agents[-1]._turn_inputs)) == pins+ assert harness.controller.im_client.sent[-1] == "recovered"+++async def test_repeated_retry_keeps_original_and_retry_steer_inputs_but_not_old_history(+ engine, session, tmp_path, published, monkeypatch+):+ entered, release = asyncio.Event(), asyncio.Event()++ async def failed_retry(request, cancel):+ entered.set()+ await release.wait()+ yield ProviderError("invalid_request", "failed again", False)++ harness = _Harness(engine, tmp_path, "avibe", [+ [Done(assistant("old task done"))],+ [ProviderError("invalid_request", "failed", False)],+ failed_retry,+ [Done(assistant("recovered"))],+ ])+ agents = _record_agents(monkeypatch, harness)+ await harness.agent.handle_message(harness.request("old unrelated task"))+ failed = harness.request("继续当前任务")+ await harness.agent.handle_message(failed)+ retry = _retry_request(harness, failed)+ running = asyncio.create_task(harness.agent.handle_message(retry))+ await entered.wait()+ try:+ steer_id = await _accepted_steer(harness, retry, "保留数据库")+ finally:+ release.set()+ await running+ again = _retry_request(harness, retry)+ await harness.agent.handle_message(again)++ entries = await harness.context_rows()+ expected = {row.context_seq for row in entries+ if row.row_id in {failed.context.platform_specific["delivery_id"], steer_id}}+ assert len(expected) == 2+ assert agents[-1]._turn_inputs == expected+ assert set(_kept_after_cut(entries, agents[-1]._turn_inputs)) == expected+ assert len(harness.rows("agent_initiated")) == 2+ assert harness.controller.im_client.sent[-1] == "recovered"+++async def test_live_retry_attributes_tool_results_and_audits_without_consuming_control_input(+ engine, session, tmp_path, published+):+ harness = _Harness(engine, tmp_path, "avibe", [+ [ProviderError("invalid_request", "failed", False)],+ [Done(assistant("", calls=[ToolCallBlock("retry_tool", "echo", {})]))],+ [Done(assistant("recovered"))],+ ])+ original = harness.request("继续运行检查")+ await harness.agent.handle_message(original)+ retry = _retry_request(harness, original)+ with engine.connect() as conn:+ before = set(conn.execute(select(agent_events.c.id)).scalars())+ await harness.agent.handle_message(retry)++ with engine.connect() as conn:+ events = [row for row in conn.execute(select(agent_events)).mappings() if row["id"] not in before]+ assert any(row["event_type"] == "tool_result" for row in events)+ assert {row["turn_id"] for row in events} == {_turn(retry.context)}+ assert len(harness.rows("user")) == 1+ assert harness.rows("agent_initiated")[0]["context_seq"] is None+++async def test_retry_events_and_recovered_job_belong_to_retry_turn_not_last_input(+ engine, session, tmp_path, published+):+ jobs = FakeJobHost()++ async def recovered(call, job_id, status, watch_id):+ return ToolResult((text(f"continued as {watch_id}"),))++ suite = ToolSuite(+ jobs=jobs, create_tools=lambda jobs_, sink: [FakeTool("bash")], render_recovered=recovered,+ find_job=lambda call: "job_retry" if call.tool_call_id == "retry_bash" else None,+ )+ harness = _Harness(engine, tmp_path, "avibe", [[ProviderError("invalid_request", "failed", False)]], suite=suite)+ original = harness.request("运行检查")+ await harness.agent.handle_message(original)+ retry = _retry_request(harness, original)+ retry_turn = _turn(retry.context)+ harness.controller._native_start(retry.context)+ # Simulate the retry process dying after the tool call was committed, before its result.+ harness.agent.store.bind_agent(SESSION, "vibey", turn_id=retry_turn)+ response = await harness.agent.store.append_response(+ SESSION, assistant("", calls=[ToolCallBlock("retry_bash", "bash", {"command": "pytest"})]), final=False+ )+ await harness.agent.store.append_audit(SESSION, "attempt", {"version": 1, "test": "retry"})+ await harness.agent.store.append_payload(SESSION, "agent_state", {"version": 1, "state": {"resumed": True}})+ jobs.states["job_retry"] = JobStatus("running")+ harness.new_agent()+ assert await harness.agent.recover_runtime_state() == []++ with engine.connect() as conn:+ events = conn.execute(select(agent_events).where(agent_events.c.session_id == SESSION)).mappings().all()+ retry_events = [row for row in events if row["context_seq"] is None or row["context_seq"] > response.context_seq]+ assert {row["turn_id"] for row in retry_events} == {retry_turn}+ assert jobs.watches == {"job_retry": "watch_job_retry"}+ [result] = [entry for entry in await harness.context_rows() if entry.kind == "tool_result"]+ assert "watch_job_retry" in result.message.content[0].text+ [response_row] = harness.rows("assistant")+ assert json.loads(response_row["metadata_json"])["turn_id"] == retry_turndiff --git a/tests/test_vibey_resume_recovery_query.py b/tests/test_vibey_resume_recovery_query.pynew file mode 100644index 000000000..d7d333132--- /dev/null+++ b/tests/test_vibey_resume_recovery_query.py@@ -0,0 +1,345 @@+"""Bounded Vibey T3 recovery over the real Message/Delivery boundary.++The regression this owns is the second-head finding in PR #2689: accepted hidden+Vibey retry Deliveries remain null-context forever, so a Python-side filter made+every recovery pass scan retry history and hydrate attachments/Deliveries before+throwing those rows away. The owning query must exclude the trusted control+shape and use the partial index, while ordinary and forged-marker inputs remain+recoverable.+"""++from __future__ import annotations++import importlib+import sqlite3+from pathlib import Path+from typing import Any, Callable++import pytest+from alembic import command+from sqlalchemy import event++from modules.agents.vibey import VibeyAgent+from storage import message_deliveries+from storage.db import create_sqlite_engine+from storage.migrations import alembic_config, run_migrations+from storage.models import agent_sessions+from storage.vibey_recovery import VIBEY_RECOVERY_INPUT_PREDICATE++pytestmark = pytest.mark.no_sqlite_template++_NOW = "2026-10-16T00:00:00.000000Z"+_SESSION = "ses_recovery"+_MIGRATION = importlib.import_module(+ "storage.alembic.versions.20261016_0067_vibey_recovery_input_index"+)+++def _insert_session(conn, session_id: str) -> None:+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ agent_backend="vibey",+ agent_variant="vibey",+ session_anchor=session_id,+ workdir="/tmp",+ native_session_id=session_id,+ status="active",+ visibility="foreground",+ pinned=0,+ agent_status="idle",+ metadata_json="{}",+ created_at=_NOW,+ updated_at=_NOW,+ last_active_at=_NOW,+ )+ )+++def _accepted_input(+ engine,+ session_id: str,+ ordinal: int,+ *,+ author: str,+ source: str,+ message_type: str,+ text: str | None,+ metadata: dict[str, Any] | None = None,+) -> tuple[str, str]:+ delivery_id = f"dlv_recovery_{session_id}_{ordinal}"+ turn_id = f"turn_recovery_{session_id}_{ordinal}"+ dispatch_text = text or ""+ with engine.begin() as conn:+ delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id=delivery_id,+ session_id=session_id,+ priority="p3",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=None,+ session_id=session_id,+ platform="avibe",+ author=author,+ source=source,+ message_type=message_type,+ text=text,+ metadata=metadata,+ ),+ dispatch_text=dispatch_text,+ now=_NOW,+ )+ claimed = message_deliveries.claim_start_batch(+ conn,+ turn_id=turn_id,+ session_id=session_id,+ backend="vibey",+ deliveries=[delivery],+ dispatch_text=dispatch_text,+ )+ started = message_deliveries.bind_native_start(+ conn,+ turn_id=turn_id,+ expected_version=int(claimed["turn"]["version"]),+ runtime_key="test",+ runtime_turn_id=turn_id,+ native_turn_id=f"vibey:test:{turn_id}",+ )+ assert started is not None+ message_deliveries.materialize_start_acceptance(+ conn,+ turn_id=turn_id,+ evidence={"kind": "test"},+ )+ message_deliveries.terminalize_turn(+ conn,+ turn_id,+ outcome="completed",+ settled_by="test",+ evidence_kind="test",+ )+ return delivery_id, turn_id+++def recovery_engine(tmp_path: Path):+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path)+ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ _insert_session(conn, _SESSION)+ try:+ yield engine+ finally:+ engine.dispose()+++def _agent(engine) -> VibeyAgent:+ agent = object.__new__(VibeyAgent)+ agent._engine = engine+ return agent+++def _recovery_query_plan(+ engine,+ operation: Callable[[], Any],+) -> str:+ statements: list[tuple[str, Any]] = []++ def capture(_conn, _cursor, statement, parameters, _context, _executemany):+ if "message_deliveries" in statement.lower() and "context_seq is null" in statement.lower():+ statements.append((statement, parameters))++ event.listen(engine, "before_cursor_execute", capture)+ try:+ operation()+ finally:+ event.remove(engine, "before_cursor_execute", capture)+ assert statements, "the recovery operation did not issue its Message query"+ statement, parameters = statements[-1]+ with engine.connect() as conn:+ rows = conn.exec_driver_sql(+ f"EXPLAIN QUERY PLAN {statement}", parameters+ ).all()+ return " ".join(str(row[3]) for row in rows)+++def test_migration_round_trip_owns_the_recovery_index(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision=_MIGRATION.down_revision)+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "select name from sqlite_master where type = 'index' and name = ?",+ (_MIGRATION._INDEX,),+ ).fetchone() is None+ assert conn.execute(+ "select name from sqlite_master where type = 'index' and name = ?", (_MIGRATION._DELIVERY_INDEX,)+ ).fetchone() is None++ run_migrations(db_path)+ with sqlite3.connect(db_path) as conn:+ row = conn.execute(+ "select sql from sqlite_master where type = 'index' and name = ?",+ (_MIGRATION._INDEX,),+ ).fetchone()+ assert row is not None+ assert row[0].lower() == _MIGRATION.CREATE_INDEX_SQL.lower()+ assert [item[2] for item in conn.execute(f"pragma index_info({_MIGRATION._INDEX})")] == [+ "context_seq",+ "session_id",+ "id",+ ]+ assert [item[2] for item in conn.execute(f"pragma index_info({_MIGRATION._DELIVERY_INDEX})")] == ["message_id"]++ command.downgrade(alembic_config(db_path), _MIGRATION.down_revision)+ with sqlite3.connect(db_path) as conn:+ assert conn.execute(+ "select name from sqlite_master where type = 'index' and name = ?",+ (_MIGRATION._INDEX,),+ ).fetchone() is None+ assert conn.execute(+ "select name from sqlite_master where type = 'index' and name = ?", (_MIGRATION._DELIVERY_INDEX,)+ ).fetchone() is None+++def test_recovery_excludes_hidden_history_before_delivery_and_attachment_hydration(+ recovery_engine, monkeypatch+) -> None:+ hidden_ids = {+ _accepted_input(+ recovery_engine,+ _SESSION,+ ordinal,+ author="harness",+ source="harness",+ message_type="agent_initiated",+ text=None,+ metadata={"vibey_resume": True, "retry_notice_id": f"notice-{ordinal}"},+ )[0]+ for ordinal in range(300)+ }+ real_id, _ = _accepted_input(+ recovery_engine,+ _SESSION,+ 1000,+ author="harness",+ source="harness",+ message_type="agent_initiated",+ text="continue the real agent-initiated input",+ metadata={"origin": "watch"},+ )+ forged_id, _ = _accepted_input(+ recovery_engine,+ _SESSION,+ 1001,+ author="user",+ source="user",+ message_type="user",+ text="a user message carrying a forged marker",+ metadata={"vibey_resume": True},+ )+ missing = object()+ negative_ids = []+ for ordinal, marker in enumerate((1, 1.0, "true", None, False, missing), start=1100):+ metadata = {} if marker is missing else {"vibey_resume": marker}+ negative_ids.append(+ _accepted_input(+ recovery_engine,+ _SESSION,+ ordinal,+ author="harness",+ source="harness",+ message_type="agent_initiated",+ text=f"marker negative {ordinal}",+ metadata=metadata,+ )[0]+ )+ null_source_id, _ = _accepted_input(+ recovery_engine,+ _SESSION,+ 1200,+ author="harness",+ source=None,+ message_type="agent_initiated",+ text="null source is an ordinary input",+ metadata={"vibey_resume": True},+ )++ delivery_lookups: list[str] = []+ attachment_lookups: list[tuple[str, list[Any]]] = []+ original_get_delivery = message_deliveries.get_delivery+ monkeypatch.setattr(+ message_deliveries,+ "get_delivery",+ lambda conn, delivery_id: (+ delivery_lookups.append(str(delivery_id))+ or original_get_delivery(conn, delivery_id)+ ),+ )+ import core.workbench_media as workbench_media++ original_resolve = workbench_media.resolve_attachment_specs+ monkeypatch.setattr(+ workbench_media,+ "resolve_attachment_specs",+ lambda conn, *, session_id, attachments: (+ attachment_lookups.append((str(session_id), list(attachments)))+ or original_resolve(conn, session_id=session_id, attachments=attachments)+ ),+ )++ agent = _agent(recovery_engine)+ inputs = agent._unconsumed_inputs(_SESSION)++ assert {row[0] for row in inputs} == {real_id, forged_id, *negative_ids, null_source_id}+ assert hidden_ids.isdisjoint(delivery_lookups)+ assert set(delivery_lookups) == {real_id, forged_id, *negative_ids, null_source_id}+ assert len(attachment_lookups) == 9+ delivery_lookups.clear()+ assert agent._sessions_with_unconsumed_inputs() == [_SESSION]+ assert delivery_lookups == []+++def test_recovery_queries_seek_the_partial_index(recovery_engine) -> None:+ _accepted_input(+ recovery_engine,+ _SESSION,+ 1,+ author="harness",+ source="harness",+ message_type="agent_initiated",+ text=None,+ metadata={"vibey_resume": True},+ )+ _accepted_input(+ recovery_engine,+ _SESSION,+ 2,+ author="user",+ source="user",+ message_type="user",+ text="real input",+ )+ agent = _agent(recovery_engine)++ session_plan = _recovery_query_plan(+ recovery_engine,+ lambda: agent._unconsumed_inputs(_SESSION),+ )+ global_plan = _recovery_query_plan(+ recovery_engine,+ agent._sessions_with_unconsumed_inputs,+ )++ for plan in (session_plan, global_plan):+ assert "USING INDEX ix_messages_vibey_recovery_input" in plan, (+ f"session_plan={session_plan}; global_plan={global_plan}"+ )+ assert "USING INDEX ix_message_deliveries_message (message_id=?)" in plan, plan+ for table in ("messages", "message_deliveries", "session_turns"):+ assert f"SCAN {table}" not in plan, plan+ assert f"SEARCH {table}" in plan, plan+ assert "context_seq=? AND session_id=?" in session_plan+ assert "context_seq=?" in global_plan+ assert VIBEY_RECOVERY_INPUT_PREDICATE in _MIGRATION.CREATE_INDEX_SQLdiff --git a/tests/test_web_push_provider_invalidation_migration.py b/tests/test_web_push_provider_invalidation_migration.pyindex 36d0e0ba8..832ef51a0 100644--- a/tests/test_web_push_provider_invalidation_migration.py+++ b/tests/test_web_push_provider_invalidation_migration.py@@ -69,7 +69,7 @@ def test_upgrade_keeps_legacy_disabled_failure_opted_out(tmp_path):web_push_service.mark_send_failure(conn, endpoint=enabled["endpoint"], disable=True)with sqlite3.connect(path) as conn:assert conn.execute("select version_num from alembic_version").fetchone() == (- "20261015_0066",+ "20261016_0067",)command.downgrade(migrations.alembic_config(path), "20260907_0061")diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex da775dad4..b71fa4fc7 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -12159,10 +12159,16 @@ async def sessions_messages_create(session_id: str):attachment_specs = resolve_attachment_specs(conn, session_id=session_id, attachments=content.get("attachments") or [])+ from storage import message_deliveries++ internal_resume = bool(+ retry_for and message_deliveries.is_vibey_resume_payload(message)+ )if (not dispatch_text.strip()and not attachment_specsand not (retry_for and message.get("state") == "accepted")+ and not internal_resume):from storage import message_deliveries