@anureo/refactor 0.3.0 → 0.3.2

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.
Files changed (86) hide show
  1. package/bin/anureo-refactor.ts +5 -0
  2. package/package.json +21 -23
  3. package/src/agent-work.ts +184 -0
  4. package/src/checks.ts +82 -0
  5. package/src/cli.ts +214 -0
  6. package/src/client.ts +93 -0
  7. package/src/errors.ts +70 -0
  8. package/src/git-path.ts +47 -0
  9. package/src/git-tree.ts +55 -0
  10. package/src/git.ts +55 -0
  11. package/src/graph-artifacts.ts +73 -0
  12. package/src/graph.ts +145 -0
  13. package/src/index.ts +40 -0
  14. package/src/options.ts +65 -0
  15. package/src/plan-validation.ts +38 -0
  16. package/src/{process.d.ts → process.ts} +4 -2
  17. package/src/{prompts.js → prompts.ts} +145 -67
  18. package/src/refactor.ts +191 -0
  19. package/src/{report-store.js → report-store.ts} +10 -8
  20. package/src/report.ts +60 -0
  21. package/src/results.ts +83 -0
  22. package/src/run-lifecycle.ts +117 -0
  23. package/src/{schema.d.ts → schema.ts} +29 -23
  24. package/src/source-inventory.ts +17 -0
  25. package/src/source-policy.ts +50 -0
  26. package/src/worktree.ts +322 -0
  27. package/tests/agent-contract.test.ts +180 -0
  28. package/tests/cli.test.ts +378 -0
  29. package/tests/fixtures/acp.mjs +38 -0
  30. package/tests/fixtures/ahp.mjs +50 -0
  31. package/tests/fixtures/answer.mjs +15 -0
  32. package/tests/fixtures/codex.mjs +44 -0
  33. package/tests/fixtures/repograph.ts +24 -0
  34. package/tests/graph.integration.test.ts +110 -0
  35. package/tests/helpers.ts +109 -0
  36. package/tests/refactor.test.ts +536 -0
  37. package/tests/run-lifecycle.test.ts +136 -0
  38. package/tests/tree.test.ts +210 -0
  39. package/tsconfig.json +12 -0
  40. package/LICENSE +0 -201
  41. package/bin/anureo-refactor.d.ts +0 -2
  42. package/bin/anureo-refactor.js +0 -4
  43. package/src/agent-work.d.ts +0 -41
  44. package/src/agent-work.js +0 -131
  45. package/src/checks.d.ts +0 -26
  46. package/src/checks.js +0 -66
  47. package/src/cli.d.ts +0 -27
  48. package/src/cli.js +0 -189
  49. package/src/client.d.ts +0 -26
  50. package/src/client.js +0 -73
  51. package/src/errors.d.ts +0 -9
  52. package/src/errors.js +0 -22
  53. package/src/git-path.d.ts +0 -15
  54. package/src/git-path.js +0 -46
  55. package/src/git-tree.d.ts +0 -18
  56. package/src/git-tree.js +0 -56
  57. package/src/git.d.ts +0 -23
  58. package/src/git.js +0 -40
  59. package/src/graph-artifacts.d.ts +0 -19
  60. package/src/graph-artifacts.js +0 -58
  61. package/src/graph.d.ts +0 -47
  62. package/src/graph.js +0 -71
  63. package/src/index.d.ts +0 -11
  64. package/src/index.js +0 -4
  65. package/src/options.d.ts +0 -55
  66. package/src/options.js +0 -15
  67. package/src/plan-validation.d.ts +0 -10
  68. package/src/plan-validation.js +0 -38
  69. package/src/process.js +0 -10
  70. package/src/prompts.d.ts +0 -47
  71. package/src/refactor.d.ts +0 -17
  72. package/src/refactor.js +0 -168
  73. package/src/report-store.d.ts +0 -9
  74. package/src/report.d.ts +0 -6
  75. package/src/report.js +0 -52
  76. package/src/results.d.ts +0 -80
  77. package/src/results.js +0 -0
  78. package/src/run-lifecycle.d.ts +0 -18
  79. package/src/run-lifecycle.js +0 -100
  80. package/src/schema.js +0 -31
  81. package/src/source-inventory.d.ts +0 -9
  82. package/src/source-inventory.js +0 -17
  83. package/src/source-policy.d.ts +0 -11
  84. package/src/source-policy.js +0 -56
  85. package/src/worktree.d.ts +0 -57
  86. package/src/worktree.js +0 -195
@@ -0,0 +1,536 @@
1
+ // Exercises public sequencing, checkpoints and failure gates through refactorCode.
2
+ import { expect, test } from 'bun:test'
3
+ import { mkdir, readFile, readdir, rename, rm, stat, symlink, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { createClient, HarnessSdkError, type StructuredOutputToolDefinition } from '@anureo/sdk'
6
+ import { createPiAdapter } from '@anureo/adapter-pi'
7
+ import { fakeFactory } from '../../../packages/adapter/pi/tests/fake-host'
8
+ import { startFake } from '../../../packages/adapter/hermes/tests/helpers'
9
+ import { refactorCode, formatReport } from '../src'
10
+ import { captureTree, treeVersion } from '../src/git-tree'
11
+ import { git } from '../src/git'
12
+ import { edited, fixture, graph, kind, moduleOf, plan, temporary, unchanged } from './helpers'
13
+
14
+ const DESIGN = 'DESIGN MODULE BOUNDARIES'
15
+ const MODULE = 'REFACTOR MODULE'
16
+
17
+ test('refactor completes through the Hermes gateway with schema-validated text', async () => {
18
+ const { cwd } = await fixture()
19
+ const server = await startFake('refactor', { FAKE_HERMES_RESPONSE_MODULE: new URL('./fixtures/answer.mjs', import.meta.url).href })
20
+ try {
21
+ const client = await createClient({ adapter: server.adapter(), identity: { adapterId: 'hermes', runtimeConfigId: 'refactor-test' } })
22
+ try {
23
+ const report = await refactorCode({ client, cwd, reviewOnly: true, noGraph: true })
24
+ expect(report.status).toBe('completed')
25
+ expect(report.plan?.modules[0]?.files).toEqual(['a.ts', 'b.ts'])
26
+ expect((await server.state()).inputs).toHaveLength(3)
27
+ } finally { await client.dispose() }
28
+ } finally { await server.dispose() }
29
+ }, 20_000)
30
+
31
+ test('refactor completes through Pi with its structured output tool', async () => {
32
+ const { cwd } = await fixture()
33
+ const fake = fakeFactory(host => {
34
+ let tool: StructuredOutputToolDefinition | undefined
35
+ Object.assign(host, { async setOutputTool(next?: StructuredOutputToolDefinition) { tool = next } })
36
+ host.script = async (host, prompt) => {
37
+ const value = prompt.startsWith('PLAN') ? plan : unchanged
38
+ expect(await tool?.execute(value)).toMatchObject({ accepted: true })
39
+ await host.assistant('Submitted the result')
40
+ }
41
+ })
42
+ const client = await createClient({
43
+ adapter: createPiAdapter({ version: '1.5.2', createHost: fake.factory }),
44
+ identity: { adapterId: 'pi', runtimeConfigId: 'refactor-test' },
45
+ })
46
+ try {
47
+ const report = await refactorCode({ client, cwd, noGraph: true, readPermissionMode: 'read-only', editPermissionMode: 'agent-full-access' })
48
+ expect(report.status).toBe('completed')
49
+ expect(report.plan).toEqual(plan)
50
+ } finally { await client.dispose() }
51
+ })
52
+
53
+ /** Require argument failure before filesystem preflight can mask it; fixture cleanup owns the client. */
54
+ test('blank library checks fail before repository setup or agent dispatch', async () => {
55
+ const context = await fixture()
56
+ await expect(refactorCode({ ...context, cwd: join(context.cwd, 'missing'), checks: [' '] })).rejects.toThrow('check commands must be nonempty')
57
+ expect(context.prompts).toHaveLength(0)
58
+ expect(await stat(join(context.cwd, '.anureo')).catch(() => null)).toBeNull()
59
+ })
60
+
61
+ test('each agent has a worktree and module sessions overlap on the same post-design baseline', async () => {
62
+ let exports = 0
63
+ const order: string[] = []
64
+ const worktrees: string[] = []
65
+ const modulesReady = Promise.withResolvers<void>()
66
+ let runningModules = 0
67
+ const context = await fixture(async (prompt, cwd) => {
68
+ worktrees.push(cwd)
69
+ expect((await git(cwd, 'rev-parse', '--show-toplevel')).trim()).toBe(cwd)
70
+ const module = moduleOf(prompt)
71
+ order.push(module ? `module:${module}` : kind(prompt))
72
+ if (prompt.startsWith(DESIGN)) {
73
+ expect(await readFile(join(cwd, 'README.md'), 'utf8')).toBe('untracked input')
74
+ expect(await readFile(join(cwd, 'a.ts'), 'utf8')).toContain('unstaged')
75
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 1 // design\n')
76
+ return edited()
77
+ }
78
+ expect(await readFile(join(cwd, 'a.ts'), 'utf8')).toContain('// design')
79
+ if (prompt.startsWith('PLAN')) return plan
80
+
81
+ if (++runningModules === 2) modulesReady.resolve()
82
+ await modulesReady.promise
83
+ await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
84
+ const other = module === 'a' ? 'b' : 'a'
85
+ expect(await readFile(join(cwd, `${other}.ts`), 'utf8')).toContain('value = 1')
86
+ return edited()
87
+ })
88
+ await writeFile(join(context.cwd, 'README.md'), 'untracked input')
89
+ await writeFile(join(context.cwd, 'a.ts'), 'export const value = 1 // unstaged\n')
90
+ const indexBefore = await git(context.cwd, 'ls-files', '--stage')
91
+ const report = await refactorCode({
92
+ ...context, checks: ['git diff --exit-code -- .gitignore'],
93
+ readPermissionMode: 'read-only', editPermissionMode: 'agent-full-access',
94
+ graphLoader: async () => { exports++; return graph(context.cwd) },
95
+ })
96
+ expect(report.status).toBe('completed')
97
+ expect(order.slice(0, 2)).toEqual([DESIGN, 'PLAN REFACTOR MODULES'])
98
+ expect(order.slice(2).sort()).toEqual(['module:a', 'module:b'])
99
+ expect(new Set(worktrees).size).toBe(4)
100
+ expect(worktrees).not.toContain(context.cwd)
101
+ expect(exports).toBe(2)
102
+ expect(report.design).toMatchObject({ status: 'applied', changedFiles: ['a.ts'] })
103
+ expect(report.modules.map(item => [item.module.id, item.step?.status])).toEqual([['a', 'applied'], ['b', 'applied']])
104
+ expect(report.modules.every(item => item.step?.checks[0]?.status === 'passed')).toBe(true)
105
+ for (const file of ['a.ts', 'b.ts']) expect(await readFile(join(context.cwd, file), 'utf8')).toContain('value = 2')
106
+ for (const cwd of worktrees) expect(await stat(cwd).catch(() => null)).toBeNull()
107
+ expect((await git(context.cwd, 'worktree', 'list', '--porcelain')).match(/^worktree /gm)).toHaveLength(1)
108
+ expect(await git(context.cwd, 'ls-files', '--stage')).toBe(indexBefore)
109
+ expect(context.adapter.opened.filter(session => session.permissionMode === 'read-only')).toHaveLength(1)
110
+ expect(context.adapter.opened.filter(session => session.permissionMode === 'agent-full-access')).toHaveLength(3)
111
+ expect(context.prompts.find(prompt => prompt.startsWith(MODULE))).toContain('Cross-module design step already done in this run: Edited')
112
+ expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
113
+ expect(await stat(join(context.cwd, '.anureo/refactor/writer.lock')).catch(() => null)).toBeNull()
114
+ })
115
+
116
+ /** Inspect scripted prompts without edits so review instructions and report wording stay aligned. */
117
+ test('prompts name the problem catalog, the graph guide and the mode', async () => {
118
+ const context = await fixture()
119
+ const report = await refactorCode({ ...context, reviewOnly: true })
120
+ expect(report.status).toBe('completed')
121
+ const design = context.prompts.find(prompt => prompt.startsWith(DESIGN))!
122
+ const module = context.prompts.find(prompt => prompt.startsWith(MODULE))!
123
+ for (const prompt of [design, module]) {
124
+ expect(prompt).toContain('MODE: READ ONLY')
125
+ expect(prompt).toContain('Graph artifact:')
126
+ expect(prompt).toContain('local_name')
127
+ expect(prompt).toContain('Optimize for the cost of understanding and changing the code.')
128
+ expect(prompt.replace(/\s+/g, ' ')).toContain('verify call targets, imports, aliases, re-exports and callback registration/invocation in source')
129
+ expect(prompt).toContain('Missing edges do not prove absence of calls')
130
+ }
131
+ expect(design).toContain('Wrong dependency direction')
132
+ expect(design).toContain('Import cycles between files')
133
+ expect(module).toContain('shares mutable variables across them')
134
+ expect(module).toContain('five or more positional parameters')
135
+ for (const prompt of [design, module]) {
136
+ expect(prompt).toContain('Comment WHY, not WHAT')
137
+ expect(prompt).toContain('doc comment stating')
138
+ expect(prompt).toContain('Documentation conventions and tags:')
139
+ expect(prompt).toContain('re-export chains')
140
+ expect(prompt).toContain('Declaration order:')
141
+ }
142
+ expect(design).toContain('Design documentation scope:')
143
+ expect(module).toContain('Module documentation scope:')
144
+ expect(module).toContain('including declarations\nwhose implementation stays unchanged')
145
+ expect(formatReport(report)).toContain('review only')
146
+ })
147
+
148
+ /** Verify explicit edit checks reach the agent even when its response leaves the tree unchanged. */
149
+ test('edit mode states how to edit and lists the validation commands', async () => {
150
+ const context = await fixture()
151
+ await refactorCode({ ...context, checks: ['true'] })
152
+ const module = context.prompts.find(prompt => prompt.startsWith(MODULE))!
153
+ expect(module).toContain('MODE: EDIT')
154
+ expect(module).toContain('Validation commands: ["true"]')
155
+ })
156
+
157
+ /** Feed malformed assignments through the real planner boundary; no module may start after rejection. */
158
+ test.each([
159
+ { ...plan, modules: [plan.modules[0]] },
160
+ { ...plan, modules: [plan.modules[0], plan.modules[0]] },
161
+ { ...plan, modules: [plan.modules[0], { ...plan.modules[1], id: 'A' }] },
162
+ { ...plan, modules: [{ ...plan.modules[0], files: ['a.ts', 'not-in-inventory.ts'] }, plan.modules[1]] },
163
+ ])('rejects missing, duplicate and invented inventory assignments before any module agent', async invalid => {
164
+ const context = await fixture(prompt => prompt.startsWith('PLAN') ? invalid : unchanged)
165
+ const report = await refactorCode({ ...context, checks: [] })
166
+ expect(report.status).toBe('incomplete')
167
+ expect(context.prompts.some(prompt => prompt.startsWith(MODULE))).toBe(false)
168
+ })
169
+
170
+ /** Inject an unknown SDK outcome after a real edit; planning stops and the target retains its original contents. */
171
+ test('a failed design step stops before planning and records its observed edit', async () => {
172
+ const context = await fixture(async (_prompt, cwd) => {
173
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
174
+ return new HarnessSdkError('RECEIPT_LOST', 'Unknown', false, true)
175
+ })
176
+ const report = await refactorCode({ ...context, checks: [] })
177
+ expect(report.status).toBe('incomplete')
178
+ expect(report.design).toMatchObject({ status: 'failed', changedFiles: ['a.ts'], failure: { code: 'RECEIPT_LOST', outcomeUnknown: true } })
179
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toBe('export const value = 1\n')
180
+ expect(context.prompts).toHaveLength(1)
181
+ expect(formatReport(report)).toContain('execution outcome is unknown')
182
+ })
183
+
184
+ test('a failed module leaves the target untouched for its assignment while siblings merge', async () => {
185
+ const context = await fixture(async (prompt, cwd) => {
186
+ if (prompt.startsWith('PLAN')) return plan
187
+ const module = moduleOf(prompt)
188
+ if (!module) return unchanged
189
+ await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
190
+ return module === 'a' ? new HarnessSdkError('NATIVE_FAILED', 'Writer failed') : edited()
191
+ })
192
+ const report = await refactorCode({ ...context, checks: [] })
193
+ expect(report.status).toBe('incomplete')
194
+ expect(report.modules[0]?.step).toMatchObject({ status: 'failed', changedFiles: ['a.ts'] })
195
+ expect(report.modules[1]?.step).toMatchObject({ status: 'applied', changedFiles: ['b.ts'] })
196
+ expect(await readdir(report.directory)).not.toContain('module-a.patch')
197
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
198
+ expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toContain('value = 2')
199
+ expect((await git(context.cwd, 'worktree', 'list', '--porcelain')).match(/^worktree /gm)).toHaveLength(1)
200
+ })
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
+
255
+ test('verified work merges while an earlier agent is still running, and competing additions fail', async () => {
256
+ const merged = Promise.withResolvers<void>()
257
+ const context = await fixture(async (prompt, cwd) => {
258
+ if (prompt.startsWith('PLAN')) return plan
259
+ const module = moduleOf(prompt)
260
+ if (!module) return unchanged
261
+ if (module === 'a') {
262
+ await merged.promise
263
+ expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toContain('value = 2')
264
+ expect(await readFile(join(cwd, 'b.ts'), 'utf8')).toContain('value = 1')
265
+ }
266
+ await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
267
+ await writeFile(join(cwd, 'shared.ts'), `export const owner = '${module}'\n`)
268
+ return edited()
269
+ })
270
+ const report = await refactorCode({
271
+ ...context, concurrency: 2,
272
+ checks: [{ executable: process.execPath, args: ['-e', 'if (!(await Bun.file("shared.ts").text()).includes("owner")) process.exit(1)'] }],
273
+ onProgress: event => { if (event === 'module/b: applied') merged.resolve() },
274
+ })
275
+ expect(report.status).toBe('incomplete')
276
+ expect(report.modules[0]?.step).toMatchObject({ status: 'failed', error: 'Source changed during refactor: shared.ts' })
277
+ expect(report.modules[1]?.step).toMatchObject({ status: 'applied', checks: [{ status: 'passed' }] })
278
+ expect(await readFile(join(context.cwd, 'shared.ts'), 'utf8')).toContain("owner = 'b'")
279
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
280
+ })
281
+
282
+ test('edits to another module and review-only writes stay out of the target checkout', async () => {
283
+ const context = await fixture(async (prompt, cwd) => {
284
+ if (prompt.startsWith('PLAN')) return plan
285
+ if (moduleOf(prompt) !== 'a') return unchanged
286
+ await writeFile(join(cwd, 'b.ts'), 'export const value = 2\n')
287
+ return edited()
288
+ })
289
+ for (const reviewOnly of [false, true]) {
290
+ const report = await refactorCode({ ...context, reviewOnly, checks: [] })
291
+ expect(report.status).toBe('incomplete')
292
+ expect(report.modules[0]?.step).toMatchObject({
293
+ status: 'failed', changedFiles: ['b.ts'],
294
+ error: reviewOnly ? 'Review-only agent modified files' : 'Module edited paths outside its assignment: b.ts',
295
+ })
296
+ expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toContain('value = 1')
297
+ }
298
+ })
299
+
300
+ test('failed validation retains its output and prevents unverified changes from reaching the target', async () => {
301
+ const context = await fixture(async (prompt, cwd) => {
302
+ if (prompt.startsWith('PLAN')) return plan
303
+ const module = moduleOf(prompt)
304
+ if (!module) return unchanged
305
+ await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
306
+ return edited()
307
+ })
308
+ const report = await refactorCode({ ...context, checks: [
309
+ { executable: process.execPath, args: ['-e', 'if ((await Bun.file("a.ts").text()).includes("value = 2")) { console.error("validation-broken"); process.exit(7) }'] },
310
+ { executable: process.execPath, args: ['-e', 'if (!(await Bun.file("b.ts").text()).includes("value = 2")) process.exit(8)'] },
311
+ ] })
312
+ expect(report.status).toBe('incomplete')
313
+ expect(report.modules[0]?.step).toMatchObject({
314
+ status: 'failed',
315
+ checks: [{ status: 'failed', output: expect.stringContaining('validation-broken') }],
316
+ })
317
+ expect(report.modules[1]?.step).toMatchObject({ status: 'applied', checks: [{ status: 'passed' }, { status: 'passed' }] })
318
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toBe('export const value = 1\n')
319
+ expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toBe('export const value = 2\n')
320
+ })
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
+
369
+ test('the plan checkpoint is published before either module starts', async () => {
370
+ let directory = ''
371
+ const context = await fixture(async prompt => {
372
+ if (prompt.startsWith(DESIGN)) return unchanged
373
+ const saved = JSON.parse(await readFile(join(directory, 'report.json'), 'utf8'))
374
+ expect(saved.design.status).toBe('unchanged')
375
+ if (prompt.startsWith('PLAN')) {
376
+ expect(saved.plan).toBeNull()
377
+ return plan
378
+ }
379
+ expect(saved.plan).toEqual(plan)
380
+ expect(saved.modules).toEqual([])
381
+ return unchanged
382
+ })
383
+ const report = await refactorCode({ ...context, checks: [],
384
+ onProgress: event => { if (event.startsWith('run: ')) directory = event.slice('run: '.length) },
385
+ })
386
+ expect(report.status).toBe('completed')
387
+ })
388
+
389
+ test('a failed post-design graph refresh prevents module dispatch and releases the lock', async () => {
390
+ const context = await fixture(async (prompt, cwd) => {
391
+ if (prompt.startsWith('PLAN')) return plan
392
+ if (prompt.startsWith(DESIGN)) {
393
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
394
+ return edited()
395
+ }
396
+ return unchanged
397
+ })
398
+ let exports = 0
399
+ const report = await refactorCode({ ...context, checks: [],
400
+ graphLoader: async () => {
401
+ if (++exports === 2) throw new Error('Graph refresh unavailable')
402
+ return graph(context.cwd)
403
+ },
404
+ })
405
+ expect(report.status).toBe('incomplete')
406
+ expect(report.errors).toEqual(['Graph refresh unavailable'])
407
+ expect(report.modules).toEqual([])
408
+ expect(context.prompts.some(prompt => prompt.startsWith(MODULE))).toBe(false)
409
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toBe('export const value = 2\n')
410
+ expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
411
+ expect(await stat(join(context.cwd, '.anureo/refactor/writer.lock')).catch(() => null)).toBeNull()
412
+ })
413
+
414
+ /** Discover real package scripts and confirm typecheck failure prevents the test script from running. */
415
+ test('default validation discovers root package scripts and stops on a failing typecheck', async () => {
416
+ const context = await fixture(async (prompt, cwd) => {
417
+ if (prompt.startsWith('PLAN')) return plan
418
+ if (moduleOf(prompt) === 'a') await writeFile(join(cwd, 'a.ts'), 'const named = 1; export { named as value }\n')
419
+ return moduleOf(prompt) === 'a' ? edited() : unchanged
420
+ })
421
+ await writeFile(join(context.cwd, 'package.json'), JSON.stringify({ packageManager: 'bun@1.4.2', scripts: { typecheck: 'exit 9', test: 'exit 0' } }))
422
+ const report = await refactorCode(context)
423
+ expect(report.status).toBe('incomplete')
424
+ expect(report.modules[0]?.step?.checks).toMatchObject([{ command: 'bun run typecheck', status: 'failed' }])
425
+ })
426
+
427
+ test('validation resolves installed workspace links to edited files in the agent worktree', async () => {
428
+ const context = await fixture(async (prompt, cwd) => {
429
+ if (prompt.startsWith('PLAN')) return plan
430
+ if (moduleOf(prompt) !== 'a') return unchanged
431
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
432
+ return edited()
433
+ })
434
+ await mkdir(join(context.cwd, 'node_modules'))
435
+ await symlink(context.cwd, join(context.cwd, 'node_modules', 'workspace'), 'junction')
436
+ await writeFile(join(context.cwd, '.gitignore'), '.anureo/\nnode_modules/\n')
437
+ const report = await refactorCode({ ...context, checks: [
438
+ { executable: process.execPath, args: ['-e', 'if ((await import("workspace/a.ts")).value !== 2) process.exit(9)'] },
439
+ ] })
440
+ expect(report.modules[0]?.step).toMatchObject({ status: 'applied', checks: [{ status: 'passed' }] })
441
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 2')
442
+ })
443
+
444
+ test('a passing command that rewrites agent source prevents the merge', async () => {
445
+ const context = await fixture(async (prompt, cwd) => {
446
+ if (prompt.startsWith('PLAN')) return plan
447
+ if (moduleOf(prompt) !== 'a') return unchanged
448
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
449
+ return edited()
450
+ })
451
+ const report = await refactorCode({ ...context, checks: [
452
+ { executable: process.execPath, args: ['-e', 'await Bun.write("a.ts", "export const value = 3\\n")'] },
453
+ ] })
454
+ expect(report.modules[0]?.step).toMatchObject({ status: 'failed', error: 'Validation modified source files: a.ts' })
455
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
456
+ })
457
+
458
+ /** Move/add files during design so the host diff and post-design inventory use observed paths. */
459
+ test('moves and new files need no declaration and are reported from the real diff', async () => {
460
+ const context = await fixture(async (prompt, cwd) => {
461
+ if (prompt.startsWith('PLAN')) return { ...plan, modules: [{ ...plan.modules[0], files: ['moved.ts', 'types.ts'] }, plan.modules[1]] }
462
+ if (prompt.startsWith(DESIGN)) {
463
+ await rename(join(cwd, 'a.ts'), join(cwd, 'moved.ts'))
464
+ await writeFile(join(cwd, 'types.ts'), 'export type T = 1\n')
465
+ return edited('Moved a.ts, added types.ts')
466
+ }
467
+ return unchanged
468
+ })
469
+ const report = await refactorCode({ ...context, checks: [] })
470
+ expect(report.status).toBe('completed')
471
+ expect(report.design?.changedFiles).toEqual(['a.ts', 'moved.ts', 'types.ts'])
472
+ expect(report.plan).not.toBeNull()
473
+ })
474
+
475
+ /** Add a design-time source and require its inclusion in the subsequent planning prompt. */
476
+ test('the plan is made from the tree after the design step', async () => {
477
+ const context = await fixture(async (prompt, cwd) => {
478
+ if (prompt.startsWith(DESIGN)) { await writeFile(join(cwd, 'extra.ts'), 'export const extra = 1\n'); return edited() }
479
+ if (prompt.startsWith('PLAN')) return { ...plan, modules: [{ ...plan.modules[0], files: ['a.ts', 'extra.ts'] }, plan.modules[1]] }
480
+ return unchanged
481
+ })
482
+ const report = await refactorCode({ ...context, checks: [] })
483
+ expect(report.status).toBe('completed')
484
+ expect(context.prompts.find(prompt => prompt.startsWith('PLAN'))).toContain('"extra.ts"')
485
+ })
486
+
487
+ /** Use an external fixture path to ensure source safety rejects links before graph or agent work. */
488
+ test.skipIf(process.platform === 'win32')('a symlinked source file is rejected before any agent runs', async () => {
489
+ const outside = await temporary()
490
+ const context = await fixture()
491
+ await writeFile(join(outside, 'x.ts'), 'export const x = 1\n')
492
+ await symlink(join(outside, 'x.ts'), join(context.cwd, 'linked.ts'))
493
+ const report = await refactorCode({ ...context })
494
+ expect(report.status).toBe('incomplete')
495
+ expect(report.errors.join()).toContain('Symlink')
496
+ expect(context.prompts).toHaveLength(0)
497
+ })
498
+
499
+ /** Precreate a competing writer lock; acquisition failure must reject without dispatching agents. */
500
+ test('one cooperating process owns the tree', async () => {
501
+ const context = await fixture()
502
+ await mkdir(join(context.cwd, '.anureo/refactor'), { recursive: true })
503
+ await writeFile(join(context.cwd, '.anureo/refactor/writer.lock'), 'active')
504
+ await expect(refactorCode(context)).rejects.toThrow('Cannot acquire refactor lock')
505
+ expect(context.prompts).toHaveLength(0)
506
+ })
507
+
508
+ /** Throw from the observer and supply a failing check; unchanged steps must still complete without edits. */
509
+ test('progress errors are observational and unchanged steps run no checks', async () => {
510
+ const context = await fixture()
511
+ const before = treeVersion(await captureTree(context.cwd))
512
+ const report = await refactorCode({ ...context, checks: ['exit 1'], onProgress: () => { throw new Error('Sink unavailable') } })
513
+ expect(report.status).toBe('completed')
514
+ expect(report.modules.map(item => item.step?.status)).toEqual(['unchanged', 'unchanged'])
515
+ expect(report.progressErrors.length).toBeGreaterThan(0)
516
+ expect(treeVersion(await captureTree(context.cwd))).toBe(before)
517
+ })
518
+
519
+ /** Target a nested Git directory to verify inventory and graph context do not expand to the repository root. */
520
+ test('a subdirectory of a Git repository is a valid target and only its files are in scope', async () => {
521
+ const context = await fixture(async (prompt, cwd) => {
522
+ expect(await readFile(join(cwd, '..', 'a.ts'), 'utf8')).toContain('value = 1')
523
+ if (prompt.startsWith('PLAN')) return plan
524
+ if (moduleOf(prompt) !== 'a') return unchanged
525
+ await writeFile(join(cwd, 'a.ts'), 'export const value = 3\n')
526
+ return edited()
527
+ })
528
+ await mkdir(join(context.cwd, 'pkg'))
529
+ const cwd = join(context.cwd, 'pkg')
530
+ await Promise.all(['a.ts', 'b.ts'].map(file => writeFile(join(cwd, file), 'export const value = 1\n')))
531
+ const report = await refactorCode({ ...context, cwd, checks: [], graphLoader: async () => graph(cwd) })
532
+ expect(report.status).toBe('completed')
533
+ expect(await readFile(join(cwd, 'a.ts'), 'utf8')).toContain('value = 3')
534
+ expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
535
+ expect(JSON.parse(context.prompts.find(prompt => prompt.startsWith('PLAN'))!.split('Inventory: ')[1]!.split('\n')[0]!)).toEqual(['a.ts', 'b.ts'])
536
+ })