@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.
- package/bin/anureo-refactor.ts +5 -0
- package/package.json +21 -23
- package/src/agent-work.ts +184 -0
- package/src/checks.ts +82 -0
- package/src/cli.ts +214 -0
- package/src/client.ts +93 -0
- package/src/errors.ts +70 -0
- package/src/git-path.ts +47 -0
- package/src/git-tree.ts +55 -0
- package/src/git.ts +55 -0
- package/src/graph-artifacts.ts +73 -0
- package/src/graph.ts +145 -0
- package/src/index.ts +40 -0
- package/src/options.ts +65 -0
- package/src/plan-validation.ts +38 -0
- package/src/{process.d.ts → process.ts} +4 -2
- package/src/{prompts.js → prompts.ts} +145 -67
- package/src/refactor.ts +191 -0
- package/src/{report-store.js → report-store.ts} +10 -8
- package/src/report.ts +60 -0
- package/src/results.ts +83 -0
- package/src/run-lifecycle.ts +117 -0
- package/src/{schema.d.ts → schema.ts} +29 -23
- package/src/source-inventory.ts +17 -0
- package/src/source-policy.ts +50 -0
- package/src/worktree.ts +322 -0
- package/tests/agent-contract.test.ts +180 -0
- package/tests/cli.test.ts +378 -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 +24 -0
- package/tests/graph.integration.test.ts +110 -0
- package/tests/helpers.ts +109 -0
- package/tests/refactor.test.ts +536 -0
- package/tests/run-lifecycle.test.ts +136 -0
- package/tests/tree.test.ts +210 -0
- package/tsconfig.json +12 -0
- package/LICENSE +0 -201
- package/bin/anureo-refactor.d.ts +0 -2
- package/bin/anureo-refactor.js +0 -4
- package/src/agent-work.d.ts +0 -41
- package/src/agent-work.js +0 -131
- package/src/checks.d.ts +0 -26
- package/src/checks.js +0 -66
- package/src/cli.d.ts +0 -27
- package/src/cli.js +0 -189
- package/src/client.d.ts +0 -26
- package/src/client.js +0 -73
- package/src/errors.d.ts +0 -9
- package/src/errors.js +0 -22
- package/src/git-path.d.ts +0 -15
- package/src/git-path.js +0 -46
- package/src/git-tree.d.ts +0 -18
- package/src/git-tree.js +0 -56
- package/src/git.d.ts +0 -23
- package/src/git.js +0 -40
- package/src/graph-artifacts.d.ts +0 -19
- package/src/graph-artifacts.js +0 -58
- package/src/graph.d.ts +0 -47
- package/src/graph.js +0 -71
- package/src/index.d.ts +0 -11
- package/src/index.js +0 -4
- package/src/options.d.ts +0 -55
- package/src/options.js +0 -15
- package/src/plan-validation.d.ts +0 -10
- package/src/plan-validation.js +0 -38
- package/src/process.js +0 -10
- package/src/prompts.d.ts +0 -47
- package/src/refactor.d.ts +0 -17
- package/src/refactor.js +0 -168
- package/src/report-store.d.ts +0 -9
- package/src/report.d.ts +0 -6
- package/src/report.js +0 -52
- package/src/results.d.ts +0 -80
- package/src/results.js +0 -0
- package/src/run-lifecycle.d.ts +0 -18
- package/src/run-lifecycle.js +0 -100
- package/src/schema.js +0 -31
- package/src/source-inventory.d.ts +0 -9
- package/src/source-inventory.js +0 -17
- package/src/source-policy.d.ts +0 -11
- package/src/source-policy.js +0 -56
- package/src/worktree.d.ts +0 -57
- package/src/worktree.js +0 -195
|
@@ -0,0 +1,180 @@
|
|
|
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
|
+
/** Verify the runner's prompt inputs across modes and check lists. */
|
|
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
|
+
])('prompts describe the mode and host validation 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
|
+
for (const prompt of prompts) {
|
|
21
|
+
expect(prompt).toContain(readOnly ? 'MODE: READ ONLY' : 'MODE: EDIT')
|
|
22
|
+
expect(prompt.includes('Validation commands:')).toBe(!readOnly && checks.length > 0)
|
|
23
|
+
if (!readOnly && checks.length > 0) {
|
|
24
|
+
expect(prompt).toContain(`Validation commands: ${JSON.stringify(checks)}. The host runs them on the combined tree before merging your edits.`)
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
/** Preserve the alternatives and their evidence requirements even when a graph is unavailable. */
|
|
30
|
+
test.each(['read-only', 'edit'] as const)('structural decisions compare keeping, consolidation and extraction in %s mode', mode => {
|
|
31
|
+
const context = { graphFile: null, version: 'snapshot', checks: [], mode }
|
|
32
|
+
const design = designPrompt({ ...context, files: ['api.ts', 'types.ts'] })
|
|
33
|
+
const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Keep the shared policy owner' })
|
|
34
|
+
for (const prompt of [design, module]) {
|
|
35
|
+
const instructions = prompt.replace(/\s+/g, ' ')
|
|
36
|
+
expect(instructions).toContain('compare keeping it, consolidating it into an existing owner and extracting it')
|
|
37
|
+
expect(instructions).toContain('Describe the current reading/editing path')
|
|
38
|
+
expect(instructions).toContain('Prefer an existing cohesive module before creating a new file')
|
|
39
|
+
expect(instructions).toContain('Preserve small modules with useful independent contracts')
|
|
40
|
+
expect(instructions).toContain('Keep related types with their owning feature')
|
|
41
|
+
expect(instructions).toContain('Set no target file count')
|
|
42
|
+
expect(instructions).toContain('An unchanged structure is a valid outcome')
|
|
43
|
+
expect(prompt.split('Optimize for the cost of understanding and changing the code.')).toHaveLength(2)
|
|
44
|
+
expect(prompt).toContain('Static graph unavailable.')
|
|
45
|
+
}
|
|
46
|
+
expect(design).not.toContain('Give each\n its own file')
|
|
47
|
+
expect(design).not.toContain('Split by group')
|
|
48
|
+
expect(design).toContain('Later module agents receive this summary')
|
|
49
|
+
expect(design).toContain('the existing layout from proposed boundaries')
|
|
50
|
+
expect(module).not.toContain('Extract each phase')
|
|
51
|
+
expect(module).toContain('Read the design summary before changing structure')
|
|
52
|
+
expect(module).toContain('explain any revision supported by new source evidence')
|
|
53
|
+
expect(module).toContain('Keep short, cohesive sequences together')
|
|
54
|
+
expect(module).toContain('Keep simple one-use expressions inline')
|
|
55
|
+
expect(module).toContain('Consolidate or split code within this module')
|
|
56
|
+
expect(module).toContain('Preserve the existing-file assignment')
|
|
57
|
+
expect(module).toContain('Edit only the files assigned to this module')
|
|
58
|
+
if (mode === 'read-only') expect(module).toContain('describe resulting edits as proposals')
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
/** Both editing phases receive the same audience/language policy, even when only proposing changes. */
|
|
62
|
+
test.each(['read-only', 'edit'] as const)('documentation guidance reaches both phases in %s mode', mode => {
|
|
63
|
+
const context = { graphFile: 'graph.json', version: 'snapshot', checks: [], mode }
|
|
64
|
+
const prompts = [
|
|
65
|
+
designPrompt({ ...context, files: ['api.ts', 'worker.py'] }),
|
|
66
|
+
modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' }),
|
|
67
|
+
]
|
|
68
|
+
for (const prompt of prompts) {
|
|
69
|
+
const documentation = prompt.replace(/\s+/g, ' ')
|
|
70
|
+
expect(documentation).toContain('An exported declaration is not automatically a supported public API')
|
|
71
|
+
expect(documentation).toContain('an extension interface can be public')
|
|
72
|
+
expect(documentation).toContain('Lead public API comments with the consumer\'s task')
|
|
73
|
+
expect(documentation).toContain('a short contract can be one sentence')
|
|
74
|
+
expect(documentation).toContain('Select the documentation convention for each declaration from its language')
|
|
75
|
+
expect(documentation).toContain('In mixed-language files')
|
|
76
|
+
expect(documentation).toContain('Preserve the exact documentation dialect across phases and moved declarations')
|
|
77
|
+
expect(documentation).toContain('Record identified conventions in the summary')
|
|
78
|
+
expect(documentation).toContain('Examples are not a language allowlist')
|
|
79
|
+
expect(documentation).toContain('For any other language or DSL')
|
|
80
|
+
expect(documentation).toContain('ordinary native comments if no structured convention is established')
|
|
81
|
+
expect(documentation).toContain('Documentation tags are convention-specific, not a universal @ syntax')
|
|
82
|
+
expect(documentation).toContain('Do not transplant TSDoc tags or restrictions into another convention')
|
|
83
|
+
expect(documentation).toContain('Go uses doc comments and prose')
|
|
84
|
+
expect(documentation).toContain('docstrings with the project\'s Sphinx, Google or NumPy style')
|
|
85
|
+
expect(documentation).toContain('C# uses XML documentation')
|
|
86
|
+
expect(documentation).toContain('Do not infer support or release stage')
|
|
87
|
+
expect(documentation).toContain('Verify these claims')
|
|
88
|
+
expect(documentation).toContain('review comments against the final code')
|
|
89
|
+
expect(documentation).toContain('Record documentation changes or proposals in "changes"')
|
|
90
|
+
expect(documentation).toContain('concrete unresolved gaps in "deferred"')
|
|
91
|
+
expect(documentation).toContain('Do not claim unavailable tooling was run')
|
|
92
|
+
expect(documentation).toContain('Correct stale names, unsupported tags and misleading descriptions')
|
|
93
|
+
expect(documentation).toContain('Type annotations, braces, delimiters and tag placement must follow that exact dialect')
|
|
94
|
+
expect(documentation).toContain('Do not describe a returned failure as a thrown exception')
|
|
95
|
+
expect(documentation).toContain('A parser pass alone does not establish semantic accuracy')
|
|
96
|
+
expect(prompt.indexOf('Documentation conventions and tags:')).toBe(prompt.lastIndexOf('Documentation conventions and tags:'))
|
|
97
|
+
if (mode === 'read-only') expect(prompt).toContain('apply this review to proposed comments without editing')
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
|
|
101
|
+
/** Both phases prioritize actual API definitions while preserving executable declaration order. */
|
|
102
|
+
test.each(['read-only', 'edit'] as const)('declaration ordering reaches both phases in %s mode', mode => {
|
|
103
|
+
const context = { graphFile: 'graph.json', version: 'snapshot', checks: [], mode }
|
|
104
|
+
const prompts = [
|
|
105
|
+
designPrompt({ ...context, files: ['api.ts'] }),
|
|
106
|
+
modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' }),
|
|
107
|
+
]
|
|
108
|
+
for (const prompt of prompts) {
|
|
109
|
+
const instructions = prompt.replace(/\s+/g, ' ')
|
|
110
|
+
expect(instructions).toContain('Keep license/file comments and imports at the beginning')
|
|
111
|
+
expect(instructions).toContain('exported types/interfaces, functions and classes before unexported implementation helpers')
|
|
112
|
+
expect(instructions).toContain('move the actual declaration, not just its export statement')
|
|
113
|
+
expect(instructions).toContain('constructor and public methods/accessors first')
|
|
114
|
+
expect(instructions).toContain('Include implicitly public members and static public methods')
|
|
115
|
+
expect(instructions).toContain('do not change visibility')
|
|
116
|
+
expect(instructions).toContain('Preserve overload order')
|
|
117
|
+
expect(instructions).toContain('field initialization order, static blocks, computed names and decorator evaluation')
|
|
118
|
+
expect(instructions).toContain('report the concrete constraint in "deferred"')
|
|
119
|
+
expect(instructions).toContain('do not skip safe ordering changes elsewhere')
|
|
120
|
+
expect(prompt.indexOf('Declaration order:')).toBe(prompt.lastIndexOf('Declaration order:'))
|
|
121
|
+
if (mode === 'read-only') expect(prompt).toContain('propose the reordering without editing files')
|
|
122
|
+
}
|
|
123
|
+
expect(prompts[0]).toContain('Apply declaration ordering to files affected by boundary changes')
|
|
124
|
+
expect(prompts[1]).toContain('public class methods hidden below internal implementation helpers')
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
/** Verify that phase-specific scope survives shared guidance and checks stay with the host. */
|
|
128
|
+
test('documentation scope is phase-specific and planning remains inventory-only', () => {
|
|
129
|
+
const files = ['api.ts']
|
|
130
|
+
const context = {
|
|
131
|
+
graphFile: 'graph.json', version: 'snapshot', mode: 'edit' as const,
|
|
132
|
+
checks: [{ executable: 'bun', args: ['run', 'typecheck'] }],
|
|
133
|
+
}
|
|
134
|
+
const design = designPrompt({ ...context, files })
|
|
135
|
+
const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' })
|
|
136
|
+
expect(design).toContain('preserve contract comments on moved declarations')
|
|
137
|
+
expect(design).toContain('Do not perform a repository-wide comment rewrite')
|
|
138
|
+
expect(design).not.toContain('Module documentation scope:')
|
|
139
|
+
expect(module).toContain('including declarations\nwhose implementation stays unchanged')
|
|
140
|
+
expect(module).toContain('keep accurate concise comments without cosmetic rewrites')
|
|
141
|
+
expect(module).not.toContain('Design documentation scope:')
|
|
142
|
+
const planning = planPrompt(files, 'snapshot')
|
|
143
|
+
expect(planning).not.toContain('Documentation conventions and tags:')
|
|
144
|
+
expect(planning).toContain('cohesive review/edit task groups')
|
|
145
|
+
expect(planning).toContain('Keep files that require coordinated edits in the same assignment')
|
|
146
|
+
expect(planning).toContain('Plan against the existing inventory')
|
|
147
|
+
expect(planning).toContain('Assign every listed source file exactly once')
|
|
148
|
+
expect(planning).toContain('Do not review or edit yet')
|
|
149
|
+
const hostChecks = `Validation commands: ${JSON.stringify(context.checks)}. The host runs them on the combined tree before merging your edits.`
|
|
150
|
+
for (const prompt of [design, module]) {
|
|
151
|
+
expect(prompt).toContain(hostChecks)
|
|
152
|
+
expect(prompt).not.toContain('Run them before returning')
|
|
153
|
+
}
|
|
154
|
+
expect(module).toContain('Other modules may run concurrently.')
|
|
155
|
+
expect(design).not.toContain('Other modules may run concurrently.')
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
/** Module IDs keep the existing alphabet and length boundaries, including uppercase letters and underscores. */
|
|
159
|
+
test.each(['a', 'A_0-module', 'a'.repeat(80)])('accepts safe module ID %s', id => {
|
|
160
|
+
const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
|
|
161
|
+
expect(() => validatePlan(candidate, ['a.ts'])).not.toThrow()
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
/** Reject path components and out-of-policy IDs before their values can reach reports. */
|
|
165
|
+
test.each(['', '../escape', 'a/b', 'a\\b', '_module', '-module', 'a.b', 'a b', 'a'.repeat(81)])('rejects unsafe module ID %s', id => {
|
|
166
|
+
const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
|
|
167
|
+
expect(() => validatePlan(candidate, ['a.ts'])).toThrow(`modules[0].id: ${JSON.stringify(id)} must start with an ASCII letter or digit`)
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
test('plan validation reports all issues in traversal and inventory order', () => {
|
|
171
|
+
const first = plan.modules[0]!
|
|
172
|
+
const second = plan.modules[1]!
|
|
173
|
+
const candidate = { ...plan, modules: [first, { ...second, id: 'A', files: ['extra.ts', 'a.ts'] }] }
|
|
174
|
+
expect(() => validatePlan(candidate, ['c.ts', 'a.ts', 'b.ts'])).toThrow([
|
|
175
|
+
'modules[1].id: "A" duplicates modules[0].id ignoring case',
|
|
176
|
+
'modules[1].files[0]: "extra.ts" is absent from the inventory',
|
|
177
|
+
'modules[1].files[1]: "a.ts" was already assigned at modules[0].files[0]',
|
|
178
|
+
'Module plan omitted source files: "c.ts", "b.ts"',
|
|
179
|
+
].join('\n'))
|
|
180
|
+
})
|
|
@@ -0,0 +1,378 @@
|
|
|
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 { HarnessSdkError } from '@anureo/sdk'
|
|
8
|
+
import { runCli } from '../src/cli'
|
|
9
|
+
import { refactorHarnesses } from '../src/client'
|
|
10
|
+
import { loadGraph } from '../src/graph'
|
|
11
|
+
import { exec } from '../src/process'
|
|
12
|
+
import { edited, fixture, moduleOf, plan, temporary, unchanged } from './helpers'
|
|
13
|
+
|
|
14
|
+
/** Exercise argument/help precedence without acquiring a client; failures remain CLI diagnostics. */
|
|
15
|
+
test('help and invalid arguments do not construct a backend', async () => {
|
|
16
|
+
let created = 0
|
|
17
|
+
let errors = ''
|
|
18
|
+
const dependencies = {
|
|
19
|
+
stdout: () => {}, stderr: (text: string) => { errors += text },
|
|
20
|
+
createClient: async () => { created++; throw new Error('Unexpected backend') },
|
|
21
|
+
}
|
|
22
|
+
expect(await runCli(['--help'], dependencies)).toBe(0)
|
|
23
|
+
expect(await runCli(['--help', 'a', 'b', '--check', ' '], dependencies)).toBe(0)
|
|
24
|
+
for (const args of [
|
|
25
|
+
['--unknown'], ['--concurrency', '0'], ['--concurrency', '1.5'], ['a', 'b'], ['--check', ' '],
|
|
26
|
+
['--check-argv', '[]'], ['--check-argv', '["git", 1]'], ['--no-graph', '--repograph', 'other.ts'],
|
|
27
|
+
['--harness', 'unknown'], ['--harness', 'acp'], ['--harness-url', 'ws://localhost:3000'],
|
|
28
|
+
['--harness', 'ahp', '--harness-command', 'peer', '--harness-url', 'ws://localhost:3000'],
|
|
29
|
+
]) {
|
|
30
|
+
expect(await runCli(args, dependencies)).toBe(2)
|
|
31
|
+
}
|
|
32
|
+
expect(created).toBe(0)
|
|
33
|
+
expect(errors).toContain('anureo-refactor: --concurrency must be a positive integer\n')
|
|
34
|
+
expect(errors).toContain('anureo-refactor: --check commands must be nonempty\n')
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('CLI limits concurrent module sessions while running every planned module', async () => {
|
|
38
|
+
let active = 0
|
|
39
|
+
let peak = 0
|
|
40
|
+
const modules = Array.from({ length: 10 }, (_, index) => ({
|
|
41
|
+
id: `module-${index}`, name: `Module ${index}`, description: 'Fixture module',
|
|
42
|
+
files: [`module-${index}.ts`],
|
|
43
|
+
}))
|
|
44
|
+
const firstWorkersReady = Promise.withResolvers<void>()
|
|
45
|
+
const context = await fixture(async prompt => {
|
|
46
|
+
if (prompt.startsWith('PLAN')) return { summary: plan.summary, modules }
|
|
47
|
+
if (!moduleOf(prompt)) return unchanged
|
|
48
|
+
peak = Math.max(peak, ++active)
|
|
49
|
+
if (active === 8) firstWorkersReady.resolve()
|
|
50
|
+
await firstWorkersReady.promise
|
|
51
|
+
active--
|
|
52
|
+
return unchanged
|
|
53
|
+
})
|
|
54
|
+
await Promise.all(modules.map(module => writeFile(join(context.cwd, module.files[0]!), 'export {}\n')))
|
|
55
|
+
let output = ''
|
|
56
|
+
const code = await runCli([
|
|
57
|
+
context.cwd, '--include', 'module-*.ts', '--concurrency', '8', '--review-only', '--no-graph', '--json',
|
|
58
|
+
], {
|
|
59
|
+
stdout: text => { output += text }, stderr: () => {}, createClient: async () => context.client,
|
|
60
|
+
})
|
|
61
|
+
expect({ code, errors: JSON.parse(output).errors }).toEqual({ code: 0, errors: [] })
|
|
62
|
+
expect(peak).toBe(8)
|
|
63
|
+
expect(JSON.parse(output).modules.map((result: { module: { id: string } }) => result.module.id))
|
|
64
|
+
.toEqual(modules.map(module => module.id))
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test.each([...refactorHarnesses])('CLI dispatches %s with the matching permission and model settings', async id => {
|
|
68
|
+
const context = await fixture()
|
|
69
|
+
const transport = id === 'acp' ? ['--harness-command', 'agent', '--harness-arg=--stdio']
|
|
70
|
+
: id === 'ahp' ? ['--harness-url', 'ws://localhost:3000'] : []
|
|
71
|
+
const code = await runCli([context.cwd, '--harness', id, ...transport, '--review-only'], {
|
|
72
|
+
...context, env: { CODEX_MODEL: 'codex-fixture' }, stdout: () => {}, stderr: () => {},
|
|
73
|
+
createClient: async (cwd, selection) => {
|
|
74
|
+
expect(cwd).toBe(context.cwd)
|
|
75
|
+
expect(selection.id).toBe(id)
|
|
76
|
+
if (id === 'acp') expect(selection).toMatchObject({ command: 'agent', args: ['--stdio'] })
|
|
77
|
+
if (id === 'ahp') expect(selection.url).toBe('ws://localhost:3000')
|
|
78
|
+
return context.client
|
|
79
|
+
},
|
|
80
|
+
})
|
|
81
|
+
expect(code).toBe(0)
|
|
82
|
+
const mode = id === 'claude' ? 'plan' : id === 'codex' || id === 'pi' ? 'read-only' : undefined
|
|
83
|
+
expect(context.adapter.opened).toHaveLength(4)
|
|
84
|
+
for (const session of context.adapter.opened) {
|
|
85
|
+
expect(session.permissionMode).toBe(mode)
|
|
86
|
+
expect(session.model).toBe(id === 'codex' ? 'codex-fixture' : undefined)
|
|
87
|
+
}
|
|
88
|
+
expect(context.adapter.disposeCount).toBe(1)
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
test.each(['acp', 'ahp'])('installed CLI completes a run over a scripted %s stdio peer', async id => {
|
|
92
|
+
const target = await temporary()
|
|
93
|
+
await exec('git', ['init', '-q', target])
|
|
94
|
+
await writeFile(join(target, 'task.custom'), 'do work\n')
|
|
95
|
+
const peer = fileURLToPath(new URL(`./fixtures/${id}.mjs`, import.meta.url))
|
|
96
|
+
const { stdout } = await runInstalledCli([
|
|
97
|
+
target, '--harness', id, '--harness-command', process.execPath, '--harness-arg', peer,
|
|
98
|
+
'--no-graph', '--review-only', '--json',
|
|
99
|
+
])
|
|
100
|
+
expect(JSON.parse(stdout)).toMatchObject({
|
|
101
|
+
status: 'completed', plan: { modules: [{ files: ['task.custom'] }] },
|
|
102
|
+
modules: [{ step: { status: 'unchanged' } }],
|
|
103
|
+
})
|
|
104
|
+
}, 25_000)
|
|
105
|
+
|
|
106
|
+
test('installed CLI completes a run through the Claude SDK with native structured output', async () => {
|
|
107
|
+
const target = await temporary()
|
|
108
|
+
const state = await temporary()
|
|
109
|
+
await exec('git', ['init', '-q', target])
|
|
110
|
+
await writeFile(join(target, 'script.rb'), 'puts "hello"\n')
|
|
111
|
+
const claude = fileURLToPath(new URL('../../../packages/adapter/claude/tests/fixtures/fake-claude.mjs', import.meta.url))
|
|
112
|
+
const answer = fileURLToPath(new URL('./fixtures/answer.mjs', import.meta.url))
|
|
113
|
+
const { stdout } = await runInstalledCli([
|
|
114
|
+
target, '--harness', 'claude', '--no-graph', '--review-only', '--json',
|
|
115
|
+
], { env: { ...process.env, CLAUDE_BIN: claude, CLAUDE_CONFIG_DIR: state, FAKE_STRUCTURED_ANSWER: answer } })
|
|
116
|
+
expect(JSON.parse(stdout)).toMatchObject({
|
|
117
|
+
status: 'completed', plan: { modules: [{ files: ['script.rb'] }] },
|
|
118
|
+
})
|
|
119
|
+
}, 25_000)
|
|
120
|
+
|
|
121
|
+
/** Run scripted agents through the CLI; the shared fixture removes the repository after assertions. */
|
|
122
|
+
test('CLI reports completion and owns client cleanup', async () => {
|
|
123
|
+
const context = await fixture(prompt => prompt.startsWith('PLAN') ? plan : moduleOf(prompt) === 'a' ? edited() : unchanged)
|
|
124
|
+
let output = ''
|
|
125
|
+
const code = await runCli([context.cwd, '--review-only', '--json'], {
|
|
126
|
+
...context, createClient: async () => context.client,
|
|
127
|
+
stdout: text => { output += text }, stderr: () => {},
|
|
128
|
+
})
|
|
129
|
+
expect(code).toBe(0)
|
|
130
|
+
expect(JSON.parse(output)).toMatchObject({ status: 'completed', reviewOnly: true })
|
|
131
|
+
expect(context.adapter.disposeCount).toBe(1)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
/** Check primary/cleanup error precedence and awaited disposal after preflight or report output.
|
|
135
|
+
* Each case uses a real scripted client; the one-shot disposal override releases it before failing. */
|
|
136
|
+
test.each([
|
|
137
|
+
{ failure: 'none', cleanupError: null },
|
|
138
|
+
{ failure: 'none', cleanupError: 'Disposal unavailable' },
|
|
139
|
+
{ failure: 'incomplete', cleanupError: 'Disposal unavailable' },
|
|
140
|
+
{ failure: 'output', cleanupError: null },
|
|
141
|
+
{ failure: 'output', cleanupError: 'Disposal unavailable' },
|
|
142
|
+
{ failure: 'preflight', cleanupError: null },
|
|
143
|
+
{ failure: 'preflight', cleanupError: 'Disposal unavailable' },
|
|
144
|
+
])('CLI handles $failure failure with cleanup error $cleanupError', async ({ failure, cleanupError }) => {
|
|
145
|
+
const context = await fixture()
|
|
146
|
+
const events: string[] = []
|
|
147
|
+
let output = ''
|
|
148
|
+
let errors = ''
|
|
149
|
+
const dispose = context.client.dispose.bind(context.client)
|
|
150
|
+
/** Release actual SDK resources before injecting a rejection, leaving shared cleanup safe to retry. */
|
|
151
|
+
const disposal = spyOn(context.client, 'dispose').mockImplementationOnce(async () => {
|
|
152
|
+
await dispose()
|
|
153
|
+
events.push('disposed')
|
|
154
|
+
if (cleanupError) throw new Error(cleanupError)
|
|
155
|
+
})
|
|
156
|
+
try {
|
|
157
|
+
const cwd = failure === 'preflight' ? join(context.cwd, 'missing') : context.cwd
|
|
158
|
+
const code = await runCli([cwd, '--json'], {
|
|
159
|
+
...context, createClient: async () => context.client,
|
|
160
|
+
graphLoader: failure === 'incomplete' ? async () => { throw new Error('Graph unavailable') } : context.graphLoader,
|
|
161
|
+
/** Record report delivery before optionally failing the sink to exercise post-run cleanup. */
|
|
162
|
+
stdout: text => {
|
|
163
|
+
output += text
|
|
164
|
+
events.push('report')
|
|
165
|
+
if (failure === 'output') throw new Error('Output unavailable')
|
|
166
|
+
},
|
|
167
|
+
stderr: text => { errors += text },
|
|
168
|
+
})
|
|
169
|
+
expect(code).toBe(failure === 'none' && !cleanupError ? 0 : 2)
|
|
170
|
+
expect(events).toEqual(failure === 'preflight' ? ['disposed'] : ['report', 'disposed'])
|
|
171
|
+
expect(disposal).toHaveBeenCalledTimes(1)
|
|
172
|
+
expect(context.adapter.disposeCount).toBe(1)
|
|
173
|
+
if (failure === 'preflight') {
|
|
174
|
+
expect(output).toBe('')
|
|
175
|
+
expect(errors).toContain('missing')
|
|
176
|
+
expect(errors).toContain('anureo-refactor: ')
|
|
177
|
+
} else {
|
|
178
|
+
expect(JSON.parse(output).status).toBe(failure === 'incomplete' ? 'incomplete' : 'completed')
|
|
179
|
+
if (failure === 'output') expect(errors).toContain('anureo-refactor: Output unavailable\n')
|
|
180
|
+
}
|
|
181
|
+
if (cleanupError) {
|
|
182
|
+
const executionThrew = failure === 'output' || failure === 'preflight'
|
|
183
|
+
const diagnostic = `anureo-refactor: ${executionThrew ? 'cleanup failed: ' : ''}${cleanupError}\n`
|
|
184
|
+
expect(errors).toContain(diagnostic)
|
|
185
|
+
expect(errors.endsWith(diagnostic)).toBe(!executionThrew)
|
|
186
|
+
if (!executionThrew) expect(errors).not.toContain('cleanup failed:')
|
|
187
|
+
} else {
|
|
188
|
+
expect(errors).not.toContain('cleanup failed:')
|
|
189
|
+
if (failure === 'none') expect(errors).not.toContain('anureo-refactor:')
|
|
190
|
+
}
|
|
191
|
+
} finally { disposal.mockRestore() }
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
/** A reported orchestration failure still prints JSON and disposes the CLI client before returning 2. */
|
|
195
|
+
test('CLI prints an incomplete report and cleans up its client', async () => {
|
|
196
|
+
const context = await fixture()
|
|
197
|
+
let output = ''
|
|
198
|
+
const code = await runCli([context.cwd, '--json'], {
|
|
199
|
+
...context, createClient: async () => context.client,
|
|
200
|
+
graphLoader: async () => { throw new Error('Graph unavailable') },
|
|
201
|
+
stdout: text => { output += text }, stderr: () => {},
|
|
202
|
+
})
|
|
203
|
+
expect(code).toBe(2)
|
|
204
|
+
expect(JSON.parse(output)).toMatchObject({ status: 'incomplete', errors: ['Graph unavailable'] })
|
|
205
|
+
expect(context.adapter.disposeCount).toBe(1)
|
|
206
|
+
expect(context.prompts).toHaveLength(0)
|
|
207
|
+
})
|
|
208
|
+
|
|
209
|
+
test('CLI text keeps agent text within each field and preserves raw report data', async () => {
|
|
210
|
+
const summary = 'Summary\x1b[2J\nResult: failed'
|
|
211
|
+
const context = await fixture(prompt => prompt.startsWith('PLAN') ? {
|
|
212
|
+
...plan, summary,
|
|
213
|
+
modules: plan.modules.map(module => ({ ...module, name: module.name + '\rName' })),
|
|
214
|
+
} : {
|
|
215
|
+
...unchanged, summary, changes: ['Change\ttext'],
|
|
216
|
+
deferred: [{ title: 'Title\x9b', reason: 'Reason\u2028Error: fake' }],
|
|
217
|
+
})
|
|
218
|
+
let output = ''
|
|
219
|
+
const code = await runCli([context.cwd, '--review-only', '--no-graph'], {
|
|
220
|
+
createClient: async () => context.client, stdout: text => { output += text }, stderr: () => {},
|
|
221
|
+
})
|
|
222
|
+
expect(code).toBe(0)
|
|
223
|
+
expect(output).toContain('Refactor: completed (review only)\n')
|
|
224
|
+
expect(output).toContain('Summary\\u001b[2J\\u000aResult: failed')
|
|
225
|
+
expect(output).toContain('a: A\\u000dName')
|
|
226
|
+
expect(output).toContain('- Change\\u0009text')
|
|
227
|
+
expect(output).toContain('Deferred Title\\u009b: Reason\\u2028Error: fake')
|
|
228
|
+
expect(output).not.toContain('\nResult: failed')
|
|
229
|
+
expect(output).not.toContain('\x1b')
|
|
230
|
+
const reportPath = /^Report: (.+)$/m.exec(output)![1]!
|
|
231
|
+
const report = JSON.parse(await readFile(reportPath, 'utf8'))
|
|
232
|
+
expect(report.plan.summary).toBe(summary)
|
|
233
|
+
expect(report.design.summary).toBe(summary)
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
test.each([
|
|
237
|
+
{
|
|
238
|
+
plannerOutput: new HarnessSdkError('RECEIPT_LOST', 'Planning outcome unavailable', true, true),
|
|
239
|
+
code: 'RECEIPT_LOST', retryable: true,
|
|
240
|
+
diagnostics: ['Agent execution outcome is unknown'],
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
plannerOutput: { summary: 123, modules: [] },
|
|
244
|
+
code: 'STRUCTURED_OUTPUT_INVALID', retryable: false,
|
|
245
|
+
diagnostics: ['Validation issue: /summary [type]', 'Validation issue: /modules [minItems]'],
|
|
246
|
+
},
|
|
247
|
+
])('CLI displays planning diagnostics for $code', async ({ plannerOutput, code, retryable, diagnostics }) => {
|
|
248
|
+
const context = await fixture(prompt => prompt.startsWith('PLAN') ? plannerOutput : unchanged)
|
|
249
|
+
let output = ''
|
|
250
|
+
const exitCode = await runCli([context.cwd, '--review-only', '--no-graph'], {
|
|
251
|
+
createClient: async () => context.client, stdout: text => { output += text }, stderr: () => {},
|
|
252
|
+
})
|
|
253
|
+
expect(exitCode).toBe(2)
|
|
254
|
+
for (const diagnostic of diagnostics) expect(output).toContain(diagnostic)
|
|
255
|
+
const reportPath = /^Report: (.+)$/m.exec(output)![1]!
|
|
256
|
+
const report = JSON.parse(await readFile(reportPath, 'utf8'))
|
|
257
|
+
expect(report).toMatchObject({ plan: null, failure: { code, retryable } })
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
/** Use the deterministic graph executable to verify transport/JSON handling without live indexing. */
|
|
261
|
+
test('graph adapter invokes the real subprocess interface and reads its JSON', async () => {
|
|
262
|
+
const context = await fixture()
|
|
263
|
+
const entry = fileURLToPath(new URL('./fixtures/repograph.ts', import.meta.url))
|
|
264
|
+
const graph = await loadGraph(context.cwd, entry)
|
|
265
|
+
expect(graph.kind).toBe('all')
|
|
266
|
+
expect(graph.nodes[0]?.filePath).toBe('main.ts')
|
|
267
|
+
expect(graph.nodes[0]?.callable).toEqual({ parameters: [], returnType: 'number' })
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
/** Launch the installed entry outside its target with scripted Codex/repograph executables, then
|
|
271
|
+
* compare stdout with the persisted report. Temporary repositories are fixture-owned;
|
|
272
|
+
* executable failures/timeouts reject the test. No model calls or live indexing are involved. */
|
|
273
|
+
test('installed CLI entry runs from an unrelated cwd through real Codex and graph process boundaries', async () => {
|
|
274
|
+
const target = await temporary()
|
|
275
|
+
const outside = await temporary()
|
|
276
|
+
await writeFile(join(target, 'main.ts'), 'export function main() { return 1 }\n')
|
|
277
|
+
await writeFile(join(target, 'task.dsl'), 'do work\n')
|
|
278
|
+
await exec('git', ['init', '-q', target])
|
|
279
|
+
const repograph = fileURLToPath(new URL('./fixtures/repograph.ts', import.meta.url))
|
|
280
|
+
const { stdout, stderr } = await runInstalledCli([target, '--review-only', '--repograph', repograph, '--json'], {
|
|
281
|
+
cwd: outside, env: { ...process.env, CODEX_BIN: codexFixture }, maxBuffer: 1 << 20,
|
|
282
|
+
})
|
|
283
|
+
const report = JSON.parse(stdout)
|
|
284
|
+
expect(report).toMatchObject({ status: 'completed', reviewOnly: true })
|
|
285
|
+
expect(report.modules[0].module.id).toBe('main')
|
|
286
|
+
expect(report.graphCoverage).toEqual([{ phase: 'design', status: 'available', filesWithoutSymbols: ['task.dsl'] }])
|
|
287
|
+
expect(stderr).toContain('module/main: unchanged')
|
|
288
|
+
expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
|
|
289
|
+
}, 25_000)
|
|
290
|
+
|
|
291
|
+
test('installed CLI edits a mixed-language repository and runs ordered checks without a graph', async () => {
|
|
292
|
+
const target = join(await temporary(), 'mixed 项目')
|
|
293
|
+
const outside = await temporary()
|
|
294
|
+
await mkdir(target)
|
|
295
|
+
await exec('git', ['init', '-q', target])
|
|
296
|
+
for (const [file, content] of Object.entries({
|
|
297
|
+
'main.py': 'def main(): return 1\r\n', 'worker.zig': 'pub fn run() void {}\n',
|
|
298
|
+
'start': '#!/bin/sh\nexit 0\n', 'job 配置.custom': 'task = "main"\n',
|
|
299
|
+
'excluded.custom': 'task = "ignore"\n', 'binary.custom': Buffer.from([0, 0xff]),
|
|
300
|
+
'README.md': '# Project\n', 'secret.txt': 'outside the include patterns\n',
|
|
301
|
+
})) await writeFile(join(target, file), content)
|
|
302
|
+
const literal = 'label with spaces & symbols %! ${value}'
|
|
303
|
+
const check = [
|
|
304
|
+
process.execPath, '-e',
|
|
305
|
+
'if (process.argv[1] !== "label with spaces & symbols %! ${value}") process.exit(7); console.log("verified")',
|
|
306
|
+
literal,
|
|
307
|
+
]
|
|
308
|
+
const { stdout } = await runInstalledCli([
|
|
309
|
+
target, '--no-graph', '--json', '--include', '**/*.{py,zig,custom}',
|
|
310
|
+
'--include', 'start', '--exclude', 'excluded.*', '--check-argv', JSON.stringify(check),
|
|
311
|
+
'--check', 'git rev-parse --is-inside-work-tree',
|
|
312
|
+
], {
|
|
313
|
+
cwd: outside, env: { ...process.env, CODEX_BIN: codexFixture, REFACTOR_FIXTURE_EDIT: 'job 配置.custom' },
|
|
314
|
+
maxBuffer: 1 << 20,
|
|
315
|
+
})
|
|
316
|
+
const report = JSON.parse(stdout)
|
|
317
|
+
const files = ['job 配置.custom', 'main.py', 'start', 'worker.zig']
|
|
318
|
+
expect(report.status).toBe('completed')
|
|
319
|
+
expect(report.modules[0].module.files).toEqual(files)
|
|
320
|
+
expect(report.modules[0].step).toMatchObject({
|
|
321
|
+
status: 'applied', changedFiles: ['job 配置.custom'],
|
|
322
|
+
checks: [{ status: 'passed', output: expect.stringContaining('verified') },
|
|
323
|
+
{ status: 'passed', output: expect.stringContaining('true') }],
|
|
324
|
+
})
|
|
325
|
+
expect(report.graphCoverage).toEqual([{ phase: 'design', status: 'disabled', filesWithoutSymbols: files }])
|
|
326
|
+
expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
|
|
327
|
+
}, 25_000)
|
|
328
|
+
|
|
329
|
+
test.skipIf(process.platform === 'win32')('installed CLI resolves a native Codex override against the target', async () => {
|
|
330
|
+
const outside = await temporary()
|
|
331
|
+
const target = join(outside, 'target')
|
|
332
|
+
await mkdir(target)
|
|
333
|
+
await exec('git', ['init', '-q', target])
|
|
334
|
+
await writeFile(join(target, 'main.ts'), 'export {}\n')
|
|
335
|
+
await writeFile(join(outside, 'codex-peer'), '#!/bin/sh\nexec "$REFACTOR_TEST_BUN" "$REFACTOR_TEST_CODEX" "$@"\n', { mode: 0o755 })
|
|
336
|
+
const { stdout } = await runInstalledCli([target, '--no-graph', '--review-only', '--json'], {
|
|
337
|
+
cwd: outside,
|
|
338
|
+
env: { ...process.env, CODEX_BIN: '../codex-peer', REFACTOR_TEST_BUN: process.execPath, REFACTOR_TEST_CODEX: codexFixture },
|
|
339
|
+
})
|
|
340
|
+
expect(JSON.parse(stdout)).toMatchObject({ status: 'completed', modules: [{ step: { status: 'unchanged' } }] })
|
|
341
|
+
}, 25_000)
|
|
342
|
+
|
|
343
|
+
test('CLI automatically falls back when the optional graph package is absent', async () => {
|
|
344
|
+
const target = await temporary()
|
|
345
|
+
const isolated = await temporary()
|
|
346
|
+
await exec('git', ['init', '-q', target])
|
|
347
|
+
await writeFile(join(target, 'program.unknown-dsl'), 'do work\n')
|
|
348
|
+
const isolatedEntry = join(isolated, manifest.bin['anureo-refactor'])
|
|
349
|
+
await cp(join(packageDirectory, 'src'), join(isolated, 'src'), { recursive: true })
|
|
350
|
+
await mkdir(dirname(isolatedEntry), { recursive: true })
|
|
351
|
+
await cp(installedEntry, isolatedEntry)
|
|
352
|
+
await mkdir(join(isolated, 'node_modules', '@anureo'), { recursive: true })
|
|
353
|
+
for (const name of Object.keys(manifest.dependencies)) {
|
|
354
|
+
const directory = await realpath(join(packageDirectory, 'node_modules', name))
|
|
355
|
+
await symlink(directory, join(isolated, 'node_modules', name), 'junction')
|
|
356
|
+
}
|
|
357
|
+
const { stdout, stderr } = await exec(process.execPath, [
|
|
358
|
+
isolatedEntry, target, '--review-only', '--json',
|
|
359
|
+
], { cwd: isolated, env: { ...process.env, CODEX_BIN: codexFixture }, timeout: 20_000 })
|
|
360
|
+
expect(JSON.parse(stdout)).toMatchObject({
|
|
361
|
+
status: 'completed',
|
|
362
|
+
graphCoverage: [{ phase: 'design', status: 'unavailable', filesWithoutSymbols: ['program.unknown-dsl'] }],
|
|
363
|
+
})
|
|
364
|
+
expect(stderr).toContain('continuing with source')
|
|
365
|
+
}, 25_000)
|
|
366
|
+
|
|
367
|
+
const codexFixture = fileURLToPath(new URL('./fixtures/codex.mjs', import.meta.url))
|
|
368
|
+
const packageDirectory = fileURLToPath(new URL('../', import.meta.url))
|
|
369
|
+
const manifest = createRequire(import.meta.url)(join(packageDirectory, 'package.json')) as {
|
|
370
|
+
bin: { 'anureo-refactor': string }
|
|
371
|
+
dependencies: Record<string, string>
|
|
372
|
+
}
|
|
373
|
+
const installedEntry = join(packageDirectory, manifest.bin['anureo-refactor'])
|
|
374
|
+
|
|
375
|
+
/** Run the manifest-declared CLI in a child with a 20-second timeout. */
|
|
376
|
+
async function runInstalledCli(args: string[], options: { cwd?: string; env?: NodeJS.ProcessEnv; maxBuffer?: number } = {}) {
|
|
377
|
+
return exec(process.execPath, [installedEntry, ...args], { ...options, timeout: 20_000 })
|
|
378
|
+
}
|
|
@@ -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
|
+
}
|