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.

feat(agent-core): the fork point, and Vibey user forks that never carry an unfinished Turn (#2413)

Call White8ff64dfa932f
diff --git a/core/agent_core/harness/fork.py b/core/agent_core/harness/fork.py
new file mode 100644
index 000000000..5359c57e6
--- /dev/null
+++ b/core/agent_core/harness/fork.py
@@ -0,0 +1,70 @@
+"""C-10 fork point (``agent-core-contracts/fork.md`` section 2).
+
+A fork's model-visible messages begin with a source context's projection at a
+fork point and then diverge. The point is a committed ``context_seq`` (0 is the
+empty prefix) at which the context is settled: every tool call at or before it
+has its result at or before it, so a fork never inherits an open call. These
+are pure functions of the rows; nothing here reads a clock or a live job.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal, Optional, Sequence
+
+from core.agent_core.harness.projection import context_view, open_tool_calls
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.messages import Message
+
+
+@dataclass(frozen=True)
+class ForkPoint:
+ """``as_of``: the source's view is its rows with ``context_seq <= as_of``; ``units``: keep only that many of
+ the view's units (a side turn's prefix of its caller's current view), or all of them."""
+
+ as_of: int
+ units: Optional[int] = None
+
+
+class ForkPointError(ValueError):
+ """An internal fork point that is not legal; no product surface reaches it."""
+
+ def __init__(self, code: Literal["unsettled", "out_of_range"], message: str) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+def settled(entries: Sequence[ContextEntry], as_of: int) -> bool:
+ """No tool call in the rows up to ``as_of`` lacks its result in those rows."""
+ return not open_tool_calls([entry for entry in entries if entry.context_seq <= as_of])
+
+
+def latest_cut(entries: Sequence[ContextEntry], *, unended_input_seq: Optional[int]) -> int:
+ """The largest settled point before ``unended_input_seq`` (anywhere when it is ``None``).
+
+ A user's fork passes the first input of the earliest unfinished Turn (live, holding a call without a result, or
+ with an accepted input not yet in the context; C-10 section 2). A Turn writes every row of its own after that
+ input (one writer per Session), so the point ends the previous finished Turn and no partial Turn is inherited.
+ A self-fork passes ``None``.
+ """
+ seqs = sorted(
+ {entry.context_seq for entry in entries if unended_input_seq is None or entry.context_seq < unended_input_seq},
+ reverse=True,
+ )
+ return next((seq for seq in seqs if settled(entries, seq)), 0)
+
+
+def fork_point(entries: Sequence[ContextEntry], as_of: int) -> ForkPoint:
+ """An arbitrary point a system mechanism names: in range and settled, or ``ForkPointError``."""
+ bound = max((entry.context_seq for entry in entries), default=0)
+ if not 0 <= as_of <= bound:
+ raise ForkPointError("out_of_range", f"fork point {as_of} is outside the source context (0 to {bound})")
+ if not settled(entries, as_of):
+ raise ForkPointError("unsettled", f"fork point {as_of} leaves a tool call without its result")
+ return ForkPoint(as_of)
+
+
+def fork_prefix(entries: Sequence[ContextEntry], point: ForkPoint) -> tuple[Message, ...]:
+ """The fork's messages through its cut: the source's view at ``as_of``, whole or its first ``units`` units."""
+ view = context_view(entries, fork_point=point.as_of)
+ return view.prefix(len(view.units) if point.units is None else point.units)
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index f0ad69afa..ddbe29932 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -187,6 +187,8 @@ def reserve_forked_session(
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.
@@ -195,6 +197,15 @@ def reserve_forked_session(
``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")
@@ -260,6 +271,11 @@ def reserve_forked_session(
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 (
@@ -363,7 +379,7 @@ def reserve_forked_session(
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 anchor; the child's is resolved below.
+ # 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(
{
@@ -379,24 +395,19 @@ def reserve_forked_session(
}
)
if source_backend == "vibey":
- # Vibey's context is the source's rows up to the anchor, resolved
- # once now so later rows never enter the prefix (C-5 section 4). With no
- # running Turn the anchor is the whole context, as a native fork keeps the
- # whole settled session: a silent or stopped Turn shows no row to name.
- from storage.agent_transcript import context_bound, resolve_fork_anchor_seq
- from storage.models import session_turns
-
- running = conn.execute(
- select(session_turns.c.id).where(
- session_turns.c.session_id == str(row["id"]),
- session_turns.c.state.in_(("starting", "active")),
- ).limit(1)
- ).first()
- metadata["fork_source_context_seq"] = (
- resolve_fork_anchor_seq(conn, str(row["id"]), source_message_id)
- if running is not None
- else context_bound(conn, str(row["id"]))
- )
+ # 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:
diff --git a/docs/plans/agent-core-contracts/fork.md b/docs/plans/agent-core-contracts/fork.md
index 026566960..2278ef1da 100644
--- a/docs/plans/agent-core-contracts/fork.md
+++ b/docs/plans/agent-core-contracts/fork.md
@@ -125,11 +125,10 @@ Two kinds of fork, told apart by construction, never by timing:
| a self-fork | the largest settled `context_seq` of the source's context: the live Turn's input and finished steps, stopping before the response whose call is running the fork, which is still open |
| a system mechanism's fork at a given `context_seq` `s` (internal only: `reserve_forked_session(..., as_of=s)`, which no CLI, HTTP, or Web path passes) | `s`, when `0 <= s <=` the source's last `context_seq` and `s` is settled; otherwise refused (`ForkPointError`) |
-**The owner's rule for a user's fork**, for every backend: a fork never carries a live Turn. The cut is the end of the
-previous **ended** Turn: its final reply, or, for a Turn the user stopped or that failed, its last row once recovery
-has settled it (T2 and T3). The live Turn's input, its tool calls, and its intermediate responses never reach the
-child. Vibey enforces it through its fork point, as below; a native backend trims the live Turn or refuses the fork
-while it is live, by construction or by a check (§11). For Vibey it holds by construction:
+**The owner's rule for a user's fork of a Vibey Session**: a fork never carries a live Turn. The cut is the end of
+the previous **finished** Turn: its final reply, or, for a Turn the user stopped or that failed, its last row once
+recovery has settled it (T2 and T3). The live Turn's input, its tool calls, and its intermediate responses never
+reach the child. Vibey enforces it through its fork point, by construction:
- The live Turn writes all of its rows after its first input, because the loop is the Session's single writer
(C-5 §2), so every row before that input belongs to an ended Turn.
@@ -137,6 +136,9 @@ while it is live, by construction or by a check (§11). For Vibey it holds by co
later never move into or out of the prefix (C-5 §4).
- The fork never waits on, or races with, a timing condition.
+The rule is Vibey's. Native backends keep their existing fork logic, and C-10 makes no claim about the cut they take
+(§11, O-5).
+
**Unfinished Turn**, the one definition the cut, §15, and F3 use. A Turn is unfinished while any of these holds:
1. it is live (`session_turns.state` is `starting` or `active`);
@@ -164,10 +166,7 @@ Other rules:
- Today a fork of a running Vibey Turn takes the running Turn's first input as its anchor (`session_fork.py:263`,
`:389-399`). It includes that input row (`agent_transcript.py:521-527`), so the child starts with a request that
is unanswered and not its own.
-- Trimming removes that. It aligns Vibey with Codex and OpenCode, which already trim the live Turn
- (`session_fork.py:27`, `:269-286`).
-- Claude Code's native fork copies whatever is on disk when the child first runs. A test pins this
- (`tests/test_ui_session_stream.py:1101-1134`).
+- Trimming removes that.
## 3. Prefix identity
@@ -246,13 +245,10 @@ Consequences:
- **Child to source.** The reservation writes top-level metadata on the child Session (`session_fork.py:368-399`):
- `fork_source_session_id`
- - `fork_source_message_id`: unchanged, the anchor message the reservation reads (for a live Turn, its first
- input, which the cut excludes); native backends trim at it
- - `fork_source_context_seq`: Vibey only
+ - `fork_source_message_id`: unchanged, the anchor message the reservation reads (for a Vibey live Turn, its first
+ input, which the cut excludes)
+ - `fork_source_context_seq`: Vibey only, fixed at reservation, so whether the fork was a self-fork needs no record
- `fork_created_at`
- - `fork_self`: `true` on a self-fork only, so a native backend's first Turn skips the live-Turn check (§11). The
- reservation copies the source's metadata, so it removes a `fork_self` inherited from a source that was itself a
- self-fork; only a self-fork's reservation sets it.
- **Source to children.** This is absent today. Lineage is recorded only child to parent, and the UI only shows the
child's banner (`ui/src/components/workbench/ChatPage.tsx:4071-4083`). Retention and teams need the reverse
lookup. When one of them is designed, it adds an expression index on
@@ -366,7 +362,7 @@ move; the API reserves this (§15).
fork point (§2) inside the reservation's transaction and writes the metadata (§5): the user's latest point, a
self-fork's point with `self_fork=True` (only the `--fork-self` path passes it), or, with the internal keyword
`as_of`, a settled point a system mechanism names. No CLI, HTTP, or Web path passes `as_of`, and it is refused for
- other backends. Native backends trim or refuse while live (§11).
+ other backends. Native backends keep their existing fork logic and ignore `self_fork` (§11).
- **It owns nothing its ancestors started (F4).** A side turn, by contrast, starts nothing.
- Jobs, Watches, Tasks, delegated runs, and scratch stay with the Session that started them. In a nested fork (P,
then C forked from P, then D forked from C), a job P started still reports to P, not to D's source C.
@@ -447,38 +443,23 @@ information shown to the model.
| `core/agent_core/agent` | side turn: `SideTurn`, `ForkPolicy`, `DREAMING`, `Agent.side_turn`, `Agent.side_turn_fits` | extract them from C-9 (§12) |
| `storage/agent_transcript.py` | storage by reference, ancestry, `resolve_fork_point` (SQL around the harness rule) | replace `resolve_fork_anchor_seq` and `context_bound` |
| `modules/agents/vibey` | the fork notice on the first input; T2 without the inherited branch | as listed |
-| `core/services/session_fork.py` | the reservation for every backend | for `vibey`, call `resolve_fork_point`; the internal keyword `as_of` (no product surface passes it) |
-
-### Backend support and enforcement
-
-Point-in-time fork for native backends is cancelled (owner decision, 2026-10-10): they keep forking at the latest
-point, which they already support. The user-fork rule (§2) holds for every backend. Vibey and Codex enforce it by
-construction; OpenCode and Claude enforce it by a check, with the residual window stated below:
-
-| Backend | Fork | A user's fork while the source has a live Turn | Holds | A self-fork |
-| --- | --- | --- | --- | --- |
-| `vibey` | by reference (§2, §4); arbitrary settled points internally | **trim**: cut at the previous ended Turn, fixed at reservation | by construction | the largest settled point (§2) |
-| `codex` | `thread/fork` (`modules/agents/codex/agent.py:3316-3421`) | **trim**: `lastTurnId` is always the last completed Turn, resolved when the native fork runs (the child's first Turn), so a Turn that starts later is excluded by the backend's own boundary; when the whole turn listing proves no Turn has completed (the source's first Turn is live), the child starts a fresh thread, the empty prefix; an unknown boundary fails closed | by construction | unchanged (trims) |
-| `opencode` | `POST /session/{id}/fork` (`modules/agents/opencode/server.py:818-837`) | **trim**: `messageID` before the live Turn's input; checked at reservation and again at the child's first Turn | by check | unchanged (trims) |
-| `claude` | `resume` with `fork_session` (`core/handlers/session_handler.py:1558-1563`, `:1730-1731`) | **refuse while live**: `session_fork_source_running`, "This conversation is still running. Wait for the current turn to finish, then fork." (en and zh); checked at reservation and again at the child's first Turn | by check | unchanged: copies the transcript as it stands |
-
-A native fork copies when the child first runs, not at reservation, so each check runs at both points. The child's
-first Turn reads the source's Turn rows (`uq_session_turns_live_session`, `storage/models.py:875-879`) in a
-transaction, never a clock; for Claude a live source fails that Turn with the same message, its input kept for an
-explicit retry. A self-fork is exempt: the reservation records `fork_self` on the child, so the first-Turn checks
-skip it.
-
-**Residual window (OpenCode and Claude).** A source Turn that starts after the first-Turn check and before the
-backend makes its copy can still reach the child. Closing it needs no fence: the Turn owner's admission lock is
-best-effort, and Turn dispatch never awaits it (`core/session_turns.py:745-747`), so a fork must not block the
-source's next message. It needs a boundary the backend applies itself, which is the follow-up "native fork
-boundaries", scheduled after Phase 1b:
-
-- **OpenCode:** fork, then revert the private child to the last message of the last completed Turn, resolved before
- the fork call. Nothing else writes to the child, so nothing races.
-- **Claude:** `resume_session_at` with the UUID of the last message of the last completed Turn, read from Claude's own
- transcript when the native fork runs, with a fixture-based test against real transcripts. It replaces the refusal:
- Claude then trims like the others.
+| `core/services/session_fork.py` | the reservation for every backend | for `vibey`, call `resolve_fork_point` with `self_fork` from `--fork-self`; the internal keyword `as_of` (no product surface passes it; refused for native backends); nothing else changes for native backends |
+
+### Backend support
+
+Native backends keep their existing fork logic (owner decision O-5, 2026-10-10). C-10 changes nothing in how Claude,
+Codex, or OpenCode fork and makes no claim about the cut they take; any native question is a later discussion.
+Point-in-time fork for native backends is cancelled.
+
+| Backend | Fork | A user's fork | A self-fork |
+| --- | --- | --- | --- |
+| `vibey` | by reference (§2, §4); arbitrary settled points internally | cut before the earliest unfinished Turn, fixed at reservation (§2) | the largest settled point (§2) |
+| `codex` | `thread/fork` (`modules/agents/codex/agent.py:3316-3421`) | existing behavior, unchanged | existing behavior, unchanged |
+| `opencode` | `POST /session/{id}/fork` (`modules/agents/opencode/server.py:818-837`) | existing behavior, unchanged | existing behavior, unchanged |
+| `claude` | `resume` with `fork_session` (`core/handlers/session_handler.py:1558-1563`, `:1730-1731`) | existing behavior, unchanged | existing behavior, unchanged |
+
+For a native source, `reserve_forked_session` ignores `self_fork` and refuses the internal `as_of`
+(`session_fork_point_unsupported`); no product surface passes `as_of`.
### Surfaces
@@ -570,7 +551,7 @@ already provide, plus work outside fork.
| --- | --- | --- | --- |
| F1 | A fork's messages through its cut equal `prefix(source, point)`, and a fork Session gets the same bytes on every request, whatever either Session commits later | harness, storage | a source with checkpoints and edits both before and after the cut, plus a cut before a later checkpoint; after N commits in each Session, the child's projection through `as_of` serializes equal to `project(source, fork_point=as_of)` |
| F2 | A side turn's first request has the caller's endpoint, system prompt, tool definitions, tool choice, and reasoning settings, and its messages begin with the caller's latest request through the cut | agent | the stub's request log, for normal and rolling side turns |
-| F3 | Every fork point is settled; a fork never inherits an open call, and never settles or looks up a call it did not make (settled calls are inherited as history, F1) | harness, storage, service, adapters | a user's fork while the live Turn is mid tool batch gets exactly the previous ended Turn's prefix; a stopped and a failed previous Turn are legal cuts; nothing of the live Turn (input, calls, responses) reaches the child; every unfinished Turn (§2's definition: live, an open call awaiting T2, or an accepted input awaiting T3) is cut out whole; a Vibey self-fork keeps the live Turn's input and finished steps and no open call (native self-forks keep their behavior, §11); a user's fork of a Session that was itself a self-fork carries no `fork_self`; `--fork-session` naming the caller's own Session is a user's fork; a Codex fork always passes `lastTurnId` resolved at first use, including for a source that was idle at reservation, and starts a fresh thread when the listing proves no Turn has completed; an OpenCode user's fork trims a source that became live after reservation; a Claude user's fork is refused while the source has a live Turn, at reservation and at the child's first Turn, and a Claude self-fork is not; the internal API refuses an unsettled or out-of-range point and accepts 0 |
+| F3 | Every fork point is settled; a fork never inherits an open call, and never settles or looks up a call it did not make (settled calls are inherited as history, F1) | harness, storage, service, adapters | a user's fork while the live Turn is mid tool batch gets exactly the previous ended Turn's prefix; a stopped and a failed previous Turn are legal cuts; nothing of the live Turn (input, calls, responses) reaches the child; every unfinished Turn (§2's definition: live, an open call awaiting T2, or an accepted input awaiting T3) is cut out whole; a Vibey self-fork keeps the live Turn's input and finished steps and no open call; `--fork-session` naming the caller's own Session is a user's fork; the internal API refuses an unsettled or out-of-range point, accepts 0, and is refused for a native source; native fork tests pass unchanged (§11) |
| F4 | A fork Session owns nothing an ancestor started: jobs, Watches, Tasks, runs, scratch stay with the Session that started them. A side turn starts nothing: its calls have no call instance | vibey, service, agent | a child of a source with a live job Watch neither lists it nor receives its follow-up, and its first input carries the notice; a side turn's `bash` call starts no job even when a policy allowed it |
| F5 | A fork Session never writes a row of its source. A side turn writes only its audit row and, after the reply, what its fold commits | agent, storage | the source's rows before and after a child's Turns; the caller's rows after a failed and after a successful side turn |
| F6 | A side turn has no capability its caller lacks; a fork Session runs an Agent the requesting caller may select, on the source's backend | agent, service | a side turn's call to every tool its policy does not allow is denied and never runs; a reservation without editor on the source, chat in the destination, or selection authority for the Agent (inherited or `--agent`) is refused, as is an Agent on another backend |
@@ -664,9 +645,7 @@ def reserve_forked_session(*, source_session_id: str, ..., self_fork: bool = Fal
as_of: Optional[int] = None) -> SessionForkResult: ...
# vibey: resolve_fork_point(conn, source_session_id, as_of=as_of, self_fork=self_fork). self_fork is passed by
# --fork-self only; as_of is internal (no CLI, HTTP, or Web path passes it) and refused for other backends.
-# ForkPointError surfaces as SessionForkError. A backend that cannot trim a live Turn (claude) refuses a user's
-# fork while the source has one: SessionForkError(code="session_fork_source_running"), localized en and zh.
-def user_fork_source_is_running(fork: Mapping[str, Any]) -> bool: ... # the native first Turn's re-check
+# ForkPointError surfaces as SessionForkError. Native backends: unchanged; self_fork is ignored.
```
The `ForkTurn` audit (`agent_events.event_type = 'fork_turn'`, `visibility = 'audit'`, no `context_seq`) replaces
@@ -717,12 +696,12 @@ are those before the freeze PR.
| Phase | Scope | Acceptance (properties) |
| --- | --- | --- |
| 0 | this contract; owner decisions; the §16 delta; freeze | done 2026-10-10 |
-| 1a | the fork point for Vibey: `harness/fork.py` (`ForkPoint`, `settled`, `latest_cut`, `fork_point`, `fork_prefix`), `resolve_fork_point` (no clock); the existing session fork wired to it for `vibey`, trimming the live Turn, and `self_fork` from `--fork-self`; Codex's `lastTurnId` always resolved at first use; OpenCode's live check at first use; Claude's refusal while live (reservation and first Turn, en and zh copy); the fork notice; T2's inherited branch removed; the internal API for an arbitrary settled point (`resolve_fork_point(..., as_of=)` and `reserve_forked_session(..., as_of=)`) | F1, F3, F4, F6 (reservation), F8 pin; an E2E on a local dev instance with a throwaway home: fork a Vibey Session while it runs a long tool call, check the child's context, and check that the parent continues unaffected |
+| 1a | the fork point for Vibey: `harness/fork.py` (`ForkPoint`, `settled`, `latest_cut`, `fork_point`, `fork_prefix`), `resolve_fork_point` (no clock); the existing session fork wired to it for `vibey`, trimming the live Turn, and `self_fork` from `--fork-self`; native backends unchanged (O-5); the fork notice, also on the empty prefix; T2's inherited branch removed; the internal API for an arbitrary settled point (`resolve_fork_point(..., as_of=)` and `reserve_forked_session(..., as_of=)`) | F1, F3, F4, F6 (reservation), F8 pin; an E2E on a local dev instance with a throwaway home: fork a Vibey Session while it runs a long tool call, check the child's context, and check that the parent continues unaffected |
| 1b | C-9 on the side turn, as a pure refactor: `ForkPolicy` and `DREAMING`, `Agent.side_turn`, the `fork_turn` audit | F2, F5, F6 (policy), F7; the C-9 suite passes with only the audit kind renamed |
-| after 1b | native fork boundaries: OpenCode (revert the private child to the boundary), then Claude (`resume_session_at` from its own transcript, replacing the refusal) (§11) | the user-fork rule by construction for every backend; Claude's parser tested on fixtures of real transcripts |
| later | teams: the descendant lookup, a Session-invariant system prompt, an Agent fork tool, side turns while idle | a separate design |
Point-in-time fork for native backends (the former Phase 3) and the Harness bound are cancelled by owner decision.
+Native fork logic is not in any phase (O-5).
Files each lane touches, from a search of the code, tests, and prompts for the identifiers it changes
(`resolve_fork_anchor_seq`, `context_bound`, `fork_source_context_seq`, `call_instance_result`, `checkpoint_turn`,
@@ -730,7 +709,7 @@ Files each lane touches, from a search of the code, tests, and prompts for the i
| Lane | Code | Tests | Prompts |
| --- | --- | --- | --- |
-| 1a | `core/agent_core/harness/fork.py` (new); `storage/agent_transcript.py` (fork resolution); `core/services/session_fork.py`; `modules/agents/vibey/{agent,store,prompt}.py` (T2's inherited branch, the fork notice); `vibe/cli.py` (`self_fork` from `--fork-self`; localized fork errors); `vibe/ui_server.py` (localized fork errors); `core/handlers/session_handler.py` (Claude's first-Turn check); `modules/agents/codex/agent.py` (`lastTurnId` at first use); `modules/agents/opencode/session.py` (the live check at first use) | `tests/agent_core/agent/test_fork.py` (the pure rule), `tests/test_agent_transcript.py`, `tests/test_transcript_store_contract.py`, `tests/test_vibey_agent.py`, `tests/test_vibey_agent_context.py`, `tests/test_session_fork.py`, `tests/test_ui_session_stream.py` (the Claude fork), `tests/test_claude_cli_path.py`, `tests/test_cli_agent_run_schema.py`, `tests/test_codex_agent.py`, `tests/test_opencode_session_manager.py` | the fork notice's text; `vibe/i18n/{en,zh}.json` and `ui/src/i18n/{en,zh}.json` (`session_fork_source_running`) |
+| 1a | `core/agent_core/harness/fork.py` (new); `storage/agent_transcript.py` (fork resolution); `core/services/session_fork.py`; `modules/agents/vibey/{agent,store,prompt}.py` (T2's inherited branch, the fork notice); `vibe/cli.py` (`self_fork` from `--fork-self`) | `tests/agent_core/agent/test_fork.py` (the pure rule), `tests/test_agent_transcript.py`, `tests/test_transcript_store_contract.py`, `tests/test_vibey_agent.py`, `tests/test_vibey_agent_context.py`, `tests/test_session_fork.py`, `tests/test_cli_agent_run_schema.py` | the fork notice's text |
| 1b | `core/agent_core/agent/loop.py`; `core/agent_core/agent/checkpoint.py` (becomes `fork.py`); `core/agent_core/harness/context.py` (the `CHECKPOINT_TOOL_*` constants); `core/agent_core/harness/store.py` (the audit kind); `storage/agent_transcript.py` (the audit map, lines 94-95); `modules/agents/vibey/store.py` (the audit kind) | `tests/agent_core/fakes.py`, `tests/agent_core/agent/test_compaction.py`, `tests/agent_core/agent/test_context.py`, `tests/test_agent_transcript.py`, `tests/test_transcript_store_contract.py` | none |
1b follows 1a; they are not parallel lanes. Both edit `storage/agent_transcript.py` and its two test suites, and 1b
@@ -747,16 +726,15 @@ Decided 2026-10-10.
| O-2 | Point-in-time fork is internal only. Forking at an arbitrary settled point is an engine capability for system mechanisms (C-9, later memory and self context management), with no CLI, HTTP, or Web surface. A user's fork always takes the latest point: the end of the previous ended Turn, by construction (§2). |
| O-3 | No new Web interaction. The existing Fork action stays and follows the cut rule. No banner change, no inherited-history rendering, no edit-and-resend, no `design.pen` frame. |
| O-4 | No new limits. Agents keep forking themselves through `vibe agent run --fork-self`, with no depth or descendant bound. |
+| O-5 | Native backends keep their fork logic (2026-10-10, 17:03). This work does not change how Claude, Codex, or OpenCode fork, and focuses only on Vibey. The existing native fork logic is right, and any native issue is a later discussion. Supersedes the design lane's Claude refusal while live, Codex's first-use boundary, and OpenCode's first-use check. |
Also decided: point-in-time fork for native backends is cancelled, and teams stay a later design.
Decided in the design lane, all reversible:
- A user's fork of a Vibey Session trims a live Turn (§2), which O-2's rule confirms.
-- The user-fork rule holds for every backend: trim, or refuse while live (Claude); a self-fork is part of the Turn
- that requests it and keeps today's behavior (O-4). Vibey and Codex hold by construction in Phase 1; OpenCode and
- Claude by a check until the native fork boundaries land; no fence on the Turn owner. Confirmed by the
- orchestrator, 2026-10-10.
+- A self-fork is part of the Turn that requests it (O-4); only `--fork-self` makes one, and `--fork-session` naming
+ the caller's own Session is a user's fork. Confirmed by the orchestrator, 2026-10-10.
- The audit kind is renamed `fork_turn` (§7).
- Scratch is not forked (§4).
- Making the system prompt Session-invariant is left to the teams design (§3).
diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.md
index 2510653a2..85bba1b3a 100644
--- a/docs/plans/avibe-agent-core.md
+++ b/docs/plans/avibe-agent-core.md
@@ -388,7 +388,7 @@ contracts and checked against the implementing lane's code before they are close
| --- | --- | --- |
| Product-wide media retention | `storage/media_service.py` | No media file is removed from disk today, whether Workbench upload, IM attachment, or Avibe Agent context snapshot (`<state>/agent_core/media`); session deletion only clears or cascades `media_objects` references. Retention needs one owner for every source. It must be fork-aware: a fork descendant keeps replaying the image tokens of a source Session that was deleted. Recorded as a v1 known limit in PR #2345. |
| Steer receipt fencing in the shared Turn owner | `core/session_turns.py` (`_finish_steer`) | **Done in PR #2345** (orchestrator-authorized cross-lane fix): a negative receipt settles only a current attempt whose Deliveries are still steering or reconciling, and a caller that knows the attempt passes `expected_attempt_id`, so a late or duplicate receipt can no longer pull a Delivery out of a Turn that claimed it. Regression: `test_a_late_negative_steer_receipt_never_moves_a_delivery_its_attempt_no_longer_owns`. |
-| Fork as the runtime's base primitive | `core/agent_core/harness`, `core/agent_core/agent`, `storage/agent_transcript.py`, `core/services/session_fork.py` | Contract [`agent-core-contracts/fork.md`](agent-core-contracts/fork.md) (C-10, frozen 2026-10-10 by owner decision): one fork point with two carriers, the side turn and the fork Session. Phase 1a wires Vibey's existing session fork to the fork point (a user's fork cuts at the end of the previous ended Turn; arbitrary settled points are internal only, with no product surface); Phase 1b rebuilds C-9's checkpoint turn on the side turn. Teams are a later design; native point-in-time fork and a self-fork bound are not planned. |
+| Fork as the runtime's base primitive | `core/agent_core/harness`, `core/agent_core/agent`, `storage/agent_transcript.py`, `core/services/session_fork.py` | Contract [`agent-core-contracts/fork.md`](agent-core-contracts/fork.md) (C-10, frozen 2026-10-10 by owner decision): one fork point with two carriers, the side turn and the fork Session. Phase 1a wires Vibey's existing session fork to the fork point (a user's fork cuts at the end of the previous ended Turn; arbitrary settled points are internal only, with no product surface); Phase 1b rebuilds C-9's checkpoint turn on the side turn. Native backends keep their existing fork logic (owner decision, 2026-10-10). Teams are a later design; native point-in-time fork and a self-fork bound are not planned. |
| Hooks with context management | `core/agent_core/agent/` (C-3, C-9) | In v1, an Agent with a `ContextConfig` takes no user hooks: `before_model` rewrites and `before_tool`/`after_tool` decisions each changed what C-9 owns (the route, the projected prefix, artifacts, the checkpoint budget). A post-v1 design defines which hook outputs C-9 accepts and how it accounts for them before the two are combined (owner decision, PR #2360 round 5). |
| Call-instance identity for job files | `core/agent_core/tools/` (`ToolContext`, job `meta.json`), the adapter | **Done.** A tool call's identity is its instance: the owning response plus the call id, because providers reuse ids. The loop gives every executed call its instance (`ToolContext.call`: the response's row id and `context_seq`), and the job's `meta.json` records it. T2's job lookup (`find_job`), J5's settled check, and the hand-over's owning Turn match on the whole instance in context order; the clock fallback, which assumed a non-decreasing wall clock between a response's commit and its job's start, is gone. |
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index c4aacbaa3..c6f1234df 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -718,35 +718,24 @@ class VibeyAgent(BaseAgent):
return
suite = self._tools()
- def evidence() -> tuple[list[ContextEntry], dict[CallInstance, str]]:
- # A call is its instance, the owning response plus its id (providers reuse ids).
- # A call this Session inherited open takes the result its owner committed, matched
- # in context order; any other call, the job its instance started.
- inherited, found = [], {}
- with self._engine.connect() as conn:
- for owner, call in open_calls:
- if owner.session_id != session_id:
- result = call_instance_result(conn, owner.session_id, owner.context_seq, call.id)
- if result is not None:
- inherited.append(result)
- continue
- instance = CallInstance(owner.session_id, owner.row_id, owner.context_seq, call.id)
- job_id = suite.find_job(instance)
- if job_id is not None:
- found[instance] = job_id
- return inherited, found
+ def evidence() -> dict[CallInstance, str]:
+ # A call is its instance, the owning response plus its id (providers reuse ids). A fork's
+ # point is settled (C-10 fork.md section 2), so every open call is this Session's own.
+ found = {}
+ for owner, call in open_calls:
+ instance = CallInstance(owner.session_id, owner.row_id, owner.context_seq, call.id)
+ job_id = suite.find_job(instance)
+ if job_id is not None:
+ found[instance] = job_id
+ return found
# Each job lookup lists the jobs directory: one pass, off the event loop.
- inherited, job_ids = await asyncio.to_thread(evidence)
+ job_ids = await asyncio.to_thread(evidence)
# A tool result is the Agent's that made the call: its owning response's author, not
# the Turn writing it now (or none, at startup) or the Session's current selection.
# Only the last response can hold open calls, so they share one owner.
owner_agent = await asyncio.to_thread(self._author_of, open_calls[0][0].row_id)
with self.store.writing_as(session_id, owner_agent):
- for result in inherited:
- await self.store.append_tool_result(
- session_id, result.message, details=dict(result.payload.get("details") or {})
- )
await settle_open_calls(
session_id=session_id,
store=self.store,
diff --git a/modules/agents/vibey/prompt.py b/modules/agents/vibey/prompt.py
index 6c8777180..7f29122a2 100644
--- a/modules/agents/vibey/prompt.py
+++ b/modules/agents/vibey/prompt.py
@@ -54,6 +54,13 @@ TOOL_GUIDELINES: dict[str, tuple[str, ...]] = {
}
TOOL_ORDER = ("read", "bash", "edit", "write")
FINAL_REPLY_RULE = "Only your final reply is reliably shown to the user; put anything the user must see in it"
+#: The first input of a fork (C-10 fork.md section 8): the inherited history is the source's, and so is its work.
+FORK_NOTICE = (
+ "<fork>\nThis Session is a fork of {title} (Session {source}): {history}. Every command, Watch, Task, and run "
+ "in that Session stays with the Session that started it and reports there, not here.\n</fork>"
+)
+FORK_HISTORY = "the conversation above is that Session's history through context_seq {seq}"
+FORK_NO_HISTORY = "it starts empty, before that Session's first finished Turn, so no history is inherited"
def coding_prompt(tool_names: Iterable[str]) -> str:
@@ -201,6 +208,19 @@ def environment_delta(
}
+def with_fork_notice(message: UserMessage, *, source_session_id: str, source_title: str, through_seq: int) -> UserMessage:
+ """A fork's first input names whose history the model inherited and who owns the work in it (C-10 section 8).
+
+ Placed before the input's own content; the environment block, when there is one, still comes first.
+ """
+ notice = FORK_NOTICE.format(
+ title=display(source_title) if source_title else "an earlier Session",
+ source=display(source_session_id),
+ history=FORK_HISTORY.format(seq=int(through_seq)) if through_seq else FORK_NO_HISTORY,
+ )
+ return UserMessage(content=(TextBlock(text=notice), *message.content))
+
+
def with_environment(message: UserMessage, delta: Mapping[str, EnvironmentValue]) -> UserMessage:
if not delta:
return message
diff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.py
index b0635a7ce..8d7340988 100644
--- a/modules/agents/vibey/store.py
+++ b/modules/agents/vibey/store.py
@@ -6,6 +6,9 @@ Two adapter rules live at this boundary, where the loop consumes an input:
it is consumed, with the fields the projected context does not already show
(after a checkpoint, the summarized inputs' fields are not shown), so what
``consume_input`` stores is exactly what the model is sent;
+* a fork's first own input carries the fork notice (C-10 fork.md section 8):
+ whose history the model inherited, and that its work stays with the Session
+ that started it;
* a steered input's ``messages`` row is inserted by the Delivery manager right
after the backend accepts the steer. The loop can reach that input first, so
consumption waits, bounded, for the row to exist.
@@ -17,6 +20,7 @@ owns it; nothing here keeps responses after that.
from __future__ import annotations
import asyncio
+import json
from contextlib import contextmanager
import time
from typing import Any, Callable, Iterator, Literal, Mapping, Optional, Sequence
@@ -33,9 +37,10 @@ from modules.agents.vibey.prompt import (
environment_delta,
environment_state,
with_environment,
+ with_fork_notice,
)
-from storage.agent_transcript import SQLiteTranscriptStore
-from storage.models import messages
+from storage.agent_transcript import SQLiteTranscriptStore, fork_link
+from storage.models import agent_sessions, messages
EnvironmentSource = Callable[[str], Mapping[str, EnvironmentValue]]
ResponseObserver = Callable[[str, str, AssistantMessage], None]
@@ -104,8 +109,12 @@ class AdapterTranscriptStore:
if previous is None:
# What the model still sees: the inputs the projected context keeps. After a checkpoint the
# summarized inputs are gone, so the next input carries every field the context no longer shows.
- view = context_view(await self._store.load(session_id))
+ entries = await self._store.load(session_id)
+ view = context_view(entries)
previous = environment_state([unit.lead for unit in view.units if unit.lead.kind == "input"])
+ if not any(entry.session_id == session_id for entry in entries):
+ # No row of its own yet: a fork's first own input carries the notice, an empty prefix included.
+ message = await asyncio.to_thread(self._with_fork_notice, session_id, message)
current = dict(self._environment(session_id))
rendered = with_environment(message, environment_delta(previous, current))
entry = await self._store.consume_input(session_id, message_id, rendered)
@@ -159,6 +168,18 @@ class AdapterTranscriptStore:
await asyncio.sleep(delay)
delay = min(delay * 2, 0.25)
+ def _with_fork_notice(self, session_id: str, message: UserMessage) -> UserMessage:
+ with self._engine.connect() as conn:
+ link = fork_link(conn, session_id)
+ raw = conn.execute(select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)).scalar()
+ if link is None:
+ return message
+ metadata = json.loads(raw or "{}")
+ title = metadata.get("fork_source_session_title") if isinstance(metadata, dict) else None
+ return with_fork_notice(
+ message, source_session_id=link[0], source_title=str(title or ""), through_seq=link[1]
+ )
+
def _input_row_exists(self, session_id: str, message_id: str) -> bool:
with self._engine.connect() as conn:
owner = conn.execute(select(messages.c.session_id).where(messages.c.id == message_id)).scalar()
diff --git a/storage/agent_transcript.py b/storage/agent_transcript.py
index 241153997..16eb45973 100644
--- a/storage/agent_transcript.py
+++ b/storage/agent_transcript.py
@@ -31,17 +31,16 @@ Delivery, and that Turn's initial Delivery names the input row. That is the
channel the Turn answers, where ``persist_agent_message`` attributes the same
output, and a steer from another surface does not re-home the reply. An input
without a Delivery link stands for itself. ``agent_events.turn_id`` is that
-Turn. A fork that settles the calls it inherited open before its first input
-attributes those rows to its own scope, with no Turn.
-
-Fork. A child inherits its source's context rows up to ``anchor_seq``, read
-from the top-level Session metadata ``fork_source_session_id`` and
-``fork_source_context_seq`` and followed through the source's own fork. The
-anchor is resolved once, when the fork is reserved
-(``resolve_fork_anchor_seq``), so rows that receive a ``context_seq`` later can
-never move into or out of the prefix. A fork without that key (a released fork,
-or one from another backend) inherits nothing. The child's own rows continue
-from ``anchor_seq + 1``.
+Turn.
+
+Fork (C-10 ``fork.md``). A child inherits its source's context rows up to its
+fork point, read from the top-level Session metadata ``fork_source_session_id``
+and ``fork_source_context_seq`` and followed through the source's own fork. The
+point is resolved once, when the fork is reserved (``resolve_fork_point``), and
+is settled, so a child never inherits an open call; rows that receive a
+``context_seq`` later can never move into or out of the prefix. A fork without
+that key (a released fork, or one from another backend) inherits nothing. The
+child's own rows continue from the point plus one.
Display. A response row commits with the display text its renderer gives it.
Its display columns (``content_text``, the display keys of ``content_json``,
@@ -67,6 +66,8 @@ from typing import Any, Callable, Literal, Mapping, Optional, Sequence, TypeVar
from sqlalchemy import and_, func, or_, select, text
from sqlalchemy.engine import Connection, Engine
+from core.agent_core.harness.fork import fork_point, latest_cut
+from core.agent_core.harness.projection import open_tool_calls
from core.agent_core.harness.store import ContextEntry, EntryKind
from core.agent_core.messages import (
AssistantMessage,
@@ -79,6 +80,7 @@ from core.agent_core.messages import (
)
from storage import agent_events_service, messages_service
from storage.agent_session_rows import reserve_write_lock
+from storage.message_deliveries import TURN_OWNER_STATES
from storage.models import agent_events, agent_sessions, message_deliveries, messages, scopes, session_turns
INPUT_TYPES = ("user", "harness", "agent_initiated", "annotation")
@@ -377,16 +379,7 @@ class SQLiteTranscriptStore:
# One read snapshot across both tables and every ancestor.
if not conn.connection.dbapi_connection.in_transaction:
conn.exec_driver_sql("BEGIN")
- entries = [
- entry for member, bound in _ancestry(conn, session_id) for entry in _context_rows(conn, member, bound)
- ]
- entries.sort(key=lambda entry: entry.context_seq)
- for previous, current in zip(entries, entries[1:]):
- if previous.context_seq == current.context_seq:
- raise TranscriptError(
- f"rows {previous.row_id} and {current.row_id} share context_seq {current.context_seq}"
- )
- return entries
+ return _context_entries(conn, session_id)
async def _settle(task: asyncio.Future[Any]) -> None:
"""Wait for ``task`` to finish, whatever cancellations arrive meanwhile."""
@@ -489,50 +482,62 @@ def _turn_origin(conn: Connection, session_id: str, agent_name: Optional[str] =
# --- fork ancestry -------------------------------------------------------------
-def context_bound(conn: Connection, session_id: str) -> int:
- """The last ``context_seq`` of a Session's context, including the prefix it inherited.
+def resolve_fork_point(
+ conn: Connection, source_session_id: str, *, as_of: Optional[int] = None, self_fork: bool = False
+) -> int:
+ """The fork point of a new fork of ``source_session_id`` (C-10 ``fork.md`` section 2), in the caller's transaction.
- A fork of a Session with no running Turn inherits all of it: a Turn that ended
- silently or was stopped shows no row a message anchor could name.
+ A user's fork: the end of the previous ended Turn, so a live Turn's input, calls, and responses never reach the
+ child. ``self_fork``, the Agent's own fork from inside its live Turn: the largest settled point, which keeps that
+ Turn's input and finished steps and stops before the open call running the fork. ``as_of``: a point a system
+ mechanism names, which must be in range and settled (``ForkPointError`` otherwise). Decided from committed rows
+ and the live Turn's first input, never a clock. The reservation persists the result as the child's
+ ``fork_source_context_seq``.
"""
- link = fork_link(conn, session_id)
- return max(value for value in (_own_bound(conn, session_id), link[1] if link else 0) if value is not None)
+ entries = _context_entries(conn, source_session_id)
+ if as_of is not None:
+ return fork_point(entries, as_of).as_of
+ unended = None if self_fork else _unended_input_seq(conn, source_session_id, entries)
+ return latest_cut(entries, unended_input_seq=unended)
-def resolve_fork_anchor_seq(conn: Connection, source_session_id: str, anchor_message_id: Optional[str]) -> int:
- """``anchor_seq`` for a fork of ``source_session_id`` at ``anchor_message_id`` (C-5 §4).
+def _unended_input_seq(conn: Connection, session_id: str, entries: Sequence[ContextEntry]) -> Optional[int]:
+ """The first input of the earliest unfinished Turn (C-10 ``fork.md`` section 2).
- The largest ``context_seq`` of the source's context among rows at or before
- the anchor in transcript order, including the prefix the source itself
- inherited; the anchor may be a display-only row. The fork reservation calls
- this in its own transaction and persists the result as the child's
- ``fork_source_context_seq``.
+ A Turn is unfinished while it is live, while it holds a call without a result (T2), or while an input it
+ accepted is not yet in the context (T3). A Turn's first input is the row its initial Delivery names; Turns run
+ one at a time and each writes its rows after that input, so the Turn owning an open call is the latest one whose
+ input precedes the call. A Turn whose first input is not consumed has no row in the context yet.
"""
- link = fork_link(conn, source_session_id)
- inherited = link[1] if link is not None else 0
- if anchor_message_id is None:
- return inherited
- order = messages_service.transcript_order_value()
- anchor = conn.execute(
- select(messages.c.session_id, order.label("order_at")).where(messages.c.id == anchor_message_id)
- ).first()
- if anchor is None or anchor.session_id != source_session_id:
- raise TranscriptError(f"fork anchor {anchor_message_id} is not a message of Session {source_session_id}")
- own_messages = conn.execute(
- select(func.max(messages.c.context_seq)).where(
- messages.c.session_id == source_session_id,
- messages.c.context_seq.is_not(None),
- or_(order < anchor.order_at, and_(order == anchor.order_at, messages.c.id <= anchor_message_id)),
- )
- ).scalar()
- own_events = conn.execute(
- select(func.max(agent_events.c.context_seq)).where(
- agent_events.c.session_id == source_session_id,
- agent_events.c.context_seq.is_not(None),
- agent_events.c.created_at <= anchor.order_at,
- )
- ).scalar()
- return max(value for value in (inherited, own_messages, own_events) if value is not None)
+ turns = conn.execute(
+ select(session_turns.c.id, session_turns.c.state, messages.c.context_seq)
+ .select_from(session_turns.join(messages, messages.c.id == session_turns.c.initial_delivery_id))
+ .where(session_turns.c.session_id == session_id, messages.c.session_id == session_id)
+ ).all()
+ awaiting_input = set(
+ conn.execute(
+ select(message_deliveries.c.turn_id)
+ .select_from(message_deliveries.join(messages, messages.c.id == message_deliveries.c.message_id))
+ .where(
+ messages.c.session_id == session_id,
+ messages.c.context_seq.is_(None),
+ messages.c.type.in_(INPUT_TYPES),
+ message_deliveries.c.state == "accepted",
+ )
+ ).scalars()
+ )
+ inputs = sorted(seq for _, _, seq in turns if seq is not None)
+ candidates = [
+ seq
+ for turn_id, state, seq in turns
+ if seq is not None and (state in TURN_OWNER_STATES or turn_id in awaiting_input)
+ ]
+ open_calls = open_tool_calls(entries)
+ if open_calls:
+ first_open = min(owner.context_seq for owner, _ in open_calls)
+ owner_input = max((seq for seq in inputs if seq <= first_open), default=None)
+ candidates.append(owner_input if owner_input is not None else first_open)
+ return min(candidates, default=None)
def _settled_result(conn: Connection, session_id: str, tool_call_id: str) -> Optional[ContextEntry]:
@@ -698,6 +703,16 @@ def _ancestry(conn: Connection, session_id: str) -> list[tuple[str, Optional[int
# --- reading rows --------------------------------------------------------------
+def _context_entries(conn: Connection, session_id: str) -> list[ContextEntry]:
+ """The Session's context rows and its fork ancestry's, in ``context_seq`` order, read on ``conn``."""
+ entries = [entry for member, bound in _ancestry(conn, session_id) for entry in _context_rows(conn, member, bound)]
+ entries.sort(key=lambda entry: entry.context_seq)
+ for previous, current in zip(entries, entries[1:]):
+ if previous.context_seq == current.context_seq:
+ raise TranscriptError(f"rows {previous.row_id} and {current.row_id} share context_seq {current.context_seq}")
+ return entries
+
+
def _context_rows(conn: Connection, session_id: str, bound: Optional[int]) -> list[ContextEntry]:
entries: list[ContextEntry] = []
for table, columns, to_entry in (
diff --git a/tests/agent_core/agent/test_fork.py b/tests/agent_core/agent/test_fork.py
new file mode 100644
index 000000000..aa95654ab
--- /dev/null
+++ b/tests/agent_core/agent/test_fork.py
@@ -0,0 +1,118 @@
+"""C-10 fork point as pure functions (``agent-core-contracts/fork.md`` section 2)."""
+
+import pytest
+
+from core.agent_core.harness.fork import ForkPoint, ForkPointError, fork_point, fork_prefix, latest_cut, settled
+from core.agent_core.harness.projection import project
+from core.agent_core.harness.store import ContextEntry
+from core.agent_core.messages import ToolCallBlock, ToolResultMessage, text
+from tests.agent_core.agent.test_projection import _checkpoint_payload
+from tests.agent_core.fakes import assistant, user
+
+
+class Rows:
+ def __init__(self) -> None:
+ self.rows: list[ContextEntry] = []
+
+ def add(self, kind, message=None, payload=None) -> ContextEntry:
+ seq = len(self.rows) + 1
+ row = ContextEntry("source", seq, kind, f"{kind}-{seq}", message, payload or {})
+ self.rows.append(row)
+ return row
+
+ def input(self, value: str) -> ContextEntry:
+ return self.add("input", user(value))
+
+ def reply(self, value: str) -> ContextEntry:
+ return self.add("response", assistant(value))
+
+ def calls(self, *ids: str) -> ContextEntry:
+ return self.add("response", assistant("working", calls=[ToolCallBlock(call, "read") for call in ids]))
+
+ def result(self, call: str, value: str = "ok") -> ContextEntry:
+ return self.add("tool_result", ToolResultMessage(call, "read", (text(value),)))
+
+
+def _ended_turn_then(rows: Rows) -> int:
+ rows.input("first")
+ return rows.reply("first answer").context_seq
+
+
+def test_a_users_fork_of_a_turn_mid_tool_batch_cuts_at_the_previous_ended_turn():
+ rows = Rows()
+ ended = _ended_turn_then(rows)
+ live = rows.input("second")
+ rows.calls("a")
+ rows.result("a")
+ rows.calls("b", "c")
+ rows.result("b") # c is still running
+ assert latest_cut(rows.rows, unended_input_seq=live.context_seq) == ended
+ # Without the live Turn's first input the largest settled point is mid-Turn: what a self-fork takes.
+ assert latest_cut(rows.rows, unended_input_seq=None) == 5
+
+
[email protected]("outcome", ["stopped", "failed"])
+def test_a_stopped_or_failed_previous_turn_is_a_legal_cut_once_recovery_settled_it(outcome):
+ rows = Rows()
+ _ended_turn_then(rows)
+ rows.input("second")
+ rows.calls("a", "b")
+ rows.result("a")
+ # Recovery (T2) settles what the Stop or the failure left open, before the next Turn's input.
+ settled_by_recovery = rows.result("b", f"[tool call interrupted: {outcome}]")
+ live = rows.input("third")
+ assert latest_cut(rows.rows, unended_input_seq=live.context_seq) == settled_by_recovery.context_seq
+ assert latest_cut(rows.rows, unended_input_seq=None) == live.context_seq
+
+
+def test_an_ended_turn_recovery_has_not_settled_is_cut_out_whole():
+ rows = Rows()
+ ended = _ended_turn_then(rows)
+ ask = rows.input("second")
+ rows.calls("a")
+ rows.result("a")
+ rows.calls("b") # the Turn ended by a crash; T2 has not settled b yet
+ # The storage layer names that Turn's first input; nothing of the partial Turn is kept.
+ assert latest_cut(rows.rows, unended_input_seq=ask.context_seq) == ended
+ # Without it, the largest settled point would fall mid-Turn: what a self-fork from inside a live Turn takes.
+ assert latest_cut(rows.rows, unended_input_seq=None) == 5
+
+
+def test_an_empty_or_unanswered_context_cuts_at_the_empty_prefix():
+ assert latest_cut([], unended_input_seq=None) == 0
+ rows = Rows()
+ live = rows.input("only")
+ assert latest_cut(rows.rows, unended_input_seq=live.context_seq) == 0
+
+
+def test_the_internal_point_must_be_in_range_and_settled():
+ rows = Rows()
+ _ended_turn_then(rows)
+ rows.calls("a")
+ rows.result("a")
+ assert fork_point(rows.rows, 0) == ForkPoint(0)
+ assert fork_point(rows.rows, 4) == ForkPoint(4)
+ with pytest.raises(ForkPointError) as unsettled:
+ fork_point(rows.rows, 3)
+ assert unsettled.value.code == "unsettled"
+ for outside in (-1, 5):
+ with pytest.raises(ForkPointError) as out_of_range:
+ fork_point(rows.rows, outside)
+ assert out_of_range.value.code == "out_of_range"
+ assert settled(rows.rows, 2) and not settled(rows.rows, 3)
+
+
+def test_the_prefix_is_the_view_at_the_cut_and_a_later_checkpoint_does_not_exist_there():
+ rows = Rows()
+ _ended_turn_then(rows)
+ rows.input("second")
+ rows.reply("second answer")
+ rows.add("compaction", payload=_checkpoint_payload(3))
+ assert fork_prefix(rows.rows, ForkPoint(4)) == project(rows.rows, fork_point=4).messages
+ assert [message.content[0].text for message in fork_prefix(rows.rows, ForkPoint(4))] == [
+ "first",
+ "first answer",
+ "second",
+ "second answer",
+ ]
+ assert fork_prefix(rows.rows, ForkPoint(4, units=2)) == project(rows.rows, fork_point=2).messages
diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.py
index fbd9a95df..53fe95acc 100644
--- a/tests/test_agent_transcript.py
+++ b/tests/test_agent_transcript.py
@@ -30,7 +30,7 @@ from core.agent_core.messages import (
)
from config.paths import get_sqlite_state_path
from storage import message_deliveries, messages_service
-from storage.agent_transcript import SQLiteTranscriptStore, TranscriptError, resolve_fork_anchor_seq
+from storage.agent_transcript import SQLiteTranscriptStore, TranscriptError, resolve_fork_point
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events, messages
@@ -63,11 +63,13 @@ def _session(conn, session_id: str, scope_id: str, metadata: dict | None = None)
)
-def _fork(conn, session_id: str, scope_id: str, source_id: str, anchor_id: str | None) -> None:
- """A fork as reservation records it, with the anchor resolved by the transcript rule."""
- metadata = {"created_via": "session_fork", "fork_source_session_id": source_id, "fork_source_message_id": anchor_id}
- if anchor_id is not None:
- metadata["fork_source_context_seq"] = resolve_fork_anchor_seq(conn, source_id, anchor_id)
+def _fork(conn, session_id: str, scope_id: str, source_id: str, *, as_of: int | None = None) -> None:
+ """A fork as reservation records it: a user's fork at the latest point, or an internal one at ``as_of``."""
+ metadata = {
+ "created_via": "session_fork",
+ "fork_source_session_id": source_id,
+ "fork_source_context_seq": resolve_fork_point(conn, source_id, as_of=as_of),
+ }
_session(conn, session_id, scope_id, metadata)
@@ -338,7 +340,7 @@ async def test_concurrent_writers_never_share_a_context_seq(engine) -> None:
assert [entry.context_seq for entry in loaded] == list(range(1, 62))
-async def test_fork_chain_reads_the_ancestry_up_to_each_anchor(engine) -> None:
+async def test_fork_chain_reads_the_ancestry_up_to_each_fork_point(engine) -> None:
with engine.begin() as conn:
home = _scope(conn, "C-home")
_session(conn, "ses_root", home)
@@ -350,13 +352,13 @@ async def test_fork_chain_reads_the_ancestry_up_to_each_anchor(engine) -> None:
await store.append_tool_result("ses_root", _tool_result("call_1", "ok"), details={}),
]
with engine.begin() as conn:
- # A steer accepted before the anchor but consumed after the fork, and a
- # display-only anchor whose last preceding context row is a tool result.
+ # A steer accepted before the fork but consumed after it, and a display-only row: the latest settled
+ # point is the tool result.
steer = _row(conn, "ses_root", home, "steer")
- anchor = _row(conn, "ses_root", home, "progress", kind="notify")
- _fork(conn, "ses_child", home, "ses_root", anchor)
- # Released forks and forks of other backends carry no anchor_seq.
- _session(conn, "ses_released", home, {"fork_source_session_id": "ses_root", "fork_source_message_id": anchor})
+ _row(conn, "ses_root", home, "progress", kind="notify")
+ _fork(conn, "ses_child", home, "ses_root")
+ # Released forks and forks of other backends carry no fork point.
+ _session(conn, "ses_released", home, {"fork_source_session_id": "ses_root"})
await store.consume_input("ses_root", steer, _user("steer"))
await store.append_payload("ses_root", "compaction", {**COMPACTION, "first_kept_seq": 4})
@@ -368,16 +370,16 @@ async def test_fork_chain_reads_the_ancestry_up_to_each_anchor(engine) -> None:
await store.append_response("ses_child", _assistant("child done"), final=True),
]
with engine.begin() as conn:
- _fork(conn, "ses_grandchild", home, "ses_child", child[1].row_id)
+ _fork(conn, "ses_grandchild", home, "ses_child")
grandchild_ask = _row(conn, "ses_grandchild", home, "grandchild ask")
- # A fork at an earlier message of a Session that has moved on.
- _fork(conn, "ses_early", home, "ses_root", ask)
+ # An internal fork at an earlier settled point of a Session that has moved on.
+ _fork(conn, "ses_early", home, "ses_root", as_of=root[0].context_seq)
early_ask = _row(conn, "ses_early", home, "early ask")
grandchild = await store.consume_input("ses_grandchild", grandchild_ask, _user("grandchild ask"))
released = await store.consume_input("ses_released", released_ask, _user("fresh"))
early = await store.consume_input("ses_early", early_ask, _user("early ask"))
- # The child continues after the anchor; the root's later steer and checkpoint
+ # The child continues after its fork point; the root's later steer and checkpoint
# (4, 5) are not in its context.
assert [entry.context_seq for entry in child] == [4, 5]
assert list(await store.load("ses_child")) == root + child
diff --git a/tests/test_cli_agent_run_schema.py b/tests/test_cli_agent_run_schema.py
index f507d0507..ff451afcc 100644
--- a/tests/test_cli_agent_run_schema.py
+++ b/tests/test_cli_agent_run_schema.py
@@ -1721,6 +1721,55 @@ def test_agent_run_fork_rejects_cross_backend_agent(tmp_path: Path, capsys) -> N
assert payload["code"] == "session_fork_failed"
+ ("flags", "self_fork"),
+ [(["--fork-self"], True), (["--fork-session", "SOURCE"], False)],
+ ids=["fork-self", "fork-session-naming-own-session"],
+)
+def test_only_fork_self_is_the_agents_own_fork(tmp_path: Path, capsys, flags, self_fork) -> None:
+ # C-10 section 2: --fork-self, which resolves the source from AVIBE_SESSION_ID, is the only self-fork;
+ # --fork-session stays a user's fork even when it names the caller's own Session from inside its Turn.
+ from core.services import session_fork
+ from storage.importer import ensure_sqlite_state
+
+ state_home = tmp_path / "home"
+ with patch.dict("os.environ", {"AVIBE_HOME": str(state_home)}):
+ ensure_sqlite_state()
+ db_path = state_home / "state" / "vibe.sqlite"
+ source_session_id = _seed_bound_session(db_path, tmp_path)
+ agent_store = cli.VibeAgentStore(db_path)
+ agent_store.create(name="worker", backend="codex")
+ request_store = cli.TaskExecutionStore(tmp_path / "task_requests")
+ args = _parse_agent_run(
+ [
+ *[source_session_id if flag == "SOURCE" else flag for flag in flags],
+ "--agent",
+ "worker",
+ "--async",
+ "--no-callback",
+ "--message",
+ "try the other fix",
+ ]
+ )
+
+ with (
+ patch.dict("os.environ", {"AVIBE_SESSION_ID": source_session_id}),
+ patch("vibe.cli._agent_store", return_value=agent_store),
+ patch("vibe.cli._task_request_store", return_value=request_store),
+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),
+ patch("vibe.cli._primary_platform", return_value="slack"),
+ patch.object(
+ session_fork, "reserve_forked_session", wraps=session_fork.reserve_forked_session
+ ) as reserve,
+ ):
+ result = cli.cmd_agent_run(args)
+
+ assert result == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert payload["forked_from_session_id"] == source_session_id
+ assert reserve.call_args.kwargs["self_fork"] is self_fork
+
+
def test_agent_run_fork_localizes_unavailable_source_agent(monkeypatch) -> None:
from core.services.session_fork import (
SESSION_AGENT_UNAVAILABLE_CODE,
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index e2acd0e41..d8533d238 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import json
import sqlite3
from datetime import datetime, timezone
@@ -26,7 +27,7 @@ from modules.im import MessageContext
from storage.agent_session_rows import create_agent_session_row
from storage.db import create_sqlite_engine
from storage import message_deliveries, messages_service
-from storage.models import agent_events, agent_runs, agent_sessions, messages, scope_settings
+from storage.models import agent_events, agent_runs, agent_sessions, messages, scope_settings, session_turns
from storage.sessions_service import SQLiteSessionsService
from storage.settings_service import upsert_scope
@@ -201,41 +202,199 @@ def test_reserve_forked_session_copies_row_and_applies_overrides(tmp_path: Path)
assert metadata["fork_trim_latest_running_turn"] is False
-def test_reserve_forked_vibey_session_records_its_context_anchor(tmp_path: Path) -> None:
- # The Avibe Agent's context is the source's rows up to the anchor (C-5 section 4):
- # resolved once at reservation, so rows the source commits later never enter the prefix.
- db_path = tmp_path / "vibe.sqlite"
- source_id = _seed_source_session(db_path, tmp_path, backend="vibey")
+def _source_scope(db_path: Path, source_id: str) -> str:
engine = create_sqlite_engine(db_path)
try:
+ with engine.connect() as conn:
+ return conn.execute(select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)).scalar_one()
+ finally:
+ engine.dispose()
+
+
+def _seed_vibey_turns(db_path: Path, source_id: str) -> dict[str, int]:
+ """An ended Turn with its reply, then a live Turn mid tool batch: one finished step, one call still running."""
+ from core.agent_core.messages import ToolCallBlock, ToolResultMessage, UserMessage, text
+ from storage.agent_transcript import SQLiteTranscriptStore
+ from tests.agent_core.fakes import assistant
+
+ scope_id = _source_scope(db_path, source_id)
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteTranscriptStore(engine)
+
+ async def seed() -> dict[str, int]:
with engine.begin() as conn:
- scope_id = conn.execute(
- select(agent_sessions.c.scope_id).where(agent_sessions.c.id == source_id)
- ).scalar_one()
- turns = (("user", "user", "first question"), ("agent", "result", "first answer"),
- ("user", "user", "fyi"), ("agent", "assistant", ""))
- # The last Turn ended silently: its final is a hidden row no message anchor names.
- for seq, (author, mtype, text) in enumerate(turns, start=1):
- row = messages_service.append(
- conn, scope_id=scope_id, session_id=source_id, platform="avibe", author=author,
- source=author, message_type=mtype, text=text,
+ ask = messages_service.append(
+ conn, scope_id=scope_id, session_id=source_id, platform="avibe", author="user",
+ source="user", message_type="user", text="first question",
+ )
+ await store.consume_input(source_id, ask["id"], UserMessage((text("first question"),)))
+ answer = await store.append_response(source_id, assistant("first answer"), final=True)
+ with engine.begin() as conn:
+ turn_id = _seed_started_delivery(conn, scope_id=scope_id, session_id=source_id, text="ship it")
+ live_input = conn.execute(
+ select(session_turns.c.initial_delivery_id).where(
+ session_turns.c.id == turn_id
)
- conn.execute(messages.update().where(messages.c.id == row["id"]).values(context_seq=seq))
+ ).scalar_one()
+ live = await store.consume_input(source_id, live_input, UserMessage((text("ship it"),)))
+ await store.append_response(
+ source_id, assistant("Reading.", calls=[ToolCallBlock("call_read", "read")]), final=False
+ )
+ step = await store.append_tool_result(
+ source_id, ToolResultMessage("call_read", "read", (text("## 1.2.0"),)), details={}
+ )
+ await store.append_response(
+ source_id, assistant("Releasing.", calls=[ToolCallBlock("call_build", "bash")]), final=False
+ )
+ return {"answer": answer.context_seq, "live": live.context_seq, "step": step.context_seq}
+
+ try:
+ return asyncio.run(seed())
finally:
engine.dispose()
- result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+def _fork_metadata(db_path: Path, session_id: str) -> dict:
engine = create_sqlite_engine(db_path)
try:
with engine.connect() as conn:
- row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == result.session_id)).mappings().one()
+ raw = conn.execute(
+ select(agent_sessions.c.metadata_json).where(agent_sessions.c.id == session_id)
+ ).scalar_one()
finally:
engine.dispose()
- metadata = json.loads(row["metadata_json"])
+ return json.loads(raw)
+
+
+def test_a_users_fork_of_a_vibey_turn_mid_tool_batch_cuts_at_the_previous_ended_turn(tmp_path: Path) -> None:
+ # C-10 section 2: a user's fork never carries a live Turn; the cut is the end of the previous finished Turn,
+ # fixed once at reservation from committed rows.
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path, backend="vibey")
+ seqs = _seed_vibey_turns(db_path, source_id)
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ metadata = _fork_metadata(db_path, result.session_id)
assert result.fork.source_backend == "vibey"
- # With no running Turn the child inherits the whole settled context, as a native fork does.
- assert metadata["fork_source_context_seq"] == 4
+ assert metadata["fork_source_context_seq"] == seqs["answer"]
+
+
+def test_a_vibey_self_fork_keeps_its_live_turns_input_and_finished_steps(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path, backend="vibey")
+ seqs = _seed_vibey_turns(db_path, source_id)
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path, self_fork=True)
+
+ metadata = _fork_metadata(db_path, result.session_id)
+ # The largest settled point: after the finished step, before the response whose call runs the fork.
+ assert metadata["fork_source_context_seq"] == seqs["step"]
+
+
+def test_a_users_fork_cuts_out_an_ended_turn_whose_calls_await_recovery(tmp_path: Path) -> None:
+ # T2 has not settled the ended Turn's open call: it is cut out whole, like a live Turn, so the child never
+ # inherits a partial Turn whose recovery result would land after its fixed point.
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path, backend="vibey")
+ seqs = _seed_vibey_turns(db_path, source_id)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ session_turns.update()
+ .where(session_turns.c.session_id == source_id)
+ .values(state="terminal", terminal_outcome="failed", terminal_at="2026-08-01T00:02:00Z")
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert _fork_metadata(db_path, result.session_id)["fork_source_context_seq"] == seqs["answer"]
+
+
+def test_a_users_fork_cuts_out_an_ended_turn_with_an_accepted_input_not_yet_admitted(tmp_path: Path) -> None:
+ # T3: the Turn ended (no open call left) while a steer it accepted is not in the context yet; recovery admits
+ # it later. The Turn is unfinished, so it is cut out whole rather than fixed without that input.
+ from core.agent_core.messages import ToolResultMessage, text
+ from storage.agent_transcript import SQLiteTranscriptStore
+ from tests.agent_core.fakes import assistant
+
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path, backend="vibey")
+ seqs = _seed_vibey_turns(db_path, source_id)
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteTranscriptStore(engine)
+
+ async def finish_the_turn() -> None:
+ await store.append_tool_result(
+ source_id, ToolResultMessage("call_build", "bash", (text("built"),)), details={}
+ )
+ await store.append_response(source_id, assistant("Released."), final=True)
+
+ try:
+ asyncio.run(finish_the_turn())
+ with engine.begin() as conn:
+ turn = conn.execute(select(session_turns).where(session_turns.c.session_id == source_id)).mappings().one()
+ steer = message_deliveries.insert_delivery(
+ conn,
+ delivery_id=message_deliveries.new_delivery_id(),
+ session_id=source_id,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=_source_scope(db_path, source_id),
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="also bump the version",
+ ),
+ dispatch_text="also bump the version",
+ )
+ assert message_deliveries.open_steer_attempt(
+ conn,
+ steer["id"],
+ expected_version=int(steer["version"]),
+ turn_id=turn["id"],
+ attempt_id="att_steer",
+ expected_native_turn_id=turn["native_turn_id"],
+ )
+ assert message_deliveries.materialize_steer_acceptance(
+ conn, leader_delivery_id=steer["id"], expected_attempt_id="att_steer", turn_id=turn["id"], evidence={}
+ )
+ conn.execute(
+ session_turns.update()
+ .where(session_turns.c.id == turn["id"])
+ .values(state="terminal", terminal_outcome="failed", terminal_at="2026-08-01T00:02:00Z")
+ )
+ finally:
+ engine.dispose()
+
+ result = reserve_forked_session(source_session_id=source_id, db_path=db_path)
+
+ assert _fork_metadata(db_path, result.session_id)["fork_source_context_seq"] == seqs["answer"]
+
+
+def test_an_internal_fork_point_must_be_settled_and_needs_a_vibey_source(tmp_path: Path) -> None:
+ db_path = tmp_path / "vibe.sqlite"
+ source_id = _seed_source_session(db_path, tmp_path, backend="vibey")
+ seqs = _seed_vibey_turns(db_path, source_id)
+
+ earlier = reserve_forked_session(source_session_id=source_id, db_path=db_path, as_of=seqs["live"])
+ assert _fork_metadata(db_path, earlier.session_id)["fork_source_context_seq"] == seqs["live"]
+ with pytest.raises(SessionForkError) as unsettled:
+ reserve_forked_session(source_session_id=source_id, db_path=db_path, as_of=seqs["step"] + 1)
+ assert unsettled.value.code == "session_fork_point_unsettled"
+
+ native_db = tmp_path / "native" / "vibe.sqlite"
+ native_db.parent.mkdir()
+ native_id = _seed_source_session(native_db, tmp_path)
+ with pytest.raises(SessionForkError) as unsupported:
+ reserve_forked_session(source_session_id=native_id, db_path=native_db, as_of=0)
+ assert unsupported.value.code == "session_fork_point_unsupported"
def test_reserve_forked_codex_running_fork_marks_trim(tmp_path: Path) -> None:
diff --git a/tests/test_transcript_store_contract.py b/tests/test_transcript_store_contract.py
index 5aa68651d..7fa8a95b0 100644
--- a/tests/test_transcript_store_contract.py
+++ b/tests/test_transcript_store_contract.py
@@ -25,7 +25,7 @@ from core.agent_core.harness.store import TranscriptStore
from core.agent_core.messages import AssistantMessage, ToolCallBlock, ToolResultMessage, Usage, text, usage_to_dict
from modules.agents.vibey.store import AdapterTranscriptStore
from storage import agent_events_service, messages_service
-from storage.agent_transcript import SQLiteTranscriptStore, resolve_fork_anchor_seq
+from storage.agent_transcript import SQLiteTranscriptStore, resolve_fork_point
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events
@@ -115,8 +115,7 @@ class _SQLite:
metadata = {
"created_via": "session_fork",
"fork_source_session_id": source,
- "fork_source_message_id": anchor.row_id,
- "fork_source_context_seq": resolve_fork_anchor_seq(conn, source, anchor.row_id),
+ "fork_source_context_seq": resolve_fork_point(conn, source, as_of=anchor.context_seq),
}
_session(conn, child, self.scope, metadata)
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index ac1c26351..37370b8b5 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -44,7 +44,7 @@ from modules.agents.base import AgentRequest
from modules.agents.model_hub import ModelHubLaunch
from modules.im import MessageContext
from storage import message_deliveries
-from storage.agent_transcript import resolve_fork_anchor_seq
+from storage.agent_transcript import resolve_fork_point
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events, agent_sessions, messages, session_turns
@@ -971,14 +971,47 @@ async def test_resume_renders_a_recovered_steer_as_the_live_path_would(engine, s
assert "From: #ses_source" in recovered.message.content[-1].text
-async def test_a_fork_from_an_earlier_message_continues_only_the_inherited_prefix(
+async def _blocked_second_turn(engine, tmp_path, *, finished_step: bool):
+ """A source whose first Turn ended with a reply and whose second Turn is live, blocked inside a tool call."""
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def release_build(arguments, ctx):
+ started.set()
+ await release.wait()
+ return ToolResult((text("release 1.2.0 published"),))
+
+ read = ToolCallBlock(id="call_read", name="read", arguments={"path": "CHANGELOG.md"})
+ build = ToolCallBlock(id="call_build", name="bash", arguments={"command": "make release"})
+ second = [[Done(assistant("Reading first.", calls=(read,)))]] if finished_step else []
+ source = _Harness(
+ engine,
+ tmp_path,
+ "avibe",
+ [
+ [Done(assistant("first answer"))],
+ *second,
+ [Done(assistant("Releasing.", calls=(build,)))],
+ [Done(assistant("Released."))],
+ ],
+ tools=[
+ FakeTool("read", result=ToolResult((text("## 1.2.0"),))),
+ FakeTool("bash", execute=release_build),
+ ],
+ )
+ await source.agent.handle_message(source.request("first question"))
+ running = asyncio.create_task(source.agent.handle_message(source.request("ship it")))
+ await started.wait()
+ return source, running, release
+
+
+async def test_a_users_fork_of_a_turn_mid_tool_batch_gets_exactly_the_previous_ended_turn(
engine, session, tmp_path, published
) -> None:
- source = _Harness(engine, tmp_path, "avibe", [[Done(assistant("first answer"))], [Done(assistant("later"))]])
- await source.agent.handle_message(source.request("first question"))
- [anchor] = source.rows("result")
+ source, running, release = await _blocked_second_turn(engine, tmp_path, finished_step=True)
+ [first_answer] = source.rows("result")
with engine.begin() as conn:
- # What fork reservation records (core/services/session_fork.py, C-5 section 4).
+ # What reservation records for a user's fork (core/services/session_fork.py, C-10 section 2).
+ cut = resolve_fork_point(conn, SESSION)
_insert_session(
conn,
"ses_child",
@@ -986,47 +1019,49 @@ async def test_a_fork_from_an_earlier_message_continues_only_the_inherited_prefi
{
"created_via": "session_fork",
"fork_source_session_id": SESSION,
- "fork_source_message_id": anchor["id"],
- "fork_source_context_seq": resolve_fork_anchor_seq(conn, SESSION, anchor["id"]),
+ "fork_source_session_title": "Release work",
+ "fork_source_context_seq": cut,
},
)
- # The source moves on after the fork; none of it may reach the child.
- await source.agent.handle_message(source.request("source continues"))
+ live = [entry for entry in await source.context_rows() if entry.context_seq > cut]
+ # The previous Turn ended with its reply; the live Turn's input and finished step come after it.
+ assert cut == first_answer["context_seq"]
+ assert [entry.kind for entry in live] == ["input", "response", "tool_result", "response"]
+
+ # The source continues, unaffected by the fork.
+ release.set()
+ await running
+ assert [row["content_text"] for row in source.rows("result")] == ["first answer", "Released."]
child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("child answer"))]], session_id="ses_child")
await child.agent.handle_message(child.request("child question"))
- inherited = [entry for entry in await source.context_rows() if entry.context_seq <= 2]
rows = await child.context_rows()
- assert rows[:2] == inherited
- assert [(entry.session_id, entry.context_seq, entry.kind) for entry in rows[2:]] == [
- ("ses_child", 3, "input"),
- ("ses_child", 4, "response"),
+ inherited = [entry for entry in await source.context_rows() if entry.context_seq <= cut]
+ assert rows[: len(inherited)] == inherited
+ assert [(entry.session_id, entry.context_seq, entry.kind) for entry in rows[len(inherited) :]] == [
+ ("ses_child", cut + 1, "input"),
+ ("ses_child", cut + 2, "response"),
]
+ # Nothing of the live Turn reaches the child: not its input, its calls, or its replies.
+ live_ids = {entry.row_id for entry in live}
+ assert not live_ids & {entry.row_id for entry in rows}
[request] = child.provider.requests
- assert request.messages == project(rows[:3]).messages
- assert "source continues" not in json.dumps([str(message) for message in request.messages], ensure_ascii=False)
-
-
-async def test_a_fork_settles_a_call_it_inherited_open_with_the_sources_result(
- engine, session, tmp_path, published
-) -> None:
- # The source's job is gone (J5 pruned it once the source's call settled).
- suite = ToolSuite(
- jobs=FakeJobHost(),
- create_tools=lambda jobs_, sink: [FakeTool("bash")],
- render_recovered=_unused_renderer,
- find_job=lambda *_args, **_kwargs: None,
- )
- call = ToolCallBlock(id="call_1", name="bash", arguments={"command": "make release"})
- source = _Harness(
- engine, tmp_path, "avibe", [[Done(assistant("Releasing.", calls=(call,)))], [Done(assistant("Released."))]],
- tools=[FakeTool("bash", result=ToolResult((text("release 1.2.0 published"),)))],
- )
- await source.agent.handle_message(source.request("ship it"))
- narration = (await source.context_rows())[1]
+ sent = json.dumps([str(message) for message in request.messages], ensure_ascii=False)
+ assert "ship it" not in sent and "make release" not in sent and "Reading first." not in sent
+ assert request.messages == project(rows[: len(inherited) + 1]).messages
+ # The child's first input says whose history it inherited and who owns the work in it.
+ first_input = rows[len(inherited)].message.content
+ [notice] = [block.text for block in first_input if isinstance(block, TextBlock) and block.text.startswith("<fork>")]
+ assert "fork of Release work (Session " + SESSION + ")" in notice
+ assert f"through context_seq {cut}" in notice
+ assert "stays with the Session that started it" in notice
+
+
+async def test_a_fork_at_the_empty_prefix_still_carries_the_fork_notice(engine, session, tmp_path, published) -> None:
+ # A fork cut at 0 (the source's first Turn is live) inherits no row, yet its first input still says whose fork
+ # it is and that the source's work stays there.
with engine.begin() as conn:
- # A fork from the narration message: its anchor precedes the call's result.
_insert_session(
conn,
"ses_child",
@@ -1034,78 +1069,35 @@ async def test_a_fork_settles_a_call_it_inherited_open_with_the_sources_result(
{
"created_via": "session_fork",
"fork_source_session_id": SESSION,
- "fork_source_message_id": narration.row_id,
- "fork_source_context_seq": resolve_fork_anchor_seq(conn, SESSION, narration.row_id),
+ "fork_source_session_title": "Release work",
+ "fork_source_context_seq": 0,
},
)
- child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]], suite=suite, session_id="ses_child")
+ child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("child answer"))]], session_id="ses_child")
+ await child.agent.handle_message(child.request("child question"))
- await child.agent.handle_message(child.request("what happened?"))
+ first = (await child.context_rows())[0]
+ assert first.context_seq == 1 and first.session_id == "ses_child"
+ blocks = [block.text for block in first.message.content if isinstance(block, TextBlock)]
+ [notice] = [text_value for text_value in blocks if text_value.startswith("<fork>")]
+ assert "fork of Release work (Session " + SESSION + ")" in notice
+ assert "no history is inherited" in notice
+ assert "stays with the Session that started it" in notice
- rows = await child.context_rows()
- assert [(entry.session_id, entry.kind) for entry in rows[:3]] == [
- (SESSION, "input"), (SESSION, "response"), ("ses_child", "tool_result")
- ]
- # The child settles with what the source recorded, not with an uncertain effect.
- assert rows[2].message.content == (text("release 1.2.0 published"),)
- assert child.provider.requests[0].messages == project(rows[:4]).messages
-
-async def test_a_nested_fork_takes_the_result_of_its_own_call_instance(engine, session, tmp_path, published) -> None:
- # Grandparent SESSION -> parent ses_parent -> child ses_child; providers reuse the call id.
- reused = ToolCallBlock(id="call_1", name="bash", arguments={})
- grandparent = _Harness(
- engine, tmp_path, "avibe",
- [[Done(assistant("hello"))], [Done(assistant("", calls=(reused,)))], [Done(assistant("checked"))]],
- tools=[FakeTool("bash", result=ToolResult((text("the grandparent's own check"),)))],
- )
- await grandparent.agent.handle_message(grandparent.request("hi"))
- [anchor] = grandparent.rows("result")
+async def test_a_self_fork_keeps_the_live_turns_input_and_finished_steps(engine, session, tmp_path, published) -> None:
+ source, running, release = await _blocked_second_turn(engine, tmp_path, finished_step=True)
with engine.begin() as conn:
- _insert_session(conn, "ses_parent", _SCOPES["avibe"], {
- "created_via": "session_fork",
- "fork_source_session_id": SESSION,
- "fork_source_message_id": anchor["id"],
- "fork_source_context_seq": resolve_fork_anchor_seq(conn, SESSION, anchor["id"]),
- })
- started, release = asyncio.Event(), asyncio.Event()
-
- async def release_build(arguments, ctx):
- started.set()
- await release.wait()
- return ToolResult((text("release 1.2.0 published"),))
-
- parent = _Harness(
- engine, tmp_path, "avibe",
- [[Done(assistant("Releasing.", calls=(reused,)))], [Done(assistant("Released."))]],
- tools=[FakeTool("bash", execute=release_build)], session_id="ses_parent",
- )
- running = asyncio.create_task(parent.agent.handle_message(parent.request("ship it")))
- await started.wait()
- # The grandparent continues on its own and settles its own call_1 first.
- await grandparent.agent.handle_message(grandparent.request("check something"))
+ user_cut = resolve_fork_point(conn, SESSION)
+ self_cut = resolve_fork_point(conn, SESSION, self_fork=True)
+ rows = await source.context_rows()
+ by_seq = {entry.context_seq: entry for entry in rows}
+ # The Agent's own fork from inside its live Turn keeps that Turn's input and its finished step, and stops
+ # before the response whose call is still running: no open call is inherited.
+ assert [by_seq[seq].kind for seq in range(user_cut + 1, self_cut + 1)] == ["input", "response", "tool_result"]
+ assert by_seq[self_cut + 1].message.tool_calls[0].id == "call_build"
release.set()
await running
- narration = next(entry for entry in await parent.context_rows() if entry.session_id == "ses_parent"
- and entry.kind == "response")
- with engine.begin() as conn:
- _insert_session(conn, "ses_child", _SCOPES["avibe"], {
- "created_via": "session_fork",
- "fork_source_session_id": "ses_parent",
- "fork_source_message_id": narration.row_id,
- "fork_source_context_seq": resolve_fork_anchor_seq(conn, "ses_parent", narration.row_id),
- })
- suite = ToolSuite(
- jobs=FakeJobHost(), create_tools=lambda jobs_, sink: [FakeTool("bash")],
- render_recovered=_unused_renderer, find_job=lambda *_args, **_kwargs: None,
- )
- child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))]], suite=suite, session_id="ses_child")
-
- await child.agent.handle_message(child.request("what happened?"))
-
- [settled] = [entry for entry in await child.context_rows()
- if entry.session_id == "ses_child" and entry.kind == "tool_result"]
- assert settled.message.content == (text("release 1.2.0 published"),)
async def test_a_google_hop_is_called_over_chat_at_the_gateway_prefix(engine, session, tmp_path, published) -> None:
diff --git a/vibe/cli.py b/vibe/cli.py
index e7cfa715b..5623e68a0 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -6598,6 +6598,7 @@ def _reserve_forked_cli_session(
scope_key: Optional[str],
visibility: str,
authorization_context=None,
+ self_fork: bool = False,
):
from core.services.session_fork import (
SESSION_AGENT_UNAVAILABLE_CODE,
@@ -6616,6 +6617,7 @@ def _reserve_forked_cli_session(
visibility=visibility,
db_path=paths.get_sqlite_state_path(),
authorization_context=authorization_context,
+ self_fork=self_fork,
)
except SessionForkError as exc:
if exc.code == SESSION_AGENT_UNAVAILABLE_CODE:
@@ -6873,6 +6875,9 @@ def cmd_agent_run(args):
scope_key=scope_key,
visibility=visibility,
authorization_context=caller_authorization,
+ # Only --fork-self, which resolves the source from AVIBE_SESSION_ID, is the Agent's own fork
+ # from inside its live Turn; --fork-session is a user's fork even when it names that Session.
+ self_fork=bool(getattr(args, "fork_self", False)),
)
session_id = fork_result.session_id
reserved_session_id = session_id