Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(workbench): pin each thread to one backend — unique (scope, anchor) session model + migration
Call Whiteffcd2f0856b5
diff --git a/config/v2_sessions.py b/config/v2_sessions.pyindex 449399680..65e606860 100644--- a/config/v2_sessions.py+++ b/config/v2_sessions.py@@ -356,6 +356,16 @@ class SessionsStore:self.get_agent_map(user_id, agent_name).setdefault(thread_id, "")return agent_session_id+ def find_session_for_anchor(self, user_id: str, session_anchor: str):+ """Read-through to the SQLite service's ``(scope, anchor)`` lookup (latest+ row, any backend). Not cached — callers use it only to pin a thread's+ backend at resolution time."""+ self._ensure_service()+ finder = getattr(self._service, "find_session_for_anchor", None)+ if not callable(finder):+ return None+ return finder(scope_key=user_id, session_anchor=session_anchor)+def bind_agent_session(self,user_id: str,@@ -375,7 +385,12 @@ class SessionsStore:vibe_agent_id=vibe_agent_id,vibe_agent_name=vibe_agent_name,)- self.get_agent_map(user_id, agent_name)[thread_id] = session_id+ # WRITE-ONCE in the in-memory cache too: the map mirrors the (write-once)+ # table, so don't overwrite an existing native — otherwise a later+ # ``save_state`` flush could reintroduce a changed native id.+ agent_map = self.get_agent_map(user_id, agent_name)+ if not agent_map.get(thread_id):+ agent_map[thread_id] = session_idreturn agent_session_iddef bind_agent_session_by_id(diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 498a7d007..bb602b8a9 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -733,6 +733,16 @@ class CommandHandlers(BaseHandler):await self._handle_wechat_resume(context, args)return+ # /resume is only allowed at the SCOPE level (channel/DM), never inside an+ # existing thread/topic: binding there would rebind that thread's session,+ # mutating an existing record. Reject in-thread invocations so resume always+ # opens a FRESH scope-level session (maintainer decision; preserves the+ # native_session_id write-once invariant). WeChat above has no threads.+ if context.thread_id and context.thread_id != context.message_id:+ channel_context = self._get_channel_context(context)+ await im_client.send_message(channel_context, self._t("command.resume.scopeOnly"))+ return+if platform == "discord":interaction = context.platform_specific.get("interaction") if context.platform_specific else Noneif interaction and hasattr(im_client, "open_resume_session_modal"):diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 7c8a0fdac..65c28d30f 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -185,6 +185,23 @@ class MessageHandler(BaseHandler):if isinstance(session_target, dict) and session_target.get("agent_backend")else None)+ # Pin an EXISTING thread to its OWN backend. avibe carries the session+ # row in ``agent_session_target``; IM/CLI turns don't, so look up the+ # thread's (scope, anchor) row and adopt its agent/backend. A thread+ # keeps its backend for life — a scope-level backend change only affects+ # NEWLY created threads, never established ones. Falls through to channel+ # routing when no row exists yet (a new thread).+ if not isinstance(session_target, dict) and not requested_vibe_agent and not session_agent_backend:+ finder = getattr(self.sessions, "find_session_for_anchor", None)+ existing_thread = None+ if callable(finder):+ try:+ existing_thread = finder(session_key, base_session_id)+ except Exception:+ logger.debug("find_session_for_anchor failed; falling back to routing", exc_info=True)+ if existing_thread:+ requested_vibe_agent = existing_thread.get("agent_name") or requested_vibe_agent+ session_agent_backend = existing_thread.get("agent_backend") or session_agent_backendresolve_vibe_agent = getattr(self.controller, "resolve_vibe_agent_for_context", None)vibe_agent = Noneif requested_vibe_agent and callable(resolve_vibe_agent):@@ -312,6 +329,14 @@ class MessageHandler(BaseHandler):# Update session IDs for routing-based agent to match SessionHandlerbase_session_id = f"{base_session_id}:{routing_agent}"composite_key = f"{base_session_id}:{working_path}"+ # 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 = specif is_human:processing_indicator = await self.controller.processing_indicator.start(context, agent_name)diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex 3a4f8025d..ef3b652d6 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -140,6 +140,31 @@ class SessionHandler(BaseHandler):base_id = context.message_id if use_message_id and context.message_id else context.channel_idreturn f"{platform}_{base_id}"+ @staticmethod+ def _reserved_native_session_id(context: MessageContext) -> Optional[str]:+ """Native session id bound to the RESERVED workbench row (by PK).++ avibe dispatch carries it in+ ``platform_specific['agent_session_target']['native_session_id']`` (read+ from the ``agent_sessions`` row). Resuming from this keeps the resume READ+ on the same key as the by-PK bind WRITE, so a restart resumes the same+ native session instead of forking a fresh one. ``None`` for IM/CLI turns+ or before the first native is captured. Only returns the native when the+ reserved row's ``agent_backend`` is Claude — after a header backend switch+ the row still carries the previous backend's native, which Claude can't+ resume. Mirrors ``BaseAgent._reserved_native_session_id``."""+ payload = getattr(context, "platform_specific", None) or {}+ target = payload.get("agent_session_target")+ if not isinstance(target, dict):+ return None+ native = str(target.get("native_session_id") or "").strip()+ if not native:+ return None+ target_backend = str(target.get("agent_backend") or "").strip()+ if target_backend and target_backend != "claude":+ return None+ return native+def _get_context_platform(self, context: MessageContext) -> str:return (context.platform@@ -425,7 +450,20 @@ class SessionHandler(BaseHandler):settings_key = self._get_settings_key(context)session_key = self._get_session_key(context)+ # Resume the native session bound to the RESERVED workbench row (by PK).+ # The bind WRITE (_bind_reserved_workbench_session) records the native on+ # that row by id; the resume READ must read it back from there, because the+ # (session_key, anchor) projection drifts for avibe (its scope/anchor differ+ # from where the native was bound) and a restart would otherwise fork a fresh+ # session and lose context. Skip it for ANY subagent — explicit (its own+ # session resolved below) OR a routing-default subagent (its namespaced base+ # has its own session) — else the first subagent turn after the subagent is+ # enabled would resume the MAIN transcript under the subagent. IM/CLI turns+ # carry no reserved target, so this is a no-op for them.+ routing_subagent = (getattr(context, "platform_specific", None) or {}).get("routing_subagent")stored_claude_session_id = self.sessions.get_claude_session_id(session_key, base_session_id)+ if not subagent_name and not routing_subagent:+ stored_claude_session_id = self._reserved_native_session_id(context) or stored_claude_session_id# Read routing overrides via get_channel_routing which correctly# resolves DM users from the users store (not the stale channels store).@@ -646,6 +684,12 @@ class SessionHandler(BaseHandler):stderr_text = "\n".join(claude_stderr_lines)match = CLAUDE_NO_CONVERSATION_RE.search(stderr_text) or CLAUDE_NO_CONVERSATION_RE.search(str(exc))if match:+ # FAIL LOUD: a session bound to a native id that no longer resumes+ # (cwd changed, expired, or gone) surfaces the error rather than+ # silently starting a fresh session — silent recovery hides the+ # context loss and strands the user in an empty conversation+ # (product decision: no silent fallbacks). The persisted mapping is+ # kept so resuming in the correct cwd still works.raise ClaudeSessionNotFoundError(session_id=match.group(1),working_path=str(working_path),@@ -847,12 +891,39 @@ class SessionHandler(BaseHandler):working_path=working_path,)- # OpenCode session mappings use composite keys that include- # working_path so that cwd changes create new sessions.+ # The anchor is the bare base for every backend. OpenCode no longer+ # folds working_path into the key (the cwd is a per-request param that+ # lives on the ``workdir`` column, not part of the thread identity), so+ # this writer must match the bare-anchor read path in+ # OpenCodeSessionManager.get_or_create_session_id — otherwise a resumed+ # OpenCode session is written under ``base:/cwd`` but the next message+ # looks up ``base`` and forks a different session.mapping_key = base_session_id- if agent == "opencode":- mapping_key = f"{base_session_id}:{working_path}"+ # Resume creates a FRESH session record, never mutates an existing one:+ # clear any prior binding at this anchor first so the bind below INSERTs+ # a new row (new PK) bound to the user-selected native, instead of+ # UPDATE-ing the current row's native_session_id — which the write-once+ # guard would (correctly) drop, silently leaving the thread on its old+ # conversation (Codex P2). A no-op when the anchor is a brand-new+ # confirmation message (channel/DM resume).+ #+ # A thread is ONE session per (scope, anchor). If this anchor already+ # holds a row pinned to a DIFFERENT backend (e.g. a Feishu resume button+ # fired inside an existing thread, which bypasses the scope-only command+ # guard), clear that row too — otherwise the bind below collides with the+ # (scope_id, session_anchor) unique invariant and resume fails after+ # channel routing was already updated (Codex P2).+ finder = getattr(self.sessions, "find_session_for_anchor", None)+ if callable(finder):+ try:+ prior = finder(session_key, mapping_key)+ except Exception:+ prior = None+ prior_agent = str((prior or {}).get("agent_variant") or (prior or {}).get("agent_backend") or "")+ if prior_agent and prior_agent != agent:+ self.sessions.remove_agent_session(session_key, prior_agent, mapping_key)+ self.sessions.remove_agent_session(session_key, agent, mapping_key)self.sessions.set_agent_session_mapping(session_key, agent, mapping_key, session_id)self.sessions.mark_thread_active(user_id, context.channel_id, mapped_thread)except Exception as e:diff --git a/core/services/sessions.py b/core/services/sessions.pyindex 4c88c8f5c..70e1a8861 100644--- a/core/services/sessions.py+++ b/core/services/sessions.py@@ -37,6 +37,7 @@ from typing import Optionalfrom config import pathsfrom storage.workbench_sessions_service import (+ SessionBackendLockedError,archive_session,create_session,get_session,@@ -46,6 +47,7 @@ from storage.workbench_sessions_service import ()__all__ = [+ "SessionBackendLockedError","archive_session","create_session","get_session",diff --git a/docs/plans/session-anchor-backend-pin.md b/docs/plans/session-anchor-backend-pin.mdnew file mode 100644index 000000000..76db8f53a--- /dev/null+++ b/docs/plans/session-anchor-backend-pin.md@@ -0,0 +1,75 @@+# Session model rework — `(scope, anchor)` backend-pin (no workdir)++## Background++`agent_sessions` rows are looked up by `(scope_id, agent_variant, session_anchor)`+with `LIMIT 1`; the only DB-unique key is the PK `id`. Consequences:++- An IM thread's **backend** is resolved from **channel (scope) routing**, then+ used as part of the lookup key — so changing a channel's backend re-routes+ **existing** threads too. Evidence: a real `discord::user::…` anchor has two+ rows, `codex` + `claude`.+- The avibe Chat header can switch an existing session's backend, leaving the+ old `native_session_id` on the row → the new backend fail-louds on a stale+ native (Codex P1 `#3330391462`).++## Confirmed fact (backend source of truth)++When a turn dispatches, the backend is resolved in `MessageHandler` as:+`vibe_agent.backend > agent_sessions.agent_backend > channel routing`+(message_handler.py:201-206), then `agent_service.handle_message(agent_name)`.++So the **actual backend comes from the AGENT** — the session's `agent_name`+resolved to a VibeAgent whose `.backend` is the `agents` table's `backend`+column. `agent_sessions.agent_backend` is only a **fallback** (used when no+agent resolves) → **redundant** for any session that has an agent.++## Target model (maintainer-decided)++- A thread/session is **pinned to one backend** for life. Changing a scope's+ backend only affects **newly created** threads.+- **Unique key = `(scope_id, session_anchor)`** — one row per thread. No+ `workdir`, no `agent_variant` in the key, ever.+- **Backend = the session's AGENT's backend** (`agents.backend` via+ `agent_name`). `agent_sessions.agent_backend` is a redundant denormalized+ copy (kept only as a fallback for agent-less legacy sessions for now).+- Lookup: by `(scope, anchor)`, **take the latest** (`last_active_at`) if+ several.+- `/resume` is scope-level only (done) and creates a fresh record (done).++### OpenCode & workdir++OpenCode currently appends `:working_path` to `session_anchor` to rotate a new+session per cwd. We DROP that: the OpenCode directory is a **per-request** param+(`x-opencode-directory`), so one session per `(scope, anchor)` is reused across+cwds (directory passed each turn). `workdir` is never part of any key. This+supersedes the earlier read-side cwd fix and the opencode-cwd write-path P2.++## Steps++1. **avibe (b)** — forbid switching a session's backend when it already has a+ native. Changing the **agent is allowed as long as the new agent's backend+ equals the current one**; a cross-backend change is rejected.+2. **OpenCode anchor** — `session_anchor` becomes the bare base (no+ `:working_path`); the cwd lives only in the `workdir` column as metadata.+3. **Lookup** — `_find_agent_session_row_id` keys on `(scope_id, session_anchor)`,+ `ORDER BY last_active_at DESC LIMIT 1`; drop `agent_variant` (and never add+ `workdir`).+4. **Backend resolution** — for an **existing** thread, read the backend from+ its `(scope, anchor)` row's agent; channel routing only seeds **new** threads.+5. **Write uniqueness** — binds find-or-create by `(scope, anchor)` only; never+ a second backend for an existing `(scope, anchor)`.+6. **Migration** (alembic) — (i) strip `:cwd` from existing OpenCode anchors+ (`anchor=base`, keep cwd in `workdir`); (ii) dedup `(scope, anchor)` rows+ keeping the most-recently-active; (iii) add a UNIQUE index on+ `(scope_id, session_anchor)`.+7. **Tests + supersession** — addresses Codex P1 `#3330391462`; supersedes the+ opencode-cwd P2 `#3330391467` and reshapes the subagent write P2 `#3330391464`.++## Risks / open++- Central lookup change → blast radius across all platforms + avibe.+- Migration rewrites how existing sessions are keyed (incl. live regression+ data). Write + test on a copy first; never run against a real env unprompted.+- Whether to **drop** `agent_sessions.agent_backend` column (true redundancy) or+ keep as a fallback for agent-less sessions — defer the column drop.diff --git a/modules/agents/base.py b/modules/agents/base.pyindex 0fd6fdade..ad0501b16 100644--- a/modules/agents/base.py+++ b/modules/agents/base.py@@ -148,6 +148,38 @@ class BaseAgent(ABC):return reserved or Nonereturn None+ @staticmethod+ def _reserved_native_session_id(context: Any, backend: Optional[str] = None) -> Optional[str]:+ """The backend-native session id last bound to the RESERVED workbench row.++ avibe dispatch carries it in+ ``platform_specific['agent_session_target']['native_session_id']`` (read+ from the ``agent_sessions`` row by its PK). Resuming from THIS — rather+ than the ``(session_key, anchor)`` projection — keeps the resume READ on+ the same key as the by-PK bind WRITE (``_bind_reserved_workbench_session``),+ so a controller restart resumes the SAME native session instead of forking+ a fresh one and losing context. Empty until the first turn captures a+ native; ``None`` for IM/CLI turns (no reserved target). Mirrors+ ``_reserved_agent_session_id``.++ ``backend``: when given, only return the native if the reserved row's+ ``agent_backend`` matches — after a header backend switch the row still+ carries the previous backend's native, and handing e.g. a Claude id to+ Codex would fail to resume; in that case return ``None`` so the newly+ selected backend starts its own first thread for this Chat."""+ payload = getattr(context, "platform_specific", None) or {}+ target = payload.get("agent_session_target")+ if not isinstance(target, dict):+ return None+ native = str(target.get("native_session_id") or "").strip()+ if not native:+ return None+ if backend:+ target_backend = str(target.get("agent_backend") or "").strip()+ if target_backend and target_backend != backend:+ return None+ return native+@staticmethoddef _pin_agent_session_id(context: Any, agent_session_id: str) -> None:payload = dict(getattr(context, "platform_specific", None) or {})diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 23a9894b3..5690a8d11 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -23,6 +23,22 @@ logger = logging.getLogger(__name__)_CODEX_MANAGED_PROVIDER_IDS = frozenset((MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS))+class CodexResumeUnavailableError(RuntimeError):+ """The Codex thread associated with this session can no longer be resumed.++ Raised instead of silently starting a fresh thread, so the user is told their+ conversation context is gone rather than landing in an empty thread without+ knowing (product decision: no silent fallbacks)."""++ def __init__(self, thread_id: str, detail: str = "") -> None:+ self.thread_id = thread_id+ msg = (+ f"Could not resume the previous Codex conversation ({thread_id}); it may have expired. "+ "Not starting a new conversation to avoid silently losing context — start a new session to continue."+ )+ super().__init__(f"{msg} ({detail})" if detail else msg)++class CodexAgent(BaseAgent):"""Codex CLI integration via persistent ``codex app-server`` subprocess.@@ -155,27 +171,12 @@ class CodexAgent(BaseAgent):except Exception as retry_err:e = retry_err # fall through to normal error handling- if "thread not found" in str(e).lower():- logger.warning(- "Stale Codex thread for session %s, clearing and retrying: %s",- request.base_session_id,- e,- )- self._session_mgr.invalidate_thread(request.base_session_id)- self._clear_thread_developer_instructions(request.base_session_id)- self._turn_registry.clear_session(request.base_session_id)- self.sessions.clear_agent_session_mapping(- request.session_key,- self.name,- request.base_session_id,- )- try:- thread_id = await self._start_or_resume_thread(transport, request)- await self._start_turn(transport, request, thread_id)- return # retry succeeded- except Exception as retry_err:- e = retry_err # fall through to normal error handling-+ # FAIL LOUD on a server-side "thread not found": the conversation is+ # gone, so surface the error instead of silently clearing the+ # mapping and forking a fresh thread (which hid the context loss).+ # The mapping is kept so the failure is consistent until the user+ # explicitly starts a new session (product decision: no silent+ # fallbacks).self._turn_registry.clear_pending_turn_start(request.base_session_id, request)logger.error("Error in Codex handle_message: %s", e, exc_info=True)error_text = f"❌ Codex error: {e}"@@ -586,12 +587,22 @@ class CodexAgent(BaseAgent):request: AgentRequest,) -> str:"""Try to resume a persisted thread, fall back to creating a new one."""- # Check if we have a persisted Codex thread_id from settings_manager+ # Resume the native thread bound to the RESERVED workbench row (by PK): the+ # bind WRITE is by-PK, so the resume READ must read it back from the row, not+ # the (session_key, anchor) projection which drifts for avibe and would fork+ # a fresh thread (context loss) after a restart. Skip it for ANY subagent —+ # explicit (its own thread, distinct base_session_id) OR a routing-default+ # subagent (the namespaced base also has its own thread) — else the first+ # subagent turn would resume the MAIN thread. Falls back to the projection+ # for IM/CLI turns (no reserved target).persisted = self.sessions.get_agent_session_id(request.session_key,request.base_session_id,self.name,)+ _ctx_spec = getattr(getattr(request, "context", None), "platform_specific", None) or {}+ if not getattr(request, "subagent_name", None) and not _ctx_spec.get("routing_subagent"):+ persisted = self._reserved_native_session_id(getattr(request, "context", None), self.name) or persistedif persisted:try:self.bind_agent_session_id(request, persisted)@@ -612,21 +623,37 @@ class CodexAgent(BaseAgent):thread_obj = resp.get("thread")if isinstance(thread_obj, dict):thread_id = thread_obj.get("id", "")- if thread_id:- self._session_mgr.set_thread_id(request.base_session_id, thread_id)- self._remember_thread_developer_instructions(- request.base_session_id,- thread_id,- resume_params.get("developerInstructions"),- )- logger.info("Resumed Codex thread %s for session %s", thread_id, request.base_session_id)- return thread_idexcept Exception as e:if self._is_recoverable_transport_error(e):+ # Transient: reconnect the SAME thread (handled by the outer+ # retry) — not context loss, keep.logger.warning("Failed to resume Codex thread %s due to transport failure: %s", persisted, e)raise- logger.warning("Failed to resume Codex thread %s: %s, starting new", persisted, e)+ from core.agent_auth_service import classify_auth_error++ if classify_auth_error("codex", str(e)):+ # Auth expired/invalid: preserve the ORIGINAL error so+ # handle_message's auth-recovery classifier can surface the+ # reset-OAuth button — don't mask it as a generic resume failure.+ logger.warning("Codex auth error while resuming thread %s: %s", persisted, e)+ raise+ # FAIL LOUD: an associated thread that won't resume (expired/gone) is+ # context loss — surface it rather than silently starting a fresh+ # thread (product decision: no silent fallbacks).+ logger.warning("Failed to resume Codex thread %s: %s", persisted, e)+ raise CodexResumeUnavailableError(persisted) from e+ if not thread_id:+ raise CodexResumeUnavailableError(persisted, detail="thread/resume returned no thread id")+ self._session_mgr.set_thread_id(request.base_session_id, thread_id)+ self._remember_thread_developer_instructions(+ request.base_session_id,+ thread_id,+ resume_params.get("developerInstructions"),+ )+ logger.info("Resumed Codex thread %s for session %s", thread_id, request.base_session_id)+ return thread_id+ # No associated thread yet (genuinely first turn) — start fresh.return await self._start_thread(transport, request)async def _resolve_resume_model_provider_override(diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex eecdb3127..d2e1fa7ee 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -21,7 +21,7 @@ from .client_manager import OpenCodeClientManagerfrom .message_processor import OpenCodeMessageProcessorMixinfrom .poll_loop import OpenCodePollLoopfrom .server import OpenCodeServerManager-from .session import OpenCodeSessionManager+from .session import OpenCodeResumeUnavailableError, OpenCodeSessionManagerlogger = logging.getLogger(__name__)@@ -119,6 +119,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):async def _process_message(self, request: AgentRequest) -> None:run_registered = False+ # Bind early: get_or_create_session_id (below) can raise BEFORE assigning+ # session_id (a transient server error now that get_session raises on+ # non-404), and the error-cleanup paths reference session_id — keep it+ # defined so they can't trip UnboundLocalError (Codex P2).+ session_id = Nonetry:server = await self._get_server()await server.ensure_running()@@ -135,7 +140,28 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):await self._delete_ack(request)await self._session_manager.ensure_working_dir(request.working_path)- session_id = await self._session_manager.get_or_create_session_id(request, server)+ try:+ session_id = await self._session_manager.get_or_create_session_id(request, server)+ except OpenCodeResumeUnavailableError as e:+ # The previous session is gone server-side — surface it, don't silently+ # fork a fresh session and lose context.+ await self.controller.emit_agent_message(request.context, "notify", f"❌ {e}")+ await self._remove_ack_reaction(request)+ return+ except Exception as e:+ # A transient/transport/auth failure while acquiring the session+ # (get_session now raises on non-404, Codex P2): surface it as a+ # terminal error instead of letting it propagate unhandled or be+ # mislabeled as expiry. Route auth errors through the reset-OAuth flow.+ logger.error(f"OpenCode session acquisition failed: {e}", exc_info=True)+ message = f"OpenCode error: {type(e).__name__}: {e}".strip()+ handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ request.context, "opencode", message+ )+ if not handled:+ await self.controller.emit_agent_message(request.context, "notify", message)+ await self._remove_ack_reaction(request)+ returnif not session_id:await self.controller.emit_agent_message(request.context,diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 7feb1041f..961b254b7 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -779,7 +779,16 @@ class OpenCodeServerManager:logger.warning(f"Failed to abort session {session_id}: {e}")return False- async def get_session(self, session_id: str, directory: str) -> Optional[Dict[str, Any]]:+ async def get_session(+ self, session_id: str, directory: str, *, raise_on_error: bool = False+ ) -> Optional[Dict[str, Any]]:+ """Fetch a session. ``None`` means the server reported it does not exist.++ ``raise_on_error``: when True, a transport/connection error is re-raised+ instead of being collapsed into ``None`` — so a caller validating an+ existing session can tell "genuinely gone" (None) from "couldn't reach the+ server" (raise) and not mislabel a transient blip as session expiry.+ """async with self._request_scope():session = await self._get_http_session()try:@@ -789,9 +798,23 @@ class OpenCodeServerManager:) as resp:if resp.status == 200:return await resp.json()+ # Only a genuine "not found" means the session is gone. Other+ # non-200s (transient 500/503, auth 401) are NOT expiry — when a+ # caller is validating an existing session (raise_on_error), raise+ # so it surfaces as a transient/auth failure rather than being+ # mislabeled as session expiry / context loss (Codex P2).+ if resp.status == 404:+ return None+ if raise_on_error:+ error_text = await resp.text()+ raise RuntimeError(+ f"get session {session_id} failed: HTTP {resp.status} {error_text[:300]}"+ )return Noneexcept Exception as e:logger.debug(f"Failed to get session {session_id}: {e}")+ if raise_on_error:+ raisereturn Noneasync def get_available_agents(self, directory: str) -> List[Dict[str, Any]]:diff --git a/modules/agents/opencode/session.py b/modules/agents/opencode/session.pyindex 88ffd68e1..7e8f8d0c2 100644--- a/modules/agents/opencode/session.py+++ b/modules/agents/opencode/session.py@@ -12,10 +12,24 @@ import osimport timefrom typing import Dict, Optional, Tuple-from modules.agents.base import AgentRequest+from modules.agents.base import AgentRequest, BaseAgentfrom .server import OpenCodeServerManager++class OpenCodeResumeUnavailableError(RuntimeError):+ """The OpenCode session associated with this conversation can no longer be+ validated on the server. Raised instead of silently creating a fresh session,+ so the user is told the context is gone (product decision: no silent+ fallbacks)."""++ def __init__(self, session_id: str) -> None:+ self.session_id = session_id+ super().__init__(+ f"Could not resume the previous OpenCode session ({session_id}); it may have expired. "+ "Not creating a new one to avoid silently losing context — start a new session to continue."+ )+logger = logging.getLogger(__name__)@@ -75,7 +89,7 @@ class OpenCodeSessionManager:return target_idreturn None- def ensure_agent_session_id(self, request: AgentRequest, composite_session_key: str) -> Optional[str]:+ def ensure_agent_session_id(self, request: AgentRequest, session_anchor: str) -> Optional[str]:reserved_id = self._reserved_agent_session_id(request)if reserved_id:self._set_request_agent_session_id(request, reserved_id)@@ -83,11 +97,11 @@ class OpenCodeSessionManager:sessions = getattr(self._settings_manager, "sessions", self._settings_manager)ensure = getattr(sessions, "ensure_agent_session_id", None)if callable(ensure):- agent_session_id = ensure(request.session_key, self._agent_name, composite_session_key)+ agent_session_id = ensure(request.session_key, self._agent_name, session_anchor)else:getter = getattr(sessions, "get_agent_session_row_id", None)agent_session_id = (- getter(request.session_key, composite_session_key, self._agent_name)+ getter(request.session_key, session_anchor, self._agent_name)if callable(getter)else None)@@ -97,7 +111,7 @@ class OpenCodeSessionManager:def bind_agent_session_id(self,request: AgentRequest,- composite_session_key: str,+ session_anchor: str,opencode_session_id: str,) -> Optional[str]:sessions = getattr(self._settings_manager, "sessions", self._settings_manager)@@ -122,19 +136,19 @@ class OpenCodeSessionManager:agent_session_id = binder(request.session_key,self._agent_name,- composite_session_key,+ session_anchor,opencode_session_id,)else:sessions.set_agent_session_mapping(request.session_key,self._agent_name,- composite_session_key,+ session_anchor,opencode_session_id,)agent_session_id = Noneif not agent_session_id:- agent_session_id = self.ensure_agent_session_id(request, composite_session_key)+ agent_session_id = self.ensure_agent_session_id(request, session_anchor)else:self._set_request_agent_session_id(request, agent_session_id)return agent_session_id@@ -196,48 +210,30 @@ class OpenCodeSessionManager:async def get_or_create_session_id(self, request: AgentRequest, server: OpenCodeServerManager) -> Optional[str]:"""Get a cached OpenCode session id, or create a new session.- The session mapping key includes working_path so that changing the- working directory (e.g. via the Web UI) automatically creates a new- session instead of reusing the old one anchored to a stale directory.- This mirrors how Claude sessions use composite_key = base:working_path.+ The session anchor is the bare base (the thread's identity), independent+ of the working directory: OpenCode takes the directory as a PER-REQUEST+ param (``x-opencode-directory``), so ONE session per ``(scope, anchor)`` is+ reused across cwds. (New session model: one thread → one session → one+ backend; the cwd is metadata on the ``workdir`` column, never part of the+ key.)"""sessions = getattr(self._settings_manager, "sessions", self._settings_manager)- # Include working_path in the mapping key so cwd changes create new sessions- composite_session_key = f"{request.base_session_id}:{request.working_path}"- self.ensure_agent_session_id(request, composite_session_key)+ anchor = request.base_session_id+ self.ensure_agent_session_id(request, anchor)- session_id = sessions.get_agent_session_id(+ # Prefer the native bound to the RESERVED workbench row (by PK): the by-PK+ # bind WRITE and this resume READ must agree, else avibe forks a fresh+ # session after a restart (context loss). IM/CLI turns (no reserved target)+ # fall back to the (scope, anchor) projection. The server-validation below+ # still handles a reserved native the server no longer knows.+ session_id = BaseAgent._reserved_native_session_id(request.context, self._agent_name) or sessions.get_agent_session_id(request.session_key,- composite_session_key,+ anchor,agent_name=self._agent_name,)- # Legacy fallback: migrate sessions stored under the old key format- # (base_session_id only, without working_path) so existing users- # don't lose session continuity on upgrade.- if not session_id:- legacy_id = sessions.get_agent_session_id(- request.session_key,- request.base_session_id,- agent_name=self._agent_name,- )- if legacy_id:- if await server.get_session(legacy_id, request.working_path):- self.bind_agent_session_id(request, composite_session_key, legacy_id)- logger.info(- "Migrated legacy OpenCode session %s to composite key for %s",- legacy_id,- request.base_session_id,- )- return legacy_id- else:- logger.info(- "Legacy OpenCode session %s no longer valid, will create new session",- legacy_id,- )-if not session_id:try:session_data = await server.create_session(@@ -246,30 +242,24 @@ class OpenCodeSessionManager:)session_id = session_data.get("id")if session_id:- self.bind_agent_session_id(request, composite_session_key, session_id)+ self.bind_agent_session_id(request, anchor, session_id)logger.info(f"Created OpenCode session {session_id} for {request.base_session_id}")except Exception as e:logger.error(f"Failed to create OpenCode session: {e}", exc_info=True)return Nonereturn session_id- existing = await server.get_session(session_id, request.working_path)+ # raise_on_error=True so a transport/connection failure propagates as a+ # transient server error (handled by the normal error path) rather than+ # being mislabeled as expiry — only a genuine "not found" (None) is+ # treated as context loss below.+ existing = await server.get_session(session_id, request.working_path, raise_on_error=True)if existing:- self.bind_agent_session_id(request, composite_session_key, session_id)+ self.bind_agent_session_id(request, anchor, session_id)return session_id- try:- session_data = await server.create_session(- directory=request.working_path,- title=f"vibe-remote:{request.base_session_id}",- )- new_session_id = session_data.get("id")- if new_session_id:- self.bind_agent_session_id(request, composite_session_key, new_session_id)- logger.info(f"Recreated OpenCode session {new_session_id} for {request.base_session_id}")- return new_session_id- except Exception as e:- logger.error(f"Failed to recreate session: {e}", exc_info=True)- return None-- return None+ # FAIL LOUD: an existing mapped session the server says is gone is context+ # loss — surface it rather than silently creating a fresh session (product+ # decision: no silent fallbacks). A fresh session is only created when+ # there was NO prior mapping (handled above).+ raise OpenCodeResumeUnavailableError(session_id)diff --git a/modules/sessions_facade.py b/modules/sessions_facade.pyindex 41224b7cb..23fa82bce 100644--- a/modules/sessions_facade.py+++ b/modules/sessions_facade.py@@ -70,6 +70,16 @@ class SessionsFacade:return Nonereturn getter(user_key, agent_name, thread_id)+ def find_session_for_anchor(self, user_id: Union[int, str], session_anchor: str) -> Optional[dict]:+ """Latest session row for ``(scope, anchor)`` regardless of backend, or+ ``None``. Lets a turn pin a thread to its OWN backend instead of the+ scope's current routing. Read-only; tolerates stores without support."""+ user_key = self._normalize_user_id(user_id)+ finder = getattr(self.sessions_store, "find_session_for_anchor", None)+ if not callable(finder):+ return None+ return finder(user_key, session_anchor)+def ensure_agent_session_id(self,user_id: Union[int, str],diff --git a/storage/alembic/versions/20260601_0011_session_anchor_unique.py b/storage/alembic/versions/20260601_0011_session_anchor_unique.pynew file mode 100644index 000000000..d6003640f--- /dev/null+++ b/storage/alembic/versions/20260601_0011_session_anchor_unique.py@@ -0,0 +1,150 @@+"""pin sessions to (scope, anchor): strip cwd from anchors, dedup, unique index++Realises the new session model where a thread is one session pinned to one+backend, keyed by ``(scope_id, session_anchor)`` (see+docs/plans/session-anchor-backend-pin.md):++1. OpenCode used to fold the working directory into ``session_anchor``+ (``base:/path``) to rotate a session per cwd. The cwd now lives only in the+ ``workdir`` column (it is a per-request OpenCode param), so strip the+ ``:<cwd>`` suffix back to the bare base anchor. Only ABSOLUTE-path suffixes+ are stripped, so claude/codex ``base:<subagent>`` anchors are preserved.+2. With anchors normalised, an IM thread that toggled backends (or had a cwd+ suffix) can have several rows for one ``(scope_id, session_anchor)``. Reattach+ the loser rows' transcripts to the survivor, then keep the most-recently-active+ row per group and delete the rest — a thread is now ONE session.+3. Add a UNIQUE index on ``(scope_id, session_anchor)`` so the invariant holds+ going forward.++NOTE: steps 1-2 rewrite/remove rows and are NOT reversible; ``downgrade`` only+drops the unique index.++Revision ID: 20260601_0011+Revises: 20260531_0010+Create Date: 2026-06-01+"""++from __future__ import annotations++import re++from alembic import op++revision = "20260601_0011"+down_revision = "20260531_0010"+branch_labels = None+depends_on = None++_UNIQUE_INDEX = "uq_agent_sessions_scope_anchor"++# An ABSOLUTE cwd suffix: POSIX ``/...``, Windows drive ``C:\`` / ``C:/``, or UNC+# ``\\...``. Mirrors storage.sessions_service._ABS_CWD_PREFIX (kept inline so the+# migration stays self-contained / independent of app-code drift).+_ABS_CWD_PREFIX = re.compile(r"(/|[A-Za-z]:[\\/]|\\\\)")+++def _split_anchor_cwd(anchor: str) -> tuple[str, str | None]:+ """Split ``base:<abs-cwd>`` into ``(bare_base, cwd)``; passthrough otherwise.++ Splits on the FIRST ``:`` and only strips when the suffix is an absolute path,+ so an OpenCode cwd composite (POSIX/Windows/UNC, even double-nested+ ``base:/p:/p``) collapses to the bare base while a claude/codex subagent name+ (``base:reviewer``) is preserved. First-colon also tolerates the Windows+ drive-letter colon that a last-colon split would mangle into ``base:C``."""+ base, sep, suffix = anchor.partition(":")+ if sep and base and _ABS_CWD_PREFIX.match(suffix):+ return base, suffix+ return anchor, None+++def _tables(bind) -> set[str]:+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}+++# Window expression selecting, for every agent_sessions row, the id that survives+# dedup for its (scope_id, session_anchor) group: the most-recently-active row+# (``last_active_at`` desc, then ``id`` desc as a stable tiebreak). Reused by both+# the message-reattach and the delete below so they agree on the winner.+_DEDUP_ANCHORED = """+ select id,+ row_number() over (+ partition by scope_id, session_anchor+ order by coalesce(last_active_at, '') desc, id desc+ ) as rn,+ first_value(id) over (+ partition by scope_id, session_anchor+ order by coalesce(last_active_at, '') desc, id desc+ ) as keep_id+ from agent_sessions+"""+++def upgrade() -> None:+ bind = op.get_bind()+ tables = _tables(bind)+ if "agent_sessions" not in tables:+ return++ # 1. Strip the ``:<cwd>`` suffix OpenCode folded into the anchor back to the+ # bare base, and move the cwd onto the ``workdir`` column. Done row-by-row in+ # Python (not SQL): only an ABSOLUTE-path suffix is a cwd, and recognising+ # POSIX + Windows (``C:\``) + UNC absolute paths — and tolerating the Windows+ # drive-letter colon — is not expressible in portable SQLite string ops. A+ # claude/codex SUBAGENT anchor (``base:reviewer``) is NOT a path and is+ # preserved; collapsing it would let the dedup below delete the subagent's+ # native binding (lost context). avibe anchors (no ``:``) never match.+ rows = bind.exec_driver_sql("select id, session_anchor, workdir from agent_sessions").fetchall()+ for row_id, anchor, workdir in rows:+ if anchor is None:+ continue+ bare, cwd = _split_anchor_cwd(str(anchor))+ if bare != anchor:+ bind.exec_driver_sql(+ "update agent_sessions set session_anchor = ?, workdir = ? where id = ?",+ (bare, cwd if cwd is not None else workdir, row_id),+ )++ # 2. Reattach transcripts before dedup deletes the loser rows. messages.session_id+ # is FK ``ondelete=SET NULL`` and alembic runs with ``PRAGMA foreign_keys=ON``,+ # so deleting a duplicate session row would orphan its messages and drop them+ # from ``/api/sessions/<kept>/messages``. Point every loser row's messages at+ # the row that survives dedup for the same (scope, anchor) first, so the+ # consolidated session keeps the full visible history.+ if "messages" in tables:+ bind.exec_driver_sql(+ f"""+ update messages+ set session_id = (+ select w.keep_id from ({_DEDUP_ANCHORED}) as w+ where w.id = messages.session_id+ )+ where messages.session_id in (+ select id from ({_DEDUP_ANCHORED}) where rn > 1+ )+ """+ )++ # 3. Dedup: keep the most-recently-active row per (scope_id, session_anchor),+ # delete the rest. A thread is now ONE session regardless of how many+ # backends it cycled through. (Messages were reattached above.)+ bind.exec_driver_sql(+ f"""+ delete from agent_sessions+ where id in (+ select id from ({_DEDUP_ANCHORED}) where rn > 1+ )+ """+ )++ # 4. Enforce uniqueness going forward. (NULL scope_id rows stay distinct under+ # SQLite's NULL semantics — they're orphaned/legacy and not load-bearing.)+ bind.exec_driver_sql(+ f"create unique index if not exists {_UNIQUE_INDEX} "+ "on agent_sessions (scope_id, session_anchor)"+ )+++def downgrade() -> None:+ bind = op.get_bind()+ if "agent_sessions" in _tables(bind):+ bind.exec_driver_sql(f"drop index if exists {_UNIQUE_INDEX}")diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex 0637b1792..1ad1f4111 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -1,6 +1,8 @@from __future__ import annotationsimport json+import logging+import reimport secretsfrom datetime import datetime, timezone, timedeltafrom pathlib import Path@@ -20,6 +22,31 @@ SESSIONS_LAST_ACTIVITY_KEY = "sessions_last_activity"JSON_VALUE_PREFIX = "__json__:"SESSION_ID_ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz"+logger = logging.getLogger(__name__)+++def _set_native_once(conn: Connection, row_id: str, encoded_session_id: str) -> bool:+ """Return True iff a row's ``native_session_id`` should be written now.++ Enforces the write-once invariant: a native session id is bound exactly once+ and never changed. Returns True only when the row currently has no native+ (first bind). If a DIFFERENT native is already stored, keep it and log the+ ignored attempt; if the SAME value is already stored, no rewrite is needed.+ No fallback / fork / subagent / recapture flow may overwrite a stored native.+ """+ current = conn.execute(+ select(agent_sessions.c.native_session_id).where(agent_sessions.c.id == row_id)+ ).scalar_one_or_none()+ current_str = str(current or "")+ if not current_str:+ return True+ if current_str != str(encoded_session_id):+ logger.warning(+ "WRITE-ONCE: native_session_id for session %s is already set; ignoring attempt to change it",+ row_id,+ )+ return False+class SQLiteSessionsService:def __init__(self, db_path: Path):@@ -212,12 +239,17 @@ class SQLiteSessionsService:now=now,)values = {- "native_session_id": encoded_session_id,"workdir": _workdir_from_anchor(str(session_anchor)),"status": "active","updated_at": now,"last_active_at": now,}+ # WRITE-ONCE: a row's native_session_id is bound exactly once and never+ # changed. Set it only when the row has none yet; never let a recapture,+ # fork, subagent, or any fallback overwrite an existing native (product+ # invariant — one agent session ↔ one fixed native).+ if _set_native_once(conn, row_id, encoded_session_id):+ values["native_session_id"] = encoded_session_idif vibe_agent_id is not None:values["agent_id"] = vibe_agent_idif vibe_agent_name is not None:@@ -238,7 +270,6 @@ class SQLiteSessionsService:now = _utc_now_iso()encoded_session_id = encode_session_value(native_session_id)values = {- "native_session_id": encoded_session_id,"status": "active","updated_at": now,"last_active_at": now,@@ -250,6 +281,11 @@ class SQLiteSessionsService:if vibe_agent_name is not None:values["agent_name"] = vibe_agent_namewith self.engine.begin() as conn:+ # WRITE-ONCE: bind the native only if the row has none yet; never let a+ # recapture / fork / subagent overwrite an existing native (see+ # ``_set_native_once`` + bind_agent_session).+ if _set_native_once(conn, str(session_id), encoded_session_id):+ values["native_session_id"] = encoded_session_idresult = conn.execute(agent_sessions.update().where(agent_sessions.c.id == str(session_id))@@ -257,6 +293,37 @@ class SQLiteSessionsService:)return str(session_id) if result.rowcount else None+ def find_session_for_anchor(self, *, scope_key: str, session_anchor: str) -> dict[str, Any] | None:+ """Latest ``agent_sessions`` row for ``(scope, anchor)``, any backend.++ Basis for the new session model: a thread resolves to ONE session via+ ``(scope_id, session_anchor)`` and its backend is pinned to whatever that+ row's agent uses — independent of the scope's current routing. The+ most-recently-active row wins if legacy duplicates for the same+ ``(scope, anchor)`` still exist. Read-only: never creates a scope (unlike+ the bind path), so resolving a brand-new thread returns ``None``."""+ with self.engine.begin() as conn:+ scope_id = _lookup_scope_id(conn, str(scope_key))+ if scope_id is None:+ return None+ row = (+ conn.execute(+ select(agent_sessions)+ .where(agent_sessions.c.scope_id == scope_id)+ .where(agent_sessions.c.session_anchor == str(session_anchor))+ .order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc())+ .limit(1)+ )+ .mappings()+ .first()+ )+ if row is None:+ return None+ data = dict(row)+ if "native_session_id" in data:+ data["native_session_id"] = decode_session_value(data["native_session_id"])+ return data+def delete_agent_session(self,*,@@ -494,6 +561,12 @@ class SQLiteSessionsService:existing_session_ids = self._load_existing_session_ids(conn)used_session_ids: set[str] = set(existing_session_ids.values())+ # (scope_id, bare anchor) -> row id already written in THIS call. A thread+ # is now ONE session per (scope, anchor); legacy JSON can list several+ # backends under one thread, so the FIRST one establishes the row and+ # later duplicates are skipped (write-once), instead of fighting the+ # unique index with a second insert.+ seen_anchor_rows: dict[tuple[str | None, str], str] = {}for scope_key, agent_maps in state.session_mappings.items():if not isinstance(agent_maps, dict):continue@@ -503,23 +576,32 @@ class SQLiteSessionsService:continuefor thread_id, native_session_id in thread_map.items():thread_key = str(thread_id)+ # Normalise OpenCode ``base:/cwd`` composites to the bare+ # anchor (cwd kept on the workdir column) so imported rows+ # match the bare-anchor read path; subagent ``base:<name>``+ # anchors are preserved. Mirrors migration 20260601_0011,+ # which never sees JSON-imported rows (it runs first).+ base_anchor = _base_session_anchor(thread_key)+ dedup_key = (scope_id, base_anchor)+ if dedup_key in seen_anchor_rows:+ continueencoded_session_id = encode_session_value(native_session_id)row_key = _session_row_key(scope_id=scope_id,agent_variant=str(agent_name) or "default",- session_anchor=thread_key,+ session_anchor=base_anchor,native_session_id=encoded_session_id,)row_id = (- _find_agent_session_row_id(+ _find_row_id_for_scope_anchor(conn,scope_id=scope_id,- agent_name=str(agent_name),- session_anchor=thread_key,+ session_anchor=base_anchor,)or existing_session_ids.get(row_key)or _new_session_id(used_session_ids))+ seen_anchor_rows[dedup_key] = row_idstmt = sqlite_insert(agent_sessions).values(id=row_id,scope_id=scope_id,@@ -527,7 +609,7 @@ class SQLiteSessionsService:agent_variant=str(agent_name) or "default",model=None,reasoning_effort=None,- session_anchor=thread_key,+ session_anchor=base_anchor,workdir=_workdir_from_anchor(thread_key),native_session_id=encoded_session_id,title=None,@@ -766,6 +848,25 @@ class SQLiteSessionsService:return _json_loads(value, None)+def _lookup_scope_id(conn: Connection, scope_key: str) -> str | None:+ """Read-only scope-id resolution. Like ``resolve_scope_from_legacy_key`` but+ NEVER upserts a scope — for read paths that must not create one."""+ raw = str(scope_key or "")+ parts = raw.split("::")+ if len(parts) >= 3 and parts[1] in {"channel", "user", "platform", "project"}:+ platform, native_id = parts[0], "::".join(parts[2:])+ else:+ platform, native_id = _split_scoped_key(scope_key)+ if platform is None:+ platform = "unknown"+ if not platform or not native_id:+ return None+ found = conn.execute(+ select(scopes.c.id).where(scopes.c.platform == platform, scopes.c.native_id == native_id).limit(1)+ ).scalar_one_or_none()+ return str(found) if found is not None else None++def resolve_scope_from_legacy_key(conn: Connection, scope_key: str, *, now: str) -> str | None:raw_scope_key = str(scope_key or "")parts = raw_scope_key.split("::")@@ -886,6 +987,28 @@ def _find_agent_session_row_id().scalar_one_or_none()+def _find_row_id_for_scope_anchor(+ conn: Connection,+ *,+ scope_id: str | None,+ session_anchor: str,+) -> str | None:+ """Latest row id for ``(scope_id, session_anchor)`` regardless of backend.++ The dedup key for the new ``(scope, anchor)`` unique invariant. The+ variant-filtered ``_find_agent_session_row_id`` is wrong for the import path:+ two legacy backends under one thread (``claude`` + ``codex`` at the same bare+ anchor) would each miss and INSERT, colliding on the unique index. Matching by+ (scope, anchor) only lets the import collapse them onto one row instead."""+ return conn.execute(+ select(agent_sessions.c.id)+ .where(agent_sessions.c.scope_id == scope_id)+ .where(agent_sessions.c.session_anchor == str(session_anchor))+ .order_by(agent_sessions.c.last_active_at.desc(), agent_sessions.c.id.desc())+ .limit(1)+ ).scalar_one_or_none()++def _insert_agent_session_row(conn: Connection,*,@@ -1049,6 +1172,34 @@ def _workdir_from_anchor(anchor: str) -> str | None:return suffix or None+# An ABSOLUTE cwd suffix: POSIX ``/...``, Windows drive ``C:\`` / ``C:/``, or UNC+# ``\\...``. OpenCode's cwd is always absolute (``get_cwd`` -> ``os.path.abspath``),+# so this cleanly separates a cwd composite from a claude/codex subagent name.+_ABS_CWD_PREFIX = re.compile(r"(/|[A-Za-z]:[\\/]|\\\\)")+++def _base_session_anchor(anchor: str) -> str:+ """Strip an OpenCode ``base:<abs-cwd>`` suffix back to the bare base anchor.++ The cwd now lives only on the ``workdir`` column; the anchor is the bare thread+ identity. Split on the FIRST ``:`` and drop the suffix iff it is an absolute+ path — POSIX ``/...``, Windows ``C:\\...`` / ``C:/...``, or UNC ``\\\\...``. A+ non-path suffix is a claude/codex subagent name (``base:reviewer``) and is+ preserved. Splitting on the first colon also collapses a double-nested cwd+ (``base:/p:/p``) in one pass and tolerates the drive-letter colon in Windows+ paths (which a last-colon split would mangle into ``base:C``).++ The Python twin of the alembic ``session_anchor`` strip (migration+ 20260601_0011) for the legacy-JSON import path: ``ensure_sqlite_state`` runs+ migrations on an empty table and only then imports ``sessions.json``, so the+ import writer must normalise legacy rows itself or it persists composite+ anchors the bare-anchor read path can't find."""+ base, sep, suffix = str(anchor).partition(":")+ if sep and base and _ABS_CWD_PREFIX.match(suffix):+ return base+ return str(anchor)++def _json_dumps(value: Any) -> str:return json.dumps(value, ensure_ascii=False, separators=(",", ":"))diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 5804547d9..29dec3186 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -206,6 +206,23 @@ def create_session(return get_session(conn, session_id)+class SessionBackendLockedError(Exception):+ """Raised when a caller tries to switch the backend of a session that already+ has a native conversation. A session is pinned to its backend for life: the+ native can only be resumed by the backend that created it, so switching would+ strand it and silently lose context. Changing the agent WITHIN the same+ backend stays allowed."""++ def __init__(self, *, session_id: str, current_backend: Optional[str], requested_backend: Optional[str]):+ self.session_id = session_id+ self.current_backend = current_backend+ self.requested_backend = requested_backend+ super().__init__(+ f"Session {session_id} is bound to backend "+ f"'{current_backend}' and cannot switch to '{requested_backend}'."+ )++def update_session(conn: Connection,session_id: str,@@ -219,11 +236,36 @@ def update_session(reasoning_effort: Any = _UNSET,) -> dict[str, Any]:existing = conn.execute(- select(agent_sessions.c.id).where(agent_sessions.c.id == session_id)- ).scalar_one_or_none()+ select(+ agent_sessions.c.id,+ agent_sessions.c.agent_backend,+ agent_sessions.c.native_session_id,+ ).where(agent_sessions.c.id == session_id)+ ).first()if existing is None:raise LookupError(f"Session not found: {session_id}")+ # Backend is pinned once the session has a real native conversation AND a+ # concrete backend recorded. Allow changing the agent/model/effort within the+ # SAME backend; reject a switch to a DIFFERENT backend (it would strand the+ # native and lose context). Two transitions are NOT a switch and must be+ # allowed: (a) no native yet (empty native_session_id) — backend is still free;+ # (b) a plain Workbench chat created with an EMPTY agent_backend — its first+ # real backend selection from the chat header is the initial pin, not a switch+ # away from a concrete backend (Codex P2: otherwise the chat can't pick an+ # agent/model after its first reply).+ if (+ agent_backend is not None+ and existing.native_session_id+ and str(existing.agent_backend or "")+ and str(agent_backend) != str(existing.agent_backend or "")+ ):+ raise SessionBackendLockedError(+ session_id=session_id,+ current_backend=existing.agent_backend,+ requested_backend=agent_backend,+ )+values: dict[str, Any] = {"updated_at": _utc_now_iso()}if title is not None:cleaned = title.strip()diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex a6fe8dee7..535cd6d13 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -48,6 +48,25 @@ class _BaseAgent:session_id = Nonereturn session_id or self.ensure_agent_session_id(request, session_anchor=anchor)+ @staticmethod+ def _reserved_native_session_id(context, backend=None):+ # Mirrors the real BaseAgent helper: native session bound to the reserved+ # workbench row (by PK), carried in agent_session_target; gated by backend+ # match. None for the IM-style turns these tests exercise (no reserved+ # target).+ payload = getattr(context, "platform_specific", None) or {}+ target = payload.get("agent_session_target")+ if not isinstance(target, dict):+ return None+ native = str(target.get("native_session_id") or "").strip()+ if not native:+ return None+ if backend:+ target_backend = str(target.get("agent_backend") or "").strip()+ if target_backend and target_backend != backend:+ return None+ return native+setattr(_base_module, "BaseAgent", _BaseAgent)@@ -110,6 +129,7 @@ assert _SPEC is not None and _SPEC.loader is not None_MODULE = importlib.util.module_from_spec(_SPEC)_SPEC.loader.exec_module(_MODULE)CodexAgent = _MODULE.CodexAgent+CodexResumeUnavailableError = _MODULE.CodexResumeUnavailableErrorfor name, module in _saved_modules.items():if module is None:@@ -553,6 +573,7 @@ class _HandleMessageTurnRegistry:self.active_turn = active_turnself.remembered_requests = []self.cleared_sessions = []+ self.cleared_pending_starts = []def remember_request(self, request):self.remembered_requests.append(request)@@ -563,6 +584,10 @@ class _HandleMessageTurnRegistry:def has_pending_turn_start(self, base_session_id: str):return False+ def clear_pending_turn_start(self, base_session_id: str, request=None):+ # Mirrors TurnRegistry.clear_pending_turn_start; the error path calls it.+ self.cleared_pending_starts.append((base_session_id, request))+def clear_session(self, base_session_id: str):self.cleared_sessions.append(base_session_id)@@ -633,7 +658,10 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):)agent._session_locks = {}agent._turn_registry = _HandleMessageTurnRegistry(active_turn="turn-1")- agent._event_handler = SimpleNamespace(clear_pending=Mock(return_value=SimpleNamespace()))+ agent._event_handler = SimpleNamespace(+ clear_pending=Mock(return_value=SimpleNamespace()),+ _release_stream_turn=Mock(),+ )agent._remove_ack_reaction = AsyncMock()agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())agent._get_or_create_transport = AsyncMock(return_value=transport)@@ -1134,6 +1162,96 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(method, "thread/resume")self.assertEqual(params["modelProvider"], "openai-managed")+ async def test_resume_thread_prefers_reserved_native_for_main_turn(self):+ # avibe main turn: resume the native bound to the reserved row (by PK),+ # NOT the (session_key, anchor) projection — the restart-resume fix.+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-projection"))+ agent.bind_agent_session_id = Mock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)+ request = SimpleNamespace(+ working_path="/tmp/work",+ context=SimpleNamespace(+ platform="avibe",+ platform_specific={+ "agent_session_target": {+ "id": "ses-1",+ "native_session_id": "native-reserved",+ "session_anchor": "ses-1",+ }+ },+ ),+ base_session_id="ses-1",+ session_key="avibe::ses-1",+ subagent_name=None,+ )+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"id": "native-reserved"}))++ thread_id = await agent._start_or_resume_thread(transport, request)++ self.assertEqual(thread_id, "native-reserved")+ method, params = transport.send_request.await_args_list[0].args+ self.assertEqual(method, "thread/resume")+ self.assertEqual(params["threadId"], "native-reserved")++ async def test_resume_thread_skips_reserved_native_for_explicit_subagent(self):+ # Explicit per-turn subagent: it has its own thread; must NOT resume the+ # reserved MAIN native.+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-subagent"))+ agent.bind_agent_session_id = Mock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)+ request = SimpleNamespace(+ working_path="/tmp/work",+ context=SimpleNamespace(+ platform="avibe",+ platform_specific={+ "agent_session_target": {+ "id": "ses-1",+ "native_session_id": "native-reserved",+ "session_anchor": "ses-1",+ }+ },+ ),+ base_session_id="ses-1:reviewer",+ session_key="avibe::ses-1",+ subagent_name="reviewer",+ )+ transport = SimpleNamespace(send_request=AsyncMock(return_value={"id": "thread-subagent"}))++ thread_id = await agent._start_or_resume_thread(transport, request)++ self.assertEqual(thread_id, "thread-subagent")+ method, params = transport.send_request.await_args_list[0].args+ self.assertEqual(params["threadId"], "thread-subagent")++ async def test_resume_thread_fails_loud_on_non_transport_resume_error(self):+ # An associated thread that won't resume for a non-transport reason+ # (expired/gone) must RAISE, not silently start a fresh thread.+ agent = object.__new__(CodexAgent)+ agent.sessions = SimpleNamespace(get_agent_session_id=Mock(return_value="thread-old"))+ agent.bind_agent_session_id = Mock()+ agent._session_mgr = SimpleNamespace(set_thread_id=Mock())+ agent._start_thread = AsyncMock()+ agent._build_thread_developer_instructions = Mock(return_value=None)+ agent._resolve_resume_model_provider_override = AsyncMock(return_value=None)+ request = SimpleNamespace(+ working_path="/tmp/work",+ context=SimpleNamespace(platform="slack", platform_specific={}),+ base_session_id="session-1",+ session_key="slack::channel::C1",+ subagent_name=None,+ )+ transport = SimpleNamespace(send_request=AsyncMock(side_effect=RuntimeError("thread is gone")))++ with self.assertRaises(CodexResumeUnavailableError):+ await agent._start_or_resume_thread(transport, request)+ agent._start_thread.assert_not_awaited() # must NOT silently fork a fresh thread+async def test_resume_thread_preserves_unmanaged_cross_provider_session(self):agent = object.__new__(CodexAgent)agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.pyindex 1383e4c51..a55388ad8 100644--- a/tests/test_core_services_sessions.py+++ b/tests/test_core_services_sessions.py@@ -55,6 +55,8 @@ def test_public_surface_is_stable():# Legacy IM-style reservation helpers added in C2 for the CLI:"reserve_agent_session","reserve_private_agent_session",+ # Backend-pin guard raised by update_session on a cross-backend switch:+ "SessionBackendLockedError",}assert set(sessions_service.__all__) == expectedfor name in expected:@@ -169,3 +171,56 @@ def test_update_session_present_null_clears_model_and_effort(isolated_state):assert kept["model"] == "claude-sonnet-4-6"assert kept["reasoning_effort"] == "low"assert kept["title"] == "renamed"+++def test_update_session_pins_backend_after_native_bound(isolated_state):+ """A session is locked to its backend once it has a native conversation:+ same-backend agent/model changes are allowed; a cross-backend switch raises+ SessionBackendLockedError. A session with no native yet can still switch+ freely (the avibe header picks the backend before the first turn)."""+ from sqlalchemy import update as sa_update++ from storage.models import agent_sessions++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(+ conn, scope_id=scope_id, agent_backend="claude", agent_name="claude"+ )["id"]+ # No native yet → switching backend is allowed.+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")+ # Bind a native → backend is now pinned.+ conn.execute(+ sa_update(agent_sessions).where(agent_sessions.c.id == sid).values(native_session_id="nat-1")+ )+ # Same-backend change (different agent / model) is still allowed.+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex-pro", model="o3")+ # Cross-backend switch is rejected.+ with pytest.raises(sessions_service.SessionBackendLockedError):+ sessions_service.update_session(conn, sid, agent_backend="claude", agent_name="claude")+++def test_update_session_blank_backend_takes_first_concrete_pin(isolated_state):+ """A plain Workbench chat is created with an EMPTY agent_backend. After its+ first turn binds a native, selecting the real agent in the chat header is the+ INITIAL pin, not a cross-backend switch — it must be allowed, then lock the+ session to that backend going forward (Codex P2: otherwise the chat can't pick+ an agent/model after its first reply)."""+ from sqlalchemy import update as sa_update++ from storage.models import agent_sessions++ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_avibe_scope(conn)+ sid = sessions_service.create_session(conn, scope_id=scope_id, agent_backend="")["id"]+ conn.execute(+ sa_update(agent_sessions).where(agent_sessions.c.id == sid).values(native_session_id="nat-blank")+ )+ # Empty -> concrete is the first pin, allowed even with a native bound.+ sessions_service.update_session(conn, sid, agent_backend="codex", agent_name="codex")+ assert sessions_service.get_session(conn, sid)["agent_backend"] == "codex"+ # Now pinned: a different backend is rejected.+ with pytest.raises(sessions_service.SessionBackendLockedError):+ sessions_service.update_session(conn, sid, agent_backend="claude", agent_name="claude")diff --git a/tests/test_opencode_session_manager.py b/tests/test_opencode_session_manager.pyindex 845ab9ac9..4d6cee803 100644--- a/tests/test_opencode_session_manager.py+++ b/tests/test_opencode_session_manager.py@@ -4,8 +4,10 @@ import asynciofrom types import SimpleNamespacefrom unittest.mock import AsyncMock, Mock+import pytest+from modules.agents.base import AgentRequest-from modules.agents.opencode.session import OpenCodeSessionManager+from modules.agents.opencode.session import OpenCodeResumeUnavailableError, OpenCodeSessionManagerfrom modules.im import MessageContextfrom modules.sessions_facade import SessionsFacade@@ -35,15 +37,17 @@ def test_opencode_reused_session_attaches_agent_session_id() -> None:assert session_id == "oc-session-1"assert request.context.platform_specific["agent_session_id"] == "sesk8m4q2p7x"+ # Anchor is the bare base now (cwd is per-request, not part of the key) —+ # one OpenCode session per (scope, anchor), reused across working dirs.sessions.ensure_agent_session_id.assert_called_once_with("slack::channel::C1","opencode",- "base-1:/repo",+ "base-1",)sessions.bind_agent_session.assert_called_once_with("slack::channel::C1","opencode",- "base-1:/repo",+ "base-1","oc-session-1",)@@ -78,6 +82,81 @@ def test_opencode_reserved_agent_session_id_is_not_replaced() -> None:)+def test_opencode_resumes_reserved_native_session_id() -> None:+ """When the reserved workbench row carries a native session id, resume from+ THAT (by-PK), NOT the (session_key, anchor) projection. This is the restart-+ resume fix: the by-PK bind WRITE and the resume READ must agree, else avibe+ forks a fresh OpenCode session after a controller restart and loses context."""+ sessions = SimpleNamespace(+ # If this projection lookup were used, resume would pick the WRONG (or no)+ # session — the test asserts it is never consulted.+ get_agent_session_id=Mock(return_value="oc-from-projection"),+ ensure_agent_session_id=Mock(return_value="ses-different"),+ bind_agent_session=Mock(return_value="ses-different"),+ bind_agent_session_by_id=Mock(return_value="ses-reserved"),+ )+ manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")+ server = SimpleNamespace(get_session=AsyncMock(return_value={"id": "oc-native-reserved"}))+ request = _request()+ request.context.platform_specific = {+ "agent_session_id": "ses-reserved",+ "agent_session_target": {"id": "ses-reserved", "native_session_id": "oc-native-reserved"},+ }++ session_id = asyncio.run(manager.get_or_create_session_id(request, server))++ assert session_id == "oc-native-reserved"+ # The reserved native short-circuits the projection lookup entirely.+ sessions.get_agent_session_id.assert_not_called()+ sessions.ensure_agent_session_id.assert_not_called()+ # Validated against the server, then re-bound to the reserved row by PK.+ server.get_session.assert_awaited_once_with("oc-native-reserved", "/repo", raise_on_error=True)+ sessions.bind_agent_session_by_id.assert_called_once_with(+ "ses-reserved",+ "oc-native-reserved",+ workdir="/repo",+ vibe_agent_id=None,+ vibe_agent_name=None,+ )+++def test_opencode_fails_loud_when_existing_session_invalid() -> None:+ """An existing mapped session that no longer validates on the server must+ RAISE (context loss), not silently create a fresh session and hide it."""+ sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value="oc-existing"),+ ensure_agent_session_id=Mock(return_value="ses-1"),+ bind_agent_session=Mock(return_value="ses-1"),+ )+ manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")+ create = AsyncMock(return_value={"id": "oc-new"})+ server = SimpleNamespace(get_session=AsyncMock(return_value=None), create_session=create)+ request = _request()++ with pytest.raises(OpenCodeResumeUnavailableError):+ asyncio.run(manager.get_or_create_session_id(request, server))+ create.assert_not_awaited() # must NOT silently recreate+++def test_opencode_transport_error_during_validation_is_not_mislabeled_expiry() -> None:+ """A transport/connection error validating an existing session must propagate+ as-is (transient), NOT be converted into a session-expiry error."""+ sessions = SimpleNamespace(+ get_agent_session_id=Mock(return_value="oc-existing"),+ ensure_agent_session_id=Mock(return_value="ses-1"),+ bind_agent_session=Mock(return_value="ses-1"),+ )+ manager = OpenCodeSessionManager(SimpleNamespace(sessions=sessions), "opencode")+ server = SimpleNamespace(+ get_session=AsyncMock(side_effect=ConnectionError("server down")),+ create_session=AsyncMock(),+ )+ request = _request()++ with pytest.raises(ConnectionError):+ asyncio.run(manager.get_or_create_session_id(request, server))++def test_session_facade_ensure_fallback_does_not_clear_existing_native_session() -> None:class _LegacyStore:def __init__(self):diff --git a/tests/test_reserved_native_session_id.py b/tests/test_reserved_native_session_id.pynew file mode 100644index 000000000..a40922965--- /dev/null+++ b/tests/test_reserved_native_session_id.py@@ -0,0 +1,56 @@+"""Contract for the reserved-native resume helper across backends.++Claude (``SessionHandler``) and Codex (``BaseAgent``) resume from the native+session bound to the RESERVED workbench row (by PK) via+``_reserved_native_session_id``. This pins the helper's behavior so the resume+READ stays on the same key as the by-PK bind WRITE — the fix for "restart loses+context". Both are static, so no heavy SDK/controller setup is needed.+"""++from __future__ import annotations++import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.handlers.session_handler import SessionHandler+from modules.agents.base import BaseAgent++# Both helpers read the same payload path, so one parametrized suite covers them.+HELPERS = [BaseAgent._reserved_native_session_id, SessionHandler._reserved_native_session_id]+++def _ctx(platform_specific):+ return SimpleNamespace(platform_specific=platform_specific)++[email protected]("helper", HELPERS)+def test_returns_reserved_native_when_present(helper):+ ctx = _ctx({"agent_session_target": {"id": "ses-1", "native_session_id": "native-abc"}})+ assert helper(ctx) == "native-abc"++[email protected]("helper", HELPERS)+def test_strips_whitespace(helper):+ ctx = _ctx({"agent_session_target": {"id": "ses-1", "native_session_id": " native-abc "}})+ assert helper(ctx) == "native-abc"++[email protected]("helper", HELPERS)+def test_none_when_no_reserved_target(helper):+ # IM/CLI turns carry no reserved target → fall back to the projection lookup.+ assert helper(_ctx({})) is None+ assert helper(_ctx(None)) is None+ assert helper(SimpleNamespace(platform_specific=None)) is None++[email protected]("helper", HELPERS)+def test_none_when_native_absent_or_empty(helper):+ # First turn of a session: reserved row exists but no native captured yet.+ assert helper(_ctx({"agent_session_target": {"id": "ses-1"}})) is None+ assert helper(_ctx({"agent_session_target": {"id": "ses-1", "native_session_id": ""}})) is None+ assert helper(_ctx({"agent_session_target": {"id": "ses-1", "native_session_id": " "}})) is Nonediff --git a/tests/test_resume_session.py b/tests/test_resume_session.pyindex 8be46bc57..b3f0ba6ad 100644--- a/tests/test_resume_session.py+++ b/tests/test_resume_session.py@@ -20,6 +20,13 @@ class _StubSettingsManager:self.set_calls = []self.mark_calls = []self.routing_calls = []+ self.remove_calls = []++ def remove_agent_session(self, settings_key, agent_name, thread_id):+ # Resume clears any prior binding at the anchor before re-binding so the+ # bind creates a fresh record (never mutates an existing native).+ self.remove_calls.append((settings_key, agent_name, thread_id))+ return Falsedef set_agent_session_mapping(self, settings_key, agent_name, thread_id, session_id):self.set_calls.append((settings_key, agent_name, thread_id, session_id))@@ -116,6 +123,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):im_client = _StubIMClient()ctrl = _StubController()ctrl.init_minimal(im_client, settings, _StubConfig())+ ctrl.im_client.should_use_thread_for_reply = lambda: Truectrl.native_session_service = _StubNativeSessionService([NativeResumeSession(@@ -150,11 +158,63 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):self.assertIn("The latest Claude answer ends with a concise handoff", im_client.messages[0][2])self.assertIn("Reply in this thread", im_client.messages[1][2])+ async def test_handle_resume_session_submission_clears_prior_backend_at_anchor(self):+ # A resume landing on an anchor already pinned to a DIFFERENT backend must+ # clear that row first, or the bind collides with the (scope_id,+ # session_anchor) unique invariant (e.g. a Feishu resume button fired+ # inside an existing thread, bypassing the scope-only command guard). (Codex P2.)+ settings = _StubSettingsManager()+ settings.find_session_for_anchor = lambda settings_key, anchor: {+ "agent_variant": "claude",+ "agent_backend": "claude",+ }+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig())+ ctrl.im_client.should_use_thread_for_reply = lambda: True+ ctrl.agent_service = type("A", (), {"agents": {"opencode": object(), "claude": object()}})()++ await ctrl.session_handler.handle_resume_session_submission(+ user_id="U123",+ channel_id="C111",+ thread_id="169999.123",+ agent="opencode",+ session_id="oc_sess",+ )++ anchor = "slack_169999.123"+ # The prior claude row at the anchor was cleared before binding opencode.+ self.assertIn(("slack::C111", "claude", anchor), settings.remove_calls)+ self.assertEqual(settings.set_calls, [("slack::C111", "opencode", anchor, "oc_sess")])++ async def test_handle_resume_session_submission_replaces_record_not_mutates(self):+ # Resume must create a FRESH record at the anchor (clear + re-bind), never+ # mutate the existing native in place — otherwise the native_session_id+ # write-once guard would silently drop the rebind (Codex P2).+ settings = _StubSettingsManager()+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig())+ ctrl.im_client.should_use_thread_for_reply = lambda: True++ await ctrl.session_handler.handle_resume_session_submission(+ user_id="U123",+ channel_id="C111",+ thread_id="169999.123",+ agent="claude",+ session_id="sess_new",+ )++ # The anchor is cleared first, then re-bound to the user-selected native.+ self.assertEqual(settings.remove_calls, [("slack::C111", "claude", "slack_169999.123")])+ self.assertEqual(settings.set_calls, [("slack::C111", "claude", "slack_169999.123", "sess_new")])+async def test_handle_resume_session_submission_dm_falls_back_to_channel(self):settings = _StubSettingsManager()im_client = _StubIMClient()ctrl = _StubController()ctrl.init_minimal(im_client, settings, _StubConfig())+ ctrl.im_client.should_use_thread_for_reply = lambda: Trueawait ctrl.session_handler.handle_resume_session_submission(user_id="U999",@@ -389,10 +449,12 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):])+ # Scope-level invocation (no thread): /resume is only allowed at the+ # channel level, so the modal anchors on the host message.ctx = MessageContext(user_id="U1",channel_id="CCHAN",- thread_id="TH1",+ thread_id=None,message_id="TS1",platform_specific={"trigger_id": "TRIG"},)@@ -402,10 +464,34 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(im_client.messages, [])self.assertEqual(len(im_client.resume_calls), 1)trigger_id, sessions, channel_id, thread_id, host_ts = im_client.resume_calls[0]- self.assertEqual((trigger_id, channel_id, thread_id, host_ts), ("TRIG", "CCHAN", "TH1", "TS1"))+ self.assertEqual((trigger_id, channel_id, thread_id, host_ts), ("TRIG", "CCHAN", "TS1", "TS1"))self.assertEqual([item.native_session_id for item in sessions], ["thread_123"])self.assertEqual(ctrl.native_session_service.calls, [("/Users/cyh/vibe-remote", 100)])+ async def test_handle_resume_in_existing_thread_is_rejected(self):+ # /resume is scope-level only: invoking it inside an existing thread must be+ # rejected (no modal/menu) so it can never rebind that thread's session.+ settings = _StubSettingsManager()+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig(platform="slack"))++ ctx = MessageContext(+ user_id="U1",+ channel_id="CCHAN",+ thread_id="TH1",+ message_id="TS1",+ platform="slack",+ platform_specific={"trigger_id": "TRIG"},+ )++ await ctrl.command_handler.handle_resume(ctx)++ # No modal opened; a scope-only explanation is sent instead.+ self.assertEqual(im_client.resume_calls, [])+ self.assertEqual(len(im_client.messages), 1)+ self.assertIn("channel level", im_client.messages[0][2])+async def test_command_handlers_handle_resume_filters_disabled_backends_before_modal(self):settings = _StubSettingsManager()im_client = _StubIMClient()@@ -441,7 +527,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):ctx = MessageContext(user_id="U1",channel_id="CCHAN",- thread_id="TH1",+ thread_id=None,message_id="TS1",platform="slack",platform_specific={"trigger_id": "TRIG"},@@ -463,7 +549,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):ctx = MessageContext(user_id="U1",channel_id="CCHAN",- thread_id="TH1",+ thread_id=None,message_id="TS1",platform="slack",platform_specific={},@@ -497,10 +583,12 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):])+ # Scope-level invocation (no topic/thread): resume is only allowed at the+ # group/channel level, so the modal anchors on the host message.ctx = MessageContext(user_id="U1",channel_id="TGCHAN",- thread_id="TOPIC1",+ thread_id=None,message_id="MSG1",platform="telegram",platform_specific={"is_dm": False},@@ -512,7 +600,7 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(len(im_client.resume_calls), 1)trigger_id, sessions, channel_id, thread_id, host_ts = im_client.resume_calls[0]self.assertEqual(trigger_id, ctx)- self.assertEqual((channel_id, thread_id, host_ts), ("TGCHAN", "TOPIC1", "MSG1"))+ self.assertEqual((channel_id, thread_id, host_ts), ("TGCHAN", "MSG1", "MSG1"))self.assertEqual([item.native_session_id for item in sessions], ["session_telegram_123"])self.assertEqual(ctrl.native_session_service.calls, [("/Users/cyh/vibe-remote", 25)])diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.pyindex 35ee021e3..ca8c69f97 100644--- a/tests/test_sqlite_sessions_store.py+++ b/tests/test_sqlite_sessions_store.py@@ -59,7 +59,10 @@ def test_sessions_store_uses_sqlite_without_rewriting_legacy_json(tmp_path: Pathreloaded = SessionsStore(sessions_path)try:- assert reloaded.state.session_mappings["slack::C123"]["opencode"]["slack_123.456:/repo"] == "session-old"+ # Legacy OpenCode ``base:/cwd`` composite is normalised to the bare anchor+ # on import (cwd -> workdir column), matching the bare-anchor read path; the+ # native id is preserved. (Codex P2: composite anchors were unreadable.)+ assert reloaded.state.session_mappings["slack::C123"]["opencode"]["slack_123.456"] == "session-old"assert reloaded.state.active_polls["oc-1"]["settings_key"] == "C123"assert reloaded.state.active_polls["oc-1"]["platform"] == "slack"assert reloaded.get_active_poll("oc-2") is not None@@ -256,6 +259,81 @@ def test_sqlite_sessions_service_binds_reserved_agent_session_by_id(tmp_path: Paservice.close()+def test_find_session_for_anchor_returns_latest_regardless_of_backend(tmp_path: Path) -> None:+ """The new session model resolves a thread to ONE session by (scope, anchor),+ independent of backend. With legacy multi-backend rows for one anchor, the+ most-recently-active wins. Read-only — an unknown scope is never created."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ service.bind_agent_session(+ scope_key="slack::C123",+ agent_name="claude",+ session_anchor="slack_T1",+ native_session_id="claude-native",+ )+ service.bind_agent_session(+ scope_key="slack::C123",+ agent_name="codex",+ session_anchor="slack_T1",+ native_session_id="codex-native",+ )+ row = service.find_session_for_anchor(scope_key="slack::C123", session_anchor="slack_T1")+ assert row is not None+ # Most-recently-active row (codex, bound last) wins, regardless of backend.+ assert row["agent_backend"] == "codex"+ assert row["native_session_id"] == "codex-native"+ # Read-only: an unknown scope is never created.+ assert service.find_session_for_anchor(scope_key="slack::CNONE", session_anchor="slack_T1") is None+ finally:+ service.close()+++def test_native_session_id_is_write_once_by_id(tmp_path: Path) -> None:+ """Once a row's native_session_id is bound, a second bind (fork / recapture /+ subagent / any fallback) must NOT overwrite it — the table is write-once."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ reserved_id = service.reserve_agent_session(+ scope_key="slack::channel::C123",+ agent_backend="claude",+ session_anchor="slack_C123",+ agent_name="claude",+ )+ assert reserved_id is not None+ assert service.bind_agent_session_by_id(session_id=reserved_id, native_session_id="native-1") == reserved_id+ # A second bind with a DIFFERENT native must be ignored (kept = native-1).+ service.bind_agent_session_by_id(session_id=reserved_id, native_session_id="native-2")+ assert service.get_agent_session_by_id(reserved_id)["native_session_id"] == "native-1"+ finally:+ service.close()+++def test_native_session_id_is_write_once_by_anchor(tmp_path: Path) -> None:+ """bind_agent_session (scope+anchor path) is also write-once."""+ db_path = tmp_path / "vibe.sqlite"+ service = SQLiteSessionsService(db_path)+ try:+ first = service.bind_agent_session(+ scope_key="slack::channel::C123",+ agent_name="claude",+ session_anchor="slack_C123",+ native_session_id="native-1",+ )+ assert first is not None+ # Re-bind a different native on the same row → ignored.+ service.bind_agent_session(+ scope_key="slack::channel::C123",+ agent_name="claude",+ session_anchor="slack_C123",+ native_session_id="native-2",+ )+ assert service.get_agent_session_by_id(first)["native_session_id"] == "native-1"+ finally:+ service.close()++def test_sqlite_sessions_service_delete_agent_sessions_escapes_anchor_prefix(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"service = SQLiteSessionsService(db_path)diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex a401966ab..d208aed83 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260531_0010"+HEAD_REVISION = "20260601_0011"def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:@@ -1086,6 +1086,117 @@ def test_run_migrations_does_not_stamp_partial_schema_missing_scopes(tmp_path: Passert conn.execute("select name from sqlite_master where name = 'scopes'").fetchone() is None+def _insert_scope(conn: sqlite3.Connection, scope_id: str) -> None:+ conn.execute(+ """+ insert into scopes (+ id, platform, scope_type, native_id, is_private, supports_threads,+ metadata_json, first_seen_at, last_seen_at, updated_at+ ) values (?, 'slack', 'channel', ?, 0, 1, '{}', 'now', 'now', 'now')+ """,+ (scope_id, scope_id),+ )+++def _insert_agent_session(+ conn: sqlite3.Connection,+ *,+ row_id: str,+ scope_id: str,+ anchor: str,+ workdir: str | None,+ backend: str,+ native: str,+ last_active: str,+) -> None:+ conn.execute(+ """+ insert into agent_sessions (+ id, scope_id, agent_backend, agent_variant, session_anchor, workdir,+ native_session_id, status, metadata_json, created_at, updated_at, last_active_at+ ) values (?, ?, ?, ?, ?, ?, ?, 'active', '{}', 'now', 'now', ?)+ """,+ (row_id, scope_id, backend, backend, anchor, workdir, native, last_active),+ )+++def test_run_migrations_session_anchor_unique_strips_dedups_and_reattaches(tmp_path: Path) -> None:+ # Build the pre-0011 schema, seed the exact legacy states 0011 must handle,+ # then upgrade to head and assert the three guarantees: OpenCode cwd anchors+ # collapse to the bare base (cwd kept on workdir), claude/codex subagent+ # anchors are PRESERVED, duplicate (scope, anchor) rows dedup to the most+ # recent, and the loser's transcript is reattached to the survivor first.+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path, revision="20260531_0010")++ with sqlite3.connect(db_path) as conn:+ _insert_scope(conn, "sc1")+ # OpenCode cwd composite -> stripped to bare base.+ _insert_agent_session(+ conn, row_id="ses_oc0000001", scope_id="sc1", anchor="oc-base:/repo/x",+ workdir="/repo/x", backend="opencode", native="oc-native", last_active="2026-06-01T08:00:00",+ )+ # claude SUBAGENT anchor (non-path suffix) -> preserved.+ _insert_agent_session(+ conn, row_id="ses_sub0000001", scope_id="sc1", anchor="cl-base:reviewer",+ workdir="reviewer", backend="claude", native="sub-native", last_active="2026-06-01T08:00:00",+ )+ # Windows OpenCode cwd composite (drive-letter colon) -> bare base, cwd+ # re-derived onto workdir. The old last-colon backfill stored a wrong+ # workdir ("\\repo\\x"); the migration corrects it. (Codex P2 #095.)+ _insert_agent_session(+ conn, row_id="ses_oswin00001", scope_id="sc1", anchor="win-base:C:\\repo\\x",+ workdir="\\repo\\x", backend="opencode", native="win-native2", last_active="2026-06-01T08:00:00",+ )+ # Duplicate group: a bare row + a cwd composite that strips onto it. The+ # later last_active row survives; the loser carries a transcript.+ _insert_agent_session(+ conn, row_id="ses_win0000001", scope_id="sc1", anchor="dup-base",+ workdir=None, backend="claude", native="win-native", last_active="2026-06-01T10:00:00",+ )+ _insert_agent_session(+ conn, row_id="ses_lose000001", scope_id="sc1", anchor="dup-base:/cwd",+ workdir="/cwd", backend="opencode", native="lose-native", last_active="2026-06-01T09:00:00",+ )+ conn.execute(+ """+ insert into messages (+ id, scope_id, session_id, platform, author, type,+ content_json, metadata_json, created_at, updated_at+ ) values ('msg1', 'sc1', 'ses_lose000001', 'slack', 'agent', 'assistant',+ '{}', '{}', 'now', 'now')+ """,+ )+ conn.commit()++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ rows = {+ r[0]: (r[1], r[2])+ for r in conn.execute("select id, session_anchor, workdir from agent_sessions")+ }+ # OpenCode cwd stripped to bare base; cwd retained on workdir.+ assert rows["ses_oc0000001"] == ("oc-base", "/repo/x")+ # Subagent anchor preserved (Codex P2: do not collapse base:<subagent>).+ assert rows["ses_sub0000001"] == ("cl-base:reviewer", "reviewer")+ # Windows drive-letter cwd stripped to bare base; full cwd on workdir.+ assert rows["ses_oswin00001"] == ("win-base", "C:\\repo\\x")+ # Dedup kept the most-recently-active row; the loser is gone.+ assert "ses_win0000001" in rows+ assert "ses_lose000001" not in rows+ assert len(rows) == 4+ # Transcript reattached to the survivor before the loser was deleted+ # (Codex P2: ondelete=SET NULL would otherwise orphan it).+ msg_session = conn.execute("select session_id from messages where id = 'msg1'").fetchone()+ assert msg_session == ("ses_win0000001",)+ # The invariant is enforced going forward.+ index = conn.execute(+ "select name from sqlite_master where type = 'index' and name = 'uq_agent_sessions_scope_anchor'"+ ).fetchone()+ assert index == ("uq_agent_sessions_scope_anchor",)++def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:state_dir = tmp_path / "state"state_dir.mkdir()@@ -1154,12 +1265,17 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:assert user_settings == ("admin", "opencode", "opencode")assert re.fullmatch(r"ses[23456789abcdefghjkmnpqrstuvwxyz]{10}", agent_session[0])assert agent_session[1] == "slack::channel::C123"- assert agent_session[2] == "slack_1774074591.762089:/repo"+ # OpenCode ``base:/cwd`` composite is normalised to the bare anchor on import+ # (the cwd stays on the ``workdir`` column), matching the migration + the+ # bare-anchor read path. (Codex P2: composite anchors were unreadable.)+ assert agent_session[2] == "slack_1774074591.762089"assert agent_session[3] == "/repo"assert agent_session[4] == "codex-session-1"assert agent_session[5] is Noneassert agent_session[6] == "codex"- assert duplicate_insert_ok is True+ # The (scope_id, session_anchor) unique index now rejects a second row for the+ # same thread — a thread is ONE session.+ assert duplicate_insert_ok is Falseassert second.imported is Falseassert second.backup_path is None@@ -1176,6 +1292,44 @@ def test_ensure_sqlite_state_imports_json_once(tmp_path: Path) -> None:}+def test_ensure_sqlite_state_collapses_multi_backend_anchor_on_import(tmp_path: Path) -> None:+ # ensure_sqlite_state runs the migration (installing the (scope, anchor) unique+ # index) BEFORE importing sessions.json. Legacy JSON can list several backends+ # under ONE thread (pre-pin), so the import must collapse them onto a single+ # bare-anchor row instead of crashing on the unique index or leaving a composite+ # anchor the bare-anchor read path can't find. (Codex P2 #263.)+ state_dir = tmp_path / "state"+ state_dir.mkdir()+ db_path = state_dir / "vibe.sqlite"+ (state_dir / "sessions.json").write_text(+ json.dumps(+ {+ "session_mappings": {+ "slack::C123": {+ "claude": {"slack_T1": "claude-native"},+ "codex": {"slack_T1": "codex-native"},+ "opencode": {"slack_T1:/repo": "opencode-native"},+ }+ }+ }+ ),+ encoding="utf-8",+ )++ ensure_sqlite_state(db_path=db_path, state_dir=state_dir, primary_platform="slack")++ with sqlite3.connect(db_path) as conn:+ rows = conn.execute("select session_anchor, workdir from agent_sessions").fetchall()+ # All three backends collapsed to ONE bare-anchor row — no IntegrityError,+ # no leftover ``slack_T1:/repo`` composite.+ assert len(rows) == 1+ assert rows[0][0] == "slack_T1"+ index = conn.execute(+ "select name from sqlite_master where type = 'index' and name = 'uq_agent_sessions_scope_anchor'"+ ).fetchone()+ assert index == ("uq_agent_sessions_scope_anchor",)++def test_ensure_sqlite_state_import_skips_agent_name_conflict(tmp_path: Path) -> None:state_dir = tmp_path / "state"state_dir.mkdir()diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 84c30bbb4..eb67d23b6 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -230,6 +230,7 @@},"resume": {"slackOnly": "Resume is currently available only on Slack. Continue in the same thread to auto-resume.",+ "scopeOnly": "⏮️ /resume can only be used at the channel level, not inside an existing thread. Start it from the main channel — it opens a fresh session you can continue.","clickButton": "Please click the Resume Session button in the menu message below to open the picker.","noStoredSessions": "No recent agent sessions found for this working directory.","noStoredSessionsForBackend": "No recent {backend} sessions found for this working directory.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 354dac699..e7c45c909 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -230,6 +230,7 @@},"resume": {"slackOnly": "恢复功能目前仅在 Slack 上可用。在同一线程中继续可自动恢复。",+ "scopeOnly": "⏮️ /resume 只能在频道层级使用,不能在已有线程里。请在主频道里发起——它会开一个可继续的新会话。","clickButton": "请在下面这条菜单消息中点击“恢复会话”按钮打开选择器。","noStoredSessions": "当前工作目录下未找到最近的 Agent 会话。","noStoredSessionsForBackend": "当前工作目录下未找到最近的 {backend} 会话。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex cc7b98fc6..22c4da646 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3064,6 +3064,20 @@ def sessions_update(session_id: str):session = workbench_sessions_service.update_session(conn, session_id, **updatable)except LookupError as err:return jsonify({"error": str(err)}), 404+ except workbench_sessions_service.SessionBackendLockedError as err:+ # A session is pinned to its backend once it has a conversation; the UI+ # may switch the agent within the same backend, but not across backends.+ return (+ jsonify(+ {+ "error": str(err),+ "code": "backend_locked",+ "current_backend": err.current_backend,+ "requested_backend": err.requested_backend,+ }+ ),+ 409,+ )# Broadcast so other surfaces (e.g. the sidebar session list) reflect the# edit live — renaming a session in the chat header should rename its# sidebar row without a manual refresh.