normalize.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. import { describe, expect, it } from 'vitest'
  2. import {
  3. type NormalizeContext,
  4. normalizeSessionLog,
  5. normalizeStdout,
  6. scrubRequestHeaders,
  7. scrubSystemPrompts,
  8. scrubToolSchemas,
  9. } from '../src/normalize.ts'
  10. /**
  11. * Unit tests for the pure snapshot normalizers. Live as a *.spec.ts (runs in
  12. * the default unit gate) and import the normalizers directly.
  13. */
  14. const ctx: NormalizeContext = {
  15. sessionIds: ['11111111-2222-3333-4444-555555555555'],
  16. cwd: '/tmp/acp-snap-cwd-abc123',
  17. }
  18. describe('normalizeStdout', () => {
  19. it('rewrites JSON-RPC ids to a stable first-seen sequence', () => {
  20. const raw = [
  21. JSON.stringify({ jsonrpc: '2.0', id: 42, method: 'initialize' }),
  22. JSON.stringify({ jsonrpc: '2.0', id: 42, result: {} }),
  23. JSON.stringify({ jsonrpc: '2.0', id: 99, method: 'session/new' }),
  24. ].join('\n')
  25. const out = normalizeStdout(raw, ctx)
  26. expect(out).toContain('"id":1')
  27. expect(out).toContain('"id":2')
  28. expect(out).not.toContain('42')
  29. expect(out).not.toContain('99')
  30. })
  31. it('scrubs the cwd and session id anywhere they appear', () => {
  32. const raw = JSON.stringify({
  33. jsonrpc: '2.0', method: 'session/update',
  34. params: { sessionId: ctx.sessionIds[0], cwd: ctx.cwd, note: `at ${ctx.cwd}/x` },
  35. })
  36. const out = normalizeStdout(raw, ctx)
  37. expect(out).toContain('{{sessionId}}')
  38. expect(out).toContain('{{cwd}}')
  39. expect(out).not.toContain(ctx.cwd)
  40. expect(out).not.toContain(ctx.sessionIds[0] as string)
  41. })
  42. it('canonicalizes only cwd-rooted path separators', () => {
  43. const windowsCtx: NormalizeContext = {
  44. sessionIds: [],
  45. cwd: String.raw`C:\Users\runner\AppData\Local\Temp\acp-snapshot`,
  46. }
  47. const raw = JSON.stringify({
  48. jsonrpc: '2.0',
  49. method: 'session/update',
  50. params: {
  51. path: `${windowsCtx.cwd}\\nested\\proof.txt`,
  52. regex: String.raw`\d+\w+`,
  53. command: String.raw`printf "\\n"`,
  54. },
  55. })
  56. const frame = JSON.parse(normalizeStdout(raw, windowsCtx)) as {
  57. params: { path: string; regex: string; command: string }
  58. }
  59. expect(frame.params).toEqual({
  60. path: '{{cwd}}/nested/proof.txt',
  61. regex: String.raw`\d+\w+`,
  62. command: String.raw`printf "\\n"`,
  63. })
  64. })
  65. it('canonicalizes generated relative path fields and text markers without rewriting other text', () => {
  66. const raw = JSON.stringify({
  67. path: String.raw`nested\AGENTS.md`,
  68. content: String.raw`<path>.\nested\task.txt</path>
  69. Additional instructions from: nested\AGENTS.md`,
  70. regex: String.raw`\d+\w+`,
  71. })
  72. const frame = JSON.parse(normalizeStdout(raw, { sessionIds: [], cwd: '/unused' })) as {
  73. path: string
  74. content: string
  75. regex: string
  76. }
  77. expect(frame).toEqual({
  78. path: 'nested/AGENTS.md',
  79. content: '<path>./nested/task.txt</path>\nAdditional instructions from: nested/AGENTS.md',
  80. regex: String.raw`\d+\w+`,
  81. })
  82. })
  83. it('can preserve native cwd-rooted separators for a platform golden', () => {
  84. const windowsCtx: NormalizeContext = { sessionIds: [], cwd: String.raw`C:\work\snapshot` }
  85. const raw = JSON.stringify({ path: `${windowsCtx.cwd}\\nested\\proof.txt` })
  86. const frame = JSON.parse(normalizeStdout(raw, windowsCtx, { cwdPathMode: 'native' })) as { path: string }
  87. expect(frame.path).toBe(String.raw`{{cwd}}\nested\proof.txt`)
  88. })
  89. it('scrubs a stray UUID not in the known list', () => {
  90. const raw = JSON.stringify({ jsonrpc: '2.0', method: 'x', params: { id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' } })
  91. expect(normalizeStdout(raw, ctx)).toContain('{{sessionId}}')
  92. })
  93. it('leaves notification frames without an id untouched in id-space', () => {
  94. const raw = JSON.stringify({ jsonrpc: '2.0', method: 'session/update', params: {} })
  95. const out = normalizeStdout(raw, ctx)
  96. expect(out).not.toContain('"id"')
  97. })
  98. it('throws on a non-JSON stdout line (the purity check)', () => {
  99. const raw = `${JSON.stringify({ jsonrpc: '2.0', id: 1 })}\noops a log leaked\n`
  100. expect(() => normalizeStdout(raw, ctx)).toThrow()
  101. })
  102. it('ignores blank lines', () => {
  103. const raw = `\n${JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'm' })}\n\n`
  104. expect(() => normalizeStdout(raw, ctx)).not.toThrow()
  105. })
  106. })
  107. describe('normalizeSessionLog', () => {
  108. const header = (over: object) => JSON.stringify({ type: 'session', version: 0, id: 's', createdAt: 123, ...over })
  109. const event = (over: object) => JSON.stringify({ type: 'turn/start', seq: 1, time: 999, data: { turn: 1 }, ...over })
  110. it('zeroes the header createdAt', () => {
  111. const out = normalizeSessionLog(`${header({})}\n`, ctx)
  112. expect(out).toContain('"createdAt":0')
  113. expect(out).not.toContain('123')
  114. })
  115. it('zeroes each event time but keeps seq', () => {
  116. const out = normalizeSessionLog(`${header({})}\n${event({ seq: 7, time: 999 })}\n`, ctx)
  117. expect(out).toContain('"time":0')
  118. expect(out).toContain('"seq":7') // seq is deterministic — NOT scrubbed
  119. expect(out).not.toContain('999')
  120. })
  121. it('scrubs cwd and session id deep inside event data', () => {
  122. const ev = JSON.stringify({
  123. type: 'tool/result', seq: 2, time: 5,
  124. data: { content: [{ type: 'text', text: `wrote ${ctx.cwd}/proof.txt` }] },
  125. })
  126. const out = normalizeSessionLog(`${header({ cwd: ctx.cwd })}\n${ev}\n`, ctx)
  127. expect(out).toContain('{{cwd}}')
  128. expect(out).not.toContain(ctx.cwd)
  129. })
  130. it('scrubs random local spill paths under the snapshot cwd', () => {
  131. const ev = JSON.stringify({
  132. type: 'tool/result', seq: 2, time: 5,
  133. data: {
  134. content: [{
  135. type: 'text',
  136. text: `Full formatted result stored at: ${ctx.cwd}/.spill/session-c22bc3f1d2af/8a7b6c5d4e3f-bash.txt. Use read with offset/limit, or grep this path to search within it.`,
  137. }],
  138. },
  139. })
  140. const out = normalizeSessionLog(`${header({ cwd: ctx.cwd })}\n${ev}\n`, ctx)
  141. expect(out).toContain('{{spillLocator:bash.txt}}')
  142. expect(out).not.toContain('session-c22bc3f1d2af')
  143. expect(out).not.toContain('8a7b6c5d4e3f')
  144. })
  145. it('scrubs macOS /private aliases for local spill paths', () => {
  146. const ev = JSON.stringify({
  147. type: 'tool/result', seq: 2, time: 5,
  148. data: {
  149. content: [{
  150. type: 'text',
  151. text: `Full formatted result stored at: /private${ctx.cwd}/.spill/session-c22bc3f1d2af/8a7b6c5d4e3f-bash.txt. Use read with offset/limit, or grep this path to search within it.`,
  152. }],
  153. },
  154. })
  155. const out = normalizeSessionLog(`${header({ cwd: ctx.cwd })}\n${ev}\n`, ctx)
  156. expect(out).toContain('{{spillLocator:bash.txt}}')
  157. expect(out).not.toContain('/private{{spillLocator')
  158. })
  159. it('scrubs fixed snapshot spill paths', () => {
  160. const ev = JSON.stringify({
  161. type: 'tool/result', seq: 2, time: 5,
  162. data: {
  163. content: [{
  164. type: 'text',
  165. text: 'Full formatted result stored at: /tmp/dsh-acp-snapshot-spill/session-c22bc3f1d2af/8a7b6c5d4e3f-bash.txt. Use read with offset/limit, or grep this path to search within it.',
  166. }],
  167. },
  168. })
  169. const out = normalizeSessionLog(`${header({ cwd: ctx.cwd })}\n${ev}\n`, ctx)
  170. expect(out).toContain('{{spillLocator:bash.txt}}')
  171. expect(out).not.toContain('/tmp/dsh-acp-snapshot-spill')
  172. })
  173. it('scrubs fixed snapshot spill paths with Windows drive and separators', () => {
  174. const ev = JSON.stringify({
  175. type: 'tool/result', seq: 2, time: 5,
  176. data: {
  177. content: [{
  178. type: 'text',
  179. text: String.raw`Full formatted result stored at: C:\t\dsh-acp-snapshot-spill\session-c22bc3f1d2af\8a7b6c5d4e3f-bash.txt. Use read with offset/limit, or grep this path to search within it.`,
  180. }],
  181. },
  182. })
  183. const out = normalizeSessionLog(`${header({ cwd: ctx.cwd })}\n${ev}\n`, ctx)
  184. expect(out).toContain('{{spillLocator:bash.txt}}')
  185. expect(out).not.toContain('C:\\t\\dsh-acp-snapshot-spill')
  186. })
  187. it('shares cwd-rooted path handling with stdout normalization', () => {
  188. const windowsCtx: NormalizeContext = { sessionIds: [], cwd: String.raw`C:\work\snapshot` }
  189. const ev = JSON.stringify({
  190. type: 'tool/result', seq: 2, time: 5,
  191. data: { path: `${windowsCtx.cwd}\\nested\\proof.txt` },
  192. })
  193. expect(normalizeSessionLog(`${header({ cwd: windowsCtx.cwd })}\n${ev}\n`, windowsCtx))
  194. .toContain('{{cwd}}/nested/proof.txt')
  195. expect(normalizeSessionLog(`${header({ cwd: windowsCtx.cwd })}\n${ev}\n`, windowsCtx, { cwdPathMode: 'native' }))
  196. .toContain(String.raw`{{cwd}}\\nested\\proof.txt`)
  197. })
  198. it('scrubs the session id in the header', () => {
  199. const out = normalizeSessionLog(`${header({ id: ctx.sessionIds[0] })}\n`, ctx)
  200. expect(out).toContain('{{sessionId}}')
  201. })
  202. it('zeroes a hook/result durationMs (run-to-run noise) but keeps its decision', () => {
  203. const ev = JSON.stringify({
  204. type: 'hook/result', seq: 2, time: 5,
  205. data: { turn: 1, point: 'UserPromptSubmit', handlerId: 'h', decision: 'block', exitCode: 2, durationMs: 37 },
  206. })
  207. const out = normalizeSessionLog(`${header({})}\n${ev}\n`, ctx)
  208. expect(out).toContain('"durationMs":0')
  209. expect(out).not.toContain('37')
  210. expect(out).toContain('"decision":"block"') // the decision is the behavior — kept
  211. })
  212. it('leaves a non-hook event durationMs untouched (only hook/result is scrubbed)', () => {
  213. const ev = JSON.stringify({ type: 'tool/result', seq: 2, time: 5, data: { durationMs: 88 } })
  214. const out = normalizeSessionLog(`${header({})}\n${ev}\n`, ctx)
  215. expect(out).toContain('"durationMs":88')
  216. })
  217. it('tolerates records missing the volatile fields it would zero', () => {
  218. const bareHeader = JSON.stringify({ type: 'session', id: 's' })
  219. const timeless = JSON.stringify({ type: 'note', seq: 1 })
  220. const bareHook = JSON.stringify({ type: 'hook/result', seq: 2, time: 5, data: { decision: 'allow' } })
  221. const nullDataHook = JSON.stringify({ type: 'hook/result', seq: 3, time: 6, data: null })
  222. const out = normalizeSessionLog(`${bareHeader}\n${timeless}\n${bareHook}\n${nullDataHook}\n`, ctx)
  223. expect(out).toContain('"type":"note","seq":1')
  224. expect(out).toContain('"decision":"allow"')
  225. expect(out).not.toContain('durationMs')
  226. })
  227. })
  228. describe('scrubRequestHeaders', () => {
  229. const headerLine = JSON.stringify({ type: 'session', version: 0, id: 's', createdAt: 1, cwd: '/w' })
  230. const headerEvent = (header: object) =>
  231. JSON.stringify({ type: 'request/header', seq: 3, time: 9, data: { header, reason: 'initial' } })
  232. it('replaces header system and tools with tokens, keeping config and reason', () => {
  233. const ev = headerEvent({
  234. config: { model: 'm' },
  235. system: 'You are an agent.\nBe brief.',
  236. tools: [{ name: 'read', description: 'Read a file.', parameters: { type: 'object' } }],
  237. })
  238. const out = scrubRequestHeaders(`${headerLine}\n${ev}\n`)
  239. expect(out).toContain('"system":"{{system}}"')
  240. expect(out).toContain('"tools":"{{tools}}"')
  241. expect(out).toContain('"config":{"model":"m"}')
  242. expect(out).toContain('"reason":"initial"')
  243. expect(out).not.toContain('You are an agent')
  244. expect(out).not.toContain('Read a file')
  245. })
  246. it('keeps an absent system/tools absent (presence is behavior)', () => {
  247. const out = scrubRequestHeaders(`${headerLine}\n${headerEvent({ config: { model: 'm' } })}\n`)
  248. expect(out).not.toContain('{{system}}')
  249. expect(out).not.toContain('{{tools}}')
  250. })
  251. it('scrubs a header carrying only one of system/tools, leaving the other absent', () => {
  252. const systemOnly = scrubRequestHeaders(`${headerLine}\n${headerEvent({ system: 'secret prompt' })}\n`)
  253. expect(systemOnly).toContain('"system":"{{system}}"')
  254. expect(systemOnly).not.toContain('{{tools}}')
  255. const toolsOnly = scrubRequestHeaders(`${headerLine}\n${headerEvent({ tools: [{ name: 't' }] })}\n`)
  256. expect(toolsOnly).toContain('"tools":"{{tools}}"')
  257. expect(toolsOnly).not.toContain('{{system}}')
  258. })
  259. it('scrubs the header session prefix to one token per message, keeping the count', () => {
  260. const ev = headerEvent({
  261. config: { model: 'm' },
  262. messagePrefix: [
  263. { role: 'user', content: [{ type: 'text', text: 'workspace AGENTS digest' }] },
  264. { role: 'user', content: [{ type: 'text', text: 'skills catalog' }] },
  265. ],
  266. })
  267. const out = scrubRequestHeaders(`${headerLine}\n${ev}\n`)
  268. expect(out).toContain('"messagePrefix":["{{messagePrefix}}","{{messagePrefix}}"]')
  269. expect(out).not.toContain('AGENTS digest')
  270. expect(out).not.toContain('skills catalog')
  271. // Absence stays absent — a prefix-less header gains no token…
  272. expect(scrubRequestHeaders(`${headerLine}\n${headerEvent({ system: 's' })}\n`)).not.toContain('{{messagePrefix}}')
  273. // …and a non-array shape passes through untouched.
  274. const odd = JSON.stringify({ type: 'request/header', seq: 4, time: 9, data: { header: { config: { model: 'm' }, messagePrefix: 'weird' }, reason: 'initial' } })
  275. expect(scrubRequestHeaders(`${headerLine}\n${odd}\n`)).toContain('"messagePrefix":"weird"')
  276. })
  277. it('leaves malformed headers with no scrubbable payload byte-identical', () => {
  278. const headerless = JSON.stringify({ type: 'request/header', seq: 10, time: 9, data: { reason: 'initial' } })
  279. const nullData = JSON.stringify({ type: 'request/header', seq: 11, time: 9, data: null })
  280. const raw = `${headerLine}\n${headerless}\n${nullData}\n`
  281. expect(scrubRequestHeaders(raw)).toBe(raw)
  282. })
  283. it('passes every other line through byte-for-byte and is idempotent', () => {
  284. const other = JSON.stringify({ type: 'assistant/chunk', seq: 4, time: 9, data: { turn: 1, step: 1, chunk: { type: 'text-delta', index: 0, text: 'hi' } } })
  285. const raw = `${headerLine}\n${headerEvent({ config: { model: 'm' }, system: 's', tools: [] })}\n${other}\n`
  286. const once = scrubRequestHeaders(raw)
  287. expect(once.split('\n')[0]).toBe(headerLine)
  288. expect(once.split('\n')[2]).toBe(other)
  289. expect(scrubRequestHeaders(once)).toBe(once)
  290. })
  291. })
  292. describe('scrubSystemPrompts', () => {
  293. it('scrubs only system prompt payloads while keeping tools and prefixes verbatim', () => {
  294. const header = JSON.stringify({
  295. type: 'request/header', seq: 1, time: 2,
  296. data: {
  297. header: {
  298. system: 'full prompt',
  299. tools: [{ name: 'read', description: 'full schema' }],
  300. messagePrefix: [{ role: 'user', content: [{ type: 'text', text: 'full prefix' }] }],
  301. },
  302. reason: 'initial',
  303. },
  304. })
  305. const changed = JSON.stringify({
  306. type: 'request/header', seq: 2, time: 3,
  307. data: {
  308. header: {
  309. system: 'new prompt',
  310. tools: [{ name: 'read', description: 'changed schema' }],
  311. messagePrefix: [{ role: 'user', content: [{ type: 'text', text: 'changed prefix' }] }],
  312. },
  313. reason: 'change',
  314. },
  315. })
  316. const toolsOnly = JSON.stringify({
  317. type: 'request/header', seq: 3, time: 4,
  318. data: { header: { tools: [{ name: 'read', description: 'schema only' }] }, reason: 'resume' },
  319. })
  320. const out = scrubSystemPrompts(`${header}\n${changed}\n${toolsOnly}\n`)
  321. expect(out).toContain('"system":"{{system}}"')
  322. expect(out).not.toContain('full prompt')
  323. expect(out).not.toContain('new prompt')
  324. expect(out).toContain('full schema')
  325. expect(out).toContain('full prefix')
  326. expect(out).toContain('changed schema')
  327. expect(out).toContain('changed prefix')
  328. expect(out.split('\n')[2]).toBe(toolsOnly)
  329. expect(scrubSystemPrompts(out)).toBe(out)
  330. })
  331. })
  332. describe('scrubToolSchemas', () => {
  333. it('scrubs only tool-schema payloads while keeping prompts and prefixes verbatim', () => {
  334. const header = JSON.stringify({
  335. type: 'request/header', seq: 1, time: 2,
  336. data: {
  337. header: {
  338. system: 'full prompt',
  339. tools: [{ name: 'read', description: 'full schema', parameters: { type: 'object' } }],
  340. messagePrefix: [{ role: 'user', content: [{ type: 'text', text: 'full prefix' }] }],
  341. },
  342. reason: 'initial',
  343. },
  344. })
  345. const changed = JSON.stringify({
  346. type: 'request/header', seq: 2, time: 3,
  347. data: {
  348. header: {
  349. system: 'new prompt',
  350. tools: [{ name: 'grep', description: 'new schema' }],
  351. messagePrefix: [{ role: 'user', content: [{ type: 'text', text: 'changed prefix' }] }],
  352. },
  353. reason: 'change',
  354. },
  355. })
  356. const systemOnly = JSON.stringify({
  357. type: 'request/header', seq: 3, time: 4,
  358. data: { header: { system: 'prompt only' }, reason: 'resume' },
  359. })
  360. const out = scrubToolSchemas(`${header}\n${changed}\n${systemOnly}\n`)
  361. expect(out.match(/"tools":"{{tools}}"/g)).toHaveLength(2)
  362. expect(out).not.toContain('full schema')
  363. expect(out).not.toContain('new schema')
  364. expect(out).toContain('full prompt')
  365. expect(out).toContain('new prompt')
  366. expect(out).toContain('full prefix')
  367. expect(out).toContain('changed prefix')
  368. expect(out.split('\n')[2]).toBe(systemOnly)
  369. expect(scrubToolSchemas(out)).toBe(out)
  370. })
  371. })