headless.snapshot.ts 22 KB

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