@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,44 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// Emulates the Codex app-server wire lifecycle for CLI subprocess tests; it must not run models or read credentials.
|
|
3
|
+
import readline from 'node:readline'
|
|
4
|
+
import { appendFile } from 'node:fs/promises'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
if (process.argv.includes('--version')) { process.stdout.write('codex-cli 0.164.0\n'); process.exit(0) }
|
|
7
|
+
/** Serialize one fixture reply/event to stdout, returning the stream write result.
|
|
8
|
+
* The protocol loop owns ordering; serialization or synchronous stream errors escape to fail the test. */
|
|
9
|
+
const send = value => process.stdout.write(`${JSON.stringify(value)}\n`)
|
|
10
|
+
const threadId = 'refactor-fixture'
|
|
11
|
+
for await (const line of readline.createInterface({ input: process.stdin })) {
|
|
12
|
+
const message = JSON.parse(line)
|
|
13
|
+
if (message.id === undefined) continue
|
|
14
|
+
/** Send a result for this request ID, returning send's write result or propagating its errors.
|
|
15
|
+
* The protocol loop must acknowledge turn/start before publishing that turn's lifecycle events. */
|
|
16
|
+
const reply = result => send({ id: message.id, result })
|
|
17
|
+
switch (message.method) {
|
|
18
|
+
case 'initialize': reply({ userAgent: 'codex/0.164.0' }); break
|
|
19
|
+
case 'account/read': reply({ account: null, requiresOpenaiAuth: false }); break
|
|
20
|
+
case 'model/list': reply({ data: [], nextCursor: null }); break
|
|
21
|
+
case 'thread/start': reply({ thread: { id: threadId } }); break
|
|
22
|
+
case 'turn/start': {
|
|
23
|
+
const prompt = message.params.input.filter(part => part.type === 'text').map(part => part.text).join('\n')
|
|
24
|
+
const inventory = prompt.split('\n').find(line => line.startsWith('Inventory: '))
|
|
25
|
+
const files = inventory ? JSON.parse(inventory.slice('Inventory: '.length)) : []
|
|
26
|
+
if (prompt.startsWith('REFACTOR') && process.env.REFACTOR_FIXTURE_EDIT) {
|
|
27
|
+
await appendFile(join(process.cwd(), process.env.REFACTOR_FIXTURE_EDIT), '\n')
|
|
28
|
+
}
|
|
29
|
+
const result = prompt.startsWith('PLAN')
|
|
30
|
+
? { summary: 'One module', modules: [{ id: 'main', name: 'Main', description: 'Entry point', files }] }
|
|
31
|
+
: { summary: 'Direct and readable implementation; keep it.', changes: [], deferred: [] }
|
|
32
|
+
// The adapter needs the turn acknowledgement before it can associate subsequent events.
|
|
33
|
+
// Final text must arrive before completion so structured-output parsing sees a full response.
|
|
34
|
+
reply({ turn: { id: 'turn', status: 'inProgress', items: [] } })
|
|
35
|
+
send({ method: 'turn/started', params: { threadId, turn: { id: 'turn', status: 'inProgress', items: [] } } })
|
|
36
|
+
send({ method: 'item/completed', params: { threadId, turnId: 'turn', item: {
|
|
37
|
+
id: 'message', type: 'agentMessage', phase: 'final_answer', text: JSON.stringify(result),
|
|
38
|
+
} } })
|
|
39
|
+
send({ method: 'turn/completed', params: { threadId, turn: { id: 'turn', status: 'completed', items: [] } } })
|
|
40
|
+
break
|
|
41
|
+
}
|
|
42
|
+
default: reply({})
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Stand-in subprocess for the CLI suite's direct loadGraph and installed-entry tests.
|
|
2
|
+
// Checks the export kind and output location, then writes a minimal graph without indexing.
|
|
3
|
+
import { writeFile } from 'node:fs/promises'
|
|
4
|
+
import { isAbsolute, relative, sep } from 'node:path'
|
|
5
|
+
|
|
6
|
+
const args = process.argv.slice(2)
|
|
7
|
+
const [command, repositoryPath] = args
|
|
8
|
+
if (command !== 'export' || args[args.indexOf('--kind') + 1] !== 'all') process.exit(3)
|
|
9
|
+
const output = args[args.indexOf('--out') + 1]
|
|
10
|
+
// Keeping the export outside the target prevents a later export from indexing it.
|
|
11
|
+
const relativeOutput = relative(repositoryPath, output)
|
|
12
|
+
if (!isAbsolute(relativeOutput) && !relativeOutput.startsWith(`..${sep}`) && relativeOutput !== '..') process.exit(4)
|
|
13
|
+
await writeFile(output, JSON.stringify({
|
|
14
|
+
schemaVersion: 1, kind: 'all', repositoryPath, indexReport: { status: 'indexed' },
|
|
15
|
+
nodes: [{ id: 'main', name: 'main', filePath: 'main.ts', labels: ['Function'], startLine: 1, endLine: 1,
|
|
16
|
+
callable: { parameters: [], returnType: 'number' } }], edges: [],
|
|
17
|
+
}))
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// Exercises the real Repograph exporter only when REPOGRAPH_INTEGRATION=1.
|
|
2
|
+
import { expect, test } from 'bun:test'
|
|
3
|
+
import { realpath, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
import { loadGraph, resolveRepographEntry } from '../src/graph'
|
|
6
|
+
import { exec } from '../src/process'
|
|
7
|
+
import { temporary } from './helpers'
|
|
8
|
+
|
|
9
|
+
const fixtures = [
|
|
10
|
+
{ language: 'TypeScript', extension: 'ts', main: 'import { save } from "./store";\nexport function main() { return save() }\n',
|
|
11
|
+
store: 'export function save() { return 1 }\nexport function isolated() { return 2 }\n' },
|
|
12
|
+
{ language: 'Python', extension: 'py', main: 'from store import save\n\ndef main():\n return save()\n',
|
|
13
|
+
store: 'def save():\n return 1\n\ndef isolated():\n return 2\n' },
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
// Each live case uses the installed CLI or REPOGRAPH_CLI. The shared temporary() hook removes
|
|
17
|
+
// its Git repository, and the test uses the returned index report to attempt project deletion.
|
|
18
|
+
test.skipIf(process.env.REPOGRAPH_INTEGRATION !== '1').each(fixtures)('real repograph exports $language cross-file callers', async ({ extension, main, store }) => {
|
|
19
|
+
const cwd = await realpath(await temporary())
|
|
20
|
+
await exec('git', ['init', '-q', cwd])
|
|
21
|
+
await writeFile(join(cwd, `main.${extension}`), main)
|
|
22
|
+
await writeFile(join(cwd, `store.${extension}`), store)
|
|
23
|
+
const entry = process.env.REPOGRAPH_CLI ?? resolveRepographEntry()
|
|
24
|
+
const graph = await loadGraph(cwd, entry)
|
|
25
|
+
try {
|
|
26
|
+
const byId = new Map(graph.nodes.map(node => [node.id, node.name]))
|
|
27
|
+
expect(graph.edges.some(edge => edge.type === 'CALLS' && byId.get(edge.source) === 'main' && byId.get(edge.target) === 'save')).toBe(true)
|
|
28
|
+
expect(graph.nodes.some(node => node.name === 'isolated')).toBe(true)
|
|
29
|
+
expect(graph.indexReport.nodes).toBe(graph.nodes.length)
|
|
30
|
+
expect(graph.indexReport.edges).toBe(graph.edges.length)
|
|
31
|
+
} finally {
|
|
32
|
+
// Use the sibling backend matching the CLI's source or installed layout to delete the index.
|
|
33
|
+
const backend = entry.endsWith('.ts') ? 'cbm.ts' : 'cbm.js'
|
|
34
|
+
const { runTool } = await import(join(dirname(entry), backend))
|
|
35
|
+
await runTool('delete_project', { project: graph.indexReport.project })
|
|
36
|
+
}
|
|
37
|
+
}, 120_000)
|
package/tests/helpers.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// Builds scripted repositories and clients with shared cleanup for refactor tests.
|
|
2
|
+
import { afterEach } from 'bun:test'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
|
5
|
+
import { tmpdir } from 'node:os'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { createClient, HarnessSdkError, type Client } from '@anureo/sdk'
|
|
8
|
+
import { createScriptedAdapter } from '@anureo/conformance'
|
|
9
|
+
import type { JsonObject } from '@anureo/protocol'
|
|
10
|
+
import type { RepositoryGraph } from '../src/graph'
|
|
11
|
+
import { exec } from '../src/process'
|
|
12
|
+
|
|
13
|
+
/** Create a test-owned temporary directory, registering removal after the test; filesystem errors reject. */
|
|
14
|
+
export async function temporary(): Promise<string> {
|
|
15
|
+
const path = await mkdtemp(join(tmpdir(), 'anureo-refactor-test-'))
|
|
16
|
+
directories.push(path)
|
|
17
|
+
return path
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Default exact-cover response for fixture planning; consumers derive variants rather than mutate shared state. */
|
|
21
|
+
export const plan = { summary: 'Two cohesive modules', modules: [
|
|
22
|
+
{ id: 'a', name: 'A', description: 'A responsibility', files: ['a.ts'] },
|
|
23
|
+
{ id: 'b', name: 'B', description: 'B responsibility', files: ['b.ts'] },
|
|
24
|
+
] }
|
|
25
|
+
/** Default work response for fixture agents; consumers reuse it without mutating shared state. */
|
|
26
|
+
export const unchanged = { summary: 'Read the code; direct expression is appropriate.', changes: [], deferred: [] }
|
|
27
|
+
/** Return an agent's edit claim. Tests make the real edit separately so host observations
|
|
28
|
+
* remain independent of the claim. */
|
|
29
|
+
export const edited = (change = 'Renamed internal value') => ({ summary: 'Edited', changes: [change], deferred: [] })
|
|
30
|
+
/** Return the first line for prompt routing, or an empty string for empty input. */
|
|
31
|
+
export const kind = (prompt: string) => prompt.split('\n')[0]!
|
|
32
|
+
/** Read a module ID from its serialized prompt header, or return undefined when absent. */
|
|
33
|
+
export const moduleOf = (prompt: string) => /Module: \{"id":"([^"]+)"/.exec(prompt)?.[1]
|
|
34
|
+
/** Build a two-file graph rooted at the test target for injected graph loaders. */
|
|
35
|
+
export function graph(cwd: string): RepositoryGraph {
|
|
36
|
+
return { schemaVersion: 1, repositoryPath: cwd, kind: 'all', indexReport: { status: 'indexed' }, nodes: [
|
|
37
|
+
{ id: 'a', labels: ['Function'], name: 'calculate', filePath: 'a.ts', startLine: 1, endLine: 1 },
|
|
38
|
+
{ id: 'b', labels: ['Function'], name: 'persist', filePath: 'b.ts', startLine: 1, endLine: 1 },
|
|
39
|
+
], edges: [{ id: 'call', source: 'a', target: 'b', type: 'CALLS' }] }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Create a staged two-file Git repository and scripted SDK client for refactor, CLI and lifecycle tests.
|
|
43
|
+
* Defaults to the shared plan for planning prompts and unchanged work otherwise. A supplied responder
|
|
44
|
+
* is awaited on each submission; return HarnessSdkError to fail the turn or a JSON-serializable value
|
|
45
|
+
* as agent output. Tests make edits themselves so host snapshots can verify them independently.
|
|
46
|
+
* Returns the cwd, client, adapter, prompt log and an in-memory graph loader. Setup failures reject.
|
|
47
|
+
* Shared afterEach handles registered resources, including directories from failed setup. */
|
|
48
|
+
export async function fixture(respond: Responder = prompt => prompt.startsWith('PLAN') ? plan : unchanged) {
|
|
49
|
+
const cwd = await temporary()
|
|
50
|
+
await Promise.all(['a.ts', 'b.ts'].map(file => writeFile(join(cwd, file), 'export const value = 1\n')))
|
|
51
|
+
await writeFile(join(cwd, '.gitignore'), '.anureo/\n')
|
|
52
|
+
await exec('git', ['init', '-q', cwd])
|
|
53
|
+
await exec('git', ['-C', cwd, 'add', '.'])
|
|
54
|
+
const prompts: string[] = []
|
|
55
|
+
const adapter = respondingAdapter(respond, prompts)
|
|
56
|
+
const client = await createClient({ adapter, identity: { adapterId: 'scripted', runtimeConfigId: randomUUID() } })
|
|
57
|
+
clients.push(client)
|
|
58
|
+
return { cwd, client, adapter, prompts, graphLoader: async () => graph(cwd) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Script one submission's output against the session's own working directory. */
|
|
62
|
+
type Responder = (prompt: string, cwd: string) => unknown | Promise<unknown>
|
|
63
|
+
|
|
64
|
+
const clients: Client[] = []
|
|
65
|
+
const directories: string[] = []
|
|
66
|
+
/** Attempt client disposal before removing test repositories. Disposal or removal failures reject
|
|
67
|
+
* the hook; finally starts directory cleanup even when Promise.all rejects during disposal. */
|
|
68
|
+
afterEach(async () => {
|
|
69
|
+
try { await Promise.all(clients.splice(0).map(client => client.dispose())) }
|
|
70
|
+
finally { await Promise.all(directories.splice(0).map(path => rm(path, { recursive: true, force: true }))) }
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
/** Build the adapter that fixture passes to createClient. During submission, the scripted
|
|
74
|
+
* backend invokes execute to log the prompt and emit start before awaiting the responder.
|
|
75
|
+
* A returned HarnessSdkError becomes a failed terminal event. Other values are serialized to
|
|
76
|
+
* final JSON before completion. Responder, serialization and event errors reject the submission.
|
|
77
|
+
* Other session calls use the adapter defaults. */
|
|
78
|
+
function respondingAdapter(respond: Responder, prompts: string[]) {
|
|
79
|
+
const sessionDirectories = new Map<string, string>()
|
|
80
|
+
return createScriptedAdapter({
|
|
81
|
+
/** The adapter awaits this at session open, before a submission can use the recorded cwd. */
|
|
82
|
+
onOpen: async params => { sessionDirectories.set(params.binding.sessionId, params.cwd) },
|
|
83
|
+
execute: async (call, sink) => {
|
|
84
|
+
if (call.method !== 'input/submit' || !('input' in call.params) || !('submissionId' in call.params)) return undefined
|
|
85
|
+
const { input, submissionId, sessionId } = call.params
|
|
86
|
+
const prompt = input.filter(part => part.type === 'text').map(part => part.text).join('\n')
|
|
87
|
+
prompts.push(prompt)
|
|
88
|
+
const turnId = randomUUID()
|
|
89
|
+
await sink.emit({ type: 'turn/started', payload: { turnId } })
|
|
90
|
+
const result = await respond(prompt, sessionDirectories.get(sessionId)!)
|
|
91
|
+
if (result instanceof HarnessSdkError) {
|
|
92
|
+
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'failed', error: {
|
|
93
|
+
code: result.code, message: result.message, retryable: result.retryable, outcomeUnknown: result.outcomeUnknown,
|
|
94
|
+
...(result.details ? { details: result.details as JsonObject } : {}),
|
|
95
|
+
} } })
|
|
96
|
+
} else {
|
|
97
|
+
await sink.emit({ type: 'item/completed', payload: { item: {
|
|
98
|
+
id: randomUUID(), type: 'agentMessage', phase: 'final', text: JSON.stringify(result),
|
|
99
|
+
} } }, { turnId })
|
|
100
|
+
await sink.emit({ type: 'turn/completed', payload: { turnId, status: 'completed' } })
|
|
101
|
+
}
|
|
102
|
+
return { submissionId, accepted: true, disposition: 'started', turnId }
|
|
103
|
+
},
|
|
104
|
+
})
|
|
105
|
+
}
|
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
// Exercises public sequencing, checkpoints and failure gates through refactorCode.
|
|
2
|
+
import { expect, test } from 'bun:test'
|
|
3
|
+
import { mkdir, readFile, readdir, rename, stat, symlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { createClient, HarnessSdkError, type StructuredOutputToolDefinition } from '@anureo/sdk'
|
|
6
|
+
import { createPiAdapter } from '@anureo/adapter-pi'
|
|
7
|
+
import { fakeFactory } from '../../../packages/adapter/pi/tests/fake-host'
|
|
8
|
+
import { startFake } from '../../../packages/adapter/hermes/tests/helpers'
|
|
9
|
+
import { refactorCode, formatReport } from '../src'
|
|
10
|
+
import { captureTree, treeVersion } from '../src/git-tree'
|
|
11
|
+
import { git } from '../src/git'
|
|
12
|
+
import { edited, fixture, graph, kind, moduleOf, plan, temporary, unchanged } from './helpers'
|
|
13
|
+
|
|
14
|
+
const DESIGN = 'DESIGN MODULE BOUNDARIES'
|
|
15
|
+
const MODULE = 'REFACTOR MODULE'
|
|
16
|
+
|
|
17
|
+
test('refactor completes through the Hermes gateway with schema-validated text', async () => {
|
|
18
|
+
const { cwd } = await fixture()
|
|
19
|
+
const server = await startFake('refactor', { FAKE_HERMES_RESPONSE_MODULE: new URL('./fixtures/answer.mjs', import.meta.url).href })
|
|
20
|
+
try {
|
|
21
|
+
const client = await createClient({ adapter: server.adapter(), identity: { adapterId: 'hermes', runtimeConfigId: 'refactor-test' } })
|
|
22
|
+
try {
|
|
23
|
+
const report = await refactorCode({ client, cwd, reviewOnly: true, noGraph: true })
|
|
24
|
+
expect(report.status).toBe('completed')
|
|
25
|
+
expect(report.plan?.modules[0]?.files).toEqual(['a.ts', 'b.ts'])
|
|
26
|
+
expect((await server.state()).inputs).toHaveLength(3)
|
|
27
|
+
} finally { await client.dispose() }
|
|
28
|
+
} finally { await server.dispose() }
|
|
29
|
+
}, 20_000)
|
|
30
|
+
|
|
31
|
+
test('refactor completes through Pi with its structured output tool', async () => {
|
|
32
|
+
const { cwd } = await fixture()
|
|
33
|
+
const fake = fakeFactory(host => {
|
|
34
|
+
let tool: StructuredOutputToolDefinition | undefined
|
|
35
|
+
Object.assign(host, { async setOutputTool(next?: StructuredOutputToolDefinition) { tool = next } })
|
|
36
|
+
host.script = async (host, prompt) => {
|
|
37
|
+
const value = prompt.startsWith('PLAN') ? plan : unchanged
|
|
38
|
+
expect(await tool?.execute(value)).toMatchObject({ accepted: true })
|
|
39
|
+
await host.assistant('Submitted the result')
|
|
40
|
+
}
|
|
41
|
+
})
|
|
42
|
+
const client = await createClient({
|
|
43
|
+
adapter: createPiAdapter({ version: '1.5.2', createHost: fake.factory }),
|
|
44
|
+
identity: { adapterId: 'pi', runtimeConfigId: 'refactor-test' },
|
|
45
|
+
})
|
|
46
|
+
try {
|
|
47
|
+
const report = await refactorCode({ client, cwd, noGraph: true, readPermissionMode: 'read-only', editPermissionMode: 'agent-full-access' })
|
|
48
|
+
expect(report.status).toBe('completed')
|
|
49
|
+
expect(report.plan).toEqual(plan)
|
|
50
|
+
} finally { await client.dispose() }
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
/** Require argument failure before filesystem preflight can mask it; fixture cleanup owns the client. */
|
|
54
|
+
test('blank library checks fail before repository setup or agent dispatch', async () => {
|
|
55
|
+
const context = await fixture()
|
|
56
|
+
await expect(refactorCode({ ...context, cwd: join(context.cwd, 'missing'), checks: [' '] })).rejects.toThrow('check commands must be nonempty')
|
|
57
|
+
expect(context.prompts).toHaveLength(0)
|
|
58
|
+
expect(await stat(join(context.cwd, '.anureo')).catch(() => null)).toBeNull()
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
test('each agent has a worktree and module sessions overlap on the same post-design baseline', async () => {
|
|
62
|
+
let exports = 0
|
|
63
|
+
const order: string[] = []
|
|
64
|
+
const worktrees: string[] = []
|
|
65
|
+
const modulesReady = Promise.withResolvers<void>()
|
|
66
|
+
let runningModules = 0
|
|
67
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
68
|
+
worktrees.push(cwd)
|
|
69
|
+
expect((await git(cwd, 'rev-parse', '--show-toplevel')).trim()).toBe(cwd)
|
|
70
|
+
const module = moduleOf(prompt)
|
|
71
|
+
order.push(module ? `module:${module}` : kind(prompt))
|
|
72
|
+
if (prompt.startsWith(DESIGN)) {
|
|
73
|
+
expect(await readFile(join(cwd, 'README.md'), 'utf8')).toBe('untracked input')
|
|
74
|
+
expect(await readFile(join(cwd, 'a.ts'), 'utf8')).toContain('unstaged')
|
|
75
|
+
await writeFile(join(cwd, 'a.ts'), 'export const value = 1 // design\n')
|
|
76
|
+
return edited()
|
|
77
|
+
}
|
|
78
|
+
expect(await readFile(join(cwd, 'a.ts'), 'utf8')).toContain('// design')
|
|
79
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
80
|
+
|
|
81
|
+
if (++runningModules === 2) modulesReady.resolve()
|
|
82
|
+
await modulesReady.promise
|
|
83
|
+
await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
|
|
84
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('// design')
|
|
85
|
+
const other = module === 'a' ? 'b' : 'a'
|
|
86
|
+
expect(await readFile(join(cwd, `${other}.ts`), 'utf8')).toContain('value = 1')
|
|
87
|
+
return edited()
|
|
88
|
+
})
|
|
89
|
+
await writeFile(join(context.cwd, 'README.md'), 'untracked input')
|
|
90
|
+
await writeFile(join(context.cwd, 'a.ts'), 'export const value = 1 // unstaged\n')
|
|
91
|
+
const indexBefore = await git(context.cwd, 'ls-files', '--stage')
|
|
92
|
+
const report = await refactorCode({
|
|
93
|
+
...context, checks: ['git diff --exit-code -- .gitignore'],
|
|
94
|
+
readPermissionMode: 'read-only', editPermissionMode: 'agent-full-access',
|
|
95
|
+
graphLoader: async () => { exports++; return graph(context.cwd) },
|
|
96
|
+
})
|
|
97
|
+
expect(report.status).toBe('completed')
|
|
98
|
+
expect(order.slice(0, 2)).toEqual([DESIGN, 'PLAN REFACTOR MODULES'])
|
|
99
|
+
expect(order.slice(2).sort()).toEqual(['module:a', 'module:b'])
|
|
100
|
+
expect(new Set(worktrees).size).toBe(4)
|
|
101
|
+
expect(worktrees).not.toContain(context.cwd)
|
|
102
|
+
expect(exports).toBe(2)
|
|
103
|
+
expect(report.design).toMatchObject({ status: 'applied', changedFiles: ['a.ts'] })
|
|
104
|
+
expect(report.modules.map(item => [item.module.id, item.step?.status])).toEqual([['a', 'applied'], ['b', 'applied']])
|
|
105
|
+
expect(report.modules.every(item => item.step?.checks[0]?.status === 'passed')).toBe(true)
|
|
106
|
+
for (const file of ['a.ts', 'b.ts']) expect(await readFile(join(context.cwd, file), 'utf8')).toContain('value = 2')
|
|
107
|
+
for (const cwd of worktrees) expect(await stat(cwd).catch(() => null)).toBeNull()
|
|
108
|
+
expect((await git(context.cwd, 'worktree', 'list', '--porcelain')).match(/^worktree /gm)).toHaveLength(1)
|
|
109
|
+
expect(await git(context.cwd, 'ls-files', '--stage')).toBe(indexBefore)
|
|
110
|
+
expect(context.adapter.opened.filter(session => session.permissionMode === 'read-only')).toHaveLength(1)
|
|
111
|
+
expect(context.adapter.opened.filter(session => session.permissionMode === 'agent-full-access')).toHaveLength(3)
|
|
112
|
+
expect(context.prompts.find(prompt => prompt.startsWith(MODULE))).toContain('Cross-module design step already done in this run: Edited')
|
|
113
|
+
expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
|
|
114
|
+
expect(await stat(join(context.cwd, '.anureo/refactor/writer.lock')).catch(() => null)).toBeNull()
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
/** Inspect scripted prompts without edits so review instructions and report wording stay aligned. */
|
|
118
|
+
test('prompts name the problem catalog, the graph guide and the mode', async () => {
|
|
119
|
+
const context = await fixture()
|
|
120
|
+
const report = await refactorCode({ ...context, reviewOnly: true })
|
|
121
|
+
expect(report.status).toBe('completed')
|
|
122
|
+
const design = context.prompts.find(prompt => prompt.startsWith(DESIGN))!
|
|
123
|
+
const module = context.prompts.find(prompt => prompt.startsWith(MODULE))!
|
|
124
|
+
for (const prompt of [design, module]) {
|
|
125
|
+
expect(prompt).toContain('MODE: READ ONLY')
|
|
126
|
+
expect(prompt).toContain('Graph artifact:')
|
|
127
|
+
expect(prompt).toContain('local_name')
|
|
128
|
+
expect(prompt).toContain('Optimize for the cost of understanding and changing the code.')
|
|
129
|
+
expect(prompt.replace(/\s+/g, ' ')).toContain('verify call targets, imports, aliases, re-exports and callback registration/invocation in source')
|
|
130
|
+
expect(prompt).toContain('Missing edges do not prove absence of calls')
|
|
131
|
+
}
|
|
132
|
+
expect(design).toContain('Wrong dependency direction')
|
|
133
|
+
expect(design).toContain('Import cycles between files')
|
|
134
|
+
expect(module).toContain('shares mutable variables across them')
|
|
135
|
+
expect(module).toContain('five or more positional parameters')
|
|
136
|
+
for (const prompt of [design, module]) {
|
|
137
|
+
expect(prompt).toContain('Comment WHY, not WHAT')
|
|
138
|
+
expect(prompt).toContain('doc comment stating')
|
|
139
|
+
expect(prompt).toContain('Documentation conventions and tags:')
|
|
140
|
+
expect(prompt).toContain('re-export chains')
|
|
141
|
+
expect(prompt).toContain('Declaration order:')
|
|
142
|
+
}
|
|
143
|
+
expect(design).toContain('Design documentation scope:')
|
|
144
|
+
expect(module).toContain('Module documentation scope:')
|
|
145
|
+
expect(module).toContain('including declarations\nwhose implementation stays unchanged')
|
|
146
|
+
expect(formatReport(report)).toContain('review only')
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
/** Verify explicit edit checks reach the agent even when its response leaves the tree unchanged. */
|
|
150
|
+
test('edit mode states how to edit and lists the validation commands', async () => {
|
|
151
|
+
const context = await fixture()
|
|
152
|
+
await refactorCode({ ...context, checks: ['true'] })
|
|
153
|
+
const module = context.prompts.find(prompt => prompt.startsWith(MODULE))!
|
|
154
|
+
expect(module).toContain('MODE: EDIT')
|
|
155
|
+
expect(module).toContain('Validation commands: ["true"]')
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
/** Feed malformed assignments through the real planner boundary; no module may start after rejection. */
|
|
159
|
+
test.each([
|
|
160
|
+
{ ...plan, modules: [plan.modules[0]] },
|
|
161
|
+
{ ...plan, modules: [plan.modules[0], plan.modules[0]] },
|
|
162
|
+
{ ...plan, modules: [plan.modules[0], { ...plan.modules[1], id: 'A' }] },
|
|
163
|
+
{ ...plan, modules: [{ ...plan.modules[0], files: ['a.ts', 'not-in-inventory.ts'] }, plan.modules[1]] },
|
|
164
|
+
])('rejects missing, duplicate and invented inventory assignments before any module agent', async invalid => {
|
|
165
|
+
const context = await fixture(prompt => prompt.startsWith('PLAN') ? invalid : unchanged)
|
|
166
|
+
const report = await refactorCode({ ...context, checks: [] })
|
|
167
|
+
expect(report.status).toBe('incomplete')
|
|
168
|
+
expect(context.prompts.some(prompt => prompt.startsWith(MODULE))).toBe(false)
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
/** Inject an unknown SDK outcome after a real edit; planning stops and the target retains its original contents. */
|
|
172
|
+
test('a failed design step stops before planning and records its observed edit', async () => {
|
|
173
|
+
const context = await fixture(async (_prompt, cwd) => {
|
|
174
|
+
await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
|
|
175
|
+
return new HarnessSdkError('RECEIPT_LOST', 'Unknown', false, true)
|
|
176
|
+
})
|
|
177
|
+
const report = await refactorCode({ ...context, checks: [] })
|
|
178
|
+
expect(report.status).toBe('incomplete')
|
|
179
|
+
expect(report.design).toMatchObject({ status: 'failed', changedFiles: ['a.ts'], failure: { code: 'RECEIPT_LOST', outcomeUnknown: true } })
|
|
180
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toBe('export const value = 1\n')
|
|
181
|
+
expect(context.prompts).toHaveLength(1)
|
|
182
|
+
expect(formatReport(report)).toContain('execution outcome is unknown')
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
test('a failed module leaves the target untouched for its assignment while siblings merge', async () => {
|
|
186
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
187
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
188
|
+
const module = moduleOf(prompt)
|
|
189
|
+
if (!module) return unchanged
|
|
190
|
+
await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
|
|
191
|
+
return module === 'a' ? new HarnessSdkError('NATIVE_FAILED', 'Writer failed') : edited()
|
|
192
|
+
})
|
|
193
|
+
const report = await refactorCode({ ...context, checks: [] })
|
|
194
|
+
expect(report.status).toBe('incomplete')
|
|
195
|
+
expect(report.modules[0]?.step).toMatchObject({ status: 'failed', changedFiles: ['a.ts'] })
|
|
196
|
+
expect(report.modules[1]?.step).toMatchObject({ status: 'applied', changedFiles: ['b.ts'] })
|
|
197
|
+
expect(await readdir(report.directory)).not.toContain('module-a.patch')
|
|
198
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
|
|
199
|
+
expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toContain('value = 2')
|
|
200
|
+
expect((await git(context.cwd, 'worktree', 'list', '--porcelain')).match(/^worktree /gm)).toHaveLength(1)
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
test('verified work merges while an earlier agent is still running, and competing additions fail', async () => {
|
|
204
|
+
const merged = Promise.withResolvers<void>()
|
|
205
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
206
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
207
|
+
const module = moduleOf(prompt)
|
|
208
|
+
if (!module) return unchanged
|
|
209
|
+
if (module === 'a') {
|
|
210
|
+
await merged.promise
|
|
211
|
+
expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toContain('value = 2')
|
|
212
|
+
expect(await readFile(join(cwd, 'b.ts'), 'utf8')).toContain('value = 1')
|
|
213
|
+
}
|
|
214
|
+
await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
|
|
215
|
+
await writeFile(join(cwd, 'shared.ts'), `export const owner = '${module}'\n`)
|
|
216
|
+
return edited()
|
|
217
|
+
})
|
|
218
|
+
const report = await refactorCode({
|
|
219
|
+
...context, concurrency: 2,
|
|
220
|
+
checks: [{ executable: process.execPath, args: ['-e', 'if (!(await Bun.file("shared.ts").text()).includes("owner")) process.exit(1)'] }],
|
|
221
|
+
onProgress: event => { if (event === 'module/b: applied') merged.resolve() },
|
|
222
|
+
})
|
|
223
|
+
expect(report.status).toBe('incomplete')
|
|
224
|
+
expect(report.modules[0]?.step).toMatchObject({ status: 'failed', error: 'Source changed during refactor: shared.ts' })
|
|
225
|
+
expect(report.modules[1]?.step).toMatchObject({ status: 'applied', checks: [{ status: 'passed' }] })
|
|
226
|
+
expect(await readFile(join(context.cwd, 'shared.ts'), 'utf8')).toContain("owner = 'b'")
|
|
227
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
|
|
228
|
+
})
|
|
229
|
+
|
|
230
|
+
test('edits to another module and review-only writes stay out of the target checkout', async () => {
|
|
231
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
232
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
233
|
+
if (moduleOf(prompt) !== 'a') return unchanged
|
|
234
|
+
await writeFile(join(cwd, 'b.ts'), 'export const value = 2\n')
|
|
235
|
+
return edited()
|
|
236
|
+
})
|
|
237
|
+
for (const reviewOnly of [false, true]) {
|
|
238
|
+
const report = await refactorCode({ ...context, reviewOnly, checks: [] })
|
|
239
|
+
expect(report.status).toBe('incomplete')
|
|
240
|
+
expect(report.modules[0]?.step).toMatchObject({
|
|
241
|
+
status: 'failed', changedFiles: ['b.ts'],
|
|
242
|
+
error: reviewOnly ? 'Review-only agent modified files' : 'Module edited paths outside its assignment: b.ts',
|
|
243
|
+
})
|
|
244
|
+
expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toContain('value = 1')
|
|
245
|
+
}
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
test('failed validation retains its output and prevents unverified changes from reaching the target', async () => {
|
|
249
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
250
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
251
|
+
const module = moduleOf(prompt)
|
|
252
|
+
if (!module) return unchanged
|
|
253
|
+
await writeFile(join(cwd, `${module}.ts`), 'export const value = 2\n')
|
|
254
|
+
return edited()
|
|
255
|
+
})
|
|
256
|
+
const report = await refactorCode({ ...context, checks: [
|
|
257
|
+
{ executable: process.execPath, args: ['-e', 'if ((await Bun.file("a.ts").text()).includes("value = 2")) { console.error("validation-broken"); process.exit(7) }'] },
|
|
258
|
+
{ executable: process.execPath, args: ['-e', 'if (!(await Bun.file("b.ts").text()).includes("value = 2")) process.exit(8)'] },
|
|
259
|
+
] })
|
|
260
|
+
expect(report.status).toBe('incomplete')
|
|
261
|
+
expect(report.modules[0]?.step).toMatchObject({
|
|
262
|
+
status: 'failed',
|
|
263
|
+
checks: [{ status: 'failed', output: expect.stringContaining('validation-broken') }],
|
|
264
|
+
})
|
|
265
|
+
expect(report.modules[1]?.step).toMatchObject({ status: 'applied', checks: [{ status: 'passed' }, { status: 'passed' }] })
|
|
266
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toBe('export const value = 1\n')
|
|
267
|
+
expect(await readFile(join(context.cwd, 'b.ts'), 'utf8')).toBe('export const value = 2\n')
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
test('the plan checkpoint is published before either module starts', async () => {
|
|
271
|
+
let directory = ''
|
|
272
|
+
const context = await fixture(async prompt => {
|
|
273
|
+
if (prompt.startsWith(DESIGN)) return unchanged
|
|
274
|
+
const saved = JSON.parse(await readFile(join(directory, 'report.json'), 'utf8'))
|
|
275
|
+
expect(saved.design.status).toBe('unchanged')
|
|
276
|
+
if (prompt.startsWith('PLAN')) {
|
|
277
|
+
expect(saved.plan).toBeNull()
|
|
278
|
+
return plan
|
|
279
|
+
}
|
|
280
|
+
expect(saved.plan).toEqual(plan)
|
|
281
|
+
expect(saved.modules).toEqual([])
|
|
282
|
+
return unchanged
|
|
283
|
+
})
|
|
284
|
+
const report = await refactorCode({ ...context, checks: [],
|
|
285
|
+
onProgress: event => { if (event.startsWith('run: ')) directory = event.slice('run: '.length) },
|
|
286
|
+
})
|
|
287
|
+
expect(report.status).toBe('completed')
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
test('a failed post-design graph refresh prevents module dispatch and releases the lock', async () => {
|
|
291
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
292
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
293
|
+
if (prompt.startsWith(DESIGN)) {
|
|
294
|
+
await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
|
|
295
|
+
return edited()
|
|
296
|
+
}
|
|
297
|
+
return unchanged
|
|
298
|
+
})
|
|
299
|
+
let exports = 0
|
|
300
|
+
const report = await refactorCode({ ...context, checks: [],
|
|
301
|
+
graphLoader: async () => {
|
|
302
|
+
if (++exports === 2) throw new Error('Graph refresh unavailable')
|
|
303
|
+
return graph(context.cwd)
|
|
304
|
+
},
|
|
305
|
+
})
|
|
306
|
+
expect(report.status).toBe('incomplete')
|
|
307
|
+
expect(report.errors).toEqual(['Graph refresh unavailable'])
|
|
308
|
+
expect(report.modules).toEqual([])
|
|
309
|
+
expect(context.prompts.some(prompt => prompt.startsWith(MODULE))).toBe(false)
|
|
310
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toBe('export const value = 2\n')
|
|
311
|
+
expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
|
|
312
|
+
expect(await stat(join(context.cwd, '.anureo/refactor/writer.lock')).catch(() => null)).toBeNull()
|
|
313
|
+
})
|
|
314
|
+
|
|
315
|
+
/** Discover real package scripts and confirm typecheck failure prevents the test script from running. */
|
|
316
|
+
test('default validation discovers root package scripts and stops on a failing typecheck', async () => {
|
|
317
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
318
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
319
|
+
if (moduleOf(prompt) === 'a') await writeFile(join(cwd, 'a.ts'), 'const named = 1; export { named as value }\n')
|
|
320
|
+
return moduleOf(prompt) === 'a' ? edited() : unchanged
|
|
321
|
+
})
|
|
322
|
+
await writeFile(join(context.cwd, 'package.json'), JSON.stringify({ packageManager: 'bun@1.4.2', scripts: { typecheck: 'exit 9', test: 'exit 0' } }))
|
|
323
|
+
const report = await refactorCode(context)
|
|
324
|
+
expect(report.status).toBe('incomplete')
|
|
325
|
+
expect(report.modules[0]?.step?.checks).toMatchObject([{ command: 'bun run typecheck', status: 'failed' }])
|
|
326
|
+
})
|
|
327
|
+
|
|
328
|
+
test('validation resolves installed workspace links to edited files in the agent worktree', async () => {
|
|
329
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
330
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
331
|
+
if (moduleOf(prompt) !== 'a') return unchanged
|
|
332
|
+
await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
|
|
333
|
+
return edited()
|
|
334
|
+
})
|
|
335
|
+
await mkdir(join(context.cwd, 'node_modules'))
|
|
336
|
+
await symlink(context.cwd, join(context.cwd, 'node_modules', 'workspace'), 'junction')
|
|
337
|
+
await writeFile(join(context.cwd, '.gitignore'), '.anureo/\nnode_modules/\n')
|
|
338
|
+
const report = await refactorCode({ ...context, checks: [
|
|
339
|
+
{ executable: process.execPath, args: ['-e', 'if ((await import("workspace/a.ts")).value !== 2) process.exit(9)'] },
|
|
340
|
+
] })
|
|
341
|
+
expect(report.modules[0]?.step).toMatchObject({ status: 'applied', checks: [{ status: 'passed' }] })
|
|
342
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 2')
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
test('a passing command that rewrites agent source prevents the merge', async () => {
|
|
346
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
347
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
348
|
+
if (moduleOf(prompt) !== 'a') return unchanged
|
|
349
|
+
await writeFile(join(cwd, 'a.ts'), 'export const value = 2\n')
|
|
350
|
+
return edited()
|
|
351
|
+
})
|
|
352
|
+
const report = await refactorCode({ ...context, checks: [
|
|
353
|
+
{ executable: process.execPath, args: ['-e', 'await Bun.write("a.ts", "export const value = 3\\n")'] },
|
|
354
|
+
] })
|
|
355
|
+
expect(report.modules[0]?.step).toMatchObject({ status: 'failed', error: 'Validation modified source files: a.ts' })
|
|
356
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
|
|
357
|
+
})
|
|
358
|
+
|
|
359
|
+
/** Move/add files during design so the host diff and post-design inventory use observed paths. */
|
|
360
|
+
test('moves and new files need no declaration and are reported from the real diff', async () => {
|
|
361
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
362
|
+
if (prompt.startsWith('PLAN')) return { ...plan, modules: [{ ...plan.modules[0], files: ['moved.ts', 'types.ts'] }, plan.modules[1]] }
|
|
363
|
+
if (prompt.startsWith(DESIGN)) {
|
|
364
|
+
await rename(join(cwd, 'a.ts'), join(cwd, 'moved.ts'))
|
|
365
|
+
await writeFile(join(cwd, 'types.ts'), 'export type T = 1\n')
|
|
366
|
+
return edited('Moved a.ts, added types.ts')
|
|
367
|
+
}
|
|
368
|
+
return unchanged
|
|
369
|
+
})
|
|
370
|
+
const report = await refactorCode({ ...context, checks: [] })
|
|
371
|
+
expect(report.status).toBe('completed')
|
|
372
|
+
expect(report.design?.changedFiles).toEqual(['a.ts', 'moved.ts', 'types.ts'])
|
|
373
|
+
expect(report.plan).not.toBeNull()
|
|
374
|
+
})
|
|
375
|
+
|
|
376
|
+
/** Add a design-time source and require its inclusion in the subsequent planning prompt. */
|
|
377
|
+
test('the plan is made from the tree after the design step', async () => {
|
|
378
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
379
|
+
if (prompt.startsWith(DESIGN)) { await writeFile(join(cwd, 'extra.ts'), 'export const extra = 1\n'); return edited() }
|
|
380
|
+
if (prompt.startsWith('PLAN')) return { ...plan, modules: [{ ...plan.modules[0], files: ['a.ts', 'extra.ts'] }, plan.modules[1]] }
|
|
381
|
+
return unchanged
|
|
382
|
+
})
|
|
383
|
+
const report = await refactorCode({ ...context, checks: [] })
|
|
384
|
+
expect(report.status).toBe('completed')
|
|
385
|
+
expect(context.prompts.find(prompt => prompt.startsWith('PLAN'))).toContain('"extra.ts"')
|
|
386
|
+
})
|
|
387
|
+
|
|
388
|
+
/** Use an external fixture path to ensure source safety rejects links before graph or agent work. */
|
|
389
|
+
test.skipIf(process.platform === 'win32')('a symlinked source file is rejected before any agent runs', async () => {
|
|
390
|
+
const outside = await temporary()
|
|
391
|
+
const context = await fixture()
|
|
392
|
+
await writeFile(join(outside, 'x.ts'), 'export const x = 1\n')
|
|
393
|
+
await symlink(join(outside, 'x.ts'), join(context.cwd, 'linked.ts'))
|
|
394
|
+
const report = await refactorCode({ ...context })
|
|
395
|
+
expect(report.status).toBe('incomplete')
|
|
396
|
+
expect(report.errors.join()).toContain('Symlink')
|
|
397
|
+
expect(context.prompts).toHaveLength(0)
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
/** Precreate a competing writer lock; acquisition failure must reject without dispatching agents. */
|
|
401
|
+
test('one cooperating process owns the tree', async () => {
|
|
402
|
+
const context = await fixture()
|
|
403
|
+
await mkdir(join(context.cwd, '.anureo/refactor'), { recursive: true })
|
|
404
|
+
await writeFile(join(context.cwd, '.anureo/refactor/writer.lock'), 'active')
|
|
405
|
+
await expect(refactorCode(context)).rejects.toThrow('Cannot acquire refactor lock')
|
|
406
|
+
expect(context.prompts).toHaveLength(0)
|
|
407
|
+
})
|
|
408
|
+
|
|
409
|
+
/** Throw from the observer and supply a failing check; unchanged steps must still complete without edits. */
|
|
410
|
+
test('progress errors are observational and unchanged steps run no checks', async () => {
|
|
411
|
+
const context = await fixture()
|
|
412
|
+
const before = treeVersion(await captureTree(context.cwd))
|
|
413
|
+
const report = await refactorCode({ ...context, checks: ['exit 1'], onProgress: () => { throw new Error('Sink unavailable') } })
|
|
414
|
+
expect(report.status).toBe('completed')
|
|
415
|
+
expect(report.modules.map(item => item.step?.status)).toEqual(['unchanged', 'unchanged'])
|
|
416
|
+
expect(report.progressErrors.length).toBeGreaterThan(0)
|
|
417
|
+
expect(treeVersion(await captureTree(context.cwd))).toBe(before)
|
|
418
|
+
})
|
|
419
|
+
|
|
420
|
+
/** Target a nested Git directory to verify inventory and graph context do not expand to the repository root. */
|
|
421
|
+
test('a subdirectory of a Git repository is a valid target and only its files are in scope', async () => {
|
|
422
|
+
const context = await fixture(async (prompt, cwd) => {
|
|
423
|
+
expect(await readFile(join(cwd, '..', 'a.ts'), 'utf8')).toContain('value = 1')
|
|
424
|
+
if (prompt.startsWith('PLAN')) return plan
|
|
425
|
+
if (moduleOf(prompt) !== 'a') return unchanged
|
|
426
|
+
await writeFile(join(cwd, 'a.ts'), 'export const value = 3\n')
|
|
427
|
+
return edited()
|
|
428
|
+
})
|
|
429
|
+
await mkdir(join(context.cwd, 'pkg'))
|
|
430
|
+
const cwd = join(context.cwd, 'pkg')
|
|
431
|
+
await Promise.all(['a.ts', 'b.ts'].map(file => writeFile(join(cwd, file), 'export const value = 1\n')))
|
|
432
|
+
const report = await refactorCode({ ...context, cwd, checks: [], graphLoader: async () => graph(cwd) })
|
|
433
|
+
expect(report.status).toBe('completed')
|
|
434
|
+
expect(await readFile(join(cwd, 'a.ts'), 'utf8')).toContain('value = 3')
|
|
435
|
+
expect(await readFile(join(context.cwd, 'a.ts'), 'utf8')).toContain('value = 1')
|
|
436
|
+
expect(JSON.parse(context.prompts.find(prompt => prompt.startsWith('PLAN'))!.split('Inventory: ')[1]!.split('\n')[0]!)).toEqual(['a.ts', 'b.ts'])
|
|
437
|
+
})
|