headless.snapshot.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. import { readFile, readdir, writeFile } from 'node:fs/promises'
  2. import { delimiter, dirname, join } from 'node:path'
  3. import { fileURLToPath } from 'node:url'
  4. import {
  5. normalizeSessionLog,
  6. normalizeStdout,
  7. refreshFixtureReplacements,
  8. scrubRequestHeaders,
  9. stabilizeRefreshLog,
  10. type HarvestedLog,
  11. type NormalizeContext,
  12. } from '@deepseek-ai/dsh-acp-snapshot'
  13. import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
  14. import { describe, expect, it } from 'vitest'
  15. const snapshotsDir = join(dirname(fileURLToPath(import.meta.url)), 'snapshots')
  16. const advancedScenarioDir = join(snapshotsDir, 'advanced-toolchain')
  17. const advancedSessionFixture = join(advancedScenarioDir, 'session.jsonl')
  18. const advancedStreamExpected = join(advancedScenarioDir, 'stream-json.expected.jsonl')
  19. const advancedConfigPath = fileURLToPath(new URL('../advanced.cordis.snapshot.yml', import.meta.url))
  20. const ptyScenarioDir = join(snapshotsDir, 'pty-tools')
  21. const ptySessionFixture = join(ptyScenarioDir, 'session.jsonl')
  22. const ptyStreamExpected = join(ptyScenarioDir, 'stream-json.expected.jsonl')
  23. const ptyConfigPath = fileURLToPath(new URL('../pty.cordis.snapshot.yml', import.meta.url))
  24. const goalScenarioDir = join(snapshotsDir, 'goal-tools')
  25. const goalConfigPath = fileURLToPath(new URL('../goal.cordis.snapshot.yml', import.meta.url))
  26. const ralphScenarioDir = join(snapshotsDir, 'ralph-loop')
  27. const ralphConfigPath = fileURLToPath(new URL('../ralph.cordis.snapshot.yml', import.meta.url))
  28. const binScript = fileURLToPath(new URL('../../../packages/examples/cli-demo/src/bin.ts', import.meta.url))
  29. const tsconfigPath = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  30. const reasoningConfigPath = fileURLToPath(new URL('./fixtures/cli.cordis.yml', import.meta.url))
  31. const refreshing = process.env.DSH_SNAPSHOT === 'refresh'
  32. interface JsonObject {
  33. [key: string]: unknown
  34. }
  35. interface PersistedLog {
  36. readonly content: string
  37. readonly header: JsonObject
  38. }
  39. function parseJsonl(content: string): JsonObject[] {
  40. return content.split('\n')
  41. .filter(line => line.trim().length > 0)
  42. .map(line => JSON.parse(line) as JsonObject)
  43. }
  44. function contextFromLogs(contents: readonly string[]): NormalizeContext {
  45. const headers = contents.map(content => parseJsonl(content)[0])
  46. return {
  47. sessionIds: headers.flatMap(header => typeof header?.id === 'string' ? [header.id] : []),
  48. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  49. }
  50. }
  51. function normalizeHeadlessStream(rawStdout: string, cwd: string): string {
  52. const records = parseJsonl(rawStdout)
  53. if (records.length === 0) throw new Error('headless snapshot emitted no stream-json records')
  54. const final = records.at(-1)
  55. if (final?.type !== 'result') throw new Error('headless snapshot did not end with a result record')
  56. if (records.slice(0, -1).some(record => record.type !== 'session_event')) {
  57. throw new Error('headless snapshot emitted a non-event record before its result')
  58. }
  59. const sessionIds = [...new Set(records.flatMap(record => typeof record.sessionId === 'string' ? [record.sessionId] : []))]
  60. if (sessionIds.length !== 1) throw new Error(`headless snapshot streamed ${sessionIds.length} main session ids`)
  61. const context: NormalizeContext = { sessionIds, cwd }
  62. const events = records.slice(0, -1).map((record) => {
  63. if (record.event === null || typeof record.event !== 'object' || Array.isArray(record.event)) {
  64. throw new Error('headless snapshot emitted an invalid session event')
  65. }
  66. return record.event as JsonObject
  67. })
  68. const normalizedEvents = parseJsonl(scrubRequestHeaders(normalizeSessionLog(
  69. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  70. context,
  71. )))
  72. const normalizedRecords = records.map((record, index) => index < normalizedEvents.length
  73. ? { ...record, event: normalizedEvents[index] }
  74. : record)
  75. return normalizeStdout(`${normalizedRecords.map(record => JSON.stringify(record)).join('\n')}\n`, context)
  76. }
  77. /** Zero durable goal timestamps inside both metadata records and rendered XML JSON. */
  78. function normalizeGoalTimestamps(value: unknown): unknown {
  79. if (typeof value === 'string') {
  80. return value.replace(/("(?:createdAt|updatedAt|clearedAt)":)\d+/g, '$10')
  81. }
  82. if (Array.isArray(value)) return value.map(normalizeGoalTimestamps)
  83. if (value !== null && typeof value === 'object') {
  84. return Object.fromEntries(Object.entries(value).map(([key, item]) => [
  85. key,
  86. ['createdAt', 'updatedAt', 'clearedAt'].includes(key) && typeof item === 'number'
  87. ? 0
  88. : normalizeGoalTimestamps(item),
  89. ]))
  90. }
  91. return value
  92. }
  93. /** Normalize the stream's durable goal timestamps after the shared scrubbers. */
  94. function normalizeGoalStream(rawStdout: string, cwd: string): string {
  95. return parseJsonl(normalizeHeadlessStream(rawStdout, cwd))
  96. .map(record => JSON.stringify(normalizeGoalTimestamps(record)))
  97. .join('\n') + '\n'
  98. }
  99. async function scenarioPrompt(dir: string, label: string): Promise<string> {
  100. const input = JSON.parse(await readFile(join(dir, 'input.json'), 'utf8')) as {
  101. steps?: { op?: unknown; text?: unknown }[]
  102. }
  103. const prompt = input.steps?.find(step => step.op === 'prompt')?.text
  104. if (typeof prompt !== 'string') throw new Error(`${label} input has no prompt step`)
  105. return prompt
  106. }
  107. async function persistedLogs(cwd: string): Promise<PersistedLog[]> {
  108. const root = join(cwd, '.sessions')
  109. const files = (await readdir(root, { recursive: true })).filter(file => file.endsWith('.jsonl'))
  110. return Promise.all(files.map(async (file) => {
  111. const content = await readFile(join(root, file), 'utf8')
  112. return { content, header: parseJsonl(content)[0] ?? {} }
  113. }))
  114. }
  115. describe('headless stream-json snapshots', () => {
  116. it('logs the model default and a dynamic next-step reasoning effort', async () => {
  117. const result = await runLoaderSmoke({
  118. label: 'reasoning effort headless stream-json snapshot',
  119. tempDirPrefix: 'headless-snapshot-reasoning-effort-',
  120. binScript,
  121. configPath: reasoningConfigPath,
  122. binArgs: ['--config', reasoningConfigPath, '--output-format', 'stream-json', 'prove dynamic reasoning effort'],
  123. tsconfigPath,
  124. })
  125. expect(result.stderr).toBe('')
  126. const headers = parseJsonl(result.stdout)
  127. .map(record => record.event)
  128. .filter((event): event is JsonObject => (
  129. event !== null
  130. && typeof event === 'object'
  131. && !Array.isArray(event)
  132. && 'type' in event
  133. && event.type === 'request/header'
  134. ))
  135. .map((event) => {
  136. const data = event.data as JsonObject
  137. return (data.header as JsonObject).config
  138. })
  139. expect(headers).toMatchInlineSnapshot(`
  140. [
  141. {
  142. "model": "cli-mock",
  143. "provider": "cli-mock",
  144. "reasoningEffort": "high",
  145. },
  146. {
  147. "model": "cli-mock",
  148. "provider": "cli-mock",
  149. "reasoningEffort": "off",
  150. },
  151. ]
  152. `)
  153. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  154. it('replays the advanced toolchain through the one-shot app', async () => {
  155. const prompt = await scenarioPrompt(advancedScenarioDir, 'advanced-toolchain')
  156. const fixtureFiles = [
  157. advancedSessionFixture,
  158. join(advancedScenarioDir, 'session.1.jsonl'),
  159. join(advancedScenarioDir, 'session.2.jsonl'),
  160. ]
  161. let expectedSessions = await Promise.all(fixtureFiles.map(file => readFile(file, 'utf8')))
  162. let runCwd = ''
  163. const result = await runLoaderSmoke({
  164. label: 'advanced headless stream-json snapshot',
  165. tempDirPrefix: 'headless-snapshot-advanced-',
  166. binScript,
  167. configPath: advancedConfigPath,
  168. binArgs: ['--config', advancedConfigPath, '--output-format', 'stream-json', prompt],
  169. tsconfigPath,
  170. env: {
  171. DSH_SNAPSHOT: 'replay',
  172. DSH_SNAPSHOT_FILE: advancedSessionFixture,
  173. DSH_SNAPSHOT_CHILD_FILES: [
  174. join(advancedScenarioDir, 'session.1.jsonl'),
  175. join(advancedScenarioDir, 'session.2.jsonl'),
  176. ].join(delimiter),
  177. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  178. },
  179. prepare: (cwd) => { runCwd = cwd },
  180. inspect: async (cwd) => {
  181. const logs = await persistedLogs(cwd)
  182. expect(logs).toHaveLength(3)
  183. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  184. expect(parents).toHaveLength(1)
  185. const parent = parents[0]
  186. if (parent === undefined) throw new Error('headless snapshot did not persist its main session')
  187. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  188. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  189. const actualSessions = [parent, ...children]
  190. if (refreshing) {
  191. const harvested = actualSessions.map((log): HarvestedLog => ({
  192. id: String(log.header.id),
  193. createdAt: Number(log.header.createdAt),
  194. ...typeof log.header.parentSession === 'string'
  195. ? { parentSession: log.header.parentSession }
  196. : {},
  197. content: log.content,
  198. }))
  199. const replacements = refreshFixtureReplacements(harvested, expectedSessions)
  200. expectedSessions = await Promise.all(actualSessions.map(async (actual, index) => {
  201. const existing = expectedSessions[index]
  202. const file = fixtureFiles[index]
  203. if (existing === undefined || file === undefined) {
  204. throw new Error(`headless snapshot has no fixture for persisted log ${index}`)
  205. }
  206. const stable = stabilizeRefreshLog(actual.content, existing, replacements)
  207. await writeFile(file, stable)
  208. return stable
  209. }))
  210. }
  211. const actualContext = contextFromLogs(actualSessions.map(log => log.content))
  212. const expectedContext = contextFromLogs(expectedSessions)
  213. for (const [index, actual] of actualSessions.entries()) {
  214. const expected = expectedSessions[index]
  215. if (expected === undefined) throw new Error(`headless snapshot has no fixture for persisted log ${index}`)
  216. expect(scrubRequestHeaders(normalizeSessionLog(actual.content, actualContext)))
  217. .toBe(scrubRequestHeaders(normalizeSessionLog(expected, expectedContext)))
  218. }
  219. },
  220. })
  221. expect(result.stderr).toBe('')
  222. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  223. if (refreshing) await writeFile(advancedStreamExpected, normalized)
  224. expect(normalized).toBe(await readFile(advancedStreamExpected, 'utf8'))
  225. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  226. it('replays persisted goal tools through the one-shot app', async () => {
  227. const prompt = await scenarioPrompt(goalScenarioDir, 'goal-tools')
  228. const streamExpected = join(goalScenarioDir, 'stream-json.expected.jsonl')
  229. let runCwd = ''
  230. const result = await runLoaderSmoke({
  231. label: 'goal tools headless stream-json snapshot',
  232. tempDirPrefix: 'headless-snapshot-goal-tools-',
  233. binScript,
  234. configPath: goalConfigPath,
  235. binArgs: ['--config', goalConfigPath, '--output-format', 'stream-json', prompt],
  236. tsconfigPath,
  237. env: {
  238. DSH_SNAPSHOT: 'replay',
  239. DSH_SNAPSHOT_FILE: join(goalScenarioDir, 'session.jsonl'),
  240. DSH_SNAPSHOT_OVERRIDE: join(goalScenarioDir, 'replay.override.json'),
  241. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  242. },
  243. prepare: (cwd) => { runCwd = cwd },
  244. inspect: async (cwd) => {
  245. const logs = await persistedLogs(cwd)
  246. expect(logs).toHaveLength(1)
  247. const records = parseJsonl(logs[0]?.content ?? '')
  248. const calls = records.filter(record => record.type === 'tool/call')
  249. .map(record => (record.data as JsonObject | undefined)?.name)
  250. expect(calls).toEqual(['update_goal', 'create_goal', 'get_goal'])
  251. const probeResult = records.find(record => record.type === 'tool/result'
  252. && (record.data as JsonObject | undefined)?.callId === 'call_goal_probe')
  253. const probeData = probeResult?.data as JsonObject | undefined
  254. expect(probeData?.isError).toBe(true)
  255. expect((probeData?.error as JsonObject | undefined)?.code).toBe('GOAL_NOT_FOUND')
  256. const goalChanges = records.filter((record) => {
  257. if (record.type !== 'user/message') return false
  258. const data = record.data as JsonObject | undefined
  259. const meta = data?.meta as JsonObject | undefined
  260. return meta?.kind === 'goal/change'
  261. })
  262. expect(goalChanges).toHaveLength(1)
  263. const data = goalChanges[0]?.data as JsonObject | undefined
  264. const meta = data?.meta as JsonObject | undefined
  265. const goal = meta?.goal as JsonObject | undefined
  266. expect(meta?.operation).toBe('create')
  267. expect(goal).toMatchObject({
  268. objective: 'Finish the headless goal-tool snapshot proof',
  269. phase: 'active',
  270. maxGoalRounds: 7,
  271. })
  272. },
  273. })
  274. expect(result.stderr).toBe('')
  275. const normalized = normalizeGoalStream(result.stdout, runCwd)
  276. if (refreshing) await writeFile(streamExpected, normalized)
  277. expect(normalized).toBe(await readFile(streamExpected, 'utf8'))
  278. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  279. it('replays two fresh Ralph rounds through the one-shot app', async () => {
  280. const prompt = await scenarioPrompt(ralphScenarioDir, 'ralph-loop')
  281. const streamExpected = join(ralphScenarioDir, 'stream-json.expected.jsonl')
  282. let runCwd = ''
  283. const result = await runLoaderSmoke({
  284. label: 'Ralph loop headless stream-json snapshot',
  285. tempDirPrefix: 'headless-snapshot-ralph-loop-',
  286. binScript,
  287. configPath: ralphConfigPath,
  288. binArgs: ['--config', ralphConfigPath, '--output-format', 'stream-json', prompt],
  289. tsconfigPath,
  290. env: {
  291. DSH_SNAPSHOT: 'replay',
  292. DSH_SNAPSHOT_FILE: join(ralphScenarioDir, 'session.jsonl'),
  293. DSH_SNAPSHOT_OVERRIDE: join(ralphScenarioDir, 'replay.override.json'),
  294. DSH_SNAPSHOT_CHILD_FILES: [
  295. join(ralphScenarioDir, 'session.1.jsonl'),
  296. join(ralphScenarioDir, 'session.2.jsonl'),
  297. ].join(delimiter),
  298. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  299. },
  300. prepare: (cwd) => { runCwd = cwd },
  301. inspect: async (cwd) => {
  302. const logs = await persistedLogs(cwd)
  303. expect(logs).toHaveLength(3)
  304. const parent = logs.find(log => typeof log.header.parentSession !== 'string')
  305. if (parent === undefined) throw new Error('Ralph snapshot did not persist its parent session')
  306. const parentId = parent.header.id
  307. expect(typeof parentId).toBe('string')
  308. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  309. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  310. expect(children).toHaveLength(2)
  311. expect(children.map(child => child.header.parentSession)).toEqual([parentId, parentId])
  312. expect(children.map(child => child.header.cwd)).toEqual([parent.header.cwd, parent.header.cwd])
  313. expect(parent.header.delegationDepth).toBe(0)
  314. expect(children.map(child => child.header.delegationDepth)).toEqual([1, 1])
  315. expect(children.map(child => child.header.seedLength)).toEqual([undefined, undefined])
  316. expect(new Set(children.map(child => child.header.id)).size).toBe(2)
  317. const parentRecords = parseJsonl(parent.content)
  318. const parentCalls = parentRecords.filter(record => record.type === 'tool/call')
  319. expect(parentCalls.map(record => (record.data as JsonObject | undefined)?.name)).toEqual(['ralph'])
  320. const parentResult = parentRecords.find(record => record.type === 'tool/result')
  321. const parentResultData = parentResult?.data as JsonObject | undefined
  322. expect(parentResultData?.isError).toBe(false)
  323. expect(JSON.stringify(parentResultData?.content)).toContain('reported completion after 2 rounds')
  324. const childRecords = children.map(child => parseJsonl(child.content))
  325. const childPrompts = childRecords.map((records) => {
  326. const message = records.find(record => record.type === 'user/message')
  327. return JSON.stringify((message?.data as JsonObject | undefined)?.content)
  328. })
  329. expect(childPrompts[0]).toContain('Ralph round: 1 of 2.')
  330. expect(childPrompts[0]).toContain('(none — this is the first round)')
  331. expect(childPrompts[0]).not.toContain('ROUND_ONE_HANDOFF')
  332. expect(childPrompts[1]).toContain('Ralph round: 2 of 2.')
  333. expect(childPrompts[1]).toContain('ROUND_ONE_HANDOFF')
  334. for (const childPrompt of childPrompts) {
  335. expect(childPrompt).toContain('Prove two fresh Ralph rounds through the shipped headless app.')
  336. expect(childPrompt).not.toContain('Run a two-round fresh-agent Ralph loop')
  337. }
  338. for (const records of childRecords) {
  339. const calls = records.filter(record => record.type === 'tool/call')
  340. expect(calls.map(record => (record.data as JsonObject | undefined)?.name))
  341. .toEqual(['structured_output'])
  342. }
  343. },
  344. })
  345. expect(result.stderr).toBe('')
  346. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  347. if (refreshing) await writeFile(streamExpected, normalized)
  348. expect(normalized).toBe(await readFile(streamExpected, 'utf8'))
  349. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  350. it('replays persistent PTY tools through the one-shot app', async () => {
  351. const input = JSON.parse(await readFile(join(ptyScenarioDir, 'input.json'), 'utf8')) as {
  352. steps?: { op?: unknown; text?: unknown }[]
  353. }
  354. const prompt = input.steps?.find(step => step.op === 'prompt')?.text
  355. if (typeof prompt !== 'string') throw new Error('pty-tools input has no prompt step')
  356. let expectedSession = await readFile(ptySessionFixture, 'utf8')
  357. let runCwd = ''
  358. const result = await runLoaderSmoke({
  359. label: 'headless persistent PTY snapshot',
  360. tempDirPrefix: 'headless-snapshot-pty-',
  361. binScript,
  362. configPath: ptyConfigPath,
  363. binArgs: ['--config', ptyConfigPath, '--output-format', 'stream-json', prompt],
  364. tsconfigPath,
  365. env: {
  366. DSH_SNAPSHOT: 'replay',
  367. DSH_SNAPSHOT_FILE: ptySessionFixture,
  368. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  369. },
  370. prepare: (cwd) => { runCwd = cwd },
  371. inspect: async (cwd) => {
  372. const logs = await persistedLogs(cwd)
  373. expect(logs).toHaveLength(1)
  374. const actual = logs[0]
  375. if (actual === undefined) throw new Error('headless PTY snapshot did not persist its session')
  376. if (refreshing) {
  377. const harvested: HarvestedLog = {
  378. id: String(actual.header.id),
  379. createdAt: Number(actual.header.createdAt),
  380. content: actual.content,
  381. }
  382. const replacements = refreshFixtureReplacements([harvested], [expectedSession])
  383. expectedSession = stabilizeRefreshLog(actual.content, expectedSession, replacements)
  384. await writeFile(ptySessionFixture, expectedSession)
  385. }
  386. const actualContext = contextFromLogs([actual.content])
  387. const expectedContext = contextFromLogs([expectedSession])
  388. expect(scrubRequestHeaders(normalizeSessionLog(actual.content, actualContext)))
  389. .toBe(scrubRequestHeaders(normalizeSessionLog(expectedSession, expectedContext)))
  390. },
  391. })
  392. expect(result.stderr).toBe('')
  393. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  394. if (refreshing) await writeFile(ptyStreamExpected, normalized)
  395. expect(normalized).toBe(await readFile(ptyStreamExpected, 'utf8'))
  396. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  397. })