@anureo/refactor 0.0.0-stage → 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.
- package/bin/anureo-refactor.ts +5 -0
- package/package.json +46 -4
- package/src/agent-work.ts +132 -0
- package/src/checks.ts +70 -0
- package/src/cli.ts +214 -0
- package/src/client.ts +91 -0
- package/src/errors.ts +33 -0
- package/src/git-path.ts +47 -0
- package/src/git-tree.ts +55 -0
- package/src/git.ts +42 -0
- package/src/graph-artifacts.ts +70 -0
- package/src/graph.ts +88 -0
- package/src/index.ts +12 -0
- package/src/options.ts +65 -0
- package/src/plan-validation.ts +39 -0
- package/src/process.ts +11 -0
- package/src/prompts.ts +356 -0
- package/src/refactor.ts +186 -0
- package/src/report-store.ts +17 -0
- package/src/report.ts +44 -0
- package/src/results.ts +81 -0
- package/src/run-lifecycle.ts +117 -0
- package/src/schema.ts +48 -0
- package/src/source-inventory.ts +17 -0
- package/src/source-policy.ts +50 -0
- package/src/worktree.ts +287 -0
- package/tests/agent-contract.test.ts +188 -0
- package/tests/cli.test.ts +313 -0
- package/tests/fixtures/acp.mjs +38 -0
- package/tests/fixtures/ahp.mjs +50 -0
- package/tests/fixtures/answer.mjs +15 -0
- package/tests/fixtures/codex.mjs +44 -0
- package/tests/fixtures/repograph.ts +17 -0
- package/tests/graph.integration.test.ts +37 -0
- package/tests/helpers.ts +105 -0
- package/tests/refactor.test.ts +437 -0
- package/tests/run-lifecycle.test.ts +82 -0
- package/tests/tree.test.ts +99 -0
- package/tsconfig.json +12 -0
- package/README.md +0 -3
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { validatePlan } from '../src/plan-validation'
|
|
3
|
+
import { designPrompt, modulePrompt, planPrompt } from '../src/prompts'
|
|
4
|
+
import { plan } from './helpers'
|
|
5
|
+
|
|
6
|
+
/** Compare both prompt APIs across modes and check lists so migrating callers cannot alter instructions. */
|
|
7
|
+
test.each([
|
|
8
|
+
{ readOnly: false, checks: [] },
|
|
9
|
+
{ readOnly: false, checks: ['bun test', 'bun run typecheck'] },
|
|
10
|
+
{ readOnly: true, checks: [] },
|
|
11
|
+
{ readOnly: true, checks: ['bun test', 'bun run typecheck'] },
|
|
12
|
+
])('named and positional prompts agree for readOnly=$readOnly checks=$checks', ({ readOnly, checks }) => {
|
|
13
|
+
const files = plan.modules.flatMap(module => module.files)
|
|
14
|
+
const module = plan.modules[0]!
|
|
15
|
+
const context = { graphFile: 'graph.json', version: 'snapshot', checks, mode: readOnly ? 'read-only' as const : 'edit' as const }
|
|
16
|
+
const prompts = [
|
|
17
|
+
designPrompt({ ...context, files }),
|
|
18
|
+
modulePrompt({ ...context, module, design: 'Reviewed boundaries' }),
|
|
19
|
+
]
|
|
20
|
+
expect(prompts).toEqual([
|
|
21
|
+
designPrompt(files, context.graphFile, context.version, checks, readOnly),
|
|
22
|
+
modulePrompt(module, context.graphFile, context.version, checks, readOnly, 'Reviewed boundaries'),
|
|
23
|
+
])
|
|
24
|
+
for (const prompt of prompts) {
|
|
25
|
+
expect(prompt).toContain(readOnly ? 'MODE: READ ONLY' : 'MODE: EDIT')
|
|
26
|
+
expect(prompt.includes('Validation commands:')).toBe(!readOnly && checks.length > 0)
|
|
27
|
+
if (!readOnly && checks.length > 0) {
|
|
28
|
+
expect(prompt).toContain(`Validation commands: ${JSON.stringify(checks)}. Run them before returning and fix failures.`)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
/** Preserve the alternatives and their evidence requirements even when a graph is unavailable. */
|
|
34
|
+
test.each(['read-only', 'edit'] as const)('structural decisions compare keeping, consolidation and extraction in %s mode', mode => {
|
|
35
|
+
const context = { graphFile: null, version: 'snapshot', checks: [], mode, isolated: true }
|
|
36
|
+
const design = designPrompt({ ...context, files: ['api.ts', 'types.ts'] })
|
|
37
|
+
const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Keep the shared policy owner' })
|
|
38
|
+
for (const prompt of [design, module]) {
|
|
39
|
+
const instructions = prompt.replace(/\s+/g, ' ')
|
|
40
|
+
expect(instructions).toContain('compare keeping it, consolidating it into an existing owner and extracting it')
|
|
41
|
+
expect(instructions).toContain('Describe the current reading/editing path')
|
|
42
|
+
expect(instructions).toContain('Prefer an existing cohesive module before creating a new file')
|
|
43
|
+
expect(instructions).toContain('Preserve small modules with useful independent contracts')
|
|
44
|
+
expect(instructions).toContain('Keep related types with their owning feature')
|
|
45
|
+
expect(instructions).toContain('Set no target file count')
|
|
46
|
+
expect(instructions).toContain('An unchanged structure is a valid outcome')
|
|
47
|
+
expect(prompt.split('Optimize for the cost of understanding and changing the code.')).toHaveLength(2)
|
|
48
|
+
expect(prompt).toContain('Static graph unavailable.')
|
|
49
|
+
}
|
|
50
|
+
expect(design).not.toContain('Give each\n its own file')
|
|
51
|
+
expect(design).not.toContain('Split by group')
|
|
52
|
+
expect(design).toContain('Later module agents receive this summary')
|
|
53
|
+
expect(design).toContain('the existing layout from proposed boundaries')
|
|
54
|
+
expect(module).not.toContain('Extract each phase')
|
|
55
|
+
expect(module).toContain('Read the design summary before changing structure')
|
|
56
|
+
expect(module).toContain('explain any revision supported by new source evidence')
|
|
57
|
+
expect(module).toContain('Keep short, cohesive sequences together')
|
|
58
|
+
expect(module).toContain('Keep simple one-use expressions inline')
|
|
59
|
+
expect(module).toContain('Consolidate or split code within this module')
|
|
60
|
+
expect(module).toContain('Preserve the existing-file assignment')
|
|
61
|
+
expect(module).toContain('Edit only the files assigned to this module')
|
|
62
|
+
if (mode === 'read-only') expect(module).toContain('describe resulting edits as proposals')
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
/** Both editing phases receive the same audience/language policy, even when only proposing changes. */
|
|
66
|
+
test.each(['read-only', 'edit'] as const)('documentation guidance reaches both phases in %s mode', mode => {
|
|
67
|
+
const context = { graphFile: 'graph.json', version: 'snapshot', checks: [], mode }
|
|
68
|
+
const prompts = [
|
|
69
|
+
designPrompt({ ...context, files: ['api.ts', 'worker.py'] }),
|
|
70
|
+
modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' }),
|
|
71
|
+
]
|
|
72
|
+
for (const prompt of prompts) {
|
|
73
|
+
const documentation = prompt.replace(/\s+/g, ' ')
|
|
74
|
+
expect(documentation).toContain('An exported declaration is not automatically a supported public API')
|
|
75
|
+
expect(documentation).toContain('an extension interface can be public')
|
|
76
|
+
expect(documentation).toContain('Lead public API comments with the consumer\'s task')
|
|
77
|
+
expect(documentation).toContain('a short contract can be one sentence')
|
|
78
|
+
expect(documentation).toContain('Select the documentation convention for each declaration from its language')
|
|
79
|
+
expect(documentation).toContain('In mixed-language files')
|
|
80
|
+
expect(documentation).toContain('Preserve the exact documentation dialect across phases and moved declarations')
|
|
81
|
+
expect(documentation).toContain('Record identified conventions in the summary')
|
|
82
|
+
expect(documentation).toContain('Examples are not a language allowlist')
|
|
83
|
+
expect(documentation).toContain('For any other language or DSL')
|
|
84
|
+
expect(documentation).toContain('ordinary native comments if no structured convention is established')
|
|
85
|
+
expect(documentation).toContain('Documentation tags are convention-specific, not a universal @ syntax')
|
|
86
|
+
expect(documentation).toContain('Do not transplant TSDoc tags or restrictions into another convention')
|
|
87
|
+
expect(documentation).toContain('Go uses doc comments and prose')
|
|
88
|
+
expect(documentation).toContain('docstrings with the project\'s Sphinx, Google or NumPy style')
|
|
89
|
+
expect(documentation).toContain('C# uses XML documentation')
|
|
90
|
+
expect(documentation).toContain('Do not infer support or release stage')
|
|
91
|
+
expect(documentation).toContain('Verify these claims')
|
|
92
|
+
expect(documentation).toContain('review comments against the final code')
|
|
93
|
+
expect(documentation).toContain('Record documentation changes or proposals in "changes"')
|
|
94
|
+
expect(documentation).toContain('concrete unresolved gaps in "deferred"')
|
|
95
|
+
expect(documentation).toContain('Do not claim unavailable tooling was run')
|
|
96
|
+
expect(documentation).toContain('Correct stale names, unsupported tags and misleading descriptions')
|
|
97
|
+
expect(documentation).toContain('Type annotations, braces, delimiters and tag placement must follow that exact dialect')
|
|
98
|
+
expect(documentation).toContain('Do not describe a returned failure as a thrown exception')
|
|
99
|
+
expect(documentation).toContain('A parser pass alone does not establish semantic accuracy')
|
|
100
|
+
expect(prompt.indexOf('Documentation conventions and tags:')).toBe(prompt.lastIndexOf('Documentation conventions and tags:'))
|
|
101
|
+
if (mode === 'read-only') expect(prompt).toContain('apply this review to proposed comments without editing')
|
|
102
|
+
}
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
/** Both phases prioritize actual API definitions while preserving executable declaration order. */
|
|
106
|
+
test.each(['read-only', 'edit'] as const)('declaration ordering reaches both phases in %s mode', mode => {
|
|
107
|
+
const context = { graphFile: 'graph.json', version: 'snapshot', checks: [], mode }
|
|
108
|
+
const prompts = [
|
|
109
|
+
designPrompt({ ...context, files: ['api.ts'] }),
|
|
110
|
+
modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' }),
|
|
111
|
+
]
|
|
112
|
+
for (const prompt of prompts) {
|
|
113
|
+
const instructions = prompt.replace(/\s+/g, ' ')
|
|
114
|
+
expect(instructions).toContain('Keep license/file comments and imports at the beginning')
|
|
115
|
+
expect(instructions).toContain('exported types/interfaces, functions and classes before unexported implementation helpers')
|
|
116
|
+
expect(instructions).toContain('move the actual declaration, not just its export statement')
|
|
117
|
+
expect(instructions).toContain('constructor and public methods/accessors first')
|
|
118
|
+
expect(instructions).toContain('Include implicitly public members and static public methods')
|
|
119
|
+
expect(instructions).toContain('do not change visibility')
|
|
120
|
+
expect(instructions).toContain('Preserve overload order')
|
|
121
|
+
expect(instructions).toContain('field initialization order, static blocks, computed names and decorator evaluation')
|
|
122
|
+
expect(instructions).toContain('report the concrete constraint in "deferred"')
|
|
123
|
+
expect(instructions).toContain('do not skip safe ordering changes elsewhere')
|
|
124
|
+
expect(prompt.indexOf('Declaration order:')).toBe(prompt.lastIndexOf('Declaration order:'))
|
|
125
|
+
if (mode === 'read-only') expect(prompt).toContain('propose the reordering without editing files')
|
|
126
|
+
}
|
|
127
|
+
expect(prompts[0]).toContain('Apply declaration ordering to files affected by boundary changes')
|
|
128
|
+
expect(prompts[1]).toContain('public class methods hidden below internal implementation helpers')
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
/** Verify that phase-specific scope survives shared guidance and that isolated checks stay with the host. */
|
|
132
|
+
test('documentation scope is phase-specific and planning remains inventory-only', () => {
|
|
133
|
+
const files = ['api.ts']
|
|
134
|
+
const context = {
|
|
135
|
+
graphFile: 'graph.json', version: 'snapshot', mode: 'edit' as const, isolated: true,
|
|
136
|
+
checks: [{ executable: 'bun', args: ['run', 'typecheck'] }],
|
|
137
|
+
}
|
|
138
|
+
const design = designPrompt({ ...context, files })
|
|
139
|
+
const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' })
|
|
140
|
+
expect(design).toContain('preserve contract comments on moved declarations')
|
|
141
|
+
expect(design).toContain('Do not perform a repository-wide comment rewrite')
|
|
142
|
+
expect(design).not.toContain('Module documentation scope:')
|
|
143
|
+
expect(module).toContain('including declarations\nwhose implementation stays unchanged')
|
|
144
|
+
expect(module).toContain('keep accurate concise comments without cosmetic rewrites')
|
|
145
|
+
expect(module).not.toContain('Design documentation scope:')
|
|
146
|
+
const planning = planPrompt(files, 'snapshot')
|
|
147
|
+
expect(planning).not.toContain('Documentation conventions and tags:')
|
|
148
|
+
expect(planning).toContain('cohesive review/edit task groups')
|
|
149
|
+
expect(planning).toContain('Keep files that require coordinated edits in the same assignment')
|
|
150
|
+
expect(planning).toContain('Plan against the existing inventory')
|
|
151
|
+
expect(planning).toContain('Assign every listed source file exactly once')
|
|
152
|
+
expect(planning).toContain('Do not review or edit yet')
|
|
153
|
+
const hostChecks = `Validation commands: ${JSON.stringify(context.checks)}. The host runs them in your worktree before merging your edits.`
|
|
154
|
+
for (const prompt of [design, module]) {
|
|
155
|
+
expect(prompt).toContain(hostChecks)
|
|
156
|
+
expect(prompt).not.toContain('Run them before returning')
|
|
157
|
+
}
|
|
158
|
+
expect(module).toContain('Other modules run concurrently.')
|
|
159
|
+
expect(design).not.toContain('Other modules run concurrently.')
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
/** Module IDs keep the existing alphabet and length boundaries, including uppercase letters and underscores. */
|
|
163
|
+
test.each(['a', 'A_0-module', 'a'.repeat(80)])('accepts safe module ID %s', id => {
|
|
164
|
+
const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
|
|
165
|
+
expect(() => validatePlan(candidate, ['a.ts'])).not.toThrow()
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
/** Reject path components and out-of-policy IDs before their values can reach reports. */
|
|
169
|
+
test.each(['', '../escape', 'a/b', 'a\\b', '_module', '-module', 'a.b', 'a b', 'a'.repeat(81)])('rejects unsafe module ID %s', id => {
|
|
170
|
+
const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
|
|
171
|
+
expect(() => validatePlan(candidate, ['a.ts'])).toThrow(`Invalid or duplicate module id: ${id}`)
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
/** Plans fail in traversal order, with omissions delayed until all explicit assignments are checked. */
|
|
175
|
+
test('plan validation preserves error precedence and inventory ordering', () => {
|
|
176
|
+
const first = plan.modules[0]!
|
|
177
|
+
const second = plan.modules[1]!
|
|
178
|
+
expect(() => validatePlan({ ...plan, modules: [first, { ...second, id: first.id, files: ['extra.ts'] }] }, ['a.ts', 'b.ts']))
|
|
179
|
+
.toThrow('Invalid or duplicate module id: a')
|
|
180
|
+
expect(() => validatePlan({ ...plan, modules: [first, { ...second, id: first.id.toUpperCase(), files: ['extra.ts'] }] }, ['a.ts', 'b.ts']))
|
|
181
|
+
.toThrow('Invalid or duplicate module id: A')
|
|
182
|
+
expect(() => validatePlan({ ...plan, modules: [{ ...first, files: ['extra.ts'] }, { ...second, id: '../unsafe' }] }, ['a.ts', 'b.ts']))
|
|
183
|
+
.toThrow('Unlisted or duplicate module file: extra.ts')
|
|
184
|
+
expect(() => validatePlan({ ...plan, modules: [first, { ...second, files: ['a.ts'] }] }, ['a.ts', 'b.ts']))
|
|
185
|
+
.toThrow('Unlisted or duplicate module file: a.ts')
|
|
186
|
+
expect(() => validatePlan({ ...plan, modules: [first] }, ['c.ts', 'a.ts', 'b.ts']))
|
|
187
|
+
.toThrow('Module plan omitted source files: c.ts, b.ts')
|
|
188
|
+
})
|
|
@@ -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
|
+
}
|