diff --git a/docs/core-data-structures/session.md b/docs/core-data-structures/session.md index dc755b9c3f..69ac26bad0 100644 --- a/docs/core-data-structures/session.md +++ b/docs/core-data-structures/session.md @@ -163,9 +163,9 @@ Everything else (`turn/*`, `step/*`) is structural and does not project into a m `ctx.sessions.create(id, { seed, meta })` is the low-level replay/fork primitive. For ordinary live-session forks, `SessionStore` exposes one policy API: -- `fork({ source, boundary?, childSessionId? })` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `boundary` seq (default: current last event), validates that selected prefix is turn-enclosed and empty or ends at `turn/end`, then creates a live child session with deep-cloned seed events plus child metadata (`parentSession`, `seedLength`, and inherited `cwd`). +- `fork({ source, boundary?, childSessionId? })` accepts a live `Session` object or live `SessionId`, selects source events through the inclusive `boundary` seq (default: current last event), requires the boundary event to be `turn/end`, then creates a live child session with deep-cloned seed events plus child metadata (`parentSession`, `seedLength`, and inherited `cwd`). -An explicit `boundary` lets callers fork from a previous completed turn even if the source has newer events or an open current turn. The API rejects open or malformed selected prefixes instead of clipping silently. `dsh-subagent-fork` keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should make the requested boundary explicit. +An explicit `boundary` lets callers fork from a previous completed turn even if the source has newer events or an open current turn. The API rejects non-`turn/end` boundaries instead of clipping silently. Broader turn-enclosure sanity stays in the existing `dsh-invariants` plugin and persistence repair path rather than being duplicated in `fork()`. `dsh-subagent-fork` keeps its completed-prefix clipping because tool-time delegation usually starts while the parent turn is open; ordinary session branching should make the requested boundary explicit. ## What started a turn: `TurnTriggerMap` diff --git a/docs/rfc/implemented/feature/2026-06-30-session-store-fork-api.md b/docs/rfc/implemented/feature/2026-06-30-session-store-fork-api.md index cbc445d727..a1eac1baec 100644 --- a/docs/rfc/implemented/feature/2026-06-30-session-store-fork-api.md +++ b/docs/rfc/implemented/feature/2026-06-30-session-store-fork-api.md @@ -28,9 +28,9 @@ class SessionStore extends Service { } ``` -`boundary` is the inclusive source event `seq` to copy through. When omitted, it defaults to the source session's current last event; on an empty source, omitted `boundary` creates an empty child. The selected prefix is deep-cloned into the child seed. The child inherits the source session's `cwd`, stamps `parentSession` to the source id, and sets `seedLength` to the copied prefix length. When `childSessionId` is omitted, `SessionStore` generates one using its existing id policy. +`boundary` is the inclusive source event `seq` to copy through. When omitted, it defaults to the source session's current last event; on an empty source, omitted `boundary` creates an empty child. Fork-specific validation only checks that the requested boundary exists and is a `turn/end`. The selected prefix is then deep-cloned into the child seed. The child inherits the source session's `cwd`, stamps `parentSession` to the source id, and sets `seedLength` to the copied prefix length. When `childSessionId` is omitted, `SessionStore` generates one using its existing id policy. -The boundary rule is structural: an empty selected prefix is forkable, and any non-empty selected prefix must be turn-enclosed and end at `turn/end`, regardless of the turn-end reason (`completed`, `aborted`, `error`, `disposed`, `max-tokens`, `interrupted`, or a future merge-extensible reason). Any selected prefix whose boundary is not an existing event seq, ends inside a turn, contains events outside a turn, contains nested turns, or has an orphan `turn/end` is rejected with a typed `SessionForkError` code. The API also classifies non-live source ids (`SESSION_NOT_FOUND`), stale `Session` object references whose id is live on a different instance (`SESSION_NOT_LIVE`), duplicate requested child ids (`SESSION_ALREADY_EXISTS`), and invalid boundary values (`INVALID_BOUNDARY`). +The boundary rule is structural: an empty selected prefix is forkable, and any non-empty selected prefix must end at `turn/end`, regardless of the turn-end reason (`completed`, `aborted`, `error`, `disposed`, `max-tokens`, `interrupted`, or a future merge-extensible reason). A boundary that is not an existing event seq, is not a safe integer, or does not point at `turn/end` is rejected with a typed `SessionForkError` code. Broader session-log sanity remains in the existing invariant/repair layers: `dsh-invariants` checks turn enclosure and richer event ordering in dev, while persistence repair handles the valid crash-tail case of a final interrupted turn. The API also classifies non-live source ids (`SESSION_NOT_FOUND`), stale `Session` object references whose id is live on a different instance (`SESSION_NOT_LIVE`), duplicate requested child ids (`SESSION_ALREADY_EXISTS`), and invalid boundary values (`INVALID_BOUNDARY`). ## Alternatives considered diff --git a/packages/core/session/README.md b/packages/core/session/README.md index 7115b162cf..030af3700c 100644 --- a/packages/core/session/README.md +++ b/packages/core/session/README.md @@ -9,7 +9,7 @@ Creates and holds event-sourced `Session` instances. Persistence is intentionall ### Public API - `ctx.sessions.create(id?: SessionId, options?: { seed?: SessionEvent[]; meta?: { cwd?: string; parentSession?: SessionId; createdAt?: number; seedLength?: number } }): Session` — Create a session. `options.seed` replays/forks an existing event log; `options.meta` attaches creation metadata (validated absolute `cwd`, `parentSession` lineage, seed boundary) as the immutable `SessionHeader`. The store fills `version`/`id` and defaults `createdAt` to now; a caller reconstructing a persisted session passes the original `createdAt` and persisted `seedLength` to preserve them. Disposed with the calling fiber. -- `ctx.sessions.fork({ source, boundary?, childSessionId? }): Session` — Resolve a live session object or id, select a seed through the inclusive `boundary` event seq (default: current last event), require that selected prefix to be turn-enclosed, and create a live child session with lineage metadata. +- `ctx.sessions.fork({ source, boundary?, childSessionId? }): Session` — Resolve a live session object or id, select a seed through the inclusive `boundary` event seq (default: current last event), require that boundary to be `turn/end`, and create a live child session with lineage metadata. - `ctx.sessions.get(id: SessionId): Session | undefined` - `ctx.sessions.list(): Session[]` @@ -68,7 +68,7 @@ Every `SessionEvent` carries two optional top-level fields (structural metadata) ### Extension points - Persistence plugins: subscribe to `session/event` (write-behind) and drain on `session/flush` (awaited) and fiber dispose. A durable backend reads the log and reloads it into a live session; the metadata seam (`SessionHeader`, `session.header`) is what such a backend stores beside the log. -- Replay/fork: `ctx.sessions.create(id, { seed })` seeds a new session with an existing event log. The surface rebuilds deterministically from `surfaceOp` markers in the seeded events. The seed is validated to the SAME invariants `append` enforces — including that every surface-eligible event (`SurfaceEventType`) carries a `surfaceOp` marker — so a marker-less message event is rejected at construction rather than silently vanishing from `deriveMessages()` (the surface is the sole derivation path) on resume. Ordinary live-session forks use `ctx.sessions.fork({ source, boundary?, childSessionId? })`, where `boundary` is the inclusive source event seq to fork through. +- Replay/fork: `ctx.sessions.create(id, { seed })` seeds a new session with an existing event log. The surface rebuilds deterministically from `surfaceOp` markers in the seeded events. The seed is validated to the SAME always-on invariants `append` enforces — contiguous seqs, JSON-serializable data, and required `surfaceOp` markers on surface-eligible events — so marker-less message events are rejected at construction rather than silently vanishing from `deriveMessages()`. Broader turn-enclosure checks stay in `dsh-invariants` and persistence repair. Ordinary live-session forks use `ctx.sessions.fork({ source, boundary?, childSessionId? })`, where `boundary` is the inclusive source event seq to fork through. - Compaction: the `dsh-compact-basic` plugin appends a `user/message` with `surfaceOp: { op: 'replace', start, end }` to shadow old surface nodes behind a summary checkpoint. ### What is NOT here (TODO) diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts index ee4c6fa8f1..e7445da1c1 100644 --- a/packages/core/session/src/index.ts +++ b/packages/core/session/src/index.ts @@ -487,8 +487,7 @@ export class SessionStore extends Service { /** * Create a live child session from a turn-enclosed prefix of a live source. * `boundary` is an inclusive source event seq; omitted means the source's - * current last event. A non-empty selected slice must be turn-enclosed and end - * at `turn/end`; this rejects open turns rather than clipping silently. + * current last event. A non-empty selected slice must end at `turn/end`. * * @param options Source, optional boundary, and optional child id for the fork. * @returns The created live child session. @@ -540,10 +539,14 @@ export class SessionStore extends Service { 'INVALID_BOUNDARY', ) } + if (boundaryEvent.type !== 'turn/end') { + throw new SessionForkError( + `fork boundary ${boundary} in session "${session.id}" must be turn/end, got ${boundaryEvent.type}`, + 'OPEN_TURN', + ) + } - const seed = events.slice(0, boundary + 1) - this._assertForkBoundary(session, seed, boundary) - return seed.map(event => structuredClone(event)) + return events.slice(0, boundary + 1).map(event => structuredClone(event)) } private _resolveForkSource(source: SessionForkSource): Session { @@ -561,50 +564,6 @@ export class SessionStore extends Service { return source } - private _assertForkBoundary(session: Session, seed: readonly SessionEvent[], boundary: number): void { - let openTurn: SessionEvent<'turn/start'> | undefined - for (const event of seed) { - switch (event.type) { - case 'turn/start': { - if (openTurn !== undefined) { - throw new SessionForkError( - `cannot fork session "${session.id}" at boundary ${boundary}: turn ${event.data.turn} starts before turn ${openTurn.data.turn} ended`, - 'OPEN_TURN', - ) - } - openTurn = event - break - } - case 'turn/end': { - if (openTurn === undefined) { - throw new SessionForkError( - `cannot fork session "${session.id}" at boundary ${boundary}: turn/end at seq ${event.seq} has no matching turn/start`, - 'OPEN_TURN', - ) - } - openTurn = undefined - break - } - default: { - if (openTurn === undefined) { - throw new SessionForkError( - `cannot fork session "${session.id}" at boundary ${boundary}: event ${event.seq} (${event.type}) is outside a turn`, - 'OPEN_TURN', - ) - } - break - } - } - } - - const last = seed.at(-1) - if (openTurn !== undefined || last?.type !== 'turn/end') { - throw new SessionForkError( - `cannot fork session "${session.id}" at boundary ${boundary}: slice ends inside an open turn (last event: ${last?.type ?? 'none'})`, - 'OPEN_TURN', - ) - } - } } export default SessionStore diff --git a/packages/core/session/tests/fork.spec.ts b/packages/core/session/tests/fork.spec.ts index 17cc7a590b..189d5ae690 100644 --- a/packages/core/session/tests/fork.spec.ts +++ b/packages/core/session/tests/fork.spec.ts @@ -210,38 +210,10 @@ describe('SessionStore.fork', () => { const boundary = build(source) expect(() => sessions.fork({ source, boundary })) - .toThrow(new SessionForkError(`cannot fork session "open-${lastType}" at boundary ${boundary}: slice ends inside an open turn (last event: ${lastType})`, 'OPEN_TURN')) + .toThrow(new SessionForkError(`fork boundary ${boundary} in session "open-${lastType}" must be turn/end, got ${lastType}`, 'OPEN_TURN')) } }) - it('rejects malformed turn enclosure in the selected slice', async () => { - const { ctx, sessions } = await setup() - const outside = ctx.sessions.create(SessionId('outside'), { - seed: [ - { type: 'step/start', seq: 0, time: 1, data: { turn: 1, step: 1 } }, - ], - }) - expect(() => sessions.fork({ source: outside, boundary: 0 })) - .toThrow(new SessionForkError('cannot fork session "outside" at boundary 0: event 0 (step/start) is outside a turn', 'OPEN_TURN')) - - const nested = ctx.sessions.create(SessionId('nested'), { - seed: [ - { type: 'turn/start', seq: 0, time: 1, data: { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } } }, - { type: 'turn/start', seq: 1, time: 2, data: { turn: 2, trigger: { kind: 'message', source: { kind: 'user' } } } }, - ], - }) - expect(() => sessions.fork({ source: nested, boundary: 1 })) - .toThrow(new SessionForkError('cannot fork session "nested" at boundary 1: turn 2 starts before turn 1 ended', 'OPEN_TURN')) - - const orphanEnd = ctx.sessions.create(SessionId('orphan-end'), { - seed: [ - { type: 'turn/end', seq: 0, time: 1, data: { turn: 1, reason: { kind: 'completed' } } }, - ], - }) - expect(() => sessions.fork({ source: orphanEnd, boundary: 0 })) - .toThrow(new SessionForkError('cannot fork session "orphan-end" at boundary 0: turn/end at seq 0 has no matching turn/start', 'OPEN_TURN')) - }) - it('rejects a child session id that is already live with a typed fork error', async () => { const { ctx, sessions } = await setup() const source = ctx.sessions.create(SessionId('parent')) diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index 27f8b5d420..695ef2441f 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -61,8 +61,10 @@ describe('Session', () => { it('replays identically from a seeded event log', () => { const original = new Session(SessionId('s3')) + original.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) original.append('user/message', { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) original.append('assistant/message', { turn: 1, step: 1, content: [{ type: 'text', text: 'a' }] }, { surfaceOp: 'append' }) + original.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) const replayed = new Session(SessionId('s3-replay'), [...original.events]) expect(replayed.deriveMessages()).toEqual(original.deriveMessages()) @@ -417,7 +419,9 @@ describe('todo/write event', () => { it('round-trips through a seeded replay identically (durable, no surfaceOp needed)', () => { const original = new Session(SessionId('t4')) + original.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) original.append('todo/write', { todos: [{ content: 'only', status: 'completed' }] }) + original.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) // Seeding a non-surface event with no surfaceOp must not throw. const replayed = new Session(SessionId('t4-replay'), [...original.events]) expect(replayed.events.findLast(e => e.type === 'todo/write')!.data.todos)