From 73b971fa16d74da4744a0502dc18a71451c2ef54 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Sat, 14 Nov 2026 12:04:31 +0800 Subject: [PATCH] test(session): run persistence consumers against both backends --- .../workflows/build-exe-for-python-sdk.yml | 12 +- .github/workflows/python-release.yml | 4 +- .../profiles/headless/tests/compaction.e2e.ts | 10 +- .../tests/profiles/headless/tests/harness.ts | 13 +- .../profiles/headless/tests/resume.e2e.ts | 12 +- apps/web/tests/message-actions.e2e.ts | 12 +- apps/web/tests/navigation-panes.e2e.ts | 22 +- apps/web/tests/preset-migration.snapshot.ts | 26 +- apps/web/tests/scaffold.ts | 24 +- packages/acp/acp/tests/approval.spec.ts | 20 +- packages/acp/acp/tests/bridge.spec.ts | 210 +++--- packages/acp/acp/tests/dispose.spec.ts | 42 +- packages/acp/acp/tests/edges.spec.ts | 20 +- packages/acp/acp/tests/harness.ts | 4 +- packages/acp/acp/tests/multi-session.spec.ts | 16 +- packages/acp/acp/tests/turns.spec.ts | 160 ++--- .../tests/projection-discovery.host.spec.ts | 24 +- .../tests/config-session-id.spec.ts | 34 +- .../agent-loop/tests/input-lifecycle.spec.ts | 20 +- .../tests/resource-lifecycle.spec.ts | 8 +- packages/core/agent-loop/tests/resume.spec.ts | 246 +++---- .../tests/serial-listener-review.spec.ts | 7 +- .../agent-loop/tests/shutdown-drain.spec.ts | 14 +- .../tests/directory-resume.spec.ts | 4 +- .../tests/composition.host.spec.ts | 11 +- .../tests/resume.host.spec.ts | 4 +- .../hooks-claude-code/tests/coverage-cases.ts | 8 +- .../hooks-codex/tests/coverage-cases.ts | 8 +- .../tests/relay-target-admission.host.spec.ts | 4 +- .../timeline/tests/config.spec.ts | 4 +- .../timeline/tests/controls.spec.ts | 22 +- .../timeline/tests/delegation.spec.ts | 10 +- .../timeline/tests/feedback.spec.ts | 16 +- .../experimental/timeline/tests/fixture.ts | 3 +- .../timeline/tests/history.spec.ts | 16 +- .../timeline/tests/host-process.mjs | 4 +- .../timeline/tests/persistence-process.e2e.ts | 6 +- .../timeline/tests/persistence.spec.ts | 22 +- .../experimental/timeline/tests/pull.spec.ts | 18 +- .../timeline/tests/reminders.spec.ts | 24 +- .../timeline/tests/reports.spec.ts | 110 ++-- .../timeline/tests/storage.spec.ts | 22 +- .../experimental/timeline/tests/tools.spec.ts | 40 +- .../timeline/tests/transfer.spec.ts | 60 +- .../tool-ralph/tests/integration.spec.ts | 18 +- .../tests/sqlite-integration.spec.ts | 6 +- .../translator/tests/audit.spec.ts | 44 +- .../translator/tests/deepseek.spec.ts | 64 +- .../translator/tests/paid-fixture.ts | 12 +- .../translator/tests/storage-fixture.ts | 16 +- .../translator/tests/storage-helper.spec.ts | 8 +- .../tests/storage-lifecycle.spec.ts | 14 +- .../tests/storage-settlement.spec.ts | 6 +- .../translator/tests/storage.spec.ts | 38 +- .../worktree/tests/archive.spec.ts | 58 +- .../tests/loader-composition.spec.ts | 5 +- .../llm/llm-retry/tests/persistence.spec.ts | 8 +- .../schedule/tests/change-notice.spec.ts | 12 +- .../schedule/tests/serial-delivery.spec.ts | 8 +- .../server/tests/built-scope-carrier.e2e.ts | 6 +- .../sdk/server/tests/plugin-apply.spec.ts | 27 +- packages/sdk/server/tests/resume.spec.ts | 14 +- packages/sdk/server/tests/server.spec.ts | 7 +- packages/sdk/server/tests/wait.spec.ts | 26 +- .../tests/load-path.e2e.ts | 4 +- .../session-query-sqlite/tests/sqlite.spec.ts | 12 +- .../tests/crash-recovery.e2e.ts | 20 +- .../tests/fixtures/crash-child.ts | 8 +- .../tests/feedback-composition.spec.ts | 13 +- .../tests/fixtures/legacy-persistence.ts | 6 +- .../tests/teardown-loader.e2e.ts | 28 +- .../session-title/tests/persistence.spec.ts | 8 +- .../shell/tool-bash/tests/integration.spec.ts | 8 +- .../tests/multi-subagent.spec.ts | 12 +- .../tests/subagent-fork-in-process.spec.ts | 40 +- .../tests/harness.ts | 4 +- .../tests/spawn-in-process.e2e.ts | 4 +- .../tests/subagent-spawn-in-process.spec.ts | 88 +-- .../subagent/tests/activation-policy.spec.ts | 38 +- .../subagent/tests/activation-presets.spec.ts | 28 +- .../tests/continuation-inheritance.spec.ts | 46 +- .../continuation-messages-adapter.spec.ts | 4 +- .../tests/continuation-presets.spec.ts | 56 +- .../subagent/tests/continuation.spec.ts | 614 +++++++++--------- .../subagent/tests/list-children.spec.ts | 78 +-- .../subagent/tests/local-activation.ts | 5 +- .../subagent/tests/parent-result.spec.ts | 8 +- .../subagent/tests/schedule-tools.spec.ts | 8 +- .../subagent/tests/sibling-messages.spec.ts | 64 +- .../subagent/tests/structured.spec.ts | 146 ++--- .../subagent/tests/working-directory.spec.ts | 16 +- .../tests/list-agents.spec.ts | 56 +- .../tests/tool-subagent-control.spec.ts | 100 +-- .../tests/preset-selection.spec.ts | 18 +- .../tool-subagent/tests/tool-subagent.spec.ts | 28 +- .../team/agent-team/tests/persistence.spec.ts | 9 + packages/team/agent-team/tests/team.spec.ts | 131 ++-- .../tool-agent-team/tests/tool-team.spec.ts | 152 ++--- .../session-snapshot/README.i18n.yaml | 16 +- .../test-support/session-snapshot/README.md | 6 +- .../session-snapshot/README.zh.md | 6 +- .../session-snapshot/src/harness.ts | 51 +- .../session-snapshot/src/launcher.ts | 8 +- .../session-snapshot/src/suite.ts | 3 +- .../tests/fixtures/fake-acp-agent.ts | 14 +- .../session-snapshot/tests/harness.spec.ts | 11 +- .../session-snapshot/tests/suite.spec.ts | 49 +- python/sdk/tests/test_smoke_model.py | 49 +- .../fixtures/python-sdk-session-reader.mjs | 26 + scripts/run-gates.spec.ts | 18 +- scripts/run-gates.ts | 25 +- scripts/smoke-python-runtime.py | 364 ++++++----- 112 files changed, 2309 insertions(+), 1970 deletions(-) create mode 100644 scripts/fixtures/python-sdk-session-reader.mjs diff --git a/.github/workflows/build-exe-for-python-sdk.yml b/.github/workflows/build-exe-for-python-sdk.yml index 35f5a33df1..941e72b0d5 100644 --- a/.github/workflows/build-exe-for-python-sdk.yml +++ b/.github/workflows/build-exe-for-python-sdk.yml @@ -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/upload-artifact@v7.0.1 diff --git a/.github/workflows/python-release.yml b/.github/workflows/python-release.yml index 0474ccfe92..69ec2303d2 100644 --- a/.github/workflows/python-release.yml +++ b/.github/workflows/python-release.yml @@ -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 diff --git a/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts b/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts index 4f3edd44ed..c69cf90f08 100644 --- a/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/compaction.e2e.ts @@ -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('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) }) diff --git a/apps/cli/tests/profiles/headless/tests/harness.ts b/apps/cli/tests/profiles/headless/tests/harness.ts index 43164c9d7b..0bbf37ab78 100644 --- a/apps/cli/tests/profiles/headless/tests/harness.ts +++ b/apps/cli/tests/profiles/headless/tests/harness.ts @@ -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 diff --git a/apps/cli/tests/profiles/headless/tests/resume.e2e.ts b/apps/cli/tests/profiles/headless/tests/resume.e2e.ts index fe1c68cd56..546d9a5236 100644 --- a/apps/cli/tests/profiles/headless/tests/resume.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/resume.e2e.ts @@ -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' }, diff --git a/apps/web/tests/message-actions.e2e.ts b/apps/web/tests/message-actions.e2e.ts index f138a997b5..bff88c25cb 100644 --- a/apps/web/tests/message-actions.e2e.ts +++ b/apps/web/tests/message-actions.e2e.ts @@ -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([]) diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 0b2aeb56eb..c2635977ad 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -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(SEED_ID)) expect(snapshot?.header.id).toBe(SEED_ID) - expect(snapshot?.location).toBeUndefined() + const sourcePath = generationLogPath(scaffold.persistenceRoot, scaffold.workspaceCwd, + brandString(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') diff --git a/apps/web/tests/preset-migration.snapshot.ts b/apps/web/tests/preset-migration.snapshot.ts index a9fe2c1a0a..fa0a5a395a 100644 --- a/apps/web/tests/preset-migration.snapshot.ts +++ b/apps/web/tests/preset-migration.snapshot.ts @@ -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 => { + 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('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() } diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index d3528d9eec..4ead0043f3 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -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 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 { 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() diff --git a/packages/acp/acp/tests/approval.spec.ts b/packages/acp/acp/tests/approval.spec.ts index 300be2b040..7899c31136 100644 --- a/packages/acp/acp/tests/approval.spec.ts +++ b/packages/acp/acp/tests/approval.spec.ts @@ -27,8 +27,8 @@ describe('ACP machine permission policy', () => { return { agent, toolName: 'bash', callId: brandString('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') diff --git a/packages/acp/acp/tests/bridge.spec.ts b/packages/acp/acp/tests/bridge.spec.ts index 7e2bc160ab..60fdc85e0a 100644 --- a/packages/acp/acp/tests/bridge.spec.ts +++ b/packages/acp/acp/tests/bridge.spec.ts @@ -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 = 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(created.sessionId))! @@ -164,8 +164,8 @@ describe('automation-only ACP bridge', () => { expect(harness.ctx.agents.get(brandString(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('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(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('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))?.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))?.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/) diff --git a/packages/acp/acp/tests/dispose.spec.ts b/packages/acp/acp/tests/dispose.spec.ts index 9ee0912839..0ecc2388f8 100644 --- a/packages/acp/acp/tests/dispose.spec.ts +++ b/packages/acp/acp/tests/dispose.spec.ts @@ -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))! @@ -32,9 +32,9 @@ describe('ACP connection ownership', () => { expect(harness.ctx.agents.get(brandString(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))).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))).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() harness.ctx.provide('subagents', { @@ -124,8 +124,8 @@ describe('ACP connection ownership', () => { expect(harness.ctx.agents.get(brandString(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))).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() 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() @@ -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))! @@ -270,8 +270,8 @@ describe('ACP connection ownership', () => { expect(harness.ctx.agents.get(brandString(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) }) diff --git a/packages/acp/acp/tests/edges.spec.ts b/packages/acp/acp/tests/edges.spec.ts index 44c626befa..8b1501a682 100644 --- a/packages/acp/acp/tests/edges.spec.ts +++ b/packages/acp/acp/tests/edges.spec.ts @@ -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))! @@ -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 = () => {} diff --git a/packages/acp/acp/tests/harness.ts b/packages/acp/acp/tests/harness.ts index 077ef05cba..9c2744ecba 100644 --- a/packages/acp/acp/tests/harness.ts +++ b/packages/acp/acp/tests/harness.ts @@ -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: [] }) diff --git a/packages/acp/acp/tests/multi-session.spec.ts b/packages/acp/acp/tests/multi-session.spec.ts index 3ad7e1b5e5..c7146e23fb 100644 --- a/packages/acp/acp/tests/multi-session.spec.ts +++ b/packages/acp/acp/tests/multi-session.spec.ts @@ -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 diff --git a/packages/acp/acp/tests/turns.spec.ts b/packages/acp/acp/tests/turns.spec.ts index c212ef1c0f..e536e10dac 100644 --- a/packages/acp/acp/tests/turns.spec.ts +++ b/packages/acp/acp/tests/turns.spec.ts @@ -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))! 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))! 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))! 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))! 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))?.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() const releaseValidation = Promise.withResolvers() 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() const releaseValidation = Promise.withResolvers() 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() const releaseValidation = Promise.withResolvers() 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() const releaseValidation = Promise.withResolvers() 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))! 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))! @@ -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))! @@ -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))! 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))?.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() const children = Promise.withResolvers() @@ -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) diff --git a/packages/api/session-controller/tests/projection-discovery.host.spec.ts b/packages/api/session-controller/tests/projection-discovery.host.spec.ts index 52a9041ed3..116d8ea871 100644 --- a/packages/api/session-controller/tests/projection-discovery.host.spec.ts +++ b/packages/api/session-controller/tests/projection-discovery.host.spec.ts @@ -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> +type Harness = Awaited> 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('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('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 () => { diff --git a/packages/core/agent-loop/tests/config-session-id.spec.ts b/packages/core/agent-loop/tests/config-session-id.spec.ts index 2640a58cca..a1bdd3aa49 100644 --- a/packages/core/agent-loop/tests/config-session-id.spec.ts +++ b/packages/core/agent-loop/tests/config-session-id.spec.ts @@ -59,7 +59,7 @@ async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise { +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('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('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('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() 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('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('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('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('main'), provider: 'mock', model: 'mock', resumeSessionId: brandString('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('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('main'), ...route, resumeSessionId: brandString('sticky-route') }] }) await expect.poll(() => ctx2.agents.get(brandString('sticky-route')), { timeout: 5_000 }).toBeDefined() const resumed = ctx2.agents.get(brandString('sticky-route'))! @@ -530,7 +530,7 @@ describe('config-driven session id', () => { await ctx.plugin(AgentLoop, { agents: [{ id: brandString('main'), provider: 'mock', model: 'mock', resumeSessionId: brandString('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 diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 2c6d5fed0c..6b666e86df 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -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() const release = Promise.withResolvers() 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() 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() const release = Promise.withResolvers() const signal = new AbortController() diff --git a/packages/core/agent-loop/tests/resource-lifecycle.spec.ts b/packages/core/agent-loop/tests/resource-lifecycle.spec.ts index 581ae0340b..a83598e3aa 100644 --- a/packages/core/agent-loop/tests/resource-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/resource-lifecycle.spec.ts @@ -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() 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() diff --git a/packages/core/agent-loop/tests/resume.spec.ts b/packages/core/agent-loop/tests/resume.spec.ts index 976cae3e1b..63a187fc32 100644 --- a/packages/core/agent-loop/tests/resume.spec.ts +++ b/packages/core/agent-loop/tests/resume.spec.ts @@ -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 { +async function mountPersistentHarness(storage: 'jsonl' | 'sqlite', root: string, adapter: MockAdapter, compression?: 'none'): Promise { const ctx = new Context() await ctx.plugin(LlmRuntime) await ctx.plugin(SessionStore) @@ -81,8 +81,8 @@ async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise { - const { ctx, root } = await persistentHarness(new MockAdapter([])) +async function persistSession(storage: 'jsonl' | 'sqlite', sessionId: SessionId): Promise { + 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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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('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() const setupStarted = Promise.withResolvers() 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('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('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('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('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('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('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() const setupStarted = Promise.withResolvers() 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('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() const openStarted = Promise.withResolvers() 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('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() @@ -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('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('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('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('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('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('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('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('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() const setupGate = Promise.withResolvers() @@ -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('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 => { const sessionId = brandString(`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('create-abandoned-handle') - const { ctx } = await persistentHarness(new MockAdapter([])) + const { ctx } = await persistentHarness(storage, new MockAdapter([])) const lateCreate = Promise.withResolvers() const createStarted = Promise.withResolvers() 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('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('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() const openStarted = Promise.withResolvers() 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('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() gate.promise.catch(() => undefined) const openStarted = Promise.withResolvers() @@ -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('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('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() gate.promise.catch(() => undefined) diff --git a/packages/core/agent-loop/tests/serial-listener-review.spec.ts b/packages/core/agent-loop/tests/serial-listener-review.spec.ts index dcb3836118..d7aa7667c6 100644 --- a/packages/core/agent-loop/tests/serial-listener-review.spec.ts +++ b/packages/core/agent-loop/tests/serial-listener-review.spec.ts @@ -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[] = [] diff --git a/packages/core/agent-loop/tests/shutdown-drain.spec.ts b/packages/core/agent-loop/tests/shutdown-drain.spec.ts index 4587164af4..c5b8edef74 100644 --- a/packages/core/agent-loop/tests/shutdown-drain.spec.ts +++ b/packages/core/agent-loop/tests/shutdown-drain.spec.ts @@ -29,7 +29,7 @@ function waitForIdle(ctx: Context, agent: Agent): Promise { }) } -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('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() diff --git a/packages/experimental/claude-code-mods/tests/directory-resume.spec.ts b/packages/experimental/claude-code-mods/tests/directory-resume.spec.ts index c32f973614..77edea98e4 100644 --- a/packages/experimental/claude-code-mods/tests/directory-resume.spec.ts +++ b/packages/experimental/claude-code-mods/tests/directory-resume.spec.ts @@ -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({ diff --git a/packages/experimental/deepseek-chat-import/tests/composition.host.spec.ts b/packages/experimental/deepseek-chat-import/tests/composition.host.spec.ts index 5073352f69..f1a4560d78 100644 --- a/packages/experimental/deepseek-chat-import/tests/composition.host.spec.ts +++ b/packages/experimental/deepseek-chat-import/tests/composition.host.spec.ts @@ -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 = () => Promise.reject(new Error('unused'))) { +async function boot(backend: 'jsonl' | 'sqlite', saveImage: (input: SaveImageAttachment) => Promise = () => 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 Promise => (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() const release = Promise.withResolvers() - const { ctx, routes, post, importer } = await boot(() => { + const { ctx, routes, post, importer } = await boot(backend, () => { saving.resolve(undefined) return release.promise }) diff --git a/packages/experimental/deepseek-chat-import/tests/resume.host.spec.ts b/packages/experimental/deepseek-chat-import/tests/resume.host.spec.ts index bc931c8d31..d8eab8e32e 100644 --- a/packages/experimental/deepseek-chat-import/tests/resume.host.spec.ts +++ b/packages/experimental/deepseek-chat-import/tests/resume.host.spec.ts @@ -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) diff --git a/packages/experimental/hooks-claude-code/tests/coverage-cases.ts b/packages/experimental/hooks-claude-code/tests/coverage-cases.ts index a0b933165c..148a8d1e4b 100644 --- a/packages/experimental/hooks-claude-code/tests/coverage-cases.ts +++ b/packages/experimental/hooks-claude-code/tests/coverage-cases.ts @@ -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 { 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('transcript'), { provider: 'mock', model: 'mock' }) agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })) diff --git a/packages/experimental/hooks-codex/tests/coverage-cases.ts b/packages/experimental/hooks-codex/tests/coverage-cases.ts index fd9ebbb558..706a473790 100644 --- a/packages/experimental/hooks-codex/tests/coverage-cases.ts +++ b/packages/experimental/hooks-codex/tests/coverage-cases.ts @@ -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 { 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('transcript'), { provider: 'mock', model: 'mock' }) agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } })) diff --git a/packages/experimental/liveshare/tests/relay-target-admission.host.spec.ts b/packages/experimental/liveshare/tests/relay-target-admission.host.spec.ts index 7b7583dc71..b242a49fe7 100644 --- a/packages/experimental/liveshare/tests/relay-target-admission.host.spec.ts +++ b/packages/experimental/liveshare/tests/relay-target-admission.host.spec.ts @@ -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() fixture.ctx.on('agent/pre-step', async (_input, next) => { diff --git a/packages/experimental/timeline/tests/config.spec.ts b/packages/experimental/timeline/tests/config.spec.ts index 7307a39d6f..cd5bb161f4 100644 --- a/packages/experimental/timeline/tests/config.spec.ts +++ b/packages/experimental/timeline/tests/config.spec.ts @@ -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' } } diff --git a/packages/experimental/timeline/tests/controls.spec.ts b/packages/experimental/timeline/tests/controls.spec.ts index 0e1c93a34a..6c756e8f3c 100644 --- a/packages/experimental/timeline/tests/controls.spec.ts +++ b/packages/experimental/timeline/tests/controls.spec.ts @@ -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 }) diff --git a/packages/experimental/timeline/tests/delegation.spec.ts b/packages/experimental/timeline/tests/delegation.spec.ts index bee7258c83..eabff88352 100644 --- a/packages/experimental/timeline/tests/delegation.spec.ts +++ b/packages/experimental/timeline/tests/delegation.spec.ts @@ -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({ diff --git a/packages/experimental/timeline/tests/feedback.spec.ts b/packages/experimental/timeline/tests/feedback.spec.ts index 8299a32b83..f233d97110 100644 --- a/packages/experimental/timeline/tests/feedback.spec.ts +++ b/packages/experimental/timeline/tests/feedback.spec.ts @@ -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, diff --git a/packages/experimental/timeline/tests/fixture.ts b/packages/experimental/timeline/tests/fixture.ts index fbccdf7410..5f8ace7e7f 100644 --- a/packages/experimental/timeline/tests/fixture.ts +++ b/packages/experimental/timeline/tests/fixture.ts @@ -122,6 +122,7 @@ export class Adapter extends LlmAdapter { } } export async function setup( + backend: 'jsonl' | 'sqlite', config: Partial = {}, 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({ diff --git a/packages/experimental/timeline/tests/history.spec.ts b/packages/experimental/timeline/tests/history.spec.ts index 50ea3400ff..e103f8b54f 100644 --- a/packages/experimental/timeline/tests/history.spec.ts +++ b/packages/experimental/timeline/tests/history.spec.ts @@ -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')) diff --git a/packages/experimental/timeline/tests/host-process.mjs b/packages/experimental/timeline/tests/host-process.mjs index 1a7fc6eeaa..5570678c3a 100644 --- a/packages/experimental/timeline/tests/host-process.mjs +++ b/packages/experimental/timeline/tests/host-process.mjs @@ -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 { diff --git a/packages/experimental/timeline/tests/persistence-process.e2e.ts b/packages/experimental/timeline/tests/persistence-process.e2e.ts index 211ff5816d..6e8f14b666 100644 --- a/packages/experimental/timeline/tests/persistence-process.e2e.ts +++ b/packages/experimental/timeline/tests/persistence-process.e2e.ts @@ -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]) diff --git a/packages/experimental/timeline/tests/persistence.spec.ts b/packages/experimental/timeline/tests/persistence.spec.ts index 411256f37b..2b9cb713c9 100644 --- a/packages/experimental/timeline/tests/persistence.spec.ts +++ b/packages/experimental/timeline/tests/persistence.spec.ts @@ -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>) { return tree } -async function restart(f: Awaited>, adapter = new Adapter()) { +async function restart(backend: 'jsonl' | 'sqlite', f: Awaited>, 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) diff --git a/packages/experimental/timeline/tests/pull.spec.ts b/packages/experimental/timeline/tests/pull.spec.ts index 8d19dd015b..384f33e7e7 100644 --- a/packages/experimental/timeline/tests/pull.spec.ts +++ b/packages/experimental/timeline/tests/pull.spec.ts @@ -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', { diff --git a/packages/experimental/timeline/tests/reminders.spec.ts b/packages/experimental/timeline/tests/reminders.spec.ts index bdb840bfb4..5d9ae24a75 100644 --- a/packages/experimental/timeline/tests/reminders.spec.ts +++ b/packages/experimental/timeline/tests/reminders.spec.ts @@ -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, diff --git a/packages/experimental/timeline/tests/reports.spec.ts b/packages/experimental/timeline/tests/reports.spec.ts index f7dd8bbfcd..1737709df3 100644 --- a/packages/experimental/timeline/tests/reports.spec.ts +++ b/packages/experimental/timeline/tests/reports.spec.ts @@ -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() - 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() 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() - 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() const release = Promise.withResolvers() @@ -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() - 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() - 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() - 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() - 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() - 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' }) diff --git a/packages/experimental/timeline/tests/storage.spec.ts b/packages/experimental/timeline/tests/storage.spec.ts index b43bd4e0f4..5b7424d1bc 100644 --- a/packages/experimental/timeline/tests/storage.spec.ts +++ b/packages/experimental/timeline/tests/storage.spec.ts @@ -14,8 +14,8 @@ const fixtures: Awaited>[] = [] 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() @@ -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([]) diff --git a/packages/experimental/timeline/tests/tools.spec.ts b/packages/experimental/timeline/tests/tools.spec.ts index 0f7bf4d099..73ba95a0ba 100644 --- a/packages/experimental/timeline/tests/tools.spec.ts +++ b/packages/experimental/timeline/tests/tools.spec.ts @@ -25,9 +25,9 @@ function toolsOf(fixture: Awaited>, 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>) => @@ -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, { diff --git a/packages/experimental/timeline/tests/transfer.spec.ts b/packages/experimental/timeline/tests/transfer.spec.ts index 8f070bfbd7..e28cf02ccf 100644 --- a/packages/experimental/timeline/tests/transfer.spec.ts +++ b/packages/experimental/timeline/tests/transfer.spec.ts @@ -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>[] = [] 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() const release = Promise.withResolvers() @@ -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') diff --git a/packages/experimental/tool-ralph/tests/integration.spec.ts b/packages/experimental/tool-ralph/tests/integration.spec.ts index 44f873b6b0..aae7b9a2c2 100644 --- a/packages/experimental/tool-ralph/tests/integration.spec.ts +++ b/packages/experimental/tool-ralph/tests/integration.spec.ts @@ -22,23 +22,23 @@ import { mountWorkflowRuntime } from '../../../workflow/workflow-ptc/tests/setup type MockScript = ConstructorParameters[0] const testToolSignal = new AbortController().signal -async function mountExecution(ctx: Context): Promise { +async function mountExecution(backend: 'jsonl' | 'sqlite', ctx: Context): Promise { 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 diff --git a/packages/experimental/tool-session-query/tests/sqlite-integration.spec.ts b/packages/experimental/tool-session-query/tests/sqlite-integration.spec.ts index f4bfc58896..5905c10e09 100644 --- a/packages/experimental/tool-session-query/tests/sqlite-integration.spec.ts +++ b/packages/experimental/tool-session-query/tests/sqlite-integration.spec.ts @@ -39,7 +39,7 @@ async function registerTurnBoundary(ctx: Context): Promise { 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) diff --git a/packages/experimental/translator/tests/audit.spec.ts b/packages/experimental/translator/tests/audit.spec.ts index aebd515e96..f2db919ee1 100644 --- a/packages/experimental/translator/tests/audit.spec.ts +++ b/packages/experimental/translator/tests/audit.spec.ts @@ -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(), release = Promise.withResolvers() 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('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('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('owned-history'), historicalEvents()) + const b = await paidFixture(cleanups, backend, { withSession: false }), original = await b.createHistorical(brandString('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 } }) diff --git a/packages/experimental/translator/tests/deepseek.spec.ts b/packages/experimental/translator/tests/deepseek.spec.ts index a6eb9ca7eb..7e47d604b2 100644 --- a/packages/experimental/translator/tests/deepseek.spec.ts +++ b/packages/experimental/translator/tests/deepseek.spec.ts @@ -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('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(), continueLookup = Promise.withResolvers() 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('off') }) vi.spyOn(b.ctx.llm, 'prepareCall').mockResolvedValueOnce({ ...prepared, config: { ...prepared.config, reasoningEffort: brandString('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('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(), release = Promise.withResolvers() + const b = await paidFixture(cleanups, backend) + const entered = Promise.withResolvers(), release = Promise.withResolvers() 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(), release = Promise.withResolvers() + const b = await paidFixture(cleanups, backend) + const entered = Promise.withResolvers(), release = Promise.withResolvers() 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 | 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('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(), closed = Promise.withResolvers() - 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() - 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(), release = Promise.withResolvers() 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(), release = Promise.withResolvers() 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(), release = Promise.withResolvers() vi.spyOn(b.ctx.get('credentials')!, 'describe').mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise; return { configured: true, writable: true } diff --git a/packages/experimental/translator/tests/paid-fixture.ts b/packages/experimental/translator/tests/paid-fixture.ts index 7290ec16fa..ab628dfe8c 100644 --- a/packages/experimental/translator/tests/paid-fixture.ts +++ b/packages/experimental/translator/tests/paid-fixture.ts @@ -70,8 +70,14 @@ export interface RestartOptions { translator?: Partial } -/** Boot actual native provider rows; cleanup is registered as soon as resources exist. */ -export async function paidFixture(cleanups: Array<() => Promise>, 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>, 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>, 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' }], } }, diff --git a/packages/experimental/translator/tests/storage-fixture.ts b/packages/experimental/translator/tests/storage-fixture.ts index b51ce6ea9d..4709dc2053 100644 --- a/packages/experimental/translator/tests/storage-fixture.ts +++ b/packages/experimental/translator/tests/storage-fixture.ts @@ -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>, options: StorageFixtureOptions = {}) { +export async function storageFixture(cleanups: Array<() => Promise>, 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>() @@ -99,7 +100,7 @@ export async function storageFixture(cleanups: Array<() => Promise>, 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>, 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 = ?') diff --git a/packages/experimental/translator/tests/storage-helper.spec.ts b/packages/experimental/translator/tests/storage-helper.spec.ts index 2e05acb78b..aa73f9ef7d 100644 --- a/packages/experimental/translator/tests/storage-helper.spec.ts +++ b/packages/experimental/translator/tests/storage-helper.spec.ts @@ -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) => { diff --git a/packages/experimental/translator/tests/storage-lifecycle.spec.ts b/packages/experimental/translator/tests/storage-lifecycle.spec.ts index 497d6f06e6..87cfc6418e 100644 --- a/packages/experimental/translator/tests/storage-lifecycle.spec.ts +++ b/packages/experimental/translator/tests/storage-lifecycle.spec.ts @@ -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(), release = Promise.withResolvers() - 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(), release = Promise.withResolvers() 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(), release = Promise.withResolvers() 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(), release = Promise.withResolvers() - 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('live-without-writer'), true) + const b = await storageFixture(cleanups, backend), original = await b.createSession(brandString('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) diff --git a/packages/experimental/translator/tests/storage-settlement.spec.ts b/packages/experimental/translator/tests/storage-settlement.spec.ts index fcf94f74fb..ddbac29691 100644 --- a/packages/experimental/translator/tests/storage-settlement.spec.ts +++ b/packages/experimental/translator/tests/storage-settlement.spec.ts @@ -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(), release = Promise.withResolvers() const deadline = Promise.withResolvers() 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() diff --git a/packages/experimental/translator/tests/storage.spec.ts b/packages/experimental/translator/tests/storage.spec.ts index a8f93050b9..ad95096424 100644 --- a/packages/experimental/translator/tests/storage.spec.ts +++ b/packages/experimental/translator/tests/storage.spec.ts @@ -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('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(), release = Promise.withResolvers() - 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(), release = Promise.withResolvers() - 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() - 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(), closed = Promise.withResolvers() 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('inactive'), false) + const b = await storageFixture(cleanups, backend, { withSessions }), original = await b.createSession(brandString('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('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('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('malformed'), false) + const b = await storageFixture(cleanups, backend), original = await b.createSession(brandString('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') diff --git a/packages/experimental/worktree/tests/archive.spec.ts b/packages/experimental/worktree/tests/archive.spec.ts index 680527e712..56d7a89674 100644 --- a/packages/experimental/worktree/tests/archive.spec.ts +++ b/packages/experimental/worktree/tests/archive.spec.ts @@ -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() 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('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('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('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('other-parent'), { meta: { cwd: f.root } }) f.ctx.sessions.create(brandString('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('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() const release = Promise.withResolvers() 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() const release = Promise.withResolvers() 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('orphan-child'), { meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: brandString('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() const release = Promise.withResolvers() removeCheckout.mockImplementation(async () => { diff --git a/packages/feedback/message-feedback/tests/loader-composition.spec.ts b/packages/feedback/message-feedback/tests/loader-composition.spec.ts index b0401bdb66..2f686c372d 100644 --- a/packages/feedback/message-feedback/tests/loader-composition.spec.ts +++ b/packages/feedback/message-feedback/tests/loader-composition.spec.ts @@ -51,7 +51,7 @@ async function loadComposition(configPath: string): Promise { 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 }) diff --git a/packages/llm/llm-retry/tests/persistence.spec.ts b/packages/llm/llm-retry/tests/persistence.spec.ts index ac5bda8f7e..68f9231856 100644 --- a/packages/llm/llm-retry/tests/persistence.spec.ts +++ b/packages/llm/llm-retry/tests/persistence.spec.ts @@ -15,18 +15,18 @@ afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }) }) -async function backend(): Promise { +async function backend(storage: 'jsonl' | 'sqlite'): Promise { 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('retry-jsonl')) const handle = await ctx.sessionPersistence.create(session.header) diff --git a/packages/schedule/schedule/tests/change-notice.spec.ts b/packages/schedule/schedule/tests/change-notice.spec.ts index 70f203ea8e..e6b38f5d16 100644 --- a/packages/schedule/schedule/tests/change-notice.spec.ts +++ b/packages/schedule/schedule/tests/change-notice.spec.ts @@ -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('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 }, diff --git a/packages/schedule/schedule/tests/serial-delivery.spec.ts b/packages/schedule/schedule/tests/serial-delivery.spec.ts index 791ead2914..0c5aa16af1 100644 --- a/packages/schedule/schedule/tests/serial-delivery.spec.ts +++ b/packages/schedule/schedule/tests/serial-delivery.spec.ts @@ -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') }) diff --git a/packages/sdk/server/tests/built-scope-carrier.e2e.ts b/packages/sdk/server/tests/built-scope-carrier.e2e.ts index 20a07f6702..e281608531 100644 --- a/packages/sdk/server/tests/built-scope-carrier.e2e.ts +++ b/packages/sdk/server/tests/built-scope-carrier.e2e.ts @@ -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, }) diff --git a/packages/sdk/server/tests/plugin-apply.spec.ts b/packages/sdk/server/tests/plugin-apply.spec.ts index 9236dfcf26..afcb3a5eac 100644 --- a/packages/sdk/server/tests/plugin-apply.spec.ts +++ b/packages/sdk/server/tests/plugin-apply.spec.ts @@ -69,6 +69,7 @@ async function settle(): Promise { /** 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((resolve) => { markStarted = resolve }) const ready = new Promise((resolve) => { release = resolve }) let delayedEntry: Promise | 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' }) diff --git a/packages/sdk/server/tests/resume.spec.ts b/packages/sdk/server/tests/resume.spec.ts index 97afa702dc..add17bb4e2 100644 --- a/packages/sdk/server/tests/resume.spec.ts +++ b/packages/sdk/server/tests/resume.spec.ts @@ -28,11 +28,11 @@ async function storageRoot(): Promise { 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('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) diff --git a/packages/sdk/server/tests/server.spec.ts b/packages/sdk/server/tests/server.spec.ts index feabf16163..de9bda9354 100644 --- a/packages/sdk/server/tests/server.spec.ts +++ b/packages/sdk/server/tests/server.spec.ts @@ -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) diff --git a/packages/sdk/server/tests/wait.spec.ts b/packages/sdk/server/tests/wait.spec.ts index 69da2ca8a8..20ac88814b 100644 --- a/packages/sdk/server/tests/wait.spec.ts +++ b/packages/sdk/server/tests/wait.spec.ts @@ -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() const release = Promise.withResolvers() let closeChildren: (() => Promise) | 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('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() 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) diff --git a/packages/session-query/session-query-sqlite/tests/load-path.e2e.ts b/packages/session-query/session-query-sqlite/tests/load-path.e2e.ts index cbd7f81a30..d20f3c175d 100644 --- a/packages/session-query/session-query-sqlite/tests/load-path.e2e.ts +++ b/packages/session-query/session-query-sqlite/tests/load-path.e2e.ts @@ -32,13 +32,13 @@ async function temporaryPath(name: string): Promise { } 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', }) diff --git a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts index 8cd0d47304..8bde582c90 100644 --- a/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts +++ b/packages/session-query/session-query-sqlite/tests/sqlite.spec.ts @@ -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 }) diff --git a/packages/session/session-checkpoint-policy/tests/crash-recovery.e2e.ts b/packages/session/session-checkpoint-policy/tests/crash-recovery.e2e.ts index e173c604e1..f2bd59d19b 100644 --- a/packages/session/session-checkpoint-policy/tests/crash-recovery.e2e.ts +++ b/packages/session/session-checkpoint-policy/tests/crash-recovery.e2e.ts @@ -37,7 +37,7 @@ async function waitForMarker(path: string, expected: string): Promise { 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 { +async function load(storage: 'jsonl' | 'sqlite', root: string): Promise { 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') diff --git a/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts b/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts index a6c462a885..228a3cdade 100644 --- a/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts +++ b/packages/session/session-checkpoint-policy/tests/fixtures/crash-child.ts @@ -12,9 +12,9 @@ function waitForCrash(): Promise { 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 ') +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 ') } 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({ diff --git a/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts b/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts index 3ecf031750..cfa33903ac 100644 --- a/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts +++ b/packages/session/session-log-deepseek/tests/feedback-composition.spec.ts @@ -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('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('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() } diff --git a/packages/session/session-persistence-jsonl/tests/fixtures/legacy-persistence.ts b/packages/session/session-persistence-jsonl/tests/fixtures/legacy-persistence.ts index 2fad9a5ab6..762445998f 100644 --- a/packages/session/session-persistence-jsonl/tests/fixtures/legacy-persistence.ts +++ b/packages/session/session-persistence-jsonl/tests/fixtures/legacy-persistence.ts @@ -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 { - 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 }, + }) } diff --git a/packages/session/session-persistence-jsonl/tests/teardown-loader.e2e.ts b/packages/session/session-persistence-jsonl/tests/teardown-loader.e2e.ts index bdae8ea049..b7e4061059 100644 --- a/packages/session/session-persistence-jsonl/tests/teardown-loader.e2e.ts +++ b/packages/session/session-persistence-jsonl/tests/teardown-loader.e2e.ts @@ -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() @@ -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 => { - 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') diff --git a/packages/session/session-title/tests/persistence.spec.ts b/packages/session/session-title/tests/persistence.spec.ts index d922f363e5..b62b019744 100644 --- a/packages/session/session-title/tests/persistence.spec.ts +++ b/packages/session/session-title/tests/persistence.spec.ts @@ -62,8 +62,8 @@ async function expectPersistedTitle(ctx: Context, id: SessionId): Promise } } -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('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() }) diff --git a/packages/shell/tool-bash/tests/integration.spec.ts b/packages/shell/tool-bash/tests/integration.spec.ts index e388e0f53b..3fb50d5f4f 100644 --- a/packages/shell/tool-bash/tests/integration.spec.ts +++ b/packages/shell/tool-bash/tests/integration.spec.ts @@ -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('session-env-id'), agentOptions: { provider: 'mock', model: 'mock' }, diff --git a/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts b/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts index 381501b9b8..7f37c65ed4 100644 --- a/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts +++ b/packages/subagent/subagent-fork-in-process/tests/multi-subagent.spec.ts @@ -20,10 +20,10 @@ type Script = ConstructorParameters[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'), diff --git a/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts b/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts index e76903f93e..075ecfd773 100644 --- a/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts +++ b/packages/subagent/subagent-fork-in-process/tests/subagent-fork-in-process.spec.ts @@ -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 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 diff --git a/packages/subagent/subagent-spawn-in-process/tests/harness.ts b/packages/subagent/subagent-spawn-in-process/tests/harness.ts index 6bc59cb6b4..a3695d358e 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/harness.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/harness.ts @@ -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 { +export async function spawnHarness(storage: 'jsonl' | 'sqlite', workdir: string): Promise { 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 { 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' }) diff --git a/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts b/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts index d0338d811a..701b942744 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/spawn-in-process.e2e.ts @@ -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('e2e-parent'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir }) parent.followup(createUserMessage({ diff --git a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts index 08ca12fc5d..3b5b03e959 100644 --- a/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts +++ b/packages/subagent/subagent-spawn-in-process/tests/subagent-spawn-in-process.spec.ts @@ -23,11 +23,11 @@ type Script = ConstructorParameters[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 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('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('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('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('setup-race-parent-session'), agentOptions: { provider: 'mock', model: 'mock' }, diff --git a/packages/subagent/subagent/tests/activation-policy.spec.ts b/packages/subagent/subagent/tests/activation-policy.spec.ts index 175dff67f1..54bc2fb8f0 100644 --- a/packages/subagent/subagent/tests/activation-policy.spec.ts +++ b/packages/subagent/subagent/tests/activation-policy.spec.ts @@ -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', () => { diff --git a/packages/subagent/subagent/tests/activation-presets.spec.ts b/packages/subagent/subagent/tests/activation-presets.spec.ts index 661d48c96e..d6e02e0c9d 100644 --- a/packages/subagent/subagent/tests/activation-presets.spec.ts +++ b/packages/subagent/subagent/tests/activation-presets.spec.ts @@ -33,7 +33,7 @@ afterEach(async () => { /** A host composition carrying no model-facing rows, plus the preset roster. */ async function setupPresetHost( - script: ConstructorParameters[0] = [textResponse('parent idle'), textResponse('child done')], + storage: 'jsonl' | 'sqlite', script: ConstructorParameters[0] = [textResponse('parent idle'), textResponse('child done')], ): Promise<{ ctx: Context; adapter: MockAdapter; parent: Agent; unregister: Map Promise> }> { 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', diff --git a/packages/subagent/subagent/tests/continuation-inheritance.spec.ts b/packages/subagent/subagent/tests/continuation-inheritance.spec.ts index 8bc18b99e8..13188233a3 100644 --- a/packages/subagent/subagent/tests/continuation-inheritance.spec.ts +++ b/packages/subagent/subagent/tests/continuation-inheritance.spec.ts @@ -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({ diff --git a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts index 5c980cf5e3..a58d43ba46 100644 --- a/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts +++ b/packages/subagent/subagent/tests/continuation-messages-adapter.spec.ts @@ -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> | 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) diff --git a/packages/subagent/subagent/tests/continuation-presets.spec.ts b/packages/subagent/subagent/tests/continuation-presets.spec.ts index c7239dc46b..aeb2647527 100644 --- a/packages/subagent/subagent/tests/continuation-presets.spec.ts +++ b/packages/subagent/subagent/tests/continuation-presets.spec.ts @@ -39,7 +39,7 @@ afterEach(async () => { }) /** Real preset mounts, Agent lifecycle, and persistence with a scripted model. */ -async function setup(script: ConstructorParameters[0] = [textResponse('done'), textResponse('continued'), textResponse('done again')]) { +async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters[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[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('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) diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index 244b345754..4197fcf77f 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -82,7 +82,7 @@ afterEach(async () => { /** Boot the full continuable stack: loop, persistence, providers, and subagents. */ async function setupWith( - adapter: LlmAdapter, + storage: 'jsonl' | 'sqlite', adapter: LlmAdapter, options: { persistence?: boolean; sessionQuery?: boolean; maxActiveSubagents?: number } = {}, ) { const ctx = new Context() @@ -92,7 +92,7 @@ async function setupWith( if (options.persistence !== false) { root = mkdtempSync(join(tmpdir(), 'dsh-subagent-continuation-')) const persistedRoot = root - const persistenceFiber = await ctx.plugin(JsonlSessionPersistence, { root }) + const persistenceFiber = await ctx.plugin(JsonlSessionPersistence, { storage, root }) disposePersistence = () => persistenceFiber.dispose() cleanups.push(async () => { await persistenceFiber.dispose() @@ -112,9 +112,9 @@ async function setupWith( return { ctx, parent, disposePersistence, root, loop } } -async function setup(script: Script, options: { persistence?: boolean } = {}) { +async function setup(storage: 'jsonl' | 'sqlite', script: Script, options: { persistence?: boolean } = {}) { const adapter = new MockAdapter(script) - const booted = await setupWith(adapter, options) + const booted = await setupWith(storage, adapter, options) return { ...booted, adapter } } @@ -294,10 +294,10 @@ describe('continuable activation capacity', () => { } }) - it('applies capacity edits to an existing root without stopping resident children', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: applies capacity edits to an existing root without stopping resident children', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter(Array.from({ length: 4 }, () => ({ chunks: textResponse('done'), gate: release.promise }))) - const { ctx, parent } = await setupWith(adapter, { maxActiveSubagents: 1 }) + const { ctx, parent } = await setupWith(storage, adapter, { maxActiveSubagents: 1 }) parkParent(ctx, parent) try { const first = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) @@ -318,13 +318,13 @@ describe('continuable activation capacity', () => { } }) - it('defaults to eight live children and reuses capacity after settlement', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: defaults to eight live children and reuses capacity after settlement', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ ...Array.from({ length: 8 }, () => ({ chunks: textResponse('done'), gate: release.promise })), { chunks: textResponse('replacement') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) try { const started = await Promise.all(Array.from({ length: 8 }, () => ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }))) @@ -339,14 +339,14 @@ describe('continuable activation capacity', () => { } }) - it('shares slots across siblings, providers and nested children while isolating roots', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: shares slots across siblings, providers and nested children while isolating roots', async (storage) => { const release = Promise.withResolvers() const releaseParent = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('parent done'), gate: releaseParent.promise }, ...Array.from({ length: 3 }, () => ({ chunks: textResponse('done'), gate: release.promise })), ]) - const { ctx, parent } = await setupWith(adapter, { maxActiveSubagents: 3 }) + const { ctx, parent } = await setupWith(storage, adapter, { maxActiveSubagents: 3 }) const other = await ctx.agentLoop.create(brandString('other-root'), { provider: 'mock', model: 'mock' }) parkParent(ctx, parent) parkParent(ctx, other) @@ -376,8 +376,8 @@ describe('continuable activation capacity', () => { } }) - it('reserves the last slot before asynchronous creation and returns it after failure', async () => { - const { ctx, parent } = await setupWith(new MockAdapter([textResponse('replacement')]), { maxActiveSubagents: 1 }) + it.each(['jsonl', 'sqlite'] as const)('%s: reserves the last slot before asynchronous creation and returns it after failure', async (storage) => { + const { ctx, parent } = await setupWith(storage, new MockAdapter([textResponse('replacement')]), { maxActiveSubagents: 1 }) parkParent(ctx, parent) const agents = managerState(ctx).ownerCtx.agents const entered = Promise.withResolvers() @@ -406,14 +406,14 @@ describe('continuable activation capacity', () => { } }) - it('counts caller-awaited and parent-delivered runs against the same capacity', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: counts caller-awaited and parent-delivered runs against the same capacity', async (storage) => { const release = Promise.withResolvers() const releaseCaller = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('parent-delivered'), gate: release.promise }, { chunks: textResponse('caller-awaited'), gate: releaseCaller.promise }, ]) - const { ctx, parent } = await setupWith(adapter, { maxActiveSubagents: 1 }) + const { ctx, parent } = await setupWith(storage, adapter, { maxActiveSubagents: 1 }) parkParent(ctx, parent) try { const child = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) @@ -438,7 +438,7 @@ describe('continuable activation capacity', () => { } }) - it('checks cold resume but accepts messages to an already resident child at capacity', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: checks cold resume but accepts messages to an already resident child at capacity', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first') }, @@ -446,7 +446,7 @@ describe('continuable activation capacity', () => { { chunks: textResponse('queued') }, { chunks: textResponse('resumed') }, ]) - const { ctx, parent } = await setupWith(adapter, { maxActiveSubagents: 1 }) + const { ctx, parent } = await setupWith(storage, adapter, { maxActiveSubagents: 1 }) parkParent(ctx, parent) try { const old = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) @@ -467,13 +467,13 @@ describe('continuable activation capacity', () => { } }) - it.each([false, true])('retains the slot through disposal, including cleanup failure: %s', async (failDisposal) => { + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: retains the slot through disposal, including cleanup failure: %s', async (storage, failDisposal) => { const releaseRun = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('busy'), gate: releaseRun.promise }, { chunks: textResponse('replacement') }, ]) - const { ctx, parent } = await setupWith(adapter, { maxActiveSubagents: 1 }) + const { ctx, parent } = await setupWith(storage, adapter, { maxActiveSubagents: 1 }) parkParent(ctx, parent) const entered = Promise.withResolvers() const releaseDisposal = Promise.withResolvers() @@ -507,8 +507,8 @@ describe('continuable activation capacity', () => { }) describe('SubagentRuntime.startActivation', () => { - it('returns both identities at inbox acceptance, without waiting for the turn or the log', async () => { - const { ctx, parent, adapter } = await setup([textResponse('first answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: returns both identities at inbox acceptance, without waiting for the turn or the log', async (storage) => { + const { ctx, parent, adapter } = await setup(storage, [textResponse('first answer')]) const enqueued: { id: MessageId; loggedYet: boolean; requestedYet: boolean }[] = [] ctx.on('agent/inbox/inserted', ({ agent, message }) => { // Acceptance is the boundary `startActivation` resolves at, so observe @@ -528,12 +528,12 @@ describe('SubagentRuntime.startActivation', () => { expect(hasUserText(loaded.events, 'child task')).toBe(true) }) - it('uses a caller-reserved child identity and rejects a duplicate reservation', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: uses a caller-reserved child identity and rejects a duplicate reservation', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('reserved answer'), gate: release.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const reservedId = brandString('00000000-0000-4000-8000-000000000123') const started = await ctx.subagents.startActivation({ @@ -563,8 +563,8 @@ describe('SubagentRuntime.startActivation', () => { expect(ctx.agents.get(reservedId)).toBeUndefined() }) - it('rejects reserved child ids for an external backend before dispatch', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects reserved child ids for an external backend before dispatch', async (storage) => { + const { ctx, parent } = await setup(storage, []) const start = vi.fn(async () => { throw new Error('must not dispatch') }) ctx.subagents.registerProvider({ name: 'one-shot', @@ -580,14 +580,14 @@ describe('SubagentRuntime.startActivation', () => { expect(ctx.agents.list().map(agent => agent.id)).toEqual([brandString('parent')]) }) - it('rejects synchronously when persistence is not configured', async () => { - const { ctx, parent } = await setup([textResponse('unused')], { persistence: false }) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects synchronously when persistence is not configured', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('unused')], { persistence: false }) await expect(ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' })) .rejects.toThrow(/require session persistence/) }) - it('publishes the reserved child id and appends the pre-turn descriptor', async () => { - const { ctx, parent } = await setup([textResponse('answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: publishes the reserved child id and appends the pre-turn descriptor', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('answer')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -612,7 +612,7 @@ describe('SubagentRuntime.startActivation', () => { expect(loaded.meta.origin).toBe('subagent') }) - it('persists a selected reasoning effort and reapplies it on cold resume', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: persists a selected reasoning effort and reapplies it on cold resume', async (storage) => { const effort = brandString('max') const adapter = new MockAdapter([ textResponse('first answer'), @@ -621,7 +621,7 @@ describe('SubagentRuntime.startActivation', () => { efforts: [{ id: effort, name: 'Max' }], defaultEffort: effort, }) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const childEfforts: Array = [] ctx.on('agent/created', ({ agent }) => { @@ -645,8 +645,8 @@ describe('SubagentRuntime.startActivation', () => { expect(childEfforts).toEqual(['max', 'max']) }) - it('rolls the child back completely when the caller signal aborts before acceptance', async () => { - const { ctx, parent } = await setup([textResponse('unused')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rolls the child back completely when the caller signal aborts before acceptance', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('unused')]) const controller = new AbortController() // Abort inside the child's creation window: setup runs before publication. ctx.on('agent/created', ({ agent: child }) => { @@ -661,8 +661,8 @@ describe('SubagentRuntime.startActivation', () => { }) }) - it('rolls the child back when the signal aborts between publication and acceptance', async () => { - const { ctx, parent } = await setup([textResponse('unused')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rolls the child back when the signal aborts between publication and acceptance', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('unused')]) const controller = new AbortController() // `subagent/start` fires once the epoch is resident, before the prompt is // submitted, so cancelling here lands squarely in the handoff window. @@ -677,8 +677,8 @@ describe('SubagentRuntime.startActivation', () => { }) }) - it.each(['parent', 'caller'] as const)('releases the %s-delivery activation when its catalog append fails', async (delivery) => { - const { ctx, parent } = await setup([textResponse('unused')]) + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['parent', 'caller'] as const).map(value => [storage, value] as const)))('%s: releases the %s-delivery activation when its catalog append fails', async (storage, delivery) => { + const { ctx, parent } = await setup(storage, [textResponse('unused')]) const childId = brandString('00000000-0000-4000-8000-000000000321') const catalogFailure = new Error('catalog append failed') const cleanupFailure = new Error('activation disposal also failed') @@ -711,8 +711,8 @@ describe('SubagentRuntime.startActivation', () => { expect(parent.session.snapshotEvents().filter(event => event.type === 'subagent/catalog')).toEqual([]) }) - it('preserves prompt admission failure when Activation disposal also fails', async () => { - const { ctx, parent } = await setup([textResponse('unused')]) + it.each(['jsonl', 'sqlite'] as const)('%s: preserves prompt admission failure when Activation disposal also fails', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('unused')]) const childId = brandString('00000000-0000-4000-8000-000000000322') const admissionFailure = new Error('prompt admission failed') const cleanupFailure = new Error('activation disposal also failed') @@ -742,8 +742,8 @@ describe('SubagentRuntime.startActivation', () => { ))).toBe(true) }) - it('rolls an unpublished Activation back when lifecycle publication fails', async () => { - const { ctx, parent } = await setup([textResponse('unused')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rolls an unpublished Activation back when lifecycle publication fails', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('unused')]) const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/end', info => void ends.push(info)) ctx.on('internal/dispatch', (_mode, eventName) => { @@ -760,8 +760,8 @@ describe('SubagentRuntime.startActivation', () => { await expect(drainManager(ctx)).resolves.toBeUndefined() }) - it('rejects a continuable child that would exceed the configured depth cap', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a continuable child that would exceed the configured depth cap', async (storage) => { + const { ctx, parent } = await setup(storage, []) await expect(ctx.subagents.startActivation({ delivery: 'parent', ...startSpec(parent), @@ -770,8 +770,8 @@ describe('SubagentRuntime.startActivation', () => { expect(ctx.agents.list().map(agent => agent.id)).toEqual([brandString('parent')]) }) - it('rejects an invalid continuable depth cap before provider preparation', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects an invalid continuable depth cap before provider preparation', async (storage) => { + const { ctx, parent } = await setup(storage, []) await expect(ctx.subagents.startActivation({ delivery: 'parent', ...startSpec(parent), @@ -780,8 +780,8 @@ describe('SubagentRuntime.startActivation', () => { expect(ctx.agents.list().map(agent => agent.id)).toEqual([brandString('parent')]) }) - it('omits undeclared composition fields from the descriptor', async () => { - const { ctx } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: omits undeclared composition fields from the descriptor', async (storage) => { + const { ctx } = await setup(storage, []) const routeless = await ctx.agentLoop.create(brandString('routeless'), {}) const started = await ctx.subagents.startActivation({ ...startSpec(routeless), delivery: 'parent' }) const child = await vi.waitFor(() => { @@ -800,8 +800,8 @@ describe('SubagentRuntime.startActivation', () => { await drainManager(ctx) }) - it('cold-resumes without inventing a model route the descriptor never declared', async () => { - const { ctx, root } = await setup([textResponse('first')]) + it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes without inventing a model route the descriptor never declared', async (storage) => { + const { ctx, root } = await setup(storage, [textResponse('first')]) const routeless = await ctx.agentLoop.create(brandString('routeless-resume'), {}) const started = await ctx.subagents.startActivation({ ...startSpec(routeless), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -811,7 +811,7 @@ describe('SubagentRuntime.startActivation', () => { const fresh = new Context() await mountAgentLoopTestDependencies(fresh) - const freshPersistence = await fresh.plugin(JsonlSessionPersistence, { root: root! }) + const freshPersistence = await fresh.plugin(JsonlSessionPersistence, { storage, root: root! }) // This context opened a second handle on the same root; register it so // afterEach closes it before removing the root (even on a failure path). cleanups.push(async () => { await freshPersistence.dispose() }) @@ -835,8 +835,8 @@ describe('SubagentRuntime.startActivation', () => { await drainManager(fresh) }) - it('continues turn numbering after an inherited fork prefix and pre-turn descriptor', async () => { - const { ctx, parent } = await setup([ + it.each(['jsonl', 'sqlite'] as const)('%s: continues turn numbering after an inherited fork prefix and pre-turn descriptor', async (storage) => { + const { ctx, parent } = await setup(storage, [ textResponse('parent turn'), textResponse('forked child'), ]) @@ -869,8 +869,8 @@ describe('continuable image Queue prompts', () => { }, } - it('checks the subagent tree root model before accepting an image from a member', async () => { - const { ctx, parent } = await setup(['hang']) + it.each(['jsonl', 'sqlite'] as const)('%s: checks the subagent tree root model before accepting an image from a member', async (storage) => { + const { ctx, parent } = await setup(storage, ['hang']) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const sender = ctx.agents.get(started.childId)! const resolve = vi.spyOn(ctx.llm, 'resolveModelInfo').mockResolvedValue({ inputModalities: ['text'] } as never) @@ -884,8 +884,8 @@ describe('continuable image Queue prompts', () => { } }) - it('refuses an image follow-up when the child model declines image input, leaving no partial message', async () => { - const { ctx, parent } = await setup([textResponse('child work')]) + it.each(['jsonl', 'sqlite'] as const)('%s: refuses an image follow-up when the child model declines image input, leaving no partial message', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('child work')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) const resolve = vi.spyOn(ctx.llm, 'resolveModelInfo') @@ -903,13 +903,13 @@ describe('continuable image Queue prompts', () => { await drainManager(ctx) }) - it('delivers an image follow-up to a resident child when its model accepts image input', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: delivers an image follow-up to a resident child when its model accepts image input', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child work'), gate: releaseFirst.promise }, { chunks: textResponse('image reply') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) @@ -934,10 +934,10 @@ describe('continuable image Queue prompts', () => { await drainManager(ctx) }) - it('re-checks the disposal cutoff when a drain begins during a live image capability read', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: re-checks the disposal cutoff when a drain begins during a live image capability read', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('child work'), gate: releaseFirst.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const capability = Promise.withResolvers<{ inputModalities: string[] }>() @@ -963,8 +963,8 @@ describe('continuable image Queue prompts', () => { } }) - it('rejects a materialized image follow-up whose capability read raced a drain', async () => { - const { ctx, parent } = await setup([textResponse('child work')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a materialized image follow-up whose capability read raced a drain', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('child work')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) const capability = Promise.withResolvers<{ inputModalities: string[] }>() @@ -991,8 +991,8 @@ describe('continuable image Queue prompts', () => { && event.data.content.some(block => block.type === 'image'))).toBe(false) }) - it('defers to the text-only projection when the descriptor declares no model route', async () => { - const { ctx } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: defers to the text-only projection when the descriptor declares no model route', async (storage) => { + const { ctx } = await setup(storage, []) const routeless = await ctx.agentLoop.create(brandString('routeless-image'), {}) const started = await ctx.subagents.startActivation({ ...startSpec(routeless), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -1008,8 +1008,8 @@ describe('continuable image Queue prompts', () => { }) describe('target-only Queue residency routing', () => { - it('fails a cold follow-up when Session query is unavailable', async () => { - const { ctx } = await setupWith(new MockAdapter([]), { + it.each(['jsonl', 'sqlite'] as const)('%s: fails a cold follow-up when Session query is unavailable', async (storage) => { + const { ctx } = await setupWith(storage, new MockAdapter([]), { persistence: false, sessionQuery: false, }) @@ -1018,14 +1018,14 @@ describe('target-only Queue residency routing', () => { .rejects.toMatchObject({ code: 'CONTINUATION_UNAVAILABLE' }) }) - it('enqueues in the same Activation while it is running, preserving one inbox FIFO', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: enqueues in the same Activation while it is running, preserving one inbox FIFO', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first'), gate: releaseFirst.promise }, { chunks: textResponse('second') }, { chunks: textResponse('third') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId) @@ -1044,8 +1044,8 @@ describe('target-only Queue residency routing', () => { expect(userTexts(loaded.events)).toEqual(['child task', 'first follow-up', 'second follow-up']) }) - it('cold-resumes a settled child into a new Activation', async () => { - const { ctx, parent } = await setup([textResponse('first'), textResponse('after resume')]) + it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes a settled child into a new Activation', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('after resume')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -1059,8 +1059,8 @@ describe('target-only Queue residency routing', () => { expect(loaded.events.filter(event => event.type === 'subagent/descriptor')).toHaveLength(1) }) - it('cold-resumes after the initial provider unregisters', async () => { - const { ctx, parent } = await setup([textResponse('first'), textResponse('after resume')]) + it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes after the initial provider unregisters', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('after resume')]) const disposeProvider = ctx.subagents.registerProvider({ name: 'retired', capabilities: { agentOptions: false, agentPreset: false, outputSchema: false, depthLimit: false }, @@ -1089,7 +1089,7 @@ describe('target-only Queue residency routing', () => { expect(userTexts(loaded.events)).toEqual(['child task', 'continue without provider']) }) - it('cold-resumes a finished creator while its child keeps the same instance', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes a finished creator while its child keeps the same instance', async (storage) => { const releaseCreator = Promise.withResolvers() const releaseLeaf = Promise.withResolvers() const adapter = new GatedAdapter([ @@ -1097,7 +1097,7 @@ describe('target-only Queue residency routing', () => { { chunks: textResponse('leaf'), gate: releaseLeaf.promise }, { chunks: textResponse('creator resumed') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const creator = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const first = ctx.agents.get(creator.childId)! @@ -1122,8 +1122,8 @@ describe('target-only Queue residency routing', () => { } }) - it('delivers to a nested target by id and rejects a root as a subagent target', async () => { - const { ctx, parent } = await setup(['hang', 'hang', 'hang']) + it.each(['jsonl', 'sqlite'] as const)('%s: delivers to a nested target by id and rejects a root as a subagent target', async (storage) => { + const { ctx, parent } = await setup(storage, ['hang', 'hang', 'hang']) const first = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const second = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const creator = ctx.agents.get(second.childId)! @@ -1138,8 +1138,8 @@ describe('target-only Queue residency routing', () => { } }) - it('rejects a cold target whose persisted identity cannot establish tree membership', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a cold target whose persisted identity cannot establish tree membership', async (storage) => { + const { ctx, parent } = await setup(storage, []) const childId = brandString('child-without-descriptor') const child = await ctx.agents.create({ sessionId: childId, @@ -1160,8 +1160,8 @@ describe('target-only Queue residency routing', () => { .rejects.toMatchObject({ code: 'NOT_RESUMABLE' }) }) - it('rejects a cold target whose persisted descriptor is corrupt as not resumable', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a cold target whose persisted descriptor is corrupt as not resumable', async (storage) => { + const { ctx, parent } = await setup(storage, []) const childId = brandString('child-with-corrupt-descriptor') const child = await ctx.agents.create({ sessionId: childId, @@ -1185,14 +1185,14 @@ describe('target-only Queue residency routing', () => { }) }) - it('reports an unknown child id as unavailable', async () => { - const { ctx } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: reports an unknown child id as unavailable', async (storage) => { + const { ctx } = await setup(storage, []) await expect(queuePrompt(ctx, brandString('missing'), message('hello'))) .rejects.toMatchObject({ code: 'NOT_RESUMABLE' }) }) - it('propagates cancellation while inspecting a cold child', async () => { - const { ctx, parent } = await setup([textResponse('first')]) + it.each(['jsonl', 'sqlite'] as const)('%s: propagates cancellation while inspecting a cold child', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) const inspectStarted = Promise.withResolvers() @@ -1222,8 +1222,8 @@ describe('target-only Queue residency routing', () => { } }) - it('preserves a SubagentError raised while cold-materializing a child', async () => { - const { ctx, parent } = await setup([textResponse('first')]) + it.each(['jsonl', 'sqlite'] as const)('%s: preserves a SubagentError raised while cold-materializing a child', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) const failure = new SubagentError('materialization denied', 'UNAUTHORIZED') @@ -1233,8 +1233,8 @@ describe('target-only Queue residency routing', () => { .rejects.toBe(failure) }) - it('cold-resumes a delivery that lost the race with final disposal', async () => { - const { ctx, parent } = await setup([textResponse('first'), textResponse('after the race')]) + it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes a delivery that lost the race with final disposal', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('after the race')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -1255,13 +1255,13 @@ describe('target-only Queue residency routing', () => { }) describe('continuable human steering delivery', () => { - it('places resident steering in nextStep with its durable identity and source', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: places resident steering in nextStep with its durable identity and source', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first'), gate: release.promise }, { chunks: textResponse('steered') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) @@ -1278,8 +1278,8 @@ describe('continuable human steering delivery', () => { await waitNoActivation(ctx, started.childId) }) - it('cold-resumes steering into nextStep instead of inventing another queue', async () => { - const { ctx, parent } = await setup([textResponse('first'), textResponse('steered')]) + it.each(['jsonl', 'sqlite'] as const)('%s: cold-resumes steering into nextStep instead of inventing another queue', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('steered')]) parkParent(ctx, parent) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -1295,7 +1295,7 @@ describe('continuable human steering delivery', () => { }) describe('continuable child ownership', () => { - it.each(['queue', 'steer'] as const)('delivers human %s to a resident and cold child after its creator exits', async (delivery) => { + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['queue', 'steer'] as const).map(value => [storage, value] as const)))('%s: delivers human %s to a resident and cold child after its creator exits', async (storage, delivery) => { const releaseCreator = Promise.withResolvers() const releaseLeaf = Promise.withResolvers() const adapter = new GatedAdapter([ @@ -1304,7 +1304,7 @@ describe('continuable child ownership', () => { { chunks: textResponse('resident follow-up') }, { chunks: textResponse('cold follow-up') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const starts: SubagentRunInfo[] = [] const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/start', info => void starts.push(info)) @@ -1344,14 +1344,14 @@ describe('continuable child ownership', () => { } }) - it('releases a finished creator while its child remains owned by the subagent tree root', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: releases a finished creator while its child remains owned by the subagent tree root', async (storage) => { const releaseCreator = Promise.withResolvers() const releaseLeaf = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('creator done'), gate: releaseCreator.promise }, { chunks: textResponse('leaf'), gate: releaseLeaf.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const creator = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = ctx.agents.get(creator.childId)! @@ -1375,7 +1375,7 @@ describe('continuable child ownership', () => { } }) - it.each([false, true])('archives a descendant through an offline creator (cold resume=%s)', async (coldResume) => { + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([false, true]).map(value => [storage, value] as const)))('%s: archives a descendant through an offline creator (cold resume=%s)', async (storage, coldResume) => { const releaseCreator = Promise.withResolvers() const releaseLeaf = Promise.withResolvers() const adapter = new GatedAdapter([ @@ -1383,7 +1383,7 @@ describe('continuable child ownership', () => { { chunks: textResponse('leaf'), ...coldResume ? {} : { gate: releaseLeaf.promise } }, ...coldResume ? [{ chunks: textResponse('resumed leaf'), gate: releaseLeaf.promise }] : [], ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const archived: SessionId[] = [] ctx.provide('workspaceRegistry', { get archivedSessionIds() { return archived } } as never) @@ -1423,8 +1423,8 @@ describe('continuable child ownership', () => { } }) - it('does not add a top-level parent to the waiting graph', async () => { - const { ctx, parent } = await setup([textResponse('done')]) + it.each(['jsonl', 'sqlite'] as const)('%s: does not add a top-level parent to the waiting graph', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('done')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) // The top-level parent remains independently registered after its child settles. @@ -1433,13 +1433,13 @@ describe('continuable child ownership', () => { }) describe('continuable durability and teardown', () => { - it('rechecks direct Agent inbox work accepted during the final flush', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rechecks direct Agent inbox work accepted during the final flush', async (storage) => { const releaseFirstTurn = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first answer'), gate: releaseFirstTurn.promise }, { chunks: textResponse('late answer') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const flushing = Promise.withResolvers() const releaseFlush = Promise.withResolvers() @@ -1473,12 +1473,12 @@ describe('continuable durability and teardown', () => { expect(hasAssistantText(loaded.events, 'late answer')).toBe(true) }) - it('retries after Session-only work completes during the final flush', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: retries after Session-only work completes during the final flush', async (storage) => { const releaseFirstTurn = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('answer'), gate: releaseFirstTurn.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const flushing = Promise.withResolvers() const releaseFlush = Promise.withResolvers() @@ -1507,14 +1507,14 @@ describe('continuable durability and teardown', () => { expect(hasUserText(loaded.events, 'detached result')).toBe(true) }) - it('keeps a child acquired during the final flush before settling', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: keeps a child acquired during the final flush before settling', async (storage) => { const releaseFirstTurn = Promise.withResolvers() const releaseGrandchild = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child answer'), gate: releaseFirstTurn.promise }, { chunks: textResponse('grandchild answer'), gate: releaseGrandchild.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const flushing = Promise.withResolvers() const releaseFlush = Promise.withResolvers() @@ -1542,12 +1542,12 @@ describe('continuable durability and teardown', () => { await waitNoActivation(ctx, started.childId) }) - it('lets explicit disposal win while the natural final flush is pending', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: lets explicit disposal win while the natural final flush is pending', async (storage) => { const releaseFirstTurn = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('answer'), gate: releaseFirstTurn.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const flushing = Promise.withResolvers() const releaseFlush = Promise.withResolvers() @@ -1570,10 +1570,10 @@ describe('continuable durability and teardown', () => { expect(ctx.agents.get(started.childId)).toBeUndefined() }) - it('rechecks maintenance that claims the Agent during the final flush', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rechecks maintenance that claims the Agent during the final flush', async (storage) => { const releaseFirstTurn = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: releaseFirstTurn.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) const flushing = Promise.withResolvers() const releaseFlush = Promise.withResolvers() @@ -1614,12 +1614,12 @@ describe('continuable durability and teardown', () => { await waitNoActivation(ctx, started.childId) }) - it('settles despite the persistence backend being disposed mid-run', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: settles despite the persistence backend being disposed mid-run', async (storage) => { const releaseResponse = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('unconfirmed answer'), gate: releaseResponse.promise }, ]) - const { ctx, parent, disposePersistence } = await setupWith(adapter) + const { ctx, parent, disposePersistence } = await setupWith(storage, adapter) const warnings: string[] = [] ctx.logger.warn = (message: string) => { warnings.push(message) } @@ -1636,8 +1636,8 @@ describe('continuable durability and teardown', () => { expect(warnings.join('\n')).not.toContain('final session flush') }) - it('logs a failed final flush after every listener settles without failing the Activation', async () => { - const { ctx, parent } = await setup([textResponse('answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: logs a failed final flush after every listener settles without failing the Activation', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('answer')]) const warnings: string[] = [] const ends: SubagentRunEndInfo[] = [] let peerFlushed = false @@ -1657,10 +1657,10 @@ describe('continuable durability and teardown', () => { expect(ends.at(-1)?.stopReason).toBe('completed') }) - it('logs a teardown failure reached through normal settlement', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: logs a teardown failure reached through normal settlement', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const warnings: string[] = [] ctx.logger.warn = (message: string) => { warnings.push(message) } @@ -1682,13 +1682,13 @@ describe('continuable durability and teardown', () => { }, { timeout: 5_000 }) }) - it('disposes every subagent tree instance on manager teardown', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: disposes every subagent tree instance on manager teardown', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child done'), gate: hold.promise }, { chunks: textResponse('grandchild'), gate: hold.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -1711,7 +1711,7 @@ describe('continuable durability and teardown', () => { expect(loaded.meta.id).toBe(started.childId) }) - it('drains one parent forest without disabling a sibling parent forest', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: drains one parent forest without disabling a sibling parent forest', async (storage) => { const releaseTarget = Promise.withResolvers() const releaseGrandchild = Promise.withResolvers() const releaseSibling = Promise.withResolvers() @@ -1721,7 +1721,7 @@ describe('continuable durability and teardown', () => { { chunks: textResponse('target grandchild'), gate: releaseGrandchild.promise }, { chunks: textResponse('sibling follow-up') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const siblingParent = await ctx.agentLoop.create( brandString('sibling-parent'), { provider: 'mock', model: 'mock' }, @@ -1769,8 +1769,8 @@ describe('continuable durability and teardown', () => { await waitNoActivation(ctx, sibling.childId) }) - it('does not drain a subagent tree when only an ordinary member closes', async () => { - const { ctx, parent } = await setup(['hang', 'hang']) + it.each(['jsonl', 'sqlite'] as const)('%s: does not drain a subagent tree when only an ordinary member closes', async (storage) => { + const { ctx, parent } = await setup(storage, ['hang', 'hang']) const creator = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const child = ctx.agents.get(creator.childId)! const leaf = await ctx.subagents.startActivation({ ...startSpec(child), delivery: 'caller' }) @@ -1784,7 +1784,7 @@ describe('continuable durability and teardown', () => { expect(ctx.agents.get(leaf.childId)).toBeUndefined() }) - it('disposes one activation without releasing siblings or descendants', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: disposes one activation without releasing siblings or descendants', async (storage) => { const releaseTarget = Promise.withResolvers() const releaseSibling = Promise.withResolvers() const releaseGrandchild = Promise.withResolvers() @@ -1793,7 +1793,7 @@ describe('continuable durability and teardown', () => { { chunks: textResponse('sibling'), gate: releaseSibling.promise }, { chunks: textResponse('grandchild'), gate: releaseGrandchild.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const target = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const sibling = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(2) }) @@ -1818,10 +1818,10 @@ describe('continuable durability and teardown', () => { await waitNoActivation(ctx, sibling.childId) }) - it('reports activation disposal failures after releasing the child', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports activation disposal failures after releasing the child', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('target'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const target = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const activation = managerState(ctx).resident.get(target.childId)! @@ -1839,14 +1839,14 @@ describe('continuable durability and teardown', () => { expect(ctx.agents.get(target.childId)).toBeUndefined() }) - it('drains the subagent tree after an intermediate creator leaves the registry', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: drains the subagent tree after an intermediate creator leaves the registry', async (storage) => { const releaseIntermediate = Promise.withResolvers() const releaseDescendant = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('host task'), gate: releaseIntermediate.promise }, { chunks: textResponse('continuable descendant'), gate: releaseDescendant.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) try { const handle = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const intermediate = ctx.agents.get(handle.childId)! @@ -1877,8 +1877,8 @@ describe('continuable durability and teardown', () => { } }) - it('awaits and rolls back an admitted materialization below a scoped root', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: awaits and rolls back an admitted materialization below a scoped root', async (storage) => { + const { ctx, parent } = await setup(storage, []) const agents = managerState(ctx).ownerCtx.agents const create = agents.create.bind(agents) const published = Promise.withResolvers() @@ -1909,8 +1909,8 @@ describe('continuable durability and teardown', () => { } }) - it('ignores a stale scoped root without disabling its live same-id Agent', async () => { - const { ctx, parent } = await setup([textResponse('done')]) + it.each(['jsonl', 'sqlite'] as const)('%s: ignores a stale scoped root without disabling its live same-id Agent', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('done')]) const stale = { ...parent, id: parent.id } as Agent await ctx.subagents.drainDescendants([stale]) @@ -1919,12 +1919,12 @@ describe('continuable durability and teardown', () => { await waitNoActivation(ctx, started.childId) }) - it('reports a scoped teardown failure after releasing the selected branch', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports a scoped teardown failure after releasing the selected branch', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('target child'), gate: hold.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const activation = managerState(ctx).resident.get(started.childId)! @@ -1942,8 +1942,8 @@ describe('continuable durability and teardown', () => { expect(ctx.agents.get(started.childId)).toBeUndefined() }) - it('rejects new materialization and delivery once draining begins', async () => { - const { ctx, parent } = await setup([textResponse('done')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects new materialization and delivery once draining begins', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('done')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -1955,8 +1955,8 @@ describe('continuable durability and teardown', () => { .rejects.toMatchObject({ code: 'DRAINING' }) }) - it('rejects an initial prompt when drain starts after materialization', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects an initial prompt when drain starts after materialization', async (storage) => { + const { ctx, parent } = await setup(storage, []) const drains: Promise[] = [] const accepted: MessageId[] = [] ctx.on('subagent/start', () => { drains.push(drainManager(ctx)) }) @@ -1970,8 +1970,8 @@ describe('continuable durability and teardown', () => { expect(ctx.agents.list()).toEqual([parent]) }) - it('waits for a published materialization to finish rollback before drain resolves', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: waits for a published materialization to finish rollback before drain resolves', async (storage) => { + const { ctx, parent } = await setup(storage, []) const order: string[] = [] const drains: Promise[] = [] ctx.on('agent/created', ({ agent: child }) => { @@ -1993,10 +1993,10 @@ describe('continuable durability and teardown', () => { expect(ctx.agents.list()).toEqual([parent]) }) - it('admits a live follow-up before a later drain can begin disposal', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: admits a live follow-up before a later drain can begin disposal', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2020,10 +2020,10 @@ describe('continuable durability and teardown', () => { expect(order).toEqual(['enqueue', 'cancel']) }) - it('has no automatic replay for an accepted but unlogged message', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: has no automatic replay for an accepted but unlogged message', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('first'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) // Accepted into the inbox, but this queued turn never opens. @@ -2041,8 +2041,8 @@ describe('continuable durability and teardown', () => { }) describe('continuable review regressions', () => { - it('rechecks exact root liveness after cold-resume materialization', async () => { - const { ctx } = await setup([textResponse('first')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rechecks exact root liveness after cold-resume materialization', async (storage) => { + const { ctx } = await setup(storage, [textResponse('first')]) const parentId = brandString('replaceable-parent') const originalParent = await ctx.agents.create({ sessionId: parentId, @@ -2087,10 +2087,10 @@ describe('continuable review regressions', () => { await replacement.dispose() }) - it('accepts a later delivery after Agent.followup throws', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: accepts a later delivery after Agent.followup throws', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2110,9 +2110,9 @@ describe('continuable review regressions', () => { await drained }) - it('reports the child\'s own terminal reason, not teardown success', async () => { + it.each(['jsonl', 'sqlite'] as const)("%s: reports the child's own terminal reason, not teardown success", async (storage) => { // The child hits its token ceiling; teardown still succeeds. - const { ctx, parent } = await setupWith(new MockAdapter([ + const { ctx, parent } = await setupWith(storage, new MockAdapter([ [{ type: 'block-start', index: 0, blockType: 'text' }, { type: 'text-delta', index: 0, text: 'partial' }, { type: 'block-end', index: 0, block: { type: 'text', text: 'partial' } }, @@ -2129,8 +2129,8 @@ describe('continuable review regressions', () => { expect(ends[0]!.stopReason).toBe('max-tokens') }) - it.each(['turn/start', 'turn/end'] as const)('settles a local child whose first %s append fails', async (failedEvent) => { - const { ctx, parent, adapter } = await setup([textResponse('child answer')]) + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['turn/start', 'turn/end'] as const).map(value => [storage, value] as const)))('%s: settles a local child whose first %s append fails', async (storage, failedEvent) => { + const { ctx, parent, adapter } = await setup(storage, [textResponse('child answer')]) const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/end', (info) => { ends.push(info) }) ctx.on('subagent/start', ({ id }) => { @@ -2161,8 +2161,8 @@ describe('continuable review regressions', () => { } }) - it.each(['turn/start', 'turn/end'] as const)('accepts recovery after a local %s append failure', async (failedEvent) => { - const { ctx, parent } = await setup(failedEvent === 'turn/start' + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['turn/start', 'turn/end'] as const).map(value => [storage, value] as const)))('%s: accepts recovery after a local %s append failure', async (storage, failedEvent) => { + const { ctx, parent } = await setup(storage, failedEvent === 'turn/start' ? [textResponse('recovered')] : [textResponse('first answer'), textResponse('recovered')]) let failed = false @@ -2196,8 +2196,8 @@ describe('continuable review regressions', () => { } }) - it('retains a local failure emitted during an earlier terminal notification', async () => { - const { ctx, parent } = await setup([textResponse('child answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: retains a local failure emitted during an earlier terminal notification', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('child answer')]) ctx.on('session/event', (session, event) => { if (session === parent.session || event.type !== 'turn/end') return const child = ctx.agents.get(session.id)! @@ -2214,8 +2214,8 @@ describe('continuable review regressions', () => { } }) - it('ignores another Agent failure delivered to a local activation observer', async () => { - const { ctx, parent } = await setup([textResponse('child answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: ignores another Agent failure delivered to a local activation observer', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('child answer')]) ctx.on('subagent/start', ({ id }) => { const child = ctx.agents.get(id)! child.ctx.emit('agent/error', { agent: parent, turn: 0, step: 0, error: new Error('unrelated failure') }) @@ -2229,10 +2229,10 @@ describe('continuable review regressions', () => { } }) - it('rejects a live delivery whose caller signal aborted before admission', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a live delivery whose caller signal aborted before admission', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: releaseFirst.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2251,8 +2251,8 @@ describe('continuable review regressions', () => { expect(before).toBeGreaterThan(0) }) - it('reports this epoch\'s own output, captured while the child was still live', async () => { - const { ctx, parent } = await setup([ + it.each(['jsonl', 'sqlite'] as const)("%s: reports this epoch's own output, captured while the child was still live", async (storage) => { + const { ctx, parent } = await setup(storage, [ textResponse('first answer'), textResponse('first acknowledgement'), textResponse('second answer'), textResponse('second acknowledgement'), ]) @@ -2283,11 +2283,11 @@ describe('continuable review regressions', () => { expect(notices[1]!.text).toContain('second answer') }) - it('keeps the epoch\'s earlier text past a final empty usage-only message', async () => { + it.each(['jsonl', 'sqlite'] as const)("%s: keeps the epoch's earlier text past a final empty usage-only message", async (storage) => { // A tool-only max-tokens step records an empty assistant/message for // usage. The terminal event retains the previous assistant content, // including its tool call but not the intervening tool result. - const { ctx, parent } = await setup([ + const { ctx, parent } = await setup(storage, [ toolCallResponse('t1', 'noop', {}, 'partial one'), [ { type: 'block-start', index: 0, blockType: 'tool-call' }, @@ -2321,8 +2321,8 @@ describe('continuable review regressions', () => { ]) }) - it('reports a resumed epoch that opened no turn without the previous answer', async () => { - const { ctx, parent } = await setup([textResponse('first answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: reports a resumed epoch that opened no turn without the previous answer', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first answer')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -2343,12 +2343,12 @@ describe('continuable review regressions', () => { expect(ends[0]!.stopReason).toBe('refusal') }) - it('delivers a local result after handle cleanup and parent notifications', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: delivers a local result after handle cleanup and parent notifications', async (storage) => { const turn = Promise.withResolvers() const cleaning = Promise.withResolvers() const cleanup = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: turn.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const followup = vi.spyOn(parent, 'followup') const steer = vi.spyOn(parent, 'steer') const ended = vi.fn() @@ -2383,8 +2383,8 @@ describe('continuable review regressions', () => { await expect(waiting).resolves.toBe(true) }) - it('reports handle-disposal failure on the terminal edge', async () => { - const { ctx, parent } = await setup([textResponse('answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: reports handle-disposal failure on the terminal edge', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('answer')]) const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/end', (info) => { ends.push(info) }) @@ -2407,10 +2407,10 @@ describe('continuable review regressions', () => { expect(ends[0]!.stopReason).toBe('error') }) - it('reports a pre-disposal teardown failure on the terminal edge', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports a pre-disposal teardown failure on the terminal edge', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/end', info => void ends.push(info)) @@ -2429,10 +2429,10 @@ describe('continuable review regressions', () => { } }) - it('releases a naturally settled Activation when terminal capture fails', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: releases a naturally settled Activation when terminal capture fails', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/end', info => void ends.push(info)) @@ -2478,10 +2478,10 @@ describe('continuable review regressions', () => { } }) - it('preserves independent pre-disposal and handle-disposal failures', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: preserves independent pre-disposal and handle-disposal failures', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const activation = managerState(ctx).resident.get(started.childId)! const handle = requireLocalActivation(activation).handle @@ -2507,10 +2507,10 @@ describe('continuable review regressions', () => { } }) - it('cancels a running turn before the best-effort final flush', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: cancels a running turn before the best-effort final flush', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('slow'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const order: string[] = [] ctx.on('session/flush', (session) => { if (session.header.parentSession !== undefined) order.push('flush') @@ -2533,10 +2533,10 @@ describe('continuable review regressions', () => { expect(order.indexOf('cancel')).toBeLessThan(order.lastIndexOf('flush')) }) - it('releases an accepted message that is discarded instead of run', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: releases an accepted message that is discarded instead of run', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) // Queue a turn, then cancel so it is discarded rather than dequeued. The @@ -2552,10 +2552,10 @@ describe('continuable review regressions', () => { expect(hasUserText(loaded.events, 'discarded')).toBe(false) }) - it('settles after removing the last message from an idle parked Inbox', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: settles after removing the last message from an idle parked Inbox', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2568,10 +2568,10 @@ describe('continuable review regressions', () => { await waitNoActivation(ctx, started.childId) }) - it('shares disposal when explicit close overtakes a queued idle settlement', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: shares disposal when explicit close overtakes a queued idle settlement', async (storage) => { const turn = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: turn.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const activation = managerState(ctx).resident.get(started.childId)! const child = ctx.agents.get(started.childId)! @@ -2595,10 +2595,10 @@ describe('continuable review regressions', () => { expect(managerState(ctx).resident.get(started.childId)).toBeUndefined() }) - it('keeps a maintenance task that claimed the idle phase after whenIdle resolved', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: keeps a maintenance task that claimed the idle phase after whenIdle resolved', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2623,10 +2623,10 @@ describe('continuable review regressions', () => { await waitNoActivation(ctx, started.childId) }) - it('settles when maintenance finishes after losing the idle phase', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: settles when maintenance finishes after losing the idle phase', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2646,13 +2646,13 @@ describe('continuable review regressions', () => { await waitNoActivation(ctx, started.childId) }) - it.each([ + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([ { label: 'plugin', source: { kind: 'tool-jobs' as const } }, { label: 'non-plugin', source: { kind: 'team-message', teamId: 't-1' } as never }, - ])('keeps an idle child resident while its Inbox holds $label injected context', async ({ source }) => { + ]).map(value => [storage, value] as const)))('%s: keeps an idle child resident while its Inbox holds $label injected context', async (storage, { source }) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2670,10 +2670,10 @@ describe('continuable review regressions', () => { await waitNoActivation(ctx, started.childId) }) - it('keeps an idle child resident while plugin-sourced steering stays unclaimed', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: keeps an idle child resident while plugin-sourced steering stays unclaimed', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2693,10 +2693,10 @@ describe('continuable review regressions', () => { await waitNoActivation(ctx, started.childId) }) - it('keeps an idle child resident while an interrupted turn leaves human steering parked', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: keeps an idle child resident while an interrupted turn leaves human steering parked', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2711,10 +2711,10 @@ describe('continuable review regressions', () => { await waitNoActivation(ctx, started.childId) }) - it('settles after a delivery discarded inside its own admission window', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: settles after a delivery discarded inside its own admission window', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: releaseFirst.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2736,10 +2736,10 @@ describe('continuable review regressions', () => { expect(hasUserText(loaded.events, 'doomed')).toBe(false) }) - it('settles after a later delivery discards older queued work', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: settles after a later delivery discards older queued work', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: releaseFirst.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -2760,8 +2760,8 @@ describe('continuable review regressions', () => { expect(hasUserText(loaded.events, 'doomed')).toBe(false) }) - it('reports a prompt a pre-step rejection discarded as refusal', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: reports a prompt a pre-step rejection discarded as refusal', async (storage) => { + const { ctx, parent } = await setup(storage, []) parkParent(ctx, parent) const ends: SubagentRunEndInfo[] = [] ctx.on('subagent/end', (info) => { ends.push(info) }) @@ -2781,13 +2781,13 @@ describe('continuable review regressions', () => { expect(ends[0]!.stopReason).toBe('refusal') }) - it('retains the Activation while an accepted message is still in the inbox', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: retains the Activation while an accepted message is still in the inbox', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first'), gate: releaseFirst.promise }, { chunks: textResponse('second') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const registeredAtEnqueue: boolean[] = [] // A synchronous inbox observer runs before the admitting microtask, the // exact window where `Agent.status` is still idle. @@ -2830,8 +2830,8 @@ function settlementNotices(agent: Agent) { } describe('continuable adjacent-Agent delivery', () => { - it('rejects a stale sender before resolving either adjacent target', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a stale sender before resolving either adjacent target', async (storage) => { + const { ctx, parent } = await setup(storage, []) const stale = { ...parent, id: parent.id } as Agent await expect(ctx.subagents.sendMessage(stale, brandString('target'), message('stale'), { @@ -2839,8 +2839,8 @@ describe('continuable adjacent-Agent delivery', () => { })).rejects.toMatchObject({ code: 'UNAUTHORIZED' }) }) - it('explains that a host-owned child Session is not a resident continuable child', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: explains that a host-owned child Session is not a resident continuable child', async (storage) => { + const { ctx, parent } = await setup(storage, []) const childId = brandString('host-owned-child') const handle = await ctx.agents.create({ sessionId: childId, @@ -2858,14 +2858,14 @@ describe('continuable adjacent-Agent delivery', () => { await handle.dispose() }) - it('steers an idle direct parent and preserves sender attribution', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: steers an idle direct parent and preserves sender attribution', async (storage) => { const releaseChild = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child answer'), gate: releaseChild.promise }, { chunks: textResponse('parent report ack') }, { chunks: textResponse('parent settlement ack') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests.filter(request => request.sessionId === started.childId)).toHaveLength(1) @@ -2900,12 +2900,12 @@ describe('continuable adjacent-Agent delivery', () => { }) }) - it.each(['absent', 'replaced'] as const)('rejects delivery when the subagent tree root is %s', async (state) => { + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['absent', 'replaced'] as const).map(value => [storage, value] as const)))('%s: rejects delivery when the subagent tree root is %s', async (storage, state) => { const releaseChild = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child answer'), gate: releaseChild.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -2926,12 +2926,12 @@ describe('continuable adjacent-Agent delivery', () => { await waitNoActivation(ctx, started.childId) }) - it('propagates the subagent tree root inbox rejection', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: propagates the subagent tree root inbox rejection', async (storage) => { const releaseChild = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child answer'), gate: releaseChild.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -2951,7 +2951,7 @@ describe('continuable adjacent-Agent delivery', () => { }) describe('continuable settlement delivery', () => { - it.each(['parent', 'root', 'sibling'] as const)('omits closing text only after messaging the direct parent: %s', async (target) => { + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['parent', 'root', 'sibling'] as const).map(value => [storage, value] as const)))('%s: omits closing text only after messaging the direct parent: %s', async (storage, target) => { const releaseCreator = Promise.withResolvers() const releaseLeaf = Promise.withResolvers() const adapter = new GatedAdapter([ @@ -2959,7 +2959,7 @@ describe('continuable settlement delivery', () => { { chunks: textResponse('leaf answer'), gate: releaseLeaf.promise }, { chunks: textResponse('sibling done'), gate: releaseCreator.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) parkParent(ctx, parent) try { const creator = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) @@ -2987,8 +2987,8 @@ describe('continuable settlement delivery', () => { } }) - it('includes the child answer when messaging is available', async () => { - const { ctx, parent } = await setup([textResponse('the answer'), textResponse('parent ack')]) + it.each(['jsonl', 'sqlite'] as const)('%s: includes the child answer when messaging is available', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('the answer'), textResponse('parent ack')]) await ctx.plugin(SubagentControl) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -3005,8 +3005,8 @@ describe('continuable settlement delivery', () => { ) }) - it('delivers settlement even when the child already sent a message', async () => { - const { ctx, parent } = await setup([textResponse('the answer'), textResponse('parent ack')]) + it.each(['jsonl', 'sqlite'] as const)('%s: delivers settlement even when the child already sent a message', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('the answer'), textResponse('parent ack')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const live = ctx.agents.get(started.childId) @@ -3028,7 +3028,7 @@ describe('continuable settlement delivery', () => { ) }) - it('reports the closing message again when the child received input after its message', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports the closing message again when the child received input after its message', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('interim'), gate: release.promise }, @@ -3036,7 +3036,7 @@ describe('continuable settlement delivery', () => { { chunks: textResponse('the answer') }, { chunks: textResponse('parent ack') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const live = ctx.agents.get(started.childId) @@ -3057,7 +3057,7 @@ describe('continuable settlement delivery', () => { ) }) - it('reports the closing message when the child ran a tool after its message, even past a short-circuiting tool policy', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports the closing message when the child ran a tool after its message, even past a short-circuiting tool policy', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: toolCallResponse('t1', 'noop', {}), gate: release.promise }, @@ -3065,7 +3065,7 @@ describe('continuable settlement delivery', () => { { chunks: textResponse('the answer') }, { chunks: textResponse('parent ack') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) ctx.tools.register(defineTool({ name: 'noop', description: 'does nothing', @@ -3096,10 +3096,10 @@ describe('continuable settlement delivery', () => { ) }) - it.each([ + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([ ['reports', 'another call follows the message in its step', ['send_message', 'noop'], 'Its closing message:\nthe answer'], ['omits', 'the message is the last call of its step', ['noop', 'send_message'], 'It sent you a message just before finishing, so its closing message is omitted.'], - ] as const)('%s the closing message when %s', async (_verb, _case, order, ending) => { + ] as const).map(value => [storage, ...value] as const)))('%s: %s the closing message when %s', async (storage, _verb, _case, order, ending) => { let childTurns = 0 const respond = (options: GenerateOptions): StreamChunk[] => { const history = JSON.stringify(options.messages) @@ -3120,7 +3120,7 @@ describe('continuable settlement delivery', () => { { type: 'finish', reason: { kind: 'tool-calls' } }, ] } - const { ctx, parent } = await setup(Array.from({ length: 6 }, () => respond)) + const { ctx, parent } = await setup(storage, Array.from({ length: 6 }, () => respond)) await ctx.plugin(SubagentControl) ctx.tools.register(defineTool({ name: 'noop', @@ -3141,8 +3141,8 @@ describe('continuable settlement delivery', () => { ) }) - it('delivers the terminal reason when the child never had a chance to report', async () => { - const { ctx, parent } = await setup([maxTokensResponse('half an ans'), textResponse('parent ack')]) + it.each(['jsonl', 'sqlite'] as const)('%s: delivers the terminal reason when the child never had a chance to report', async (storage) => { + const { ctx, parent } = await setup(storage, [maxTokensResponse('half an ans'), textResponse('parent ack')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -3152,8 +3152,8 @@ describe('continuable settlement delivery', () => { ) }) - it('tells the parent a policy-rejected delivery was declined, not finished', async () => { - const { ctx, parent } = await setup([textResponse('parent ack')]) + it.each(['jsonl', 'sqlite'] as const)('%s: tells the parent a policy-rejected delivery was declined, not finished', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('parent ack')]) // A pre-step rejection on the child — a UserPromptSubmit deny, a policy // plugin — discards the claimed prompt without running it. ctx.on('agent/pre-step', async ({ agent: subject }, next) => { @@ -3170,13 +3170,13 @@ describe('continuable settlement delivery', () => { ) }) - it('reports a turn that failed before reaching its first step', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports a turn that failed before reaching its first step', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('the answer'), gate: releaseFirst.promise }, { chunks: textResponse('parent ack') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) // The shipped durability checkpoint (`dsh-session-checkpoint-policy`) is // fail-closed at the step boundary, so a rejected write ends the turn after // it claimed its messages and before it entered a step. @@ -3200,12 +3200,12 @@ describe('continuable settlement delivery', () => { ) }) - it('reports accepted work cut short before its first step as stopped', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports accepted work cut short before its first step as stopped', async (storage) => { const releaseFirst = Promise.withResolvers() const releaseCheckpoint = Promise.withResolvers() const atCheckpoint = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('the answer'), gate: releaseFirst.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) // A step-boundary participant — the shipped durability checkpoint, a hook, // prompt assembly — holding the child's second turn open before its first // step, which is where teardown cancellation then catches it. @@ -3235,10 +3235,10 @@ describe('continuable settlement delivery', () => { ) }) - it('reports a child stopped before it ever reached the model as stopped', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports a child stopped before it ever reached the model as stopped', async (storage) => { const releaseCheckpoint = Promise.withResolvers() const atCheckpoint = Promise.withResolvers() - const { ctx, parent } = await setupWith(new GatedAdapter([])) + const { ctx, parent } = await setupWith(storage, new GatedAdapter([])) ctx.on('agent/pre-step', async ({ agent: subject }, next) => { if (subject.session.header.parentSession === undefined) return next() atCheckpoint.resolve(undefined) @@ -3261,11 +3261,11 @@ describe('continuable settlement delivery', () => { ) }) - it('reports a child an ancestor interrupted before its first step as stopped', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports a child an ancestor interrupted before its first step as stopped', async (storage) => { const atCheckpoint = Promise.withResolvers() const releaseCheckpoint = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('parent ack') }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) ctx.on('agent/pre-step', async ({ agent: subject }, next) => { if (subject.session.header.parentSession === undefined) return next() atCheckpoint.resolve(undefined) @@ -3287,13 +3287,13 @@ describe('continuable settlement delivery', () => { ) }) - it('reports accepted work cancelled before any turn could open as stopped', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports accepted work cancelled before any turn could open as stopped', async (storage) => { const releaseChild = Promise.withResolvers() const releaseMaintenance = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('the answer'), gate: releaseChild.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const live = ctx.agents.get(started.childId) @@ -3324,8 +3324,8 @@ describe('continuable settlement delivery', () => { ) }) - it('delivers the captured answer when local handle cleanup fails', async () => { - const { ctx, parent } = await setup([textResponse('the answer'), textResponse('parent ack')]) + it.each(['jsonl', 'sqlite'] as const)('%s: delivers the captured answer when local handle cleanup fails', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('the answer'), textResponse('parent ack')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const activation = await vi.waitFor(() => { const live = managerState(ctx).resident.get(started.childId) @@ -3348,8 +3348,8 @@ describe('continuable settlement delivery', () => { await expect(started.dispose()).rejects.toThrow('scope unwind failed') }) - it('gives an idle parent one ordinary turn on the notice', async () => { - const { ctx, parent, adapter } = await setup([textResponse('the answer'), textResponse('parent ack')]) + it.each(['jsonl', 'sqlite'] as const)('%s: gives an idle parent one ordinary turn on the notice', async (storage) => { + const { ctx, parent, adapter } = await setup(storage, [textResponse('the answer'), textResponse('parent ack')]) const turnStarts: number[] = [] ctx.on('session/event', (session, event) => { if (session.id === parent.id && event.type === 'turn/start') turnStarts.push(event.data.turn) @@ -3363,7 +3363,7 @@ describe('continuable settlement delivery', () => { expect(turnStarts).toEqual([1]) }) - it('batches simultaneous notices into one step of a busy parent', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: batches simultaneous notices into one step of a busy parent', async (storage) => { const releaseChildren = Promise.withResolvers() const releaseParent = Promise.withResolvers() const adapter = new GatedAdapter([ @@ -3372,7 +3372,7 @@ describe('continuable settlement delivery', () => { { chunks: textResponse('second child'), gate: releaseChildren.promise }, { chunks: textResponse('parent reacts') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) // Open a parent turn first, so both notices arrive while it is running. parent.followup(createUserMessage({ content: message('start working'), source: { kind: 'user' } })) await vi.waitFor(() => { expect(parent.status).toBe('running') }) @@ -3402,10 +3402,10 @@ describe('continuable settlement delivery', () => { - it('does not wake a parent whose own teardown already began', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: does not wake a parent whose own teardown already began', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('interrupted'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(ctx.agents.get(started.childId)).toBeDefined() }) @@ -3425,10 +3425,10 @@ describe('continuable settlement delivery', () => { expect(parent.status).toBe('idle') }) - it('does not wake a parent below a scoped teardown root', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: does not wake a parent below a scoped teardown root', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('interrupted'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(ctx.agents.get(started.childId)).toBeDefined() }) @@ -3440,10 +3440,10 @@ describe('continuable settlement delivery', () => { expect(parent.session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false) }) - it('records but cannot deliver a teardown notice once the parent is disposed too', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: records but cannot deliver a teardown notice once the parent is disposed too', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('interrupted'), gate: hold.promise }]) - const { ctx } = await setupWith(adapter) + const { ctx } = await setupWith(storage, adapter) const parentId = brandString('closing-parent') const host = await ctx.agents.create({ sessionId: parentId, @@ -3475,8 +3475,8 @@ describe('continuable settlement delivery', () => { : [])).toEqual([{ inserted: 1, removed: 0 }, { inserted: 0, removed: 1 }]) }) - it('does not wake a parent whose scope is unwinding during factory unload', async () => { - const { ctx, parent, loop } = await setup([textResponse('child answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: does not wake a parent whose scope is unwinding during factory unload', async (storage) => { + const { ctx, parent, loop } = await setup(storage, [textResponse('child answer')]) const flushing = Promise.withResolvers() const releaseFlush = Promise.withResolvers() const unwinding = Promise.withResolvers() @@ -3508,10 +3508,10 @@ describe('continuable settlement delivery', () => { } }) - it('drops the notice without disturbing teardown when the parent is gone', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: drops the notice without disturbing teardown when the parent is gone', async (storage) => { const releaseChild = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: releaseChild.promise }]) - const { ctx } = await setupWith(adapter) + const { ctx } = await setupWith(storage, adapter) const warnings: string[] = [] ctx.logger.warn = (text: string) => { warnings.push(text) } const host = await ctx.agents.create({ @@ -3529,8 +3529,8 @@ describe('continuable settlement delivery', () => { expect(warnings).toEqual([]) }) - it('logs a rejected notice instead of failing the child\'s teardown', async () => { - const { ctx, parent } = await setup([textResponse('the answer')]) + it.each(['jsonl', 'sqlite'] as const)("%s: logs a rejected notice instead of failing the child's teardown", async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('the answer')]) const warnings: string[] = [] ctx.logger.warn = (text: string) => { warnings.push(text) } vi.spyOn(parent, 'followup').mockImplementation(() => { @@ -3546,8 +3546,8 @@ describe('continuable settlement delivery', () => { expect(warnings.some(warning => warning.includes('settlement notice was not delivered'))).toBe(true) }) - it('stays silent about a child the caller was told does not exist', async () => { - const { ctx, parent } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: stays silent about a child the caller was told does not exist', async (storage) => { + const { ctx, parent } = await setup(storage, []) const drains: Promise[] = [] ctx.on('subagent/start', () => { drains.push(drainManager(ctx)) }) @@ -3559,8 +3559,8 @@ describe('continuable settlement delivery', () => { }) describe('continuable lifecycle observation', () => { - it('emits one paired start/end per residency epoch', async () => { - const { ctx, parent } = await setup([textResponse('first'), textResponse('second')]) + it.each(['jsonl', 'sqlite'] as const)('%s: emits one paired start/end per residency epoch', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first'), textResponse('second')]) parkParent(ctx, parent) const starts: SubagentRunInfo[] = [] const ends: SubagentRunEndInfo[] = [] @@ -3588,8 +3588,8 @@ describe('continuable lifecycle observation', () => { }) describe('continuable public API', () => { - it('exposes no host authority, residency query, cancellation, steering, or report operation', async () => { - const { ctx } = await setup([]) + it.each(['jsonl', 'sqlite'] as const)('%s: exposes no host authority, residency query, cancellation, steering, or report operation', async (storage) => { + const { ctx } = await setup(storage, []) const subagents: Record = ctx.subagents as unknown as Record for (const absent of [ 'activationState', @@ -3609,8 +3609,8 @@ describe('continuable public API', () => { expect(names).not.toContain('steer_subagent') }) - it('catalogs caller-awaited local work without a notice and permits cold continuation', async () => { - const { ctx, parent } = await setup([textResponse('first answer'), textResponse('second answer')]) + it.each(['jsonl', 'sqlite'] as const)('%s: catalogs caller-awaited local work without a notice and permits cold continuation', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first answer'), textResponse('second answer')]) parkParent(ctx, parent) const run = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) expect('steer' in run).toBe(false) @@ -3631,8 +3631,8 @@ describe('continuable public API', () => { expect(stored.events.some(event => event.type === 'assistant/message' && JSON.stringify(event).includes('second answer'))).toBe(true) }) - it('reports a caller-signal abort before acceptance without delivering', async () => { - const { ctx, parent } = await setup([textResponse('first')]) + it.each(['jsonl', 'sqlite'] as const)('%s: reports a caller-signal abort before acceptance without delivering', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('first')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) @@ -3645,13 +3645,13 @@ describe('continuable public API', () => { expect(hasUserText(loaded.events, 'aborted')).toBe(false) }) - it('does not cancel an accepted turn when the caller signal aborts afterwards', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: does not cancel an accepted turn when the caller signal aborts afterwards', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first'), gate: releaseFirst.promise }, { chunks: textResponse('second') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) @@ -3668,8 +3668,8 @@ describe('continuable public API', () => { }) describe('continuable errors', () => { - it('rejects nested creation until the child has a managed Activation', async () => { - const { ctx, parent } = await setup([textResponse('child done')]) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects nested creation until the child has a managed Activation', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('child done')]) parkParent(ctx, parent) let observed = false ctx.on('agent/created', async ({ agent }) => { @@ -3683,10 +3683,10 @@ describe('continuable errors', () => { expect(observed).toBe(true) }) - it('rejects a duplicate Activation at the agent registry collision boundary', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a duplicate Activation at the agent registry collision boundary', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -3703,8 +3703,8 @@ describe('continuable errors', () => { hold.resolve(undefined) }) - it('rejects delegation from an unregistered instance and input to a closing startup', async () => { - const { ctx, parent } = await setup(['hang']) + it.each(['jsonl', 'sqlite'] as const)('%s: rejects delegation from an unregistered instance and input to a closing startup', async (storage) => { + const { ctx, parent } = await setup(storage, ['hang']) const unmanaged = await ctx.agents.create({ sessionId: brandString('unmanaged'), meta: { parentSession: parent.id, origin: 'subagent' }, @@ -3736,10 +3736,10 @@ describe('continuable errors', () => { expect(ends[0]).toMatchObject(starts[0]!) }) - it('rejects establishing a child under a parent whose disposal already began', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rejects establishing a child under a parent whose disposal already began', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('child'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -3755,8 +3755,8 @@ describe('continuable errors', () => { await drained }) - it.each([1, 2])('closes the subagent tree only after pending startup at depth %s rolls back', async (depth) => { - const { ctx, parent } = await setup(Array.from({ length: depth }, () => 'hang' as const)) + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => ([1, 2]).map(value => [storage, value] as const)))('%s: closes the subagent tree only after pending startup at depth %s rolls back', async (storage, depth) => { + const { ctx, parent } = await setup(storage, Array.from({ length: depth }, () => 'hang' as const)) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) const child = ctx.agents.get(started.childId)! const entered = Promise.withResolvers() @@ -3813,13 +3813,13 @@ describe('continuable errors', () => { } }) - it('reports a failing branch after every branch settles, without pinning the rest', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reports a failing branch after every branch settles, without pinning the rest', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child done'), gate: hold.promise }, { chunks: textResponse('grandchild'), gate: hold.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -3847,13 +3847,13 @@ describe('continuable errors', () => { expect(loaded.meta.id).toBe(started.childId) }) - it('rejects a new child at admission when the parent disposal transaction is already open', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rejects a new child at admission when the parent disposal transaction is already open', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('parent child'), gate: hold.promise }, { chunks: textResponse('unused') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const outer = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(outer.childId) @@ -3876,13 +3876,13 @@ describe('continuable errors', () => { } }) - it.each(['agent/created', 'subagent/start'] as const)('rejects child admission when parent disposal begins at %s', async (event) => { + it.each((['jsonl', 'sqlite'] as const).flatMap(storage => (['agent/created', 'subagent/start'] as const).map(value => [storage, value] as const)))('%s: rejects child admission when parent disposal begins at %s', async (storage, event) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('parent child'), gate: hold.promise }, { chunks: textResponse('unused') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const outer = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(outer.childId) @@ -3906,12 +3906,12 @@ describe('continuable errors', () => { } }) - it('allows a sender to settle after a cold delivery fails', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: allows a sender to settle after a cold delivery fails', async (storage) => { const release = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('child done'), gate: release.promise }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) const child = await vi.waitFor(() => { const found = ctx.agents.get(started.childId) @@ -3928,13 +3928,13 @@ describe('continuable errors', () => { - it('reapplies the descriptor model route and reasoning effort on cold resume', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: reapplies the descriptor model route and reasoning effort on cold resume', async (storage) => { const effort = brandString('high') const adapter = new MockAdapter([textResponse('first'), textResponse('resumed')], { efforts: [{ id: effort, name: 'High' }], defaultEffort: effort, }) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ delivery: 'parent', ...startSpec(parent), @@ -3966,13 +3966,13 @@ describe('continuable errors', () => { : [])).toEqual([effort, effort]) }) - it('unloading the manager drains its live activations', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: unloading the manager drains its live activations', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('child'), gate: hold.promise }]) const ctx = new Context() await mountAgentLoopTestDependencies(ctx) const root = mkdtempSync(join(tmpdir(), 'dsh-subagent-continuation-')) - const persistenceFiber = await ctx.plugin(JsonlSessionPersistence, { root }) + const persistenceFiber = await ctx.plugin(JsonlSessionPersistence, { storage, root }) cleanups.push(async () => { await persistenceFiber.dispose() rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) @@ -3996,7 +3996,7 @@ describe('continuable errors', () => { }) describe('SubagentRuntime.interrupt', () => { - it('aborts the current turn durably, parks accepted follow-ups, and settles after direct Agent followup', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: aborts the current turn durably, parks accepted follow-ups, and settles after direct Agent followup', async (storage) => { const releaseFirst = Promise.withResolvers() const adapter = new GatedAdapter([ { chunks: textResponse('first'), gate: releaseFirst.promise }, @@ -4004,7 +4004,7 @@ describe('SubagentRuntime.interrupt', () => { { chunks: textResponse('third') }, { chunks: textResponse('fourth') }, ]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -4039,14 +4039,14 @@ describe('SubagentRuntime.interrupt', () => { expect(turnEnds).toEqual(['aborted', 'completed', 'completed', 'completed']) }) - it('interrupts only the target while its resident descendant keeps running', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: interrupts only the target while its resident descendant keeps running', async (storage) => { const releaseChild = Promise.withResolvers() const releaseGrandchild = Promise.withResolvers() 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({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -4077,10 +4077,10 @@ describe('SubagentRuntime.interrupt', () => { expect(turnEnds).toEqual(['completed']) }) - it('interrupts a target by id as a trusted user operation', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: interrupts a target by id as a trusted user operation', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -4092,14 +4092,14 @@ describe('SubagentRuntime.interrupt', () => { await waitNoActivation(ctx, started.childId) }) - it('lets a deep exact live ancestor interrupt its descendant with the parent cause', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: lets a deep exact live ancestor interrupt its descendant with the parent cause', async (storage) => { const releaseChild = Promise.withResolvers() const releaseGrandchild = Promise.withResolvers() 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({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! @@ -4122,14 +4122,14 @@ describe('SubagentRuntime.interrupt', () => { await waitNoActivation(ctx, started.childId) }) - it('rejects self, sibling, stale, and unrelated ancestor callers without touching the target', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: rejects self, sibling, stale, and unrelated ancestor callers without touching the target', async (storage) => { const releaseA = Promise.withResolvers() const releaseB = Promise.withResolvers() 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 targetStart = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const target = ctx.agents.get(targetStart.childId)! @@ -4159,9 +4159,9 @@ describe('SubagentRuntime.interrupt', () => { await waitNoActivation(ctx, siblingStart.childId) }) - it('accepts absent ids and interrupts caller-awaited local activations', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: accepts absent ids and interrupts caller-awaited local activations', async (storage) => { const release = Promise.withResolvers() - const { ctx, parent } = await setupWith(new GatedAdapter([ + const { ctx, parent } = await setupWith(storage, new GatedAdapter([ { chunks: textResponse('unfinished'), gate: release.promise }, ])) ctx.subagents.interrupt(brandString('missing'), { kind: 'user' }) @@ -4184,18 +4184,18 @@ describe('SubagentRuntime.interrupt', () => { } }) - it('accepts an interrupt after natural completion', async () => { - const { ctx, parent } = await setup([textResponse('done')]) + it.each(['jsonl', 'sqlite'] as const)('%s: accepts an interrupt after natural completion', async (storage) => { + const { ctx, parent } = await setup(storage, [textResponse('done')]) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await waitNoActivation(ctx, started.childId) ctx.subagents.interrupt(started.childId, { kind: 'user' }) ctx.subagents.interrupt(started.childId, { kind: 'ancestor', agent: parent }) }) - it('accepts an interrupt that lost the race with disposal without signalling twice', async () => { + it.each(['jsonl', 'sqlite'] as const)('%s: accepts an interrupt that lost the race with disposal without signalling twice', async (storage) => { const hold = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: hold.promise }]) - const { ctx, parent } = await setupWith(adapter) + const { ctx, parent } = await setupWith(storage, adapter) const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) const child = ctx.agents.get(started.childId)! diff --git a/packages/subagent/subagent/tests/list-children.spec.ts b/packages/subagent/subagent/tests/list-children.spec.ts index 2316cd29eb..a37e6f46dd 100644 --- a/packages/subagent/subagent/tests/list-children.spec.ts +++ b/packages/subagent/subagent/tests/list-children.spec.ts @@ -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('historical-parent') const child = brandString('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('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('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('branch')) const leaf = ctx.sessions.create(brandString('leaf')) const sibling = ctx.sessions.create(brandString('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('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('once')) const unknown = ctx.sessions.create(brandString('unknown')) const leaf = ctx.sessions.create(brandString('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('branch')) const leaf = ctx.sessions.create(brandString('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('ordinary-fork')) const leaf = ctx.sessions.create(brandString('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('branch')) const hidden = ctx.sessions.create(brandString('hidden')) const sibling = ctx.sessions.create(brandString('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('branch')) const sibling = ctx.sessions.create(brandString('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('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('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('branch')) catalog(parent.session, [child('branch')]) const controller = new AbortController() diff --git a/packages/subagent/subagent/tests/local-activation.ts b/packages/subagent/subagent/tests/local-activation.ts index 4baaf348aa..a9b9672243 100644 --- a/packages/subagent/subagent/tests/local-activation.ts +++ b/packages/subagent/subagent/tests/local-activation.ts @@ -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 { +export async function mountLocalActivations(storage: 'jsonl' | 'sqlite', ctx: Context): Promise { 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 }) } /** diff --git a/packages/subagent/subagent/tests/parent-result.spec.ts b/packages/subagent/subagent/tests/parent-result.spec.ts index 331825d178..94a90aaef0 100644 --- a/packages/subagent/subagent/tests/parent-result.spec.ts +++ b/packages/subagent/subagent/tests/parent-result.spec.ts @@ -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) diff --git a/packages/subagent/subagent/tests/schedule-tools.spec.ts b/packages/subagent/subagent/tests/schedule-tools.spec.ts index 29ffc4823c..69b2da6881 100644 --- a/packages/subagent/subagent/tests/schedule-tools.spec.ts +++ b/packages/subagent/subagent/tests/schedule-tools.spec.ts @@ -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 }> { +async function setupScheduleHost(storage: 'jsonl' | 'sqlite' ): Promise<{ ctx: Context; parent: Agent; dispatched: ReturnType }> { 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', diff --git a/packages/subagent/subagent/tests/sibling-messages.spec.ts b/packages/subagent/subagent/tests/sibling-messages.spec.ts index abd8e78a5b..c236ec9952 100644 --- a/packages/subagent/subagent/tests/sibling-messages.spec.ts +++ b/packages/subagent/subagent/tests/sibling-messages.spec.ts @@ -60,13 +60,13 @@ afterEach(async () => { }) /** Boot persistence, the Agent loop, one spawn provider, and the routed model. */ -async function setup(replies: Record, maxActiveSubagents = 16) { +async function setup(storage: 'jsonl' | 'sqlite', replies: Record, 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('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('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('legacy-child'), { provider: 'mock', model: 'mock' }) bindSubagentActivation(ctx, legacy, parent) expect(ctx.subagents.namesOf(legacy)).toEqual({ self: 'legacy-child', parent: 'lead' }) diff --git a/packages/subagent/subagent/tests/structured.spec.ts b/packages/subagent/subagent/tests/structured.spec.ts index 141e569a4d..b27c1c6e14 100644 --- a/packages/subagent/subagent/tests/structured.spec.ts +++ b/packages/subagent/subagent/tests/structured.spec.ts @@ -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('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('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 diff --git a/packages/subagent/subagent/tests/working-directory.spec.ts b/packages/subagent/subagent/tests/working-directory.spec.ts index 067becefd8..e628cf31c0 100644 --- a/packages/subagent/subagent/tests/working-directory.spec.ts +++ b/packages/subagent/subagent/tests/working-directory.spec.ts @@ -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('missing-directory-service') const create = ctx.agents.create.bind(ctx.agents) diff --git a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts index 4456259267..b5aa0a2e11 100644 --- a/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/list-agents.spec.ts @@ -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[0]) { - return setupWith(new MockAdapter(script)) +async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters[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 } 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('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('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() const releaseGrandchild = Promise.withResolvers() 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() const releaseDelta = Promise.withResolvers() 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, diff --git a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts index a6b5b08860..4bee1407e9 100644 --- a/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts +++ b/packages/subagent/tool-subagent-control/tests/tool-subagent-control.spec.ts @@ -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[0]) { - return setupWith(new MockAdapter(script)) +async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters[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 } 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 }).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() - 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('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('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('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() - 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 }).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() 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() const releaseGrandchild = Promise.withResolvers() 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() const releaseB = Promise.withResolvers() 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') diff --git a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts index c6b7b99c5e..16a15c870d 100644 --- a/packages/subagent/tool-subagent/tests/preset-selection.spec.ts +++ b/packages/subagent/tool-subagent/tests/preset-selection.spec.ts @@ -33,10 +33,10 @@ afterEach(async () => { } }) -async function mountSpawn(ctx: Context, providerName: string): Promise { +async function mountSpawn(storage: 'jsonl' | 'sqlite', ctx: Context, providerName: string): Promise { 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('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: { diff --git a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts index 3a012203ee..6231d78953 100644 --- a/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts +++ b/packages/subagent/tool-subagent/tests/tool-subagent.spec.ts @@ -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('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('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() const releasePreparations = Promise.withResolvers() const cancelled = new AbortController() diff --git a/packages/team/agent-team/tests/persistence.spec.ts b/packages/team/agent-team/tests/persistence.spec.ts index 44a62fd421..e132dbfc35 100644 --- a/packages/team/agent-team/tests/persistence.spec.ts +++ b/packages/team/agent-team/tests/persistence.spec.ts @@ -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', }), }, diff --git a/packages/team/agent-team/tests/team.spec.ts b/packages/team/agent-team/tests/team.spec.ts index 96cc80d536..c87c066291 100644 --- a/packages/team/agent-team/tests/team.spec.ts +++ b/packages/team/agent-team/tests/team.spec.ts @@ -52,6 +52,7 @@ function durable(agent: Agent): TeamProjectionState { } async function setup( + storage: 'jsonl' | 'sqlite', script: ConstructorParameters[0], config: ConstructorParameters[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 { } 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('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('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('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() const release = Promise.withResolvers() 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(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 { return this[Service.init]() } @@ -415,10 +416,10 @@ describe('Tree-owned task boards', () => { expect([first.id, second.id]).toEqual([brandString('task-1'), brandString('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('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('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(`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('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() const release = Promise.withResolvers() @@ -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' })) diff --git a/packages/team/tool-agent-team/tests/tool-team.spec.ts b/packages/team/tool-agent-team/tests/tool-team.spec.ts index 0de7b27cb1..6c166cfb17 100644 --- a/packages/team/tool-agent-team/tests/tool-team.spec.ts +++ b/packages/team/tool-agent-team/tests/tool-team.spec.ts @@ -70,14 +70,14 @@ afterEach(async () => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) }) -async function setup(script: ConstructorParameters[0], enabled = true) { +async function setup(storage: 'jsonl' | 'sqlite', script: ConstructorParameters[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 { } 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('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('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('historical-worker') for (const phase of ['provisioning', 'active'] as const) lead.session.append('team/member', { version: 2, teamId: brandString(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('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('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() @@ -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('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() const release = Promise.withResolvers() 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"') diff --git a/packages/test-support/session-snapshot/README.i18n.yaml b/packages/test-support/session-snapshot/README.i18n.yaml index 1425edc812..b7d219c943 100644 --- a/packages/test-support/session-snapshot/README.i18n.yaml +++ b/packages/test-support/session-snapshot/README.i18n.yaml @@ -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 diff --git a/packages/test-support/session-snapshot/README.md b/packages/test-support/session-snapshot/README.md index 09aed7ac61..88b295a4f6 100644 --- a/packages/test-support/session-snapshot/README.md +++ b/packages/test-support/session-snapshot/README.md @@ -88,6 +88,8 @@ For an initial headless live recording with no Session file, temporarily set `in A nested `workspace.expected//.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 `` 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. diff --git a/packages/test-support/session-snapshot/README.zh.md b/packages/test-support/session-snapshot/README.zh.md index 01089dfd4f..f2086231cd 100644 --- a/packages/test-support/session-snapshot/README.zh.md +++ b/packages/test-support/session-snapshot/README.zh.md @@ -88,6 +88,8 @@ Headless/ACP 与 SDK 适配器在规范化之前,将原始目录中的子创 嵌套的 `workspace.expected//.empty` 标记表示空目录;实际 workspace 中的同名文件仍按普通文件比较。 +`DSH_SNAPSHOT_STORAGE` 为子进程与 Web 快照测试选择 `jsonl`(默认)或 `sqlite`。两种后端使用同一份预期 fixture。可比较日志会解析为 JSON 记录:忽略对象字段顺序,但每个字段值、事件数量、事件顺序与数组顺序都参与比较。 + ### 固定请求 header 与系统提示 每个 pin 默认拥有其生成的 `system-prompt.expected.md` 或 `tool-schemas.expected.json` 伴随文件;当完整的对应序列相同时,`systemPromptSource` 与 `toolSchemasSource` 指定另一个 pin 作为来源,因此每个不同版本只提交一次。系统提示是 surface 节点 0,作为 `system/message` 事件记录在该步骤第一个 `request/header` 之前;每个 fixture 把其文本块存储为 `"text":"{{system}}"`,提示词伴随文件保留完整文本。该 pin 的 `request/header` 事件存储 `"tools":"{{tools}}"`,同时保留配置与原因,结构化 schema 伴随文件保留完整目录。包含 developer 消息的日志会在各 header 中保留有序工具名,而不使用 token,以便继续校验历史工具添加引用。自身作用域组合出不同请求的 child Session 按 fixture 索引以 `pinsChildToolSchemas` 与 `pinsChildSystemPrompts` 单独声明。运行中改变请求 header 的场景声明 `expectedHeaderChanges`;运行中提示词发生变化的场景——替换节点 0,或在 `in-history` 路由上追加到已缓存历史之后——声明 `expectedPromptChanges`,每次变化在提示词伴随文件中增加一个 `` 小节。manifest 中对应字段为 `header.changes` 与 `header.promptChanges`。没有工具的请求头在 sidecar 中保留空 schema 集,使后续首次添加仍与其请求头对齐。 @@ -100,7 +102,6 @@ Headless/ACP 与 SDK 适配器在规范化之前,将原始目录中的子创 - **持久记录等待超时**——即使首次日志收集就超过期限,`waitForTurnStart`、`waitForTurnEnd`、`waitForSubagentTurnEnd`、`waitForGoalPhase`、`waitForInboxMessage`、`waitForTitleAfterTurnEnd` 和 `waitForEventAfterTurnEnd` 也会指出会话或子会话及等待期限。子会话等待还会指出目标轮次。这些等待都通过错误的 cause 保留底层失败。`waitForTurnStart` 会立即拒绝格式错误的轮次记录。 - **fixture 保护拒绝已提交文件**——遗留场景目录、缺失文件、一个 header 类别包含多个 pin、重复的伴随文件内容、未擦除的提示文本或工具 schema、没有前置 `system/message` 的 `request/header`,以及格式错误的 pin header 都会在比较运行前使套件失败。 -- **会话收集需要原始 JSONL mode**——快照配置使用 JSONL 后端的 `compression: 'none'`;压缩 JSONL 没有快照收集路径。 - **构建 mode 需要当前产物**——选择 `DSH_EXAMPLE_MODE=lib` 前先运行 `pnpm run build`;源 mode 仍是零构建路径。 ----- @@ -115,7 +116,7 @@ Headless/ACP 与 SDK 适配器在规范化之前,将原始目录中的子创 ### 设计 -共享核心拥有 manifest、generation 限定角色选择、workspace 设置/比较、类型化身份映射、normalizer 与 fixture 不变式。ACP 适配器增加四个可组合层:launcher、场景 harness、normalizer 与 suite factory。`launchAcpTestAgent` 在 tsx 下启动源码 profile,或在普通 Node 下启动已构建 `lib` profile,通过原始字节 stdout tee 连接 SDK client,收集 Session update 与 stderr,默认拒绝未处理的权限请求,并负责关闭。`runScenario` 驱动 ACP JSON-RPC stdio,并收集每个 Session 目录中数值最高的持久原始 JSONL generation。纯 normalizer 把 cwd 路径与类型化身份变为稳定 token,将时间归零、展开物理来源区间,并擦除系统提示词文本与工具 schema bulk。`defineAcpSnapshotSuite` 注册比较、generation 限定 fixture 回写与实时一致性保护。 +共享核心拥有 manifest、generation 限定角色选择、workspace 设置/比较、类型化身份映射、normalizer 与 fixture 不变式。ACP 适配器增加四个可组合层:launcher、场景 harness、normalizer 与 suite factory。`launchAcpTestAgent` 在 tsx 下启动源码 profile,或在普通 Node 下启动已构建 `lib` profile,通过原始字节 stdout tee 连接 SDK client,收集 Session update 与 stderr,默认拒绝未处理的权限请求,并负责关闭。`runScenario` 驱动 ACP JSON-RPC stdio,并通过 `SessionPersistence.list/open/read` 读取已提交的逻辑历史,包括压缩 JSONL 与 SQLite 会话。纯 normalizer 把 cwd 路径与类型化身份变为稳定 token,将时间归零、展开物理来源区间,并擦除系统提示词文本与工具 schema bulk。`defineAcpSnapshotSuite` 注册比较、generation 限定 fixture 回写与实时一致性保护。 ### 源码地图 @@ -167,7 +168,6 @@ Headless/ACP 与 SDK 适配器在规范化之前,将原始目录中的子创 这些限制说明何时需要对该工具包特别小心。它们是当前包约束,不是任务积压。 -- **会话收集需要原始 JSONL mode**——`runScenario` 收集持久化 `.jsonl` 日志,因此快照配置使用 JSONL 后端的 `compression: 'none'`;压缩 JSONL 没有快照收集路径。 - **构建 mode 需要当前产物**——选择 `DSH_EXAMPLE_MODE=lib` 前先运行 `pnpm run build`;源 mode 仍是零构建路径。 - **ACP 继续覆盖协议行为**——刺激来自 ACP 客户端的取消与权限往返留在该适配器;组装式一次性行为与持久控制行为使用 headless 与 SDK 适配器。 diff --git a/packages/test-support/session-snapshot/src/harness.ts b/packages/test-support/session-snapshot/src/harness.ts index e2e4712408..815160f718 100644 --- a/packages/test-support/session-snapshot/src/harness.ts +++ b/packages/test-support/session-snapshot/src/harness.ts @@ -248,7 +248,9 @@ export function snapshotSpillRoot( export async function runScenario(input: InputScript, opts: RunOptions): Promise { const cwd = await mkdtemp(join(opts.workspaceParent ?? tmpdir(), 'acp-snap-cwd-')) const cwdAliases = [...new Set([realpathSync(cwd), realpathSync.native(cwd)])] + const storage = (opts.env?.DSH_SNAPSHOT_STORAGE ?? process.env.DSH_SNAPSHOT_STORAGE ?? 'jsonl') as 'jsonl' | 'sqlite' const sessionsRoot = await mkdtemp(join(tmpdir(), 'acp-snap-sessions-')) + const readLogs = (): Promise => harvestSessionLogs(sessionsRoot, storage) let spillRoot: string | undefined // Everything past the temp-dir creation is followed by failure-safe cleanup, // so a failure in workspace seeding, spawn, or any step never leaks resources. @@ -279,6 +281,7 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise DSH_SNAPSHOT: opts.mode, DSH_SNAPSHOT_FILE: opts.fixtureFile, DSH_SNAPSHOT_SESSIONS_ROOT: sessionsRoot, + DSH_SNAPSHOT_STORAGE: storage, DSH_SNAPSHOT_SPILL_ROOT: spillRoot, DSH_SNAPSHOT_SPILL_LOCATOR_ROOT: snapshotSpillRoot(opts.fixtureFile), DSH_HOME: join(cwd, '.dsh'), @@ -334,13 +337,13 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise match => active.waitForUpdate(match), () => sessionId, (id) => { sessionId = id }, - (id, timeoutMs, minimumTurn) => waitForPersistedTurnStart(sessionsRoot, id, timeoutMs, minimumTurn), - (id, timeoutMs) => waitForPersistedTurnEnd(sessionsRoot, id, timeoutMs), - (child, timeoutMs, minimumTurn) => waitForPersistedChildTurnEnd(sessionsRoot, child, timeoutMs, minimumTurn), - (id, phase, timeoutMs) => waitForPersistedGoalPhase(sessionsRoot, id, phase, timeoutMs), - (id, text, timeoutMs) => waitForPersistedInboxMessage(sessionsRoot, id, text, timeoutMs), - (id, timeoutMs) => waitForPersistedTitleAfterTurnEnd(sessionsRoot, id, timeoutMs), - (id, type, timeoutMs) => waitForPersistedEventAfterTurnEnd(sessionsRoot, id, type, timeoutMs), + (id, timeoutMs, minimumTurn) => waitForPersistedTurnStart(readLogs, id, timeoutMs, minimumTurn), + (id, timeoutMs) => waitForPersistedTurnEnd(readLogs, id, timeoutMs), + (child, timeoutMs, minimumTurn) => waitForPersistedChildTurnEnd(readLogs, child, timeoutMs, minimumTurn), + (id, phase, timeoutMs) => waitForPersistedGoalPhase(readLogs, id, phase, timeoutMs), + (id, text, timeoutMs) => waitForPersistedInboxMessage(readLogs, id, text, timeoutMs), + (id, timeoutMs) => waitForPersistedTitleAfterTurnEnd(readLogs, id, timeoutMs), + (id, type, timeoutMs) => waitForPersistedEventAfterTurnEnd(readLogs, id, type, timeoutMs), ) // A permission exchange happens while a step's request is in flight, so // by the time the step settles any script bug it exposed is captured — @@ -353,7 +356,7 @@ export async function runScenario(input: InputScript, opts: RunOptions): Promise await active.close() // Harvest EVERY persisted log (parent + any subagent children) while the // generated dirs still exist, ordered primary-first. - sessionLogs = await harvestSessionLogs(sessionsRoot) + sessionLogs = await readLogs() const finalWorkspace = await captureWorkspaceSnapshot(cwd, { ignoredRootEntries: ['.agents', '.dsh', '.dsh-profile-patches', '.dsh-snapshot-stream-ready'], }) @@ -560,7 +563,7 @@ async function runStep( /** Wait until persistence exposes an open turn for the selected session. */ async function waitForPersistedTurnStart( - root: string, + readLogs: () => Promise, sessionId: string, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, minimumTurn?: number, @@ -569,7 +572,7 @@ async function waitForPersistedTurnStart( const message = `snapshot-harness: session "${sessionId}" did not persist ${detail} within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const log = (await harvestSessionLogs(root)).find(candidate => candidate.id === sessionId) + const log = (await readLogs()).find(candidate => candidate.id === sessionId) const openTurn = log === undefined ? undefined : latestOpenTurn(log.content) if (openTurn === undefined || (minimumTurn !== undefined && openTurn < minimumTurn)) { throw new Error(message) @@ -587,14 +590,14 @@ async function waitForPersistedTurnStart( * keep subprocess disposal from changing an `aborted` turn into `disposed`. */ async function waitForPersistedTurnEnd( - root: string, + readLogs: () => Promise, sessionId: string, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, ): Promise { const message = `snapshot-harness: session "${sessionId}" did not persist turn/end within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const log = (await harvestSessionLogs(root)).find(candidate => candidate.id === sessionId) + const log = (await readLogs()).find(candidate => candidate.id === sessionId) if (log === undefined || !latestTurnIsClosed(log.content)) throw new Error(message) }, { interval: WAIT_POLL_INTERVAL_MS, timeout: timeoutMs }) } catch (cause) { @@ -612,7 +615,7 @@ async function waitForPersistedTurnEnd( * own model work reached a closed turn. */ async function waitForPersistedChildTurnEnd( - root: string, + readLogs: () => Promise, child: number, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, minimumTurn = 1, @@ -620,7 +623,7 @@ async function waitForPersistedChildTurnEnd( const message = `snapshot-harness: subagent child #${child} did not persist closed turn ${minimumTurn} within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const log = (await harvestSessionLogs(root))[child] + const log = (await readLogs())[child] if (log === undefined || !latestTurnIsClosed(log.content) || !hasRequestHeaderAfterDescriptor(log.content) || !hasClosedTurn(log.content, minimumTurn)) { @@ -643,7 +646,7 @@ function hasClosedTurn(content: string, turn: number): boolean { /** Wait until the latest durable goal snapshot reaches one phase. */ async function waitForPersistedGoalPhase( - root: string, + readLogs: () => Promise, sessionId: string, phase: string, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, @@ -651,7 +654,7 @@ async function waitForPersistedGoalPhase( const message = `snapshot-harness: session "${sessionId}" did not persist goal phase "${phase}" within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const content = (await harvestSessionLogs(root)).find(log => log.id === sessionId)?.content + const content = (await readLogs()).find(log => log.id === sessionId)?.content const matched = content?.split('\n').filter(Boolean).some((line) => { const event = JSON.parse(line) as { type?: unknown; data?: { goal?: { phase?: unknown } } } return event.type === 'goal/change' && event.data?.goal?.phase === phase @@ -665,7 +668,7 @@ async function waitForPersistedGoalPhase( /** Wait until an inserted inbox message contains scenario-owned text. */ async function waitForPersistedInboxMessage( - root: string, + readLogs: () => Promise, sessionId: string, text: string, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, @@ -673,7 +676,7 @@ async function waitForPersistedInboxMessage( const message = `snapshot-harness: session "${sessionId}" did not persist expected inbox message within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const log = (await harvestSessionLogs(root)).find(candidate => candidate.id === sessionId) + const log = (await readLogs()).find(candidate => candidate.id === sessionId) const matched = log?.content.split('\n').some((line) => { if (line.length === 0) return false const record = JSON.parse(line) as { @@ -704,14 +707,14 @@ function hasRequestHeaderAfterDescriptor(content: string): boolean { /** Wait until a complete provider or fallback title record follows the latest closed turn. */ async function waitForPersistedTitleAfterTurnEnd( - root: string, + readLogs: () => Promise, sessionId: string, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, ): Promise { const message = `snapshot-harness: session "${sessionId}" did not persist session/title after turn/end within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const log = (await harvestSessionLogs(root)).find(candidate => candidate.id === sessionId) + const log = (await readLogs()).find(candidate => candidate.id === sessionId) if (log === undefined || !latestTitleFollowsTurnEnd(log.content)) throw new Error(message) }, { interval: WAIT_POLL_INTERVAL_MS, timeout: timeoutMs }) } catch (cause) { @@ -721,7 +724,7 @@ async function waitForPersistedTitleAfterTurnEnd( /** Wait until a complete record of `type` follows the latest closed turn. */ async function waitForPersistedEventAfterTurnEnd( - root: string, + readLogs: () => Promise, sessionId: string, type: string, timeoutMs = DEFAULT_WAIT_TIMEOUT_MS, @@ -729,7 +732,7 @@ async function waitForPersistedEventAfterTurnEnd( const message = `snapshot-harness: session "${sessionId}" did not persist ${type} after turn/end within ${timeoutMs}ms` try { await vi.waitFor(async () => { - const log = (await harvestSessionLogs(root)).find(candidate => candidate.id === sessionId) + const log = (await readLogs()).find(candidate => candidate.id === sessionId) if (log === undefined || !latestEventFollowsTurnEnd(log.content, type)) throw new Error(message) }, { interval: WAIT_POLL_INTERVAL_MS, timeout: timeoutMs }) } catch (cause) { @@ -783,10 +786,10 @@ function latestOpenTurn(content: string): number | undefined { } /** Read settled logical Session histories through the provider and order the parent before its children. */ -async function harvestSessionLogs(root: string): Promise { +async function harvestSessionLogs(root: string, storage: 'jsonl' | 'sqlite'): Promise { const ctx = new Context() try { - await ctx.plugin(persistencePlugin, { root, compression: 'none' }) + await ctx.plugin(persistencePlugin, { root, compression: 'none', storage }) const logs: HarvestedLog[] = [] for (const snapshot of await ctx.sessionPersistence.list()) { const handle = await ctx.sessionPersistence.open(snapshot.header.id, 'read') diff --git a/packages/test-support/session-snapshot/src/launcher.ts b/packages/test-support/session-snapshot/src/launcher.ts index 3524da3347..86a0f2ae5c 100644 --- a/packages/test-support/session-snapshot/src/launcher.ts +++ b/packages/test-support/session-snapshot/src/launcher.ts @@ -123,7 +123,7 @@ export function launchAcpTestAgent(options: AcpTestLaunchOptions): LaunchedAcpTe libBin: agent.libBinScript, configArgs: agent.profile === undefined ? ['--config', selectedConfig] - : profileArgs(agent.profile, agent.configPath, selectedConfig, options.env?.DSH_SNAPSHOT, cwd), + : profileArgs(agent.profile, agent.configPath, selectedConfig, options.env?.DSH_SNAPSHOT, cwd, options.env?.DSH_SNAPSHOT_STORAGE), tsconfigPath: agent.tsconfigPath, ...agent.profile === undefined ? {} : { sourceImport: 'tsx/esm' }, env: { @@ -346,6 +346,7 @@ function profileArgs( selectedPatch: string, snapshotMode: string | undefined, cwd: string, + storage: string | undefined, ): string[] { const base = resolve(cwd, basePatch) const selected = resolve(cwd, selectedPatch) @@ -358,6 +359,11 @@ function profileArgs( mkdirSync(materializedRoot, { recursive: true }) const materializedDir = mkdtempSync(join(materializedRoot, 'launch-')) const materialized = patches.map((file, index) => materializeProfilePatch(file, cwd, profile, materializedDir, index)) + if (storage !== undefined) { + const storagePatch = join(materializedDir, 'session-storage.yml') + writeFileSync(storagePatch, stringifyEntryYaml([{ id: 'session-persistence-jsonl', config: { storage } }])) + materialized.push(storagePatch) + } return ['--profile', profile, ...materialized.flatMap(file => ['--patch', file])] } diff --git a/packages/test-support/session-snapshot/src/suite.ts b/packages/test-support/session-snapshot/src/suite.ts index ccaf94d7a8..ad76259d43 100644 --- a/packages/test-support/session-snapshot/src/suite.ts +++ b/packages/test-support/session-snapshot/src/suite.ts @@ -1483,7 +1483,8 @@ export function defineAcpSnapshotSuite(options: SnapshotSuiteOptions): void { const actualSnapshots = normalizeSessionSnapshots(harvested, ctx, { nativeWriterOutput: true }) const expectedSnapshots = normalizeSessionSnapshots(fixtures, fixtureCtx, { nativeWriterOutput: true }) for (const [index, actual] of actualSnapshots.entries()) { - expect(actual, `${fixtureFiles[index]} mismatch`).toEqual(expectedSnapshots[index]) + expect(parseJsonlRecords(actual), `${fixtureFiles[index]} mismatch`) + .toEqual(parseJsonlRecords(expectedSnapshots[index] as string)) } } diff --git a/packages/test-support/session-snapshot/tests/fixtures/fake-acp-agent.ts b/packages/test-support/session-snapshot/tests/fixtures/fake-acp-agent.ts index 2c541f63ca..46cb73b8db 100644 --- a/packages/test-support/session-snapshot/tests/fixtures/fake-acp-agent.ts +++ b/packages/test-support/session-snapshot/tests/fixtures/fake-acp-agent.ts @@ -135,7 +135,9 @@ function instantiate(value: unknown): unknown { /** Persist an open turn so cancellation tests wait on agent state, not presentation output. */ async function persistParkedTurnStart(): Promise { persistence = new Context() - await persistence.plugin(persistencePlugin, { root: sessionsRoot, compression: 'none' }) + await persistence.plugin(persistencePlugin, { + root: sessionsRoot, compression: 'none', storage: process.env.DSH_SNAPSHOT_STORAGE as 'jsonl' | 'sqlite', + }) parkedHandle = await persistence.sessionPersistence.create({ version: SESSION_FORMAT_VERSION, id: SessionId(sessionId), createdAt: 1, cwd: sessionCwd, delegationDepth: 0, isSeeded: false, @@ -238,6 +240,14 @@ async function handleFrame(frame: Record): Promise { } } +function reverseRecordKeys(value: unknown): unknown { + if (Array.isArray(value)) return value.map(reverseRecordKeys) + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).reverse().map(([key, child]) => [key, key === 'tools' ? child : reverseRecordKeys(child)])) + } + return value +} + async function writeLogs(): Promise { if (logsWritten) return logsWritten = true @@ -270,7 +280,7 @@ async function writeLogs(): Promise { mkdirSync(dirname(target), { recursive: true }) const records = log.lines.map(line => instantiate(line)) if (header !== undefined) records[0] = { delegationDepth: 0, ...header } - writeFileSync(target, records.map(line => JSON.stringify(line)).join('\n') + '\n') + writeFileSync(target, records.map(line => JSON.stringify(process.env.DSH_SNAPSHOT_REVERSE_RECORD_KEYS === '1' ? reverseRecordKeys(line) : line)).join('\n') + '\n') } } diff --git a/packages/test-support/session-snapshot/tests/harness.spec.ts b/packages/test-support/session-snapshot/tests/harness.spec.ts index c83d740d3e..f77bb0c318 100644 --- a/packages/test-support/session-snapshot/tests/harness.spec.ts +++ b/packages/test-support/session-snapshot/tests/harness.spec.ts @@ -7,7 +7,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import { afterAll, describe, expect, it, vi, type TestContext } from 'vitest' import { PROTOCOL_VERSION } from '@agentclientprotocol/sdk' import { createUserMessage } from '@deepseek-ai/dsh-llm' -import { runScenario, snapshotSpillRoot, type AgentUnderTest, type InputStep } from '../src/harness.ts' +import { runScenario as runStoredScenario, snapshotSpillRoot, type AgentUnderTest, type InputStep } from '../src/harness.ts' import { launchAcpTestAgent } from '../src/launcher.ts' const fsControl = vi.hoisted(() => ({ @@ -112,7 +112,10 @@ function environmentEcho(rawStdout: string): Record { return JSON.parse(text.slice('env:'.length)) as Record } -describe('runScenario', () => { +describe.each(['jsonl', 'sqlite'] as const)('runScenario (%s)', (storage) => { + const runScenario: typeof runStoredScenario = (input, options) => runStoredScenario(input, { + ...options, env: { ...options.env, DSH_SNAPSHOT_STORAGE: storage }, + }) it('surfaces an asynchronous child spawn failure through startup and close', async () => { const { dir } = await scenario({}) const launched = launchAcpTestAgent({ agent: AGENT, cwd: join(dir, 'missing') }) @@ -223,7 +226,7 @@ describe('runScenario', () => { agent: profileAgent, cwd: dir, configPath: selectedPatch, - env: { DSH_SNAPSHOT: 'record', DSH_SNAPSHOT_FILE: fixtureFile }, + env: { DSH_SNAPSHOT: 'record', DSH_SNAPSHOT_FILE: fixtureFile, DSH_SNAPSHOT_STORAGE: storage }, }) await live.spawned await live.close() @@ -232,6 +235,8 @@ describe('runScenario', () => { expect(materialized).toContain(pathToFileURL(join(patchDir, 'plugin.mjs')).href) expect(materialized).toContain(pathToFileURL(join(dir, 'nested.mjs')).href) expect(materialized).toContain('example-package') + expect(await readFile(await materializedPatch(materializedRoot, 'session-storage.yml'), 'utf8')) + .toContain(`storage: ${storage}`) expect(await realpath(join(dir, '.dsh', 'profiles', 'acp', 'node_modules', 'example-package'))) .toBe(await realpath(packageDir)) expect(await realpath(join(dir, '.dsh', 'profiles', 'acp', 'node_modules', '@fixture', 'example-package'))) diff --git a/packages/test-support/session-snapshot/tests/suite.spec.ts b/packages/test-support/session-snapshot/tests/suite.spec.ts index 168a118036..e4dbeae6c9 100644 --- a/packages/test-support/session-snapshot/tests/suite.spec.ts +++ b/packages/test-support/session-snapshot/tests/suite.spec.ts @@ -7,6 +7,8 @@ import { SESSION_FORMAT_VERSION } from '@deepseek-ai/dsh-session' import { afterAll, describe, expect, it } from 'vitest' import { assertPersistedSessionVersion, + normalizeSessionSnapshots, + normalizeSessionFormatMetadata, assertSessionFixtureVersion, defineAcpSnapshotSuite, latestPersistedSessionPaths, @@ -171,8 +173,51 @@ function staleRefreshFixtures(dir: string): void { ].join('\n')) } -describe('defineAcpSnapshotSuite: replay mode', () => { - defineAcpSnapshotSuite({ agent: AGENT, snapshotsDir: REPLAY_DIR, scenarios: REPLAY_SCENARIOS, mode: 'replay' }) +describe.each(['jsonl', 'sqlite'] as const)('defineAcpSnapshotSuite: replay mode (%s)', (storage) => { + defineAcpSnapshotSuite({ + agent: AGENT, snapshotsDir: REPLAY_DIR, + scenarios: REPLAY_SCENARIOS.map(scenario => ({ + ...scenario, env: { ...scenario.env, DSH_SNAPSHOT_STORAGE: storage, DSH_SNAPSHOT_REVERSE_RECORD_KEYS: '1' }, + })), mode: 'replay', + }) +}) + +describe('logical Session snapshot records', () => { + const original = readFileSync(join(REPLAY_DIR, 'pin-turn', 'session.v4.jsonl'), 'utf8') + const records = (): Record[] => original.trimEnd().split('\n') + .map(line => JSON.parse(line) as Record) + const encode = (values: readonly unknown[]): string => values.map(value => JSON.stringify(value)).join('\n') + '\n' + const logical = (text: string): unknown[] => normalizeSessionSnapshots([normalizeSessionFormatMetadata(text)], fixtureContext(text))[0]! + .trimEnd().split('\n').map((line): unknown => JSON.parse(line)) + + it('ignores object key order at every depth', () => { + const reorder = (value: unknown): unknown => { + if (Array.isArray(value)) return value.map(reorder) + if (value !== null && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).reverse().map(([key, child]) => [key, reorder(child)])) + } + return value + } + const actual = encode(records().map(reorder)) + expect(actual).not.toBe(original) + expect(logical(actual)).toEqual(logical(original)) + }) + + it.each(['missing event', 'extra event', 'event order', 'field value', 'array order'] as const)( + 'preserves a change to %s', (change) => { + const expected = records() + const actual = records() + if (change === 'missing event') actual.splice(1, 1) + if (change === 'extra event') actual.splice(1, 0, actual[1]!) + if (change === 'event order') [actual[1], actual[2]] = [actual[2]!, actual[1]!] + if (change === 'field value') actual[1]!.data = { turn: 2 } + if (change === 'array order') { + expected[7]!.sourceEventSeqs = [0, 2] + actual[7]!.sourceEventSeqs = [2, 0] + } + expect(logical(encode(actual))).not.toEqual(logical(encode(expected))) + }, + ) }) // The record suite's tests run in registration order: rec-pin re-records the diff --git a/python/sdk/tests/test_smoke_model.py b/python/sdk/tests/test_smoke_model.py index ded9c6517d..c422bc04e6 100644 --- a/python/sdk/tests/test_smoke_model.py +++ b/python/sdk/tests/test_smoke_model.py @@ -99,7 +99,7 @@ def live_smoke(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: monkeypatch.setenv("DEEPSEEK_BASE_URL", "https://api.invalid") monkeypatch.setattr(deepseek_harness, "DeepSeekHarness", ScriptedHarness) monkeypatch.setattr(globals_["secrets"], "token_hex", fresh_challenge) - monkeypatch.setitem(globals_, "assert_sqlite_session_log", state.checked_logs.append) + monkeypatch.setitem(globals_, "assert_session_log", lambda sessions, *_args, **_kwargs: state.checked_logs.append(sessions)) return state @@ -707,6 +707,53 @@ def test_snapshot_generation_comparison_rejects_changed_payload(tmp_path: Path) ) +def test_snapshot_comparison_ignores_object_keys_and_retains_array_order(tmp_path: Path) -> None: + filename = f"session.v{SESSION_FORMAT_VERSION}.jsonl" + header = {"type": "session", "version": SESSION_FORMAT_VERSION, "id": "ordered"} + event = {"type": "plugin:fixture/ordered", "ignorable": True, "data": {"text": "saved", "items": [1, 2], "active": True}} + second = {"type": "plugin:fixture/end", "ignorable": True, "data": {"done": True}} + golden = "".join(json.dumps(record) + "\n" for record in [header, event, second]) + (tmp_path / filename).write_text(golden, encoding="utf-8") + reordered = [ + {"id": "ordered", "version": SESSION_FORMAT_VERSION, "type": "session"}, + {"data": {"active": True, "items": [1, 2], "text": "saved"}, "ignorable": True, "type": "plugin:fixture/ordered"}, + second, + ] + compare = SMOKE["compare_snapshot_files"] + + def check(records: list[dict[str, object]]) -> None: + compare({filename: "".join(json.dumps(record) + "\n" for record in records)}, False, tmp_path, (filename,)) + + check(reordered) + for changed in [ + [reordered[0], reordered[2], reordered[1]], + reordered[:2], + [reordered[0], {**event, "data": {**event["data"], "items": [2, 1]}}, second], + [reordered[0], {**event, "data": {"items": [1, 2], "active": True}}, second], + [reordered[0], {**event, "data": {**event["data"], "active": 1}}, second], + ]: + with pytest.raises(AssertionError, match="executable snapshot mismatch"): + check(changed) + assert (tmp_path / filename).read_text(encoding="utf-8") == golden + + +def test_json_snapshot_comparison_preserves_values_and_types(tmp_path: Path) -> None: + filename = "result.json" + value = {"active": False, "items": [{"number": 1, "text": "saved"}, 2]} + golden = json.dumps(value) + "\n" + (tmp_path / filename).write_text(golden, encoding="utf-8") + compare = SMOKE["compare_snapshot_files"] + compare({filename: json.dumps({"items": [{"text": "saved", "number": 1.0}, 2], "active": False})}, False, tmp_path, (filename,)) + for changed in [ + {**value, "active": 0}, + {**value, "items": [2, {"number": 1, "text": "saved"}]}, + {**value, "items": [{"number": 1, "text": "changed"}, 2]}, + ]: + with pytest.raises(AssertionError, match="executable snapshot mismatch"): + compare({filename: json.dumps(changed)}, False, tmp_path, (filename,)) + assert (tmp_path / filename).read_text(encoding="utf-8") == golden + + @pytest.mark.parametrize("version", [SESSION_FORMAT_VERSION - 1, SESSION_FORMAT_VERSION + 1]) @pytest.mark.parametrize("update", [False, True]) def test_snapshot_comparison_rejects_noncurrent_writer( diff --git a/scripts/fixtures/python-sdk-session-reader.mjs b/scripts/fixtures/python-sdk-session-reader.mjs new file mode 100644 index 0000000000..7e4d167a98 --- /dev/null +++ b/scripts/fixtures/python-sdk-session-reader.mjs @@ -0,0 +1,26 @@ +/** Read persisted histories through the installed profile's persistence service. */ +import { writeFile } from 'node:fs/promises' + +/** Private profile reader label. */ +export const name = 'python-sdk-session-reader' +/** Persistence must be mounted before this fixture reads histories. */ +export const inject = ['sessionPersistence'] + +/** + * Write complete logical histories after the SDK profile mounts persistence. + * @param {import('@deepseek-ai/cordis').Context} ctx - Installed SDK profile services. + * @param {{ output: string }} config - Private JSON output file. + */ +export async function apply(ctx, config) { + const sessions = {} + for (const snapshot of await ctx.sessionPersistence.list()) { + const handle = await ctx.sessionPersistence.open(snapshot.header.id, 'read') + try { + const { events } = await handle.read() + sessions[handle.header.id] = [{ type: 'session', ...handle.header }, ...events] + } finally { + await handle.close() + } + } + await writeFile(config.output, JSON.stringify(sessions), { mode: 0o600 }) +} diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index a0019438ee..547e02285a 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -993,8 +993,10 @@ describe('Node 24 lane ownership', () => { 'node-compat', 'publint', 'snapshot', + 'snapshot-sqlite', 'expected-output', 'web-snapshot', + 'web-snapshot-sqlite', 'doc-typecheck', 'node-next-types', 'built-bin-smoke', @@ -1011,15 +1013,20 @@ describe('Node 24 lane ownership', () => { }) for (const id of [ 'snapshot', + 'snapshot-sqlite', 'expected-output', 'web-snapshot', + 'web-snapshot-sqlite', 'doc-typecheck', 'node-next-types', 'built-bin-smoke', ]) { expect(subject.find(item => item.id === id)?.needs).toEqual(['build']) } - expect(subject.find(item => item.id === 'snapshot')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' }) + expect(subject.find(item => item.id === 'snapshot')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib', DSH_SNAPSHOT_STORAGE: 'jsonl' }) + expect(subject.find(item => item.id === 'snapshot-sqlite')).toMatchObject({ + env: { DSH_EXAMPLE_MODE: 'lib', DSH_SNAPSHOT_STORAGE: 'sqlite' }, after: ['snapshot'], + }) expect(subject.find(item => item.id === 'expected-output')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' }) expect(subject.find(item => item.id === 'built-bin-smoke')?.env).toEqual({ DSH_EXAMPLE_MODE: 'lib' }) expect(subject.find(item => item.id === 'doc-typecheck')?.env).toEqual({ @@ -1038,11 +1045,12 @@ describe('Node 24 lane ownership', () => { ]), ) expect(subject.find(item => item.id === 'web-snapshot')).toMatchObject({ - displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built', - env: { DSH_SNAPSHOT: 'replay' }, + displayCommand: 'DSH_SNAPSHOT_STORAGE=jsonl DSH_SNAPSHOT=replay pnpm run test:web:built', + env: { DSH_SNAPSHOT: 'replay', DSH_SNAPSHOT_STORAGE: 'jsonl' }, after: [ 'publint', 'snapshot', + 'snapshot-sqlite', 'expected-output', 'doc-typecheck', 'node-next-types', @@ -1058,8 +1066,8 @@ describe('Linux primary graph', () => { const web = subject.find(item => item.id === 'web-snapshot') expect(web).toMatchObject({ - displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built', - env: { DSH_SNAPSHOT: 'replay' }, + displayCommand: 'DSH_SNAPSHOT_STORAGE=jsonl DSH_SNAPSHOT=replay pnpm run test:web:built', + env: { DSH_SNAPSHOT: 'replay', DSH_SNAPSHOT_STORAGE: 'jsonl' }, needs: ['build'], }) }) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index d4fb6bad04..6c4a769977 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -314,7 +314,7 @@ export function gatesForMode(selected: Mode): Gate[] { case 'ci-primary': return ciPrimaryGates() case 'ci-linux-primary': - return [...ciPrimaryGates(), webSnapshotGate(['build'])] + return [...ciPrimaryGates(), ...sessionBackendGates(webSnapshotGate(['build']))] case 'ci-static': return ciStaticGates({ ownsBuild: false }) case 'ci-lint-contracts-ready': @@ -329,7 +329,7 @@ export function gatesForMode(selected: Mode): Gate[] { case 'ci-bench': return [pnpmExec('bench', ['tsx', 'scripts/run-ci-bench.ts'], { label: 'performance benchmarks' })] case 'ci-snapshot': - return [ciBuildGate(), snapshotGate()] + return [ciBuildGate(), ...sessionBackendGates(snapshotGate())] case 'ci-artifacts': return ciArtifactGates() case 'ci-consumers': @@ -359,7 +359,7 @@ export function gatesForMode(selected: Mode): Gate[] { pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }), pnpmScript('stale-pull-requests', 'test:stale-pull-requests', { label: 'Stale pull-request reminders' }), pnpmScript('duplication', 'duplication'), - snapshotGate(), + ...sessionBackendGates(snapshotGate()), expectedOutputGate(), pnpmScript('build', 'build'), pnpmScript('build:web', 'build:web'), @@ -442,7 +442,7 @@ function ciPrimaryGates(): Gate[] { pnpmScript('duplication', 'duplication'), ...coverageGates(), ...nodeCompatSmokeGates(), - snapshotGate(), + ...sessionBackendGates(snapshotGate()), ...docSyncLeafGates({ docTypecheckNeeds: ['typert-contracts'], docTypecheckScript: 'doc-typecheck:contracts-ready', @@ -551,6 +551,7 @@ function ciConsumerGates(): Gate[] { const buildArtifactReaders = [ 'publint', 'snapshot', + 'snapshot-sqlite', 'expected-output', 'doc-typecheck', 'node-next-types', @@ -563,9 +564,9 @@ function ciConsumerGates(): Gate[] { env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' }, }), pnpmScript('publint', 'publint', { needs: builtTree }), - snapshotGate(builtTree), + ...sessionBackendGates(snapshotGate(builtTree)), expectedOutputGate(builtTree), - webSnapshotGate(builtTree, buildArtifactReaders), + ...sessionBackendGates(webSnapshotGate(builtTree, buildArtifactReaders)), pnpmScript('doc-typecheck', 'doc-typecheck:contracts-ready', { needs: builtTree, env: { DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT: '1' }, @@ -578,6 +579,18 @@ function ciConsumerGates(): Gate[] { ] } +/** Run each persistence adapter against the same expected outputs, serially per lane. */ +function sessionBackendGates(gate: Gate): Gate[] { + return (['jsonl', 'sqlite'] as const).map(storage => ({ + ...gate, + id: storage === 'jsonl' ? gate.id : `${gate.id}-sqlite`, + label: `${gate.label} (${storage})`, + env: { ...gate.env, DSH_SNAPSHOT_STORAGE: storage }, + displayCommand: `DSH_SNAPSHOT_STORAGE=${storage} ${gate.displayCommand}`, + ...storage === 'sqlite' ? { after: [...gate.after ?? [], gate.id] } : {}, + })) +} + function webSnapshotGate(needs: string[], after?: string[]): Gate { const order = after === undefined ? { needs } : { needs, after } const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 22e3d5accf..f68d5fddcf 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -15,7 +15,6 @@ import runpy import secrets import shutil import subprocess -import sqlite3 import sys import sysconfig import tempfile @@ -31,6 +30,9 @@ if TYPE_CHECKING: from deepseek_harness import Notification, RunResult +StorageBackend = Literal["jsonl", "sqlite"] + + EXPECTED_TEXT = "runtime smoke ok" LIVE_API_SENTINEL = "PYTHON_SDK_LIVE_OK" CODE_PROMPT = "Use run_code to compute the packaged worker smoke value." @@ -245,13 +247,15 @@ def write_profile_patch( name: str, sessions: Path, patches: list[dict[str, object]], + *, + storage: StorageBackend = "jsonl", ) -> Path: """Write one JSON-form dsh profile patch with deterministic persistence.""" path = root / name path.write_text(json.dumps([ { "id": "session-persistence-jsonl", - "config": {"root": str(sessions), "storage": "jsonl", "compression": "none"}, + "config": {"root": str(sessions), "storage": storage, "compression": "none"}, }, {"id": "session-telemetry-otel", "disabled": True}, *patches, @@ -261,6 +265,7 @@ def write_profile_patch( def write_advanced_profile_patch( root: Path, name: str, sessions: Path, mode: Literal["native", "ptc"] = "native", + *, storage: StorageBackend = "jsonl", ) -> Path: """Write the shared custom, snapshot, and restart profile patch.""" return write_profile_patch(root, name, sessions, [ @@ -288,10 +293,10 @@ def write_advanced_profile_patch( {"id": "cordis-host-runner", "name": "@deepseek-ai/dsh-cordis-host-runner"}, {"id": "cordis-tool", "name": "@deepseek-ai/dsh-tool-cordis"}, ]}, - ]) + ], storage=storage) -def write_mcp_patch(root: Path, sessions: Path, server_script: Path) -> Path: +def write_mcp_patch(root: Path, sessions: Path, server_script: Path, *, storage: StorageBackend = "jsonl") -> Path: """Write a profile patch that mounts the packaged MCP client.""" return write_profile_patch(root, "mcp.patch.yml", sessions, [{ "insert": [{ @@ -307,7 +312,7 @@ def write_mcp_patch(root: Path, sessions: Path, server_script: Path) -> Path: "reconnect": {"enabled": False}, }, }], - }]) + }], storage=storage) class MockModelHandler(BaseHTTPRequestHandler): @@ -859,6 +864,7 @@ def main() -> None: default="all", ) parser.add_argument("--exe", type=Path) + parser.add_argument("--storage", choices=("jsonl", "sqlite"), nargs="+", default=("jsonl",)) parser.add_argument( "--installed-wheel", action="store_true", @@ -896,70 +902,76 @@ def main() -> None: return if args.scenario == "sdk-live": - smoke_sdk_live() - print("smoke-python-runtime: sdk-live passed") + for storage in args.storage: + smoke_sdk_live(storage=storage) + print(f"smoke-python-runtime: sdk-live ({storage}) passed") return - with MockModel() as model: - if args.scenario == "sdk-plugin-manager": - assert args.exe is not None - with tempfile.TemporaryDirectory(prefix="dsh-sdk-plugin-cache-") as cache: - subprocess.run([str(args.exe.resolve())], check=True, capture_output=True, text=True, - env={**os.environ, "DSH_RESOURCE_CACHE": cache, "DSH_RUNTIME_DOWNLOAD": "primary"}) - smoke_sdk_plugin_manager(model.url, args.exe.resolve(), Path(cache)) - if args.scenario in {"all", "sdk-authoring"}: - assert args.exe is not None - smoke_sdk_authoring(model.url, args.exe.resolve(), args.update_snapshots) - if args.scenario in {"all", "sdk-default"}: - smoke_sdk_default(model.url) - if args.scenario in {"all", "sdk-custom"}: - assert args.exe is not None - smoke_sdk_custom(model.url, args.exe.resolve()) - if args.scenario in {"all", "sdk-minimal"}: - assert args.exe is not None - smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots) - if args.scenario in {"all", "sdk-minimal-in-history"}: - assert args.exe is not None - smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots, in_history=True) - if args.scenario in {"all", "sdk-dynamic-tools"}: - assert args.exe is not None - smoke_sdk_dynamic_tools(model.url, args.exe.resolve(), args.update_snapshots) - if args.scenario in {"all", "sdk-fs-search"}: - assert args.exe is not None - smoke_sdk_fs_search(model.url, args.exe.resolve()) - if args.scenario in {"all", "sdk-spawn-node"}: - assert args.exe is not None - smoke_sdk_spawn_node(model.url, args.exe.resolve()) - if args.scenario in {"all", "sdk-mcp"}: - smoke_sdk_mcp(model.url, None if args.exe is None else args.exe.resolve()) - if args.scenario in {"all", "sdk-snapshot"}: - assert args.exe is not None - smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots) - if args.scenario in {"all", "sdk-snapshot", "sdk-recovery"}: - assert args.exe is not None - smoke_sdk_scheduler_recovery(model.url, args.exe.resolve(), args.update_snapshots) - if args.scenario in {"all", "sdk-restart"}: - assert args.exe is not None - smoke_sdk_v3_resume(model.url, args.exe.resolve()) - smoke_sdk_restart_snapshot(model.url, args.exe.resolve(), args.update_snapshots) - if args.installed_wheel and args.scenario in {"all", "sdk-profile-plugin"}: - smoke_sdk_profile_plugin(model.url) - if args.scenario in {"all", "direct"}: - assert args.exe is not None - smoke_direct(model.url, args.exe.resolve()) - if not MockModelHandler.requests: - raise AssertionError("mock model endpoint received no requests") - print(f"smoke-python-runtime: {args.scenario} passed") + for storage in args.storage: + with MockModel() as model: + if args.scenario == "sdk-plugin-manager": + assert args.exe is not None + with tempfile.TemporaryDirectory(prefix="dsh-sdk-plugin-cache-") as cache: + subprocess.run([str(args.exe.resolve())], check=True, capture_output=True, text=True, + env={**os.environ, "DSH_RESOURCE_CACHE": cache, "DSH_RUNTIME_DOWNLOAD": "primary"}) + smoke_sdk_plugin_manager(model.url, args.exe.resolve(), Path(cache), storage=storage) + if args.scenario in {"all", "sdk-authoring"}: + assert args.exe is not None + smoke_sdk_authoring(model.url, args.exe.resolve(), args.update_snapshots, storage=storage) + if args.scenario in {"all", "sdk-default"}: + smoke_sdk_default(model.url, storage=storage) + if args.scenario in {"all", "sdk-custom"}: + assert args.exe is not None + smoke_sdk_custom(model.url, args.exe.resolve(), storage=storage) + if args.scenario in {"all", "sdk-minimal"}: + assert args.exe is not None + smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots, storage=storage) + if args.scenario in {"all", "sdk-minimal-in-history"}: + assert args.exe is not None + smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots, in_history=True, storage=storage) + if args.scenario in {"all", "sdk-dynamic-tools"}: + assert args.exe is not None + smoke_sdk_dynamic_tools(model.url, args.exe.resolve(), args.update_snapshots, storage=storage) + if args.scenario in {"all", "sdk-fs-search"}: + assert args.exe is not None + smoke_sdk_fs_search(model.url, args.exe.resolve(), storage=storage) + if args.scenario in {"all", "sdk-spawn-node"}: + assert args.exe is not None + smoke_sdk_spawn_node(model.url, args.exe.resolve(), storage=storage) + if args.scenario in {"all", "sdk-mcp"}: + smoke_sdk_mcp(model.url, None if args.exe is None else args.exe.resolve(), storage=storage) + if args.scenario in {"all", "sdk-snapshot"}: + assert args.exe is not None + smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots, storage=storage) + if args.scenario in {"all", "sdk-snapshot", "sdk-recovery"}: + assert args.exe is not None + smoke_sdk_scheduler_recovery(model.url, args.exe.resolve(), args.update_snapshots, storage=storage) + if args.scenario in {"all", "sdk-restart"}: + assert args.exe is not None + smoke_sdk_v3_resume(model.url, args.exe.resolve(), storage=storage) + smoke_sdk_restart_snapshot(model.url, args.exe.resolve(), args.update_snapshots, storage=storage) + if args.installed_wheel and args.scenario in {"all", "sdk-profile-plugin"}: + smoke_sdk_profile_plugin(model.url, storage=storage) + if args.scenario in {"all", "direct"}: + assert args.exe is not None + smoke_direct(model.url, args.exe.resolve(), storage=storage) + if not MockModelHandler.requests: + raise AssertionError("mock model endpoint received no requests") + print(f"smoke-python-runtime: {args.scenario} ({storage}) passed") -def smoke_sdk_authoring(base_url: str, executable: Path, update_snapshots: bool) -> None: +def smoke_sdk_authoring( + base_url: str, executable: Path, update_snapshots: bool, *, storage: StorageBackend = "jsonl", +) -> None: """Query the bundled Python and switch skills without replacing that environment.""" with tempfile.TemporaryDirectory(prefix="dsh-sdk-authoring-cache-") as cache_directory: - _smoke_sdk_authoring_cached(base_url, executable, update_snapshots, Path(cache_directory)) + _smoke_sdk_authoring_cached(base_url, executable, update_snapshots, Path(cache_directory), storage=storage) -def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshots: bool, cache: Path) -> None: +def _smoke_sdk_authoring_cached( + base_url: str, executable: Path, update_snapshots: bool, cache: Path, *, storage: StorageBackend = "jsonl", +) -> None: from deepseek_harness import DeepSeekHarness cache_environment = {**os.environ, "DSH_RESOURCE_CACHE": str(cache), "DSH_RUNTIME_DOWNLOAD": "primary"} @@ -974,7 +986,6 @@ def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshot skill = home / "skills/office-docx/SKILL.md" skill.parent.mkdir(parents=True) skill.write_text("---\nname: office-docx\ndescription: CUSTOM_OFFICE_DOCX\n---\nUse the bundled Python for custom document work.\n") - patch = root / "skills.patch.yml" # Fix the model-visible clock in this child only; native timers stay live. patch_rows = [ {"insert": [{"id": "authoring-clock", "name": ( @@ -984,7 +995,7 @@ def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshot ] if mode == "disabled": patch_rows.append({"id": "skill-office", "disabled": True}) - patch.write_text(json.dumps(patch_rows)) + patch = write_profile_patch(root, "skills.patch.yml", home / "sessions", patch_rows, storage=storage) first = len(MockModelHandler.requests) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), @@ -995,6 +1006,7 @@ def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshot ) as harness: result = harness.run(AUTHORING_PROMPT, session_id="authoring") assert result.final_response == EXPECTED_TEXT, result.final_response + assert_session_log(home / "sessions", root, EXPECTED_TEXT, storage=storage, executable=executable) requests = MockModelHandler.requests[first:] assert len(requests) == 2, requests prompt = json.dumps(requests[0], ensure_ascii=False) @@ -1032,11 +1044,13 @@ def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshot update_snapshots, AUTHORING_SNAPSHOT_DIRECTORY, ("model-visible.json",), ) - smoke_sdk_plugin_manager(base_url, executable, cache) + smoke_sdk_plugin_manager(base_url, executable, cache, storage=storage) print("smoke-python-runtime: bundled Python, default skills, replacement and disabled skills passed") -def smoke_sdk_plugin_manager(base_url: str, executable: Path, cache: Path) -> None: +def smoke_sdk_plugin_manager( + base_url: str, executable: Path, cache: Path, *, storage: StorageBackend = "jsonl", +) -> None: """Approve a real local installation with bundled pnpm, then load it after restart.""" from deepseek_harness import ApprovalRequestParams, DeepSeekHarness @@ -1059,10 +1073,11 @@ def smoke_sdk_plugin_manager(base_url: str, executable: Path, cache: Path) -> No "insert": [{"id": "sdk-managed-fixture", "name": "dsh-sdk-managed-fixture"}], }])) home = root / "home" + patch = write_profile_patch(root, "storage.patch.yml", home / "sessions", [], storage=storage) environment = {"PATH": "", "DSH_RESOURCE_CACHE": str(cache), "DSH_PERMISSION_MODE": "workspace-write", "DSH_TELEMETRY_DISABLED": "1"} config = dict(provider="deepseek-official", model="smoke-model", cwd=str(root), - dsh_bin=str(executable), dsh_home=str(home), env=environment, + dsh_bin=str(executable), dsh_home=str(home), env=environment, patches=(str(patch),), api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60) with ThreadPoolExecutor(max_workers=2) as worker: harness = DeepSeekHarness(**config, approval_requests=True) @@ -1092,8 +1107,12 @@ def smoke_sdk_plugin_manager(base_url: str, executable: Path, cache: Path) -> No with DeepSeekHarness(**config) as restarted: result = restarted.run(PROFILE_PLUGIN_PROMPT, session_id="installed-after-restart") assert result.final_response == PROFILE_PLUGIN_TEXT, result.final_response + logs = read_session_logs(home / "sessions", storage=storage, executable=executable) + assert set(logs) == {"rejected", "allowed-once", "installed-after-restart"}, logs.keys() example = Path(__file__).resolve().parent.parent / "python/sdk/examples/manage_plugins.py" example_home = root / "example-home" + example_home.mkdir() + write_profile_patch(example_home, "cordis.patch.yml", example_home / "sessions", [], storage=storage) example_environment = {**os.environ, **environment, "DEEPSEEK_BASE_URL": base_url, "DEEPSEEK_API_KEY": "sk-keyless-smoke"} example_args = [sys.executable, str(example), "--dsh-home", str(example_home), @@ -1264,7 +1283,7 @@ def assert_installed_wheel_environment() -> Path: return executable -def smoke_sdk_live() -> None: +def smoke_sdk_live(*, storage: StorageBackend = "jsonl") -> None: """Run a real-model, tool-using two-turn task through installed wheels.""" from deepseek_harness import DeepSeekHarness @@ -1282,6 +1301,7 @@ def smoke_sdk_live() -> None: marker = root / "live-api-marker.txt" session_id = "installed-wheel-live-api" shell_tool = "pwsh" if IS_WINDOWS else "bash" + patch = write_profile_patch(root, "storage.patch.yml", sessions, [], storage=storage) create_prompt = ( f"Use the {shell_tool} tool to create the file at the absolute path below with exact UTF-8 " f"content {LIVE_API_SENTINEL}, with no newline or byte-order mark. " @@ -1292,6 +1312,7 @@ def smoke_sdk_live() -> None: model="deepseek-v4-flash", cwd=str(root), dsh_home=str(dsh_home), + patches=(str(patch),), env={ "DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", @@ -1329,7 +1350,7 @@ def smoke_sdk_live() -> None: raise AssertionError(f"verify turn wrote unexpected bytes to receipt {receipt}") if not marker.is_file() or marker.read_bytes() != challenge: raise AssertionError(f"verify turn changed source file {marker}") - assert_sqlite_session_log(sessions) + assert_session_log(sessions, root, storage=storage) def assert_live_turn(label: str, result: RunResult) -> None: @@ -1377,18 +1398,20 @@ def safe_turn_end(value: object) -> object: } -def smoke_sdk_default(base_url: str) -> None: +def smoke_sdk_default(base_url: str, *, storage: StorageBackend = "jsonl") -> None: from deepseek_harness import DeepSeekHarness with tempfile.TemporaryDirectory(prefix="dsh-sdk-default-") as temporary: root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" + patch = write_profile_patch(root, "storage.patch.yml", sessions, [], storage=storage) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), dsh_home=str(dsh_home), + patches=(str(patch),), env={ "DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", @@ -1403,11 +1426,12 @@ def smoke_sdk_default(base_url: str) -> None: f"events={[event.get('type') for event in result.events]!r} " f"turn_end={safe_turn_end(next((event.get('data', event) for event in reversed(result.events) if event.get('type') == 'turn/end'), {}))!r}" ) - assert_sqlite_session_log(sessions) + assert_session_log(sessions, root, storage=storage) # The installed runtime starts with an empty PATH; no checkout or global pnpm can satisfy the tool. before = (dsh_home / "profiles/sdk/package.json").read_bytes() with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), dsh_home=str(dsh_home), + patches=(str(patch),), env={"DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", "PATH": "", "DSH_PRIMARY_RUNTIME": "", "DSH_RESOURCE_CACHE": str(root / "empty-resource-cache")}, api_key="sk-keyless-smoke", base_url=base_url, request_timeout_seconds=60, @@ -1417,7 +1441,7 @@ def smoke_sdk_default(base_url: str) -> None: assert (dsh_home / "profiles/sdk/package.json").read_bytes() == before -def smoke_sdk_custom(base_url: str, executable: Path) -> None: +def smoke_sdk_custom(base_url: str, executable: Path, *, storage: StorageBackend = "jsonl") -> None: from deepseek_harness import DeepSeekHarness cases: tuple[tuple[Literal["native", "ptc"], tuple[tuple[str, str], ...]], ...] = ( @@ -1429,7 +1453,7 @@ def smoke_sdk_custom(base_url: str, executable: Path) -> None: root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" - patch = write_advanced_profile_patch(root, "custom.patch.yml", sessions, mode) + patch = write_advanced_profile_patch(root, "custom.patch.yml", sessions, mode, storage=storage) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", @@ -1448,11 +1472,11 @@ def smoke_sdk_custom(base_url: str, executable: Path) -> None: for prompt, expected in turns: result = harness.run(prompt, session_id=f"custom-{mode}") assert result.final_response == expected, result.final_response - assert_session_log(sessions, root, *(expected for _, expected in turns)) + assert_session_log(sessions, root, *(expected for _, expected in turns), storage=storage, executable=executable) def smoke_sdk_minimal( - base_url: str, executable: Path, update_snapshots: bool, *, in_history: bool = False, + base_url: str, executable: Path, update_snapshots: bool, *, in_history: bool = False, storage: StorageBackend = "jsonl", ) -> None: """Exercise the shipped standalone minimal profile through the packaged executable.""" from deepseek_harness import DeepSeekHarness @@ -1466,7 +1490,7 @@ def smoke_sdk_minimal( storage_patch = root / "persistence.patch.yml" storage_patch.write_text(json.dumps([{ "id": "sessions", - "config": {"root": str(sessions), "storage": "jsonl", "compression": "none"}, + "config": {"root": str(sessions), "storage": storage, "compression": "none"}, }])) patches = (str(storage_patch),) if in_history: @@ -1498,11 +1522,11 @@ def smoke_sdk_minimal( event_text = json.dumps(result.events) if MINIMAL_TEXT not in event_text: raise AssertionError(f"minimal agent run emitted no final response: {result.events}") - assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2") + assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2", storage=storage, executable=executable) requests = MockModelHandler.requests[first_request:] if in_history: - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) files = build_in_history_snapshot_files(result, requests, logs[result.session_id]) compare_snapshot_files( files, update_snapshots, IN_HISTORY_SNAPSHOT_DIRECTORY, IN_HISTORY_SNAPSHOT_FILENAMES, @@ -1514,7 +1538,7 @@ def smoke_sdk_minimal( ) -def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: bool) -> None: +def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: bool, *, storage: StorageBackend = "jsonl") -> None: """Observe native tool changes through the shipped SDK profile and its durable log.""" from deepseek_harness import DeepSeekHarness @@ -1543,7 +1567,7 @@ def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: b "id": "dynamic-tools", "name": (Path(__file__).resolve().parent / "fixtures/python-sdk-dynamic-tools.mjs").as_uri(), }]}, - ]) + ], storage=storage) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", cwd=str(root), dsh_bin=str(executable), dsh_home=str(dsh_home), patches=(str(patch),), @@ -1559,7 +1583,7 @@ def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: b result = harness.run(DYNAMIC_TOOLS_PROMPT, session_id="dynamic-tools-smoke") assert result.final_response == DYNAMIC_TOOLS_TEXT, result.final_response assert task.read_text(encoding="utf-8") == "Call snapshot_ping once.\n" - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) assert set(logs) == {result.session_id}, sorted(logs) files = build_dynamic_tools_snapshot_files( result, MockModelHandler.requests[first_request:], logs[result.session_id], root, @@ -1569,7 +1593,7 @@ def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: b ) -def smoke_sdk_fs_search(base_url: str, executable: Path) -> None: +def smoke_sdk_fs_search(base_url: str, executable: Path, *, storage: StorageBackend = "jsonl") -> None: """Exercise real grep and glob spawns through the packaged executable.""" from deepseek_harness import DeepSeekHarness @@ -1581,7 +1605,7 @@ def smoke_sdk_fs_search(base_url: str, executable: Path) -> None: patch = write_profile_patch(root, "fs-search.patch.yml", sessions, [ {"id": "skill-filesystem", "disabled": True}, {"id": "tool-fs-search", "config": {"sampleOverCapGlobResults": False}}, - ]) + ], storage=storage) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", @@ -1600,10 +1624,10 @@ def smoke_sdk_fs_search(base_url: str, executable: Path) -> None: result = harness.run(FS_SEARCH_PROMPT, session_id="fs-search-smoke") assert result.final_response == FS_SEARCH_TEXT, result.final_response - assert_session_log(sessions, root, FS_SEARCH_TEXT, FS_SEARCH_MARKER, "needle.txt") + assert_session_log(sessions, root, FS_SEARCH_TEXT, FS_SEARCH_MARKER, "needle.txt", storage=storage, executable=executable) -def smoke_sdk_spawn_node(base_url: str, executable: Path) -> None: +def smoke_sdk_spawn_node(base_url: str, executable: Path, *, storage: StorageBackend = "jsonl") -> None: """A shell command starting with `node` must reach the machine's Node, not the executable.""" from deepseek_harness import DeepSeekHarness @@ -1611,7 +1635,7 @@ def smoke_sdk_spawn_node(base_url: str, executable: Path) -> None: root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" - patch = write_profile_patch(root, "spawn-node.patch.yml", sessions, []) + patch = write_profile_patch(root, "spawn-node.patch.yml", sessions, [], storage=storage) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", @@ -1630,10 +1654,10 @@ def smoke_sdk_spawn_node(base_url: str, executable: Path) -> None: result = harness.run(SPAWN_NODE_PROMPT, session_id="spawn-node-smoke") assert result.final_response == SPAWN_NODE_TEXT, result.final_response - assert_session_log(sessions, root, SPAWN_NODE_TEXT, "PKG_EXECPATH=ABSENT") + assert_session_log(sessions, root, SPAWN_NODE_TEXT, "PKG_EXECPATH=ABSENT", storage=storage, executable=executable) -def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None: +def smoke_sdk_mcp(base_url: str, executable: Path | None, *, storage: StorageBackend = "jsonl") -> None: """Discover and call an external stdio MCP tool through the packaged client.""" from deepseek_harness import DeepSeekHarness @@ -1643,7 +1667,7 @@ def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None: sessions = dsh_home / "sessions" server_script = root / "mcp_server.py" server_script.write_text(MCP_SERVER_SCRIPT) - patch = write_mcp_patch(root, sessions, server_script) + patch = write_mcp_patch(root, sessions, server_script, storage=storage) discovery_log = server_script.with_suffix(".log") with DeepSeekHarness( provider="deepseek-official", @@ -1670,16 +1694,17 @@ def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None: "tools/list", "tools/call", ] - assert_session_log(sessions, root, MCP_TEXT, "mcp__fixture__add", "42") + assert_session_log(sessions, root, MCP_TEXT, "mcp__fixture__add", "42", storage=storage, executable=executable) -def smoke_sdk_profile_plugin(base_url: str) -> None: +def smoke_sdk_profile_plugin(base_url: str, *, storage: StorageBackend = "jsonl") -> None: """Install an external bundle through Python's dsh command and load it in the SDK.""" from deepseek_harness import DeepSeekHarness with tempfile.TemporaryDirectory(prefix="dsh-sdk-profile-plugin-") as temporary: root = Path(temporary).resolve() dsh_home = root / "home" + patch = write_profile_patch(root, "storage.patch.yml", dsh_home / "sessions", [], storage=storage) plugin = root / "plugin" plugin.mkdir() (plugin / "package.json").write_text(json.dumps({ @@ -1735,6 +1760,7 @@ def smoke_sdk_profile_plugin(base_url: str) -> None: model="smoke-model", cwd=str(root), dsh_home=str(dsh_home), + patches=(str(patch),), env={ "DSH_PERMISSION_MODE": "danger-full-access", "DSH_TELEMETRY_DISABLED": "1", @@ -1752,17 +1778,18 @@ def smoke_sdk_profile_plugin(base_url: str) -> None: ) from error assert result.final_response == PROFILE_PLUGIN_TEXT, result.final_response - assert_sqlite_session_log(dsh_home / "sessions") + assert_session_log(dsh_home / "sessions", root, storage=storage) -def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None: +def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool, *, storage: StorageBackend = "jsonl") -> None: """Exercise native and PTC calls in independent packaged-runtime compositions.""" for mode in ("native", "ptc"): - smoke_sdk_snapshot_mode(base_url, executable, update_snapshots, mode) + smoke_sdk_snapshot_mode(base_url, executable, update_snapshots, mode, storage=storage) def smoke_sdk_snapshot_mode( base_url: str, executable: Path, update_snapshots: bool, mode: Literal["native", "ptc"], + *, storage: StorageBackend = "jsonl", ) -> None: """Drive one supported presentation through the SDK and persistent Session log.""" from deepseek_harness import DeepSeekHarness @@ -1771,7 +1798,7 @@ def smoke_sdk_snapshot_mode( root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" - patch = write_advanced_profile_patch(root, "snapshot.patch.yml", sessions, mode) + patch = write_advanced_profile_patch(root, "snapshot.patch.yml", sessions, mode, storage=storage) feedback_patch = write_profile_patch(root, "feedback.patch.yml", sessions, [{"insert": [ {"id": "snapshot-tool", "name": ( Path(__file__).resolve().parent / "fixtures/python-snapshot-tool.mjs" @@ -1790,13 +1817,13 @@ def smoke_sdk_snapshot_mode( {"id": "snapshot-feedback-producer", "name": ( Path(__file__).resolve().parent.parent / "snapshots/sdk/text-turn/feedback-producer.mjs" ).as_uri()}, - ]}]) + ]}], storage=storage) creation_patch = write_profile_patch(root, "creation.patch.yml", sessions, [ {"insert": [{ "id": "serial-created-fixture", "name": str(Path(__file__).resolve().parents[1] / "packages/core/agent-loop/tests/fixtures/serial-created.mjs"), }]}, - ]) + ], storage=storage) with DeepSeekHarness( provider="deepseek-official", model="smoke-model", @@ -1875,7 +1902,7 @@ def smoke_sdk_snapshot_mode( "name": "AutoReviewDeniedError", "code": "AUTO_REVIEW_DENIED", "reason": " transport raw\r\nreason ", }], errors - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) child_ids = snapshot_child_ids(result, expected_children) expected_ids = {SNAPSHOT_SESSION_ID, *child_ids} if set(logs) != expected_ids: @@ -1896,7 +1923,7 @@ def smoke_sdk_snapshot_mode( ) -def smoke_sdk_v3_resume(base_url: str, executable: Path) -> None: +def smoke_sdk_v3_resume(base_url: str, executable: Path, *, storage: StorageBackend = "jsonl") -> None: """Migrate persisted V3 history and reopen the published log in a fresh runtime.""" from deepseek_harness import DeepSeekHarness @@ -1923,7 +1950,7 @@ def smoke_sdk_v3_resume(base_url: str, executable: Path) -> None: records = [header, *({**event, "seq": seq, "time": seq + 10} for seq, event in enumerate(events))] original = "".join(json.dumps(record) + "\n" for record in records).encode("utf-8") source.write_bytes(original) - patch = write_profile_patch(root, "v3-resume.patch.yml", sessions, []) + patch = write_profile_patch(root, "v3-resume.patch.yml", sessions, [], storage=storage) request_count = len(MockModelHandler.requests) def connect() -> DeepSeekHarness: @@ -1937,23 +1964,28 @@ def smoke_sdk_v3_resume(base_url: str, executable: Path) -> None: with connect() as harness: session = harness.resume_session(session_id) assert session.id == session_id, f"migration resumed {session.id!r}" - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) assert set(logs) == {session_id}, f"unexpected persisted sessions: {list(logs)}" assert any(row.get("type") == "user/message" and row.get("data") == message for row in logs[session_id]), ( "the migrated log lost the saved V3 user message" ) - (published,) = latest_persisted_session_paths(sessions) - migrated = published.read_bytes() + migrated = logs[session_id] + if storage == "jsonl": + (published,) = latest_persisted_session_paths(sessions) + migrated_bytes = published.read_bytes() with connect() as harness: session = harness.resume_session(session_id) assert session.id == session_id, f"restart resumed {session.id!r}" - assert published.read_bytes().startswith(migrated), "restart rewrote the published session history" + reopened = read_session_logs(sessions, storage=storage, executable=executable)[session_id] + assert reopened[:len(migrated)] == migrated, "restart rewrote the published session history" + if storage == "jsonl": + assert published.read_bytes().startswith(migrated_bytes), "restart rewrote the published JSONL generation" assert source.read_bytes() == original, "resuming changed the original V3 log" assert len(MockModelHandler.requests) == request_count, "resuming sent a model request" -def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None: +def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots: bool, *, storage: StorageBackend = "jsonl") -> None: """Check isolated sessions and explicit history restoration across runtime restarts.""" from deepseek_harness import DeepSeekHarness @@ -1961,7 +1993,7 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" - patch = write_advanced_profile_patch(root, "restart.patch.yml", sessions) + patch = write_advanced_profile_patch(root, "restart.patch.yml", sessions, storage=storage) first_request = len(MockModelHandler.requests) def connect(model: str = "smoke-model") -> DeepSeekHarness: @@ -1993,7 +2025,7 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots f"restart snapshot responses differ: {first.final_response!r}, {second.final_response!r}" ) - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) expected_ids = {RESTART_FIRST_SESSION_ID, RESTART_SECOND_SESSION_ID} if set(logs) != expected_ids: raise AssertionError(f"restart snapshot expected two durable sessions: {sorted(logs)}") @@ -2042,7 +2074,7 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots for message in messages ): raise AssertionError(f"resumed model history has no {role} message: {expected}") - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) if set(logs) != expected_ids: raise AssertionError(f"resume created an unexpected durable session: {sorted(logs)}") restored = logs[RESTART_FIRST_SESSION_ID] @@ -2090,7 +2122,7 @@ def smoke_sdk_restart_snapshot(base_url: str, executable: Path, update_snapshots ) -def smoke_sdk_scheduler_recovery(base_url: str, executable: Path, update_snapshots: bool) -> None: +def smoke_sdk_scheduler_recovery(base_url: str, executable: Path, update_snapshots: bool, *, storage: StorageBackend = "jsonl") -> None: """Keep a failed tool turn usable through the real Messages serializer and SDK.""" from deepseek_harness import DeepSeekHarness @@ -2099,7 +2131,7 @@ def smoke_sdk_scheduler_recovery(base_url: str, executable: Path, update_snapsho root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" - base_patch = write_advanced_profile_patch(root, "base.patch.yml", sessions) + base_patch = write_advanced_profile_patch(root, "base.patch.yml", sessions, storage=storage) patch = write_profile_patch(root, "recovery.patch.yml", sessions, [ {"id": "tool-todo", "disabled": False}, {"id": "session-title-llm", "disabled": True}, @@ -2111,7 +2143,7 @@ def smoke_sdk_scheduler_recovery(base_url: str, executable: Path, update_snapsho / "snapshots/sdk/tool-scheduler-recovery/scheduler-failure.mjs" ).as_uri(), }]}, - ]) + ], storage=storage) def connect() -> DeepSeekHarness: return DeepSeekHarness( @@ -2137,7 +2169,7 @@ def smoke_sdk_scheduler_recovery(base_url: str, executable: Path, update_snapsho requests = MockModelHandler.requests[first_request:] if len(requests) != 2: raise AssertionError(f"scheduler recovery expected two serialized model requests: {requests}") - logs = read_session_logs(sessions) + logs = read_session_logs(sessions, storage=storage, executable=executable) records = logs[RECOVERY_SESSION_ID] calls = [record["data"]["callId"] for record in records if record.get("type") == "tool/call"] if calls != list(RECOVERY_CALL_IDS[:2]): @@ -2181,12 +2213,12 @@ def smoke_sdk_scheduler_recovery(base_url: str, executable: Path, update_snapsho ) -def smoke_direct(base_url: str, executable: Path) -> None: +def smoke_direct(base_url: str, executable: Path, *, storage: StorageBackend = "jsonl") -> None: with tempfile.TemporaryDirectory(prefix="dsh-direct-") as temporary: root = Path(temporary).resolve() dsh_home = root / "home" sessions = dsh_home / "sessions" - patch = write_profile_patch(root, "direct.patch.yml", sessions, []) + patch = write_profile_patch(root, "direct.patch.yml", sessions, [], storage=storage) environment = { **os.environ, "DSH_HOME": str(dsh_home), @@ -2219,7 +2251,7 @@ def smoke_direct(base_url: str, executable: Path) -> None: peer.read_until(lambda message: message.get("id") == "shutdown") finally: peer.close() - assert_session_log(sessions, root, EXPECTED_TEXT) + assert_session_log(sessions, root, EXPECTED_TEXT, storage=storage, executable=executable) def smoke_packaged_runner(executable: Path) -> None: @@ -2508,57 +2540,51 @@ def selected_snapshot_session_files(directory: Path) -> dict[int, Path]: return {index: value[1] for index, value in selected.items()} -def assert_session_log(sessions: Path, cwd: Path, *expected_texts: str) -> None: - logs = latest_persisted_session_paths(sessions) +def assert_session_log( + sessions: Path, cwd: Path, *expected_texts: str, + storage: StorageBackend = "jsonl", executable: Path | None = None, +) -> None: + """Read one complete Session through the selected persistence provider.""" + logs = read_session_logs(sessions, storage=storage, executable=executable) if len(logs) != 1: - raise AssertionError(f"expected one JSONL session log under {sessions}, found {logs}") - content = logs[0].read_text() - assert_persisted_session_version(logs[0], content) - lines = content.splitlines() - header = json.loads(lines[0]) + raise AssertionError(f"expected one persisted Session under {sessions}, found {list(logs)}") + records = next(iter(logs.values())) + header = records[0] if header.get("cwd") != str(cwd): raise AssertionError(f"session header cwd is not absolute/canonical: {header}") - rendered = "\n".join(lines) + if not any(record.get("type") == "turn/end" for record in records[1:]): + raise AssertionError(f"persisted Session has no completed turn under {sessions}") + rendered = render_jsonl(records) for expected in expected_texts: if expected not in rendered: - raise AssertionError(f"session log has no {expected!r} response: {logs[0]}") + raise AssertionError(f"session log has no {expected!r} response under {sessions}") -def assert_sqlite_session_log(sessions: Path) -> None: - """Verify the default profile persisted one complete turn in SQLite.""" - database = sessions / ".segments" / "sessions.sqlite" - if not database.is_file(): - raise AssertionError(f"expected SQLite session database: {database}") - with sqlite3.connect(f"{database.as_uri()}?mode=ro", uri=True) as connection: - if connection.execute("PRAGMA integrity_check").fetchone() != ("ok",): - raise AssertionError(f"session database failed integrity check: {database}") - headers = connection.execute("SELECT header FROM traces").fetchall() - if len(headers) != 1: - raise AssertionError(f"expected one persisted Session, found {len(headers)}") - events = [json.loads(row[0]) for row in connection.execute("SELECT payload FROM events ORDER BY seq")] - if not any(event.get("type") == "turn/end" for event in events): - raise AssertionError(f"session database has no completed turn: {database}") +def read_session_logs( + sessions: Path, *, storage: StorageBackend = "jsonl", executable: Path | None = None, +) -> dict[str, list[dict[str, object]]]: + """Collect cold logical histories through the installed profile's persistence API.""" + from deepseek_harness import DeepSeekHarness - -def read_session_logs(sessions: Path) -> dict[str, list[dict[str, object]]]: - """Parse every persisted JSONL session into a map keyed by header id.""" - logs: dict[str, list[dict[str, object]]] = {} - for path in latest_persisted_session_paths(sessions): - content = path.read_text(encoding="utf-8") - assert_persisted_session_version(path, content) - records = [ - json.loads(line) - for line in content.splitlines() - if line - ] - if not records or records[0].get("type") != "session": - raise AssertionError(f"session log has no header: {path}") - session_id = records[0].get("id") - if not isinstance(session_id, str): - raise AssertionError(f"session log header has no string id: {path}") - if session_id in logs: - raise AssertionError(f"duplicate persisted session id: {session_id}") - logs[session_id] = records + if storage == "sqlite" and not (sessions / ".segments" / "sessions.sqlite").is_file(): + raise AssertionError(f"expected SQLite session database under {sessions}") + with tempfile.TemporaryDirectory(prefix="dsh-sdk-session-reader-") as temporary: + root = Path(temporary).resolve() + output = root / "sessions.json" + patch = write_profile_patch(root, "reader.patch.yml", sessions, [{"insert": [{ + "id": "python-sdk-session-reader", + "name": (Path(__file__).resolve().parent / "fixtures/python-sdk-session-reader.mjs").as_uri(), + "config": {"output": str(output)}, + }]}], storage=storage) + with DeepSeekHarness( + dsh_bin=None if executable is None else str(executable), + cwd=str(root), dsh_home=str(root / "home"), patches=(str(patch),), + env={"DSH_TELEMETRY_DISABLED": "1"}, request_timeout_seconds=60, + ): + pass + logs: dict[str, list[dict[str, object]]] = json.loads(output.read_text(encoding="utf-8")) + for session_id, records in logs.items(): + assert_current_session_version(session_header_version(render_jsonl(records), session_id), session_id) return logs @@ -3268,6 +3294,21 @@ def normalize_snapshot_comparison_text( return content +def _same_json_value(actual: object, expected: object) -> bool: + """Compare parsed JSON, preserving array order and distinguishing booleans from numbers.""" + if isinstance(actual, bool) or isinstance(expected, bool): + return type(actual) is type(expected) and actual == expected + if isinstance(actual, dict) and isinstance(expected, dict): + return actual.keys() == expected.keys() and all( + _same_json_value(value, expected[key]) for key, value in actual.items() + ) + if isinstance(actual, list) and isinstance(expected, list): + return len(actual) == len(expected) and all( + _same_json_value(value, other) for value, other in zip(actual, expected) + ) + return actual == expected + + def compare_snapshot_files( files: dict[str, str], update: bool, @@ -3346,7 +3387,16 @@ def compare_snapshot_files( expected_text = expected_path.read_text(encoding="utf-8") compared_actual = normalize_snapshot_comparison_text(name, actual, actual_native_version) compared_expected = normalize_snapshot_comparison_text(expected_path.name, expected_text, expected_native_version) - if compared_actual == compared_expected: + if name.endswith(".jsonl"): + matches = _same_json_value( + [json.loads(line) for line in compared_actual.splitlines() if line], + [json.loads(line) for line in compared_expected.splitlines() if line], + ) + elif name.endswith(".json"): + matches = _same_json_value(json.loads(compared_actual), json.loads(compared_expected)) + else: + matches = compared_actual == compared_expected + if matches: continue diff = "".join(difflib.unified_diff( compared_expected.splitlines(keepends=True),