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
feat(delivery): complete P0/P1/P3 source cutover (#1135)
Call Whited903d5273074
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex 6ca79fe2b..d1a127f94 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -575,6 +575,19 @@ class SessionsStore:"""Check if a message ID is in the processed set."""return message_ts in self._get_processed_set(channel_id, thread_ts)+ def has_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:+ """Check the cross-process processed-message authority."""++ self._ensure_service()+ exists = self._service.processed_message_exists(+ channel_id,+ thread_ts,+ message_ts,+ )+ if exists:+ self._remember_processed_message(channel_id, thread_ts, message_ts)+ return exists+def _remember_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> None:if channel_id not in self.state.processed_message_ts:self.state.processed_message_ts[channel_id] = {}diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex 18cad19ce..feaec7e8e 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -858,7 +858,13 @@ class AgentAuthService:flow.awaiting_code = Falseawait self._send_message(context, f"✅ {self._t('command.setup.codeSubmitted', backend=flow.backend)}")- async def maybe_consume_setup_reply(self, context: MessageContext, message: str) -> bool:+ async def maybe_consume_setup_reply(+ self,+ context: MessageContext,+ message: str,+ *,+ claim_native_event: Callable[[], bool] | None = None,+ ) -> bool:"""Intercept plain-text replies for active setup flows before normal agent routing."""if not message or message.lstrip().startswith("/"):return False@@ -866,6 +872,8 @@ class AgentAuthService:flow = self._find_flow_for_submission(context, "claude")if flow is not None and flow.backend == "claude" and flow.initiator_user_id == context.user_id:if self._allows_proactive_code_submission(flow) and self._parse_claude_callback_code(message) is not None:+ if claim_native_event is not None and not claim_native_event():+ return Trueawait self.submit_code(context, message, backend_hint="claude")return True@@ -877,6 +885,8 @@ class AgentAuthService:and opencode_flow.awaiting_codeand self._looks_like_direct_opencode_credential(message)):+ if claim_native_event is not None and not claim_native_event():+ return Trueawait self.submit_code(context, message.strip(), backend_hint="opencode")return Truediff --git a/core/controller.py b/core/controller.pyindex 61ebd0dd3..aa8c3cf99 100644--- a/core/controller.py+++ b/core/controller.py@@ -210,11 +210,10 @@ class Controller:# the ``active_turn_sinks`` property below delegate to it.# Per-session turn gate, published by ``core.internal_server.create_app``- # once the internal server is built on the loop. The scheduler routes- # avibe scheduled / watch turns through it so they QUEUE behind an active- # Chat turn (never preempt it) and get the Chat path's turn lifecycle- # (in_flight + turn.start / turn.end + Stop). ``None`` until the server is- # up — callers must treat its absence as "fall back to the direct path".+ # once the internal server is built on the loop. Persisted Session inputs+ # route through it so their source policy can queue, steer, or replace via+ # the same durable lifecycle (in_flight + turn.start / turn.end + Stop).+ # ``None`` until the server is up; callers then fall back to the direct path.self.session_turn_gate: Optional[Any] = None# Per-session turn owner (FSM). Created here so the controller owns it fromdiff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 5d668255b..3427ce874 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -96,12 +96,27 @@ class MessageHandler(BaseHandler):agent_dispatched = Falsetry:is_human = source == self.TURN_SOURCE_HUMAN+ durable_delivery_owned = bool(+ (context.platform_specific or {}).get("delivery_ids")+ )+ delivery_manager = getattr(self.controller, "session_turns", None)+ durable_ingress_enabled = bool(+ is_human+ and callable(getattr(delivery_manager, "deliver", None))+ )control_message = self._get_control_message(context, message) if is_human else message# Record user activity for auto-update idle detectionif is_human and hasattr(self.controller, "update_checker"):self.controller.update_checker.record_activity()+ if (+ durable_ingress_enabled+ and not durable_delivery_owned+ and self._is_duplicate_human_delivery(context)+ ):+ return None+# 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)@@ -110,34 +125,27 @@ class MessageHandler(BaseHandler):await self.controller.command_handler.handle_start(context, "")return None- if is_human:- # Claim the message before processing so duplicate IM deliveries or- # parallel runtime instances cannot start separate agent turns.- message_ts = context.message_id- thread_ts = context.thread_id or context.message_id- if message_ts and thread_ts:- try_record = getattr(self.sessions, "try_record_processed_message", None)- if callable(try_record):- recorded = try_record(context.channel_id, thread_ts, message_ts)- else:- recorded = not self.sessions.is_message_already_processed(- context.channel_id,- thread_ts,- message_ts,- )- if recorded:- self.sessions.record_processed_message(context.channel_id, thread_ts, message_ts)- if not recorded:- logger.info(- f"Skipping already processed message: channel={context.channel_id}, "- f"thread={thread_ts}, message={message_ts}"- )- return None+ if (+ is_human+ and not durable_delivery_owned+ and not durable_ingress_enabled+ ):+ if not self._claim_native_human_event(context):+ return None- if is_human and not has_files:+ if is_human and not durable_delivery_owned and not has_files:maybe_consume_setup_reply = getattr(self.controller.agent_auth_service, "maybe_consume_setup_reply", None)if callable(maybe_consume_setup_reply):- consumed = await maybe_consume_setup_reply(context, control_message)+ kwargs = {}+ if durable_ingress_enabled:+ kwargs["claim_native_event"] = lambda: self._claim_native_human_event(+ context+ )+ consumed = await maybe_consume_setup_reply(+ context,+ control_message,+ **kwargs,+ )if consumed:return None@@ -145,7 +153,16 @@ class MessageHandler(BaseHandler):# Allow "stop" shortcut inside Slack threadsactive_thread_id = resolve_context_thread_id(context) or context.thread_id- if is_human and active_thread_id and control_message.strip().lower() in ["stop", "/stop"]:+ if (+ is_human+ and not durable_delivery_owned+ and active_thread_id+ and control_message.strip().lower() in ["stop", "/stop"]+ ):+ if durable_ingress_enabled and not self._claim_native_human_event(+ context+ ):+ return Noneif await self._handle_inline_stop(context):return None@@ -161,10 +178,7 @@ class MessageHandler(BaseHandler):# Durable Deliveries materialize their Message only after exact native# acceptance. Legacy direct turns still mirror at this boundary.- durable_delivery_owned = bool(- (context.platform_specific or {}).get("delivery_ids")- )- if not durable_delivery_owned:+ if not durable_delivery_owned and not durable_ingress_enabled:if source == self.TURN_SOURCE_HUMAN:from core.message_mirror import mirror_inbound@@ -398,8 +412,32 @@ class MessageHandler(BaseHandler):subagent_name = Nonesubagent_model = Nonesubagent_reasoning_effort = None+ delivery_context = platform_payload.get("delivery_admission_context")+ restored_route = (+ delivery_context.get("message_handler_route")+ if durable_delivery_owned and isinstance(delivery_context, dict)+ else None+ )+ restored_route = restored_route if isinstance(restored_route, dict) else None- if agent_name in ["opencode", "claude", "codex"]:+ if restored_route is not None:+ base_session_id = str(+ restored_route.get("base_session_id") or base_session_id+ )+ composite_key = str(+ restored_route.get("composite_session_id") or composite_key+ )+ subagent_name = restored_route.get("subagent_name") or None+ matched_prefix = restored_route.get("subagent_key") or None+ subagent_model = restored_route.get("subagent_model") or None+ subagent_reasoning_effort = (+ restored_route.get("subagent_reasoning_effort") or None+ )+ if restored_route.get("routing_subagent"):+ spec = dict(context.platform_specific or {})+ spec["routing_subagent"] = subagent_name+ context.platform_specific = spec+ elif agent_name in ["opencode", "claude", "codex"]:from modules.agents.subagent_router import (load_codex_subagent,load_claude_subagent,@@ -460,24 +498,39 @@ class MessageHandler(BaseHandler):matched_prefix = parsed.namesubagent_message = parsed.message- if subagent_name and subagent_message:- message = subagent_message- if agent_name in {"claude", "codex"}:- base_session_id = f"{base_session_id}:{subagent_name}"+ if restored_route is None:+ if subagent_name and subagent_message:+ message = subagent_message+ if agent_name in {"claude", "codex"}:+ base_session_id = f"{base_session_id}:{subagent_name}"+ composite_key = f"{base_session_id}:{working_path}"+ elif agent_name in {"claude", "codex"} and routing_agent and not subagent_name:+ # Update session IDs for routing-based agent to match SessionHandler+ base_session_id = f"{base_session_id}:{routing_agent}"composite_key = f"{base_session_id}:{working_path}"- elif agent_name in {"claude", "codex"} and routing_agent and not subagent_name:- # Update session IDs for routing-based agent to match SessionHandler- base_session_id = f"{base_session_id}:{routing_agent}"- composite_key = f"{base_session_id}:{working_path}"- subagent_name = routing_agent- # Flag the routing-default subagent so the backends' reserved-native- # resume shortcut treats it like an explicit subagent: this namespaced- # base has its OWN thread, so resuming the MAIN session's reserved- # native here would wrongly replay the main transcript under the- # subagent on the first turn after the subagent is enabled (Codex P2).- spec = dict(context.platform_specific or {})- spec["routing_subagent"] = routing_agent- context.platform_specific = spec+ subagent_name = routing_agent+ # Flag the routing-default subagent so the backends' reserved-native+ # resume shortcut treats it like an explicit subagent: this namespaced+ # base has its OWN thread, so resuming the MAIN session's reserved+ # native here would wrongly replay the main transcript under the+ # subagent on the first turn after the subagent is enabled (Codex P2).+ spec = dict(context.platform_specific or {})+ spec["routing_subagent"] = routing_agent+ context.platform_specific = spec++ from core.message_priority import delivery_intent_for_trigger++ delivery_intent = delivery_intent_for_trigger("im")+ if (+ restored_route is None+ and agent_name == "opencode"+ and subagent_name+ and subagent_message is not None+ ):+ # OpenCode subagents share the main Session anchor. They need a+ # fresh Turn so the persisted route can select the requested+ # native subagent instead of text-steering the active main Turn.+ delivery_intent = "queue"if agent_name in {"claude", "codex"} and subagent_name:spec = dict(context.platform_specific or {})@@ -485,6 +538,80 @@ class MessageHandler(BaseHandler):spec["backend_composite_session_id"] = composite_keycontext.platform_specific = spec+ durable_dispatch_text = None+ if durable_ingress_enabled and not durable_delivery_owned:+ durable_dispatch_text = await self._prepend_message_metadata(+ context,+ message,+ include_user_info=True,+ )++ # Resolve remote attachments before admission so a queued Delivery+ # owns stable local media references and can survive a restart.+ processed_files = None+ attachment_errors: List[str] = []+ downloaded_attachment_paths: list[str] = []+ if context.files:+ existing_local_paths = {+ str(attachment.local_path)+ for attachment in context.files+ if isinstance(attachment, FileAttachment)+ and attachment.local_path+ }+ processed_files, attachment_errors = await self._process_file_attachments(+ context,+ working_path,+ )+ if processed_files:+ downloaded_attachment_paths = [+ str(attachment.local_path)+ for attachment in processed_files+ if isinstance(attachment, FileAttachment)+ and attachment.local_path+ and str(attachment.local_path) not in existing_local_paths+ ]+ logger.info(+ "Processed %s file attachments for message",+ len(processed_files),+ )++ if durable_ingress_enabled and not durable_delivery_owned:+ assert durable_dispatch_text is not None+ admitted = await self._admit_human_delivery(+ manager=delivery_manager,+ context=context,+ dispatch_text=self._append_attachment_errors(+ durable_dispatch_text,+ attachment_errors,+ ),+ display_text=control_message,+ processed_files=processed_files or [],+ session_key=session_key,+ agent_name=agent_name,+ session_anchor=base_session_id,+ working_path=working_path,+ vibe_agent=vibe_agent,+ delivery_intent=delivery_intent,+ downloaded_attachment_paths=downloaded_attachment_paths,+ admission_context={+ "message_handler_route": {+ "base_session_id": base_session_id,+ "composite_session_id": composite_key,+ "subagent_name": subagent_name,+ "subagent_key": matched_prefix,+ "subagent_model": subagent_model,+ "subagent_reasoning_effort": subagent_reasoning_effort,+ "routing_subagent": bool(+ (context.platform_specific or {}).get(+ "routing_subagent"+ )+ ),+ }+ },+ )+ if admitted:+ return None+if is_human:# The concise status bubble (footer-only at turn start) is now# posted by AgentService.handle_message after the runtime gate is acquired,@@ -507,14 +634,6 @@ class MessageHandler(BaseHandler):# removed here immediately, leaving no processing indicator# for the entire duration of the subagent run.- # Process file attachments if present- processed_files = None- attachment_errors: List[str] = []- if context.files:- processed_files, attachment_errors = await self._process_file_attachments(context, working_path)- if processed_files:- logger.info(f"Processed {len(processed_files)} file attachments for message")-user_message = self._get_user_message(context, message)audio_transcripts = await self._transcribe_audio_attachments(context, processed_files or [])if audio_transcripts:@@ -522,7 +641,12 @@ class MessageHandler(BaseHandler):user_message = append_audio_transcripts_to_message(user_message, audio_transcripts)await self._echo_audio_transcripts_if_enabled(context, audio_transcripts)- message = await self._prepend_message_metadata(context, message, include_user_info=is_human)+ if not (is_human and durable_delivery_owned):+ message = await self._prepend_message_metadata(+ context,+ message,+ include_user_info=is_human,+ )message = self._append_attachment_errors(message, attachment_errors)@@ -566,7 +690,13 @@ class MessageHandler(BaseHandler):# session PK exists (mirror_inbound runs above, pre-dispatch); the PK# now lives on platform_specific['agent_session_id'] — the same field# the agent reply uses — so a session's transcript stays complete.- if is_human and context.platform and context.platform != "avibe" and context.message_id:+ if (+ is_human+ and not durable_delivery_owned+ and context.platform+ and context.platform != "avibe"+ and context.message_id+ ):bound_session_id = (context.platform_specific or {}).get("agent_session_id")if bound_session_id:from core.message_mirror import link_inbound_message_session@@ -639,6 +769,263 @@ class MessageHandler(BaseHandler):if callable(mark_complete):mark_complete(context)+ async def _admit_human_delivery(+ self,+ *,+ manager: Any,+ context: MessageContext,+ dispatch_text: str,+ display_text: str,+ processed_files: List[FileAttachment],+ session_key: str,+ agent_name: str,+ session_anchor: str,+ working_path: str,+ vibe_agent: Any,+ delivery_intent: str,+ downloaded_attachment_paths: List[str],+ admission_context: dict[str, Any],+ ) -> bool:+ """Transfer one IM input to its durable owner before native work."""++ session_id = self.session_handler.ensure_agent_session_id(+ context,+ session_key=session_key,+ agent_name=agent_name,+ session_anchor=session_anchor,+ working_path=working_path,+ vibe_agent_id=getattr(vibe_agent, "id", None),+ vibe_agent_name=getattr(vibe_agent, "name", None),+ )+ if not session_id:+ raise RuntimeError("Could not reserve the Agent Session before delivery")++ from core.message_priority import priority_for_delivery_intent+ from core.session_turns import DeliveryRequest+ from storage import message_deliveries, media_service, messages_service+ from storage.agent_session_rows import reserve_write_lock+ from storage.db import get_cached_sqlite_engine++ priority = priority_for_delivery_intent(delivery_intent)+ scope_id = None+ request = None+ duplicate_delivery_id = None+ try:+ with get_cached_sqlite_engine().begin() as conn:+ from core.message_mirror import _scope_id_for_session++ reserve_write_lock(conn)+ scope_id = _scope_id_for_session(conn, session_id)+ platform = str(context.platform or "")+ native_message_id = str(context.message_id or "").strip()+ if native_message_id and messages_service.native_message_exists(+ conn,+ platform=platform,+ scope_id=scope_id,+ native_message_id=native_message_id,+ ):+ duplicate_delivery_id = ""+ elif native_message_id:+ existing = message_deliveries.get_delivery_by_native_identity(+ conn,+ platform=platform,+ native_message_id=native_message_id,+ scope_id=scope_id,+ session_id=session_id,+ normalize_legacy=True,+ )+ if existing is not None:+ duplicate_delivery_id = str(existing["id"])++ if duplicate_delivery_id is None:+ attachment_refs: list[dict[str, Any]] = []+ for attachment in processed_files:+ if not attachment.local_path:+ continue+ token = media_service.register(+ conn,+ scope_id=scope_id,+ session_id=session_id,+ kind=(+ "image"+ if str(attachment.mimetype or "").startswith("image/")+ else "file"+ ),+ source="im_inbound",+ local_path=attachment.local_path,+ file_name=attachment.name,+ content_type=attachment.mimetype,+ )+ attachment_refs.append(+ {+ "token": token,+ "name": attachment.name,+ "mimetype": attachment.mimetype,+ "size": attachment.size,+ }+ )++ if not message_deliveries.has_substantive_input(+ dispatch_text,+ has_attachments=bool(attachment_refs),+ ):+ raise ValueError(+ "Message contains no deliverable text or attachment"+ )++ content = {"text": display_text}+ if attachment_refs:+ content["attachments"] = attachment_refs+ request = DeliveryRequest(+ session_id=session_id,+ priority=priority,+ content=dispatch_text,+ has_content=True,+ delivery_id=message_deliveries.new_delivery_id(),+ scope_id=scope_id,+ platform=platform,+ source="user",+ author="user",+ message_type="user",+ author_id=str(context.user_id or "").strip() or None,+ display_text=display_text,+ content_json=content,+ admission_context=admission_context,+ native_message_id=native_message_id or None,+ parent_native_message_id=(+ str(context.thread_id or "").strip() or None+ ),+ )+ reserved = manager.reserve_delivery(conn, request)+ if str(reserved["id"]) != request.delivery_id:+ raise RuntimeError(+ "native Delivery appeared after writer reservation"+ )+ except Exception:+ self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)+ raise++ if duplicate_delivery_id is not None:+ self._cleanup_unowned_attachment_paths(downloaded_attachment_paths)+ if duplicate_delivery_id:+ payload = dict(context.platform_specific or {})+ payload["delivery_id"] = duplicate_delivery_id+ context.platform_specific = payload+ return True++ if request is None:+ raise RuntimeError("Delivery reservation did not produce a request")+ result = await manager.deliver(request, context=context)+ payload = dict(context.platform_specific or {})+ payload["delivery_id"] = result.delivery_id+ context.platform_specific = payload+ if result.state in {+ "queued",+ "pending_steer",+ "steering",+ "reconciling_steer",+ }:+ from core.inbox_events import bus++ bus.publish("queue.updated", {"session_id": session_id})+ return True++ @staticmethod+ def _cleanup_unowned_attachment_paths(paths: List[str]) -> None:+ from pathlib import Path++ for path in dict.fromkeys(str(value) for value in paths if value):+ try:+ Path(path).unlink(missing_ok=True)+ except Exception as err:+ logger.warning("Failed to remove unowned attachment %s: %s", path, err)++ def _is_duplicate_human_delivery(self, context: MessageContext) -> bool:+ """Reject a retried native event before pre-admission side effects."""++ if self._native_human_event_processed(context):+ return True+ platform = str(context.platform or "").strip()+ native_message_id = str(context.message_id or "").strip()+ if not platform or not native_message_id:+ return False+ try:+ from storage import message_deliveries, messages_service+ from storage.db import get_cached_sqlite_engine+ from core.message_mirror import scope_id_for_context++ scope_id = scope_id_for_context(context)++ with get_cached_sqlite_engine().connect() as conn:+ if messages_service.native_message_exists(+ conn,+ platform=platform,+ scope_id=scope_id,+ native_message_id=native_message_id,+ ):+ return True+ return bool(+ message_deliveries.get_delivery_by_native_identity(+ conn,+ platform=platform,+ native_message_id=native_message_id,+ scope_id=scope_id,+ )+ is not None+ )+ except Exception:+ logger.exception(+ "Could not preflight native Message dedupe for %s:%s",+ platform,+ native_message_id,+ )+ return False++ def _native_human_event_processed(self, context: MessageContext) -> bool:+ message_ts = context.message_id+ thread_ts = context.thread_id or context.message_id+ if not message_ts or not thread_ts:+ return False+ checker = getattr(self.sessions, "has_processed_message", None)+ if callable(checker):+ return bool(checker(context.channel_id, thread_ts, message_ts))+ checker = getattr(self.sessions, "is_message_already_processed", None)+ return bool(+ callable(checker)+ and checker(context.channel_id, thread_ts, message_ts)+ )++ def _claim_native_human_event(self, context: MessageContext) -> bool:+ """Fence a native control input that intentionally creates no Delivery."""++ message_ts = context.message_id+ thread_ts = context.thread_id or context.message_id+ if not message_ts or not thread_ts:+ return True+ try_record = getattr(self.sessions, "try_record_processed_message", None)+ if callable(try_record):+ recorded = try_record(context.channel_id, thread_ts, message_ts)+ else:+ recorded = not self.sessions.is_message_already_processed(+ context.channel_id,+ thread_ts,+ message_ts,+ )+ if recorded:+ self.sessions.record_processed_message(+ context.channel_id,+ thread_ts,+ message_ts,+ )+ if not recorded:+ logger.info(+ "Skipping already processed message: channel=%s, thread=%s, message=%s",+ context.channel_id,+ thread_ts,+ message_ts,+ )+ return bool(recorded)+@staticmethoddef _build_agent_request(**kwargs: Any) -> AgentRequest:try:@@ -953,6 +1340,26 @@ class MessageHandler(BaseHandler):base_session_id, working_path, composite_key = self.session_handler.get_session_info(context)session_key = self._get_session_key(context)agent_name = self.controller.resolve_agent_for_context(context)+ manager = getattr(self.controller, "session_turns", None)+ cancel = getattr(manager, "cancel", None)+ session_id = str(+ (context.platform_specific or {}).get("agent_session_id") or ""+ ).strip()+ if not session_id:+ getter = getattr(self.sessions, "get_agent_session_row_id", None)+ if callable(getter):+ session_id = str(+ getter(session_key, base_session_id, agent_name) or ""+ ).strip()+ if session_id and callable(cancel):+ result = await cancel(session_id)+ handled = bool(isinstance(result, dict) and result.get("ok"))+ if not handled:+ await self._get_im_client(context).send_message(+ context,+ f"ℹ️ {self._t('command.stop.noActiveSession')}",+ )+ return handledrequest = AgentRequest(context=context,message="stop",@@ -1104,7 +1511,7 @@ class MessageHandler(BaseHandler):if key in {"name", "mimetype", "url", "content", "local_path", "size"}:continuefile_info[key] = value- timestamp = int(time.time())+ timestamp = time.time_ns()safe_name = self._sanitize_filename(attachment.name)filename = f"{timestamp}_{safe_name}"local_path = attachments_dir / filenamediff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex b8959fc4f..f0ce7dd5e 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -1828,6 +1828,9 @@ class SessionHandler(BaseHandler):session_key: str,agent_name: str,session_anchor: str,+ working_path: Optional[str] = None,+ vibe_agent_id: Optional[str] = None,+ vibe_agent_name: Optional[str] = None,) -> Optional[str]:# avibe: pin the reserved workbench row id before any hidden-row creation# (mirrors BaseAgent.ensure_agent_session_id) so a pre-bind setup/query@@ -1843,7 +1846,19 @@ class SessionHandler(BaseHandler):return reserved_idensure = getattr(self.sessions, "ensure_agent_session_id", None)if callable(ensure):- agent_session_id = ensure(session_key, agent_name, session_anchor)+ ensure_kwargs: dict[str, Any] = {}+ if working_path is not None:+ ensure_kwargs["workdir"] = working_path+ if vibe_agent_id is not None:+ ensure_kwargs["vibe_agent_id"] = vibe_agent_id+ if vibe_agent_name is not None:+ ensure_kwargs["vibe_agent_name"] = vibe_agent_name+ agent_session_id = ensure(+ session_key,+ agent_name,+ session_anchor,+ **ensure_kwargs,+ )else:getter = getattr(self.sessions, "get_agent_session_row_id", None)agent_session_id = getter(session_key, session_anchor, agent_name) if callable(getter) else Nonediff --git a/core/internal_server.py b/core/internal_server.pyindex c3c336f0c..a713fa52b 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -133,11 +133,11 @@ def create_app(controller: "Controller") -> FastAPI:*,delivery_intent: str = "steer",) -> Any:- """Run a scheduled / watch turn through the SAME unified ``manager.submit``- the interactive Chat path uses, so a scheduled run can never preempt an- active Chat turn and gets the full turn lifecycle (in_flight + turn.start /- turn.end + Stop) the Chat page renders (Codex P2). Its submission is a- Delivery until exact native acceptance materializes the harness Message.+ """Run a Harness input through the same durable owner as interactive Chat.++ The explicit source intent decides whether it queues, steers, or replaces.+ The submission remains a Delivery until exact native acceptance materializes+ the harness Message."""if not session_id:submission = await manager.submit(None, context, text, source=SOURCE_SCHEDULED)@@ -160,10 +160,9 @@ def create_app(controller: "Controller") -> FastAPI:run_update_event_transaction,)+ submission_platform = str(getattr(context, "platform", None) or "avibe").strip()native_message_id = str(getattr(context, "message_id", None) or "").strip()- dedupe_key = message_deliveries.native_dedupe_key(- "avibe", native_message_id- )+ dedupe_key: str | None = Nonedelivery_id: str | None = Nonedelivery_request: DeliveryRequest | None = Nonescope_id: str | None = None@@ -179,16 +178,26 @@ def create_app(controller: "Controller") -> FastAPI:from storage.models import agent_runs, agent_sessionsreserve_write_lock(conn)- existing = (- message_deliveries.get_delivery_by_dedupe(conn, dedupe_key)- if dedupe_key- else None+ scope_id = _scope_id_for_session(conn, session_id)+ dedupe_key = message_deliveries.native_dedupe_key(+ submission_platform,+ native_message_id,+ scope_id=scope_id,+ )+ existing = message_deliveries.get_delivery_by_native_identity(+ conn,+ platform=submission_platform,+ native_message_id=native_message_id,+ scope_id=scope_id,+ session_id=session_id,+ normalize_legacy=True,)legacy_accepted = bool(native_message_idand messages_service.native_message_exists(conn,- platform="avibe",+ platform=submission_platform,+ scope_id=scope_id,native_message_id=native_message_id,))@@ -256,8 +265,10 @@ def create_app(controller: "Controller") -> FastAPI:delivery_id = str(existing["id"])delivery_request = manager._request_from_delivery(existing)scope_id = delivery_request.scope_id- effective_delivery_intent = (- "send_now" if delivery_request.priority == "p0" else "steer"+ from core.message_priority import delivery_intent_for_priority++ effective_delivery_intent = delivery_intent_for_priority(+ delivery_request.priority)provenance = (delivery_request.metadata or {}).get(SCHEDULED_PROVENANCE_KEY@@ -272,19 +283,21 @@ def create_app(controller: "Controller") -> FastAPI:persisted_spec.get("task_execution_id") or execution_id).strip()else:- scope_id = _scope_id_for_session(conn, session_id)+ from core.message_priority import priority_for_delivery_intent+delivery_id = message_deliveries.new_delivery_id()admitted_state = "reserved"+ priority = priority_for_delivery_intent(delivery_intent)message_deliveries.insert_delivery(conn,delivery_id=delivery_id,session_id=session_id,- priority="p0" if delivery_intent == "send_now" else "p1",+ priority=priority,state=admitted_state,snapshot=message_deliveries.message_snapshot(scope_id=scope_id,session_id=session_id,- platform="avibe",+ platform=submission_platform,author="harness",source="harness",message_type="harness",@@ -300,7 +313,7 @@ def create_app(controller: "Controller") -> FastAPI:dedupe_key=dedupe_key,history_event={"kind": "admission",- "priority": "p0" if delivery_intent == "send_now" else "p1",+ "priority": priority,"state": admitted_state,},)@@ -332,12 +345,15 @@ def create_app(controller: "Controller") -> FastAPI:delivery_owner_transferred = Trueif delivery_request is None:+ from core.message_priority import priority_for_delivery_intent+delivery_request = DeliveryRequest(session_id=session_id,- priority="p0" if delivery_intent == "send_now" else "p1",+ priority=priority_for_delivery_intent(delivery_intent),content=text,delivery_id=delivery_id,scope_id=scope_id,+ platform=submission_platform,source="harness",author="harness",message_type="harness",@@ -518,12 +534,19 @@ def create_app(controller: "Controller") -> FastAPI:from storage import workbench_sessions_servicepayload = await _safe_json(request)- try:- text, context = await _build_dispatch_payload(payload)- except ValueError as err:- return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})session_id = str(payload.get("session_id") or "").strip()delivery_id = str(payload.get("user_message_id") or "").strip()+ if not delivery_id:+ from core.workbench_media import file_attachments_from_specs++ raw_text = payload.get("text")+ if not (+ isinstance(raw_text, str) and raw_text.strip()+ ) and not file_attachments_from_specs(payload.get("files")):+ return JSONResponse(+ status_code=400,+ content={"ok": False, "error": "text or files is required"},+ )if not session_id or not delivery_id:return JSONResponse(status_code=400,@@ -548,6 +571,23 @@ def create_app(controller: "Controller") -> FastAPI:reason="session_archived",)delivery = message_deliveries.get_delivery(conn, delivery_id)+ delivery_payload = (+ message_deliveries.delivery_payload(delivery)+ if delivery is not None and delivery["session_id"] == session_id+ else None+ )+ attachment_specs: list[dict[str, Any]] = []+ if delivery_payload is not None:+ from core.workbench_media import resolve_attachment_specs++ attachment_specs = resolve_attachment_specs(+ conn,+ session_id=session_id,+ attachments=(delivery_payload.get("content") or {}).get(+ "attachments"+ )+ or [],+ )if archived or delivery is None or delivery["session_id"] != session_id:return JSONResponse(status_code=409,@@ -571,20 +611,49 @@ def create_app(controller: "Controller") -> FastAPI:"queued": delivery["state"] == "queued",},)+ # The HTTP request only wakes the durable owner. Prompt, provenance, and+ # attachments always come from the reservation, never from a stale caller.+ dispatch_payload = {+ **payload,+ "text": str(delivery.get("dispatch_text") or ""),+ "files": attachment_specs,+ "platform": delivery_payload.get("platform"),+ "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"),+ "scope_id": delivery_payload.get("scope_id"),+ "display_text": delivery_payload.get("text"),+ "content": dict(delivery_payload.get("content") or {}),+ "metadata": dict(delivery_payload.get("metadata") or {}),+ "author_id": delivery_payload.get("author_id"),+ "author_name": delivery_payload.get("author_name"),+ }+ try:+ text, context = await _build_dispatch_payload(dispatch_payload)+ except ValueError as err:+ return JSONResponse(status_code=400, content={"ok": False, "error": str(err)})if context.platform_specific is None:context.platform_specific = {}context.platform_specific.update({"delivery_id": delivery_id,- "scope_id": payload.get("scope_id"),- "display_text": payload.get("display_text"),- "message_content": payload.get("content"),- "message_metadata": payload.get("metadata") or {},- "author_id": payload.get("author_id"),- "author_name": payload.get("author_name"),+ "scope_id": dispatch_payload.get("scope_id"),+ "display_text": dispatch_payload.get("display_text"),+ "message_content": dispatch_payload.get("content"),+ "message_metadata": dispatch_payload.get("metadata") or {},+ "author_id": dispatch_payload.get("author_id"),+ "author_name": dispatch_payload.get("author_name"),})- submission = await manager.submit(session_id, context, text)+ from core.message_priority import delivery_intent_for_priority++ delivery_intent = delivery_intent_for_priority(str(delivery["priority"]))+ submission = await manager.submit(+ session_id,+ context,+ text,+ delivery_intent=delivery_intent,+ )with get_cached_sqlite_engine().connect() as conn:settled = message_deliveries.get_delivery(conn, delivery_id)return JSONResponse(@@ -781,8 +850,8 @@ def create_app(controller: "Controller") -> FastAPI:# Expose the per-session turn gate to in-process callers (the scheduler)# WITHOUT going through the HTTP surface: ``ScheduledTaskService`` runs on the- # same loop and routes avibe scheduled / watch turns through- # ``submit_scheduled`` so they share the Chat path's queueing + lifecycle.+ # same loop and routes persisted Session inputs through ``submit_scheduled``+ # so they share the Chat path's durable priority and lifecycle authority.# ``in_flight`` is the SAME dict object as ``app.state.in_flight_dispatches``# (the cancel endpoint, turn-state, and the tests all read it), so a scheduled# run registered by ``_run_turn`` is Stoppable through ``/internal/cancel``.@@ -1006,23 +1075,37 @@ def _build_session_context(message_id: Optional[str] = None,files: Optional[list] = None,) -> MessageContext:- """Build the avibe ``MessageContext`` for a workbench session.+ """Rebuild a Session's routing context from its durable scope and target.Shared by the dispatch endpoint and the cancel endpoint so a stop reusesthe exact same session-routing context (chosen agent / model / effort,native session id, workdir) the turn ran under — that's what lets cancelreuse the IM ``/stop`` path to interrupt the right backend session.- Defaults to ``platform="avibe"``.+ Workbench and IM Sessions use the same builder; Delivery hydration adds the+ exact sender and native Message identity afterward."""- # ``agent_session_id`` is the agent_sessions PK; persist_agent_message reads- # it to attribute avibe agent replies to the right session (IM stamps it at- # session-resolve time). For avibe the dispatch session_id IS that PK.+ from core.scheduled_tasks import resolve_session_id_target++ target_info = resolve_session_id_target(session_id)+ session_row = _lookup_session(session_id)+ resolved_platform = platform or target_info.session_key.platform or "avibe"+ is_dm = target_info.session_key.scope_type == "user"+ resolved_channel_id = channel_id or (+ session_id+ if resolved_platform == "avibe"+ else target_info.session_key.scope_id+ )+ resolved_user_id = user_id or (+ target_info.session_key.scope_id if is_dm else "workbench"+ )platform_specific: dict[str, Any] = {- "workbench_session_id": session_id,"agent_session_id": session_id,+ "platform": resolved_platform,+ "is_dm": is_dm,}- session_row = _lookup_session(session_id)+ if resolved_platform == "avibe":+ platform_specific["workbench_session_id"] = session_idif session_row is not None:target = {"id": session_row.get("id"),@@ -1047,10 +1130,10 @@ def _build_session_context(platform_specific["vibe_agent_name"] = session_row["agent_name"]return MessageContext(- user_id=str(user_id or "workbench"),- channel_id=str(channel_id or session_id),- platform=platform or "avibe",- thread_id=thread_id,+ user_id=str(resolved_user_id),+ channel_id=str(resolved_channel_id),+ platform=resolved_platform,+ thread_id=thread_id or target_info.session_key.thread_id,message_id=message_id,platform_specific=platform_specific,files=files,diff --git a/core/message_mirror.py b/core/message_mirror.pyindex 07b0c2974..91a1faf56 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -48,14 +48,46 @@ def _now() -> str:return datetime.now(timezone.utc).isoformat()-def _resolve_scope_id(conn, context: MessageContext) -> Optional[str]:+def _scope_identity_for_context(context: MessageContext) -> tuple[str, str, str] | None:platform = (context.platform or "").strip()is_dm = bool((context.platform_specific or {}).get("is_dm", False))- use_user_scope = is_dm and context.channel_id and context.user_id and context.channel_id == context.user_id+ use_user_scope = bool(+ is_dm+ and context.channel_id+ and context.user_id+ and context.channel_id == context.user_id+ )scope_type = "user" if use_user_scope else DEFAULT_SCOPE_TYPEnative_id = ((context.user_id if use_user_scope else context.channel_id) or "").strip()if not platform or not native_id:return None+ return platform, scope_type, native_id+++def scope_id_for_context(context: MessageContext) -> Optional[str]:+ """Return the stable native conversation identity without writing storage."""++ identity = _scope_identity_for_context(context)+ if identity is None:+ return None+ return settings_service.make_scope_id(*identity)+++def _agent_message_scope_id(conn, context: MessageContext) -> Optional[str]:+ """Resolve the same scope used when an accepted agent Message is persisted."""++ if context.platform == "avibe":+ session_id = (context.platform_specific or {}).get("agent_session_id")+ session_row = _session_row(conn, session_id) if session_id else None+ return session_row["scope_id"] if session_row else None+ return scope_id_for_context(context)+++def _resolve_scope_id(conn, context: MessageContext) -> Optional[str]:+ identity = _scope_identity_for_context(context)+ if identity is None:+ return None+ platform, scope_type, native_id = identitytry:return settings_service.upsert_scope(conn,@@ -504,6 +536,7 @@ def agent_message_exists(context: MessageContext, native_message_id: str | None)return messages_service.native_message_exists(conn,platform=platform,+ scope_id=_agent_message_scope_id(conn, context),native_message_id=identity,)except Exception:diff --git a/core/message_priority.py b/core/message_priority.pynew file mode 100644index 000000000..bd735a498--- /dev/null+++ b/core/message_priority.py@@ -0,0 +1,53 @@+from __future__ import annotations++from typing import Literal, cast+++DeliveryIntent = Literal["send_now", "steer", "queue"]+DeliveryPriority = Literal["p0", "p1", "p3"]++_PRIORITY_BY_INTENT: dict[DeliveryIntent, DeliveryPriority] = {+ "send_now": "p0",+ "steer": "p1",+ "queue": "p3",+}+_INTENT_BY_PRIORITY: dict[DeliveryPriority, DeliveryIntent] = {+ priority: intent for intent, priority in _PRIORITY_BY_INTENT.items()+}+_INTENT_BY_TRIGGER: dict[str, DeliveryIntent] = {+ "im": "steer",+ "scheduled": "queue",+ "task_run": "queue",+ "watch": "steer",+ "hook": "steer",+ "webhook": "steer",+ "agent_run": "steer",+ "show_annotation": "steer",+ "callback": "steer",+}+++def priority_for_delivery_intent(intent: str) -> DeliveryPriority:+ normalized = cast(DeliveryIntent, str(intent or "").strip())+ try:+ return _PRIORITY_BY_INTENT[normalized]+ except KeyError as exc:+ raise ValueError(f"unsupported delivery intent: {intent}") from exc+++def delivery_intent_for_priority(priority: str) -> DeliveryIntent:+ normalized = cast(DeliveryPriority, str(priority or "").strip())+ try:+ return _INTENT_BY_PRIORITY[normalized]+ except KeyError as exc:+ raise ValueError(f"unsupported delivery priority: {priority}") from exc+++def delivery_intent_for_trigger(trigger_kind: str) -> DeliveryIntent:+ """Map a producer class to its one public delivery policy."""++ normalized = str(trigger_kind or "").strip()+ try:+ return _INTENT_BY_TRIGGER[normalized]+ except KeyError as exc:+ raise ValueError(f"unsupported delivery trigger: {trigger_kind}") from excdiff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 434d381f7..e4161538c 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -92,8 +92,13 @@ logger = logging.getLogger(__name__)AGENT_RUN_DELIVERY_STEER = "steer"AGENT_RUN_DELIVERY_SEND_NOW = "send_now"+AGENT_RUN_DELIVERY_QUEUE = "queue"AGENT_RUN_DELIVERY_INTENTS = frozenset(- {AGENT_RUN_DELIVERY_STEER, AGENT_RUN_DELIVERY_SEND_NOW}+ {+ AGENT_RUN_DELIVERY_STEER,+ AGENT_RUN_DELIVERY_SEND_NOW,+ AGENT_RUN_DELIVERY_QUEUE,+ })AGENT_RUN_DELIVERY_INTENT_METADATA_KEY = "delivery_intent"AGENT_RUN_DELIVERY_OUTCOME_METADATA_KEY = "delivery_outcome"@@ -138,8 +143,6 @@ def normalize_agent_run_delivery_intent(value: Any) -> str:"""Return the durable Agent Run delivery intent or reject an unknown value."""normalized = str(value or AGENT_RUN_DELIVERY_STEER).strip().lower()- if normalized == "queue":- normalized = AGENT_RUN_DELIVERY_STEERif normalized not in AGENT_RUN_DELIVERY_INTENTS:raise ValueError(f"unsupported Agent Run delivery intent: {normalized}")return normalized@@ -754,6 +757,8 @@ def enqueue_session_callback(if existing is not None:return TaskExecutionRequest.from_dict(existing)target = resolve_session_id_target(session_id)+ from core.message_priority import delivery_intent_for_trigger+return request_store.enqueue_agent_run(session_id=session_id,session_key=target.session_key.to_key(),@@ -767,6 +772,7 @@ def enqueue_session_callback(source_kind="callback",source_actor=source_actor,parent_run_id=parent_run_id,+ delivery_intent=delivery_intent_for_trigger("callback"),metadata={"callback_parent_run_id": parent_run_id} if parent_run_id else {},)@@ -5327,8 +5333,8 @@ class ScheduledTaskService:complete_on_return=True,delivery_outcome=delivery_outcome,)- if target.platform == "avibe" and session_id and gate is not None:- if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW:+ if session_id and gate is not None:+ if delivery_intent != AGENT_RUN_DELIVERY_STEER:state = await gate.submit_scheduled(session_id,context,@@ -6574,21 +6580,23 @@ class ScheduledTaskService:# ``context`` carries the avibe ``agent_session_id`` (set in# ``_build_context``). No dot bookkeeping here.#- # Route avibe runs through the per-session turn gate the Chat HTTP path- # uses, so a scheduled / watch / webhook / agent_run turn targeting an- # avibe session QUEUES behind an active Chat turn (never preempts it) and- # gets the in_flight + turn.start / turn.end lifecycle that makes the Chat- # page show the working indicator + Stop (Codex P2). The gate runs on the- # controller's loop and is published by ``internal_server.create_app``.+ # Route every persisted Session target through the durable owner. The+ # source policy decides whether this input queues or steers; the platform+ # only controls native routing and outward delivery.# Returning ``None`` keeps ``ok = not error`` true (the run's own outcome# surfaces via the outbound terminal result + sidebar dot, exactly as the- # interactive Chat turn does). IM targets NEVER touch the gate — they keep- # the direct ``handle_scheduled_message`` path byte-for-byte.+ # interactive Chat turn does).gate = getattr(self.controller, "session_turn_gate", None)- if target.platform == "avibe" and session_id and gate is not None:+ if session_id and gate is not None:+ from core.message_priority import delivery_intent_for_triggerfrom core.session_turns import TurnSubmissionResult- submission = await gate.submit_scheduled(session_id, context, prompt)+ submission = await gate.submit_scheduled(+ session_id,+ context,+ prompt,+ delivery_intent=delivery_intent_for_trigger(trigger_kind),+ )if isinstance(submission, TurnSubmissionResult):result = TaskDispatchResult(error=None,diff --git a/core/session_turns.py b/core/session_turns.pyindex b20541089..19fe8c04e 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -403,6 +403,7 @@ class DeliveryRequest:display_text: str | None = Nonecontent_json: dict[str, Any] | None = Nonemetadata: dict[str, Any] | None = None+ admission_context: dict[str, Any] | None = Nonenative_message_id: str | None = Noneparent_native_message_id: str | None = None@@ -1130,8 +1131,15 @@ class SessionTurnManager:"""Restore dispatch inputs only from the durable Delivery snapshot."""payload = delivery_store.delivery_payload(delivery)- context.message_id = str(delivery["id"])context.platform = str(payload.get("platform") or context.platform or "avibe")+ native_message_id = str(payload.get("native_message_id") or "").strip()+ context.message_id = (+ native_message_id+ if context.platform != "avibe" and native_message_id+ else str(delivery["id"])+ )+ if payload.get("author_id"):+ context.user_id = str(payload["author_id"])if context.platform_specific is None:context.platform_specific = {}context.platform_specific.update(@@ -1144,6 +1152,9 @@ class SessionTurnManager:"author_id": payload.get("author_id"),"author_name": payload.get("author_name"),"native_message_id": payload.get("native_message_id"),+ "delivery_admission_context": (+ delivery_store.delivery_admission_context(delivery)+ ),})from core.workbench_media import (@@ -1251,7 +1262,21 @@ class SessionTurnManager:dedupe_key = delivery_store.native_dedupe_key(request.platform,request.native_message_id,+ scope_id=request.scope_id,)+ if dedupe_key:+ existing = delivery_store.get_delivery_by_native_identity(+ conn,+ platform=request.platform,+ native_message_id=str(request.native_message_id or ""),+ scope_id=request.scope_id,+ session_id=request.session_id,+ normalize_legacy=True,+ )+ if existing is not None:+ if existing["session_id"] != request.session_id:+ raise ValueError("Delivery dedupe identity belongs to another Session")+ return existingreturn delivery_store.insert_delivery(conn,delivery_id=delivery_id,@@ -1261,7 +1286,34 @@ class SessionTurnManager:snapshot=SessionTurnManager._delivery_snapshot(request),dispatch_text=str(request.content or ""),dedupe_key=dedupe_key,- history_event={"kind": "admission", "priority": priority, "state": state},+ history_event={+ "kind": "admission",+ "priority": priority,+ "state": state,+ **(+ {"context": dict(request.admission_context)}+ if request.admission_context+ else {}+ ),+ },+ )++ @staticmethod+ def reserve_delivery(+ conn: Connection,+ request: DeliveryRequest,+ ) -> dict[str, Any]:+ """Persist a producer-owned content reservation in the caller's transaction."""++ if request.content is None:+ raise ValueError("content Delivery requires a Message snapshot")+ if request.priority not in {"p1", "p3"}:+ raise ValueError("content reservation requires P1 or P3 priority")+ return SessionTurnManager._insert_delivery(+ conn,+ request,+ priority=request.priority,+ state="reserved",)def _active_identity(@@ -2713,7 +2765,14 @@ class SessionTurnManager:})else:- resolved.message_id = str(delivery["id"])+ native_message_id = str(+ delivery_payload.get("native_message_id") or ""+ ).strip()+ resolved.message_id = (+ native_message_id+ if resolved.platform != "avibe" and native_message_id+ else str(delivery["id"])+ )text = str(turn.get("dispatch_text") or "")except Exception:logger.exception(@@ -4066,11 +4125,12 @@ class SessionTurnManager:text: str,*,source: str = SOURCE_HUMAN,- delivery_intent: Literal["queue", "send_now"] = "queue",+ delivery_intent: Literal["queue", "send_now", "steer"] = "queue",) -> TurnSubmissionResult:"""Admit one caller through the durable Delivery owner."""- if delivery_intent not in {"queue", "send_now"}:- raise ValueError(f"unsupported delivery intent: {delivery_intent}")+ from core.message_priority import priority_for_delivery_intent++ priority = priority_for_delivery_intent(delivery_intent)if not (isinstance(session_id, str) and session_id):# No session key (CLI-style) — just run; nothing to queue against.await self._run(None, context, text, source=source)@@ -4093,7 +4153,7 @@ class SessionTurnManager:delivery_id = candidaterequest = DeliveryRequest(session_id=session_id,- priority="p0" if delivery_intent == "send_now" else "p3",+ priority=priority,content=text,has_content=delivery_store.has_substantive_input(text,@@ -4101,7 +4161,7 @@ class SessionTurnManager:),delivery_id=delivery_id,scope_id=str(spec.get("scope_id") or "").strip() or None,- platform="avibe",+ platform=str(getattr(context, "platform", None) or "avibe"),source=source_value,author="harness" if source == SOURCE_SCHEDULED else "user",message_type="harness" if source == SOURCE_SCHEDULED else "user",diff --git a/core/show_session_events.py b/core/show_session_events.pyindex 2535d8079..75de41181 100644--- a/core/show_session_events.py+++ b/core/show_session_events.py@@ -292,12 +292,20 @@ class ShowSessionEventStore:content["attachments"] = attachmentsmetadata.update(_annotation_metadata(event_payload, anchor))if requests_dispatch:+ from core.message_priority import (+ delivery_intent_for_trigger,+ priority_for_delivery_intent,+ )++ priority = priority_for_delivery_intent(+ delivery_intent_for_trigger("show_annotation")+ )delivery_id = message_deliveries.new_delivery_id()delivery_row = message_deliveries.insert_delivery(conn,delivery_id=delivery_id,session_id=session_id,- priority="p3",+ priority=priority,state="reserved",snapshot=message_deliveries.message_snapshot(scope_id=session["scope_id"],@@ -321,7 +329,7 @@ class ShowSessionEventStore:dedupe_key=f"show:{event_id}",history_event={"kind": "admission",- "priority": "p3",+ "priority": priority,"state": "reserved",},)diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex bfdff0187..571db7105 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -297,7 +297,7 @@ Use `vibe agent run --fork-self --message ...` when work should branch from thisWhen `vibe agent run --session-id <id>` targets an existing Session, it sends a new message into that Session. It does not change that Session's cwd, scope, Agent, model, or reasoning settings; those properties belong to the Session itself. Use a new Session or a fork when those properties need to differ.-That existing-Session send is a P1 delivery by default: it steers into an active native Turn, starts immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. When coordinating another Workbench Session, decide whether its current work should finish, accept a steer, or be replaced based on the dependency, urgency, and cost of discarding in-flight work; an explicit user request is one signal, not a prerequisite. Use `vibe agent run --session-id <id> --send-now --message ...` when the new instruction itself must preempt: `--send-now --message` is a content-P0 admission. With an active turn it claims the shared interrupt control and persists its successor before Stop; when idle it starts that new instruction immediately even if older backlog is held, without releasing or promoting that backlog. Use `vibe session send-now <id>` for an empty-P1 promotion: it adds no Message; it releases the hold and promotes the exact oldest queued P3 head. If a Turn is active, empty P1 steers that exact head into the active logical/native Turn; if the Session is idle, it starts that head as a new Turn. Both forms require a Web/Workbench Session. Only content P0 interrupts through the shared Stop path; if that interruption is refused, the active Turn and durable queue remain intact.+That existing-Session send is a P1 delivery by default: it steers into an active native Turn, starts immediately when idle, and falls back to the durable P3 queue if steering is definitively refused or no longer active. Use `--queue` when the new Run should enter that P3 queue without steering. When coordinating another Workbench Session, decide whether its current work should finish, accept a steer, or be replaced based on the dependency, urgency, and cost of discarding in-flight work; an explicit user request is one signal, not a prerequisite. Use `vibe agent run --session-id <id> --send-now --message ...` when the new instruction itself must preempt: `--send-now --message` is a content-P0 admission. With an active turn it claims the shared interrupt control and persists its successor before Stop; when idle it starts that new instruction immediately even if older backlog is held, without releasing or promoting that backlog. Use `vibe session send-now <id>` for an empty-P1 promotion: it adds no Message; it releases the hold and promotes the exact oldest queued P3 head. If a Turn is active, empty P1 steers that exact head into the active logical/native Turn; if the Session is idle, it starts that head as a new Turn. Both forms require a Web/Workbench Session. Only content P0 interrupts through the shared Stop path; if that interruption is refused, the active Turn and durable queue remain intact.Coordinating Agents can inspect the same durable Workbench queue the user sees with `vibe session queue list <id>`. If one queued instruction has become obsolete, contradictory, or duplicated, remove that exact row with `vibe session queue remove <id> <message-id>`. Always list first and use the returned stable message id; never guess an id or delete a different row to simulate reordering.diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 70cb0a064..9a4ed141d 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -726,7 +726,6 @@ Important options:- `--name`- `--session-id`-- `--send-now`- `--create-session`- `--create-session-per-run`- `--agent`@@ -875,10 +874,11 @@ result later. Use `--sync` only when the terminal should wait for completion.With an existing `--session-id`, the default is P1: steer the new Run into anactive native Turn, start it when idle, or move the same Delivery to P3 after a-definitive refusal/not-active receipt. `--send-now` instead admits the new Run as-content P0 and persists its replacement successor before stopping an active-Turn. `vibe session send-now` adds no message; it promotes only the exact current-P3 queue head, steering it when active or starting it when idle.+definitive refusal/not-active receipt. `--queue` selects P3 without attempting a+steer. `--send-now` instead admits the new Run as content P0 and persists its+replacement successor before stopping an active Turn. `vibe session send-now`+adds no message; it promotes only the exact current P3 queue head, steering it+when active or starting it when idle.`--fork-session <session_id>` creates a new Agent Session by forking the sourceSession's native backend context. It is for alternate investigations ordiff --git a/docs/plans/agent-message-priority.md b/docs/plans/agent-message-priority.mdindex cb4ce5eaa..7337b564a 100644--- a/docs/plans/agent-message-priority.md+++ b/docs/plans/agent-message-priority.md@@ -2,19 +2,19 @@## Status-Owner-approved program contract. This file freezes the P0, P1, and P3 delivery-semantics and the backend-native steering boundary used by the implementation-slices below. P2 and P4 remain reserved for a separate Mailbox design.+Implemented program contract. P0, P1, and P3 share one durable Delivery owner+across interactive input, Harness input, queue promotion, and restart recovery.+P2 and P4 remain reserved for a separate Mailbox design.## Priority Semantics- **P0 interrupt** is an explicit action, never a default for ordinary input.- Without content it stops the active Turn. With content, the future delivery- owner must first persist one successor Message, then stop the active Turn and- start the successor as a new Turn.+ Without content it stops the active Turn. With content, the delivery owner+ first persists the replacement Delivery and waiting successor Turn, then+ stops the active Turn and starts the successor.- **P1 steer** delivers content into the expected currently active Turn without- stopping it. A future content-free P1 request atomically promotes the current- P3 queue head. A definitive steering failure may transfer the same Message to+ stopping it. A content-free P1 request atomically promotes the current+ P3 queue head. A definitive steering failure may transfer the same Delivery toP3; an acknowledgement-ambiguous result must be reconciled durably first.- **P3 queue** starts immediately when the Session is idle and otherwise remainsFIFO until the active Turn ends. Queueing is not a hold mechanism.@@ -87,31 +87,38 @@ These acknowledgement strengths are intentionally different because the nativeprotocols expose different boundaries. The common result preserves that truthinstead of claiming equivalent durability.-## Delivery Slices--1. **Native adapters (this PR):** add the shared contract and Codex, Claude, and- OpenCode insertion adapters. Keep every public source and Send Now behavior- unchanged.-2. **P0/P1/P3 admission owner:** make the Session delivery owner perform the- durable claim, native steer, refusal-to-P3 transfer, unknown reconciliation,- content-free P1 promotion, and P0 successor-before-interrupt transition.-3. **Result and callback ownership:** keep one terminal Result authority while- allowing accepted cross-Agent participants to subscribe once per callback- Session. A P1-to-P3 transfer joins only the future Turn.-4. **Atomic source cutover:** switch Web Send Now, IM, Agent CLI, Watch, Show- Annotation, and Session Callback to their approved defaults in one release;- keep Task at P3 and remove the old Send Now interrupt-and-flush path then.--Until slice 4 lands, Web Send Now, IM handling, CLI defaults, Watch/Task/Show and-Callback routing, `SessionTurnManager.send_now`, queue behavior, and every source-default retain their pre-program behavior. Existing HFR-430 coverage remains the-contract test for Send Now interrupt-and-flush in this slice; no new scenario id-is allocated for this invisible backend capability.+## Source Policy++| Source | Default | Behavior |+| --- | --- | --- |+| Web composer | P3 | Starts when idle; otherwise joins the FIFO backlog. |+| Ordinary IM message | P1 | Steers the active Turn or starts when idle; a definitive refusal falls back to P3. |+| Existing-Session Agent Run | P1 | Same as ordinary IM. `--queue` selects P3 and `--send-now` selects content P0 for Workbench Sessions. |+| Watch, Hook, Webhook | P1 | Continues the target Session without interrupting it. |+| Show annotation | P1 | Delivers the annotation to the current Turn when possible. |+| Session callback | P1 | Delivers each completed child Run independently. |+| Scheduled Task | P3 | Never interrupts or steers the work a user is already doing. |+| Stop | Empty P0 | Stops the exact live Turn and establishes the durable queue hold. |+| Send Now existing head | Empty P1 | Releases the hold and promotes only the exact observed FIFO head. |++Attachments remain part of the same Delivery. Because native steer adapters+accept text only, an attachment-bearing P1 is preserved as P3 and starts a new+Turn after the current one finishes.++## Ownership Closure++- `message_deliveries` owns every unaccepted input, queue position, attempt, and+ receipt. No unaccepted input is a transcript Message.+- `session_turns` owns execution and its immutable terminal snapshot.+- `messages` contains accepted communication records only.+- Accepted Agent Runs attached to one Turn are independent terminal subscribers.+ The existing Run rows and their Delivery-to-Turn links are sufficient; no+ callback table or second terminal writer is introduced.+- One terminal snapshot settles every accepted Run once, after which each Run's+ existing callback state produces at most one P1 callback Delivery.## Deferred Work- P2/P4 Mailbox cursor, unread, acknowledgement, merge, and retrieval semantics- generic exact-id promotion or demotion-- source-policy catalog and public surface changes-- callback subscriber persistence and fan-out- authentication, authorization, ACL, and unrelated issue dependenciesdiff --git a/docs/plans/agent-run-callback-session.md b/docs/plans/agent-run-callback-session.mdindex fd93d76d2..eb05cb338 100644--- a/docs/plans/agent-run-callback-session.md+++ b/docs/plans/agent-run-callback-session.md@@ -53,9 +53,9 @@ Rules:run also posts to its IM scope, the callback still happens.- Callback sends all terminal outcomes for v1: success, failure, cancellation,and terminal errors. Do not add filtering flags yet.-- The callback message should enter the Caller Session through the same- scheduled/watch-style turn path, so it queues behind any active turn instead- of interrupting it.+- The callback message enters the Caller Session as P1: it steers the active+ Turn when possible, starts when idle, and falls back to P3 after a definitive+ steer refusal. It never interrupts the active Turn.- The callback message should trigger the Caller Session Agent as a normalfollow-up message. It is not just passive transcript decoration.diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex dd0ded8a1..552f92b2c 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -395,6 +395,13 @@ class SessionsFacade:def is_message_already_processed(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:return self.sessions_store.is_message_in_processed_set(channel_id, thread_ts, message_ts)+ def has_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:+ return self.sessions_store.has_processed_message(+ channel_id,+ thread_ts,+ message_ts,+ )+def record_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> None:self.sessions_store.add_to_processed_set(channel_id, thread_ts, message_ts)logger.debug("Recorded processed message: channel=%s, thread=%s, message=%s", channel_id, thread_ts, message_ts)diff --git a/storage/alembic/versions/20260802_0045_scope_native_message_identity.py b/storage/alembic/versions/20260802_0045_scope_native_message_identity.pynew file mode 100644index 000000000..953bcdc9c--- /dev/null+++ b/storage/alembic/versions/20260802_0045_scope_native_message_identity.py@@ -0,0 +1,294 @@+"""scope native message identity to its conversation++Revision ID: 20260802_0045+Revises: 20260801_0044+Create Date: 2026-08-02+"""++from __future__ import annotations++import json++import sqlalchemy as sa+from alembic import op++revision = "20260802_0045"+down_revision = "20260801_0044"+branch_labels = None+depends_on = None++_SCOPED_INDEX = "uq_messages_platform_scope_native"+_UNSCOPED_INDEX = "uq_messages_platform_native_unscoped"+_OLD_CONSTRAINT = "uq_messages_platform_native"+++def _scoped_delivery_key(platform: str, scope_id: str, native_id: str) -> str:+ return f"{platform}:scope:{len(scope_id)}:{scope_id}:{native_id}"+++def _delivery_identities(bind) -> list[dict[str, object]]:+ rows = bind.execute(+ sa.text(+ """+ select d.id, d.dedupe_key, d.snapshot_json, d.message_id,+ m.platform as message_platform,+ m.scope_id as message_scope_id,+ m.native_message_id as message_native_message_id+ from message_deliveries d+ left join messages m on m.id = d.message_id+ where d.dedupe_key is not null+ """+ )+ ).mappings()+ identities: list[dict[str, object]] = []+ for row in rows:+ snapshot: dict[str, object] = {}+ try:+ parsed = json.loads(str(row["snapshot_json"] or "{}"))+ if isinstance(parsed, dict):+ snapshot = parsed+ except (TypeError, ValueError, json.JSONDecodeError):+ snapshot = {}+ platform = str(snapshot.get("platform") or row["message_platform"] or "")+ scope_id = str(snapshot.get("scope_id") or row["message_scope_id"] or "")+ recorded_native_id = str(+ snapshot.get("native_message_id")+ or row["message_native_message_id"]+ or ""+ )+ current_key = str(row["dedupe_key"])+ scoped_prefix = (+ f"{platform}:scope:{len(scope_id)}:{scope_id}:"+ if platform and scope_id+ else ""+ )+ if scoped_prefix and current_key.startswith(scoped_prefix):+ native_id = current_key.removeprefix(scoped_prefix)+ elif platform and current_key.startswith(f"{platform}:"):+ native_id = current_key.removeprefix(f"{platform}:")+ else:+ native_id = recorded_native_id+ identities.append(+ {+ "id": str(row["id"]),+ "dedupe_key": current_key,+ "platform": platform,+ "scope_id": scope_id,+ "native_id": native_id,+ }+ )+ return identities+++def _rewrite_delivery_keys(bind, *, scoped: bool) -> None:+ updates: list[dict[str, str]] = []+ seen: dict[str, str] = {}+ for identity in _delivery_identities(bind):+ delivery_id = str(identity["id"])+ current = str(identity["dedupe_key"])+ platform = str(identity["platform"])+ scope_id = str(identity["scope_id"])+ native_id = str(identity["native_id"])+ old_key = f"{platform}:{native_id}" if platform and native_id else current+ scoped_key = (+ _scoped_delivery_key(platform, scope_id, native_id)+ if platform and scope_id and native_id+ else old_key+ )+ if scoped:+ target = scoped_key if current == old_key else current+ else:+ target = old_key if current == scoped_key else current+ previous = seen.get(target)+ if previous is not None and previous != delivery_id:+ raise RuntimeError(+ "cannot downgrade 0045: conversation-scoped Delivery identities "+ "would collide"+ )+ seen[target] = delivery_id+ if target != current:+ updates.append({"id": delivery_id, "dedupe_key": target})+ if updates:+ bind.execute(+ sa.text(+ "update message_deliveries set dedupe_key=:dedupe_key where id=:id"+ ),+ updates,+ )+++def _index_names(bind) -> set[str]:+ return {+ str(name)+ for name in bind.execute(+ sa.text(+ "select name from sqlite_master "+ "where type='index' and tbl_name='messages'"+ )+ ).scalars()+ }+++def _has_old_constraint(bind) -> bool:+ return any(+ constraint.get("name") == _OLD_CONSTRAINT+ for constraint in sa.inspect(bind).get_unique_constraints("messages")+ )+++def _snapshot_message_references(bind) -> None:+ bind.execute(+ sa.text(+ "create temporary table _0045_show_message_refs as "+ "select id, message_id from show_session_events where message_id is not null"+ )+ )+ bind.execute(+ sa.text(+ "create temporary table _0045_media_message_refs as "+ "select token, message_id from media_objects where message_id is not null"+ )+ )+ bind.execute(+ sa.text(+ "create temporary table _0045_delivery_message_refs as "+ "select id, message_id from message_deliveries where message_id is not null"+ )+ )+ bind.execute(sa.text("pragma ignore_check_constraints=on"))+ bind.execute(+ sa.text(+ "update message_deliveries set message_id=null where message_id is not null"+ )+ )+++def _snapshot_message_indexes(bind) -> None:+ bind.execute(+ sa.text(+ "create temporary table _0045_message_indexes as "+ "select name, sql from sqlite_master "+ "where type='index' and tbl_name='messages' and sql is not null"+ )+ )+++def _restore_message_indexes(bind) -> None:+ indexes = list(+ bind.execute(+ sa.text("select name, sql from _0045_message_indexes order by name")+ ).mappings()+ )+ for index in indexes:+ bind.execute(sa.text(f'drop index if exists "{index["name"]}"'))+ bind.execute(sa.text(str(index["sql"])))+ bind.execute(sa.text("drop table _0045_message_indexes"))+++def _restore_message_references(bind) -> None:+ bind.execute(+ sa.text(+ "update show_session_events set message_id = ("+ "select message_id from _0045_show_message_refs refs "+ "where refs.id = show_session_events.id) "+ "where id in (select id from _0045_show_message_refs)"+ )+ )+ bind.execute(+ sa.text(+ "update media_objects set message_id = ("+ "select message_id from _0045_media_message_refs refs "+ "where refs.token = media_objects.token) "+ "where token in (select token from _0045_media_message_refs)"+ )+ )+ bind.execute(+ sa.text(+ "update message_deliveries set message_id = ("+ "select message_id from _0045_delivery_message_refs refs "+ "where refs.id = message_deliveries.id) "+ "where id in (select id from _0045_delivery_message_refs)"+ )+ )+ bind.execute(sa.text("pragma ignore_check_constraints=off"))+ bind.execute(sa.text("drop table _0045_show_message_refs"))+ bind.execute(sa.text("drop table _0045_media_message_refs"))+ bind.execute(sa.text("drop table _0045_delivery_message_refs"))+++def upgrade() -> None:+ bind = op.get_bind()+ if _has_old_constraint(bind):+ _snapshot_message_references(bind)+ _snapshot_message_indexes(bind)+ try:+ with op.batch_alter_table("messages") as batch_op:+ batch_op.drop_constraint(_OLD_CONSTRAINT, type_="unique")+ _restore_message_indexes(bind)+ _restore_message_references(bind)+ except Exception:+ bind.execute(sa.text("pragma ignore_check_constraints=off"))+ raise+ indexes = _index_names(bind)+ if _SCOPED_INDEX not in indexes:+ op.create_index(+ _SCOPED_INDEX,+ "messages",+ ["platform", "scope_id", "native_message_id"],+ unique=True,+ sqlite_where=sa.text(+ "scope_id is not null and native_message_id is not null"+ ),+ )+ if _UNSCOPED_INDEX not in indexes:+ op.create_index(+ _UNSCOPED_INDEX,+ "messages",+ ["platform", "native_message_id"],+ unique=True,+ sqlite_where=sa.text(+ "scope_id is null and native_message_id is not null"+ ),+ )+ if sa.inspect(bind).has_table("message_deliveries"):+ _rewrite_delivery_keys(bind, scoped=True)+++def downgrade() -> None:+ bind = op.get_bind()+ collision = bind.execute(+ sa.text(+ """+ select platform, native_message_id+ from messages+ where native_message_id is not null+ group by platform, native_message_id+ having count(*) > 1+ limit 1+ """+ )+ ).first()+ if collision is not None:+ raise RuntimeError(+ "cannot downgrade 0045: conversation-scoped Message identities would collide"+ )+ if sa.inspect(bind).has_table("message_deliveries"):+ _rewrite_delivery_keys(bind, scoped=False)+ indexes = _index_names(bind)+ if _UNSCOPED_INDEX in indexes:+ op.drop_index(_UNSCOPED_INDEX, table_name="messages")+ if _SCOPED_INDEX in indexes:+ op.drop_index(_SCOPED_INDEX, table_name="messages")+ _snapshot_message_references(bind)+ _snapshot_message_indexes(bind)+ try:+ with op.batch_alter_table("messages") as batch_op:+ batch_op.create_unique_constraint(+ _OLD_CONSTRAINT,+ ["platform", "native_message_id"],+ )+ _restore_message_indexes(bind)+ _restore_message_references(bind)+ except Exception:+ bind.execute(sa.text("pragma ignore_check_constraints=off"))+ raisediff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 2def4e653..c47722e79 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -61,11 +61,21 @@ def _sha256_text(value: str) -> str:return hashlib.sha256(value.encode("utf-8")).hexdigest()-def native_dedupe_key(platform: str, native_message_id: str | None) -> str | None:+def native_dedupe_key(+ platform: str,+ native_message_id: str | None,+ *,+ scope_id: str | None = None,+) -> str | None:"""Return the canonical live dedupe identity for a native submission."""native_id = str(native_message_id or "").strip()- return f"{platform}:{native_id}" if native_id else None+ if not native_id:+ return None+ native_scope = str(scope_id or "").strip()+ if not native_scope:+ return f"{platform}:{native_id}"+ return f"{platform}:scope:{len(native_scope)}:{native_scope}:{native_id}"def _json_object(value: Any) -> dict[str, Any]:@@ -159,6 +169,77 @@ def get_delivery_by_dedupe(conn: Connection, dedupe_key: str) -> dict[str, Any])+def get_delivery_by_native_identity(+ conn: Connection,+ *,+ platform: str,+ native_message_id: str,+ scope_id: str | None,+ session_id: str | None = None,+ normalize_legacy: bool = False,+) -> dict[str, Any] | None:+ """Resolve one native event, including the pre-0045 unscoped key."""++ canonical_key = native_dedupe_key(+ platform,+ native_message_id,+ scope_id=scope_id,+ )+ if canonical_key is None:+ return None+ delivery = get_delivery_by_dedupe(conn, canonical_key)+ if delivery is not None or scope_id is None:+ return delivery++ legacy_key = native_dedupe_key(platform, native_message_id)+ if legacy_key is None or legacy_key == canonical_key:+ return None+ delivery = get_delivery_by_dedupe(conn, legacy_key)+ if delivery is None:+ return None+ if session_id is not None and delivery["session_id"] != session_id:+ return None++ delivery_scope = _json_object(delivery.get("snapshot_json")).get("scope_id")+ if delivery_scope is None and delivery.get("message_id"):+ delivery_scope = conn.execute(+ select(messages.c.scope_id)+ .where(messages.c.id == delivery["message_id"])+ .limit(1)+ ).scalar_one_or_none()+ if delivery_scope != scope_id:+ return None+ if not normalize_legacy:+ return delivery++ result = conn.execute(+ update(message_deliveries)+ .where(message_deliveries.c.id == delivery["id"])+ .where(message_deliveries.c.dedupe_key == legacy_key)+ .values(dedupe_key=canonical_key)+ )+ if result.rowcount != 1:+ return get_delivery_by_dedupe(conn, canonical_key)+ delivery["dedupe_key"] = canonical_key+ return delivery+++def delivery_admission_context(delivery: dict[str, Any]) -> dict[str, Any]:+ """Return immutable operational context captured by the admission event."""++ try:+ history = json.loads(str(delivery.get("delivery_history_json") or "{}"))+ except (TypeError, ValueError, json.JSONDecodeError):+ return {}+ events = history.get("events") if isinstance(history, dict) else None+ for event in events or []:+ if not isinstance(event, dict) or event.get("kind") != "admission":+ continue+ context = event.get("context")+ return dict(context) if isinstance(context, dict) else {}+ return {}++def active_turn(conn: Connection, session_id: str) -> dict[str, Any] | None:return _one(conn,@@ -487,7 +568,11 @@ def enqueue_queued(native_message_id=native_message_id,),dispatch_text=text if dispatch_text is None else dispatch_text,- dedupe_key=native_dedupe_key(platform, native_message_id),+ dedupe_key=native_dedupe_key(+ platform,+ native_message_id,+ scope_id=scope_id,+ ),history_event={"kind": "submitted", "priority": "p3"},now=now,)diff --git a/storage/messages_service.py b/storage/messages_service.pyindex ef530885a..5f5a14e02 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -480,15 +480,27 @@ def get_message(return _row_to_payload(dict(row)) if row else None-def native_message_exists(conn: Connection, *, platform: str, native_message_id: str) -> bool:- """True when a platform/native message id has already been recorded."""+def native_message_exists(+ conn: Connection,+ *,+ platform: str,+ scope_id: str | None,+ native_message_id: str,+) -> bool:+ """True when a conversation-scoped native message has been recorded."""platform = str(platform or "").strip()native_message_id = str(native_message_id or "").strip()if not platform or not native_message_id:return False+ scope_predicate = (+ messages.c.scope_id == scope_id+ if scope_id is not None+ else messages.c.scope_id.is_(None)+ )row_id = conn.execute(select(messages.c.id).where(messages.c.platform == platform)+ .where(scope_predicate).where(messages.c.native_message_id == native_message_id).limit(1)).scalar_one_or_none()diff --git a/storage/models.py b/storage/models.pyindex 870bb4312..d111c3858 100644--- a/storage/models.py+++ b/storage/models.py@@ -373,9 +373,9 @@ agent_events = Table(# Platform-agnostic chat message store. Every IM adapter (Slack, Discord,# Telegram, Lark, WeChat, Avibe/Web UI) writes user+agent turns here so the# workbench Inbox and per-session history can read from a single ORM-# surface instead of round-tripping the platform's own API. ``platform`` +-# ``native_message_id`` is unique when present so a duplicate webhook-# delivery is a no-op upsert. ``read_at`` drives unread counts for the+# surface instead of round-tripping the platform's own API. Native message+# identity is scoped to its conversation because some platforms reuse message+# ids across chats. ``read_at`` drives unread counts for the# Inbox; legacy IM platforms ignore it.messages = Table("messages",@@ -416,7 +416,21 @@ messages = Table(Column("updated_at", String, nullable=False),Column("delivered_at", String, nullable=True),Column("read_at", String, nullable=True),- UniqueConstraint("platform", "native_message_id", name="uq_messages_platform_native"),+ Index(+ "uq_messages_platform_scope_native",+ "platform",+ "scope_id",+ "native_message_id",+ unique=True,+ sqlite_where=text("scope_id is not null and native_message_id is not null"),+ ),+ Index(+ "uq_messages_platform_native_unscoped",+ "platform",+ "native_message_id",+ unique=True,+ sqlite_where=text("scope_id is null and native_message_id is not null"),+ ),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"),diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 35e6cffa6..885ded4f5 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -1211,6 +1211,26 @@ class SQLiteSessionsService:last_activity=self._load_last_activity(conn),)+ def processed_message_exists(+ self,+ channel_id: str,+ thread_ts: str,+ message_ts: str,+ ) -> bool:+ record_key = _processed_message_record_key(+ str(channel_id),+ str(thread_ts),+ str(message_ts),+ )+ with self.engine.connect() as conn:+ row_id = conn.execute(+ select(runtime_records.c.id)+ .where(runtime_records.c.record_type == "processed_message")+ .where(runtime_records.c.record_key == record_key)+ .limit(1)+ ).scalar_one_or_none()+ return row_id is not None+def try_record_processed_message(self, channel_id: str, thread_ts: str, message_ts: str) -> bool:"""Atomically claim a message for processing.diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 4ae9a1d8f..724ae0759 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -58,10 +58,10 @@ scenarios:test: tests/test_scheduled_tasks.py::test_base_agent_terminal_markdown_example_persists_complete_run_and_callback- id: MESSAGE-DELIVERY-008name: Run callbacks use only terminal output while directed child Runs remain independent- status: partial+ status: coveredkind: concurrencylayer: contract- test: tests/test_scheduled_tasks.py::test_directed_run_and_callback_remain_distinct_while_target_busy+ test: tests/test_scheduled_tasks.py::test_one_terminal_turn_fans_out_each_accepted_run_callback_once- id: MESSAGE-DELIVERY-009name: P1 terminal race produces one accepted attachment or one P3 fallback ownerstatus: covered@@ -128,6 +128,18 @@ scenarios:kind: lifecyclelayer: contracttest: tests/test_session_delivery_fsm.py::test_held_old_backlog_does_not_block_new_idle_p3+ - id: MESSAGE-DELIVERY-201+ name: Every approved producer class maps to one explicit delivery priority+ status: covered+ kind: contract+ layer: contract+ test: tests/test_message_priority_cutover.py::test_source_policy_has_one_explicit_delivery_intent+ - id: MESSAGE-DELIVERY-202+ name: Ordinary IM input remains outside transcript until exact P1 acceptance+ status: covered+ kind: lifecycle+ layer: contract+ test: tests/test_session_delivery_fsm.py::test_im_p1_materializes_only_after_exact_native_acceptancenext_priority:- - MESSAGE-DELIVERY-201- - MESSAGE-DELIVERY-202+ - MESSAGE-DELIVERY-301+ - MESSAGE-DELIVERY-302diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex 2abcf5e1b..b4254c0f2 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -904,6 +904,39 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynself.assertTrue(consumed)service.submit_code.assert_awaited_once_with(context, "sk-opencode-secret", backend_hint="opencode")+ async def test_maybe_consume_setup_reply_fences_duplicate_before_submission(self):+ controller = _StubController()+ service = AgentAuthService(controller)+ context = MessageContext(user_id="U1", channel_id="C1")+ done_task = asyncio.create_task(asyncio.sleep(0))+ await done_task+ flow = AgentAuthFlow(+ flow_id="flow-opencode-duplicate",+ backend="opencode",+ settings_key="C1",+ initiator_user_id="U1",+ context=context,+ process=SimpleNamespace(returncode=None),+ reader_task=done_task,+ waiter_task=done_task,+ pty_master_fd=11,+ awaiting_code=True,+ provider="opencode",+ )+ service._flows[flow.flow_key] = flow+ service.submit_code = AsyncMock()+ claim_native_event = Mock(return_value=False)++ consumed = await service.maybe_consume_setup_reply(+ context,+ "sk-opencode-secret",+ claim_native_event=claim_native_event,+ )++ self.assertTrue(consumed)+ claim_native_event.assert_called_once_with()+ service.submit_code.assert_not_awaited()+async def test_maybe_consume_setup_reply_accepts_non_sk_opencode_credential(self):controller = _StubController()service = AgentAuthService(controller)diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.pyindex c94f87f3e..88ee918d0 100644--- a/tests/test_cli_agent_run_schema.py+++ b/tests/test_cli_agent_run_schema.py@@ -517,6 +517,83 @@ def test_agent_run_send_now_rejects_a_new_session(capsys) -> None:assert "--session-id" in payload["hint"]+def test_agent_run_queue_persists_explicit_p3_intent(+ tmp_path: Path,+ capsys,+) -> None:+ from core.services import sessions as sessions_service+ from storage.db import create_sqlite_engine+ from storage.importer import ensure_sqlite_state+ from storage.models import scope_settings+ from storage.settings_service import upsert_scope++ state_home = tmp_path / "home"+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):+ ensure_sqlite_state()+ db_path = state_home / "state" / "vibe.sqlite"+ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="avibe",+ scope_type="project",+ native_id="proj_queue",+ now="2026-08-02T00:00:00Z",+ )+ conn.execute(+ scope_settings.insert().values(+ scope_id=scope_id,+ enabled=1,+ role=None,+ workdir=str(tmp_path),+ agent_name=None,+ agent_backend=None,+ agent_variant=None,+ model=None,+ reasoning_effort=None,+ require_mention=None,+ settings_version=1,+ settings_json="{}",+ created_at="2026-08-02T00:00:00Z",+ updated_at="2026-08-02T00:00:00Z",+ )+ )+ session_id = sessions_service.create_session(+ conn,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="worker",+ )["id"]+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")+ args = _parse_agent_run(+ [+ "--session-id",+ session_id,+ "--queue",+ "--no-callback",+ "--message",+ "finish current work first",+ ]+ )++ with (+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),+ ):+ result = cli.cmd_agent_run(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["delivery_intent"] == "queue"+ assert payload["run"]["delivery_intent"] == "queue"+ stored = request_store.get_run(payload["run_id"])+ assert stored is not None+ assert stored["metadata"]["delivery_intent"] == "queue"++def test_agent_run_send_now_rejects_an_im_backed_session(tmp_path: Path,capsys,diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 07df51660..df5ea87bb 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -1054,8 +1054,10 @@ def test_dispatch_async_persists_acceptance_before_a_lost_response_replay()controller = None+ dispatched_text: list[str] = []- async def handler(context, _text):+ async def handler(context, text):+ dispatched_text.append(text)controller.mark_turn_complete(context)controller = _build_controller_double(handler)@@ -1069,7 +1071,7 @@ def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(transport = httpx.ASGITransport(app=app)payload = {"session_id": session["id"],- "text": "Dispatch exactly once.",+ "text": "stale caller text must not replace the reservation","user_message_id": row["id"],}@@ -1092,6 +1094,7 @@ def test_dispatch_async_persists_acceptance_before_a_lost_response_replay(assert first.json()["delivery_state"] in {"claimed", "accepted"}assert replay.status_code == 202assert replay.json()["duplicate"] is True+ assert dispatched_text == ["Dispatch exactly once."]controller.message_handler.handle_user_message.assert_awaited_once()with engine.connect() as conn:settled = messages_service.get_message(conn, row["id"], session_id=session["id"])@@ -1404,7 +1407,7 @@ def test_slow_live_show_post_cli_timeout_waits_without_duplicate_submit(),],)-def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(+def test_dispatch_async_defers_show_annotation_and_runs_it_after_active_turn(monkeypatch,tmp_path,comment,@@ -1505,10 +1508,16 @@ def test_dispatch_async_queues_show_annotation_and_runs_it_after_active_turn(assert queued.status_code == 202assert queued.json()["queued"] is Truewith engine.connect() as conn:- queued_rows = message_deliveries.list_queued(conn, session_id)- assert [row["id"] for row in queued_rows] == [annotation["delivery_id"]]- assert queued_rows[0]["text"] == annotation["transcript_text"]- assert queued_rows[0]["dispatch_text"] == enriched_dispatch_text+ pending = message_deliveries.get_delivery(+ conn,+ annotation["delivery_id"],+ )+ assert pending is not None+ assert pending["priority"] == "p1"+ assert pending["state"] == "pending_steer"+ payload = message_deliveries.delivery_payload(pending)+ assert payload["text"] == annotation["transcript_text"]+ assert pending["dispatch_text"] == enriched_dispatch_textvisible = messages_service.list_session_messages(conn,session_id=session_id,@@ -3655,7 +3664,11 @@ def test_agent_run_send_now_idle_start_failure_is_reconciled_without_replay(with engine.connect() as conn:delivery = message_deliveries.get_delivery_by_dedupe(conn,- f"avibe:agent_run:{request.id}",+ message_deliveries.native_dedupe_key(+ "avibe",+ f"agent_run:{request.id}",+ scope_id=scope_id,+ ),)assert delivery is not Noneassert delivery["state"] == "claimed"@@ -4120,7 +4133,11 @@ def test_scheduled_gate_retry_resumes_matching_reserved_delivery(monkeypatch, tmwith engine.connect() as conn:reserved = message_deliveries.get_delivery_by_dedupe(conn,- "avibe:watch:def-watch:reserved-retry",+ message_deliveries.native_dedupe_key(+ "avibe",+ "watch:def-watch:reserved-retry",+ scope_id=session["scope_id"],+ ),)assert reserved is not Noneassert reserved["state"] == "reserved"diff --git a/tests/test_message_handler_auth_setup.py b/tests/test_message_handler_auth_setup.pyindex aa6e0ab32..c74c22f17 100644--- a/tests/test_message_handler_auth_setup.py+++ b/tests/test_message_handler_auth_setup.py@@ -3,7 +3,7 @@ import sysimport typesimport unittestfrom pathlib import Path-from unittest.mock import AsyncMock+from unittest.mock import AsyncMock, Mock, patchROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT))@@ -63,14 +63,23 @@ MessageHandler = _load_message_handler_class()class _StubSessions:def __init__(self):self.recorded = []+ self._claimed = set()def is_message_already_processed(self, channel_id, thread_ts, message_ts):- return False+ return (channel_id, thread_ts, message_ts) in self._claimeddef record_processed_message(self, channel_id, thread_ts, message_ts):self.recorded.append((channel_id, thread_ts, message_ts))return None+ def try_record_processed_message(self, channel_id, thread_ts, message_ts):+ key = (channel_id, thread_ts, message_ts)+ if key in self._claimed:+ return False+ self._claimed.add(key)+ self.recorded.append(key)+ return True+class _StubSettingsManager:def __init__(self):@@ -160,6 +169,71 @@ class MessageHandlerAuthSetupTests(unittest.IsolatedAsyncioTestCase):)self.assertEqual(controller.settings_manager.sessions.recorded, [("C1", "m1", "m1")])+ async def test_durable_setup_reply_claims_native_event_before_consuming(self):+ controller = _StubController()+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ consumed = []+ flow_active = True++ async def consume_once(context, message, *, claim_native_event):+ nonlocal flow_active+ if not flow_active:+ return False+ if not claim_native_event():+ return True+ consumed.append(message)+ flow_active = False+ return True++ controller.agent_auth_service.maybe_consume_setup_reply = AsyncMock(+ side_effect=consume_once+ )+ handler = MessageHandler(controller)+ handler._is_duplicate_human_delivery = Mock(+ side_effect=lambda context: controller.settings_manager.sessions.is_message_already_processed(+ context.channel_id,+ context.thread_id or context.message_id,+ context.message_id,+ )+ )+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="slack",+ message_id="m-setup",+ )++ await handler.handle_user_message(context, "sk-opencode-secret")+ await handler.handle_user_message(context, "sk-opencode-secret")++ self.assertEqual(consumed, ["sk-opencode-secret"])+ self.assertEqual(+ controller.settings_manager.sessions.recorded,+ [("C1", "m-setup", "m-setup")],+ )+ self.assertEqual(+ controller.agent_auth_service.maybe_consume_setup_reply.await_count,+ 1,+ )+ controller.session_turns.deliver.assert_not_awaited()++ async def test_consumed_control_fence_precedes_delivery_lookup(self):+ controller = _StubController()+ handler = MessageHandler(controller)+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ platform="telegram",+ message_id="1",+ )+ assert handler._claim_native_human_event(context)++ with patch(+ "storage.db.get_cached_sqlite_engine",+ side_effect=AssertionError("Delivery lookup must not run"),+ ):+ assert handler._is_duplicate_human_delivery(context)+if __name__ == "__main__":unittest.main()diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.pyindex f1cb882c7..8fe0c3dc4 100644--- a/tests/test_message_handler_typing.py+++ b/tests/test_message_handler_typing.py@@ -281,6 +281,190 @@ class _StubSessionHandler:class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):+ async def test_im_human_input_enters_delivery_owner_before_backend(self):+ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ controller.settings_manager.sessions.try_record_processed_message = Mock()+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._admit_human_delivery = AsyncMock(return_value=True)+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(+ return_value="[metadata]\nhello"+ )+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m1",+ platform="slack",+ )++ await handler.handle_user_message(context, "hello")++ handler._admit_human_delivery.assert_awaited_once()+ assert (+ handler._admit_human_delivery.await_args.kwargs["dispatch_text"]+ == "[metadata]\nhello"+ )+ controller.settings_manager.sessions.try_record_processed_message.assert_not_called()+ self.assertEqual(controller.agent_service.requests, [])++ async def test_explicit_opencode_subagent_uses_new_turn_delivery_intent(self):+ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ server = types.SimpleNamespace(+ ensure_running=AsyncMock(),+ get_available_agents=AsyncMock(return_value=[{"name": "reviewer"}]),+ )+ controller.agent_service.agents = {+ "opencode": types.SimpleNamespace(+ _get_server=AsyncMock(return_value=server)+ )+ }+ controller.get_cwd = Mock(return_value="/tmp")+ controller.resolve_vibe_agent_for_context = Mock(+ return_value=types.SimpleNamespace(+ id="agent-opencode",+ name="opencode",+ backend="opencode",+ model=None,+ reasoning_effort=None,+ system_prompt=None,+ )+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._admit_human_delivery = AsyncMock(return_value=True)+ handler._is_duplicate_human_delivery = Mock(return_value=False)+ handler._prepend_message_metadata = AsyncMock(return_value="check this")+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-subagent",+ platform="slack",+ )++ await handler.handle_user_message(context, "reviewer: check this")++ call = handler._admit_human_delivery.await_args.kwargs+ self.assertEqual(call["delivery_intent"], "queue")+ self.assertEqual(+ call["admission_context"]["message_handler_route"]["subagent_name"],+ "reviewer",+ )+ self.assertEqual(+ call["admission_context"]["message_handler_route"]["base_session_id"],+ "base-session",+ )+ self.assertEqual(controller.agent_service.requests, [])++ async def test_duplicate_im_attachment_skips_download_before_admission(self):+ from modules.im.base import FileAttachment++ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ controller.session_turns = types.SimpleNamespace(deliver=AsyncMock())+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ handler._is_duplicate_human_delivery = Mock(return_value=True)+ handler._process_file_attachments = AsyncMock()+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="m-attachment-retry",+ platform="slack",+ files=[+ FileAttachment(+ name="report.pdf",+ mimetype="application/pdf",+ url="https://files.example/report.pdf",+ )+ ],+ )++ await handler.handle_user_message(context, "review this")++ handler._process_file_attachments.assert_not_awaited()+ controller.session_turns.deliver.assert_not_awaited()+ self.assertEqual(controller.agent_service.requests, [])++ async def test_inline_stop_uses_durable_empty_p0_owner(self):+ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ cancel = AsyncMock(return_value={"ok": True, "status": "cancel_requested"})+ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ cancel=cancel,+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ thread_id="T1",+ message_id="m-stop",+ platform="slack",+ platform_specific={+ "agent_session_id": "ses-durable",+ "control_text": "stop",+ },+ )++ await handler.handle_user_message(context, "stop")++ cancel.assert_awaited_once_with("ses-durable")+ self.assertEqual(controller.agent_service.stop_requests, [])+ self.assertEqual(controller.agent_service.requests, [])++ async def test_retried_inline_stop_cannot_cancel_a_newer_turn(self):+ controller = _StubController(+ platform="slack",+ ack_mode="reaction",+ typing_result=True,+ )+ cancel = AsyncMock(return_value={"ok": True, "status": "cancel_requested"})+ controller.session_turns = types.SimpleNamespace(+ deliver=AsyncMock(),+ cancel=cancel,+ )+ controller.settings_manager.sessions.try_record_processed_message = Mock(+ side_effect=[True, False]+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(_StubSessionHandler())+ context = MessageContext(+ user_id="U1",+ channel_id="C1",+ thread_id="T1",+ message_id="m-stop-retry",+ platform="slack",+ platform_specific={+ "agent_session_id": "ses-durable",+ "control_text": "stop",+ },+ )++ await handler.handle_user_message(context, "stop")+ await handler.handle_user_message(context, "stop")++ cancel.assert_awaited_once_with("ses-durable")+ self.assertEqual(controller.agent_service.stop_requests, [])+ self.assertEqual(controller.agent_service.requests, [])+async def test_pre_request_failure_uses_plain_terminal_output(self):controller = _StubController(platform="slack",diff --git a/tests/test_message_priority_cutover.py b/tests/test_message_priority_cutover.pynew file mode 100644index 000000000..da8b5ecb8--- /dev/null+++ b/tests/test_message_priority_cutover.py@@ -0,0 +1,116 @@+from __future__ import annotations++import pytest++from core.scheduled_tasks import ParsedSessionKey, ResolvedSessionIdTarget+++ ("trigger_kind", "expected_intent"),+ [+ ("im", "steer"),+ ("scheduled", "queue"),+ ("task_run", "queue"),+ ("watch", "steer"),+ ("hook", "steer"),+ ("webhook", "steer"),+ ("agent_run", "steer"),+ ("show_annotation", "steer"),+ ("callback", "steer"),+ ],+)+def test_source_policy_has_one_explicit_delivery_intent(+ trigger_kind: str,+ expected_intent: str,+) -> None:+ from core.message_priority import delivery_intent_for_trigger++ assert delivery_intent_for_trigger(trigger_kind) == expected_intent+++ ("intent", "expected_priority"),+ [+ ("send_now", "p0"),+ ("steer", "p1"),+ ("queue", "p3"),+ ],+)+def test_delivery_intent_maps_to_exact_priority(+ intent: str,+ expected_priority: str,+) -> None:+ from core.message_priority import priority_for_delivery_intent++ assert priority_for_delivery_intent(intent) == expected_priority+++ ("priority", "expected_intent"),+ [("p0", "send_now"), ("p1", "steer"), ("p3", "queue")],+)+def test_delivery_priority_maps_to_exact_intent(+ priority: str,+ expected_intent: str,+) -> None:+ from core.message_priority import delivery_intent_for_priority++ assert delivery_intent_for_priority(priority) == expected_intent+++def test_agent_run_queue_intent_is_not_normalized_back_to_steer() -> None:+ from core.scheduled_tasks import normalize_agent_run_delivery_intent++ assert normalize_agent_run_delivery_intent("queue") == "queue"+++def test_session_context_rebuilds_an_im_target_from_durable_scope(monkeypatch) -> None:+ from core import internal_server+ from core import scheduled_tasks++ target = ResolvedSessionIdTarget(+ session_id="ses_im",+ session_key=ParsedSessionKey(+ platform="slack",+ scope_type="channel",+ scope_id="C123",+ thread_id="171.2",+ ),+ agent_backend="codex",+ agent_variant="default",+ native_session_id="native-1",+ scope_id="scp_1",+ agent_name="codex",+ session_anchor="slack_C123_171.2",+ )+ monkeypatch.setattr(+ scheduled_tasks,+ "resolve_session_id_target",+ lambda _session_id: target,+ )+ monkeypatch.setattr(+ internal_server,+ "_lookup_session",+ lambda _session_id: {+ "id": "ses_im",+ "agent_id": None,+ "agent_name": "codex",+ "agent_backend": "codex",+ "agent_variant": "default",+ "model": None,+ "reasoning_effort": None,+ "native_session_id": "native-1",+ "workdir": "/tmp/project",+ "metadata": {},+ "session_anchor": "slack_C123_171.2",+ "visibility": "foreground",+ },+ )++ context = internal_server._build_session_context("ses_im")++ assert context.platform == "slack"+ assert context.channel_id == "C123"+ assert context.thread_id == "171.2"+ assert context.platform_specific["agent_session_id"] == "ses_im"+ assert "workbench_session_id" not in context.platform_specificdiff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 52779694f..c4d71d2e9 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -53,6 +53,116 @@ def _seed_session(conn, scope_id: str, session_id: str) -> None:)+def test_native_message_identity_is_scoped_to_conversation(isolated_state):+ engine = create_sqlite_engine(isolated_state / "state" / "vibe.sqlite")+ with engine.begin() as conn:+ now = messages_service._utc_now_iso()+ first_scope = upsert_scope(+ conn,+ platform="telegram",+ scope_type="channel",+ native_id="chat-1",+ now=now,+ )+ second_scope = upsert_scope(+ conn,+ platform="telegram",+ scope_type="channel",+ native_id="chat-2",+ now=now,+ )+ _seed_session(conn, first_scope, "ses_chat_1")+ _seed_session(conn, second_scope, "ses_chat_2")+ messages_service.append(+ conn,+ scope_id=first_scope,+ session_id="ses_chat_1",+ platform="telegram",+ author="user",+ text="first chat",+ native_message_id="1",+ )++ assert messages_service.native_message_exists(+ conn,+ platform="telegram",+ scope_id=first_scope,+ native_message_id="1",+ )+ assert not messages_service.native_message_exists(+ conn,+ platform="telegram",+ scope_id=second_scope,+ native_message_id="1",+ )+ messages_service.append(+ conn,+ scope_id=second_scope,+ session_id="ses_chat_2",+ platform="telegram",+ author="user",+ text="second chat",+ native_message_id="1",+ )+ first_delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id="msg_delivery_chat_1",+ session_id="ses_chat_1",+ priority="p1",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=first_scope,+ session_id="ses_chat_1",+ platform="telegram",+ author="user",+ source="user",+ message_type="user",+ text="queued first chat",+ native_message_id="2",+ ),+ dispatch_text="queued first chat",+ dedupe_key=message_deliveries.native_dedupe_key(+ "telegram",+ "2",+ scope_id=first_scope,+ ),+ )+ second_delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id="msg_delivery_chat_2",+ session_id="ses_chat_2",+ priority="p1",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=second_scope,+ session_id="ses_chat_2",+ platform="telegram",+ author="user",+ source="user",+ message_type="user",+ text="queued second chat",+ native_message_id="2",+ ),+ dispatch_text="queued second chat",+ dedupe_key=message_deliveries.native_dedupe_key(+ "telegram",+ "2",+ scope_id=second_scope,+ ),+ )+ assert first_delivery["id"] != second_delivery["id"]++ assert message_deliveries.native_dedupe_key(+ "telegram",+ "1",+ scope_id=first_scope,+ ) != message_deliveries.native_dedupe_key(+ "telegram",+ "1",+ scope_id=second_scope,+ )++def _list_production_transcript(conn, session_id: str):return messages_service.list_session_messages(conn,diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 2e93e3b68..cec510b7a 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -4556,6 +4556,71 @@ def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Patassert callback_run["message"] == "complete delegated result"+def test_one_terminal_turn_fans_out_each_accepted_run_callback_once(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """Scenario: MESSAGE-DELIVERY-008 closed-loop subscriber fan-out."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ caller_session_id = _make_avibe_session(+ monkeypatch,+ tmp_path,+ scope_native_id="callback-fanout-caller",+ )+ target_session_id = _make_avibe_session(+ monkeypatch,+ tmp_path,+ scope_native_id="callback-fanout-target",+ )+ request_store = TaskExecutionStore()+ requests = [+ request_store.enqueue_agent_run(+ session_id=target_session_id,+ message=message,+ agent_name="codex",+ callback_session_id=caller_session_id,+ )+ for message in ("participant one", "participant two")+ ]+ for request in requests:+ assert request_store.claim(request.id) is not None++ service = _callback_service(tmp_path=tmp_path, request_store=request_store)+ service.settle_agent_runs_from_terminal_turn(+ [request.id for request in requests],+ turn_id="turn-shared-by-two-runs",+ outcome="completed",+ settled_by="terminal_result",+ evidence_kind="terminal_result",+ evidence={+ "settles_run": True,+ "result_text": "shared immutable terminal result",+ },+ )++ asyncio.run(service._drain_callbacks())+ asyncio.run(service._drain_callbacks())++ originals = [request_store.get_run(request.id) for request in requests]+ assert all(row is not None and row["callback_status"] == "sent" for row in originals)+ callbacks = [+ run+ for run in request_store.list_runs()+ if run.get("source_kind") == "callback"+ ]+ assert len(callbacks) == 2+ assert {run["parent_run_id"] for run in callbacks} == {+ request.id for request in requests+ }+ assert {run["message"] for run in callbacks} == {+ "shared immutable terminal result"+ }+ assert {+ run["metadata"]["delivery_intent"] for run in callbacks+ } == {"steer"}++def test_historical_conflated_sent_callback_stays_inert_on_startup(tmp_path: Path,monkeypatch,@@ -6376,8 +6441,16 @@ def test_avibe_agent_run_routes_through_gate_without_completing_early(monkeypatcsubmitted: list[tuple] = []handler_calls: list = []- async def _submit_scheduled(sid, ctx, text):- submitted.append((sid, text, ctx.platform, ctx.platform_specific.get("task_execution_id")))+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):+ submitted.append(+ (+ sid,+ text,+ ctx.platform,+ ctx.platform_specific.get("task_execution_id"),+ delivery_intent,+ )+ )return "ran"async def _handle_scheduled_message(context, message, parsed_session_key=None):@@ -6404,12 +6477,14 @@ def test_avibe_agent_run_routes_through_gate_without_completing_early(monkeypatcassert run is not Noneassert run["status"] == "running"assert run.get("completed_at") is None- assert submitted == [(session_id, "run in workbench session", "avibe", request.id)]+ assert submitted == [+ (session_id, "run in workbench session", "avibe", request.id, "queue")+ ]assert handler_calls == []-def test_legacy_queue_delivery_intent_normalizes_to_current_steer() -> None:- assert normalize_agent_run_delivery_intent("queue") == "steer"+def test_explicit_queue_delivery_intent_remains_queued() -> None:+ assert normalize_agent_run_delivery_intent("queue") == "queue"def test_busy_avibe_agent_run_send_now_keeps_transferred_owner_running(monkeypatch, tmp_path) -> None:@@ -6884,11 +6959,16 @@ def test_claimed_watch_stays_nonterminal_after_delivery_ownership_transfer()submitted: list[tuple[str, str, str]] = []- async def _submit_scheduled(sid, ctx, text):+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):from core.session_turns import TurnSubmissionResultsubmitted.append(- (sid, text, str(ctx.platform_specific.get("task_execution_id") or ""))+ (+ sid,+ text,+ str(ctx.platform_specific.get("task_execution_id") or ""),+ delivery_intent,+ ))return TurnSubmissionResult(route="enqueued",@@ -6922,7 +7002,7 @@ def test_claimed_watch_stays_nonterminal_after_delivery_ownership_transfer(assert stored is not Noneassert stored["status"] == "running"assert stored.get("completed_at") is None- assert submitted == [(session_id, "watch result", request.id)]+ assert submitted == [(session_id, "watch result", request.id, "steer")]def test_drain_requests_records_scheduled_create_per_run_reserved_session(tmp_path: Path) -> None:@@ -7770,11 +7850,12 @@ def _make_avibe_session(metadata: dict | None = None,visibility: str = "foreground",scope_native_id: str = "proj_gate_exec",+ platform: str = "avibe",+ scope_type: str = "project",agent_backend: str = "claude",agent_name: str = "worker",) -> str:- """Create a real avibe workbench session so ``resolve_session_id_target``- resolves it to ``platform='avibe'`` (the gate trigger)."""+ """Create a real persisted Session target for delivery-gate tests."""from core.services import sessions as sessions_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state@@ -7787,8 +7868,8 @@ def _make_avibe_session(with engine.begin() as conn:scope_id = upsert_scope(conn,- platform="avibe",- scope_type="project",+ platform=platform,+ scope_type=scope_type,native_id=scope_native_id,now="2026-05-31T00:00:00Z",)@@ -7832,8 +7913,8 @@ def test_execute_request_avibe_routes_through_gate(monkeypatch, tmp_path) -> Nonsubmitted: list[tuple] = []handler_calls: list = []- async def _submit_scheduled(sid, ctx, text):- submitted.append((sid, text, getattr(ctx, "platform", None)))+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):+ submitted.append((sid, text, getattr(ctx, "platform", None), delivery_intent))async def _handle_scheduled_message(context, message, parsed_session_key=None):handler_calls.append(message)@@ -7858,19 +7939,29 @@ def test_execute_request_avibe_routes_through_gate(monkeypatch, tmp_path) -> Non)assert error is None, "dispatched-success returns None so ok=not error stays true"- assert submitted == [(session_id, "run the digest", "avibe")], "routed through the turn gate"+ assert submitted == [+ (session_id, "run the digest", "avibe", "queue")+ ], "routed through the turn gate"assert handler_calls == [], "the direct handle_scheduled_message path is bypassed for avibe"-def test_execute_request_im_bypasses_gate(monkeypatch, tmp_path) -> None:- """An IM (slack/discord/...) scheduled run NEVER touches the gate — it keeps- the direct ``handle_scheduled_message`` path byte-for-byte, even when a gate- is present on the controller."""+def test_execute_request_im_watch_steers_through_delivery_owner(+ monkeypatch,+ tmp_path,+) -> None:+ """An IM Watch uses the same durable P1 owner as every Session target."""+ session_id = _make_avibe_session(+ monkeypatch,+ tmp_path,+ platform="slack",+ scope_type="channel",+ scope_native_id="C123",+ )submitted: list = []handler_calls: list = []- async def _submit_scheduled(sid, ctx, text):- submitted.append((sid, text))+ async def _submit_scheduled(sid, ctx, text, *, delivery_intent="steer"):+ submitted.append((sid, text, delivery_intent))async def _handle_scheduled_message(context, message, parsed_session_key=None):handler_calls.append((message, context.platform))@@ -7898,13 +7989,14 @@ def test_execute_request_im_bypasses_gate(monkeypatch, tmp_path) -> None:deliver_key=None,prompt="send digest",execution_id="exec-im-1",- trigger_kind="scheduled",+ trigger_kind="watch",+ session_id=session_id,))assert error is None- assert submitted == [], "IM runs must never reach the turn gate"- assert handler_calls == [("send digest", "slack")], "IM keeps the direct scheduled path"+ assert submitted == [(session_id, "send digest", "steer")]+ assert handler_calls == []def test_execute_request_avibe_falls_back_when_no_gate(monkeypatch, tmp_path) -> None:diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex f7c239f2b..3da0429b0 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -26,7 +26,9 @@ from core.session_turns import (SessionTurnManager,Turn,)+from core.handlers.message_handler import MessageHandlerfrom modules.im import MessageContext+from modules.im.base import FileAttachmentfrom storage import message_deliveries as delivery_storefrom storage import messages_servicefrom storage import workbench_sessions_service@@ -319,6 +321,148 @@ def test_persisted_start_attempt_reaches_dispatch_context(managers) -> None:assert captured["delivery_start_attempt_id"] == turn["start_attempt_id"]+def test_im_p1_materializes_only_after_exact_native_acceptance(managers) -> None:+ manager, _other, engine, _engine_b, _starts = managers++ async def run() -> tuple[str, str]:+ active_turn_id, _ = await _activate(manager, text="active")+ entered = asyncio.Event()+ release = asyncio.Event()++ async def accept(_backend, request):+ assert request.text == "steer this exact text"+ entered.set()+ await release.wait()+ return steer_result(SteerOutcome.ACCEPTED)++ manager._steer = accept+ pending = asyncio.create_task(+ manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p1",+ content="steer this exact text",+ platform="slack",+ source="user",+ author="user",+ message_type="user",+ author_id="U42",+ author_name="Ada",+ native_message_id="slack-msg-42",+ ),+ context=_context(),+ )+ )+ await entered.wait()+ with engine.connect() as conn:+ delivery = conn.execute(+ select(message_deliveries).where(+ message_deliveries.c.dedupe_key == "slack:slack-msg-42"+ )+ ).mappings().one()+ materialized = conn.execute(+ select(messages.c.id).where(+ messages.c.native_message_id == "slack-msg-42"+ )+ ).first()+ assert delivery["state"] == "steering"+ assert delivery["message_id"] is None+ assert materialized is None++ release.set()+ accepted = await pending+ assert accepted.state == "accepted"+ return active_turn_id, str(accepted.delivery_id)++ turn_id, delivery_id = asyncio.run(run())+ with engine.connect() as conn:+ delivery = delivery_store.get_delivery(conn, delivery_id)+ message = conn.execute(+ select(messages).where(messages.c.id == delivery_id)+ ).mappings().one()+ assert delivery is not None+ assert delivery["turn_id"] == turn_id+ assert delivery["message_id"] == delivery_id+ assert message["platform"] == "slack"+ assert message["native_message_id"] == "slack-msg-42"+ assert message["content_text"] == "steer this exact text"+ assert message["author_id"] == "U42"+++def test_duplicate_im_p1_reuses_one_delivery_and_one_native_steer(managers) -> None:+ manager, _other, engine, _engine_b, _starts = managers++ async def run() -> tuple[str, str]:+ await _activate(manager, text="active")+ manager._steer = AsyncMock(+ return_value=steer_result(SteerOutcome.ACCEPTED)+ )+ request = DeliveryRequest(+ session_id="ses_fsm",+ priority="p1",+ content="deliver once",+ platform="slack",+ source="user",+ author="user",+ message_type="user",+ native_message_id="slack-duplicate-1",+ )++ first = await manager.deliver(request, context=_context())+ duplicate = await manager.deliver(request, context=_context())++ manager._steer.assert_awaited_once()+ return first.delivery_id, duplicate.delivery_id++ first_id, duplicate_id = asyncio.run(run())+ assert duplicate_id == first_id+ with engine.connect() as conn:+ rows = conn.execute(+ select(message_deliveries).where(+ message_deliveries.c.dedupe_key == "slack:slack-duplicate-1"+ )+ ).mappings().all()+ assert len(rows) == 1+ assert rows[0]["state"] == "accepted"+++def test_delivery_admission_context_restores_route_without_message_metadata(+ managers,+) -> None:+ manager, _other, engine, _engine_b, _starts = managers+ admitted = asyncio.run(+ manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p3",+ content="route me",+ metadata={"visible": "record metadata"},+ admission_context={+ "message_handler_route": {+ "base_session_id": "slack_C1:reviewer",+ "subagent_name": "reviewer",+ "routing_subagent": True,+ }+ },+ ),+ context=_context(),+ )+ )+ delivery = _row(engine, str(admitted.delivery_id))+ context = _context()++ payload = manager._hydrate_delivery_context(context, delivery)++ assert payload["metadata"] == {"visible": "record metadata"}+ assert context.platform_specific["delivery_admission_context"] == {+ "message_handler_route": {+ "base_session_id": "slack_C1:reviewer",+ "subagent_name": "reviewer",+ "routing_subagent": True,+ }+ }++def test_dispatch_uses_current_session_route_without_mutating_delivery_provenance(managers,) -> None:@@ -2469,6 +2613,75 @@ def test_two_restart_recoveries_claim_reserved_submission_once(managers) -> Noneassert _row(engine, delivery_id)["state"] == "claimed"+async def test_concurrent_im_attachment_retry_keeps_one_reserved_owner(+ managers,+ tmp_path: Path,+ monkeypatch,+) -> None:+ manager, _other, engine, _engine_b, _starts = managers+ first_path = tmp_path / "first.txt"+ retry_path = tmp_path / "retry.txt"+ first_path.write_text("first", encoding="utf-8")+ retry_path.write_text("retry", encoding="utf-8")+ controller = SimpleNamespace(+ config=SimpleNamespace(language="en"),+ im_client=SimpleNamespace(formatter=None),+ settings_manager=SimpleNamespace(sessions=SimpleNamespace()),+ session_manager=SimpleNamespace(),+ receiver_tasks={},+ )+ handler = MessageHandler(controller)+ handler.set_session_handler(+ SimpleNamespace(ensure_agent_session_id=lambda *_args, **_kwargs: "ses_fsm")+ )+ monkeypatch.setattr("storage.db.get_cached_sqlite_engine", lambda: engine)++ def context() -> MessageContext:+ return MessageContext(+ user_id="U1",+ channel_id="C1",+ message_id="native-attachment-1",+ platform="slack",+ )++ async def admit(path: Path) -> None:+ await handler._admit_human_delivery(+ manager=manager,+ context=context(),+ dispatch_text="review attachment",+ display_text="review attachment",+ processed_files=[+ FileAttachment(+ name=path.name,+ mimetype="text/plain",+ local_path=str(path),+ size=path.stat().st_size,+ )+ ],+ session_key="slack::C1",+ agent_name="codex",+ session_anchor="base-session",+ working_path="/tmp",+ vibe_agent=None,+ delivery_intent="steer",+ downloaded_attachment_paths=[str(path)],+ admission_context={},+ )++ await admit(first_path)+ await admit(retry_path)++ with engine.connect() as conn:+ deliveries = conn.execute(select(message_deliveries)).mappings().all()+ media = conn.execute(select(media_objects)).mappings().all()+ assert len(deliveries) == 1+ assert len(media) == 1+ assert media[0]["local_path"] == str(first_path)+ assert first_path.exists()+ assert not retry_path.exists()++def test_reserved_attachment_only_submission_recovers_exact_dispatch_inputs(managers,tmp_path: Path,diff --git a/tests/test_show_session_events.py b/tests/test_show_session_events.pyindex 928fc45df..293cde44c 100644--- a/tests/test_show_session_events.py+++ b/tests/test_show_session_events.py@@ -1374,6 +1374,7 @@ def test_dispatching_show_event_reserves_delivery_outside_transcript(isolated_stassert dispatching["message"] is Noneassert dispatching["message_id"] is None+ assert dispatching["delivery"]["priority"] == "p1"assert dispatching["delivery"]["state"] == "reserved"assert dispatching["delivery"]["author"] == messages_service.HARNESS_TYPEassert dispatching["delivery"]["source"] == messages_service.HARNESS_TYPEdiff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex d3bb1e6b4..35d59b9da 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -3104,6 +3104,7 @@ def test_sessions_store_atomically_claims_processed_messages_across_instances(tmsecond = SessionsStore(sessions_path)try:assert first.try_add_to_processed_set("C123", "171717.123", "171717.456") is True+ assert second.has_processed_message("C123", "171717.123", "171717.456") is Trueassert second.try_add_to_processed_set("C123", "171717.123", "171717.456") is Falseassert second.is_message_in_processed_set("C123", "171717.123", "171717.456") is Truefinally:diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 8ffee249b..6d0d3a25c 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -13,21 +13,22 @@ import pytestfrom alembic import commandfrom alembic.script import ScriptDirectoryfrom sqlalchemy.dialects.sqlite import dialect as sqlite_dialect+from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.schema import CreateIndexfrom config import pathsfrom config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStorefrom storage.db import SqliteInvalidationProbe, create_sqlite_enginefrom storage.importer import JSON_IMPORT_MARKER, ensure_sqlite_state-from storage import migrations+from storage import message_deliveries, messages_service, migrationsfrom storage.background import SQLiteBackgroundTaskStorefrom storage.migrations import UnsafeDefaultStateMigrationError, background_tables_ready, run_migrationsfrom storage.models import metadata-from storage.settings_service import SQLiteSettingsService+from storage.settings_service import SQLiteSettingsService, upsert_scopefrom vibe.message_types import build_partial_index_predicate-HEAD_REVISION = "20260801_0044"+HEAD_REVISION = "20260802_0045"MESSAGE_PARTIAL_INDEX_PREDICATES = {"ix_messages_inbox_activity": ("session_id is not null and type in "@@ -100,6 +101,180 @@ def test_alembic_script_directory_has_exactly_one_head() -> None:assert heads[0] == HEAD_REVISION+def test_scoped_native_message_identity_upgrade_and_safe_downgrade(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260801_0044")+ engine = create_sqlite_engine(db_path)+ with engine.begin() as conn:+ now = messages_service._utc_now_iso()+ first_scope = upsert_scope(+ conn,+ platform="telegram",+ scope_type="channel",+ native_id="chat-1",+ now=now,+ )+ messages_service.append(+ conn,+ scope_id=first_scope,+ session_id=None,+ platform="telegram",+ author="user",+ text="first",+ native_message_id="1",+ )++ command.upgrade(migrations.alembic_config(db_path), "head")++ with engine.begin() as conn:+ now = messages_service._utc_now_iso()+ second_scope = upsert_scope(+ conn,+ platform="telegram",+ scope_type="channel",+ native_id="chat-2",+ now=now,+ )+ messages_service.append(+ conn,+ scope_id=second_scope,+ session_id=None,+ platform="telegram",+ author="user",+ text="second",+ native_message_id="1",+ )+ indexes = {+ row[1]+ for row in conn.exec_driver_sql("pragma index_list(messages)")+ }+ assert "uq_messages_platform_scope_native" in indexes+ assert "uq_messages_platform_native_unscoped" in indexes++ with pytest.raises(IntegrityError), engine.begin() as conn:+ messages_service.append(+ conn,+ scope_id=second_scope,+ session_id=None,+ platform="telegram",+ author="user",+ text="duplicate",+ native_message_id="1",+ )++ with pytest.raises(+ RuntimeError,+ match="conversation-scoped Message identities would collide",+ ):+ command.downgrade(migrations.alembic_config(db_path), "20260801_0044")+++def test_scoped_native_message_identity_upgrade_preserves_accepted_delivery(+ tmp_path: Path,+) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260801_0044")+ engine = create_sqlite_engine(db_path)+ now = "2026-08-02T00:00:00Z"+ with engine.begin() as conn:+ scope_id = upsert_scope(+ conn,+ platform="telegram",+ scope_type="channel",+ native_id="chat-accepted",+ now=now,+ )+ conn.exec_driver_sql(+ """+ insert into agent_sessions (+ id, scope_id, agent_name, agent_backend, agent_variant,+ session_anchor, workdir, native_session_id, status, visibility,+ pinned, agent_status, metadata_json, created_at, updated_at,+ last_active_at+ ) values (+ 'ses_accepted', ?, 'codex', 'codex', 'codex', 'accepted',+ '/tmp', '', 'active', 'foreground', 0, 'idle', '{}', ?, ?, ?+ )+ """,+ (scope_id, now, now, now),+ )+ delivery = message_deliveries.insert_delivery(+ conn,+ delivery_id="msg_accepted_delivery",+ session_id="ses_accepted",+ priority="p3",+ state="reserved",+ snapshot=message_deliveries.message_snapshot(+ scope_id=scope_id,+ session_id="ses_accepted",+ platform="telegram",+ author="user",+ source="user",+ message_type="user",+ text="accepted",+ native_message_id="1",+ ),+ dispatch_text="accepted",+ dedupe_key="telegram:1",+ now=now,+ )+ claimed = message_deliveries.claim_start_batch(+ conn,+ turn_id="turn_accepted_delivery",+ session_id="ses_accepted",+ backend="codex",+ deliveries=[delivery],+ dispatch_text="accepted",+ )+ turn = message_deliveries.bind_native_start(+ conn,+ "turn_accepted_delivery",+ expected_version=int(claimed["turn"]["version"]),+ runtime_key="runtime",+ runtime_turn_id="runtime-turn",+ native_turn_id="native-turn",+ )+ assert turn is not None+ assert message_deliveries.materialize_start_acceptance(+ conn,+ turn_id="turn_accepted_delivery",+ evidence={"kind": "test"},+ )++ command.upgrade(migrations.alembic_config(db_path), "head")++ with engine.connect() as conn:+ accepted = conn.exec_driver_sql(+ "select message_id, dedupe_key from message_deliveries "+ "where id='msg_accepted_delivery'"+ ).one()+ message = conn.exec_driver_sql(+ "select scope_id, native_message_id from messages "+ "where id='msg_accepted_delivery'"+ ).one()+ foreign_key_errors = conn.exec_driver_sql("pragma foreign_key_check").all()+ assert accepted == (+ "msg_accepted_delivery",+ message_deliveries.native_dedupe_key(+ "telegram",+ "1",+ scope_id=scope_id,+ ),+ )+ assert message == (scope_id, "1")+ assert foreign_key_errors == []++ command.downgrade(migrations.alembic_config(db_path), "20260801_0044")+ with engine.connect() as conn:+ assert conn.exec_driver_sql(+ "select message_id, dedupe_key from message_deliveries "+ "where id='msg_accepted_delivery'"+ ).one() == ("msg_accepted_delivery", "telegram:1")+ assert conn.exec_driver_sql("pragma foreign_key_check").all() == []++def test_session_delivery_fsm_upgrade_and_downgrade_preserve_existing_rows(tmp_path: Path,) -> None:diff --git a/vibe/cli.py b/vibe/cli.pyindex 337156f64..ed33f4a48 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -35,6 +35,7 @@ from sqlalchemy import selectfrom config import SettingsStore, pathsfrom config.v2_config import V2Configfrom core.scheduled_tasks import (+ AGENT_RUN_DELIVERY_QUEUE,AGENT_RUN_DELIVERY_STEER,AGENT_RUN_DELIVERY_SEND_NOW,BINDING_FOLLOWS_SESSION_METADATA_KEY,@@ -1180,6 +1181,7 @@ def _agent_run_examples_text() -> str:Session target:Use --session-id to continue an existing Agent Session.The default is P1: steer an active native Turn, start when idle, or fall back to the durable P3 queue.+ Add --queue to persist this Run as P3 behind the active Turn.Add --send-now to admit this new Run as content P0 and replace the active Turn.To promote the exact existing P3 queue head without a new message, use: vibe session send-now <session-id>Inspect queued work with: vibe session queue list <session-id>@@ -4858,6 +4860,8 @@ def cmd_agent_run(args):delivery_intent = (AGENT_RUN_DELIVERY_SEND_NOWif bool(getattr(args, "send_now", False))+ else AGENT_RUN_DELIVERY_QUEUE+ if bool(getattr(args, "queue", False))else AGENT_RUN_DELIVERY_STEER)if delivery_intent == AGENT_RUN_DELIVERY_SEND_NOW and session_policy != "existing":@@ -4945,7 +4949,10 @@ def cmd_agent_run(args):raise TaskCliError("--send-now requires a Web/Workbench Agent Session",code="send_now_unsupported_target",- hint="Omit --send-now to queue work for an IM-backed Session.",+ hint=(+ "Omit --send-now to steer the active IM Turn or start a new "+ "Turn when idle."+ ),help_command="vibe agent run --help",details={"session_id": session_id,@@ -13123,11 +13130,17 @@ def build_parser():)agent_run_parser.add_argument("--agent", help="Avibe Agent name")agent_run_parser.add_argument("--session-id", help="Existing Agent Session ID to continue")- agent_run_parser.add_argument(+ agent_run_delivery_group = agent_run_parser.add_mutually_exclusive_group()+ agent_run_delivery_group.add_argument("--send-now",action="store_true",help="Replace the active Turn with this new Run; start it immediately when idle",)+ agent_run_delivery_group.add_argument(+ "--queue",+ action="store_true",+ help="Queue this Run behind the active Turn instead of steering it",+ )agent_run_parser.add_argument("--fork-session", help="Existing Agent Session ID to fork into a new Session")agent_run_parser.add_argument("--fork-self", action="store_true", help="Fork this current Agent Session")agent_run_parser.add_argument("--create-session", action="store_true", help="Create a new Avibe Session ID before running")