Files
deepseek-harness/packages/api/session-controller/tests/session-fork.host.spec.ts
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

704 lines
31 KiB
TypeScript

/** Session Controller fork boundaries, lineage, and inherited model routing. */
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent, AgentHandle, CreateAgentOptions } from '@deepseek-ai/dsh-agent'
import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic'
import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
import { type ToolCallId, createMessage, createUserMessage, type ReasoningEffortId } from '@deepseek-ai/dsh-llm'
import SessionStore, { TOOL_OUTCOME_UNKNOWN, SESSION_FORMAT_VERSION, SessionLogOffset, SessionSeq } from '@deepseek-ai/dsh-session'
import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { SessionPersistenceRevision, SessionPersistenceSnapshot } from '@deepseek-ai/dsh-session-persistence'
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
import TokenMeter from '@deepseek-ai/dsh-token-meter'
import type { Workspace } from '@deepseek-ai/dsh-workspace'
import {
createSessionTestRemote, installSessionReadTestServices, testSessionPersistence,
} from './test-remote.ts'
const sid = (id: string): SessionId => id as SessionId
const message = (text: string) => createUserMessage({
content: [{ type: 'text', text }], source: { kind: 'user' },
})
function request<P>(payload: P): P {
return payload
}
async function composed(workspaces: readonly Workspace[] = []): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(SystemPrompt, { personaPrefix: '' })
await ctx.plugin(AgentRegistry)
await installSessionReadTestServices(ctx)
ctx.provide('workspaceRegistry', { list: () => workspaces, archivedSessionIds: [] } as never)
ctx.agents.setFactory({
createAgent: async (ownerCtx: Context, options: CreateAgentOptions): Promise<AgentHandle> => {
const session = ctx.sessions.create(options.sessionId, {
...options.seed === undefined ? {} : { seed: [...options.seed] },
...options.meta === undefined ? {} : { meta: options.meta },
...options.inheritedEventCount === undefined
? {}
: { inheritedEventCount: options.inheritedEventCount },
})
const agent = {} as Agent
const agentCtx = ownerCtx
Object.assign(agent, { id: session.id, session, status: 'idle', ctx: agentCtx })
await options.setup?.(agentCtx, agent)
await ctx.agents.register(agent)
return { agent, dispose: () => Promise.resolve() }
},
resume: () => Promise.reject(new Error('fork test sources are live')),
})
return ctx
}
/** Tail turn appended after the completed ones: left open, or closed as aborted (a stopped turn). */
type Tail = 'none' | 'open' | 'aborted'
async function liveAgent(
ctx: Context,
id: string,
turns: number,
tail: Tail = 'none',
lineage: { parentSession?: SessionId; origin?: 'subagent' } = {},
): Promise<Session> {
const session = ctx.sessions.create(sid(id), { meta: { cwd: '/proj', ...lineage } })
for (let turn = 1; turn <= turns; turn++) {
session.append('turn/start', { turn })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: `prompt ${String(turn)}` }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
session.append('turn/end', { turn, reason: { kind: 'completed' } })
}
if (tail !== 'none') {
session.append('turn/start', { turn: turns + 1 })
session.append('user/message', createUserMessage({
content: [{ type: 'text', text: 'open prompt' }],
source: { kind: 'user' },
}), { surfaceOp: 'append' })
if (tail === 'aborted') session.append('turn/end', {
turn: turns + 1,
reason: { kind: 'aborted', reason: { kind: 'user' } },
})
}
await ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent)
return session
}
const remote = async (ctx: Context) => await createSessionTestRemote(ctx, {
defaultModelSelection: () => ({ provider: 'default-provider', model: 'default-model' }),
cwd: '/tmp',
})
describe('sessions.fork', () => {
it.each([
{ allowMigration: undefined, status: 'current' },
{ allowMigration: false, status: 'current' },
{ allowMigration: false, status: undefined },
{ allowMigration: undefined, status: 'migration-required' },
{ allowMigration: true, status: 'migration-required' },
] as const)('forks cold history with allowMigration=$allowMigration and format=$status', async ({ allowMigration, status }) => {
const ctx = await composed()
try {
const source = ctx.sessions.prepare(sid('current-cold'), { meta: { cwd: '/proj' } })
const detach = ctx.effect(() => ctx.sessions.enter(source))
ctx.sessions.announce(source)
source.append('turn/start', { turn: 1 })
source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
await detach()
const snapshot: SessionPersistenceSnapshot = {
header: source.header,
revision: brandString<SessionPersistenceRevision>('test:cold-source'),
...status === undefined ? {} : { formatStatus: status },
}
ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
list: () => Promise.resolve([source.header]),
stat: () => Promise.resolve(snapshot),
inspect: () => Promise.resolve({ meta: source.header, events: source.snapshotEvents() }),
}) as never)
const open = vi.spyOn(ctx.sessionPersistence, 'open')
const response = await (await remote(ctx)).fork({
sessionId: source.id,
...allowMigration === undefined ? {} : { allowMigration },
})
if (!response.ok) throw response.error
expect(open).toHaveBeenCalledWith(source.id, 'read', undefined)
expect(ctx.sessions.get(source.id)).toBeUndefined()
expect(ctx.sessions.get(response.value.sessionId)?.inheritedEventCount).toBe(2)
} finally {
await ctx.fiber.dispose()
}
})
it('reports required migration before creating a fork when the caller disallows it', async () => {
const ctx = await composed()
try {
const sourceId = sid('requires-migration')
const source = ctx.sessions.prepare(sourceId, { meta: { cwd: '/proj' } })
const snapshot: SessionPersistenceSnapshot = {
header: source.header,
revision: brandString<SessionPersistenceRevision>('test:requires-migration'),
formatStatus: 'migration-required',
}
const stat = vi.fn(async () => snapshot)
ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never)
const open = vi.spyOn(ctx.sessionPersistence, 'open')
const observe = vi.spyOn(ctx.sessionQuery, 'observeSession')
const create = vi.spyOn(ctx.agents, 'create')
await expect((await remote(ctx)).fork({ sessionId: sourceId, allowMigration: false })).resolves.toMatchObject({
ok: false, error: { code: 'session/migration-required', details: { sessionId: sourceId } },
})
expect(stat).toHaveBeenCalledExactlyOnceWith(sourceId)
expect(open).not.toHaveBeenCalled()
expect(observe).not.toHaveBeenCalled()
expect(create).not.toHaveBeenCalled()
} finally {
await ctx.fiber.dispose()
}
})
it('shares the whole selected prefix of a live observation, which carries no persisted count', async () => {
const ctx = await composed()
try {
const source = ctx.sessions.create(sid('unreported-source'), { meta: { cwd: '/proj' } })
source.append('turn/start', { turn: 1 })
source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
const observe = ctx.sessionQuery.observeSession.bind(ctx.sessionQuery)
vi.spyOn(ctx.sessionQuery, 'observeSession').mockImplementation(async (...args) => {
const observation = await observe(...args)
expect(observation.persistedEventCount).toBeUndefined()
return observation
})
const create = vi.spyOn(ctx.agents, 'create')
const result = await (await remote(ctx)).fork({ sessionId: source.id, allowMigration: false })
if (!result.ok) throw result.error
expect(create.mock.calls[0]?.[0].parentSource).toMatchObject({ sessionId: source.id, endSeq: 2 })
expect(ctx.sessions.get(result.value.sessionId)?.inheritedEventCount).toBe(2)
} finally {
await ctx.fiber.dispose()
}
})
it('forks a resident Session without consulting disk metadata or requiring a live Agent', async () => {
const ctx = await composed()
try {
const source = ctx.sessions.create(sid('resident-source'), { meta: { cwd: '/proj' } })
source.append('turn/start', { turn: 1 })
source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
const stat = vi.fn(() => Promise.reject(new Error('unexpected metadata read')))
ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never)
const result = await (await remote(ctx)).fork({ sessionId: source.id, allowMigration: false })
if (!result.ok) throw result.error
expect(stat).not.toHaveBeenCalled()
expect(ctx.agents.get(source.id)).toBeUndefined()
expect(ctx.sessions.get(result.value.sessionId)?.inheritedEventCount).toBe(2)
} finally {
await ctx.fiber.dispose()
}
})
it('forks a source attached while its historical format stat is pending', async () => {
const ctx = await composed()
try {
const sourceId = sid('attached-during-stat')
const source = ctx.sessions.prepare(sourceId, { meta: { cwd: '/proj' } })
const snapshot: SessionPersistenceSnapshot = {
header: source.header,
revision: brandString<SessionPersistenceRevision>('test:attaching-source'),
formatStatus: 'migration-required',
}
const entered = Promise.withResolvers<undefined>()
const finish = Promise.withResolvers<SessionPersistenceSnapshot | undefined>()
const stat = vi.fn(() => {
entered.resolve(undefined)
return finish.promise
})
ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never)
const operation = (await remote(ctx)).fork({ sessionId: sourceId, allowMigration: false })
try {
await entered.promise
const live = ctx.sessions.create(sourceId, { meta: source.header })
live.append('turn/start', { turn: 1 })
live.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
finish.resolve(snapshot)
const result = await operation
if (!result.ok) throw result.error
expect(stat).toHaveBeenCalledExactlyOnceWith(sourceId)
expect(ctx.sessions.get(result.value.sessionId)?.inheritedEventCount).toBe(2)
} finally {
finish.resolve(undefined)
await Promise.allSettled([operation])
}
} finally {
await ctx.fiber.dispose()
}
})
it('reports a stat failure without treating it as required migration or opening the source', async () => {
const ctx = await composed()
try {
const sourceId = sid('failed-source-stat')
const stat = vi.fn(() => Promise.reject(new Error('source metadata unavailable')))
ctx.provide('sessionPersistence', testSessionPersistence(ctx, { stat }) as never)
const observe = vi.spyOn(ctx.sessionQuery, 'observeSession')
const create = vi.spyOn(ctx.agents, 'create')
await expect((await remote(ctx)).fork({ sessionId: sourceId, allowMigration: false })).resolves.toMatchObject({
ok: false, error: { code: 'gateway/internal', message: 'source metadata unavailable' },
})
expect(stat).toHaveBeenCalledExactlyOnceWith(sourceId)
expect(observe).not.toHaveBeenCalled()
expect(create).not.toHaveBeenCalled()
} finally {
await ctx.fiber.dispose()
}
})
it('keeps the completed manual compaction checkpoint when atSeq is omitted', async () => {
const ctx = new Context()
try {
await mountAgentLoopTestDependencies(ctx)
const harness = await mountAgentLoopTestHarness(ctx)
await ctx.plugin(TokenMeter)
await installSessionReadTestServices(ctx)
const compact = new BasicCompactionEngine(ctx, { auto: false })
const adapter = new MockAdapter([
textResponse('reply'), textResponse('checkpoint'), textResponse('continued'),
])
ctx.llm.registerAdapter(['mock'], adapter)
ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never)
const source = await harness.create(sid('manual-compaction-source'), { provider: 'mock', model: 'mock' })
const originalPrompt = 'older conversation history '.repeat(60)
source.followup(message(originalPrompt))
await source.whenIdle()
expect(await compact.compactNow(source, new AbortController().signal)).not.toBeNull()
const compacted = source.session.snapshotEvents()
expect(compacted.at(-1)).toMatchObject({ type: 'compaction/end', data: { turn: null } })
source.inbox.append('next-turn', message('queued after compaction'))
const response = await (await createSessionTestRemote(ctx, {
defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: '/tmp',
})).fork({ sessionId: source.id })
if (!response.ok) throw response.error
const child = ctx.agents.get(response.value.sessionId)!
expect(child.session.inheritedEventCount).toBe(compacted.length)
expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(compacted)
expect(child.session.deriveMessages()).toEqual(source.session.deriveMessages())
child.followup(message('continue from checkpoint'))
await child.whenIdle()
const requestText = JSON.stringify(adapter.requests.at(-1)?.messages)
expect(requestText).toContain('checkpoint')
expect(requestText).toContain('continue from checkpoint')
expect(requestText).not.toContain(originalPrompt)
expect(requestText).not.toContain('queued after compaction')
} finally {
await ctx.fiber.dispose()
}
})
it.each(['turn-end', 'omitted'] as const)(
'excludes the next user input when forking at %s', async (anchor) => {
const ctx = new Context()
try {
await mountAgentLoopTestDependencies(ctx)
const harness = await mountAgentLoopTestHarness(ctx)
const adapter = new MockAdapter(Array.from({ length: 4 }, () => textResponse('reply')))
ctx.llm.registerAdapter(['mock'], adapter)
ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never)
const source = await harness.create(sid('source'), { provider: 'mock', model: 'mock' })
source.followup(message('A'))
await source.whenIdle()
const boundary = source.session.snapshotEvents().at(-1)!.seq
if (anchor === 'turn-end') {
source.followup(message('B'))
await source.whenIdle()
} else {
source.inbox.append('next-turn', message('B'))
}
const original = source.session.snapshotEvents()
const atSeq = anchor === 'omitted' ? undefined : boundary
const response = await (await createSessionTestRemote(ctx, {
defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: '/tmp',
})).fork({ sessionId: source.id, ...(atSeq === undefined ? {} : { atSeq }) })
if (!response.ok) throw response.error
const child = ctx.agents.get(response.value.sessionId)!
const requestCount = adapter.requests.length
child.followup(message('C'))
await child.whenIdle()
const userTexts = child.session.deriveMessages().flatMap(item => item.role === 'user'
? item.content.flatMap(part => part.type === 'text' ? [part.text] : []) : [])
expect(userTexts).toEqual(['A', 'C'])
expect(adapter.requests.slice(requestCount)).toHaveLength(1)
expect(child.session.inheritedEventCount).toBe(boundary + 1)
expect(source.session.snapshotEvents()).toEqual(original)
} finally {
await ctx.fiber.dispose()
}
},
)
it('cuts exactly at a completed turn and retains cwd without source lineage', async () => {
const ctx = await composed()
const source = await liveAgent(ctx, 'session-source', 2)
const response = await (await remote(ctx)).fork(request({ sessionId: source.id, atSeq: 2 }))
expect(response.ok ? null : response.error).toBeNull()
if (!response.ok) return
const child = ctx.sessions.get(response.value.sessionId)
expect(child?.snapshotEvents().map(event => event.type)).toEqual([
'turn/start', 'user/message', 'turn/end', 'session/end-seed',
])
expect(child?.header.parentSession).toBeUndefined()
expect(child?.header.cwd).toBe('/proj')
await ctx.fiber.dispose()
})
it('attaches a subagent fork to its nearest workspace-owning ancestor', async () => {
const accounted: SessionId[] = []
const attachSession = vi.fn<(sessionId: SessionId) => Promise<void>>()
.mockResolvedValue(undefined)
const workspace = {
sessionIds: accounted,
attachSession,
} as unknown as Workspace
const ctx = await composed([workspace])
const owner = await liveAgent(ctx, 'session-owner', 1)
accounted.push(owner.id)
const child = await liveAgent(ctx, 'session-child', 1, 'none', {
parentSession: owner.id,
origin: 'subagent',
})
const grandchild = await liveAgent(ctx, 'session-grandchild', 1, 'none', {
parentSession: child.id,
origin: 'subagent',
})
vi.spyOn(ctx.sessionQuery, 'traceSession').mockResolvedValue({
target: { header: grandchild.header, live: true, persisted: false },
ancestors: [
{ header: child.header, live: true, persisted: false },
{ header: owner.header, live: true, persisted: false },
],
descendants: [],
complete: true,
root: { header: owner.header, live: true, persisted: false },
})
const response = await (await remote(ctx)).fork(request({ sessionId: grandchild.id }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
expect(attachSession).toHaveBeenCalledWith(response.value.sessionId)
expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
cwd: '/proj',
})
expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
expect(ctx.sessions.get(response.value.sessionId)?.header.parentSession).toBeUndefined()
await ctx.fiber.dispose()
})
it('forks a persisted subagent without resuming its Agent', async () => {
const ctx = await composed()
const sourceId = sid('session-cold-subagent')
const parentId = sid('session-cold-parent')
const header: SessionHeader = {
version: SESSION_FORMAT_VERSION,
id: sourceId,
createdAt: 1,
cwd: '/proj',
parentSession: parentId,
isSeeded: false,
origin: 'subagent',
}
const events = [
{
type: 'turn/start',
seq: SessionSeq(0),
time: 1,
data: {
turn: 1,
trigger: { kind: 'message', source: { kind: 'user' } },
} as SessionEvent<'turn/start'>['data'],
},
{
type: 'user/message',
seq: SessionSeq(1),
time: 2,
data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
surfaceOp: 'append',
},
{ type: 'turn/end', seq: SessionSeq(2), time: 3, data: { turn: 1, reason: { kind: 'completed' } } },
] satisfies SessionEvent[]
ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
list: () => Promise.resolve([header]),
inspect: () => Promise.resolve({
meta: header,
inheritedEventCount: SessionLogOffset(0),
events,
}),
}) as never)
const resume = vi.spyOn(ctx.agents, 'resume')
const response = await (await remote(ctx)).fork(request({ sessionId: sourceId }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
expect(resume).not.toHaveBeenCalled()
expect(ctx.agents.get(sourceId)).toBeUndefined()
expect(ctx.sessions.get(response.value.sessionId)?.header).toMatchObject({
cwd: '/proj',
})
expect(ctx.sessions.get(response.value.sessionId)?.header.origin).toBeUndefined()
expect(ctx.sessions.get(response.value.sessionId)?.header.parentSession).toBeUndefined()
await ctx.fiber.dispose()
})
it('uses the latest completed prefix only when atSeq is omitted', async () => {
const ctx = await composed()
const source = await liveAgent(ctx, 'session-tail', 2, 'open')
const proxy = await remote(ctx)
const omitted = await proxy.fork(request({ sessionId: source.id }))
expect(omitted.ok).toBe(true)
if (omitted.ok) {
expect(ctx.sessions.get(omitted.value.sessionId)?.snapshotEvents().map(event => event.type))
.toEqual([
'turn/start', 'user/message', 'turn/end',
'turn/start', 'user/message', 'turn/end',
'session/end-seed',
])
}
const pastEnd = await proxy.fork(request({ sessionId: source.id, atSeq: 999 }))
expect(pastEnd).toMatchObject({
ok: false,
error: { code: 'session/fork-unavailable', details: { sessionId: source.id } },
})
if (!pastEnd.ok) expect(pastEnd.error.message).toMatch(/does not exist/)
await ctx.fiber.dispose()
})
it('rejects an omitted boundary when no turn has completed', async () => {
const ctx = await composed()
const source = await liveAgent(ctx, 'session-never-completed', 0, 'open')
const response = await (await remote(ctx)).fork(request({ sessionId: source.id }))
expect(response).toMatchObject({
ok: false,
error: { code: 'session/fork-unavailable', details: { sessionId: source.id } },
})
if (!response.ok) expect(response.error.message).toMatch(/no completed turn/)
await ctx.fiber.dispose()
})
it.each([false, true])('inherits standalone tail events with the next turn open: %s', async (openNextTurn) => {
const ctx = await composed()
try {
const source = await liveAgent(ctx, 'session-standalone-tail', 1)
source.append('session/title', { title: 'After the turn', messageSeqs: [], source: { kind: 'user' } })
const inherited = source.snapshotEvents()
if (openNextTurn) source.append('turn/start', { turn: 2 })
const response = await (await remote(ctx)).fork({ sessionId: source.id })
if (!response.ok) throw response.error
const child = ctx.sessions.get(response.value.sessionId)!
expect(child.inheritedEventCount).toBe(inherited.length)
expect(child.snapshotEvents().slice(0, child.inheritedEventCount)).toEqual(inherited)
expect(child.snapshotEvents().slice(child.inheritedEventCount).map(event => event.type))
.toEqual(['session/end-seed'])
} finally {
await ctx.fiber.dispose()
}
})
it('rejects invalid fork anchors before reading or creating a Session', async () => {
const ctx = await composed()
const proxy = await remote(ctx)
for (const atSeq of [-1, 0.5]) {
await expect(proxy.fork(request({ sessionId: sid('missing'), atSeq })))
.resolves.toMatchObject({ ok: false, error: { code: 'gateway/bad-request' } })
}
expect(ctx.sessions.list()).toEqual([])
await ctx.fiber.dispose()
})
it('cuts before an aborted turn/end and synthesizes a forked closer', async () => {
const ctx = await composed()
const source = await liveAgent(ctx, 'session-aborted', 1, 'aborted')
const anchor = (source.snapshotEvents().at(-1)?.seq ?? 0) - 1
const response = await (await remote(ctx)).fork(request({ sessionId: source.id, atSeq: anchor }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
const child = ctx.sessions.get(response.value.sessionId)
expect(child?.snapshotEvents().map(event => event.type)).toEqual([
'turn/start', 'user/message', 'turn/end',
'turn/start', 'user/message', 'session/end-seed', 'turn/end',
])
const closer = child?.snapshotEvents().at(-1)
expect(closer?.type === 'turn/end' && closer.data.reason).toEqual({ kind: 'forked' })
await ctx.fiber.dispose()
})
it('cuts exactly inside a live open turn and preserves the source', async () => {
const ctx = await composed()
const source = await liveAgent(ctx, 'session-open', 1, 'open')
const boundary = source.snapshotEvents().at(-1)?.seq ?? 0
const response = await (await remote(ctx)).fork(request({ sessionId: source.id, atSeq: boundary }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
const child = ctx.sessions.get(response.value.sessionId)
expect(child?.snapshotEvents().map(event => event.type)).toEqual([
'turn/start', 'user/message', 'turn/end',
'turn/start', 'user/message', 'session/end-seed', 'turn/end',
])
const closer = child?.snapshotEvents().at(-1)
expect(closer?.type === 'turn/end' && closer.data.reason).toEqual({ kind: 'forked' })
expect(child?.inheritedEventCount).toBe(boundary + 1)
expect(source.snapshotEvents().at(-1)?.type).toBe('user/message')
await ctx.fiber.dispose()
})
it('does not extend an explicit boundary through standalone tail events', async () => {
const ctx = await composed()
const source = await liveAgent(ctx, 'session-exact', 1)
const boundary = source.snapshotEvents().at(-1)?.seq ?? 0
source.append('session/title', { title: 'after boundary', messageSeqs: [], source: { kind: 'fallback' } })
const response = await (await remote(ctx)).fork(request({ sessionId: source.id, atSeq: boundary }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
expect(ctx.sessions.get(response.value.sessionId)?.snapshotEvents().map(event => event.type)).toEqual([
'turn/start', 'user/message', 'turn/end', 'session/end-seed',
])
await ctx.fiber.dispose()
})
it('repairs a cold open-step cut without resuming its Agent', async () => {
const ctx = await composed()
const sourceId = sid('session-cold-mid-turn')
const callId = brandString<ToolCallId>('cold-dangling')
const header: SessionHeader = { version: SESSION_FORMAT_VERSION, id: sourceId, createdAt: 1, cwd: '/proj', isSeeded: false }
const events = [
{ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } },
{ type: 'step/start', seq: 1, time: 2, data: { turn: 1, step: 1 } },
{
type: 'user/message',
seq: 2,
time: 3,
data: createUserMessage({ content: [{ type: 'text', text: 'work' }], source: { kind: 'user' } }),
surfaceOp: 'append',
},
{
type: 'assistant/message',
seq: 3,
time: 4,
data: {
stream: [],
turn: 1,
step: 1,
message: createMessage({
role: 'assistant',
content: [{ type: 'tool-call', id: callId, name: 'read', arguments: '{}' }],
source: { kind: 'model', provider: 'mock', model: 'mock' },
}),
},
surfaceOp: 'append',
},
{ type: 'tool/call', seq: 4, time: 5, data: { turn: 1, step: 1, callId, name: 'read', arguments: '{}' } },
{ type: 'step/end', seq: 5, time: 6, data: { turn: 1, step: 1 } },
{
type: 'turn/end',
seq: 6,
time: 7,
data: { turn: 1, reason: { kind: 'error', error: { message: 'scheduler failed', code: 'UNKNOWN' } } },
},
] as SessionEvent[]
ctx.provide('sessionPersistence', testSessionPersistence(ctx, {
list: () => Promise.resolve([header]),
inspect: () => Promise.resolve({ meta: header, events }),
}) as never)
const resume = vi.spyOn(ctx.agents, 'resume')
const response = await (await remote(ctx)).fork(request({ sessionId: sourceId, atSeq: 4 }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
expect(resume).not.toHaveBeenCalled()
const child = ctx.sessions.get(response.value.sessionId)
expect(child?.snapshotEvents().map(event => event.type)).toEqual([
'turn/start', 'step/start', 'user/message', 'assistant/message',
'tool/call', 'session/end-seed', 'tool/result', 'step/end', 'turn/end',
])
expect(child?.inheritedEventCount).toBe(5)
expect(child?.snapshotEvents().at(-3)).toMatchObject({
type: 'tool/result',
data: {
turn: 1,
step: 1,
message: { source: { callId } },
error: { code: TOOL_OUTCOME_UNKNOWN },
},
sourceEventSeqs: [4],
})
const closer = child?.snapshotEvents().at(-1)
expect(closer?.type === 'turn/end' && closer.data.reason).toEqual({ kind: 'forked' })
expect(child?.deriveMessages().at(-1)).toMatchObject({ source: { kind: 'tool', callId } })
await ctx.fiber.dispose()
})
it('inherits model selection through the completed turn and excludes later changes', async () => {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
await mountAgentLoopTestDependencies(ctx)
const harness = await mountAgentLoopTestHarness(ctx)
ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never)
const { session: source } = await harness.create(sid('session-routed'))
source.append('turn/start', { turn: 1 })
source.append('request/header', {
header: {
config: {
provider: 'inherited-provider',
model: 'inherited-model',
reasoningEffort: brandString<ReasoningEffortId>('high'),
},
},
reason: 'initial',
})
const boundary = source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
const inherited = source.snapshotEvents()
source.append('session/title', {
title: 'Title after the selected turn', messageSeqs: [], source: { kind: 'user' },
})
source.append('turn/start', { turn: 2 })
source.append('request/header', {
header: { config: { provider: 'later-provider', model: 'later-model' } },
reason: 'change',
})
source.append('turn/end', { turn: 2, reason: { kind: 'completed' } })
const response = await (await remote(ctx)).fork(request({ sessionId: source.id, atSeq: boundary.seq }))
expect(response.ok ? undefined : response.error).toBeUndefined()
if (!response.ok) return
const child = ctx.agents.get(response.value.sessionId)
if (child === undefined) throw new Error('fork did not publish the child agent')
expect(child.session.snapshotEvents().slice(0, child.session.inheritedEventCount)).toEqual(inherited)
expect(child.model.current()).toEqual({
provider: 'inherited-provider', model: 'inherited-model', reasoningEffort: 'high',
})
})
})