@anureo/refactor 0.3.0 → 0.3.1

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 (85) hide show
  1. package/bin/anureo-refactor.ts +5 -0
  2. package/package.json +21 -23
  3. package/src/agent-work.ts +132 -0
  4. package/src/checks.ts +70 -0
  5. package/src/cli.ts +214 -0
  6. package/src/client.ts +91 -0
  7. package/src/errors.ts +33 -0
  8. package/src/git-path.ts +47 -0
  9. package/src/git-tree.ts +55 -0
  10. package/src/git.ts +42 -0
  11. package/src/graph-artifacts.ts +70 -0
  12. package/src/graph.ts +88 -0
  13. package/src/index.ts +12 -0
  14. package/src/options.ts +65 -0
  15. package/src/plan-validation.ts +39 -0
  16. package/src/{process.d.ts → process.ts} +4 -2
  17. package/src/{prompts.js → prompts.ts} +162 -62
  18. package/src/refactor.ts +186 -0
  19. package/src/{report-store.js → report-store.ts} +9 -7
  20. package/src/report.ts +44 -0
  21. package/src/results.ts +81 -0
  22. package/src/run-lifecycle.ts +117 -0
  23. package/src/{schema.d.ts → schema.ts} +28 -22
  24. package/src/source-inventory.ts +17 -0
  25. package/src/{source-policy.js → source-policy.ts} +31 -37
  26. package/src/worktree.ts +287 -0
  27. package/tests/agent-contract.test.ts +188 -0
  28. package/tests/cli.test.ts +313 -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 +17 -0
  34. package/tests/graph.integration.test.ts +37 -0
  35. package/tests/helpers.ts +105 -0
  36. package/tests/refactor.test.ts +437 -0
  37. package/tests/run-lifecycle.test.ts +82 -0
  38. package/tests/tree.test.ts +99 -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/worktree.d.ts +0 -57
  85. package/src/worktree.js +0 -195
@@ -0,0 +1,313 @@
1
+ // Verifies CLI exit codes, client ownership and subprocess boundaries with scripted harnesses.
2
+ import { expect, spyOn, test } from 'bun:test'
3
+ import { cp, mkdir, readFile, realpath, symlink, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { createRequire } from 'node:module'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { runCli } from '../src/cli'
8
+ import { refactorHarnesses } from '../src/client'
9
+ import { loadGraph } from '../src/graph'
10
+ import { exec } from '../src/process'
11
+ import { edited, fixture, moduleOf, plan, temporary, unchanged } from './helpers'
12
+
13
+ /** Exercise argument/help precedence without acquiring a client; failures remain CLI diagnostics. */
14
+ test('help and invalid arguments do not construct a backend', async () => {
15
+ let created = 0
16
+ let errors = ''
17
+ const dependencies = {
18
+ stdout: () => {}, stderr: (text: string) => { errors += text },
19
+ createClient: async () => { created++; throw new Error('Unexpected backend') },
20
+ }
21
+ expect(await runCli(['--help'], dependencies)).toBe(0)
22
+ expect(await runCli(['--help', 'a', 'b', '--check', ' '], dependencies)).toBe(0)
23
+ for (const args of [
24
+ ['--unknown'], ['--concurrency', '0'], ['--concurrency', '1.5'], ['a', 'b'], ['--check', ' '],
25
+ ['--check-argv', '[]'], ['--check-argv', '["git", 1]'], ['--no-graph', '--repograph', 'other.ts'],
26
+ ['--harness', 'unknown'], ['--harness', 'acp'], ['--harness-url', 'ws://localhost:3000'],
27
+ ['--harness', 'ahp', '--harness-command', 'peer', '--harness-url', 'ws://localhost:3000'],
28
+ ]) {
29
+ expect(await runCli(args, dependencies)).toBe(2)
30
+ }
31
+ expect(created).toBe(0)
32
+ expect(errors).toContain('anureo-refactor: --concurrency must be a positive integer\n')
33
+ expect(errors).toContain('anureo-refactor: --check commands must be nonempty\n')
34
+ })
35
+
36
+ test('CLI limits concurrent module sessions while running every planned module', async () => {
37
+ let active = 0
38
+ let peak = 0
39
+ const modules = Array.from({ length: 10 }, (_, index) => ({
40
+ id: `module-${index}`, name: `Module ${index}`, description: 'Fixture module',
41
+ files: [`module-${index}.ts`],
42
+ }))
43
+ const firstWorkersReady = Promise.withResolvers<void>()
44
+ const context = await fixture(async prompt => {
45
+ if (prompt.startsWith('PLAN')) return { summary: plan.summary, modules }
46
+ if (!moduleOf(prompt)) return unchanged
47
+ peak = Math.max(peak, ++active)
48
+ if (active === 8) firstWorkersReady.resolve()
49
+ await firstWorkersReady.promise
50
+ active--
51
+ return unchanged
52
+ })
53
+ await Promise.all(modules.map(module => writeFile(join(context.cwd, module.files[0]!), 'export {}\n')))
54
+ let output = ''
55
+ const code = await runCli([
56
+ context.cwd, '--include', 'module-*.ts', '--concurrency', '8', '--review-only', '--no-graph', '--json',
57
+ ], {
58
+ stdout: text => { output += text }, stderr: () => {}, createClient: async () => context.client,
59
+ })
60
+ expect({ code, errors: JSON.parse(output).errors }).toEqual({ code: 0, errors: [] })
61
+ expect(peak).toBe(8)
62
+ expect(JSON.parse(output).modules.map((result: { module: { id: string } }) => result.module.id))
63
+ .toEqual(modules.map(module => module.id))
64
+ })
65
+
66
+ test.each([...refactorHarnesses])('CLI dispatches %s with the matching permission and model settings', async id => {
67
+ const context = await fixture()
68
+ const transport = id === 'acp' ? ['--harness-command', 'agent', '--harness-arg=--stdio']
69
+ : id === 'ahp' ? ['--harness-url', 'ws://localhost:3000'] : []
70
+ const code = await runCli([context.cwd, '--harness', id, ...transport, '--review-only'], {
71
+ ...context, env: { CODEX_MODEL: 'codex-fixture' }, stdout: () => {}, stderr: () => {},
72
+ createClient: async (cwd, selection) => {
73
+ expect(cwd).toBe(context.cwd)
74
+ expect(selection.id).toBe(id)
75
+ if (id === 'acp') expect(selection).toMatchObject({ command: 'agent', args: ['--stdio'] })
76
+ if (id === 'ahp') expect(selection.url).toBe('ws://localhost:3000')
77
+ return context.client
78
+ },
79
+ })
80
+ expect(code).toBe(0)
81
+ const mode = id === 'claude' ? 'plan' : id === 'codex' || id === 'pi' ? 'read-only' : undefined
82
+ expect(context.adapter.opened).toHaveLength(4)
83
+ for (const session of context.adapter.opened) {
84
+ expect(session.permissionMode).toBe(mode)
85
+ expect(session.model).toBe(id === 'codex' ? 'codex-fixture' : undefined)
86
+ }
87
+ expect(context.adapter.disposeCount).toBe(1)
88
+ })
89
+
90
+ test.each(['acp', 'ahp'])('installed CLI completes a run over a scripted %s stdio peer', async id => {
91
+ const target = await temporary()
92
+ await exec('git', ['init', '-q', target])
93
+ await writeFile(join(target, 'task.custom'), 'do work\n')
94
+ const peer = fileURLToPath(new URL(`./fixtures/${id}.mjs`, import.meta.url))
95
+ const { stdout } = await runInstalledCli([
96
+ target, '--harness', id, '--harness-command', process.execPath, '--harness-arg', peer,
97
+ '--no-graph', '--review-only', '--json',
98
+ ])
99
+ expect(JSON.parse(stdout)).toMatchObject({
100
+ status: 'completed', plan: { modules: [{ files: ['task.custom'] }] },
101
+ modules: [{ step: { status: 'unchanged' } }],
102
+ })
103
+ }, 25_000)
104
+
105
+ test('installed CLI completes a run through the Claude SDK with native structured output', async () => {
106
+ const target = await temporary()
107
+ const state = await temporary()
108
+ await exec('git', ['init', '-q', target])
109
+ await writeFile(join(target, 'script.rb'), 'puts "hello"\n')
110
+ const claude = fileURLToPath(new URL('../../../packages/adapter/claude/tests/fixtures/fake-claude.mjs', import.meta.url))
111
+ const answer = fileURLToPath(new URL('./fixtures/answer.mjs', import.meta.url))
112
+ const { stdout } = await runInstalledCli([
113
+ target, '--harness', 'claude', '--no-graph', '--review-only', '--json',
114
+ ], { env: { ...process.env, CLAUDE_BIN: claude, CLAUDE_CONFIG_DIR: state, FAKE_STRUCTURED_ANSWER: answer } })
115
+ expect(JSON.parse(stdout)).toMatchObject({
116
+ status: 'completed', plan: { modules: [{ files: ['script.rb'] }] },
117
+ })
118
+ }, 25_000)
119
+
120
+ /** Run scripted agents through the CLI; the shared fixture removes the repository after assertions. */
121
+ test('CLI reports completion and owns client cleanup', async () => {
122
+ const context = await fixture(prompt => prompt.startsWith('PLAN') ? plan : moduleOf(prompt) === 'a' ? edited() : unchanged)
123
+ let output = ''
124
+ const code = await runCli([context.cwd, '--review-only', '--json'], {
125
+ ...context, createClient: async () => context.client,
126
+ stdout: text => { output += text }, stderr: () => {},
127
+ })
128
+ expect(code).toBe(0)
129
+ expect(JSON.parse(output)).toMatchObject({ status: 'completed', reviewOnly: true })
130
+ expect(context.adapter.disposeCount).toBe(1)
131
+ })
132
+
133
+ /** Check primary/cleanup error precedence and awaited disposal after preflight or report output.
134
+ * Each case uses a real scripted client; the one-shot disposal override releases it before failing. */
135
+ test.each([
136
+ { failure: 'none', cleanupError: null },
137
+ { failure: 'none', cleanupError: 'Disposal unavailable' },
138
+ { failure: 'incomplete', cleanupError: 'Disposal unavailable' },
139
+ { failure: 'output', cleanupError: null },
140
+ { failure: 'output', cleanupError: 'Disposal unavailable' },
141
+ { failure: 'preflight', cleanupError: null },
142
+ { failure: 'preflight', cleanupError: 'Disposal unavailable' },
143
+ ])('CLI handles $failure failure with cleanup error $cleanupError', async ({ failure, cleanupError }) => {
144
+ const context = await fixture()
145
+ const events: string[] = []
146
+ let output = ''
147
+ let errors = ''
148
+ const dispose = context.client.dispose.bind(context.client)
149
+ /** Release actual SDK resources before injecting a rejection, leaving shared cleanup safe to retry. */
150
+ const disposal = spyOn(context.client, 'dispose').mockImplementationOnce(async () => {
151
+ await dispose()
152
+ events.push('disposed')
153
+ if (cleanupError) throw new Error(cleanupError)
154
+ })
155
+ try {
156
+ const cwd = failure === 'preflight' ? join(context.cwd, 'missing') : context.cwd
157
+ const code = await runCli([cwd, '--json'], {
158
+ ...context, createClient: async () => context.client,
159
+ graphLoader: failure === 'incomplete' ? async () => { throw new Error('Graph unavailable') } : context.graphLoader,
160
+ /** Record report delivery before optionally failing the sink to exercise post-run cleanup. */
161
+ stdout: text => {
162
+ output += text
163
+ events.push('report')
164
+ if (failure === 'output') throw new Error('Output unavailable')
165
+ },
166
+ stderr: text => { errors += text },
167
+ })
168
+ expect(code).toBe(failure === 'none' && !cleanupError ? 0 : 2)
169
+ expect(events).toEqual(failure === 'preflight' ? ['disposed'] : ['report', 'disposed'])
170
+ expect(disposal).toHaveBeenCalledTimes(1)
171
+ expect(context.adapter.disposeCount).toBe(1)
172
+ if (failure === 'preflight') {
173
+ expect(output).toBe('')
174
+ expect(errors).toContain('missing')
175
+ expect(errors).toContain('anureo-refactor: ')
176
+ } else {
177
+ expect(JSON.parse(output).status).toBe(failure === 'incomplete' ? 'incomplete' : 'completed')
178
+ if (failure === 'output') expect(errors).toContain('anureo-refactor: Output unavailable\n')
179
+ }
180
+ if (cleanupError) {
181
+ const executionThrew = failure === 'output' || failure === 'preflight'
182
+ const diagnostic = `anureo-refactor: ${executionThrew ? 'cleanup failed: ' : ''}${cleanupError}\n`
183
+ expect(errors).toContain(diagnostic)
184
+ expect(errors.endsWith(diagnostic)).toBe(!executionThrew)
185
+ if (!executionThrew) expect(errors).not.toContain('cleanup failed:')
186
+ } else {
187
+ expect(errors).not.toContain('cleanup failed:')
188
+ if (failure === 'none') expect(errors).not.toContain('anureo-refactor:')
189
+ }
190
+ } finally { disposal.mockRestore() }
191
+ })
192
+
193
+ /** A reported orchestration failure still prints JSON and disposes the CLI client before returning 2. */
194
+ test('CLI prints an incomplete report and cleans up its client', async () => {
195
+ const context = await fixture()
196
+ let output = ''
197
+ const code = await runCli([context.cwd, '--json'], {
198
+ ...context, createClient: async () => context.client,
199
+ graphLoader: async () => { throw new Error('Graph unavailable') },
200
+ stdout: text => { output += text }, stderr: () => {},
201
+ })
202
+ expect(code).toBe(2)
203
+ expect(JSON.parse(output)).toMatchObject({ status: 'incomplete', errors: ['Graph unavailable'] })
204
+ expect(context.adapter.disposeCount).toBe(1)
205
+ expect(context.prompts).toHaveLength(0)
206
+ })
207
+
208
+ /** Use the deterministic graph executable to verify transport/JSON handling without live indexing. */
209
+ test('graph adapter invokes the real subprocess interface and reads its JSON', async () => {
210
+ const context = await fixture()
211
+ const entry = fileURLToPath(new URL('./fixtures/repograph.ts', import.meta.url))
212
+ const graph = await loadGraph(context.cwd, entry)
213
+ expect(graph.kind).toBe('all')
214
+ expect(graph.nodes[0]?.filePath).toBe('main.ts')
215
+ expect(graph.nodes[0]?.callable).toEqual({ parameters: [], returnType: 'number' })
216
+ })
217
+
218
+ /** Launch the installed entry outside its target with scripted Codex/repograph executables, then
219
+ * compare stdout with the persisted report. Temporary repositories are fixture-owned;
220
+ * executable failures/timeouts reject the test. No model calls or live indexing are involved. */
221
+ test('installed CLI entry runs from an unrelated cwd through real Codex and graph process boundaries', async () => {
222
+ const target = await temporary()
223
+ const outside = await temporary()
224
+ await writeFile(join(target, 'main.ts'), 'export function main() { return 1 }\n')
225
+ await writeFile(join(target, 'task.dsl'), 'do work\n')
226
+ await exec('git', ['init', '-q', target])
227
+ const repograph = fileURLToPath(new URL('./fixtures/repograph.ts', import.meta.url))
228
+ const { stdout, stderr } = await runInstalledCli([target, '--review-only', '--repograph', repograph, '--json'], {
229
+ cwd: outside, env: { ...process.env, CODEX_BIN: codexFixture }, maxBuffer: 1 << 20,
230
+ })
231
+ const report = JSON.parse(stdout)
232
+ expect(report).toMatchObject({ status: 'completed', reviewOnly: true })
233
+ expect(report.modules[0].module.id).toBe('main')
234
+ expect(report.graphCoverage).toEqual([{ phase: 'design', status: 'available', filesWithoutSymbols: ['task.dsl'] }])
235
+ expect(stderr).toContain('module/main: unchanged')
236
+ expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
237
+ }, 25_000)
238
+
239
+ test('installed CLI edits a mixed-language repository and runs ordered checks without a graph', async () => {
240
+ const target = join(await temporary(), 'mixed 项目')
241
+ const outside = await temporary()
242
+ await mkdir(target)
243
+ await exec('git', ['init', '-q', target])
244
+ for (const [file, content] of Object.entries({
245
+ 'main.py': 'def main(): return 1\r\n', 'worker.zig': 'pub fn run() void {}\n',
246
+ 'start': '#!/bin/sh\nexit 0\n', 'job 配置.custom': 'task = "main"\n',
247
+ 'excluded.custom': 'task = "ignore"\n', 'binary.custom': Buffer.from([0, 0xff]),
248
+ 'README.md': '# Project\n', 'secret.txt': 'outside the include patterns\n',
249
+ })) await writeFile(join(target, file), content)
250
+ const literal = 'label with spaces & symbols %! ${value}'
251
+ const check = [
252
+ process.execPath, '-e',
253
+ 'if (process.argv[1] !== "label with spaces & symbols %! ${value}") process.exit(7); console.log("verified")',
254
+ literal,
255
+ ]
256
+ const { stdout } = await runInstalledCli([
257
+ target, '--no-graph', '--json', '--include', '**/*.{py,zig,custom}',
258
+ '--include', 'start', '--exclude', 'excluded.*', '--check-argv', JSON.stringify(check),
259
+ '--check', 'git rev-parse --is-inside-work-tree',
260
+ ], {
261
+ cwd: outside, env: { ...process.env, CODEX_BIN: codexFixture, REFACTOR_FIXTURE_EDIT: 'job 配置.custom' },
262
+ maxBuffer: 1 << 20,
263
+ })
264
+ const report = JSON.parse(stdout)
265
+ const files = ['job 配置.custom', 'main.py', 'start', 'worker.zig']
266
+ expect(report.status).toBe('completed')
267
+ expect(report.modules[0].module.files).toEqual(files)
268
+ expect(report.modules[0].step).toMatchObject({
269
+ status: 'applied', changedFiles: ['job 配置.custom'],
270
+ checks: [{ status: 'passed', output: expect.stringContaining('verified') },
271
+ { status: 'passed', output: expect.stringContaining('true') }],
272
+ })
273
+ expect(report.graphCoverage).toEqual([{ phase: 'design', status: 'disabled', filesWithoutSymbols: files }])
274
+ expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
275
+ }, 25_000)
276
+
277
+ test('CLI automatically falls back when the optional graph package is absent', async () => {
278
+ const target = await temporary()
279
+ const isolated = await temporary()
280
+ await exec('git', ['init', '-q', target])
281
+ await writeFile(join(target, 'program.unknown-dsl'), 'do work\n')
282
+ const packageDirectory = dirname(dirname(installedEntry()))
283
+ for (const folder of ['bin', 'src']) await cp(join(packageDirectory, folder), join(isolated, folder), { recursive: true })
284
+ await mkdir(join(isolated, 'node_modules', '@anureo'), { recursive: true })
285
+ const manifest = JSON.parse(await readFile(join(packageDirectory, 'package.json'), 'utf8'))
286
+ for (const name of Object.keys(manifest.dependencies)) {
287
+ const directory = await realpath(join(packageDirectory, 'node_modules', name))
288
+ await symlink(directory, join(isolated, 'node_modules', name), 'junction')
289
+ }
290
+ const { stdout, stderr } = await exec(process.execPath, [
291
+ join(isolated, 'bin', 'anureo-refactor.ts'), target, '--review-only', '--json',
292
+ ], { cwd: isolated, env: { ...process.env, CODEX_BIN: codexFixture }, timeout: 20_000 })
293
+ expect(JSON.parse(stdout)).toMatchObject({
294
+ status: 'completed',
295
+ graphCoverage: [{ phase: 'design', status: 'unavailable', filesWithoutSymbols: ['program.unknown-dsl'] }],
296
+ })
297
+ expect(stderr).toContain('continuing with source')
298
+ }, 25_000)
299
+
300
+ const codexFixture = fileURLToPath(new URL('./fixtures/codex.mjs', import.meta.url))
301
+
302
+ /** Run the package-resolved CLI in a child with a 20-second timeout. Return its buffered streams
303
+ * on success. Failed resolution, launch, exit, timeout or buffer errors reject the test. */
304
+ async function runInstalledCli(args: string[], options: { cwd?: string; env?: NodeJS.ProcessEnv; maxBuffer?: number } = {}) {
305
+ return exec(process.execPath, [installedEntry(), ...args], { ...options, timeout: 20_000 })
306
+ }
307
+
308
+ /** Locate the executable relative to the resolved package root entry, independent of test cwd.
309
+ * A missing package throws here. The optional-dependency test also uses this to locate copy inputs. */
310
+ function installedEntry(): string {
311
+ const require = createRequire(import.meta.url)
312
+ return join(dirname(require.resolve('@anureo/refactor')), '../bin/anureo-refactor.ts')
313
+ }
@@ -0,0 +1,38 @@
1
+ // Simulates an ACP stdio agent that submits validated work through the SDK's MCP bridge.
2
+ import { createInterface } from 'node:readline'
3
+ import { submitOutput } from '../../../../packages/adapter/acp/tests/fixtures/mcp-output-client.mjs'
4
+ import { answer } from './answer.mjs'
5
+
6
+ const servers = new Map()
7
+ const send = frame => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...frame }) + '\n')
8
+ for await (const line of createInterface({ input: process.stdin })) {
9
+ const { id, method, params } = JSON.parse(line)
10
+ if (id === undefined) continue
11
+ let result
12
+ switch (method) {
13
+ case 'initialize':
14
+ result = { protocolVersion: 1, agentCapabilities: { sessionCapabilities: { close: {} }, mcpCapabilities: { http: true } } }
15
+ break
16
+ case 'session/new': {
17
+ const sessionId = String(id)
18
+ servers.set(sessionId, params.mcpServers)
19
+ result = { sessionId }
20
+ break
21
+ }
22
+ case 'session/prompt': {
23
+ const server = servers.get(params.sessionId).find(server => server.name === 'anureo_output')
24
+ // The bridge must accept the result before the prompt reply ends the turn.
25
+ await submitOutput(server, params.prompt, answer)
26
+ result = { stopReason: 'end_turn' }
27
+ break
28
+ }
29
+ case 'session/close':
30
+ servers.delete(params.sessionId)
31
+ result = {}
32
+ break
33
+ default:
34
+ send({ id, error: { code: -32601, message: 'Unsupported fixture method' } })
35
+ continue
36
+ }
37
+ send({ id, result })
38
+ }
@@ -0,0 +1,50 @@
1
+ // Simulates a native-lifecycle AHP peer that supports only text output.
2
+ import { createInterface } from 'node:readline'
3
+ import { answer } from './answer.mjs'
4
+
5
+ const sessions = new Map()
6
+ const capabilities = { input: { delivery: ['native'] }, turn: { inputModalities: ['text'] } }
7
+ const send = frame => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...frame }) + '\n')
8
+ for await (const line of createInterface({ input: process.stdin })) {
9
+ const { id, method, params } = JSON.parse(line)
10
+ if (id === undefined) continue
11
+ let result
12
+ switch (method) {
13
+ case 'initialize':
14
+ result = { protocolVersion: 1, protocolContract: 'native-lifecycle', runtime: { name: 'fixture', version: '1', adapter: 'ahp' }, capabilities }
15
+ break
16
+ case 'session/open': {
17
+ const binding = params.binding
18
+ sessions.set(binding.sessionId, { seq: 0 })
19
+ result = { binding, capabilities, streamId: 'fixture', state: { binding, capabilities, status: 'ready', activeTurnIds: [], config: {}, capabilityRevision: 1 } }
20
+ break
21
+ }
22
+ case 'input/submit': {
23
+ const { sessionId, submissionId, input, outputSchema } = params
24
+ const text = input.filter(block => block.type === 'text').map(block => block.text).join('\n')
25
+ if (outputSchema || !text.includes('matches this JSON Schema')) throw new Error('Expected JSON text fallback')
26
+ const session = sessions.get(sessionId)
27
+ const turnId = `turn-${id}`
28
+ /** Publish one notification in this session's observation sequence. Only item events carry
29
+ * the optional envelope turn ID here. Serialization and write failures fail the fixture. */
30
+ const event = (type, payload, itemTurnId) => send({ method: type, params: {
31
+ sessionId, streamId: 'fixture', seq: ++session.seq, timestamp: new Date().toISOString(), turnId: itemTurnId, type, payload,
32
+ } })
33
+ event('turn/started', { turnId })
34
+ event('submission/bound', { submissionId, turnId })
35
+ // Put fallback JSON in final text before completion so the SDK can validate the full result.
36
+ event('item/completed', { item: { id: 'result', type: 'agentMessage', phase: 'final', text: JSON.stringify(answer(text)) } }, turnId)
37
+ event('turn/completed', { turnId, status: 'completed' })
38
+ result = { accepted: true, submissionId, disposition: 'started', turnId }
39
+ break
40
+ }
41
+ case 'session/close':
42
+ sessions.delete(params.sessionId)
43
+ result = { closed: true, observationClosed: true, executionStopped: 'unconfirmed' }
44
+ break
45
+ default:
46
+ send({ id, error: { code: -32601, message: 'Unsupported fixture method' } })
47
+ continue
48
+ }
49
+ send({ id, result })
50
+ }
@@ -0,0 +1,15 @@
1
+ /** Build scripted structured output for ACP's MCP submission, AHP's final message and Claude's
2
+ * fake SDK result. Planning prompts must carry an Inventory JSON line. Malformed fixtures throw
3
+ * so a peer cannot complete planning with an invented inventory. */
4
+ export function answer(prompt) {
5
+ if (!prompt.startsWith('PLAN')) return { summary: 'Keep the existing code.', changes: [], deferred: [] }
6
+ const inventory = prompt.split('\n').find(line => line.startsWith('Inventory: '))
7
+ const files = JSON.parse(inventory.slice('Inventory: '.length))
8
+ return { summary: 'One module', modules: [{ id: 'main', name: 'Main', description: 'Entry point', files }] }
9
+ }
10
+
11
+ /** The Hermes fake gateway calls this to put the same scripted result in a completed text turn.
12
+ * Planning input errors propagate from answer. */
13
+ export function respond(prompt) {
14
+ return JSON.stringify(answer(prompt))
15
+ }
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env bun
2
+ // Emulates the Codex app-server wire lifecycle for CLI subprocess tests; it must not run models or read credentials.
3
+ import readline from 'node:readline'
4
+ import { appendFile } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ if (process.argv.includes('--version')) { process.stdout.write('codex-cli 0.164.0\n'); process.exit(0) }
7
+ /** Serialize one fixture reply/event to stdout, returning the stream write result.
8
+ * The protocol loop owns ordering; serialization or synchronous stream errors escape to fail the test. */
9
+ const send = value => process.stdout.write(`${JSON.stringify(value)}\n`)
10
+ const threadId = 'refactor-fixture'
11
+ for await (const line of readline.createInterface({ input: process.stdin })) {
12
+ const message = JSON.parse(line)
13
+ if (message.id === undefined) continue
14
+ /** Send a result for this request ID, returning send's write result or propagating its errors.
15
+ * The protocol loop must acknowledge turn/start before publishing that turn's lifecycle events. */
16
+ const reply = result => send({ id: message.id, result })
17
+ switch (message.method) {
18
+ case 'initialize': reply({ userAgent: 'codex/0.164.0' }); break
19
+ case 'account/read': reply({ account: null, requiresOpenaiAuth: false }); break
20
+ case 'model/list': reply({ data: [], nextCursor: null }); break
21
+ case 'thread/start': reply({ thread: { id: threadId } }); break
22
+ case 'turn/start': {
23
+ const prompt = message.params.input.filter(part => part.type === 'text').map(part => part.text).join('\n')
24
+ const inventory = prompt.split('\n').find(line => line.startsWith('Inventory: '))
25
+ const files = inventory ? JSON.parse(inventory.slice('Inventory: '.length)) : []
26
+ if (prompt.startsWith('REFACTOR') && process.env.REFACTOR_FIXTURE_EDIT) {
27
+ await appendFile(join(process.cwd(), process.env.REFACTOR_FIXTURE_EDIT), '\n')
28
+ }
29
+ const result = prompt.startsWith('PLAN')
30
+ ? { summary: 'One module', modules: [{ id: 'main', name: 'Main', description: 'Entry point', files }] }
31
+ : { summary: 'Direct and readable implementation; keep it.', changes: [], deferred: [] }
32
+ // The adapter needs the turn acknowledgement before it can associate subsequent events.
33
+ // Final text must arrive before completion so structured-output parsing sees a full response.
34
+ reply({ turn: { id: 'turn', status: 'inProgress', items: [] } })
35
+ send({ method: 'turn/started', params: { threadId, turn: { id: 'turn', status: 'inProgress', items: [] } } })
36
+ send({ method: 'item/completed', params: { threadId, turnId: 'turn', item: {
37
+ id: 'message', type: 'agentMessage', phase: 'final_answer', text: JSON.stringify(result),
38
+ } } })
39
+ send({ method: 'turn/completed', params: { threadId, turn: { id: 'turn', status: 'completed', items: [] } } })
40
+ break
41
+ }
42
+ default: reply({})
43
+ }
44
+ }
@@ -0,0 +1,17 @@
1
+ // Stand-in subprocess for the CLI suite's direct loadGraph and installed-entry tests.
2
+ // Checks the export kind and output location, then writes a minimal graph without indexing.
3
+ import { writeFile } from 'node:fs/promises'
4
+ import { isAbsolute, relative, sep } from 'node:path'
5
+
6
+ const args = process.argv.slice(2)
7
+ const [command, repositoryPath] = args
8
+ if (command !== 'export' || args[args.indexOf('--kind') + 1] !== 'all') process.exit(3)
9
+ const output = args[args.indexOf('--out') + 1]
10
+ // Keeping the export outside the target prevents a later export from indexing it.
11
+ const relativeOutput = relative(repositoryPath, output)
12
+ if (!isAbsolute(relativeOutput) && !relativeOutput.startsWith(`..${sep}`) && relativeOutput !== '..') process.exit(4)
13
+ await writeFile(output, JSON.stringify({
14
+ schemaVersion: 1, kind: 'all', repositoryPath, indexReport: { status: 'indexed' },
15
+ nodes: [{ id: 'main', name: 'main', filePath: 'main.ts', labels: ['Function'], startLine: 1, endLine: 1,
16
+ callable: { parameters: [], returnType: 'number' } }], edges: [],
17
+ }))
@@ -0,0 +1,37 @@
1
+ // Exercises the real Repograph exporter only when REPOGRAPH_INTEGRATION=1.
2
+ import { expect, test } from 'bun:test'
3
+ import { realpath, writeFile } from 'node:fs/promises'
4
+ import { dirname, join } from 'node:path'
5
+ import { loadGraph, resolveRepographEntry } from '../src/graph'
6
+ import { exec } from '../src/process'
7
+ import { temporary } from './helpers'
8
+
9
+ const fixtures = [
10
+ { language: 'TypeScript', extension: 'ts', main: 'import { save } from "./store";\nexport function main() { return save() }\n',
11
+ store: 'export function save() { return 1 }\nexport function isolated() { return 2 }\n' },
12
+ { language: 'Python', extension: 'py', main: 'from store import save\n\ndef main():\n return save()\n',
13
+ store: 'def save():\n return 1\n\ndef isolated():\n return 2\n' },
14
+ ]
15
+
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.
18
+ test.skipIf(process.env.REPOGRAPH_INTEGRATION !== '1').each(fixtures)('real repograph exports $language cross-file callers', async ({ extension, main, store }) => {
19
+ const cwd = await realpath(await temporary())
20
+ await exec('git', ['init', '-q', cwd])
21
+ await writeFile(join(cwd, `main.${extension}`), main)
22
+ await writeFile(join(cwd, `store.${extension}`), store)
23
+ const entry = process.env.REPOGRAPH_CLI ?? resolveRepographEntry()
24
+ const graph = await loadGraph(cwd, entry)
25
+ try {
26
+ const byId = new Map(graph.nodes.map(node => [node.id, node.name]))
27
+ expect(graph.edges.some(edge => edge.type === 'CALLS' && byId.get(edge.source) === 'main' && byId.get(edge.target) === 'save')).toBe(true)
28
+ expect(graph.nodes.some(node => node.name === 'isolated')).toBe(true)
29
+ expect(graph.indexReport.nodes).toBe(graph.nodes.length)
30
+ expect(graph.indexReport.edges).toBe(graph.edges.length)
31
+ } 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 })
36
+ }
37
+ }, 120_000)
@@ -0,0 +1,105 @@
1
+ // Builds scripted repositories and clients with shared cleanup for refactor tests.
2
+ import { afterEach } from 'bun:test'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
5
+ import { tmpdir } from 'node:os'
6
+ import { join } from 'node:path'
7
+ import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
8
+ import { createScriptedAdapter } from '@anureo/conformance'
9
+ import type { JsonObject } from '@anureo/protocol'
10
+ import type { RepositoryGraph } from '../src/graph'
11
+ import { exec } from '../src/process'
12
+
13
+ /** Create a test-owned temporary directory, registering removal after the test; filesystem errors reject. */
14
+ export async function temporary(): Promise<string> {
15
+ const path = await mkdtemp(join(tmpdir(), 'anureo-refactor-test-'))
16
+ directories.push(path)
17
+ return path
18
+ }
19
+
20
+ /** Default exact-cover response for fixture planning; consumers derive variants rather than mutate shared state. */
21
+ export const plan = { summary: 'Two cohesive modules', modules: [
22
+ { id: 'a', name: 'A', description: 'A responsibility', files: ['a.ts'] },
23
+ { id: 'b', name: 'B', description: 'B responsibility', files: ['b.ts'] },
24
+ ] }
25
+ /** Default work response for fixture agents; consumers reuse it without mutating shared state. */
26
+ export const unchanged = { summary: 'Read the code; direct expression is appropriate.', changes: [], deferred: [] }
27
+ /** Return an agent's edit claim. Tests make the real edit separately so host observations
28
+ * remain independent of the claim. */
29
+ export const edited = (change = 'Renamed internal value') => ({ summary: 'Edited', changes: [change], deferred: [] })
30
+ /** Return the first line for prompt routing, or an empty string for empty input. */
31
+ export const kind = (prompt: string) => prompt.split('\n')[0]!
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]
34
+ /** Build a two-file graph rooted at the test target for injected graph loaders. */
35
+ export function graph(cwd: string): RepositoryGraph {
36
+ return { schemaVersion: 1, repositoryPath: cwd, kind: 'all', indexReport: { status: 'indexed' }, nodes: [
37
+ { id: 'a', labels: ['Function'], name: 'calculate', filePath: 'a.ts', startLine: 1, endLine: 1 },
38
+ { id: 'b', labels: ['Function'], name: 'persist', filePath: 'b.ts', startLine: 1, endLine: 1 },
39
+ ], edges: [{ id: 'call', source: 'a', target: 'b', type: 'CALLS' }] }
40
+ }
41
+
42
+ /** Create a staged two-file Git repository and scripted SDK client for refactor, CLI and lifecycle tests.
43
+ * Defaults to the shared plan for planning prompts and unchanged work otherwise. A supplied responder
44
+ * is awaited on each submission; return HarnessSdkError to fail the turn or a JSON-serializable value
45
+ * as agent output. Tests make edits themselves so host snapshots can verify them independently.
46
+ * Returns the cwd, client, adapter, prompt log and an in-memory graph loader. Setup failures reject.
47
+ * Shared afterEach handles registered resources, including directories from failed setup. */
48
+ export async function fixture(respond: Responder = prompt => prompt.startsWith('PLAN') ? plan : unchanged) {
49
+ const cwd = await temporary()
50
+ await Promise.all(['a.ts', 'b.ts'].map(file => writeFile(join(cwd, file), 'export const value = 1\n')))
51
+ await writeFile(join(cwd, '.gitignore'), '.anureo/\n')
52
+ await exec('git', ['init', '-q', cwd])
53
+ await exec('git', ['-C', cwd, 'add', '.'])
54
+ const prompts: string[] = []
55
+ const adapter = respondingAdapter(respond, prompts)
56
+ const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
57
+ clients.push(client)
58
+ return { cwd, client, adapter, prompts, graphLoader: async () => graph(cwd) }
59
+ }
60
+
61
+ /** Script one submission's output against the session's own working directory. */
62
+ type Responder = (prompt: string, cwd: string) => unknown | Promise<unknown>
63
+
64
+ const clients: Client[] = []
65
+ const directories: string[] = []
66
+ /** Attempt client disposal before removing test repositories. Disposal or removal failures reject
67
+ * the hook; finally starts directory cleanup even when Promise.all rejects during disposal. */
68
+ afterEach(async () => {
69
+ try { await Promise.all(clients.splice(0).map(client => client.dispose())) }
70
+ finally { await Promise.all(directories.splice(0).map(path => rm(path, { recursive: true, force: true }))) }
71
+ })
72
+
73
+ /** Build the adapter that fixture passes to createClient. During submission, the scripted
74
+ * backend invokes execute to log the prompt and emit start before awaiting the responder.
75
+ * A returned HarnessSdkError becomes a failed terminal event. Other values are serialized to
76
+ * final JSON before completion. Responder, serialization and event errors reject the submission.
77
+ * Other session calls use the adapter defaults. */
78
+ function respondingAdapter(respond: Responder, prompts: string[]) {
79
+ const sessionDirectories = new Map<string, string>()
80
+ return createScriptedAdapter({
81
+ /** The adapter awaits this at session open, before a submission can use the recorded cwd. */
82
+ onOpen: async params => { sessionDirectories.set(params.binding.sessionId, params.cwd) },
83
+ execute: async (call, sink) => {
84
+ if (call.method !== 'input/submit' || !('input' in call.params) || !('submissionId' in call.params)) return undefined
85
+ const { input, submissionId, sessionId } = call.params
86
+ const prompt = input.filter(part => part.type === 'text').map(part => part.text).join('\n')
87
+ prompts.push(prompt)
88
+ const turnId = randomUUID()
89
+ await sink.emit({ type: 'turn/started', payload: { turnId } })
90
+ const result = await respond(prompt, sessionDirectories.get(sessionId)!)
91
+ if (result instanceof HarnessSdkError) {
92
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
93
+ code: result.code, message: result.message, retryable: result.retryable, outcomeUnknown: result.outcomeUnknown,
94
+ ...(result.details ? { details: result.details as JsonObject } : {}),
95
+ } } })
96
+ } else {
97
+ await sink.emit({ type: 'item/completed', payload: { item: {
98
+ id: randomUUID(), type: 'agentMessage', phase: 'final', text: JSON.stringify(result),
99
+ } } }, { turnId })
100
+ await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
101
+ }
102
+ return { submissionId, accepted: true, disposition: 'started', turnId }
103
+ },
104
+ })
105
+ }