sdk.snapshot.ts 24 KB

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