acp.snapshot.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. import { fileURLToPath } from 'node:url'
  2. import { readFileSync } from 'node:fs'
  3. import { dirname, join } from 'node:path'
  4. import { homedir } from 'node:os'
  5. import { expect, it } from 'vitest'
  6. import { defineAcpSnapshotSuite, type Scenario, type SnapshotSuiteOptions } from '@deepseek-ai/dsh-acp-snapshot'
  7. import { decodeStorageRecord } from '@deepseek-ai/dsh-session'
  8. /**
  9. * The acp-agent example's snapshot suite: the scenario table for
  10. * `dsh-acp-snapshot`'s suite factory, which owns every compare/guard mechanic
  11. * (expected-output + re-persisted-log diffs, record/refresh write-back, the pinned-header
  12. * uniformity guard, the fixture guards). Fixtures live under `snapshots/<name>/`;
  13. * `pnpm run test:snapshot:record` re-records model transcripts against the real
  14. * API; `pnpm run test:snapshot:refresh` rewrites current replay expected outputs keyless.
  15. * See the package README (packages/support/acp-snapshot) and the snapshot Agent Note,
  16. * .agents/notes/implemented/testing/2026-06-19-acp-snapshot-tests.md.
  17. */
  18. // The dsh-acp-demo bin (the demo:acp entry), this example's cordis.yml, and
  19. // the repo-root tsconfig (four levels up from examples/acp-agent/tests) — all
  20. // ABSOLUTE: the subprocess cwd is a temp dir outside the repo.
  21. const AGENT = {
  22. binScript: fileURLToPath(new URL('../../../packages/examples/acp-demo/src/bin.ts', import.meta.url)),
  23. configPath: fileURLToPath(new URL('../cordis.yml', import.meta.url)),
  24. tsconfigPath: fileURLToPath(new URL('../../../tsconfig.json', import.meta.url)),
  25. }
  26. // The Code Mode overlay configs (include-patched variants of cordis.yml; the
  27. // replay swap resolves each one's sibling `*cordis.snapshot.yml`).
  28. const CODE_MODE_CONFIG = fileURLToPath(new URL('../code-mode.cordis.yml', import.meta.url))
  29. const CODE_MODE_WORKSPACE_CONTEXT_CONFIG = fileURLToPath(new URL('../code-mode-workspace-context.cordis.yml', import.meta.url))
  30. const BOTH_MODE_CONFIG = fileURLToPath(new URL('../both-mode.cordis.yml', import.meta.url))
  31. const WORKSPACE_CONTEXT_CONFIG = fileURLToPath(new URL('../workspace-context.cordis.yml', import.meta.url))
  32. const ADVANCED_CONFIG = fileURLToPath(new URL('../advanced.cordis.yml', import.meta.url))
  33. const FS_CONFIG = fileURLToPath(new URL('../fs.cordis.yml', import.meta.url))
  34. const SESSION_QUERY_CONFIG = fileURLToPath(new URL('../session-query.cordis.yml', import.meta.url))
  35. const PTY_CONFIG = fileURLToPath(new URL('../pty.cordis.yml', import.meta.url))
  36. const DEPTH_TWO_CONFIG = fileURLToPath(new URL('../depth-two.cordis.yml', import.meta.url))
  37. const SESSION_SANDBOX_ROOT_CONFIG = fileURLToPath(new URL('../session-sandbox-root.cordis.yml', import.meta.url))
  38. const RETRY_CONFIG = fileURLToPath(new URL('../retry.cordis.yml', import.meta.url))
  39. const LSP_CONFIG = fileURLToPath(new URL('./lsp.cordis.yml', import.meta.url))
  40. const WEB_CONFIG = fileURLToPath(new URL('../web.cordis.yml', import.meta.url))
  41. const SNAPSHOTS_DIR = join(dirname(fileURLToPath(import.meta.url)), 'snapshots')
  42. const PACKED_CHUNKS_SOURCE = 'hook-cc-pretool-deny'
  43. // FIXME: Migrate backend-oriented scenarios to the headless stream-json suite;
  44. // this ACP suite should eventually retain only automation-protocol contracts.
  45. function fixtureRecords(name: string): unknown[] {
  46. return readFileSync(join(SNAPSHOTS_DIR, name, 'session.jsonl'), 'utf8')
  47. .trimEnd()
  48. .split('\n')
  49. .map(line => JSON.parse(line) as unknown)
  50. }
  51. function snapshotModeFromEnv(value: string | undefined): SnapshotSuiteOptions['mode'] {
  52. switch (value) {
  53. case undefined:
  54. case '':
  55. case 'replay':
  56. return 'replay'
  57. case 'record':
  58. return 'record'
  59. case 'refresh':
  60. return 'refresh'
  61. default:
  62. throw new Error(`unknown DSH_SNAPSHOT mode: ${value}`)
  63. }
  64. }
  65. const SCENARIOS: Scenario[] = [
  66. { name: 'handshake', hasModelTurn: false, recorded: false },
  67. { name: 'reject-extra-dirs', hasModelTurn: false, recorded: false },
  68. // text-turn is the pinned-header scenario: the minimal single text turn.
  69. // Its prompt and tool-schema sidecars pin the composed header.
  70. { name: 'text-turn', hasModelTurn: true, recorded: true, pinsHeader: true },
  71. { name: 'tool-call-turn', hasModelTurn: true, recorded: true },
  72. // Authored from the real PACKED_CHUNKS_SOURCE recording under the ordinary
  73. // app composition. The contract below pins decoded equality and all three
  74. // row kinds; replay additionally proves the assembled app re-packs identically.
  75. { name: 'packed-chunks', hasModelTurn: true, recorded: false },
  76. // The fs overlay only adds the spill stack (the sandboxed filesystem tools
  77. // live in the base tree), so these scenarios share the default header class.
  78. {
  79. name: 'parallel-tool-calls',
  80. hasModelTurn: true,
  81. recorded: false,
  82. configPath: FS_CONFIG,
  83. },
  84. { name: 'bash-spill', hasModelTurn: true, recorded: false, configPath: FS_CONFIG },
  85. {
  86. name: 'session-query-spill',
  87. hasModelTurn: true,
  88. recorded: false,
  89. pinsHeader: true,
  90. headerClass: 'session-query',
  91. configPath: SESSION_QUERY_CONFIG,
  92. posixOnly: true,
  93. },
  94. {
  95. name: 'pty-tools',
  96. hasModelTurn: true,
  97. recorded: false,
  98. pinsHeader: true,
  99. headerClass: 'pty',
  100. configPath: PTY_CONFIG,
  101. },
  102. { name: 'bash-tool-turn', hasModelTurn: true, recorded: true },
  103. { name: 'todo-write', hasModelTurn: true, recorded: true },
  104. { name: 'skill-load', hasModelTurn: true, recorded: false, pinsHeader: true, headerClass: 'skill' },
  105. { name: 'lsp-definition', hasModelTurn: true, recorded: false, pinsHeader: true, headerClass: 'lsp', configPath: LSP_CONFIG },
  106. // web_fetch markdown rendering end to end: the overlay's loopback fixture
  107. // server supplies deterministic HTML (entities, a GFM table, nesting), the
  108. // REAL local fetch provider retrieves it, and the tool result pins the
  109. // turndown conversion. The fetched URL (fixed port) is part of the recorded
  110. // transcript; replay re-executes the real fetch against the same fixture.
  111. { name: 'web-fetch', hasModelTurn: true, recorded: true, pinsHeader: true, headerClass: 'web', configPath: WEB_CONFIG },
  112. {
  113. name: 'workspace-edit',
  114. hasModelTurn: true,
  115. recorded: true,
  116. },
  117. { name: 'fs-read', hasModelTurn: true, recorded: true },
  118. { name: 'fs-write', hasModelTurn: true, recorded: true },
  119. { name: 'fs-edit', hasModelTurn: true, recorded: true },
  120. { name: 'fs-write-overwrite', hasModelTurn: true, recorded: true },
  121. { name: 'fs-read-window', hasModelTurn: true, recorded: true },
  122. { name: 'fs-policy-reject', hasModelTurn: true, recorded: true },
  123. { name: 'multi-turn', hasModelTurn: true, recorded: true },
  124. { name: 'error-finish', hasModelTurn: true, recorded: false, overridden: true },
  125. // Keyless, authored (like error-finish): a live provider cannot be coaxed
  126. // into a degenerate empty completion, so the fixture scripts the adapters'
  127. // EMPTY_RESPONSE error finish in turn 1 followed by the recovered reply
  128. // in retry turn 2, proving the default retry policy end to end: the durable
  129. // llm/retry event, no ACP output for the discarded attempt, the recovered
  130. // reply, and a clean completed retry turn. Its overlay only pins a deterministic
  131. // 1 ms zero-jitter delay, so it shares the default header class.
  132. { name: 'empty-response-retry', hasModelTurn: true, recorded: false, configPath: RETRY_CONFIG },
  133. // Keyless, authored (like error-finish/cancel): deterministically forcing a
  134. // LIVE model to repeat one call three times is not a stable recording, so
  135. // the fixture scripts five identical todo_write calls and pins BOTH reminder
  136. // tiers (gentle at 3, detailed at 5) as injected user/message in transcript and log.
  137. { name: 'repeat-tool-guard', hasModelTurn: true, recorded: false },
  138. // Authored replay: a root AGENTS.md pins the session prefix, then a read in
  139. // nested/ discovers its narrower AGENTS.md as a raw, metadata-bearing
  140. // injected user/message. Both AGENTS.md fixtures are symlinks to a sibling
  141. // AGENTS.canonical.md, so this scenario also guards that discovery follows a
  142. // symlinked instruction file to its target's content. The scenario-specific
  143. // config keeps home/root discovery hermetic, and the resulting prefix needs
  144. // its own pinned header class.
  145. {
  146. name: 'workspace-context',
  147. hasModelTurn: true,
  148. recorded: false,
  149. overridden: true,
  150. pinsHeader: true,
  151. headerClass: 'workspace-context',
  152. configPath: WORKSPACE_CONTEXT_CONFIG,
  153. },
  154. { name: 'cancel', hasModelTurn: true, recorded: false, overridden: true },
  155. // Cancelling a live bash call relies on POSIX process-group termination;
  156. // Windows bash process-tree kill is deferred with the Bash execution domain.
  157. { name: 'cancel-tool-calls', hasModelTurn: true, recorded: false, overridden: true, posixOnly: true },
  158. { name: 'subagent-spawn', hasModelTurn: true, recorded: true },
  159. { name: 'subagent-multi', hasModelTurn: true, recorded: true },
  160. { name: 'subagent-fork', hasModelTurn: true, recorded: true },
  161. { name: 'subagent-mixed', hasModelTurn: true, recorded: true },
  162. {
  163. name: 'subagent-depth-two-rejection',
  164. hasModelTurn: true,
  165. recorded: false,
  166. overridden: true,
  167. configPath: DEPTH_TWO_CONFIG,
  168. },
  169. // The workflow tool: the model writes a one-child orchestration script; the
  170. // child runs as a spawn subagent under the worker-thread engine (its session is the
  171. // child fixture), and the tool result carries the script's return value.
  172. { name: 'workflow-run', hasModelTurn: true, recorded: true },
  173. // Authored counterpart to the packaged Python SDK snapshot: mount a live marker, inspect it
  174. // through Code Mode, run direct and workflow children, then unmount it. The extra Code Mode and
  175. // Cordis plugins require their own request-header pin; the fixture tests deterministic composition.
  176. {
  177. name: 'advanced-toolchain',
  178. hasModelTurn: true,
  179. recorded: false,
  180. pinsHeader: true,
  181. headerClass: 'advanced',
  182. configPath: ADVANCED_CONFIG,
  183. },
  184. {
  185. name: 'cordis-inspect-jsdoc',
  186. hasModelTurn: true,
  187. recorded: false,
  188. headerClass: 'advanced',
  189. configPath: ADVANCED_CONFIG,
  190. },
  191. // Prompt-submit blocks are authored keylessly. Admission rejects before a
  192. // turn opens, so only the ACP stop reason is observable and no log is harvested.
  193. { name: 'hook-cc-promptsubmit-block', hasModelTurn: false, recorded: false },
  194. { name: 'hook-codex-promptsubmit-block', hasModelTurn: false, recorded: false },
  195. // The mid-turn seams fire during a real model turn, so each is recorded with its hook active
  196. // (the model's reaction to a deny/block/force-continue is part of the captured transcript).
  197. // SessionStart/SubagentStart are excluded because detached injection races log
  198. // order; SubagentStop writes no transcript, so an expected output could not prove it ran.
  199. // Unit tests cover those points; the hook-snapshot-matrix Agent Note owns the rationale.
  200. { name: 'hook-cc-promptsubmit-context', hasModelTurn: true, recorded: true },
  201. { name: 'hook-cc-pretool-deny', hasModelTurn: true, recorded: true },
  202. { name: 'hook-cc-pretool-ask', hasModelTurn: true, recorded: true },
  203. { name: 'hook-cc-posttool-block', hasModelTurn: true, recorded: true },
  204. { name: 'hook-cc-posttool-context', hasModelTurn: true, recorded: true },
  205. { name: 'hook-cc-stop-continue', hasModelTurn: true, recorded: true },
  206. { name: 'hook-codex-promptsubmit-context', hasModelTurn: true, recorded: true },
  207. { name: 'hook-codex-pretool-block', hasModelTurn: true, recorded: true },
  208. { name: 'hook-codex-posttool-block', hasModelTurn: true, recorded: true },
  209. { name: 'hook-codex-posttool-context', hasModelTurn: true, recorded: true },
  210. { name: 'hook-codex-stop-continue', hasModelTurn: true, recorded: true },
  211. // Code Mode: the registry in `mode: code` — the wire tool list collapses to [run_code], the
  212. // tools:sdk section rides in the prompt, and the program's tool calls land as
  213. // tool/code-dispatch events. Each overlay composes and pins its own header class.
  214. { name: 'code-mode-turn', hasModelTurn: true, recorded: true, pinsHeader: true, headerClass: 'code', configPath: CODE_MODE_CONFIG },
  215. // A nested fs dispatch inside run_code discovers workspace instructions. The
  216. // injected user/message must follow the outer result while retaining workspace
  217. // provenance, which proves Code Mode carries deferred tool context end to end.
  218. {
  219. name: 'code-mode-workspace-context',
  220. hasModelTurn: true,
  221. recorded: true,
  222. pinsHeader: true,
  223. headerClass: 'code-workspace-context',
  224. configPath: CODE_MODE_WORKSPACE_CONTEXT_CONFIG,
  225. },
  226. { name: 'both-mode-turn', hasModelTurn: true, recorded: true, pinsHeader: true, headerClass: 'both', configPath: BOTH_MODE_CONFIG },
  227. // Machine permission scenarios use an explicit deployment policy; there is
  228. // no session-scoped UI picker on the automation protocol.
  229. {
  230. name: 'escalation-approved',
  231. hasModelTurn: true,
  232. recorded: true,
  233. pinsHeader: true,
  234. headerClass: 'sandbox',
  235. env: { DSH_PERMISSION_MODE: 'workspace-write' },
  236. },
  237. {
  238. name: 'escalation-rejected',
  239. hasModelTurn: true,
  240. recorded: true,
  241. headerClass: 'sandbox',
  242. env: { DSH_PERMISSION_MODE: 'workspace-write' },
  243. },
  244. {
  245. name: 'fs-escalation-approved',
  246. hasModelTurn: true,
  247. recorded: true,
  248. headerClass: 'sandbox',
  249. env: { DSH_PERMISSION_MODE: 'workspace-write' },
  250. },
  251. // Unlike ordinary snapshots, this session cwd is outside the platform temp
  252. // roots that workspace-write always grants. The overlay points the
  253. // deployment fallback at /tmp, so a successful relative write proves the
  254. // assembled app replaced that process-level fallback with SessionHeader.cwd.
  255. {
  256. name: 'session-sandbox-root',
  257. hasModelTurn: true,
  258. recorded: false,
  259. overridden: true,
  260. headerClass: 'sandbox',
  261. configPath: SESSION_SANDBOX_ROOT_CONFIG,
  262. env: { DSH_PERMISSION_MODE: 'workspace-write' },
  263. workspaceParent: homedir(),
  264. },
  265. ]
  266. defineAcpSnapshotSuite({
  267. agent: AGENT,
  268. snapshotsDir: SNAPSHOTS_DIR,
  269. scenarios: SCENARIOS,
  270. mode: snapshotModeFromEnv(process.env.DSH_SNAPSHOT),
  271. })
  272. it('packed ACP fixture retains every chunk row kind without changing the logical session', () => {
  273. const source = fixtureRecords(PACKED_CHUNKS_SOURCE)
  274. const packed = fixtureRecords('packed-chunks')
  275. const rowTypes = packed.flatMap((record) => {
  276. if (record === null || typeof record !== 'object') return []
  277. const type = (record as { type?: unknown }).type
  278. return type === 'text-chunks' || type === 'reasoning-chunks' || type === 'tool-call-chunks' ? [type] : []
  279. })
  280. expect([...new Set(rowTypes)].sort()).toStrictEqual(['reasoning-chunks', 'text-chunks', 'tool-call-chunks'])
  281. const logicalRecords = (records: readonly unknown[]): unknown[] => [
  282. records[0],
  283. ...records.slice(1).flatMap(record => decodeStorageRecord(record)),
  284. ]
  285. expect(logicalRecords(packed)).toStrictEqual(logicalRecords(source))
  286. })