@anureo/refactor 0.3.1 → 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/src/graph.ts CHANGED
@@ -4,8 +4,8 @@ import { tmpdir } from 'node:os'
4
4
  import { dirname, join } from 'node:path'
5
5
  import { createRequire } from 'node:module'
6
6
  import { createHash } from 'node:crypto'
7
+ import { spawnHarnessProcess } from '@anureo/sdk/process'
7
8
  import { z } from 'zod'
8
- import { exec } from './process'
9
9
 
10
10
  /** Shape of a Repograph `--kind all` export. Node and edge properties can carry exporter metadata
11
11
  * such as symbol metrics, call lines and imported names. startLine and endLine allow null for
@@ -20,10 +20,26 @@ export type RepositoryGraph = z.infer<typeof graphSchema>
20
20
  * Finish temporary cleanup before the returned promise settles. */
21
21
  export type GraphLoader = (cwd: string) => Promise<RepositoryGraph>
22
22
 
23
+ export class RepographNotInstalledError extends Error {}
24
+
25
+ export class GraphCleanupError extends Error {
26
+ readonly code = 'RESOURCE_RELEASE_FAILED'
27
+ }
28
+
23
29
  /** Resolve the optional Repograph package's CLI entry for loadGraph's default and live tests.
24
30
  * Throws if the package cannot be resolved. Deferring resolution allows source-only runs. */
25
31
  export function resolveRepographEntry(): string {
26
- return join(dirname(createRequire(import.meta.url).resolve('@youichi/repograph')), 'cli.js')
32
+ try {
33
+ return join(dirname(createRequire(import.meta.url).resolve('@youichi/repograph')), 'cli.js')
34
+ } catch (cause) {
35
+ if ((cause as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw cause
36
+ throw new RepographNotInstalledError('Cannot resolve the optional @youichi/repograph package', { cause })
37
+ }
38
+ }
39
+
40
+ /** Keep the supplied path as the index key so repeated exports reuse the same project. */
41
+ export function repographProject(cwd: string): string {
42
+ return `anureo-refactor-${createHash('sha256').update(cwd).digest('hex').slice(0, 16)}`
27
43
  }
28
44
 
29
45
  /** Export a validated graph for an absolute target directory. Supply an absolute CLI entry to
@@ -40,12 +56,14 @@ export async function loadGraph(cwd: string, entry = resolveRepographEntry()): P
40
56
  await validateRepositoryGraph(graph, cwd)
41
57
  return graph
42
58
  } finally {
43
- await rm(temporary, { recursive: true, force: true })
59
+ await rm(temporary, { recursive: true, force: true }).catch(cause => {
60
+ throw new GraphCleanupError(`Unable to remove temporary graph directory ${temporary}: ${cause.message}`, { cause })
61
+ })
44
62
  }
45
63
  }
46
64
 
47
- /** Validate the core export fields and retain language-specific node metadata. */
48
- const graphSchema = z.object({
65
+ /** Validate the core export fields and retain exporter and language-specific node metadata. */
66
+ const graphSchema = z.looseObject({
49
67
  schemaVersion: z.literal(1), repositoryPath: z.string(), kind: z.literal('all'),
50
68
  indexReport: z.record(z.string(), z.unknown()),
51
69
  nodes: z.array(z.looseObject({
@@ -62,27 +80,66 @@ const graphSchema = z.object({
62
80
  })),
63
81
  })
64
82
 
65
- /** Return the parsed CLI payload for loadGraph to validate. Await the subprocess before reading
66
- * graph.json from loadGraph's temporary directory. The subprocess has a five-minute timeout and
67
- * an 8 MiB output buffer limit. Process, filesystem, JSON and schema errors reject to loadGraph,
68
- * which removes the directory in either case. */
83
+ const exportTimeout = 300_000
84
+ const outputLimit = 8 << 20
85
+
86
+ /** Return the parsed CLI payload after the exporter has exited and its process tree is disposed. */
69
87
  async function exportRepositoryGraph(input: { cwd: string; entry: string; temporary: string }): Promise<RepositoryGraph> {
70
88
  const { cwd, entry, temporary } = input
71
89
  const output = join(temporary, 'graph.json')
72
- // Keep the supplied path as the index key so repeated exports reuse the same project.
73
- const project = `anureo-refactor-${createHash('sha256').update(cwd).digest('hex').slice(0, 16)}`
74
- await exec(process.execPath, [entry, 'export', cwd, '--kind', 'all', '--project', project, '--out', output],
75
- { cwd: temporary, maxBuffer: 8 << 20, timeout: 300_000 })
90
+ const child = await spawnHarnessProcess({
91
+ command: process.execPath, cwd: temporary,
92
+ args: [entry, 'export', cwd, '--kind', 'all', '--project', repographProject(cwd), '--out', output],
93
+ })
94
+ let timer: ReturnType<typeof setTimeout> | undefined
95
+ try {
96
+ const completion = Promise.all([child.exited, drainOutput(child.stdout, 'stdout'), drainOutput(child.stderr, 'stderr')])
97
+ const deadline = new Promise<never>((_, reject) => {
98
+ timer = setTimeout(() => reject(new Error(`repograph export timed out after ${exportTimeout} ms`)), exportTimeout)
99
+ })
100
+ const [exit, , stderr] = await Promise.race([completion, deadline])
101
+ if (exit.code !== 0) {
102
+ const status = exit.signal ? `with signal ${exit.signal}` : `with code ${exit.code}`
103
+ throw new Error(`repograph exited ${status}${stderr ? `: ${stderr}` : ''}`)
104
+ }
105
+ } finally {
106
+ clearTimeout(timer)
107
+ await child.dispose().catch(cause => {
108
+ throw new GraphCleanupError(`Unable to dispose repograph process: ${cause.message}`, { cause })
109
+ })
110
+ }
76
111
  return graphSchema.parse(JSON.parse(await readFile(output, 'utf8')))
77
112
  }
78
113
 
114
+ /** Enforce a byte limit on each pipe and retain stderr for exit diagnostics. */
115
+ async function drainOutput(stream: AsyncIterable<Uint8Array>, name: 'stdout' | 'stderr'): Promise<string> {
116
+ let bytes = 0
117
+ const chunks: Uint8Array[] = []
118
+ for await (const chunk of stream) {
119
+ bytes += chunk.byteLength
120
+ if (bytes > outputLimit) throw new Error(`repograph ${name} exceeded the ${outputLimit}-byte output limit`)
121
+ if (name === 'stderr') chunks.push(chunk)
122
+ }
123
+ return Buffer.concat(chunks).toString('utf8')
124
+ }
125
+
79
126
  /** Require a parsed graph to describe the same real directory and have unique node IDs and valid
80
127
  * edge references. loadGraph awaits this read-only check before returning the graph. Filesystem,
81
128
  * repository identity and graph integrity failures reject through loadGraph's cleanup. */
82
129
  async function validateRepositoryGraph(graph: RepositoryGraph, cwd: string): Promise<void> {
83
130
  if (await realpath(graph.repositoryPath) !== await realpath(cwd)) throw new Error('repograph returned a different repository')
84
- const ids = new Set(graph.nodes.map(node => node.id))
85
- if (ids.size !== graph.nodes.length || graph.edges.some(edge => !ids.has(edge.source) || !ids.has(edge.target))) {
86
- throw new Error('repograph returned duplicate nodes or missing edge endpoints')
131
+ const ids = new Set<string>()
132
+ let duplicateId: string | undefined
133
+ for (const node of graph.nodes) {
134
+ if (ids.has(node.id)) duplicateId ??= node.id
135
+ ids.add(node.id)
136
+ }
137
+ const edge = graph.edges.find(edge => !ids.has(edge.source) || !ids.has(edge.target))
138
+ const diagnostics: string[] = []
139
+ if (duplicateId !== undefined) diagnostics.push(`Duplicate node ID ${JSON.stringify(duplicateId)}`)
140
+ if (edge) {
141
+ const missingIds = [...new Set([edge.source, edge.target])].filter(id => !ids.has(id))
142
+ diagnostics.push(`Edge ${JSON.stringify(edge.id)} references missing node IDs ${JSON.stringify(missingIds)}`)
87
143
  }
144
+ if (diagnostics.length) throw new Error(diagnostics.join('\n'))
88
145
  }
package/src/index.ts CHANGED
@@ -1,4 +1,32 @@
1
- // Library entry point for running refactors, presenting reports and supplying repository graphs.
1
+ /**
2
+ * Refactor code with agents in isolated Git worktrees. The host validates edits before merging.
3
+ * The CLI requires Bun, Git and a configured harness. With Codex on PATH, run
4
+ * `anureo-refactor . --review-only` to inspect proposals without applying edits.
5
+ *
6
+ * Library callers supply and dispose an initialized client. Reports are saved under
7
+ * `<target>/.anureo/refactor/<run-id>/report.json`. A phase failure can return an incomplete
8
+ * report with edits already merged. Invalid input, run setup, final publication and lock
9
+ * cleanup failures reject the call.
10
+ *
11
+ * ```ts
12
+ * import { createCodexAdapter } from '@anureo/adapter-codex'
13
+ * import { createClient } from '@anureo/sdk'
14
+ * import { refactorCode } from '@anureo/refactor'
15
+ *
16
+ * const cwd = process.cwd()
17
+ * const client = await createClient({
18
+ * adapter: createCodexAdapter({ command: 'codex', cwd }),
19
+ * identity: { adapterId: 'codex', runtimeConfigId: 'refactor-example' },
20
+ * })
21
+ * try {
22
+ * const report = await refactorCode({ client, cwd, reviewOnly: true })
23
+ * console.log(report.status, report.directory)
24
+ * if (report.status === 'incomplete') process.exitCode = 2
25
+ * } finally {
26
+ * await client.dispose()
27
+ * }
28
+ * ```
29
+ */
2
30
  export { refactorCode } from './refactor'
3
31
  export type { RefactorOptions } from './options'
4
32
  export type { CheckCommand } from './checks'
package/src/options.ts CHANGED
@@ -33,7 +33,7 @@ export interface RefactorOptions {
33
33
  * subprocess and repographEntry. A rejection is recorded as a run failure. The loader owns
34
34
  * temporary resources and must clean them up before settling. */
35
35
  graphLoader?: GraphLoader
36
- /** Commands run serially in each edited worktree before integration. The first failure
36
+ /** Commands run serially on the prospective combined tree before integration. The first failure
37
37
  * stops later checks. An empty list disables checks. Omission discovers typecheck then test in
38
38
  * the target's own package.json. Blank executables or NUL bytes reject before the run, including
39
39
  * in reviewOnly mode, which skips execution. */
@@ -5,35 +5,34 @@ import type { ModulePlan } from './schema'
5
5
  * After the planning worktree is released, plan in refactor.ts supplies the schema-validated
6
6
  * response and the inventory it sent to the agent. A thrown Error leaves the plan unpublished
7
7
  * and stops module dispatch. The run lifecycle records that error in the incomplete report.
8
- * Compare paths literally. Check each module's ID before its files, and throw on the first invalid
9
- * ID or assignment. Report omissions in inventory order after checking all assignments.
8
+ * Compare paths literally. Report ID and assignment errors in traversal order, then omissions
9
+ * in inventory order.
10
10
  */
11
11
  export function validatePlan(plan: ModulePlan, files: readonly string[]): void {
12
12
  const expectedFiles = new Set(files)
13
- const assignedFiles = new Set<string>()
14
- const claimedIds = new Set<string>()
15
- for (const module of plan.modules) {
16
- claimModuleId(module.id, claimedIds)
17
- for (const file of module.files) {
18
- if (!expectedFiles.has(file) || assignedFiles.has(file)) {
19
- throw new Error(`Unlisted or duplicate module file: ${file}`)
13
+ const assignments = new Map<string, string>()
14
+ const claimedIds = new Map<string, string>()
15
+ const issues: string[] = []
16
+ for (const [index, module] of plan.modules.entries()) {
17
+ const location = `modules[${index}]`
18
+ const key = module.id.toLowerCase()
19
+ const firstId = claimedIds.get(key)
20
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(module.id)) {
21
+ issues.push(`${location}.id: ${JSON.stringify(module.id)} must start with an ASCII letter or digit and contain at most 80 letters, digits, underscores or hyphens`)
22
+ }
23
+ if (firstId) issues.push(`${location}.id: ${JSON.stringify(module.id)} duplicates ${firstId} ignoring case`)
24
+ else claimedIds.set(key, `${location}.id`)
25
+ for (const [fileIndex, file] of module.files.entries()) {
26
+ const assignment = `${location}.files[${fileIndex}]`
27
+ const firstAssignment = assignments.get(file)
28
+ if (!expectedFiles.has(file)) {
29
+ issues.push(`${assignment}: ${JSON.stringify(file)} is absent from the inventory`)
20
30
  }
21
- assignedFiles.add(file)
31
+ if (firstAssignment) issues.push(`${assignment}: ${JSON.stringify(file)} was already assigned at ${firstAssignment}`)
32
+ else assignments.set(file, assignment)
22
33
  }
23
34
  }
24
- const missing = files.filter(file => !assignedFiles.has(file))
25
- if (missing.length) throw new Error(`Module plan omitted source files: ${missing.join(', ')}`)
26
- }
27
-
28
- /**
29
- * Reserve an ID in validatePlan's set of lowercase keys. IDs are 1–80 ASCII characters
30
- * and start with a letter or digit. Later characters can also be underscores or hyphens.
31
- * Throw on an unsafe or repeated ID so runModules can report each assignment using a unique ID.
32
- */
33
- function claimModuleId(id: string, claimedIds: Set<string>): void {
34
- const key = id.toLowerCase()
35
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(id) || claimedIds.has(key)) {
36
- throw new Error(`Invalid or duplicate module id: ${id}`)
37
- }
38
- claimedIds.add(key)
35
+ const missing = files.filter(file => !assignments.has(file))
36
+ if (missing.length) issues.push(`Module plan omitted source files: ${missing.map(file => JSON.stringify(file)).join(', ')}`)
37
+ if (issues.length) throw new Error(issues.join('\n'))
39
38
  }
package/src/prompts.ts CHANGED
@@ -39,15 +39,7 @@ ${rules}`
39
39
  /** Build cross-file design instructions for runDesign to pass to runAgentWork before planning.
40
40
  * Supply the snapshot inventory and its graph path, or null to request direct source inspection.
41
41
  * runAgentWork configures session permissions separately. JSON serialization errors throw synchronously. */
42
- export function designPrompt(input: DesignPromptInput): string
43
- /** Build the same design instructions from positional arguments. Passing true for readOnly requests
44
- * read-only instructions. JSON serialization errors throw synchronously. */
45
- export function designPrompt(files: string[], graphFile: string, version: string, checks: readonly CheckCommand[], readOnly: boolean): string
46
- export function designPrompt(...args: [DesignPromptInput] | [string[], string, string, readonly CheckCommand[], boolean]): string {
47
- const input: DesignPromptInput = args.length === 1 ? args[0] : {
48
- files: args[0], graphFile: args[1], version: args[2], checks: args[3],
49
- mode: args[4] ? 'read-only' : 'edit',
50
- }
42
+ export function designPrompt(input: DesignPromptInput): string {
51
43
  const { files, graphFile, version } = input
52
44
  return `DESIGN MODULE BOUNDARIES
53
45
  Source version: ${version}
@@ -93,15 +85,7 @@ ${workResponseInstructions(input)}`
93
85
  /** Build instructions for runModules to pass to runAgentWork for one validated assignment.
94
86
  * Supply the module snapshot, its graph path or null, and the completed design summary.
95
87
  * runAgentWork configures session permissions separately. JSON serialization errors throw synchronously. */
96
- export function modulePrompt(input: ModulePromptInput): string
97
- /** Build the same module instructions from positional arguments. Passing true for readOnly requests
98
- * read-only instructions. JSON serialization errors throw synchronously. */
99
- export function modulePrompt(module: RefactorModule, graphFile: string, version: string, checks: readonly CheckCommand[], readOnly: boolean, design: string): string
100
- export function modulePrompt(...args: [ModulePromptInput] | [RefactorModule, string, string, readonly CheckCommand[], boolean, string]): string {
101
- const input: ModulePromptInput = args.length === 1 ? args[0] : {
102
- module: args[0], graphFile: args[1], version: args[2], checks: args[3],
103
- mode: args[4] ? 'read-only' : 'edit', design: args[5],
104
- }
88
+ export function modulePrompt(input: ModulePromptInput): string {
105
89
  const { module, graphFile, version, design } = input
106
90
  return `REFACTOR MODULE
107
91
  Module: ${JSON.stringify(module)}
@@ -113,7 +97,9 @@ ${structureGuide}
113
97
  Read the design summary before changing structure. Preserve its justified boundary decisions, and
114
98
  explain any revision supported by new source evidence. In read-only mode, evaluate proposed boundaries
115
99
  against the existing files and describe resulting edits as proposals.
116
- ${input.isolated ? 'Other modules run concurrently. Edit only the files assigned to this module and any new source files it needs. Defer changes to existing files outside the assignment.\n' : ''}Review this module's files and then fix what you find, in one pass. Identify its functions, callers
100
+ Other modules may run concurrently. Edit only the files assigned to this module and any new source
101
+ files it needs. Defer changes to existing files outside the assignment.
102
+ Review this module's files and then fix what you find, in one pass. Identify its functions, callers
117
103
  and callees from the source, using graph metrics where available to find the largest or most
118
104
  connected functions. Read those functions and the callers that matter. Before writing a function's
119
105
  doc comment, read its implementation and the production call sites needed to explain its role.
@@ -153,8 +139,6 @@ interface PromptContext {
153
139
  checks: readonly CheckCommand[]
154
140
  /** Instruction mode. The caller configures the agent session's permissions. */
155
141
  mode: 'read-only' | 'edit'
156
- /** True tells module agents to edit only assigned existing files and leaves edit checks to the host. */
157
- isolated?: boolean
158
142
  }
159
143
 
160
144
  /**
@@ -343,14 +327,8 @@ is already well organized and say why. Support structural changes with the maint
343
327
  before/after reading and editing paths, and ownership decisions. Distinguish source reasoning from
344
328
  checks actually run, and report unresolved evidence limits in "deferred".`
345
329
 
346
- /** Omit checks for review-only runs and empty command lists. For isolated edits, announce host
347
- * checks before integration. Otherwise ask the agent to run the checks before returning. A rendered
348
- * section ends with a newline so the response guidance starts on its own line. Serializing
349
- * commands can throw synchronously. */
350
- function validationInstructions({ checks, mode, isolated }: PromptContext): string {
330
+ /** Announce host checks for edits when commands are configured. */
331
+ function validationInstructions({ checks, mode }: PromptContext): string {
351
332
  if (mode === 'read-only' || checks.length === 0) return ''
352
- if (isolated) return `Validation commands: ${JSON.stringify(checks)}. The host runs them in your worktree before merging your edits.\n`
353
- return `Validation commands: ${JSON.stringify(checks)}. Run them before returning and fix failures.
354
- Object entries specify an executable and literal arguments. String entries use the platform shell.
355
- The host reruns them.\n`
333
+ return `Validation commands: ${JSON.stringify(checks)}. The host runs them on the combined tree before merging your edits.\n`
356
334
  }
package/src/refactor.ts CHANGED
@@ -5,7 +5,7 @@ import { agent } from '@anureo/workflow'
5
5
  import { inAgentWorktree, runAgentWork } from './agent-work'
6
6
  import { defaultChecks, validateChecks, type CheckCommand } from './checks'
7
7
  import { repositoryDirectory } from './git'
8
- import { treeVersion } from './git-tree'
8
+ import { captureTree, changes, treeVersion } from './git-tree'
9
9
  import { exportGraph, type GraphArtifactContext } from './graph-artifacts'
10
10
  import { validateConcurrency, validateGraphOptions, type RefactorOptions } from './options'
11
11
  import { validatePlan } from './plan-validation'
@@ -22,11 +22,12 @@ export type { RefactorOptions } from './options'
22
22
  /** Overall run report and the step, validation and failure records it contains. */
23
23
  export type { RefactorReport, ModuleResult, StepResult, CheckResult, Failure } from './results'
24
24
 
25
- /** Refactor a Git target in detached worktrees. The host checks edits in each worktree and
26
- * serializes transfers into the target as worktrees become ready. Review-only runs skip both.
25
+ /** Refactor a Git target in detached worktrees. The host serializes checks of prospective
26
+ * changes and transfers into the target as worktrees become ready. Review-only runs skip both.
27
27
  *
28
28
  * Returns a completed or incomplete report after final publication and writer-lock release. Design and planning failures
29
- * stop advancement. Module failures are recorded while other modules continue. Invalid input, repository preflight,
29
+ * stop advancement. Unknown outcomes or cleanup failures stop new module sessions. Active sessions settle.
30
+ * Invalid input, repository preflight,
30
31
  * lock acquisition, report initialization, final publication and lock cleanup failures reject.
31
32
  * Keep the supplied client usable until settlement and dispose it separately. */
32
33
  export async function refactorCode(input: RefactorOptions): Promise<RefactorReport> {
@@ -87,10 +88,11 @@ async function runDesign(context: RunContext): Promise<DesignResult> {
87
88
  baseline, options, checks, assignedFiles: initial.files, publish: operation => operation(),
88
89
  prompt: designPrompt({
89
90
  files: initial.files, graphFile, version: treeVersion(initial.tree), checks,
90
- mode: options.reviewOnly ? 'read-only' : 'edit', isolated: true,
91
+ mode: options.reviewOnly ? 'read-only' : 'edit',
91
92
  }),
92
93
  }),
93
94
  )
95
+ if (!design) throw new Error('Cross-module design did not start')
94
96
  report.design = design
95
97
  await checkpointStep(context, 'design', design)
96
98
  if (design.status === 'failed') throw new Error(`Cross-module design failed: ${design.error}`)
@@ -116,6 +118,7 @@ async function runModules(context: RunContext, baseline: WorktreeBaseline, input
116
118
  const { options, report, checks, progress } = context
117
119
  const results: ModuleResult[] = input.plan.modules.map(module => ({ module, step: null }))
118
120
  report.modules = results
121
+ const dispatch = { stopped: false }
119
122
  let writer = Promise.resolve()
120
123
  const publish = (operation: () => Promise<void>) => {
121
124
  const result = writer.then(operation)
@@ -123,16 +126,17 @@ async function runModules(context: RunContext, baseline: WorktreeBaseline, input
123
126
  return result
124
127
  }
125
128
 
126
- await runModuleWorkers(results, options.concurrency ?? results.length, async result => {
129
+ await runModuleWorkers(results, options.concurrency ?? results.length, () => !dispatch.stopped, async result => {
127
130
  const { module } = result
128
131
  progress(`module/${module.id}: started`)
129
132
  const step = await runAgentWork({
130
- baseline, options, checks, publish, assignedFiles: module.files,
133
+ baseline, options, checks, publish, dispatch, assignedFiles: module.files,
131
134
  prompt: modulePrompt({
132
135
  module, graphFile: input.graphFile, version: input.version, checks,
133
- mode: options.reviewOnly ? 'read-only' : 'edit', design: input.design, isolated: true,
136
+ mode: options.reviewOnly ? 'read-only' : 'edit', design: input.design,
134
137
  }),
135
138
  })
139
+ if (!step) return
136
140
  progress(`module/${module.id}: finished`)
137
141
  await publish(async () => {
138
142
  result.step = step
@@ -151,29 +155,30 @@ async function checkpointStep(context: RunContext, label: string, step: StepResu
151
155
  await saveReport(context.report)
152
156
  }
153
157
 
154
- /** Partition the post-design inventory for prepareModules. Supply the read permission mode
155
- * and await checkout removal before checking exact path coverage. A missing result, invalid
156
- * assignment, session failure or checkout failure rejects before the report can record a plan. */
158
+ /** Partition the post-design inventory without edits, then verify coverage after checkout removal. */
157
159
  async function plan(options: RefactorOptions, baseline: WorktreeBaseline, files: string[], version: string): Promise<ModulePlan> {
158
- const result = await inAgentWorktree(baseline, ({ cwd }) =>
159
- agent(planPrompt(files, version), {
160
+ const result = await inAgentWorktree(baseline, async ({ cwd, root }) => {
161
+ const before = await captureTree(root)
162
+ const planned = await agent(planPrompt(files, version), {
160
163
  client: options.client, cwd, model: options.model, permissionMode: options.readPermissionMode,
161
164
  schema: modulePlanSchema, outputFallback: 'json-text',
162
- }),
163
- )
164
- if (!result) throw new Error('Module planning returned no result')
165
+ })
166
+ if (changes(before, await captureTree(root)).length) throw new Error('Module planner modified files')
167
+ if (!planned) throw new Error('Module planning returned no result')
168
+ return planned
169
+ })
165
170
  validatePlan(result, files)
166
171
  return result
167
172
  }
168
173
 
169
- /** Claim each result slot once, with at most limit callbacks active. runModules supplies a callback
170
- * that records the step and emits progress. Drain every slot before propagating the earliest
174
+ /** Claim available slots while dispatch is open, with at most limit callbacks active. runModules
175
+ * supplies a callback that records the step and emits progress. Drain active workers before propagating the earliest
171
176
  * callback rejection in plan order, so baseline cleanup cannot race a running worker. */
172
- async function runModuleWorkers(results: ModuleResult[], limit: number, run: (result: ModuleResult) => Promise<void>): Promise<void> {
177
+ async function runModuleWorkers(results: ModuleResult[], limit: number, mayDispatch: () => boolean, run: (result: ModuleResult) => Promise<void>): Promise<void> {
173
178
  let next = 0
174
179
  let rejection: { index: number; cause: unknown } | undefined
175
180
  const workers = Array.from({ length: Math.min(limit, results.length) }, async () => {
176
- while (next < results.length) {
181
+ while (next < results.length && mayDispatch()) {
177
182
  const index = next++
178
183
  try { await run(results[index]!) }
179
184
  catch (cause) {
@@ -4,7 +4,7 @@ import type { RefactorReport } from './results'
4
4
 
5
5
  /** Publish the current report as newline-terminated JSON and resolve after replacing report.json.
6
6
  * checkpointStep saves the design outcome before its failure gate, prepareModules saves the plan
7
- * before dispatch, and runModules saves each recorded outcome in integration order. finalizeRun
7
+ * before dispatch, and runModules saves each recorded outcome in integration order. withRun
8
8
  * awaits the last publication attempt before releasing the lock.
9
9
  * The caller supplies an existing run directory and serializes writes under the writer lock
10
10
  * because all saves use the same sibling temporary file. Serialization and filesystem errors
package/src/report.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { join } from 'node:path'
2
- import type { RefactorReport, StepResult } from './results'
2
+ import type { Failure, RefactorReport, StepResult } from './results'
3
3
 
4
4
  /** Render a report from refactorCode as newline-terminated text, the format executeRefactor
5
5
  * prints in CLI text mode. Design appears before module results in plan order. The text includes
@@ -8,8 +8,8 @@ import type { RefactorReport, StepResult } from './results'
8
8
  export function formatReport(report: RefactorReport): string {
9
9
  const lines = [
10
10
  `Refactor: ${report.status}${report.reviewOnly ? ' (review only)' : ''}`,
11
- `Directory: ${report.cwd}`,
12
- `Report: ${join(report.directory, 'report.json')}`,
11
+ `Directory: ${field(report.cwd)}`,
12
+ `Report: ${field(join(report.directory, 'report.json'))}`,
13
13
  ]
14
14
  if (report.design) {
15
15
  lines.push('', 'Cross-module design')
@@ -17,28 +17,44 @@ export function formatReport(report: RefactorReport): string {
17
17
  }
18
18
  for (const graph of report.graphCoverage ?? []) {
19
19
  const missing = graph.filesWithoutSymbols
20
- lines.push('', `Graph (${graph.phase}): ${graph.status}${graph.error ? ` — ${graph.error}` : ''}`)
21
- if (missing.length) lines.push(`Files without indexed symbols: ${missing.join(', ')}`)
20
+ lines.push('', `Graph (${field(graph.phase)}): ${graph.status}${graph.error ? ` — ${field(graph.error)}` : ''}`)
21
+ if (missing.length) lines.push(`Files without indexed symbols: ${missing.map(field).join(', ')}`)
22
22
  }
23
- lines.push('', report.plan?.summary ?? 'Module planning did not complete.')
23
+ lines.push('', field(report.plan?.summary ?? 'Module planning did not complete.'))
24
24
  for (const item of report.modules) {
25
- lines.push('', `${item.module.id}: ${item.module.name}`)
25
+ lines.push('', `${field(item.module.id)}: ${field(item.module.name)}`)
26
26
  if (item.step) appendStep(lines, item.step)
27
27
  }
28
- for (const error of report.errors) lines.push('', `Error: ${error}`)
29
- for (const error of report.progressErrors) lines.push('', `Progress reporting error: ${error}`)
28
+ for (const error of report.errors) lines.push('', `Error: ${field(error)}`)
29
+ appendFailure(lines, report.failure)
30
+ for (const error of report.progressErrors) lines.push('', `Progress reporting error: ${field(error)}`)
30
31
  return `${lines.join('\n')}\n`
31
32
  }
32
33
 
33
- /** Append a design or module result to formatReport's text buffer. Call out execution uncertainty
34
- * explicitly because the error text alone cannot tell a reader whether edits ran. */
34
+ /** Append a design or module result to formatReport's text buffer. */
35
35
  function appendStep(lines: string[], step: StepResult): void {
36
- lines.push(`Result: ${step.status}. ${step.error ?? step.summary}`)
37
- if (step.failure?.outcomeUnknown) lines.push('Agent execution outcome is unknown; inspect source and backend execution before starting another run.')
38
- for (const change of step.changes) lines.push(`- ${change}`)
39
- if (step.changedFiles.length) lines.push(`Changed files: ${step.changedFiles.join(', ')}`)
40
- if (step.status === 'failed' && step.patch) lines.push(`Patch: ${step.patch}`)
41
- for (const item of step.deferred) lines.push(`Deferred ${item.title}: ${item.reason}`)
42
- for (const check of step.checks) lines.push(`Check ${check.status}: ${check.command}`)
36
+ lines.push(`Result: ${step.status}. ${field(step.error ?? step.summary)}`)
37
+ appendFailure(lines, step.failure)
38
+ for (const change of step.changes) lines.push(`- ${field(change)}`)
39
+ if (step.changedFiles.length) lines.push(`Files changed in the agent worktree: ${step.changedFiles.map(field).join(', ')}`)
40
+ if (step.status === 'failed' && step.patch) lines.push(`Patch: ${field(step.patch)}`)
41
+ for (const item of step.deferred) lines.push(`Deferred ${field(item.title)}: ${field(item.reason)}`)
42
+ for (const check of step.checks) lines.push(`Check ${check.status}: ${field(check.command)}`)
43
43
  if (step.status === 'applied' && !step.checks.length) lines.push('No validation commands ran; runtime behavior was not tested.')
44
44
  }
45
+
46
+ function appendFailure(lines: string[], failure: Failure | null | undefined): void {
47
+ if (failure?.outcomeUnknown) {
48
+ lines.push('Agent execution outcome is unknown. Inspect source and backend execution before starting another run.')
49
+ }
50
+ for (const { path, code } of failure?.issues ?? []) {
51
+ const location = typeof path === 'string' ? path : JSON.stringify(path)
52
+ lines.push(`Validation issue: ${field(location || '(root)')} [${field(code)}]`)
53
+ }
54
+ }
55
+
56
+ /** Keep controls and embedded line breaks inside their text field. */
57
+ function field(value: string): string {
58
+ return value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, char =>
59
+ '\\u' + char.charCodeAt(0).toString(16).padStart(4, '0'))
60
+ }
package/src/results.ts CHANGED
@@ -24,6 +24,8 @@ export interface StepResult extends Work {
24
24
  status: 'applied' | 'unchanged' | 'failed'
25
25
  /** Sorted Git-visible paths changed by the isolated agent within the target directory. */
26
26
  changedFiles: string[]
27
+ /** Paths confirmed transferred to the target, even if cleanup later failed. Absence conveys no confirmed transfer. */
28
+ appliedFiles?: string[]
27
29
  /** Legacy report field containing the path to a historical patch artifact. */
28
30
  patch?: string
29
31
  /** Executed checks in command order; a failure stops subsequent checks. */