sdk.snapshot.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. /**
  2. * Keyless snapshot coverage for the TypeScript SDK path: each scenario spawns
  3. * the real `dsh --profile sdk` runtime through
  4. * `@deepseek-ai/dsh-sdk-client`, drives one turn over stdio JSON-RPC,
  5. * and pins the SDK `RunResult`, the complete notification stream, and the
  6. * persisted session logs. Replay serves recorded model
  7. * responses via `llm-replay` (`cordis.snapshot.yml`); `DSH_SNAPSHOT=record`
  8. * re-records against the live API; `DSH_SNAPSHOT=refresh` replays committed
  9. * fixtures and rewrites expected outputs.
  10. */
  11. import { existsSync } from 'node:fs'
  12. import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises'
  13. import { tmpdir } from 'node:os'
  14. import { basename, delimiter, join } from 'node:path'
  15. import { fileURLToPath, pathToFileURL } from 'node:url'
  16. import { describe, expect, it } from 'vitest'
  17. import {
  18. normalizeSessionLog,
  19. normalizeSessionSnapshot,
  20. normalizeStdout,
  21. refreshFixtureReplacements,
  22. scrubRequestHeaders,
  23. scrubSessionSnapshot,
  24. stabilizeFixtureMessageIds,
  25. stabilizeRefreshLog,
  26. tokenizeSessionFixtureCwd,
  27. type HarvestedLog,
  28. type NormalizeContext,
  29. } from '@deepseek-ai/dsh-acp-snapshot'
  30. import { DeepSeekHarness, type HarnessNotification, type RunResult } from '@deepseek-ai/dsh-sdk-client'
  31. const testsDir = dirOf(import.meta.url)
  32. const snapshotsDir = join(testsDir, 'snapshots')
  33. const liveConfig = join(testsDir, '..', 'typescript-sdk.cordis.yml')
  34. const replayConfig = join(testsDir, '..', 'typescript-sdk.cordis.snapshot.yml')
  35. const minimalLiveConfig = join(testsDir, '..', 'typescript-sdk-minimal.cordis.yml')
  36. const minimalReplayConfig = join(testsDir, '..', 'typescript-sdk-minimal.cordis.snapshot.yml')
  37. const sessionUploadLivePatch = join(testsDir, '..', 'session-upload.cordis.yml')
  38. const sessionUploadReplayPatch = join(testsDir, '..', 'session-upload.snapshot.cordis.yml')
  39. const exampleMode = process.env.DSH_EXAMPLE_MODE ?? 'src'
  40. const replayPlugin = fileURLToPath(new URL(
  41. exampleMode === 'lib'
  42. ? '../../../packages/test-support/llm-replay/lib/index.js'
  43. : '../../../packages/test-support/llm-replay/src/index.ts',
  44. import.meta.url,
  45. ))
  46. const dshSdkFixtureDir = join(testsDir, 'fixtures', 'subagent', 'subagent-dsh-sdk')
  47. const dshSdkSnapshotConfig = join(dshSdkFixtureDir, 'snapshot.cordis.yml')
  48. const dshSdkSnapshotReplayConfig = join(dshSdkFixtureDir, 'snapshot.replay.cordis.yml')
  49. const dshSdkChildConfig = join(dshSdkFixtureDir, 'child.cordis.yml')
  50. const dshSdkChildMockPath = join(dshSdkFixtureDir, 'child-mock-llm.ts')
  51. const dshSdkParentMockPath = join(dshSdkFixtureDir, 'mock-delegating-llm.ts')
  52. const dshSdkProviderPlugin = fileURLToPath(new URL(
  53. exampleMode === 'lib'
  54. ? '../../../packages/subagent/subagent-dsh-sdk/lib/index.js'
  55. : '../../../packages/subagent/subagent-dsh-sdk/src/index.ts',
  56. import.meta.url,
  57. ))
  58. const MINIMAL_SYSTEM_PROMPT = 'You are the environment-selected minimal software engineer.'
  59. const MINIMAL_BASH_DESCRIPTION = `Run commands in a bash shell
  60. * When invoking this tool, the contents of the "command" parameter does NOT need to be XML-escaped.
  61. * You don't have access to the internet via this tool.
  62. * You do have access to a mirror of common linux and python packages via apt and pip.
  63. * State is persistent across command calls and discussions with the user.
  64. * To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.
  65. * Please avoid commands that may produce a very large amount of output.
  66. * Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.`
  67. const mode = process.env.DSH_SNAPSHOT ?? 'replay'
  68. const recording = mode === 'record'
  69. const refreshing = mode === 'refresh'
  70. function dirOf(url: string): string {
  71. return fileURLToPath(new URL('.', url))
  72. }
  73. interface SdkScenario {
  74. /** Scenario name; the snapshots/<name> fixture directory. */
  75. name: string
  76. /** The user prompt for the single SDK turn. */
  77. prompt: string
  78. /** Fixed SDK session id, so fixtures and replay binding stay stable. */
  79. sessionId: string
  80. /** How many additional session logs the scenario persists. */
  81. children: number
  82. /** Optional scenario-specific live and replay compositions. */
  83. configs?: { live: string; replay: string }
  84. /** Additional ordered patches applied after the selected live or replay patch. */
  85. additionalPatches?: { live: readonly string[]; replay: readonly string[] }
  86. /** Environment overrides passed to the runtime subprocess. */
  87. environment?: Readonly<Record<string, string>>
  88. /** SDK initialization route for the root runtime. */
  89. sdkRoute?: { provider: string; model: string }
  90. /** Separate DSH SDK child process and the route its persisted request must prove. */
  91. dshSdkChild?: {
  92. config: string
  93. sessionRoot: string
  94. }
  95. /** Cwd-relative files whose final contents are part of the scenario contract. */
  96. expectedFiles?: Readonly<Record<string, string>>
  97. /** Assembled model-facing tool names and required argument keys. */
  98. expectedTools?: Readonly<Record<string, readonly string[]>>
  99. /** Exact assembled system prompt for the root request. */
  100. expectedSystem?: string
  101. /** Exact model-facing descriptions for selected tools. */
  102. expectedToolDescriptions?: Readonly<Record<string, string>>
  103. /** Expected runtime-context state in the real assembled request. */
  104. runtimeContext?: false | { includes: readonly string[]; excludes: readonly string[] }
  105. }
  106. const SCENARIOS: SdkScenario[] = [
  107. {
  108. name: 'text-turn',
  109. prompt: 'Reply with exactly: SDK snapshot OK',
  110. sessionId: 'sdk-snapshot-text',
  111. children: 0,
  112. additionalPatches: { live: [sessionUploadLivePatch], replay: [sessionUploadReplayPatch] },
  113. },
  114. {
  115. name: 'bash-tool',
  116. prompt: 'Run this exact command with your bash tool, then reply with its stdout only: echo dsh-sdk-proof-7391',
  117. sessionId: 'sdk-snapshot-bash',
  118. children: 0,
  119. },
  120. {
  121. name: 'subagent-spawn-in-process',
  122. prompt: "Use the subagent tool exactly once with description 'echo probe' and prompt: Reply with exactly: child answer 42. Then reply with the subagent's final answer verbatim.",
  123. sessionId: 'sdk-snapshot-subagent',
  124. children: 1,
  125. },
  126. {
  127. name: 'subagent-dsh-sdk-dynamic-route',
  128. prompt: 'Delegate once using the requested child route.',
  129. sessionId: 'sdk-snapshot-dsh-sdk',
  130. children: 1,
  131. configs: { live: dshSdkSnapshotConfig, replay: dshSdkSnapshotReplayConfig },
  132. environment: { DSH_TEST_PARENT_PROVIDER: 'deepseek-official' },
  133. sdkRoute: { provider: 'deepseek-official', model: 'mock-delegate' },
  134. dshSdkChild: {
  135. config: dshSdkChildConfig,
  136. sessionRoot: '.child-dsh/sessions',
  137. },
  138. },
  139. {
  140. name: 'persistent-tools',
  141. prompt: 'Prove that bash state persists. Then create {{cwd}}/note.txt with a tab-indented line, view it, replace that literal tab-indented line, and make the persistent shell exit with code 9.',
  142. sessionId: 'persistent-tools-snapshot',
  143. children: 0,
  144. configs: { live: minimalLiveConfig, replay: minimalReplayConfig },
  145. environment: { DSH_SYSTEM_PROMPT: MINIMAL_SYSTEM_PROMPT },
  146. expectedFiles: { 'note.txt': 'target:\n\tnew\n' },
  147. expectedTools: { bash: ['command'], str_replace_editor: ['command', 'path'] },
  148. expectedSystem: MINIMAL_SYSTEM_PROMPT,
  149. expectedToolDescriptions: { bash: MINIMAL_BASH_DESCRIPTION },
  150. runtimeContext: {
  151. includes: ['Current DSH file policy: danger-full-access', 'Approval prompts are disabled in this session'],
  152. excludes: ['workspace-write'],
  153. },
  154. },
  155. ]
  156. interface PersistedLog {
  157. readonly path: string
  158. readonly content: string
  159. readonly header: Record<string, unknown>
  160. }
  161. interface MissingFile {
  162. readonly missing: true
  163. }
  164. async function jsonlFiles(dir: string): Promise<string[]> {
  165. const entries = await readdir(dir, { recursive: true })
  166. return entries.filter(entry => entry.endsWith('.jsonl')).map(entry => join(dir, entry)).sort()
  167. }
  168. async function persistedLogs(sessionsRoot: string): Promise<PersistedLog[]> {
  169. const files = await jsonlFiles(sessionsRoot)
  170. return Promise.all(files.map(async (path) => {
  171. const content = await readFile(path, 'utf8')
  172. const header = JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>
  173. return { path, content, header }
  174. }))
  175. }
  176. interface LoggedRequestHeader {
  177. type?: string
  178. data?: { header?: { system?: unknown; tools?: LoggedTool[] } }
  179. }
  180. interface LoggedTool {
  181. readonly name: string
  182. readonly description?: unknown
  183. readonly parameters: { readonly required?: string[] }
  184. }
  185. function assembledTools(log: PersistedLog): LoggedTool[] {
  186. const event = log.content.trimEnd().split('\n')
  187. .map(line => JSON.parse(line) as LoggedRequestHeader)
  188. .find(candidate => candidate.type === 'request/header')
  189. const tools = event?.data?.header?.tools
  190. if (tools === undefined) throw new Error('session log has no request/header tools')
  191. return tools
  192. }
  193. function assembledToolRequirements(log: PersistedLog): Record<string, string[]> {
  194. return Object.fromEntries(assembledTools(log).map(tool => [tool.name, tool.parameters.required ?? []]))
  195. }
  196. function assembledToolDescriptions(log: PersistedLog): Record<string, string> {
  197. return Object.fromEntries(assembledTools(log).map((tool) => {
  198. if (typeof tool.description !== 'string') throw new Error(`tool ${tool.name} has no description`)
  199. return [tool.name, tool.description]
  200. }))
  201. }
  202. function assembledSystem(log: PersistedLog): string {
  203. const event = log.content.trimEnd().split('\n')
  204. .map(line => JSON.parse(line) as LoggedRequestHeader)
  205. .find(candidate => candidate.type === 'request/header')
  206. const system = event?.data?.header?.system
  207. if (typeof system !== 'string') throw new Error('session log has no request/header system')
  208. return system
  209. }
  210. function assembledRuntimeContexts(log: PersistedLog): string[] {
  211. return log.content.trimEnd().split('\n').flatMap((line) => {
  212. const event = JSON.parse(line) as {
  213. type?: string
  214. data?: { source?: { kind?: string; plugin?: string }; content?: Array<{ type?: string; text?: unknown }> }
  215. }
  216. if (event.type !== 'user/message'
  217. || event.data?.source?.kind !== 'plugin'
  218. || event.data.source.plugin !== '@deepseek-ai/dsh-system-prompt') return []
  219. return event.data.content?.flatMap(block => block.type === 'text' && typeof block.text === 'string' ? [block.text] : []) ?? []
  220. })
  221. }
  222. function contextOf(logs: readonly { content: string; header: Record<string, unknown> }[], cwd: string): NormalizeContext {
  223. return {
  224. sessionIds: logs.flatMap(log => typeof log.header.id === 'string' ? [log.header.id] : []),
  225. cwd,
  226. }
  227. }
  228. function contextOfContents(contents: readonly string[]): NormalizeContext {
  229. const headers = contents.map(content => JSON.parse(content.slice(0, content.indexOf('\n'))) as Record<string, unknown>)
  230. return {
  231. sessionIds: headers.flatMap(header => typeof header.id === 'string' ? [header.id] : []),
  232. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  233. }
  234. }
  235. async function hydrateReplayFixtures(scenario: SdkScenario, cwd: string): Promise<string[]> {
  236. const root = join(cwd, '.replay-fixtures')
  237. await mkdir(root, { recursive: true })
  238. return Promise.all(fixtureFiles(scenario).map(async (source) => {
  239. const destination = join(root, basename(source))
  240. await writeFile(destination, (await readFile(source, 'utf8')).replaceAll('{{cwd}}', cwd))
  241. return destination
  242. }))
  243. }
  244. async function readExpectedFile(path: string): Promise<string | MissingFile> {
  245. try {
  246. return await readFile(path, 'utf8')
  247. } catch (error: unknown) {
  248. if (error instanceof Error && (error as NodeJS.ErrnoException).code === 'ENOENT') return { missing: true }
  249. throw error
  250. }
  251. }
  252. /** Materialize a built-mode replay patch with an absolute test-plugin module URL. */
  253. async function materializeReplayPatch(source: string, cwd: string): Promise<string> {
  254. const target = join(cwd, `.sdk-${basename(source)}`)
  255. const content = (await readFile(source, 'utf8'))
  256. .replaceAll("'@deepseek-ai/dsh-llm-replay'", JSON.stringify(pathToFileURL(replayPlugin).href))
  257. await writeFile(target, content)
  258. return target
  259. }
  260. /** Materialize the DSH SDK scenario patch with absolute test and provider modules. */
  261. async function materializeDshSdkPatch(source: string, cwd: string): Promise<string> {
  262. const target = join(cwd, `.sdk-${basename(source)}`)
  263. const content = (await readFile(source, 'utf8'))
  264. .replaceAll("'@deepseek-ai/dsh-subagent-dsh-sdk'", JSON.stringify(pathToFileURL(dshSdkProviderPlugin).href))
  265. .replaceAll("'./mock-delegating-llm.ts'", JSON.stringify(pathToFileURL(dshSdkParentMockPath).href))
  266. await writeFile(target, content)
  267. return target
  268. }
  269. /**
  270. * Normalize the SDK-visible notification stream: embedded `session.event`
  271. * envelopes get the session-log treatment (times zeroed, headers tokenized),
  272. * then every record is scrubbed like a wire frame.
  273. */
  274. function normalizeNotifications(notifications: readonly HarnessNotification[], ctx: NormalizeContext): string {
  275. const events = notifications
  276. .filter(n => n.method === 'session.event')
  277. .map(n => n.params.event as Record<string, unknown>)
  278. const normalizedEvents = events.length === 0
  279. ? []
  280. : scrubRequestHeaders(normalizeSessionLog(
  281. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  282. ctx,
  283. )).trimEnd().split('\n').map(line => JSON.parse(line) as Record<string, unknown>)
  284. let eventIndex = 0
  285. const records = notifications.map((notification) => {
  286. if (notification.method !== 'session.event') return { method: notification.method, params: notification.params }
  287. const event = normalizedEvents[eventIndex++]
  288. return { method: notification.method, params: { ...notification.params, event } }
  289. })
  290. return normalizeStdout(`${records.map(record => JSON.stringify(record)).join('\n')}\n`, ctx)
  291. }
  292. /** Normalize the owned-run projection. */
  293. function normalizeResult(result: RunResult, ctx: NormalizeContext): string {
  294. return normalizeStdout(`${JSON.stringify({
  295. sessionId: result.sessionId,
  296. finalResponse: result.finalResponse,
  297. })}\n`, ctx)
  298. }
  299. /** One SDK turn against a fresh runtime subprocess in an isolated cwd. */
  300. async function runScenario(scenario: SdkScenario): Promise<{
  301. result: RunResult
  302. notifications: HarnessNotification[]
  303. logs: PersistedLog[]
  304. observedFiles: Record<string, string | MissingFile>
  305. cwd: string
  306. }> {
  307. const cwd = await mkdtemp(join(tmpdir(), `sdk-snapshot-${scenario.name}-`))
  308. const dshHome = join(cwd, '.dsh')
  309. const sessionsRoot = join(dshHome, 'sessions')
  310. const replayFixtures = recording ? [] : await hydrateReplayFixtures(scenario, cwd)
  311. const livePatch = scenario.configs?.live ?? liveConfig
  312. const resolvedLivePatch = scenario.dshSdkChild === undefined
  313. ? livePatch
  314. : await materializeDshSdkPatch(livePatch, cwd)
  315. const replayPatch = scenario.configs?.replay ?? replayConfig
  316. const resolvedReplayPatch = recording ? undefined : await materializeReplayPatch(replayPatch, cwd)
  317. const additionalPatches = recording
  318. ? scenario.additionalPatches?.live ?? []
  319. : scenario.additionalPatches?.replay ?? []
  320. const [parentFixture, ...childFixtures] = replayFixtures
  321. let childEnvironment: Record<string, string> = {}
  322. if (scenario.dshSdkChild !== undefined) {
  323. const childHome = join(cwd, '.child-dsh')
  324. const childPatch = join(childHome, 'child.cordis.yml')
  325. await mkdir(childHome, { recursive: true })
  326. await writeFile(childPatch, (await readFile(scenario.dshSdkChild.config, 'utf8'))
  327. .replace("'./child-mock-llm.ts'", JSON.stringify(pathToFileURL(dshSdkChildMockPath).href)))
  328. childEnvironment = {
  329. DSH_TEST_CHILD_PATCHES: JSON.stringify([childPatch]),
  330. DSH_TEST_CHILD_HOME: childHome,
  331. }
  332. }
  333. const env: Record<string, string> = {
  334. ...Object.fromEntries(Object.entries(process.env).filter(([, value]) => value !== undefined)) as Record<string, string>,
  335. DSH_SNAPSHOT: mode,
  336. DSH_TELEMETRY_DISABLED: '1',
  337. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  338. ...parentFixture === undefined ? {} : {
  339. DSH_SNAPSHOT_FILE: parentFixture,
  340. ...childFixtures.length > 0 ? { DSH_SNAPSHOT_CHILD_FILES: childFixtures.join(delimiter) } : {},
  341. },
  342. ...scenario.environment,
  343. ...childEnvironment,
  344. }
  345. const harness = new DeepSeekHarness({
  346. profile: 'sdk',
  347. patches: [
  348. resolvedLivePatch,
  349. ...resolvedReplayPatch === undefined ? [] : [resolvedReplayPatch],
  350. ...additionalPatches,
  351. ],
  352. dshHome,
  353. processCwd: cwd,
  354. env,
  355. requestTimeoutMs: 110_000,
  356. cwd,
  357. provider: scenario.sdkRoute?.provider ?? 'deepseek-official',
  358. model: scenario.sdkRoute?.model ?? 'deepseek-v4-flash',
  359. })
  360. try {
  361. const notifications: HarnessNotification[] = []
  362. const result = await harness.run(scenario.prompt.replaceAll('{{cwd}}', cwd), {
  363. sessionId: scenario.sessionId,
  364. onNotification: (notification) => { notifications.push(notification) },
  365. })
  366. await harness.close()
  367. const logs = (await Promise.all([
  368. persistedLogs(sessionsRoot),
  369. ...(scenario.dshSdkChild === undefined
  370. ? []
  371. : [persistedLogs(join(cwd, scenario.dshSdkChild.sessionRoot))]),
  372. ])).flat()
  373. const observedFiles = Object.fromEntries(await Promise.all(
  374. Object.keys(scenario.expectedFiles ?? {}).map(async (path): Promise<[string, string | MissingFile]> => [
  375. path,
  376. await readExpectedFile(join(cwd, path)),
  377. ]),
  378. ))
  379. return { result, notifications, logs, observedFiles, cwd }
  380. } finally {
  381. await harness.close()
  382. await rm(cwd, { recursive: true, force: true })
  383. }
  384. }
  385. /** Order logs parent-first, children by creation time (fixture layout order). */
  386. function orderLogs(logs: PersistedLog[], scenario: SdkScenario): PersistedLog[] {
  387. if (scenario.dshSdkChild !== undefined) {
  388. expect(logs).toHaveLength(scenario.children + 1)
  389. return logs
  390. }
  391. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  392. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  393. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  394. expect(parents).toHaveLength(1)
  395. expect(children).toHaveLength(scenario.children)
  396. return [...parents, ...children]
  397. }
  398. function fixtureFiles(scenario: SdkScenario): string[] {
  399. const dir = join(snapshotsDir, scenario.name)
  400. return [
  401. join(dir, 'session.jsonl'),
  402. ...Array.from({ length: scenario.children }, (_, index) => join(dir, `session.${index + 1}.jsonl`)),
  403. ]
  404. }
  405. describe('TypeScript SDK snapshots over the jsonrpc runtime', () => {
  406. for (const scenario of SCENARIOS) {
  407. it(`replays ${scenario.name} through the SDK`, async () => {
  408. const scenarioDir = join(snapshotsDir, scenario.name)
  409. const notificationsExpectedPath = join(scenarioDir, 'notifications.expected.jsonl')
  410. const resultExpectedPath = join(scenarioDir, 'result.expected.json')
  411. const { result, notifications, logs, observedFiles, cwd } = await runScenario(scenario)
  412. const ordered = orderLogs(logs, scenario)
  413. const actualContext = contextOf(ordered, cwd)
  414. const files = fixtureFiles(scenario)
  415. if (recording) {
  416. // Fixtures carry tokenized request headers; llm-replay reads only
  417. // assistant output and tool traffic, so scrubbing keeps prompts and
  418. // schemas out of the corpus without affecting replay.
  419. await mkdir(scenarioDir, { recursive: true })
  420. const existing = await Promise.all(files.map(async file => existsSync(file) ? readFile(file, 'utf8') : ''))
  421. const fixtures = stabilizeFixtureMessageIds(
  422. ordered.map(log => scrubSessionSnapshot(tokenizeSessionFixtureCwd(log.content))),
  423. existing,
  424. )
  425. await Promise.all(fixtures.map(async (fixture, index) => {
  426. const file = files[index]
  427. if (file === undefined) throw new Error(`no fixture path for persisted log ${index}`)
  428. await writeFile(file, fixture)
  429. }))
  430. }
  431. let expectedContents = await Promise.all(files.map(file => readFile(file, 'utf8')))
  432. if (refreshing) {
  433. const harvested = ordered.map((log): HarvestedLog => ({
  434. id: String(log.header.id),
  435. createdAt: Number(log.header.createdAt),
  436. ...typeof log.header.parentSession === 'string' ? { parentSession: log.header.parentSession } : {},
  437. content: log.content,
  438. }))
  439. const replacements = refreshFixtureReplacements(harvested, expectedContents)
  440. const refreshed = ordered.map((log, index) => {
  441. const existing = expectedContents[index]
  442. if (existing === undefined) throw new Error(`no fixture for persisted log ${index}`)
  443. return scrubSessionSnapshot(tokenizeSessionFixtureCwd(
  444. stabilizeRefreshLog(log.content, existing, replacements, actualContext),
  445. ))
  446. })
  447. expectedContents = stabilizeFixtureMessageIds(refreshed, expectedContents)
  448. await Promise.all(expectedContents.map(async (stable, index) => {
  449. const file = files[index]
  450. if (file === undefined) throw new Error(`no fixture for persisted log ${index}`)
  451. await writeFile(file, stable)
  452. }))
  453. }
  454. for (const [index, expected] of expectedContents.entries()) {
  455. expect(scrubRequestHeaders(expected), `${scenario.name} session fixture ${index} carries request-header bulk`)
  456. .toBe(expected)
  457. }
  458. // Persisted transcripts match the committed fixtures.
  459. const expectedContext = contextOfContents(expectedContents)
  460. for (const [index, log] of ordered.entries()) {
  461. const expected = expectedContents[index]
  462. if (expected === undefined) throw new Error(`no fixture for persisted log ${index}`)
  463. expect(normalizeSessionSnapshot(log.content, actualContext))
  464. .toBe(normalizeSessionSnapshot(expected, expectedContext))
  465. }
  466. // The SDK-visible wire stream and turn result match their expected outputs.
  467. const normalizedNotifications = normalizeNotifications(notifications, actualContext)
  468. const normalizedResult = normalizeResult(result, actualContext)
  469. if (recording || refreshing) {
  470. await writeFile(notificationsExpectedPath, normalizedNotifications)
  471. await writeFile(resultExpectedPath, normalizedResult)
  472. }
  473. expect(normalizedNotifications).toBe(await readFile(notificationsExpectedPath, 'utf8'))
  474. expect(normalizedResult).toBe(await readFile(resultExpectedPath, 'utf8'))
  475. // Wire-shape invariants that must hold in every mode.
  476. expect(notifications.at(-1)).toMatchObject({
  477. method: 'session.status',
  478. params: { status: 'idle' },
  479. })
  480. expect(observedFiles).toEqual(scenario.expectedFiles ?? {})
  481. if (scenario.expectedTools !== undefined) {
  482. const parent = ordered[0]
  483. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  484. expect(assembledToolRequirements(parent)).toEqual(scenario.expectedTools)
  485. }
  486. if (scenario.expectedSystem !== undefined) {
  487. const parent = ordered[0]
  488. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  489. expect(assembledSystem(parent)).toBe(scenario.expectedSystem)
  490. }
  491. if (scenario.expectedToolDescriptions !== undefined) {
  492. const parent = ordered[0]
  493. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  494. expect(assembledToolDescriptions(parent)).toMatchObject(scenario.expectedToolDescriptions)
  495. }
  496. if (scenario.runtimeContext !== undefined) {
  497. const parent = ordered[0]
  498. if (parent === undefined) throw new Error(`${scenario.name} has no parent session log`)
  499. const contexts = assembledRuntimeContexts(parent)
  500. if (scenario.runtimeContext === false) {
  501. expect(contexts).toEqual([])
  502. } else {
  503. expect(contexts).toHaveLength(1)
  504. const context = contexts[0] as string
  505. for (const clause of scenario.runtimeContext.includes) expect(context).toContain(clause)
  506. for (const clause of scenario.runtimeContext.excludes) expect(context).not.toContain(clause)
  507. const system = assembledSystem(parent)
  508. for (const clause of scenario.runtimeContext.includes) expect(system).not.toContain(clause)
  509. }
  510. }
  511. if (scenario.children > 0 && scenario.dshSdkChild === undefined) {
  512. expect(notifications.some(n => n.method === 'subagent.started')).toBe(true)
  513. expect(notifications.some(n => n.method === 'subagent.finished')).toBe(true)
  514. }
  515. })
  516. }
  517. })