sdk.snapshot.ts 23 KB

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