@anureo/refactor 0.3.1 → 0.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,65 @@
1
- // Exercises the real Repograph exporter only when REPOGRAPH_INTEGRATION=1.
1
+ // Exercises the subprocess graph adapter, with optional live Repograph coverage.
2
2
  import { expect, test } from 'bun:test'
3
- import { realpath, writeFile } from 'node:fs/promises'
3
+ import { mkdir, readFile, realpath, symlink, writeFile } from 'node:fs/promises'
4
+ import { createRequire } from 'node:module'
4
5
  import { dirname, join } from 'node:path'
5
- import { loadGraph, resolveRepographEntry } from '../src/graph'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { loadGraph, repographProject, resolveRepographEntry } from '../src/graph'
8
+ import { exportGraph, type GraphArtifactContext } from '../src/graph-artifacts'
6
9
  import { exec } from '../src/process'
7
10
  import { temporary } from './helpers'
8
11
 
12
+ test('graph artifacts retain metadata and cover symbols under either spelling of the target', async () => {
13
+ const outside = await temporary()
14
+ const cwd = await realpath(await temporary())
15
+ const directory = join(cwd, '.anureo', 'refactor', 'run')
16
+ const alias = join(outside, 'alias')
17
+ await exec('git', ['init', '-q', cwd])
18
+ await mkdir(directory, { recursive: true })
19
+ await writeFile(join(dirname(directory), '.gitignore'), 'writer.lock\n')
20
+ await symlink(cwd, alias, 'junction')
21
+ const entry = fileURLToPath(new URL('./fixtures/repograph.ts', import.meta.url))
22
+ const context: GraphArtifactContext = {
23
+ options: { cwd, graphLoader: async () => {
24
+ expect(await readFile(join(directory, '.gitignore'), 'utf8')).toBe('*\n')
25
+ return loadGraph(alias, entry)
26
+ } },
27
+ report: { directory, graphCoverage: [] }, progress: () => {},
28
+ }
29
+ const file = await exportGraph(context, 'design', ['main.ts', 'relative.ts', 'absolute.ts', 'canonical.ts', 'missing.ts'])
30
+ expect(context.report.graphCoverage).toEqual([{ phase: 'design', status: 'available', filesWithoutSymbols: ['missing.ts'] }])
31
+ expect(JSON.parse(await readFile(file!, 'utf8'))).toMatchObject({
32
+ repositoryPath: alias, project: repographProject(alias), generatedAt: expect.any(String), files: { 'main.ts': { lines: 1 } },
33
+ })
34
+ await exec('git', ['-C', cwd, 'check-ignore', '--quiet', file!])
35
+ })
36
+
37
+ test('graph validation reports duplicate nodes and missing edge endpoints together', async () => {
38
+ const cwd = await temporary()
39
+ const entry = join(cwd, 'invalid.mjs')
40
+ await writeFile(entry, `
41
+ import { writeFileSync } from 'node:fs'
42
+ const node = { id: 'duplicate', name: 'main', filePath: 'main.ts', labels: ['Function'], startLine: 1, endLine: 1 }
43
+ writeFileSync(process.argv.at(-1), JSON.stringify({
44
+ schemaVersion: 1, kind: 'all', repositoryPath: process.argv[3], indexReport: {}, nodes: [node, node],
45
+ edges: [{ id: 'bad-edge', source: 'missing-source', target: 'missing-target', type: 'CALLS' }],
46
+ }))
47
+ `)
48
+ await expect(loadGraph(cwd, entry)).rejects.toThrow(
49
+ 'Duplicate node ID "duplicate"\nEdge "bad-edge" references missing node IDs ["missing-source","missing-target"]',
50
+ )
51
+ })
52
+
53
+ test.each(['stdout', 'stderr'])('graph export enforces the byte limit on %s', async stream => {
54
+ const cwd = await temporary()
55
+ const entry = join(cwd, 'overflow.mjs')
56
+ await writeFile(entry, `
57
+ process.${stream}.write(Buffer.alloc((8 << 20) + 1))
58
+ setInterval(() => {}, 1000)
59
+ `)
60
+ await expect(loadGraph(cwd, entry)).rejects.toThrow(`repograph ${stream} exceeded the 8388608-byte output limit`)
61
+ })
62
+
9
63
  const fixtures = [
10
64
  { language: 'TypeScript', extension: 'ts', main: 'import { save } from "./store";\nexport function main() { return save() }\n',
11
65
  store: 'export function save() { return 1 }\nexport function isolated() { return 2 }\n' },
@@ -13,25 +67,44 @@ const fixtures = [
13
67
  store: 'def save():\n return 1\n\ndef isolated():\n return 2\n' },
14
68
  ]
15
69
 
16
- // Each live case uses the installed CLI or REPOGRAPH_CLI. The shared temporary() hook removes
17
- // its Git repository, and the test uses the returned index report to attempt project deletion.
70
+ // Each live case uses the installed CLI or REPOGRAPH_CLI and owns its deterministic project key.
18
71
  test.skipIf(process.env.REPOGRAPH_INTEGRATION !== '1').each(fixtures)('real repograph exports $language cross-file callers', async ({ extension, main, store }) => {
19
72
  const cwd = await realpath(await temporary())
20
73
  await exec('git', ['init', '-q', cwd])
21
74
  await writeFile(join(cwd, `main.${extension}`), main)
22
75
  await writeFile(join(cwd, `store.${extension}`), store)
23
76
  const entry = process.env.REPOGRAPH_CLI ?? resolveRepographEntry()
24
- const graph = await loadGraph(cwd, entry)
77
+ const project = repographProject(cwd)
78
+ const shim = createRequire(entry).resolve('codebase-memory-mcp/bin.js')
79
+ const errors: unknown[] = []
25
80
  try {
81
+ const graph = await loadGraph(cwd, entry)
26
82
  const byId = new Map(graph.nodes.map(node => [node.id, node.name]))
27
83
  expect(graph.edges.some(edge => edge.type === 'CALLS' && byId.get(edge.source) === 'main' && byId.get(edge.target) === 'save')).toBe(true)
28
84
  expect(graph.nodes.some(node => node.name === 'isolated')).toBe(true)
29
85
  expect(graph.indexReport.nodes).toBe(graph.nodes.length)
30
86
  expect(graph.indexReport.edges).toBe(graph.edges.length)
87
+ } catch (cause) {
88
+ errors.push(cause)
31
89
  } finally {
32
- // Use the sibling backend matching the CLI's source or installed layout to delete the index.
33
- const backend = entry.endsWith('.ts') ? 'cbm.ts' : 'cbm.js'
34
- const { runTool } = await import(join(dirname(entry), backend))
35
- await runTool('delete_project', { project: graph.indexReport.project })
90
+ try {
91
+ await deleteTestProject(shim, project)
92
+ } catch (cause) {
93
+ errors.push(cause)
94
+ }
36
95
  }
96
+ if (errors.length > 1) throw new AggregateError(errors, errors.map(String).join('\n'))
97
+ if (errors.length) throw errors[0]
37
98
  }, 120_000)
99
+
100
+ async function deleteTestProject(shim: string, project: string): Promise<void> {
101
+ try {
102
+ await exec(process.execPath, [shim, 'cli', '--json', 'delete_project', '--project', project], { timeout: 30_000 })
103
+ } catch (cause) {
104
+ // The native CLI uses exit status 1 when the exporter never created the project.
105
+ const stdout = (cause as { stdout?: string }).stdout
106
+ let result: { structuredContent?: { project?: string; status?: string } } | undefined
107
+ try { result = stdout ? JSON.parse(stdout) : undefined } catch { throw cause }
108
+ if (result?.structuredContent?.project !== project || result.structuredContent.status !== 'not_found') throw cause
109
+ }
110
+ }
package/tests/helpers.ts CHANGED
@@ -30,7 +30,11 @@ export const edited = (change = 'Renamed internal value') => ({ summary: 'Edited
30
30
  /** Return the first line for prompt routing, or an empty string for empty input. */
31
31
  export const kind = (prompt: string) => prompt.split('\n')[0]!
32
32
  /** Read a module ID from its serialized prompt header, or return undefined when absent. */
33
- export const moduleOf = (prompt: string) => /Module: \{"id":"([^"]+)"/.exec(prompt)?.[1]
33
+ export function moduleOf(prompt: string): string | undefined {
34
+ const prefix = 'Module: '
35
+ const header = prompt.split('\n').find(line => line.startsWith(prefix))
36
+ return header ? JSON.parse(header.slice(prefix.length)).id : undefined
37
+ }
34
38
  /** Build a two-file graph rooted at the test target for injected graph loaders. */
35
39
  export function graph(cwd: string): RepositoryGraph {
36
40
  return { schemaVersion: 1, repositoryPath: cwd, kind: 'all', indexReport: { status: 'indexed' }, nodes: [
@@ -1,7 +1,7 @@
1
1
  // Exercises public sequencing, checkpoints and failure gates through refactorCode.
2
2
  import { expect, test } from 'bun:test'
3
- import { mkdir, readFile, readdir, rename, stat, symlink, writeFile } from 'node:fs/promises'
4
- import { join } from 'node:path'
3
+ import { mkdir, readFile, readdir, rename, rm, stat, symlink, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
5
  import { createClient, HarnessSdkError, type StructuredOutputToolDefinition } from '@anureo/sdk'
6
6
  import { createPiAdapter } from '@anureo/adapter-pi'
7
7
  import { fakeFactory } from '../../../packages/adapter/pi/tests/fake-host'
@@ -81,7 +81,6 @@ test('each agent has a worktree and module sessions overlap on the same post-des
81
81
  if (++runningModules === 2) modulesReady.resolve()
82
82
  await modulesReady.promise
83
83
  await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
84
- expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('// design')
85
84
  const other = module === 'a' ? 'b' : 'a'
86
85
  expect(await readFile(join(cwd, `${other}.ts`), 'utf8')).toContain('value = 1')
87
86
  return edited()
@@ -200,6 +199,59 @@ test('a failed module leaves the target untouched for its assignment while sibli
200
199
  expect((await git(context.cwd, 'worktree', 'list', '--porcelain')).match(/^worktree /gm)).toHaveLength(1)
201
200
  })
202
201
 
202
+ test('an unknown module outcome stops queued session dispatch', async () => {
203
+ const context = await fixture(prompt => {
204
+ if (prompt.startsWith('PLAN')) return plan
205
+ if (moduleOf(prompt) === 'a') return new HarnessSdkError('RECEIPT_LOST', 'Unknown', false, true)
206
+ return unchanged
207
+ })
208
+ const report = await refactorCode({ ...context, concurrency: 1, checks: [] })
209
+ expect(report.status).toBe('incomplete')
210
+ expect(report.modules[0]?.step?.failure).toMatchObject({ code: 'RECEIPT_LOST', outcomeUnknown: true })
211
+ expect(report.modules[1]?.step).toBeNull()
212
+ expect(context.adapter.opened).toHaveLength(3)
213
+ })
214
+
215
+ test.each(['planning', 'module'])('worktree cleanup failure preserves the %s outcome', async phase => {
216
+ let locked: string | undefined
217
+ const context = await fixture(async (prompt, cwd) => {
218
+ const planning = prompt.startsWith('PLAN')
219
+ if (phase === 'planning' ? planning : moduleOf(prompt) === 'a') {
220
+ await git(context.cwd, 'worktree', 'lock', cwd)
221
+ locked = cwd
222
+ if (planning) return new HarnessSdkError('RECEIPT_LOST', 'Planner receipt lost', true, true)
223
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
224
+ return edited()
225
+ }
226
+ return planning ? plan : unchanged
227
+ })
228
+ try {
229
+ const report = await refactorCode({ ...context, concurrency: 1, checks: [] })
230
+ expect(report.status).toBe('incomplete')
231
+ if (phase === 'planning') {
232
+ expect(report.failure).toMatchObject({
233
+ code: 'RECEIPT_LOST', outcomeUnknown: true, retryable: true, cleanupFailed: true,
234
+ })
235
+ expect(report.errors[0]).toContain('Planner receipt lost')
236
+ expect(report.errors[0]).toContain('Could not remove refactor worktree')
237
+ expect(report.plan).toBeNull()
238
+ } else {
239
+ expect(report.modules[0]?.step).toMatchObject({
240
+ status: 'failed', appliedFiles: ['a.ts'], failure: { cleanupFailed: true },
241
+ })
242
+ expect(report.modules[1]?.step).toBeNull()
243
+ expect(formatReport(report)).toContain('Files already applied: a.ts')
244
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 2')
245
+ }
246
+ expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
247
+ } finally {
248
+ if (locked) {
249
+ try { await git(context.cwd, 'worktree', 'remove', '--force', '--force', locked) }
250
+ finally { await rm(dirname(locked), { recursive: true, force: true }) }
251
+ }
252
+ }
253
+ })
254
+
203
255
  test('verified work merges while an earlier agent is still running, and competing additions fail', async () => {
204
256
  const merged = Promise.withResolvers<void>()
205
257
  const context = await fixture(async (prompt, cwd) => {
@@ -267,6 +319,53 @@ test('failed validation retains its output and prevents unverified changes from
267
319
  expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toBe('export const value = 2\n')
268
320
  })
269
321
 
322
+ test('disjoint candidates are checked against the edits already merged', async () => {
323
+ const context = await fixture(async (prompt, cwd) => {
324
+ if (prompt.startsWith('PLAN')) return plan
325
+ const module = moduleOf(prompt)
326
+ if (!module) return unchanged
327
+ await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
328
+ return edited()
329
+ })
330
+ const report = await refactorCode({ ...context, checks: [
331
+ { executable: process.execPath, args: ['-e',
332
+ 'if ((await import("./a.ts")).value + (await import("./b.ts")).value > 3) process.exit(1)'] },
333
+ ] })
334
+ expect(report.status).toBe('incomplete')
335
+ const applied = report.modules.find(item => item.step?.status === 'applied')
336
+ const failed = report.modules.find(item => item.step?.status === 'failed')
337
+ expect(applied?.step?.checks).toMatchObject([{ status: 'passed' }])
338
+ expect(failed?.step?.checks).toMatchObject([{ status: 'failed' }])
339
+ expect(await readFile(join(context.cwd, applied!.module.files[0]!), 'utf8')).toContain('value = 2')
340
+ expect(await readFile(join(context.cwd, failed!.module.files[0]!), 'utf8')).toContain('value = 1')
341
+ })
342
+
343
+ test('an assigned file cannot be replaced with binary data', async () => {
344
+ const context = await fixture(async (prompt, cwd) => {
345
+ if (prompt.startsWith('PLAN')) return plan
346
+ if (moduleOf(prompt) !== 'a') return unchanged
347
+ await writeFile(join(cwd, 'a.ts'), Buffer.from([0xff, 0x00]))
348
+ return edited()
349
+ })
350
+ const report = await refactorCode({ ...context, checks: [] })
351
+ expect(report.modules[0]?.step).toMatchObject({ status: 'failed', error: 'Assigned files must remain text source: a.ts' })
352
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
353
+ })
354
+
355
+ test('the planner cannot publish assignments after editing its checkout', async () => {
356
+ const context = await fixture(async (prompt, cwd) => {
357
+ if (!prompt.startsWith('PLAN')) return unchanged
358
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
359
+ return plan
360
+ })
361
+ const report = await refactorCode({ ...context, checks: [] })
362
+ expect(report.status).toBe('incomplete')
363
+ expect(report.errors).toEqual(['Module planner modified files'])
364
+ expect(report.plan).toBeNull()
365
+ expect(context.adapter.opened).toHaveLength(2)
366
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
367
+ })
368
+
270
369
  test('the plan checkpoint is published before either module starts', async () => {
271
370
  let directory = ''
272
371
  const context = await fixture(async prompt => {
@@ -1,56 +1,99 @@
1
1
  import { expect, test } from 'bun:test'
2
- import { mkdir, readFile, rm, stat } from 'node:fs/promises'
2
+ import { mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises'
3
3
  import { join } from 'node:path'
4
+ import { git } from '../src/git'
4
5
  import { saveReport } from '../src/report-store'
6
+ import { formatReport } from '../src/report'
5
7
  import type { RefactorReport } from '../src/results'
6
8
  import { withRun } from '../src/run-lifecycle'
7
9
  import { fixture } from './helpers'
8
10
 
9
11
  test('lifecycle holds the lock through body execution and records synchronous observer failures in order', async () => {
10
12
  const context = await fixture()
13
+ const child = join(context.cwd, 'child')
14
+ await mkdir(child)
11
15
  const events: string[] = []
12
16
  let competingBodyRan = false
13
17
  const report = await withRun({
14
18
  ...context,
15
19
  onProgress: event => {
16
20
  events.push(event)
21
+ if (events.length === 1) throw Object.create(null)
17
22
  throw new Error(`Observer ${events.length}`)
18
23
  },
19
24
  }, async (report, progress) => {
20
25
  expect(report.status).toBe('incomplete')
21
26
  expect(events).toEqual([`run: ${report.directory}`])
22
- await expect(withRun(context, async () => { competingBodyRan = true })).rejects.toThrow('Cannot acquire refactor lock')
27
+ for (const cwd of [context.cwd, child]) {
28
+ await expect(withRun({ ...context, cwd }, async () => { competingBodyRan = true })).rejects.toThrow('Cannot acquire refactor lock')
29
+ }
23
30
  expect((await stat(join(context.cwd, '.anureo/refactor/writer.lock'))).isFile()).toBe(true)
24
31
  progress('body: finished')
25
32
  })
26
33
  expect(competingBodyRan).toBe(false)
27
34
  expect(events).toEqual([`run: ${report.directory}`, 'body: finished'])
28
35
  expect(report.status).toBe('completed')
29
- expect(report.progressErrors).toEqual(['Observer 1', 'Observer 2'])
36
+ expect(report.progressErrors).toEqual(['Error details could not be displayed', 'Observer 2'])
30
37
  await expectFinalizedRun(report)
38
+
39
+ const nested = await withRun({ ...context, cwd: child }, async () => {})
40
+ expect(nested.directory).toBe(join(child, '.anureo/refactor', nested.runId))
41
+ await expectFinalizedRun(nested, context.cwd)
31
42
  })
32
43
 
33
44
  test('lifecycle publishes classified body failures before releasing the lock', async () => {
34
45
  const context = await fixture()
35
46
  const report = await withRun(context, async () => {
36
47
  throw Object.assign(new Error('Body unavailable'), {
37
- code: 'RECEIPT_LOST', outcomeUnknown: true, details: { cleanupErrors: ['Release unavailable'] },
48
+ code: 'RECEIPT_LOST', outcomeUnknown: true, retryable: true,
49
+ details: { cleanupErrors: ['Release unavailable'], issues: [
50
+ { path: '/summary', code: 'type', message: 'Omit this detail' },
51
+ { path: ['modules', 0], code: 'invalid_type' },
52
+ { path: [-1], code: 'ignored' },
53
+ ] },
38
54
  })
39
55
  })
40
56
  expect(report.status).toBe('incomplete')
41
57
  expect(report.errors).toEqual(['Body unavailable'])
42
- expect(report.failure).toEqual({ code: 'RECEIPT_LOST', outcomeUnknown: true, cleanupFailed: true })
58
+ expect(report.failure).toEqual({
59
+ code: 'RECEIPT_LOST', outcomeUnknown: true, cleanupFailed: true, retryable: true,
60
+ issues: [{ path: '/summary', code: 'type' }, { path: ['modules', 0], code: 'invalid_type' }],
61
+ })
62
+ expect(formatReport(report)).toContain('Agent execution outcome is unknown')
63
+ expect(formatReport(report)).toContain('Validation issue: /summary [type]')
64
+ expect(formatReport(report)).toContain('Validation issue: ["modules",0] [invalid_type]')
65
+ await expectFinalizedRun(report)
66
+ })
67
+
68
+ test('run artifacts are ignored without a repository ignore rule', async () => {
69
+ const context = await fixture()
70
+ await rm(join(context.cwd, '.gitignore'))
71
+ const report = await withRun(context, async () => {})
43
72
  await expectFinalizedRun(report)
73
+ expect(await git(context.cwd, 'ls-files', '--others', '--exclude-standard')).toBe('')
74
+ })
75
+
76
+ test('storage setup failures retain their filesystem diagnostic and release the checkout lock', async () => {
77
+ const context = await fixture()
78
+ const child = join(context.cwd, 'child')
79
+ const obstruction = join(child, '.anureo')
80
+ await mkdir(child)
81
+ await writeFile(obstruction, '')
82
+ let bodyRan = false
83
+ await expect(withRun({ ...context, cwd: child }, async () => { bodyRan = true }))
84
+ .rejects.toMatchObject({ path: join(obstruction, 'refactor') })
85
+ expect(bodyRan).toBe(false)
86
+ await expect(stat(join(context.cwd, '.anureo/refactor/writer.lock'))).rejects.toMatchObject({ code: 'ENOENT' })
44
87
  })
45
88
 
46
- // Obstruct real paths so failure precedence is exercised without replacing filesystem calls.
89
+ // Obstruct real paths to exercise finalization diagnostics without replacing filesystem calls.
47
90
  test.each([
48
91
  { publicationFails: true, removalFails: false },
49
92
  { publicationFails: false, removalFails: true },
50
93
  { publicationFails: true, removalFails: true },
51
94
  ])('finalization handles publication failure $publicationFails and removal failure $removalFails', async ({ publicationFails, removalFails }) => {
52
95
  const context = await fixture()
53
- const lockPath = join(context.cwd, '.anureo/refactor/writer.lock')
96
+ const lockPath = join(await realpath(context.cwd), '.anureo/refactor/writer.lock')
54
97
  let directory = ''
55
98
  let checkpoint = ''
56
99
  const run = withRun(context, async report => {
@@ -64,7 +107,18 @@ test.each([
64
107
  }
65
108
  })
66
109
  const error = await run.then(() => null, cause => cause)
67
- expect(error).toMatchObject({ path: removalFails ? lockPath : join(directory, 'report.json.tmp') })
110
+ const temporaryReport = join(directory, 'report.json.tmp')
111
+ if (publicationFails && removalFails) {
112
+ expect(error).toBeInstanceOf(AggregateError)
113
+ expect(error.errors).toEqual([
114
+ expect.objectContaining({ path: temporaryReport }),
115
+ expect.objectContaining({ path: lockPath }),
116
+ ])
117
+ expect(error.message).toContain(temporaryReport)
118
+ expect(error.message).toContain(lockPath)
119
+ } else {
120
+ expect(error).toMatchObject({ path: removalFails ? lockPath : temporaryReport })
121
+ }
68
122
  const saved = await readFile(join(directory, 'report.json'), 'utf8')
69
123
  if (publicationFails) expect(saved).toBe(checkpoint)
70
124
  else expect(JSON.parse(saved).status).toBe('completed')
@@ -73,10 +127,10 @@ test.each([
73
127
  })
74
128
 
75
129
  /** Assert the returned record was fully published and writer ownership was released. */
76
- async function expectFinalizedRun(report: RefactorReport): Promise<void> {
130
+ async function expectFinalizedRun(report: RefactorReport, checkout = report.cwd): Promise<void> {
77
131
  const saved = await readFile(join(report.directory, 'report.json'), 'utf8')
78
132
  expect(JSON.parse(saved)).toEqual(report)
79
133
  expect(saved.endsWith('\n')).toBe(true)
80
134
  await expect(stat(join(report.directory, 'report.json.tmp'))).rejects.toMatchObject({ code: 'ENOENT' })
81
- await expect(stat(join(report.cwd, '.anureo/refactor/writer.lock'))).rejects.toMatchObject({ code: 'ENOENT' })
135
+ await expect(stat(join(checkout, '.anureo/refactor/writer.lock'))).rejects.toMatchObject({ code: 'ENOENT' })
82
136
  }
@@ -1,11 +1,14 @@
1
1
  // Verifies Git snapshots and source eligibility against real filesystem entries.
2
- import { expect, test } from 'bun:test'
3
- import { chmod, lstat, mkdir, rm, symlink, writeFile } from 'node:fs/promises'
4
- import { join } from 'node:path'
2
+ import { expect, spyOn, test } from 'bun:test'
3
+ import * as fs from 'node:fs/promises'
4
+ import { chmod, lstat, mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
5
+ import { join, resolve } from 'node:path'
6
+ import { runChecks, validateChecks } from '../src/checks'
5
7
  import { captureTree, changes, treeVersion } from '../src/git-tree'
6
- import { gitFiles } from '../src/git'
8
+ import { git, gitFiles } from '../src/git'
7
9
  import { exec } from '../src/process'
8
10
  import { isSource, isTextSource } from '../src/source-policy'
11
+ import { createAgentWorktree, mergeWorktree, prepareCheckDependencies, removeAgentWorktree, withWorktreeBaseline } from '../src/worktree'
9
12
  import { fixture, temporary } from './helpers'
10
13
 
11
14
  /** Exercise Git visibility separately from snapshot exclusions, including force-added run storage. */
@@ -27,6 +30,114 @@ test('snapshots sort visible files, omit deleted entries and metadata, and retai
27
30
  expect(treeVersion(await captureTree(cwd))).toBe(version)
28
31
  })
29
32
 
33
+ test('Git file discovery preserves an initial BOM and rejects invalid filename bytes', async () => {
34
+ const { cwd } = await fixture()
35
+ await writeFile(join(cwd, '\uFEFFfile.ts'), 'text')
36
+ expect(await gitFiles(cwd)).toContain('\uFEFFfile.ts')
37
+
38
+ const blob = (await git(cwd, 'rev-parse', ':a.ts')).trim()
39
+ const stdin = Buffer.concat([Buffer.from(`100644 ${blob}\t`), Buffer.from([0xff, 0])])
40
+ const child = Bun.spawn(['git', '-C', cwd, 'update-index', '-z', '--index-info'], { stdin })
41
+ expect(await child.exited).toBe(0)
42
+ await expect(gitFiles(cwd)).rejects.toThrow('filename that is not valid UTF-8')
43
+ })
44
+
45
+ test('detached worktrees restore the frozen split index and discover its paths', async () => {
46
+ const { cwd } = await fixture()
47
+ await git(cwd, 'update-index', '--split-index')
48
+ const before = await captureTree(cwd)
49
+ await withWorktreeBaseline(cwd, async baseline => {
50
+ const worktree = await createAgentWorktree(baseline)
51
+ try {
52
+ expect(await captureTree(worktree.root)).toEqual(before)
53
+ } finally {
54
+ await removeAgentWorktree(baseline, worktree)
55
+ }
56
+ })
57
+ })
58
+
59
+ test('validation copies ignored in-repository dependency targets and rebases workspace links', async () => {
60
+ const { cwd } = await fixture()
61
+ const installed = join(cwd, '.deps', 'node_modules')
62
+ await mkdir(installed, { recursive: true })
63
+ await writeFile(join(installed, 'installed.txt'), 'dependency content')
64
+ await symlink(cwd, join(installed, 'workspace'), 'junction')
65
+ await symlink(installed, join(cwd, 'node_modules'), 'junction')
66
+ await writeFile(join(cwd, '.gitignore'), '.anureo/\n.deps/\n')
67
+ await withWorktreeBaseline(cwd, async baseline => {
68
+ const worktree = await createAgentWorktree(baseline)
69
+ try {
70
+ await writeFile(join(worktree.cwd, 'a.ts'), 'candidate content')
71
+ await prepareCheckDependencies(baseline, worktree)
72
+ expect(await readFile(join(worktree.cwd, 'node_modules', 'installed.txt'), 'utf8')).toBe('dependency content')
73
+ expect(await readFile(join(worktree.cwd, 'node_modules', 'workspace', 'a.ts'), 'utf8')).toBe('candidate content')
74
+ } finally {
75
+ await removeAgentWorktree(baseline, worktree)
76
+ }
77
+ })
78
+ })
79
+
80
+ test('shell and argv validation commands use their checkout despite inherited Git selectors', async () => {
81
+ const { cwd } = await fixture()
82
+ await withWorktreeBaseline(cwd, async baseline => {
83
+ const worktree = await createAgentWorktree(baseline)
84
+ const previous = { GIT_DIR: process.env.GIT_DIR, GIT_WORK_TREE: process.env.GIT_WORK_TREE }
85
+ try {
86
+ await writeFile(join(worktree.cwd, 'a.ts'), 'candidate content')
87
+ process.env.GIT_DIR = join(cwd, '.git')
88
+ process.env.GIT_WORK_TREE = cwd
89
+ for (const command of ['git diff --exit-code -- a.ts', { executable: 'git', args: ['diff', '--exit-code', '--', 'a.ts'] }]) {
90
+ const results: Parameters<typeof runChecks>[2] = []
91
+ await expect(runChecks(worktree.cwd, [command], results)).rejects.toThrow('Validation failed')
92
+ expect(results).toMatchObject([{ status: 'failed', output: expect.stringContaining('+candidate content') }])
93
+ }
94
+ } finally {
95
+ for (const [key, value] of Object.entries(previous)) {
96
+ if (value === undefined) delete process.env[key]
97
+ else process.env[key] = value
98
+ }
99
+ await removeAgentWorktree(baseline, worktree)
100
+ }
101
+ })
102
+ })
103
+
104
+ test('validation preflight reports every invalid command and argument position', () => {
105
+ expect(() => validateChecks([' ', { executable: 'git\0', args: ['diff', 'a\0', 'b\0'] }])).toThrow(
106
+ 'check commands must be nonempty\ncheck #1 is blank\ncheck #2 contains NUL\ncheck #2 argument #2 contains NUL\ncheck #2 argument #3 contains NUL',
107
+ )
108
+ })
109
+
110
+ test('merge rolls back a late target edit from its target-relative recovery path', async () => {
111
+ const { cwd } = await fixture()
112
+ const file = 'nested/edit.ts'
113
+ const target = join(cwd, file)
114
+ await mkdir(join(cwd, 'nested'))
115
+ await mkdir(join(cwd, '.anureo', 'refactor'), { recursive: true })
116
+ await writeFile(target, 'baseline content')
117
+ await withWorktreeBaseline(cwd, async baseline => {
118
+ const worktree = await createAgentWorktree(baseline)
119
+ const mergeTarget = resolve(baseline.root, baseline.scope, file)
120
+ const rename = fs.rename
121
+ const moves: string[] = []
122
+ const mock = spyOn(fs, 'rename').mockImplementation(async (from, to) => {
123
+ if (from === mergeTarget) {
124
+ moves.push(String(to))
125
+ await writeFile(from, 'late editor save')
126
+ }
127
+ await rename(from, to)
128
+ })
129
+ try {
130
+ await writeFile(join(worktree.cwd, file), 'candidate content')
131
+ await expect(mergeWorktree(baseline, worktree, [file])).rejects.toThrow(`Source changed during refactor: ${file}`)
132
+ expect(moves).toEqual([expect.stringContaining(join('backups', file))])
133
+ expect(await readFile(target, 'utf8')).toBe('late editor save')
134
+ } finally {
135
+ mock.mockRestore()
136
+ await removeAgentWorktree(baseline, worktree)
137
+ }
138
+ })
139
+ })
140
+
30
141
  /** Compare real file/link edits so content, mode and link text remain independently observable. */
31
142
  test.skipIf(process.platform === 'win32')('snapshot changes track content and modes, and hash symlink text without reading its destination', async () => {
32
143
  const { cwd } = await fixture()