Skip to content

armgit / avibe

Public Imported from GitHub
0

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

41.9 KB
Raw Blame
"""Fork Avibe Agent Sessions.

This module owns the Avibe-level fork contract: validate the source Session,
copy its row into a new pending Session, and carry enough metadata for backend
adapters to call their native fork API on the first turn.
"""

from __future__ import annotations

import json
import secrets
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Mapping, Optional

from config import paths
from modules.agents.catalog import AGENT_BACKENDS
from vibe.authorization import (
    AuthorizationContext,
    require_instance_role,
)
from vibe.i18n import t
from vibe.message_identity import INPUT_TURN_AUTHOR_TYPES, is_input_turn
from vibe.message_types import activity_role_for, spec_for, types_with

TRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}
# Turn settlement is read from ``session_turns`` below, so a reply-less completion
# cannot be mistaken for a still-running input.
TERMINAL_AGENT_OUTPUT_TYPES = {
    message_type
    for message_type in types_with("activityRole")
    if spec_for(message_type)["activityRole"] == "terminal"
}
# Agent rows that show a Turn completed: a terminal row always, and a reply when its
# Turn is no longer running, since a Turn may reply more than once
# (docs/plans/reply-and-turn-end.md).
_COMPLETION_ACTIVITY_ROLES = frozenset({"reply", "terminal"})
SOURCE_PROGRESS_AGENT_OUTPUT_TYPES = {
    message_type
    for message_type in set(types_with("activityRole")) | set(types_with("transcript"))
    if spec_for(message_type)["activityRole"] in {"activity", "terminal"}
    or spec_for(message_type)["render"] == "agent"
}
ACTIVE_SOURCE_RUN_STATUSES = ("pending", "queued", "processing", "running")
INPUT_TURN_MESSAGE_TYPES = tuple(message_type for _, message_type in INPUT_TURN_AUTHOR_TYPES)
_CONDITIONAL_TERMINAL_TYPES = types_with("terminalWhenEvents")
_DETACHED_COMPLETION_TYPES = types_with("detachedCompletion")
# Muted ``interim`` narration is a copy of process log, not a Turn boundary, so
# it never becomes the anchor a fork resumes from.
_FORK_ANCHOR_TYPES = tuple(
    dict.fromkeys(
        (
            *(
                message_type
                for message_type in types_with("transcript")
                if spec_for(message_type)["render"] != "muted"
            ),
            *(
                message_type
                for message_type in types_with("activityRole")
                if message_type in TERMINAL_AGENT_OUTPUT_TYPES
            ),
        )
    )
)

SESSION_AGENT_UNAVAILABLE_CODE = "session_agent_unavailable"
SESSION_AGENT_UNAVAILABLE_I18N_KEY = "error.sessionFork.agentUnavailable"


class SessionForkError(ValueError):
    """Raised when a Session cannot be forked."""

    def __init__(
        self,
        message: str,
        *,
        code: str = "session_fork_failed",
        details: Optional[dict[str, Any]] = None,
    ) -> None:
        super().__init__(message)
        self.code = code
        self.details = details or {}


@dataclass(frozen=True)
class SessionForkSpec:
    source_session_id: str
    source_native_session_id: str
    source_backend: str
    source_message_id: Optional[str] = None
    trim_latest_running_turn: bool = False
    native_turn_started: bool = False
    opencode_fork_message_id: Optional[str] = None
    opencode_fork_empty_history: bool = False
    opencode_boundary_from_active_run: bool = False

    def to_metadata(self) -> dict[str, Any]:
        metadata = {
            "source_session_id": self.source_session_id,
            "source_native_session_id": self.source_native_session_id,
            "source_backend": self.source_backend,
        }
        if self.source_message_id:
            metadata["source_message_id"] = self.source_message_id
        if self.trim_latest_running_turn:
            metadata["trim_latest_running_turn"] = True
        if self.native_turn_started:
            metadata["native_turn_started"] = True
        if self.opencode_fork_message_id:
            metadata["opencode_fork_message_id"] = self.opencode_fork_message_id
        if self.opencode_fork_empty_history:
            metadata["opencode_fork_empty_history"] = True
        if self.opencode_boundary_from_active_run:
            metadata["opencode_boundary_from_active_run"] = True
        return metadata


@dataclass(frozen=True)
class SessionForkResult:
    session_id: str
    agent_name: Optional[str]
    agent_id: Optional[str]
    agent_backend: str
    model: Optional[str]
    reasoning_effort: Optional[str]
    fork: SessionForkSpec


@dataclass(frozen=True)
class ForkSourceState:
    anchor_author: Optional[str] = None
    anchor_type: Optional[str] = None
    latest_after_anchor_author: Optional[str] = None
    latest_after_anchor_type: Optional[str] = None
    has_messages_after_anchor: bool = False
    has_terminal_agent_output_after_anchor: bool = False
    has_input_turn_after_anchor: bool = False
    anchor_activity_role: str = "none"

    @property
    def anchor_is_terminal_agent_output(self) -> bool:
        # A reservation anchors on a running Turn's input, so an agent anchor is a
        # finished Turn's reply or terminal row.
        return self.anchor_author == "agent" and self.anchor_activity_role in _COMPLETION_ACTIVITY_ROLES


@dataclass(frozen=True)
class SourceMessageAnchor:
    message_id: Optional[str] = None
    author: Optional[str] = None
    message_type: Optional[str] = None
    running_turn: bool = False

    @property
    def is_running_input_turn(self) -> bool:
        return self.running_turn or is_input_turn(self.author, self.message_type)


def _require_agent_selection(
    conn: Any,
    context: Any,
    *,
    agent_id: Optional[str] = None,
    agent_name: Optional[str] = None,
) -> None:
    """Hold the Agent the fork will run as to the caller's selection authority."""

    from core.vibe_agents import VibeAgentAccessError, ensure_agent_selection_access

    try:
        ensure_agent_selection_access(
            conn, agent_id=agent_id, agent_name=agent_name, user_context=context
        )
    except VibeAgentAccessError as exc:
        raise SessionForkError(
            "agent access is not permitted",
            code="session_fork_agent_forbidden",
        ) from exc


def reserve_forked_session(
    *,
    source_session_id: str,
    agent_name: Optional[str] = None,
    model: Optional[str] = None,
    reasoning_effort: Optional[str] = None,
    scope_id: Optional[str] = None,
    visibility: str = "foreground",
    trim_latest_running_turn: bool = False,
    native_turn_started: bool = False,
    db_path: Optional[Path] = None,
    title_lang: str = "en",
    authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
    self_fork: bool = False,
    as_of: Optional[int] = None,
) -> SessionForkResult:
    """Copy an existing Agent Session row into a new pending fork target.

    ``agent_name`` may switch to another enabled Avibe Agent only when that
    Agent uses the same backend as the source. ``model`` and
    ``reasoning_effort`` are simple per-session overrides. The new row's native
    id stays empty until the backend adapter successfully forks the native
    session.

    A Vibey source's fork point (C-10 fork.md section 2) is resolved here. A
    user's fork cuts before its earliest unfinished Turn, so the child never
    inherits a partial Turn. ``self_fork`` is the Agent's own fork from inside
    its live Turn, set only by ``vibe agent run --fork-self``; it cuts at the
    largest settled point, keeping that Turn's input and finished steps.
    ``as_of`` is internal, for system mechanisms: a settled Vibey point. No
    product surface passes it. Native backends fork by their own existing
    logic and ignore ``self_fork``; they refuse ``as_of``.
    """

    context = require_instance_role(authorization_context, "editor")

    from sqlalchemy import select

    from core.vibe_agents import VibeAgentStore
    from storage.agent_session_rows import create_agent_session_row, reserve_write_lock, utc_now_iso
    from storage.db import create_sqlite_engine
    from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
    from storage.models import agent_sessions
    from storage.session_reclaim import reconcile_explicit_overrides
    from storage.workbench_sessions_service import require_enabled_agent_identity

    path = db_path or paths.get_sqlite_state_path()
    if db_path is None:
        ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
    engine = create_sqlite_engine(path)
    agent_store = VibeAgentStore(path)
    try:
        with engine.begin() as conn:
            reserve_write_lock(conn)
            if not context.is_instance_owner:
                from storage import project_access_service

                if not project_access_service.role_allows(
                    project_access_service.get_effective_session_role(
                        conn,
                        context,
                        source_session_id,
                    ),
                    "editor",
                ):
                    raise SessionForkError("source_not_found")
                # A permitted source does not authorize an arbitrary
                # destination: without this, a fork can place a copy of the
                # transcript into a Project the caller cannot chat in. Same
                # rule and same tier as an ordinary re-placement in
                # ``workbench_sessions_service.update_workbench_session``, and
                # it runs before any reserved row or native-fork metadata.
                destination_scope_id = _clean_optional(scope_id) if scope_id is not None else None
                if destination_scope_id and not context.can_manage_instance:
                    destination_project_id = project_access_service.project_id_from_scope_id(
                        destination_scope_id
                    )
                    if destination_project_id is None or not project_access_service.can_chat_project(
                        conn, context, destination_project_id
                    ):
                        raise SessionForkError("destination_not_permitted")
            row = conn.execute(
                select(agent_sessions).where(agent_sessions.c.id == str(source_session_id)).limit(1)
            ).mappings().first()
            if row is None:
                raise SessionForkError(f"agent session id not found: {source_session_id}")
            if str(row["status"] or "") == "archived":
                raise SessionForkError(f"agent session is archived: {source_session_id}")

            source_backend = str(row["agent_backend"] or "").strip()
            if source_backend not in AGENT_BACKENDS:
                raise SessionForkError(f"session backend cannot be forked: {source_backend or 'unknown'}")
            source_native = str(row["native_session_id"] or "").strip()
            if not source_native:
                raise SessionForkError(
                    f"agent session has no native session id to fork: {source_session_id}"
                )
            if as_of is not None and source_backend != "vibey":
                raise SessionForkError(
                    "an explicit fork point needs a vibey source session",
                    code="session_fork_point_unsupported",
                )
            source_anchor = _latest_source_message_anchor(conn, str(row["id"]))
            source_has_active_run = _source_has_active_agent_run(conn, str(row["id"]))
            inferred_running_turn = source_anchor.is_running_input_turn or (
                source_backend == "opencode"
                and source_has_active_run
            )
            effective_trim_latest_running_turn = bool(
                source_backend in TRIM_LATEST_RUNNING_TURN_BACKENDS
                and (trim_latest_running_turn or inferred_running_turn)
            )
            effective_native_turn_started = bool(
                effective_trim_latest_running_turn and native_turn_started
            )
            opencode_fork_message_id: Optional[str] = None
            opencode_fork_empty_history = False
            opencode_boundary_from_active_run = False
            if effective_trim_latest_running_turn and source_backend == "opencode":
                fork_point = _opencode_running_fork_point(source_native)
                if fork_point is not None:
                    opencode_fork_message_id, opencode_fork_empty_history = fork_point
                    opencode_boundary_from_active_run = bool(
                        source_has_active_run and not source_anchor.is_running_input_turn
                    )
                    effective_native_turn_started = True
            source_message_id = source_anchor.message_id
            if agent_name:
                # The fork will RUN AS this Agent, so selecting it needs use
                # access to that exact resource — being enabled is not the same
                # as being one this caller may select. Ordered after the source
                # checks so an unreachable source still answers first.
                _require_agent_selection(conn, context, agent_name=agent_name)
            override_agent = agent_store.require_enabled(agent_name) if agent_name else None
            if override_agent is not None and override_agent.backend != source_backend:
                raise SessionForkError(
                    "agent backend does not match the source session backend"
                )

            inherited_agent = None
            if override_agent is None and (row["agent_id"] or row["agent_name"]):
                try:
                    inherited_agent = require_enabled_agent_identity(
                        conn,
                        agent_id=row["agent_id"],
                        agent_name=row["agent_name"],
                    )
                except LookupError as exc:
                    raise SessionForkError(
                        "source session Agent is unavailable; choose an enabled Agent override",
                        code=SESSION_AGENT_UNAVAILABLE_CODE,
                        details={"source_session_id": source_session_id},
                    ) from exc
                if inherited_agent["backend"] != source_backend:
                    raise SessionForkError(
                        "source session Agent backend does not match the session backend"
                    )
                # Without an override the fork still runs as the source's Agent,
                # so that inherited identity is selected authority too. Ordered
                # after the unavailable and backend answers so their existing
                # meaning is unchanged.
                _require_agent_selection(
                    conn,
                    context,
                    agent_id=inherited_agent["id"],
                    agent_name=inherited_agent["name"],
                )

            if override_agent is not None:
                target_agent_id = override_agent.id
                target_agent_name = override_agent.name
                target_backend = override_agent.backend
            elif inherited_agent is not None:
                target_agent_id = inherited_agent["id"]
                target_agent_name = inherited_agent["name"]
                target_backend = inherited_agent["backend"]
            else:
                target_agent_id = None
                target_agent_name = None
                target_backend = source_backend
            target_variant = target_backend if override_agent else str(row["agent_variant"] or target_backend)
            now = utc_now_iso()
            target_model = _clean_optional(model) if model is not None else row["model"]
            target_effort = (
                _clean_optional(reasoning_effort)
                if reasoning_effort is not None
                else row["reasoning_effort"]
            )
            explicit_scope_id = _clean_optional(scope_id) if scope_id is not None else None
            target_scope_id = explicit_scope_id or row["scope_id"]
            if explicit_scope_id or target_scope_id != row["scope_id"]:
                target_anchor = _fork_session_anchor(
                    _anchor_for_scope_id(target_scope_id),
                    source_session_id=str(row["id"]),
                    now=now,
                )
            else:
                target_anchor = _fork_session_anchor(row["session_anchor"], source_session_id=str(row["id"]), now=now)
            source_title = str(row["title"] or "").strip()
            target_title = _forked_session_title(source_title, title_lang)

            metadata = _load_metadata(row["metadata_json"])
            metadata.pop("fork_opencode_message_id", None)
            metadata.pop("fork_opencode_fork_empty_history", None)
            metadata.pop("fork_opencode_boundary_from_active_run", None)
            # A source that is itself a fork carries its own point; the child's is resolved below.
            metadata.pop("fork_source_context_seq", None)
            metadata.update(
                {
                    "created_via": "session_fork",
                    "fork_source_session_id": str(row["id"]),
                    "fork_source_session_title": source_title,
                    "fork_source_message_id": source_message_id,
                    "fork_source_native_session_id": source_native,
                    "fork_source_backend": source_backend,
                    "fork_trim_latest_running_turn": effective_trim_latest_running_turn,
                    "fork_native_turn_started": effective_native_turn_started,
                    "fork_created_at": now,
                }
            )
            if source_backend == "vibey":
                # Vibey's context is the source's rows up to the fork point, resolved once
                # now so later rows never enter the prefix. A user's fork cuts before the
                # earliest unfinished Turn, so a live Turn's input, calls, and replies never
                # reach the child (C-10 fork.md section 2).
                from core.agent_core.harness.fork import ForkPointError
                from storage.agent_transcript import resolve_fork_point

                try:
                    metadata["fork_source_context_seq"] = resolve_fork_point(
                        conn, str(row["id"]), as_of=as_of, self_fork=self_fork
                    )
                except ForkPointError as exc:
                    raise SessionForkError(str(exc), code=f"session_fork_point_{exc.code}") from exc
            if opencode_fork_message_id:
                metadata["fork_opencode_message_id"] = opencode_fork_message_id
            if opencode_fork_empty_history:
                metadata["fork_opencode_fork_empty_history"] = True
            if opencode_boundary_from_active_run:
                metadata["fork_opencode_boundary_from_active_run"] = True
            if target_scope_id != row["scope_id"]:
                metadata["fork_target_scope_id"] = target_scope_id
                metadata["legacy_scope_key"] = target_scope_id
            # The copied metadata carries the SOURCE session's explicit-override
            # marker. Whether that claim is still TRUE depends on whether this fork
            # copied the column or replaced it, and the two cases are opposites:
            #
            # - OMITTED (``model is None``): ``target_model`` above is
            #   ``row["model"]`` -- the column is copied verbatim, so the source's
            #   marker is a true claim about the value the fork now holds and must
            #   be PRESERVED. Dropping it converts a fork of an explicit-null
            #   session into an ordinary inherited-null one, and the next Agent
            #   default change silently hands the fork settings the source had
            #   deliberately pinned away.
            # - SUPPLIED: the fork owns the setting. It is an explicit pin only
            #   when the resolved value is empty (pin nothing); a concrete value
            #   needs no marker, because dispatch reads a non-null column anyway.
            #
            # Only the supplied fields are reconciled. This is the inverse of the
            # first version of this guard, which cleared exactly the copied fields.
            resolved_forked_settings = {"model": target_model, "reasoning_effort": target_effort}
            supplied_settings = [
                name
                for name, value in (("model", model), ("reasoning_effort", reasoning_effort))
                if value is not None
            ]
            metadata = reconcile_explicit_overrides(
                metadata,
                cleared=[
                    name for name in supplied_settings if resolved_forked_settings[name] is not None
                ],
                explicit=[
                    name for name in supplied_settings if resolved_forked_settings[name] is None
                ],
            )
            session_id = create_agent_session_row(
                conn,
                scope_id=target_scope_id,
                # Keep IM delivery stable while satisfying the per-scope anchor
                # uniqueness invariant. resolve_session_id_target strips the
                # suffix after ":" when deriving the IM thread id.
                session_anchor=target_anchor,
                agent_id=target_agent_id,
                agent_name=target_agent_name,
                agent_backend=target_backend,
                agent_variant=target_variant,
                model=target_model,
                reasoning_effort=target_effort,
                workdir=row["workdir"],
                native_session_id="",
                title=target_title,
                visibility=visibility,
                metadata=metadata,
                now=now,
                require_workdir=False,
            )

        if source_backend == "vibey":
            from modules.agents.vibey.prompt_snapshot import SnapshotStore

            # This service already runs on its callers' worker paths. Copy now: a
            # source may refresh again before the child's first Turn begins.
            SnapshotStore(paths.get_state_dir() / "agent_core").inherit(str(source_session_id), session_id)

        fork = SessionForkSpec(
            source_session_id=str(source_session_id),
            source_native_session_id=source_native,
            source_backend=source_backend,
            source_message_id=source_message_id,
            trim_latest_running_turn=effective_trim_latest_running_turn,
            native_turn_started=effective_native_turn_started,
            opencode_fork_message_id=opencode_fork_message_id,
            opencode_fork_empty_history=opencode_fork_empty_history,
            opencode_boundary_from_active_run=opencode_boundary_from_active_run,
        )
        return SessionForkResult(
            session_id=session_id,
            agent_name=str(target_agent_name).strip() if target_agent_name else None,
            agent_id=str(target_agent_id).strip() if target_agent_id else None,
            agent_backend=target_backend,
            model=target_model,
            reasoning_effort=target_effort,
            fork=fork,
        )
    finally:
        agent_store.close()
        engine.dispose()


def fork_metadata_from_request(metadata: dict[str, Any] | None) -> dict[str, Any] | None:
    """Return normalized pending fork metadata from an Agent Run record."""

    if not isinstance(metadata, dict):
        return None
    fork = metadata.get("session_fork")
    if not isinstance(fork, dict):
        return None
    source_backend = _clean_optional(fork.get("source_backend"))
    source_native = _clean_optional(fork.get("source_native_session_id"))
    source_session = _clean_optional(fork.get("source_session_id"))
    if not (source_backend and source_native and source_session):
        return None
    result = {
        "source_session_id": source_session,
        "source_native_session_id": source_native,
        "source_backend": source_backend,
    }
    if bool(fork.get("trim_latest_running_turn")):
        result["trim_latest_running_turn"] = True
    if bool(fork.get("native_turn_started")):
        result["native_turn_started"] = True
    opencode_message = _clean_optional(fork.get("opencode_fork_message_id"))
    if opencode_message:
        result["opencode_fork_message_id"] = opencode_message
    if bool(fork.get("opencode_fork_empty_history")):
        result["opencode_fork_empty_history"] = True
    if bool(fork.get("opencode_boundary_from_active_run")):
        result["opencode_boundary_from_active_run"] = True
    source_message = _clean_optional(fork.get("source_message_id"))
    if source_message:
        result["source_message_id"] = source_message
    return result


def fork_metadata_from_session_metadata(metadata: dict[str, Any] | None) -> dict[str, Any] | None:
    """Return pending fork metadata persisted on a fork target Session row."""

    if not isinstance(metadata, dict):
        return None
    source_backend = _clean_optional(metadata.get("fork_source_backend"))
    source_native = _clean_optional(metadata.get("fork_source_native_session_id"))
    source_session = _clean_optional(metadata.get("fork_source_session_id"))
    if not (source_backend and source_native and source_session):
        return None
    result = {
        "source_session_id": source_session,
        "source_native_session_id": source_native,
        "source_backend": source_backend,
    }
    if bool(metadata.get("fork_trim_latest_running_turn")):
        result["trim_latest_running_turn"] = True
    if bool(metadata.get("fork_native_turn_started")):
        result["native_turn_started"] = True
    opencode_message = _clean_optional(metadata.get("fork_opencode_message_id"))
    if opencode_message:
        result["opencode_fork_message_id"] = opencode_message
    if bool(metadata.get("fork_opencode_fork_empty_history")):
        result["opencode_fork_empty_history"] = True
    if bool(metadata.get("fork_opencode_boundary_from_active_run")):
        result["opencode_boundary_from_active_run"] = True
    source_message = _clean_optional(metadata.get("fork_source_message_id"))
    if source_message:
        result["source_message_id"] = source_message
    return result


def pending_native_fork(context: Any, backend: str) -> Optional[dict[str, Any]]:
    """Native fork spec if this turn should fork instead of start fresh."""

    payload = getattr(context, "platform_specific", None) or {}
    target = payload.get("agent_session_target")
    if not isinstance(target, dict):
        return None
    target_backend = str(target.get("agent_backend") or "").strip()
    if target_backend and target_backend != backend:
        return None
    if str(target.get("native_session_id") or "").strip():
        return None
    fork = target.get("native_session_fork")
    if not isinstance(fork, dict):
        fork = fork_metadata_from_session_metadata(target.get("metadata"))
    if not isinstance(fork, dict):
        return None
    if str(fork.get("source_backend") or "").strip() != backend:
        return None
    source_native = str(fork.get("source_native_session_id") or "").strip()
    if not source_native:
        return None
    return {**fork, "source_native_session_id": source_native}


def pending_native_fork_source(context: Any, backend: str) -> Optional[str]:
    """Native source id if this turn should fork instead of start fresh."""

    fork = pending_native_fork(context, backend)
    if not fork:
        return None
    return str(fork.get("source_native_session_id") or "").strip() or None


def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
    """Return source transcript state relative to the fork reservation anchor."""

    if not isinstance(fork, dict):
        return ForkSourceState()
    source_session_id = _clean_optional(fork.get("source_session_id"))
    source_message_id = _clean_optional(fork.get("source_message_id"))
    if not source_session_id or not source_message_id:
        return ForkSourceState()

    from sqlalchemy import and_, func, or_, select

    from storage.db import create_sqlite_engine
    from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
    from storage.messages_service import transcript_order_value
    from storage.models import messages, session_turns

    ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
    engine = create_sqlite_engine(paths.get_sqlite_state_path())
    try:
        with engine.connect() as conn:
            anchor = conn.execute(
                select(
                    transcript_order_value().label("transcript_order_at"),
                    messages.c.id,
                    messages.c.author,
                    messages.c.type,
                    messages.c.metadata_json,
                )
                .where(messages.c.session_id == source_session_id, messages.c.id == source_message_id)
                .limit(1)
            ).mappings().first()
            if anchor is None:
                return ForkSourceState()
            anchor_order_at = anchor["transcript_order_at"]
            anchor_id = anchor["id"]
            after_anchor = (
                (transcript_order_value() > anchor_order_at)
                | ((transcript_order_value() == anchor_order_at) & (messages.c.id > anchor_id))
            )
            latest_after_anchor = conn.execute(
                select(messages.c.author, messages.c.type, messages.c.metadata_json)
                .where(
                    messages.c.session_id == source_session_id,
                    or_(
                        messages.c.type.in_(
                            [*INPUT_TURN_MESSAGE_TYPES, *list(SOURCE_PROGRESS_AGENT_OUTPUT_TYPES)]
                        ),
                        *(
                            and_(
                                messages.c.type == message_type,
                                func.json_extract(messages.c.metadata_json, "$.event").in_(
                                    spec_for(message_type)["terminalWhenEvents"]
                                ),
                            )
                            for message_type in _CONDITIONAL_TERMINAL_TYPES
                        ),
                    ),
                    after_anchor,
                    ~and_(
                        messages.c.type.in_(_DETACHED_COMPLETION_TYPES),
                        func.coalesce(
                            func.json_extract(messages.c.metadata_json, "$.detached"),
                            0,
                        )
                        == 1,
                    ),
                    ~and_(
                        messages.c.type == "notify",
                        func.coalesce(
                            func.json_extract(messages.c.metadata_json, "$.event"), ""
                        ) == "backend_failure",
                        func.coalesce(
                            func.json_extract(messages.c.metadata_json, "$.replayed"), 0
                        ) == 1,
                    ),
                )
                .order_by(transcript_order_value().desc(), messages.c.id.desc())
                .limit(1)
            ).mappings().first()
            latest_after_anchor_author = (
                str(latest_after_anchor["author"] or "").strip() if latest_after_anchor else ""
            )
            latest_after_anchor_type = (
                str(latest_after_anchor["type"] or "").strip() if latest_after_anchor else ""
            )
            latest_after_anchor_metadata = _load_metadata(
                latest_after_anchor["metadata_json"] if latest_after_anchor else None
            )
            latest_after_anchor_role = activity_role_for(
                latest_after_anchor_type,
                latest_after_anchor_metadata,
            )
            has_terminal_agent_output_after_anchor = latest_after_anchor_author == "agent" and (
                latest_after_anchor_role == "terminal"
                or (
                    latest_after_anchor_role == "reply"
                    # A reply ends nothing while its Turn still runs: input steered
                    # into it is being answered. IM Turns have no durable row, so
                    # their reply stays the latest evidence.
                    and conn.execute(
                        select(session_turns.c.id)
                        .where(
                            session_turns.c.session_id == source_session_id,
                            session_turns.c.state.in_(("starting", "active")),
                        )
                        .limit(1)
                    ).first()
                    is None
                )
            )
            has_input_turn_after_anchor = (
                conn.execute(
                    select(messages.c.id)
                    .where(
                        messages.c.session_id == source_session_id,
                        or_(
                            *(
                                and_(messages.c.author == author, messages.c.type == message_type)
                                for author, message_type in INPUT_TURN_AUTHOR_TYPES
                            )
                        ),
                        after_anchor,
                    )
                    .limit(1)
                ).first()
                is not None
            )
            return ForkSourceState(
                anchor_author=str(anchor["author"] or "").strip() or None,
                anchor_type=str(anchor["type"] or "").strip() or None,
                latest_after_anchor_author=latest_after_anchor_author or None,
                latest_after_anchor_type=latest_after_anchor_type or None,
                has_messages_after_anchor=latest_after_anchor is not None,
                has_terminal_agent_output_after_anchor=has_terminal_agent_output_after_anchor,
                has_input_turn_after_anchor=has_input_turn_after_anchor,
                anchor_activity_role=activity_role_for(
                    str(anchor["type"] or "").strip(),
                    _load_metadata(anchor["metadata_json"]),
                ),
            )
    except Exception as exc:
        import logging

        logging.getLogger(__name__).warning(
            "Failed to inspect fork source state for %s after %s: %s",
            source_session_id,
            source_message_id,
            exc,
        )
        return ForkSourceState()
    finally:
        engine.dispose()


def fork_source_has_agent_output_after_anchor(fork: dict[str, Any] | None) -> bool:
    """Whether the source produced terminal agent output after the fork anchor."""

    return fork_source_state(fork).has_terminal_agent_output_after_anchor


def fork_anchor_is_terminal_agent_output(fork: dict[str, Any] | None) -> bool:
    """Whether the reservation anchor already points at a completed agent row."""

    return fork_source_state(fork).anchor_is_terminal_agent_output


def _load_metadata(value: Any) -> dict[str, Any]:
    try:
        loaded = json.loads(value or "{}")
    except (TypeError, ValueError):
        return {}
    return loaded if isinstance(loaded, dict) else {}


def _clean_optional(value: Any) -> Optional[str]:
    if value is None:
        return None
    text = str(value).strip()
    return text or None


def _parse_utc_timestamp(value: Any) -> datetime | None:
    try:
        parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
    except (TypeError, ValueError):
        return None
    if parsed.tzinfo is None:
        parsed = parsed.replace(tzinfo=timezone.utc)
    return parsed.astimezone(timezone.utc)


def _emitted_micros(row_id: Any, timestamp: datetime) -> int:
    identity = str(row_id or "")
    if len(identity) >= 19 and identity[3] == "_":
        try:
            return int(identity[4:19], 16)
        except ValueError:
            pass
    return int(timestamp.timestamp() * 1_000_000)


def _forked_session_title(source_title: str, lang: str = "en") -> str:
    return t("fork.title", lang, title=source_title) if source_title else t("fork.titleUntitled", lang)


def _latest_source_message_anchor(conn: Any, source_session_id: str) -> SourceMessageAnchor:
    from sqlalchemy import select

    from storage.messages_service import transcript_order_value
    from storage.models import agent_events, message_deliveries, messages, session_turns

    active_initial = conn.execute(
        select(
            messages.c.id,
            messages.c.author,
            messages.c.type,
            message_deliveries.c.state.label("delivery_state"),
        )
        .select_from(
            session_turns.join(
                message_deliveries,
                message_deliveries.c.id == session_turns.c.initial_delivery_id,
            ).outerjoin(
                messages,
                messages.c.id == message_deliveries.c.message_id,
            )
        )
        .where(
            session_turns.c.session_id == source_session_id,
            session_turns.c.state.in_(("starting", "active")),
        )
        .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
        .limit(1)
    ).mappings().first()
    if active_initial is not None and active_initial["id"] is not None:
        return SourceMessageAnchor(
            message_id=str(active_initial["id"]),
            author=str(active_initial["author"] or "").strip() or None,
            message_type=str(active_initial["type"] or "").strip() or None,
        )
    pre_materialized_start = bool(
        active_initial is not None
        and active_initial["delivery_state"] == "claimed"
    )

    row = conn.execute(
        select(messages.c.id, messages.c.author, messages.c.type, messages.c.created_at)
        .where(
            messages.c.session_id == source_session_id,
            messages.c.type.in_(_FORK_ANCHOR_TYPES),
        )
        .order_by(transcript_order_value().desc(), messages.c.id.desc())
        .limit(1)
    ).mappings().first()
    if row is None:
        return SourceMessageAnchor(running_turn=pre_materialized_start)
    latest_turn = conn.execute(
        select(
            session_turns.c.state,
            session_turns.c.terminal_outcome,
            session_turns.c.terminal_at,
        )
        .where(session_turns.c.session_id == source_session_id)
        .where(
            session_turns.c.terminal_outcome.is_(None)
            | (session_turns.c.terminal_outcome != "not_written")
        )
        .order_by(session_turns.c.created_at.desc(), session_turns.c.id.desc())
        .limit(1)
    ).mappings().first()
    silent_terminal = conn.execute(
        select(
            agent_events.c.id,
            agent_events.c.created_at,
            agent_events.c.metadata_json,
        )
        .where(
            agent_events.c.session_id == source_session_id,
            agent_events.c.event_type == "silent_terminal",
        )
        .order_by(agent_events.c.created_at.desc(), agent_events.c.id.desc())
        .limit(1)
    ).mappings().first()
    terminal_candidates: list[tuple[int, str]] = []
    if latest_turn is not None and latest_turn["state"] == "terminal":
        terminal_at = _parse_utc_timestamp(latest_turn["terminal_at"])
        if terminal_at is not None:
            terminal_candidates.append(
                (
                    int(terminal_at.timestamp() * 1_000_000),
                    str(latest_turn["terminal_outcome"] or "completed"),
                )
            )
    if silent_terminal is not None:
        terminal_at = _parse_utc_timestamp(silent_terminal["created_at"])
        if terminal_at is not None:
            metadata = _load_metadata(silent_terminal["metadata_json"])
            event_id = metadata.get("legacy_message_id") or silent_terminal["id"]
            terminal_candidates.append(
                (
                    _emitted_micros(event_id, terminal_at),
                    str(metadata.get("terminal_outcome") or "completed"),
                )
            )
    message_at = _parse_utc_timestamp(row["created_at"])
    latest_terminal = max(terminal_candidates, default=None)
    if (
        message_at is not None
        and latest_terminal is not None
        and latest_terminal[0] >= _emitted_micros(row["id"], message_at)
    ):
        return SourceMessageAnchor(
            message_id=str(row["id"]) if row["id"] else None,
            author="agent",
            message_type=(
                "error" if latest_terminal[1] == "failed" else "result"
            ),
            running_turn=pre_materialized_start,
        )
    return SourceMessageAnchor(
        message_id=str(row["id"]) if row["id"] else None,
        author=str(row["author"] or "").strip() or None,
        message_type=str(row["type"] or "").strip() or None,
        running_turn=pre_materialized_start,
    )


def _source_has_active_agent_run(conn: Any, source_session_id: str) -> bool:
    from sqlalchemy import select

    from storage.models import agent_runs

    return (
        conn.execute(
            select(agent_runs.c.id)
            .where(
                agent_runs.c.session_id == source_session_id,
                agent_runs.c.status.in_(ACTIVE_SOURCE_RUN_STATUSES),
            )
            .order_by(agent_runs.c.created_at.desc(), agent_runs.c.id.desc())
            .limit(1)
        ).scalar_one_or_none()
        is not None
    )


def _opencode_running_fork_point(source_native_session_id: str) -> Optional[tuple[Optional[str], bool]]:
    from modules.agents.native_sessions.opencode import OpenCodeNativeSessionProvider

    point = OpenCodeNativeSessionProvider().running_fork_point_before_latest_user(source_native_session_id)
    if not point.available:
        return None
    return point.message_id, point.empty_history


def _fork_session_anchor(value: Any, *, source_session_id: str, now: str) -> Optional[str]:
    anchor = _clean_optional(value)
    if not anchor or anchor == source_session_id:
        return None
    suffix = "".join(ch for ch in f"{source_session_id}_{now}" if ch.isalnum())
    return f"{anchor}:fork_{suffix}_{secrets.token_hex(3)}"


def _anchor_for_scope_id(scope_id: Any) -> Optional[str]:
    value = _clean_optional(scope_id)
    if not value:
        return None
    try:
        platform, scope_type, native_id = value.split("::", 2)
    except ValueError:
        return None
    if not (platform and scope_type and native_id):
        return None
    return f"{platform}_{native_id}"