headless.snapshot.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import { readFile, readdir, writeFile } from 'node:fs/promises'
  2. import { createServer } from 'node:http'
  3. import type { IncomingMessage, ServerResponse } from 'node:http'
  4. import { delimiter, dirname, join } from 'node:path'
  5. import { fileURLToPath } from 'node:url'
  6. import {
  7. normalizeSessionLog,
  8. normalizeStdout,
  9. refreshFixtureReplacements,
  10. scrubRequestHeaders,
  11. stabilizeRefreshLog,
  12. tokenizeSessionFixtureCwd,
  13. type HarvestedLog,
  14. type NormalizeContext,
  15. } from '@deepseek-ai/dsh-acp-snapshot'
  16. import { LOADER_SMOKE_TEST_TIMEOUT_MS, runLoaderSmoke } from '@deepseek-ai/dsh-loader-smoke'
  17. import { describe, expect, it } from 'vitest'
  18. const snapshotsDir = join(dirname(fileURLToPath(import.meta.url)), 'snapshots')
  19. const advancedScenarioDir = join(snapshotsDir, 'advanced-toolchain')
  20. const advancedSessionFixture = join(advancedScenarioDir, 'session.jsonl')
  21. const advancedStreamExpected = join(advancedScenarioDir, 'stream-json.expected.jsonl')
  22. const advancedConfigPath = fileURLToPath(new URL('../advanced.cordis.snapshot.yml', import.meta.url))
  23. const ptyScenarioDir = join(snapshotsDir, 'pty-tools')
  24. const ptySessionFixture = join(ptyScenarioDir, 'session.jsonl')
  25. const ptyStreamExpected = join(ptyScenarioDir, 'stream-json.expected.jsonl')
  26. const ptyConfigPath = fileURLToPath(new URL('../pty.cordis.snapshot.yml', import.meta.url))
  27. const goalScenarioDir = join(snapshotsDir, 'goal-tools')
  28. const goalConfigPath = fileURLToPath(new URL('../goal.cordis.snapshot.yml', import.meta.url))
  29. const retryScenarioDir = join(snapshotsDir, 'provider-retry')
  30. const retryConfigPath = fileURLToPath(new URL('../retry.cordis.snapshot.yml', import.meta.url))
  31. const credentialsScenarioDir = join(snapshotsDir, 'missing-credential')
  32. const credentialsConfigPath = fileURLToPath(new URL('../credentials.cordis.snapshot.yml', import.meta.url))
  33. const ralphScenarioDir = join(snapshotsDir, 'ralph-loop')
  34. const ralphConfigPath = fileURLToPath(new URL('../ralph.cordis.snapshot.yml', import.meta.url))
  35. const startupFailureConfigPath = fileURLToPath(new URL('./fixtures/startup-activation-error/cordis.yml', import.meta.url))
  36. const startupFailureExpected = join(snapshotsDir, 'startup-activation-error', 'stderr.expected.txt')
  37. const binScript = fileURLToPath(new URL('../../../packages/examples/cli-demo/src/bin.ts', import.meta.url))
  38. const tsconfigPath = fileURLToPath(new URL('../../../tsconfig.json', import.meta.url))
  39. const reasoningConfigPath = fileURLToPath(new URL('./fixtures/cli.cordis.yml', import.meta.url))
  40. const deepseekDefaultsConfigPath = fileURLToPath(new URL('./fixtures/deepseek-defaults.cordis.yml', import.meta.url))
  41. const refreshing = process.env.DSH_SNAPSHOT === 'refresh'
  42. interface JsonObject {
  43. [key: string]: unknown
  44. }
  45. interface PersistedLog {
  46. readonly content: string
  47. readonly header: JsonObject
  48. }
  49. interface DeepSeekDefaultsServer {
  50. readonly url: string
  51. readonly requests: JsonObject[]
  52. close(): Promise<void>
  53. }
  54. /** Serve one deterministic DeepSeek-compatible response while retaining its request body. */
  55. async function deepseekDefaultsServer(): Promise<DeepSeekDefaultsServer> {
  56. const requests: JsonObject[] = []
  57. const server = createServer((request: IncomingMessage, response: ServerResponse) => {
  58. let body = ''
  59. request.setEncoding('utf8')
  60. request.on('data', (chunk: string) => { body += chunk })
  61. request.on('end', () => {
  62. requests.push(JSON.parse(body) as JsonObject)
  63. response.writeHead(200, { 'content-type': 'text/event-stream' })
  64. response.end([
  65. 'data: {"choices":[{"delta":{"content":"DEFAULTS_OK"}}]}',
  66. 'data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}',
  67. 'data: [DONE]',
  68. '',
  69. ].join('\n\n'))
  70. })
  71. })
  72. await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
  73. const address = server.address()
  74. if (address === null || typeof address === 'string') throw new Error('DeepSeek defaults snapshot server has no port')
  75. return {
  76. url: `http://127.0.0.1:${address.port}`,
  77. requests,
  78. close: () => new Promise(resolve => server.close(() => { resolve() })),
  79. }
  80. }
  81. function parseJsonl(content: string): JsonObject[] {
  82. return content.split('\n')
  83. .filter(line => line.trim().length > 0)
  84. .map(line => JSON.parse(line) as JsonObject)
  85. }
  86. function contextFromLogs(contents: readonly string[]): NormalizeContext {
  87. const headers = contents.map(content => parseJsonl(content)[0])
  88. return {
  89. sessionIds: headers.flatMap(header => typeof header?.id === 'string' ? [header.id] : []),
  90. cwd: typeof headers[0]?.cwd === 'string' ? headers[0].cwd : '\0no-cwd\0',
  91. }
  92. }
  93. function normalizeHeadlessStream(rawStdout: string, cwd: string): string {
  94. const records = parseJsonl(rawStdout)
  95. if (records.length === 0) throw new Error('headless snapshot emitted no stream-json records')
  96. const final = records.at(-1)
  97. if (final?.type !== 'result') throw new Error('headless snapshot did not end with a result record')
  98. if (records.slice(0, -1).some(record => record.type !== 'session_event')) {
  99. throw new Error('headless snapshot emitted a non-event record before its result')
  100. }
  101. const sessionIds = [...new Set(records.flatMap(record => typeof record.sessionId === 'string' ? [record.sessionId] : []))]
  102. if (sessionIds.length !== 1) throw new Error(`headless snapshot streamed ${sessionIds.length} main session ids`)
  103. const context: NormalizeContext = { sessionIds, cwd }
  104. const events = records.slice(0, -1).map((record) => {
  105. if (record.event === null || typeof record.event !== 'object' || Array.isArray(record.event)) {
  106. throw new Error('headless snapshot emitted an invalid session event')
  107. }
  108. return record.event as JsonObject
  109. })
  110. const normalizedEvents = parseJsonl(scrubRequestHeaders(normalizeSessionLog(
  111. `${events.map(event => JSON.stringify(event)).join('\n')}\n`,
  112. context,
  113. )))
  114. const normalizedRecords = records.map((record, index) => index < normalizedEvents.length
  115. ? { ...record, event: normalizedEvents[index] }
  116. : record)
  117. return normalizeStdout(`${normalizedRecords.map(record => JSON.stringify(record)).join('\n')}\n`, context)
  118. }
  119. /** Zero durable goal timestamps inside both metadata records and rendered XML JSON. */
  120. function normalizeGoalTimestamps(value: unknown): unknown {
  121. if (typeof value === 'string') {
  122. return value.replace(/("(?:createdAt|updatedAt|clearedAt)":)\d+/g, '$10')
  123. }
  124. if (Array.isArray(value)) return value.map(normalizeGoalTimestamps)
  125. if (value !== null && typeof value === 'object') {
  126. return Object.fromEntries(Object.entries(value).map(([key, item]) => [
  127. key,
  128. ['createdAt', 'updatedAt', 'clearedAt'].includes(key) && typeof item === 'number'
  129. ? 0
  130. : normalizeGoalTimestamps(item),
  131. ]))
  132. }
  133. return value
  134. }
  135. /** Normalize the stream's durable goal timestamps after the shared scrubbers. */
  136. function normalizeGoalStream(rawStdout: string, cwd: string): string {
  137. return parseJsonl(normalizeHeadlessStream(rawStdout, cwd))
  138. .map(record => JSON.stringify(normalizeGoalTimestamps(record)))
  139. .join('\n') + '\n'
  140. }
  141. async function scenarioPrompt(dir: string, label: string): Promise<string> {
  142. const input = JSON.parse(await readFile(join(dir, 'input.json'), 'utf8')) as {
  143. steps?: { op?: unknown; text?: unknown }[]
  144. }
  145. const prompt = input.steps?.find(step => step.op === 'prompt')?.text
  146. if (typeof prompt !== 'string') throw new Error(`${label} input has no prompt step`)
  147. return prompt
  148. }
  149. async function persistedLogs(cwd: string): Promise<PersistedLog[]> {
  150. const root = join(cwd, '.sessions')
  151. const files = (await readdir(root, { recursive: true })).filter(file => file.endsWith('.jsonl'))
  152. return Promise.all(files.map(async (file) => {
  153. const content = await readFile(join(root, file), 'utf8')
  154. return { content, header: parseJsonl(content)[0] ?? {} }
  155. }))
  156. }
  157. describe('headless stream-json snapshots', () => {
  158. it('prints the original Loader activation error through the assembled one-shot app', async () => {
  159. const result = await runLoaderSmoke({
  160. label: 'headless startup activation error snapshot',
  161. tempDirPrefix: 'headless-snapshot-startup-error-',
  162. binScript,
  163. configPath: startupFailureConfigPath,
  164. binArgs: ['--config', startupFailureConfigPath, '--output-format', 'stream-json', 'unreachable task'],
  165. tsconfigPath,
  166. expectedExitCode: 1,
  167. })
  168. expect(result.stdout).toBe('')
  169. await expect(result.stderr).toMatchFileSnapshot(startupFailureExpected)
  170. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  171. it('retries a transient provider failure through the one-shot app', async () => {
  172. const prompt = await scenarioPrompt(retryScenarioDir, 'provider-retry')
  173. const streamExpected = join(retryScenarioDir, 'stream-json.expected.jsonl')
  174. let runCwd = ''
  175. const result = await runLoaderSmoke({
  176. label: 'provider retry headless stream-json snapshot',
  177. tempDirPrefix: 'headless-snapshot-provider-retry-',
  178. binScript,
  179. configPath: retryConfigPath,
  180. binArgs: ['--config', retryConfigPath, '--output-format', 'stream-json', prompt],
  181. tsconfigPath,
  182. env: {
  183. DSH_SNAPSHOT: 'replay',
  184. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  185. },
  186. prepare: (cwd) => { runCwd = cwd },
  187. inspect: async (cwd) => {
  188. const logs = await persistedLogs(cwd)
  189. expect(logs).toHaveLength(1)
  190. const records = parseJsonl(logs[0]?.content ?? '')
  191. const retries = records.filter(record => record.type === 'llm/retry')
  192. expect(retries).toHaveLength(1)
  193. expect(retries[0]?.data).toMatchObject({
  194. provider: 'deepseek-official',
  195. mode: 'normal',
  196. policyKey: '["normal",1,["RATE_LIMIT"],1,1,0]',
  197. retry: 1,
  198. maxRetries: 1,
  199. delayMs: 1,
  200. failure: { message: 'snapshot transient failure', code: 'RATE_LIMIT', status: 429 },
  201. })
  202. },
  203. })
  204. expect(result.stderr).toBe('')
  205. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  206. if (refreshing) await writeFile(streamExpected, normalized)
  207. expect(normalized).toBe(await readFile(streamExpected, 'utf8'))
  208. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  209. it('logs actionable missing-credential guidance through the one-shot app', async () => {
  210. const streamExpected = join(credentialsScenarioDir, 'stream-json.expected.jsonl')
  211. let runCwd = ''
  212. const result = await runLoaderSmoke({
  213. label: 'missing-credential headless stream-json snapshot',
  214. tempDirPrefix: 'headless-snapshot-missing-credential-',
  215. binScript,
  216. configPath: credentialsConfigPath,
  217. binArgs: ['--config', credentialsConfigPath, '--output-format', 'stream-json', 'say pong'],
  218. tsconfigPath,
  219. env: {
  220. // First-run posture: no key in the environment, none under ./.dsh.
  221. DEEPSEEK_API_KEY: '',
  222. DEEPSEEK_BASE_URL: '',
  223. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  224. },
  225. prepare: (cwd) => { runCwd = cwd },
  226. })
  227. expect(result.stderr).toBe('')
  228. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  229. if (refreshing) await writeFile(streamExpected, normalized)
  230. expect(normalized).toBe(await readFile(streamExpected, 'utf8'))
  231. // The durable failure leads with the credential store — the path that
  232. // keeps the secret out of configuration files — and offers a literal key last.
  233. expect(normalized).toContain(
  234. 'store DEEPSEEK_API_KEY through the credentials service (the web Models page writes it),',
  235. )
  236. expect(normalized).toContain('as a last resort')
  237. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  238. it('logs the model default and a dynamic next-step reasoning effort', async () => {
  239. const result = await runLoaderSmoke({
  240. label: 'reasoning effort headless stream-json snapshot',
  241. tempDirPrefix: 'headless-snapshot-reasoning-effort-',
  242. binScript,
  243. configPath: reasoningConfigPath,
  244. binArgs: ['--config', reasoningConfigPath, '--output-format', 'stream-json', 'prove dynamic reasoning effort'],
  245. tsconfigPath,
  246. })
  247. expect(result.stderr).toBe('')
  248. const headers = parseJsonl(result.stdout)
  249. .map(record => record.event)
  250. .filter((event): event is JsonObject => (
  251. event !== null
  252. && typeof event === 'object'
  253. && !Array.isArray(event)
  254. && 'type' in event
  255. && event.type === 'request/header'
  256. ))
  257. .map((event) => {
  258. const data = event.data as JsonObject
  259. return (data.header as JsonObject).config
  260. })
  261. expect(headers).toMatchInlineSnapshot(`
  262. [
  263. {
  264. "model": "cli-mock",
  265. "provider": "cli-mock",
  266. "reasoningEffort": "high",
  267. },
  268. {
  269. "model": "cli-mock",
  270. "provider": "cli-mock",
  271. "reasoningEffort": "off",
  272. },
  273. ]
  274. `)
  275. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  276. it('logs and sends the DeepSeek adapter maxTokens default through the one-shot app', async () => {
  277. const server = await deepseekDefaultsServer()
  278. try {
  279. const result = await runLoaderSmoke({
  280. label: 'DeepSeek adapter defaults headless stream-json snapshot',
  281. tempDirPrefix: 'headless-snapshot-deepseek-defaults-',
  282. binScript,
  283. configPath: deepseekDefaultsConfigPath,
  284. binArgs: [
  285. '--config',
  286. deepseekDefaultsConfigPath,
  287. '--output-format',
  288. 'stream-json',
  289. 'return the deterministic response',
  290. ],
  291. tsconfigPath,
  292. env: {
  293. DSH_SNAPSHOT_BASE_URL: server.url,
  294. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  295. },
  296. })
  297. expect(result.stderr).toBe('')
  298. expect(server.requests).toHaveLength(1)
  299. expect(server.requests[0]?.max_tokens).toBe(256_000)
  300. const header = (parseJsonl(result.stdout)
  301. .map(record => record.event)
  302. .find((event): event is JsonObject => (
  303. event !== null
  304. && typeof event === 'object'
  305. && !Array.isArray(event)
  306. && 'type' in event
  307. && event.type === 'request/header'
  308. ))?.data as JsonObject | undefined)?.header as JsonObject | undefined
  309. expect(header?.config).toMatchInlineSnapshot(`
  310. {
  311. "maxTokens": 256000,
  312. "model": "deepseek-v4-flash",
  313. "provider": "deepseek-official",
  314. "reasoningEffort": "off",
  315. }
  316. `)
  317. expect(header?.adapterDefaults).toEqual({
  318. maxTokens: true,
  319. reasoningEffort: true,
  320. })
  321. } finally {
  322. await server.close()
  323. }
  324. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  325. it('replays the advanced toolchain through the one-shot app', async () => {
  326. const prompt = await scenarioPrompt(advancedScenarioDir, 'advanced-toolchain')
  327. const fixtureFiles = [
  328. advancedSessionFixture,
  329. join(advancedScenarioDir, 'session.1.jsonl'),
  330. join(advancedScenarioDir, 'session.2.jsonl'),
  331. ]
  332. let expectedSessions = await Promise.all(fixtureFiles.map(file => readFile(file, 'utf8')))
  333. let runCwd = ''
  334. const result = await runLoaderSmoke({
  335. label: 'advanced headless stream-json snapshot',
  336. tempDirPrefix: 'headless-snapshot-advanced-',
  337. binScript,
  338. configPath: advancedConfigPath,
  339. binArgs: ['--config', advancedConfigPath, '--output-format', 'stream-json', prompt],
  340. tsconfigPath,
  341. env: {
  342. DSH_SNAPSHOT: 'replay',
  343. DSH_SNAPSHOT_FILE: advancedSessionFixture,
  344. DSH_SNAPSHOT_CHILD_FILES: [
  345. join(advancedScenarioDir, 'session.1.jsonl'),
  346. join(advancedScenarioDir, 'session.2.jsonl'),
  347. ].join(delimiter),
  348. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  349. },
  350. prepare: (cwd) => { runCwd = cwd },
  351. inspect: async (cwd) => {
  352. const logs = await persistedLogs(cwd)
  353. expect(logs).toHaveLength(3)
  354. const parents = logs.filter(log => typeof log.header.parentSession !== 'string')
  355. expect(parents).toHaveLength(1)
  356. const parent = parents[0]
  357. if (parent === undefined) throw new Error('headless snapshot did not persist its main session')
  358. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  359. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  360. const actualSessions = [parent, ...children]
  361. const actualContext = contextFromLogs(actualSessions.map(log => log.content))
  362. if (refreshing) {
  363. const harvested = actualSessions.map((log): HarvestedLog => ({
  364. id: String(log.header.id),
  365. createdAt: Number(log.header.createdAt),
  366. ...typeof log.header.parentSession === 'string'
  367. ? { parentSession: log.header.parentSession }
  368. : {},
  369. content: log.content,
  370. }))
  371. const replacements = refreshFixtureReplacements(harvested, expectedSessions)
  372. expectedSessions = await Promise.all(actualSessions.map(async (actual, index) => {
  373. const existing = expectedSessions[index]
  374. const file = fixtureFiles[index]
  375. if (existing === undefined || file === undefined) {
  376. throw new Error(`headless snapshot has no fixture for persisted log ${index}`)
  377. }
  378. const stable = tokenizeSessionFixtureCwd(
  379. stabilizeRefreshLog(actual.content, existing, replacements, actualContext),
  380. )
  381. await writeFile(file, stable)
  382. return stable
  383. }))
  384. }
  385. const expectedContext = contextFromLogs(expectedSessions)
  386. for (const [index, actual] of actualSessions.entries()) {
  387. const expected = expectedSessions[index]
  388. if (expected === undefined) throw new Error(`headless snapshot has no fixture for persisted log ${index}`)
  389. expect(scrubRequestHeaders(normalizeSessionLog(actual.content, actualContext)))
  390. .toBe(scrubRequestHeaders(normalizeSessionLog(expected, expectedContext)))
  391. }
  392. },
  393. })
  394. expect(result.stderr).toBe('')
  395. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  396. if (refreshing) await writeFile(advancedStreamExpected, normalized)
  397. expect(normalized).toBe(await readFile(advancedStreamExpected, 'utf8'))
  398. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  399. it('replays persisted goal tools through the one-shot app', async () => {
  400. const prompt = await scenarioPrompt(goalScenarioDir, 'goal-tools')
  401. const streamExpected = join(goalScenarioDir, 'stream-json.expected.jsonl')
  402. let runCwd = ''
  403. const result = await runLoaderSmoke({
  404. label: 'goal tools headless stream-json snapshot',
  405. tempDirPrefix: 'headless-snapshot-goal-tools-',
  406. binScript,
  407. configPath: goalConfigPath,
  408. binArgs: ['--config', goalConfigPath, '--output-format', 'stream-json', prompt],
  409. tsconfigPath,
  410. env: {
  411. DSH_SNAPSHOT: 'replay',
  412. DSH_SNAPSHOT_FILE: join(goalScenarioDir, 'session.jsonl'),
  413. DSH_SNAPSHOT_OVERRIDE: join(goalScenarioDir, 'replay.override.json'),
  414. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  415. },
  416. prepare: (cwd) => { runCwd = cwd },
  417. inspect: async (cwd) => {
  418. const logs = await persistedLogs(cwd)
  419. expect(logs).toHaveLength(1)
  420. const records = parseJsonl(logs[0]?.content ?? '')
  421. const calls = records.filter(record => record.type === 'tool/call')
  422. .map(record => (record.data as JsonObject | undefined)?.name)
  423. expect(calls).toEqual(['update_goal', 'create_goal', 'get_goal'])
  424. const probeResult = records.find((record) => {
  425. if (record.type !== 'tool/result') return false
  426. const data = record.data as JsonObject | undefined
  427. const message = data?.message as JsonObject | undefined
  428. const source = message?.source as JsonObject | undefined
  429. return source?.callId === 'call_goal_probe'
  430. })
  431. const probeData = probeResult?.data as JsonObject | undefined
  432. const probeMessage = probeData?.message as JsonObject | undefined
  433. const probeContent = probeMessage?.content as JsonObject[] | undefined
  434. expect(probeContent?.[0]?.isError).toBe(true)
  435. expect((probeData?.error as JsonObject | undefined)?.code).toBe('GOAL_NOT_FOUND')
  436. const goalChanges = records.filter(record => record.type === 'goal/change')
  437. expect(goalChanges).toHaveLength(1)
  438. const data = goalChanges[0]?.data as JsonObject | undefined
  439. const goal = data?.goal as JsonObject | undefined
  440. expect(data?.operation).toBe('create')
  441. expect(goal).toMatchObject({
  442. objective: 'Finish the headless goal-tool snapshot proof',
  443. phase: 'active',
  444. maxGoalRounds: 7,
  445. })
  446. },
  447. })
  448. expect(result.stderr).toBe('')
  449. const normalized = normalizeGoalStream(result.stdout, runCwd)
  450. if (refreshing) await writeFile(streamExpected, normalized)
  451. expect(normalized).toBe(await readFile(streamExpected, 'utf8'))
  452. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  453. it('replays two fresh Ralph rounds through the one-shot app', async () => {
  454. const prompt = await scenarioPrompt(ralphScenarioDir, 'ralph-loop')
  455. const streamExpected = join(ralphScenarioDir, 'stream-json.expected.jsonl')
  456. let runCwd = ''
  457. const result = await runLoaderSmoke({
  458. label: 'Ralph loop headless stream-json snapshot',
  459. tempDirPrefix: 'headless-snapshot-ralph-loop-',
  460. binScript,
  461. configPath: ralphConfigPath,
  462. binArgs: ['--config', ralphConfigPath, '--output-format', 'stream-json', prompt],
  463. tsconfigPath,
  464. env: {
  465. DSH_SNAPSHOT: 'replay',
  466. DSH_SNAPSHOT_FILE: join(ralphScenarioDir, 'session.jsonl'),
  467. DSH_SNAPSHOT_OVERRIDE: join(ralphScenarioDir, 'replay.override.json'),
  468. DSH_SNAPSHOT_CHILD_FILES: [
  469. join(ralphScenarioDir, 'session.1.jsonl'),
  470. join(ralphScenarioDir, 'session.2.jsonl'),
  471. ].join(delimiter),
  472. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  473. },
  474. prepare: (cwd) => { runCwd = cwd },
  475. inspect: async (cwd) => {
  476. const logs = await persistedLogs(cwd)
  477. expect(logs).toHaveLength(3)
  478. const parent = logs.find(log => typeof log.header.parentSession !== 'string')
  479. if (parent === undefined) throw new Error('Ralph snapshot did not persist its parent session')
  480. const parentId = parent.header.id
  481. expect(typeof parentId).toBe('string')
  482. const children = logs.filter(log => typeof log.header.parentSession === 'string')
  483. .sort((left, right) => Number(left.header.createdAt) - Number(right.header.createdAt))
  484. expect(children).toHaveLength(2)
  485. expect(children.map(child => child.header.parentSession)).toEqual([parentId, parentId])
  486. expect(children.map(child => child.header.cwd)).toEqual([parent.header.cwd, parent.header.cwd])
  487. expect(parent.header.delegationDepth).toBe(0)
  488. expect(children.map(child => child.header.delegationDepth)).toEqual([1, 1])
  489. expect(children.map(child => child.header.seedLength)).toEqual([undefined, undefined])
  490. expect(new Set(children.map(child => child.header.id)).size).toBe(2)
  491. const parentRecords = parseJsonl(parent.content)
  492. const parentCalls = parentRecords.filter(record => record.type === 'tool/call')
  493. expect(parentCalls.map(record => (record.data as JsonObject | undefined)?.name)).toEqual(['ralph'])
  494. const parentResult = parentRecords.find(record => record.type === 'tool/result')
  495. const parentResultData = parentResult?.data as JsonObject | undefined
  496. const parentMessage = parentResultData?.message as JsonObject | undefined
  497. const parentContent = parentMessage?.content as JsonObject[] | undefined
  498. expect(parentContent?.[0]?.isError).toBe(false)
  499. expect(JSON.stringify(parentContent?.[0]?.content)).toContain('reported completion after 2 rounds')
  500. const childRecords = children.map(child => parseJsonl(child.content))
  501. const childPrompts = childRecords.map((records) => {
  502. const message = records.find(record => record.type === 'user/message')
  503. return JSON.stringify((message?.data as JsonObject | undefined)?.content)
  504. })
  505. expect(childPrompts[0]).toContain('Ralph round: 1 of 2.')
  506. expect(childPrompts[0]).toContain('(none — this is the first round)')
  507. expect(childPrompts[0]).not.toContain('ROUND_ONE_HANDOFF')
  508. expect(childPrompts[1]).toContain('Ralph round: 2 of 2.')
  509. expect(childPrompts[1]).toContain('ROUND_ONE_HANDOFF')
  510. for (const childPrompt of childPrompts) {
  511. expect(childPrompt).toContain('Prove two fresh Ralph rounds through the shipped headless app.')
  512. expect(childPrompt).not.toContain('Run a two-round fresh-agent Ralph loop')
  513. }
  514. for (const records of childRecords) {
  515. const calls = records.filter(record => record.type === 'tool/call')
  516. expect(calls.map(record => (record.data as JsonObject | undefined)?.name))
  517. .toEqual(['structured_output'])
  518. }
  519. },
  520. })
  521. expect(result.stderr).toBe('')
  522. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  523. if (refreshing) await writeFile(streamExpected, normalized)
  524. expect(normalized).toBe(await readFile(streamExpected, 'utf8'))
  525. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  526. it('replays persistent PTY tools through the one-shot app', async () => {
  527. const input = JSON.parse(await readFile(join(ptyScenarioDir, 'input.json'), 'utf8')) as {
  528. steps?: { op?: unknown; text?: unknown }[]
  529. }
  530. const prompt = input.steps?.find(step => step.op === 'prompt')?.text
  531. if (typeof prompt !== 'string') throw new Error('pty-tools input has no prompt step')
  532. let expectedSession = await readFile(ptySessionFixture, 'utf8')
  533. let runCwd = ''
  534. const result = await runLoaderSmoke({
  535. label: 'headless persistent PTY snapshot',
  536. tempDirPrefix: 'headless-snapshot-pty-',
  537. binScript,
  538. configPath: ptyConfigPath,
  539. binArgs: ['--config', ptyConfigPath, '--output-format', 'stream-json', prompt],
  540. tsconfigPath,
  541. env: {
  542. DSH_SNAPSHOT: 'replay',
  543. DSH_SNAPSHOT_FILE: ptySessionFixture,
  544. NODE_OPTIONS: [process.env.NODE_OPTIONS, '--disable-warning=ExperimentalWarning'].filter(Boolean).join(' '),
  545. },
  546. prepare: (cwd) => { runCwd = cwd },
  547. inspect: async (cwd) => {
  548. const logs = await persistedLogs(cwd)
  549. expect(logs).toHaveLength(1)
  550. const actual = logs[0]
  551. if (actual === undefined) throw new Error('headless PTY snapshot did not persist its session')
  552. const actualContext = contextFromLogs([actual.content])
  553. if (refreshing) {
  554. const harvested: HarvestedLog = {
  555. id: String(actual.header.id),
  556. createdAt: Number(actual.header.createdAt),
  557. content: actual.content,
  558. }
  559. const replacements = refreshFixtureReplacements([harvested], [expectedSession])
  560. expectedSession = tokenizeSessionFixtureCwd(
  561. stabilizeRefreshLog(actual.content, expectedSession, replacements, actualContext),
  562. )
  563. await writeFile(ptySessionFixture, expectedSession)
  564. }
  565. const expectedContext = contextFromLogs([expectedSession])
  566. expect(scrubRequestHeaders(normalizeSessionLog(actual.content, actualContext)))
  567. .toBe(scrubRequestHeaders(normalizeSessionLog(expectedSession, expectedContext)))
  568. },
  569. })
  570. expect(result.stderr).toBe('')
  571. const normalized = normalizeHeadlessStream(result.stdout, runCwd)
  572. if (refreshing) await writeFile(ptyStreamExpected, normalized)
  573. expect(normalized).toBe(await readFile(ptyStreamExpected, 'utf8'))
  574. }, LOADER_SMOKE_TEST_TIMEOUT_MS)
  575. })