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

git.test.ts

463 lines13.5 KB

1import { describe, expect, it } from 'vitest'
2import { spawnSync } from 'node:child_process'
3import { mkdtemp, writeFile, rename, rm } from 'node:fs/promises'
4import { tmpdir } from 'node:os'
5import { join } from 'node:path'
6import {
7 applyPatch,
8 commitAll,
9 headRemoteUrl,
10 preparePullWorktree,
11 pushHead,
12 readPullSnapshot,
13} from './git'
14import type { GitRunner } from './git'
15import { auditPullSecurity } from './security'
16​
17type GitResult = { stdout: string; stderr: string; code: number }
18​
19const CWD = '/tmp/review'
20const IDENTITY = { name: 'TanStack AI Bot', email: 'bot@tanstack.com' }
21const TOKEN = 'ghs_abc'
22const ORIGIN = 'TanStack/ai'
23const FORK = 'alice/ai'
24const REMOTE = `https://x-access-token:tok@github.com/${ORIGIN}.git`
25​
26const BASE = 'a'.repeat(40)
27const HEAD = 'b'.repeat(40)
28const MERGE_BASE = 'c'.repeat(40)
29const OLD_BLOB = 'd'.repeat(40)
30const NEW_BLOB = 'e'.repeat(40)
31​
32function snapshotRunner(
33 options: {
34 paths?: Array<string>
35 raw?: string
36 diff?: string
37 failFetch?: boolean
38 } = {},
39) {
40 const paths = options.paths ?? ['package.json']
41 return createFakeRunner((args) => {
42 if (args[0] === 'fetch' && options.failFetch)
43 return { stdout: '', stderr: 'missing object', code: 1 }
44 let stdout = ''
45 if (args[0] === 'merge-base') stdout = MERGE_BASE
46 if (args.includes('--raw'))
47 stdout =
48 options.raw ??
49 paths
50 .map((path) => `:100644 100644 ${OLD_BLOB} ${NEW_BLOB} M\0${path}\0`)
51 .join('')
52 if (args.includes('--patch'))
53 stdout =
54 options.diff ??
55 paths
56 .map(
57 (path) =>
58 `diff --git a/${JSON.stringify(path)} b/${JSON.stringify(path)}\n--- old\n+++ new\n@@ -1 +1 @@\n-old\n+new\n`,
59 )
60 .join('')
61 if (args[0] === 'cat-file')
62 stdout = args[2] === OLD_BLOB ? '{}' : '{"dependencies":{"left-pad":"1"}}'
63 return { stdout, stderr: '', code: 0 }
64 })
66​
67describe('readPullSnapshot', () => {
68 it('reads real Git renames, modes, UTF-8 paths, and divergent base manifests', async () => {
69 const directory = await mkdtemp(join(tmpdir(), 'ai-review-snapshot-'))
70 const run = (args: Array<string>) => {
71 const result = spawnSync(
72 'git',
73 [
74 '-c',
75 'user.name=Fixture',
76 '-c',
77 'user.email=fixture@example.com',
78 '-c',
79 `core.hooksPath=${join(directory, 'no-hooks')}`,
80 ...args,
81 ],
82 { cwd: directory, encoding: 'utf8' },
83 )
84 if (result.status !== 0) throw new Error(result.stderr)
85 return result.stdout.trim()
86 }
87 const runner: GitRunner = async (args, cwd) => {
88 const result = spawnSync('git', args, { cwd, encoding: 'utf8' })
89 return {
90 stdout: result.stdout,
91 stderr: result.stderr,
92 code: result.status ?? 1,
93 }
94 }
95 try {
96 run(['init'])
97 await writeFile(join(directory, 'package.json'), '{}\n')
98 await writeFile(join(directory, 'AGENTS.md'), 'fixture instructions\n')
99 await writeFile(join(directory, 'café.ts'), 'old\n')
100 run(['add', '.'])
101 run(['commit', '-m', 'fixture base'])
102 const mergeBase = run(['rev-parse', 'HEAD'])
103 await writeFile(
104 join(directory, 'package.json'),
105 '{"dependencies":{"left-pad":"1"}}\n',
106 )
107 run(['add', '.'])
108 run(['commit', '-m', 'base update'])
109 const baseSha = run(['rev-parse', 'HEAD'])
110 run(['checkout', '--detach', mergeBase])
111 await writeFile(
112 join(directory, 'package.json'),
113 '{"dependencies":{"left-pad":"1"}}\n',
114 )
115 await rename(
116 join(directory, 'AGENTS.md'),
117 join(directory, 'old-rules.md'),
118 )
119 await writeFile(join(directory, 'café.ts'), 'new\n')
120 run(['add', '.'])
121 run(['update-index', '--chmod=+x', 'café.ts'])
122 run(['commit', '-m', 'head change'])
123 const headSha = run(['rev-parse', 'HEAD'])
124 run(['remote', 'add', 'origin', directory])
125 const snapshot = await readPullSnapshot(
126 directory,
127 { baseSha, headSha },
128 runner,
129 )
130 expect(snapshot.mergeBase).toBe(mergeBase)
131 expect(snapshot.files.map((file) => file.path)).toEqual([
132 'AGENTS.md',
133 'café.ts',
134 'old-rules.md',
135 'package.json',
136 ])
137 expect(
138 snapshot.files.find((file) => file.path === 'AGENTS.md')?.headMode,
139 ).toBe('000000')
140 expect(auditPullSecurity(snapshot).reasons).toEqual([
141 'AGENTS.md: changes security-sensitive instructions or automation',
142 'café.ts: becomes executable',
143 'package.json: adds dependencies: left-pad',
144 ])
145 } finally {
146 await rm(directory, { recursive: true, force: true })
147 }
148 })
149​
150 it('uses the merge base and fixed blob IDs without checking out files', async () => {
151 const { runner, calls } = snapshotRunner()
152 const snapshot = await readPullSnapshot(
153 CWD,
154 { baseSha: BASE, headSha: HEAD },
155 runner,
156 )
157 expect(snapshot.mergeBase).toBe(MERGE_BASE)
158 expect(snapshot.files[0]).toMatchObject({
159 path: 'package.json',
160 before: '{}',
161 after: '{"dependencies":{"left-pad":"1"}}',
162 })
163 expect(
164 calls
165 .filter(({ args }) => args[0] === 'diff')
166 .every(
167 ({ args }) =>
168 args.includes(MERGE_BASE) &&
169 args.includes(HEAD) &&
170 args.includes('--no-ext-diff') &&
171 args.includes('--no-textconv') &&
172 args.includes('--no-renames'),
173 ),
174 ).toBe(true)
175 expect(
176 calls.some(
177 ({ args }) => args.includes('checkout') || args.includes('worktree'),
178 ),
179 ).toBe(false)
180 })
181​
182 it('names a file type change instead of reporting an incomplete patch', async () => {
183 const { runner } = snapshotRunner({
184 raw: `:120000 100644 ${OLD_BLOB} ${NEW_BLOB} T\0link.ts\0`,
185 diff: 'diff --git a/link.ts b/link.ts\ndeleted file mode 120000\ndiff --git a/link.ts b/link.ts\nnew file mode 100644\n',
186 })
187 await expect(
188 readPullSnapshot(CWD, { baseSha: BASE, headSha: HEAD }, runner),
189 ).rejects.toThrow('File type changes are not supported')
190 })
191​
192 it('keeps dotfiles and control characters from NUL-delimited paths', async () => {
193 const paths = ['.hidden', 'quote"name.ts', 'line\nname.ts']
194 const { runner } = snapshotRunner({ paths })
195 const snapshot = await readPullSnapshot(
196 CWD,
197 { baseSha: BASE, headSha: HEAD },
198 runner,
199 )
200 expect(snapshot.files.map((file) => file.path)).toEqual(paths)
201 })
202​
203 it('scans a sensitive path after more than 3000 changed files', async () => {
204 const paths = [
205 ...Array.from({ length: 3001 }, (_, index) => `src/${index}.ts`),
206 '.agents/rules.md',
207 ]
208 const { runner } = snapshotRunner({ paths })
209 const snapshot = await readPullSnapshot(
210 CWD,
211 { baseSha: BASE, headSha: HEAD },
212 runner,
213 )
214 expect(snapshot.files).toHaveLength(3002)
215 expect(auditPullSecurity(snapshot)).toEqual({
216 ok: false,
217 reasons: [
218 '.agents/rules.md: changes security-sensitive instructions or automation',
219 ],
220 })
221 })
222​
223 it.each([
224 { raw: 'incomplete' },
225 { raw: `:100644 100644 ${OLD_BLOB} ${NEW_BLOB} R100\0old\0new\0` },
226 { diff: '' },
227 ])('rejects incomplete or unsupported Git output', async (options) => {
228 const { runner } = snapshotRunner(options)
229 await expect(
230 readPullSnapshot(CWD, { baseSha: BASE, headSha: HEAD }, runner),
231 ).rejects.toThrow(/snapshot/i)
232 })
233​
234 it('does not fall back to a mutable reference after a fetch failure', async () => {
235 const { runner, calls } = snapshotRunner({ failFetch: true })
236 await expect(
237 readPullSnapshot(CWD, { baseSha: BASE, headSha: HEAD }, runner),
238 ).rejects.toThrow('missing object')
239 expect(calls).toHaveLength(1)
240 })
241})
242​
243function createFakeRunner(
244 impl?: (args: Array<string>, cwd: string) => GitResult,
245) {
246 const calls: Array<{ args: Array<string>; cwd: string; input?: string }> = []
247 const runner: GitRunner = async (args, cwd, input) => {
248 calls.push({
249 args: [...args],
250 cwd,
251 ...(input === undefined ? {} : { input }),
252 })
253 if (impl) {
254 return impl(args, cwd)
255 }
256 return { stdout: '', stderr: '', code: 0 }
257 }
258 return { runner, calls }
260​
261describe('applyPatch', () => {
262 it('checks a patch before it applies it', async () => {
263 const { runner, calls } = createFakeRunner()
264​
265 await applyPatch(CWD, 'diff text', runner)
266​
267 expect(calls).toEqual([
268 {
269 args: ['apply', '--check', '--whitespace=error-all', '-'],
270 cwd: CWD,
271 input: 'diff text',
272 },
273 {
274 args: ['apply', '--whitespace=error-all', '-'],
275 cwd: CWD,
276 input: 'diff text',
277 },
278 ])
279 })
280​
281 it('does not apply a patch that fails its check', async () => {
282 const { runner, calls } = createFakeRunner((args) => ({
283 stdout: '',
284 stderr: args.includes('--check') ? 'bad patch' : '',
285 code: args.includes('--check') ? 1 : 0,
286 }))
287​
288 await expect(applyPatch(CWD, 'bad', runner)).rejects.toThrow(/bad patch/)
289 expect(calls).toHaveLength(1)
290 })
291})
292​
293describe('preparePullWorktree', () => {
294 it('creates the worktree after the fetched SHA matches', async () => {
295 const { runner, calls } = createFakeRunner((args) => ({
296 stdout: args[0] === 'rev-parse' ? 'abc123\n' : '',
297 stderr: '',
298 code: 0,
299 }))
300​
301 await preparePullWorktree(CWD, '/tmp/pr-head', 42, 'abc123', runner)
302​
303 expect(calls).toEqual([
304 {
305 args: ['fetch', '--no-tags', 'origin', 'pull/42/head'],
306 cwd: CWD,
307 },
308 { args: ['rev-parse', 'FETCH_HEAD'], cwd: CWD },
309 {
310 args: ['worktree', 'add', '--detach', '/tmp/pr-head', 'abc123'],
311 cwd: CWD,
312 },
313 ])
314 })
315​
316 it('does not check out a head that changed during review', async () => {
317 const { runner, calls } = createFakeRunner((args) => ({
318 stdout: args[0] === 'rev-parse' ? 'new-sha\n' : '',
319 stderr: '',
320 code: 0,
321 }))
322​
323 await expect(
324 preparePullWorktree(CWD, '/tmp/pr-head', 42, 'old-sha', runner),
325 ).rejects.toThrow(/PR head changed during review/)
326 expect(calls).toHaveLength(2)
327 })
328})
329​
330describe('commitAll', () => {
331 it('adds all files then commits with the given identity', async () => {
332 const { runner, calls } = createFakeRunner()
333​
334 expect(await commitAll(CWD, 'polish: fix nits', runner, IDENTITY)).toEqual({
335 committed: true,
336 })
337 expect(calls).toEqual([
338 { args: ['add', '-A'], cwd: CWD },
339 {
340 args: [
341 '-c',
342 'user.name=TanStack AI Bot',
343 '-c',
344 'user.email=bot@tanstack.com',
345 'commit',
346 '-m',
347 'polish: fix nits',
348 ],
349 cwd: CWD,
350 },
351 ])
352 })
353​
354 it('returns committed false when git reports nothing to commit', async () => {
355 const { runner } = createFakeRunner((args) => {
356 if (args.includes('commit')) {
357 return {
358 stdout: 'On branch main\nnothing to commit, working tree clean\n',
359 stderr: '',
360 code: 1,
361 }
362 }
363 return { stdout: '', stderr: '', code: 0 }
364 })
365​
366 expect(await commitAll(CWD, 'nope', runner, IDENTITY)).toEqual({
367 committed: false,
368 })
369 })
370​
371 it('throws when add exits non-zero', async () => {
372 const { runner } = createFakeRunner((args) => {
373 if (args[0] === 'add') {
374 return { stdout: '', stderr: 'index.lock exists', code: 128 }
375 }
376 return { stdout: '', stderr: '', code: 0 }
377 })
378​
379 await expect(commitAll(CWD, 'nope', runner, IDENTITY)).rejects.toThrow(
380 /index.lock exists/,
381 )
382 })
383​
384 it('throws when commit fails for a reason other than an empty tree', async () => {
385 const { runner } = createFakeRunner((args) => {
386 if (args.includes('commit')) {
387 return { stdout: '', stderr: 'hook declined', code: 1 }
388 }
389 return { stdout: '', stderr: '', code: 0 }
390 })
391​
392 await expect(commitAll(CWD, 'nope', runner, IDENTITY)).rejects.toThrow(
393 /hook declined/,
394 )
395 })
396})
397​
398describe('pushHead', () => {
399 it('pushes HEAD to the dest ref with --force-with-lease and no bare --force', async () => {
400 const { runner, calls } = createFakeRunner()
401​
402 await pushHead(CWD, runner, {
403 remoteUrl: REMOTE,
404 ref: 'fix-nits',
405 expectedSha: 'abc123',
406 })
407​
408 const args = calls[0]?.args ?? []
409 expect(calls).toEqual([
410 {
411 args: [
412 'push',
413 '--force-with-lease=refs/heads/fix-nits:abc123',
414 REMOTE,
415 'HEAD:fix-nits',
416 ],
417 cwd: CWD,
418 },
419 ])
420 expect(args).toContain('--force-with-lease=refs/heads/fix-nits:abc123')
421 expect(args).not.toContain('--force')
422 })
423​
424 it('throws when push exits non-zero', async () => {
425 const { runner } = createFakeRunner(() => ({
426 stdout: '',
427 stderr: `stale info for ${REMOTE}`,
428 code: 1,
429 }))
430​
431 await expect(
432 pushHead(CWD, runner, {
433 remoteUrl: REMOTE,
434 ref: 'main',
435 expectedSha: 'abc123',
436 }),
437 ).rejects.toThrow('stale info for <redacted remote>')
438 })
439})
440​
441describe('headRemoteUrl', () => {
442 it('uses originRepo for a same-repo PR', () => {
443 expect(
444 headRemoteUrl({
445 isFork: false,
446 originRepo: ORIGIN,
447 headRepo: FORK,
448 token: TOKEN,
449 }),
450 ).toBe(`https://x-access-token:${TOKEN}@github.com/${ORIGIN}.git`)
451 })
452​
453 it('uses headRepo for a fork PR', () => {
454 expect(
455 headRemoteUrl({
456 isFork: true,
457 originRepo: ORIGIN,
458 headRepo: FORK,
459 token: TOKEN,
460 }),
461 ).toBe(`https://x-access-token:${TOKEN}@github.com/${FORK}.git`)
462 })
463})