@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,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,24 @@
|
|
|
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 { realpath, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { isAbsolute, join, 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
|
+
const project = args[args.indexOf('--project') + 1]
|
|
11
|
+
// Keeping the export outside the target prevents a later export from indexing it.
|
|
12
|
+
const relativeOutput = relative(repositoryPath, output)
|
|
13
|
+
if (!isAbsolute(relativeOutput) && !relativeOutput.startsWith(`..${sep}`) && relativeOutput !== '..') process.exit(4)
|
|
14
|
+
await writeFile(output, JSON.stringify({
|
|
15
|
+
schemaVersion: 1, kind: 'all', repositoryPath, project, generatedAt: new Date().toISOString(),
|
|
16
|
+
files: { 'main.ts': { lines: 1 } }, indexReport: { status: 'indexed' },
|
|
17
|
+
nodes: [{ id: 'main', name: 'main', filePath: 'main.ts', labels: ['Function'], startLine: 1, endLine: 1,
|
|
18
|
+
callable: { parameters: [], returnType: 'number' } },
|
|
19
|
+
...[
|
|
20
|
+
['relative', './relative.ts'], ['absolute', join(repositoryPath, 'absolute.ts')],
|
|
21
|
+
['canonical', join(await realpath(repositoryPath), 'canonical.ts')],
|
|
22
|
+
].map(([name, filePath]) => ({ id: name, name, filePath, labels: ['Function'], startLine: 1, endLine: 1 }))],
|
|
23
|
+
edges: [],
|
|
24
|
+
}))
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Exercises the subprocess graph adapter, with optional live Repograph coverage.
|
|
2
|
+
import { expect, test } from 'bun:test'
|
|
3
|
+
import { mkdir, readFile, realpath, symlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
import { fileURLToPath } from 'node:url'
|
|
7
|
+
import { loadGraph, repographProject, resolveRepographEntry } from '../src/graph'
|
|
8
|
+
import { exportGraph, type GraphArtifactContext } from '../src/graph-artifacts'
|
|
9
|
+
import { exec } from '../src/process'
|
|
10
|
+
import { temporary } from './helpers'
|
|
11
|
+
|
|
12
|
+
test('graph artifacts retain metadata and cover symbols under either spelling of the target', async () => {
|
|
13
|
+
const outside = await temporary()
|
|
14
|
+
const cwd = await realpath(await temporary())
|
|
15
|
+
const directory = join(cwd, '.anureo', 'refactor', 'run')
|
|
16
|
+
const alias = join(outside, 'alias')
|
|
17
|
+
await exec('git', ['init', '-q', cwd])
|
|
18
|
+
await mkdir(directory, { recursive: true })
|
|
19
|
+
await writeFile(join(dirname(directory), '.gitignore'), 'writer.lock\n')
|
|
20
|
+
await symlink(cwd, alias, 'junction')
|
|
21
|
+
const entry = fileURLToPath(new URL('./fixtures/repograph.ts', import.meta.url))
|
|
22
|
+
const context: GraphArtifactContext = {
|
|
23
|
+
options: { cwd, graphLoader: async () => {
|
|
24
|
+
expect(await readFile(join(directory, '.gitignore'), 'utf8')).toBe('*\n')
|
|
25
|
+
return loadGraph(alias, entry)
|
|
26
|
+
} },
|
|
27
|
+
report: { directory, graphCoverage: [] }, progress: () => {},
|
|
28
|
+
}
|
|
29
|
+
const file = await exportGraph(context, 'design', ['main.ts', 'relative.ts', 'absolute.ts', 'canonical.ts', 'missing.ts'])
|
|
30
|
+
expect(context.report.graphCoverage).toEqual([{ phase: 'design', status: 'available', filesWithoutSymbols: ['missing.ts'] }])
|
|
31
|
+
expect(JSON.parse(await readFile(file!, 'utf8'))).toMatchObject({
|
|
32
|
+
repositoryPath: alias, project: repographProject(alias), generatedAt: expect.any(String), files: { 'main.ts': { lines: 1 } },
|
|
33
|
+
})
|
|
34
|
+
await exec('git', ['-C', cwd, 'check-ignore', '--quiet', file!])
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
test('graph validation reports duplicate nodes and missing edge endpoints together', async () => {
|
|
38
|
+
const cwd = await temporary()
|
|
39
|
+
const entry = join(cwd, 'invalid.mjs')
|
|
40
|
+
await writeFile(entry, `
|
|
41
|
+
import { writeFileSync } from 'node:fs'
|
|
42
|
+
const node = { id: 'duplicate', name: 'main', filePath: 'main.ts', labels: ['Function'], startLine: 1, endLine: 1 }
|
|
43
|
+
writeFileSync(process.argv.at(-1), JSON.stringify({
|
|
44
|
+
schemaVersion: 1, kind: 'all', repositoryPath: process.argv[3], indexReport: {}, nodes: [node, node],
|
|
45
|
+
edges: [{ id: 'bad-edge', source: 'missing-source', target: 'missing-target', type: 'CALLS' }],
|
|
46
|
+
}))
|
|
47
|
+
`)
|
|
48
|
+
await expect(loadGraph(cwd, entry)).rejects.toThrow(
|
|
49
|
+
'Duplicate node ID "duplicate"\nEdge "bad-edge" references missing node IDs ["missing-source","missing-target"]',
|
|
50
|
+
)
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
test.each(['stdout', 'stderr'])('graph export enforces the byte limit on %s', async stream => {
|
|
54
|
+
const cwd = await temporary()
|
|
55
|
+
const entry = join(cwd, 'overflow.mjs')
|
|
56
|
+
await writeFile(entry, `
|
|
57
|
+
process.${stream}.write(Buffer.alloc((8 << 20) + 1))
|
|
58
|
+
setInterval(() => {}, 1000)
|
|
59
|
+
`)
|
|
60
|
+
await expect(loadGraph(cwd, entry)).rejects.toThrow(`repograph ${stream} exceeded the 8388608-byte output limit`)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
const fixtures = [
|
|
64
|
+
{ language: 'TypeScript', extension: 'ts', main: 'import { save } from "./store";\nexport function main() { return save() }\n',
|
|
65
|
+
store: 'export function save() { return 1 }\nexport function isolated() { return 2 }\n' },
|
|
66
|
+
{ language: 'Python', extension: 'py', main: 'from store import save\n\ndef main():\n return save()\n',
|
|
67
|
+
store: 'def save():\n return 1\n\ndef isolated():\n return 2\n' },
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
// Each live case uses the installed CLI or REPOGRAPH_CLI and owns its deterministic project key.
|
|
71
|
+
test.skipIf(process.env.REPOGRAPH_INTEGRATION !== '1').each(fixtures)('real repograph exports $language cross-file callers', async ({ extension, main, store }) => {
|
|
72
|
+
const cwd = await realpath(await temporary())
|
|
73
|
+
await exec('git', ['init', '-q', cwd])
|
|
74
|
+
await writeFile(join(cwd, `main.${extension}`), main)
|
|
75
|
+
await writeFile(join(cwd, `store.${extension}`), store)
|
|
76
|
+
const entry = process.env.REPOGRAPH_CLI ?? resolveRepographEntry()
|
|
77
|
+
const project = repographProject(cwd)
|
|
78
|
+
const shim = createRequire(entry).resolve('codebase-memory-mcp/bin.js')
|
|
79
|
+
const errors: unknown[] = []
|
|
80
|
+
try {
|
|
81
|
+
const graph = await loadGraph(cwd, entry)
|
|
82
|
+
const byId = new Map(graph.nodes.map(node => [node.id, node.name]))
|
|
83
|
+
expect(graph.edges.some(edge => edge.type === 'CALLS' && byId.get(edge.source) === 'main' && byId.get(edge.target) === 'save')).toBe(true)
|
|
84
|
+
expect(graph.nodes.some(node => node.name === 'isolated')).toBe(true)
|
|
85
|
+
expect(graph.indexReport.nodes).toBe(graph.nodes.length)
|
|
86
|
+
expect(graph.indexReport.edges).toBe(graph.edges.length)
|
|
87
|
+
} catch (cause) {
|
|
88
|
+
errors.push(cause)
|
|
89
|
+
} finally {
|
|
90
|
+
try {
|
|
91
|
+
await deleteTestProject(shim, project)
|
|
92
|
+
} catch (cause) {
|
|
93
|
+
errors.push(cause)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (errors.length > 1) throw new AggregateError(errors, errors.map(String).join('\n'))
|
|
97
|
+
if (errors.length) throw errors[0]
|
|
98
|
+
}, 120_000)
|
|
99
|
+
|
|
100
|
+
async function deleteTestProject(shim: string, project: string): Promise<void> {
|
|
101
|
+
try {
|
|
102
|
+
await exec(process.execPath, [shim, 'cli', '--json', 'delete_project', '--project', project], { timeout: 30_000 })
|
|
103
|
+
} catch (cause) {
|
|
104
|
+
// The native CLI uses exit status 1 when the exporter never created the project.
|
|
105
|
+
const stdout = (cause as { stdout?: string }).stdout
|
|
106
|
+
let result: { structuredContent?: { project?: string; status?: string } } | undefined
|
|
107
|
+
try { result = stdout ? JSON.parse(stdout) : undefined } catch { throw cause }
|
|
108
|
+
if (result?.structuredContent?.project !== project || result.structuredContent.status !== 'not_found') throw cause
|
|
109
|
+
}
|
|
110
|
+
}
|
package/tests/helpers.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
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 function moduleOf(prompt: string): string | undefined {
|
|
34
|
+
const prefix = 'Module: '
|
|
35
|
+
const header = prompt.split('\n').find(line => line.startsWith(prefix))
|
|
36
|
+
return header ? JSON.parse(header.slice(prefix.length)).id : undefined
|
|
37
|
+
}
|
|
38
|
+
/** Build a two-file graph rooted at the test target for injected graph loaders. */
|
|
39
|
+
export function graph(cwd: string): RepositoryGraph {
|
|
40
|
+
return { schemaVersion: 1, repositoryPath: cwd, kind: 'all', indexReport: { status: 'indexed' }, nodes: [
|
|
41
|
+
{ id: 'a', labels: ['Function'], name: 'calculate', filePath: 'a.ts', startLine: 1, endLine: 1 },
|
|
42
|
+
{ id: 'b', labels: ['Function'], name: 'persist', filePath: 'b.ts', startLine: 1, endLine: 1 },
|
|
43
|
+
], edges: [{ id: 'call', source: 'a', target: 'b', type: 'CALLS' }] }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Create a staged two-file Git repository and scripted SDK client for refactor, CLI and lifecycle tests.
|
|
47
|
+
* Defaults to the shared plan for planning prompts and unchanged work otherwise. A supplied responder
|
|
48
|
+
* is awaited on each submission; return HarnessSdkError to fail the turn or a JSON-serializable value
|
|
49
|
+
* as agent output. Tests make edits themselves so host snapshots can verify them independently.
|
|
50
|
+
* Returns the cwd, client, adapter, prompt log and an in-memory graph loader. Setup failures reject.
|
|
51
|
+
* Shared afterEach handles registered resources, including directories from failed setup. */
|
|
52
|
+
export async function fixture(respond: Responder = prompt => prompt.startsWith('PLAN') ? plan : unchanged) {
|
|
53
|
+
const cwd = await temporary()
|
|
54
|
+
await Promise.all(['a.ts', 'b.ts'].map(file => writeFile(join(cwd, file), 'export const value = 1\n')))
|
|
55
|
+
await writeFile(join(cwd, '.gitignore'), '.anureo/\n')
|
|
56
|
+
await exec('git', ['init', '-q', cwd])
|
|
57
|
+
await exec('git', ['-C', cwd, 'add', '.'])
|
|
58
|
+
const prompts: string[] = []
|
|
59
|
+
const adapter = respondingAdapter(respond, prompts)
|
|
60
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
|
|
61
|
+
clients.push(client)
|
|
62
|
+
return { cwd, client, adapter, prompts, graphLoader: async () => graph(cwd) }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Script one submission's output against the session's own working directory. */
|
|
66
|
+
type Responder = (prompt: string, cwd: string) => unknown | Promise<unknown>
|
|
67
|
+
|
|
68
|
+
const clients: Client[] = []
|
|
69
|
+
const directories: string[] = []
|
|
70
|
+
/** Attempt client disposal before removing test repositories. Disposal or removal failures reject
|
|
71
|
+
* the hook; finally starts directory cleanup even when Promise.all rejects during disposal. */
|
|
72
|
+
afterEach(async () => {
|
|
73
|
+
try { await Promise.all(clients.splice(0).map(client => client.dispose())) }
|
|
74
|
+
finally { await Promise.all(directories.splice(0).map(path => rm(path, { recursive: true, force: true }))) }
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
/** Build the adapter that fixture passes to createClient. During submission, the scripted
|
|
78
|
+
* backend invokes execute to log the prompt and emit start before awaiting the responder.
|
|
79
|
+
* A returned HarnessSdkError becomes a failed terminal event. Other values are serialized to
|
|
80
|
+
* final JSON before completion. Responder, serialization and event errors reject the submission.
|
|
81
|
+
* Other session calls use the adapter defaults. */
|
|
82
|
+
function respondingAdapter(respond: Responder, prompts: string[]) {
|
|
83
|
+
const sessionDirectories = new Map<string, string>()
|
|
84
|
+
return createScriptedAdapter({
|
|
85
|
+
/** The adapter awaits this at session open, before a submission can use the recorded cwd. */
|
|
86
|
+
onOpen: async params => { sessionDirectories.set(params.binding.sessionId, params.cwd) },
|
|
87
|
+
execute: async (call, sink) => {
|
|
88
|
+
if (call.method !== 'input/submit' || !('input' in call.params) || !('submissionId' in call.params)) return undefined
|
|
89
|
+
const { input, submissionId, sessionId } = call.params
|
|
90
|
+
const prompt = input.filter(part => part.type === 'text').map(part => part.text).join('\n')
|
|
91
|
+
prompts.push(prompt)
|
|
92
|
+
const turnId = randomUUID()
|
|
93
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
94
|
+
const result = await respond(prompt, sessionDirectories.get(sessionId)!)
|
|
95
|
+
if (result instanceof HarnessSdkError) {
|
|
96
|
+
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
|
|
97
|
+
code: result.code, message: result.message, retryable: result.retryable, outcomeUnknown: result.outcomeUnknown,
|
|
98
|
+
...(result.details ? { details: result.details as JsonObject } : {}),
|
|
99
|
+
} } })
|
|
100
|
+
} else {
|
|
101
|
+
await sink.emit({ type: 'item/completed', payload: { item: {
|
|
102
|
+
id: randomUUID(), type: 'agentMessage', phase: 'final', text: JSON.stringify(result),
|
|
103
|
+
} } }, { turnId })
|
|
104
|
+
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
|
|
105
|
+
}
|
|
106
|
+
return { submissionId, accepted: true, disposition: 'started', turnId }
|
|
107
|
+
},
|
|
108
|
+
})
|
|
109
|
+
}
|