Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

file-diff.test.ts

438 lines15.3 KB

1import { describe, expect, it } from 'vitest'
2import { buildFileHookEvent } from '../src/file-diff'
3import { captureLogger } from './fakes'
4import type { SandboxHandle } from '../src/contracts'
5​
6function fakeHandle(
7 overrides: Partial<SandboxHandle['process']> & {
8 read?: (p: string) => Promise<string>
9 },
10): SandboxHandle {
11 return {
12 fs: { read: overrides.read ?? (async () => 'AFTER') },
13 process: {
14 exec:
15 overrides.exec ??
16 (async () => ({ stdout: '', stderr: '', exitCode: 0 })),
17 },
18 } as unknown as SandboxHandle
20​
21describe('buildFileHookEvent', () => {
22 it('after() reads current content; delete → empty', async () => {
23 const h = fakeHandle({ read: async () => 'HELLO' })
24 const created = buildFileHookEvent(h, '/workspace', 'sha1', {
25 type: 'create',
26 path: '/workspace/a.ts',
27 timestamp: 1,
28 })
29 expect(await created.after()).toBe('HELLO')
30 const deleted = buildFileHookEvent(h, '/workspace', 'sha1', {
31 type: 'delete',
32 path: '/workspace/a.ts',
33 timestamp: 1,
34 })
35 expect(await deleted.after()).toBe('')
36 })
37​
38 it('before() runs `git show <base>:<rel>` and returns "" on non-zero exit', async () => {
39 const calls: Array<string> = []
40 const h = fakeHandle({
41 exec: async (cmd: string) => {
42 calls.push(cmd)
43 return { stdout: 'OLD', stderr: '', exitCode: 0 }
44 },
45 })
46 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
47 type: 'change',
48 path: '/workspace/src/a.ts',
49 timestamp: 1,
50 })
51 expect(await e.before()).toBe('OLD')
52 expect(calls[0]).toBe("git show 'sha1':'src/a.ts'")
53​
54 const missing = buildFileHookEvent(
55 fakeHandle({
56 exec: async () => ({ stdout: '', stderr: 'x', exitCode: 128 }),
57 }),
58 '/workspace',
59 'sha1',
60 { type: 'change', path: '/workspace/src/a.ts', timestamp: 1 },
61 )
62 expect(await missing.before()).toBe('')
63 })
64​
65 it('diff() with empty base synthesizes an add-patch from after()', async () => {
66 const e = buildFileHookEvent(
67 fakeHandle({ read: async () => 'line1\n' }),
68 '/workspace',
69 '',
70 { type: 'create', path: '/workspace/a.ts', timestamp: 1 },
71 )
72 const patch = await e.diff()
73 expect(patch).toContain('+line1')
74 })
75​
76 it('diff() with empty base and a delete event resolves to "" (no bogus add-patch)', async () => {
77 const e = buildFileHookEvent(
78 fakeHandle({ read: async () => 'AFTER' }),
79 '/workspace',
80 '',
81 { type: 'delete', path: '/workspace/a.ts', timestamp: 1 },
82 )
83 expect(await e.diff()).toBe('')
84 })
85​
86 it('diff() with a base runs `git diff <base> -- <rel-path>`', async () => {
87 const calls: Array<string> = []
88 const h = fakeHandle({
89 exec: async (cmd: string) => {
90 calls.push(cmd)
91 return { stdout: 'DIFF', stderr: '', exitCode: 0 }
92 },
93 })
94 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
95 type: 'change',
96 path: '/workspace/a.ts',
97 timestamp: 1,
98 })
99 expect(await e.diff()).toBe('DIFF')
100 // Pathspec is relativized (like before()'s `git show`) — a bare leading
101 // `/` is resolved by git against the filesystem root, not the repo root,
102 // and would fail with "fatal: Invalid path" once `root` isn't literally
103 // `/workspace` on disk (e.g. every local-process sandbox).
104 expect(calls[0]).toBe("git diff 'sha1' -- 'a.ts'")
105 })
106​
107 it('diff() relativizes a nested path the same way before() does', async () => {
108 const calls: Array<string> = []
109 const h = fakeHandle({
110 exec: async (cmd: string) => {
111 calls.push(cmd)
112 return { stdout: 'DIFF', stderr: '', exitCode: 0 }
113 },
114 })
115 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
116 type: 'change',
117 path: '/workspace/src/a.ts',
118 timestamp: 1,
119 })
120 expect(await e.diff()).toBe('DIFF')
121 expect(calls[0]).toBe("git diff 'sha1' -- 'src/a.ts'")
122 })
123​
124 it('diff() with a base synthesizes an add-patch when git diff is empty for a create (untracked file)', async () => {
125 // `git diff <sha> -- <path>` shows nothing for an untracked file, so a
126 // freshly created file yields exitCode 0 + empty stdout even though it has
127 // content. The git-show probe exits non-zero (absent at baseline), so the
128 // create must still get a real diff.
129 const h = fakeHandle({
130 read: async () => 'line1\n',
131 exec: async (cmd: string) => {
132 if (cmd.startsWith('git check-ignore'))
133 return { stdout: '', stderr: '', exitCode: 1 } // not ignored
134 if (cmd.startsWith('git show'))
135 return { stdout: '', stderr: 'fatal', exitCode: 128 } // untracked
136 return { stdout: '', stderr: '', exitCode: 0 } // git diff empty
137 },
138 })
139 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
140 type: 'create',
141 path: '/workspace/new.ts',
142 timestamp: 1,
143 })
144 const patch = await e.diff()
145 expect(patch).toContain('--- /dev/null')
146 expect(patch).toContain('+line1')
147 })
148​
149 it('diff() returns "" for a TRACKED file whose git diff is empty (identical to baseline, no bogus add-patch)', async () => {
150 // A file present at the baseline (before() non-empty) whose content now
151 // matches it legitimately diffs empty — it must NOT be synthesized into a
152 // full-file add-patch. Only a file ABSENT at the baseline synthesizes.
153 const h = fakeHandle({
154 read: async () => 'X',
155 exec: async (cmd: string) => {
156 if (cmd.startsWith('git check-ignore'))
157 return { stdout: '', stderr: '', exitCode: 1 } // not ignored
158 if (cmd.startsWith('git show'))
159 return { stdout: 'X', stderr: '', exitCode: 0 } // tracked at baseline
160 return { stdout: '', stderr: '', exitCode: 0 } // git diff: identical
161 },
162 })
163 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
164 type: 'change',
165 path: '/workspace/a.ts',
166 timestamp: 1,
167 })
168 expect(await e.diff()).toBe('')
169 })
170​
171 it('diff() synthesizes an add-patch for a CHANGE to an untracked file (the post-create edit case)', async () => {
172 // The dominant #914 case: an agent creates a file then edits it. The edit
173 // arrives as a `change`, `git diff` is still empty (git ignores untracked
174 // files), and before() is '' (absent at baseline) — so it must synthesize,
175 // not stream an empty diff. This is what keys on tracked-ness, not on the
176 // event being a `create`.
177 const h = fakeHandle({
178 read: async () => 'hello\n',
179 exec: async (cmd: string) => {
180 if (cmd.startsWith('git check-ignore'))
181 return { stdout: '', stderr: '', exitCode: 1 } // not ignored
182 if (cmd.startsWith('git show'))
183 return { stdout: '', stderr: 'fatal', exitCode: 128 } // untracked
184 return { stdout: '', stderr: '', exitCode: 0 } // git diff empty
185 },
186 })
187 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
188 type: 'change',
189 path: '/workspace/new.ts',
190 timestamp: 1,
191 })
192 const patch = await e.diff()
193 expect(patch).toContain('diff --git a/new.ts b/new.ts')
194 expect(patch).toContain('+hello')
195 })
196​
197 it('diff() withholds content for a git-ignored file — notify-only, empty diff', async () => {
198 // `git check-ignore` reports the path as ignored (exit 0). Even though the
199 // file has content and is untracked, diff() returns '' so the file's
200 // contents (e.g. a .env / secret) never reach the diff feed. The file event
201 // itself still fires elsewhere to notify that it changed.
202 const h = fakeHandle({
203 read: async () => 'SECRET=1\n',
204 exec: async (cmd: string) => {
205 if (cmd.startsWith('git check-ignore'))
206 return { stdout: '', stderr: '', exitCode: 0 } // ignored
207 if (cmd.startsWith('git show'))
208 return { stdout: '', stderr: 'fatal', exitCode: 128 } // untracked
209 return { stdout: '', stderr: '', exitCode: 0 } // git diff empty
210 },
211 })
212 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
213 type: 'create',
214 path: '/workspace/.env',
215 timestamp: 1,
216 })
217 expect(await e.diff()).toBe('')
218 })
219​
220 it('diff() falls through to a normal diff (does NOT withhold) when git check-ignore itself throws', async () => {
221 const { logger, calls } = captureLogger()
222 const h = fakeHandle({
223 read: async () => 'x\n',
224 exec: async (cmd: string) => {
225 if (cmd.startsWith('git check-ignore'))
226 throw new Error('check-ignore boom')
227 if (cmd.startsWith('git show'))
228 return { stdout: '', stderr: 'fatal', exitCode: 128 } // untracked
229 return { stdout: '', stderr: '', exitCode: 0 } // git diff empty
230 },
231 })
232 const e = buildFileHookEvent(
233 h,
234 '/workspace',
235 'sha1',
236 { type: 'create', path: '/workspace/n.ts', timestamp: 1 },
237 logger,
238 )
239 const patch = await e.diff()
240 expect(patch).toContain('+x') // synthesized, not withheld
241 expect(
242 calls.some((c) => c.level === 'warn' && c.msg.includes('check-ignore')),
243 ).toBe(true)
244 })
245​
246 it('logs a warning and still diffs when git check-ignore errors (exit 128)', async () => {
247 const { logger, calls } = captureLogger()
248 const h = fakeHandle({
249 read: async () => 'y\n',
250 exec: async (cmd: string) => {
251 if (cmd.startsWith('git check-ignore'))
252 return { stdout: '', stderr: 'fatal', exitCode: 128 } // error, not "1"
253 if (cmd.startsWith('git show'))
254 return { stdout: '', stderr: 'fatal', exitCode: 128 } // untracked
255 return { stdout: '', stderr: '', exitCode: 0 } // git diff empty
256 },
257 })
258 const e = buildFileHookEvent(
259 h,
260 '/workspace',
261 'sha1',
262 { type: 'create', path: '/workspace/z.ts', timestamp: 1 },
263 logger,
264 )
265 const patch = await e.diff()
266 expect(patch).toContain('+y') // not withheld on a check-ignore error
267 expect(
268 calls.some(
269 (c) => c.level === 'warn' && c.msg.includes('check-ignore non-zero'),
270 ),
271 ).toBe(true)
272 })
273​
274 it('logs (sandbox) when the tracked-ness probe exits non-zero before synthesizing', async () => {
275 const { logger, calls } = captureLogger()
276 const h = fakeHandle({
277 read: async () => 'q\n',
278 exec: async (cmd: string) => {
279 if (cmd.startsWith('git check-ignore'))
280 return { stdout: '', stderr: '', exitCode: 1 } // not ignored
281 if (cmd.startsWith('git show'))
282 return { stdout: '', stderr: 'fatal', exitCode: 128 }
283 return { stdout: '', stderr: '', exitCode: 0 }
284 },
285 })
286 const e = buildFileHookEvent(
287 h,
288 '/workspace',
289 'sha1',
290 { type: 'create', path: '/workspace/q.ts', timestamp: 1 },
291 logger,
292 )
293 const patch = await e.diff()
294 expect(patch).toContain('+q')
295 expect(
296 calls.some(
297 (c) =>
298 c.level === 'debug' && c.msg.includes('tracked-ness probe non-zero'),
299 ),
300 ).toBe(true)
301 })
302​
303 it('logs a warning when git diff itself throws', async () => {
304 const { logger, calls } = captureLogger()
305 const h = fakeHandle({
306 exec: async (cmd: string) => {
307 if (cmd.startsWith('git diff')) throw new Error('diff boom')
308 return { stdout: '', stderr: '', exitCode: 0 }
309 },
310 })
311 const e = buildFileHookEvent(
312 h,
313 '/workspace',
314 'sha1',
315 { type: 'change', path: '/workspace/a.ts', timestamp: 1 },
316 logger,
317 )
318 expect(await e.diff()).toBe('')
319 expect(
320 calls.some((c) => c.level === 'warn' && c.msg.includes('git diff')),
321 ).toBe(true)
322 })
323​
324 it('synthesizes a git-shaped add-patch for a multi-line untracked file, with the no-newline marker', async () => {
325 const h = fakeHandle({
326 read: async () => 'a\nb\nc', // 3 lines, NO trailing newline
327 exec: async (cmd: string) => {
328 if (cmd.startsWith('git check-ignore'))
329 return { stdout: '', stderr: '', exitCode: 1 }
330 if (cmd.startsWith('git show'))
331 return { stdout: '', stderr: 'fatal', exitCode: 128 }
332 return { stdout: '', stderr: '', exitCode: 0 }
333 },
334 })
335 const e = buildFileHookEvent(h, '/workspace', 'sha1', {
336 type: 'create',
337 path: '/workspace/m.ts',
338 timestamp: 1,
339 })
340 const patch = await e.diff()
341 expect(patch).toContain('new file mode 100644')
342 expect(patch).toContain('@@ -0,0 +1,3 @@')
343 expect(patch).toContain('+a\n+b\n+c')
344 expect(patch).toContain('\\ No newline at end of file')
345 })
346​
347 it('synthesized add-patch omits the no-newline marker for content that ends in a newline', async () => {
348 const e = buildFileHookEvent(
349 fakeHandle({ read: async () => 'one\ntwo\n' }),
350 '/workspace',
351 '',
352 { type: 'create', path: '/workspace/a.ts', timestamp: 1 },
353 )
354 const patch = await e.diff()
355 expect(patch).toContain('@@ -0,0 +1,2 @@')
356 expect(patch).toContain('+one\n+two\n')
357 expect(patch).not.toContain('No newline at end of file')
358 })
359​
360 it('synthesized add-patch for an empty file is header-only (no hunk)', async () => {
361 const e = buildFileHookEvent(
362 fakeHandle({ read: async () => '' }),
363 '/workspace',
364 '',
365 { type: 'create', path: '/workspace/empty.ts', timestamp: 1 },
366 )
367 const patch = await e.diff()
368 expect(patch).toBe(
369 'diff --git a/empty.ts b/empty.ts\nnew file mode 100644\n',
370 )
371 })
372​
373 it('diff() does NOT synthesize when the tracked-ness probe throws (no bogus add-patch on a git hiccup)', async () => {
374 // git diff comes back empty (looks like a no-op), but the git-show probe
375 // that would confirm tracked-ness rejects transiently. We must NOT read
376 // that as "untracked" and fabricate a full-file add-patch for a file that
377 // is (probably) a tracked, unchanged file.
378 const { logger, calls } = captureLogger()
379 const h = fakeHandle({
380 read: async () => 'X',
381 exec: async (cmd: string) => {
382 if (cmd.startsWith('git check-ignore'))
383 return { stdout: '', stderr: '', exitCode: 1 } // not ignored
384 if (cmd.startsWith('git show')) throw new Error('git hiccup')
385 return { stdout: '', stderr: '', exitCode: 0 } // git diff empty
386 },
387 })
388 const e = buildFileHookEvent(
389 h,
390 '/workspace',
391 'sha1',
392 { type: 'change', path: '/workspace/a.ts', timestamp: 1 },
393 logger,
394 )
395 expect(await e.diff()).toBe('')
396 expect(
397 calls.some((c) => c.level === 'warn' && c.msg.includes('tracked-ness')),
398 ).toBe(true)
399 })
400​
401 it('logs a warning when git diff exits non-zero', async () => {
402 const { logger, calls } = captureLogger()
403 const h = fakeHandle({
404 exec: async () => ({ stdout: '', stderr: 'boom', exitCode: 128 }),
405 })
406 const e = buildFileHookEvent(
407 h,
408 '/workspace',
409 'sha1',
410 { type: 'change', path: '/workspace/a.ts', timestamp: 1 },
411 logger,
412 )
413 expect(await e.diff()).toBe('')
414 expect(
415 calls.some((c) => c.level === 'warn' && c.msg.includes('git diff')),
416 ).toBe(true)
417 })
418​
419 it('logs a warning when after() fails to read the file', async () => {
420 const { logger, calls } = captureLogger()
421 const h = fakeHandle({
422 read: async () => {
423 throw new Error('nope')
424 },
425 })
426 const e = buildFileHookEvent(
427 h,
428 '/workspace',
429 'sha1',
430 { type: 'change', path: '/workspace/a.ts', timestamp: 1 },
431 logger,
432 )
433 expect(await e.after()).toBe('')
434 expect(
435 calls.some((c) => c.level === 'warn' && c.msg.includes('after()')),
436 ).toBe(true)
437 })
438})