chore(session): narrow storage PR to implementation

This commit is contained in:
liukx0205 committed 2026-11-15 01:42:34 +08:00
1 parent 86ecc66742
commit 0d8fbdd956
225 files changed
+2568 -7665

No files matched your search

@@ -366,7 +366,7 @@ jobs:
"${{ steps.smoke-venv-posix.outputs.python }}" \
"$GITHUB_WORKSPACE/scripts/smoke-python-runtime.py" \
--scenario all \
--installed-wheel --storage jsonl sqlite
--installed-wheel
- 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 --storage jsonl sqlite
& "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario all --installed-wheel
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 --storage jsonl sqlite
--installed-wheel
- 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 --storage jsonl sqlite
& "${{ steps.smoke-venv-windows.outputs.python }}" "$env:GITHUB_WORKSPACE\scripts\smoke-python-runtime.py" --scenario sdk-live --installed-wheel
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 --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
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
'
- uses: actions/[email protected]
+2 -2
View File
@@ -72,8 +72,8 @@ jobs:
python -m pip install \
"dist/deepseek_harness_sdk-$VERSION-py3-none-any.whl" \
"dist/deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl"
python scripts/smoke-python-runtime.py --scenario sdk-default --storage jsonl sqlite
python scripts/smoke-python-runtime.py --scenario sdk-mcp --storage jsonl sqlite
python scripts/smoke-python-runtime.py --scenario sdk-default
python scripts/smoke-python-runtime.py --scenario sdk-mcp
validate:
name: Validate release candidate
@@ -43,7 +43,6 @@ describe('dsh run with Agent Teams enabled', () => {
'- id: session-persistence-jsonl',
' config:',
` root: '${sessions}'`,
' storage: jsonl',
' compression: none',
'- insert:',
' - id: team-fixture-llm',
@@ -114,8 +114,7 @@ describe.skipIf(!requireBuiltArtifacts)('built CLI lazy-search startup', () => {
const result = await runBuiltWeb(cwd)
expect(result.stdout).toMatch(/dsh web: http:\/\/127\.0\.0\.1:\d+/u)
expect(result.code).toBe(0)
// Node 24.9 warns about the SQLite persistence used even while full-text search is off.
expect(result.stderr.replace(/\(node:\d+\) ExperimentalWarning: SQLite[^\n]*\n(?:\(Use `node --trace-warnings \.\.\.` to show where the warning was created\)\n)?/gu, '')).toBe('')
expect(result.stderr).not.toMatch(/ExperimentalWarning: SQLite/u)
} finally {
await rm(cwd, { recursive: true, force: true })
}
@@ -9,7 +9,6 @@
disabled: true
- id: agent-loop
inject: [sessionPersistence]
config:
agents:
- id: main
@@ -9,7 +9,6 @@
disabled: true
- id: agent-loop
inject: [sessionPersistence]
config:
agents:
- id: main
@@ -10,7 +10,6 @@
- id: session-persistence-jsonl
config:
storage: jsonl
root: './.sessions'
compression: none
@@ -13,7 +13,6 @@
- id: session-persistence-jsonl
config:
storage: jsonl
root: './.sessions'
compression: none
@@ -23,7 +23,6 @@
- id: session-persistence-jsonl
config:
storage: jsonl
root: './.sessions'
compression: none
@@ -9,7 +9,6 @@
disabled: true
- id: agent-loop
inject: [sessionPersistence]
config:
agents:
- id: main
@@ -9,7 +9,6 @@
disabled: true
- id: agent-loop
inject: [sessionPersistence]
config:
agents:
- id: main
@@ -25,7 +25,7 @@ afterEach(async () => {
workdir = undefined
})
describe.skipIf(!process.env.DEEPSEEK_API_KEY).each(['jsonl', 'sqlite'] as const)('compaction: a long session compacts mid-flight and keeps running (%s)', (storage) => {
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('compaction: a long session compacts mid-flight and keeps running', () => {
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,7 +49,6 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY).each(['jsonl', 'sqlite'] as const
compactionRetries: 1,
},
persistenceRoot: join(workdir, '.sessions'),
persistenceStorage: storage,
})
const agent = await ctx.agentLoop.create(brandString<SessionId>('e2e-compaction'), { provider: 'deepseek-official', model: 'deepseek-v4-flash' }, { cwd: workdir })
@@ -103,12 +102,5 @@ describe.skipIf(!process.env.DEEPSEEK_API_KEY).each(['jsonl', 'sqlite'] as const
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)
})
@@ -9,7 +9,6 @@
disabled: true
- id: agent-loop
inject: [sessionPersistence]
config:
agents:
- id: main
@@ -41,10 +41,8 @@ export interface CodingHarnessOptions {
* config — per-context, not per-agent). Omitted ⇒ no persona prefix section.
*/
personaPrefix?: string
/** Durable persistence root; omitted roots keep the suite file-free. */
/** Durable JSONL persistence root (the resume suite needs it; others stay 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
@@ -92,12 +90,11 @@ export async function codingHarness(workdir: string, options: CodingHarnessOptio
await ctx.plugin(ToolResultPruner)
await ctx.plugin(BasicCompactionEngine, options.compact)
}
// Loaded last so a resume's deferred persistence injection resolves here.
// 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.
if (options.persistenceRoot !== undefined) {
await ctx.plugin(JsonlSessionPersistence, {
root: options.persistenceRoot,
...options.persistenceStorage === undefined ? {} : { storage: options.persistenceStorage },
})
await ctx.plugin(JsonlSessionPersistence, { root: options.persistenceRoot })
await ctx.plugin(SessionCheckpointPolicy)
}
return ctx
@@ -1,4 +1,4 @@
import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
@@ -13,7 +13,10 @@ import {
type NormalizeContext,
} from '@deepseek-ai/dsh-session-snapshot'
import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
import { persistedSessionLogs } from '../../session-logs.ts'
import {
decompressZstdFrame,
scanZstdFrames,
} from '@deepseek-ai/dsh-session-persistence-jsonl/src/zstd.ts'
import { describe, expect, it } from 'vitest'
const goldensDir = fileURLToPath(new URL('./expected/', import.meta.url))
@@ -276,11 +279,25 @@ async function scenarioPrompt(dir: string, label: string): Promise<string> {
return prompt
}
async function persistedLogs(
cwd: string, root?: string, compression: 'none' | 'zstd' = 'none',
): Promise<PersistedLog[]> {
const logs = await persistedSessionLogs(root ?? join(await realpath(cwd), '.sessions'), compression)
return logs.map(log => ({ content: log.content, header: { ...log.header } }))
async function readPersistedLog(file: string): Promise<string> {
const content = await readFile(file)
if (!file.endsWith('.zstd')) return content.toString('utf8')
const scan = scanZstdFrames(content)
if (scan.tornStart !== undefined) throw new Error(`persisted snapshot log has a torn Zstandard frame: ${file}`)
const decoded: Buffer[] = []
for (const frame of scan.frames) {
decoded.push(await decompressZstdFrame(content.subarray(frame.start, frame.end)))
}
return Buffer.concat(decoded).toString('utf8')
}
async function persistedLogs(cwd: string, root: string = join(cwd, '.sessions')): Promise<PersistedLog[]> {
const files = (await readdir(root, { recursive: true }))
.filter(file => file.endsWith('.jsonl') || file.endsWith('.jsonl.zstd'))
return Promise.all(files.map(async (file) => {
const content = await readPersistedLog(join(root, file))
return { content, header: parseJsonl(content)[0] ?? {} }
}))
}
describe('headless stream-json snapshots', () => {
@@ -307,7 +324,7 @@ describe('headless stream-json snapshots', () => {
'Record this wake without calling tools.',
],
inspect: async () => {
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd')
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'))
expect(logs).toHaveLength(1)
const log = logs[0]!
expect(typeof log.header.id).toBe('string')
@@ -324,7 +341,7 @@ describe('headless stream-json snapshots', () => {
type: 'final', sessionId, reason: { kind: 'completed' }, text: 'AUTO_SHUTDOWN_OK',
})
}
const beforeRejectedRestore = (await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd'))[0]!.content
const beforeRejectedRestore = (await persistedLogs(cwd, join(cwd, '.dsh', 'sessions')))[0]!.content
const unavailable = await runLoaderSmoke({
...options,
label: 'Auto restore without its integration',
@@ -333,7 +350,7 @@ describe('headless stream-json snapshots', () => {
})
expect(unavailable.stderr).toContain('cannot restore preset "auto" without its active integration')
expect(parseJsonl(unavailable.stdout).some(event => event.type === 'final')).toBe(false)
const afterRejectedRestore = (await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd'))[0]!.content
const afterRejectedRestore = (await persistedLogs(cwd, join(cwd, '.dsh', 'sessions')))[0]!.content
expect(afterRejectedRestore.startsWith(beforeRejectedRestore)).toBe(true)
// Restore records its seed boundary before live publication validates the saved permission.
const appended = parseJsonl(afterRejectedRestore.slice(beforeRejectedRestore.length))
@@ -353,7 +370,7 @@ describe('headless stream-json snapshots', () => {
'--session-id', sessionId, '--permission-mode', 'read-only', 'Continue.',
],
inspect: async () => {
const log = (await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd'))[0]!
const log = (await persistedLogs(cwd, join(cwd, '.dsh', 'sessions')))[0]!
const restored = parseJsonl(log.content)
expect(restored.filter(event => event.type === 'permission/preset').at(-1)?.data)
.toEqual({ preset: 'read-only' })
@@ -382,7 +399,7 @@ describe('headless stream-json snapshots', () => {
NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
},
inspect: async (cwd) => {
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd')
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'))
expect(logs).toHaveLength(1)
const actual = logs[0]
if (actual === undefined) throw new Error('the headless profile did not persist its session')
@@ -422,7 +439,7 @@ describe('headless stream-json snapshots', () => {
NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
},
inspect: async (cwd) => {
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd')
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'))
const content = logs[0]?.content ?? ''
const modes = parseJsonl(content).filter(event => event.type === 'sandbox/mode')
expect(modes.at(-1)?.data).toEqual({ mode: 'workspace-write' })
@@ -505,7 +522,7 @@ describe('headless stream-json snapshots', () => {
tsconfigPath,
env,
inspect: async (inspected) => {
const logs = await persistedLogs(inspected, join(inspected, '.dsh', 'sessions'), 'zstd')
const logs = await persistedLogs(inspected, join(inspected, '.dsh', 'sessions'))
expect(logs).toHaveLength(1)
const content = logs[0]?.content ?? ''
expect(content).toContain(firstTask)
@@ -540,7 +557,7 @@ describe('headless stream-json snapshots', () => {
tsconfigPath,
env: { DSH_AUTO_REVIEW_TEST_MODE: mode, DSH_TELEMETRY_DISABLED: '1' },
inspect: async (cwd) => {
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'), 'zstd')
const logs = await persistedLogs(cwd, join(cwd, '.dsh', 'sessions'))
expect(logs).toHaveLength(1)
const events = parseJsonl(logs[0]!.content)
expect(events.find(event => event.type === 'user/message')?.data).toMatchObject({
@@ -600,7 +617,7 @@ describe('headless stream-json snapshots', () => {
binArgs: [...args, '--session-id', sessionId, 'I authorize the exact CLI probe. Retry it.'], tsconfigPath,
env: { DSH_AUTO_REVIEW_TEST_MODE: 'allow', DSH_TELEMETRY_DISABLED: '1' },
inspect: async (directory) => {
const logs = await persistedLogs(directory, join(directory, '.dsh', 'sessions'), 'zstd')
const logs = await persistedLogs(directory, join(directory, '.dsh', 'sessions'))
expect(logs).toHaveLength(1)
const events = parseJsonl(logs[0]!.content)
const sources = events.filter(event => event.type === 'user/message')
@@ -1,10 +1,11 @@
import { realpath } from 'node:fs/promises'
import { readFile, readdir } from 'node:fs/promises'
import { zstdDecompressSync } from 'node:zlib'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
import type { SessionEvent } from '@deepseek-ai/dsh-session'
import { persistedSessionLogs } from '../../session-logs.ts'
import { scanZstdFrames } from '@deepseek-ai/dsh-session-persistence-jsonl/src/zstd.js'
const PRODUCTION_PROFILE_PROCESS_TIMEOUT_MS = 60_000
const PRODUCTION_PROFILE_TEST_TIMEOUT_MS = PRODUCTION_PROFILE_PROCESS_TIMEOUT_MS + 15_000
@@ -26,10 +27,16 @@ describe('headless-agent keyless smoke', () => {
tsconfigPath,
processTimeoutMs: PRODUCTION_PROFILE_PROCESS_TIMEOUT_MS,
inspect: async (cwd) => {
const sessionsDir = await realpath(join(cwd, '.sessions'))
const logs = await persistedSessionLogs(sessionsDir, 'zstd')
expect(logs).toHaveLength(1)
const records = logs[0]!.content.trim().split('\n')
const sessionsDir = join(cwd, '.sessions')
const files = await readdir(sessionsDir, { recursive: true })
const relativePath = files.find(file => file.endsWith('.jsonl.zstd'))
if (relativePath === undefined) return
const compressed = await readFile(join(sessionsDir, relativePath))
expect(compressed.subarray(0, 4).toString('hex')).toBe('28b52ffd')
const { frames, tornStart } = scanZstdFrames(compressed)
expect(tornStart).toBeUndefined()
const records = frames.flatMap(({ start, end }) =>
zstdDecompressSync(compressed.subarray(start, end)).toString().trim().split('\n'))
.map(line => JSON.parse(line) as Record<string, unknown>)
persistedHeader = records[0]
const requestHeader = records.find(record => record.type === 'request/header')
@@ -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; run 2 is a fresh harness (new Context,
* a fact and persists the turn to JSONL; 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
// persistence backend flushes; then drop the on-disk session log.
// JSONL 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).each(['jsonl', 'sqlite'] as const)('resume: continue a persisted session across processes (%s)', (storage) => {
describe.skipIf(!process.env.DEEPSEEK_API_KEY)('resume: continue a persisted session across processes', () => {
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 durable
// dispose the whole context (simulating process exit) so only the JSONL
// log on disk survives.
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root, persistenceStorage: storage })
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root })
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).each(['jsonl', 'sqlite'] as const
// 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, persistenceStorage: storage })
ctx = await codingHarness(process.cwd(), { personaPrefix: SYSTEM_PROMPT, persistenceRoot: root })
const resumed = (await ctx.agents.resume({
resumeSessionId: SESSION_ID,
agentOptions: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
@@ -14,7 +14,6 @@
- id: session-persistence-jsonl
config:
storage: jsonl
root: './.sessions'
compression: none
@@ -3,13 +3,14 @@ import { cp, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/pr
import { tmpdir } from 'node:os'
import { dirname, join, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { zstdDecompressSync } from 'node:zlib'
import { resolveExampleLaunch } from '@deepseek-ai/dsh-loader-smoke'
import { scanZstdFrames } from '@deepseek-ai/dsh-session-persistence-jsonl/src/zstd.js'
import { execa } from 'execa'
import { describe, expect, it, onTestFinished } from 'vitest'
import { workspaceDependencyPaths, type PrimaryRuntimeManifest } from '@deepseek-ai/dsh-tool-workspace-dependencies'
import { messagesResponse } from './fixtures/messages-response.ts'
import { persistedSessionLogs } from '../session-logs.ts'
const repoRoot = fileURLToPath(new URL('../../../../../', import.meta.url))
const launch = resolveExampleLaunch({
@@ -219,10 +220,27 @@ describe('Python SDK dsh profile keyless smoke', () => {
const exit = await child
expect(exit.exitCode, `signal=${String(exit.signal)}; stderr=${stderr}`).toBe(0)
const sessionsRoot = join(root, '.dsh', 'sessions')
const logs = await persistedSessionLogs(sessionsRoot, 'zstd')
const log = logs.find(entry => entry.header.id === 'main')
const files = await readdir(sessionsRoot, { recursive: true })
// Session logs are JSONL across one zstd frame per batch, header frame
// first. Decompress frames explicitly: a single call over concatenated
// frames returned only the first frame on Node 24.19 and returns every
// frame on 24.22, so neither behavior may back the assertion.
const logs: { compressed: Buffer; header: Record<string, unknown> }[] = []
for (const file of files.filter(file => file.endsWith('.jsonl.zstd'))) {
const compressed = await readFile(join(sessionsRoot, file))
expect(compressed.subarray(0, 4).toString('hex')).toBe('28b52ffd')
const first = scanZstdFrames(compressed).frames[0]
if (first === undefined) continue
const headerLine = zstdDecompressSync(compressed.subarray(first.start, first.end)).toString().trim().split('\n')[0]
if (headerLine === undefined) continue
logs.push({ compressed, header: JSON.parse(headerLine) as Record<string, unknown> })
}
const log = logs.find(entry => entry.header.type === 'session' && entry.header.id === 'main')
expect(log).toBeDefined()
const records = log!.content.trimEnd().split('\n')
const { frames, tornStart } = scanZstdFrames(log!.compressed)
expect(tornStart).toBeUndefined()
const records = frames
.flatMap(({ start, end }) => zstdDecompressSync(log!.compressed.subarray(start, end)).toString().trim().split('\n'))
.map(line => JSON.parse(line) as Record<string, unknown>)
expect(records[0]).toMatchObject({ type: 'session', id: 'main' })
expect(records.length).toBeGreaterThan(1)
-37
View File
@@ -1,37 +0,0 @@
/** Logical persisted history inspection for shipped-profile acceptance tests. @module */
import { Context } from '@deepseek-ai/cordis'
import { snapshotSessionFormatJson } from '@deepseek-ai/dsh-session-format'
import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
import type { SessionHeader } from '@deepseek-ai/dsh-session'
import * as SessionPersistencePlugin from '@deepseek-ai/dsh-session-persistence-jsonl'
import type { JsonlCompression } from '@deepseek-ai/dsh-session-persistence-jsonl'
/**
* Read logical history after the profile process has settled its writes.
* @param root - the exact persistence directory configured by the profile process.
* @param compression - encoding of any retained JSONL import sources.
* @returns current-format logs, with parent Sessions ordered before children.
*/
export async function persistedSessionLogs(root: string, compression: JsonlCompression): Promise<{
readonly content: string
readonly header: SessionHeader
}[]> {
const ctx = new Context()
try {
await ctx.plugin(SessionPersistencePlugin, { root, compression })
const logs = []
for (const snapshot of await ctx.sessionPersistence.list()) {
await using handle = await ctx.sessionPersistence.open(snapshot.header.id, 'read')
const { events } = await handle.read()
const header = sessionFormatCatalog.encodeCurrentHeader(
{ ...handle.header, delegationDepth: handle.header.delegationDepth ?? 0 }, handle.inheritedEventCount,
)
const content = [header, ...events.map(event => sessionFormatCatalog.encodeCurrentEvent({
...event, data: snapshotSessionFormatJson(event.data),
}))].map(record => JSON.stringify(record)).join('\n') + '\n'
logs.push({ header: handle.header, content })
}
return logs.sort((a, b) => Number(a.header.parentSession !== undefined) - Number(b.header.parentSession !== undefined)
|| a.header.createdAt - b.header.createdAt || a.header.id.localeCompare(b.header.id))
} finally { await ctx.fiber.dispose() }
}
+5 -12
View File
@@ -17,7 +17,6 @@ import {
} from './scaffold.ts'
import { openSettings, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, WEB_FIXTURE_TIME } from './support.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
import { sessionDir } from '../../../packages/session/session-persistence-jsonl/src/format.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/message-actions', import.meta.url))
// Borrowed read-only: this scenario needs any settled user+assistant pair, not
@@ -465,7 +464,9 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
const [header, ...events] = realizeSeedFixture(scaffold, await readFile(SEED, 'utf8'), id).trimEnd().split('\n')
.map((line): Record<string, unknown> => JSON.parse(line) as Record<string, unknown>)
expect(header?.version).toBe(3)
const directory = sessionDir(scaffold.persistenceRoot, scaffold.workspaceCwd, id)
const projects = (await readdir(scaffold.persistenceRoot, { withFileTypes: true })).filter(entry => entry.isDirectory())
expect(projects).toHaveLength(1)
const directory = join(scaffold.persistenceRoot, projects[0]!.name, id)
const predecessor = join(directory, 'session.v3.jsonl.zstd')
const createdAt = WEB_FIXTURE_TIME - 90_000
const rows = [{ ...header, id, cwd: scaffold.workspaceCwd, createdAt },
@@ -477,13 +478,7 @@ describe('web e2e: message IconActions and clocks on settled history', () => {
const warningStart = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
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()
await page.getByRole('button', { name: /^Show \d+ more sessions$/ }).click()
const row = page.locator(`[data-row-key="session:${id}"]`)
await row.waitFor()
acknowledgeReloadConnectionLoss(tripwire, warningStart)
@@ -511,9 +506,7 @@ 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)).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 readdir(directory)).toContain(`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([])
+12 -22
View File
@@ -6,7 +6,7 @@
// under the standard discipline: turn 1 produces a bash call plus two
// parallel reads in one assistant message (tool-call density for the
// trajectory ledger/timing lanes), turn 2 a markdown-rich reply.
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { join } from 'node:path'
import type { Browser, Page, Response } from 'playwright'
@@ -25,7 +25,6 @@ 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')
@@ -502,27 +501,18 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
await page.getByText('Session copied as Markdown.', { exact: true }).waitFor({ timeout: 30_000 })
expect(await page.evaluate(() => Number(Reflect.get(globalThis, '__dshClipboardWrites')))).toBe(1)
const snapshot = await scaffold.ctx.sessionPersistence.stat(brandString<SessionId>(SEED_ID))
expect(snapshot?.header.id).toBe(SEED_ID)
const sourcePath = generationLogPath(scaffold.persistenceRoot, scaffold.workspaceCwd,
brandString<SessionId>(SEED_ID), SESSION_FORMAT_VERSION, 'zstd')
const sqlite = process.env.DSH_SNAPSHOT_STORAGE === 'sqlite'
expect(snapshot?.location).toEqual(sqlite ? undefined : { kind: 'jsonl', path: sourcePath })
const sourcePath = (await scaffold.ctx.sessionPersistence.stat(brandString<SessionId>(SEED_ID)))?.location?.path
if (sourcePath === undefined) throw new Error('seeded Session has no materialized artifact location')
expect((await stat(sourcePath)).isFile()).toBe(true)
expect(sourcePath.startsWith(`${scaffold.persistenceRoot}/`)).toBe(true)
const markdown = await page.evaluate(() => navigator.clipboard.readText())
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(markdown).toContain(`Session file:\n\n\`\`\`text\n${sourcePath}\n\`\`\``)
const normalized = markdown
.split(sourcePath).join('{{sessionFile}}')
.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)
expect(normalized).toContain('Session file:\n\n```text\n{{sessionFile}}\n```')
expect(normalized).toContain('# NavScenario: first run bash to')
expect(normalized).toContain('> NavScenario: first run bash to print exactly NAVIGATION_OK')
expect(normalized).toContain('<details><summary>3 previous messages</summary>')
+8 -18
View File
@@ -21,12 +21,6 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
it.each([false, true])('resumes code as PTC (selection events=%s)', async (withSelections) => {
const scaffold = await launchWebScaffold()
try {
const sqlite = process.env.DSH_SNAPSHOT_STORAGE === 'sqlite'
const readStored = async (id: SessionId): Promise<string> => {
await using handle = await scaffold.ctx.sessionPersistence.open(id, 'read')
const { events } = await handle.read()
return [{ type: 'session', ...handle.header }, ...events].map(row => JSON.stringify(row)).join('\n') + '\n'
}
const id = brandString<SessionId>('preset-migration')
const fixture = await readFile(fixturePath, 'utf8')
const [fixtureHeader, ...fixtureEvents] = fixture.trimEnd().split('\n')
@@ -103,10 +97,9 @@ 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 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' })
const childPublished = await readFile(childSuccessor)
const childText = Buffer.concat(scanZstdFrames(childPublished).frames
.map(({ start, end }) => zstdDecompressSync(childPublished.subarray(start, end)))).toString('utf8')
expect(childText.trimEnd().split('\n').map((line): unknown => JSON.parse(line))).toEqual([
{ ...childHeader, version: SESSION_FORMAT_VERSION, agentPreset: 'ptc' }, ...childRows,
])
@@ -116,10 +109,9 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
.rejects.toMatchObject({ code: 'ENOENT' })
await scaffold.ctx.sessions.flush(resolved.agent.session)
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 publishedBytes = await readFile(successor)
const published = Buffer.concat(scanZstdFrames(publishedBytes).frames
.map(({ start, end }) => zstdDecompressSync(publishedBytes.subarray(start, end)))).toString('utf8')
const expected = [
{ ...header, version: SESSION_FORMAT_VERSION, agentPreset: 'ptc' },
...rows.map(row => row['type'] === 'agent-preset/selected'
@@ -139,14 +131,12 @@ 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 }
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(normalizeSessionSnapshots([published], context)).toEqual(normalizeSessionSnapshots([expected], context))
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(sqlite ? ['session.v2.jsonl.zstd'] : ['session.v2.jsonl.zstd', `session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`])
.toEqual(['session.v2.jsonl.zstd', `session.v${SESSION_FORMAT_VERSION}.jsonl.zstd`])
} finally {
await scaffold.close()
}
+10 -14
View File
@@ -88,8 +88,6 @@ 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
@@ -598,7 +596,7 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
: [{ id: 'agent-default-model', config: { provider: 'deepseek-official', model: 'deepseek-v4-flash' } }],
...extraOverlayPatches,
{ id: 'agent-preset-registry', config: { default: 'standard' } },
{ id: 'session-persistence-jsonl', config: { root: persistenceRoot, storage: SNAPSHOT_STORAGE } },
{ id: 'session-persistence-jsonl', config: { root: persistenceRoot } },
// Content search is enabled here although the shipped bundles default it
// off (`openAt: never`, pinned by apps/cli/tests/lazy-search-startup):
// the seeded-session scenarios navigate by content search, and these e2e
@@ -1288,12 +1286,11 @@ async function assertReplaySession(
sessionIds: typeof expectedHeader.id === 'string' ? [expectedHeader.id] : [],
cwd: typeof expectedHeader.cwd === 'string' ? expectedHeader.cwd : '\0no-cwd\0',
}
const actualSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(actual)], actualContext)[0]!
.split(harnessHome).join('{{harnessHome}}')
const expectedSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(expected)], expectedContext)[0]!
.split(harnessHome).join('{{harnessHome}}')
const records = (text: string): unknown[] => text.split('\n').filter(line => line.trim() !== '').map((line): unknown => JSON.parse(line))
expect(records(actualSnapshot), `${fixturePath}: persisted replay`).toEqual(records(expectedSnapshot))
const actualSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(actual)], actualContext)[0]
?.split(harnessHome).join('{{harnessHome}}')
const expectedSnapshot = normalizeSessionSnapshots([normalizeWebSessionVolatiles(expected)], expectedContext)[0]
?.split(harnessHome).join('{{harnessHome}}')
expect(actualSnapshot, `${fixturePath}: persisted replay`).toBe(expectedSnapshot)
if (manifest.header?.pin !== true) return
const normalizePrompt = (value: string): string => value
@@ -1563,7 +1560,7 @@ export async function seedSession(
return meta.id
}
/** Materialize one detached Session fixture through the booted persistence provider. */
/** Materialize one detached Session fixture through the shipped JSONL provider. */
async function persistSeedSession(
scaffold: WebScaffold,
meta: SessionHeader,
@@ -1571,10 +1568,9 @@ async function persistSeedSession(
): Promise<void> {
const seeder = new Context()
try {
await seeder.plugin(JsonlSessionPersistence, {
root: scaffold.persistenceRoot,
storage: SNAPSHOT_STORAGE,
})
// 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 })
const handle = await seeder.sessionPersistence.create(meta)
await handle.append(events)
await handle.close()
+5 -2
View File
@@ -22,7 +22,6 @@ import {
} from './scaffold.ts'
import { connectFreshWorkspace, newEnglishPage, pinBrowserClock, pinHostClock, saveFailureShot, writeComposerDraft } from './support.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
import { sessionDir } from '../../../packages/session/session-persistence-jsonl/src/format.ts'
const BASE_FIXTURE = fileURLToPath(new URL('../../../snapshots/web/live-interactions/session.v3.jsonl', import.meta.url))
const AVAILABLE_CHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/ui.expected.md', import.meta.url))
@@ -1012,6 +1011,10 @@ describe('web e2e: migration-required subagent catalog', () => {
} finally {
await parentHandle.close()
}
const projects = (await readdir(scaffold.persistenceRoot, { withFileTypes: true })).filter(entry => entry.isDirectory())
expect(projects).toHaveLength(1)
const project = projects[0]
if (project === undefined) throw new Error('parent seed has no project directory')
// Keep historical bytes on disk; seeding through the writer would migrate them before the browser opens.
for (const [id, parentSession, label, depth] of [
[childId, parentId, childLabel, 1],
@@ -1032,7 +1035,7 @@ describe('web e2e: migration-required subagent catalog', () => {
{ ...header, id, createdAt: createdAt + depth, cwd: scaffold.workspaceCwd, parentSession, origin: 'subagent', delegationDepth: depth },
...body.map((event, seq) => ({ ...event, seq, time: createdAt + depth + seq + 1 })),
]
const directory = sessionDir(scaffold.persistenceRoot, scaffold.workspaceCwd, id)
const directory = join(scaffold.persistenceRoot, project.name, id)
const path = join(directory, 'session.v3.jsonl.zstd')
const source = Buffer.concat(rows.map(row => zstdCompressSync(Buffer.from(`${JSON.stringify(row)}\n`))))
await mkdir(directory, { recursive: true })
+7 -5
View File
@@ -11,13 +11,14 @@
// are host RPCs with no model involvement, and the one session row the
// flat/hover/menu/archive scenarios need comes from a seeded fixture (the
// seeded-history seed reused verbatim — no new recording).
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'
import { fileURLToPath } from 'node:url'
import { join, sep } from 'node:path'
import type { Browser, Locator, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { logPath } from '../../../packages/session/session-persistence-jsonl/src/format.ts'
import {
acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, readPersistedEvents, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
@@ -254,8 +255,9 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
.map(snapshot => snapshot.header)
.find(candidate => candidate.id === SEED_ID)
if (header === undefined) throw new Error('seeded Session log disappeared before deletion')
const seededLogPath = logPath(scaffold.persistenceRoot, header.cwd, header.id, 'zstd')
expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
await expect(scaffold.ctx.sessionPersistence.stat(header.id)).resolves.toBeDefined()
await stat(seededLogPath)
// The attachment stream can lag the Host commit while New Session is
// already visible. A row count or position cannot identify the seed.
@@ -301,7 +303,7 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
{ timeout: 10_000 },
).toBe(1)
expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
await expect(scaffold.ctx.sessionPersistence.stat(header.id)).resolves.toBeDefined()
await stat(seededLogPath)
expect((await readPersistedEvents(scaffold, brandString<SessionId>(SEED_ID))).length).toBeGreaterThan(0)
// Re-registering the exact deleted path immediately, without a reload, is
@@ -325,7 +327,7 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 10_000 })
.toBeGreaterThanOrEqual(1)
expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
await expect(scaffold.ctx.sessionPersistence.stat(header.id)).resolves.toBeDefined()
await stat(seededLogPath)
// Restore the deleted-registry state so reload still verifies deletion
// persistence independently of the successful re-registration above.
@@ -348,7 +350,7 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo
).toBe(1)
expect(scaffold.ctx.workspaceRegistry.get(workspace.id)).toBeUndefined()
expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
await expect(scaffold.ctx.sessionPersistence.stat(header.id)).resolves.toBeDefined()
await stat(seededLogPath)
expect((await readPersistedEvents(scaffold, brandString<SessionId>(SEED_ID))).length).toBeGreaterThan(0)
expect(transientSlotErrors).toEqual([])
+1 -4
View File
@@ -3269,13 +3269,11 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
## `@deepseek-ai/dsh-session-persistence-jsonl`
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:100`](../packages/session/session-persistence-jsonl/src/index.ts)
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:95`](../packages/session/session-persistence-jsonl/src/index.ts)
```ts config-catalog
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
export interface Config {
/** Storage for Sessions; defaults to JSONL. SQLite explicitly enables legacy import. */
storage?: 'sqlite' | 'jsonl'
/**
* Root directory for all session files. Required (no default): a default of
* `process.cwd()` would scatter session files as the process's cwd changes
@@ -5439,7 +5437,6 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them.
| `@deepseek-ai/dsh-session-format-v1-to-v2` | — | [`packages/session/session-format-v1-to-v2/src/index.ts`](../packages/session/session-format-v1-to-v2/src/index.ts) |
| `@deepseek-ai/dsh-session-format-v2-to-v3` | — | [`packages/session/session-format-v2-to-v3/src/index.ts`](../packages/session/session-format-v2-to-v3/src/index.ts) |
| `@deepseek-ai/dsh-session-format-v3-to-v4` | — | [`packages/session/session-format-v3-to-v4/src/index.ts`](../packages/session/session-format-v3-to-v4/src/index.ts) |
| `@deepseek-ai/dsh-session-persistence-sqlite` | — | [`packages/session/session-persistence-sqlite/src/index.ts`](../packages/session/session-persistence-sqlite/src/index.ts) |
| `@deepseek-ai/dsh-session-snapshot` | — | [`packages/test-support/session-snapshot/src/index.ts`](../packages/test-support/session-snapshot/src/index.ts) |
| `@deepseek-ai/dsh-session-telemetry` | — | [`packages/session/session-telemetry/src/index.ts`](../packages/session/session-telemetry/src/index.ts) |
| `@deepseek-ai/dsh-session-title-llm` | — | [`packages/session/session-title-llm/src/index.ts`](../packages/session/session-title-llm/src/index.ts) |
+1 -4
View File
@@ -3271,13 +3271,11 @@ export type SessionLogCompressionLevel = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
## `@deepseek-ai/dsh-session-persistence-jsonl`
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:100`](../packages/session/session-persistence-jsonl/src/index.ts)
- `source`: [`packages/session/session-persistence-jsonl/src/index.ts:95`](../packages/session/session-persistence-jsonl/src/index.ts)
```ts config-catalog
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
export interface Config {
/** Storage for Sessions; defaults to JSONL. SQLite explicitly enables legacy import. */
storage?: 'sqlite' | 'jsonl'
/**
* Root directory for all session files. Required (no default): a default of
* `process.cwd()` would scatter session files as the process's cwd changes
@@ -5441,7 +5439,6 @@ export interface Config {
| `@deepseek-ai/dsh-session-format-v1-to-v2` | — | [`packages/session/session-format-v1-to-v2/src/index.ts`](../packages/session/session-format-v1-to-v2/src/index.ts) |
| `@deepseek-ai/dsh-session-format-v2-to-v3` | — | [`packages/session/session-format-v2-to-v3/src/index.ts`](../packages/session/session-format-v2-to-v3/src/index.ts) |
| `@deepseek-ai/dsh-session-format-v3-to-v4` | — | [`packages/session/session-format-v3-to-v4/src/index.ts`](../packages/session/session-format-v3-to-v4/src/index.ts) |
| `@deepseek-ai/dsh-session-persistence-sqlite` | — | [`packages/session/session-persistence-sqlite/src/index.ts`](../packages/session/session-persistence-sqlite/src/index.ts) |
| `@deepseek-ai/dsh-session-snapshot` | — | [`packages/test-support/session-snapshot/src/index.ts`](../packages/test-support/session-snapshot/src/index.ts) |
| `@deepseek-ai/dsh-session-telemetry` | — | [`packages/session/session-telemetry/src/index.ts`](../packages/session/session-telemetry/src/index.ts) |
| `@deepseek-ai/dsh-session-title-llm` | — | [`packages/session/session-title-llm/src/index.ts`](../packages/session/session-title-llm/src/index.ts) |
@@ -30,8 +30,8 @@
en: fb1c6d23599659c5
zh: b51e4ee8c0d1daeb
/cookbook-adding-a-session-log-format-version/6-validate-the-integrated-result/developer-v4-corpus-trial:
en: cbb1815a2476c046
zh: d6a5bae14a35a9c5
en: f22ab2d7b089a6d2
zh: 0a47f543899f0161
/cookbook-adding-a-session-log-format-version/6-validate-the-integrated-result/final-v3-event-vocabulary-before-v4-publication:
en: a6ed1788dc64efbe
zh: 9ca3382f92df986b
@@ -127,7 +127,7 @@ Use the one-time [migration script](../../scripts/migrate-sessions-to-v4.ts) fro
pnpm run migrate:sessions-to-v4
```
The default root is `~/.dsh/sessions`. Use `--sessions-dir /path/to/sessions-copy` for another corpus, or `--help` for usage. Concurrent jobs default to the available CPU count capped at 16; `--jobs N` accepts any positive safe integer, including larger expert overrides, and `--jobs 1` runs serially. A bounded queue opens only that many Sessions at once, regardless of corpus size. Each historical Session goes through the normal locked, validated publication path to create a V4 successor beside its unchanged source files. Existing V4 Sessions are opened read-only; rerunning does not reconvert them. The script explicitly selects JSONL storage, so it publishes V4 JSONL successors even though the application defaults to SQLite. It does not import Sessions into SQLite, makes no model requests, and does not change conversion or refusal rules.
The default root is `~/.dsh/sessions`. Use `--sessions-dir /path/to/sessions-copy` for another corpus, or `--help` for usage. Concurrent jobs default to the available CPU count capped at 16; `--jobs N` accepts any positive safe integer, including larger expert overrides, and `--jobs 1` runs serially. A bounded queue opens only that many Sessions at once, regardless of corpus size. Each historical Session goes through the normal locked, validated publication path to create a V4 successor beside its unchanged source files. Existing V4 Sessions are opened read-only; rerunning does not reconvert them. The script makes no model requests and does not change conversion or refusal rules.
The terminal reports each Session's selected file, version, progress, outcome, and elapsed time. Individual errors do not stop later Sessions. The final summary lists every failure and the full diagnostic log under the system temporary directory; any failure returns a nonzero exit status. It also prints JSON and saves the same report as `summary.json` beside `migration.log`: counts by source version and outcome, grouped failure reasons, per-input diagnostics, runtime details, and both report paths. Known diagnostics expose event types, unexpected members, child-log involvement, and sequence numbers; unrecognized errors retain their messages without inferred causes. Include these reports when reporting a migration problem. Sessions converted during this run remain distinct from those already at V4.
@@ -127,7 +127,7 @@ git diff --check
pnpm run migrate:sessions-to-v4
```
默认根目录是 `~/.dsh/sessions`。可用 `--sessions-dir /path/to/sessions-copy` 指定其他日志集,或用 `--help` 查看用法。默认并发数取可用 CPU 数且最多为 16;`--jobs N` 接受任意正安全整数,专家用户可指定更大的值,`--jobs 1` 则串行运行。有界队列只同时打开指定数量的 Session,不随日志集大小增加。每个历史 Session 都通过正常的加锁、校验和发布流程,在未修改的源文件旁创建 V4 后继。已有 V4 Session 仅以只读方式打开;重复运行不会重新转换它们。脚本明确选择 JSONL 存储,因此即使应用默认使用 SQLite,也会发布 V4 JSONL 后继文件。它不将 Session 导入 SQLite,不发起模型请求,也不改变转换或拒绝规则。
默认根目录是 `~/.dsh/sessions`。可用 `--sessions-dir /path/to/sessions-copy` 指定其他日志集,或用 `--help` 查看用法。默认并发数取可用 CPU 数且最多为 16;`--jobs N` 接受任意正安全整数,专家用户可指定更大的值,`--jobs 1` 则串行运行。有界队列只同时打开指定数量的 Session,不随日志集大小增加。每个历史 Session 都通过正常的加锁、校验和发布流程,在未修改的源文件旁创建 V4 后继。已有 V4 Session 仅以只读方式打开;重复运行不会重新转换它们。脚本不发起模型请求,也不改变转换或拒绝规则。
终端逐个报告 Session 选中的文件、版本、进度、结果和耗时。单个错误不会阻止后续 Session。最终摘要列出全部失败项及系统临时目录中的完整诊断日志;存在任何失败时返回非零退出状态。同时打印 JSON,并把相同报告保存为 `migration.log` 旁的 `summary.json`:包含按源版本和结果统计的数量、失败原因分组、逐项诊断、运行时信息和两份报告路径。已知诊断提取事件类型、非预期字段、是否涉及子日志及序号;未知错误保留消息,不推断原因。报告迁移问题时,请附上这些报告。本次转换成功的 Session 与运行前已为 V4 的 Session 分开统计。
+3 -3
View File
@@ -73,9 +73,9 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
+3 -3
View File
@@ -75,9 +75,9 @@
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
| `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` |
| `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - |
| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` |
+3 -8
View File
@@ -414,7 +414,6 @@ flowchart TD
pkg_session_log_deepseek["session-log-deepseek"]
pkg_session_persistence["session-persistence"]
pkg_session_persistence_jsonl["session-persistence-jsonl"]
pkg_session_persistence_sqlite["session-persistence-sqlite"]
pkg_session_projection["session-projection"]
pkg_session_projection_cache["session-projection-cache"]
pkg_session_stats["session-stats"]
@@ -566,6 +565,8 @@ flowchart TD
pkg_subprocess_local --> pkg_timeout
pkg_otel --> pkg_session
pkg_remote_mock --> pkg_typert_protocol
pkg_session_snapshot --> pkg_http_proxy
pkg_session_snapshot --> pkg_session
pkg_fs --> pkg_llm
pkg_fs --> pkg_sandbox
pkg_skill_office --> pkg_skill
@@ -601,8 +602,6 @@ flowchart TD
pkg_sandbox_windows_acl --> pkg_subprocess
pkg_session_persistence_jsonl --> pkg_session
pkg_session_persistence_jsonl --> pkg_session_persistence
pkg_session_persistence_sqlite --> pkg_session
pkg_session_persistence_sqlite --> pkg_session_persistence
pkg_session_projection_cache --> pkg_session
pkg_session_projection_cache --> pkg_session_projection
pkg_session_projection_cache --> pkg_storage_domain
@@ -614,9 +613,6 @@ flowchart TD
pkg_session_turn_outline --> pkg_session_projection
pkg_shell --> pkg_sandbox
pkg_shell --> pkg_subprocess
pkg_session_snapshot --> pkg_http_proxy
pkg_session_snapshot --> pkg_session
pkg_session_snapshot --> pkg_session_persistence
pkg_workspace --> pkg_session
pkg_workspace --> pkg_session_persistence
pkg_workspace --> pkg_storage
@@ -1776,6 +1772,7 @@ flowchart TD
| [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) |
| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) |
| [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) |
| [`fs`](../packages/fs/fs) | `fs` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) |
| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) |
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
@@ -1793,12 +1790,10 @@ flowchart TD
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
| [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`shell`](../packages/shell/shell) | `shell` | [`sandbox`](../packages/sandbox/sandbox), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`workspace`](../packages/workspace/workspace) | `workspace` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) |
| [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`atomic-write`](../packages/util/atomic-write), [`attachment`](../packages/attachment/attachment), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
| [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`attachment`](../packages/attachment/attachment), [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`fs`](../packages/fs/fs), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
+3 -8
View File
@@ -416,7 +416,6 @@ flowchart TD
pkg_session_log_deepseek["session-log-deepseek"]
pkg_session_persistence["session-persistence"]
pkg_session_persistence_jsonl["session-persistence-jsonl"]
pkg_session_persistence_sqlite["session-persistence-sqlite"]
pkg_session_projection["session-projection"]
pkg_session_projection_cache["session-projection-cache"]
pkg_session_stats["session-stats"]
@@ -568,6 +567,8 @@ flowchart TD
pkg_subprocess_local --> pkg_timeout
pkg_otel --> pkg_session
pkg_remote_mock --> pkg_typert_protocol
pkg_session_snapshot --> pkg_http_proxy
pkg_session_snapshot --> pkg_session
pkg_fs --> pkg_llm
pkg_fs --> pkg_sandbox
pkg_skill_office --> pkg_skill
@@ -603,8 +604,6 @@ flowchart TD
pkg_sandbox_windows_acl --> pkg_subprocess
pkg_session_persistence_jsonl --> pkg_session
pkg_session_persistence_jsonl --> pkg_session_persistence
pkg_session_persistence_sqlite --> pkg_session
pkg_session_persistence_sqlite --> pkg_session_persistence
pkg_session_projection_cache --> pkg_session
pkg_session_projection_cache --> pkg_session_projection
pkg_session_projection_cache --> pkg_storage_domain
@@ -616,9 +615,6 @@ flowchart TD
pkg_session_turn_outline --> pkg_session_projection
pkg_shell --> pkg_sandbox
pkg_shell --> pkg_subprocess
pkg_session_snapshot --> pkg_http_proxy
pkg_session_snapshot --> pkg_session
pkg_session_snapshot --> pkg_session_persistence
pkg_workspace --> pkg_session
pkg_workspace --> pkg_session_persistence
pkg_workspace --> pkg_storage
@@ -1778,6 +1774,7 @@ flowchart TD
| [`subprocess-local`](../packages/subprocess/subprocess-local) | `subprocess` | [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) |
| [`otel`](../packages/telemetry/otel) | `telemetry` | [`session`](../packages/core/session) |
| [`remote-mock`](../packages/test-support/remote-mock) | `test-support` | [`typert-protocol`](../packages/typert/protocol) |
| [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session) |
| [`fs`](../packages/fs/fs) | `fs` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) |
| [`skill-office`](../packages/skill/skill-office) | `skill` | [`skill`](../packages/skill/skill) |
| [`web-fetch-http`](../packages/web/web-fetch-http) | `web` | [`timeout`](../packages/util/timeout), [`web`](../packages/web/web) |
@@ -1795,12 +1792,10 @@ flowchart TD
| [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) |
| [`sandbox-windows-acl`](../packages/sandbox/sandbox-windows-acl) | `sandbox` | [`skill`](../packages/skill/skill), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite) | `session` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`session-projection-cache`](../packages/session/session-projection-cache) | `session` | [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain) |
| [`session-stats`](../packages/session/session-stats) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`session-turn-outline`](../packages/session/session-turn-outline) | `session` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection) |
| [`shell`](../packages/shell/shell) | `shell` | [`sandbox`](../packages/sandbox/sandbox), [`subprocess`](../packages/subprocess/subprocess) |
| [`session-snapshot`](../packages/test-support/session-snapshot) | `test-support` | [`http-proxy`](../packages/util/http-proxy), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence) |
| [`workspace`](../packages/workspace/workspace) | `workspace` | [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`storage`](../packages/storage/storage), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol) |
| [`llm-deepseek`](../packages/llm/llm-deepseek) | `llm` | [`anonymous-user-id`](../packages/identity/anonymous-user-id), [`atomic-write`](../packages/util/atomic-write), [`attachment`](../packages/attachment/attachment), [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
| [`llm-pi-ai`](../packages/llm/llm-pi-ai) | `llm` | [`attachment`](../packages/attachment/attachment), [`authorization`](../packages/credentials/authorization), [`credentials`](../packages/credentials/credentials), [`fs`](../packages/fs/fs), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`timeout`](../packages/util/timeout) |
+2 -4
View File
@@ -392,10 +392,8 @@ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions
/**
* Open an existing stored session.
*
* `read` does not retain write ownership and works while another handle (or process)
* holds write ownership in the selected backend. A legacy import may wait for
* the old writer to release ownership before opening the read handle.
* `write` atomically claims single-writer ownership;
* `read` never takes ownership and works while another handle (or process)
* holds write ownership. `write` atomically claims single-writer ownership;
* an existing active owner rejects.
* @param id - the stored session to open.
* @param access - `read` or `write`.
+2 -4
View File
@@ -392,10 +392,8 @@ abstract create(header: SessionHeader, options?: SessionPersistenceCreateOptions
/**
* Open an existing stored session.
*
* `read` does not retain write ownership and works while another handle (or process)
* holds write ownership in the selected backend. A legacy import may wait for
* the old writer to release ownership before opening the read handle.
* `write` atomically claims single-writer ownership;
* `read` never takes ownership and works while another handle (or process)
* holds write ownership. `write` atomically claims single-writer ownership;
* an existing active owner rejects.
* @param id - the stored session to open.
* @param access - `read` or `write`.
@@ -1,16 +0,0 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.3/session-sqlite-storage/guide.md
/:
en: 891a19cef1fea509
zh: 5b0dc9781c88a7c2
/opt-into-sqlite-session-storage:
en: acd0b773d78139b1
zh: 470c0c0ec82406b5
/opt-into-sqlite-session-storage/change:
en: c75cbe9149b426e9
zh: 49761e99ce666204
/opt-into-sqlite-session-storage/migration:
en: 6673f999a9827b56
zh: 93a27bfc276c7c33
@@ -1,21 +0,0 @@
---
kind: upgrade-guide
description: "Opting into SQLite imports Session history; retained JSONL files no longer contain new events after import."
---
# Opt into SQLite Session storage
English | [中文](guide.zh.md)
## Change
The `@deepseek-ai/dsh-session-persistence-jsonl` plugin previously wrote Session history to per-session JSONL files. Its `storage` option defaults to `jsonl`. Explicitly setting `storage: sqlite` writes to `<root>/.segments/sessions.sqlite`. First open of supported JSONL history, including read-only open, imports it transactionally and preserves the original files. Subsequent events go to SQLite. Concurrent readers wait for import and then read SQLite alongside its writer.
External tools that read JSONL directly will no longer see new events. Retained JSONL does not provide fallback or downgrade for imported Sessions. Browser Workers explicitly select `storage: jsonl` and `compression: none`.
## Migration
1. Stop all applications writing to the configured `root` and back up the complete root before upgrading. Keep the database, its SQLite sidecar files, routing records, and retained JSONL together in later backups; copy them with writers stopped.
2. Keep the existing plugin and `root` configuration to use SQLite. The `compression` setting controls legacy JSONL encoding, not SQLite. Update external history readers to use the [Session persistence service](../../../../packages/session/session-persistence/README.md).
3. To enable SQLite, explicitly set `storage: sqlite` in the plugin's `config` before opening Sessions. Omit `storage` or select `storage: jsonl` to keep JSONL output without importing history. To change storage after import, use a separate root for new Sessions; retained JSONL lacks later SQLite events.
4. Open an existing Session and confirm its history is readable, append a new turn, and reopen it to confirm that turn persists. For SQLite, confirm the database exists under `.segments`; do not use unchanged legacy JSONL as evidence of lost writes.
@@ -1,21 +0,0 @@
---
kind: upgrade-guide
description: "显式启用 SQLite 会导入 Session 历史;导入后,保留的 JSONL 文件不再包含新事件。"
---
# 显式启用 SQLite Session 存储
[English](guide.md) | 中文
## 变更
`@deepseek-ai/dsh-session-persistence-jsonl` 插件此前将 Session 历史写入每个 Session 的 JSONL 文件。`storage` 选项默认值为 `jsonl`。显式设置 `storage: sqlite` 后,写入 `<root>/.segments/sessions.sqlite`。首次打开支持的 JSONL 历史(包括只读打开)会在事务内导入并保留原文件。后续事件写入 SQLite。并发读者等待导入,然后与写入者并存读取 SQLite。
直接读取 JSONL 的外部工具将无法看到新事件。保留的 JSONL 不为已导入 Session 提供回退或降级。浏览器 Worker 明确选择 `storage: jsonl` 和 `compression: none`。
## 迁移
1. 升级前,停止所有写入配置 `root` 的应用,并备份完整根目录。后续备份一起保留数据库、SQLite 辅助文件、路由记录与原 JSONL;复制前停止写入者。
2. 保留现有插件与 `root` 配置即可使用 SQLite。`compression` 控制旧 JSONL 编码,不控制 SQLite。将外部历史读取工具改为使用 [Session 持久化服务](../../../../packages/session/session-persistence/README.zh.md)。
3. 如需启用 SQLite,在打开 Session 前,在插件 `config` 中显式设置 `storage: sqlite`。省略 `storage` 或选择 `storage: jsonl` 会继续输出 JSONL,不导入历史。导入后如需切换存储,为新 Session 使用独立根目录;保留的 JSONL 缺少后续 SQLite 事件。
4. 打开已有 Session,确认能读取历史,追加一个新 turn,再次打开确认该 turn 已持久化。使用 SQLite 时,确认 `.segments` 下存在数据库;不要根据旧 JSONL 未变化判断写入丢失。
+10 -10
View File
@@ -27,8 +27,8 @@ describe('ACP machine permission policy', () => {
return { agent, toolName: 'bash', callId: brandString<ToolCallId>('call-9'), ...overrides }
}
it.each(['jsonl', 'sqlite'] as const)('%s: maps the two advertised one-shot choices', async (storage) => {
harness = await makeBridgeHarness(storage)
it('maps the two advertised one-shot choices', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: maps cancellation and unknown choices without granting access', async (storage) => {
harness = await makeBridgeHarness(storage)
it('maps cancellation and unknown choices without granting access', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: fails closed when the client errors the permission request', async (storage) => {
harness = await makeBridgeHarness(storage)
it('fails closed when the client errors the permission request', async () => {
harness = await makeBridgeHarness()
const request = await ownedRequest()
harness.onPermission = () => { throw new Error('client gone') }
await expect(harness.ctx.approval.request(request)).resolves.toBe('unavailable')
})
it.each(['jsonl', 'sqlite'] as const)('%s: delegates a same-id foreign agent', async (storage) => {
harness = await makeBridgeHarness(storage)
it('delegates a same-id foreign agent', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: delegates requests that have no protocol tool-call identity', async (storage) => {
harness = await makeBridgeHarness(storage)
it('delegates requests that have no protocol tool-call identity', async () => {
harness = await makeBridgeHarness()
const request = await ownedRequest()
await expect(harness.ctx.approval.request({ agent: request.agent, toolName: request.toolName }))
.resolves.toBe('unavailable')
+110 -110
View File
@@ -40,8 +40,8 @@ describe('automation-only ACP bridge', () => {
harness = undefined
})
it.each(['jsonl', 'sqlite'] as const)('%s: advertises the standard automation controls without private metadata', async (storage) => {
harness = await makeBridgeHarness(storage)
it('advertises the standard automation controls without private metadata', async () => {
harness = await makeBridgeHarness()
const response = await harness.client.initialize({
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: { _meta: { terminal_output: true } },
@@ -59,26 +59,26 @@ describe('automation-only ACP bridge', () => {
})
})
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 })
it('advertises image prompts only with an exact capable route and attachment store', async () => {
harness = await makeBridgeHarness({ 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(storage, { imageCapable: true, attachments: false })
harness = await makeBridgeHarness({ imageCapable: true, attachments: false })
const noStore = await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
expect(noStore.agentCapabilities?.promptCapabilities?.image).toBe(false)
})
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)
it('negotiates an unsupported version and accepts the required no-op authentication call', async () => {
harness = await makeBridgeHarness()
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.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')] })
it('creates a session, emits one committed answer, and settles the prompt', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: closes one active session without affecting its neighbor', async (storage) => {
harness = await makeBridgeHarness(storage)
it('closes one active session without affecting its neighbor', async () => {
harness = await makeBridgeHarness()
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.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')] })
it('cancels a running prompt and makes its session resumable before close returns', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: shares one close operation and rejects new work while close is draining', async (storage) => {
harness = await makeBridgeHarness(storage)
it('shares one close operation and rejects new work while close is draining', async () => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const flushing: PromiseWithResolvers<void> = Promise.withResolvers()
@@ -152,8 +152,8 @@ describe('automation-only ACP bridge', () => {
await expect(Promise.all([first, second])).resolves.toEqual([{}, {}])
})
it.each(['jsonl', 'sqlite'] as const)('%s: disposes the Agent and reports an explicit close drain failure', async (storage) => {
harness = await makeBridgeHarness(storage)
it('disposes the Agent and reports an explicit close drain failure', async () => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(created.sessionId))!
@@ -164,8 +164,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(created.sessionId))).toBeUndefined()
})
it.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')] })
it('resumes a closed persisted session without replaying its history', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: materializes an empty closed session for list and resume', async (storage) => {
harness = await makeBridgeHarness(storage)
it('materializes an empty closed session for list and resume', async () => {
harness = await makeBridgeHarness()
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.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')] })
it('rejects active or wrong-workspace resume before composing another Agent', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: reserves a persisted id across concurrent resume admission', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
it('reserves a persisted id across concurrent resume admission', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: excludes a globally live session owned outside this ACP bridge', async (storage) => {
harness = await makeBridgeHarness(storage)
it('excludes a globally live session owned outside this ACP bridge', async () => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const sessionId = brandString<SessionId>('other-frontend-live')
harness.ctx.sessions.create(sessionId, { meta: { cwd: process.cwd() } })
@@ -280,8 +280,8 @@ describe('automation-only ACP bridge', () => {
expect(resume).not.toHaveBeenCalled()
})
it.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')] })
it('rejects unknown resume ids and rolls back invalid resume MCP', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: restores the deployment selection when persisted events have no request header', async (storage) => {
harness = await makeBridgeHarness(storage)
it('restores the deployment selection when persisted events have no request header', async () => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const created = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(created.sessionId))!
@@ -315,8 +315,8 @@ describe('automation-only ACP bridge', () => {
})
})
it.each(['jsonl', 'sqlite'] as const)('%s: restores a pending model selection without any request header', async (storage) => {
harness = await makeBridgeHarness(storage)
it('restores a pending model selection without any request header', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: restores an explicitly selected reasoning effort', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
it('restores an explicitly selected reasoning effort', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: lists closed persisted sessions without presentation metadata', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
it('lists closed persisted sessions without presentation metadata', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: paginates resumable sessions with an opaque deterministic cursor', async (storage) => {
harness = await makeBridgeHarness(storage, {
it('paginates resumable sessions with an opaque deterministic cursor', async () => {
harness = await makeBridgeHarness({
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((['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)
it.each([false, true])('resumes an ordinary fork with legacy parent metadata=%s', async (legacy) => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const id = brandString<SessionId>('ordinary-fork')
const writer = await harness.ctx.sessionPersistence.create({
@@ -405,8 +405,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.get(id)?.session.header.parentSession).toBe(legacy ? 'source' : undefined)
})
it.each(['jsonl', 'sqlite'] as const)('%s: filters non-resumable headers and canonical missing workspaces', async (storage) => {
harness = await makeBridgeHarness(storage)
it('filters non-resumable headers and canonical missing workspaces', async () => {
harness = await makeBridgeHarness()
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((['jsonl', 'sqlite'] as const).flatMap(storage => ([
null,
[],
['not-a-number', 'id'],
[-1, 'id'],
[1, ''],
] as const).map(decoded => ({ storage, decoded }))))('$storage: rejects malformed decoded list cursors %#', async ({ storage, decoded }) => {
harness = await makeBridgeHarness(storage)
it.each([
[null],
[[]],
[['not-a-number', 'id']],
[[-1, 'id']],
[[1, '']],
] as const)('rejects malformed decoded list cursors %#', async (decoded) => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: rejects invalid and non-canonical cursor encodings', async (storage) => {
harness = await makeBridgeHarness(storage)
it('rejects invalid and non-canonical cursor encodings', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: rolls back new and resume when configuration discovery fails', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('persisted')] })
it('rolls back new and resume when configuration discovery fails', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('propagates non-MCP Agent factory failures and non-config selection failures', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: lists and resumes persisted sessions after an equivalent process restart', async (storage) => {
it('lists and resumes persisted sessions after an equivalent process restart', async () => {
const persistenceRoot = await mkdtemp(join(tmpdir(), 'dsh-acp-restart-'))
try {
harness = await makeBridgeHarness(storage, { persistenceRoot, script: [textResponse('before restart')] })
harness = await makeBridgeHarness({ 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(storage, { persistenceRoot, script: [textResponse('after restart')] })
harness = await makeBridgeHarness({ 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.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')] })
it('discovers and selects a session model through standard config options', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: publishes complete config options when adapter topology changes', async (storage) => {
harness = await makeBridgeHarness(storage)
it('publishes complete config options when adapter topology changes', async () => {
harness = await makeBridgeHarness()
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.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')] })
it('does not let hung topology discovery block prompt completion or close', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: publishes recoverable options when the selected adapter disappears', async (storage) => {
harness = await makeBridgeHarness(storage)
it('publishes recoverable options when the selected adapter disappears', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: selects an advertised reasoning effort for the next turn', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('reasoned')] })
it('selects an advertised reasoning effort for the next turn', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: rejects unknown config choices without changing the selected route', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('unchanged')] })
it('rejects unknown config choices without changing the selected route', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: serializes concurrent standard config changes in receive order', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('plain')] })
it('serializes concurrent standard config changes in receive order', async () => {
harness = await makeBridgeHarness({ 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.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')] })
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')] })
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.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')] })
it('applies a mid-turn model change to the following step', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('mounts a standard stdio MCP server inside the created session', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: mounts a standard Streamable HTTP MCP server with request headers', async (storage) => {
it('mounts a standard Streamable HTTP MCP server with request headers', async () => {
const fixture = await startHttpMcpFixture()
try {
harness = await makeBridgeHarness(storage, { script: [textResponse('used HTTP MCP')] })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: allows the same MCP server namespace in independent sessions', async (storage) => {
harness = await makeBridgeHarness(storage)
it('allows the same MCP server namespace in independent sessions', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: validates standard MCP declarations before publishing an Agent', async (storage) => {
harness = await makeBridgeHarness(storage)
it('validates standard MCP declarations before publishing an Agent', async () => {
harness = await makeBridgeHarness()
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.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')] })
it('reconnects requested MCP servers when resuming a closed session', async () => {
harness = await makeBridgeHarness({ 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.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 } })
it('leaves absent agent targets for request listeners to supply', async () => {
harness = await makeBridgeHarness({ config: { provider: undefined, model: undefined } })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))?.options).toEqual({})
})
it.each(['jsonl', 'sqlite'] as const)('%s: uses a recorded selection when ACP has no initial route', async (storage) => {
harness = await makeBridgeHarness(storage, {
it('uses a recorded selection when ACP has no initial route', async () => {
harness = await makeBridgeHarness({
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.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')] })
it('concatenates text blocks without exposing protocol framing to the model', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('admits mixed text/image prompts in wire order and logs references only', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('rejects a malformed image batch atomically and frees the prompt slot', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: reports durable image write failures as internal prompt failures', async (storage) => {
harness = await makeBridgeHarness(storage, { imageCapable: true })
it('reports durable image write failures as internal prompt failures', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('renders the deployment persona for an ACP-created agent', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: requires one absolute primary workspace', async (storage) => {
harness = await makeBridgeHarness(storage)
it('requires one absolute primary workspace', async () => {
harness = await makeBridgeHarness()
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.each(['jsonl', 'sqlite'] as const)('%s: rejects empty and unadvertised image prompts before a turn starts', async (storage) => {
harness = await makeBridgeHarness(storage)
it('rejects empty and unadvertised image prompts before a turn starts', async () => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
@@ -1011,8 +1011,8 @@ describe('automation-only ACP bridge', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))?.session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false)
})
it.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')] })
it('renders baseline resource links as textual references in the user message', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: rejects prompts for unknown sessions and ignores unknown cancellation', async (storage) => {
harness = await makeBridgeHarness(storage)
it('rejects prompts for unknown sessions and ignores unknown cancellation', async () => {
harness = await makeBridgeHarness()
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
await expect(harness.client.prompt({ sessionId: 'missing', prompt: [{ type: 'text', text: 'go' }] }))
.rejects.toThrow(/unknown session/)
+21 -21
View File
@@ -18,8 +18,8 @@ describe('ACP connection ownership', () => {
await bridge?.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: disposal cancels a running prompt and awaits agent teardown', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('disposal cancels a running prompt and awaits agent teardown', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -32,9 +32,9 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it.each(['jsonl', 'sqlite'] as const)('%s: disposal drains asynchronous assistant image delivery before releasing sessions', async (storage) => {
it('disposal drains asynchronous assistant image delivery before releasing sessions', async () => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ script })
const ref = await harness.attachments!.saveImage({ data: Uint8Array.of(4), mediaType: 'image/png' })
script.push([
{ type: 'block-start', index: 0, blockType: 'image' },
@@ -63,8 +63,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it.each(['jsonl', 'sqlite'] as const)('%s: drains continuable subagents before disposing its own sessions', async (storage) => {
harness = await makeBridgeHarness(storage)
it('drains continuable subagents before disposing its own sessions', async () => {
harness = await makeBridgeHarness()
const order: string[] = []
let drainedParents: readonly Agent[] = []
// A continuable Activation outlives the turn that started it, so the bridge
@@ -88,8 +88,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it.each(['jsonl', 'sqlite'] as const)('%s: cancels its own prompt before awaiting the descendant drain', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('cancels its own prompt before awaiting the descendant drain', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
const order: string[] = []
const release = Promise.withResolvers<undefined>()
harness.ctx.provide('subagents', {
@@ -124,8 +124,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it.each(['jsonl', 'sqlite'] as const)('%s: reports a failed continuable drain and still disposes its sessions', async (storage) => {
harness = await makeBridgeHarness(storage)
it('reports a failed continuable drain and still disposes its sessions', async () => {
harness = await makeBridgeHarness()
const warnings: string[] = []
harness.ctx.logger.warn = (message: string) => { warnings.push(message) }
harness.ctx.provide('subagents', {
@@ -141,8 +141,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it.each(['jsonl', 'sqlite'] as const)('%s: awaits every owned session disposal and reports nested failure reasons', async (storage) => {
harness = await makeBridgeHarness(storage)
it('awaits every owned session disposal and reports nested failure reasons', async () => {
harness = await makeBridgeHarness()
const create = harness.ctx.agents.create.bind(harness.ctx.agents)
const releaseSecond = Promise.withResolvers<undefined>()
const warnings: string[] = []
@@ -194,8 +194,8 @@ describe('ACP connection ownership', () => {
await disposed.dispose().catch(() => undefined)
})
it.each(['jsonl', 'sqlite'] as const)('%s: an ACP-only reload rejects new sessions before creating an orphan', async (storage) => {
harness = await makeBridgeHarness(storage)
it('an ACP-only reload rejects new sessions before creating an orphan', async () => {
harness = await makeBridgeHarness()
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((['jsonl', 'sqlite'] as const).flatMap(storage => ([
it.each([
['a client disconnect', 'closeClientTransport'],
['a failed client transport', 'abortClientTransport'],
] 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'] })
] as const)('%s disposes its session without plugin disposal', async (_name, disconnect) => {
harness = await makeBridgeHarness({ script: ['hang'] })
const bridge = harness
const create = bridge.ctx.agents.create.bind(bridge.ctx.agents)
const disposalStarted = Promise.withResolvers<undefined>()
@@ -257,8 +257,8 @@ describe('ACP connection ownership', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: disconnect and plugin disposal share one quiescence boundary', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('disconnect and plugin disposal share one quiescence boundary', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -270,8 +270,8 @@ describe('ACP connection ownership', () => {
expect(harness.ctx.agents.get(brandString<SessionId>(sessionId))).toBeUndefined()
})
it.each(['jsonl', 'sqlite'] as const)('%s: disposing a session-less bridge is idempotent', async (storage) => {
harness = await makeBridgeHarness(storage)
it('disposing a session-less bridge is idempotent', async () => {
harness = await makeBridgeHarness()
await Promise.all([harness.acpFiber.dispose(), harness.acpFiber.dispose()])
expect(harness.ctx.agents.list()).toHaveLength(0)
})
+10 -10
View File
@@ -34,8 +34,8 @@ describe('ACP automation output boundary', () => {
harness = undefined
})
it.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')] })
it('emits committed reasoning, generic tool lifecycle, usage, and final text in order', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: ignores events from agents the bridge does not own', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('foreign')] })
it('ignores events from agents the bridge does not own', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('delivers output from a bridge-owned session driven by another in-process producer', async () => {
harness = await makeBridgeHarness({ script: [textResponse('external')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -117,8 +117,8 @@ describe('ACP automation output boundary', () => {
expect('messageId' in harness.updates[0]!).toBe(true)
})
it.each(['jsonl', 'sqlite'] as const)('%s: contains output conversion failure outside an ACP prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [[
it('contains output conversion failure outside an ACP prompt', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('settles the prompt normally when the client rejects update notifications', async () => {
harness = await makeBridgeHarness({ script: [textResponse('answer')] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const { sessionId } = await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })
harness.onSessionUpdateError = () => {}
+2 -2
View File
@@ -220,7 +220,7 @@ export interface BridgeHarness {
type AcpConfigOverrides = { [K in keyof AcpConfig]?: AcpConfig[K] | undefined }
/** Build the bridge and a connected SDK client over cross-wired byte streams. */
export async function makeBridgeHarness(storage: 'jsonl' | 'sqlite', options: {
export async function makeBridgeHarness(options: {
script?: (StreamChunk[] | 'hang')[]
config?: AcpConfigOverrides
persona?: string
@@ -233,7 +233,7 @@ export async function makeBridgeHarness(storage: 'jsonl' | 'sqlite', 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, { storage, root: persistenceRoot, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
await ctx.plugin(TokenMeter)
if (options.attachments !== false) await ctx.plugin(MemoryAttachmentStore)
const loopFiber = await ctx.plugin(AgentLoop, { agents: [] })
+8 -8
View File
@@ -23,8 +23,8 @@ describe('ACP multi-session isolation', () => {
harness = undefined
})
it.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')] })
it('demultiplexes concurrent answers by session id', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: cancels one session without affecting another', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', textResponse('B done')] })
it('cancels one session without affecting another', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: enforces one in-flight prompt independently for each session', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', 'hang'] })
it('enforces one in-flight prompt independently for each session', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: drains every live session on bridge disposal', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang', 'hang'] })
it('drains every live session on bridge disposal', async () => {
harness = await makeBridgeHarness({ script: ['hang', 'hang'] })
await harness.client.initialize({ protocolVersion: PROTOCOL_VERSION, clientCapabilities: {} })
const a = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
const b = (await harness.client.newSession({ cwd: process.cwd(), mcpServers: [] })).sessionId
+80 -80
View File
@@ -69,17 +69,17 @@ describe('ACP prompt lifecycle', () => {
harness = undefined
})
it.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')] })
it('reports a max-token turn without losing its committed text', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: delivers a committed assistant image as verified ACP base64', async (storage) => {
it('delivers a committed assistant image as verified ACP base64', async () => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: preserves committed text/image/text order on the ACP wire', async (storage) => {
it('preserves committed text/image/text order on the ACP wire', async () => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: does not settle a prompt before ordered output delivery drains', async (storage) => {
it('does not settle a prompt before ordered output delivery drains', async () => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: fails prompt delivery when a committed image attachment is missing', async (storage) => {
it('fails prompt delivery when a committed image attachment is missing', async () => {
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(storage, { script: [[
harness = await makeBridgeHarness({ 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.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')] })
it('rejects a failed turn and never publishes its partial chunks', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('rejects an ordinary plugin failure through the same prompt boundary', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('rejects a turn-start failure before the prompt is claimed', async () => {
harness = await makeBridgeHarness({ script: [textResponse('must not run')] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
const append = agent.session.append.bind(agent.session)
@@ -208,8 +208,8 @@ describe('ACP prompt lifecycle', () => {
vi.restoreAllMocks()
})
it.each((['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')] })
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')] })
const sessionId = await newSession(harness)
const parent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
const append = parent.session.append.bind(parent.session)
@@ -235,8 +235,8 @@ describe('ACP prompt lifecycle', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: settles even when an earlier turn observer throws', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
it('settles even when an earlier turn observer throws', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('correlates the owning prompt when a synchronous injection joins its first step', async () => {
harness = await makeBridgeHarness({ script: [textResponse('real answer')] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
let injected = false
@@ -262,8 +262,8 @@ describe('ACP prompt lifecycle', () => {
await vi.waitFor(() => { expect(messageText(harness!)).toBe('real answer') })
})
it.each(['jsonl', 'sqlite'] as const)('%s: ignores an autonomous message turn while correlating the client turn', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('ignores an autonomous message turn while correlating the client turn', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
let autonomousStarted!: () => void
@@ -289,8 +289,8 @@ describe('ACP prompt lifecycle', () => {
await expect(prompt).resolves.toEqual({ stopReason: 'cancelled' })
})
it.each(['jsonl', 'sqlite'] as const)('%s: correlates a prompt whose step history is replaced', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('rewritten answer')] })
it('correlates a prompt whose step history is replaced', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: frees the prompt slot when the agent rejects the send synchronously', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
it('frees the prompt slot when the agent rejects the send synchronously', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: permits only one in-flight prompt per session', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('permits only one in-flight prompt per session', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
const sessionId = await newSession(harness)
const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] })
await vi.waitFor(() => { expect(harness!.ctx.agents.get(brandString<SessionId>(sessionId))?.status).toBe('running') })
@@ -328,8 +328,8 @@ describe('ACP prompt lifecycle', () => {
await expect(first).resolves.toEqual({ stopReason: 'cancelled' })
})
it.each(['jsonl', 'sqlite'] as const)('%s: routes JSON-RPC request cancellation through the prompt cancellation path', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('routes JSON-RPC request cancellation through the prompt cancellation path', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: cancels a prompt request whose JSON-RPC signal is already aborted', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
it('cancels a prompt request whose JSON-RPC signal is already aborted', async () => {
harness = await makeBridgeHarness({ 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.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: [] })
it('reserves the prompt slot during image admission and cancels without a late followup', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -385,8 +385,8 @@ describe('ACP prompt lifecycle', () => {
expect(events.some(event => event.type === 'user/message' || event.type === 'turn/start')).toBe(false)
})
it.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'] })
it('does not cancel unrelated Agent work while its prompt is still in admission', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: ['hang'] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -416,8 +416,8 @@ describe('ACP prompt lifecycle', () => {
await agent.whenIdle()
})
it.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')] })
it('does not attribute an unrelated Agent failure during prompt admission', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [textResponse('answer')] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -449,8 +449,8 @@ describe('ACP prompt lifecycle', () => {
expect(messageText(harness)).toBe('answer')
})
it.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: [] })
it('does not queue admitted content into an agent retired during storage', async () => {
harness = await makeBridgeHarness({ imageCapable: true, script: [] })
const validationStarted = Promise.withResolvers<undefined>()
const releaseValidation = Promise.withResolvers<undefined>()
harness.attachments!.beforeValidate = () => {
@@ -472,8 +472,8 @@ describe('ACP prompt lifecycle', () => {
expect(harness.adapter.requests).toEqual([])
})
it.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: [] })
it('cancels after image storage completes before admission receives the result', async () => {
harness = await makeBridgeHarness({ 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.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: [] })
it('wraps an unexpected same-process followup failure and frees the prompt slot', async () => {
harness = await makeBridgeHarness({ script: [] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
vi.spyOn(agent, 'followup').mockImplementationOnce(() => { throw new Error('synthetic followup failure') })
@@ -502,8 +502,8 @@ describe('ACP prompt lifecycle', () => {
.rejects.toThrow(/prompt was not queued: synthetic followup failure/)
})
it.each(['jsonl', 'sqlite'] as const)('%s: cancels a running turn and records the aborted outcome', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('cancels a running turn and records the aborted outcome', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
const sessionId = await newSession(harness)
const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -515,8 +515,8 @@ describe('ACP prompt lifecycle', () => {
.toEqual({ kind: 'aborted', reason: { kind: 'user' } })
})
it.each(['jsonl', 'sqlite'] as const)('%s: settles a hook-cancelled turn as end_turn, not cancelled', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('settles a hook-cancelled turn as end_turn, not cancelled', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
const sessionId = await newSession(harness)
const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'go' }] })
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
@@ -527,8 +527,8 @@ describe('ACP prompt lifecycle', () => {
await expect(prompt).resolves.toEqual({ stopReason: 'end_turn' })
})
it.each(['jsonl', 'sqlite'] as const)('%s: cancels autonomous running work without an in-flight prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: ['hang'] })
it('cancels autonomous running work without an in-flight prompt', async () => {
harness = await makeBridgeHarness({ script: ['hang'] })
const sessionId = await newSession(harness)
const agent = harness.ctx.agents.get(brandString<SessionId>(sessionId))!
agent.followup(createUserMessage({
@@ -546,8 +546,8 @@ describe('ACP prompt lifecycle', () => {
.toEqual({ kind: 'aborted', reason: { kind: 'user' } })
})
it.each(['jsonl', 'sqlite'] as const)('%s: an idle cancel does not affect the following prompt', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [textResponse('answer')] })
it('an idle cancel does not affect the following prompt', async () => {
harness = await makeBridgeHarness({ 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.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')] })
it('a late end from a cancelled turn cannot settle the next prompt', async () => {
harness = await makeBridgeHarness({ script: ['hang', textResponse('next')] })
const sessionId = await newSession(harness)
const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'one' }] })
await vi.waitFor(() => { expect(harness!.ctx.agents.get(brandString<SessionId>(sessionId))?.status).toBe('running') })
@@ -570,8 +570,8 @@ describe('ACP prompt lifecycle', () => {
await vi.waitFor(() => { expect(messageText(harness!)).toBe('partialnext') })
})
it.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')] })
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')] })
// 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((['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: [
it.each(['completed', 'error'] as const)('waits for descendants and reports the later %s summary turn', async (outcome) => {
harness = await makeBridgeHarness({ script: [
textResponse('waiting'),
outcome === 'completed' ? textResponse('summary') : errorResponse('summary failed'),
] })
@@ -615,8 +615,8 @@ describe('ACP prompt lifecycle', () => {
await observed
})
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')] })
it('cancels the child wait without closing the session to its next prompt', async () => {
harness = await makeBridgeHarness({ script: [textResponse('waiting'), textResponse('next')] })
const sessionId = await newSession(harness)
const waiting = Promise.withResolvers<undefined>()
const children = Promise.withResolvers<boolean>()
@@ -636,8 +636,8 @@ describe('ACP prompt lifecycle', () => {
expect(messageText(harness)).toBe('waitingnext')
})
it.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: [
it('releases a cancelled prompt before a late child message finishes and permits another delegation', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: settles an initially cancelled prompt after its output without waiting for a later summary', async (storage) => {
it('settles an initially cancelled prompt after its output without waiting for a later summary', async () => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: waits for cancelled maintenance cleanup without following its later summary', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [
it('waits for cancelled maintenance cleanup without following its later summary', async () => {
harness = await makeBridgeHarness({ 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((['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) => {
it.each([false, true])('waits for the later summary output and reports its delivery failure (%s)', async (fail) => {
const script: StreamChunk[][] = [textResponse('waiting')]
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: includes root work started during output draining and permits the next prompt to delegate', async (storage) => {
it('includes root work started during output draining and permits the next prompt to delegate', async () => {
const script: StreamChunk[][] = []
harness = await makeBridgeHarness(storage, { script })
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: a failed turn with no retry still rejects', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [errorResponse('terminal boom')] })
it('a failed turn with no retry still rejects', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: a pre-step-rejected prompt settles instead of hanging', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
it('a pre-step-rejected prompt settles instead of hanging', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: cancels a prompt removed before its turn claims it', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
it('cancels a prompt removed before its turn claims it', async () => {
harness = await makeBridgeHarness({ 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.each(['jsonl', 'sqlite'] as const)('%s: rejects a prompt when pre-step fails inside its open turn', async (storage) => {
harness = await makeBridgeHarness(storage, { script: [] })
it('rejects a prompt when pre-step fails inside its open turn', async () => {
harness = await makeBridgeHarness({ script: [] })
harness.ctx.on('agent/pre-step', async () => { throw new Error('pre-step exploded') })
const sessionId = await newSession(harness)
@@ -42,7 +42,7 @@ afterEach(async () => {
}
})
async function createHarness(storage: 'jsonl' | 'sqlite', withPersistence = true) {
async function harness(withPersistence = true) {
const root = await mkdtemp(join(tmpdir(), 'dsh-projection-discovery-'))
roots.push(root)
const ctx = new Context()
@@ -53,7 +53,7 @@ async function createHarness(storage: 'jsonl' | 'sqlite', withPersistence = true
await ctx.sessionProjections.register(subagentCatalogProjectionDefinition)
await ctx.sessionProjections.register(titleProjectionDefinition)
if (withPersistence) {
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'logs'), compression: 'none', storage })
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'logs'), compression: 'none' })
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 createHarness(storage: 'jsonl' | 'sqlite', withPersistence = true
return { ctx, root, controller }
}
type Harness = Awaited<ReturnType<typeof createHarness>>
type Harness = Awaited<ReturnType<typeof harness>>
async function stored(
fixture: Harness,
@@ -152,8 +152,7 @@ async function seedCache(
return { path, bytes }
}
describe.each(['jsonl', 'sqlite'] as const)('Session projection discovery (%s)', (storage) => {
const harness = (withPersistence = true) => createHarness(storage, withPersistence)
describe('Session projection discovery', () => {
it('defers V3 migration without reading child bodies or publishing a successor', async () => {
const fixture = await harness()
const parent = await stored(fixture, brandString<SessionId>('parent'), {}, 3)
@@ -247,27 +246,50 @@ describe.each(['jsonl', 'sqlite'] as const)('Session projection discovery (%s)',
expect(fixture.ctx.agents.get(parent.header.id)).toBeUndefined()
})
it('reads historical projections and publishes migration through the selected backend without a live Session', async () => {
it('reports read-prepared historical files as migration-required until a successor is published', async () => {
const fixture = await harness()
const parent = await stored(fixture, brandString<SessionId>('prepared-cold'), {}, 3)
using observation = await fixture.ctx.sessionQuery.observeSession(parent.header.id)
const observation = await fixture.ctx.sessionQuery.observeSession(parent.header.id)
observation[Symbol.dispose]()
const open = vi.spyOn(fixture.ctx.sessionPersistence, 'open').mockRejectedValue(new Error('unexpected body reread'))
expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({
formatStatus: storage === 'sqlite' ? 'current' : 'migration-required',
formatStatus: '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 })
.resolves.toEqual({ kind: 'migration-required', values: {} })
expect(open).not.toHaveBeenCalled()
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(storage === 'sqlite'
? ['session.v3.jsonl']
: ['session.v3.jsonl', `session.v${SESSION_FORMAT_VERSION}.jsonl`])
expect(await readdir(dirname(parent.path))).toEqual(['session.v3.jsonl'])
})
it('reads sequenced projections after write publication replaces the disk format status', async () => {
const fixture = await harness()
const parent = await stored(fixture, brandString<SessionId>('published-cold'), {}, 3)
using observation = await fixture.ctx.sessionQuery.observeSession(parent.header.id)
const expected = observation.projections
const signal = new AbortController().signal
await expect(fixture.controller.projections({ sessionId: parent.header.id }, signal))
.resolves.toEqual({ kind: 'migration-required', values: {} })
const writer = await fixture.ctx.sessionPersistence.open(parent.header.id, 'write')
try {
await writer.flush()
} finally {
await writer.close()
}
expect(await fixture.ctx.sessionPersistence.stat(parent.header.id)).toMatchObject({
formatStatus: 'current',
})
await expect(fixture.controller.projections({ sessionId: parent.header.id }, signal))
.resolves.toEqual({ kind: 'sequenced', ...expected })
expect(fixture.ctx.sessions.get(parent.header.id)).toBeUndefined()
expect(await readFile(parent.path, 'utf8')).toBe(parent.bytes)
// POSIX retains the write-lock inode after close; Windows uses a semaphore.
expect((await readdir(dirname(parent.path))).filter(name => name !== 'session.lock').sort())
.toEqual(['session.v3.jsonl', `session.v${SESSION_FORMAT_VERSION}.jsonl`].sort())
})
it('reports unsupported current-format events instead of deferring migration', async () => {
@@ -17,7 +17,6 @@
- id: session-persistence-jsonl
config:
root: './.sessions'
storage: jsonl
compression: none
- insert:
@@ -59,7 +59,7 @@ async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise<rea
}
}
describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (storage) => {
describe('config-driven session id', () => {
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.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-duplicate-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
const outcome = await ctx.plugin(AgentLoop, {
agents: [
@@ -135,7 +135,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-reload-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first'), textResponse('second')]))
const config = { agents: [{ id: 'main', sessionId: brandString<SessionId>('config-exact-reload'), provider: 'mock', model: 'mock' }] }
@@ -164,7 +164,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-overlap-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('saved')]))
const sessionId = brandString<SessionId>('config-exact-overlap')
const config = { agents: [{ id: 'main', sessionId, provider: 'mock', model: 'mock' }] }
@@ -211,7 +211,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-cancel-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
const sessionId = brandString<SessionId>('config-exact-cancel')
const config = { agents: [{ id: 'main', sessionId, model: 'mock' }] }
const firstLoop = await ctx.plugin(AgentLoop, config)
@@ -267,7 +267,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-failure-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
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.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-unrenderable-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
const unrenderable = {
[Symbol.toPrimitive](): never {
throw new Error('coercion escaped')
@@ -341,7 +341,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-exact-dispose-'))
dirs.push(root)
const ctx = await makeCoreContext()
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
const opening = Promise.withResolvers<SessionHandle>()
vi.spyOn(ctx.sessionPersistence, 'open').mockReturnValue(opening.promise)
const closed = vi.fn(async () => {})
@@ -402,7 +402,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
await ctx1.plugin(ToolRuntime)
await ctx1.plugin(NativeToolExecutor)
await ctx1.plugin(AgentRegistry)
await ctx1.plugin(JsonlSessionPersistence, { root, storage })
await ctx1.plugin(JsonlSessionPersistence, { root })
await ctx1.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('cfg'), provider: 'mock', model: 'mock' }] })
ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg')]))
await expect.poll(() => ctx1.agents.list().length).toBe(1)
@@ -426,7 +426,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
await ctx2.plugin(ToolRuntime)
await ctx2.plugin(NativeToolExecutor)
await ctx2.plugin(AgentRegistry)
await ctx2.plugin(JsonlSessionPersistence, { root, storage })
await ctx2.plugin(JsonlSessionPersistence, { root })
await ctx2.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('cfg'), provider: 'mock', model: 'mock' }] })
ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('cfg2')]))
await expect.poll(() => ctx2.agents.list().length).toBe(1)
@@ -453,7 +453,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
await ctx1.plugin(ToolRuntime)
await ctx1.plugin(NativeToolExecutor)
await ctx1.plugin(AgentRegistry)
await ctx1.plugin(JsonlSessionPersistence, { root, storage })
await ctx1.plugin(JsonlSessionPersistence, { root })
await ctx1.plugin(AgentLoop, { agents: [] })
ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('sticky-1'), agentOptions: { provider: 'mock', model: 'mock' } })
@@ -473,7 +473,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
await ctx2.plugin(NativeToolExecutor)
await ctx2.plugin(AgentRegistry)
await ctx2.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('main'), provider: 'mock', model: 'mock', resumeSessionId: brandString<SessionId>('sticky-1') }] })
await ctx2.plugin(JsonlSessionPersistence, { root, storage })
await ctx2.plugin(JsonlSessionPersistence, { root })
ctx2.llm.registerAdapter(['mock'], new MockAdapter([textResponse('second')]))
// The deferred resume runs after the backend is available.
@@ -496,7 +496,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
const root = await mkdtemp(join(tmpdir(), 'dsh-cfg-resume-route-'))
dirs.push(root)
const ctx1 = await makeCoreContext()
await ctx1.plugin(JsonlSessionPersistence, { root, storage })
await ctx1.plugin(JsonlSessionPersistence, { root })
await ctx1.plugin(AgentLoop, { agents: [] })
ctx1.llm.registerAdapter(['mock'], new MockAdapter([textResponse('first')]))
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('sticky-route'), agentOptions: { provider: 'mock', model: 'mock' } })
@@ -507,7 +507,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
await ctx1.fiber.dispose()
const ctx2 = await makeCoreContext()
await ctx2.plugin(JsonlSessionPersistence, { root, storage })
await ctx2.plugin(JsonlSessionPersistence, { root })
await ctx2.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('main'), ...route, resumeSessionId: brandString<SessionId>('sticky-route') }] })
await expect.poll(() => ctx2.agents.get(brandString<SessionId>('sticky-route')), { timeout: 5_000 }).toBeDefined()
const resumed = ctx2.agents.get(brandString<SessionId>('sticky-route'))!
@@ -530,7 +530,7 @@ describe.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
await ctx.plugin(AgentLoop, { agents: [{ id: brandString<SessionId>('main'), provider: 'mock', model: 'mock', resumeSessionId: brandString<SessionId>('does-not-exist') }] })
const warn = vi.spyOn((ctx.agentLoop as unknown as { ctx: { logger: { warn: (...a: unknown[]) => void } } }).ctx.logger, 'warn')
.mockImplementation(() => undefined)
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
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.each(['jsonl', 'sqlite'] as const)('config-driven session id (%s)', (st
})
})
describe.each(['jsonl', 'sqlite'] as const)('startup reporting after factory teardown (%s)', (storage) => {
describe('startup reporting after factory teardown', () => {
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, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('x')]))
// A restore open that hangs until after the loop is gone: the eventual
@@ -31,7 +31,7 @@ afterEach(async () => {
const input = (text: string) => createUserMessage({ content: [{ type: 'text' as const, text }], source: { kind: 'user' as const } })
async function harness(storage: 'jsonl' | 'sqlite') {
async function harness() {
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(storage: 'jsonl' | 'sqlite') {
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
await ctx.plugin(JsonlSessionPersistence, { root, storage, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root, 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(storage: 'jsonl' | 'sqlite') {
return { ctx, root, adapter, handle, agent: handle.agent }
}
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)
it('cancellation still aborts the running request when queue clearing fails', async () => {
const { ctx, agent } = await harness()
const entered = Promise.withResolvers<AbortSignal>()
const release = Promise.withResolvers<undefined>()
const hold = ctx.on('agent/pre-step', async ({ signal }, next) => { entered.resolve(signal); await release.promise; return next() })
@@ -83,8 +83,8 @@ it.each(['jsonl', 'sqlite'] as const)('%s: cancellation still aborts the running
}
})
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)
it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => {
const { ctx, agent, handle } = await harness()
const release = Promise.withResolvers<undefined>()
const waiting = Promise.withResolvers<'waiting'>()
const disposed = Promise.withResolvers<'disposed'>()
@@ -123,8 +123,8 @@ it.each(['jsonl', 'sqlite'] as const)('%s: waits for admitted maintenance after
}
})
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)
it('reports a quiescence failure while releasing the Agent and Session', async () => {
const { ctx, agent, handle } = await harness()
const failure = new Error('injected quiescence failure')
const idle = vi.spyOn(agent, 'whenIdle').mockRejectedValueOnce(failure)
try {
@@ -136,8 +136,8 @@ it.each(['jsonl', 'sqlite'] as const)('%s: reports a quiescence failure while re
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: keeps creation resources alive until an interrupted creation listener finishes', async (storage) => {
const { ctx } = await harness(storage)
it('keeps creation resources alive until an interrupted creation listener finishes', async () => {
const { ctx } = await harness()
const entered = Promise.withResolvers<Agent>()
const release = Promise.withResolvers<undefined>()
const signal = new AbortController()
@@ -80,9 +80,7 @@ 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((['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 }) => {
it.each(['loop', 'root'] as const)('unloads %s while a background child is stopping', async (owner) => {
const ctx = new Context()
const release = Promise.withResolvers<undefined>()
const root = mkdtempSync(join(tmpdir(), 'dsh-resource-lifecycle-'))
@@ -92,7 +90,7 @@ it.each((['jsonl', 'sqlite'] as const).flatMap(storage =>
rmSync(root, { recursive: true, force: true })
})
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
const loop = await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(LocalJobRegistry)
@@ -145,7 +143,7 @@ it.each((['jsonl', 'sqlite'] as const).flatMap(storage =>
if (owner === 'loop') {
const verify = new Context()
onTestFinished(async () => { await verify.fiber.dispose() })
await verify.plugin(JsonlSessionPersistence, { root, storage })
await verify.plugin(JsonlSessionPersistence, { root })
const reader = await verify.sessionPersistence.open(child.id, 'read')
expect((await reader.read()).events).toEqual(events)
await reader.close()
+144 -145
View File
@@ -3,9 +3,9 @@ import { brandString } from '@deepseek-ai/dsh-brand'
import { type ToolCallId, createMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import { afterEach, describe, expect, it, vi, type MockInstance } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { appendFile, mkdtemp, readdir, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { join } from 'node:path'
import LlmRuntime from '@deepseek-ai/dsh-llm'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionLogOffset, SessionSeq, Session, type SessionId, TOOL_NOT_STARTED, TOOL_OUTCOME_UNKNOWN } from '@deepseek-ai/dsh-session'
@@ -17,7 +17,6 @@ import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent'
import { SessionAlreadyExistsError, type SessionHandle } from '@deepseek-ai/dsh-session-persistence'
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import { generationLogPath, toHeaderLine } from '@deepseek-ai/dsh-session-persistence-jsonl/src/format.ts'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import { MockAdapter, textResponse } from './mock-adapter.ts'
@@ -31,13 +30,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(storage: 'jsonl' | 'sqlite', adapter: MockAdapter): Promise<{ ctx: Context; root: string }> {
async function persistentHarness(adapter: MockAdapter): Promise<{ ctx: Context; root: string }> {
const root = await mkdtemp(join(tmpdir(), 'dsh-resume-'))
dirs.push(root)
return { ctx: await mountPersistentHarness(storage, root, adapter), root }
return { ctx: await mountPersistentHarness(root, adapter), root }
}
async function mountPersistentHarness(storage: 'jsonl' | 'sqlite', root: string, adapter: MockAdapter, compression?: 'none'): Promise<Context> {
async function mountPersistentHarness(root: string, adapter: MockAdapter, compression?: 'none'): Promise<Context> {
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(SessionStore)
@@ -48,7 +47,7 @@ async function mountPersistentHarness(storage: 'jsonl' | 'sqlite', root: string,
await ctx.plugin(AgentRegistry)
// The backend mounts BEFORE the loop so root teardown unwinds the loop
// first: live agents drain their writers into still-open handles.
await ctx.plugin(JsonlSessionPersistence, { root, storage, ...compression === undefined ? {} : { compression } })
await ctx.plugin(JsonlSessionPersistence, { root, ...compression === undefined ? {} : { compression } })
await ctx.plugin(AgentLoop, { agents: [] })
ctx.llm.registerAdapter(['mock'], adapter)
return ctx
@@ -81,8 +80,8 @@ async function readStoredEvents(ctx: Context, sessionId: SessionId): Promise<rea
}
}
async function persistSession(storage: 'jsonl' | 'sqlite', sessionId: SessionId): Promise<string> {
const { ctx, root } = await persistentHarness(storage, new MockAdapter([]))
async function persistSession(sessionId: SessionId): Promise<string> {
const { ctx, root } = await persistentHarness(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 +125,10 @@ function throwUnknown(value: unknown): never {
}
describe('the session-persistence Agent Note: AgentLoop factory create/resume', () => {
it.each(['jsonl', 'sqlite'] as const)('%s: normalizes a non-Error resume publication failure for rollback and releases the write handle', async (storage) => {
it('normalizes a non-Error resume publication failure for rollback and releases the write handle', async () => {
const sessionId = brandString<SessionId>('unknown-resume-failure-s')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const failure = { source: 'resume' }
ctx.on('session/created', () => throwUnknown(failure))
@@ -145,18 +144,18 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: createAgent uses the caller-supplied sessionId (not ${id}-session)', async (storage) => {
it('createAgent uses the caller-supplied sessionId (not ${id}-session)', async () => {
const adapter = new MockAdapter([textResponse('hi')])
const { ctx } = await persistentHarness(storage, adapter)
const { ctx } = await persistentHarness(adapter)
const { agent } = await ctx.agents.create({ sessionId: brandString<SessionId>('custom-session'), meta: { cwd: '/w' } })
expect(agent.session.id).toBe('custom-session')
expect(agent.session.header.cwd).toBe('/w')
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: createAgent rejects a duplicate identity without orphaning a session', async (storage) => {
it('createAgent rejects a duplicate identity without orphaning a session', async () => {
const adapter = new MockAdapter([textResponse('hi')])
const { ctx } = await persistentHarness(storage, adapter)
const { ctx } = await persistentHarness(adapter)
const sessionId = brandString<SessionId>('sess-a')
await ctx.agents.create({ sessionId })
await expect(ctx.agents.create({ sessionId })).rejects.toThrow(/already exists/)
@@ -164,12 +163,12 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: a created agent stores its seed and live turn durably through its handle', async (storage) => {
it('a created agent stores its seed and live turn durably through its handle', async () => {
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(storage, new MockAdapter([textResponse('stored')]))
const { ctx } = await persistentHarness(new MockAdapter([textResponse('stored')]))
const sessionId = brandString<SessionId>('durable-create')
const handle = await ctx.agents.create({
sessionId,
@@ -194,16 +193,16 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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')]))
it('a rejecting final writer close releases the registries, then rejects disposal', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('hi')]))
const sessionId = brandString<SessionId>('drain-close-fails')
const create = vi.spyOn(ctx.sessionPersistence, 'create')
const handle = await ctx.agents.create({ sessionId })
const persisted = await ctx.sessionPersistence.open(sessionId, 'read')
await persisted.close()
const creation = create.mock.results[0]
if (creation?.type !== 'return') throw new Error('missing owned write handle')
const stored = await creation.value
const stored = [...(ctx.sessionPersistence as unknown as {
tracker: { openHandles: Set<SessionHandle> }
}).tracker.openHandles].find(open => open.id === sessionId && open.access === 'write')
if (stored === undefined) throw new Error('missing owned write handle')
// The real close still runs (releasing write ownership); the injected
// failure models a drain that reports a durability error at close.
const realClose = stored.close.bind(stored)
@@ -222,14 +221,14 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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')]))
it('combines a machine-teardown failure with a close failure into one rejection', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('hi')]))
const sessionId = brandString<SessionId>('drain-both-fail')
const create = vi.spyOn(ctx.sessionPersistence, 'create')
const handle = await ctx.agents.create({ sessionId })
const creation = create.mock.results[0]
if (creation?.type !== 'return') throw new Error('missing owned write handle')
const stored = await creation.value
const stored = [...(ctx.sessionPersistence as unknown as {
tracker: { openHandles: Set<SessionHandle> }
}).tracker.openHandles].find(open => open.id === sessionId && open.access === 'write')
if (stored === undefined) throw new Error('missing owned write handle')
const machine = handle.agent as Agent & { scope: { dispose: () => Promise<void> } }
vi.spyOn(machine.scope, 'dispose').mockRejectedValue(new Error('scope exploded'))
vi.spyOn(stored, 'close').mockRejectedValue(new Error('close exploded'))
@@ -242,8 +241,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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')]))
it('agent dispose releases write ownership of its stored session', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('hi')]))
const sessionId = brandString<SessionId>('ownership-release')
const handle = await ctx.agents.create({ sessionId })
@@ -260,8 +259,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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([]))
it('a stored-session create failure rolls the fresh identity back', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('create-backend-fail')
vi.spyOn(ctx.sessionPersistence, 'create').mockRejectedValueOnce(new Error('backend create failed'))
@@ -275,8 +274,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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([]))
it('a seed append failure closes the fresh write handle and rethrows', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('seed-append-fail')
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
@@ -302,8 +301,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
})
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([]))
it('stores setup events exactly once after Session creation completes', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('setup-event-feed')
const pending = createUserMessage({ content: [{ type: 'text', text: 'setup context' }], source: { kind: 'user' } })
const seen: SessionEvent[] = []
@@ -331,8 +330,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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([]))
it('a setup failure retains stored constructor history and releases the write handle', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('setup-fail-history')
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
@@ -355,8 +354,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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([]))
it('rollback swallows a rejecting handle close after initialization validation fails (create and createAgent)', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const originalCreate = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
const closeSpies: Array<{ mockRestore: () => void }> = []
ctx.sessionPersistence.create = async (header, options) => {
@@ -379,8 +378,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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([]))
it('a reentrant abort during scope construction waits for a rejecting handle close', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('scope-abort-close-reject')
const originalCreate = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
const spies: Array<{ mockRestore: () => void }> = []
@@ -417,8 +416,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
}
})
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([]))
it('config create rollback swallows a rejecting close after a publish failure', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('config-publish-close-reject')
const originalCreate = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
const spies: Array<{ mockRestore: () => void }> = []
@@ -446,8 +445,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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([]))
it('a seed append failure swallows a rejecting handle close', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const sessionId = brandString<SessionId>('seed-append-close-reject')
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
@@ -470,10 +469,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: a resume read failure swallows a rejecting handle close during rollback', async (storage) => {
it('a resume read failure swallows a rejecting handle close during rollback', async () => {
const sessionId = brandString<SessionId>('resume-read-close-reject')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(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 +491,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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')]))
it('resume cannot crash-repair a turn owned by a live agent', async () => {
const { ctx } = await persistentHarness(new MockAdapter([textResponse('unused')]))
const sessionId = brandString<SessionId>('live-resume-race')
const first = (await ctx.agents.create({ sessionId })).agent
first.session.append('turn/start', { turn: 1 })
@@ -513,10 +512,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume appends interrupted-turn closers durably through the handle', async (storage) => {
it('resume appends interrupted-turn closers durably through the handle', async () => {
// Lifecycle 1: store an interrupted log — an open turn with no turn/end.
const sessionId = brandString<SessionId>('interrupted-resume')
const { ctx: ctx1, root } = await persistentHarness(storage, new MockAdapter([]))
const { ctx: ctx1, root } = await persistentHarness(new MockAdapter([]))
await seedStoredSession(ctx1, sessionId, [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
])
@@ -526,7 +525,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(storage, root, new MockAdapter([]))
const ctx2 = await mountPersistentHarness(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 +537,9 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx2.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume closes an interrupted tool call durably: tool/result, step/end, turn/end', async (storage) => {
it('resume closes an interrupted tool call durably: tool/result, step/end, turn/end', async () => {
const sessionId = brandString<SessionId>('interrupted-tool-resume')
const { ctx: ctx1, root } = await persistentHarness(storage, new MockAdapter([]))
const { ctx: ctx1, root } = await persistentHarness(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 +556,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
] as SessionEvent[])
await ctx1.fiber.dispose()
const ctx2 = await mountPersistentHarness(storage, root, new MockAdapter([]))
const ctx2 = await mountPersistentHarness(root, new MockAdapter([]))
const handle = await ctx2.agents.resume({ resumeSessionId: sessionId })
await handle.dispose()
@@ -577,23 +576,24 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx2.fiber.dispose()
})
it('resume imports a torn legacy tail and continues from its valid prefix in SQLite', async () => {
it('resume over a torn physical tail continues from the committed prefix', async () => {
const sessionId = brandString<SessionId>('torn-tail-resume')
const root = await mkdtemp(join(tmpdir(), 'dsh-resume-torn-'))
dirs.push(root)
const ctx1 = await mountPersistentHarness('sqlite', root, new MockAdapter([]), 'none')
const header = ctx1.sessions.prepare(sessionId).header
const ctx1 = await mountPersistentHarness(root, new MockAdapter([]), 'none')
await seedStoredSession(ctx1, sessionId, [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
])
await ctx1.fiber.dispose()
const path = generationLogPath(root, header.cwd, sessionId, header.version, 'none')
await mkdir(dirname(path), { recursive: true })
const bytes = [JSON.stringify(toHeaderLine(header)),
JSON.stringify({ type: 'turn/start', seq: 0, time: 1, data: { turn: 1 } }),
'{"type":"assistant/chunk","seq":1,"ti',
].join('\n')
await writeFile(path, bytes)
// Crash artifact: a half-written record with no trailing newline.
const logs = (await readdir(root, { recursive: true })).filter(name => name.endsWith('.jsonl'))
expect(logs).toHaveLength(1)
await appendFile(join(root, logs[0] as string), '{"type":"assistant/chunk","seq":1,"ti')
const ctx2 = await mountPersistentHarness('sqlite', root, new MockAdapter([]), 'none')
// Resume truncates the torn tail under its write open, then appends the
// closers immediately after the committed prefix — no gap, no fragment.
const ctx2 = await mountPersistentHarness(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'])
@@ -602,23 +602,22 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
const stored = await readStoredEvents(ctx2, sessionId)
expect(stored.map(event => `${event.type}@${event.seq}`))
.toEqual(['turn/start@0', 'turn/end@1', 'session/end-seed@2'])
expect(await readFile(path, 'utf8')).toBe(bytes)
await ctx2.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: createAgent works without meta (no cwd)', async (storage) => {
it('createAgent works without meta (no cwd)', async () => {
const adapter = new MockAdapter([textResponse('hi')])
const { ctx } = await persistentHarness(storage, adapter)
const { ctx } = await persistentHarness(adapter)
const { agent } = await ctx.agents.create({ sessionId: brandString<SessionId>('nometa-session') })
expect(agent.session.id).toBe('nometa-session')
expect(agent.session.header.cwd).toBeUndefined()
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume of a session with no cwd carries an undefined cwd header', async (storage) => {
it('resume of a session with no cwd carries an undefined cwd header', async () => {
// Lifecycle 1: create a no-cwd session and run a turn.
const adapter1 = new MockAdapter([textResponse('a')])
const { ctx: ctx1, root } = await persistentHarness(storage, adapter1)
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('nocwd-sess') })
h1.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
await waitForIdle(ctx1, h1.agent)
@@ -627,16 +626,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(storage, root, new MockAdapter([textResponse('b')]))
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('b')]))
const a2 = (await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('nocwd-sess') })).agent
expect(a2.session.header.cwd).toBeUndefined()
await ctx2.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: agent/created fires "startup" for createAgent and "resume" for resume()', async (storage) => {
it('agent/created fires "startup" for createAgent and "resume" for resume()', async () => {
// Lifecycle 1: a fresh createAgent announces creation with source 'startup'.
const adapter1 = new MockAdapter([textResponse('a')])
const { ctx: ctx1, root } = await persistentHarness(storage, adapter1)
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const sources1: string[] = []
ctx1.on('agent/created', ({ source }) => void sources1.push(source))
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('start-sess') })
@@ -647,7 +646,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(storage, root, new MockAdapter([textResponse('b')]))
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('b')]))
const sources2: string[] = []
ctx2.on('agent/created', ({ source }) => void sources2.push(source))
await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('start-sess') })
@@ -655,10 +654,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx2.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume announces the Session before setup and the composed Agent afterward', async (storage) => {
it('resume announces the Session before setup and the composed Agent afterward', async () => {
const sessionId = brandString<SessionId>('resume-setup-success')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const order: string[] = []
@@ -715,13 +714,13 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: a resumed session stores its repair suffix durably before publication', async (storage) => {
it('a resumed session stores its repair suffix durably before publication', async () => {
// The stored fixture (two events, no end-seed) gains the end-seed marker
// through the resume handle: after one resume lifecycle the STORED log
// carries it, so the next resume reads it back without re-marking.
const sessionId = brandString<SessionId>('resume-suffix-durable')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const first = await ctx.agents.resume({ resumeSessionId: sessionId })
await first.dispose()
@@ -737,10 +736,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: successful resume disposal retires its caller-owned transaction effects', async (storage) => {
it('successful resume disposal retires its caller-owned transaction effects', async () => {
const sessionId = brandString<SessionId>('resume-retired-effects-s')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const handle = await ctx.agents.resume({
resumeSessionId: sessionId,
agentOptions: { provider: 'mock', model: 'mock' },
@@ -753,9 +752,9 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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) => {
it.each(['reject', 'abort'] as const)('preserves restored inbox messages when setup fails: %s', async (failure) => {
const sessionId = brandString<SessionId>('resume-inbox-' + failure)
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const { ctx } = await persistentHarness(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 +782,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume setup rejection disposes the announced Session and releases the identity', async (storage) => {
it('resume setup rejection disposes the announced Session and releases the identity', async () => {
const sessionId = brandString<SessionId>('resume-setup-reject')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(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 +811,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume setup commit rejection disposes the announced Session and releases the identity', async (storage) => {
it('resume setup commit rejection disposes the announced Session and releases the identity', async () => {
const sessionId = brandString<SessionId>('resume-setup-commit-reject')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(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 +839,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: owner unload aborts resume setup and cannot publish the Agent after the callback settles', async (storage) => {
it('owner unload aborts resume setup and cannot publish the Agent after the callback settles', async () => {
const sessionId = brandString<SessionId>('resume-setup-owner-unload')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const gate = Promise.withResolvers<undefined>()
const setupStarted = Promise.withResolvers<undefined>()
const published: string[] = []
@@ -876,10 +875,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: owner unload aborts a never-settling persistence open, releases the identity, and blocks late publication', async (storage) => {
it('owner unload aborts a never-settling persistence open, releases the identity, and blocks late publication', async () => {
const sessionId = brandString<SessionId>('resume-load-owner-unload')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([textResponse('next')]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const lateOpen = Promise.withResolvers<SessionHandle>()
const openStarted = Promise.withResolvers<undefined>()
const originalOpen = ctx.sessionPersistence.open.bind(ctx.sessionPersistence)
@@ -931,9 +930,9 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: AgentLoop unload aborts a never-settling persistence open and awaits wrapper settlement', async (storage) => {
it('AgentLoop unload aborts a never-settling persistence open and awaits wrapper settlement', async () => {
const sessionId = brandString<SessionId>('resume-load-factory-unload')
const root = await persistSession(storage, sessionId)
const root = await persistSession(sessionId)
const ctx = new Context()
await ctx.plugin(LlmRuntime)
await ctx.plugin(SessionStore)
@@ -943,7 +942,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, { storage, root })
await ctx.plugin(JsonlSessionPersistence, { root })
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('next')]))
const lateOpen = Promise.withResolvers<SessionHandle>()
@@ -974,7 +973,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx.fiber.dispose()
})
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) => {
it('resume of a forked session preserves the lineage, seed boundary, and delegation depth in the header', async () => {
// 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 +981,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(storage, new MockAdapter([]))
const { ctx: ctx1, root } = await persistentHarness(new MockAdapter([]))
const forked = await ctx1.agents.create({
sessionId: brandString<SessionId>('forked-sess'),
seed,
@@ -997,7 +996,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(storage, root, new MockAdapter([textResponse('b')]))
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('b')]))
const a2 = (await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('forked-sess') })).agent
expect(a2.session.header.parentSession).toBe('parent-sess')
expect(a2.session.header.cwd).toBe('/w')
@@ -1015,7 +1014,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('jsonl', adapter1)
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const a1 = (await ctx1.agents.create({ sessionId: brandString<SessionId>('inject-sess'), meta: { cwd: '/w' }, agentOptions: { provider: 'mock', model: 'mock' } })).agent
a1.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
await waitForIdle(ctx1, a1)
@@ -1031,7 +1030,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('jsonl', root, new MockAdapter([textResponse('next')]))
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('next')]))
const stored = await readStoredEvents(ctx2, brandString<SessionId>('inject-sess'))
expect(stored.some(event => event.type === 'agent/inbox/spliced')).toBe(true)
expect(JSON.stringify(stored)).toContain('background job 42 finished')
@@ -1045,7 +1044,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
await ctx1.fiber.dispose()
})
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) => {
it.each(['resume', 'fork'] as const)('%s continues persisted history after a live scheduler failure', async (mode) => {
const firstAdapter = new MockAdapter([[
{ type: 'block-start', index: 0, blockType: 'tool-call' },
{ type: 'block-end', index: 0, block: { type: 'tool-call', id: brandString<ToolCallId>('started'), name: 'probe', arguments: '{}' } },
@@ -1053,7 +1052,7 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
{ type: 'block-end', index: 1, block: { type: 'tool-call', id: brandString<ToolCallId>('pending'), name: 'probe', arguments: '{}' } },
{ type: 'finish', reason: { kind: 'tool-calls' } },
]])
const { ctx: first, root } = await persistentHarness(storage, firstAdapter)
const { ctx: first, root } = await persistentHarness(firstAdapter)
let next: Context | undefined
try {
first.tools.register(defineContentToolFixture({
@@ -1078,7 +1077,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(storage, root, nextAdapter)
next = await mountPersistentHarness(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 +1117,10 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async (storage) => {
it('resume reloads a persisted session: history + turn numbering continue, no duplicate seqs', async () => {
// Lifecycle 1: run one full turn, persisting it.
const adapter1 = new MockAdapter([textResponse('first answer')])
const { ctx: ctx1, root } = await persistentHarness(storage, adapter1)
const { ctx: ctx1, root } = await persistentHarness(adapter1)
const h1 = await ctx1.agents.create({ sessionId: brandString<SessionId>('sess-resume'), meta: { cwd: '/w' } })
const a1 = h1.agent
a1.followup(createUserMessage({ content: [{ type: 'text', text: 'first question' }], source: { kind: 'user' } }))
@@ -1133,7 +1132,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(storage, root, new MockAdapter([textResponse('second answer')]))
const ctx2 = await mountPersistentHarness(root, new MockAdapter([textResponse('second answer')]))
const a2 = (await ctx2.agents.resume({ resumeSessionId: brandString<SessionId>('sess-resume') })).agent
// The resumed session carries the prior history…
@@ -1175,8 +1174,8 @@ describe('the session-persistence Agent Note: AgentLoop factory create/resume',
})
describe('creation and resume cancellation edges', () => {
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([]))
it('rejects create() with a pre-aborted signal, including a non-Error reason', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const errorReason = new AbortController()
errorReason.abort(new Error('caller gave up'))
@@ -1200,8 +1199,8 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
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([]))
it('a non-Error abort reason arriving during setup is wrapped for the caller', async () => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const controller = new AbortController()
const setupEntered = Promise.withResolvers<undefined>()
const setupGate = Promise.withResolvers<undefined>()
@@ -1224,8 +1223,8 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
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([]))
it.each(['setup', 'commit'] as const)('rejects when %s synchronously aborts its caller signal', async (phase) => {
const { ctx } = await persistentHarness(new MockAdapter([]))
const controller = new AbortController()
const created = vi.fn()
@@ -1253,10 +1252,10 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: resume with a pre-aborted caller signal rejects out of the load race', async (storage) => {
it('resume with a pre-aborted caller signal rejects out of the load race', async () => {
const sessionId = brandString<SessionId>('resume-pre-aborted')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const controller = new AbortController()
controller.abort(new Error('resume abandoned'))
@@ -1278,19 +1277,19 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: an abort landing between crash repair and publication refuses resume, normalized', async (storage) => {
it('an abort landing between crash repair and publication refuses resume, normalized', async () => {
// Cover the publication-time abort backstop: the signal fires AFTER the
// raced open settled (during the closer append), so only the final
// pre-publication check can refuse.
const run = async (suffix: string, reason: unknown): Promise<unknown> => {
const sessionId = brandString<SessionId>(`late-abort-${suffix}`)
const { ctx: seedCtx, root } = await persistentHarness(storage, new MockAdapter([]))
const { ctx: seedCtx, root } = await persistentHarness(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(storage, root, new MockAdapter([]))
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const controller = new AbortController()
const originalOpen = ctx.sessionPersistence.open.bind(ctx.sessionPersistence)
ctx.sessionPersistence.open = async (id, access, options) => {
@@ -1318,9 +1317,9 @@ describe('creation and resume cancellation edges', () => {
expect(await run('string', 'late abort string')).toMatchObject({ message: expect.stringMatching(/creation aborted/) as unknown })
})
it.each(['jsonl', 'sqlite'] as const)('%s: an aborted create closes the write handle its abandoned backend create later resolves', async (storage) => {
it('an aborted create closes the write handle its abandoned backend create later resolves', async () => {
const sessionId = brandString<SessionId>('create-abandoned-handle')
const { ctx } = await persistentHarness(storage, new MockAdapter([]))
const { ctx } = await persistentHarness(new MockAdapter([]))
const lateCreate = Promise.withResolvers<SessionHandle>()
const createStarted = Promise.withResolvers<undefined>()
ctx.sessionPersistence.create = () => {
@@ -1344,10 +1343,10 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: closes the resume write handle when the loop becomes inactive before setup', async (storage) => {
it('closes the resume write handle when the loop becomes inactive before setup', async () => {
const sessionId = brandString<SessionId>('resume-loop-inactive-after-open')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const loop = ctx.agentLoop as unknown as {
ownership: { isActive: () => boolean }
}
@@ -1369,10 +1368,10 @@ describe('creation and resume cancellation edges', () => {
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: factory teardown during a hung resume open rejects promptly and closes the late handle', async (storage) => {
it('factory teardown during a hung resume open rejects promptly and closes the late handle', async () => {
const sessionId = brandString<SessionId>('resume-loop-teardown')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const gate = Promise.withResolvers<SessionHandle>()
const openStarted = Promise.withResolvers<undefined>()
ctx.sessionPersistence.open = () => {
@@ -1398,10 +1397,10 @@ describe('creation and resume cancellation edges', () => {
})
describe('configured-start failure edges', () => {
it.each(['jsonl', 'sqlite'] as const)('%s: a non-Error mid-open abort reason is wrapped for the resume caller', async (storage) => {
it('a non-Error mid-open abort reason is wrapped for the resume caller', async () => {
const sessionId = brandString<SessionId>('resume-string-mid-abort')
const root = await persistSession(storage, sessionId)
const ctx = await mountPersistentHarness(storage, root, new MockAdapter([]))
const root = await persistSession(sessionId)
const ctx = await mountPersistentHarness(root, new MockAdapter([]))
const gate = Promise.withResolvers<never>()
gate.promise.catch(() => undefined)
const openStarted = Promise.withResolvers<undefined>()
@@ -1424,9 +1423,9 @@ describe('configured-start failure edges', () => {
await ctx.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: a failing exact-id restore over an existing artifact stays loud', async (storage) => {
it('a failing exact-id restore over an existing artifact stays loud', async () => {
const sessionId = brandString<SessionId>('config-existing-corrupt')
const root = await persistSession(storage, sessionId)
const root = await persistSession(sessionId)
const configured = new Context()
await configured.plugin(LlmRuntime)
await configured.plugin(SessionStore)
@@ -1435,7 +1434,7 @@ describe('configured-start failure edges', () => {
await configured.plugin(ToolRuntime)
await configured.plugin(NativeToolExecutor)
await configured.plugin(AgentRegistry)
await configured.plugin(JsonlSessionPersistence, { storage, root })
await configured.plugin(JsonlSessionPersistence, { 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 +1458,9 @@ describe('configured-start failure edges', () => {
await configured.fiber.dispose()
})
it.each(['jsonl', 'sqlite'] as const)('%s: suppresses a configured-resume failure that lands after teardown', async (storage) => {
it('suppresses a configured-resume failure that lands after teardown', async () => {
const sessionId = brandString<SessionId>('config-late-resume-failure')
const root = await persistSession(storage, sessionId)
const root = await persistSession(sessionId)
const configured = new Context()
await configured.plugin(LlmRuntime)
await configured.plugin(SessionStore)
@@ -1470,7 +1469,7 @@ describe('configured-start failure edges', () => {
await configured.plugin(ToolRuntime)
await configured.plugin(NativeToolExecutor)
await configured.plugin(AgentRegistry)
await configured.plugin(JsonlSessionPersistence, { storage, root })
await configured.plugin(JsonlSessionPersistence, { root })
configured.llm.registerAdapter(['mock'], new MockAdapter([]))
const gate = Promise.withResolvers<never>()
gate.promise.catch(() => undefined)
@@ -28,11 +28,11 @@ afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
})
async function mountCore(storage: 'jsonl' | 'sqlite', persistenceRoot?: string) {
async function core(persistenceRoot?: string) {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
if (persistenceRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, storage, compression: 'none' })
if (persistenceRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
await ctx.plugin(AgentLoop, { agents: [] })
return ctx
}
@@ -74,8 +74,7 @@ function dueWorkProducer(sessionId: SessionId, plugin: string) {
return { producer, delivery: delivery.promise }
}
describe.each(['jsonl', 'sqlite'] as const)('serial creation listener integrations (%s)', (storage) => {
const core = (persistenceRoot?: string) => mountCore(storage, persistenceRoot)
describe('serial creation listener integrations', () => {
it('rolls back creation when file-reference prompt installation fails', async () => {
const ctx = await core()
const errors: string[] = []
@@ -29,7 +29,7 @@ function waitForIdle(ctx: Context, agent: Agent): Promise<void> {
})
}
async function mount(order: 'backend-first' | 'loop-first', storage: 'jsonl' | 'sqlite'): Promise<{ ctx: Context; root: string }> {
async function mount(order: 'backend-first' | 'loop-first'): Promise<{ ctx: Context; root: string }> {
const root = await mkdtemp(join(tmpdir(), 'dsh-shutdown-drain-'))
dirs.push(root)
const ctx = new Context()
@@ -41,21 +41,19 @@ async function mount(order: 'backend-first' | 'loop-first', storage: 'jsonl' | '
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(AgentRegistry)
if (order === 'backend-first') {
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(AgentLoop, { agents: [] })
} else {
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
}
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('done')]))
return { ctx, root }
}
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 }) => {
describe.each(['backend-first', 'loop-first'] as const)('root shutdown drain (%s)', (order) => {
it('persists buffered turn events without an explicit flush before dispose', async () => {
const { ctx, root } = await mount(order, storage)
const { ctx, root } = await mount(order)
const sessionId = brandString<SessionId>('shutdown-drain')
const handle = await ctx.agents.create({ sessionId, agentOptions: { provider: 'mock', model: 'mock' } })
handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }))
@@ -64,7 +62,7 @@ describe.each((['jsonl', 'sqlite'] as const).flatMap(storage =>
await ctx.fiber.dispose()
const verify = new Context()
await verify.plugin(JsonlSessionPersistence, { root, storage })
await verify.plugin(JsonlSessionPersistence, { root })
const reader = await verify.sessionPersistence.open(sessionId, 'read')
const { events } = await reader.read()
await reader.close()
@@ -13,7 +13,7 @@ import WorkingDirectory from '@deepseek-ai/dsh-working-directory'
import ClaudeCodeMods, { defineMod } from '../src/index.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
it.each(['jsonl', 'sqlite'] as const)('reports the final committed cwd when a persisted Session resumes, retaining its original project (%s)', async (backend) => {
it('reports the final committed cwd when a persisted Session resumes, retaining its original project', async () => {
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.each(['jsonl', 'sqlite'] as const)('reports the final committed cwd when a pe
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', storage: backend })
await ctx.plugin(JsonlSessionPersistence, { root: join(root, 'sessions'), compression: 'none' })
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(ClaudeCodeMods)
await ctx.plugin(defineMod({
@@ -58,7 +58,7 @@ function chat(id: string, leafAt: number): ExportSessionFile {
}
/** Boot the plugin rows through the Loader with stand-ins for the Connection route registry and the attachment store. */
async function boot(backend: 'jsonl' | 'sqlite', saveImage: (input: SaveImageAttachment) => Promise<ImageAttachmentRef> = () => Promise.reject(new Error('unused'))) {
async function boot(saveImage: (input: SaveImageAttachment) => Promise<ImageAttachmentRef> = () => Promise.reject(new Error('unused'))) {
root = await realpath(await mkdtemp(join(tmpdir(), 'dsh-deepseek-import-loader-')))
const workspacePath = join(root, 'project')
await mkdir(workspacePath)
@@ -68,7 +68,6 @@ async function boot(backend: 'jsonl' | 'sqlite', saveImage: (input: SaveImageAtt
"- name: '@deepseek-ai/dsh-session-persistence-jsonl'",
' config:',
` root: ${JSON.stringify(join(root, 'sessions'))}`,
` storage: ${backend}`,
"- name: '@deepseek-ai/dsh-storage'",
"- name: '@deepseek-ai/dsh-storage-json'",
' config:',
@@ -143,8 +142,8 @@ async function boot(backend: 'jsonl' | 'sqlite', saveImage: (input: SaveImageAtt
const lines = async (response: Response): Promise<DeepseekChatImportLine[]> =>
(await response.text()).split('\n').filter(line => line !== '').map(line => JSON.parse(line) as DeepseekChatImportLine)
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)
it('imports an uploaded archive through the registered route into a chosen Workspace', async () => {
const { ctx, routes, workspace, workspacePath, post } = await boot()
const signal = new AbortController().signal
const as = (principal: Principal) => ctx.extend({
invocation: {
@@ -225,10 +224,10 @@ it.each(['jsonl', 'sqlite'] as const)('imports an uploaded archive through the r
expect(routes.size).toBe(0)
})
it.each(['jsonl', 'sqlite'] as const)('cancels a running import when the plugin unloads and finishes unloading only after it stops (%s)', async (backend) => {
it('cancels a running import when the plugin unloads and finishes unloading only after it stops', async () => {
const saving = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<ImageAttachmentRef>()
const { ctx, routes, post, importer } = await boot(backend, () => {
const { ctx, routes, post, importer } = await boot(() => {
saving.resolve(undefined)
return release.promise
})
@@ -36,7 +36,7 @@ function text(content: readonly ContentBlock[]): string {
: block.type === 'tool-call' ? `call:${block.name}` : block.type).join(' | ')
}
it.each(['jsonl', 'sqlite'] as const)('continues an imported conversation with its finished history and without excluded replies (%s)', async (backend) => {
it('continues an imported conversation with its finished history and without excluded replies', async () => {
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.each(['jsonl', 'sqlite'] as const)('continues an imported conversation with i
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', storage: backend })
await ctx.plugin(JsonlPersistence, { root: join(root, 'sessions'), compression: 'none' })
await mountAgentLoopTestHarness(ctx)
const adapter = new MockAdapter([textResponse('Bus 2 is faster.')])
ctx.llm.registerAdapter(['mock'], adapter)
@@ -50,13 +50,13 @@ function hooks(d: string, h: unknown): string {
writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
}
type HarnessOpts = { pluginRoot?: string; projectDir?: string; stderrSummaryMaxChars?: number; session?: { root: string; storage: 'jsonl' | 'sqlite' } }
type HarnessOpts = { pluginRoot?: string; projectDir?: string; stderrSummaryMaxChars?: number; sessionRoot?: string }
async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise<Context> {
const ctx = new Context()
contexts.push(ctx)
provideWorkingDirectoryFixture(ctx)
await mountAgentLoopTestDependencies(ctx)
if (opts.session !== undefined) await ctx.plugin(JsonlSessionPersistence, opts.session)
if (opts.sessionRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: opts.sessionRoot })
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.each(['jsonl', 'sqlite'] as const)('degrades transcript_path to the empty string even with persistence mounted (%s)', async (backend) => {
it('degrades transcript_path to the empty string even with persistence mounted', async () => {
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, { session: { root: dir(), storage: backend } })
const ctx = await harness(path, adapter, { sessionRoot: dir() })
ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
const agent = await ctx.agentLoop.create(brandString<SessionId>('transcript'), { provider: 'mock', model: 'mock' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
@@ -40,13 +40,13 @@ function hooks(d: string, h: unknown): string {
writeFileSync(join(d, 'hooks.json'), JSON.stringify({ hooks: h })); return join(d, 'hooks.json')
}
type HarnessOpts = { stderrSummaryMaxChars?: number; session?: { root: string; storage: 'jsonl' | 'sqlite' } }
type HarnessOpts = { stderrSummaryMaxChars?: number; sessionRoot?: string }
async function harness(configPath: string, adapter: MockAdapter, opts: HarnessOpts = {}): Promise<Context> {
const ctx = new Context()
contexts.push(ctx)
provideWorkingDirectoryFixture(ctx)
await mountAgentLoopTestDependencies(ctx)
if (opts.session !== undefined) await ctx.plugin(JsonlSessionPersistence, opts.session)
if (opts.sessionRoot !== undefined) await ctx.plugin(JsonlSessionPersistence, { root: opts.sessionRoot })
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.each(['jsonl', 'sqlite'] as const)('degrades transcript_path to null even with persistence mounted (%s)', async (backend) => {
it('degrades transcript_path to null even with persistence mounted', async () => {
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, { session: { root: dir(), storage: backend } })
const ctx = await harness(path, adapter, { sessionRoot: dir() })
ctx.tools.register(defineContentToolFixture({ name: 'echo', description: 'e', parameters: {}, async execute() { return [{ type: 'text', text: 'ok' }] } }))
const agent = await ctx.agentLoop.create(brandString<SessionId>('transcript'), { provider: 'mock', model: 'mock' })
agent.followup(createUserMessage({ content: [{ type: 'text', text: 'go' }], source: { kind: 'user' } }))
@@ -13,7 +13,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { describe, expect, it, onTestFinished } from 'vitest'
import type {} from '../src/index.ts'
import { apply } from '../src/host/share-host.ts'
@@ -149,13 +149,6 @@ async function host(options: {
}
describe('owner host credential horizon', () => {
beforeEach(() => {
// Relay I/O and polling use real timers; only credential expiry uses this fixed clock.
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(START + 60_000)
})
afterEach(() => { vi.useRealTimers() })
it('adopts the horizon the Relay reports for a claim past the signed expiry', async () => {
const relay = await relayStandIn({ claim: { body: { claimed: true, ownerCredentialExpiresAt: LIVE } } })
onTestFinished(relay.close)
@@ -190,10 +190,10 @@ describe('share-bound receiving Session admission', () => {
},
)
it.each(['jsonl', 'sqlite'] as const)('rejects a deleted share from recovered durable Inbox without process-local share history (%s)', async (backend) => {
it('rejects a deleted share from recovered durable Inbox without process-local share history', async () => {
const fixture = await harness(true)
await mountAgentLoopTestDependencies(fixture.ctx)
await fixture.ctx.plugin(JsonlSessionPersistence, { root: join(dirname(fixture.file), 'sessions'), compression: 'none', storage: backend })
await fixture.ctx.plugin(JsonlSessionPersistence, { root: join(dirname(fixture.file), 'sessions'), compression: 'none' })
await mountAgentLoopTestHarness(fixture.ctx)
const reached = Promise.withResolvers<PreStepDecision>()
fixture.ctx.on('agent/pre-step', async (_input, next) => {
@@ -100,7 +100,6 @@ describe('three-mode acceptance: real-profile base', () => {
'- id: session-persistence-jsonl',
' config:',
` root: '${sessions}'`,
' storage: jsonl',
' compression: none',
'- insert:',
' - id: base-fixture-llm',
@@ -406,7 +406,6 @@ export async function bootWebOwner(options: WebOwnerOptions = {}): Promise<WebOw
'- id: session-persistence-jsonl',
' config:',
` root: '${sessionsRoot}'`,
' storage: jsonl',
' compression: none',
'- insert:',
' - id: base-fixture-llm',
@@ -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.each(['jsonl', 'sqlite'] as const)('reads the live app language and rejects an enabled standalone installation (%s)', async (backend) => {
const f = await setup(backend)
it('reads the live app language and rejects an enabled standalone installation', async () => {
const f = await setup()
try {
await f.plugin.dispose()
const standalone = { disabled: true, options: { name: 'cordis:@magolor/dsh-timeline' } }
@@ -9,8 +9,8 @@ import type { ControlTarget } from '../src/records.ts'
import type { UserEdit } from '../src/protocol.ts'
import { setup } from './fixture.ts'
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -47,9 +47,9 @@ async function fixture(backend: 'jsonl' | 'sqlite') {
return { ...f, view, tree, target, request, edit, call, update }
}
describe.each(['jsonl', 'sqlite'] as const)('durable asynchronous work requests (%s)', (backend) => {
describe('durable asynchronous work requests', () => {
it('keeps siblings independent and marks a request unavailable when its tree is removed', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('durable asynchronous work requests
}
})
it('suppresses dispatch if another client removes the tree before the reply', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('durable asynchronous work requests
}
})
it('serializes duplicate and overlapping requests, preserves progress, and survives plugin reload', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('durable asynchronous work requests
})
it('confirms a pause only after every unfinished leaf in scope is paused or blocked', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
const request = f.request()
await f.edit(request)
@@ -147,7 +147,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
try {
await f.update([
{ id: 'one', status: 'paused', note: 'Waiting for user.' },
@@ -198,7 +198,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
vi.useFakeTimers({ toFake: ['Date'] })
try {
const first = f.request()
@@ -229,7 +229,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable asynchronous work requests
})
it('records completion and retirement without claiming the requested pause was applied', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
const request = f.request('pause', { kind: 'task', tree: f.tree, task: taskId.parse('one') })
await f.edit(request)
@@ -251,7 +251,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
try {
const put = vi.spyOn(f.ctx.sessions, 'flush').mockRejectedValueOnce(new Error('Write failed'))
const request = f.request('pause', { kind: 'tree', tree: f.tree })
@@ -11,9 +11,9 @@ import { newId, taskId } from '../src/records.ts'
import { delegationContext } from '../src/delegation.ts'
import { setup } from './fixture.ts'
describe.each(['jsonl', 'sqlite'] as const)('manager-owned delegated planning (%s)', (backend) => {
describe('manager-owned delegated planning', () => {
it('limits guidance when restored worker ancestry is missing or cyclic', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const create = async (id: SessionId, parentSession?: SessionId) => (
await f.ctx.agents.create({
sessionId: id,
@@ -37,7 +37,7 @@ describe.each(['jsonl', 'sqlite'] as const)('manager-owned delegated planning (%
}
})
it('hides worker planning, keeps user forks independent, and shares bounded assignment references', async () => {
const f = await setup(backend, { intervalMs: 86400000, language: 'zh-CN' })
const f = await setup({ intervalMs: 86400000, language: 'zh-CN' })
let sequence = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -135,7 +135,7 @@ describe.each(['jsonl', 'sqlite'] as const)('manager-owned delegated planning (%
})
it('denies stale and agent-local worker writes without changing manager tasks or discussions', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
let sequence = 0
const call = (agent: typeof f.agent, name: string, args: object) =>
executeTool(f.ctx, {
@@ -223,7 +223,7 @@ describe.each(['jsonl', 'sqlite'] as const)('manager-owned delegated planning (%
})
it('runs worker iterations without planning reminders or separate timed reports', async () => {
const f = await setup(backend, { reminderIterations: 2, intervalMs: 60000 })
const f = await setup({ reminderIterations: 2, intervalMs: 60000 })
try {
const worker = (
await f.ctx.agents.create({
@@ -8,8 +8,8 @@ import { reportSchema, taskId } from '../src/records.ts'
import { prioritiesOf } from '../src/tasks.ts'
import { setup } from './fixture.ts'
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -40,9 +40,9 @@ async function fixture(backend: 'jsonl' | 'sqlite') {
return { ...f, call, base, view }
}
describe.each(['jsonl', 'sqlite'] as const)('user-owned Timeline feedback (%s)', (backend) => {
describe('user-owned Timeline feedback', () => {
it('acknowledges a saved note retry after its task retires without admitting a new note', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
const request = {
action: 'annotate' as const,
@@ -73,7 +73,7 @@ describe.each(['jsonl', 'sqlite'] as const)('user-owned Timeline feedback (%s)',
}
})
it('preserves user priorities and immutable note pairs across model patches, retries, and reload', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
const request = {
action: 'annotate' as const,
@@ -130,7 +130,7 @@ describe.each(['jsonl', 'sqlite'] as const)('user-owned Timeline feedback (%s)',
}
})
it('links report discussion to exact historical content and retains drafts after failed writes', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
const report = reportSchema.parse({
id: 'history',
@@ -187,7 +187,7 @@ describe.each(['jsonl', 'sqlite'] as const)('user-owned Timeline feedback (%s)',
}
})
it('does not send an expired priority notice or fail a running turn when injection throws', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
f.start()
await f.adapter.ready.promise
@@ -210,7 +210,7 @@ describe.each(['jsonl', 'sqlite'] as const)('user-owned Timeline feedback (%s)',
}
})
it('inherits priority without changing completion and coalesces only P0 notices for running work', async () => {
const f = await fixture(backend)
const f = await fixture()
try {
await f.ctx.timeline.edit({
...f.base,
@@ -122,7 +122,6 @@ export class Adapter extends LlmAdapter {
}
}
export async function setup(
backend: 'jsonl' | 'sqlite',
config: Partial<Timeline.Config> = {},
adapter = new Adapter(),
restore?: { root: string; sessionId: SessionId },
@@ -130,7 +129,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: backend })
await ctx.plugin(Jsonl, { root, compression: 'none' })
ctx.llm.registerAdapter(['fixture'], adapter)
ctx.tools.register(
defineTool({
@@ -10,8 +10,8 @@ afterEach(async () => {
vi.useRealTimers()
for (const f of fixtures.splice(0)) await f.close()
})
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend)
async function fixture() {
const f = await setup()
fixtures.push(f)
let sequence = 0
const call = (name: string, args: object, id = `history-${sequence++}`) =>
@@ -26,9 +26,9 @@ async function fixture(backend: 'jsonl' | 'sqlite') {
return { f, call }
}
describe.each(['jsonl', 'sqlite'] as const)('internal task revision history (%s)', (backend) => {
describe('internal task revision history', () => {
it('records edits and derived group progress once, without recording no-ops or failed batches', async () => {
const { f, call } = await fixture(backend)
const { f, call } = await fixture()
expect(
(
await call('timeline_tasks', {
@@ -92,7 +92,7 @@ describe.each(['jsonl', 'sqlite'] as const)('internal task revision history (%s)
})
it('retains each revision and its description without repeating full task details', async () => {
const { f, call } = await fixture(backend)
const { f, call } = await fixture()
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.each(['jsonl', 'sqlite'] as const)('internal task revision history (%s)
])
})
it('keeps history through restart and checkpoints but excludes it from agent and report inputs', async () => {
const { f, call } = await fixture(backend)
const { f, call } = await fixture()
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.each(['jsonl', 'sqlite'] as const)('internal task revision history (%s)
vi.useRealTimers()
await f.close({ preserve: true })
fixtures.splice(fixtures.indexOf(f), 1)
const next = await setup(backend, {}, undefined, { root, sessionId })
const next = await setup({}, 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.each(['jsonl', 'sqlite'] as const)('internal task revision history (%s)
})
it('does not publish a new revision when its durable write fails', async () => {
const { f, call } = await fixture(backend)
const { f, call } = await fixture()
await call('timeline_tasks', { tasks: [{ id: 'check', title: 'Verify restart' }] })
const before = f.ctx.timeline.stateOf(f.agent.session).view.trees
vi.spyOn(f.ctx.sessions, 'flush').mockRejectedValueOnce(new Error('Write failed'))
@@ -11,10 +11,10 @@ import {
} from '@deepseek-ai/dsh-agent-loop-testkit'
import * as Timeline from '@deepseek-ai/dsh-timeline'
const [mode, root, id, storage] = process.argv.slice(2)
const [mode, root, id] = process.argv.slice(2)
const ctx = new Context()
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(Jsonl, { root, storage, compression: 'none' })
await ctx.plugin(Jsonl, { root, compression: 'none' })
try {
if (mode === 'compete') {
try {
@@ -8,12 +8,12 @@ import { describe, expect, it } from 'vitest'
import { SessionId } from '@deepseek-ai/dsh-session'
import { Adapter, setup } from './fixture.ts'
describe.each(['jsonl', 'sqlite'] as const)('Timeline persistence across built Host processes (%s)', (backend) => {
describe('Timeline persistence across built Host processes', () => {
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, backend], {
const child = spawn(process.execPath, [fileURLToPath(new URL('./host-process.mjs', import.meta.url)), mode, root, sessionId], {
cwd: process.cwd(),
env: {},
stdio: ['pipe', 'pipe', 'pipe'],
@@ -54,7 +54,7 @@ describe.each(['jsonl', 'sqlite'] as const)('Timeline persistence across built H
}
owner.child.kill('SIGKILL')
expect((await owner.closed)[1]).toBe('SIGKILL')
const recovered = await setup(backend, { intervalMs: 86400000 }, new Adapter(), { root, sessionId })
const recovered = await setup({ intervalMs: 86400000 }, new Adapter(), { root, sessionId })
try {
const view = recovered.ctx.timeline.stateOf(recovered.agent.session).view
expect(view.trees[0]?.tasks[0]?.done).toEqual([2, 3])
@@ -10,8 +10,8 @@ afterEach(async () => {
for (const f of fixtures.splice(0)) await f.close()
})
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
fixtures.push(f)
return f
}
@@ -42,23 +42,23 @@ async function seed(f: Awaited<ReturnType<typeof setup>>) {
return tree
}
async function restart(backend: 'jsonl' | 'sqlite', f: Awaited<ReturnType<typeof setup>>, adapter = new Adapter()) {
async function restart(f: Awaited<ReturnType<typeof setup>>, adapter = new Adapter()) {
const restore = { root: f.root, sessionId: f.agent.session.id }
await f.close({ preserve: true })
fixtures.splice(fixtures.indexOf(f), 1)
const next = await setup(backend, { intervalMs: 86400000 }, adapter, restore)
const next = await setup({ intervalMs: 86400000 }, adapter, restore)
fixtures.push(next)
return next
}
describe.each(['jsonl', 'sqlite'] as const)('session-scoped Timeline persistence (%s)', (backend) => {
describe('session-scoped Timeline persistence', () => {
it('reopens an ordinary saved Session without creating a plan or disrupting its next turn', async () => {
const f = await fixture(backend)
const f = await fixture()
await f.ctx.sessions.flush(f.agent.session)
const adapter = new Adapter()
adapter.calls = 0
adapter.release.resolve(undefined)
const next = await restart(backend, f, adapter)
const next = await restart(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.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
const tree = await seed(f)
await f.ctx.timeline.edit({
action: 'priority',
@@ -120,7 +120,7 @@ describe.each(['jsonl', 'sqlite'] as const)('session-scoped Timeline persistence
}),
})
const saved = f.ctx.timeline.stateOf(f.agent.session)
const next = await restart(backend, f)
const next = await restart(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.each(['jsonl', 'sqlite'] as const)('session-scoped Timeline persistence
})
it('does not reapply an older tool call after newer checkpoints, selection changes, or restart', async () => {
const f = await fixture(backend)
const f = await fixture()
const tree = await seed(f)
const first = {
name: 'timeline_tasks',
@@ -148,7 +148,7 @@ describe.each(['jsonl', 'sqlite'] as const)('session-scoped Timeline persistence
).isError,
).not.toBe(true)
await call(f, 'timeline_tree', { action: 'start', title: 'Another goal' })
const next = await restart(backend, f)
const next = await restart(f)
const selected = next.ctx.timeline.stateOf(next.agent.session).view.activeTreeId
const result = await executeTool(next.ctx, { ...first, agent: next.agent })
expect(result.isError).not.toBe(true)
@@ -30,8 +30,8 @@ const resultSchema = z.object({
hasMore: z.boolean(),
})
async function scenario(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
async function scenario() {
const f = await setup({ intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object = {}) =>
executeTool(f.ctx, {
@@ -51,9 +51,9 @@ async function scenario(backend: 'jsonl' | 'sqlite') {
return { ...f, call, pull }
}
describe.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backend) => {
describe('next-work checkpoints', () => {
it('does not create a plan on an empty session and rejects unknown or invalid queries', async () => {
const f = await scenario(backend)
const f = await scenario()
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.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backe
})
it('prefers inherited user priority, then active leaves, without editing or returning groups', async () => {
const f = await scenario(backend)
const f = await scenario()
try {
await f.call('timeline_tree', { action: 'start', title: 'Deliver the requested work' })
await f.call('timeline_tasks', {
@@ -101,7 +101,7 @@ describe.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backe
})
it('rechecks blockers after runnable work ends and preserves deliberate pauses', async () => {
const f = await scenario(backend)
const f = await scenario()
try {
await f.call('timeline_tree', { action: 'start', title: 'Check dependencies' })
await f.call('timeline_tasks', {
@@ -147,7 +147,7 @@ describe.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backe
})
it('keeps persistent blockers visible after their reasons are reconfirmed', async () => {
const f = await scenario(backend)
const f = await scenario()
try {
await f.call('timeline_tree', { action: 'start', title: 'Publish the result' })
await f.call('timeline_tasks', {
@@ -173,7 +173,7 @@ describe.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backe
})
it('bounds suggestions and permits a complete blocker check when the default is truncated', async () => {
const f = await scenario(backend)
const f = await scenario()
try {
await f.call('timeline_tree', { action: 'start', title: 'Check remaining work' })
await f.call('timeline_tasks', {
@@ -196,7 +196,7 @@ describe.each(['jsonl', 'sqlite'] as const)('next-work checkpoints (%s)', (backe
})
it('checks only the addressed goal and never selects or resumes a different tree', async () => {
const f = await scenario(backend)
const f = await scenario()
try {
await f.call('timeline_tree', { action: 'start', title: 'Earlier goal' })
await f.call('timeline_tasks', {
@@ -21,9 +21,9 @@ const checkpoint = (options: Adapter['main'][number] | undefined) =>
?.content.some(block => block.type === 'text' && block.text.includes('Task progress checkpoint')) ??
false
describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (backend) => {
describe('stale task-tree reminders', () => {
it('reports unavailable persistence and keeps that context stable within the turn', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const available = vi.spyOn(f.ctx.timeline, 'available').mockReturnValue(false)
try {
const context = async (signal?: AbortSignal) => {
@@ -45,7 +45,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
}
})
it('keeps one saved-plan snapshot per turn and refreshes it on the next turn, preserving progress', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -127,7 +127,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
}
})
it('shows an empty saved plan as pending', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
try {
await executeTool(f.ctx, {
name: 'timeline_tree', arguments: { action: 'start', title: 'Plan the release' },
@@ -141,7 +141,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
}
})
it('adds discussion handling only while a saved user annotation is open', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const call = (name: string, args: object) =>
executeTool(f.ctx, {
name,
@@ -185,7 +185,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
}
})
it('counts repeated admission for the same agent step once', async () => {
const f = await setup(backend, { intervalMs: 86400000, reminderIterations: 2 })
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
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(backend, { intervalMs: 86400000, reminderIterations: 7 }, adapter)
const f = await setup({ intervalMs: 86400000, reminderIterations: 7 }, adapter)
adapter.mainActions[0] = () => {
updateVolatile(
(f.plugin.effectiveConfig as PluginConfig).reminderIterations,
@@ -237,7 +237,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
async (status) => {
const adapter = new Adapter()
adapter.steps = 0
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ intervalMs: 86400000 }, adapter)
try {
for (const [name, args] of [
['timeline_tree', { action: 'start', title: 'Saved goal' }],
@@ -272,7 +272,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
const adapter = new Adapter()
adapter.steps = 49
adapter.mainActions[23] = () => [{ name: 'timeline_read', arguments: '{}' }]
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ intervalMs: 86400000 }, adapter)
try {
f.start()
await adapter.ready.promise
@@ -299,7 +299,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
arguments: JSON.stringify({ tasks: [{ id: 'work', title: 'Ongoing work', status: 'active' }] }),
},
]
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ intervalMs: 86400000 }, adapter)
try {
f.start()
await adapter.ready.promise
@@ -318,7 +318,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
it('does not extend a closing response that reaches the reminder threshold', async () => {
const adapter = new Adapter()
adapter.steps = 23
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ intervalMs: 86400000 }, adapter)
try {
f.start()
await adapter.ready.promise
@@ -347,7 +347,7 @@ describe.each(['jsonl', 'sqlite'] as const)('stale task-tree reminders (%s)', (b
adapter.mainActions[23] = () => [
{ name: 'timeline_tasks', arguments: JSON.stringify({ tasks: [{ id: 'missing' }] }) },
]
const f = await setup(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ intervalMs: 86400000 }, adapter)
const call = (name: string, args: object) =>
executeTool(f.ctx, {
name,
@@ -18,19 +18,19 @@ afterEach(async () => {
for (const fixture of fixtures.splice(0)) await fixture.close()
vi.useRealTimers()
})
async function running(backend: 'jsonl' | 'sqlite', config = {}, adapter = new Adapter()) {
const fixture = await setup(backend, config, adapter)
async function running(config = {}, adapter = new Adapter()) {
const fixture = await setup(config, adapter)
fixtures.push(fixture)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
fixture.start()
await adapter.ready.promise
return fixture
}
describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real agent loop (%s)', (backend) => {
describe('background summaries through a real agent loop', () => {
it('admits a waiting third Session before serving the earlier sessions again', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await setup(backend, { maxConcurrent: 1, rollupFactors: [] }, adapter)
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
}
}
const adapter = new SelectiveAdapter()
const f = await setup(backend, { rollupFactors: [3], timeoutMs: 50 }, adapter)
const f = await setup({ rollupFactors: [3], timeoutMs: 50 }, adapter)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
try {
f.start()
@@ -122,7 +122,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { reportsEnabled: false }, adapter)
const f = await setup({ reportsEnabled: false }, adapter)
fixtures.push(f)
const session = f.agent.session
const now = Date.now()
@@ -157,7 +157,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
}
})
it('uses the newly selected provider for a due rollup when work resumes', async () => {
const f = await setup(backend, { rollupFactors: [2] })
const f = await setup({ rollupFactors: [2] })
const replacement = new Adapter()
replacement.calls = 0
f.ctx.llm.registerAdapter(['replacement'], replacement)
@@ -196,7 +196,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
})
it('defers dispatch when Session persistence cannot acknowledge the interval', async () => {
const f = await running(backend)
const f = await running()
const flush = vi.spyOn(f.ctx.sessions, 'flush').mockResolvedValueOnce(false)
try {
await vi.advanceTimersByTimeAsync(60000)
@@ -209,7 +209,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
}
})
it('keeps the turn alive if neither a report request nor its failure can be saved', async () => {
const f = await running(backend)
const f = await running()
const failed = Promise.withResolvers<undefined>()
const append = vi.spyOn(f.ctx.timeline, 'append')
.mockRejectedValueOnce('Report storage unavailable')
@@ -238,7 +238,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
arguments: JSON.stringify({ action: 'start', title: 'Fix session recovery' }),
},
]
const f = await running(backend, { reportsEnabled: false }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('keeps saved reports and resumes base reports and rollups after enabling', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running(backend, { rollupFactors: [2] }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('cancels an in-flight report without recording a failure or stopping the turn', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
const { reportsEnabled } = f.plugin.effectiveConfig as PluginConfig
@@ -286,7 +286,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { language }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it.each([true, false])(
'identifies independent-runtime main requests through Agent admission; main=%s',
async (main) => {
const f = await running(backend)
const f = await running()
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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it.each(['compaction', 'session-title'] as const)(
'excludes %s requests even when they share the admitted turn signal',
async (purpose) => {
const f = await running(backend)
const f = await running()
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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
},
)
it('ignores an already cancelled main request and keeps the previous report context', async () => {
const f = await running(backend)
const f = await running()
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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend)
const f = await running()
const append = vi.spyOn(f.ctx.timeline, 'append').mockImplementationOnce(async () => {
throw new Error('Cannot save request')
})
@@ -397,7 +397,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('applies elapsed thresholds to complete non-multiple periods without reusing children', async () => {
const adapter = new Adapter()
adapter.calls = 0
const f = await running(backend, { intervalMs: 600000, rollupFactors: [2.5, 2.4] }, adapter)
const f = await running({ intervalMs: 600000, rollupFactors: [2.5, 2.4] }, adapter)
let previous = 0
for (const [minute, count] of [
[10, 1],
@@ -426,7 +426,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
})
})
it('adds every level prompt to the global instructions, including the first level', async () => {
const f = await running(backend, {
const f = await running({
summaryPrompt: 'Global stable instructions.',
levelPrompts: ['First-level emphasis.', 'Higher-level emphasis.'],
rollupFactors: [2],
@@ -445,7 +445,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
const f = await running({ intervalMs: 900000, rollupFactors: [4, 4] }, adapter)
await vi.advanceTimersByTimeAsync(899999)
expect(f.reports()).toHaveLength(0)
await vi.advanceTimersByTimeAsync(1)
@@ -462,7 +462,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { language: 'zh-CN' }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
userActions: [],
}),
]
const f = await running(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]?.summary).toEqual(summary)
@@ -500,7 +500,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend)
const f = await running()
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
const end = f.reports()[0]?.end
@@ -523,7 +523,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
'covers completed tool work while another tool is running; prior work %s',
async (priorWork) => {
const adapter = new Adapter()
const f = await setup(backend, {}, adapter)
const f = await setup({}, adapter)
fixtures.push(f)
const started = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
@@ -573,7 +573,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
},
)
it('waits for the next complete snapshot when the surface changes without a new tool call', async () => {
const f = await running(backend)
const f = await running()
const session = f.agent.session
session.append('user/message', createUserMessage({
source: { kind: 'user' },
@@ -592,7 +592,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
],
defaultEffort: ReasoningEffortId('maximum'),
}
const f = await running(backend, { reportReasoningEffort: 'brief', reportMaxTokens: 512 }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { reportReasoningEffort: 'unavailable' })
const f = await running({ reportReasoningEffort: 'unavailable' })
await vi.advanceTimersByTimeAsync(60000)
await vi.waitFor(() => {
expect(f.records.some(record =>
@@ -614,7 +614,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend)
const f = await running()
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]?.summary).toEqual(summary)
@@ -635,7 +635,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
)
})
it('keeps tool results as report context without offering the main task tools to the summarizer', async () => {
const f = await running(backend)
const f = await running()
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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { maxResponseBytes: Buffer.byteLength(adapter.answer) + 128 }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/report')
expect(f.reports()[0]).toMatchObject({
@@ -676,7 +676,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { rollupFactors: [2, 2] }, adapter)
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
expect(adapter.checks).toHaveLength(0)
})
it('uses the editable prompt for base reports and rollups', async () => {
const f = await running(backend, { summaryPrompt: 'Custom short report instructions.', rollupFactors: [2] })
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { rollupFactors: [2], levelPrompts: ['', 'Combine the child results.'] })
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { rollupFactors: [2], levelPrompts: ['', 'Condense child reports.'] })
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { rollupFactors: [2] })
const f = await running({ rollupFactors: [2] })
const references = f.plugin.effectiveConfig as PluginConfig
const changed = Config({
intervalMs: 120000,
@@ -784,7 +784,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await f.waitRecords('plugin:timeline/failure')
expect(f.reports()).toHaveLength(0)
@@ -800,7 +800,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { rollupFactors: [2] }, adapter)
const f = await setup({ rollupFactors: [2] }, adapter)
fixtures.push(f)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
const session = f.agent.session
@@ -835,7 +835,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
})
it('rolls up saved reports whose older records lack generation and activity times', async () => {
const adapter = new Adapter()
const f = await setup(backend, { rollupFactors: [2] }, adapter)
const f = await setup({ rollupFactors: [2] }, adapter)
fixtures.push(f)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date', 'performance'] })
const session = f.agent.session
@@ -859,7 +859,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
expect(adapter.checks).toHaveLength(2)
})
it('commits a buffered report once when a report flush fails before recovery', async () => {
const f = await running(backend, { rollupFactors: [2] })
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('counts main work during an auxiliary query toward the next report', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
await vi.advanceTimersByTimeAsync(30000)
@@ -895,7 +895,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('aborts and drains a summary when the plugin unloads', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
expect(adapter.active).toBe(1)
@@ -907,7 +907,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it.each([1, 4])(
'catches up due levels after %ih idle without counting idle time as work',
async (hours) => {
const f = await running(backend, { intervalMs: 900000, rollupFactors: [4, 4] })
const f = await running({ intervalMs: 900000, rollupFactors: [4, 4] })
const start = Date.now()
await vi.advanceTimersByTimeAsync(24000)
f.adapter.release.resolve(undefined)
@@ -934,7 +934,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
},
)
it('reconciles uncovered work across a plugin reload and keeps captured report ranges stable', async () => {
const f = await running(backend, { rollupFactors: [2] })
const f = await running({ rollupFactors: [2] })
const start = Date.now()
await vi.advanceTimersByTimeAsync(24000)
f.adapter.release.resolve(undefined)
@@ -966,7 +966,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
})
})
it('retries a failed rollup before another base report is due', async () => {
const f = await running(backend, { intervalMs: 600000, rollupFactors: [2.5] })
const f = await running({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
})
it('restores successful thresholds and uncovered short work in a fresh Host', async () => {
const config = { intervalMs: 900000, rollupFactors: [4, 4] }
const f = await running(backend, config)
const f = await running(config)
await vi.advanceTimersByTimeAsync(900000)
await f.waitRecords('plugin:timeline/report')
const first = f.reports()[0]
@@ -1012,7 +1012,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
await vi.advanceTimersByTimeAsync(4 * 3600000)
const adapter = new Adapter()
adapter.calls = 0
const next = await setup(backend, config, adapter, restore)
const next = await setup(config, adapter, restore)
fixtures.push(next)
expect(next.reports()).toEqual([first])
expect(adapter.checks).toHaveLength(0)
@@ -1029,7 +1029,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
expect(next.reports()).toHaveLength(4)
})
it('schedules reports only for agents in the plugin scope', async () => {
const f = await setup(backend, {}, new Adapter())
const f = await setup({}, new Adapter())
fixtures.push(f)
await f.plugin.dispose()
const parent = {}
@@ -1063,7 +1063,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { intervalMs: 60000 })
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
const config = { intervalMs: 600000, rollupFactors: [2.5] }
const adapter = new Adapter()
adapter.calls = 0
const f = await running(backend, config, adapter)
const f = await running(config, adapter)
for (const count of [1, 2]) {
await vi.advanceTimersByTimeAsync(600000)
await f.waitRecords('plugin:timeline/report', count)
@@ -1105,7 +1105,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
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(backend, { intervalMs: 900000, rollupFactors: [4, 4] })
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('records a timeout and drains the canceled auxiliary stream', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running(backend, { timeoutMs: 50 }, adapter)
const f = await running({ timeoutMs: 50 }, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
await vi.advanceTimersByTimeAsync(50)
@@ -1131,7 +1131,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('does not rearm a disposed Agent after its independent report settles', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running(backend, {}, adapter)
const f = await running({}, adapter)
await vi.advanceTimersByTimeAsync(60000)
await adapter.checkStarted.promise
await f.disposeAgent()
@@ -1142,7 +1142,7 @@ describe.each(['jsonl', 'sqlite'] as const)('background summaries through a real
it('bounds concurrent summaries queued by multiple Sessions', async () => {
const adapter = new Adapter()
adapter.checkRelease = Promise.withResolvers<undefined>()
const f = await running(backend, { maxConcurrent: 1 }, adapter)
const f = await running({ maxConcurrent: 1 }, adapter)
const others = await Promise.all(
['second', 'third'].map(async (id) => {
const agent = await f.harness.create(SessionId(id), { provider: 'fixture', model: 'timeline' })
@@ -14,8 +14,8 @@ const fixtures: Awaited<ReturnType<typeof setup>>[] = []
afterEach(async () => {
for (const fixture of fixtures.splice(0)) await fixture.close()
})
async function fixture(backend: 'jsonl' | 'sqlite') {
const value = await setup(backend, { intervalMs: 86400000 })
async function fixture() {
const value = await setup({ intervalMs: 86400000 })
fixtures.push(value)
return value
}
@@ -28,9 +28,9 @@ function tree(session: Session, id = 'work'): TimelineRecordMap['plugin:timeline
}
}
describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (backend) => {
describe('public Timeline storage', () => {
it('flushes a buffered priority before a queued retry returns and sends one notice', async () => {
const f = await fixture(backend)
const f = await fixture()
const session = f.agent.session
const change = tree(session)
const task = taskId.parse('check')
@@ -61,7 +61,7 @@ describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
}
})
it('keeps whole-tree discussion context and treats an unchanged priority as a no-op', async () => {
const f = await fixture(backend)
const f = await fixture()
const session = f.agent.session
const change = tree(session)
const task = taskId.parse('check')
@@ -89,7 +89,7 @@ describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
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(backend)
const f = await fixture()
const owner = new Peer(f.ctx, { principal: { kind: 'owner' } })
const viewer = new Peer(f.ctx, {
principal: {
@@ -132,7 +132,7 @@ describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
}
})
it('rejects edits against unavailable targets and unacknowledged sessions', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
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(backend)
const f = await fixture()
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -180,7 +180,7 @@ describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
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(backend)
const f = await fixture()
const session = f.agent.session
const change = tree(session)
change.tree.tasks = patchTasks([], Array.from({ length: 180 }, (_, index) => ({
@@ -192,7 +192,7 @@ describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
expect(f.ctx.timeline.stateOf(session).view.trees).toEqual([])
})
it('drains an acknowledged log write before plugin unload finishes', async () => {
const f = await fixture(backend)
const f = await fixture()
const change = tree(f.agent.session)
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
const admitted = Promise.withResolvers<undefined>()
@@ -211,7 +211,7 @@ describe.each(['jsonl', 'sqlite'] as const)('public Timeline storage (%s)', (bac
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(backend)
const f = await fixture()
const { session: other } = await f.ctx.agents.create({ sessionId: SessionId('other'), meta: { cwd: process.cwd() } }).then(result => result.agent)
await f.ctx.timeline.append(f.agent.session, 'plugin:timeline/tree', tree(f.agent.session))
expect(f.ctx.timeline.stateOf(other).view.trees).toEqual([])
@@ -25,9 +25,9 @@ function toolsOf(fixture: Awaited<ReturnType<typeof setup>>, prefix: string) {
})
}
describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop (%s)', (backend) => {
describe('agent tools in the production loop', () => {
it('reports only open task discussions in status queries and exposes saved report failures', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const call = toolsOf(f, 'discussion')
const session = f.agent.session
try {
@@ -55,7 +55,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const call = toolsOf(f, 'incomplete-view')
const session = f.agent.session
try {
@@ -86,7 +86,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('reports an unexpected task validation failure without saving the patch', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const call = toolsOf(f, 'invalid-patch')
try {
await call('timeline_tree', { action: 'start', title: 'Review recovery' })
@@ -104,7 +104,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await setup()
try {
for (const [name, args, title] of [
['timeline_tree', { action: 'start', title: 'Plan' }, 'Timeline task tree'],
@@ -128,7 +128,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('selects existing trees, bounds new trees, and validates each read target', async () => {
const f = await setup(backend, { intervalMs: 86400000, maxTrees: 2 })
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const run = toolsOf(f, 'card')
const call = (id: string, name: string, args: object) => run(name, args, id)
const readReceipt = (result: Awaited<ReturnType<typeof call>>) =>
@@ -214,7 +214,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('serializes concurrent card baselines with the acknowledged task writes', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
let id = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -252,7 +252,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000, taskPrompt: 'Explain what recovery checks prove.' })
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -335,7 +335,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('distinguishes the complete report count from its bounded recent sample', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
try {
const call = {
name: 'timeline_tree',
@@ -413,7 +413,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('toggles only Timeline-owned Todo restrictions through live settings without changing presets', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const parent = {}
const preset = createScope(f.ctx, parent)
let writes = 0
@@ -473,7 +473,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ 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.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('updates the fixed language rule in the next prompt assembly', async () => {
const f = await setup(backend)
const f = await setup()
try {
const prompt = () => f.ctx.systemPrompt.assemble({ scope: f.agent })
expect(
@@ -526,7 +526,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('denies an explicit agent-local Todo override without breaking registration', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
let writes = 0
try {
await f.agent.ctx.inject(['tools'], (scope) => {
@@ -563,7 +563,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('replaces inherited preset Todo tools and restores them when unloaded', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const parent = {}
const preset = createScope(f.ctx, parent)
try {
@@ -616,7 +616,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend, { intervalMs: 86400000 }, adapter)
const f = await setup({ intervalMs: 86400000 }, adapter)
try {
adapter.mainActions = [
() => [
@@ -685,7 +685,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('updates an addressed tree and returns weights without ETA inputs', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
const call = async (name: string, args: object) => {
const result = await executeTool(f.ctx, {
name,
@@ -739,7 +739,7 @@ describe.each(['jsonl', 'sqlite'] as const)('agent tools in the production loop
}
})
it('returns bounded leaf-status queries without changing selection or including report history', async () => {
const f = await setup(backend, { intervalMs: 86400000 })
const f = await setup({ intervalMs: 86400000 })
let count = 0
const call = (name: string, args: object) =>
executeTool(f.ctx, {
@@ -1,6 +1,6 @@
import { pluginRecordOf, SessionId } from '@deepseek-ai/dsh-session'
import { executeTool } from './execute-tool.ts'
import { cp, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { cp, mkdtemp, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -15,8 +15,8 @@ const fixtures: Awaited<ReturnType<typeof setup>>[] = []
afterEach(async () => {
for (const fixture of fixtures.splice(0)) await fixture.close()
})
async function fixture(backend: 'jsonl' | 'sqlite') {
const f = await setup(backend, { intervalMs: 86400000 })
async function fixture() {
const f = await setup({ intervalMs: 86400000 })
f.adapter.calls = 0
f.adapter.release.resolve(undefined)
fixtures.push(f)
@@ -38,20 +38,20 @@ const imported = (
continue: proceed,
})
describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public storage (%s)', (backend) => {
describe('task-tree transfer through public storage', () => {
it('rejects import conflicts and configured tree and task limits', async () => {
const f = await setup(backend, { maxTrees: 1 })
const f = await setup({ 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(backend, { maxTasks: 1 })
const bounded = await setup({ 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(backend)
const f = await fixture()
const first = await imported(f)
if (first.action !== 'import') throw new Error('Missing import result')
expect(
@@ -86,7 +86,7 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
f.start()
await f.agent.whenIdle()
f.adapter.main = []
@@ -162,7 +162,7 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
expect(f.adapter.main).toHaveLength(1)
})
it('rejects damaged imports and uncertain saves without publishing a partial tree', async () => {
const f = await fixture(backend)
const f = await fixture()
await expect(
f.ctx.timeline.edit({
action: 'import',
@@ -180,7 +180,7 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
const adapter = new Adapter()
adapter.calls = 0
adapter.release.resolve(undefined)
const recovered = await setup(backend, { intervalMs: 86400000 }, adapter, { root, sessionId: session.id })
const recovered = await setup({ 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.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
}
})
it('recovers an unacknowledged ready marker without a second tree or continuation', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
expect(f.adapter.main).toHaveLength(1)
})
it('keeps a parked continuation across restart and never queues it twice', async () => {
const f = await fixture(backend)
const f = await fixture()
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,20 +252,12 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
const id = f.agent.inbox.nextTurn[0]?.id
expect(id).toBeDefined()
const crashStore = await mkdtemp(join(tmpdir(), 'timeline-parked-'))
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 })
}
await cp(root, crashStore, { recursive: true })
const adapter = new Adapter()
adapter.calls = 0
adapter.release.resolve(undefined)
const recovered = await setup(backend, { intervalMs: 86400000 }, adapter, { root, sessionId: session.id })
fixtures.splice(fixtures.indexOf(f), 1, recovered)
const recovered = await setup({ intervalMs: 86400000 }, adapter, { root: crashStore, sessionId: session.id })
fixtures.push(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()
@@ -277,7 +269,7 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
await expect(f.ctx.timeline.edit({
action: 'import',
sessionId: f.agent.session.id,
@@ -291,7 +283,7 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
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(backend)
const f = await fixture()
const flush = f.ctx.sessions.flush.bind(f.ctx.sessions)
const admitted = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
@@ -318,9 +310,9 @@ describe.each(['jsonl', 'sqlite'] as const)('task-tree transfer through public s
})
})
describe.each(['jsonl', 'sqlite'] as const)('human Timeline command (%s)', (backend) => {
describe('human Timeline command', () => {
it('imports without a session working directory and reports filesystem and result failures', async () => {
const f = await fixture(backend)
const f = await fixture()
await f.ctx.plugin(Commands)
await f.ctx.plugin(FsLocal, { cwd: f.root })
const { agent } = await f.ctx.agents.create({
@@ -339,7 +331,7 @@ describe.each(['jsonl', 'sqlite'] as const)('human Timeline command (%s)', (back
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(backend)
const f = await fixture()
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')
@@ -354,7 +346,7 @@ describe.each(['jsonl', 'sqlite'] as const)('human Timeline command (%s)', (back
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(backend)
const f = await fixture()
await f.ctx.plugin(Commands)
await f.ctx.plugin(FsLocal, { cwd: f.root })
const path = join(f.root, 'plan.timeline.json')
@@ -379,7 +371,7 @@ describe.each(['jsonl', 'sqlite'] as const)('human Timeline command (%s)', (back
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(backend)
const f = await fixture()
await f.ctx.plugin(Commands)
await f.ctx.plugin(FsLocal, { cwd: f.root })
const path = join(f.root, 'my plan.timeline.json')
@@ -22,23 +22,23 @@ import { mountWorkflowRuntime } from '../../../workflow/workflow-ptc/tests/setup
type MockScript = ConstructorParameters<typeof MockAdapter>[0]
const testToolSignal = new AbortController().signal
async function mountExecution(backend: 'jsonl' | 'sqlite', ctx: Context): Promise<string> {
async function mountExecution(ctx: Context): Promise<string> {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-ralph-'))
onTestFinished(async () => {
await ctx.fiber.dispose()
await rm(cwd, { recursive: true, force: true })
})
await mountWorkflowRuntime(ctx, { cwd })
await ctx.plugin(JsonlSessionPersistence, { root: join(cwd, '.sessions'), storage: backend })
await ctx.plugin(JsonlSessionPersistence, { root: join(cwd, '.sessions') })
return cwd
}
/** Mount the shipped Ralph execution stack around one keyless model script. */
async function mountRalph(backend: 'jsonl' | 'sqlite', script: MockScript, config: toolRalph.Config) {
async function mountRalph(script: MockScript, config: toolRalph.Config) {
const ctx = new Context()
const adapter = new MockAdapter(script)
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
const cwd = await mountExecution(backend, ctx)
const cwd = await mountExecution(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(spawn, { providerName: 'spawn' })
@@ -53,7 +53,7 @@ async function mountRalph(backend: 'jsonl' | 'sqlite', script: MockScript, confi
return { ctx, adapter, parentHandle, parent: parentHandle.agent }
}
describe.each(['jsonl', 'sqlite'] as const)('dsh-tool-ralph over the real spawn and sandboxed PTC stack (%s)', (backend) => {
describe('dsh-tool-ralph over the real spawn and sandboxed PTC stack', () => {
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.each(['jsonl', 'sqlite'] as const)('dsh-tool-ralph over the real spawn
toolCallResponse('round-2', STRUCTURED_OUTPUT_TOOL, finalReport),
])
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true })
const cwd = await mountExecution(backend, ctx)
const cwd = await mountExecution(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(SubagentRuntime)
await ctx.plugin(spawn, { providerName: 'spawn' })
@@ -144,7 +144,7 @@ describe.each(['jsonl', 'sqlite'] as const)('dsh-tool-ralph over the real spawn
nextSteps: ['Finish migration-b.ts.'],
blocker: '',
}
const { ctx, parent, parentHandle } = await mountRalph(backend, [
const { ctx, parent, parentHandle } = await mountRalph([
toolCallResponse('round-1', STRUCTURED_OUTPUT_TOOL, firstReport),
maxTokensResponse('unfinished child output'),
], { maxRounds: 2 })
@@ -236,7 +236,7 @@ describe.each(['jsonl', 'sqlite'] as const)('dsh-tool-ralph over the real spawn
expectedText: 'Ralph round report exceeds maxHandoffChars',
},
])('enforces the fixed script for $name', async ({ report, config, expectedError, expectedText }) => {
const { ctx, parent, parentHandle } = await mountRalph(backend, [
const { ctx, parent, parentHandle } = await mountRalph([
toolCallResponse('round-report', STRUCTURED_OUTPUT_TOOL, report),
], config)
@@ -254,7 +254,7 @@ describe.each(['jsonl', 'sqlite'] as const)('dsh-tool-ralph over the real spawn
})
it('cancels the sandboxed process and fresh child to quiescence', { timeout: 90_000 }, async () => {
const { ctx, parent, parentHandle } = await mountRalph(backend, ['hang'], { maxRounds: 2 })
const { ctx, parent, parentHandle } = await mountRalph(['hang'], { maxRounds: 2 })
const children: Agent[] = []
const outcomes: string[] = []
let resolveChildStarted!: (child: Agent) => void
@@ -39,7 +39,7 @@ async function registerTurnBoundary(ctx: Context): Promise<void> {
await ctx.plugin(AgentRegistry)
}
describe.each(['jsonl', 'sqlite'] as const)('tool-session-query with the real SQLite query provider and %s persistence', (backend) => {
describe('tool-session-query with the real SQLite provider', () => {
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.each(['jsonl', 'sqlite'] as const)('tool-session-query with the real SQ
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none', storage: backend })
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await ctx.plugin(SqliteSessionQueryEngine, { path: join(root, 'session-query.db') })
await ctx.plugin(ToolSessionQuery)
@@ -125,7 +125,7 @@ describe.each(['jsonl', 'sqlite'] as const)('tool-session-query with the real SQ
await ctx.plugin(SystemPrompt)
await ctx.plugin(ToolRuntime)
await ctx.plugin(NativeToolExecutor)
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none', storage: backend })
await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' })
await ctx.plugin(SqliteSessionQueryEngine, { path: join(root, 'session-query.db') })
await ctx.plugin(ToolSessionQuery)
@@ -1,6 +1,9 @@
/** 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 { pluginRecordOf, type SessionId, SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session'
import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence'
import type { JsonlHandleStorage } from '../../../session/session-persistence-jsonl/src/storage.ts'
import { readFile } from 'node:fs/promises'
import { setImmediate } from 'node:timers/promises'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { paidFixture } from './paid-fixture.ts'
@@ -35,47 +38,38 @@ function historicalEvents(): SessionEvent[] {
]
}
describe.each(['jsonl', 'sqlite'] as const)('common paid translation persistence (%s)', (backend) => {
describe('common paid translation persistence', () => {
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, backend, { translator: { deepseekTimeoutMs: 60_000 } })
const b = await paidFixture(cleanups, { translator: { deepseekTimeoutMs: 60_000 } }), backend = b.ctx.sessionPersistence as SessionPersistence & Pick<JsonlHandleStorage, 'persistBatch'>
expect(typeof backend.persistBatch).toBe('function')
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
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) {
const persist = backend.persistBatch.bind(backend)
vi.spyOn(backend, 'persistBatch').mockImplementation(async (...args) => {
if (results(args[1]).length > 0) {
entered.resolve(undefined)
await release.promise
}
return flush(session)
return persist(...args)
})
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 {
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]()
}
else await vi.advanceTimersByTimeAsync(60_000)
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 open = vi.spyOn(b.ctx.sessionPersistence, 'open')
const stat = vi.spyOn(backend, 'stat')
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 = open.mock.calls.length
const readsBeforeCommit = stat.mock.calls.length
release.resolve(undefined)
await expect(retry).resolves.toEqual({ text: '翻译结果' })
expect(readsBeforeCommit).toBe(0)
@@ -87,14 +81,13 @@ describe.each(['jsonl', 'sqlite'] as const)('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, backend), id = b.session!.id, oldContext = b.ctx
const b = await paidFixture(cleanups), 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)
@@ -119,7 +112,7 @@ describe.each(['jsonl', 'sqlite'] as const)('common paid translation persistence
it.each(providers)('requires a live writer for uncached %s before preparation and retains independent input and result', async (provider) => {
const id = brandString<SessionId>('historical-paid-translation')
const b = await paidFixture(cleanups, backend, { withSession: false, withSessionQuery: true })
const b = await paidFixture(cleanups, { withSession: false, withSessionQuery: true })
const original = await b.createHistorical(id, historicalEvents())
await b.restart()
using observation = await b.ctx.sessionQuery.observeSession(id, { projectionMode: 'none' })
@@ -130,7 +123,7 @@ describe.each(['jsonl', 'sqlite'] as const)('common paid translation persistence
await expect(b.ctx.translator.translate(spec)).rejects.toMatchObject({ code: 'TRANSLATION_SESSION_INACTIVE' })
expect(prepare).not.toHaveBeenCalled()
expect(b.requests).toEqual([])
expect(await b.readEvents(original.id)).toEqual(original.events)
expect(await readFile(original.file)).toEqual(original.bytes)
expect(b.ctx.sessions.list()).toEqual([])
const session = await b.activate(id)
const resumed = await b.readEvents(id), surface = await b.ctx.sessionQuery.readSurface(id)
@@ -151,7 +144,7 @@ describe.each(['jsonl', 'sqlite'] as const)('common paid translation persistence
expect(committed.slice(0, resumed.length)).toEqual(resumed)
expect(results(committed)).toHaveLength(1)
expect(results(committed)[0]).toMatchObject({ ignorable: true, data: { requestSeq: requests(committed)[0]?.seq, text: '翻译结果' } })
expect(committed.slice(0, original.events.length)).toEqual(original.events)
expect((await readFile(original.file)).subarray(0, original.bytes.length)).toEqual(original.bytes)
expect((await b.ctx.sessionPersistence.stat(id))?.header).toEqual(original.header)
const after = await b.ctx.sessionQuery.readSurface(id)
expect(after.events).toEqual(surface.events)
@@ -161,7 +154,7 @@ describe.each(['jsonl', 'sqlite'] as const)('common paid translation persistence
})
it('refuses a missing historical Session before paid dispatch', async () => {
const b = await paidFixture(cleanups, backend, { withSession: false })
const b = await paidFixture(cleanups, { withSession: false })
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ provider: 'deepseek-official', text: 'source',
targetLanguage: 'zh', sessionId: brandString<SessionId>('missing-historical') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
@@ -170,19 +163,19 @@ describe.each(['jsonl', 'sqlite'] as const)('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, backend, { withSession: false }), original = await b.createHistorical(brandString<SessionId>('owned-history'), historicalEvents())
const b = await paidFixture(cleanups, { withSession: false }), original = await b.createHistorical(brandString<SessionId>('owned-history'), historicalEvents())
await using writer = await b.ctx.sessionPersistence.open(original.id, 'write')
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ provider: 'deepseek-official', text: 'source',
targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_INACTIVE' })
expect((await writer.read()).events).toEqual(original.events)
expect(await b.readEvents(original.id)).toEqual(original.events)
expect(await readFile(original.file)).toEqual(original.bytes)
expect(b.requests).toEqual([])
expect(b.ctx.sessions.list()).toEqual([])
})
it('withholds paid translated text when its durable result cannot be written', async () => {
const b = await paidFixture(cleanups, backend), session = b.session!
const b = await paidFixture(cleanups), 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')
@@ -199,7 +192,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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, backend), id = b.session!.id
const b = await paidFixture(cleanups), id = b.session!.id
const spec = () => b.ctx.translator.resolve({ provider: 'deepseek-official', text: 'Original paragraph', targetLanguage: 'zh', sessionId: id })
expect(await b.ctx.translator.translate(spec())).toBe('翻译结果')
await b.restart({ translator: { deepseekMaxOutputTokens: 16 } })
@@ -16,7 +16,7 @@ afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
})
describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (backend) => {
describe('native Flash translation', () => {
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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('offers both actual native owners with customized settings ids and arbitrary model version names', async () => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('uses only one independent fragment despite existing main user and assistant history', async () => {
const b = await paidFixture(cleanups, backend), session = b.session!
const b = await paidFixture(cleanups), 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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
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, backend, { withSessionLog: true }), session = b.session!
const b = await paidFixture(cleanups, { 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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('respects an explicit source language in the exact independently audited prompt', async () => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('excludes pi-ai ownership, non-native settings paths, unregistered routes and inactive native rows', async () => {
const b = await paidFixture(cleanups, backend, { officialName: '@deepseek-ai/dsh-llm-pi-ai' })
const b = await paidFixture(cleanups, { 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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('requires configured credentials and exact deepseek-flash catalog identity', async () => {
const b = await paidFixture(cleanups, backend, { signedIn: false, credentialConfigured: false,
const b = await paidFixture(cleanups, { 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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
b.setSignedIn(true)
expect(await b.ctx.translator.availableProviders()).toEqual(['bing', 'google', 'deepseek-account'])
b.setConfigured(false)
const eligible = await paidFixture(cleanups, backend, { withCredentials: false })
const eligible = await paidFixture(cleanups, { withCredentials: false })
expect(await eligible.ctx.translator.availableProviders()).toContain('deepseek-official')
expect(await eligible.translate('deepseek-official')).toBe('翻译结果')
const missingAmbient = await paidFixture(cleanups, backend, { withCredentials: false, ambientConfigured: false })
const missingAmbient = await paidFixture(cleanups, { 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, backend)
const b = await paidFixture(cleanups)
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ provider: 'deepseek-account', sourceLanguage: 'auto',
targetLanguage: 'zh', text: 'source', sessionId: brandString<SessionId>('missing') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
@@ -172,7 +172,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('revalidates model configuration after asynchronous discovery and before preparing a native call', async () => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
const before = Promise.withResolvers<undefined>(), continueLookup = Promise.withResolvers<undefined>()
const original = b.ctx.llm.listModels.bind(b.ctx.llm)
const lookup = vi.spyOn(b.ctx.llm, 'listModels').mockImplementationOnce(async (provider) => {
@@ -195,7 +195,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('rechecks the owner across the eligibility return microtask before preparation', async () => {
const b = await paidFixture(cleanups, backend), directory = b.ctx.llm.listConfigurableProviders()
const b = await paidFixture(cleanups), 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.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('rejects a prepared call that cannot guarantee thinking off before auditing or network I/O', async () => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
const prepared = await b.ctx.llm.prepareCall({ provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: brandString<ReasoningEffortId>('off') })
vi.spyOn(b.ctx.llm, 'prepareCall').mockResolvedValueOnce({ ...prepared,
config: { ...prepared.config, reasoningEffort: brandString<ReasoningEffortId>('high') } })
@@ -222,7 +222,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it.each(['removed', 'replaced'])('rejects an audit Session %s during paid admission before dispatch', async (kind) => {
const b = await paidFixture(cleanups, backend, { withSession: false })
const b = await paidFixture(cleanups, { withSession: false })
const sessionId = brandString<SessionId>('transient-audit-session')
const scope = b.ctx.plugin({ inject: ['sessions'], apply: (ctx) => { ctx.sessions.create(sessionId) } })
await scope
@@ -246,13 +246,13 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it.each(['max_tokens', 'tool_use'])('rejects non-stop native finish %s while preserving the audited request', async (stop) => {
const b = await paidFixture(cleanups, backend, { reply: (response) => { response.end(sse(replyEvents('partial private output', stop))) } })
const b = await paidFixture(cleanups, { 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, backend, { responseStatus: 503,
const b = await paidFixture(cleanups, { 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,8 +261,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it.each(['withdrawn', 'catalog', 'credential'])('rejects a native route %s during async preparation before audit or dispatch', async (change) => {
const b = await paidFixture(cleanups, backend)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups), entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const original = b.ctx.llm.prepareCall.bind(b.ctx.llm)
vi.spyOn(b.ctx.llm, 'prepareCall').mockImplementationOnce(async (config, signal) => {
@@ -289,8 +288,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('rejects an Account model-override change during async preparation before audit or dispatch', async () => {
const b = await paidFixture(cleanups, backend)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups), entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const original = b.ctx.llm.prepareCall.bind(b.ctx.llm)
vi.spyOn(b.ctx.llm, 'prepareCall').mockImplementationOnce(async (config, signal) => {
const call = await original(config, signal)
@@ -308,7 +306,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it.each(['withdrawn', 'catalog', 'credential'])('rejects a native route %s by an audit observer before dispatch', async (change) => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
const owner = [...b.ctx.loader.entries()].find(entry => entry.options.id === 'official-custom-id')!
let withdrawal: Promise<void> | undefined
b.ctx.on('session/event', (_session, event) => {
@@ -326,18 +324,18 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('rejects empty text and enforces the complete multibyte output limit', async () => {
const empty = await paidFixture(cleanups, backend, { reply: (response) => { response.end(sse(replyEvents(' '))) } })
const empty = await paidFixture(cleanups, { reply: (response) => { response.end(sse(replyEvents(' '))) } })
await expect(empty.translate('deepseek-account')).rejects.toMatchObject({ code: 'TRANSLATION_INVALID_RESPONSE' })
const exact = await paidFixture(cleanups, backend, { translator: { maxResponseBytes: 3 },
const exact = await paidFixture(cleanups, { translator: { maxResponseBytes: 3 },
reply: (response) => { response.end(sse(replyEvents('中'))) } })
expect(await exact.translate('deepseek-official')).toBe('中')
const short = await paidFixture(cleanups, backend, { translator: { maxResponseBytes: 2 },
const short = await paidFixture(cleanups, { 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, backend)
const b = await paidFixture(cleanups)
const prepared = await b.ctx.llm.prepareCall({ provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: brandString<ReasoningEffortId>('off') })
const replacement: PreparedLlmCall = { ...prepared, async *stream() {
if (kind === 'block-start') yield { type: 'block-start', index: 0, blockType: 'reasoning' }
@@ -353,7 +351,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('sanitizes native model errors and does not select another route', async () => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
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([])
@@ -365,7 +363,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
it('preserves caller cancellation, including caller-owned timeouts, and aborts native sockets', async () => {
for (const reason of [new Error('caller cancelled'), new TimeoutReason('TRANSLATION_TIMEOUT', 1)]) {
const received = Promise.withResolvers<undefined>(), closed = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups, backend, { reply(response) {
const b = await paidFixture(cleanups, { reply(response) {
response.on('close', () => { closed.resolve(undefined) })
response.write(sse(replyEvents().slice(0, 2)))
received.resolve(undefined)
@@ -382,11 +380,11 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('normalizes paid deadlines and waits for accepted calls on translator disposal', async () => {
const expired = await paidFixture(cleanups, backend, { translator: { deepseekTimeoutMs: 40 },
const expired = await paidFixture(cleanups, { translator: { deepseekTimeoutMs: 40 },
reply: (response) => { response.write(sse(replyEvents().slice(0, 2))) } })
await expect(expired.translate('deepseek-official')).rejects.toMatchObject({ code: 'TRANSLATION_TIMEOUT', name: 'TranslationError' })
const received = Promise.withResolvers<undefined>()
const b = await paidFixture(cleanups, backend, { reply(response) {
const b = await paidFixture(cleanups, { reply(response) {
response.write(sse(replyEvents().slice(0, 2))); received.resolve(undefined)
} })
const pending = b.translate('deepseek-account')
@@ -398,7 +396,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('covers availability cancellation and quiescent disposal during a pending catalog lookup', async () => {
const b = await paidFixture(cleanups, backend)
const b = await paidFixture(cleanups)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const original = b.ctx.llm.listModels.bind(b.ctx.llm)
vi.spyOn(b.ctx.llm, 'listModels').mockImplementationOnce(async (provider) => {
@@ -417,7 +415,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it.each(['owned', 'caller'] as const)('classifies %s discovery deadlines without leaking native details', async (kind) => {
const b = await paidFixture(cleanups, backend, { translator: { deepseekTimeoutMs: 40 } })
const b = await paidFixture(cleanups, { translator: { deepseekTimeoutMs: 40 } })
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
vi.spyOn(b.ctx.llm, 'listModels').mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise; return [] })
const caller = new AbortController(), reason = new TimeoutReason('TRANSLATION_TIMEOUT', 1)
@@ -434,7 +432,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('cancels during native-owner inspection before starting any metadata work', async () => {
const b = await paidFixture(cleanups, backend), caller = new AbortController(), reason = new Error('metadata cancelled')
const b = await paidFixture(cleanups), 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')
@@ -443,7 +441,7 @@ describe.each(['jsonl', 'sqlite'] as const)('native Flash translation (%s)', (ba
})
it('cancels a held credential lookup promptly while service disposal still joins it', async () => {
const b = await paidFixture(cleanups, backend), caller = new AbortController(), reason = new Error('credentials observation cancelled')
const b = await paidFixture(cleanups), caller = new AbortController(), reason = new Error('credentials observation cancelled')
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
vi.spyOn(b.ctx.get('credentials')!, 'describe').mockImplementationOnce(async () => {
entered.resolve(undefined); await release.promise; return { configured: true, writable: true }
@@ -13,7 +13,7 @@ import * as SessionLogDeepSeek from '@deepseek-ai/dsh-session-log-deepseek'
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { once } from 'node:events'
import { createServer, type ServerResponse } from 'node:http'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import Translator, { type Config } from '../src/index.ts'
@@ -70,14 +70,8 @@ export interface RestartOptions {
translator?: Partial<Config>
}
/**
* Boot actual native provider rows with restartable persistence.
* @param cleanups - owning test's reverse-order cleanup list.
* @param backend - persistence implementation retained across Host restarts.
* @param options - provider, Session, and response choices.
* @returns the real composition and fixture-owned observations.
*/
export async function paidFixture(cleanups: Array<() => Promise<void>>, backend: 'jsonl' | 'sqlite', options: FixtureOptions = {}) {
/** Boot actual native provider rows; cleanup is registered as soon as resources exist. */
export async function paidFixture(cleanups: Array<() => Promise<void>>, 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
@@ -135,7 +129,7 @@ export async function paidFixture(cleanups: Array<() => Promise<void>>, backend:
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, storage: backend, compression: 'none' } },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, 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' }],
} },
@@ -214,7 +208,10 @@ export async function paidFixture(cleanups: Array<() => Promise<void>>, backend:
await using handle = await ctx.sessionPersistence.create(header)
await handle.append(events)
await handle.flush()
return { id, header, events }
const artifacts = (await readdir(storedRoot, { recursive: true })).filter(value => value.endsWith(join(id, `session.v${SESSION_FORMAT_VERSION}.jsonl`)))
if (artifacts.length !== 1) throw new Error('Expected one current Session artifact')
const file = join(storedRoot, artifacts[0]!)
return { id, header, events, file, bytes: await readFile(file) }
},
async restart(changes: RestartOptions = {}) {
await ctx.fiber.dispose()
@@ -1,4 +1,4 @@
/** Loader-owned anonymous provider, live Sessions, and restartable real persistence. */
/** Loader-owned anonymous provider, live Sessions, and restartable real JSONL storage. */
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'
@@ -6,9 +6,8 @@ import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import SessionStore, { SESSION_FORMAT_VERSION, type SessionId, SessionSeq, type Session, type SessionEvent, type SessionHeader } from '@deepseek-ai/dsh-session'
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 { appendFile, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, readFile, readdir, 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,11 +48,10 @@ function mainEvents(): SessionEvent[] {
/**
* Create private, atomically allocated resources and register teardown before use.
* @param cleanups - owning test's reverse-order quiescent cleanup list.
* @param backend - persistence implementation retained across Host restarts.
* @param options - external reply control and optional storage omission.
* @returns the real Host composition, restart operation, and Session/storage observations.
*/
export async function storageFixture(cleanups: Array<() => Promise<void>>, backend: 'jsonl' | 'sqlite', options: StorageFixtureOptions = {}) {
export async function storageFixture(cleanups: Array<() => Promise<void>>, options: StorageFixtureOptions = {}) {
const root = await mkdtemp(join(tmpdir(), 'dsh-translator-storage-'))
cleanups.push(async () => { await rm(root, { recursive: true, force: true }) })
const requests: StorageWireCall[] = [], errors: unknown[] = [], handlers = new Set<Promise<void>>()
@@ -100,7 +98,7 @@ export async function storageFixture(cleanups: Array<() => Promise<void>>, backe
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, storage: backend, compression: 'none' } },
{ id: 'storage', name: '@deepseek-ai/dsh-session-persistence-jsonl', config: { root: storedRoot, compression: 'none' } },
],
{ id: 'translator', name: '@deepseek-ai/dsh-experimental-translator', config },
]))
@@ -156,20 +154,11 @@ export async function storageFixture(cleanups: Array<() => Promise<void>>, backe
await handle.append(events)
await handle.flush()
}
return { id, session, scope, writer, events: await readEvents(id) }
const artifacts = (await readdir(storedRoot, { recursive: true })).filter(value => value.endsWith(join(id, `session.v${SESSION_FORMAT_VERSION}.jsonl`)))
if (artifacts.length !== 1) throw new Error('Expected one current Session artifact')
const file = join(storedRoot, artifacts[0]!)
return { id, session, scope, writer, events: await readEvents(id), file, bytes: await readFile(file) }
}
return { get ctx() { return ctx }, root, config, requests, errors, readEvents, createSession,
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 = ?')
.run(seq, payload, id)
} finally { db.close() }
},
async restart() { await ctx.fiber.dispose(); ctx = await start() } }
}
@@ -1,5 +1,6 @@
/** Storage helpers classify their own failures before a provider consumer can catch them. */
import { SessionSeq } from '@deepseek-ai/dsh-session'
import { rm } from 'node:fs/promises'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { TranslationStorage } from '../src/storage.ts'
import type { TranslationIdentity } from '../src/types.ts'
@@ -14,9 +15,9 @@ afterEach(async () => {
const identity: TranslationIdentity = { provider: 'bing', text: 'source', sourceLanguage: 'auto', targetLanguage: 'zh', recipe: 'fixture' }
const stages = ['request', 'result'] as const
describe.each(['jsonl', 'sqlite'] as const)('storage helper failures (%s)', (backend) => {
describe('storage helper failures', () => {
it.each(stages)('classifies %s I/O failures before returning them to the consumer', async (stage) => {
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups), 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)
@@ -32,12 +33,12 @@ describe.each(['jsonl', 'sqlite'] as const)('storage helper failures (%s)', (bac
expect(b.requests).toEqual([])
})
it.each(stages)('classifies %s writer failures after its writer is closed', async (stage) => {
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
it.each(stages)('classifies %s writer failures after its artifact is removed', async (stage) => {
const b = await storageFixture(cleanups), 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)
await original.writer?.close()
await rm(original.file)
try {
if (stage === 'request') await log.request(identity)
else await log.result(seq, 'complete')
@@ -50,7 +51,7 @@ describe.each(['jsonl', 'sqlite'] as const)('storage helper failures (%s)', (bac
})
it.each(stages)('preserves the exact caller abort reason inside %s', async (stage) => {
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups), 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) => {
@@ -1,6 +1,6 @@
/** Queued cancellation, native storage ownership, and quiescent translator disposal. */
import { pluginRecordOf, SessionId } from '@deepseek-ai/dsh-session'
import { SessionPersistenceNotFoundError } from '@deepseek-ai/dsh-session-persistence'
import { pluginRecordOf, type SessionId } from '@deepseek-ai/dsh-session'
import { rm } from 'node:fs/promises'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { storageFixture, storageReply } from './storage-fixture.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
@@ -11,10 +11,10 @@ afterEach(async () => {
for (const cleanup of cleanups.splice(0).reverse()) await cleanup()
})
describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)', (backend) => {
describe('translation storage lifecycle', () => {
it('rejects a canceled queued request promptly without dispatching it', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, backend, { reply: async (call, response) => {
const b = await storageFixture(cleanups, { reply: async (call, response) => {
entered.resolve(undefined); await release.promise; storageReply(call, response)
} })
cleanups.push(async () => { release.resolve(undefined) })
@@ -33,7 +33,7 @@ describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)'
})
it('joins an accepted storage checkpoint after public cancellation on unload', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const b = await storageFixture(cleanups), original = await b.createSession()
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const flush = b.ctx.sessions.flush.bind(b.ctx.sessions)
@@ -56,7 +56,7 @@ describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)'
})
it('refuses a withdrawn persistence provider after its metadata lookup settles', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const b = await storageFixture(cleanups), original = await b.createSession()
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
const stat = b.ctx.sessionPersistence.stat.bind(b.ctx.sessionPersistence)
@@ -74,7 +74,7 @@ describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)'
it('pins the live Session used by an accepted translation', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
const b = await storageFixture(cleanups, { async reply(call, response) {
entered.resolve(undefined); await release.promise; storageReply(call, response)
} })
cleanups.push(async () => { release.resolve(undefined) })
@@ -90,7 +90,7 @@ describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)'
})
it('requires an active live writer rather than treating an in-memory append as durable', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession(brandString<SessionId>('live-without-writer'), true)
const b = await storageFixture(cleanups), original = await b.createSession(brandString<SessionId>('live-without-writer'), true)
await original.writer?.close()
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_STORAGE_ERROR' })
@@ -98,13 +98,11 @@ describe.each(['jsonl', 'sqlite'] as const)('translation storage lifecycle (%s)'
expect(b.requests).toEqual([])
})
it('refuses a historical Session unavailable after metadata lookup before dispatch', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession(SessionId('deleted'), false)
it('refuses a historical artifact deleted after admission before dispatch', async () => {
const b = await storageFixture(cleanups), original = await b.createSession(brandString<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)
vi.spyOn(b.ctx.sessionPersistence, 'open').mockRejectedValue(new SessionPersistenceNotFoundError(id))
return value
const value = await stat(id, options); await rm(original.file); return value
})
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
@@ -14,9 +14,9 @@ afterEach(async () => {
})
const identity: TranslationIdentity = { provider: 'bing', text: 'source', sourceLanguage: 'auto', targetLanguage: 'zh', recipe: 'fixture' }
describe.each(['jsonl', 'sqlite'] as const)('accepted translation write settlement (%s)', (backend) => {
describe('accepted translation write settlement', () => {
it.each([false, true])('holds identical admission until the accepted result write settles (reject=%s)', async (rejectWrite) => {
const b = await storageFixture(cleanups, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const deadline = Promise.withResolvers<never>()
const stopped = new TranslationError('TRANSLATION_TIMEOUT', 'consumer deadline'), writeFailure = new Error('verification unavailable')
@@ -69,7 +69,7 @@ describe.each(['jsonl', 'sqlite'] as const)('accepted translation write settleme
})
it('keeps storage disposal pending until a write outliving its consumer settles', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const b = await storageFixture(cleanups), original = await b.createSession()
let storage: TranslationStorage | undefined
const owner = b.ctx.plugin({ apply(ctx: Context) { storage = new TranslationStorage(ctx) } })
await owner.await()
@@ -1,5 +1,6 @@
/** Successful Session translations survive remounts and restarts without another provider query. */
import { pluginRecordOf, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
import { pluginRecordOf, type SessionId, type SessionEvent } from '@deepseek-ai/dsh-session'
import { appendFile, readFile, writeFile } from 'node:fs/promises'
import type { ServerResponse } from 'node:http'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { TranslationStorage } from '../src/storage.ts'
@@ -21,9 +22,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.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)', (backend) => {
describe('durable translation results', () => {
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, backend), original = await b.createSession()
const b = await storageFixture(cleanups), 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)
@@ -34,6 +35,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
sourceLanguage: 'auto', targetLanguage: 'zh' } })
expect((requests(first)[0]?.data as { recipe: string }).recipe).toEqual(expect.any(String))
expect(results(first)[0]).toMatchObject({ ignorable: true, data: { requestSeq: requests(first)[0]?.seq, text: 'Stored translation' } })
expect((await readFile(original.file)).subarray(0, original.bytes.length)).toEqual(original.bytes)
await b.restart()
expect(b.ctx.sessions.list()).toEqual([])
expect(await b.ctx.translator.translate(spec())).toBe('Stored translation')
@@ -45,7 +47,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
it('persists request before dispatch and result before return through the existing live writer', async () => {
let atDispatch: readonly SessionEvent[] = []
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
const b = await storageFixture(cleanups, { async reply(call, response) {
atDispatch = await b.readEvents(brandString<SessionId>('stored-translation'))
storageReply(call, response)
} })
@@ -63,7 +65,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
it('serializes simultaneous identical requests and reuses the first completed result', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
const b = await storageFixture(cleanups, { 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 +83,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
it('lets another Session translate while the first Session provider request is held', async () => {
const entered = Promise.withResolvers<undefined>(), release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
const b = await storageFixture(cleanups, { async reply(call, response) {
if (call.text === 'Held source') { entered.resolve(undefined); await release.promise }
storageReply(call, response)
} })
@@ -99,7 +101,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
it('overlaps different fragments through the same Session writer', async () => {
const release = Promise.withResolvers<undefined>()
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
const b = await storageFixture(cleanups, { async reply(call, response) {
await release.promise; storageReply(call, response, `Translation of ${call.text}`)
} })
cleanups.push(async () => { release.resolve(undefined) })
@@ -121,7 +123,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
it('retains an unmatched failed request and permits a successful retry', async () => {
let fail = true
const b = await storageFixture(cleanups, backend, { reply(call, response) {
const b = await storageFixture(cleanups, { 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 +140,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
it('cancels before provider completion and leaves no successful result', async () => {
const entered = Promise.withResolvers<undefined>(), closed = Promise.withResolvers<undefined>()
let held: ServerResponse | undefined
const b = await storageFixture(cleanups, backend, { reply(_call, response) {
const b = await storageFixture(cleanups, { 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 +154,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
})
it('separates provider, target, source, text, and effective endpoint recipes', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const b = await storageFixture(cleanups), 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 +170,7 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
})
it('does not change cache identity for provider-owned endpoint query parameters', async () => {
const b = await storageFixture(cleanups, backend), original = await b.createSession()
const b = await storageFixture(cleanups), 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,29 +182,29 @@ describe.each(['jsonl', 'sqlite'] as const)('durable translation results (%s)',
})
})
describe.each(['jsonl', 'sqlite'] as const)('translation storage guards (%s)', (backend) => {
describe('translation storage guards', () => {
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, backend, { withSessions }), original = await b.createSession(brandString<SessionId>('inactive'), false)
const b = await storageFixture(cleanups, { withSessions }), original = await b.createSession(brandString<SessionId>('inactive'), false)
const opened = vi.spyOn(b.ctx.sessionPersistence, 'open')
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: original.id })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_INACTIVE' })
expect(opened.mock.calls.every(([, access]) => access === 'read')).toBe(true)
expect(await b.readEvents(original.id)).toEqual(original.events)
expect(await readFile(original.file)).toEqual(original.bytes)
expect(b.requests).toEqual([])
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, backend, { withPersistence: false })
const absent = await storageFixture(cleanups, { withPersistence: false })
await expect(absent.ctx.translator.translate(absent.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: brandString<SessionId>('missing') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
const b = await storageFixture(cleanups, backend)
const b = await storageFixture(cleanups)
await expect(b.ctx.translator.translate(b.ctx.translator.resolve({ text: 'source', targetLanguage: 'zh', sessionId: brandString<SessionId>('missing') })))
.rejects.toMatchObject({ code: 'TRANSLATION_SESSION_REQUIRED' })
expect([...absent.requests, ...b.requests]).toEqual([])
})
it('does not return a provider response when result durability fails', async () => {
const b = await storageFixture(cleanups, backend, { async reply(call, response) {
const b = await storageFixture(cleanups, { async reply(call, response) {
await original.writer?.close()
storageReply(call, response)
} })
@@ -221,24 +223,24 @@ describe.each(['jsonl', 'sqlite'] as const)('translation storage guards (%s)', (
['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, backend), original = await b.createSession(brandString<SessionId>('malformed'), false)
const b = await storageFixture(cleanups), original = await b.createSession(brandString<SessionId>('malformed'), false)
let record = JSON.stringify({ type, data, seq: original.events.length, time: Date.now(), ignorable: true })
if (_kind === 'result negative zero') record = record.replace('"requestSeq":0', '"requestSeq":-0')
await b.appendStored(original.id, original.events.length, record)
await writeFile(original.file, Buffer.concat([original.bytes, Buffer.from(record + '\n')]))
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, backend), original = await b.createSession(), storage = new TranslationStorage(b.ctx)
const b = await storageFixture(cleanups), 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)
await b.appendStored(original.id, saved.length, JSON.stringify({ type: 'plugin:other/unrelated', seq: saved.length, time: Date.now(),
data: { opaque: true }, ignorable: true }))
await appendFile(original.file, JSON.stringify({ type: 'plugin:other/unrelated', seq: saved.length, time: Date.now(),
data: { opaque: true }, ignorable: true }) + '\n')
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')
expect(requests(await b.readEvents(original.id))[0]?.data).toEqual(request)
@@ -48,7 +48,7 @@ describe('platform home patch', () => {
it('keeps the composed JSONL row config and sets the plaintext compression the Worker requires', () => {
expect(platformHomePatch(repoRoot, 'web')).toEqual([{
id: 'session-persistence-jsonl',
config: { root: { __jsExpr: "dshHomePath('sessions')" }, compression: 'none', storage: 'jsonl' },
config: { root: { __jsExpr: "dshHomePath('sessions')" }, compression: 'none' },
}])
})
})
@@ -64,7 +64,7 @@ function agentFor(ctx: Context, session: Session): Agent {
return agent
}
async function fixture(backend: 'jsonl' | 'sqlite', options: { cache?: boolean; retainOnArchive?: boolean; maxOutputBytes?: number } = {}) {
async function fixture(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(backend: 'jsonl' | 'sqlite', options: { cache?: boolean;
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', storage: backend })
await ctx.plugin(SessionPersistence, { root: join(temporary, 'sessions'), compression: 'none' })
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup (%s)', (backend) => {
describe('archive-triggered worktree cleanup', () => {
it('removes the clean checkout the archived Session created and keeps its branch and commits', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('removes a clean checkout whose file listing exceeds maxOutputBytes', async () => {
const f = await fixture(backend, { maxOutputBytes: 1_024 })
const f = await fixture({ 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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('retains a checkout whose status output exceeds maxOutputBytes instead of failing', async () => {
const f = await fixture(backend, { maxOutputBytes: 1_024 })
const f = await fixture({ 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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('removes a clean checkout when the worktree listing exceeds maxOutputBytes', async () => {
const f = await fixture(backend, { maxOutputBytes: 1_024 })
const f = await fixture({ 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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('returns from admission before the inspection runs', async () => {
const f = await fixture(backend)
const f = await fixture()
const release = Promise.withResolvers<undefined>()
const list = f.ctx.sessionQuery.listSessions.bind(f.ctx.sessionQuery)
vi.spyOn(f.ctx.sessionQuery, 'listSessions').mockImplementation(async (...args) => {
@@ -188,7 +188,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('retains an untracked file but not ignored files', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('registers nothing for a Session that created no checkout or only inherited one', async () => {
const f = await fixture(backend)
const f = await fixture()
const other = f.ctx.sessions.create(brandString<SessionId>('no-checkout'), { meta: { cwd: f.root } })
await f.ctx.workspaceRegistry.archiveSession(other.id)
expect(await f.ctx.worktrees.cleanupOf(other, null)).toBeNull()
@@ -232,7 +232,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
const seed = f.session.snapshotEvents()
const fork = f.ctx.sessions.create(brandString<SessionId>('fork'), {
seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root },
@@ -252,7 +252,7 @@ describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('treats a subagent child beneath the archived Session as archived', async () => {
const f = await fixture(backend)
const f = await fixture()
const child = f.ctx.sessions.create(brandString<SessionId>('child'), {
meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: f.session.id },
})
@@ -266,7 +266,7 @@ describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('retains a checkout for an unrelated subagent child that works inside it', async () => {
const f = await fixture(backend)
const f = await fixture()
const other = f.ctx.sessions.create(brandString<SessionId>('other-parent'), { meta: { cwd: f.root } })
f.ctx.sessions.create(brandString<SessionId>('other-child'), { meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: other.id } })
await f.ctx.workspaceRegistry.archiveSession(f.session.id)
@@ -274,7 +274,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend, { cache: true })
const f = await fixture({ 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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('retains a checkout while a live fork that moved elsewhere still carries its creation', async () => {
const f = await fixture(backend)
const f = await fixture()
const seed = f.session.snapshotEvents()
const fork = f.ctx.sessions.create(brandString<SessionId>('fork-elsewhere'), {
seed, inheritedEventCount: SessionLogOffset(seed.length), meta: { isSeeded: true, cwd: f.root },
@@ -315,7 +315,7 @@ describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('treats a cached cold Session that recorded no directory as working nowhere', async () => {
const f = await fixture(backend, { cache: true })
const f = await fixture({ 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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('reads a cold Session from its log without the cache', async () => {
const f = await fixture(backend)
const f = await fixture()
const borrower = detachable(f, 'cold-borrower', { cwd: f.worktree.path })
await persisted(f, borrower.session)
borrower.detach()
@@ -335,14 +335,14 @@ describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('does not wait for the archived Session\'s own stopping work', async () => {
const f = await fixture(backend)
const f = await fixture()
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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('keeps the archive and reports a failed removal', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('cancels an unadmitted removal on unarchive and waits for an admitted one', async () => {
const f = await fixture(backend)
const f = await fixture()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
removeCheckout.mockImplementation(async (...args) => {
@@ -384,7 +384,7 @@ describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('holds directory entry into a checkout being removed and leaves other paths alone', async () => {
const f = await fixture(backend)
const f = await fixture()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
removeCheckout.mockImplementation(async (...args) => {
@@ -413,7 +413,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
const cold = detachable(f, 'cold-empty', { cwd: f.root })
await persisted(f, cold.session)
cold.detach()
@@ -426,7 +426,7 @@ describe.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('treats a subagent child whose parent is unknown to the corpus as unarchived', async () => {
const f = await fixture(backend)
const f = await fixture()
f.ctx.sessions.create(brandString<SessionId>('orphan-child'), {
meta: { cwd: f.worktree.path, origin: 'subagent', parentSession: brandString<SessionId>('never-existed') },
})
@@ -449,7 +449,7 @@ describe.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('skips a creation record whose payload fails validation', async () => {
const f = await fixture(backend)
const f = await fixture()
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.each(['jsonl', 'sqlite'] as const)('archive-triggered worktree cleanup
})
it('registers no attempt while retainOnArchive is set, and resumes once it is cleared', async () => {
const f = await fixture(backend, { retainOnArchive: true })
const f = await fixture({ 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.each(['jsonl', 'sqlite'] as const)('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(backend)
const f = await fixture()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
removeCheckout.mockImplementation(async () => {
@@ -3195,7 +3195,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: 'abstract open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>',
description: 'Open an existing stored session.\n\n`read` does not retain write ownership and works while another handle (or process) holds write ownership in the selected backend. A legacy import may wait for the old writer to release ownership before opening the read handle. `write` atomically claims single-writer ownership; an existing active owner rejects.',
description: 'Open an existing stored session.\n\n`read` never takes ownership and works while another handle (or process) holds write ownership. `write` atomically claims single-writer ownership; an existing active owner rejects.',
parameters: [{ name: 'id', description: 'the stored session to open.' }, { name: 'access', description: '`read` or `write`.' }, { name: 'options', description: 'optional cancellation.' }],
returns: 'the open handle.',
throws: ['{SessionPersistenceNotFoundError} when the session does not exist.', '{SessionAlreadyOwnedError} for `write` when ownership is taken.'],
@@ -51,7 +51,7 @@ async function loadComposition(configPath: string): Promise<Context> {
return ctx
}
describe.each(['jsonl', 'sqlite'] as const)('message feedback through a real Loader composition (%s)', (storage) => {
describe('message feedback through a real Loader composition', () => {
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,7 +60,6 @@ describe.each(['jsonl', 'sqlite'] as const)('message feedback through a real Loa
"- 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:',
@@ -78,7 +77,7 @@ describe.each(['jsonl', 'sqlite'] as const)('message feedback through a real Loa
const unownedRequest = {
sessionId: unowned.id, messageId: unownedFixture.assistantMessageIds[0], rating: 'positive' as const, ifVersion: null,
}
// A mounted persistence listener alone does not persist Sessions without a write handle.
// A mounted JSONL 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 })
@@ -21,7 +21,6 @@
- id: session-persistence-jsonl
config:
root: './.sessions'
storage: jsonl
compression: none
- insert:
@@ -15,18 +15,18 @@ afterEach(async () => {
for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true })
})
async function backend(storage: 'jsonl' | 'sqlite'): Promise<Context> {
async function backend(): Promise<Context> {
const ctx = new Context()
await ctx.plugin(SessionStore)
const root = await mkdtemp(join(tmpdir(), 'dsh-llm-retry-jsonl-'))
dirs.push(root)
await ctx.plugin(JsonlSessionPersistence, { root, storage })
await ctx.plugin(JsonlSessionPersistence, { root })
return ctx
}
describe.each(['jsonl', 'sqlite'] as const)('retry-event persistence (%s)', (storage) => {
describe('JSONL retry-event persistence', () => {
it('round-trips the event losslessly without adding a model message', async () => {
const ctx = await backend(storage)
const ctx = await backend()
try {
const session = ctx.sessions.create(brandString<SessionId>('retry-jsonl'))
const handle = await ctx.sessionPersistence.create(session.header)
@@ -44,13 +44,13 @@ class ReplyAdapter extends LlmAdapter {
}
/** Schedule service beside a production AgentLoop with one idle Agent that answers through {@link ReplyAdapter}. */
async function setup(storage: 'jsonl' | 'sqlite') {
async function setup() {
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, { storage, root: join(root, 'sessions'), compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { 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.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)
it('adds notices queued while the Agent is idle to the first step of its next turn', async () => {
const { service, adapter, agent } = await setup()
const created = await service.create({
title: 'Standup', prompt: 'Prompt', timing: { kind: 'rrule', rrule: distant }, target: { kind: 'session', sessionId: agent.session.id },
}, brandString<SessionId>('actor'))
@@ -93,8 +93,8 @@ it.each(['jsonl', 'sqlite'] as const)('%s: adds notices queued while the Agent i
])
})
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)
it('adds one step to a turn whose last step was running when a notice arrived', async () => {
const { service, adapter, agent } = await setup()
// The Agent created the task itself, so only the later edit notifies it.
const created = await service.create({
title: 'Standup', prompt: 'Prompt', timing: { kind: 'rrule', rrule: distant }, target: { kind: 'session', sessionId: agent.session.id },
@@ -26,20 +26,20 @@ afterEach(async () => {
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true })
})
async function core(storage: 'jsonl' | 'sqlite', persistenceRoot: string) {
async function core(persistenceRoot: string) {
const ctx = new Context()
contexts.push(ctx)
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(JsonlSessionPersistence, { storage, root: persistenceRoot, compression: 'none' })
await ctx.plugin(JsonlSessionPersistence, { root: persistenceRoot, compression: 'none' })
await ctx.plugin(AgentLoop, { agents: [] })
return ctx
}
describe('due delivery during Agent creation', () => {
it.each(['jsonl', 'sqlite'] as const)('%s: enqueues the reminder without starting a turn before every creation listener finishes', async (storage) => {
it('enqueues the reminder without starting a turn before every creation listener finishes', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-schedule-serial-'))
roots.push(root)
const ctx = await core(storage, join(root, 'sessions'))
const ctx = await core(join(root, 'sessions'))
const warnings = vi.spyOn(ctx.logger, 'warn')
await ctx.plugin(Storage)
await ctx.plugin(StorageJson, { root: join(root, 'schedule-storage') })
@@ -48,7 +48,7 @@ try {
await mountAgentLoopTestDependencies(ctx, { workingDirectory: true });
await ctx.plugin(AgentLoop, { agents: [] });
await ctx.plugin(SubagentRuntime);
await ctx.plugin(JsonlSessionPersistence, { storage: process.argv[1], root: storageRoot });
await ctx.plugin(JsonlSessionPersistence, { 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.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], {
it('preserves parent-scoped completion after child disposal', async () => {
const { stdout, stderr } = await execFileAsync(process.execPath, ['--input-type=module', '-e', builtRuntimeProbe], {
cwd: repoRoot,
timeout: 15_000,
})
+13 -14
View File
@@ -69,7 +69,6 @@ async function settle(): Promise<void> {
/** Mount the real plugin on a minimal harness with in-memory stdio and exit. */
async function mountPlugin(
storage: 'jsonl' | 'sqlite',
storageDir: string,
options: {
writeDelayMs?: number
@@ -81,7 +80,7 @@ async function mountPlugin(
await mountAgentLoopTestDependencies(ctx)
await mountWorkingDirectoryFixture(ctx)
await ctx.plugin(AgentLoop, { agents: [] })
await ctx.plugin(JsonlSessionPersistence, { storage, root: storageDir })
await ctx.plugin(JsonlSessionPersistence, { root: storageDir })
await new Promise(resolve => setTimeout(resolve, 50))
await options.beforeServer?.(ctx)
@@ -171,10 +170,10 @@ async function mockCompletionServer(): Promise<{ url: string; requests: unknown[
}
describe('dsh-sdk-jsonrpc-server plugin apply', () => {
it.each(['jsonl', 'sqlite'] as const)('%s: serves initialize over the injected stdio pair', async (storage) => {
it('serves initialize over the injected stdio pair', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-init-'))
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
const harness = await mountPlugin(storage, storageDir)
const harness = await mountPlugin(storageDir)
try {
harness.send({ jsonrpc: '2.0', id: 'init-1', method: 'initialize', params: { cwd: storageDir, provider: 'deepseek-official', model: 'apply-model' } })
@@ -191,7 +190,7 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: waits for Loader-owned adapter registration before initialize', async (storage) => {
it('waits for Loader-owned adapter registration before initialize', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-readiness-'))
vi.stubEnv('DEEPSEEK_API_KEY', 'test-key')
let markStarted!: () => void
@@ -199,7 +198,7 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
const started = new Promise<void>((resolve) => { markStarted = resolve })
const ready = new Promise<void>((resolve) => { release = resolve })
let delayedEntry: Promise<string> | undefined
const harness = await mountPlugin(storage, storageDir, {
const harness = await mountPlugin(storageDir, {
beforeServer: async (ctx) => {
await ctx.plugin(Loader)
ctx.loader.builtins['delayed-readiness'] = {
@@ -246,12 +245,12 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: drives a session/prompt turn end-to-end and forwards session notifications as output frames', async (storage) => {
it('drives a session/prompt turn end-to-end and forwards session notifications as output frames', async () => {
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(storage, storageDir)
const harness = await mountPlugin(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')
@@ -288,9 +287,9 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async (storage) => {
it('answers shutdown before exiting 0 exactly once, even against a racing second shutdown', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-shutdown-'))
const harness = await mountPlugin(storage, storageDir, { writeDelayMs: 10 })
const harness = await mountPlugin(storageDir, { writeDelayMs: 10 })
try {
// One chunk makes the two deferred exit callbacks race.
const first = { jsonrpc: '2.0', id: 'sd-1', method: 'shutdown' }
@@ -331,9 +330,9 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: still disposes and exits once when the flush callback fails', async (storage) => {
it('still disposes and exits once when the flush callback fails', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-flush-failure-'))
const harness = await mountPlugin(storage, storageDir, { failFlush: true })
const harness = await mountPlugin(storageDir, { failFlush: true })
try {
harness.send({ jsonrpc: '2.0', id: 'sd-fail', method: 'shutdown' })
@@ -353,9 +352,9 @@ describe('dsh-sdk-jsonrpc-server plugin apply', () => {
}
})
it.each(['jsonl', 'sqlite'] as const)('%s: stops serving on a bare fiber dispose (HMR-style unload) without calling exit', async (storage) => {
it('stops serving on a bare fiber dispose (HMR-style unload) without calling exit', async () => {
const storageDir = await mkdtemp(join(tmpdir(), 'dsh-jsonrpc-apply-dispose-'))
const harness = await mountPlugin(storage, storageDir)
const harness = await mountPlugin(storageDir)
try {
// Prove the handler-rejection path is live before disposal.
harness.send({ jsonrpc: '2.0', id: 'probe-1', method: 'nope/unknown' })
+6 -8
View File
@@ -28,11 +28,11 @@ async function storageRoot(): Promise<string> {
return root
}
async function mountRuntime(root: string, storage: 'jsonl' | 'sqlite', persistence = true, reasoning?: LlmModelReasoningInfo) {
async function runtime(root: string, persistence = true, reasoning?: LlmModelReasoningInfo) {
const ctx = new Context()
cleanups.push(() => ctx.fiber.dispose())
await mountAgentLoopTestDependencies(ctx)
if (persistence) await ctx.plugin(JsonlSessionPersistence, { root, storage })
if (persistence) await ctx.plugin(JsonlSessionPersistence, { root })
await ctx.plugin(AgentLoop, { agents: [] })
const adapter = new MockAdapter([textResponse('remembered')], reasoning)
ctx.llm.registerAdapter(['mock'], adapter)
@@ -48,8 +48,8 @@ async function mountRuntime(root: string, storage: 'jsonl' | 'sqlite', persisten
return { ctx, server, adapter, events }
}
async function initializeRuntime(root: string, storage: 'jsonl' | 'sqlite') {
const result = await mountRuntime(root, storage)
async function initialized(root: string) {
const result = await runtime(root)
await result.server.initialize({ cwd: root, provider: 'mock', model: 'mock' })
return result
}
@@ -62,10 +62,7 @@ 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 })
@@ -75,6 +72,7 @@ async function withPermissions(root: string) {
return result
}
describe('SDK persisted session resume', () => {
it.each([undefined, 'danger-full-access'])('applies persisted or explicit permissions before resumed execution: %s', async (permissionMode) => {
const root = await storageRoot()
const sessionId = brandString<SessionId>('saved-permissions')
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff. Show more