test(session): run persistence consumers against both backends

This commit is contained in:
liukx0205 committed 2026-11-15 01:42:16 +08:00
1 parent b467fa6ee5
commit 73b971fa16
112 files changed
+2309 -1970

No files matched your search

@@ -366,7 +366,7 @@ jobs:
"${{ steps.smoke-venv-posix.outputs.python }}" \
"$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \
--scenario all \
--installed-wheel
--installed-wheel --storage jsonl sqlite
- name: Run installed-wheel keyless black-box tests (Windows)
if: runner.os == 'Windows'
@@ -377,7 +377,7 @@ jobs:
Remove-Item Env:DSH_RUNTIME_MODE -ErrorAction SilentlyContinue
Push-Location $blackboxRoot
try {
& "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario all --installed-wheel
& "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario all --installed-wheel --storage jsonl sqlite
if ($LASTEXITCODE -ne 0) { throw "Installed-wheel black-box failed with exit code $LASTEXITCODE" }
} finally {
Pop-Location
@@ -445,7 +445,7 @@ jobs:
"${{ steps.smoke-venv-posix.outputs.python }}" \
"$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \
--scenario sdk-live \
--installed-wheel
--installed-wheel --storage jsonl sqlite
- name: Run installed-wheel real API black-box test (Windows)
if: >-
@@ -464,7 +464,7 @@ jobs:
Remove-Item Env:DSH_RUNTIME_MODE -ErrorAction SilentlyContinue
Push-Location $blackboxRoot
try {
& "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario sdk-live --installed-wheel
& "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario sdk-live --installed-wheel --storage jsonl sqlite
if ($LASTEXITCODE -ne 0) { throw "Installed-wheel live API smoke failed with exit code $LASTEXITCODE" }
} finally {
Pop-Location
@@ -518,8 +518,8 @@ jobs:
/tmp/dsh-sdk/bin/python -m pip install "/work/dist-python/$SDK_WHEEL" "/work/dist-python/$RUNTIME_WHEEL"
mkdir -p /tmp/dsh-sdk-manylinux-smoke
cd /tmp/dsh-sdk-manylinux-smoke
env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-default --installed-wheel
env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-mcp --installed-wheel
env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-default --installed-wheel --storage jsonl sqlite
env -u PYTHONPATH -u DSH_RUNTIME_MODE /tmp/dsh-sdk/bin/python /work/scripts/smoke-python-runtime.py --scenario sdk-mcp --installed-wheel --storage jsonl sqlite
'
- uses: actions/[email protected]
+2 -2
View File
@@ -72,8 +72,8 @@ jobs:
python -m pip install \
"dist/deepseek_harness_sdk-$VERSION-py3-none-any.whl" \
"dist/deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl"
python scripts/smoke-python-runtime.py --scenario sdk-default
python scripts/smoke-python-runtime.py --scenario sdk-mcp
python scripts/smoke-python-runtime.py --scenario sdk-default --storage jsonl sqlite
python scripts/smoke-python-runtime.py --scenario sdk-mcp --storage jsonl sqlite
validate:
name: Validate release candidate
@@ -25,7 +25,7 @@ afterEach(async () => {
workdir = undefined
})
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compacts mid-flight and keeps running', () => {
describe.skipIf(!process.env.DEEPSEEK_API_KEY).each(['jsonl', 'sqlite'] as const)('compaction: a long session compacts mid-flight and keeps running (%s)', (storage) => {
it('summarizes older history into a checkpoint without breaking the task', async () => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-compaction-'))
// An older file result must exceed the framed checkpoint's fixed sections.
@@ -49,6 +49,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compa
compactionRetries: 1,
},
persistenceRoot: join(workdir, '.sessions'),
persistenceStorage: storage,
})
const agent = await ctx.agentLoop.create(brandString<SessionId>('e2e-compaction'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir })
@@ -102,5 +103,12 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compa
expect(answer.length).toBeGreaterThan(0)
expect(answer).toMatch(/\b(4|four)\b/)
expect(answer).toMatch(/\b(1|one)\b/)
await ctx.sessions.flush(agent.session)
const handle = await ctx.sessionPersistence.open(agent.session.id, 'read')
try {
expect((await handle.read()).events).toEqual(events)
} finally {
await handle.close()
}
}, 240_000)
})
@@ -41,8 +41,10 @@ export interface CodingHarnessOptions {
* config — per-context, not per-agent). Omitted ⇒ no persona prefix section.
*/
personaPrefix?: string
/** Durable JSONL persistence root (the resume suite needs it; others stay file-free). */
/** Durable persistence root; omitted roots keep the suite file-free. */
persistenceRoot?: string
/** Persistence backend; omitted values use the plugin's JSONL default. */
persistenceStorage?: 'jsonl' | 'sqlite'
/**
* Load {@link BasicCompactionEngine} with this config so the compaction e2e can
* trigger compaction at a small, controlled history size. Omitted ⇒ no
@@ -90,11 +92,12 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio
await ctx.plugin(ToolResultPruner)
await ctx.plugin(BasicCompactionEngine, options.compact)
}
// Durable JSONL persistence is opt-in: only the resume e2e needs it, and the
// other suites stay file-free. Loaded last so a resume's deferred
// `ctx.inject(['sessionPersistence'])` resolves once this is present.
// Loaded last so a resume's deferred persistence injection resolves here.
if (options.persistenceRoot !== undefined) {
await ctx.plugin(JsonlSessionPersistence, { root: options.persistenceRoot })
await ctx.plugin(JsonlSessionPersistence, {
root: options.persistenceRoot,
...options.persistenceStorage === undefined ? {} : { storage: options.persistenceStorage },
})
await ctx.plugin(SessionCheckpointPolicy)
}
return ctx
@@ -10,7 +10,7 @@ import { brandString } from '@deepseek-ai/dsh-brand'
/**
* Proves durable conversation continuity end-to-end: run 1 tells the REAL model
* a fact and persists the turn to JSONL; run 2 is a fresh harness (new Context,
* a fact and persists the turn; run 2 is a fresh harness (new Context,
* same `.sessions` root) that RESUMES the persisted session id and asks the
* model to recall the fact. The recall can only come from the rehydrated event
* log — a fresh session would have no idea. Key-gated like the other e2es.
@@ -24,21 +24,21 @@ let root: string | undefined
afterEach(async () => {
// Dispose even on failure/retry: agent-loop teardown stops the loop and the
// JSONL backend flushes; then drop the on-disk session log.
// persistence backend flushes; then drop the on-disk session log.
await ctx?.fiber.dispose()
ctx = undefined
if (root !== undefined) await rm(root, { recursive: true, force: true })
root = undefined
})
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('resume: continue a persisted session across processes', () => {
describe.skipIf(!process.env.DEEPSEEK_API_KEY).each(['jsonl', 'sqlite'] as const)('resume: continue a persisted session across processes (%s)', (storage) => {
it('recalls a fact stored in a prior, separately-disposed session', async () => {
root = await mkdtemp(join(tmpdir(), 'dsh-resume-e2e-'))
// Run 1: a fresh agent on a KNOWN session id learns a secret, then we
// dispose the whole context (simulating process exit) so only the JSONL
// dispose the whole context (simulating process exit) so only the durable
// log on disk survives.
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root })
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root, persistenceStorage: storage })
const first = (await ctx.agents.create({
sessionId: SESSION_ID,
agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
@@ -51,7 +51,7 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY)('resume: continue a persisted ses
// Run 2: a brand-new context over the SAME root resumes the persisted
// session. The loaded event log seeds the live session, so the model sees
// run 1's exchange as conversation history.
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root })
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root, persistenceStorage: storage })
const resumed = (await ctx.agents.resume({
resumeSessionId: SESSION_ID,
agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
+10 -2
View File
@@ -477,7 +477,13 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
await page.getByRole('button', { name: /^Show \d+ more sessions$/ }).click()
const group = page.getByRole('treeitem', { name: /^Ungrouped/ })
await group.waitFor()
if (await group.getAttribute('aria-expanded') !== 'true') {
await page.getByText('Ungrouped', { exact: true }).click()
}
const showMore = page.getByRole('button', { name: /^Show \d+ more sessions$/ })
if (await showMore.count() > 0) await showMore.click()
const row = page.locator(`[data-row-key="session:${id}"]`)
await row.waitFor()
acknowledgeReloadConnectionLoss(tripwire, warningStart)
@@ -505,7 +511,9 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
await expect.poll(() => row.getAttribute('aria-selected')).toBe('true')
await expect.poll(() => scaffold.ctx.agents.get(id)).toBeDefined()
await expect(scaffold.ctx.sessionPersistence.stat(id)).resolves.toMatchObject({ formatStatus: 'current' })
expect(await readdir(directory)).not.toContain(`session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`)
expect(await readdir(directory)).toEqual((process.env.DSH_SNAPSHOT_STORAGE ?? 'jsonl') === 'sqlite'
? ['session.lock', 'session.v3.jsonl.zstd']
: ['session.lock', 'session.v3.jsonl.zstd', `session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`])
expect(await readFile(predecessor)).toEqual(source)
expect(forkRequests).toEqual(['/api/session/fork'])
expect(scaffold.ctx.agents.list().filter(agent => !existing.has(agent.id) && agent.id !== id)).toEqual([])
+18 -4
View File
@@ -25,6 +25,7 @@ import {
} from './scaffold.ts'
import { expandOwningTurnProcess, newEnglishPage, saveFailureShot } from './support.ts'
import { expectWrappedTerminalCommand } from './terminal-command-browser.ts'
import { generationLogPath } from '../../../packages/session/session-persistence-jsonl/src/format.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/navigation-panes', import.meta.url))
const SEED = join(SNAPSHOT_DIR, 'session.v3.jsonl')
@@ -503,11 +504,24 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
const snapshot = await scaffold.ctx.sessionPersistence.stat(brandString<SessionId>(SEED_ID))
expect(snapshot?.header.id).toBe(SEED_ID)
expect(snapshot?.location).toBeUndefined()
const sourcePath = generationLogPath(scaffold.persistenceRoot, scaffold.workspaceCwd,
brandString<SessionId>(SEED_ID), SESSION_FORMAT_VERSION, 'zstd')
const sqlite = process.env.DSH_SNAPSHOT_STORAGE === 'sqlite'
expect(snapshot?.location).toEqual(sqlite ? undefined : { kind: 'jsonl', path: sourcePath })
const markdown = await page.evaluate(() => navigator.clipboard.readText())
const normalized = markdown.split(scaffold.workspaceCwd).join('{{cwd}}')
// compareOrRefreshGolden appends its own newline; the clipboard text already ends with exactly one.
await compareOrRefreshGolden(COPY_MARKDOWN_EXPECTED, normalized.replace(/\n$/u, ''), MODE)
const sourceBlock = `Session file:\n\n\`\`\`text\n${sourcePath}\n\`\`\`\n\n`
if (sqlite) expect(markdown).not.toContain('Session file:')
else expect(markdown).toContain(sourceBlock)
const normalized = markdown.replace(sourceBlock, '').split(scaffold.workspaceCwd).join('{{cwd}}')
// The artifact location is asserted separately; both backends share the transcript body.
const fixtureSourceBlock = 'Session file:\n\n```text\n{{sessionFile}}\n```\n\n'
if (MODE === 'refresh') {
const titleEnd = normalized.indexOf('\n\n') + 2
const fixture = normalized.slice(0, titleEnd) + fixtureSourceBlock + normalized.slice(titleEnd)
await compareOrRefreshGolden(COPY_MARKDOWN_EXPECTED, fixture.replace(/\n$/u, ''), MODE)
}
const expected = await readFile(COPY_MARKDOWN_EXPECTED, 'utf8')
expect(normalized).toBe(expected.replace(fixtureSourceBlock, ''))
expect(normalized).not.toContain('Session file:')
expect(normalized).toContain('# NavScenario: first run bash to')
expect(normalized).toContain('> NavScenario: first run bash to print exactly NAVIGATION_OK')
+18 -8
View File
@@ -21,6 +21,12 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
it.each([false, true])('resumes code as PTC (selection events=%s)', async (withSelections) => {
const scaffold = await launchWebScaffold()
try {
const sqlite = process.env.DSH_SNAPSHOT_STORAGE === 'sqlite'
const readStored = async (id: SessionId): Promise<string> => {
await using handle = await scaffold.ctx.sessionPersistence.open(id, 'read')
const { events } = await handle.read()
return [{ type: 'session', ...handle.header }, ...events].map(row => JSON.stringify(row)).join('\n') + '\n'
}
const id = brandString<SessionId>('preset-migration')
const fixture = await readFile(fixturePath, 'utf8')
const [fixtureHeader, ...fixtureEvents] = fixture.trimEnd().split('\n')
@@ -97,9 +103,10 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
.resolves.toMatchObject({ hasMore: false })
const childWriter = await scaffold.ctx.sessionPersistence.open(childId, 'write')
await childWriter.close()
const childPublished = await readFile(childSuccessor)
const childText = Buffer.concat(scanZstdFrames(childPublished).frames
.map(({ start, end }) => zstdDecompressSync(childPublished.subarray(start, end)))).toString('utf8')
const childText = sqlite ? await readStored(childId) : await readFile(childSuccessor).then(bytes =>
Buffer.concat(scanZstdFrames(bytes).frames
.map(({ start, end }) => zstdDecompressSync(bytes.subarray(start, end)))).toString('utf8'))
if (sqlite) await expect(readFile(childSuccessor)).rejects.toMatchObject({ code: 'ENOENT' })
expect(childText.trimEnd().split('\n').map((line): unknown => JSON.parse(line))).toEqual([
{ ...childHeader, version: SESSION_FORMAT_VERSION, agentPreset: 'ptc' }, ...childRows,
])
@@ -109,9 +116,10 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
.rejects.toMatchObject({ code: 'ENOENT' })
await scaffold.ctx.sessions.flush(resolved.agent.session)
const publishedBytes = await readFile(successor)
const published = Buffer.concat(scanZstdFrames(publishedBytes).frames
.map(({ start, end }) => zstdDecompressSync(publishedBytes.subarray(start, end)))).toString('utf8')
const published = sqlite ? await readStored(id) : await readFile(successor).then(bytes =>
Buffer.concat(scanZstdFrames(bytes).frames
.map(({ start, end }) => zstdDecompressSync(bytes.subarray(start, end)))).toString('utf8'))
if (sqlite) await expect(readFile(successor)).rejects.toMatchObject({ code: 'ENOENT' })
const expected = [
{ ...header, version: SESSION_FORMAT_VERSION, agentPreset: 'ptc' },
...rows.map(row => row['type'] === 'agent-preset/selected'
@@ -131,12 +139,14 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
{ type: 'approval/policy', seq: rows.length + 5, time: 0, data: { policy: 'ask' } },
].map(row => JSON.stringify(row)).join('\n') + '\n'
const context = { sessionIds: [id], cwd: scaffold.workspaceCwd }
expect(normalizeSessionSnapshots([published], context)).toEqual(normalizeSessionSnapshots([expected], context))
const records = (text: string): unknown[] => normalizeSessionSnapshots([text], context)[0]!.trimEnd()
.split('\n').map((line): unknown => JSON.parse(line))
expect(records(published)).toEqual(records(expected))
expect(await readFile(predecessor)).toEqual(source)
await expect(scaffold.ctx.sessionPersistence.open(corruptHeaderId, 'read')).rejects.toThrow(/invalid frame magic/)
expect(await readFile(corruptHeaderPath)).toEqual(corruptHeaderSource)
expect((await readdir(dirname(predecessor))).filter(name => name.endsWith('.jsonl.zstd')).sort())
.toEqual(['session.v2.jsonl.zstd', `session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`])
.toEqual(sqlite ? ['session.v2.jsonl.zstd'] : ['session.v2.jsonl.zstd', `session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`])
} finally {
await scaffold.close()
}
+14 -10
View File
@@ -88,6 +88,8 @@ import { startPrefixProxy, type PrefixProxy } from './prefix-proxy.ts'
import { REPO_ROOT, requireBuilt, requireDist } from './support.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
const SNAPSHOT_STORAGE = (process.env.DSH_SNAPSHOT_STORAGE ?? 'jsonl') as 'jsonl' | 'sqlite'
type AppBoot = typeof import('@deepseek-ai/dsh-app-boot')
let builtAppBoot: AppBoot | undefined
@@ -596,7 +598,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
: [{ id: 'agent-default-model', config: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } }],
...extraOverlayPatches,
{ id: 'agent-preset-registry', config: { default: 'standard' } },
{ id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
{ id: 'session-persistence-jsonl', config: { root: persistenceRoot, storage: SNAPSHOT_STORAGE } },
// Content search is enabled here although the shipped bundles default it
// off (`openAt: never`, pinned by apps/cli/tests/lazy-search-startup):
// the seeded-session scenarios navigate by content search, and these e2e
@@ -1286,11 +1288,12 @@ async function assertReplaySession(
sessionIds: typeof expectedHeader.id === 'string' ? [expectedHeader.id] : [],
cwd: typeof expectedHeader.cwd === 'string' ? expectedHeader.cwd : '\0no-cwd\0',
}
const actualSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(actual)], actualContext)[0]
?.split(harnessHome).join('{{harnessHome}}')
const expectedSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(expected)], expectedContext)[0]
?.split(harnessHome).join('{{harnessHome}}')
expect(actualSnapshot, `${fixturePath}: persisted replay`).toBe(expectedSnapshot)
const actualSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(actual)], actualContext)[0]!
.split(harnessHome).join('{{harnessHome}}')
const expectedSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(expected)], expectedContext)[0]!
.split(harnessHome).join('{{harnessHome}}')
const records = (text: string): unknown[] => text.split('\n').filter(line => line.trim() !== '').map((line): unknown => JSON.parse(line))
expect(records(actualSnapshot), `${fixturePath}: persisted replay`).toEqual(records(expectedSnapshot))
if (manifest.header?.pin !== true) return
const normalizePrompt = (value: string): string => value
@@ -1560,7 +1563,7 @@ export async function seedSession(
return meta.id
}
/** Materialize one detached Session fixture through the shipped JSONL provider. */
/** Materialize one detached Session fixture through the booted persistence provider. */
async function persistSeedSession(
scaffold: WebScaffold,
meta: SessionHeader,
@@ -1568,9 +1571,10 @@ async function persistSeedSession(
): Promise<void> {
const seeder = new Context()
try {
// Same root as the booted tree with the plugin's own default compression,
// so the host's directory-scan list() sees one consistent encoding.
await seeder.plugin(JsonlSessionPersistence, { root: scaffold.persistenceRoot })
await seeder.plugin(JsonlSessionPersistence, {
root: scaffold.persistenceRoot,
storage: SNAPSHOT_STORAGE,
})
const handle = await seeder.sessionPersistence.create(meta)
await handle.append(events)
await handle.close()
+10 -10
View File
@@ -27,8 +27,8 @@ describe('ACP machine permission policy', () => {
return { agent, toolName: 'bash', callId: brandString<ToolCallId>('call-9'), ...overrides }
}
it('maps the two advertised one-shot choices', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: maps the two advertised one-shot choices', async (storage) => {
harness = await makeBridgeHarness(storage)
harness.onPermission = () => {
expect(harness?.sessionUpdates.at(-1)?.update).toMatchObject({
sessionUpdate: 'tool_call',
@@ -51,23 +51,23 @@ describe('ACP machine permission policy', () => {
await expect(harness.ctx.approval.request(request)).resolves.toBe('rejected')
})
it('maps cancellation and unknown choices without granting access', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: maps cancellation and unknown choices without granting access', async (storage) => {
harness = await makeBridgeHarness(storage)
const request = await ownedRequest()
await expect(harness.ctx.approval.request(request)).resolves.toBe('cancelled')
harness.onPermission = () => ({ outcome: { outcome: 'selected', optionId: 'unknown-grant' } })
await expect(harness.ctx.approval.request(request)).resolves.toBe('rejected')
})
it('fails closed when the client errors the permission request', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: fails closed when the client errors the permission request', async (storage) => {
harness = await makeBridgeHarness(storage)
const request = await ownedRequest()
harness.onPermission = () => { throw new Error('client gone') }
await expect(harness.ctx.approval.request(request)).resolves.toBe('unavailable')
})
it('delegates a same-id foreign agent', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: delegates a same-id foreign agent', async (storage) => {
harness = await makeBridgeHarness(storage)
const request = await ownedRequest()
const events = [{ type: 'turn/start', seq: 0, time: 0, data: { turn: 1 } }]
const foreign = {
@@ -84,8 +84,8 @@ describe('ACP machine permission policy', () => {
expect(harness.permissionRequests).toHaveLength(0)
})
it('delegates requests that have no protocol tool-call identity', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: delegates requests that have no protocol tool-call identity', async (storage) => {
harness = await makeBridgeHarness(storage)
const request = await ownedRequest()
await expect(harness.ctx.approval.request({ agent: request.agent, toolName: request.toolName }))
.resolves.toBe('unavailable')
+105 -105
View File
@@ -40,8 +40,8 @@ describe('automation-only ACP bridge', () => {
harness = undefined
})
it('advertises the standard automation controls without private metadata', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: advertises the standard automation controls without private metadata', async (storage) => {
harness = await makeBridgeHarness(storage)
const response = await harness.client.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: { _meta: { terminal_output: true } },
@@ -59,26 +59,26 @@ describe('automation-only ACP bridge', () => {
})
})
it('advertises image prompts only with an exact capable route and attachment store', async () => {
harness = await makeBridgeHarness({ imageCapable: true })
it.each(['jsonl', 'sqlite'] as const)('%s: advertises image prompts only with an exact capable route and attachment store', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true })
const capable = await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
expect(capable.agentCapabilities?.promptCapabilities?.image).toBe(true)
await harness.dispose()
harness = await makeBridgeHarness({ imageCapable: true, attachments: false })
harness = await makeBridgeHarness(storage, { imageCapable: true, attachments: false })
const noStore = await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
expect(noStore.agentCapabilities?.promptCapabilities?.image).toBe(false)
})
it('negotiates an unsupported version and accepts the required no-op authentication call', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: negotiates an unsupported version and accepts the required no-op authentication call', async (storage) => {
harness = await makeBridgeHarness(storage)
const response = await harness.client.initialize({ protocolVersion: 0, clientCapabilities: {} })
expect(response.protocolVersion).toBe(PROTOCOL_VERSION)
await expect(harness.client.authenticate({ methodId: 'unused' })).resolves.toEqual({})
})
it('creates a session, emits one committed answer, and settles the prompt', async () => {
harness = await makeBridgeHarness({ script: [textResponse('hello there')] })
it.each(['jsonl', 'sqlite'] as const)('%s: creates a session, emits one committed answer, and settles the prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('hello there')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const result = await harness.client.prompt({
@@ -98,8 +98,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]?.messages.at(-1)?.content).toEqual([{ type: 'text', text: 'say hello' }])
})
it('closes one active session without affecting its neighbor', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: closes one active session without affecting its neighbor', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const first = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const second = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -114,8 +114,8 @@ describe('automation-only ACP bridge', () => {
})).rejects.toThrow(/unknown session/)
})
it('cancels a running prompt and makes its session resumable before close returns', async () => {
harness = await makeBridgeHarness({ script: ['hang', textResponse('resumed')] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels a running prompt and makes its session resumable before close returns', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', textResponse('resumed')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const prompt = harness.client.prompt({ sessionId: created.sessionId, prompt: [{ type: 'text', text: 'hang' }] })
@@ -132,8 +132,8 @@ describe('automation-only ACP bridge', () => {
await harness.client.resumeSession({ sessionId: created.sessionId, cwd: process.cwd(), mcpServers: [] })
})
it('shares one close operation and rejects new work while close is draining', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: shares one close operation and rejects new work while close is draining', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const flushing: PromiseWithResolvers<void> = Promise.withResolvers()
@@ -152,8 +152,8 @@ describe('automation-only ACP bridge', () => {
await expect(Promise.all([first, second])).resolves.toEqual([{}, {}])
})
it('disposes the Agent and reports an explicit close drain failure', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: disposes the Agent and reports an explicit close drain failure', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(created.sessionId))!
@@ -164,8 +164,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(created.sessionId))).toBeUndefined()
})
it('resumes a closed persisted session without replaying its history', async () => {
harness = await makeBridgeHarness({ script: [textResponse('first answer'), textResponse('second answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: resumes a closed persisted session without replaying its history', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('first answer'), textResponse('second answer')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({ sessionId: created.sessionId, prompt: [{ type: 'text', text: 'first prompt' }] })
@@ -191,8 +191,8 @@ describe('automation-only ACP bridge', () => {
])
})
it('materializes an empty closed session for list and resume', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: materializes an empty closed session for list and resume', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -205,8 +205,8 @@ describe('automation-only ACP bridge', () => {
.resolves.toHaveProperty('configOptions')
})
it('rejects active or wrong-workspace resume before composing another Agent', async () => {
harness = await makeBridgeHarness({ script: [textResponse('persisted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects active or wrong-workspace resume before composing another Agent', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await expect(harness.client.resumeSession({
@@ -232,8 +232,8 @@ describe('automation-only ACP bridge', () => {
})).resolves.toHaveProperty('configOptions')
})
it('reserves a persisted id across concurrent resume admission', async () => {
harness = await makeBridgeHarness({ script: [textResponse('persisted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: reserves a persisted id across concurrent resume admission', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({ sessionId: created.sessionId, prompt: [{ type: 'text', text: 'persist' }] })
@@ -257,8 +257,8 @@ describe('automation-only ACP bridge', () => {
await expect(first).resolves.toHaveProperty('configOptions')
})
it('excludes a globally live session owned outside this ACP bridge', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: excludes a globally live session owned outside this ACP bridge', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const sessionId = brandString<SessionId>('other-frontend-live')
harness.ctx.sessions.create(sessionId, { meta: { cwd: process.cwd() } })
@@ -280,8 +280,8 @@ describe('automation-only ACP bridge', () => {
expect(resume).not.toHaveBeenCalled()
})
it('rejects unknown resume ids and rolls back invalid resume MCP', async () => {
harness = await makeBridgeHarness({ script: [textResponse('persisted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects unknown resume ids and rolls back invalid resume MCP', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await expect(harness.client.resumeSession({
sessionId: 'missing',
@@ -300,8 +300,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.list()).toHaveLength(0)
})
it('restores the deployment selection when persisted events have no request header', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: restores the deployment selection when persisted events have no request header', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(created.sessionId))!
@@ -315,8 +315,8 @@ describe('automation-only ACP bridge', () => {
})
})
it('restores a pending model selection without any request header', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: restores a pending model selection without any request header', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.setSessionConfigOption({
@@ -333,8 +333,8 @@ describe('automation-only ACP bridge', () => {
})
})
it('restores an explicitly selected reasoning effort', async () => {
harness = await makeBridgeHarness({ script: [textResponse('persisted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: restores an explicitly selected reasoning effort', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.setSessionConfigOption({
@@ -352,8 +352,8 @@ describe('automation-only ACP bridge', () => {
})
})
it('lists closed persisted sessions without presentation metadata', async () => {
harness = await makeBridgeHarness({ script: [textResponse('answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: lists closed persisted sessions without presentation metadata', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({ sessionId: created.sessionId, prompt: [{ type: 'text', text: 'persist me' }] })
@@ -364,8 +364,8 @@ describe('automation-only ACP bridge', () => {
})
})
it('paginates resumable sessions with an opaque deterministic cursor', async () => {
harness = await makeBridgeHarness({
it.each(['jsonl', 'sqlite'] as const)('%s: paginates resumable sessions with an opaque deterministic cursor', async (storage) => {
harness = await makeBridgeHarness(storage, {
config: { sessionListPageSize: 1 },
script: [textResponse('first'), textResponse('second')],
})
@@ -389,8 +389,8 @@ describe('automation-only ACP bridge', () => {
await expect(harness.client.listSessions({ cursor: 'not-a-cursor' })).rejects.toThrow(/cursor is invalid/)
})
it.each([false, true])('resumes an ordinary fork with legacy parent metadata=%s', async (legacy) => {
harness = await makeBridgeHarness()
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: resumes an ordinary fork with legacy parent metadata=%s', async (storage, legacy) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const id = brandString<SessionId>('ordinary-fork')
const writer = await harness.ctx.sessionPersistence.create({
@@ -405,8 +405,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.get(id)?.session.header.parentSession).toBe(legacy ? 'source' : undefined)
})
it('filters non-resumable headers and canonical missing workspaces', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: filters non-resumable headers and canonical missing workspaces', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const active = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const persistence = harness.ctx.get('sessionPersistence')!
@@ -439,21 +439,21 @@ describe('automation-only ACP bridge', () => {
})).rejects.toThrow(/cwd does not match/)
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
[null],
[[]],
[['not-a-number', 'id']],
[[-1, 'id']],
[[1, '']],
] as const)('rejects malformed decoded list cursors %#', async (decoded) => {
harness = await makeBridgeHarness()
] as const).map(value => [storage, value] as const)))('%s: rejects malformed decoded list cursors %#', async (storage, decoded) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const cursor = Buffer.from(JSON.stringify(decoded)).toString('base64url')
await expect(harness.client.listSessions({ cursor })).rejects.toThrow(/cursor is invalid/)
})
it('rejects invalid and non-canonical cursor encodings', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: rejects invalid and non-canonical cursor encodings', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await expect(harness.client.listSessions({ cursor: '*' })).rejects.toThrow(/cursor is invalid/)
const bytes = Buffer.from(JSON.stringify([1, 'id']))
@@ -467,8 +467,8 @@ describe('automation-only ACP bridge', () => {
await expect(harness.client.listSessions({ cursor: nonCanonical })).rejects.toThrow(/cursor is invalid/)
})
it('rolls back new and resume when configuration discovery fails', async () => {
harness = await makeBridgeHarness({ script: [textResponse('persisted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rolls back new and resume when configuration discovery fails', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const resolve = vi.spyOn(harness.ctx.llm, 'resolveCallConfig')
resolve.mockRejectedValueOnce(new Error('catalog resolution failed'))
@@ -489,8 +489,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.list()).toHaveLength(0)
})
it('propagates non-MCP Agent factory failures and non-config selection failures', async () => {
harness = await makeBridgeHarness({ script: [textResponse('persisted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: propagates non-MCP Agent factory failures and non-config selection failures', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const create = vi.spyOn(harness.ctx.agents, 'create')
create.mockRejectedValueOnce(new Error('factory create failed'))
@@ -518,17 +518,17 @@ describe('automation-only ACP bridge', () => {
.rejects.toThrow(/Internal error/)
})
it('lists and resumes persisted sessions after an equivalent process restart', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: lists and resumes persisted sessions after an equivalent process restart', async (storage) => {
const persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-acp-restart-'))
try {
harness = await makeBridgeHarness({ persistenceRoot, script: [textResponse('before restart')] })
harness = await makeBridgeHarness(storage, { persistenceRoot, script: [textResponse('before restart')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({ sessionId: created.sessionId, prompt: [{ type: 'text', text: 'first' }] })
await harness.client.closeSession({ sessionId: created.sessionId })
await harness.dispose()
harness = await makeBridgeHarness({ persistenceRoot, script: [textResponse('after restart')] })
harness = await makeBridgeHarness(storage, { persistenceRoot, script: [textResponse('after restart')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await expect(harness.client.listSessions({})).resolves.toEqual({
sessions: [{ sessionId: created.sessionId, cwd: process.cwd() }],
@@ -545,8 +545,8 @@ describe('automation-only ACP bridge', () => {
}
})
it('discovers and selects a session model through standard config options', async () => {
harness = await makeBridgeHarness({ script: [textResponse('plain answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: discovers and selects a session model through standard config options', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('plain answer')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const model = created.configOptions?.find(option => option.id === 'model')
@@ -566,8 +566,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]).toMatchObject({ provider: 'mock', model: 'plain' })
})
it('publishes complete config options when adapter topology changes', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: publishes complete config options when adapter topology changes', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -584,8 +584,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.sessionUpdates.at(-1)?.sessionId).toBe(created.sessionId)
})
it('does not let hung topology discovery block prompt completion or close', async () => {
harness = await makeBridgeHarness({ script: [textResponse('still responsive')] })
it.each(['jsonl', 'sqlite'] as const)('%s: does not let hung topology discovery block prompt completion or close', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('still responsive')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const original = harness.ctx.llm.listModels.bind(harness.ctx.llm)
@@ -608,8 +608,8 @@ describe('automation-only ACP bridge', () => {
}
})
it('publishes recoverable options when the selected adapter disappears', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: publishes recoverable options when the selected adapter disappears', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
harness.registerCatalogProvider('other')
@@ -634,8 +634,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.sessionUpdates.at(-1)?.sessionId).toBe(created.sessionId)
})
it('selects an advertised reasoning effort for the next turn', async () => {
harness = await makeBridgeHarness({ script: [textResponse('reasoned')] })
it.each(['jsonl', 'sqlite'] as const)('%s: selects an advertised reasoning effort for the next turn', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('reasoned')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const reasoning = created.configOptions?.find(option => option.id === 'reasoning_effort')
@@ -653,8 +653,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]?.reasoningEffort).toBe('low')
})
it('rejects unknown config choices without changing the selected route', async () => {
harness = await makeBridgeHarness({ script: [textResponse('unchanged')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects unknown config choices without changing the selected route', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('unchanged')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -673,8 +673,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]).toMatchObject({ provider: 'mock', model: 'mock' })
})
it('serializes concurrent standard config changes in receive order', async () => {
harness = await makeBridgeHarness({ script: [textResponse('plain')] })
it.each(['jsonl', 'sqlite'] as const)('%s: serializes concurrent standard config changes in receive order', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('plain')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const model = created.configOptions?.find(option => option.id === 'model')
@@ -703,8 +703,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]?.reasoningEffort).toBeUndefined()
})
it('checks images against the admission route and uses the latest selection when the step starts', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [textResponse('image accepted')] })
it.each(['jsonl', 'sqlite'] as const)('%s: checks images against the admission route and uses the latest selection when the step starts', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [textResponse('image accepted')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const model = created.configOptions?.find(option => option.id === 'model')
@@ -740,8 +740,8 @@ describe('automation-only ACP bridge', () => {
})).rejects.toThrow(/does not declare image input/)
})
it('applies a mid-turn model change to the following step', async () => {
harness = await makeBridgeHarness({ script: [oneToolCall(), textResponse('first turn'), textResponse('second turn')] })
it.each(['jsonl', 'sqlite'] as const)('%s: applies a mid-turn model change to the following step', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [oneToolCall(), textResponse('first turn'), textResponse('second turn')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const model = created.configOptions?.find(option => option.id === 'model')
@@ -769,8 +769,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests.map(request => request.model)).toEqual(['mock', 'plain', 'plain'])
})
it('mounts a standard stdio MCP server inside the created session', async () => {
harness = await makeBridgeHarness({ script: [textResponse('used MCP')] })
it.each(['jsonl', 'sqlite'] as const)('%s: mounts a standard stdio MCP server inside the created session', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('used MCP')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const fixtureServer = fileURLToPath(new URL('../../../mcp/mcp-client/tests/fixture-server.ts', import.meta.url))
const created = await harness.client.newSession({
@@ -784,10 +784,10 @@ describe('automation-only ACP bridge', () => {
await harness.client.closeSession({ sessionId: created.sessionId })
}, 30_000)
it('mounts a standard Streamable HTTP MCP server with request headers', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: mounts a standard Streamable HTTP MCP server with request headers', async (storage) => {
const fixture = await startHttpMcpFixture()
try {
harness = await makeBridgeHarness({ script: [textResponse('used HTTP MCP')] })
harness = await makeBridgeHarness(storage, { script: [textResponse('used HTTP MCP')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({
cwd: process.cwd(),
@@ -809,8 +809,8 @@ describe('automation-only ACP bridge', () => {
}
}, 30_000)
it('allows the same MCP server namespace in independent sessions', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: allows the same MCP server namespace in independent sessions', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const fixtureServer = fileURLToPath(new URL('../../../mcp/mcp-client/tests/fixture-server.ts', import.meta.url))
const mcpServers = [{ name: 'fixture', command: process.execPath, args: [fixtureServer], env: [] }]
@@ -824,8 +824,8 @@ describe('automation-only ACP bridge', () => {
])
}, 30_000)
it('validates standard MCP declarations before publishing an Agent', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: validates standard MCP declarations before publishing an Agent', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const stdio = { name: 'fixture', command: process.execPath, args: [], env: [] }
const invalidLists = [
@@ -847,8 +847,8 @@ describe('automation-only ACP bridge', () => {
}
})
it('reconnects requested MCP servers when resuming a closed session', async () => {
harness = await makeBridgeHarness({ script: [textResponse('first'), textResponse('second')] })
it.each(['jsonl', 'sqlite'] as const)('%s: reconnects requested MCP servers when resuming a closed session', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('first'), textResponse('second')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const fixtureServer = fileURLToPath(new URL('../../../mcp/mcp-client/tests/fixture-server.ts', import.meta.url))
const mcpServers = [{ name: 'fixture', command: process.execPath, args: [fixtureServer], env: [] }]
@@ -862,16 +862,16 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[1]?.tools?.map(tool => tool.name)).toContain('mcp__fixture__add')
}, 30_000)
it('leaves absent agent targets for request listeners to supply', async () => {
harness = await makeBridgeHarness({ config: { provider: undefined, model: undefined } })
it.each(['jsonl', 'sqlite'] as const)('%s: leaves absent agent targets for request listeners to supply', async (storage) => {
harness = await makeBridgeHarness(storage, { config: { provider: undefined, model: undefined } })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))?.options).toEqual({})
})
it('uses a recorded selection when ACP has no initial route', async () => {
harness = await makeBridgeHarness({
it.each(['jsonl', 'sqlite'] as const)('%s: uses a recorded selection when ACP has no initial route', async (storage) => {
harness = await makeBridgeHarness(storage, {
config: { provider: undefined, model: undefined },
script: [textResponse('listener-routed')],
})
@@ -888,8 +888,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]).toMatchObject({ provider: 'mock', model: 'mock' })
})
it('concatenates text blocks without exposing protocol framing to the model', async () => {
harness = await makeBridgeHarness({ script: [textResponse('done')] })
it.each(['jsonl', 'sqlite'] as const)('%s: concatenates text blocks without exposing protocol framing to the model', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('done')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({
@@ -903,8 +903,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.adapter.requests[0]?.messages.at(-1)?.content).toEqual([{ type: 'text', text: 'first second' }])
})
it('admits mixed text/image prompts in wire order and logs references only', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [textResponse('done')] })
it.each(['jsonl', 'sqlite'] as const)('%s: admits mixed text/image prompts in wire order and logs references only', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [textResponse('done')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const resolve = vi.spyOn(harness.ctx.llm, 'resolveModelInfo')
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -938,8 +938,8 @@ describe('automation-only ACP bridge', () => {
expect(JSON.stringify(agent?.session.snapshotEvents())).not.toContain('AQ==')
})
it('rejects a malformed image batch atomically and frees the prompt slot', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [textResponse('recovered')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a malformed image batch atomically and frees the prompt slot', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [textResponse('recovered')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -956,8 +956,8 @@ describe('automation-only ACP bridge', () => {
.resolves.toEqual({ stopReason: 'end_turn' })
})
it('reports durable image write failures as internal prompt failures', async () => {
harness = await makeBridgeHarness({ imageCapable: true })
it.each(['jsonl', 'sqlite'] as const)('%s: reports durable image write failures as internal prompt failures', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
vi.spyOn(harness.attachments!, 'saveImages').mockRejectedValueOnce(
@@ -970,8 +970,8 @@ describe('automation-only ACP bridge', () => {
})).rejects.toThrow(/unable to persist the prompt image batch/)
})
it('renders the deployment persona for an ACP-created agent', async () => {
harness = await makeBridgeHarness({ persona: 'Automation persona for {{model}}.', script: [textResponse('ok')] })
it.each(['jsonl', 'sqlite'] as const)('%s: renders the deployment persona for an ACP-created agent', async (storage) => {
harness = await makeBridgeHarness(storage, { persona: 'Automation persona for {{model}}.', script: [textResponse('ok')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })
@@ -980,8 +980,8 @@ describe('automation-only ACP bridge', () => {
expect(head?.content.some(part => part.type === 'text' && part.text.includes('Automation persona for mock.'))).toBe(true)
})
it('requires one absolute primary workspace', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: requires one absolute primary workspace', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await expect(harness.client.newSession({ cwd: 'relative', mcpServers: [] })).rejects.toThrow(/absolute path/)
@@ -997,8 +997,8 @@ describe('automation-only ACP bridge', () => {
})).resolves.toHaveProperty('sessionId')
})
it('rejects empty and unadvertised image prompts before a turn starts', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: rejects empty and unadvertised image prompts before a turn starts', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -1011,8 +1011,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))?.session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false)
})
it('renders baseline resource links as textual references in the user message', async () => {
harness = await makeBridgeHarness({ script: [textResponse('done')] })
it.each(['jsonl', 'sqlite'] as const)('%s: renders baseline resource links as textual references in the user message', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('done')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
await harness.client.prompt({
@@ -1028,8 +1028,8 @@ describe('automation-only ACP bridge', () => {
}])
})
it('rejects prompts for unknown sessions and ignores unknown cancellation', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: rejects prompts for unknown sessions and ignores unknown cancellation', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await expect(harness.client.prompt({ sessionId: 'missing', prompt: [{ type: 'text', text: 'go' }] }))
.rejects.toThrow(/unknown session/)
+21 -21
View File
@@ -18,8 +18,8 @@ describe('ACP connection ownership', () => {
await bridge?.dispose()
})
it('disposal cancels a running prompt and awaits agent teardown', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: disposal cancels a running prompt and awaits agent teardown', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -32,9 +32,9 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it('disposal drains asynchronous assistant image delivery before releasing sessions', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: disposal drains asynchronous assistant image delivery before releasing sessions', async (storage) => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(4), mediaType: 'image/png' })
script.push([
{ type: 'block-start', index: 0, blockType: 'image' },
@@ -63,8 +63,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it('drains continuable subagents before disposing its own sessions', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: drains continuable subagents before disposing its own sessions', async (storage) => {
harness = await makeBridgeHarness(storage)
const order: string[] = []
let drainedParents: readonly Agent[] = []
// A continuable Activation outlives the turn that started it, so the bridge
@@ -88,8 +88,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it('cancels its own prompt before awaiting the descendant drain', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels its own prompt before awaiting the descendant drain', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const order: string[] = []
const release = Promise.withResolvers<undefined>()
harness.ctx.provide('subagents', {
@@ -124,8 +124,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it('reports a failed continuable drain and still disposes its sessions', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: reports a failed continuable drain and still disposes its sessions', async (storage) => {
harness = await makeBridgeHarness(storage)
const warnings: string[] = []
harness.ctx.logger.warn = (message: string) => { warnings.push(message) }
harness.ctx.provide('subagents', {
@@ -141,8 +141,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it('awaits every owned session disposal and reports nested failure reasons', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: awaits every owned session disposal and reports nested failure reasons', async (storage) => {
harness = await makeBridgeHarness(storage)
const create = harness.ctx.agents.create.bind(harness.ctx.agents)
const releaseSecond = Promise.withResolvers<undefined>()
const warnings: string[] = []
@@ -194,8 +194,8 @@ describe('ACP connection ownership', () => {
await disposed.dispose().catch(() => undefined)
})
it('an ACP-only reload rejects new sessions before creating an orphan', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: an ACP-only reload rejects new sessions before creating an orphan', async (storage) => {
harness = await makeBridgeHarness(storage)
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await harness.acpFiber.dispose()
await expect(harness.client.newSession({ cwd: process.cwd(), mcpServers: [] }))
@@ -203,11 +203,11 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.list()).toHaveLength(0)
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
['a client disconnect', 'closeClientTransport'],
['a failed client transport', 'abortClientTransport'],
] as const)('%s disposes its session without plugin disposal', async (_name, disconnect) => {
harness = await makeBridgeHarness({ script: ['hang'] })
] as const).map(value => [storage, ...value] as const)))('%s: %s disposes its session without plugin disposal', async (storage, _name, disconnect) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const bridge = harness
const create = bridge.ctx.agents.create.bind(bridge.ctx.agents)
const disposalStarted = Promise.withResolvers<undefined>()
@@ -257,8 +257,8 @@ describe('ACP connection ownership', () => {
}
})
it('disconnect and plugin disposal share one quiescence boundary', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: disconnect and plugin disposal share one quiescence boundary', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -270,8 +270,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it('disposing a session-less bridge is idempotent', async () => {
harness = await makeBridgeHarness()
it.each(['jsonl', 'sqlite'] as const)('%s: disposing a session-less bridge is idempotent', async (storage) => {
harness = await makeBridgeHarness(storage)
await Promise.all([harness.acpFiber.dispose(), harness.acpFiber.dispose()])
expect(harness.ctx.agents.list()).toHaveLength(0)
})
+10 -10
View File
@@ -34,8 +34,8 @@ describe('ACP automation output boundary', () => {
harness = undefined
})
it('emits committed reasoning, generic tool lifecycle, usage, and final text in order', async () => {
harness = await makeBridgeHarness({ script: [toolCallResponse(), textResponse('done')] })
it.each(['jsonl', 'sqlite'] as const)('%s: emits committed reasoning, generic tool lifecycle, usage, and final text in order', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [toolCallResponse(), textResponse('done')] })
harness.ctx.tools.register(defineContentToolFixture({
name: 'echo',
description: 'Return a deterministic result.',
@@ -87,8 +87,8 @@ describe('ACP automation output boundary', () => {
expect(typeof harness.updates[5].used).toBe('number')
})
it('ignores events from agents the bridge does not own', async () => {
harness = await makeBridgeHarness({ script: [textResponse('foreign')] })
it.each(['jsonl', 'sqlite'] as const)('%s: ignores events from agents the bridge does not own', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('foreign')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const { agent } = await harness.ctx.agents.create({
@@ -100,8 +100,8 @@ describe('ACP automation output boundary', () => {
expect(harness.updates).toHaveLength(0)
})
it('delivers output from a bridge-owned session driven by another in-process producer', async () => {
harness = await makeBridgeHarness({ script: [textResponse('external')] })
it.each(['jsonl', 'sqlite'] as const)('%s: delivers output from a bridge-owned session driven by another in-process producer', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('external')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -117,8 +117,8 @@ describe('ACP automation output boundary', () => {
expect('messageId' in harness.updates[0]!).toBe(true)
})
it('contains output conversion failure outside an ACP prompt', async () => {
harness = await makeBridgeHarness({ script: [[
it.each(['jsonl', 'sqlite'] as const)('%s: contains output conversion failure outside an ACP prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [[
{ type: 'block-start', index: 0, blockType: 'image' },
{
type: 'block-end',
@@ -151,8 +151,8 @@ describe('ACP automation output boundary', () => {
// failure never reaches the bridge; this pins that the prompt still settles
// normally with such a client. The bridge's own write-failure guard is
// transport-level and documented untestable at `notify`.
it('settles the prompt normally when the client rejects update notifications', async () => {
harness = await makeBridgeHarness({ script: [textResponse('answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: settles the prompt normally when the client rejects update notifications', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
harness.onSessionUpdateError = () => {}
+2 -2
View File
@@ -220,7 +220,7 @@ export interface BridgeHarness {
type AcpConfigOverrides = { [K in keyof AcpConfig]?: AcpConfig[K] | undefined }
/** Build the bridge and a connected SDK client over cross-wired byte streams. */
export async function makeBridgeHarness(options: {
export async function makeBridgeHarness(storage: 'jsonl' | 'sqlite', options: {
script?: (StreamChunk[] | 'hang')[]
config?: AcpConfigOverrides
persona?: string
@@ -233,7 +233,7 @@ export async function makeBridgeHarness(options: {
const ownsPersistenceRoot = options.persistenceRoot === undefined
const persistenceRoot = options.persistenceRoot ?? await mkdtemp(join(tmpdir(), 'dsh-acp-test-'))
await mountAgentLoopTestDependencies(ctx, { systemPrompt: { personaPrefix: options.persona ?? '' } })
await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { storage, root: persistenceRoot, compression: 'none' })
await ctx.plugin(TokenMeter)
if (options.attachments !== false) await ctx.plugin(MemoryAttachmentStore)
const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
+8 -8
View File
@@ -23,8 +23,8 @@ describe('ACP multi-session isolation', () => {
harness = undefined
})
it('demultiplexes concurrent answers by session id', async () => {
harness = await makeBridgeHarness({ script: [textResponse('answer-A'), textResponse('answer-B')] })
it.each(['jsonl', 'sqlite'] as const)('%s: demultiplexes concurrent answers by session id', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer-A'), textResponse('answer-B')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
@@ -41,8 +41,8 @@ describe('ACP multi-session isolation', () => {
})
})
it('cancels one session without affecting another', async () => {
harness = await makeBridgeHarness({ script: ['hang', textResponse('B done')] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels one session without affecting another', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', textResponse('B done')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
@@ -56,8 +56,8 @@ describe('ACP multi-session isolation', () => {
await vi.waitFor(() => { expect(messageTextFor(harness!.sessionUpdates, b)).toBe('B done') })
})
it('enforces one in-flight prompt independently for each session', async () => {
harness = await makeBridgeHarness({ script: ['hang', 'hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: enforces one in-flight prompt independently for each session', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', 'hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
@@ -75,8 +75,8 @@ describe('ACP multi-session isolation', () => {
await expect(pendingB).resolves.toEqual({ stopReason: 'cancelled' })
})
it('drains every live session on bridge disposal', async () => {
harness = await makeBridgeHarness({ script: ['hang', 'hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: drains every live session on bridge disposal', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', 'hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
+80 -80
View File
@@ -69,17 +69,17 @@ describe('ACP prompt lifecycle', () => {
harness = undefined
})
it('reports a max-token turn without losing its committed text', async () => {
harness = await makeBridgeHarness({ script: [maxTokensResponse('cut off')] })
it.each(['jsonl', 'sqlite'] as const)('%s: reports a max-token turn without losing its committed text', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [maxTokensResponse('cut off')] })
const sessionId = await newSession(harness)
const result = await harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })
expect(result.stopReason).toBe('max_tokens')
await vi.waitFor(() => { expect(messageText(harness!)).toBe('cut off') })
})
it('delivers a committed assistant image as verified ACP base64', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: delivers a committed assistant image as verified ACP base64', async (storage) => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(1), mediaType: 'image/png' })
script.push([
{ type: 'block-start', index: 0, blockType: 'image' },
@@ -103,9 +103,9 @@ describe('ACP prompt lifecycle', () => {
expect(image !== undefined && 'messageId' in image && typeof image.messageId === 'string').toBe(true)
})
it('preserves committed text/image/text order on the ACP wire', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: preserves committed text/image/text order on the ACP wire', async (storage) => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(2), mediaType: 'image/jpeg' })
script.push([
{ type: 'block-start', index: 0, blockType: 'text' },
@@ -131,9 +131,9 @@ describe('ACP prompt lifecycle', () => {
expect(new Set(harness.updates.map(update => 'messageId' in update ? update.messageId : undefined)).size).toBe(1)
})
it('does not settle a prompt before ordered output delivery drains', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: does not settle a prompt before ordered output delivery drains', async (storage) => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(3), mediaType: 'image/png' })
script.push([
{ type: 'block-start', index: 0, blockType: 'image' },
@@ -157,7 +157,7 @@ describe('ACP prompt lifecycle', () => {
await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' })
})
it('fails prompt delivery when a committed image attachment is missing', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: fails prompt delivery when a committed image attachment is missing', async (storage) => {
const missing = {
attachmentId: `sha256:${'a'.repeat(64)}` as never,
mediaType: 'image/png' as const,
@@ -165,7 +165,7 @@ describe('ACP prompt lifecycle', () => {
width: 1,
height: 1,
}
harness = await makeBridgeHarness({ script: [[
harness = await makeBridgeHarness(storage, { script: [[
{ type: 'block-start', index: 0, blockType: 'image' },
{ type: 'block-end', index: 0, block: { type: 'image', attachment: missing } },
{ type: 'finish', reason: { kind: 'stop' } },
@@ -177,24 +177,24 @@ describe('ACP prompt lifecycle', () => {
expect(harness.updates).toEqual([])
})
it('rejects a failed turn and never publishes its partial chunks', async () => {
harness = await makeBridgeHarness({ script: [errorResponse('provider boom')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a failed turn and never publishes its partial chunks', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [errorResponse('provider boom')] })
const sessionId = await newSession(harness)
await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }))
.rejects.toThrow(/turn failed: provider boom/)
expect(messageText(harness)).toBe('')
})
it('rejects an ordinary plugin failure through the same prompt boundary', async () => {
harness = await makeBridgeHarness({ script: [textResponse('must not run')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects an ordinary plugin failure through the same prompt boundary', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('must not run')] })
harness.ctx.on('agent/pre-step', () => { throw new Error('plugin pre-step failed') })
const sessionId = await newSession(harness)
await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }))
.rejects.toThrow(/turn failed: plugin pre-step failed/)
})
it('rejects a turn-start failure before the prompt is claimed', async () => {
harness = await makeBridgeHarness({ script: [textResponse('must not run')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a turn-start failure before the prompt is claimed', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('must not run')] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
const append = agent.session.append.bind(agent.session)
@@ -208,8 +208,8 @@ describe('ACP prompt lifecycle', () => {
vi.restoreAllMocks()
})
it.each(['turn/start', 'turn/end'] as const)('rejects a later %s append failure after an earlier completed turn', async (failedEvent) => {
harness = await makeBridgeHarness({ script: [textResponse('waiting'), textResponse('summary')] })
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['turn/start', 'turn/end'] as const).map(value => [storage, value] as const)))('%s: rejects a later %s append failure after an earlier completed turn', async (storage, failedEvent) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('waiting'), textResponse('summary')] })
const sessionId = await newSession(harness)
const parent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
const append = parent.session.append.bind(parent.session)
@@ -235,8 +235,8 @@ describe('ACP prompt lifecycle', () => {
}
})
it('settles even when an earlier turn observer throws', async () => {
harness = await makeBridgeHarness({ script: [textResponse('answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: settles even when an earlier turn observer throws', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
harness.ctx.on('session/event', (_session, event) => {
if (event.type === 'turn/start' || event.type === 'turn/end') throw new Error('peer listener boom')
}, { prepend: true })
@@ -245,8 +245,8 @@ describe('ACP prompt lifecycle', () => {
.resolves.toEqual({ stopReason: 'end_turn' })
})
it('correlates the owning prompt when a synchronous injection joins its first step', async () => {
harness = await makeBridgeHarness({ script: [textResponse('real answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: correlates the owning prompt when a synchronous injection joins its first step', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('real answer')] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
let injected = false
@@ -262,8 +262,8 @@ describe('ACP prompt lifecycle', () => {
await vi.waitFor(() => { expect(messageText(harness!)).toBe('real answer') })
})
it('ignores an autonomous message turn while correlating the client turn', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: ignores an autonomous message turn while correlating the client turn', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
let autonomousStarted!: () => void
@@ -289,8 +289,8 @@ describe('ACP prompt lifecycle', () => {
await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' })
})
it('correlates a prompt whose step history is replaced', async () => {
harness = await makeBridgeHarness({ script: [textResponse('rewritten answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: correlates a prompt whose step history is replaced', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('rewritten answer')] })
harness.ctx.on('agent/pre-step', async () => ({
kind: 'enter',
messages: [createUserMessage({
@@ -304,8 +304,8 @@ describe('ACP prompt lifecycle', () => {
.resolves.toEqual({ stopReason: 'end_turn' })
})
it('frees the prompt slot when the agent rejects the send synchronously', async () => {
harness = await makeBridgeHarness({ script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: frees the prompt slot when the agent rejects the send synchronously', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
const sessionId = await newSession(harness)
// Reload the loop out from under the bridge: its agents dispose while the
// bridge record survives, so the next send() throws synchronously.
@@ -317,8 +317,8 @@ describe('ACP prompt lifecycle', () => {
.rejects.toThrow(/prompt was not queued/)
})
it('permits only one in-flight prompt per session', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: permits only one in-flight prompt per session', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const sessionId = await newSession(harness)
const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] })
await vi.waitFor(() => { expect(harness!.ctx.agents.get(brandString<SessionId>(sessionId))?.status).toBe('running') })
@@ -328,8 +328,8 @@ describe('ACP prompt lifecycle', () => {
await expect(first).resolves.toEqual({ stopReason: 'cancelled' })
})
it('routes JSON-RPC request cancellation through the prompt cancellation path', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: routes JSON-RPC request cancellation through the prompt cancellation path', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const sessionId = await newSession(harness)
const controller = new AbortController()
const prompt = harness.client.prompt(
@@ -344,8 +344,8 @@ describe('ACP prompt lifecycle', () => {
expect(harness.adapter.requests[0]?.signal?.aborted).toBe(true)
})
it('cancels a prompt request whose JSON-RPC signal is already aborted', async () => {
harness = await makeBridgeHarness({ script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels a prompt request whose JSON-RPC signal is already aborted', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
const sessionId = await newSession(harness)
const controller = new AbortController()
controller.abort()
@@ -357,8 +357,8 @@ describe('ACP prompt lifecycle', () => {
expect(harness.adapter.requests).toEqual([])
})
it('reserves the prompt slot during image admission and cancels without a late followup', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: reserves the prompt slot during image admission and cancels without a late followup', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -385,8 +385,8 @@ describe('ACP prompt lifecycle', () => {
expect(events.some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false)
})
it('does not cancel unrelated Agent work while its prompt is still in admission', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: does not cancel unrelated Agent work while its prompt is still in admission', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: ['hang'] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -416,8 +416,8 @@ describe('ACP prompt lifecycle', () => {
await agent.whenIdle()
})
it('does not attribute an unrelated Agent failure during prompt admission', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [textResponse('answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: does not attribute an unrelated Agent failure during prompt admission', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [textResponse('answer')] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -449,8 +449,8 @@ describe('ACP prompt lifecycle', () => {
expect(messageText(harness)).toBe('answer')
})
it('does not queue admitted content into an agent retired during storage', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: does not queue admitted content into an agent retired during storage', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -472,8 +472,8 @@ describe('ACP prompt lifecycle', () => {
expect(harness.adapter.requests).toEqual([])
})
it('cancels after image storage completes before admission receives the result', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels after image storage completes before admission receives the result', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true, script: [] })
const sessionId = await newSession(harness)
const saveImages = harness.attachments!.saveImages.bind(harness.attachments!)
const cancel = vi.spyOn(AcpSession.prototype, 'cancel')
@@ -492,8 +492,8 @@ describe('ACP prompt lifecycle', () => {
expect(harness.adapter.requests).toEqual([])
})
it('wraps an unexpected same-process followup failure and frees the prompt slot', async () => {
harness = await makeBridgeHarness({ script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: wraps an unexpected same-process followup failure and frees the prompt slot', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
vi.spyOn(agent, 'followup').mockImplementationOnce(() => { throw new Error('synthetic followup failure') })
@@ -502,8 +502,8 @@ describe('ACP prompt lifecycle', () => {
.rejects.toThrow(/prompt was not queued: synthetic followup failure/)
})
it('cancels a running turn and records the aborted outcome', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels a running turn and records the aborted outcome', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const sessionId = await newSession(harness)
const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -515,8 +515,8 @@ describe('ACP prompt lifecycle', () => {
.toEqual({ kind: 'aborted', reason: { kind: 'user' } })
})
it('settles a hook-cancelled turn as end_turn, not cancelled', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: settles a hook-cancelled turn as end_turn, not cancelled', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const sessionId = await newSession(harness)
const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -527,8 +527,8 @@ describe('ACP prompt lifecycle', () => {
await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' })
})
it('cancels autonomous running work without an in-flight prompt', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels autonomous running work without an in-flight prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
agent.followup(createUserMessage({
@@ -546,8 +546,8 @@ describe('ACP prompt lifecycle', () => {
.toEqual({ kind: 'aborted', reason: { kind: 'user' } })
})
it('an idle cancel does not affect the following prompt', async () => {
harness = await makeBridgeHarness({ script: [textResponse('answer')] })
it.each(['jsonl', 'sqlite'] as const)('%s: an idle cancel does not affect the following prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
const sessionId = await newSession(harness)
await harness.client.cancel({ sessionId })
await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] }))
@@ -555,8 +555,8 @@ describe('ACP prompt lifecycle', () => {
await vi.waitFor(() => { expect(messageText(harness!)).toBe('answer') })
})
it('a late end from a cancelled turn cannot settle the next prompt', async () => {
harness = await makeBridgeHarness({ script: ['hang', textResponse('next')] })
it.each(['jsonl', 'sqlite'] as const)('%s: a late end from a cancelled turn cannot settle the next prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', textResponse('next')] })
const sessionId = await newSession(harness)
const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] })
await vi.waitFor(() => { expect(harness!.ctx.agents.get(brandString<SessionId>(sessionId))?.status).toBe('running') })
@@ -570,8 +570,8 @@ describe('ACP prompt lifecycle', () => {
await vi.waitFor(() => { expect(messageText(harness!)).toBe('partialnext') })
})
it('a retry turn adopts the prompt instead of rejecting at the failed turn end', async () => {
harness = await makeBridgeHarness({ script: [errorResponse('transient boom'), textResponse('recovered')] })
it.each(['jsonl', 'sqlite'] as const)('%s: a retry turn adopts the prompt instead of rejecting at the failed turn end', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [errorResponse('transient boom'), textResponse('recovered')] })
// A recovery policy: schedule one retry for the failed request.
let retried = false
harness.ctx.on('agent/request-error', async () => {
@@ -586,8 +586,8 @@ describe('ACP prompt lifecycle', () => {
await vi.waitFor(() => { expect(messageText(harness!)).toBe('recovered') })
})
it.each(['completed', 'error'] as const)('waits for descendants and reports the later %s summary turn', async (outcome) => {
harness = await makeBridgeHarness({ script: [
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['completed', 'error'] as const).map(value => [storage, value] as const)))('%s: waits for descendants and reports the later %s summary turn', async (storage, outcome) => {
harness = await makeBridgeHarness(storage, { script: [
textResponse('waiting'),
outcome === 'completed' ? textResponse('summary') : errorResponse('summary failed'),
] })
@@ -615,8 +615,8 @@ describe('ACP prompt lifecycle', () => {
await observed
})
it('cancels the child wait without closing the session to its next prompt', async () => {
harness = await makeBridgeHarness({ script: [textResponse('waiting'), textResponse('next')] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels the child wait without closing the session to its next prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('waiting'), textResponse('next')] })
const sessionId = await newSession(harness)
const waiting = Promise.withResolvers<undefined>()
const children = Promise.withResolvers<boolean>()
@@ -636,8 +636,8 @@ describe('ACP prompt lifecycle', () => {
expect(messageText(harness)).toBe('waitingnext')
})
it('releases a cancelled prompt before a late child message finishes and permits another delegation', async () => {
harness = await makeBridgeHarness({ script: [
it.each(['jsonl', 'sqlite'] as const)('%s: releases a cancelled prompt before a late child message finishes and permits another delegation', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [
textResponse('waiting'), textResponse('late autonomous answer'),
toolCallResponse('delegate-again', 'delegate_again', {}),
textResponse('later child answer'), textResponse('later parent answer'),
@@ -695,9 +695,9 @@ describe('ACP prompt lifecycle', () => {
}
})
it('settles an initially cancelled prompt after its output without waiting for a later summary', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: settles an initially cancelled prompt after its output without waiting for a later summary', async (storage) => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ctx = harness.ctx
const delegated = await installDelegationTool(ctx)
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(6), mediaType: 'image/png' })
@@ -790,8 +790,8 @@ describe('ACP prompt lifecycle', () => {
}
})
it('waits for cancelled maintenance cleanup without following its later summary', async () => {
harness = await makeBridgeHarness({ script: [
it.each(['jsonl', 'sqlite'] as const)('%s: waits for cancelled maintenance cleanup without following its later summary', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [
textResponse('late autonomous answer'),
toolCallResponse('delegate-again', 'delegate_again', {}),
textResponse('later child answer'), textResponse('later parent answer'),
@@ -856,9 +856,9 @@ describe('ACP prompt lifecycle', () => {
}
})
it.each([false, true])('waits for the later summary output and reports its delivery failure (%s)', async (fail) => {
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: waits for the later summary output and reports its delivery failure (%s)', async (storage, fail) => {
const script: StreamChunk[][] = [textResponse('waiting')]
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(4), mediaType: 'image/png' })
script.push([
{ type: 'block-start', index: 0, blockType: 'image' },
@@ -890,9 +890,9 @@ describe('ACP prompt lifecycle', () => {
await observed
})
it('includes root work started during output draining and permits the next prompt to delegate', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: includes root work started during output draining and permits the next prompt to delegate', async (storage) => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness({ script })
harness = await makeBridgeHarness(storage, { script })
const ctx = harness.ctx
const delegated = await installDelegationTool(ctx)
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(5), mediaType: 'image/png' })
@@ -950,8 +950,8 @@ describe('ACP prompt lifecycle', () => {
}
})
it('a failed turn with no retry still rejects', async () => {
harness = await makeBridgeHarness({ script: [errorResponse('terminal boom')] })
it.each(['jsonl', 'sqlite'] as const)('%s: a failed turn with no retry still rejects', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [errorResponse('terminal boom')] })
let offered = 0
harness.ctx.on('agent/request-error', async () => { offered += 1 })
const sessionId = await newSession(harness)
@@ -960,8 +960,8 @@ describe('ACP prompt lifecycle', () => {
expect(offered).toBe(1)
})
it('a pre-step-rejected prompt settles instead of hanging', async () => {
harness = await makeBridgeHarness({ script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: a pre-step-rejected prompt settles instead of hanging', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
harness.ctx.on('agent/pre-step', async () => ({
kind: 'reject' as const,
}))
@@ -972,8 +972,8 @@ describe('ACP prompt lifecycle', () => {
expect(messageText(harness)).toBe('')
})
it('cancels a prompt removed before its turn claims it', async () => {
harness = await makeBridgeHarness({ script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: cancels a prompt removed before its turn claims it', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
const sessionId = await newSession(harness)
const dispose = harness.ctx.on('agent/inbox/inserted', ({ agent, message }) => {
if (message.source.kind === 'user') agent.inbox.remove(message.id)
@@ -984,8 +984,8 @@ describe('ACP prompt lifecycle', () => {
dispose()
})
it('rejects a prompt when pre-step fails inside its open turn', async () => {
harness = await makeBridgeHarness({ script: [] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a prompt when pre-step fails inside its open turn', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
harness.ctx.on('agent/pre-step', async () => { throw new Error('pre-step exploded') })
const sessionId = await newSession(harness)
@@ -42,7 +42,7 @@ afterEach(async () => {
}
})
async function harness(withPersistence = true) {
async function createHarness(storage: 'jsonl' | 'sqlite', withPersistence = true) {
const root = await mkdtemp(join(tmpdir(), 'dsh-projection-discovery-'))
roots.push(root)
const ctx = new Context()
@@ -53,7 +53,7 @@ async function harness(withPersistence = true) {
await ctx.sessionProjections.register(subagentCatalogProjectionDefinition)
await ctx.sessionProjections.register(titleProjectionDefinition)
if (withPersistence) {
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'logs'), compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'logs'), compression: 'none', storage })
const list = vi.spyOn(ctx.sessionPersistence, 'list').mockRejectedValue(new Error('unexpected corpus listing'))
readAudits.push(() => {
expect(list).not.toHaveBeenCalled()
@@ -70,7 +70,7 @@ async function harness(withPersistence = true) {
return { ctx, root, controller }
}
type Harness = Awaited<ReturnType<typeof harness>>
type Harness = Awaited<ReturnType<typeof createHarness>>
async function stored(
fixture: Harness,
@@ -152,7 +152,8 @@ async function seedCache(
return { path, bytes }
}
describe('Session projection discovery', () => {
describe.each(['jsonl', 'sqlite'] as const)('Session projection discovery (%s)', (storage) => {
const harness = (withPersistence = true) => createHarness(storage, withPersistence)
it('defers V3 migration without reading child bodies or publishing a successor', async () => {
const fixture = await harness()
const parent = await stored(fixture, brandString<SessionId>('parent'), {}, 3)
@@ -246,16 +247,27 @@ describe('Session projection discovery', () => {
expect(fixture.ctx.agents.get(parent.header.id)).toBeUndefined()
})
it('imports historical files on observation and reads sequenced projections without a live Session', async () => {
it('reads historical projections and publishes migration through the selected backend without a live Session', async () => {
const fixture = await harness()
const parent = await stored(fixture, brandString<SessionId>('prepared-cold'), {}, 3)
using observation = await fixture.ctx.sessionQuery.observeSession(parent.header.id)
expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({
formatStatus: storage === 'sqlite' ? 'current' : 'migration-required',
})
await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal))
.resolves.toEqual(storage === 'sqlite'
? { kind: 'sequenced', ...observation.projections }
: { kind: 'migration-required', values: {} })
const writer = await fixture.ctx.sessionPersistence.open(parent.header.id, 'write')
await writer.close()
expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({ formatStatus: 'current' })
await expect(fixture.controller.projections({ sessionId: parent.header.id }, new AbortController().signal))
.resolves.toEqual({ kind: 'sequenced', ...observation.projections })
expect(fixture.ctx.sessions.get(parent.header.id)).toBeUndefined()
expect(await readFile(parent.path, 'utf8')).toBe(parent.bytes)
expect((await readdir(dirname(parent.path))).filter(name => name !== 'session.lock')).toEqual(['session.v3.jsonl'])
expect((await readdir(dirname(parent.path))).filter(name => name !== 'session.lock')).toEqual(storage === 'sqlite'
? ['session.v3.jsonl']
: ['session.v3.jsonl', `session.v${SESSION_FORMAT_VERSION}.jsonl`])
})
it('reports unsupported current-format events instead of deferring migration', async () => {
@@ -59,7 +59,7 @@ async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise<rea
}
}
describe('config-driven session id', () => {
describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (storage) => {
it('applies launcher identities by configured id without changing unmatched entries', async () => {
const ctx = await makeCoreContext()
ctx.provide(CONFIGURED_AGENT_IDENTITIES_KEY, {
@@ -116,7 +116,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-duplicate-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
const outcome = await ctx.plugin(AgentLoop, {
agents: [
@@ -135,7 +135,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-reload-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first'), textResponse('second')]))
const config = { agents: [{ id: 'main', sessionId: brandString<SessionId>('config-exact-reload'), provider: 'mock', model: 'mock' }] }
@@ -164,7 +164,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-overlap-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('saved')]))
const sessionId = brandString<SessionId>('config-exact-overlap')
const config = { agents: [{ id: 'main', sessionId, provider: 'mock', model: 'mock' }] }
@@ -211,7 +211,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-cancel-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
const sessionId = brandString<SessionId>('config-exact-cancel')
const config = { agents: [{ id: 'main', sessionId, model: 'mock' }] }
const firstLoop = await ctx.plugin(AgentLoop, config)
@@ -267,7 +267,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-failure-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
const failure = new Error('persistence index failed')
const listenerFailure = new Error('failure observer failed')
const asyncListenerFailure = new Error('async failure observer failed')
@@ -303,7 +303,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-unrenderable-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
const unrenderable = {
[Symbol.toPrimitive](): never {
throw new Error('coercion escaped')
@@ -341,7 +341,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-dispose-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
const opening = Promise.withResolvers<SessionHandle>()
vi.spyOn(ctx.sessionPersistence, 'open').mockReturnValue(opening.promise)
const closed = vi.fn(async () => {})
@@ -402,7 +402,7 @@ describe('config-driven session id', () => {
await ctx1.plugin(ToolRuntime)
await ctx1.plugin(NativeToolExecutor)
await ctx1.plugin(AgentRegistry)
await ctx1.plugin(JsonlSessionPersistence, { root })
await ctx1.plugin(JsonlSessionPersistence, { root, storage })
await ctx1.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('cfg'), provider: 'mock', model: 'mock' }] })
ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg')]))
await expect.poll(() => ctx1.agents.list().length).toBe(1)
@@ -426,7 +426,7 @@ describe('config-driven session id', () => {
await ctx2.plugin(ToolRuntime)
await ctx2.plugin(NativeToolExecutor)
await ctx2.plugin(AgentRegistry)
await ctx2.plugin(JsonlSessionPersistence, { root })
await ctx2.plugin(JsonlSessionPersistence, { root, storage })
await ctx2.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('cfg'), provider: 'mock', model: 'mock' }] })
ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg2')]))
await expect.poll(() => ctx2.agents.list().length).toBe(1)
@@ -453,7 +453,7 @@ describe('config-driven session id', () => {
await ctx1.plugin(ToolRuntime)
await ctx1.plugin(NativeToolExecutor)
await ctx1.plugin(AgentRegistry)
await ctx1.plugin(JsonlSessionPersistence, { root })
await ctx1.plugin(JsonlSessionPersistence, { root, storage })
await ctx1.plugin(AgentLoop, { agents: [] })
ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('sticky-1'), agentOptions: { provider: 'mock', model: 'mock' } })
@@ -473,7 +473,7 @@ describe('config-driven session id', () => {
await ctx2.plugin(NativeToolExecutor)
await ctx2.plugin(AgentRegistry)
await ctx2.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('main'), provider: 'mock', model: 'mock', resumeSessionId: brandString<SessionId>('sticky-1') }] })
await ctx2.plugin(JsonlSessionPersistence, { root })
await ctx2.plugin(JsonlSessionPersistence, { root, storage })
ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('second')]))
// The deferred resume runs after the backend is available.
@@ -496,7 +496,7 @@ describe('config-driven session id', () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-route-'))
dirs.push(root)
const ctx1 = await makeCoreContext()
await ctx1.plugin(JsonlSessionPersistence, { root })
await ctx1.plugin(JsonlSessionPersistence, { root, storage })
await ctx1.plugin(AgentLoop, { agents: [] })
ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('sticky-route'), agentOptions: { provider: 'mock', model: 'mock' } })
@@ -507,7 +507,7 @@ describe('config-driven session id', () => {
await ctx1.fiber.dispose()
const ctx2 = await makeCoreContext()
await ctx2.plugin(JsonlSessionPersistence, { root })
await ctx2.plugin(JsonlSessionPersistence, { root, storage })
await ctx2.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('main'), ...route, resumeSessionId: brandString<SessionId>('sticky-route') }] })
await expect.poll(() => ctx2.agents.get(brandString<SessionId>('sticky-route')), { timeout: 5_000 }).toBeDefined()
const resumed = ctx2.agents.get(brandString<SessionId>('sticky-route'))!
@@ -530,7 +530,7 @@ describe('config-driven session id', () => {
await ctx.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('main'), provider: 'mock', model: 'mock', resumeSessionId: brandString<SessionId>('does-not-exist') }] })
const warn = vi.spyOn((ctx.agentLoop as unknown as { ctx: { logger: { warn: (...a: unknown[]) => void } } }).ctx.logger, 'warn')
.mockImplementation(() => undefined)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
// The deferred resume fails (no such session on disk). It must be contained:
@@ -544,12 +544,12 @@ describe('config-driven session id', () => {
})
})
describe('startup reporting after factory teardown', () => {
describe.each(['jsonl', 'sqlite'] as const)('startup reporting after factory teardown (%s)', (storage) => {
it('suppresses the configured-restore failure report once the loop is disposed', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-disposed-report-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
// A restore open that hangs until after the loop is gone: the eventual
@@ -31,7 +31,7 @@ afterEach(async () => {
const input = (text: string) => createUserMessage({ content: [{ type: 'text' as const, text }], source: { kind: 'user' as const } })
async function harness() {
async function harness(storage: 'jsonl' | 'sqlite') {
const ctx = new Context()
const root = await mkdtemp(join(tmpdir(), 'dsh-input-atomicity-'))
const fixture: { ctx: Context; agent?: Agent; root: string } = { ctx, root }
@@ -43,7 +43,7 @@ async function harness() {
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root, storage, compression: 'none' })
await ctx.plugin(CheckpointPolicy)
await ctx.plugin(AgentLoop, { agents: [] })
const adapter = new MockAdapter(Array.from({ length: 5 }, () => textResponse('ok')))
@@ -53,8 +53,8 @@ async function harness() {
return { ctx, root, adapter, handle, agent: handle.agent }
}
it('cancellation still aborts the running request when queue clearing fails', async () => {
const { ctx, agent } = await harness()
it.each(['jsonl', 'sqlite'] as const)('%s: cancellation still aborts the running request when queue clearing fails', async (storage) => {
const { ctx, agent } = await harness(storage)
const entered = Promise.withResolvers<AbortSignal>()
const release = Promise.withResolvers<undefined>()
const hold = ctx.on('agent/pre-step', async ({ signal }, next) => { entered.resolve(signal); await release.promise; return next() })
@@ -83,8 +83,8 @@ it('cancellation still aborts the running request when queue clearing fails', as
}
})
it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => {
const { ctx, agent, handle } = await harness()
it.each(['jsonl', 'sqlite'] as const)('%s: waits for admitted maintenance after a queue-clear failure before releasing its Session', async (storage) => {
const { ctx, agent, handle } = await harness(storage)
const release = Promise.withResolvers<undefined>()
const waiting = Promise.withResolvers<'waiting'>()
const disposed = Promise.withResolvers<'disposed'>()
@@ -123,8 +123,8 @@ it('waits for admitted maintenance after a queue-clear failure before releasing
}
})
it('reports a quiescence failure while releasing the Agent and Session', async () => {
const { ctx, agent, handle } = await harness()
it.each(['jsonl', 'sqlite'] as const)('%s: reports a quiescence failure while releasing the Agent and Session', async (storage) => {
const { ctx, agent, handle } = await harness(storage)
const failure = new Error('injected quiescence failure')
const idle = vi.spyOn(agent, 'whenIdle').mockRejectedValueOnce(failure)
try {
@@ -136,8 +136,8 @@ it('reports a quiescence failure while releasing the Agent and Session', async (
}
})
it('keeps creation resources alive until an interrupted creation listener finishes', async () => {
const { ctx } = await harness()
it.each(['jsonl', 'sqlite'] as const)('%s: keeps creation resources alive until an interrupted creation listener finishes', async (storage) => {
const { ctx } = await harness(storage)
const entered = Promise.withResolvers<Agent>()
const release = Promise.withResolvers<undefined>()
const signal = new AbortController()
@@ -80,7 +80,9 @@ it.each([0, 1, 2])('retains Agent resources until all work exits with %i failed
expect(ctx.sessions.get(agent.session.id)).toBeUndefined()
})
it.each(['loop', 'root'] as const)('unloads %s while a background child is stopping', async (owner) => {
it.each((['jsonl', 'sqlite'] as const).flatMap(storage =>
(['loop', 'root'] as const).map(owner => ({ storage, owner })),
))('unloads $owner while a background child is stopping ($storage)', async ({ storage, owner }) => {
const ctx = new Context()
const release = Promise.withResolvers<undefined>()
const root = mkdtempSync(join(tmpdir(), 'dsh-resource-lifecycle-'))
@@ -90,7 +92,7 @@ it.each(['loop', 'root'] as const)('unloads %s while a background child is stopp
rmSync(root, { recursive: true, force: true })
})
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
const loop = await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(LocalJobRegistry)
@@ -143,7 +145,7 @@ it.each(['loop', 'root'] as const)('unloads %s while a background child is stopp
if (owner === 'loop') {
const verify = new Context()
onTestFinished(async () => { await verify.fiber.dispose() })
await verify.plugin(JsonlSessionPersistence, { root })
await verify.plugin(JsonlSessionPersistence, { root, storage })
const reader = await verify.sessionPersistence.open(child.id, 'read')
expect((await reader.read()).events).toEqual(events)
await reader.close()
+123 -123
View File
@@ -31,13 +31,13 @@ declare module '@deepseek-ai/dsh-llm' {
const dirs: string[] = []
afterEach(async () => { for (const d of dirs.splice(0)) await rm(d, { recursive: true, force: true }) })
async function persistentHarness(adapter: MockAdapter): Promise<{ ctx: Context; root: string }> {
async function persistentHarness(storage: 'jsonl' | 'sqlite', adapter: MockAdapter): Promise<{ ctx: Context; root: string }> {
const root = await mkdtemp(join(tmpdir(), 'dsh-resume-'))
dirs.push(root)
return { ctx: await mountPersistentHarness(root, adapter), root }
return { ctx: await mountPersistentHarness(storage, root, adapter), root }
}
async function mountPersistentHarness(root: string, adapter: MockAdapter, compression?: 'none', storage: 'jsonl' | 'sqlite' = 'jsonl'): Promise<Context> {
async function mountPersistentHarness(storage: 'jsonl' | 'sqlite', root: string, adapter: MockAdapter, compression?: 'none'): Promise<Context> {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(SessionStore)
@@ -81,8 +81,8 @@ async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise<rea
}
}
async function persistSession(sessionId: SessionId): Promise<string> {
const { ctx, root } = await persistentHarness(new MockAdapter([]))
async function persistSession(storage: 'jsonl' | 'sqlite', sessionId: SessionId): Promise<string> {
const { ctx, root } = await persistentHarness(storage, new MockAdapter([]))
// Persistence deliberately has no artifact for a truly empty session. A
// balanced completed turn is the smallest resumable log and avoids running
// the model merely to construct this lifecycle fixture.
@@ -126,10 +126,10 @@ function throwUnknown(value: unknown): never {
}
describe('the session-persistence Agent Note: AgentLoop factory create/resume', () => {
it('normalizes a non-Error resume publication failure for rollback and releases the write handle', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: normalizes a non-Error resume publication failure for rollback and releases the write handle', async (storage) => {
const sessionId = brandString<SessionId>('unknown-resume-failure-s')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const failure = { source: 'resume' }
ctx.on('session/created', () => throwUnknown(failure))
@@ -145,18 +145,18 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('createAgent uses the caller-supplied sessionId (not ${id}-session)', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: createAgent uses the caller-supplied sessionId (not ${id}-session)', async (storage) => {
const adapter = new MockAdapter([textResponse('hi')])
const { ctx } = await persistentHarness(adapter)
const { ctx } = await persistentHarness(storage, adapter)
const { agent } = await ctx.agents.create({ sessionId: brandString<SessionId>('custom-session'), meta: { cwd: '/w' } })
expect(agent.session.id).toBe('custom-session')
expect(agent.session.header.cwd).toBe('/w')
await ctx.fiber.dispose()
})
it('createAgent rejects a duplicate identity without orphaning a session', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: createAgent rejects a duplicate identity without orphaning a session', async (storage) => {
const adapter = new MockAdapter([textResponse('hi')])
const { ctx } = await persistentHarness(adapter)
const { ctx } = await persistentHarness(storage, adapter)
const sessionId = brandString<SessionId>('sess-a')
await ctx.agents.create({ sessionId })
await expect(ctx.agents.create({ sessionId })).rejects.toThrow(/already exists/)
@@ -164,12 +164,12 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a created agent stores its seed and live turn durably through its handle', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a created agent stores its seed and live turn durably through its handle', async (storage) => {
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
{ type: 'turn/end', seq: SessionSeq(1), time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
]
const { ctx } = await persistentHarness(new MockAdapter([textResponse('stored')]))
const { ctx } = await persistentHarness(storage, new MockAdapter([textResponse('stored')]))
const sessionId = brandString<SessionId>('durable-create')
const handle = await ctx.agents.create({
sessionId,
@@ -194,8 +194,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a rejecting final writer close releases the registries, then rejects disposal', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('hi')]))
it.each(['jsonl', 'sqlite'] as const)('%s: a rejecting final writer close releases the registries, then rejects disposal', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([textResponse('hi')]))
const sessionId = brandString<SessionId>('drain-close-fails')
const create = vi.spyOn(ctx.sessionPersistence, 'create')
const handle = await ctx.agents.create({ sessionId })
@@ -222,8 +222,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('combines a machine-teardown failure with a close failure into one rejection', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('hi')]))
it.each(['jsonl', 'sqlite'] as const)('%s: combines a machine-teardown failure with a close failure into one rejection', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([textResponse('hi')]))
const sessionId = brandString<SessionId>('drain-both-fail')
const create = vi.spyOn(ctx.sessionPersistence, 'create')
const handle = await ctx.agents.create({ sessionId })
@@ -242,8 +242,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('agent dispose releases write ownership of its stored session', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('hi')]))
it.each(['jsonl', 'sqlite'] as const)('%s: agent dispose releases write ownership of its stored session', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([textResponse('hi')]))
const sessionId = brandString<SessionId>('ownership-release')
const handle = await ctx.agents.create({ sessionId })
@@ -260,8 +260,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a stored-session create failure rolls the fresh identity back', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: a stored-session create failure rolls the fresh identity back', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('create-backend-fail')
vi.spyOn(ctx.sessionPersistence, 'create').mockRejectedValueOnce(new Error('backend create failed'))
@@ -275,8 +275,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a seed append failure closes the fresh write handle and rethrows', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: a seed append failure closes the fresh write handle and rethrows', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('seed-append-fail')
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
@@ -302,8 +302,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
})
it('stores setup events exactly once after Session creation completes', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: stores setup events exactly once after Session creation completes', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('setup-event-feed')
const pending = createUserMessage({ content: [{ type: 'text', text: 'setup context' }], source: { kind: 'user' } })
const seen: SessionEvent[] = []
@@ -331,8 +331,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a setup failure retains stored constructor history and releases the write handle', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: a setup failure retains stored constructor history and releases the write handle', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('setup-fail-history')
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
@@ -355,8 +355,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('rollback swallows a rejecting handle close after initialization validation fails (create and createAgent)', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: rollback swallows a rejecting handle close after initialization validation fails (create and createAgent)', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const originalCreate = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
const closeSpies: Array<{ mockRestore: () => void }> = []
ctx.sessionPersistence.create = async (header, options) => {
@@ -379,8 +379,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a reentrant abort during scope construction waits for a rejecting handle close', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: a reentrant abort during scope construction waits for a rejecting handle close', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('scope-abort-close-reject')
const originalCreate = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
const spies: Array<{ mockRestore: () => void }> = []
@@ -417,8 +417,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
}
})
it('config create rollback swallows a rejecting close after a publish failure', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: config create rollback swallows a rejecting close after a publish failure', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('config-publish-close-reject')
const originalCreate = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
const spies: Array<{ mockRestore: () => void }> = []
@@ -446,8 +446,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a seed append failure swallows a rejecting handle close', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: a seed append failure swallows a rejecting handle close', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const sessionId = brandString<SessionId>('seed-append-close-reject')
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
@@ -470,10 +470,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a resume read failure swallows a rejecting handle close during rollback', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a resume read failure swallows a rejecting handle close during rollback', async (storage) => {
const sessionId = brandString<SessionId>('resume-read-close-reject')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const originalOpen = ctx.sessionPersistence.open.bind(ctx.sessionPersistence)
const spies: Array<{ mockRestore: () => void }> = []
ctx.sessionPersistence.open = async (id, access, options) => {
@@ -492,8 +492,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('resume cannot crash-repair a turn owned by a live agent', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('unused')]))
it.each(['jsonl', 'sqlite'] as const)('%s: resume cannot crash-repair a turn owned by a live agent', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([textResponse('unused')]))
const sessionId = brandString<SessionId>('live-resume-race')
const first = (await ctx.agents.create({ sessionId })).agent
first.session.append('turn/start', { turn: 1 })
@@ -513,10 +513,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('resume appends interrupted-turn closers durably through the handle', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume appends interrupted-turn closers durably through the handle', async (storage) => {
// Lifecycle 1: store an interrupted log — an open turn with no turn/end.
const sessionId = brandString<SessionId>('interrupted-resume')
const { ctx: ctx1, root } = await persistentHarness(new MockAdapter([]))
const { ctx: ctx1, root } = await persistentHarness(storage, new MockAdapter([]))
await seedStoredSession(ctx1, sessionId, [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
])
@@ -526,7 +526,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx1.fiber.dispose()
// Lifecycle 2: resume repairs the tail and stores the repair durably.
const ctx2 = await mountPersistentHarness(root, new MockAdapter([]))
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([]))
const handle = await ctx2.agents.resume({ resumeSessionId: sessionId })
expect(handle.agent.session.snapshotEvents().map(event => event.type))
.toEqual(['turn/start', 'turn/end', 'session/end-seed'])
@@ -538,9 +538,9 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx2.fiber.dispose()
})
it('resume closes an interrupted tool call durably: tool/result, step/end, turn/end', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume closes an interrupted tool call durably: tool/result, step/end, turn/end', async (storage) => {
const sessionId = brandString<SessionId>('interrupted-tool-resume')
const { ctx: ctx1, root } = await persistentHarness(new MockAdapter([]))
const { ctx: ctx1, root } = await persistentHarness(storage, new MockAdapter([]))
await seedStoredSession(ctx1, sessionId, [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
{ type: 'step/start', seq: SessionSeq(1), time: 1, data: { turn: 1, step: 1 } },
@@ -557,7 +557,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
] as SessionEvent[])
await ctx1.fiber.dispose()
const ctx2 = await mountPersistentHarness(root, new MockAdapter([]))
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([]))
const handle = await ctx2.agents.resume({ resumeSessionId: sessionId })
await handle.dispose()
@@ -581,7 +581,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
const sessionId = brandString<SessionId>('torn-tail-resume')
const root = await mkdtemp(join(tmpdir(), 'dsh-resume-torn-'))
dirs.push(root)
const ctx1 = await mountPersistentHarness(root, new MockAdapter([]), 'none', 'sqlite')
const ctx1 = await mountPersistentHarness('sqlite', root, new MockAdapter([]), 'none')
const header = ctx1.sessions.prepare(sessionId).header
await ctx1.fiber.dispose()
@@ -593,7 +593,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
].join('\n')
await writeFile(path, bytes)
const ctx2 = await mountPersistentHarness(root, new MockAdapter([]), 'none', 'sqlite')
const ctx2 = await mountPersistentHarness('sqlite', root, new MockAdapter([]), 'none')
const handle = await ctx2.agents.resume({ resumeSessionId: sessionId })
expect(handle.agent.session.snapshotEvents().map(event => event.type))
.toEqual(['turn/start', 'turn/end', 'session/end-seed'])
@@ -606,19 +606,19 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx2.fiber.dispose()
})
it('createAgent works without meta (no cwd)', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: createAgent works without meta (no cwd)', async (storage) => {
const adapter = new MockAdapter([textResponse('hi')])
const { ctx } = await persistentHarness(adapter)
const { ctx } = await persistentHarness(storage, adapter)
const { agent } = await ctx.agents.create({ sessionId: brandString<SessionId>('nometa-session') })
expect(agent.session.id).toBe('nometa-session')
expect(agent.session.header.cwd).toBeUndefined()
await ctx.fiber.dispose()
})
it('resume of a session with no cwd carries an undefined cwd header', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume of a session with no cwd carries an undefined cwd header', async (storage) => {
// Lifecycle 1: create a no-cwd session and run a turn.
const adapter1 = new MockAdapter([textResponse('a')])
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const { ctx: ctx1, root } = await persistentHarness(storage, adapter1)
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('nocwd-sess') })
h1.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
await waitForIdle(ctx1, h1.agent)
@@ -627,16 +627,16 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx1.fiber.dispose()
// Lifecycle 2: resume it; the header cwd stays undefined (no-cwd branch).
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('b')]))
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('b')]))
const a2 = (await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('nocwd-sess') })).agent
expect(a2.session.header.cwd).toBeUndefined()
await ctx2.fiber.dispose()
})
it('agent/created fires "startup" for createAgent and "resume" for resume()', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: agent/created fires "startup" for createAgent and "resume" for resume()', async (storage) => {
// Lifecycle 1: a fresh createAgent announces creation with source 'startup'.
const adapter1 = new MockAdapter([textResponse('a')])
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const { ctx: ctx1, root } = await persistentHarness(storage, adapter1)
const sources1: string[] = []
ctx1.on('agent/created', ({ source }) => void sources1.push(source))
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('start-sess') })
@@ -647,7 +647,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx1.fiber.dispose()
// Lifecycle 2: resuming the persisted session announces creation 'resume'.
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('b')]))
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('b')]))
const sources2: string[] = []
ctx2.on('agent/created', ({ source }) => void sources2.push(source))
await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('start-sess') })
@@ -655,10 +655,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx2.fiber.dispose()
})
it('resume announces the Session before setup and the composed Agent afterward', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume announces the Session before setup and the composed Agent afterward', async (storage) => {
const sessionId = brandString<SessionId>('resume-setup-success')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const order: string[] = []
@@ -715,13 +715,13 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('a resumed session stores its repair suffix durably before publication', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a resumed session stores its repair suffix durably before publication', async (storage) => {
// The stored fixture (two events, no end-seed) gains the end-seed marker
// through the resume handle: after one resume lifecycle the STORED log
// carries it, so the next resume reads it back without re-marking.
const sessionId = brandString<SessionId>('resume-suffix-durable')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const first = await ctx.agents.resume({ resumeSessionId: sessionId })
await first.dispose()
@@ -737,10 +737,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('successful resume disposal retires its caller-owned transaction effects', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: successful resume disposal retires its caller-owned transaction effects', async (storage) => {
const sessionId = brandString<SessionId>('resume-retired-effects-s')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const handle = await ctx.agents.resume({
resumeSessionId: sessionId,
agentOptions: { provider: 'mock', model: 'mock' },
@@ -753,9 +753,9 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['reject', 'abort'] as const)('preserves restored inbox messages when setup fails: %s', async (failure) => {
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['reject', 'abort'] as const).map(value => [storage, value] as const)))('%s: preserves restored inbox messages when setup fails: %s', async (storage, failure) => {
const sessionId = brandString<SessionId>('resume-inbox-' + failure)
const { ctx } = await persistentHarness(new MockAdapter([]))
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const pending = createUserMessage({ content: [{ type: 'text', text: 'queued before restart' }], source: { kind: 'user' } })
await seedStoredSession(ctx, sessionId, [{
type: 'agent/inbox/spliced', seq: SessionSeq(0), time: 1,
@@ -783,10 +783,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('resume setup rejection disposes the announced Session and releases the identity', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume setup rejection disposes the announced Session and releases the identity', async (storage) => {
const sessionId = brandString<SessionId>('resume-setup-reject')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('session/disposed', () => void published.push('session/disposed'))
@@ -812,10 +812,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('resume setup commit rejection disposes the announced Session and releases the identity', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume setup commit rejection disposes the announced Session and releases the identity', async (storage) => {
const sessionId = brandString<SessionId>('resume-setup-commit-reject')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const published: string[] = []
ctx.on('session/created', () => void published.push('session/created'))
ctx.on('session/disposed', () => void published.push('session/disposed'))
@@ -840,10 +840,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('owner unload aborts resume setup and cannot publish the Agent after the callback settles', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: owner unload aborts resume setup and cannot publish the Agent after the callback settles', async (storage) => {
const sessionId = brandString<SessionId>('resume-setup-owner-unload')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const published: string[] = []
@@ -876,10 +876,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('owner unload aborts a never-settling persistence open, releases the identity, and blocks late publication', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: owner unload aborts a never-settling persistence open, releases the identity, and blocks late publication', async (storage) => {
const sessionId = brandString<SessionId>('resume-load-owner-unload')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const lateOpen = Promise.withResolvers<SessionHandle>()
const openStarted = Promise.withResolvers<undefined>()
const originalOpen = ctx.sessionPersistence.open.bind(ctx.sessionPersistence)
@@ -931,9 +931,9 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('AgentLoop unload aborts a never-settling persistence open and awaits wrapper settlement', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: AgentLoop unload aborts a never-settling persistence open and awaits wrapper settlement', async (storage) => {
const sessionId = brandString<SessionId>('resume-load-factory-unload')
const root = await persistSession(sessionId)
const root = await persistSession(storage, sessionId)
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(SessionStore)
@@ -943,7 +943,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('next')]))
const lateOpen = Promise.withResolvers<SessionHandle>()
@@ -974,7 +974,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it('resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async (storage) => {
// Lifecycle 1: persist a FORKED session (carries parentSession + seedLength
// in its header) through createAgent with a complete-turn seed — the
// factory stores the header and seed through its write handle.
@@ -982,7 +982,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
{ type: 'turn/end', seq: SessionSeq(1), time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
]
const { ctx: ctx1, root } = await persistentHarness(new MockAdapter([]))
const { ctx: ctx1, root } = await persistentHarness(storage, new MockAdapter([]))
const forked = await ctx1.agents.create({
sessionId: brandString<SessionId>('forked-sess'),
seed,
@@ -997,7 +997,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
// branches). seedLength must come from the PERSISTED header, not from the
// resume seed length (which is the whole stored log, not the original
// boundary).
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('b')]))
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('b')]))
const a2 = (await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('forked-sess') })).agent
expect(a2.session.header.parentSession).toBe('parent-sess')
expect(a2.session.header.cwd).toBe('/w')
@@ -1015,7 +1015,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
// two-process e2e.
it.skipIf(process.platform === 'win32')('a pending idle inject() survives persist + resume without a synthetic turn', async () => {
const adapter1 = new MockAdapter([textResponse('answer')])
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const { ctx: ctx1, root } = await persistentHarness('jsonl', adapter1)
const a1 = (await ctx1.agents.create({ sessionId: brandString<SessionId>('inject-sess'), meta: { cwd: '/w' }, agentOptions: { provider: 'mock', model: 'mock' } })).agent
a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
await waitForIdle(ctx1, a1)
@@ -1031,7 +1031,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
// Lifecycle 2: resume; the injected context is still pending and becomes
// model-visible when the next turn admits it.
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const ctx2 = await mountPersistentHarness('jsonl', root, new MockAdapter([textResponse('next')]))
const stored = await readStoredEvents(ctx2, brandString<SessionId>('inject-sess'))
expect(stored.some(event => event.type === 'agent/inbox/spliced')).toBe(true)
expect(JSON.stringify(stored)).toContain('background job 42 finished')
@@ -1045,7 +1045,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx1.fiber.dispose()
})
it.each(['resume', 'fork'] as const)('%s continues persisted history after a live scheduler failure', async (mode) => {
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['resume', 'fork'] as const).map(value => [storage, value] as const)))('%s: %s continues persisted history after a live scheduler failure', async (storage, mode) => {
const firstAdapter = new MockAdapter([[
{ type: 'block-start', index: 0, blockType: 'tool-call' },
{ type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString<ToolCallId>('started'), name: 'probe', arguments: '{}' } },
@@ -1053,7 +1053,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
{ type: 'block-end', index: 1, block: { type: 'tool-call', id: brandString<ToolCallId>('pending'), name: 'probe', arguments: '{}' } },
{ type: 'finish', reason: { kind: 'tool-calls' } },
]])
const { ctx: first, root } = await persistentHarness(firstAdapter)
const { ctx: first, root } = await persistentHarness(storage, firstAdapter)
let next: Context | undefined
try {
first.tools.register(defineContentToolFixture({
@@ -1078,7 +1078,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await first.fiber.dispose()
const nextAdapter = new MockAdapter([textResponse('continued after failure')])
next = await mountPersistentHarness(root, nextAdapter)
next = await mountPersistentHarness(storage, root, nextAdapter)
const stored = await readStoredEvents(next, sessionId)
expect(stored.filter(event => event.type === 'tool/result').map(event => [
event.data.message.toolCallId, event.data.error?.code,
@@ -1118,10 +1118,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
}
})
it('resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async (storage) => {
// Lifecycle 1: run one full turn, persisting it.
const adapter1 = new MockAdapter([textResponse('first answer')])
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const { ctx: ctx1, root } = await persistentHarness(storage, adapter1)
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('sess-resume'), meta: { cwd: '/w' } })
const a1 = h1.agent
a1.followup(createUserMessage({ content: [{ type: 'text', text: 'first question' }], source: { kind: 'user' } }))
@@ -1133,7 +1133,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx1.fiber.dispose()
// Lifecycle 2: a brand-new context over the SAME root; resume the session.
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('second answer')]))
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('second answer')]))
const a2 = (await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('sess-resume') })).agent
// The resumed session carries the prior history…
@@ -1175,8 +1175,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
})
describe('creation and resume cancellation edges', () => {
it('rejects create() with a pre-aborted signal, including a non-Error reason', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: rejects create() with a pre-aborted signal, including a non-Error reason', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const errorReason = new AbortController()
errorReason.abort(new Error('caller gave up'))
@@ -1200,8 +1200,8 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it('a non-Error abort reason arriving during setup is wrapped for the caller', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each(['jsonl', 'sqlite'] as const)('%s: a non-Error abort reason arriving during setup is wrapped for the caller', async (storage) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const controller = new AbortController()
const setupEntered = Promise.withResolvers<undefined>()
const setupGate = Promise.withResolvers<undefined>()
@@ -1224,8 +1224,8 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it.each(['setup', 'commit'] as const)('rejects when %s synchronously aborts its caller signal', async (phase) => {
const { ctx } = await persistentHarness(new MockAdapter([]))
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['setup', 'commit'] as const).map(value => [storage, value] as const)))('%s: rejects when %s synchronously aborts its caller signal', async (storage, phase) => {
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const controller = new AbortController()
const created = vi.fn()
@@ -1253,10 +1253,10 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it('resume with a pre-aborted caller signal rejects out of the load race', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: resume with a pre-aborted caller signal rejects out of the load race', async (storage) => {
const sessionId = brandString<SessionId>('resume-pre-aborted')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const controller = new AbortController()
controller.abort(new Error('resume abandoned'))
@@ -1278,19 +1278,19 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it('an abort landing between crash repair and publication refuses resume, normalized', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: an abort landing between crash repair and publication refuses resume, normalized', async (storage) => {
// Cover the publication-time abort backstop: the signal fires AFTER the
// raced open settled (during the closer append), so only the final
// pre-publication check can refuse.
const run = async (suffix: string, reason: unknown): Promise<unknown> => {
const sessionId = brandString<SessionId>(`late-abort-${suffix}`)
const { ctx: seedCtx, root } = await persistentHarness(new MockAdapter([]))
const { ctx: seedCtx, root } = await persistentHarness(storage, new MockAdapter([]))
await seedStoredSession(seedCtx, sessionId, [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
])
await seedCtx.fiber.dispose()
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const controller = new AbortController()
const originalOpen = ctx.sessionPersistence.open.bind(ctx.sessionPersistence)
ctx.sessionPersistence.open = async (id, access, options) => {
@@ -1318,9 +1318,9 @@ describe('creation and resume cancellation edges', () => {
expect(await run('string', 'late abort string')).toMatchObject({ message: expect.stringMatching(/creation aborted/) as unknown })
})
it('an aborted create closes the write handle its abandoned backend create later resolves', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: an aborted create closes the write handle its abandoned backend create later resolves', async (storage) => {
const sessionId = brandString<SessionId>('create-abandoned-handle')
const { ctx } = await persistentHarness(new MockAdapter([]))
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const lateCreate = Promise.withResolvers<SessionHandle>()
const createStarted = Promise.withResolvers<undefined>()
ctx.sessionPersistence.create = () => {
@@ -1344,10 +1344,10 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it('closes the resume write handle when the loop becomes inactive before setup', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: closes the resume write handle when the loop becomes inactive before setup', async (storage) => {
const sessionId = brandString<SessionId>('resume-loop-inactive-after-open')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const loop = ctx.agentLoop as unknown as {
ownership: { isActive: () => boolean }
}
@@ -1369,10 +1369,10 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it('factory teardown during a hung resume open rejects promptly and closes the late handle', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: factory teardown during a hung resume open rejects promptly and closes the late handle', async (storage) => {
const sessionId = brandString<SessionId>('resume-loop-teardown')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const gate = Promise.withResolvers<SessionHandle>()
const openStarted = Promise.withResolvers<undefined>()
ctx.sessionPersistence.open = () => {
@@ -1398,10 +1398,10 @@ describe('creation and resume cancellation edges', () => {
})
describe('configured-start failure edges', () => {
it('a non-Error mid-open abort reason is wrapped for the resume caller', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a non-Error mid-open abort reason is wrapped for the resume caller', async (storage) => {
const sessionId = brandString<SessionId>('resume-string-mid-abort')
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const gate = Promise.withResolvers<never>()
gate.promise.catch(() => undefined)
const openStarted = Promise.withResolvers<undefined>()
@@ -1424,9 +1424,9 @@ describe('configured-start failure edges', () => {
await ctx.fiber.dispose()
})
it('a failing exact-id restore over an existing artifact stays loud', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a failing exact-id restore over an existing artifact stays loud', async (storage) => {
const sessionId = brandString<SessionId>('config-existing-corrupt')
const root = await persistSession(sessionId)
const root = await persistSession(storage, sessionId)
const configured = new Context()
await configured.plugin(LlmRuntime)
await configured.plugin(SessionStore)
@@ -1435,7 +1435,7 @@ describe('configured-start failure edges', () => {
await configured.plugin(ToolRuntime)
await configured.plugin(NativeToolExecutor)
await configured.plugin(AgentRegistry)
await configured.plugin(JsonlSessionPersistence, { root })
await configured.plugin(JsonlSessionPersistence, { storage, root })
configured.llm.registerAdapter(['mock'], new MockAdapter([]))
// The artifact exists but its open fails with a NON-NotFound error: this is
// corruption, not first creation — the failure must be reported, and no
@@ -1459,9 +1459,9 @@ describe('configured-start failure edges', () => {
await configured.fiber.dispose()
})
it('suppresses a configured-resume failure that lands after teardown', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: suppresses a configured-resume failure that lands after teardown', async (storage) => {
const sessionId = brandString<SessionId>('config-late-resume-failure')
const root = await persistSession(sessionId)
const root = await persistSession(storage, sessionId)
const configured = new Context()
await configured.plugin(LlmRuntime)
await configured.plugin(SessionStore)
@@ -1470,7 +1470,7 @@ describe('configured-start failure edges', () => {
await configured.plugin(ToolRuntime)
await configured.plugin(NativeToolExecutor)
await configured.plugin(AgentRegistry)
await configured.plugin(JsonlSessionPersistence, { root })
await configured.plugin(JsonlSessionPersistence, { storage, root })
configured.llm.registerAdapter(['mock'], new MockAdapter([]))
const gate = Promise.withResolvers<never>()
gate.promise.catch(() => undefined)
@@ -28,11 +28,11 @@ afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
})
async function core(persistenceRoot?: string) {
async function mountCore(storage: 'jsonl' | 'sqlite', persistenceRoot?: string) {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
if (persistenceRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
if (persistenceRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, storage, compression: 'none' })
await ctx.plugin(AgentLoop, { agents: [] })
return ctx
}
@@ -74,7 +74,8 @@ function dueWorkProducer(sessionId: SessionId, plugin: string) {
return { producer, delivery: delivery.promise }
}
describe('serial creation listener integrations', () => {
describe.each(['jsonl', 'sqlite'] as const)('serial creation listener integrations (%s)', (storage) => {
const core = (persistenceRoot?: string) => mountCore(storage, persistenceRoot)
it('rolls back creation when file-reference prompt installation fails', async () => {
const ctx = await core()
const errors: string[] = []
@@ -29,7 +29,7 @@ function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
})
}
async function mount(order: 'backend-first' | 'loop-first'): Promise<{ ctx: Context; root: string }> {
async function mount(order: 'backend-first' | 'loop-first', storage: 'jsonl' | 'sqlite'): Promise<{ ctx: Context; root: string }> {
const root = await mkdtemp(join(tmpdir(), 'dsh-shutdown-drain-'))
dirs.push(root)
const ctx = new Context()
@@ -41,19 +41,21 @@ async function mount(order: 'backend-first' | 'loop-first'): Promise<{ ctx: Cont
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
if (order === 'backend-first') {
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(AgentLoop, { agents: [] })
} else {
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
}
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('done')]))
return { ctx, root }
}
describe.each(['backend-first', 'loop-first'] as const)('root shutdown drain (%s)', (order) => {
describe.each((['jsonl', 'sqlite'] as const).flatMap(storage =>
(['backend-first', 'loop-first'] as const).map(order => ({ storage, order })),
))('root shutdown drain ($storage, $order)', ({ storage, order }) => {
it('persists buffered turn events without an explicit flush before dispose', async () => {
const { ctx, root } = await mount(order)
const { ctx, root } = await mount(order, storage)
const sessionId = brandString<SessionId>('shutdown-drain')
const handle = await ctx.agents.create({ sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
@@ -62,7 +64,7 @@ describe.each(['backend-first', 'loop-first'] as const)('root shutdown drain (%s
await ctx.fiber.dispose()
const verify = new Context()
await verify.plugin(JsonlSessionPersistence, { root })
await verify.plugin(JsonlSessionPersistence, { root, storage })
const reader = await verify.sessionPersistence.open(sessionId, 'read')
const { events } = await reader.read()
await reader.close()
@@ -13,7 +13,7 @@ import WorkingDirectory from '@deepseek-ai/dsh-working-directory'
import ClaudeCodeMods, { defineMod } from '../src/index.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
it('reports the final committed cwd when a persisted Session resumes, retaining its original project', async () => {
it.each(['jsonl', 'sqlite'] as const)('reports the final committed cwd when a persisted Session resumes, retaining its original project (%s)', async (backend) => {
const root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-mods-resume-directory-')))
const origin = join(root, 'project')
const current = join(origin, 'current')
@@ -26,7 +26,7 @@ it('reports the final committed cwd when a persisted Session resumes, retaining
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(LocalFileSystem, { cwd: origin })
await ctx.plugin(WorkingDirectory, { defaultDirectory: origin })
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'sessions'), compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'sessions'), compression: 'none', storage: backend })
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(ClaudeCodeMods)
await ctx.plugin(defineMod({
@@ -58,7 +58,7 @@ function chat(id: string, leafAt: number): ExportSessionFile {
}
/** Boot the plugin rows through the Loader with stand-ins for the Connection route registry and the attachment store. */
async function boot(saveImage: (input: SaveImageAttachment) => Promise<ImageAttachmentRef> = () => Promise.reject(new Error('unused'))) {
async function boot(backend: 'jsonl' | 'sqlite', saveImage: (input: SaveImageAttachment) => Promise<ImageAttachmentRef> = () => Promise.reject(new Error('unused'))) {
root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-deepseek-import-loader-')))
const workspacePath = join(root, 'project')
await mkdir(workspacePath)
@@ -68,6 +68,7 @@ async function boot(saveImage: (input: SaveImageAttachment) => Promise<ImageAtta
"- name: '@deepseek-ai/dsh-session-persistence-jsonl'",
' config:',
` root: ${JSON.stringify(join(root, 'sessions'))}`,
` storage: ${backend}`,
"- name: '@deepseek-ai/dsh-storage'",
"- name: '@deepseek-ai/dsh-storage-json'",
' config:',
@@ -142,8 +143,8 @@ async function boot(saveImage: (input: SaveImageAttachment) => Promise<ImageAtta
const lines = async (response: Response): Promise<DeepseekChatImportLine[]> =>
(await response.text()).split('\n').filter(line => line !== '').map(line => JSON.parse(line) as DeepseekChatImportLine)
it('imports an uploaded archive through the registered route into a chosen Workspace', async () => {
const { ctx, routes, workspace, workspacePath, post } = await boot()
it.each(['jsonl', 'sqlite'] as const)('imports an uploaded archive through the registered route into a chosen Workspace (%s)', async (backend) => {
const { ctx, routes, workspace, workspacePath, post } = await boot(backend)
const signal = new AbortController().signal
const as = (principal: Principal) => ctx.extend({
invocation: {
@@ -224,10 +225,10 @@ it('imports an uploaded archive through the registered route into a chosen Works
expect(routes.size).toBe(0)
})
it('cancels a running import when the plugin unloads and finishes unloading only after it stops', async () => {
it.each(['jsonl', 'sqlite'] as const)('cancels a running import when the plugin unloads and finishes unloading only after it stops (%s)', async (backend) => {
const saving = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<ImageAttachmentRef>()
const { ctx, routes, post, importer } = await boot(() => {
const { ctx, routes, post, importer } = await boot(backend, () => {
saving.resolve(undefined)
return release.promise
})
@@ -36,7 +36,7 @@ function text(content: readonly ContentBlock[]): string {
: block.type === 'tool-call' ? `call:${block.name}` : block.type).join(' | ')
}
it('continues an imported conversation with its finished history and without excluded replies', async () => {
it.each(['jsonl', 'sqlite'] as const)('continues an imported conversation with its finished history and without excluded replies (%s)', async (backend) => {
const root = await mkdtemp(join(tmpdir(), 'dsh-deepseek-import-resume-'))
cleanups.push(async () => { await rm(root, { recursive: true, force: true }) })
const conversation = {
@@ -66,7 +66,7 @@ it('continues an imported conversation with its finished history and without exc
const ctx = new Context()
cleanups.push(async () => { await ctx.fiber.dispose() })
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
await ctx.plugin(JsonlPersistence, { root: join(root, 'sessions'), compression: 'none' })
await ctx.plugin(JsonlPersistence, { root: join(root, 'sessions'), compression: 'none', storage: backend })
await mountAgentLoopTestHarness(ctx)
const adapter = new MockAdapter([textResponse('Bus 2 is faster.')])
ctx.llm.registerAdapter(['mock'], adapter)
@@ -50,13 +50,13 @@ function hooks(d: string, h: unknown): string {
writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
}
type HarnessOpts = { pluginRoot?: string; projectDir?: string; stderrSummaryMaxChars?: number; sessionRoot?: string }
type HarnessOpts = { pluginRoot?: string; projectDir?: string; stderrSummaryMaxChars?: number; session?: { root: string; storage: 'jsonl' | 'sqlite' } }
async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise<Context> {
const ctx = new Context()
contexts.push(ctx)
provideWorkingDirectoryFixture(ctx)
await mountAgentLoopTestDependencies(ctx)
if (opts.sessionRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: opts.sessionRoot })
if (opts.session !== undefined) await ctx.plugin(JsonlSessionPersistence, opts.session)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(LocalSubprocessRuntime)
await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
@@ -102,12 +102,12 @@ export type CoverageGroup = 'config' | 'stop' | 'context' | 'edge-paths'
/** Register independently schedulable slices of the hooks-claude-code coverage matrix. */
export function defineCoverageCases(group: CoverageGroup): void {
if (group === 'config') describe('hooks-claude-code coverage — config option arms + substitution + skip warning', () => {
it('degrades transcript_path to the empty string even with persistence mounted', async () => {
it.each(['jsonl', 'sqlite'] as const)('degrades transcript_path to the empty string even with persistence mounted (%s)', async (backend) => {
const d = dir()
const cap = join(d, 'payload')
const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'capture.sh', `#!/usr/bin/env bash\ncat > "${cap}"\n`) }] }] })
const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
const ctx = await harness(path, adapter, { sessionRoot: dir() })
const ctx = await harness(path, adapter, { session: { root: dir(), storage: backend } })
ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
const agent = await ctx.agentLoop.create(brandString<SessionId>('transcript'), { provider: 'mock', model: 'mock' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
@@ -40,13 +40,13 @@ function hooks(d: string, h: unknown): string {
writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
}
type HarnessOpts = { stderrSummaryMaxChars?: number; sessionRoot?: string }
type HarnessOpts = { stderrSummaryMaxChars?: number; session?: { root: string; storage: 'jsonl' | 'sqlite' } }
async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise<Context> {
const ctx = new Context()
contexts.push(ctx)
provideWorkingDirectoryFixture(ctx)
await mountAgentLoopTestDependencies(ctx)
if (opts.sessionRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: opts.sessionRoot })
if (opts.session !== undefined) await ctx.plugin(JsonlSessionPersistence, opts.session)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(LocalSubprocessRuntime)
await ctx.plugin(LocalBashExecutor, { timeoutMs: 10_000 })
@@ -74,12 +74,12 @@ export type CoverageGroup = 'prompt' | 'post-tool' | 'result-shape' | 'edge-path
export function defineCoverageCases(groups: CoverageGroup | readonly CoverageGroup[]): void {
const selected = new Set(typeof groups === 'string' ? [groups] : groups)
if (selected.has('prompt')) describe('hooks-codex coverage — prompt decision mapping', () => {
it('degrades transcript_path to null even with persistence mounted', async () => {
it.each(['jsonl', 'sqlite'] as const)('degrades transcript_path to null even with persistence mounted (%s)', async (backend) => {
const d = dir()
const cap = join(d, 'payload')
const path = hooks(d, { PreToolUse: [{ hooks: [{ type: 'command', command: sh(d, 'capture.sh', `#!/usr/bin/env bash\ncat > "${cap}"\n`) }] }] })
const adapter = new MockAdapter([toolCallResponse('c1', 'echo', {}), textResponse('done')])
const ctx = await harness(path, adapter, { sessionRoot: dir() })
const ctx = await harness(path, adapter, { session: { root: dir(), storage: backend } })
ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
const agent = await ctx.agentLoop.create(brandString<SessionId>('transcript'), { provider: 'mock', model: 'mock' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
@@ -190,10 +190,10 @@ describe('share-bound receiving Session admission', () => {
},
)
it('rejects a deleted share from recovered durable Inbox without process-local share history', async () => {
it.each(['jsonl', 'sqlite'] as const)('rejects a deleted share from recovered durable Inbox without process-local share history (%s)', async (backend) => {
const fixture = await harness(true)
await mountAgentLoopTestDependencies(fixture.ctx)
await fixture.ctx.plugin(JsonlSessionPersistence, { root: join(dirname(fixture.file), 'sessions'), compression: 'none' })
await fixture.ctx.plugin(JsonlSessionPersistence, { root: join(dirname(fixture.file), 'sessions'), compression: 'none', storage: backend })
await mountAgentLoopTestHarness(fixture.ctx)
const reached = Promise.withResolvers<PreStepDecision>()
fixture.ctx.on('agent/pre-step', async (_input, next) => {
@@ -19,8 +19,8 @@ describe('fixed report limits', () => {
it('falls back to English for an unsupported app locale', () => {
expect(appLanguage('it-IT')).toBe('en')
})
it('reads the live app language and rejects an enabled standalone installation', async () => {
const f = await setup()
it.each(['jsonl', 'sqlite'] as const)('reads the live app language and rejects an enabled standalone installation (%s)', async (backend) => {
const f = await setup(backend)
try {
await f.plugin.dispose()
const standalone = { disabled: true, options: { name: 'cordis:@magolor/dsh-timeline' } }
@@ -9,8 +9,8 @@ import type { ControlTarget } from '../src/records.ts'
import type { UserEdit } from '../src/protocol.ts'
import { setup } from './fixture.ts'
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -47,9 +47,9 @@ async function fixture() {
return { ...f, view, tree, target, request, edit, call, update }
}
describe('durable asynchronous work requests', () => {
describe.each(['jsonl', 'sqlite'] as const)('durable asynchronous work requests (%s)', (backend) => {
it('keeps siblings independent and marks a request unavailable when its tree is removed', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const left = { kind: 'task', tree: f.tree, task: taskId.parse('one') } as const
const right = { ...left, task: taskId.parse('two') }
@@ -68,7 +68,7 @@ describe('durable asynchronous work requests', () => {
}
})
it('suppresses dispatch if another client removes the tree before the reply', async () => {
const f = await fixture()
const f = await fixture(backend)
const append = f.ctx.timeline.append.bind(f.ctx.timeline)
const request = f.request()
const write = vi.spyOn(f.ctx.timeline, 'append').mockImplementationOnce(async (...args) => {
@@ -86,7 +86,7 @@ describe('durable asynchronous work requests', () => {
}
})
it('serializes duplicate and overlapping requests, preserves progress, and survives plugin reload', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const request = f.request()
const results = await Promise.all([f.edit(request), f.edit(request), f.edit(f.request())])
@@ -125,7 +125,7 @@ describe('durable asynchronous work requests', () => {
})
it('confirms a pause only after every unfinished leaf in scope is paused or blocked', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const request = f.request()
await f.edit(request)
@@ -147,7 +147,7 @@ describe('durable asynchronous work requests', () => {
})
it('distinguishes an agent answer from a plan update and confirms continue only inside the selected scope', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
await f.update([
{ id: 'one', status: 'paused', note: 'Waiting for user.' },
@@ -198,7 +198,7 @@ describe('durable asynchronous work requests', () => {
})
it('keeps unknown delivery pending, permits only an explicit later retry, and cannot unsend an older request', async () => {
const f = await fixture()
const f = await fixture(backend)
vi.useFakeTimers({ toFake: ['Date'] })
try {
const first = f.request()
@@ -229,7 +229,7 @@ describe('durable asynchronous work requests', () => {
})
it('records completion and retirement without claiming the requested pause was applied', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const request = f.request('pause', { kind: 'task', tree: f.tree, task: taskId.parse('one') })
await f.edit(request)
@@ -251,7 +251,7 @@ describe('durable asynchronous work requests', () => {
})
it('rejects failed saves and model-written requests, and exposes whole-plan requests to the model', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const put = vi.spyOn(f.ctx.sessions, 'flush').mockRejectedValueOnce(new Error('Write failed'))
const request = f.request('pause', { kind: 'tree', tree: f.tree })
@@ -11,9 +11,9 @@ import { newId, taskId } from '../src/records.ts'
import { delegationContext } from '../src/delegation.ts'
import { setup } from './fixture.ts'
describe('manager-owned delegated planning', () => {
describe.each(['jsonl', 'sqlite'] as const)('manager-owned delegated planning (%s)', (backend) => {
it('limits guidance when restored worker ancestry is missing or cyclic', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const create = async (id: SessionId, parentSession?: SessionId) => (
await f.ctx.agents.create({
sessionId: id,
@@ -37,7 +37,7 @@ describe('manager-owned delegated planning', () => {
}
})
it('hides worker planning, keeps user forks independent, and shares bounded assignment references', async () => {
const f = await setup({ intervalMs: 86400000, language: 'zh-CN' })
const f = await setup(backend, { intervalMs: 86400000, language: 'zh-CN' })
let sequence = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -135,7 +135,7 @@ describe('manager-owned delegated planning', () => {
})
it('denies stale and agent-local worker writes without changing manager tasks or discussions', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
let sequence = 0
const call = (agent: typeof f.agent, name: string, args: object) =>
executeTool(f.ctx, {
@@ -223,7 +223,7 @@ describe('manager-owned delegated planning', () => {
})
it('runs worker iterations without planning reminders or separate timed reports', async () => {
const f = await setup({ reminderIterations: 2, intervalMs: 60000 })
const f = await setup(backend, { reminderIterations: 2, intervalMs: 60000 })
try {
const worker = (
await f.ctx.agents.create({
@@ -8,8 +8,8 @@ import { reportSchema, taskId } from '../src/records.ts'
import { prioritiesOf } from '../src/tasks.ts'
import { setup } from './fixture.ts'
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -40,9 +40,9 @@ async function fixture() {
return { ...f, call, base, view }
}
describe('user-owned Timeline feedback', () => {
describe.each(['jsonl', 'sqlite'] as const)('user-owned Timeline feedback (%s)', (backend) => {
it('acknowledges a saved note retry after its task retires without admitting a new note', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const request = {
action: 'annotate' as const,
@@ -73,7 +73,7 @@ describe('user-owned Timeline feedback', () => {
}
})
it('preserves user priorities and immutable note pairs across model patches, retries, and reload', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const request = {
action: 'annotate' as const,
@@ -130,7 +130,7 @@ describe('user-owned Timeline feedback', () => {
}
})
it('links report discussion to exact historical content and retains drafts after failed writes', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
const report = reportSchema.parse({
id: 'history',
@@ -187,7 +187,7 @@ describe('user-owned Timeline feedback', () => {
}
})
it('does not send an expired priority notice or fail a running turn when injection throws', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
f.start()
await f.adapter.ready.promise
@@ -210,7 +210,7 @@ describe('user-owned Timeline feedback', () => {
}
})
it('inherits priority without changing completion and coalesces only P0 notices for running work', async () => {
const f = await fixture()
const f = await fixture(backend)
try {
await f.ctx.timeline.edit({
...f.base,
@@ -122,6 +122,7 @@ export class Adapter extends LlmAdapter {
}
}
export async function setup(
backend: 'jsonl' | 'sqlite',
config: Partial<Timeline.Config> = {},
adapter = new Adapter(),
restore?: { root: string; sessionId: SessionId },
@@ -129,7 +130,7 @@ export async function setup(
const root = restore?.root ?? (await mkdtemp(join(tmpdir(), 'dsh-timeline-test-')))
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(Jsonl, { root, compression: 'none', storage: 'jsonl' })
await ctx.plugin(Jsonl, { root, compression: 'none', storage: backend })
ctx.llm.registerAdapter(['fixture'], adapter)
ctx.tools.register(
defineTool({
@@ -10,8 +10,8 @@ afterEach(async () => {
vi.useRealTimers()
for (const f of fixtures.splice(0)) await f.close()
})
async function fixture() {
const f = await setup()
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend)
fixtures.push(f)
let sequence = 0
const call = (name: string, args: object, id = `history-${sequence++}`) =>
@@ -26,9 +26,9 @@ async function fixture() {
return { f, call }
}
describe('internal task revision history', () => {
describe.each(['jsonl', 'sqlite'] as const)('internal task revision history (%s)', (backend) => {
it('records edits and derived group progress once, without recording no-ops or failed batches', async () => {
const { f, call } = await fixture()
const { f, call } = await fixture(backend)
expect(
(
await call('timeline_tasks', {
@@ -92,7 +92,7 @@ describe('internal task revision history', () => {
})
it('retains each revision and its description without repeating full task details', async () => {
const { f, call } = await fixture()
const { f, call } = await fixture(backend)
const details = 'Evidence '.repeat(400)
await call('timeline_tasks', { tasks: [{ id: 'check', title: 'Verify restart', description: 'Check recovery.', details }] })
expect((await call('timeline_tasks', { tasks: [{ id: 'check', done: [1, 2], note: 'Restart check passed.' }] })).isError).not.toBe(true)
@@ -104,7 +104,7 @@ describe('internal task revision history', () => {
])
})
it('keeps history through restart and checkpoints but excludes it from agent and report inputs', async () => {
const { f, call } = await fixture()
const { f, call } = await fixture(backend)
const archived = 'Archived text visible only in change history.'
await call('timeline_tasks', { tasks: [{ id: 'check', title: 'Verify restart', description: archived }] })
await call('timeline_tasks', {
@@ -136,7 +136,7 @@ describe('internal task revision history', () => {
vi.useRealTimers()
await f.close({ preserve: true })
fixtures.splice(fixtures.indexOf(f), 1)
const next = await setup({}, undefined, { root, sessionId })
const next = await setup(backend, {}, undefined, { root, sessionId })
fixtures.push(next)
expect(next.ctx.timeline.stateOf(next.agent.session).view.trees[0]?.tasks[0]?.history).toEqual(
tree.tasks[0]?.history,
@@ -144,7 +144,7 @@ describe('internal task revision history', () => {
})
it('does not publish a new revision when its durable write fails', async () => {
const { f, call } = await fixture()
const { f, call } = await fixture(backend)
await call('timeline_tasks', { tasks: [{ id: 'check', title: 'Verify restart' }] })
const before = f.ctx.timeline.stateOf(f.agent.session).view.trees
vi.spyOn(f.ctx.sessions, 'flush').mockRejectedValueOnce(new Error('Write failed'))
@@ -11,10 +11,10 @@ import {
} from '@deepseek-ai/dsh-agent-loop-testkit'
import * as Timeline from '@deepseek-ai/dsh-timeline'
const [mode, root, id] = process.argv.slice(2)
const [mode, root, id, storage] = process.argv.slice(2)
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(Jsonl, { root, storage: 'jsonl', compression: 'none' })
await ctx.plugin(Jsonl, { root, storage, compression: 'none' })
try {
if (mode === 'compete') {
try {
@@ -8,12 +8,12 @@ import { describe, expect, it } from 'vitest'
import { SessionId } from '@deepseek-ai/dsh-session'
import { Adapter, setup } from './fixture.ts'
describe('Timeline persistence across built Host processes', () => {
describe.each(['jsonl', 'sqlite'] as const)('Timeline persistence across built Host processes (%s)', (backend) => {
it('refuses a competing process and restores acknowledged saves after the writer is killed', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-timeline-process-'))
const sessionId = SessionId('timeline-process-recovery')
const start = (mode: string) => {
const child = spawn(process.execPath, [fileURLToPath(new URL('./host-process.mjs', import.meta.url)), mode, root, sessionId], {
const child = spawn(process.execPath, [fileURLToPath(new URL('./host-process.mjs', import.meta.url)), mode, root, sessionId, backend], {
cwd: process.cwd(),
env: {},
stdio: ['pipe', 'pipe', 'pipe'],
@@ -54,7 +54,7 @@ describe('Timeline persistence across built Host processes', () => {
}
owner.child.kill('SIGKILL')
expect((await owner.closed)[1]).toBe('SIGKILL')
const recovered = await setup({ intervalMs: 86400000 }, new Adapter(), { root, sessionId })
const recovered = await setup(backend, { intervalMs: 86400000 }, new Adapter(), { root, sessionId })
try {
const view = recovered.ctx.timeline.stateOf(recovered.agent.session).view
expect(view.trees[0]?.tasks[0]?.done).toEqual([2, 3])
@@ -10,8 +10,8 @@ afterEach(async () => {
for (const f of fixtures.splice(0)) await f.close()
})
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
fixtures.push(f)
return f
}
@@ -42,23 +42,23 @@ async function seed(f: Awaited<ReturnType<typeof setup>>) {
return tree
}
async function restart(f: Awaited<ReturnType<typeof setup>>, adapter = new Adapter()) {
async function restart(backend: 'jsonl' | 'sqlite', f: Awaited<ReturnType<typeof setup>>, adapter = new Adapter()) {
const restore = { root: f.root, sessionId: f.agent.session.id }
await f.close({ preserve: true })
fixtures.splice(fixtures.indexOf(f), 1)
const next = await setup({ intervalMs: 86400000 }, adapter, restore)
const next = await setup(backend, { intervalMs: 86400000 }, adapter, restore)
fixtures.push(next)
return next
}
describe('session-scoped Timeline persistence', () => {
describe.each(['jsonl', 'sqlite'] as const)('session-scoped Timeline persistence (%s)', (backend) => {
it('reopens an ordinary saved Session without creating a plan or disrupting its next turn', async () => {
const f = await fixture()
const f = await fixture(backend)
await f.ctx.sessions.flush(f.agent.session)
const adapter = new Adapter()
adapter.calls = 0
adapter.release.resolve(undefined)
const next = await restart(f, adapter)
const next = await restart(backend, f, adapter)
expect(next.ctx.timeline.available(next.agent.session)).toBe(true)
expect(next.ctx.timeline.stateOf(next.agent.session).view.trees).toEqual([])
next.start()
@@ -70,7 +70,7 @@ describe('session-scoped Timeline persistence', () => {
expect(next.ctx.timeline.stateOf(next.agent.session).view.reports).toEqual([])
})
it('restores plans, user priority, discussion pairs and report coverage in a fresh host', async () => {
const f = await fixture()
const f = await fixture(backend)
const tree = await seed(f)
await f.ctx.timeline.edit({
action: 'priority',
@@ -120,7 +120,7 @@ describe('session-scoped Timeline persistence', () => {
}),
})
const saved = f.ctx.timeline.stateOf(f.agent.session)
const next = await restart(f)
const next = await restart(backend, f)
const current = next.ctx.timeline.stateOf(next.agent.session)
expect(current.view.trees).toEqual(saved.view.trees)
expect(current.calls).toEqual(saved.calls)
@@ -131,7 +131,7 @@ describe('session-scoped Timeline persistence', () => {
})
it('does not reapply an older tool call after newer checkpoints, selection changes, or restart', async () => {
const f = await fixture()
const f = await fixture(backend)
const tree = await seed(f)
const first = {
name: 'timeline_tasks',
@@ -148,7 +148,7 @@ describe('session-scoped Timeline persistence', () => {
).isError,
).not.toBe(true)
await call(f, 'timeline_tree', { action: 'start', title: 'Another goal' })
const next = await restart(f)
const next = await restart(backend, f)
const selected = next.ctx.timeline.stateOf(next.agent.session).view.activeTreeId
const result = await executeTool(next.ctx, { ...first, agent: next.agent })
expect(result.isError).not.toBe(true)
@@ -30,8 +30,8 @@ const resultSchema = z.object({
hasMore: z.boolean(),
})
async function scenario() {
const f = await setup({ intervalMs: 86400000 })
async function scenario(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object = {}) =>
executeTool(f.ctx, {
@@ -51,9 +51,9 @@ async function scenario() {
return { ...f, call, pull }
}
describe('next-work checkpoints', () => {
describe.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backend) => {
it('does not create a plan on an empty session and rejects unknown or invalid queries', async () => {
const f = await scenario()
const f = await scenario(backend)
try {
expect(await f.pull()).toMatchObject({ tree: null, next: 'plan', tasks: [], total: 0, hasMore: false })
for (const args of [{ tree: 'tree-missing' }, { limit: 0 }, { limit: 501 }, { limit: 1.5 }])
@@ -65,7 +65,7 @@ describe('next-work checkpoints', () => {
})
it('prefers inherited user priority, then active leaves, without editing or returning groups', async () => {
const f = await scenario()
const f = await scenario(backend)
try {
await f.call('timeline_tree', { action: 'start', title: 'Deliver the requested work' })
await f.call('timeline_tasks', {
@@ -101,7 +101,7 @@ describe('next-work checkpoints', () => {
})
it('rechecks blockers after runnable work ends and preserves deliberate pauses', async () => {
const f = await scenario()
const f = await scenario(backend)
try {
await f.call('timeline_tree', { action: 'start', title: 'Check dependencies' })
await f.call('timeline_tasks', {
@@ -147,7 +147,7 @@ describe('next-work checkpoints', () => {
})
it('keeps persistent blockers visible after their reasons are reconfirmed', async () => {
const f = await scenario()
const f = await scenario(backend)
try {
await f.call('timeline_tree', { action: 'start', title: 'Publish the result' })
await f.call('timeline_tasks', {
@@ -173,7 +173,7 @@ describe('next-work checkpoints', () => {
})
it('bounds suggestions and permits a complete blocker check when the default is truncated', async () => {
const f = await scenario()
const f = await scenario(backend)
try {
await f.call('timeline_tree', { action: 'start', title: 'Check remaining work' })
await f.call('timeline_tasks', {
@@ -196,7 +196,7 @@ describe('next-work checkpoints', () => {
})
it('checks only the addressed goal and never selects or resumes a different tree', async () => {
const f = await scenario()
const f = await scenario(backend)
try {
await f.call('timeline_tree', { action: 'start', title: 'Earlier goal' })
await f.call('timeline_tasks', {
@@ -21,9 +21,9 @@ const checkpoint = (options: Adapter['main'][number] | undefined) =>
?.content.some(block => block.type === 'text' && block.text.includes('Task progress checkpoint')) ??
false
describe('stale task-tree reminders', () => {
describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (backend) => {
it('reports unavailable persistence and keeps that context stable within the turn', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const available = vi.spyOn(f.ctx.timeline, 'available').mockReturnValue(false)
try {
const context = async (signal?: AbortSignal) => {
@@ -45,7 +45,7 @@ describe('stale task-tree reminders', () => {
}
})
it('keeps one saved-plan snapshot per turn and refreshes it on the next turn, preserving progress', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -127,7 +127,7 @@ describe('stale task-tree reminders', () => {
}
})
it('shows an empty saved plan as pending', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
try {
await executeTool(f.ctx, {
name: 'timeline_tree', arguments: { action: 'start', title: 'Plan the release' },
@@ -141,7 +141,7 @@ describe('stale task-tree reminders', () => {
}
})
it('adds discussion handling only while a saved user annotation is open', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const call = (name: string, args: object) =>
executeTool(f.ctx, {
name,
@@ -185,7 +185,7 @@ describe('stale task-tree reminders', () => {
}
})
it('counts repeated admission for the same agent step once', async () => {
const f = await setup({ intervalMs: 86400000, reminderIterations: 2 })
const f = await setup(backend, { intervalMs: 86400000, reminderIterations: 2 })
const signal = new AbortController().signal
const requests = agentEvents(f.agent.ctx, f.agent)
const admit = (step: number) => requests.waterfall('agent/request', { turn: 1, step, signal },
@@ -205,7 +205,7 @@ describe('stale task-tree reminders', () => {
it('uses live reminder settings and restarts the count after a successful update', async () => {
const adapter = new Adapter()
adapter.steps = 8
const f = await setup({ intervalMs: 86400000, reminderIterations: 7 }, adapter)
const f = await setup(backend, { intervalMs: 86400000, reminderIterations: 7 }, adapter)
adapter.mainActions[0] = () => {
updateVolatile(
(f.plugin.effectiveConfig as PluginConfig).reminderIterations,
@@ -237,7 +237,7 @@ describe('stale task-tree reminders', () => {
async (status) => {
const adapter = new Adapter()
adapter.steps = 0
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
try {
for (const [name, args] of [
['timeline_tree', { action: 'start', title: 'Saved goal' }],
@@ -272,7 +272,7 @@ describe('stale task-tree reminders', () => {
const adapter = new Adapter()
adapter.steps = 49
adapter.mainActions[23] = () => [{ name: 'timeline_read', arguments: '{}' }]
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
try {
f.start()
await adapter.ready.promise
@@ -299,7 +299,7 @@ describe('stale task-tree reminders', () => {
arguments: JSON.stringify({ tasks: [{ id: 'work', title: 'Ongoing work', status: 'active' }] }),
},
]
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
try {
f.start()
await adapter.ready.promise
@@ -318,7 +318,7 @@ describe('stale task-tree reminders', () => {
it('does not extend a closing response that reaches the reminder threshold', async () => {
const adapter = new Adapter()
adapter.steps = 23
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
try {
f.start()
await adapter.ready.promise
@@ -347,7 +347,7 @@ describe('stale task-tree reminders', () => {
adapter.mainActions[23] = () => [
{ name: 'timeline_tasks', arguments: JSON.stringify({ tasks: [{ id: 'missing' }] }) },
]
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
const call = (name: string, args: object) =>
executeTool(f.ctx, {
name,
@@ -18,19 +18,19 @@ afterEach(async () => {
for (const fixture of fixtures.splice(0)) await fixture.close()
vi.useRealTimers()
})
async function running(config = {}, adapter = new Adapter()) {
const fixture = await setup(config, adapter)
async function running(backend: 'jsonl' | 'sqlite', config = {}, adapter = new Adapter()) {
const fixture = await setup(backend, config, adapter)
fixtures.push(fixture)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
fixture.start()
await adapter.ready.promise
return fixture
}
describe('background summaries through a real agent loop', () => {
describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real agent loop (%s)', (backend) => {
it('admits a waiting third Session before serving the earlier sessions again', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await setup({ maxConcurrent: 1, rollupFactors: [] }, adapter)
const f = await setup(backend, { maxConcurrent: 1, rollupFactors: [] }, adapter)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
const agents = [f.agent]
const ids = [f.agent.session.id]
@@ -86,7 +86,7 @@ describe('background summaries through a real agent loop', () => {
}
}
const adapter = new SelectiveAdapter()
const f = await setup({ rollupFactors: [3], timeoutMs: 50 }, adapter)
const f = await setup(backend, { rollupFactors: [3], timeoutMs: 50 }, adapter)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
try {
f.start()
@@ -122,7 +122,7 @@ describe('background summaries through a real agent loop', () => {
it('sends no Timeline view changes during a quiet turn with a large unchanged plan', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await setup({ reportsEnabled: false }, adapter)
const f = await setup(backend, { reportsEnabled: false }, adapter)
fixtures.push(f)
const session = f.agent.session
const now = Date.now()
@@ -157,7 +157,7 @@ describe('background summaries through a real agent loop', () => {
}
})
it('uses the newly selected provider for a due rollup when work resumes', async () => {
const f = await setup({ rollupFactors: [2] })
const f = await setup(backend, { rollupFactors: [2] })
const replacement = new Adapter()
replacement.calls = 0
f.ctx.llm.registerAdapter(['replacement'], replacement)
@@ -196,7 +196,7 @@ describe('background summaries through a real agent loop', () => {
})
it('defers dispatch when Session persistence cannot acknowledge the interval', async () => {
const f = await running()
const f = await running(backend)
const flush = vi.spyOn(f.ctx.sessions, 'flush').mockResolvedValueOnce(false)
try {
await vi.advanceTimersByTimeAsync(60000)
@@ -209,7 +209,7 @@ describe('background summaries through a real agent loop', () => {
}
})
it('keeps the turn alive if neither a report request nor its failure can be saved', async () => {
const f = await running()
const f = await running(backend)
const failed = Promise.withResolvers<undefined>()
const append = vi.spyOn(f.ctx.timeline, 'append')
.mockRejectedValueOnce('Report storage unavailable')
@@ -238,7 +238,7 @@ describe('background summaries through a real agent loop', () => {
arguments: JSON.stringify({ action: 'start', title: 'Fix session recovery' }),
},
]
const f = await running({ reportsEnabled: false }, adapter)
const f = await running(backend, { reportsEnabled: false }, adapter)
await vi.advanceTimersByTimeAsync(15 * 60000)
expect(f.ctx.timeline.stateOf(f.agent.session).view.trees).toMatchObject([
{ title: 'Fix session recovery' },
@@ -249,7 +249,7 @@ describe('background summaries through a real agent loop', () => {
it('keeps saved reports and resumes base reports and rollups after enabling', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({ rollupFactors: [2] }, adapter)
const f = await running(backend, { rollupFactors: [2] }, adapter)
const { reportsEnabled } = f.plugin.effectiveConfig as PluginConfig
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
@@ -268,7 +268,7 @@ describe('background summaries through a real agent loop', () => {
it('cancels an in-flight report without recording a failure or stopping the turn', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
const { reportsEnabled } = f.plugin.effectiveConfig as PluginConfig
@@ -286,7 +286,7 @@ describe('background summaries through a real agent loop', () => {
it('starts the first zero-tool interval at the turn that resumes a long-idle session', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await setup({ intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
const f = await setup(backend, { intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
fixtures.push(f)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
await vi.advanceTimersByTimeAsync(143 * 3600000)
@@ -305,7 +305,7 @@ describe('background summaries through a real agent loop', () => {
it.each(outputLanguages)('uses fixed %s no-activity text without a model query', async (language) => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({ language }, adapter)
const f = await running(backend, { language }, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]?.summary.progress).toEqual([languageText[language].noActivity])
@@ -314,7 +314,7 @@ describe('background summaries through a real agent loop', () => {
it.each([true, false])(
'identifies independent-runtime main requests through Agent admission; main=%s',
async (main) => {
const f = await running()
const f = await running(backend)
const namespace: unknown = await import(
/* @vite-ignore */ `${import.meta.resolve('@deepseek-ai/dsh-llm/src/call-config.ts')}?timeline-independent-runtime`,
)
@@ -346,7 +346,7 @@ describe('background summaries through a real agent loop', () => {
it.each(['compaction', 'session-title'] as const)(
'excludes %s requests even when they share the admitted turn signal',
async (purpose) => {
const f = await running()
const f = await running(backend)
const previous = f.adapter.main.at(-1)
if (previous?.signal === undefined) throw new Error('The main request signal is missing')
for await (const chunk of f.ctx.llm.stream({
@@ -365,7 +365,7 @@ describe('background summaries through a real agent loop', () => {
},
)
it('ignores an already cancelled main request and keeps the previous report context', async () => {
const f = await running()
const f = await running(backend)
const cancelled = new AbortController()
await agentEvents(f.agent.ctx, f.agent).waterfall('agent/request',
{ turn: 0, step: 2, signal: cancelled.signal },
@@ -381,7 +381,7 @@ describe('background summaries through a real agent loop', () => {
expect(JSON.stringify(f.adapter.checks.at(-1)?.messages)).not.toContain('Cancelled context')
})
it('records the request before dispatch and does not send it when persistence fails', async () => {
const f = await running()
const f = await running(backend)
const append = vi.spyOn(f.ctx.timeline, 'append').mockImplementationOnce(async () => {
throw new Error('Cannot save request')
})
@@ -397,7 +397,7 @@ describe('background summaries through a real agent loop', () => {
it('applies elapsed thresholds to complete non-multiple periods without reusing children', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({ intervalMs: 600000, rollupFactors: [2.5, 2.4] }, adapter)
const f = await running(backend, { intervalMs: 600000, rollupFactors: [2.5, 2.4] }, adapter)
let previous = 0
for (const [minute, count] of [
[10, 1],
@@ -426,7 +426,7 @@ describe('background summaries through a real agent loop', () => {
})
})
it('adds every level prompt to the global instructions, including the first level', async () => {
const f = await running({
const f = await running(backend, {
summaryPrompt: 'Global stable instructions.',
levelPrompts: ['First-level emphasis.', 'Higher-level emphasis.'],
rollupFactors: [2],
@@ -445,7 +445,7 @@ describe('background summaries through a real agent loop', () => {
it('uses 15-minute reports and 1-hour/4-hour rollups while retaining the one-minute floor', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({ intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
const f = await running(backend, { intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
await vi.advanceTimersByTimeAsync(899999)
expect(f.reports()).toHaveLength(0)
await vi.advanceTimersByTimeAsync(1)
@@ -462,7 +462,7 @@ describe('background summaries through a real agent loop', () => {
it('uses the synced app language in the task prompt and zero-activity summaries', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({ language: 'zh-CN' }, adapter)
const f = await running(backend, { language: 'zh-CN' }, adapter)
const prompt = await f.ctx.systemPrompt.assemble({ scope: f.agent })
expect(prompt.sections.find(section => section.name === 'timeline:planning')?.text).toContain(
"discussion replies in 简体中文. Follow the user's language instructions for all other work and conversation.",
@@ -489,7 +489,7 @@ describe('background summaries through a real agent loop', () => {
userActions: [],
}),
]
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]?.summary).toEqual(summary)
@@ -500,7 +500,7 @@ describe('background summaries through a real agent loop', () => {
expect(f.records.filter(event => event.type === 'plugin:timeline/failure')).toHaveLength(0)
})
it('waits for a backward wall clock without losing activity or writing reversed intervals', async () => {
const f = await running()
const f = await running(backend)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
const end = f.reports()[0]?.end
@@ -523,7 +523,7 @@ describe('background summaries through a real agent loop', () => {
'covers completed tool work while another tool is running; prior work %s',
async (priorWork) => {
const adapter = new Adapter()
const f = await setup({}, adapter)
const f = await setup(backend, {}, adapter)
fixtures.push(f)
const started = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
@@ -573,7 +573,7 @@ describe('background summaries through a real agent loop', () => {
},
)
it('waits for the next complete snapshot when the surface changes without a new tool call', async () => {
const f = await running()
const f = await running(backend)
const session = f.agent.session
session.append('user/message', createUserMessage({
source: { kind: 'user' },
@@ -592,7 +592,7 @@ describe('background summaries through a real agent loop', () => {
],
defaultEffort: ReasoningEffortId('maximum'),
}
const f = await running({ reportReasoningEffort: 'brief', reportMaxTokens: 512 }, adapter)
const f = await running(backend, { reportReasoningEffort: 'brief', reportMaxTokens: 512 }, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(adapter.main.at(-1)?.reasoningEffort).toBe('maximum')
@@ -600,7 +600,7 @@ describe('background summaries through a real agent loop', () => {
expect(adapter.checks[0]?.maxTokens).toBe(512)
})
it('rejects an explicit unsupported report effort before recording or dispatching a request', async () => {
const f = await running({ reportReasoningEffort: 'unavailable' })
const f = await running(backend, { reportReasoningEffort: 'unavailable' })
await vi.advanceTimersByTimeAsync(60000)
await vi.waitFor(() => {
expect(f.records.some(record =>
@@ -614,7 +614,7 @@ describe('background summaries through a real agent loop', () => {
expect(f.agent.status).toBe('running')
})
it('reports one tool call without a viewer or a workload threshold, and leaves the main task running', async () => {
const f = await running()
const f = await running(backend)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]?.summary).toEqual(summary)
@@ -635,7 +635,7 @@ describe('background summaries through a real agent loop', () => {
)
})
it('keeps tool results as report context without offering the main task tools to the summarizer', async () => {
const f = await running()
const f = await running(backend)
const main = f.adapter.main.at(-1)
const original = JSON.stringify(main)
expect(main?.tools?.some(tool => tool.name === 'echo')).toBe(true)
@@ -651,7 +651,7 @@ describe('background summaries through a real agent loop', () => {
it('bounds response content without charging repeated JSON framing for tiny stream deltas', async () => {
const adapter = new Adapter()
adapter.tinyDeltas = true
const f = await running({ maxResponseBytes: Buffer.byteLength(adapter.answer) + 128 }, adapter)
const f = await running(backend, { maxResponseBytes: Buffer.byteLength(adapter.answer) + 128 }, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]?.summary).toEqual(summary)
@@ -659,7 +659,7 @@ describe('background summaries through a real agent loop', () => {
it('hard-codes no activity without calling the model, including later empty intervals', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]).toMatchObject({
@@ -676,7 +676,7 @@ describe('background summaries through a real agent loop', () => {
it('rolls completed children up and avoids model calls for an entirely quiet hierarchy', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running({ rollupFactors: [2, 2] }, adapter)
const f = await running(backend, { rollupFactors: [2, 2] }, adapter)
for (const count of [1, 3, 4, 7]) {
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report', count)
@@ -686,7 +686,7 @@ describe('background summaries through a real agent loop', () => {
expect(adapter.checks).toHaveLength(0)
})
it('uses the editable prompt for base reports and rollups', async () => {
const f = await running({ summaryPrompt: 'Custom short report instructions.', rollupFactors: [2] })
const f = await running(backend, { summaryPrompt: 'Custom short report instructions.', rollupFactors: [2] })
for (const count of [1, 3]) {
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report', count)
@@ -700,7 +700,7 @@ describe('background summaries through a real agent loop', () => {
expect(f.reports().map(report => report.level)).toEqual([0, 0, 1])
})
it('uses the current plugin language for both report levels without changing or forking the working agent', async () => {
const f = await running({ rollupFactors: [2], levelPrompts: ['', 'Combine the child results.'] })
const f = await running(backend, { rollupFactors: [2], levelPrompts: ['', 'Combine the child results.'] })
const original = structuredClone(f.adapter.main.at(-1)?.messages)
const references = f.plugin.effectiveConfig as PluginConfig
updateVolatile(references.language, Config({ language: 'zh-CN' }).language)
@@ -725,7 +725,7 @@ describe('background summaries through a real agent loop', () => {
expect(f.ctx.agents.list()).toHaveLength(1)
})
it('summarizes mixed children even after a surface event invalidates the base snapshot', async () => {
const f = await running({ rollupFactors: [2], levelPrompts: ['', 'Condense child reports.'] })
const f = await running(backend, { rollupFactors: [2], levelPrompts: ['', 'Condense child reports.'] })
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
f.agent.session.append(
@@ -751,7 +751,7 @@ describe('background summaries through a real agent loop', () => {
expect(f.reports().at(-1)?.children).toHaveLength(2)
})
it('keeps live settings references and applies cadence and prompt changes to subsequent work', async () => {
const f = await running({ rollupFactors: [2] })
const f = await running(backend, { rollupFactors: [2] })
const references = f.plugin.effectiveConfig as PluginConfig
const changed = Config({
intervalMs: 120000,
@@ -784,7 +784,7 @@ describe('background summaries through a real agent loop', () => {
it('retries a malformed response at the next interval without consuming the activity watermark', async () => {
const adapter = new Adapter()
adapter.answer = 'not JSON'
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/failure')
expect(f.reports()).toHaveLength(0)
@@ -800,7 +800,7 @@ describe('background summaries through a real agent loop', () => {
it('waits for an admitted model route before rolling up saved model reports', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await setup({ rollupFactors: [2] }, adapter)
const f = await setup(backend, { rollupFactors: [2] }, adapter)
fixtures.push(f)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
const session = f.agent.session
@@ -835,7 +835,7 @@ describe('background summaries through a real agent loop', () => {
})
it('rolls up saved reports whose older records lack generation and activity times', async () => {
const adapter = new Adapter()
const f = await setup({ rollupFactors: [2] }, adapter)
const f = await setup(backend, { rollupFactors: [2] }, adapter)
fixtures.push(f)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
const session = f.agent.session
@@ -859,7 +859,7 @@ describe('background summaries through a real agent loop', () => {
expect(adapter.checks).toHaveLength(2)
})
it('commits a buffered report once when a report flush fails before recovery', async () => {
const f = await running({ rollupFactors: [2] })
const f = await running(backend, { rollupFactors: [2] })
let failed = false
f.ctx.on('session/flush', (session) => {
if (session === f.agent.session && f.reports().length === 1 && !failed) {
@@ -881,7 +881,7 @@ describe('background summaries through a real agent loop', () => {
it('counts main work during an auxiliary query toward the next report', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
await vi.advanceTimersByTimeAsync(30000)
@@ -895,7 +895,7 @@ describe('background summaries through a real agent loop', () => {
it('aborts and drains a summary when the plugin unloads', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
expect(adapter.active).toBe(1)
@@ -907,7 +907,7 @@ describe('background summaries through a real agent loop', () => {
it.each([1, 4])(
'catches up due levels after %ih idle without counting idle time as work',
async (hours) => {
const f = await running({ intervalMs: 900000, rollupFactors: [4, 4] })
const f = await running(backend, { intervalMs: 900000, rollupFactors: [4, 4] })
const start = Date.now()
await vi.advanceTimersByTimeAsync(24000)
f.adapter.release.resolve(undefined)
@@ -934,7 +934,7 @@ describe('background summaries through a real agent loop', () => {
},
)
it('reconciles uncovered work across a plugin reload and keeps captured report ranges stable', async () => {
const f = await running({ rollupFactors: [2] })
const f = await running(backend, { rollupFactors: [2] })
const start = Date.now()
await vi.advanceTimersByTimeAsync(24000)
f.adapter.release.resolve(undefined)
@@ -966,7 +966,7 @@ describe('background summaries through a real agent loop', () => {
})
})
it('retries a failed rollup before another base report is due', async () => {
const f = await running({ intervalMs: 600000, rollupFactors: [2.5] })
const f = await running(backend, { intervalMs: 600000, rollupFactors: [2.5] })
for (const count of [1, 2]) {
await vi.advanceTimersByTimeAsync(600000)
await f.waitRecords('plugin:timeline/report', count)
@@ -992,7 +992,7 @@ describe('background summaries through a real agent loop', () => {
})
it('restores successful thresholds and uncovered short work in a fresh Host', async () => {
const config = { intervalMs: 900000, rollupFactors: [4, 4] }
const f = await running(config)
const f = await running(backend, config)
await vi.advanceTimersByTimeAsync(900000)
await f.waitRecords('plugin:timeline/report')
const first = f.reports()[0]
@@ -1012,7 +1012,7 @@ describe('background summaries through a real agent loop', () => {
await vi.advanceTimersByTimeAsync(4 * 3600000)
const adapter = new Adapter()
adapter.calls = 0
const next = await setup(config, adapter, restore)
const next = await setup(backend, config, adapter, restore)
fixtures.push(next)
expect(next.reports()).toEqual([first])
expect(adapter.checks).toHaveLength(0)
@@ -1029,7 +1029,7 @@ describe('background summaries through a real agent loop', () => {
expect(next.reports()).toHaveLength(4)
})
it('schedules reports only for agents in the plugin scope', async () => {
const f = await setup({}, new Adapter())
const f = await setup(backend, {}, new Adapter())
fixtures.push(f)
await f.plugin.dispose()
const parent = {}
@@ -1063,7 +1063,7 @@ describe('background summaries through a real agent loop', () => {
expect(f.adapter.checks.map(request => request.sessionId)).toEqual([inside.agent.session.id])
})
it('writes a scoped agent report only once when a root installation also exists', async () => {
const f = await setup({ intervalMs: 60000 })
const f = await setup(backend, { intervalMs: 60000 })
fixtures.push(f)
const parent = {}
const scoped = await createScope(f.ctx, parent).ctx.isolate('timeline').plugin(Timeline, { intervalMs: 60000 })
@@ -1090,7 +1090,7 @@ describe('background summaries through a real agent loop', () => {
const config = { intervalMs: 600000, rollupFactors: [2.5] }
const adapter = new Adapter()
adapter.calls = 0
const f = await running(config, adapter)
const f = await running(backend, config, adapter)
for (const count of [1, 2]) {
await vi.advanceTimersByTimeAsync(600000)
await f.waitRecords('plugin:timeline/report', count)
@@ -1105,7 +1105,7 @@ describe('background summaries through a real agent loop', () => {
expect(adapter.checks).toHaveLength(0)
})
it('does not report a quiet Session merely because it is opened or the plugin reloads', async () => {
const f = await setup({ intervalMs: 900000, rollupFactors: [4, 4] })
const f = await setup(backend, { intervalMs: 900000, rollupFactors: [4, 4] })
fixtures.push(f)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
await vi.advanceTimersByTimeAsync(8 * 3600000)
@@ -1120,7 +1120,7 @@ describe('background summaries through a real agent loop', () => {
it('records a timeout and drains the canceled auxiliary stream', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running({ timeoutMs: 50 }, adapter)
const f = await running(backend, { timeoutMs: 50 }, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
await vi.advanceTimersByTimeAsync(50)
@@ -1131,7 +1131,7 @@ describe('background summaries through a real agent loop', () => {
it('does not rearm a disposed Agent after its independent report settles', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running({}, adapter)
const f = await running(backend, {}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
await f.disposeAgent()
@@ -1142,7 +1142,7 @@ describe('background summaries through a real agent loop', () => {
it('bounds concurrent summaries queued by multiple Sessions', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running({ maxConcurrent: 1 }, adapter)
const f = await running(backend, { maxConcurrent: 1 }, adapter)
const others = await Promise.all(
['second', 'third'].map(async (id) => {
const agent = await f.harness.create(SessionId(id), { provider: 'fixture', model: 'timeline' })
@@ -14,8 +14,8 @@ const fixtures: Awaited<ReturnType<typeof setup>>[] = []
afterEach(async () => {
for (const fixture of fixtures.splice(0)) await fixture.close()
})
async function fixture() {
const value = await setup({ intervalMs: 86400000 })
async function fixture(backend: 'jsonl' | 'sqlite') {
const value = await setup(backend, { intervalMs: 86400000 })
fixtures.push(value)
return value
}
@@ -28,9 +28,9 @@ function tree(session: Session, id = 'work'): TimelineRecordMap['plugin:timeline
}
}
describe('public Timeline storage', () => {
describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (backend) => {
it('flushes a buffered priority before a queued retry returns and sends one notice', async () => {
const f = await fixture()
const f = await fixture(backend)
const session = f.agent.session
const change = tree(session)
const task = taskId.parse('check')
@@ -61,7 +61,7 @@ describe('public Timeline storage', () => {
}
})
it('keeps whole-tree discussion context and treats an unchanged priority as a no-op', async () => {
const f = await fixture()
const f = await fixture(backend)
const session = f.agent.session
const change = tree(session)
const task = taskId.parse('check')
@@ -89,7 +89,7 @@ describe('public Timeline storage', () => {
await expect(f.ctx.timeline.edit({ ...input, id: 'note-000000000000ffff' })).rejects.toThrow('discussions per Session')
})
it('accepts authenticated edit RPCs and contains invalid requests and cancellation', async () => {
const f = await fixture()
const f = await fixture(backend)
const owner = new Peer(f.ctx, { principal: { kind: 'owner' } })
const viewer = new Peer(f.ctx, {
principal: {
@@ -132,7 +132,7 @@ describe('public Timeline storage', () => {
}
})
it('rejects edits against unavailable targets and unacknowledged sessions', async () => {
const f = await fixture()
const f = await fixture(backend)
const sessionId = f.agent.session.id
const missing = treeId.parse('missing')
await expect(f.ctx.timeline.edit({ action: 'remove', sessionId: SessionId('unknown'), tree: missing }))
@@ -152,7 +152,7 @@ describe('public Timeline storage', () => {
await expect(storage.append(f.agent.session, 'plugin:timeline/tree', change)).rejects.toThrow('storage is closed')
})
it('preserves concurrent task patches and rejects invalid edits without changing the stored view', async () => {
const f = await fixture()
const f = await fixture(backend)
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -180,7 +180,7 @@ describe('public Timeline storage', () => {
expect(f.ctx.timeline.stateOf(f.agent.session).view).toEqual(before)
})
it('rejects an oversized tree write before it reaches the session log', async () => {
const f = await fixture()
const f = await fixture(backend)
const session = f.agent.session
const change = tree(session)
change.tree.tasks = patchTasks([], Array.from({ length: 180 }, (_, index) => ({
@@ -192,7 +192,7 @@ describe('public Timeline storage', () => {
expect(f.ctx.timeline.stateOf(session).view.trees).toEqual([])
})
it('drains an acknowledged log write before plugin unload finishes', async () => {
const f = await fixture()
const f = await fixture(backend)
const change = tree(f.agent.session)
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
const admitted = Promise.withResolvers<undefined>()
@@ -211,7 +211,7 @@ describe('public Timeline storage', () => {
expect((await f.handle.read()).events.some(event => pluginRecordOf(event)?.type === 'plugin:timeline/tree')).toBe(true)
})
it('starts each Session independently and rejects mismatched or invalid storage writes', async () => {
const f = await fixture()
const f = await fixture(backend)
const { session: other } = await f.ctx.agents.create({ sessionId: SessionId('other'), meta: { cwd: process.cwd() } }).then(result => result.agent)
await f.ctx.timeline.append(f.agent.session, 'plugin:timeline/tree', tree(f.agent.session))
expect(f.ctx.timeline.stateOf(other).view.trees).toEqual([])
@@ -25,9 +25,9 @@ function toolsOf(fixture: Awaited<ReturnType<typeof setup>>, prefix: string) {
})
}
describe('agent tools in the production loop', () => {
describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop (%s)', (backend) => {
it('reports only open task discussions in status queries and exposes saved report failures', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const call = toolsOf(f, 'discussion')
const session = f.agent.session
try {
@@ -55,7 +55,7 @@ describe('agent tools in the production loop', () => {
}
})
it('keeps reads useful when a restored view lacks an annotation target or task parent', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const call = toolsOf(f, 'incomplete-view')
const session = f.agent.session
try {
@@ -86,7 +86,7 @@ describe('agent tools in the production loop', () => {
}
})
it('reports an unexpected task validation failure without saving the patch', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const call = toolsOf(f, 'invalid-patch')
try {
await call('timeline_tree', { action: 'start', title: 'Review recovery' })
@@ -104,7 +104,7 @@ describe('agent tools in the production loop', () => {
}
})
it('requires an agent to use the planning tools and provides compact call labels', async () => {
const f = await setup()
const f = await setup(backend)
try {
for (const [name, args, title] of [
['timeline_tree', { action: 'start', title: 'Plan' }, 'Timeline task tree'],
@@ -128,7 +128,7 @@ describe('agent tools in the production loop', () => {
}
})
it('selects existing trees, bounds new trees, and validates each read target', async () => {
const f = await setup({ intervalMs: 86400000, maxTrees: 2 })
const f = await setup(backend, { intervalMs: 86400000, maxTrees: 2 })
const call = toolsOf(f, 'selection')
const start = (title: string) => call('timeline_tree', { action: 'start', title })
const view = () => f.ctx.timeline.stateOf(f.agent.session).view
@@ -175,7 +175,7 @@ describe('agent tools in the production loop', () => {
}
})
it('saves stable card metadata without changing native text, and returns the original receipt on retry', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const run = toolsOf(f, 'card')
const call = (id: string, name: string, args: object) => run(name, args, id)
const readReceipt = (result: Awaited<ReturnType<typeof call>>) =>
@@ -214,7 +214,7 @@ describe('agent tools in the production loop', () => {
}
})
it('serializes concurrent card baselines with the acknowledged task writes', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
let id = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -252,7 +252,7 @@ describe('agent tools in the production loop', () => {
}
})
it('supplies live task guidance once in the writing tool description without changing the system prefix', async () => {
const f = await setup({ intervalMs: 86400000, taskPrompt: 'Explain what recovery checks prove.' })
const f = await setup(backend, { intervalMs: 86400000, taskPrompt: 'Explain what recovery checks prove.' })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -300,7 +300,7 @@ describe('agent tools in the production loop', () => {
}
})
it('rejects removed estimate arguments atomically instead of silently accepting an obsolete tool shape', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -335,7 +335,7 @@ describe('agent tools in the production loop', () => {
}
})
it('distinguishes the complete report count from its bounded recent sample', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
try {
for (let index = 0; index < 4; index++)
await f.ctx.timeline.append(f.agent.session, 'plugin:timeline/report', {
@@ -374,7 +374,7 @@ describe('agent tools in the production loop', () => {
}
})
it('returns one short tree identity for repeated starts with the same tool call', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
try {
const call = {
name: 'timeline_tree',
@@ -413,7 +413,7 @@ describe('agent tools in the production loop', () => {
}
})
it('toggles only Timeline-owned Todo restrictions through live settings without changing presets', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const parent = {}
const preset = createScope(f.ctx, parent)
let writes = 0
@@ -473,7 +473,7 @@ describe('agent tools in the production loop', () => {
})
it('advertises floating-point weights and accepts fractional values without rounding model data', async () => {
const adapter = new Adapter()
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
try {
expect(f.ctx.tools.schemas(f.agent).find(tool => tool.name === 'timeline_tasks')).toMatchObject({
parameters: { properties: { tasks: { items: { properties: { weight: { type: 'number' } } } } } },
@@ -504,7 +504,7 @@ describe('agent tools in the production loop', () => {
}
})
it('updates the fixed language rule in the next prompt assembly', async () => {
const f = await setup()
const f = await setup(backend)
try {
const prompt = () => f.ctx.systemPrompt.assemble({ scope: f.agent })
expect(
@@ -526,7 +526,7 @@ describe('agent tools in the production loop', () => {
}
})
it('denies an explicit agent-local Todo override without breaking registration', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
let writes = 0
try {
await f.agent.ctx.inject(['tools'], (scope) => {
@@ -563,7 +563,7 @@ describe('agent tools in the production loop', () => {
}
})
it('replaces inherited preset Todo tools and restores them when unloaded', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const parent = {}
const preset = createScope(f.ctx, parent)
try {
@@ -616,7 +616,7 @@ describe('agent tools in the production loop', () => {
})
it('creates and updates a named tree through real model tool calls', async () => {
const adapter = new Adapter()
const f = await setup({ intervalMs: 86400000 }, adapter)
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
try {
adapter.mainActions = [
() => [
@@ -685,7 +685,7 @@ describe('agent tools in the production loop', () => {
}
})
it('updates an addressed tree and returns weights without ETA inputs', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
const call = async (name: string, args: object) => {
const result = await executeTool(f.ctx, {
name,
@@ -739,7 +739,7 @@ describe('agent tools in the production loop', () => {
}
})
it('returns bounded leaf-status queries without changing selection or including report history', async () => {
const f = await setup({ intervalMs: 86400000 })
const f = await setup(backend, { intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -1,6 +1,6 @@
import { pluginRecordOf, SessionId } from '@deepseek-ai/dsh-session'
import { executeTool } from './execute-tool.ts'
import { cp, mkdtemp, writeFile } from 'node:fs/promises'
import { cp, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -15,8 +15,8 @@ const fixtures: Awaited<ReturnType<typeof setup>>[] = []
afterEach(async () => {
for (const fixture of fixtures.splice(0)) await fixture.close()
})
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
f.adapter.calls = 0
f.adapter.release.resolve(undefined)
fixtures.push(f)
@@ -38,20 +38,20 @@ const imported = (
continue: proceed,
})
describe('task-tree transfer through public storage', () => {
describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public storage (%s)', (backend) => {
it('rejects import conflicts and configured tree and task limits', async () => {
const f = await setup({ maxTrees: 1 })
const f = await setup(backend, { maxTrees: 1 })
fixtures.push(f)
await imported(f)
await expect(imported(f, 'checkpoint-one', true)).rejects.toThrow('identity was already used')
await expect(imported(f, 'new-copy', true)).rejects.toThrow('At most 1 task trees')
const bounded = await setup({ maxTasks: 1 })
const bounded = await setup(backend, { maxTasks: 1 })
fixtures.push(bounded)
await expect(imported(bounded)).rejects.toThrow('At most 1 tasks')
expect(bounded.ctx.timeline.stateOf(bounded.agent.session).view.trees).toEqual([])
})
it('cancels a draft import without an agent turn and refuses stale draft cancellation after a turn starts', async () => {
const f = await fixture()
const f = await fixture(backend)
const first = await imported(f)
if (first.action !== 'import') throw new Error('Missing import result')
expect(
@@ -86,7 +86,7 @@ describe('task-tree transfer through public storage', () => {
expect(f.ctx.timeline.stateOf(f.agent.session).view.trees).toHaveLength(1)
})
it('activates a cold conversation through its public controller and preserves activation errors', async () => {
const f = await fixture()
const f = await fixture(backend)
let denied = false
const resolveAgent = vi.fn(() =>
Promise.resolve(denied ? { error: new Error('Session writer is held elsewhere') } : { agent: f.agent }),
@@ -102,7 +102,7 @@ describe('task-tree transfer through public storage', () => {
expect(f.ctx.timeline.stateOf(f.agent.session).view.trees).toHaveLength(1)
})
it('copies a plan atomically, retains discussions and priorities, and reuses a modified copy without reverting it', async () => {
const f = await fixture()
const f = await fixture(backend)
const first = await imported(f)
if (first.action !== 'import') throw new Error('Missing import result')
const view = () => f.ctx.timeline.stateOf(f.agent.session).view
@@ -138,7 +138,7 @@ describe('task-tree transfer through public storage', () => {
expect(view().trees).toHaveLength(2)
})
it('removes only the selected tree, immediately notifies the conversation, and keeps stale import retries removed after restart decoding', async () => {
const f = await fixture()
const f = await fixture(backend)
f.start()
await f.agent.whenIdle()
f.adapter.main = []
@@ -162,7 +162,7 @@ describe('task-tree transfer through public storage', () => {
expect(f.adapter.main).toHaveLength(1)
})
it('rejects damaged imports and uncertain saves without publishing a partial tree', async () => {
const f = await fixture()
const f = await fixture(backend)
await expect(
f.ctx.timeline.edit({
action: 'import',
@@ -180,7 +180,7 @@ describe('task-tree transfer through public storage', () => {
expect(f.adapter.main).toHaveLength(0)
})
it('recovers a prepared import after a failed flush and delivers continuation only once', async () => {
const f = await fixture()
const f = await fixture(backend)
const { root, agent: { session } } = f
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
vi.spyOn(f.ctx.sessions, 'flush')
@@ -195,7 +195,7 @@ describe('task-tree transfer through public storage', () => {
const adapter = new Adapter()
adapter.calls = 0
adapter.release.resolve(undefined)
const recovered = await setup({ intervalMs: 86400000 }, adapter, { root, sessionId: session.id })
const recovered = await setup(backend, { intervalMs: 86400000 }, adapter, { root, sessionId: session.id })
fixtures.push(recovered)
expect(recovered.ctx.timeline.stateOf(recovered.agent.session).view.trees).toEqual([])
await expect(imported(recovered, 'retry-save', true, true)).rejects.toThrow('identity was already used')
@@ -210,7 +210,7 @@ describe('task-tree transfer through public storage', () => {
expect(verify?.history.at(-1)).toMatchObject({ status: 'paused', previousProgress: 0.4, progress: 0.4 })
})
it('acknowledges a buffered continuation once when the inbox flush recovers', async () => {
const f = await fixture()
const f = await fixture(backend)
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
const flushes = vi.spyOn(f.ctx.sessions, 'flush')
.mockImplementationOnce(flush)
@@ -227,7 +227,7 @@ describe('task-tree transfer through public storage', () => {
}
})
it('recovers an unacknowledged ready marker without a second tree or continuation', async () => {
const f = await fixture()
const f = await fixture(backend)
const session = f.agent.session
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
vi.spyOn(f.ctx.sessions, 'flush')
@@ -242,7 +242,7 @@ describe('task-tree transfer through public storage', () => {
expect(f.adapter.main).toHaveLength(1)
})
it('keeps a parked continuation across restart and never queues it twice', async () => {
const f = await fixture()
const f = await fixture(backend)
const { root, agent: { session } } = f
// Model a restart after the inbox record commits and before the driver claims the message.
vi.spyOn(f.agent, 'followup').mockImplementation((message) => {
@@ -252,12 +252,20 @@ describe('task-tree transfer through public storage', () => {
const id = f.agent.inbox.nextTurn[0]?.id
expect(id).toBeDefined()
const crashStore = await mkdtemp(join(tmpdir(), 'timeline-parked-'))
await cp(root, crashStore, { recursive: true })
try {
await cp(root, crashStore, { recursive: true })
await f.close({ preserve: true })
await rm(root, { recursive: true, force: true })
// Restore the saved data at its original path, including SQLite routing records.
await cp(crashStore, root, { recursive: true })
} finally {
await rm(crashStore, { recursive: true, force: true })
}
const adapter = new Adapter()
adapter.calls = 0
adapter.release.resolve(undefined)
const recovered = await setup({ intervalMs: 86400000 }, adapter, { root: crashStore, sessionId: session.id })
fixtures.push(recovered)
const recovered = await setup(backend, { intervalMs: 86400000 }, adapter, { root, sessionId: session.id })
fixtures.splice(fixtures.indexOf(f), 1, recovered)
expect(await imported(recovered, 'parked-notice', false, true)).toMatchObject({ reused: true, notified: false })
expect(recovered.agent.inbox.nextTurn.map(message => message.id)).toEqual([id])
recovered.start()
@@ -269,7 +277,7 @@ describe('task-tree transfer through public storage', () => {
expect(JSON.stringify(adapter.main[0]?.messages)).toContain('Continue task tree')
})
it('rejects excessive units even when the checkpoint declares the task complete', async () => {
const f = await fixture()
const f = await fixture(backend)
await expect(f.ctx.timeline.edit({
action: 'import',
sessionId: f.agent.session.id,
@@ -283,7 +291,7 @@ describe('task-tree transfer through public storage', () => {
expect(f.ctx.timeline.stateOf(f.agent.session).view.trees).toEqual([])
})
it('reserves idle maintenance while a save is pending, then releases queued work with the imported plan', async () => {
const f = await fixture()
const f = await fixture(backend)
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
const admitted = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
@@ -310,9 +318,9 @@ describe('task-tree transfer through public storage', () => {
})
})
describe('human Timeline command', () => {
describe.each(['jsonl', 'sqlite'] as const)('human Timeline command (%s)', (backend) => {
it('imports without a session working directory and reports filesystem and result failures', async () => {
const f = await fixture()
const f = await fixture(backend)
await f.ctx.plugin(Commands)
await f.ctx.plugin(FsLocal, { cwd: f.root })
const { agent } = await f.ctx.agents.create({
@@ -331,7 +339,7 @@ describe('human Timeline command', () => {
expect((await run())?.result).toMatchObject({ kind: 'error', text: 'Invalid Timeline import response' })
})
it('explains duplicate flags, unavailable filesystems and failed reads', async () => {
const f = await fixture()
const f = await fixture(backend)
await f.ctx.plugin(Commands)
const run = (text: string) => f.ctx.commands.execute(f.agent, text, [], new AbortController().signal)
expect((await run('/timeline plan.timeline.json'))?.result.kind).toBe('error')
@@ -346,7 +354,7 @@ describe('human Timeline command', () => {
expect(f.ctx.timeline.stateOf(f.agent.session).view.trees).toEqual([])
})
it('reports a saved continuation even when admission cannot be confirmed', async () => {
const f = await fixture()
const f = await fixture(backend)
await f.ctx.plugin(Commands)
await f.ctx.plugin(FsLocal, { cwd: f.root })
const path = join(f.root, 'plan.timeline.json')
@@ -371,7 +379,7 @@ describe('human Timeline command', () => {
expect(f.ctx.timeline.stateOf(f.agent.session).view.trees).toHaveLength(1)
})
it('imports a quoted @file into a blank session before any model request, then supports an explicit continuation', async () => {
const f = await fixture()
const f = await fixture(backend)
await f.ctx.plugin(Commands)
await f.ctx.plugin(FsLocal, { cwd: f.root })
const path = join(f.root, 'my plan.timeline.json')
@@ -22,23 +22,23 @@ import { mountWorkflowRuntime } from '../../../workflow/workflow-ptc/tests/setup
type MockScript = ConstructorParameters<typeof MockAdapter>[0]
const testToolSignal = new AbortController().signal
async function mountExecution(ctx: Context): Promise<string> {
async function mountExecution(backend: 'jsonl' | 'sqlite', ctx: Context): Promise<string> {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-ralph-'))
onTestFinished(async () => {
await ctx.fiber.dispose()
await rm(cwd, { recursive: true, force: true })
})
await mountWorkflowRuntime(ctx, { cwd })
await ctx.plugin(JsonlSessionPersistence, { root: join(cwd, '.sessions') })
await ctx.plugin(JsonlSessionPersistence, { root: join(cwd, '.sessions'), storage: backend })
return cwd
}
/** Mount the shipped Ralph execution stack around one keyless model script. */
async function mountRalph(script: MockScript, config: toolRalph.Config) {
async function mountRalph(backend: 'jsonl' | 'sqlite', script: MockScript, config: toolRalph.Config) {
const ctx = new Context()
const adapter = new MockAdapter(script)
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
const cwd = await mountExecution(ctx)
const cwd = await mountExecution(backend, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(spawn, { providerName: 'spawn' })
@@ -53,7 +53,7 @@ async function mountRalph(script: MockScript, config: toolRalph.Config) {
return { ctx, adapter, parentHandle, parent: parentHandle.agent }
}
describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => {
describe.each(['jsonl', 'sqlite'] as const)('dsh-tool-ralph over the real spawn and sandboxed PTC stack (%s)', (backend) => {
it('uses distinct empty-seed children, shared cwd, and only the prior bounded handoff', { timeout: 90_000 }, async () => {
const firstReport = {
status: 'continue',
@@ -76,7 +76,7 @@ describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => {
toolCallResponse('round-2', STRUCTURED_OUTPUT_TOOL, finalReport),
])
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
const cwd = await mountExecution(ctx)
const cwd = await mountExecution(backend, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(spawn, { providerName: 'spawn' })
@@ -144,7 +144,7 @@ describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => {
nextSteps: ['Finish migration-b.ts.'],
blocker: '',
}
const { ctx, parent, parentHandle } = await mountRalph([
const { ctx, parent, parentHandle } = await mountRalph(backend, [
toolCallResponse('round-1', STRUCTURED_OUTPUT_TOOL, firstReport),
maxTokensResponse('unfinished child output'),
], { maxRounds: 2 })
@@ -236,7 +236,7 @@ describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => {
expectedText: 'Ralph round report exceeds maxHandoffChars',
},
])('enforces the fixed script for $name', async ({ report, config, expectedError, expectedText }) => {
const { ctx, parent, parentHandle } = await mountRalph([
const { ctx, parent, parentHandle } = await mountRalph(backend, [
toolCallResponse('round-report', STRUCTURED_OUTPUT_TOOL, report),
], config)
@@ -254,7 +254,7 @@ describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => {
})
it('cancels the sandboxed process and fresh child to quiescence', { timeout: 90_000 }, async () => {
const { ctx, parent, parentHandle } = await mountRalph(['hang'], { maxRounds: 2 })
const { ctx, parent, parentHandle } = await mountRalph(backend, ['hang'], { maxRounds: 2 })
const children: Agent[] = []
const outcomes: string[] = []
let resolveChildStarted!: (child: Agent) => void
@@ -39,7 +39,7 @@ async function registerTurnBoundary(ctx: Context): Promise<void> {
await ctx.plugin(AgentRegistry)
}
describe('tool-session-query with the real SQLite provider', () => {
describe.each(['jsonl', 'sqlite'] as const)('tool-session-query with the real SQLite query provider and %s persistence', (backend) => {
it('searches live prior-step history and a persisted same-workspace log', { timeout: 20_000 }, async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-tool-session-query-'))
temporaryDirectories.push(root)
@@ -51,7 +51,7 @@ describe('tool-session-query with the real SQLite provider', () => {
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none', storage: backend })
await ctx.plugin(SqliteSessionQueryEngine, { path: join(root, 'session-query.db') })
await ctx.plugin(ToolSessionQuery)
@@ -125,7 +125,7 @@ describe('tool-session-query with the real SQLite provider', () => {
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none', storage: backend })
await ctx.plugin(SqliteSessionQueryEngine, { path: join(root, 'session-query.db') })
await ctx.plugin(ToolSessionQuery)
@@ -1,7 +1,6 @@
/** Common paid requests and results survive Host restart without altering main conversation input. */
import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import { pluginRecordOf, SessionId, SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session'
import type { SqliteLogs } from '@deepseek-ai/dsh-session-persistence-sqlite'
import { setImmediate } from 'node:timers/promises'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { paidFixture } from './paid-fixture.ts'
@@ -36,39 +35,47 @@ function historicalEvents(): SessionEvent[] {
]
}
describe('common paid translation persistence', () => {
describe.each(['jsonl', 'sqlite'] as const)('common paid translation persistence (%s)', (backend) => {
it.each(['caller cancellation', 'provider deadline'] as const)(
'keeps a pending result ahead of an immediate retry after %s without billing again', async (interruption) => {
const b = await paidFixture(cleanups, { translator: { deepseekTimeoutMs: 60_000 } })
const backend = Reflect.get(b.ctx.sessionPersistence, 'sqlite') as SqliteLogs
expect(typeof backend.append).toBe('function')
const b = await paidFixture(cleanups, backend, { translator: { deepseekTimeoutMs: 60_000 } })
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const persist = backend.append.bind(backend)
vi.spyOn(backend, 'append').mockImplementation(async (...args) => {
if (results(args[1]).length > 0) {
let resultPending = false
b.ctx.on('session/event', (_session, event) => {
if (pluginRecordOf(event)?.type === 'plugin:translator/result') resultPending = true
})
const flush = b.ctx.sessions.flush.bind(b.ctx.sessions)
vi.spyOn(b.ctx.sessions, 'flush').mockImplementation(async (session) => {
if (resultPending) {
entered.resolve(undefined)
await release.promise
}
return persist(...args)
return flush(session)
})
const caller = new AbortController(), reason = new Error('Canceled while saving the translation')
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const scheduled = vi.spyOn(globalThis, 'setTimeout')
try {
const first = b.translate('deepseek-official', 'Original paragraph', caller.signal).catch((error: unknown) => error)
await entered.promise
expect(b.requests).toHaveLength(1)
if (interruption === 'caller cancellation') caller.abort(reason)
else await vi.advanceTimersByTimeAsync(60_000)
else {
const deadlines = scheduled.mock.calls.filter(([, delay]) => delay === 60_000)
expect(deadlines).toHaveLength(1)
// Advancing the shared clock would also flush the accepted result behind the write barrier.
deadlines[0]![0]()
}
const rejected = await first
if (interruption === 'caller cancellation') expect(rejected).toBe(reason)
else expect(rejected).toMatchObject({ code: 'TRANSLATION_TIMEOUT' })
expect(results(await b.readEvents(b.session!.id))).toEqual([])
const stat = vi.spyOn(backend, 'stat')
const open = vi.spyOn(b.ctx.sessionPersistence, 'open')
const retry = b.translate('deepseek-official').then(text => ({ text }), (error: unknown) => ({ error }))
// Retry admission starts in promise reactions; one event-loop turn drains those without releasing the write barrier.
await setImmediate()
const readsBeforeCommit = stat.mock.calls.length
const readsBeforeCommit = open.mock.calls.length
release.resolve(undefined)
await expect(retry).resolves.toEqual({ text: '翻译结果' })
expect(readsBeforeCommit).toBe(0)
@@ -80,13 +87,14 @@ describe('common paid translation persistence', () => {
expect(b.errors).toEqual([])
} finally {
release.resolve(undefined)
scheduled.mockRestore()
vi.useRealTimers()
}
})
it.each(providers.flatMap(provider => ['credentials', 'native-owner'].map(unavailable => ({ provider, unavailable }))))(
'reuses $provider after a complete restart with unavailable $unavailable and zero new HTTP', async ({ provider, unavailable }) => {
const b = await paidFixture(cleanups), id = b.session!.id, oldContext = b.ctx
const b = await paidFixture(cleanups, backend), id = b.session!.id, oldContext = b.ctx
const specification = () => b.ctx.translator.resolve({ provider, text: 'Original paragraph', targetLanguage: 'zh', sessionId: id })
expect(await b.ctx.translator.translate(specification())).toBe('翻译结果')
const committed = await b.readEvents(id)
@@ -111,7 +119,7 @@ describe('common paid translation persistence', () => {
it.each(providers)('requires a live writer for uncached %s before preparation and retains independent input and result', async (provider) => {
const id = brandString<SessionId>('historical-paid-translation')
const b = await paidFixture(cleanups, { withSession: false, withSessionQuery: true })
const b = await paidFixture(cleanups, backend, { withSession: false, withSessionQuery: true })
const original = await b.createHistorical(id, historicalEvents())
await b.restart()
using observation = await b.ctx.sessionQuery.observeSession(id, { projectionMode: 'none' })
@@ -153,7 +161,7 @@ describe('common paid translation persistence', () => {
})
it('refuses a missing historical Session before paid dispatch', async () => {
const b = await paidFixture(cleanups, { withSession: false })
const b = await paidFixture(cleanups, backend, { withSession: false })
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ provider: 'deepseek-official', text: 'source',
targetLanguage: 'zh', sessionId: brandString<SessionId>('missing-historical') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
@@ -162,7 +170,7 @@ describe('common paid translation persistence', () => {
})
it('does not claim a historical writer on a cache miss or dispatch paid work', async () => {
const b = await paidFixture(cleanups, { withSession: false }), original = await b.createHistorical(brandString<SessionId>('owned-history'), historicalEvents())
const b = await paidFixture(cleanups, backend, { withSession: false }), original = await b.createHistorical(brandString<SessionId>('owned-history'), historicalEvents())
await using writer = await b.ctx.sessionPersistence.open(original.id, 'write')
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ provider: 'deepseek-official', text: 'source',
targetLanguage: 'zh', sessionId: original.id })))
@@ -174,7 +182,7 @@ describe('common paid translation persistence', () => {
})
it('withholds paid translated text when its durable result cannot be written', async () => {
const b = await paidFixture(cleanups), session = b.session!
const b = await paidFixture(cleanups, backend), session = b.session!
const flush = b.ctx.sessions.flush.bind(b.ctx.sessions)
const checkpoint = vi.spyOn(b.ctx.sessions, 'flush').mockImplementation(async (value) => {
if (b.requests.length > 0) throw new Error('Fixture result storage unavailable')
@@ -191,7 +199,7 @@ describe('common paid translation persistence', () => {
})
it('does not reuse a saved paid result when the configured output-token cap changes', async () => {
const b = await paidFixture(cleanups), id = b.session!.id
const b = await paidFixture(cleanups, backend), id = b.session!.id
const spec = () => b.ctx.translator.resolve({ provider: 'deepseek-official', text: 'Original paragraph', targetLanguage: 'zh', sessionId: id })
expect(await b.ctx.translator.translate(spec())).toBe('翻译结果')
await b.restart({ translator: { deepseekMaxOutputTokens: 16 } })
@@ -16,7 +16,7 @@ afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
})
describe('native Flash translation', () => {
describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (backend) => {
it('keeps anonymous choices available without any model, Loader or Session service', async () => {
const ctx = new Context()
cleanups.push(async () => { await ctx.fiber.dispose() })
@@ -30,7 +30,7 @@ describe('native Flash translation', () => {
})
it('offers both actual native owners with customized settings ids and arbitrary model version names', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
expect(await b.ctx.translator.availableProviders()).toEqual(['bing', 'google', 'deepseek-account', 'deepseek-official'])
expect(b.requests).toHaveLength(0)
expect(b.session?.snapshotEvents()).toEqual([])
@@ -62,7 +62,7 @@ describe('native Flash translation', () => {
})
it('uses only one independent fragment despite existing main user and assistant history', async () => {
const b = await paidFixture(cleanups), session = b.session!
const b = await paidFixture(cleanups, backend), session = b.session!
session.append('turn/start', { turn: 1 })
session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'Private main conversation input' }],
source: { kind: 'user' } }), { surfaceOp: 'append' })
@@ -81,7 +81,7 @@ describe('native Flash translation', () => {
it.each(['deepseek-account', 'deepseek-official'] as const)(
'keeps the enabled shipped session-log extension out of paid %s requests', async (provider) => {
const b = await paidFixture(cleanups, { withSessionLog: true }), session = b.session!
const b = await paidFixture(cleanups, backend, { withSessionLog: true }), session = b.session!
session.append('turn/start', { turn: 1 })
session.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'Private main input and tool context' }],
source: { kind: 'user' } }), { surfaceOp: 'append' })
@@ -104,7 +104,7 @@ describe('native Flash translation', () => {
})
it('respects an explicit source language in the exact independently audited prompt', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
const spec = b.ctx.translator.resolve({ text: 'source', targetLanguage: 'ja', sourceLanguage: 'en',
provider: 'deepseek-official', sessionId: b.session!.id })
await b.ctx.translator.translate(spec)
@@ -116,7 +116,7 @@ describe('native Flash translation', () => {
})
it('excludes pi-ai ownership, non-native settings paths, unregistered routes and inactive native rows', async () => {
const b = await paidFixture(cleanups, { officialName: '@deepseek-ai/dsh-llm-pi-ai' })
const b = await paidFixture(cleanups, backend, { officialName: '@deepseek-ai/dsh-llm-pi-ai' })
expect(await b.ctx.translator.availableProviders()).toEqual(['bing', 'google', 'deepseek-account'])
await expect(b.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_UNAVAILABLE' })
expect(b.requests).toEqual([])
@@ -137,7 +137,7 @@ describe('native Flash translation', () => {
})
it('requires configured credentials and exact deepseek-flash catalog identity', async () => {
const b = await paidFixture(cleanups, { signedIn: false, credentialConfigured: false,
const b = await paidFixture(cleanups, backend, { signedIn: false, credentialConfigured: false,
officialModels: [{ id: 'deepseek-v4-flash', name: 'deepseek-flash' }] })
expect(await b.ctx.translator.availableProviders()).toEqual(['bing', 'google'])
b.setConfigured(true)
@@ -146,17 +146,17 @@ describe('native Flash translation', () => {
b.setSignedIn(true)
expect(await b.ctx.translator.availableProviders()).toEqual(['bing', 'google', 'deepseek-account'])
b.setConfigured(false)
const eligible = await paidFixture(cleanups, { withCredentials: false })
const eligible = await paidFixture(cleanups, backend, { withCredentials: false })
expect(await eligible.ctx.translator.availableProviders()).toContain('deepseek-official')
expect(await eligible.translate('deepseek-official')).toBe('翻译结果')
const missingAmbient = await paidFixture(cleanups, { withCredentials: false, ambientConfigured: false })
const missingAmbient = await paidFixture(cleanups, backend, { withCredentials: false, ambientConfigured: false })
expect(await missingAmbient.ctx.translator.availableProviders()).toEqual(['bing', 'google', 'deepseek-account'])
await expect(missingAmbient.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_UNAVAILABLE' })
expect(b.requests).toEqual([])
})
it('requires an existing durable Session and retains empty results without model admission or billing', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ provider: 'deepseek-account', sourceLanguage: 'auto',
targetLanguage: 'zh', text: 'source', sessionId: brandString<SessionId>('missing') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
@@ -172,7 +172,7 @@ describe('native Flash translation', () => {
})
it('revalidates model configuration after asynchronous discovery and before preparing a native call', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
const before = Promise.withResolvers<undefined>(), continueLookup = Promise.withResolvers<undefined>()
const original = b.ctx.llm.listModels.bind(b.ctx.llm)
const lookup = vi.spyOn(b.ctx.llm, 'listModels').mockImplementationOnce(async (provider) => {
@@ -195,7 +195,7 @@ describe('native Flash translation', () => {
})
it('rechecks the owner across the eligibility return microtask before preparation', async () => {
const b = await paidFixture(cleanups), directory = b.ctx.llm.listConfigurableProviders()
const b = await paidFixture(cleanups, backend), directory = b.ctx.llm.listConfigurableProviders()
const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'official-custom-id')!
let reads = 0
vi.spyOn(b.ctx.llm, 'listConfigurableProviders').mockImplementation(() => {
@@ -212,7 +212,7 @@ describe('native Flash translation', () => {
})
it('rejects a prepared call that cannot guarantee thinking off before auditing or network I/O', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
const prepared = await b.ctx.llm.prepareCall({ provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: brandString<ReasoningEffortId>('off') })
vi.spyOn(b.ctx.llm, 'prepareCall').mockResolvedValueOnce({ ...prepared,
config: { ...prepared.config, reasoningEffort: brandString<ReasoningEffortId>('high') } })
@@ -222,7 +222,7 @@ describe('native Flash translation', () => {
})
it.each(['removed', 'replaced'])('rejects an audit Session %s during paid admission before dispatch', async (kind) => {
const b = await paidFixture(cleanups, { withSession: false })
const b = await paidFixture(cleanups, backend, { withSession: false })
const sessionId = brandString<SessionId>('transient-audit-session')
const scope = b.ctx.plugin({ inject: ['sessions'], apply: (ctx) => { ctx.sessions.create(sessionId) } })
await scope
@@ -246,13 +246,13 @@ describe('native Flash translation', () => {
})
it.each(['max_tokens', 'tool_use'])('rejects non-stop native finish %s while preserving the audited request', async (stop) => {
const b = await paidFixture(cleanups, { reply: (response) => { response.end(sse(replyEvents('partial private output', stop))) } })
const b = await paidFixture(cleanups, backend, { reply: (response) => { response.end(sse(replyEvents('partial private output', stop))) } })
await expect(b.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_INVALID_RESPONSE' })
expect(b.session?.snapshotEvents()).toHaveLength(1)
})
it('classifies native HTTP errors as request failures without forwarding response contents', async () => {
const b = await paidFixture(cleanups, { responseStatus: 503,
const b = await paidFixture(cleanups, backend, { responseStatus: 503,
reply: (response) => { response.end(JSON.stringify({ error: { type: 'api_error', message: 'private backend diagnostic' } })) } })
await expect(b.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_REQUEST_FAILED',
message: 'Native Flash translation request failed' })
@@ -261,7 +261,8 @@ describe('native Flash translation', () => {
})
it.each(['withdrawn', 'catalog', 'credential'])('rejects a native route %s during async preparation before audit or dispatch', async (change) => {
const b = await paidFixture(cleanups), entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups, backend)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const original = b.ctx.llm.prepareCall.bind(b.ctx.llm)
vi.spyOn(b.ctx.llm, 'prepareCall').mockImplementationOnce(async (config, signal) => {
@@ -288,7 +289,8 @@ describe('native Flash translation', () => {
})
it('rejects an Account model-override change during async preparation before audit or dispatch', async () => {
const b = await paidFixture(cleanups), entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups, backend)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const original = b.ctx.llm.prepareCall.bind(b.ctx.llm)
vi.spyOn(b.ctx.llm, 'prepareCall').mockImplementationOnce(async (config, signal) => {
const call = await original(config, signal)
@@ -306,7 +308,7 @@ describe('native Flash translation', () => {
})
it.each(['withdrawn', 'catalog', 'credential'])('rejects a native route %s by an audit observer before dispatch', async (change) => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'official-custom-id')!
let withdrawal: Promise<void> | undefined
b.ctx.on('session/event', (_session, event) => {
@@ -324,18 +326,18 @@ describe('native Flash translation', () => {
})
it('rejects empty text and enforces the complete multibyte output limit', async () => {
const empty = await paidFixture(cleanups, { reply: (response) => { response.end(sse(replyEvents(' '))) } })
const empty = await paidFixture(cleanups, backend, { reply: (response) => { response.end(sse(replyEvents(' '))) } })
await expect(empty.translate('deepseek-account')).rejects.toMatchObject({ code: 'TRANSLATION_INVALID_RESPONSE' })
const exact = await paidFixture(cleanups, { translator: { maxResponseBytes: 3 },
const exact = await paidFixture(cleanups, backend, { translator: { maxResponseBytes: 3 },
reply: (response) => { response.end(sse(replyEvents('中'))) } })
expect(await exact.translate('deepseek-official')).toBe('中')
const short = await paidFixture(cleanups, { translator: { maxResponseBytes: 2 },
const short = await paidFixture(cleanups, backend, { translator: { maxResponseBytes: 2 },
reply: (response) => { response.end(sse(replyEvents('中'))) } })
await expect(short.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_RESPONSE_LIMIT' })
})
it.each(['block-start', 'block-end', 'reasoning-delta', 'tool-call-delta', 'missing-finish'])('rejects unwanted model output %s', async (kind) => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
const prepared = await b.ctx.llm.prepareCall({ provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: brandString<ReasoningEffortId>('off') })
const replacement: PreparedLlmCall = { ...prepared, async *stream() {
if (kind === 'block-start') yield { type: 'block-start', index: 0, blockType: 'reasoning' }
@@ -351,7 +353,7 @@ describe('native Flash translation', () => {
})
it('sanitizes native model errors and does not select another route', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
vi.spyOn(b.ctx.llm, 'prepareCall').mockRejectedValueOnce(new Error('private credentials or original prompt'))
await expect(b.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_REQUEST_FAILED', message: 'Native Flash translation request failed' })
expect(b.requests).toEqual([])
@@ -363,7 +365,7 @@ describe('native Flash translation', () => {
it('preserves caller cancellation, including caller-owned timeouts, and aborts native sockets', async () => {
for (const reason of [new Error('caller cancelled'), new TimeoutReason('TRANSLATION_TIMEOUT', 1)]) {
const received = Promise.withResolvers<undefined>(), closed = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups, { reply(response) {
const b = await paidFixture(cleanups, backend, { reply(response) {
response.on('close', () => { closed.resolve(undefined) })
response.write(sse(replyEvents().slice(0, 2)))
received.resolve(undefined)
@@ -380,11 +382,11 @@ describe('native Flash translation', () => {
})
it('normalizes paid deadlines and waits for accepted calls on translator disposal', async () => {
const expired = await paidFixture(cleanups, { translator: { deepseekTimeoutMs: 40 },
const expired = await paidFixture(cleanups, backend, { translator: { deepseekTimeoutMs: 40 },
reply: (response) => { response.write(sse(replyEvents().slice(0, 2))) } })
await expect(expired.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_TIMEOUT', name: 'TranslationError' })
const received = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups, { reply(response) {
const b = await paidFixture(cleanups, backend, { reply(response) {
response.write(sse(replyEvents().slice(0, 2))); received.resolve(undefined)
} })
const pending = b.translate('deepseek-account')
@@ -396,7 +398,7 @@ describe('native Flash translation', () => {
})
it('covers availability cancellation and quiescent disposal during a pending catalog lookup', async () => {
const b = await paidFixture(cleanups)
const b = await paidFixture(cleanups, backend)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const original = b.ctx.llm.listModels.bind(b.ctx.llm)
vi.spyOn(b.ctx.llm, 'listModels').mockImplementationOnce(async (provider) => {
@@ -415,7 +417,7 @@ describe('native Flash translation', () => {
})
it.each(['owned', 'caller'] as const)('classifies %s discovery deadlines without leaking native details', async (kind) => {
const b = await paidFixture(cleanups, { translator: { deepseekTimeoutMs: 40 } })
const b = await paidFixture(cleanups, backend, { translator: { deepseekTimeoutMs: 40 } })
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
vi.spyOn(b.ctx.llm, 'listModels').mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise; return [] })
const caller = new AbortController(), reason = new TimeoutReason('TRANSLATION_TIMEOUT', 1)
@@ -432,7 +434,7 @@ describe('native Flash translation', () => {
})
it('cancels during native-owner inspection before starting any metadata work', async () => {
const b = await paidFixture(cleanups), caller = new AbortController(), reason = new Error('metadata cancelled')
const b = await paidFixture(cleanups, backend), caller = new AbortController(), reason = new Error('metadata cancelled')
const directory = b.ctx.llm.listConfigurableProviders()
vi.spyOn(b.ctx.llm, 'listConfigurableProviders').mockImplementationOnce(() => { caller.abort(reason); return directory })
const lookup = vi.spyOn(b.ctx.llm, 'listModels')
@@ -441,7 +443,7 @@ describe('native Flash translation', () => {
})
it('cancels a held credential lookup promptly while service disposal still joins it', async () => {
const b = await paidFixture(cleanups), caller = new AbortController(), reason = new Error('credentials observation cancelled')
const b = await paidFixture(cleanups, backend), caller = new AbortController(), reason = new Error('credentials observation cancelled')
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
vi.spyOn(b.ctx.get('credentials')!, 'describe').mockImplementationOnce(async () => {
entered.resolve(undefined); await release.promise; return { configured: true, writable: true }
@@ -70,8 +70,14 @@ export interface RestartOptions {
translator?: Partial<Config>
}
/** Boot actual native provider rows; cleanup is registered as soon as resources exist. */
export async function paidFixture(cleanups: Array<() => Promise<void>>, options: FixtureOptions = {}) {
/**
* Boot actual native provider rows with restartable persistence.
* @param cleanups - owning test's reverse-order cleanup list.
* @param backend - persistence implementation retained across Host restarts.
* @param options - provider, Session, and response choices.
* @returns the real composition and fixture-owned observations.
*/
export async function paidFixture(cleanups: Array<() => Promise<void>>, backend: 'jsonl' | 'sqlite', options: FixtureOptions = {}) {
const root = await mkdtemp(join(tmpdir(), 'dsh-paid-translator-'))
cleanups.push(async () => { await rm(root, { recursive: true, force: true }) })
const previousHome = process.env.DSH_HOME
@@ -129,7 +135,7 @@ export async function paidFixture(cleanups: Array<() => Promise<void>>, options:
const rows = () => [
{ id: 'llm', name: '@deepseek-ai/dsh-llm' },
{ id: 'session', name: '@deepseek-ai/dsh-session' },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, compression: 'none' } },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, storage: backend, compression: 'none' } },
{ id: 'official-custom-id', name: options.officialName ?? '@deepseek-ai/dsh-llm-deepseek-api-key', disabled: !withNativeOwners, config: {
baseURL, apiKeyEnv: 'PAID_TRANSLATION_FIXTURE_KEY', models: options.officialModels ?? [{ id: 'deepseek-flash', name: 'Flash version-independent name' }],
} },
@@ -1,4 +1,4 @@
/** Loader-owned anonymous provider, live Sessions, and restartable real SQLite storage. */
/** Loader-owned anonymous provider, live Sessions, and restartable real persistence. */
import type { Context, Fiber } from '@deepseek-ai/cordis'
import type { ModuleLoaderV2 } from '@deepseek-ai/cordis-plugin-loader'
import { boot } from '@deepseek-ai/dsh-app-boot'
@@ -8,7 +8,7 @@ import type { SessionHandle } from '@deepseek-ai/dsh-session-persistence'
import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import { DatabaseSync } from 'node:sqlite'
import { once } from 'node:events'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { appendFile, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -49,10 +49,11 @@ function mainEvents(): SessionEvent[] {
/**
* Create private, atomically allocated resources and register teardown before use.
* @param cleanups - owning test's reverse-order quiescent cleanup list.
* @param backend - persistence implementation retained across Host restarts.
* @param options - external reply control and optional storage omission.
* @returns the real Host composition, restart operation, and Session/storage observations.
*/
export async function storageFixture(cleanups: Array<() => Promise<void>>, options: StorageFixtureOptions = {}) {
export async function storageFixture(cleanups: Array<() => Promise<void>>, backend: 'jsonl' | 'sqlite', options: StorageFixtureOptions = {}) {
const root = await mkdtemp(join(tmpdir(), 'dsh-translator-storage-'))
cleanups.push(async () => { await rm(root, { recursive: true, force: true }) })
const requests: StorageWireCall[] = [], errors: unknown[] = [], handlers = new Set<Promise<void>>()
@@ -99,7 +100,7 @@ export async function storageFixture(cleanups: Array<() => Promise<void>>, optio
await writeFile(path, JSON.stringify([
...options.withSessions === false ? [] : [{ id: 'sessions', name: '@deepseek-ai/dsh-session' }],
...options.withPersistence === false ? [] : [
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, compression: 'none' } },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, storage: backend, compression: 'none' } },
],
{ id: 'translator', name: '@deepseek-ai/dsh-experimental-translator', config },
]))
@@ -158,7 +159,12 @@ export async function storageFixture(cleanups: Array<() => Promise<void>>, optio
return { id, session, scope, writer, events: await readEvents(id) }
}
return { get ctx() { return ctx }, root, config, requests, errors, readEvents, createSession,
appendStored(id: SessionId, seq: number, payload: string) {
async appendStored(id: SessionId, seq: number, payload: string) {
if (backend === 'jsonl') {
const snapshot = await ctx.sessionPersistence.stat(id)
await appendFile(snapshot!.location!.path, `${payload}\n`)
return
}
const db = new DatabaseSync(join(storedRoot, '.segments', 'sessions.sqlite'))
try {
db.prepare('INSERT INTO events (segment_uuid, seq, payload) SELECT tail_segment_uuid, ?, ? FROM traces WHERE trace_uuid = ?')
@@ -14,9 +14,9 @@ afterEach(async () => {
const identity: TranslationIdentity = { provider: 'bing', text: 'source', sourceLanguage: 'auto', targetLanguage: 'zh', recipe: 'fixture' }
const stages = ['request', 'result'] as const
describe('storage helper failures', () => {
describe.each(['jsonl', 'sqlite'] as const)('storage helper failures (%s)', (backend) => {
it.each(stages)('classifies %s I/O failures before returning them to the consumer', async (stage) => {
const b = await storageFixture(cleanups), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
let observed: unknown
const outcome = await storage.run(original.id, identity, new AbortController().signal, async (log) => {
const seq = stage === 'result' ? await log.request(identity) : SessionSeq(0)
@@ -33,7 +33,7 @@ describe('storage helper failures', () => {
})
it.each(stages)('classifies %s writer failures after its writer is closed', async (stage) => {
const b = await storageFixture(cleanups), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
let observed: unknown
const outcome = await storage.run(original.id, identity, new AbortController().signal, async (log) => {
const seq = stage === 'result' ? await log.request(identity) : SessionSeq(0)
@@ -50,7 +50,7 @@ describe('storage helper failures', () => {
})
it.each(stages)('preserves the exact caller abort reason inside %s', async (stage) => {
const b = await storageFixture(cleanups), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const caller = new AbortController(), reason = { canceled: true }
let observed: unknown
const outcome = await storage.run(original.id, identity, caller.signal, async (log) => {
@@ -11,10 +11,10 @@ afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
})
describe('translation storage lifecycle', () => {
describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)', (backend) => {
it('rejects a canceled queued request promptly without dispatching it', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, { reply: async (call, response) => {
const b = await storageFixture(cleanups, backend, { reply: async (call, response) => {
entered.resolve(undefined); await release.promise; storageReply(call, response)
} })
cleanups.push(async () => { release.resolve(undefined) })
@@ -33,7 +33,7 @@ describe('translation storage lifecycle', () => {
})
it('joins an accepted storage checkpoint after public cancellation on unload', async () => {
const b = await storageFixture(cleanups), original = await b.createSession()
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const flush = b.ctx.sessions.flush.bind(b.ctx.sessions)
@@ -56,7 +56,7 @@ describe('translation storage lifecycle', () => {
})
it('refuses a withdrawn persistence provider after its metadata lookup settles', async () => {
const b = await storageFixture(cleanups), original = await b.createSession()
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const stat = b.ctx.sessionPersistence.stat.bind(b.ctx.sessionPersistence)
@@ -74,7 +74,7 @@ describe('translation storage lifecycle', () => {
it('pins the live Session used by an accepted translation', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, { async reply(call, response) {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
entered.resolve(undefined); await release.promise; storageReply(call, response)
} })
cleanups.push(async () => { release.resolve(undefined) })
@@ -90,7 +90,7 @@ describe('translation storage lifecycle', () => {
})
it('requires an active live writer rather than treating an in-memory append as durable', async () => {
const b = await storageFixture(cleanups), original = await b.createSession(brandString<SessionId>('live-without-writer'), true)
const b = await storageFixture(cleanups, backend), original = await b.createSession(brandString<SessionId>('live-without-writer'), true)
await original.writer?.close()
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_STORAGE_ERROR' })
@@ -99,7 +99,7 @@ describe('translation storage lifecycle', () => {
})
it('refuses a historical Session unavailable after metadata lookup before dispatch', async () => {
const b = await storageFixture(cleanups), original = await b.createSession(SessionId('deleted'), false)
const b = await storageFixture(cleanups, backend), original = await b.createSession(SessionId('deleted'), false)
const stat = b.ctx.sessionPersistence.stat.bind(b.ctx.sessionPersistence)
vi.spyOn(b.ctx.sessionPersistence, 'stat').mockImplementation(async (id, options) => {
const value = await stat(id, options)
@@ -14,9 +14,9 @@ afterEach(async () => {
})
const identity: TranslationIdentity = { provider: 'bing', text: 'source', sourceLanguage: 'auto', targetLanguage: 'zh', recipe: 'fixture' }
describe('accepted translation write settlement', () => {
describe.each(['jsonl', 'sqlite'] as const)('accepted translation write settlement (%s)', (backend) => {
it.each([false, true])('holds identical admission until the accepted result write settles (reject=%s)', async (rejectWrite) => {
const b = await storageFixture(cleanups), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const deadline = Promise.withResolvers<never>()
const stopped = new TranslationError('TRANSLATION_TIMEOUT', 'consumer deadline'), writeFailure = new Error('verification unavailable')
@@ -69,7 +69,7 @@ describe('accepted translation write settlement', () => {
})
it('keeps storage disposal pending until a write outliving its consumer settles', async () => {
const b = await storageFixture(cleanups), original = await b.createSession()
const b = await storageFixture(cleanups, backend), original = await b.createSession()
let storage: TranslationStorage | undefined
const owner = b.ctx.plugin({ apply(ctx: Context) { storage = new TranslationStorage(ctx) } })
await owner.await()
@@ -21,9 +21,9 @@ const identity: TranslationIdentity = { provider: 'bing', text: 'Original paragr
const requests = (events: readonly SessionEvent[]) => events.filter(event => pluginRecordOf(event)?.type === 'plugin:translator/request')
const results = (events: readonly SessionEvent[]) => events.filter(event => pluginRecordOf(event)?.type === 'plugin:translator/result')
describe('durable translation results', () => {
describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)', (backend) => {
it.each(['bing', 'google'] as const)('reuses a %s result after a complete Host restart with zero new HTTP', async (provider) => {
const b = await storageFixture(cleanups), original = await b.createSession()
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const spec = () => b.ctx.translator.resolve({ text: 'Original paragraph', targetLanguage: 'zh', provider, sessionId: original.id })
expect(await b.ctx.translator.translate(spec())).toBe('Stored translation')
const first = await b.readEvents(original.id)
@@ -45,7 +45,7 @@ describe('durable translation results', () => {
it('persists request before dispatch and result before return through the existing live writer', async () => {
let atDispatch: readonly SessionEvent[] = []
const b = await storageFixture(cleanups, { async reply(call, response) {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
atDispatch = await b.readEvents(brandString<SessionId>('stored-translation'))
storageReply(call, response)
} })
@@ -63,7 +63,7 @@ describe('durable translation results', () => {
it('serializes simultaneous identical requests and reuses the first completed result', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, { async reply(call, response) {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
entered.resolve(undefined); await release.promise; storageReply(call, response)
} })
const original = await b.createSession(), spec = b.ctx.translator.resolve({ text: 'Original paragraph', targetLanguage: 'zh', sessionId: original.id })
@@ -81,7 +81,7 @@ describe('durable translation results', () => {
it('lets another Session translate while the first Session provider request is held', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, { async reply(call, response) {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
if (call.text === 'Held source') { entered.resolve(undefined); await release.promise }
storageReply(call, response)
} })
@@ -99,7 +99,7 @@ describe('durable translation results', () => {
it('overlaps different fragments through the same Session writer', async () => {
const release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, { async reply(call, response) {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
await release.promise; storageReply(call, response, `Translation of ${call.text}`)
} })
cleanups.push(async () => { release.resolve(undefined) })
@@ -121,7 +121,7 @@ describe('durable translation results', () => {
it('retains an unmatched failed request and permits a successful retry', async () => {
let fail = true
const b = await storageFixture(cleanups, { reply(call, response) {
const b = await storageFixture(cleanups, backend, { reply(call, response) {
if (fail) { response.writeHead(503); response.end() } else storageReply(call, response)
} })
const original = await b.createSession(), spec = b.ctx.translator.resolve({ text: 'Original paragraph', targetLanguage: 'zh', sessionId: original.id })
@@ -138,7 +138,7 @@ describe('durable translation results', () => {
it('cancels before provider completion and leaves no successful result', async () => {
const entered = Promise.withResolvers<undefined>(), closed = Promise.withResolvers<undefined>()
let held: ServerResponse | undefined
const b = await storageFixture(cleanups, { reply(_call, response) {
const b = await storageFixture(cleanups, backend, { reply(_call, response) {
held = response; response.once('close', () => { closed.resolve(undefined) }); entered.resolve(undefined)
} })
const original = await b.createSession(), caller = new AbortController(), reason = new Error('Stop translation')
@@ -152,7 +152,7 @@ describe('durable translation results', () => {
})
it('separates provider, target, source, text, and effective endpoint recipes', async () => {
const b = await storageFixture(cleanups), original = await b.createSession()
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const base = { text: 'Original paragraph', targetLanguage: 'zh', sessionId: original.id }
for (const selection of [base, { ...base, provider: 'google' as const }, { ...base, targetLanguage: 'ja' },
{ ...base, sourceLanguage: 'en' }, { ...base, text: 'Different paragraph' }]) {
@@ -168,7 +168,7 @@ describe('durable translation results', () => {
})
it('does not change cache identity for provider-owned endpoint query parameters', async () => {
const b = await storageFixture(cleanups), original = await b.createSession()
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const base = { text: 'Original paragraph', targetLanguage: 'zh', sessionId: original.id }
await b.ctx.translator.translate(b.ctx.translator.resolve(base))
const entry = [...b.ctx.loader.entries()].find(row => row.options.id === 'translator')
@@ -180,9 +180,9 @@ describe('durable translation results', () => {
})
})
describe('translation storage guards', () => {
describe.each(['jsonl', 'sqlite'] as const)('translation storage guards (%s)', (backend) => {
it.each([false, true])('refuses uncached inactive Sessions with live store=%s before external I/O or writes', async (withSessions) => {
const b = await storageFixture(cleanups, { withSessions }), original = await b.createSession(brandString<SessionId>('inactive'), false)
const b = await storageFixture(cleanups, backend, { withSessions }), original = await b.createSession(brandString<SessionId>('inactive'), false)
const opened = vi.spyOn(b.ctx.sessionPersistence, 'open')
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_INACTIVE' })
@@ -192,17 +192,17 @@ describe('translation storage guards', () => {
expect(b.ctx.get('sessions')?.list() ?? []).toEqual([])
})
it('refuses missing storage or a missing Session before external I/O', async () => {
const absent = await storageFixture(cleanups, { withPersistence: false })
const absent = await storageFixture(cleanups, backend, { withPersistence: false })
await expect(absent.ctx.translator.translate(absent.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: brandString<SessionId>('missing') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
const b = await storageFixture(cleanups)
const b = await storageFixture(cleanups, backend)
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: brandString<SessionId>('missing') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
expect([...absent.requests, ...b.requests]).toEqual([])
})
it('does not return a provider response when result durability fails', async () => {
const b = await storageFixture(cleanups, { async reply(call, response) {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
await original.writer?.close()
storageReply(call, response)
} })
@@ -221,23 +221,23 @@ describe('translation storage guards', () => {
['result negative zero', 'plugin:translator/result', { requestSeq: -0, text: 'orphan' }],
['result non-text', 'plugin:translator/result', { requestSeq: 0, text: 1 }],
] as const)('refuses persisted %s before provider dispatch', async (_kind, type, data) => {
const b = await storageFixture(cleanups), original = await b.createSession(brandString<SessionId>('malformed'), false)
const b = await storageFixture(cleanups, backend), original = await b.createSession(brandString<SessionId>('malformed'), false)
let record = JSON.stringify({ type, data, seq: original.events.length, time: Date.now(), ignorable: true })
if (_kind === 'result negative zero') record = record.replace('"requestSeq":0', '"requestSeq":-0')
b.appendStored(original.id, original.events.length, record)
await b.appendStored(original.id, original.events.length, record)
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_STORAGE_ERROR' })
expect(b.requests).toEqual([])
})
it('preserves request metadata, ignores unrelated records, and reuses matching success', async () => {
const b = await storageFixture(cleanups), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const request = { ...identity, metadata: { model: 'owned-model', maxTokens: 12 } }
await storage.run(original.id, identity, new AbortController().signal, async (log) => {
const seq = await log.request(request); await log.result(seq, 'Retained result'); return 'Retained result'
})
const saved = await b.readEvents(original.id)
b.appendStored(original.id, saved.length, JSON.stringify({ type: 'plugin:other/unrelated', seq: saved.length, time: Date.now(),
await b.appendStored(original.id, saved.length, JSON.stringify({ type: 'plugin:other/unrelated', seq: saved.length, time: Date.now(),
data: { opaque: true }, ignorable: true }))
const cached = await storage.run(original.id, identity, new AbortController().signal, async () => { throw new Error('Cached translation must skip provider dispatch') })
expect(cached).toBe('Retained result')
@@ -64,7 +64,7 @@ function agentFor(ctx: Context, session: Session): Agent {
return agent
}
async function fixture(options: { cache?: boolean; retainOnArchive?: boolean; maxOutputBytes?: number } = {}) {
async function fixture(backend: 'jsonl' | 'sqlite', options: { cache?: boolean; retainOnArchive?: boolean; maxOutputBytes?: number } = {}) {
const temporary = await realpath(await mkdtemp(join(tmpdir(), 'dsh-worktree-archive-')))
cleanups.push(() => rm(temporary, { recursive: true, force: true }))
const root = await repository(temporary)
@@ -79,7 +79,7 @@ async function fixture(options: { cache?: boolean; retainOnArchive?: boolean; ma
await ctx.plugin(UnusedSandbox)
await ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: root })
await ctx.plugin(WorkingDirectoryService)
await ctx.plugin(SessionPersistence, { root: join(temporary, 'sessions'), compression: 'none' })
await ctx.plugin(SessionPersistence, { root: join(temporary, 'sessions'), compression: 'none', storage: backend })
await ctx.plugin(ArchiveQueries)
await ctx.plugin(Storage)
ctx.storage.backend.register('memory', new MemoryStorageBackend(new MemoryMediaPool()))
@@ -121,9 +121,9 @@ function detachable(f: Fixture, id: string, meta: { cwd?: string }): { session:
return { session, detach }
}
describe('archive-triggered worktree cleanup', () => {
describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup (%s)', (backend) => {
it('removes the clean checkout the archived Session created and keeps its branch and commits', async () => {
const f = await fixture()
const f = await fixture(backend)
await writeFile(join(f.worktree.path, 'local.txt'), 'not pushed\n')
await git(f.worktree.path, 'add', 'local.txt')
await git(f.worktree.path, 'commit', '-m', 'local commit')
@@ -140,7 +140,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('removes a clean checkout whose file listing exceeds maxOutputBytes', async () => {
const f = await fixture({ maxOutputBytes: 1_024 })
const f = await fixture(backend, { maxOutputBytes: 1_024 })
for (let index = 0; index < 64; index++) {
await writeFile(join(f.worktree.path, `file-${String(index).padStart(3, '0')}-${'x'.repeat(24)}.txt`), `${index}\n`)
}
@@ -153,7 +153,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('retains a checkout whose status output exceeds maxOutputBytes instead of failing', async () => {
const f = await fixture({ maxOutputBytes: 1_024 })
const f = await fixture(backend, { maxOutputBytes: 1_024 })
for (let index = 0; index < 64; index++) {
await writeFile(join(f.worktree.path, `untracked-${String(index).padStart(3, '0')}-${'x'.repeat(24)}.txt`), `${index}\n`)
}
@@ -164,7 +164,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('removes a clean checkout when the worktree listing exceeds maxOutputBytes', async () => {
const f = await fixture({ maxOutputBytes: 1_024 })
const f = await fixture(backend, { maxOutputBytes: 1_024 })
for (let index = 0; index < 8; index++) await git(f.root, 'worktree', 'add', '--detach', join(f.temporary, `extra-${index}`))
expect((await git(f.root, 'worktree', 'list', '--porcelain', '-z')).length).toBeGreaterThan(1_024)
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
@@ -173,7 +173,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('returns from admission before the inspection runs', async () => {
const f = await fixture()
const f = await fixture(backend)
const release = Promise.withResolvers<undefined>()
const list = f.ctx.sessionQuery.listSessions.bind(f.ctx.sessionQuery)
vi.spyOn(f.ctx.sessionQuery, 'listSessions').mockImplementation(async (...args) => {
@@ -188,7 +188,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('removes the checkout after the Session moved elsewhere, and the ordinary ensure contract holds afterwards', async () => {
const f = await fixture()
const f = await fixture(backend)
await f.ctx.workingDirectory.set(f.agent, f.root)
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
expect(await settled(f)).toMatchObject({ status: 'removed' })
@@ -203,7 +203,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('retains an untracked file but not ignored files', async () => {
const f = await fixture()
const f = await fixture(backend)
await writeFile(join(f.worktree.path, 'keep.txt'), 'keep')
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
expect(await settled(f)).toMatchObject({ status: 'retained' })
@@ -218,7 +218,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('registers nothing for a Session that created no checkout or only inherited one', async () => {
const f = await fixture()
const f = await fixture(backend)
const other = f.ctx.sessions.create(brandString<SessionId>('no-checkout'), { meta: { cwd: f.root } })
await f.ctx.workspaceRegistry.archiveSession(other.id)
expect(await f.ctx.worktrees.cleanupOf(other, null)).toBeNull()
@@ -232,7 +232,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('retains a checkout while a fork or a directory borrower is unarchived, and does not reconsider when they archive', async () => {
const f = await fixture()
const f = await fixture(backend)
const seed = f.session.snapshotEvents()
const fork = f.ctx.sessions.create(brandString<SessionId>('fork'), {
seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root },
@@ -252,7 +252,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('treats a subagent child beneath the archived Session as archived', async () => {
const f = await fixture()
const f = await fixture(backend)
const child = f.ctx.sessions.create(brandString<SessionId>('child'), {
meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: f.session.id },
})
@@ -266,7 +266,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('retains a checkout for an unrelated subagent child that works inside it', async () => {
const f = await fixture()
const f = await fixture(backend)
const other = f.ctx.sessions.create(brandString<SessionId>('other-parent'), { meta: { cwd: f.root } })
f.ctx.sessions.create(brandString<SessionId>('other-child'), { meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: other.id } })
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
@@ -274,7 +274,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('removes a persisted checkout without loading its Agent, reading cold Sessions from the projection cache when present', async () => {
const f = await fixture({ cache: true })
const f = await fixture(backend, { cache: true })
const owner = detachable(f, 'cold-owner', { cwd: f.root })
const agent = agentFor(f.ctx, owner.session)
const registration = f.ctx.agents.register(agent)
@@ -300,7 +300,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('retains a checkout while a live fork that moved elsewhere still carries its creation', async () => {
const f = await fixture()
const f = await fixture(backend)
const seed = f.session.snapshotEvents()
const fork = f.ctx.sessions.create(brandString<SessionId>('fork-elsewhere'), {
seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root },
@@ -315,7 +315,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('treats a cached cold Session that recorded no directory as working nowhere', async () => {
const f = await fixture({ cache: true })
const f = await fixture(backend, { cache: true })
const nowhere = detachable(f, 'cold-nowhere', {})
await f.ctx.sessionProjectionCache.write(nowhere.session)
await persisted(f, nowhere.session)
@@ -325,7 +325,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('reads a cold Session from its log without the cache', async () => {
const f = await fixture()
const f = await fixture(backend)
const borrower = detachable(f, 'cold-borrower', { cwd: f.worktree.path })
await persisted(f, borrower.session)
borrower.detach()
@@ -335,14 +335,14 @@ describe('archive-triggered worktree cleanup', () => {
})
it('does not wait for the archived Session\'s own stopping work', async () => {
const f = await fixture()
const f = await fixture(backend)
f.ctx.on('workspace/session-activity', async (_request, next) => [{ kind: 'turn' }, ...await next()])
await f.ctx.workspaceRegistry.archiveSession(f.session.id, { stopActivity: true })
expect(await settled(f)).toMatchObject({ status: 'removed' })
})
it('retains a checkout under its creator\'s read-only policy', async () => {
const f = await fixture()
const f = await fixture(backend)
f.session.append('sandbox/mode', { mode: 'read-only' })
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
expect(await settled(f)).toMatchObject({ status: 'retained' })
@@ -350,7 +350,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('keeps the archive and reports a failed removal', async () => {
const f = await fixture()
const f = await fixture(backend)
const warning = vi.spyOn(f.ctx.logger, 'warn').mockImplementation(() => {})
removeCheckout.mockRejectedValue(new Error('checkout removal denied'))
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
@@ -361,7 +361,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('cancels an unadmitted removal on unarchive and waits for an admitted one', async () => {
const f = await fixture()
const f = await fixture(backend)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
removeCheckout.mockImplementation(async (...args) => {
@@ -384,7 +384,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('holds directory entry into a checkout being removed and leaves other paths alone', async () => {
const f = await fixture()
const f = await fixture(backend)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
removeCheckout.mockImplementation(async (...args) => {
@@ -413,7 +413,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('registers nothing for a cold Session without creations and ignores an unarchive without an attempt', async () => {
const f = await fixture()
const f = await fixture(backend)
const cold = detachable(f, 'cold-empty', { cwd: f.root })
await persisted(f, cold.session)
cold.detach()
@@ -426,7 +426,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('retains a checkout for a borrower that appeared between the eligible inspection and the locked recheck', async () => {
const f = await fixture()
const f = await fixture(backend)
const list = f.ctx.sessionQuery.listSessions.bind(f.ctx.sessionQuery)
vi.spyOn(f.ctx.sessionQuery, 'listSessions').mockImplementationOnce(async (...args) => {
const records = await list(...args)
@@ -440,7 +440,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('treats a subagent child whose parent is unknown to the corpus as unarchived', async () => {
const f = await fixture()
const f = await fixture(backend)
f.ctx.sessions.create(brandString<SessionId>('orphan-child'), {
meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: brandString<SessionId>('never-existed') },
})
@@ -449,7 +449,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('skips a creation record whose payload fails validation', async () => {
const f = await fixture()
const f = await fixture(backend)
const handle = await f.ctx.sessionProjections.register(worktreeProjection)
const before = handle.stateOf(f.session).created
appendPluginRecord(f.session, CREATED_RECORD, { path: '', branch: 'x', baseCommit: 'y', repositoryRoot: 'z' })
@@ -457,7 +457,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('registers no attempt while retainOnArchive is set, and resumes once it is cleared', async () => {
const f = await fixture({ retainOnArchive: true })
const f = await fixture(backend, { retainOnArchive: true })
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
expect(await f.ctx.worktrees.cleanupOf(f.session, null)).toBeNull()
await access(f.worktree.path)
@@ -468,7 +468,7 @@ describe('archive-triggered worktree cleanup', () => {
})
it('withdraws listeners before draining, so disposal neither fails unrelated access nor serves a stale result', async () => {
const f = await fixture()
const f = await fixture(backend)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
removeCheckout.mockImplementation(async () => {
@@ -51,7 +51,7 @@ async function loadComposition(configPath: string): Promise<Context> {
return ctx
}
describe('message feedback through a real Loader composition', () => {
describe.each(['jsonl', 'sqlite'] as const)('message feedback through a real Loader composition (%s)', (storage) => {
it('persists canonical feedback across live and cold operations', async () => {
root = await mkdtemp(join(tmpdir(), 'dsh-message-feedback-loader-'))
const configPath = join(root, 'cordis.yml')
@@ -60,6 +60,7 @@ describe('message feedback through a real Loader composition', () => {
"- name: '@deepseek-ai/dsh-session-persistence-jsonl'",
' config:',
` root: ${JSON.stringify(join(root, 'sessions'))}`,
` storage: ${storage}`,
' compression: none',
"- name: '@deepseek-ai/dsh-message-feedback'",
' config:',
@@ -77,7 +78,7 @@ describe('message feedback through a real Loader composition', () => {
const unownedRequest = {
sessionId: unowned.id, messageId: unownedFixture.assistantMessageIds[0], rating: 'positive' as const, ifVersion: null,
}
// A mounted JSONL listener alone does not persist Sessions without a write handle.
// A mounted persistence listener alone does not persist Sessions without a write handle.
await expect(first.messageFeedback.put(unownedRequest)).rejects.toThrow(/not found/u)
expect(await first.sessionPersistence.stat(unowned.id)).toBeUndefined()
const unownedItems = await first.messageFeedback.list({ sessionId: unowned.id })
@@ -15,18 +15,18 @@ afterEach(async () => {
for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true })
})
async function backend(): Promise<Context> {
async function backend(storage: 'jsonl' | 'sqlite'): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
const root = await mkdtemp(join(tmpdir(), 'dsh-llm-retry-jsonl-'))
dirs.push(root)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
return ctx
}
describe('JSONL retry-event persistence', () => {
describe.each(['jsonl', 'sqlite'] as const)('retry-event persistence (%s)', (storage) => {
it('round-trips the event losslessly without adding a model message', async () => {
const ctx = await backend()
const ctx = await backend(storage)
try {
const session = ctx.sessions.create(brandString<SessionId>('retry-jsonl'))
const handle = await ctx.sessionPersistence.create(session.header)
@@ -44,13 +44,13 @@ class ReplyAdapter extends LlmAdapter {
}
/** Schedule service beside a production AgentLoop with one idle Agent that answers through {@link ReplyAdapter}. */
async function setup() {
async function setup(storage: 'jsonl' | 'sqlite') {
const root = await mkdtemp(join(tmpdir(), 'dsh-schedule-notice-'))
roots.push(root)
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'sessions'), compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { storage, root: join(root, 'sessions'), compression: 'none' })
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(Storage)
await ctx.plugin(StorageJson, { root: join(root, 'schedule-storage') })
@@ -74,8 +74,8 @@ function turns(session: Session): number {
return session.snapshotEvents().filter(event => event.type === 'turn/start').length
}
it('adds notices queued while the Agent is idle to the first step of its next turn', async () => {
const { service, adapter, agent } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: adds notices queued while the Agent is idle to the first step of its next turn', async (storage) => {
const { service, adapter, agent } = await setup(storage)
const created = await service.create({
title: 'Standup', prompt: 'Prompt', timing: { kind: 'rrule', rrule: distant }, target: { kind: 'session', sessionId: agent.session.id },
}, brandString<SessionId>('actor'))
@@ -93,8 +93,8 @@ it('adds notices queued while the Agent is idle to the first step of its next tu
])
})
it('adds one step to a turn whose last step was running when a notice arrived', async () => {
const { service, adapter, agent } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: adds one step to a turn whose last step was running when a notice arrived', async (storage) => {
const { service, adapter, agent } = await setup(storage)
// The Agent created the task itself, so only the later edit notifies it.
const created = await service.create({
title: 'Standup', prompt: 'Prompt', timing: { kind: 'rrule', rrule: distant }, target: { kind: 'session', sessionId: agent.session.id },
@@ -26,20 +26,20 @@ afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
})
async function core(persistenceRoot: string) {
async function core(storage: 'jsonl' | 'sqlite', persistenceRoot: string) {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { storage, root: persistenceRoot, compression: 'none' })
await ctx.plugin(AgentLoop, { agents: [] })
return ctx
}
describe('due delivery during Agent creation', () => {
it('enqueues the reminder without starting a turn before every creation listener finishes', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: enqueues the reminder without starting a turn before every creation listener finishes', async (storage) => {
const root = await mkdtemp(join(tmpdir(), 'dsh-schedule-serial-'))
roots.push(root)
const ctx = await core(join(root, 'sessions'))
const ctx = await core(storage, join(root, 'sessions'))
const warnings = vi.spyOn(ctx.logger, 'warn')
await ctx.plugin(Storage)
await ctx.plugin(StorageJson, { root: join(root, 'schedule-storage') })
@@ -48,7 +48,7 @@ try {
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true });
await ctx.plugin(AgentLoop, { agents: [] });
await ctx.plugin(SubagentRuntime);
await ctx.plugin(JsonlSessionPersistence, { root: storageRoot });
await ctx.plugin(JsonlSessionPersistence, { storage: process.argv[1], root: storageRoot });
await new Promise((ready) => setTimeout(ready, 50));
const notifications = [];
@@ -90,8 +90,8 @@ try {
`
describe.skipIf(!existsSync(jsonrpcBundle))('dsh-sdk-jsonrpc-server BUILT scope carrier', () => {
it('preserves parent-scoped completion after child disposal', async () => {
const { stdout, stderr } = await execFileAsync(process.execPath, ['--input-type=module', '-e', builtRuntimeProbe], {
it.each(['jsonl', 'sqlite'] as const)('%s preserves parent-scoped completion after child disposal', async (storage) => {
const { stdout, stderr } = await execFileAsync(process.execPath, ['--input-type=module', '-e', builtRuntimeProbe, storage], {
cwd: repoRoot,
timeout: 15_000,
})
+14 -13
View File
@@ -69,6 +69,7 @@ async function settle(): Promise<void> {
/** Mount the real plugin on a minimal harness with in-memory stdio and exit. */
async function mountPlugin(
storage: 'jsonl' | 'sqlite',
storageDir: string,
options: {
writeDelayMs?: number
@@ -80,7 +81,7 @@ async function mountPlugin(
await mountAgentLoopTestDependencies(ctx)
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { root: storageDir })
await ctx.plugin(JsonlSessionPersistence, { storage, root: storageDir })
await new Promise(resolve => setTimeout(resolve, 50))
await options.beforeServer?.(ctx)
@@ -170,10 +171,10 @@ async function mockCompletionServer(): Promise<{ url: string; requests: unknown[
}
describe('dsh-sdk-jsonrpc-server plugin apply', () => {
it('serves initialize over the injected stdio pair', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: serves initialize over the injected stdio pair', async (storage) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-init-'))
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
const harness = await mountPlugin(storageDir)
const harness = await mountPlugin(storage, storageDir)
try {
harness.send({ jsonrpc: '2.0', id: 'init-1', method: 'initialize', params: { cwd: storageDir, provider: 'deepseek-official', model: 'apply-model' } })
@@ -190,7 +191,7 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it('waits for Loader-owned adapter registration before initialize', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: waits for Loader-owned adapter registration before initialize', async (storage) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-readiness-'))
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
let markStarted!: () => void
@@ -198,7 +199,7 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
const started = new Promise<void>((resolve) => { markStarted = resolve })
const ready = new Promise<void>((resolve) => { release = resolve })
let delayedEntry: Promise<string> | undefined
const harness = await mountPlugin(storageDir, {
const harness = await mountPlugin(storage, storageDir, {
beforeServer: async (ctx) => {
await ctx.plugin(Loader)
ctx.loader.builtins['delayed-readiness'] = {
@@ -245,12 +246,12 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it('drives a session/prompt turn end-to-end and forwards session notifications as output frames', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: drives a session/prompt turn end-to-end and forwards session notifications as output frames', async (storage) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-prompt-'))
const llmServer = await mockCompletionServer()
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
vi.stubEnv('DEEPSEEK_BASE_URL', llmServer.url)
const harness = await mountPlugin(storageDir)
const harness = await mountPlugin(storage, storageDir)
try {
harness.send({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { cwd: storageDir, provider: 'deepseek-official', model: 'dsagent-model' } })
await harness.waitForFrame(frame => frame.id === 1, 'initialize response')
@@ -287,9 +288,9 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it('answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async (storage) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-shutdown-'))
const harness = await mountPlugin(storageDir, { writeDelayMs: 10 })
const harness = await mountPlugin(storage, storageDir, { writeDelayMs: 10 })
try {
// One chunk makes the two deferred exit callbacks race.
const first = { jsonrpc: '2.0', id: 'sd-1', method: 'shutdown' }
@@ -330,9 +331,9 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it('still disposes and exits once when the flush callback fails', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: still disposes and exits once when the flush callback fails', async (storage) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-flush-failure-'))
const harness = await mountPlugin(storageDir, { failFlush: true })
const harness = await mountPlugin(storage, storageDir, { failFlush: true })
try {
harness.send({ jsonrpc: '2.0', id: 'sd-fail', method: 'shutdown' })
@@ -352,9 +353,9 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it('stops serving on a bare fiber dispose (HMR-style unload) without calling exit', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: stops serving on a bare fiber dispose (HMR-style unload) without calling exit', async (storage) => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-dispose-'))
const harness = await mountPlugin(storageDir)
const harness = await mountPlugin(storage, storageDir)
try {
// Prove the handler-rejection path is live before disposal.
harness.send({ jsonrpc: '2.0', id: 'probe-1', method: 'nope/unknown' })
+8 -6
View File
@@ -28,11 +28,11 @@ async function storageRoot(): Promise<string> {
return root
}
async function runtime(root: string, persistence = true, reasoning?: LlmModelReasoningInfo) {
async function mountRuntime(root: string, storage: 'jsonl' | 'sqlite', persistence = true, reasoning?: LlmModelReasoningInfo) {
const ctx = new Context()
cleanups.push(() => ctx.fiber.dispose())
await mountAgentLoopTestDependencies(ctx)
if (persistence) await ctx.plugin(JsonlSessionPersistence, { root })
if (persistence) await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(AgentLoop, { agents: [] })
const adapter = new MockAdapter([textResponse('remembered')], reasoning)
ctx.llm.registerAdapter(['mock'], adapter)
@@ -48,8 +48,8 @@ async function runtime(root: string, persistence = true, reasoning?: LlmModelRea
return { ctx, server, adapter, events }
}
async function initialized(root: string) {
const result = await runtime(root)
async function initializeRuntime(root: string, storage: 'jsonl' | 'sqlite') {
const result = await mountRuntime(root, storage)
await result.server.initialize({ cwd: root, provider: 'mock', model: 'mock' })
return result
}
@@ -62,6 +62,10 @@ class UnusedShell extends ShellExecutor {
override execute(): never { throw new Error('Unexpected shell execution') }
}
describe.each(['jsonl', 'sqlite'] as const)('SDK persisted session resume (%s)', (storage) => {
const runtime = (root: string, persistence = true, reasoning?: LlmModelReasoningInfo) =>
mountRuntime(root, storage, persistence, reasoning)
const initialized = (root: string) => initializeRuntime(root, storage)
async function withPermissions(root: string) {
const result = await initialized(root)
await result.ctx.plugin(SandboxPolicyService, { mode: 'danger-full-access', workspaceRoot: root })
@@ -71,7 +75,6 @@ async function withPermissions(root: string) {
return result
}
describe('SDK persisted session resume', () => {
it.each([undefined, 'danger-full-access'])('applies persisted or explicit permissions before resumed execution: %s', async (permissionMode) => {
const root = await storageRoot()
const sessionId = brandString<SessionId>('saved-permissions')
@@ -144,7 +147,6 @@ describe('SDK persisted session resume', () => {
await expect(server.handleRequest('session/resume', params)).rejects.toThrow('permission_mode')
expect(resume).not.toHaveBeenCalled()
})
it('rejects independent subagent restoration before opening or repairing its log', async () => {
const root = await storageRoot()
const { ctx, server } = await initialized(root)
+4 -3
View File
@@ -89,13 +89,13 @@ async function mockCompletionServer(): Promise<{ url: string; requests: unknown[
return { url: `http://127.0.0.1:${address.port}`, requests, headers }
}
async function makeHarness(storageDir: string, workingDirectory = false) {
async function mountHarness(storageDir: string, storage: 'jsonl' | 'sqlite', workingDirectory = false) {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx, { workingDirectory })
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(JsonlSessionPersistence, { root: storageDir })
await ctx.plugin(JsonlSessionPersistence, { root: storageDir, storage })
await new Promise(resolve => setTimeout(resolve, 50))
return ctx
}
@@ -158,7 +158,8 @@ async function settleSubagent(
}
}
describe('HarnessSdkJsonRpcServer', () => {
describe.each(['jsonl', 'sqlite'] as const)('HarnessSdkJsonRpcServer (%s)', (storage) => {
const makeHarness = (storageDir: string, workingDirectory = false) => mountHarness(storageDir, storage, workingDirectory)
it('reports a nested child creator after disposal when lifecycle dispatch belongs to the Team root', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-nested-creator-'))
const ctx = await makeHarness(storageDir)
+13 -13
View File
@@ -15,14 +15,14 @@ import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-a
import { HarnessSdkJsonRpcServer } from '../src/server.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
async function setup(beforeServer?: (ctx: Context) => void) {
async function setup(storage: 'jsonl' | 'sqlite', beforeServer?: (ctx: Context) => void) {
const root = await mkdtemp(join(tmpdir(), 'dsh-sdk-wait-'))
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
ctx.llm.registerAdapter(['mock'], new MockAdapter(Array.from({ length: 5 }, () => textResponse('answer'))))
beforeServer?.(ctx)
const server = new HarnessSdkJsonRpcServer(ctx, {
@@ -41,8 +41,8 @@ async function setup(beforeServer?: (ctx: Context) => void) {
}
describe('SDK session/wait with parked child input', () => {
it.each([1, 2])('finishes after interrupting a child at depth %s with unclaimed steering', async (depth) => {
const { ctx, server, dispose } = await setup()
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([1, 2]).map(value => [storage, value] as const)))('%s: finishes after interrupting a child at depth %s with unclaimed steering', async (storage, depth) => {
const { ctx, server, dispose } = await setup(storage)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
let closeChildren: (() => Promise<void>) | undefined
@@ -97,8 +97,8 @@ describe('SDK session/wait with parked child input', () => {
})
describe('SDK session/wait failures', () => {
it('keeps an unowned descendant failure separate from the SDK root outcome', async () => {
const { ctx, server, dispose } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: keeps an unowned descendant failure separate from the SDK root outcome', async (storage) => {
const { ctx, server, dispose } = await setup(storage)
try {
await server.prompt({ sessionId: 'main', contentBlocks: [{ type: 'text', text: 'first' }] })
const parent = ctx.agents.get(brandString<SessionId>('main'))!
@@ -132,11 +132,11 @@ describe('SDK session/wait failures', () => {
}
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
['turn/start', 'before'], ['turn/start', 'during'],
['turn/end', 'before'], ['turn/end', 'during'],
] as const)('rejects a later %s failure %s waiting and allows successful recovery', async (failedEvent, timing) => {
const { ctx, server, dispose } = await setup()
] as const).map(value => [storage, ...value] as const)))('%s: rejects a later %s failure %s waiting and allows successful recovery', async (storage, failedEvent, timing) => {
const { ctx, server, dispose } = await setup(storage)
const children = Promise.withResolvers<boolean>()
try {
await server.prompt({ sessionId: 'main', contentBlocks: [{ type: 'text', text: 'first' }] })
@@ -180,8 +180,8 @@ describe('SDK session/wait failures', () => {
}
})
it('leaves a represented turn error in the durable outcome', async () => {
const { ctx, server, dispose } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: leaves a represented turn error in the durable outcome', async (storage) => {
const { ctx, server, dispose } = await setup(storage)
try {
ctx.on('agent/pre-step', () => { throw new Error('represented failure') })
await server.prompt({ sessionId: 'main', contentBlocks: [{ type: 'text', text: 'fail normally' }] })
@@ -194,9 +194,9 @@ describe('SDK session/wait failures', () => {
}
})
it.each([new Error('terminal publication failed'), undefined])('retains an error emitted during terminal publication (%s)', async (failure) => {
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([new Error('terminal publication failed'), undefined]).map(value => [storage, value] as const)))('%s: retains an error emitted during terminal publication (%s)', async (storage, failure) => {
let enabled = true
const { ctx, server, dispose } = await setup((ctx) => {
const { ctx, server, dispose } = await setup(storage, (ctx) => {
ctx.on('session/event', (session, event) => {
if (!enabled || event.type !== 'turn/end') return
const agent = ctx.agents.get(session.id)
@@ -32,13 +32,13 @@ async function temporaryPath(name: string): Promise<string> {
}
describe('dsh-session-query-sqlite real Loader path', () => {
it('unwraps, mounts, and searches the real persistence backend', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: unwraps, mounts, and searches the real persistence backend', async (storage) => {
const persistenceRoot = await temporaryPath('canonical')
const searchPath = await temporaryPath('derived.db')
const ctx = new Context()
await ctx.plugin(SessionProjectionRegistry)
await ctx.plugin(SessionStore)
const persistence = await ctx.plugin(JsonlSessionPersistence, {
const persistence = await ctx.plugin(JsonlSessionPersistence, { storage,
root: persistenceRoot,
compression: 'none',
})
@@ -1801,13 +1801,13 @@ describe('SQLite schema, cancellation, and real persistence integration', () =>
await persistence.dispose()
})
it('combines the real JSONL persistence backend with the real search service keylessly', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: combines the real JSONL persistence backend with the real search service keylessly', async (storage) => {
const persistenceRoot = await temporaryPath('sessions')
const searchPath = await temporaryPath('derived.db')
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(SessionProjectionRegistry)
const persistence = await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
const persistence = await ctx.plugin(JsonlSessionPersistence, { storage, root: persistenceRoot, compression: 'none' })
const search = await ctx.plugin(SqliteSessionQueryEngine, { path: searchPath })
const meta = header('real', 10, { cwd: '/work' })
const writer = await ctx.sessionPersistence.create(meta)
@@ -1828,7 +1828,7 @@ describe('SQLite schema, cancellation, and real persistence integration', () =>
await persistence.dispose()
})
it('reconciles a reopened derived index: unchanged revisions skip reads, another store reloads', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: reconciles a reopened derived index: unchanged revisions skip reads, another store reloads', async (storage) => {
const persistenceRootA = await temporaryPath('sessions-a')
const persistenceRootB = await temporaryPath('sessions-b')
const searchPath = await temporaryPath('derived-collision.db')
@@ -1842,7 +1842,7 @@ describe('SQLite schema, cancellation, and real persistence integration', () =>
const first = new Context()
await first.plugin(SessionStore)
await first.plugin(SessionProjectionRegistry)
const persistenceA = await first.plugin(JsonlSessionPersistence, { root: persistenceRootA, compression: 'none' })
const persistenceA = await first.plugin(JsonlSessionPersistence, { storage, root: persistenceRootA, compression: 'none' })
await storeSession(first, messageEvents('alpha source'))
const openA = vi.spyOn(first.sessionPersistence, 'open')
const searchA = await first.plugin(SqliteSessionQueryEngine, { path: searchPath })
@@ -1855,7 +1855,7 @@ describe('SQLite schema, cancellation, and real persistence integration', () =>
const reopened = new Context()
await reopened.plugin(SessionStore)
await reopened.plugin(SessionProjectionRegistry)
const persistenceAAgain = await reopened.plugin(JsonlSessionPersistence, { root: persistenceRootA, compression: 'none' })
const persistenceAAgain = await reopened.plugin(JsonlSessionPersistence, { storage, root: persistenceRootA, compression: 'none' })
const reopenedOpen = vi.spyOn(reopened.sessionPersistence, 'open')
const searchAAgain = await reopened.plugin(SqliteSessionQueryEngine, { path: searchPath })
await expect(reopened.sessionQuery.searchSessions({ query: 'alpha' }))
@@ -1867,7 +1867,7 @@ describe('SQLite schema, cancellation, and real persistence integration', () =>
const second = new Context()
await second.plugin(SessionStore)
await second.plugin(SessionProjectionRegistry)
const persistenceB = await second.plugin(JsonlSessionPersistence, { root: persistenceRootB, compression: 'none' })
const persistenceB = await second.plugin(JsonlSessionPersistence, { storage, root: persistenceRootB, compression: 'none' })
await storeSession(second, messageEvents('bravo source'))
const openB = vi.spyOn(second.sessionPersistence, 'open')
const searchB = await second.plugin(SqliteSessionQueryEngine, { path: searchPath })
@@ -37,7 +37,7 @@ async function waitForMarker(path: string, expected: string): Promise<string> {
return content
}
async function crashAt(mode: 'request' | 'tool'): Promise<{ root: string; markerText: string }> {
async function crashAt(storage: 'jsonl' | 'sqlite', mode: 'request' | 'tool'): Promise<{ root: string; markerText: string }> {
const root = await mkdtemp(join(tmpdir(), `dsh-semantic-${mode}-`))
roots.push(root)
const marker = join(root, 'failpoint')
@@ -46,7 +46,7 @@ async function crashAt(mode: 'request' | 'tool'): Promise<{ root: string; marker
const expectedMarker = mode === 'request' ? 'request-dispatched' : 'tool-side-effect'
// The SIGKILL-at-failpoint choreography stays custom: the child must die
// mid-write, so no timeout or graceful termination may reach it first.
const child = execa(process.execPath, ['--import', tsxLoader, childScript, mode, root, marker], {
const child = execa(process.execPath, ['--import', tsxLoader, childScript, mode, root, marker, storage], {
cwd: repoRoot,
env: { TSX_TSCONFIG_PATH: join(repoRoot, 'tsconfig.json') },
stdin: 'ignore',
@@ -68,10 +68,10 @@ async function crashAt(mode: 'request' | 'tool'): Promise<{ root: string; marker
// Read the crashed durable log and balance it the way a resuming reader does:
// the stored events stay untouched; `interruptedTurnClosers` supplies the
// in-memory closers for the interrupted tail turn.
async function load(root: string): Promise<SessionEvent[]> {
async function load(storage: 'jsonl' | 'sqlite', root: string): Promise<SessionEvent[]> {
const ctx = new Context()
await ctx.plugin(SessionStore)
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root, storage, compression: 'none' })
try {
const handle = await ctx.sessionPersistence.open(sessionId, 'read')
try {
@@ -90,10 +90,10 @@ afterEach(async () => {
})
describe.skipIf(process.platform === 'win32')('semantic checkpoint hard-crash recovery', () => {
it('persists the complete request before model dispatch', async () => {
const crashed = await crashAt('request')
it.each(['jsonl', 'sqlite'] as const)('%s: persists the complete request before model dispatch', async (storage) => {
const crashed = await crashAt(storage, 'request')
expect(crashed.markerText).toBe('request-dispatched')
const events = await load(crashed.root)
const events = await load(storage, crashed.root)
expect(events.map(event => event.type)).toEqual([
'agent/inbox/spliced', 'turn/start', 'agent/inbox/spliced',
'step/start', 'system/message', 'user/message', 'request/header', 'request/context', 'step/end', 'turn/end',
@@ -103,10 +103,10 @@ describe.skipIf(process.platform === 'win32')('semantic checkpoint hard-crash re
})
})
it('persists tool intent before a side effect and repairs its missing result as unknown', async () => {
const crashed = await crashAt('tool')
it.each(['jsonl', 'sqlite'] as const)('%s: persists tool intent before a side effect and repairs its missing result as unknown', async (storage) => {
const crashed = await crashAt(storage, 'tool')
expect(crashed.markerText).toBe('tool-side-effect')
const events = await load(crashed.root)
const events = await load(storage, crashed.root)
expect(events.some(event => event.type === 'assistant/message')).toBe(true)
expect(events.some(event => event.type === 'tool/call')).toBe(true)
const result = events.find(event => event.type === 'tool/result')
@@ -12,9 +12,9 @@ function waitForCrash(): Promise<never> {
return new Promise(() => { setInterval(() => {}, 60_000) })
}
const [mode, root, marker] = process.argv.slice(2)
if ((mode !== 'request' && mode !== 'tool') || root === undefined || marker === undefined) {
throw new Error('usage: crash-child.ts <request|tool> <persistence-root> <marker>')
const [mode, root, marker, storage] = process.argv.slice(2)
if ((mode !== 'request' && mode !== 'tool') || root === undefined || marker === undefined || (storage !== 'jsonl' && storage !== 'sqlite')) {
throw new Error('usage: crash-child.ts <request|tool> <persistence-root> <marker> <jsonl|sqlite>')
}
const persistenceRoot = root
const failpoint = marker
@@ -39,7 +39,7 @@ class CrashAdapter extends LlmAdapter {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { storage, root: persistenceRoot, compression: 'none' })
await ctx.plugin(checkpointPolicy)
ctx.llm.registerAdapter(['crash'], new CrashAdapter())
ctx.tools.register({
@@ -35,6 +35,7 @@ afterEach(async () => {
/** Boot the official upload route through the Loader with one session-log configuration. */
async function boot(
sessionLog: { enabled: boolean; maxBytes?: number }, mock: MockLlmServerOptions,
storage: 'jsonl' | 'sqlite' = 'jsonl',
): Promise<{ ctx: Context; server: MockLlmServer }> {
root = await mkdtemp(join(tmpdir(), 'dsh-feedback-upload-'))
vi.stubEnv('DSH_HOME', root)
@@ -53,7 +54,7 @@ async function boot(
await writeFile(config, JSON.stringify([...modules.keys()].map(name => ({
name,
...name === '@deepseek-ai/dsh-session-persistence-jsonl'
? { config: { root: join(root!, 'sessions'), compression: 'none' } }
? { config: { root: join(root!, 'sessions'), storage, compression: 'none' } }
: name === '@deepseek-ai/dsh-message-feedback'
? { config: { maxNoteBytes: 1024 } }
: name === '@deepseek-ai/dsh-llm-deepseek-api-key'
@@ -79,8 +80,8 @@ async function boot(
return { ctx, server }
}
it('uploads freeform feedback and message put/edit/delete through the unchanged provider route', async () => {
const { ctx, server } = await boot({ enabled: true }, { sequence: ['invalid_request', 'success', 'success'] })
it.each(['jsonl', 'sqlite'] as const)('uploads freeform feedback and message put/edit/delete through the unchanged provider route (%s)', async (storage) => {
const { ctx, server } = await boot({ enabled: true }, { sequence: ['invalid_request', 'success', 'success'] }, storage)
const session = ctx.sessions.create(brandString<SessionId>('feedback-upload'))
const handle = await ctx.sessionPersistence.create(session.header)
try {
@@ -150,9 +151,9 @@ it('uploads freeform feedback and message put/edit/delete through the unchanged
}
})
it('drains a Session log above the configured maxBytes across consecutive routed requests', async () => {
it.each(['jsonl', 'sqlite'] as const)('drains a Session log above the configured maxBytes across consecutive routed requests (%s)', async (storage) => {
const maxBytes = 4096
const { ctx, server } = await boot({ enabled: true, maxBytes }, { sequence: ['success'], repeatLast: true })
const { ctx, server } = await boot({ enabled: true, maxBytes }, { sequence: ['success'], repeatLast: true }, storage)
const session = ctx.sessions.create(brandString<SessionId>('bounded-upload'))
const handle = await ctx.sessionPersistence.create(session.header)
try {
@@ -173,6 +174,8 @@ it('drains a Session log above the configured maxBytes across consecutive routed
for (const upload of uploads) expect(Buffer.byteLength(JSON.stringify(upload))).toBeLessThanOrEqual(maxBytes)
expect(uploads.flatMap(upload => upload.events).filter(event => event.type !== 'session-log-deepseek/delivery-accepted'))
.toEqual(backlog)
await ctx.sessions.flush(session)
expect((await handle.read()).events).toEqual(session.snapshotEvents())
} finally {
await handle.close()
}
@@ -15,5 +15,9 @@ export const name = 'session-persistence-jsonl-legacy-tests'
* @returns resolves when the JSONL provider and its event routing are available.
*/
export async function apply(ctx: Context, config: Config): Promise<void> {
await persistence.apply(ctx, { ...config, storage: 'jsonl' })
await persistence.apply(ctx, {
root: config.root, storage: 'jsonl',
...config.compression === undefined ? {} : { compression: config.compression },
...config.listConcurrency === undefined ? {} : { listConcurrency: config.listConcurrency },
})
}
@@ -1,7 +1,5 @@
/** SQLite Segment teardown preserves events emitted by an asynchronously disposing injected consumer. */
/** Persistence teardown preserves events emitted by an asynchronously disposing injected consumer. */
import { brandString } from '@deepseek-ai/dsh-brand'
import { DatabaseSync } from 'node:sqlite'
import { z } from 'zod'
import { Context } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import Include from '@deepseek-ai/cordis-plugin-include'
@@ -16,7 +14,7 @@ import { scheduler } from 'node:timers/promises'
import { pathToFileURL } from 'node:url'
import { expect, it } from 'vitest'
it('waits for consumer teardown, persists its final event, and releases listeners and leases', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s waits for consumer teardown, persists its final event, and releases listeners and leases', async (storage) => {
const root = await mkdtemp(join(tmpdir(), 'dsh-jsonl-teardown-'))
const ctx = new Context()
const entered = Promise.withResolvers<undefined>()
@@ -55,7 +53,7 @@ it('waits for consumer teardown, persists its final event, and releases listener
" name: '@deepseek-ai/dsh-session-persistence-jsonl'",
' config:',
` root: ${JSON.stringify(root)}`,
' storage: sqlite',
` storage: ${storage}`,
' compression: none',
'- id: consumer',
' name: async-persistence-consumer',
@@ -91,14 +89,22 @@ it('waits for consumer teardown, persists its final event, and releases listener
const live = session!
const oldReader = await ctx.sessionPersistence.open(live.id, 'read')
const readStored = async (): Promise<unknown[]> => {
const db = new DatabaseSync(join(root, '.segments/sessions.sqlite'))
const readerCtx = new Context()
await readerCtx.plugin(SessionPlugin.default)
await readerCtx.plugin(JsonlPlugin, { root, storage, compression: 'none' })
try {
const header = z.object({ header: z.string() }).parse(db.prepare('SELECT header FROM traces WHERE trace_uuid = ?').get(live.id))
const events = db.prepare('SELECT payload FROM events ORDER BY seq').all()
const metadata: unknown = JSON.parse(header.header)
return [metadata, ...events.map((row): unknown => JSON.parse(z.object({ payload: z.string() }).parse(row).payload))]
} finally { db.close() }
const reader = await readerCtx.sessionPersistence.open(live.id, 'read')
try {
const { events } = await reader.read()
return [reader.header, ...events]
} finally {
await reader.close()
}
} finally {
await readerCtx.fiber.dispose()
}
}
const before = JSON.stringify(await readStored())
expect(before).toContain('turn/start')
expect(before).not.toContain('turn/end')
@@ -62,8 +62,8 @@ async function expectPersistedTitle(ctx: Context, id: SessionId): Promise<void>
}
}
describe('session title persistence round trips', () => {
it('round-trips through a remounted JSONL backend', async () => {
describe.each(['jsonl', 'sqlite'] as const)('session title persistence round trips (%s)', (storage) => {
it('round-trips through a remounted backend', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-title-jsonl-'))
roots.push(root)
const id = brandString<SessionId>('title-jsonl')
@@ -71,7 +71,7 @@ describe('session title persistence round trips', () => {
await writer.plugin(SessionStore)
await writer.plugin(SessionProjectionRegistry)
await writer.plugin(AgentRegistry)
await writer.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await writer.plugin(JsonlSessionPersistence, { root, storage, compression: 'none' })
await writer.plugin(SessionTitleService, CONFIG)
await appendPersistedTitle(writer, id)
await writer.fiber.dispose()
@@ -79,7 +79,7 @@ describe('session title persistence round trips', () => {
const reader = new Context()
await reader.plugin(SessionStore)
await reader.plugin(SessionProjectionRegistry)
await reader.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await reader.plugin(JsonlSessionPersistence, { root, storage, compression: 'none' })
await expectPersistedTitle(reader, id)
await reader.fiber.dispose()
})
@@ -27,11 +27,11 @@ import { MockAdapter, textResponse, toolCallResponse } from '../../../core/agent
* (tool/call + tool/result session events, the generic `ctx.jobs` runtime,
* agent.inject completion notices).
*/
async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: string) {
async function harness(adapter: MockAdapter, sessionRoot?: string, dshHome?: string, storage: 'jsonl' | 'sqlite' = 'jsonl') {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
if (sessionRoot !== undefined) {
await ctx.plugin(JsonlSessionPersistence, { root: sessionRoot, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root: sessionRoot, storage, compression: 'none' })
}
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(LocalJobRegistry)
@@ -139,7 +139,7 @@ describe('bash tool through the agent loop', () => {
}
})
it('first-turn bash receives session identity in a scrubbed DSH_* namespace', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: first-turn bash receives session identity in a scrubbed DSH_* namespace', async (storage) => {
const root = mkdtempSync(join(tmpdir(), 'dsh-bash-session-env-'))
dirs.push(root)
const dshHome = join(root, 'dsh-home')
@@ -151,7 +151,7 @@ describe('bash tool through the agent loop', () => {
}),
textResponse('Session environment inspected.'),
])
const ctx = await harness(adapter, root, dshHome)
const ctx = await harness(adapter, root, dshHome, storage)
const handle = await ctx.agents.create({
sessionId: brandString<SessionId>('session-env-id'),
agentOptions: { provider: 'mock', model: 'mock' },
@@ -20,10 +20,10 @@ type Script = ConstructorParameters<typeof MockAdapter>[0]
* and keeps working itself. This is the multi-provider coexistence the seam
* exists for — the named registry lets one runtime hold both transports.
*/
async function setup(script: Script) {
async function setup(storage: 'jsonl' | 'sqlite', script: Script) {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -39,15 +39,15 @@ function text(blocks: readonly { type: string; text?: string }[]): string {
}
describe('multi-subagent coexistence (spawn + fork on one context)', () => {
it('both providers register and coexist', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: both providers register and coexist', async (storage) => {
const { ctx } = await setup(storage, [])
expect(ctx.subagents.getProvider('fork')).toBeDefined()
expect(ctx.subagents.getProvider('spawn')).toBeDefined()
})
it('the same parent drives a spawn child AND a fork child, then keeps working', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: the same parent drives a spawn child AND a fork child, then keeps working', async (storage) => {
// Script order: parent turn 1, spawn child, fork child, parent turn 2.
const { ctx, parent } = await setup([
const { ctx, parent } = await setup(storage, [
textResponse('parent turn one'),
textResponse('spawn child reply'),
textResponse('fork child reply'),
@@ -25,10 +25,10 @@ const emptyStop: StreamChunk[] = [{ type: 'finish', reason: { kind: 'stop' } }]
/**
* Drives the REAL fork backend with a real loop + scripted mock MODEL.
*/
async function setup(script: Script) {
async function setup(storage: 'jsonl' | 'sqlite', script: Script) {
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -43,8 +43,8 @@ function text(blocks: readonly { type: string; text?: string }[]): string {
}
describe('dsh-subagent-fork-in-process', () => {
it('emits subagent/start only after the seeded child is published', async () => {
const { ctx, parent } = await setup([textResponse('child answer')])
it.each(['jsonl', 'sqlite'] as const)('%s: emits subagent/start only after the seeded child is published', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('child answer')])
let childAtStart: ReturnType<typeof ctx.agents.get>
ctx.on('subagent/start', (info) => {
if (info.provider === 'fork') childAtStart = ctx.agents.get(info.id)
@@ -60,10 +60,10 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('forks an UNSEEDED (fresh) child when the parent has no completed turn', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: forks an UNSEEDED (fresh) child when the parent has no completed turn', async (storage) => {
// The parent has never completed a turn → empty prefix → the provider omits
// the seed → the child runs fresh. Exercises the `seed.length > 0` false arm.
const { ctx, parent } = await setup([textResponse('fresh child')])
const { ctx, parent } = await setup(storage, [textResponse('fresh child')])
const run = await start(ctx, 'fork', { prompt: [{ type: 'text', text: 'child q' }], parent })
const result = await run.result
expect(result.stopReason).toBe('completed')
@@ -76,8 +76,8 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('seeds every completed parent turn through the last turn/end', async () => {
const { ctx, parent } = await setup([textResponse('first'), textResponse('second'), textResponse('child')])
it.each(['jsonl', 'sqlite'] as const)('%s: seeds every completed parent turn through the last turn/end', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('second'), textResponse('child')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } }))
await parent.whenIdle()
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q2' }], source: { kind: 'user' } }))
@@ -94,8 +94,8 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('seeds the child with the parent\'s completed-turn prefix (child inherits context)', async () => {
const { ctx, parent } = await setup([textResponse('parent answer'), textResponse('child answer')])
it.each(['jsonl', 'sqlite'] as const)("%s: seeds the child with the parent's completed-turn prefix (child inherits context)", async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('parent answer'), textResponse('child answer')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
await parent.whenIdle()
const parentPrefixLen = parent.session.snapshotEvents().length
@@ -120,11 +120,11 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('produces a balanced seed: forking mid-turn excludes the open turn', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: produces a balanced seed: forking mid-turn excludes the open turn', async (storage) => {
// Drive the parent so it has one completed turn, then start a SECOND turn that is still
// open (a hanging model call), and fork while it's in flight. The seed must stop after the
// balanced first turn.
const { ctx, parent } = await setup([textResponse('done'), 'hang', textResponse('child')])
const { ctx, parent } = await setup(storage, [textResponse('done'), 'hang', textResponse('child')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q1' }], source: { kind: 'user' } }))
await parent.whenIdle()
// Start a second turn that hangs (open turn/start + open step, never ends).
@@ -147,8 +147,8 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('captures structured output through the shipped plugin (seeded child, driver runtime)', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: captures structured output through the shipped plugin (seeded child, driver runtime)', async (storage) => {
const { ctx, parent } = await setup(storage, [
textResponse('parent turn'),
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 9 }),
])
@@ -166,10 +166,10 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('does NOT return the seeded parent output when the child produces no message of its own', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: does NOT return the seeded parent output when the child produces no message of its own', async (storage) => {
// `readResult` must scan only child-owned events after the seed. The child emits no assistant
// message, so scanning the whole log would incorrectly return the parent's distinctive text.
const { ctx, parent } = await setup([textResponse('parent stale'), emptyStop])
const { ctx, parent } = await setup(storage, [textResponse('parent stale'), emptyStop])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent question' }], source: { kind: 'user' } }))
await parent.whenIdle()
@@ -182,8 +182,8 @@ describe('dsh-subagent-fork-in-process', () => {
await run.dispose()
})
it('advertises every start-time capability', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: advertises every start-time capability', async (storage) => {
const { ctx } = await setup(storage, [])
expect(ctx.subagents.getProvider('fork')!.capabilities).toEqual({
agentOptions: true,
agentPreset: false,
@@ -205,8 +205,8 @@ describe('dsh-subagent-fork-in-process', () => {
expect(ctx.subagents.getProvider('fork')).toBeUndefined()
})
it('contributes the completed-turn prefix as a continuable child\'s seed', async () => {
const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child answer')])
it.each(['jsonl', 'sqlite'] as const)("%s: contributes the completed-turn prefix as a continuable child's seed", async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('parent turn'), textResponse('child answer')])
const provider = ctx.subagents.getProvider('fork')!
const signal = new AbortController().signal
@@ -21,7 +21,7 @@ import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
* work (writes a file). Lives outside the *.e2e.ts pattern so importing it never
* re-registers another file's tests.
*/
export async function spawnHarness(workdir: string): Promise<Context> {
export async function spawnHarness(storage: 'jsonl' | 'sqlite', workdir: string): Promise<Context> {
const ctx = new Context()
// This harness installs only the global default persona, so both parent and
// spawned children render it. It stays neutral for both roles; the
@@ -37,7 +37,7 @@ export async function spawnHarness(workdir: string): Promise<Context> {
await ctx.plugin(BashEnvPlugin)
await ctx.plugin(LocalBashExecutor, { cwd: workdir, timeoutMs: 30_000 })
await ctx.plugin(ToolBash)
await ctx.plugin(JsonlSessionPersistence, { root: join(workdir, '.sessions') })
await ctx.plugin(JsonlSessionPersistence, { storage, root: join(workdir, '.sessions') })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(Spawn, { providerName: 'spawn' })
@@ -21,9 +21,9 @@ afterEach(async () => {
})
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('spawn backend with-key smoke', () => {
it('a parent delegates to a child that writes a file on disk', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a parent delegates to a child that writes a file on disk', async (storage) => {
workdir = await mkdtemp(join(tmpdir(), 'dsh-subagent-spawn-e2e-'))
ctx = await spawnHarness(workdir)
ctx = await spawnHarness(storage, workdir)
const parent = await ctx.agentLoop.create(brandString<SessionId>('e2e-parent'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir })
parent.followup(createUserMessage({
@@ -23,11 +23,11 @@ type Script = ConstructorParameters<typeof MockAdapter>[0]
* The parent is a real config agent; the spawn provider creates a real child
* agent on the same context and we assert its output.
*/
async function setup(script: Script) {
async function setup(storage: 'jsonl' | 'sqlite', script: Script) {
const ctx = new Context()
const adapter = new MockAdapter(script)
await mountAgentLoopTestDependencies(ctx)
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -53,9 +53,9 @@ function disposeChildLifecycle(parent: Agent): void {
}
describe('dsh-subagent-spawn-in-process', () => {
it('runs a fresh child to completion and returns its final assistant output', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: runs a fresh child to completion and returns its final assistant output', async (storage) => {
// One model call for the child: a plain text answer.
const { ctx, parent } = await setup([textResponse('child answer')])
const { ctx, parent } = await setup(storage, [textResponse('child answer')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'do X' }], parent })
const result = await run.result
expect(result.stopReason).toBe('completed')
@@ -63,8 +63,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('emits subagent/start only after the fresh child is published', async () => {
const { ctx, parent } = await setup([textResponse('child answer')])
it.each(['jsonl', 'sqlite'] as const)('%s: emits subagent/start only after the fresh child is published', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('child answer')])
let childAtStart: ReturnType<typeof ctx.agents.get>
ctx.on('subagent/start', (info) => {
if (info.provider === 'spawn') childAtStart = ctx.agents.get(info.id)
@@ -82,8 +82,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('gives the child its OWN session (not the parent\'s), with parentSession lineage', async () => {
const { ctx, parent } = await setup([textResponse('hi')])
it.each(['jsonl', 'sqlite'] as const)("%s: gives the child its OWN session (not the parent's), with parentSession lineage", async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('hi')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await run.result
const child = run.localAgent
@@ -92,9 +92,9 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('a fresh child does NOT inherit the parent conversation (its log starts empty before the prompt)', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a fresh child does NOT inherit the parent conversation (its log starts empty before the prompt)', async (storage) => {
// Drive the parent through one real turn so it has history, THEN spawn.
const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('child sees nothing')])
const { ctx, parent } = await setup(storage, [textResponse('parent turn'), textResponse('child sees nothing')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent prompt' }], source: { kind: 'user' } }))
await parent.whenIdle()
const parentEventCount = parent.session.snapshotEvents().length
@@ -109,8 +109,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('releases the child before delivering its result', async () => {
const { ctx, parent } = await setup([textResponse('x')])
it.each(['jsonl', 'sqlite'] as const)('%s: releases the child before delivering its result', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('x')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
expect(ctx.agents.get(run.id)).toBeDefined()
await run.result
@@ -118,8 +118,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('stamps child depth = parent depth + 1 (via the merged AgentOptions field)', async () => {
const { ctx, parent } = await setup([textResponse('x')])
it.each(['jsonl', 'sqlite'] as const)('%s: stamps child depth = parent depth + 1 (via the merged AgentOptions field)', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('x')])
expect(parent.options.subagentDepth).toBeUndefined()
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await run.result
@@ -128,8 +128,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('refuses to spawn past maxDepth (depthLimit capability)', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: refuses to spawn past maxDepth (depthLimit capability)', async (storage) => {
const { ctx, parent } = await setup(storage, [])
// parent is depth 0, child would be depth 1 — cap at 0 forbids any child.
await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, maxDepth: 0 }))
.rejects.toMatchObject({
@@ -138,18 +138,18 @@ describe('dsh-subagent-spawn-in-process', () => {
})
})
it('maps a child that hit its token ceiling to stopReason "max-tokens"', async () => {
const { ctx, parent } = await setup([maxTokensResponse('cut off')])
it.each(['jsonl', 'sqlite'] as const)('%s: maps a child that hit its token ceiling to stopReason "max-tokens"', async (storage) => {
const { ctx, parent } = await setup(storage, [maxTokensResponse('cut off')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
const result = await run.result
expect(result.stopReason).toBe('max-tokens')
await run.dispose()
})
it('maps a child whose turn errored (script exhausted) to stopReason "error" with empty output', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: maps a child whose turn errored (script exhausted) to stopReason "error" with empty output', async (storage) => {
// Empty script: the child's first model call throws "script exhausted", the
// turn ends `error`, and there is no assistant/message → empty output.
const { ctx, parent } = await setup([])
const { ctx, parent } = await setup(storage, [])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
const result = await run.result
expect(result.stopReason).toBe('error')
@@ -157,20 +157,20 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('rejects without publishing when the request signal is already aborted', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: rejects without publishing when the request signal is already aborted', async (storage) => {
// An already-aborted signal emits no future event, so start must check it before listening and
// settle aborted without running the child. The empty model script proves no turn occurs.
const controller = new AbortController()
controller.abort()
const { ctx, parent } = await setup([])
const { ctx, parent } = await setup(storage, [])
await expect(start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal }))
.rejects.toBe(controller.signal.reason)
})
it('same-tick cancellation rejects start and prevents child publication', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: same-tick cancellation rejects start and prevents child publication', async (storage) => {
// Same-tick cancellation must win before async factory publication: no child may become
// visible, `started` must not fulfill, and the empty script proves no model turn occurs.
const { ctx, parent } = await setup([])
const { ctx, parent } = await setup(storage, [])
const beforeAgents = ctx.agents.list().length
const beforeSessions = ctx.sessions.list().length
const published: string[] = []
@@ -189,10 +189,10 @@ describe('dsh-subagent-spawn-in-process', () => {
expect(published).toEqual([])
})
it('disposing a running child settles the activation as aborted', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: disposing a running child settles the activation as aborted', async (storage) => {
// 'hang' makes the child's model stream one chunk then wait until aborted.
const controller = new AbortController()
const { ctx, parent } = await setup(['hang'])
const { ctx, parent } = await setup(storage, ['hang'])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent, signal: controller.signal })
await new Promise(r => setTimeout(r, 30))
await run.dispose()
@@ -201,8 +201,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('dispose cancels the child and reaches quiescence', async () => {
const { ctx, parent } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: dispose cancels the child and reaches quiescence', async (storage) => {
const { ctx, parent } = await setup(storage, ['hang'])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
await new Promise(r => setTimeout(r, 30))
await run.dispose()
@@ -210,8 +210,8 @@ describe('dsh-subagent-spawn-in-process', () => {
expect(result.stopReason).toBe('aborted')
})
it('the provider supplies fresh local preparation for managed activations', async () => {
const { ctx, parent } = await setup([textResponse('x')])
it.each(['jsonl', 'sqlite'] as const)('%s: the provider supplies fresh local preparation for managed activations', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('x')])
const run = await start(ctx, 'spawn', { prompt: [{ type: 'text', text: 'p' }], parent })
expect('steer' in run).toBe(false)
expect('resume' in run).toBe(false)
@@ -230,8 +230,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('inherits the parent cwd into the child session', async () => {
const { ctx } = await setup([textResponse('x')])
it.each(['jsonl', 'sqlite'] as const)('%s: inherits the parent cwd into the child session', async (storage) => {
const { ctx } = await setup(storage, [textResponse('x')])
// A parent WITH a cwd (config agents have none, so create one explicitly).
const parentHandle = await ctx.agents.create({
sessionId: brandString<SessionId>('cwd-parent-session'),
@@ -246,8 +246,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await parentHandle.dispose()
})
it('uses request.agentOptions.model when the parent has no model of its own', async () => {
const { ctx } = await setup([textResponse('explicit model child')])
it.each(['jsonl', 'sqlite'] as const)('%s: uses request.agentOptions.model when the parent has no model of its own', async (storage) => {
const { ctx } = await setup(storage, [textResponse('explicit model child')])
// A parent with NO model (its own turns would need one supplied per-request).
const parentHandle = await ctx.agents.create({
sessionId: brandString<SessionId>('modelless-parent-session'),
@@ -266,8 +266,8 @@ describe('dsh-subagent-spawn-in-process', () => {
await parentHandle.dispose()
})
it('advertises every start-time capability', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: advertises every start-time capability', async (storage) => {
const { ctx } = await setup(storage, [])
const provider = ctx.subagents.getProvider('spawn')!
expect(provider.capabilities).toEqual({
agentOptions: true,
@@ -290,8 +290,8 @@ describe('dsh-subagent-spawn-in-process', () => {
expect(ctx.subagents.getProvider('spawn')).toBeUndefined()
})
it('captures structured output through the shipped plugin (driver runtime, plugin wiring)', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: captures structured output through the shipped plugin (driver runtime, plugin wiring)', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
])
const run = await start(ctx, 'spawn', {
@@ -306,12 +306,12 @@ describe('dsh-subagent-spawn-in-process', () => {
await run.dispose()
})
it('a backend unload does not revoke an accepted holder-owned run', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a backend unload does not revoke an accepted holder-owned run', async (storage) => {
// Rebuild the stack by hand so we hold the backend's fiber.
const ctx = new Context()
const adapter = new MockAdapter(['hang'])
await mountAgentLoopTestDependencies(ctx)
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -373,8 +373,8 @@ describe('dsh-subagent-spawn-in-process', () => {
expect(typeof unwrapped.apply).toBe('function')
})
it('spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: spawning from a DISPOSING parent fails loud with no orphaned child (INACTIVE_EFFECT teaching error)', async (storage) => {
const { ctx } = await setup(storage, [])
// A handle-owned parent we can dispose (config agents dispose with the loop fiber).
const parentHandle = await ctx.agents.create({
sessionId: brandString<SessionId>('doomed-s'),
@@ -395,8 +395,8 @@ describe('dsh-subagent-spawn-in-process', () => {
expect(published).toEqual([])
})
it('parent disposal during the child setup transaction prevents every publication notification', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: parent disposal during the child setup transaction prevents every publication notification', async (storage) => {
const { ctx } = await setup(storage, [])
const parentHandle = await ctx.agents.create({
sessionId: brandString<SessionId>('setup-race-parent-session'),
agentOptions: { provider: 'mock', model: 'mock' },
@@ -38,11 +38,11 @@ afterEach(async () => {
await rm(workspace, { recursive: true, force: true })
})
async function setupWalled(script: Script): Promise<{ ctx: Context; parent: Agent }> {
async function setupWalled(storage: 'jsonl' | 'sqlite', script: Script): Promise<{ ctx: Context; parent: Agent }> {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx)
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: workspace })
await ctx.plugin(SandboxedFileSystem, { cwd: workspace })
@@ -78,10 +78,10 @@ function toolResultTexts(agent: Agent): string[] {
}
describe('in-process policy inheritance', () => {
it.each(['auto', 'danger-full-access'] as const)(
'records the parent %s identity before publishing a DSH in-process child',
async (preset) => {
const { ctx, parent } = await setupWalled([textResponse('child done')])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['auto', 'danger-full-access'] as const).map(value => [storage, value] as const)))(
'%s: records the parent %s identity before publishing a DSH in-process child',
async (storage, preset) => {
const { ctx, parent } = await setupWalled(storage, [textResponse('child done')])
parent.session.append('permission/preset', { preset })
setSandboxMode(parent.session, 'danger-full-access')
ctx.provide('permissionPresets', {
@@ -103,11 +103,11 @@ describe('in-process policy inheritance', () => {
},
)
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
{ seedPreset: 'auto', preset: 'danger-full-access' },
{ seedPreset: 'danger-full-access', preset: 'auto' },
] as const)('captures $preset before child creation and overrides the $seedPreset fork prefix', async ({ seedPreset, preset }) => {
const { ctx, parent } = await setupWalled([textResponse('child done')])
] as const).map(value => [storage, value] as const)))('%s: captures $preset before child creation and overrides the $seedPreset fork prefix', async (storage, { seedPreset, preset }) => {
const { ctx, parent } = await setupWalled(storage, [textResponse('child done')])
parent.session.append('permission/preset', { preset: seedPreset })
setSandboxMode(parent.session, 'danger-full-access')
const seed = parent.session.snapshotEvents()
@@ -133,9 +133,9 @@ describe('in-process policy inheritance', () => {
}
})
it('records the parent sandbox override and the approval pin before publishing a spawn child', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: records the parent sandbox override and the approval pin before publishing a spawn child', async (storage) => {
const script: Script = []
const { ctx, parent } = await setupWalled(script)
const { ctx, parent } = await setupWalled(storage, script)
const blocked = join(workspace, 'spawn-blocked.txt')
setSandboxMode(parent.session, 'read-only')
// No parent approval override: the child pin must not depend on one.
@@ -201,9 +201,9 @@ describe('in-process policy inheritance', () => {
}
})
it('places inherited events after a fork prefix so fresh policy wins stale seed state', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: places inherited events after a fork prefix so fresh policy wins stale seed state', async (storage) => {
const script: Script = []
const { ctx, parent } = await setupWalled(script)
const { ctx, parent } = await setupWalled(storage, script)
const blocked = join(workspace, 'fork-blocked.txt')
setSandboxMode(parent.session, 'workspace-write')
const seed = parent.session.snapshotEvents()
@@ -236,9 +236,9 @@ describe('in-process policy inheritance', () => {
}
})
it('captures policy at delegation before asynchronous child creation', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: captures policy at delegation before asynchronous child creation', async (storage) => {
const script: Script = [textResponse('child done')]
const { ctx, parent } = await setupWalled(script)
const { ctx, parent } = await setupWalled(storage, script)
setSandboxMode(parent.session, 'read-only')
const starting = startPreparedActivation(spawnRequest(parent), {})
@@ -254,9 +254,9 @@ describe('in-process policy inheritance', () => {
}
})
it('leaves an unswitched sandbox on the deployment default while still pinning approval', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: leaves an unswitched sandbox on the deployment default while still pinning approval', async (storage) => {
const script: Script = []
const { parent } = await setupWalled(script)
const { parent } = await setupWalled(storage, script)
const allowed = join(workspace, 'default-allowed.txt')
script.push(
toolCallResponse('write', 'write', { file_path: allowed, content: 'fine' }),
@@ -278,9 +278,9 @@ describe('in-process policy inheritance', () => {
}
})
it('rejects a child escalation deterministically even when an answerer would allow it', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a child escalation deterministically even when an answerer would allow it', async (storage) => {
const script: Script = []
const { ctx, parent } = await setupWalled(script)
const { ctx, parent } = await setupWalled(storage, script)
// A granting answerer proves the pin resolves before any answerer runs.
let consulted = false
ctx.on('approval/request', () => {
@@ -33,7 +33,7 @@ afterEach(async () => {
/** A host composition carrying no model-facing rows, plus the preset roster. */
async function setupPresetHost(
script: ConstructorParameters<typeof MockAdapter>[0] = [textResponse('parent idle'), textResponse('child done')],
storage: 'jsonl' | 'sqlite', script: ConstructorParameters<typeof MockAdapter>[0] = [textResponse('parent idle'), textResponse('child done')],
): Promise<{ ctx: Context; adapter: MockAdapter; parent: Agent; unregister: Map<string, () => Promise<void>> }> {
const ctx = new Context()
contexts.push(ctx)
@@ -41,7 +41,7 @@ async function setupPresetHost(
await ctx.plugin(Loader)
ctx.loader.builtins.include = Include
await mountAgentLoopTestDependencies(ctx)
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(SubagentRuntime)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(AgentPresets, { default: 'coding' })
@@ -70,8 +70,8 @@ function spawnRequest(parent: Agent) {
}
describe('a child agent composed in-process', () => {
it('reaches the model with its parent\'s preset tools', async () => {
const { adapter, parent } = await setupPresetHost()
it.each(['jsonl', 'sqlite'] as const)("%s: reaches the model with its parent's preset tools", async (storage) => {
const { adapter, parent } = await setupPresetHost(storage)
const run = await startPreparedActivation(spawnRequest(parent), {})
await run.result
@@ -81,8 +81,8 @@ describe('a child agent composed in-process', () => {
await run.dispose()
})
it('carries its parent\'s prompt sections', async () => {
const { parent } = await setupPresetHost()
it.each(['jsonl', 'sqlite'] as const)("%s: carries its parent's prompt sections", async (storage) => {
const { parent } = await setupPresetHost(storage)
const run = await startPreparedActivation(spawnRequest(parent), {})
await run.result
@@ -93,8 +93,8 @@ describe('a child agent composed in-process', () => {
await run.dispose()
})
it('records the composition it ran under on the child header', async () => {
const { parent } = await setupPresetHost()
it.each(['jsonl', 'sqlite'] as const)('%s: records the composition it ran under on the child header', async (storage) => {
const { parent } = await setupPresetHost(storage)
const run = await startPreparedActivation(spawnRequest(parent), {})
await run.result
@@ -105,8 +105,8 @@ describe('a child agent composed in-process', () => {
await run.dispose()
})
it('follows a parent that switched preset while blank', async () => {
const { ctx, adapter, parent } = await setupPresetHost()
it.each(['jsonl', 'sqlite'] as const)('%s: follows a parent that switched preset while blank', async (storage) => {
const { ctx, adapter, parent } = await setupPresetHost(storage)
// A DIFFERENT preset, so the assertion below distinguishes reading the
// parent's live scope chain from reading its creation header — re-linking
// to the same id would pass either way.
@@ -120,8 +120,8 @@ describe('a child agent composed in-process', () => {
await run.dispose()
})
it('registers runtime result tools alongside an independently selected preset', async () => {
const { adapter, parent } = await setupPresetHost([
it.each(['jsonl', 'sqlite'] as const)('%s: registers runtime result tools alongside an independently selected preset', async (storage) => {
const { adapter, parent } = await setupPresetHost(storage, [
toolCallResponse('submit-result', 'structured_output', { answer: 42 }),
])
const run = await startPreparedActivation({
@@ -142,8 +142,8 @@ describe('a child agent composed in-process', () => {
}
})
it('uses the current generation for an explicit same-id selection while omission shares the parent', async () => {
const { ctx, adapter, parent, unregister } = await setupPresetHost()
it.each(['jsonl', 'sqlite'] as const)('%s: uses the current generation for an explicit same-id selection while omission shares the parent', async (storage) => {
const { ctx, adapter, parent, unregister } = await setupPresetHost(storage)
await unregister.get('coding')!()
await ctx.agentPresets.register({
id: 'coding',
@@ -40,13 +40,13 @@ afterEach(async () => {
})
/** Boot the continuable stack plus both policy services the manager consumes opportunistically. */
async function setup(script: Script) {
async function setup(storage: 'jsonl' | 'sqlite', script: Script) {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx)
const root = mkdtempSync(join(tmpdir(), 'dsh-continuation-inherit-'))
roots.push(root)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: root })
await ctx.plugin(ApprovalService)
await ctx.plugin(AgentLoop, { agents: [] })
@@ -89,11 +89,11 @@ function foldedApprovalPolicy(ctx: Context, id: SessionId, events: readonly Sess
}
describe('continuable policy inheritance', () => {
it.each(['auto', 'danger-full-access'] as const)(
'persists the delegated %s identity across cold resume without reading the parent again',
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['auto', 'danger-full-access'] as const).map(value => [storage, value] as const)))(
'%s: persists the delegated %s identity across cold resume without reading the parent again',
{ timeout: 20_000 },
async (preset) => {
const { ctx, parent } = await setup([textResponse('child done'), textResponse('resumed child done')])
async (storage, preset) => {
const { ctx, parent } = await setup(storage, [textResponse('child done'), textResponse('resumed child done')])
parent.session.append('permission/preset', { preset })
setSandboxMode(parent.session, 'danger-full-access')
const current = vi.fn((session: Session) => session === parent.session ? preset : 'custom')
@@ -127,11 +127,11 @@ describe('continuable policy inheritance', () => {
},
)
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
{ seedPreset: 'auto', preset: 'danger-full-access' },
{ seedPreset: 'danger-full-access', preset: 'auto' },
] as const)('captures $preset before child creation and overrides the $seedPreset fork prefix', { timeout: 20_000 }, async ({ seedPreset, preset }) => {
const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('forked child')])
] as const).map(value => [storage, value] as const)))('%s: captures $preset before child creation and overrides the $seedPreset fork prefix', { timeout: 20_000 }, async (storage, { seedPreset, preset }) => {
const { ctx, parent } = await setup(storage, [textResponse('parent turn'), textResponse('forked child')])
parent.session.append('permission/preset', { preset: seedPreset })
setSandboxMode(parent.session, 'danger-full-access')
parent.followup(createUserMessage({
@@ -157,8 +157,8 @@ describe('continuable policy inheritance', () => {
])
})
it('seeds the parent sandbox override and pins approval to never', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('child done')])
it.each(['jsonl', 'sqlite'] as const)('%s: seeds the parent sandbox override and pins approval to never', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('child done')])
setSandboxMode(parent.session, 'danger-full-access')
// No parent approval override: the child pin must not depend on one.
expect(ctx.approval.overrideOf(parent.session)).toBeUndefined()
@@ -194,8 +194,8 @@ describe('continuable policy inheritance', () => {
expect(contextText).toContain('You are a delegated subagent')
})
it('captures policy at delegation before asynchronous child creation', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('child done')])
it.each(['jsonl', 'sqlite'] as const)('%s: captures policy at delegation before asynchronous child creation', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('child done')])
setSandboxMode(parent.session, 'read-only')
const starting = ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' })
@@ -210,8 +210,8 @@ describe('continuable policy inheritance', () => {
expect(foldedSandboxMode(ctx, started.childId, loaded.events)).toBe('read-only')
})
it('leaves an unswitched sandbox on the deployment default while still pinning approval', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('child done')])
it.each(['jsonl', 'sqlite'] as const)('%s: leaves an unswitched sandbox on the deployment default while still pinning approval', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('child done')])
const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' })
await waitNoActivation(ctx, started.childId)
@@ -223,8 +223,8 @@ describe('continuable policy inheritance', () => {
expect(foldedSandboxMode(ctx, started.childId, loaded.events)).toBeNull()
})
it('pins approval after the fork prefix of an unswitched fork child', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('forked child')])
it.each(['jsonl', 'sqlite'] as const)('%s: pins approval after the fork prefix of an unswitched fork child', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('parent turn'), textResponse('forked child')])
parent.followup(createUserMessage({
content: [{ type: 'text', text: 'parent work' }],
source: { kind: 'user' },
@@ -242,8 +242,8 @@ describe('continuable policy inheritance', () => {
expect(foldedSandboxMode(ctx, started.childId, loaded.events)).toBeNull()
})
it('lets a later child-side switch win over the delegation snapshot', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('child done')])
it.each(['jsonl', 'sqlite'] as const)('%s: lets a later child-side switch win over the delegation snapshot', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('child done')])
setSandboxMode(parent.session, 'danger-full-access')
let child: Agent | undefined
ctx.on('agent/created', ({ agent }) => {
@@ -262,8 +262,8 @@ describe('continuable policy inheritance', () => {
expect(foldedSandboxMode(ctx, started.childId, loaded.events)).toBe('read-only')
})
it('cold-resumes on the persisted snapshot without re-capturing the parent', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('first'), textResponse('after resume')])
it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes on the persisted snapshot without re-capturing the parent', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('after resume')])
setSandboxMode(parent.session, 'read-only')
const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' })
await waitNoActivation(ctx, started.childId)
@@ -287,8 +287,8 @@ describe('continuable policy inheritance', () => {
])
})
it('places inherited events after a fork prefix so fresh policy wins stale seed state', { timeout: 20_000 }, async () => {
const { ctx, parent } = await setup([textResponse('parent turn'), textResponse('forked child')])
it.each(['jsonl', 'sqlite'] as const)('%s: places inherited events after a fork prefix so fresh policy wins stale seed state', { timeout: 20_000 }, async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('parent turn'), textResponse('forked child')])
// The stale mode lands inside the completed turn the fork seed replays.
setSandboxMode(parent.session, 'workspace-write')
parent.followup(createUserMessage({
@@ -17,7 +17,7 @@ import SubagentRuntime, { type SubagentRunEndInfo } from '../src/index.ts'
import { loadStoredSession } from './persistence-helpers.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
it('continues the parent through default Messages after a reasoning-bearing continuable child settles', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: continues the parent through default Messages after a reasoning-bearing continuable child settles', async (storage) => {
const root = mkdtempSync(join(tmpdir(), 'dsh-settlement-messages-'))
const ctx = new Context()
let http: Awaited<ReturnType<typeof server>> | undefined
@@ -44,7 +44,7 @@ it('continues the parent through default Messages after a reasoning-bearing cont
prepareExtensions: () => Promise.resolve({ fields: {}, accept: () => Promise.resolve() }),
})
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -39,7 +39,7 @@ afterEach(async () => {
})
/** Real preset mounts, Agent lifecycle, and persistence with a scripted model. */
async function setup(script: ConstructorParameters<typeof MockAdapter>[0] = [textResponse('done'), textResponse('continued'), textResponse('done again')]) {
async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters<typeof MockAdapter>[0] = [textResponse('done'), textResponse('continued'), textResponse('done again')]) {
const root = mkdtempSync(join(tmpdir(), 'dsh-continuation-presets-'))
roots.push(root)
const ctx = new Context()
@@ -48,7 +48,7 @@ async function setup(script: ConstructorParameters<typeof MockAdapter>[0] = [tex
await ctx.plugin(Loader)
ctx.loader.builtins.include = Include
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'sessions') })
await ctx.plugin(JsonlSessionPersistence, { storage, root: join(root, 'sessions') })
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(TestSessionQuery)
const presets = await ctx.plugin(AgentPresets, { default: 'coding' })
@@ -103,8 +103,8 @@ function continueChild(ctx: Context, childId: SessionId) {
}
describe('child preset start validation', () => {
it('rejects an explicit same-as-parent preset before starting a fork', async () => {
const { ctx, parent, adapter } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: rejects an explicit same-as-parent preset before starting a fork', async (storage) => {
const { ctx, parent, adapter } = await setup(storage)
const beforeSessions = ctx.sessions.list().length
const beforeEvents = parent.session.snapshotEvents()
const published: string[] = []
@@ -126,8 +126,8 @@ describe('child preset start validation', () => {
expect(adapter.requests).toEqual([])
})
it('propagates a registry join failure unchanged', async () => {
const { ctx, parent, adapter } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: propagates a registry join failure unchanged', async (storage) => {
const { ctx, parent, adapter } = await setup(storage)
const failure = new Error('Child already joined a preset')
vi.spyOn(ctx.agentPresets, 'composeFrom').mockImplementation(() => { throw failure })
@@ -136,8 +136,8 @@ describe('child preset start validation', () => {
expect(adapter.requests).toEqual([])
})
it('rejects an unknown independent preset with the registry RemoteError as a HarnessError', async () => {
const { ctx, parent, adapter } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: rejects an unknown independent preset with the registry RemoteError as a HarnessError', async (storage) => {
const { ctx, parent, adapter } = await setup(storage)
const failure: unknown = await ctx.subagents.startActivation(startSpec(parent, 'absent')).catch((error: unknown) => error)
expect(failure).toBeInstanceOf(HarnessError)
expect(failure).toMatchObject({ name: 'RemoteError', code: 'agent-preset/not-found', message: 'Unknown agent preset: absent' })
@@ -145,8 +145,8 @@ describe('child preset start validation', () => {
expect(adapter.requests).toEqual([])
})
it('rolls back an independent spawn when the preset service has unloaded', async () => {
const { ctx, parent, adapter, presets } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: rolls back an independent spawn when the preset service has unloaded', async (storage) => {
const { ctx, parent, adapter, presets } = await setup(storage)
await presets.dispose()
expect(ctx.get('agentPresets')).toBeUndefined()
const beforeSessions = ctx.sessions.list().length
@@ -171,8 +171,8 @@ describe('child preset start validation', () => {
})
describe('continuable child presets', () => {
it('records an independent selection before its descriptor and sends only the selected preset tools', async () => {
const { ctx, parent, adapter } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: records an independent selection before its descriptor and sends only the selected preset tools', async (storage) => {
const { ctx, parent, adapter } = await setup(storage)
parkParent(ctx, parent)
const started = await ctx.subagents.startActivation(startSpec(parent, 'reviewing'))
const stored = await settled(ctx, started.childId)
@@ -196,8 +196,8 @@ describe('continuable child presets', () => {
expect(ctx.tools.schemas(parent).map(tool => tool.name)).toEqual(['preset_only'])
})
it('restores an explicit same-as-parent selection after the parent switches and the provider unloads', async () => {
const { ctx, parent, adapter, spawn } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: restores an explicit same-as-parent selection after the parent switches and the provider unloads', async (storage) => {
const { ctx, parent, adapter, spawn } = await setup(storage)
parkParent(ctx, parent)
const started = await ctx.subagents.startActivation(startSpec(parent, 'coding'))
await settled(ctx, started.childId)
@@ -214,8 +214,8 @@ describe('continuable child presets', () => {
expect(ctx.tools.schemas(parent).map(tool => tool.name)).toEqual(['reviewing_only'])
})
it('restores a nested target with its own preset while its creator remains offline', async () => {
const { ctx, parent, adapter } = await setup(['hang', textResponse('leaf'), textResponse('continued')])
it.each(['jsonl', 'sqlite'] as const)('%s: restores a nested target with its own preset while its creator remains offline', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, ['hang', textResponse('leaf'), textResponse('continued')])
parkParent(ctx, parent)
const creator = await ctx.subagents.startActivation(startSpec(parent, 'reviewing'))
const branch = ctx.agents.get(creator.childId)!
@@ -237,8 +237,8 @@ describe('continuable child presets', () => {
expect(ctx.agents.get(creator.childId)).toBeUndefined()
})
it('restores the latest projected selection when it differs from the creation header', async () => {
const { ctx, parent, adapter } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: restores the latest projected selection when it differs from the creation header', async (storage) => {
const { ctx, parent, adapter } = await setup(storage)
parkParent(ctx, parent)
const stopSelecting = ctx.on('agent/created', async ({ agent, source }) => {
if (source === 'startup' && agent.session.header.parentSession === parent.id) {
@@ -258,8 +258,8 @@ describe('continuable child presets', () => {
.toEqual([['reviewing_only'], ['reviewing_only']])
})
it.each([undefined, 'coding'])('restores historical children from their own header preset %s', async (agentPreset) => {
const { ctx, parent, adapter } = await setup()
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([undefined, 'coding']).map(value => [storage, value] as const)))('%s: restores historical children from their own header preset %s', async (storage, agentPreset) => {
const { ctx, parent, adapter } = await setup(storage)
parkParent(ctx, parent)
const childId = brandString<SessionId>('historical-child')
const historical = await ctx.agents.create({
@@ -295,8 +295,8 @@ describe('continuable child presets', () => {
.toContain('Historical child persona.')
})
it('restores a fork from its own later preset selection', async () => {
const { ctx, parent, adapter } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: restores a fork from its own later preset selection', async (storage) => {
const { ctx, parent, adapter } = await setup(storage)
parkParent(ctx, parent)
const stopSelecting = ctx.on('agent/created', async ({ agent, source }) => {
if (source === 'startup' && agent.session.header.parentSession === parent.id) {
@@ -317,8 +317,8 @@ describe('continuable child presets', () => {
.toEqual([['reviewing_only'], ['reviewing_only']])
})
it('rejects a retired preset on resume even while the creator still retains its generation', async () => {
const { ctx, parent, adapter, unregister } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a retired preset on resume even while the creator still retains its generation', async (storage) => {
const { ctx, parent, adapter, unregister } = await setup(storage)
await ctx.agentPresets.select(parent, 'reviewing')
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent work' }], source: { kind: 'user' } }))
await parent.whenIdle()
@@ -335,8 +335,8 @@ describe('continuable child presets', () => {
expect(ctx.tools.schemas(parent).map(tool => tool.name)).toEqual(['reviewing_only'])
})
it.each(['missing', 'broken'] as const)('refuses an independent cold resume when its preset is %s', async (failure) => {
const { ctx, parent, adapter, unregister } = await setup()
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['missing', 'broken'] as const).map(value => [storage, value] as const)))('%s: refuses an independent cold resume when its preset is %s', async (storage, failure) => {
const { ctx, parent, adapter, unregister } = await setup(storage)
parkParent(ctx, parent)
const started = await ctx.subagents.startActivation(startSpec(parent, 'reviewing'))
const created = await settled(ctx, started.childId)
@@ -356,8 +356,8 @@ describe('continuable child presets', () => {
expect(ctx.tools.schemas(parent).map(tool => tool.name)).toEqual(['preset_only'])
})
it('refuses restoration when a recorded preset selection cannot be projected', async () => {
const { ctx, parent, adapter, presets } = await setup()
it.each(['jsonl', 'sqlite'] as const)('%s: refuses restoration when a recorded preset selection cannot be projected', async (storage) => {
const { ctx, parent, adapter, presets } = await setup(storage)
parkParent(ctx, parent)
const started = await ctx.subagents.startActivation(startSpec(parent, 'reviewing'))
await settled(ctx, started.childId)
File diff suppressed because it is too large. Load diff
@@ -37,7 +37,7 @@ afterEach(async () => {
/** Boot the continuable stack with real JSONL session persistence. */
async function setup(
script: Script,
storage: 'jsonl' | 'sqlite', script: Script,
options: { compression?: 'none' | 'zstd' } = {},
) {
const ctx = new Context()
@@ -45,7 +45,7 @@ async function setup(
const root = mkdtempSync(join(tmpdir(), 'dsh-subagent-list-'))
roots.push(root)
const persistence = await ctx.plugin(JsonlSessionPersistence, {
root,
storage, root,
...options.compression === undefined ? {} : { compression: options.compression },
})
persistenceDisposers.push(() => persistence.dispose())
@@ -88,8 +88,8 @@ async function startChild(
}
describe('direct-child catalog reader', () => {
it('lists historical children through a migrated parent while preserving V3 files', async () => {
const { ctx, root } = await setup([], { compression: 'none' })
it.each(['jsonl', 'sqlite'] as const)('%s: lists historical children through a migrated parent while preserving V3 files', async (storage) => {
const { ctx, root } = await setup(storage, [], { compression: 'none' })
const parent = brandString<SessionId>('historical-parent')
const child = brandString<SessionId>('historical-child')
const header = { type: 'session', version: 3, id: parent, createdAt: 1, isSeeded: false, delegationDepth: 0 }
@@ -117,8 +117,8 @@ describe('direct-child catalog reader', () => {
}
})
it('lists settled local children for both delivery modes without corpus or child reads', async () => {
const { ctx, parent } = await setup([textResponse('once'), textResponse('again')])
it.each(['jsonl', 'sqlite'] as const)('%s: lists settled local children for both delivery modes without corpus or child reads', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('once'), textResponse('again')])
const callerOwned = await startTestActivation(ctx, 'spawn', {
prompt: [{ type: 'text', text: 'finish once' }],
agentOptions: { model: 'child-model' },
@@ -144,8 +144,8 @@ describe('direct-child catalog reader', () => {
expect(observeSession).toHaveBeenCalledOnce()
})
it('releases its observation after reading the catalog view', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: releases its observation after reading the catalog view', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const childId = brandString<SessionId>('cold-state-child')
parent.session.append('subagent/catalog', {
version: 0,
@@ -166,8 +166,8 @@ describe('direct-child catalog reader', () => {
expect(dispose).toHaveBeenCalledOnce()
})
it('releases the observation when its catalog projection is unavailable', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: releases the observation when its catalog projection is unavailable', async (storage) => {
const { ctx, parent } = await setup(storage, [])
using observed = await ctx.sessionQuery.observeSession(parent.id, { projectionMode: 'none' })
const dispose = vi.fn()
vi.spyOn(ctx.sessionQuery, 'observeSession').mockResolvedValue({ ...observed, [Symbol.dispose]: dispose })
@@ -177,8 +177,8 @@ describe('direct-child catalog reader', () => {
expect(dispose).toHaveBeenCalledOnce()
})
it('forwards cancellation and preserves query failures', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: forwards cancellation and preserves query failures', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const controller = new AbortController()
controller.abort(new Error('cancel catalog'))
await expect(listChildren(ctx, parent.id, controller.signal)).rejects.toMatchObject({
@@ -285,8 +285,8 @@ function child(id: string, mode: SubagentCatalogEntry['mode'] = 'continuable'):
}
describe('SubagentRuntime.listDescendants', () => {
it('lists external entries as leaves without observing a nonexistent child Session', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: lists external entries as leaves without observing a nonexistent child Session', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const local = ctx.sessions.create(brandString<SessionId>('local-child'))
catalog(parent.session, [child('external-child', 'external'), child('local-child')])
catalog(local, [child('nested-external', 'external')])
@@ -303,8 +303,8 @@ describe('SubagentRuntime.listDescendants', () => {
expect(observe.mock.calls.map(([id]) => id)).toEqual([parent.id, local.id])
})
it('walks parent catalogs in event order without enumerating unrelated Sessions or reading descriptors', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: walks parent catalogs in event order without enumerating unrelated Sessions or reading descriptors', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const branch = ctx.sessions.create(brandString<SessionId>('branch'))
const leaf = ctx.sessions.create(brandString<SessionId>('leaf'))
const sibling = ctx.sessions.create(brandString<SessionId>('sibling'))
@@ -323,8 +323,8 @@ describe('SubagentRuntime.listDescendants', () => {
expect(observeSession.mock.calls.map(([id]) => id)).toEqual([parent.id, branch.id, leaf.id, sibling.id])
})
it('reads a cold child catalog without loading an Agent or requiring a descriptor', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reads a cold child catalog without loading an Agent or requiring a descriptor', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const id = brandString<SessionId>('cold-child')
await seedStoredSession(ctx.sessionPersistence, {
version: SESSION_FORMAT_VERSION, id, createdAt: 1, isSeeded: false,
@@ -338,8 +338,8 @@ describe('SubagentRuntime.listDescendants', () => {
expect(ctx.sessions.get(id)).toBeUndefined()
})
it('traverses one-shot and unknown-mode catalog entries to reach continuable children', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: traverses one-shot and unknown-mode catalog entries to reach continuable children', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const once = ctx.sessions.create(brandString<SessionId>('once'))
const unknown = ctx.sessions.create(brandString<SessionId>('unknown'))
const leaf = ctx.sessions.create(brandString<SessionId>('leaf'))
@@ -353,8 +353,8 @@ describe('SubagentRuntime.listDescendants', () => {
expect(rows[2]).toMatchObject({ kind: 'child', id: leaf.id, parentId: unknown.id, depth: 3 })
})
it('visits each catalog once when persisted membership repeats or cycles', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: visits each catalog once when persisted membership repeats or cycles', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const branch = ctx.sessions.create(brandString<SessionId>('branch'))
const leaf = ctx.sessions.create(brandString<SessionId>('leaf'))
catalog(parent.session, [child('branch'), child('leaf')])
@@ -366,13 +366,13 @@ describe('SubagentRuntime.listDescendants', () => {
expect(observe).toHaveBeenCalledTimes(3)
})
it('returns no descendants from an empty root catalog', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: returns no descendants from an empty root catalog', async (storage) => {
const { ctx, parent } = await setup(storage, [])
expect(await ctx.subagents.listDescendants(parent.id)).toEqual([])
})
it('omits an ordinary Session fork and its cataloged children from the source listing', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: omits an ordinary Session fork and its cataloged children from the source listing', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const fork = ctx.sessions.fork(parent.session, undefined, brandString<SessionId>('ordinary-fork'))
const leaf = ctx.sessions.create(brandString<SessionId>('fork-child'))
catalog(fork, [child('fork-child')])
@@ -384,13 +384,13 @@ describe('SubagentRuntime.listDescendants', () => {
])
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
['corrupt', Object.assign(new Error('corrupt branch'), { code: 'SESSION_QUERY_CORRUPT_SESSION' })],
['corrupt', Object.assign(new Error('conflicting branch'), { code: 'SESSION_QUERY_SOURCE_CONFLICT' })],
['unavailable', new Error('unavailable branch')],
['unavailable', 'unavailable branch'],
] as const)('contains a %s branch read failure and continues with siblings', async (reason, failure) => {
const { ctx, parent } = await setup([])
] as const).map(value => [storage, ...value] as const)))('%s: contains a %s branch read failure and continues with siblings', async (storage, reason, failure) => {
const { ctx, parent } = await setup(storage, [])
const branch = ctx.sessions.create(brandString<SessionId>('branch'))
const hidden = ctx.sessions.create(brandString<SessionId>('hidden'))
const sibling = ctx.sessions.create(brandString<SessionId>('sibling'))
@@ -410,8 +410,8 @@ describe('SubagentRuntime.listDescendants', () => {
expect(rows.some(row => row.id === hidden.id)).toBe(false)
})
it('reports invalid live catalog data as corrupt and continues with siblings', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reports invalid live catalog data as corrupt and continues with siblings', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const branch = ctx.sessions.create(brandString<SessionId>('branch'))
const sibling = ctx.sessions.create(brandString<SessionId>('sibling'))
catalog(parent.session, [child('branch'), child('sibling')])
@@ -424,16 +424,16 @@ describe('SubagentRuntime.listDescendants', () => {
])
})
it('reports a missing child as unavailable', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reports a missing child as unavailable', async (storage) => {
const { ctx, parent } = await setup(storage, [])
catalog(parent.session, [child('missing')])
expect(await ctx.subagents.listDescendants(parent.id)).toEqual([
{ kind: 'diagnostic', id: brandString<SessionId>('missing'), parentId: parent.id, depth: 1, reason: 'unavailable' },
])
})
it('propagates root read failures and missing catalog projections', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: propagates root read failures and missing catalog projections', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const observe = ctx.sessionQuery.observeSession.bind(ctx.sessionQuery)
const failure = new Error('root unavailable')
vi.spyOn(ctx.sessionQuery, 'observeSession').mockRejectedValueOnce(failure)
@@ -456,8 +456,8 @@ describe('SubagentRuntime.listDescendants', () => {
await expect(ctx.subagents.listDescendants(brandString<SessionId>('root'))).rejects.toMatchObject({ code: 'SUBAGENT_CONTROL_QUERY_UNAVAILABLE' })
})
it('cancels before observing the root', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: cancels before observing the root', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const controller = new AbortController()
controller.abort()
const observe = vi.spyOn(ctx.sessionQuery, 'observeSession')
@@ -465,8 +465,8 @@ describe('SubagentRuntime.listDescendants', () => {
expect(observe).not.toHaveBeenCalled()
})
it.each([false, true])('cancels the traversal when a branch read settles (failure: %s)', async (reject) => {
const { ctx, parent } = await setup([])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: cancels the traversal when a branch read settles (failure: %s)', async (storage, reject) => {
const { ctx, parent } = await setup(storage, [])
const branch = ctx.sessions.create(brandString<SessionId>('branch'))
catalog(parent.session, [child('branch')])
const controller = new AbortController()
@@ -11,16 +11,17 @@ import { onTestFinished } from 'vitest'
/**
* Mount isolated persistence and remove it after the context reaches quiescence.
* @param storage - session backend for this test case.
* @param ctx - test runtime that owns the local child sessions.
*/
export async function mountLocalActivations(ctx: Context): Promise<void> {
export async function mountLocalActivations(storage: 'jsonl' | 'sqlite', ctx: Context): Promise<void> {
await mountWorkingDirectoryFixture(ctx)
const root = await mkdtemp(join(tmpdir(), 'dsh-local-activation-'))
onTestFinished(async () => {
await ctx.fiber.dispose()
await rm(root, { recursive: true, force: true })
})
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
}
/**
@@ -13,9 +13,9 @@ import SubagentRuntime from '../src/index.ts'
import { mountLocalActivations } from './local-activation.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
it.each(['absent', 'unused'] as const)('returns the closing answer when send_message is %s', async (availability) => {
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['absent', 'unused'] as const).map(value => [storage, value] as const)))('%s: returns the closing answer when send_message is %s', async (storage, availability) => {
const ctx = new Context()
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
@@ -42,9 +42,9 @@ it.each(['absent', 'unused'] as const)('returns the closing answer when send_mes
}
})
it('delivers structured output to the parent when the child has send_message', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: delivers structured output to the parent when the child has send_message', async (storage) => {
const ctx = new Context()
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
@@ -39,7 +39,7 @@ afterEach(async () => {
})
/** One host carrying the real Schedule service and a preset that mounts the real tools. */
async function setupScheduleHost(): Promise<{ ctx: Context; parent: Agent; dispatched: ReturnType<typeof vi.fn> }> {
async function setupScheduleHost(storage: 'jsonl' | 'sqlite' ): Promise<{ ctx: Context; parent: Agent; dispatched: ReturnType<typeof vi.fn> }> {
const ctx = new Context()
contexts.push(ctx)
const root = mkdtempSync(join(tmpdir(), 'dsh-schedule-tools-'))
@@ -48,7 +48,7 @@ async function setupScheduleHost(): Promise<{ ctx: Context; parent: Agent; dispa
await ctx.plugin(Loader)
ctx.loader.builtins.include = Include
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(Storage)
const pool = new MemoryMediaPool()
const backend = new MemoryStorageBackend(pool)
@@ -93,8 +93,8 @@ function toolResultTexts(agent: Agent): string[] {
}
describe('a delegated child under a preset that mounts the Schedule tools', () => {
it('sees the four tools and is refused with subagent_session without storing a task', async () => {
const { ctx, parent, dispatched } = await setupScheduleHost()
it.each(['jsonl', 'sqlite'] as const)('%s: sees the four tools and is refused with subagent_session without storing a task', async (storage) => {
const { ctx, parent, dispatched } = await setupScheduleHost(storage)
const run = await ctx.subagents.startActivation({
provider: 'spawn',
label: 'child task',
@@ -60,13 +60,13 @@ afterEach(async () => {
})
/** Boot persistence, the Agent loop, one spawn provider, and the routed model. */
async function setup(replies: Record<string, Reply[]>, maxActiveSubagents = 16) {
async function setup(storage: 'jsonl' | 'sqlite', replies: Record<string, Reply[]>, maxActiveSubagents = 16) {
const ctx = new Context()
disposers.push(() => ctx.fiber.dispose())
await mountAgentLoopTestDependencies(ctx)
const root = mkdtempSync(join(tmpdir(), 'dsh-subagent-siblings-'))
roots.push(root)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(TestSessionQuery)
await mountWorkingDirectoryFixture(ctx)
@@ -129,8 +129,8 @@ function textOf(event: SessionEvent<'user/message'>): string {
}
describe('subagent sibling messages', () => {
it('keeps duplicate descriptions as display text and names siblings uniquely', async () => {
const { ctx, parent } = await setup({ a: ['hang'], b: [textResponse('done'), textResponse('resumed')] })
it.each(['jsonl', 'sqlite'] as const)('%s: keeps duplicate descriptions as display text and names siblings uniquely', async (storage) => {
const { ctx, parent } = await setup(storage, { a: ['hang'], b: [textResponse('done'), textResponse('resumed')] })
const a = await start(ctx, parent, 'a')
const sender = await running(ctx, a)
const b = await start(ctx, parent, 'b')
@@ -151,8 +151,8 @@ describe('subagent sibling messages', () => {
await settled(ctx, a)
})
it('keeps unrelated parents outside sibling delivery even when descriptions match', async () => {
const { ctx, parent } = await setup({ a: ['hang'], b: [textResponse('done'), textResponse('reply')] })
it.each(['jsonl', 'sqlite'] as const)('%s: keeps unrelated parents outside sibling delivery even when descriptions match', async (storage) => {
const { ctx, parent } = await setup(storage, { a: ['hang'], b: [textResponse('done'), textResponse('reply')] })
const other = await ctx.agentLoop.create(brandString<SessionId>('other-parent'), { provider: 'mock', model: 'mock' })
const a = await start(ctx, parent, 'a')
const sender = await running(ctx, a)
@@ -168,8 +168,8 @@ describe('subagent sibling messages', () => {
describe('tree-wide messages', () => {
it('keeps ordinary forks independent and rejects stale callers or broken ancestry', async () => {
const { ctx, parent } = await setup({})
it.each(['jsonl', 'sqlite'] as const)('%s: keeps ordinary forks independent and rejects stale callers or broken ancestry', async (storage) => {
const { ctx, parent } = await setup(storage, {})
expect(ctx.subagents.rootOf(parent)).toBe(parent)
expect(() => ctx.subagents.rootOf({ ...parent })).toThrow(expect.objectContaining({ code: 'UNAUTHORIZED' }))
const source = ctx.sessions.create(brandString<SessionId>('fork-source'), { meta: { origin: 'subagent', parentSession: parent.id } })
@@ -192,8 +192,8 @@ describe('tree-wide messages', () => {
}
})
it('delivers across branches, to deeper descendants, and back to the Lead', async () => {
const { ctx, parent } = await setup({ a: ['hang'], b: ['hang'], leaf: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: delivers across branches, to deeper descendants, and back to the Lead', async (storage) => {
const { ctx, parent } = await setup(storage, { a: ['hang'], b: ['hang'], leaf: ['hang'] })
const a = await start(ctx, parent, 'a')
const sender = await running(ctx, a)
const b = await start(ctx, parent, 'b')
@@ -220,8 +220,8 @@ describe('tree-wide messages', () => {
await expect(ctx.subagents.sendMessage(sender, a, [], { signal })).rejects.toMatchObject({ code: 'UNAUTHORIZED' })
})
it('restores only the target within subagent tree capacity while its creator remains offline', async () => {
const { ctx, parent, adapter } = await setup({
it.each(['jsonl', 'sqlite'] as const)('%s: restores only the target within subagent tree capacity while its creator remains offline', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, {
a: ['hang'], branch: ['hang'], leaf: [textResponse('first'), textResponse('reply')],
}, 2)
const branchId = await start(ctx, parent, 'branch')
@@ -249,8 +249,8 @@ describe('tree-wide messages', () => {
expect(branchMessages.some(event => textOf(event).includes('cold cousin'))).toBe(false)
})
it('rechecks the sender after asynchronous target discovery', async () => {
const { ctx, parent } = await setup({ a: ['hang'], b: [textResponse('done'), textResponse('reply')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rechecks the sender after asynchronous target discovery', async (storage) => {
const { ctx, parent } = await setup(storage, { a: ['hang'], b: [textResponse('done'), textResponse('reply')] })
const a = await start(ctx, parent, 'a')
const sender = await running(ctx, a)
const b = await start(ctx, parent, 'b')
@@ -273,8 +273,8 @@ describe('tree-wide messages', () => {
query.mockRestore()
}
})
it('leaves the offline creator untouched when target history cannot be read', async () => {
const { ctx, parent } = await setup({ branch: ['hang'], leaf: [textResponse('done')] })
it.each(['jsonl', 'sqlite'] as const)('%s: leaves the offline creator untouched when target history cannot be read', async (storage) => {
const { ctx, parent } = await setup(storage, { branch: ['hang'], leaf: [textResponse('done')] })
const branchId = await start(ctx, parent, 'branch')
const branch = await running(ctx, branchId)
const leafId = await start(ctx, branch, 'leaf')
@@ -291,8 +291,8 @@ describe('tree-wide messages', () => {
expect(ctx.agents.get(leafId)).toBeUndefined()
})
it.each(['missing', 'cyclic'] as const)('rejects %s creation evidence before restoring a target', async (evidence) => {
const { ctx, parent } = await setup({ branch: ['hang'], leaf: [textResponse('done')] })
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['missing', 'cyclic'] as const).map(value => [storage, value] as const)))('%s: rejects %s creation evidence before restoring a target', async (storage, evidence) => {
const { ctx, parent } = await setup(storage, { branch: ['hang'], leaf: [textResponse('done')] })
const branchId = await start(ctx, parent, 'branch')
const branch = await running(ctx, branchId)
const leafId = await start(ctx, branch, 'leaf')
@@ -316,8 +316,8 @@ describe('tree-wide messages', () => {
}
})
it('rejects a replaced root after asynchronous target discovery', async () => {
const { ctx, parent } = await setup({ a: ['hang'], b: [textResponse('done'), textResponse('reply')] })
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a replaced root after asynchronous target discovery', async (storage) => {
const { ctx, parent } = await setup(storage, { a: ['hang'], b: [textResponse('done'), textResponse('reply')] })
const a = await start(ctx, parent, 'a')
const sender = await running(ctx, a)
const b = await start(ctx, parent, 'b')
@@ -342,8 +342,8 @@ describe('tree-wide messages', () => {
}
})
it.each([false, true])('restores the target while its creator is still closing (cleanup failure=%s)', async (failCleanup) => {
const { ctx, parent } = await setup({ branch: ['hang'], leaf: [textResponse('first'), textResponse('reply')] })
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: restores the target while its creator is still closing (cleanup failure=%s)', async (storage, failCleanup) => {
const { ctx, parent } = await setup(storage, { branch: ['hang'], leaf: [textResponse('first'), textResponse('reply')] })
const branchId = await start(ctx, parent, 'branch')
const branch = await running(ctx, branchId)
const leafId = await start(ctx, branch, 'leaf')
@@ -379,8 +379,8 @@ describe('tree-wide messages', () => {
})
describe('agent names', () => {
it('records requested and default names and rejects duplicates and invalid names before startup', async () => {
const { ctx, parent, adapter } = await setup({ a: ['hang'], b: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: records requested and default names and rejects duplicates and invalid names before startup', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, { a: ['hang'], b: ['hang'] })
const reviewer = await startNamed(ctx, parent, 'a', 'reviewer')
const unnamed = await startNamed(ctx, parent, 'b')
expect([reviewer.name, unnamed.name]).toEqual(['reviewer', 'agent-1'])
@@ -399,8 +399,8 @@ describe('agent names', () => {
}
})
it('holds a requested name across concurrent startup and releases it when startup fails', async () => {
const { ctx, parent } = await setup({ a: ['hang'], b: ['hang'], c: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: holds a requested name across concurrent startup and releases it when startup fails', async (storage) => {
const { ctx, parent } = await setup(storage, { a: ['hang'], b: ['hang'], c: ['hang'] })
const first = startNamed(ctx, parent, 'a', 'worker')
const concurrent = startNamed(ctx, parent, 'c')
await expect(startNamed(ctx, parent, 'b', 'worker')).rejects.toMatchObject({ code: 'DUPLICATE_AGENT_NAME' })
@@ -417,8 +417,8 @@ describe('agent names', () => {
}
})
it('names nested members by path and resolves names without granting authority', async () => {
const { ctx, parent } = await setup({ branch: ['hang'], leaf: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: names nested members by path and resolves names without granting authority', async (storage) => {
const { ctx, parent } = await setup(storage, { branch: ['hang'], leaf: ['hang'] })
const branch = await startNamed(ctx, parent, 'branch', 'reviewer')
const branchAgent = await running(ctx, branch.childId)
const leaf = await startNamed(ctx, branchAgent, 'leaf', 'checker')
@@ -441,8 +441,8 @@ describe('agent names', () => {
await settled(ctx, leaf.childId)
})
it('restores a cold member\'s path from the catalogs along its creation chain', async () => {
const { ctx, parent } = await setup({ branch: ['hang'], leaf: [textResponse('first'), 'hang'] })
it.each(['jsonl', 'sqlite'] as const)("%s: restores a cold member's path from the catalogs along its creation chain", async (storage) => {
const { ctx, parent } = await setup(storage, { branch: ['hang'], leaf: [textResponse('first'), 'hang'] })
const branch = await startNamed(ctx, parent, 'branch', 'reviewer')
const branchAgent = await running(ctx, branch.childId)
const leaf = await startNamed(ctx, branchAgent, 'leaf', 'checker')
@@ -457,8 +457,8 @@ describe('agent names', () => {
await settled(ctx, leaf.childId)
})
it('addresses members below an unnamed historical creator by Session id', async () => {
const { ctx, parent } = await setup({ legacy: ['hang'], leaf: ['hang'] })
it.each(['jsonl', 'sqlite'] as const)('%s: addresses members below an unnamed historical creator by Session id', async (storage) => {
const { ctx, parent } = await setup(storage, { legacy: ['hang'], leaf: ['hang'] })
const legacy = await ctx.agentLoop.create(brandString<SessionId>('legacy-child'), { provider: 'mock', model: 'mock' })
bindSubagentActivation(ctx, legacy, parent)
expect(ctx.subagents.namesOf(legacy)).toEqual({ self: 'legacy-child', parent: 'lead' })
@@ -47,7 +47,7 @@ const SCHEMA: ObjectJsonSchema = {
/**
* Real loop and local preparation isolate activation-scoped structured output.
*/
async function setup(script: Script, options: SetupOptions = {}) {
async function setup(storage: 'jsonl' | 'sqlite', script: Script, options: SetupOptions = {}) {
const ctx = new Context()
const adapter = new MockAdapter(script)
await mountAgentLoopTestDependencies(ctx, {
@@ -61,7 +61,7 @@ async function setup(script: Script, options: SetupOptions = {}) {
run: options.codeRun ?? (() => Promise.resolve({ output: [] })),
} as never)
}
await mountLocalActivations(ctx)
await mountLocalActivations(storage, ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -112,8 +112,8 @@ function deliverInput(
}
describe('in-process structured output', () => {
it.each(['steer', 'queue'] as const)('consumes accepted %s input before committing a structured result', async (delivery) => {
const { ctx, parent, adapter } = await setup([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['steer', 'queue'] as const).map(value => [storage, value] as const)))('%s: consumes accepted %s input before committing a structured result', async (storage, delivery) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('before-input', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
...delivery === 'queue' ? [textResponse('Ready for the queued correction.')] : [],
toolCallResponse('after-input', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
@@ -149,13 +149,13 @@ describe('in-process structured output', () => {
}
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
{ toolMode: 'native', blocked: false },
{ toolMode: 'native', blocked: true },
{ toolMode: 'ptc', blocked: false },
{ toolMode: 'ptc', blocked: true },
] as const)('closes input through $toolMode result policy and reopens only after rejection ($blocked)', async ({ toolMode, blocked }) => {
const { ctx, parent } = await setup(['hang'], {
] as const).map(value => [storage, value] as const)))('%s: closes input through $toolMode result policy and reopens only after rejection ($blocked)', async (storage, { toolMode, blocked }) => {
const { ctx, parent } = await setup(storage, ['hang'], {
toolMode,
codeRun: async (request) => {
const capture = request.bindings.at(0)?.functions[STRUCTURED_OUTPUT_TOOL]
@@ -203,8 +203,8 @@ describe('in-process structured output', () => {
expect((await run.result).structured).toEqual(blocked ? undefined : { answer: 42 })
})
it('captures a valid structured_output call and surfaces result.structured', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: captures a valid structured_output call and surfaces result.structured', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 42, note: 'done' }),
])
let acknowledgement: unknown
@@ -219,8 +219,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('stops the turn after a successful capture — no extra model step is spent', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: stops the turn after a successful capture — no extra model step is spent', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
textResponse('MUST NOT BE CONSUMED'),
])
@@ -231,7 +231,7 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('denies tool calls that FOLLOW the capture in the same response — terminal means terminal', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: denies tool calls that FOLLOW the capture in the same response — terminal means terminal', async (storage) => {
// One model response carrying structured_output FIRST and a side-effecting
// call after it: the continuation veto only fires at step end, so without
// the pre-execute deny the trailing call would still run after the final
@@ -243,7 +243,7 @@ describe('in-process structured output', () => {
{ type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
{ type: 'finish', reason: { kind: 'tool-calls' } },
] as Script[number]
const { ctx, parent } = await setup([response])
const { ctx, parent } = await setup(storage, [response])
let sideEffectRan = false
ctx.tools.register(defineContentToolFixture({
name: 'side_effect',
@@ -263,7 +263,7 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('a later prepended pre-execute listener cannot resurrect dispatch after capture', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a later prepended pre-execute listener cannot resurrect dispatch after capture', async (storage) => {
const response = [
...toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 5 }).slice(0, -2),
{ type: 'block-start', index: 1, blockType: 'tool-call' },
@@ -271,7 +271,7 @@ describe('in-process structured output', () => {
{ type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
{ type: 'finish', reason: { kind: 'tool-calls' } },
] as Script[number]
const { ctx, parent } = await setup([response])
const { ctx, parent } = await setup(storage, [response])
let sideEffectRan = false
ctx.tools.register(defineContentToolFixture({
name: 'side_effect',
@@ -301,14 +301,14 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('leaves tool calls that PRECEDE the capture in the same response untouched', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: leaves tool calls that PRECEDE the capture in the same response untouched', async (storage) => {
const response = [
{ type: 'block-start', index: 0, blockType: 'tool-call' },
{ type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString<ToolCallId>('c1'), name: 'side_effect', arguments: '{}' } },
...toolCallResponse('c2', STRUCTURED_OUTPUT_TOOL, { answer: 6 }).map(chunk =>
'index' in chunk ? { ...chunk, index: 1 } : chunk),
] as Script[number]
const { ctx, parent } = await setup([response])
const { ctx, parent } = await setup(storage, [response])
let sideEffectRan = false
ctx.tools.register(defineContentToolFixture({
name: 'side_effect',
@@ -328,8 +328,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('an invalid call gets an INVALID_ARGS isError result and the model retries in-turn', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: an invalid call gets an INVALID_ARGS isError result and the model retries in-turn', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 'not-a-number' }),
toolCallResponse('c2', STRUCTURED_OUTPUT_TOOL, { answer: 7 }),
])
@@ -345,8 +345,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('a clean finish without a capture is an immediate error to the parent — deliberately NO re-prompt', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: a clean finish without a capture is an immediate error to the parent — deliberately NO re-prompt', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
textResponse('here is my answer in prose'),
textResponse('MUST NOT BE CONSUMED'),
])
@@ -361,9 +361,9 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('an errored child keeps its honest error result (no capture expected)', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: an errored child keeps its honest error result (no capture expected)', async (storage) => {
// Script exhaustion on the first call → the child turn errors.
const { ctx, parent, adapter } = await setup([])
const { ctx, parent, adapter } = await setup(storage, [])
const run = await startTestActivation(ctx, 'spawn', structuredRequest(parent))
const result = await run.result
expect(result.stopReason).toBe('error')
@@ -371,15 +371,15 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('disposing a running structured child settles aborted without requiring a capture', async () => {
const { ctx, parent } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: disposing a running structured child settles aborted without requiring a capture', async (storage) => {
const { ctx, parent } = await setup(storage, ['hang'])
const run = await startTestActivation(ctx, 'spawn', structuredRequest(parent))
await run.dispose()
expect((await run.result).stopReason).toBe('aborted')
})
it('accepts a final structured result without waiting for descendants', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: accepts a final structured result without waiting for descendants', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('spawn-child', 'start_descendant', {}),
toolCallResponse('final-capture', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
])
@@ -411,8 +411,8 @@ describe('in-process structured output', () => {
}
})
it('waits through interim idle while delegated work supplies the final structured answer', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: waits through interim idle while delegated work supplies the final structured answer', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('delegate', 'delegate_answer', {}),
textResponse('Waiting for the delegated answer.'),
toolCallResponse('capture', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
@@ -453,8 +453,8 @@ describe('in-process structured output', () => {
}
})
it('rejects new input after capture until closure, then cold-resumes without the schema', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: rejects new input after capture until closure, then cold-resumes without the schema', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('capture', STRUCTURED_OUTPUT_TOOL, { answer: 42 }),
textResponse('ordinary resumed answer'),
])
@@ -487,16 +487,16 @@ describe('in-process structured output', () => {
expect(toolNames(adapter.requests[1]!)).not.toContain(STRUCTURED_OUTPUT_TOOL)
})
it('rejects a schema outside the subset loud, before any child exists', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: rejects a schema outside the subset loud, before any child exists', async (storage) => {
const { ctx, parent } = await setup(storage, [])
await expect(startTestActivation(ctx, 'spawn', structuredRequest(parent, {
outputSchema: { type: 'object', oneOf: [] },
}))).rejects.toThrow(/unsupported JSON schema/)
expect(ctx.agents.get(brandString<SessionId>('parent'))).toBeDefined()
})
it('a schema carrying non-JSON values fails as JsonSchemaError at the validation boundary', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: a schema carrying non-JSON values fails as JsonSchemaError at the validation boundary', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const schema: ObjectJsonSchema = { type: 'object' }
Object.defineProperty(schema, 'default', { value: () => {}, enumerable: true })
await expect(startTestActivation(ctx, 'spawn', structuredRequest(parent, {
@@ -504,8 +504,8 @@ describe('in-process structured output', () => {
}))).rejects.toThrow(/unsupported JSON schema.*annotation must be lossless JSON data/)
})
it('a post-execute BLOCK on the capture call denies the capture: log and result agree on failure', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: a post-execute BLOCK on the capture call denies the capture: log and result agree on failure', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 7 }),
textResponse('continues after the blocked capture'),
])
@@ -533,8 +533,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('a post-execute accept-with-replacement still commits the capture', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: a post-execute accept-with-replacement still commits the capture', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 8 }),
])
ctx.on('tools/post-execute', (exec, _result, next) => {
@@ -550,8 +550,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('commits only after a later prepended post-execute wrapper returns the authoritative result', async () => {
const { ctx, parent } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: commits only after a later prepended post-execute wrapper returns the authoritative result', async (storage) => {
const { ctx, parent } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 8 }),
textResponse('capture was rejected'),
])
@@ -575,8 +575,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('appends the structured instruction to the child REQUEST\'s system text (base prompt preserved)', async () => {
const { ctx, parent, adapter } = await setup([toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 })])
it.each(['jsonl', 'sqlite'] as const)("%s: appends the structured instruction to the child REQUEST's system text (base prompt preserved)", async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 })])
// A context-wide section stands in for the deployment persona: the
// instruction must APPEND to the other scoped and global sections, not
// replace them (AgentOptions has no prompt field — the instruction is an
@@ -591,8 +591,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('keeps pure PTC mode at one wire tool and exposes structured capture through the SDK only', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: keeps pure PTC mode at one wire tool and exposes structured capture through the SDK only', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('c1', RUN_CODE_NAME, { code: 'return await tools.structured_output({ answer: 12 })', description: 'Capture the structured answer' }),
], {
toolMode: 'ptc',
@@ -618,8 +618,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('discards a nested capture when the enclosing run_code execution fails', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: discards a nested capture when the enclosing run_code execution fails', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('c1', RUN_CODE_NAME, { code: 'await tools.structured_output({ answer: 12 }); throw new Error("boom")', description: 'Capture then fail the program' }),
textResponse('outer code failed'),
], {
@@ -647,8 +647,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('discards a nested capture when post-policy blocks the enclosing run_code result', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: discards a nested capture when post-policy blocks the enclosing run_code result', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('c1', RUN_CODE_NAME, { code: 'return await tools.structured_output({ answer: 12 })', description: 'Capture the structured answer' }),
textResponse('outer code was blocked'),
], {
@@ -672,8 +672,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('the instruction rides ONLY structured requests: appended for the child, absent for a plain agent', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: the instruction rides ONLY structured requests: appended for the child, absent for a plain agent', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
textResponse('parent answer'),
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 1 }),
])
@@ -691,8 +691,8 @@ describe('in-process structured output', () => {
})
describe('scoped registration (each child owns its capture tool)', () => {
it('a plain agent never sees the tool: nothing is registered globally at all', async () => {
const { ctx, parent, adapter } = await setup([textResponse('parent answer')])
it.each(['jsonl', 'sqlite'] as const)('%s: a plain agent never sees the tool: nothing is registered globally at all', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [textResponse('parent answer')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'hello' }], source: { kind: 'user' } }))
await parent.whenIdle()
// Scoped registration: the global view has no capture tool, ever.
@@ -700,8 +700,8 @@ describe('in-process structured output', () => {
expect(toolNames(adapter.requests[0]!)).not.toContain(STRUCTURED_OUTPUT_TOOL)
})
it('a structured child sees structured_output with ITS schema; a plain agent never sees the tool', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: a structured child sees structured_output with ITS schema; a plain agent never sees the tool', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
// Parent turn (a plain agent): must NOT see the tool.
textResponse('parent answer'),
// Child turn: must see it, with the run's schema.
@@ -720,13 +720,13 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('two concurrent structured children each see their OWN schema', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: two concurrent structured children each see their OWN schema', async (storage) => {
const otherSchema: ObjectJsonSchema = {
type: 'object',
properties: { verdict: { type: 'string', enum: ['real', 'bogus'] } },
required: ['verdict'],
}
const { ctx, parent, adapter } = await setup([
const { ctx, parent, adapter } = await setup(storage, [
(options: GenerateOptions) => {
// Answer with whatever schema this child was given — proves each
// request carried the right one regardless of scheduling order.
@@ -757,8 +757,8 @@ describe('in-process structured output', () => {
await runB.dispose()
})
it('places the capture tool and instruction in their canonical orders', async () => {
const { ctx, parent, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: places the capture tool and instruction in their canonical orders', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 7 }),
])
// A global tool sorts lexicographically after structured_output, while a
@@ -787,8 +787,8 @@ describe('in-process structured output', () => {
await run.dispose()
})
it('a non-structured agent request keeps tools ABSENT when it had none (no tools: [] materialized)', async () => {
const { parent, adapter } = await setup([textResponse('plain')])
it.each(['jsonl', 'sqlite'] as const)('%s: a non-structured agent request keeps tools ABSENT when it had none (no tools: [] materialized)', async (storage) => {
const { parent, adapter } = await setup(storage, [textResponse('plain')])
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
await parent.whenIdle()
const request = adapter.requests[0]!
@@ -796,8 +796,8 @@ describe('in-process structured output', () => {
await new Promise(resolve => setTimeout(resolve, 0))
})
it('registrations survive provider reload and are removed before result delivery', async () => {
const { ctx, parent, disposeProvider } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: registrations survive provider reload and are removed before result delivery', async (storage) => {
const { ctx, parent, disposeProvider } = await setup(storage, [
toolCallResponse('c1', STRUCTURED_OUTPUT_TOOL, { answer: 4 }),
])
expect(ctx.tools.get(STRUCTURED_OUTPUT_TOOL)).toBeUndefined()
@@ -815,8 +815,8 @@ describe('in-process structured output', () => {
})
})
it('a structured_output call from an agent WITHOUT a structured run is UNKNOWN_TOOL (the tool does not exist for it)', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: a structured_output call from an agent WITHOUT a structured run is UNKNOWN_TOOL (the tool does not exist for it)', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const result = await executeToolFixture(ctx, {
signal: testToolSignal,
callId: 'x' as never,
@@ -828,8 +828,8 @@ describe('in-process structured output', () => {
expect(result.error?.info?.code).toBe('UNKNOWN_TOOL')
})
it('a structured_output call with NO calling agent at all is UNKNOWN_TOOL', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: a structured_output call with NO calling agent at all is UNKNOWN_TOOL', async (storage) => {
const { ctx } = await setup(storage, [])
const result = await executeToolFixture(ctx, {
signal: testToolSignal,
callId: 'x' as never,
@@ -840,8 +840,8 @@ describe('in-process structured output', () => {
expect(result.error?.info?.code).toBe('UNKNOWN_TOOL')
})
it('a failed execution stage is discarded and never promoted by a later call', async () => {
const { ctx, parent } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: a failed execution stage is discarded and never promoted by a later call', async (storage) => {
const { ctx, parent } = await setup(storage, ['hang'])
const run = await startTestActivation(ctx, 'spawn', structuredRequest(parent))
// A prepended post-execute listener blocks the first capture without
// delegating. The final-result notification discards that execution's
@@ -885,8 +885,8 @@ describe('in-process structured output', () => {
expect((await run.result).structured).toEqual({ answer: 9 })
})
it('reusing a failed execution\'s call id never promotes its discarded stage', async () => {
const { ctx, parent } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)("%s: reusing a failed execution's call id never promotes its discarded stage", async (storage) => {
const { ctx, parent } = await setup(storage, ['hang'])
const run = await startTestActivation(ctx, 'spawn', structuredRequest(parent))
// Block the first capture after its body stages a value. Its final error
// discards that execution's stage.
@@ -931,8 +931,8 @@ describe('in-process structured output', () => {
expect((await run.result).structured).toEqual({ answer: 5 })
})
it('a pre-execute deny with call-id reuse cannot promote another execution\'s stage', async () => {
const { ctx, parent } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)("%s: a pre-execute deny with call-id reuse cannot promote another execution's stage", async (storage) => {
const { ctx, parent } = await setup(storage, ['hang'])
const run = await startTestActivation(ctx, 'spawn', structuredRequest(parent))
// Discard the first capture's stage via a final post-execute block.
let blocks = 1
@@ -17,7 +17,7 @@ import SubagentRuntime from '../src/index.ts'
import { TestSessionQuery } from './test-session-query.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
async function fixture() {
async function fixture(storage: 'jsonl' | 'sqlite' ) {
const root = await mkdtemp(join(tmpdir(), 'dsh-child-directory-'))
const origin = join(root, 'origin')
const first = join(origin, 'first')
@@ -31,7 +31,7 @@ async function fixture() {
})
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'sessions') })
await ctx.plugin(JsonlSessionPersistence, { storage, root: join(root, 'sessions') })
await ctx.plugin(TestSessionQuery)
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -48,8 +48,8 @@ async function fixture() {
}
describe('subagent working directories', () => {
it.each(['spawn', 'fork'])('%s inherits current directory independently of origin and inherited history', async (provider) => {
const { ctx, parent, origin, first, second } = await fixture()
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['spawn', 'fork']).map(value => [storage, value] as const)))('%s: %s inherits current directory independently of origin and inherited history', async (storage, provider) => {
const { ctx, parent, origin, first, second } = await fixture(storage)
await ctx.workingDirectory.set(parent, first)
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'record first directory' }], source: { kind: 'user' } }))
await parent.whenIdle()
@@ -66,8 +66,8 @@ describe('subagent working directories', () => {
await run.dispose()
})
it.each(['relative', 'absolute'])('retains an explicit %s directory when a continuable child cold-resumes', async (form) => {
const { ctx, parent, origin, first, second } = await fixture()
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['relative', 'absolute']).map(value => [storage, value] as const)))('%s: retains an explicit %s directory when a continuable child cold-resumes', async (storage, form) => {
const { ctx, parent, origin, first, second } = await fixture(storage)
const selected = await realpath(second)
const started = await ctx.subagents.startActivation({
delivery: 'caller',
@@ -87,8 +87,8 @@ describe('subagent working directories', () => {
expect(last?.data).toMatchObject({ cwd: selected })
})
it('rolls back a local child whose setup realm has no directory service', async () => {
const { ctx, parent, second, adapter } = await fixture()
it.each(['jsonl', 'sqlite'] as const)('%s: rolls back a local child whose setup realm has no directory service', async (storage) => {
const { ctx, parent, second, adapter } = await fixture(storage)
const beforeSessions = ctx.sessions.list().length
const childId = brandString<SessionId>('missing-directory-service')
const create = ctx.agents.create.bind(ctx.agents)
@@ -58,13 +58,13 @@ afterEach(async () => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
async function setupWith(adapter: MockAdapter | GatedAdapter) {
async function setupWith(storage: 'jsonl' | 'sqlite', adapter: MockAdapter | GatedAdapter) {
const ctx = new Context()
contexts.add(ctx)
await mountAgentLoopTestDependencies(ctx)
const root = mkdtempSync(join(tmpdir(), 'dsh-tool-list-agents-'))
roots.push(root)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(TestSessionQuery)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
@@ -77,8 +77,8 @@ async function setupWith(adapter: MockAdapter | GatedAdapter) {
return { ctx, parent, adapter }
}
async function setup(script: ConstructorParameters<typeof MockAdapter>[0]) {
return setupWith(new MockAdapter(script))
async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters<typeof MockAdapter>[0]) {
return setupWith(storage, new MockAdapter(script))
}
function text(result: { content: readonly { type: string; text?: string }[] }): string {
@@ -110,8 +110,8 @@ async function waitNoActivation(ctx: Context, childId: SessionId): Promise<void>
}
describe('list_agents', () => {
it('lists a settled caller-delivery local child by name', async () => {
const { ctx, parent } = await setup([textResponse('private result')])
it.each(['jsonl', 'sqlite'] as const)('%s: lists a settled caller-delivery local child by name', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('private result')])
const started = await ctx.subagents.startActivation({
delivery: 'caller', provider: 'spawn', label: 'workflow child',
prompt: [{ type: 'text', text: 'child task' }], parent,
@@ -129,8 +129,8 @@ describe('list_agents', () => {
])
})
it('omits external leaves without diagnostics', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: omits external leaves without diagnostics', async (storage) => {
const { ctx, parent } = await setup(storage, [])
parent.session.append('subagent/catalog', {
version: 2, childId: brandString<SessionId>('external-child'), childCreatedAt: 1,
mode: 'external', label: 'external child',
@@ -140,8 +140,8 @@ describe('list_agents', () => {
expect(text(result)).toBe('lead [inactive] — root agent')
})
it('registers list_agents once, globally, without parameters', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: registers list_agents once, globally, without parameters', async (storage) => {
const { ctx } = await setup(storage, [])
const schemas = ctx.tools.schemas().filter(schema => schema.name === 'list_agents')
expect(schemas).toHaveLength(1)
const parameters = schemas[0]!.parameters as {
@@ -154,16 +154,16 @@ describe('list_agents', () => {
expect(ctx.tools.get('list_agents')?.isConcurrencySafe?.({})).toBe(true)
})
it('renders the Lead when the tree has no children', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: renders the Lead when the tree has no children', async (storage) => {
const { ctx, parent } = await setup(storage, [])
await ctx.sessions.flush(parent.session)
const result = await callTool(ctx, 'list_agents', {}, parent)
expect(result.isError).toBe(false)
expect(text(result)).toBe('lead [inactive] — root agent')
})
it('renders direct children in array order with registry statuses', async () => {
const { ctx, parent } = await setup([textResponse('done')])
it.each(['jsonl', 'sqlite'] as const)('%s: renders direct children in array order with registry statuses', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('done')])
const started = await ctx.subagents.startActivation({ delivery: 'parent',
provider: 'spawn',
label: 'real child',
@@ -222,8 +222,8 @@ describe('list_agents', () => {
)
})
it('always lists descendants and forwards the caller id and cancellation signal', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: always lists descendants and forwards the caller id and cancellation signal', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const signal = new AbortController().signal
const listDescendants = vi.spyOn(ctx.subagents, 'listDescendants').mockResolvedValue([])
@@ -233,8 +233,8 @@ describe('list_agents', () => {
expect(listDescendants).toHaveBeenCalledWith(parent.id, signal)
})
it('reports an unreadable historical branch alongside a settled continuable child', async () => {
const { ctx, parent } = await setup([textResponse('done')])
it.each(['jsonl', 'sqlite'] as const)('%s: reports an unreadable historical branch alongside a settled continuable child', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('done')])
parent.session.append('subagent/catalog', {
version: 1, childId: brandString<SessionId>('historical-one-shot'), childCreatedAt: 1,
mode: 'one-shot', label: 'finished once',
@@ -255,8 +255,8 @@ describe('list_agents', () => {
)
})
it('describes inactive as turn availability and pins the status vocabulary', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: describes inactive as turn availability and pins the status vocabulary', async (storage) => {
const { ctx } = await setup(storage, [])
const schema = ctx.tools.schemas().find(candidate => candidate.name === 'list_agents')
// Completion reaches the parent through its notice; listing is discovery,
// so its inactive status must not send the model looking for a result.
@@ -268,8 +268,8 @@ describe('list_agents', () => {
.toEqual(['running', 'inactive', 'corrupt', 'unsupported', 'unavailable'])
})
it('fails loud when invoked without a calling agent', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: fails loud when invoked without a calling agent', async (storage) => {
const { ctx } = await setup(storage, [])
const result = await callTool(ctx, 'list_agents', {})
expect(result.isError).toBe(true)
expect(text(result)).toContain('requires a calling agent')
@@ -296,14 +296,14 @@ describe('list_agents', () => {
expect(typeof tool.apply).toBe('function')
})
it('walks the complete descendant tree in pre-order with full names', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: walks the complete descendant tree in pre-order with full names', async (storage) => {
const releaseChild = Promise.withResolvers<undefined>()
const releaseGrandchild = Promise.withResolvers<undefined>()
const adapter = new GatedAdapter([
{ chunks: textResponse('child'), gate: releaseChild.promise },
{ chunks: textResponse('grandchild'), gate: releaseGrandchild.promise },
])
const { ctx, parent } = await setupWith(adapter)
const { ctx, parent } = await setupWith(storage, adapter)
const started = await ctx.subagents.startActivation({ delivery: 'parent',
provider: 'spawn',
label: 'waiting branch',
@@ -340,8 +340,8 @@ describe('list_agents', () => {
await waitNoActivation(ctx, started.childId)
})
it('omits one-shot intermediates from descendants output while surfacing what they own', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: omits one-shot intermediates from descendants output while surfacing what they own', async (storage) => {
const { ctx, parent } = await setup(storage, [])
// Deterministic service rows: a one-shot intermediate owning a continuable
// leaf, plus a positioned diagnostic. The tool filters only the one-shot.
ctx.subagents.listDescendants = () => Promise.resolve([
@@ -382,7 +382,7 @@ describe('list_agents', () => {
)
})
it('shows the same complete subagent tree from the root and each branch', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: shows the same complete subagent tree from the root and each branch', async (storage) => {
const release = Promise.withResolvers<undefined>()
const releaseDelta = Promise.withResolvers<undefined>()
const adapter = new GatedAdapter([
@@ -391,7 +391,7 @@ describe('list_agents', () => {
{ chunks: textResponse('gamma') },
{ chunks: textResponse('delta'), gate: releaseDelta.promise },
])
const { ctx, parent } = await setupWith(adapter)
const { ctx, parent } = await setupWith(storage, adapter)
const start = async (label: string) => (await ctx.subagents.startActivation({
delivery: 'caller', provider: 'spawn', label,
prompt: [{ type: 'text', text: label }], parent, signal: testToolSignal,
@@ -62,13 +62,13 @@ afterEach(async () => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 })
})
async function setupWith(adapter: MockAdapter | GatedAdapter, park = true) {
async function setupWith(storage: 'jsonl' | 'sqlite', adapter: MockAdapter | GatedAdapter, park = true) {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx)
const root = mkdtempSync(join(tmpdir(), 'dsh-tool-subagent-control-'))
roots.push(root)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(TestSessionQuery)
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
@@ -82,8 +82,8 @@ async function setupWith(adapter: MockAdapter | GatedAdapter, park = true) {
return { ctx, parent, adapter, controlFiber }
}
async function setup(script: ConstructorParameters<typeof MockAdapter>[0]) {
return setupWith(new MockAdapter(script))
async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters<typeof MockAdapter>[0]) {
return setupWith(storage, new MockAdapter(script))
}
function text(result: { content: readonly { type: string; text?: string }[] }): string {
@@ -115,8 +115,8 @@ async function waitNoActivation(ctx: Context, childId: SessionId): Promise<void>
}
describe('dsh-tool-subagent-control', () => {
it('registers send_message once, globally, with the two required parameters', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: registers send_message once, globally, with the two required parameters', async (storage) => {
const { ctx } = await setup(storage, [])
const schemas = ctx.tools.schemas().filter(schema => schema.name === 'send_message')
expect(schemas).toHaveLength(1)
const props = (schemas[0]!.parameters as { properties?: Record<string, unknown> }).properties ?? {}
@@ -130,9 +130,9 @@ describe('dsh-tool-subagent-control', () => {
})
})
it('keeps the send_message definition and ordering byte-identical in a fork child', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: keeps the send_message definition and ordering byte-identical in a fork child', async (storage) => {
const release = Promise.withResolvers<undefined>()
const { ctx, parent, adapter } = await setupWith(new GatedAdapter([
const { ctx, parent, adapter } = await setupWith(storage, new GatedAdapter([
{ chunks: textResponse('parent done') },
{ chunks: textResponse('child done'), gate: release.promise },
]), false)
@@ -177,8 +177,8 @@ describe('dsh-tool-subagent-control', () => {
expect(adapter.requests[1]!.messages[0]).toEqual(adapter.requests[0]!.messages[0])
})
it('JSON-encodes identity ids in logged runtime context', async () => {
const { ctx } = await setup([textResponse('child done')])
it.each(['jsonl', 'sqlite'] as const)('%s: JSON-encodes identity ids in logged runtime context', async (storage) => {
const { ctx } = await setup(storage, [textResponse('child done')])
const parent = await ctx.agentLoop.create(brandString<SessionId>('parent"\nagent'), { provider: 'mock', model: 'mock' })
parkParent(ctx, parent)
const started = await ctx.subagents.startActivation({
@@ -202,11 +202,11 @@ describe('dsh-tool-subagent-control', () => {
expect(guidance).not.toContain(started.childId)
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
{ name: 'send_message', instruction: 'To message other agents', other: 'Use list_agents' },
{ name: 'list_agents', instruction: 'Use list_agents', other: 'To message other agents' },
])('gates $name guidance independently in an agent scope', async ({ name, instruction, other }) => {
const { ctx, parent } = await setup([])
]).map(value => [storage, value] as const)))('%s: gates $name guidance independently in an agent scope', async (storage, { name, instruction, other }) => {
const { ctx, parent } = await setup(storage, [])
const { agent: child } = await ctx.agents.create({
sessionId: brandString<SessionId>('communication-child'),
meta: { origin: 'subagent', parentSession: parent.id },
@@ -233,8 +233,8 @@ describe('dsh-tool-subagent-control', () => {
toolSet.dispose()
})
it('keeps collaboration instructions when controls are mounted in an agent scope', async () => {
const { ctx, parent, controlFiber } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps collaboration instructions when controls are mounted in an agent scope', async (storage) => {
const { ctx, parent, controlFiber } = await setup(storage, [])
await controlFiber.dispose()
await parent.ctx.plugin(tool)
const context = renderContextSnapshot(await ctx.systemPrompt.assemble({ agent: parent, scope: parent }))
@@ -242,8 +242,8 @@ describe('dsh-tool-subagent-control', () => {
expect(context).toContain('Use list_agents')
})
it('identifies independent roots and forks before their collaboration instructions', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: identifies independent roots and forks before their collaboration instructions', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const { agent: fork } = await ctx.agents.create({
sessionId: brandString<SessionId>('ordinary-fork'), meta: { parentSession: parent.id },
})
@@ -258,11 +258,11 @@ describe('dsh-tool-subagent-control', () => {
expect(renderContextSnapshot(await ctx.systemPrompt.assemble({}))).not.toContain('To message other agents')
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
new Error('root lookup failed'),
new SubagentError('root data is unreadable', 'PERSISTENCE_UNAVAILABLE'),
])('propagates identity lookup errors other than an unavailable root: $message', async (error) => {
const { ctx, parent } = await setup([])
]).map(value => [storage, value] as const)))('%s: propagates identity lookup errors other than an unavailable root: $message', async (storage, error) => {
const { ctx, parent } = await setup(storage, [])
const lookup = vi.spyOn(ctx.subagents, 'namesOf').mockImplementation(() => { throw error })
try {
await expect(ctx.systemPrompt.assemble({ agent: parent, scope: parent })).rejects.toBe(error)
@@ -271,8 +271,8 @@ describe('dsh-tool-subagent-control', () => {
}
})
it('retains the caller id when its subagent tree root is unavailable', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: retains the caller id when its subagent tree root is unavailable', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const lookup = vi.spyOn(ctx.subagents, 'namesOf').mockImplementation(() => {
throw new SubagentError('root is unavailable', 'UNAUTHORIZED')
})
@@ -287,8 +287,8 @@ describe('dsh-tool-subagent-control', () => {
}
})
it('keeps required identity while both discovery and messaging are filtered', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps required identity while both discovery and messaging are filtered', async (storage) => {
const { ctx, parent } = await setup(storage, [])
ctx.systemPrompt.suppressRuntimeContext()
const available = await ctx.systemPrompt.assemble({ agent: parent, scope: parent })
expect(available.tools.find(tool => tool.name === 'list_agents')?.description)
@@ -306,8 +306,8 @@ describe('dsh-tool-subagent-control', () => {
toolSet.dispose()
})
it.each(['parent', 'caller'] as const)('keeps %s result delivery independent of messaging tools', async (delivery) => {
const { ctx, parent, adapter, controlFiber } = await setup([textResponse('child result')])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['parent', 'caller'] as const).map(value => [storage, value] as const)))('%s: keeps %s result delivery independent of messaging tools', async (storage, delivery) => {
const { ctx, parent, adapter, controlFiber } = await setup(storage, [textResponse('child result')])
await controlFiber.dispose()
const followup = vi.spyOn(parent, 'followup')
const started = await ctx.subagents.startActivation({
@@ -322,9 +322,9 @@ describe('dsh-tool-subagent-control', () => {
expect(followup.mock.calls.some(([message]) => message.source.kind === 'subagent-settled')).toBe(delivery === 'parent')
})
it('lets a continuable child steer its direct parent with send_message', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: lets a continuable child steer its direct parent with send_message', async (storage) => {
const release = Promise.withResolvers<undefined>()
const { ctx, parent, adapter } = await setupWith(new GatedAdapter([
const { ctx, parent, adapter } = await setupWith(storage, new GatedAdapter([
{ chunks: textResponse('child done'), gate: release.promise },
]))
const started = await ctx.subagents.startActivation({
@@ -364,8 +364,8 @@ describe('dsh-tool-subagent-control', () => {
await waitNoActivation(ctx, started.childId)
})
it('cold-resumes a settled child and reports delivery', async () => {
const { ctx, parent } = await setup([textResponse('first answer'), textResponse('second answer')])
it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes a settled child and reports delivery', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('first answer'), textResponse('second answer')])
const started = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -398,8 +398,8 @@ describe('dsh-tool-subagent-control', () => {
])
})
it('steers the nearest step of an open turn', async () => {
const { ctx, parent, adapter } = await setup([textResponse('first'), textResponse('second')])
it.each(['jsonl', 'sqlite'] as const)('%s: steers the nearest step of an open turn', async (storage) => {
const { ctx, parent, adapter } = await setup(storage, [textResponse('first'), textResponse('second')])
const started = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -430,8 +430,8 @@ describe('dsh-tool-subagent-control', () => {
])
})
it('reports a delivery failure as an errored, not-delivered result', async () => {
const { ctx, parent } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reports a delivery failure as an errored, not-delivered result', async (storage) => {
const { ctx, parent } = await setup(storage, [])
const result = await callTool(ctx, 'send_message', {
agent: 'no-such-child',
message: 'hello?',
@@ -440,8 +440,8 @@ describe('dsh-tool-subagent-control', () => {
expect(text(result)).toContain('unavailable')
})
it('rejects a caller outside the child\'s subagent tree', async () => {
const { ctx, parent } = await setup([textResponse('first')])
it.each(['jsonl', 'sqlite'] as const)("%s: rejects a caller outside the child's subagent tree", async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('first')])
const started = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -460,8 +460,8 @@ describe('dsh-tool-subagent-control', () => {
expect(text(result)).toContain('not a member of this subagent tree')
})
it('fails loud when invoked without a calling agent', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: fails loud when invoked without a calling agent', async (storage) => {
const { ctx } = await setup(storage, [])
const result = await callTool(ctx, 'send_message', { agent: 'x', message: 'y' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('requires a calling agent')
@@ -519,8 +519,8 @@ describe('dsh-tool-subagent-control', () => {
})
describe('dsh-tool-subagent-control interrupt_agent', () => {
it('registers interrupt_agent with the single agent parameter and current-turn wording', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: registers interrupt_agent with the single agent parameter and current-turn wording', async (storage) => {
const { ctx } = await setup(storage, [])
const schemas = ctx.tools.schemas().filter(schema => schema.name === 'interrupt_agent')
expect(schemas).toHaveLength(1)
const props = (schemas[0]!.parameters as { properties?: Record<string, unknown> }).properties ?? {}
@@ -529,14 +529,14 @@ describe('dsh-tool-subagent-control interrupt_agent', () => {
expect(schemas[0]!.description).toContain('send_message')
})
it('interrupts a running direct child with the parent cause, parking its queue', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: interrupts a running direct child with the parent cause, parking its queue', async (storage) => {
const releaseFirst = Promise.withResolvers<undefined>()
const adapter = new GatedAdapter([
{ chunks: textResponse('held'), gate: releaseFirst.promise },
{ chunks: textResponse('parked answer') },
{ chunks: textResponse('waking answer') },
])
const { ctx, parent } = await setupWith(adapter)
const { ctx, parent } = await setupWith(storage, adapter)
const started = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -586,14 +586,14 @@ describe('dsh-tool-subagent-control interrupt_agent', () => {
])
})
it('lets a deep live ancestor interrupt a descendant it did not directly create', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: lets a deep live ancestor interrupt a descendant it did not directly create', async (storage) => {
const releaseChild = Promise.withResolvers<undefined>()
const releaseGrandchild = Promise.withResolvers<undefined>()
const adapter = new GatedAdapter([
{ chunks: textResponse('child'), gate: releaseChild.promise },
{ chunks: textResponse('grandchild'), gate: releaseGrandchild.promise },
])
const { ctx, parent } = await setupWith(adapter)
const { ctx, parent } = await setupWith(storage, adapter)
const started = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -624,14 +624,14 @@ describe('dsh-tool-subagent-control interrupt_agent', () => {
await waitNoActivation(ctx, started.childId)
})
it('rejects self, sibling, and unrelated callers without touching the target', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: rejects self, sibling, and unrelated callers without touching the target', async (storage) => {
const releaseA = Promise.withResolvers<undefined>()
const releaseB = Promise.withResolvers<undefined>()
const adapter = new GatedAdapter([
{ chunks: textResponse('a'), gate: releaseA.promise },
{ chunks: textResponse('b'), gate: releaseB.promise },
])
const { ctx, parent } = await setupWith(adapter)
const { ctx, parent } = await setupWith(storage, adapter)
const target = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -670,8 +670,8 @@ describe('dsh-tool-subagent-control interrupt_agent', () => {
await waitNoActivation(ctx, sibling.childId)
})
it('accepts an absent target as a no-op without cold-resuming it', async () => {
const { ctx, parent } = await setup([textResponse('done')])
it.each(['jsonl', 'sqlite'] as const)('%s: accepts an absent target as a no-op without cold-resuming it', async (storage) => {
const { ctx, parent } = await setup(storage, [textResponse('done')])
const started = await ctx.subagents.startActivation({
delivery: 'parent',
provider: 'spawn',
@@ -690,8 +690,8 @@ describe('dsh-tool-subagent-control interrupt_agent', () => {
expect(ctx.agents.get(started.childId)).toBeUndefined()
})
it('fails loud when invoked without a calling agent', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: fails loud when invoked without a calling agent', async (storage) => {
const { ctx } = await setup(storage, [])
const result = await callTool(ctx, 'interrupt_agent', { agent: 'x' })
expect(result.isError).toBe(true)
expect(text(result)).toContain('requires a calling agent')
@@ -33,10 +33,10 @@ afterEach(async () => {
}
})
async function mountSpawn(ctx: Context, providerName: string): Promise<void> {
async function mountSpawn(storage: 'jsonl' | 'sqlite', ctx: Context, providerName: string): Promise<void> {
const root = mkdtempSync(join(tmpdir(), 'dsh-tool-preset-'))
roots.push(root)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(SubagentSpawn, { providerName })
}
@@ -151,13 +151,13 @@ describe('spawn preset selection', () => {
await expect(tool.apply(ctx, { provider: 'spawn', agentPreset: 'writer' })).rejects.toThrow(/requires the agent-presets service/)
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
{ config: { agentPreset: 'absent' }, selection: {} },
{ config: { allowedAgentPresets: ['absent'] }, selection: { agent_preset: 'absent' } },
])('reports a missing preset only when delegation uses it: %j', async ({ config, selection }) => {
]).map(value => [storage, value] as const)))('%s: reports a missing preset only when delegation uses it: %j', async (storage, { config, selection }) => {
const { ctx, provider } = await setup(config)
await provider.dispose()
await mountSpawn(ctx, 'custom-spawn')
await mountSpawn(storage, ctx, 'custom-spawn')
const parent = await ctx.agents.create({ sessionId: brandString<SessionId>('missing-child-preset') })
const sessions = ctx.sessions.list()
const result = await callSubagent(ctx, { ...args, ...selection }, { agent: parent.agent })
@@ -168,10 +168,10 @@ describe('spawn preset selection', () => {
expect(ctx.sessions.list()).toEqual(sessions)
})
it('reports an unloadable child preset through the tool result', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: reports an unloadable child preset through the tool result', async (storage) => {
const { ctx, presets, provider } = await setup({ agentPreset: 'reviewer' })
await provider.dispose()
await mountSpawn(ctx, 'custom-spawn')
await mountSpawn(storage, ctx, 'custom-spawn')
await presets.get('reviewer')!()
await ctx.agentPresets.register({
id: 'reviewer', plugins: [{ name: 'cordis:missing-plugin' }],
@@ -342,9 +342,9 @@ describe('spawn preset selection', () => {
},
)
it('switches to a preset with a missing child reference and retries delegation after declaration', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: switches to a preset with a missing child reference and retries delegation after declaration', async (storage) => {
const { ctx } = await setup({})
await mountSpawn(ctx, 'spawn')
await mountSpawn(storage, ctx, 'spawn')
await ctx.agentPresets.register({
id: 'pending-reference',
plugins: [{ name: 'cordis:subagentTool', config: {
@@ -681,12 +681,12 @@ describe('dsh-tool-subagent local activation', () => {
})
/** Boot the real continuable stack without any model-facing follow-up adapter. */
async function continuableSetup(modelSelection = false) {
async function continuableSetup(storage: 'jsonl' | 'sqlite', modelSelection = false) {
const ctx = new Context()
const root = mkdtempSync(path.join(tmpdir(), 'dsh-tool-subagent-continuable-'))
fixtures.push({ ctx, root })
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(JsonlSessionPersistence, { storage, root })
await ctx.plugin(AgentLoop, { agents: [] })
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(SubagentRuntime)
@@ -705,8 +705,8 @@ describe('dsh-tool-subagent local activation', () => {
return { ctx, parent }
}
it.each([undefined, 'high'] as const)('starts the explicitly selected parent model with effort %s', async (effort) => {
const { ctx, parent } = await continuableSetup(true)
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([undefined, 'high'] as const).map(value => [storage, value] as const)))('%s: starts the explicitly selected parent model with effort %s', async (storage, effort) => {
const { ctx, parent } = await continuableSetup(storage, true)
parent.options.reasoningEffort = brandString<ReasoningEffortId>('high')
let child: Agent | undefined
ctx.on('subagent/start', (info) => { child = ctx.agents.get(info.id) })
@@ -721,8 +721,8 @@ describe('dsh-tool-subagent local activation', () => {
expect(parent.options.reasoningEffort).toBe('high')
})
it('classifies local activations concurrency-safe', async () => {
const { ctx } = await continuableSetup()
it.each(['jsonl', 'sqlite'] as const)('%s: classifies local activations concurrency-safe', async (storage) => {
const { ctx } = await continuableSetup(storage)
expect(new ToolExecutionPipeline(ctx).executionMode({
signal: testToolSignal,
callId: brandString<ToolCallId>('subagent-continuable'),
@@ -731,8 +731,8 @@ describe('dsh-tool-subagent local activation', () => {
})).toEqual({ kind: 'parallel' })
})
it('starts a local activation and returns only its name in the tool receipt', async () => {
const { ctx, parent } = await continuableSetup()
it.each(['jsonl', 'sqlite'] as const)('%s: starts a local activation and returns only its name in the tool receipt', async (storage) => {
const { ctx, parent } = await continuableSetup(storage)
const schema = ctx.tools.schemas().find(s => s.name === 'subagent')!
// Continuable delegation has no Task, so the schema promises no collection.
expect(schema.description).not.toContain('job_output')
@@ -771,8 +771,8 @@ describe('dsh-tool-subagent local activation', () => {
expect(loaded.events.some(event => event.type === 'assistant/message')).toBe(true)
})
it('starts a child under a requested name and rejects a sibling with the same name', async () => {
const { ctx, parent } = await continuableSetup()
it.each(['jsonl', 'sqlite'] as const)('%s: starts a child under a requested name and rejects a sibling with the same name', async (storage) => {
const { ctx, parent } = await continuableSetup(storage)
const named = await callSubagent(ctx, { description: 'review', prompt: 'review it', name: 'reviewer' }, { agent: parent })
expect(named.isError, text(named)).toBe(false)
expect(text(named)).toBe('started subagent reviewer')
@@ -788,8 +788,8 @@ describe('dsh-tool-subagent local activation', () => {
}, { timeout: 5_000 })
})
it('hides continuable guidance when the current agent cannot see the tool', async () => {
const { ctx, parent } = await continuableSetup()
it.each(['jsonl', 'sqlite'] as const)('%s: hides continuable guidance when the current agent cannot see the tool', async (storage) => {
const { ctx, parent } = await continuableSetup(storage)
parent.ctx.tools.restrict({ deny: ['subagent'] })
expect(ctx.tools.get('subagent', parent)).toBeUndefined()
@@ -797,8 +797,8 @@ describe('dsh-tool-subagent local activation', () => {
expect(assembly.sections.find(section => section.name === 'tool:subagent')?.text).toBe('')
})
it('isolates a cancelled continuable preparation from a concurrent sibling', async () => {
const { ctx, parent } = await continuableSetup()
it.each(['jsonl', 'sqlite'] as const)('%s: isolates a cancelled continuable preparation from a concurrent sibling', async (storage) => {
const { ctx, parent } = await continuableSetup(storage)
const bothPreparing = Promise.withResolvers<undefined>()
const releasePreparations = Promise.withResolvers<undefined>()
const cancelled = new AbortController()
@@ -61,6 +61,15 @@ const backends: PersistenceMount[] = [
name: 'JSONL',
mount: async (ctx, root) => await ctx.plugin(JsonlSessionPersistence, {
root: join(root, 'jsonl'),
storage: 'jsonl',
compression: 'none',
}),
},
{
name: 'SQLite',
mount: async (ctx, root) => await ctx.plugin(JsonlSessionPersistence, {
root: join(root, 'sqlite'),
storage: 'sqlite',
compression: 'none',
}),
},
+66 -65
View File
@@ -52,6 +52,7 @@ function durable(agent: Agent): TeamProjectionState {
}
async function setup(
storage: 'jsonl' | 'sqlite',
script: ConstructorParameters<typeof MockAdapter>[0],
config: ConstructorParameters<typeof TeamService>[1] = {},
enabled = true,
@@ -62,7 +63,7 @@ async function setup(
await mountWorkingDirectoryFixture(ctx)
const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-team-'))
roots.push(storageRoot)
await ctx.plugin(JsonlSessionPersistence, { root: storageRoot })
await ctx.plugin(JsonlSessionPersistence, { storage, root: storageRoot })
await ctx.plugin(TestSessionQuery)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentService)
@@ -105,8 +106,8 @@ async function waitRunning(ctx: Context, id: SessionId): Promise<Agent> {
}
describe('Tree-owned task boards', () => {
it.each(['spawn', 'fork'])('shares the configured root mode with real %s children', async (provider) => {
const { ctx, lead } = await setup(['hang', 'hang'], { defaultEnabled: true }, false)
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['spawn', 'fork']).map(value => [storage, value] as const)))('%s: shares the configured root mode with real %s children', async (storage, provider) => {
const { ctx, lead } = await setup(storage, ['hang', 'hang'], { defaultEnabled: true }, false)
expect(durable(lead).enabled).toBe(true)
const task = await ctx.agentTeams.createTask(lead, { subject: 'configured', description: 'shared board' })
const started = await spawn(ctx, lead, 'configured child', provider)
@@ -123,14 +124,14 @@ describe('Tree-owned task boards', () => {
await started.dispose()
})
it.each([undefined, false])('leaves new roots off with defaultEnabled=%s', async (defaultEnabled) => {
const { lead } = await setup([], defaultEnabled === undefined ? {} : { defaultEnabled }, false)
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([undefined, false]).map(value => [storage, value] as const)))('%s: leaves new roots off with defaultEnabled=%s', async (storage, defaultEnabled) => {
const { lead } = await setup(storage, [], defaultEnabled === undefined ? {} : { defaultEnabled }, false)
expect(durable(lead).enabled).toBeUndefined()
expect(lead.session.ownEvents().filter(event => event.type === 'team/mode')).toEqual([])
})
it.each([false, true])('preserves a selection saved during setup: %s', async (enabled) => {
const { ctx } = await setup([], { defaultEnabled: true }, false)
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: preserves a selection saved during setup: %s', async (storage, enabled) => {
const { ctx } = await setup(storage, [], { defaultEnabled: true }, false)
const handle = await ctx.agents.create({
sessionId: brandString<SessionId>('selected-root'),
setup: (_ctx, agent) => { agent.session.append('team/mode', { enabled }) },
@@ -140,8 +141,8 @@ describe('Tree-owned task boards', () => {
await handle.dispose()
})
it('initializes an ordinary fork independently of its inherited mode and tasks', async () => {
const { ctx, lead } = await setup([], { defaultEnabled: true }, false)
it.each(['jsonl', 'sqlite'] as const)('%s: initializes an ordinary fork independently of its inherited mode and tasks', async (storage) => {
const { ctx, lead } = await setup(storage, [], { defaultEnabled: true }, false)
await ctx.agentTeams.createTask(lead, { subject: 'source', description: 'belongs to source' })
await ctx.agentTeams.setEnabled(lead, false)
const handle = await ctx.agents.create({
@@ -156,16 +157,16 @@ describe('Tree-owned task boards', () => {
await handle.dispose()
})
it('unregisters default initialization when the Team service unloads', async () => {
const { ctx, teamFiber } = await setup([], { defaultEnabled: true }, false)
it.each(['jsonl', 'sqlite'] as const)('%s: unregisters default initialization when the Team service unloads', async (storage) => {
const { ctx, teamFiber } = await setup(storage, [], { defaultEnabled: true }, false)
await teamFiber.dispose()
const handle = await ctx.agents.create({ sessionId: brandString<SessionId>('without-team') })
expect(handle.agent.session.ownEvents().filter(event => event.type === 'team/mode')).toEqual([])
await handle.dispose()
})
it('rejects Agent creation if saving the configured mode fails', async () => {
const { ctx } = await setup([], { defaultEnabled: true }, false)
it.each(['jsonl', 'sqlite'] as const)('%s: rejects Agent creation if saving the configured mode fails', async (storage) => {
const { ctx } = await setup(storage, [], { defaultEnabled: true }, false)
const failure = new Error('mode save failed')
const id = brandString<SessionId>('failed-mode-save')
vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(failure)
@@ -174,14 +175,14 @@ describe('Tree-owned task boards', () => {
expect(ctx.sessions.get(id)).toBeUndefined()
})
it('does not register a Team slash command', async () => {
const { ctx, lead } = await setup([], {}, false)
it.each(['jsonl', 'sqlite'] as const)('%s: does not register a Team slash command', async (storage) => {
const { ctx, lead } = await setup(storage, [], {}, false)
await ctx.plugin(Commands)
expect(ctx.commands.list(lead).some(command => command.name === 'team')).toBe(false)
})
it('rejects disabled task access and descendant mode changes without appending', async () => {
const { ctx, lead } = await setup([], {}, false)
it.each(['jsonl', 'sqlite'] as const)('%s: rejects disabled task access and descendant mode changes without appending', async (storage) => {
const { ctx, lead } = await setup(storage, [], {}, false)
const child = await resident(ctx, lead, 'mode-child')
expect(ctx.agentTeams.isEnabled(lead)).toBe(false)
expect(() => ctx.agentTeams.listTasks(lead)).toThrow('enable Agent Teams')
@@ -193,8 +194,8 @@ describe('Tree-owned task boards', () => {
expect(lead.session.ownEvents().filter(event => event.type === 'team/mode')).toEqual([])
})
it.each(['create', 'claim'] as const)('disables queued %s while an admitted reassignment finishes', async (action) => {
const { ctx, lead } = await setup(['hang'])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['create', 'claim'] as const).map(value => [storage, value] as const)))('%s: disables queued %s while an admitted reassignment finishes', async (storage, action) => {
const { ctx, lead } = await setup(storage, ['hang'])
const { childId } = await spawn(ctx, lead, 'worker')
const child = await waitRunning(ctx, childId)
const task = await ctx.agentTeams.createTask(lead, { subject: 'work', description: 'retained assignment' })
@@ -229,8 +230,8 @@ describe('Tree-owned task boards', () => {
expect(ctx.agentTeams.listTasks(lead)).toEqual([expect.objectContaining({ id: task.id, revision: 2, ownerId: childId })])
})
it('admits queued work using the latest selection after off then on', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: admits queued work using the latest selection after off then on', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const flush = ctx.sessions.flush.bind(ctx.sessions)
@@ -272,8 +273,8 @@ describe('Tree-owned task boards', () => {
expect(ctx.get('agentTeams') === undefined).toBe(true)
})
it('rejects reads and mutations after a Team projection fails', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: rejects reads and mutations after a Team projection fails', async (storage) => {
const { ctx, lead } = await setup(storage, [])
lead.session.append('team/task', {
version: 2,
teamId: brandString<TeamId>(lead.id),
@@ -290,24 +291,24 @@ describe('Tree-owned task boards', () => {
expect(lead.session.snapshotEvents()).toHaveLength(eventCount)
})
it('propagates unavailable subagent runtime errors', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: propagates unavailable subagent runtime errors', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const failure = new Error('runtime unavailable')
vi.spyOn(ctx.subagents, 'rootOf').mockImplementation(() => { throw failure })
expect(() => ctx.agentTeams.listTasks(lead)).toThrow(failure)
})
it('rejects task limits that are not positive safe integers and removed configuration keys', async () => {
it.each(['jsonl', 'sqlite'] as const)('%s: rejects task limits that are not positive safe integers and removed configuration keys', async (storage) => {
for (const value of [0, 1.5, Number.MAX_SAFE_INTEGER + 1]) {
await expect(setup([], { maxTasks: value })).rejects.toThrow()
await expect(setup(storage, [], { maxTasks: value })).rejects.toThrow()
}
for (const key of ['maxMembers', 'maxMessageBytes', 'disposalTimeoutMs']) {
await expect(setup([], { [key]: 1 })).rejects.toThrow(`${key} is no longer supported`)
await expect(setup(storage, [], { [key]: 1 })).rejects.toThrow(`${key} is no longer supported`)
}
})
it('makes every root a Lead and every live subagent below it a teammate', async () => {
const { ctx, lead } = await setup(['hang', 'hang', 'hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: makes every root a Lead and every live subagent below it a teammate', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang', 'hang', 'hang'])
const namedActivation = await spawn(ctx, lead, 'alpha')
const named = await waitRunning(ctx, namedActivation.childId)
const unnamed = await waitRunning(ctx, (await spawn(ctx, lead, undefined)).childId)
@@ -334,8 +335,8 @@ describe('Tree-owned task boards', () => {
await Promise.all([waitNoAgent(ctx, grandchild.id), waitNoAgent(ctx, named.id), waitNoAgent(ctx, unnamed.id)])
})
it('treats an ordinary fork as a new Root Team and filters inherited Team state', async () => {
const { ctx, lead } = await setup([textResponse('alpha done')])
it.each(['jsonl', 'sqlite'] as const)('%s: treats an ordinary fork as a new Root Team and filters inherited Team state', async (storage) => {
const { ctx, lead } = await setup(storage, [textResponse('alpha done')])
const alpha = (await spawn(ctx, lead, 'alpha')).childId
await waitNoAgent(ctx, alpha)
await ctx.agentTeams.createTask(lead, { subject: 'parent task', description: 'belongs to parent' })
@@ -357,8 +358,8 @@ describe('Tree-owned task boards', () => {
await handle.dispose()
})
it('clears a prior owner name when reassigning to an unnamed historical member', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: clears a prior owner name when reassigning to an unnamed historical member', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const legacy = await resident(ctx, lead, 'legacy-worker')
lead.session.append('subagent/catalog', {
version: 0, childId: legacy.id, childCreatedAt: legacy.session.header.createdAt,
@@ -376,8 +377,8 @@ describe('Tree-owned task boards', () => {
expect(reassigned).not.toHaveProperty('ownerName')
})
it('assigns deep descendants by id and rejects historical roster authority', async () => {
const { ctx, lead } = await setup(['hang', 'hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: assigns deep descendants by id and rejects historical roster authority', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang', 'hang'])
const child = await waitRunning(ctx, (await spawn(ctx, lead, 'parent')).childId)
const grandchild = await waitRunning(ctx, (await spawn(ctx, child, 'nested')).childId)
const task = await ctx.agentTeams.createTask(lead, { subject: 'nested work', description: 'deep assignment' })
@@ -398,8 +399,8 @@ describe('Tree-owned task boards', () => {
}
})
it('constructs with the default task limit and serializes concurrent task commits', async () => {
const { ctx, lead, teamFiber } = await setup([], {}, false)
it.each(['jsonl', 'sqlite'] as const)('%s: constructs with the default task limit and serializes concurrent task commits', async (storage) => {
const { ctx, lead, teamFiber } = await setup(storage, [], {}, false)
await teamFiber.dispose()
class DirectTeamService extends TeamService {
initialize(): Promise<void> { return this[Service.init]() }
@@ -415,10 +416,10 @@ describe('Tree-owned task boards', () => {
expect([first.id, second.id]).toEqual([brandString<TeamTaskId>('task-1'), brandString<TeamTaskId>('task-2')])
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
['create', 'disposed'], ['claim', 'disposed'], ['create', 'cancelled'], ['claim', 'cancelled'],
] as const)('rejects a queued %s after its caller is %s', async (action, stopped) => {
const { ctx, lead } = await setup([])
] as const).map(value => [storage, ...value] as const)))('%s: rejects a queued %s after its caller is %s', async (storage, action, stopped) => {
const { ctx, lead } = await setup(storage, [])
const child = await ctx.agents.create({
sessionId: brandString<SessionId>('queued-caller'), agentOptions: { provider: 'mock', model: 'mock' },
meta: { origin: 'subagent', parentSession: lead.id },
@@ -455,14 +456,14 @@ describe('Tree-owned task boards', () => {
}
})
it('does not treat a descriptor-backed Session without a parent as a Team member', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: does not treat a descriptor-backed Session without a parent as a Team member', async (storage) => {
const { ctx, lead } = await setup(storage, [])
lead.session.append('subagent/descriptor', { version: 3, mode: 'continuable', provider: 'spawn', label: 'forged' })
expect(() => ctx.agentTeams.listTasks(lead)).toThrow(expect.objectContaining({ code: 'UNAUTHORIZED' }))
})
it('does not reinterpret an orphaned subagent child as a Team root', async () => {
const { ctx } = await setup([textResponse('ordinary child done'), textResponse('orphan turn')])
it.each(['jsonl', 'sqlite'] as const)('%s: does not reinterpret an orphaned subagent child as a Team root', async (storage) => {
const { ctx } = await setup(storage, [textResponse('ordinary child done'), textResponse('orphan turn')])
const parent = await ctx.agents.create({
sessionId: brandString<SessionId>('temporary-parent'),
agentOptions: { provider: 'mock', model: 'mock' },
@@ -491,8 +492,8 @@ describe('Tree-owned task boards', () => {
})
describe('Team shared task DAG', () => {
it('fails loudly when the durable numeric task id space is exhausted', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: fails loudly when the durable numeric task id space is exhausted', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const id = brandString<TeamTaskId>(`task-${Number.MAX_SAFE_INTEGER}`)
lead.session.append('team/task', {
version: 2,
@@ -515,8 +516,8 @@ describe('Team shared task DAG', () => {
})).rejects.toMatchObject({ code: 'TEAM_TASK_LIMIT' })
})
it('bounds non-deleted tasks while retaining deleted task ids as tombstones', async () => {
const { ctx, lead } = await setup([], { maxTasks: 1 })
it.each(['jsonl', 'sqlite'] as const)('%s: bounds non-deleted tasks while retaining deleted task ids as tombstones', async (storage) => {
const { ctx, lead } = await setup(storage, [], { maxTasks: 1 })
const first = await ctx.agentTeams.createTask(lead, { subject: 'first', description: 'first task' })
await expect(ctx.agentTeams.createTask(lead, { subject: 'overflow', description: 'overflow task' }))
.rejects.toMatchObject({ code: 'TEAM_TASK_LIMIT' })
@@ -533,8 +534,8 @@ describe('Team shared task DAG', () => {
expect(ctx.agentTeams.listTasks(lead).map(task => task.id)).toEqual([second.id])
})
it('enforces CAS, ownership, dependencies, transitions, and write-scope warnings', async () => {
const { ctx, lead } = await setup(['hang', 'hang', textResponse('beta integrated update')])
it.each(['jsonl', 'sqlite'] as const)('%s: enforces CAS, ownership, dependencies, transitions, and write-scope warnings', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang', 'hang', textResponse('beta integrated update')])
const firstMember = await spawn(ctx, lead, 'alpha')
const alpha = await waitRunning(ctx, firstMember.childId)
const secondMember = await spawn(ctx, lead, 'beta')
@@ -609,8 +610,8 @@ describe('Team shared task DAG', () => {
await Promise.all([waitNoAgent(ctx, alpha.id), waitNoAgent(ctx, beta.id)])
})
it('rejects malformed scopes and every invalid dependency relation', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: rejects malformed scopes and every invalid dependency relation', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const first = await ctx.agentTeams.createTask(lead, { subject: 'one', description: 'one' })
const second = await ctx.agentTeams.createTask(lead, {
subject: 'two', description: 'two', blockedBy: [first.id],
@@ -643,8 +644,8 @@ describe('Team shared task DAG', () => {
}
})
it('rejects incomplete mutations, invalid transitions, and deletion of a live blocker', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: rejects incomplete mutations, invalid transitions, and deletion of a live blocker', async (storage) => {
const { ctx, lead } = await setup(storage, [])
await expect(ctx.agentTeams.createTask(lead, { subject: ' ', description: 'invalid' }))
.rejects.toMatchObject({ code: 'TEAM_INVALID_ARGUMENT' })
await expect(ctx.agentTeams.createTask(lead, { subject: 'invalid', description: '' }))
@@ -681,8 +682,8 @@ describe('Team shared task DAG', () => {
})).rejects.toMatchObject({ code: 'TEAM_TASK_HAS_DEPENDENTS' })
})
it('supports Lead reassignment, completion, reopen, and deletion permissions', async () => {
const { ctx, lead } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: supports Lead reassignment, completion, reopen, and deletion permissions', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'])
const started = await spawn(ctx, lead, 'owner')
const owner = await waitRunning(ctx, started.childId)
const task = await ctx.agentTeams.createTask(owner, { subject: 'lifecycle', description: 'lifecycle' })
@@ -738,8 +739,8 @@ describe('Team shared task DAG', () => {
await waitNoAgent(ctx, owner.id)
})
it('covers partial edits, Lead ownership, unassignment, and blocked reassignment', async () => {
const { ctx, lead } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: covers partial edits, Lead ownership, unassignment, and blocked reassignment', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'])
const started = await spawn(ctx, lead, 'editor')
const editor = await waitRunning(ctx, started.childId)
const blocker = await ctx.agentTeams.createTask(lead, { subject: 'blocker', description: 'blocker' })
@@ -825,8 +826,8 @@ describe('Team shared task DAG', () => {
})
describe('Task-board persistence', () => {
it('commits tasks without writing inboxes or starting idle agents', async () => {
const { ctx, lead, adapter } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: commits tasks without writing inboxes or starting idle agents', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [])
const alpha = await resident(ctx, lead, 'notify-alpha')
const beta = (await ctx.agents.create({
sessionId: brandString<SessionId>('notify-beta'), meta: { origin: 'subagent', parentSession: alpha.id },
@@ -852,8 +853,8 @@ describe('Task-board persistence', () => {
expect(adapter.requests).toHaveLength(0)
})
it('resolves task commits only after persistence succeeds', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: resolves task commits only after persistence succeeds', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const flush = ctx.sessions.flush.bind(ctx.sessions)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
@@ -888,8 +889,8 @@ describe('Task-board persistence', () => {
})).rejects.toMatchObject({ code: 'TEAM_TASK_STALE_REVISION' })
})
it('reports unconfirmed task revisions when no flush listener participates', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reports unconfirmed task revisions when no flush listener participates', async (storage) => {
const { ctx, lead } = await setup(storage, [])
vi.spyOn(ctx.sessions, 'flush').mockResolvedValue(false)
await expect(ctx.agentTeams.createTask(lead, { subject: 'unconfirmed', description: 'read before retrying' }))
@@ -70,14 +70,14 @@ afterEach(async () => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
async function setup(script: ConstructorParameters<typeof MockAdapter>[0], enabled = true) {
async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters<typeof MockAdapter>[0], enabled = true) {
const ctx = new Context()
contexts.add(ctx)
await mountAgentLoopTestDependencies(ctx)
await mountWorkingDirectoryFixture(ctx)
const storageRoot = mkdtempSync(join(tmpdir(), 'dsh-tool-team-'))
roots.push(storageRoot)
await ctx.plugin(JsonlSessionPersistence, { root: storageRoot })
await ctx.plugin(JsonlSessionPersistence, { storage, root: storageRoot })
await ctx.plugin(TestSessionQuery)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentService)
@@ -184,8 +184,8 @@ async function waitNoAgent(ctx: Context, id: SessionId): Promise<void> {
}
describe('dsh-tool-team', () => {
it.each([true, false])('cancels reassignment without appending when discovery observes cancellation: %s', async (observesCancellation) => {
const { ctx, lead } = await setup(['hang'])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([true, false]).map(value => [storage, value] as const)))('%s: cancels reassignment without appending when discovery observes cancellation: %s', async (storage, observesCancellation) => {
const { ctx, lead } = await setup(storage, ['hang'])
const childActivation = await spawn(ctx, lead, 'worker', 'stay running')
const childId = childActivation.childId
await waitRunning(ctx, childId)
@@ -215,8 +215,8 @@ describe('dsh-tool-team', () => {
expect((await stored.read()).events.filter(event => event.type === 'team/task')).toHaveLength(1)
})
it('accepts and reports task owners by agent name', async () => {
const { ctx, lead } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: accepts and reports task owners by agent name', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'])
const childActivation = await spawn(ctx, lead, 'worker', 'stay running')
await waitRunning(ctx, childActivation.childId)
const task = await ctx.agentTeams.createTask(lead, { subject: 'work', description: 'assign by name' })
@@ -235,8 +235,8 @@ describe('dsh-tool-team', () => {
await waitNoAgent(ctx, childActivation.childId)
})
it('keeps Team tools local when an external activation starts and settles', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps Team tools local when an external activation starts and settles', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const externalId = brandString<SessionId>('team-external-result')
ctx.effect(() => ctx.subagents.registerProvider({
name: 'external-team-fixture', inheritsParentContext: false, capabilities: NO_START_CAPABILITIES,
@@ -260,8 +260,8 @@ describe('dsh-tool-team', () => {
}
})
it('adds task tools and policy alongside shared subagent identity', async () => {
const { ctx, lead } = await setup(['hang', 'hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: adds task tools and policy alongside shared subagent identity', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang', 'hang'])
const leadAssembly = await assembly(ctx, lead)
expect(teamTools(leadAssembly)).toEqual(TEAM_TOOLS)
const teamTool = (name: string) => ctx.tools.get(name, scopeOf(lead.ctx))
@@ -300,10 +300,10 @@ describe('dsh-tool-team', () => {
await Promise.all([waitNoAgent(ctx, namedId), waitNoAgent(ctx, unnamedId)])
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
['spawn', undefined], ['fork', undefined], ['fork', 'in-history'],
] as const)('records %s teammate identity with update mode %s and keeps the wire prefix', async (provider, systemPromptUpdate) => {
const { ctx, lead, adapter } = await setup([textResponse('parent answer'), textResponse('child answer')])
] as const).map(value => [storage, ...value] as const)))('%s: records %s teammate identity with update mode %s and keeps the wire prefix', async (storage, provider, systemPromptUpdate) => {
const { ctx, lead, adapter } = await setup(storage, [textResponse('parent answer'), textResponse('child answer')])
if (systemPromptUpdate !== undefined) adapter.systemPromptUpdate = systemPromptUpdate
await runTurn(lead, 'Parent task')
const parentRequest = serializeRequest(adapter.requests[0]!)
@@ -323,8 +323,8 @@ describe('dsh-tool-team', () => {
expect(runtimeContextText(adapter.requests[1]!)).toContain(agentIdentity('agent-1'))
})
it('reuses the inherited Lead identity in an ordinary fork', async () => {
const { ctx, lead, adapter } = await setup([textResponse('parent answer'), textResponse('fork answer')])
it.each(['jsonl', 'sqlite'] as const)('%s: reuses the inherited Lead identity in an ordinary fork', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [textResponse('parent answer'), textResponse('fork answer')])
await runTurn(lead, 'Parent task')
const seed = lead.session.snapshotEvents()
const handle = await ctx.agents.create({
@@ -351,8 +351,8 @@ describe('dsh-tool-team', () => {
await handle.dispose()
})
it('identifies nested descendants with the tree root rather than their direct parent', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: identifies nested descendants with the tree root rather than their direct parent', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const child = await ctx.agents.create({
sessionId: brandString<SessionId>('identity-child'),
meta: { parentSession: lead.id, origin: 'subagent' },
@@ -367,8 +367,8 @@ describe('dsh-tool-team', () => {
expect(renderContextSnapshot(await assembly(ctx, nested.agent))).not.toContain(`The root agent of your collaboration tree is ${JSON.stringify(child.agent.id)}.`)
})
it.each([undefined, 'in-history'] as const)('appends current Lead identity to a teammate fork with update mode %s', async (systemPromptUpdate) => {
const { ctx, lead, adapter } = await setup([textResponse('review done'), textResponse('lead notified'), textResponse('fork answer')])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([undefined, 'in-history'] as const).map(value => [storage, value] as const)))('%s: appends current Lead identity to a teammate fork with update mode %s', async (storage, systemPromptUpdate) => {
const { ctx, lead, adapter } = await setup(storage, [textResponse('review done'), textResponse('lead notified'), textResponse('fork answer')])
if (systemPromptUpdate !== undefined) adapter.systemPromptUpdate = systemPromptUpdate
const teammateActivation = await spawn(ctx, lead, 'reviewer', 'Review the work')
const teammateId = teammateActivation.childId
@@ -400,8 +400,8 @@ describe('dsh-tool-team', () => {
}
})
it('restores compacted identity and does not repeat an unchanged retained snapshot', async () => {
const { ctx, lead, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: restores compacted identity and does not repeat an unchanged retained snapshot', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [
toolCallResponse('first-list', 'team_task_list', {}),
toolCallResponse('second-list', 'team_task_list', {}),
textResponse('done'),
@@ -435,8 +435,8 @@ describe('dsh-tool-team', () => {
&& event.data.source.kind === 'runtime-context')).toHaveLength(2)
})
it('keeps required agent identities when optional runtime context is suppressed', async () => {
const { ctx, lead, adapter } = await setup([textResponse('worker done')])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps required agent identities when optional runtime context is suppressed', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [textResponse('worker done')])
ctx.systemPrompt.suppressRuntimeContext()
const childActivation = await spawn(ctx, lead, 'reviewer', 'Review the work')
const childId = childActivation.childId
@@ -445,8 +445,8 @@ describe('dsh-tool-team', () => {
expect(runtimeContextText(adapter.requests[0]!)).toContain(agentIdentity('agent-1'))
})
it('keeps ordinary inbox waiting when the task plugin unloads', async () => {
const { ctx, lead, fiber } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps ordinary inbox waiting when the task plugin unloads', async (storage) => {
const { ctx, lead, fiber } = await setup(storage, [])
await fiber.dispose()
lead.inject(createUserMessage({ content: [{ type: 'text', text: 'pending input' }], source: { kind: 'user' } }))
const result = await execute(ctx, lead, 'wait_agent', {})
@@ -455,8 +455,8 @@ describe('dsh-tool-team', () => {
expect(lead.inbox.nextStep).toHaveLength(1)
})
it('adapts task CAS operations and waits to canonical JSON', async () => {
const { ctx, lead } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: adapts task CAS operations and waits to canonical JSON', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'])
const childActivation = await spawn(ctx, lead, 'json-worker', 'wait')
const childId = childActivation.childId
const child = await waitRunning(ctx, childId)
@@ -506,8 +506,8 @@ describe('dsh-tool-team', () => {
await waitNoAgent(ctx, childId)
})
it('adapts optional task filters, mutations, pagination, and default waiting', async () => {
const { ctx, lead } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: adapts optional task filters, mutations, pagination, and default waiting', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'])
const childActivation = await spawn(ctx, lead, 'fork-worker', 'stay active', 'fork')
const childId = childActivation.childId
await waitRunning(ctx, childId)
@@ -580,8 +580,8 @@ describe('dsh-tool-team', () => {
await waitNoAgent(ctx, childId)
})
it('distinguishes an agent named unowned from tasks without an owner', async () => {
const { ctx, lead } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: distinguishes an agent named unowned from tasks without an owner', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'])
const child = await ctx.subagents.startActivation({
provider: 'spawn', name: 'unowned', label: 'Worker', parent: lead,
prompt: [{ type: 'text', text: 'wait' }], signal: SIGNAL, delivery: 'caller',
@@ -600,8 +600,8 @@ describe('dsh-tool-team', () => {
await child.dispose()
})
it('reads and edits saved owner names without traversing descendant Sessions', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reads and edits saved owner names without traversing descendant Sessions', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const created = await ctx.agentTeams.createTask(lead, { subject: 'Review', description: 'Saved ownership' })
const { ready: _ready, writeScopeWarnings: _warnings, ...saved } = created
lead.session.append('team/task', {
@@ -619,8 +619,8 @@ describe('dsh-tool-team', () => {
expect(lookup).not.toHaveBeenCalled()
})
it('names a historical task owner by its Session id', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: names a historical task owner by its Session id', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const task = await ctx.agentTeams.createTask(lead, { subject: 'Review', description: 'Read old ownership' })
const { ready: _ready, writeScopeWarnings: _warnings, ...saved } = task
lead.session.append('team/task', {
@@ -631,8 +631,8 @@ describe('dsh-tool-team', () => {
.toMatchObject({ owner: 'missing-worker' })
})
it('edits a task whose historical owner is outside the readable catalogs', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: edits a task whose historical owner is outside the readable catalogs', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const created = await ctx.agentTeams.createTask(lead, { subject: 'Review', description: 'Read old ownership' })
const { ready: _ready, writeScopeWarnings: _warnings, ...saved } = created
lead.session.append('team/task', {
@@ -653,8 +653,8 @@ describe('dsh-tool-team', () => {
expect(lead.session.ownEvents().filter(event => event.type === 'team/task')).toHaveLength(3)
})
it.each([false, true])('rejects historical roster assignments without a readable continuable target (cataloged: %s)', async (cataloged) => {
const { ctx, lead } = await setup([])
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: rejects historical roster assignments without a readable continuable target (cataloged: %s)', async (storage, cataloged) => {
const { ctx, lead } = await setup(storage, [])
const id = brandString<SessionId>('historical-worker')
for (const phase of ['provisioning', 'active'] as const) lead.session.append('team/member', {
version: 2, teamId: brandString<TeamId>(lead.id),
@@ -672,8 +672,8 @@ describe('dsh-tool-team', () => {
})).isError).toBe(true)
})
it('removes and reinstalls every Team registration across plugin HMR without stopping the child', async () => {
const { ctx, lead, fiber } = await setup(['hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: removes and reinstalls every Team registration across plugin HMR without stopping the child', async (storage) => {
const { ctx, lead, fiber } = await setup(storage, ['hang'])
const childActivation = await spawn(ctx, lead, 'hmr-worker', 'wait')
const childId = childActivation.childId
const child = await waitRunning(ctx, childId)
@@ -699,8 +699,8 @@ describe('dsh-tool-team', () => {
await replacement.dispose()
})
it('installs tools once when the plugin activates as Agent creation dispatch begins', async () => {
const { ctx, lead, fiber } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: installs tools once when the plugin activates as Agent creation dispatch begins', async (storage) => {
const { ctx, lead, fiber } = await setup(storage, [])
await fiber.dispose()
const id = brandString<SessionId>('install-during-publication')
const stop = ctx.on('internal/dispatch', (_type, name) => {
@@ -724,8 +724,8 @@ describe('dsh-tool-team', () => {
}
})
it('leaves all current waits pending when tasks change', async () => {
const { ctx, lead, adapter } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: leaves all current waits pending when tasks change', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [])
const child = await ctx.agents.create({
sessionId: brandString<SessionId>('waiting-child'), agentOptions: { provider: 'mock', model: 'mock' },
meta: { origin: 'subagent', parentSession: lead.id },
@@ -756,8 +756,8 @@ describe('dsh-tool-team', () => {
expect(vi.getTimerCount()).toBe(0)
})
it('keeps waiting across Team mode changes until its own inbox receives input', async () => {
const { ctx, lead, adapter } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps waiting across Team mode changes until its own inbox receives input', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [])
vi.useFakeTimers()
const waiting = await startWait(ctx, lead)
let returned = false
@@ -776,8 +776,8 @@ describe('dsh-tool-team', () => {
expect(await waiting.result).toMatchObject({ isError: false, value: { timedOut: false } })
})
it('keeps waiting across successful and failed task flushes', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: keeps waiting across successful and failed task flushes', async (storage) => {
const { ctx, lead } = await setup(storage, [])
vi.useFakeTimers()
const flush = ctx.sessions.flush.bind(ctx.sessions)
const entered = Promise.withResolvers<undefined>()
@@ -812,8 +812,8 @@ describe('dsh-tool-team', () => {
expect(await afterCommit.result).toMatchObject({ isError: false, value: { timedOut: true } })
})
it('rolls back plugin registrations after a global tool collision', async () => {
const { ctx, lead, fiber } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: rolls back plugin registrations after a global tool collision', async (storage) => {
const { ctx, lead, fiber } = await setup(storage, [])
await fiber.dispose()
ctx.tools.register(defineContentToolFixture({
name: 'team_task_create',
@@ -828,8 +828,8 @@ describe('dsh-tool-team', () => {
expect(assembled.contexts.some(context => context.name === 'team:identity')).toBe(false)
})
it('applies directly without configuration and rejects removed configuration keys', async () => {
const { ctx, lead, fiber } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: applies directly without configuration and rejects removed configuration keys', async (storage) => {
const { ctx, lead, fiber } = await setup(storage, [])
await fiber.dispose()
for (const key of ['interrupt', 'freshProvider', 'forkProvider']) {
expect(() => { toolTeam.apply(ctx, { [key]: 'x' }) }).toThrow(`${key} is no longer supported`)
@@ -838,8 +838,8 @@ describe('dsh-tool-team', () => {
expect(teamTools(await assembly(ctx, lead))).toEqual(TEAM_TOOLS)
})
it('switches tools and guidance for one tree while preserving tasks and ordinary subagents', async () => {
const { ctx, lead } = await setup(['hang'], false)
it.each(['jsonl', 'sqlite'] as const)('%s: switches tools and guidance for one tree while preserving tasks and ordinary subagents', async (storage) => {
const { ctx, lead } = await setup(storage, ['hang'], false)
const other = await ctx.agents.create({ sessionId: brandString<SessionId>('other-root'), agentOptions: { provider: 'mock', model: 'mock' } })
const child = await waitRunning(ctx, (await spawn(ctx, lead, 'ordinary-child', 'work')).childId)
for (const agent of [lead, child, other.agent]) expect(teamTools(await assembly(ctx, agent))).toEqual([])
@@ -862,8 +862,8 @@ describe('dsh-tool-team', () => {
await other.dispose()
})
it('updates model requests when Team is switched on and off within a turn', async () => {
const { ctx, lead, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: updates model requests when Team is switched on and off within a turn', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [
toolCallResponse('before-team', 'list_agents', {}),
toolCallResponse('with-team', 'list_agents', {}),
textResponse('ordinary work continues'),
@@ -895,8 +895,8 @@ describe('dsh-tool-team', () => {
}
})
it('keeps tools consistent with an appended selection if flushing fails, and permits retry', async () => {
const { ctx, lead } = await setup([], false)
it.each(['jsonl', 'sqlite'] as const)('%s: keeps tools consistent with an appended selection if flushing fails, and permits retry', async (storage) => {
const { ctx, lead } = await setup(storage, [], false)
const failure = new Error('storage unavailable')
vi.spyOn(ctx.sessions, 'flush').mockRejectedValueOnce(failure)
await expect(ctx.agentTeams.setEnabled(lead, true)).rejects.toBe(failure)
@@ -905,8 +905,8 @@ describe('dsh-tool-team', () => {
expect(lead.session.ownEvents().filter(event => event.type === 'team/mode')).toHaveLength(1)
})
it('finishes an admitted task mutation after Team is disabled', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: finishes an admitted task mutation after Team is disabled', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const flush = ctx.sessions.flush.bind(ctx.sessions)
@@ -936,8 +936,8 @@ describe('dsh-tool-team', () => {
expect(ctx.agentTeams.listTasks(lead)).toEqual([expect.objectContaining({ subject: 'started' })])
})
it('reads Team mode for prompts independently of tool restrictions', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: reads Team mode for prompts independently of tool restrictions', async (storage) => {
const { ctx, lead } = await setup(storage, [])
lead.ctx.tools.restrict({ deny: TEAM_TOOLS })
const built = await assembly(ctx, lead)
expect(teamTools(built)).toEqual([])
@@ -949,8 +949,8 @@ describe('dsh-tool-team', () => {
expect(renderContextSnapshot(disabled)).toContain(leadIdentity(lead))
})
it('keeps step admission stable while task operations enforce the current mode', async () => {
const { ctx, lead } = await setup([], false)
it.each(['jsonl', 'sqlite'] as const)('%s: keeps step admission stable while task operations enforce the current mode', async (storage) => {
const { ctx, lead } = await setup(storage, [], false)
const resolve = () => ctx.tools.resolve({ agent: lead, modelSelection: { provider: 'mock', model: 'mock' }, signal: SIGNAL })
const disabled = await resolve()
await ctx.agentTeams.setEnabled(lead, true)
@@ -972,8 +972,8 @@ describe('dsh-tool-team', () => {
}
})
it('installs Team scope before a cold-resumed teammate request', async () => {
const { ctx, lead, adapter } = await setup([textResponse('first'), textResponse('lead received settlement'), 'hang'])
it.each(['jsonl', 'sqlite'] as const)('%s: installs Team scope before a cold-resumed teammate request', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [textResponse('first'), textResponse('lead received settlement'), 'hang'])
const childActivation = await spawn(ctx, lead, 'cold-worker', 'finish once')
const childId = childActivation.childId
await waitNoAgent(ctx, childId)
@@ -994,8 +994,8 @@ describe('dsh-tool-team', () => {
await waitNoAgent(ctx, childId)
})
it('keeps Team tools absent while an orphaned subagent continues ordinary work', async () => {
const { ctx, lead, adapter } = await setup([
it.each(['jsonl', 'sqlite'] as const)('%s: keeps Team tools absent while an orphaned subagent continues ordinary work', async (storage) => {
const { ctx, lead, adapter } = await setup(storage, [
textResponse('child done'), textResponse('parent received settlement'), textResponse('independent work done'),
])
const parent = await ctx.agents.create({
@@ -1032,18 +1032,18 @@ describe('dsh-tool-team', () => {
await orphan.dispose()
})
it.each([
it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([
new Error('root lookup failed'),
new SubagentError('root lookup failed', 'CONTINUATION_UNAVAILABLE'),
])('propagates unexpected identity lookup failures: %s', async (failure) => {
const { ctx, lead } = await setup([])
]).map(value => [storage, value] as const)))('%s: propagates unexpected identity lookup failures: %s', async (storage, failure) => {
const { ctx, lead } = await setup(storage, [])
vi.spyOn(ctx.subagents, 'rootOf').mockImplementation(() => { throw failure })
await expect(assembly(ctx, lead)).rejects.toMatchObject({ code: 'TOOL_ACTIVATION_FAILED', cause: failure })
await expect(ctx.systemPrompt.assemble({ scope: lead, agent: lead })).rejects.toBe(failure)
})
it('omits Team guidance when its root is unavailable', async () => {
const { ctx, lead } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: omits Team guidance when its root is unavailable', async (storage) => {
const { ctx, lead } = await setup(storage, [])
const unavailable = (): never => { throw new SubagentError('Team root is unavailable', 'UNAUTHORIZED') }
vi.spyOn(ctx.subagents, 'rootOf').mockImplementation(unavailable)
vi.spyOn(ctx.subagents, 'namesOf').mockImplementation(unavailable)
@@ -1052,8 +1052,8 @@ describe('dsh-tool-team', () => {
expect(context).not.toContain('You are a teammate in the Team')
})
it('fails safely without a calling Agent and has the function-plugin export shape', async () => {
const { ctx } = await setup([])
it.each(['jsonl', 'sqlite'] as const)('%s: fails safely without a calling Agent and has the function-plugin export shape', async (storage) => {
const { ctx } = await setup(storage, [])
const result = await execute(ctx, undefined, 'team_task_list', {})
expect(result.isError).toBe(true)
expect(text(result)).toContain('unknown tool "team_task_list"')
@@ -21,8 +21,8 @@
en: 57ff7c89e7696ee8
zh: b885ac1b4edc8c56
/deepseek-ai-dsh-session-snapshot/use-this-package/record-replay-and-refresh:
en: bd9dcb62ea4e77db
zh: be9615f0ae662c9e
en: d671025e0e040248
zh: 0b1ca30b1a6eb239
/deepseek-ai-dsh-session-snapshot/use-this-package/pinning-request-headers-and-system-prompts:
en: fe59b0197fa5e34c
zh: dfa1844c2c965358
@@ -30,14 +30,14 @@
en: 64666ea2894acc4a
zh: 0e78df32bcfd3633
/deepseek-ai-dsh-session-snapshot/use-this-package/what-can-go-wrong:
en: 0b03592947ca43d6
zh: b14a64238c4b5f80
en: badae14e4c6432fc
zh: 8c601a8386659e00
/deepseek-ai-dsh-session-snapshot/understand-the-implementation:
en: 18ff76b440fe40da
zh: 4dbf2eb5f9ee98a2
/deepseek-ai-dsh-session-snapshot/understand-the-implementation/design:
en: 8771607f15c4f4e1
zh: 7c2cf395f704717c
en: 30dc1a78497bee82
zh: 7904f391efdaed64
/deepseek-ai-dsh-session-snapshot/understand-the-implementation/source-map:
en: 1510b3b09c3bd553
zh: 1931fba0891f7d65
@@ -54,8 +54,8 @@
en: ca75c51c89c2c9b0
zh: f57cc48a1b5cbfa9
/deepseek-ai-dsh-session-snapshot/known-limitations-and-deferred-work:
en: 42e871839dddaf6d
zh: b7ab1d313527612b
en: 884c1b84c249a917
zh: 437f9046f5dfed57
/deepseek-ai-dsh-session-snapshot/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
@@ -88,6 +88,8 @@ For an initial headless live recording with no Session file, temporarily set `in
A nested `workspace.expected/<directory>/.empty` marker represents an empty directory; a marker in the actual workspace remains a regular file.
`DSH_SNAPSHOT_STORAGE` selects `jsonl` (default) or `sqlite` for subprocess and Web snapshot tests. Both backends use the same expected fixtures. Comparable logs are parsed as JSON records: object field order is ignored, while every field value, event count, event order, and array order remains significant.
### Pinning request headers and system prompts
A pin owns its generated `system-prompt.expected.md` or `tool-schemas.expected.json` sidecar by default; `systemPromptSource` and `toolSchemasSource` name another pin when the complete corresponding sequence is identical, so each distinct version is committed once. The system prompt is surface node 0, logged as a `system/message` event before the step's first `request/header`; every fixture stores its text block as `"text":"{{system}}"` and the prompt sidecar keeps the full text. The pin's `request/header` events store `"tools":"{{tools}}"` while retaining config and reason, and the structured schema sidecar keeps the full catalogs. Logs containing developer messages retain ordered tool names in each header instead of the token so historical addition references remain verifiable. A child Session whose own scope composes a different request declares it per fixture index with `pinsChildToolSchemas` and `pinsChildSystemPrompts`. A scenario that changes the request header mid-run declares `expectedHeaderChanges`; a scenario whose prompt changes mid-run — replacing node 0, or appending after the cached history on an `in-history` route — declares `expectedPromptChanges`, and each change adds a `<!-- system/message change N -->` section to the prompt sidecar. The manifest spells these `header.changes` and `header.promptChanges`. Headers without tools retain an empty schema set in the sidecar, so the first later addition stays aligned with its header.
@@ -100,7 +102,6 @@ A scenario requiring a non-Windows host declares `posixOnly`, which skips its ru
- **A durable wait times out** — `waitForTurnStart`, `waitForTurnEnd`, `waitForSubagentTurnEnd`, `waitForGoalPhase`, `waitForInboxMessage`, `waitForTitleAfterTurnEnd`, and `waitForEventAfterTurnEnd` identify the session or child and deadline even when the first log harvest exceeds that deadline. Child waits also name the requested turn. All retain the underlying failure as the error cause. `waitForTurnStart` rejects malformed turn records immediately.
- **A fixture guard rejects the committed files** — orphan scenario dirs, missing files, multiple pins for one header class, duplicate sidecar content, unscrubbed prompt text or tool schemas, a `request/header` with no preceding `system/message`, and malformed pinning headers all fail the suite before comparisons run.
- **The session harvest needs raw JSONL mode** — snapshot configs set the JSONL backend's `compression: 'none'`; compressed JSONL has no snapshot-harvest path.
- **Built mode needs current artifacts** — run `pnpm run build` before selecting `DSH_EXAMPLE_MODE=lib`; source mode remains the zero-build path.
-----
@@ -115,7 +116,7 @@ This section explains the design of the kit; the observable behavior is fully co
### Design
The shared core owns manifests, generation-qualified role selection, workspace setup/comparison, typed identity mapping, normalizers, and fixture invariants. The ACP adapter adds four composable layers: launcher, scenario harness, normalizers, and suite factory. `launchAcpTestAgent` boots a source profile under tsx or a built `lib` profile under plain Node, connects the SDK client over a raw-byte stdout tee, collects Session updates and stderr, fails closed on unhandled permission requests, and owns shutdown. `runScenario` drives ACP JSON-RPC stdio and harvests the numerically highest persisted raw JSONL generation for every Session directory. The pure normalizers replace cwd paths and typed identities with stable tokens, zero times, expand physical source-event ranges, and scrub system-prompt text and tool-schema bulk. `defineAcpSnapshotSuite` registers comparisons, generation-qualified fixture write-back, and the live uniformity guard.
The shared core owns manifests, generation-qualified role selection, workspace setup/comparison, typed identity mapping, normalizers, and fixture invariants. The ACP adapter adds four composable layers: launcher, scenario harness, normalizers, and suite factory. `launchAcpTestAgent` boots a source profile under tsx or a built `lib` profile under plain Node, connects the SDK client over a raw-byte stdout tee, collects Session updates and stderr, fails closed on unhandled permission requests, and owns shutdown. `runScenario` drives ACP JSON-RPC stdio and reads committed logical histories through `SessionPersistence.list/open/read`, including compressed JSONL and SQLite sessions. The pure normalizers replace cwd paths and typed identities with stable tokens, zero times, expand physical source-event ranges, and scrub system-prompt text and tool-schema bulk. `defineAcpSnapshotSuite` registers comparisons, generation-qualified fixture write-back, and the live uniformity guard.
### Source map
@@ -167,7 +168,6 @@ None; this package neither assembles nor sends a provider request.
These limits define when the kit needs special care. They are current package constraints, not a task backlog.
- **Session harvest requires raw JSONL mode** — `runScenario` collects persisted `.jsonl` logs, so snapshot configs set the JSONL backend's `compression: 'none'`; compressed JSONL has no snapshot-harvest path.
- **Built mode requires current artifacts** — run `pnpm run build` before selecting `DSH_EXAMPLE_MODE=lib`; source mode remains the zero-build path.
- **ACP remains for protocol behavior** — cancellation and permission round trips whose stimulus is the ACP client stay on that adapter; assembled one-shot and persistent-control behavior uses headless and SDK adapters.
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more