@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.
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ // Set the process exit code after the CLI has finished any client cleanup.
3
+ import { runCli } from '../src/cli'
4
+
5
+ process.exitCode = await runCli(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@anureo/refactor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "Graph-assisted code refactoring with parallel agents in separate Git worktrees",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/hi-youichi/anureo-sdk.git",
9
+ "directory": "apps/refactor"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "exports": {
16
+ ".": "./src/index.ts"
17
+ },
18
+ "bin": {
19
+ "anureo-refactor": "./bin/anureo-refactor.ts"
20
+ },
21
+ "scripts": {
22
+ "build": "tsc --noEmit",
23
+ "typecheck": "tsc --noEmit --pretty false",
24
+ "test": "bun test tests"
25
+ },
26
+ "dependencies": {
27
+ "@anureo/adapter-acp": "0.3.1",
28
+ "@anureo/adapter-ahp": "0.3.1",
29
+ "@anureo/adapter-claude": "0.3.1",
30
+ "@anureo/adapter-codex": "0.3.1",
31
+ "@anureo/adapter-hermes": "0.3.1",
32
+ "@anureo/adapter-pi": "0.3.1",
33
+ "@anureo/sdk": "0.3.1",
34
+ "@anureo/workflow": "0.3.1",
35
+ "zod": "4.6.7"
36
+ },
37
+ "optionalDependencies": {
38
+ "@youichi/repograph": "0.1.1"
39
+ },
40
+ "devDependencies": {
41
+ "@anureo/conformance": "0.3.1",
42
+ "@anureo/protocol": "0.3.1"
43
+ },
44
+ "engines": {
45
+ "node": ">=22",
46
+ "bun": ">=1.4.2"
47
+ }
48
+ }
@@ -0,0 +1,132 @@
1
+ // Runs isolated agent sessions and integrates their observed changes.
2
+ import { sep } from 'node:path'
3
+ import { agent } from '@anureo/workflow'
4
+ import { runChecks, type CheckCommand } from './checks'
5
+ import { failure, message } from './errors'
6
+ import { captureTree, changes } from './git-tree'
7
+ import type { RefactorOptions } from './options'
8
+ import type { StepResult } from './results'
9
+ import { workSchema } from './schema'
10
+ import { isSource, isTextSource } from './source-policy'
11
+ import { createAgentWorktree, mergeWorktree, prepareCheckDependencies, removeAgentWorktree, type AgentWorktree, type WorktreeBaseline } from './worktree'
12
+
13
+ /** Run one callback in a fresh checkout of the supplied baseline. The callback must await all
14
+ * work that uses the checkout. Removal is awaited before returning its result or propagating its
15
+ * error. Creation and removal failures propagate, and a removal failure takes precedence over
16
+ * a callback failure. The caller owns the baseline. */
17
+ export async function inAgentWorktree<T>(baseline: WorktreeBaseline, use: (worktree: AgentWorktree) => Promise<T>): Promise<T> {
18
+ const worktree = await createAgentWorktree(baseline)
19
+ try {
20
+ return await use(worktree)
21
+ } finally {
22
+ await removeAgentWorktree(baseline, worktree)
23
+ }
24
+ }
25
+
26
+ /** Run a session, validate its edits in the worktree, and merge on the caller's writer queue.
27
+ * A failed session, policy check or validation leaves the target untouched. Cleanup is awaited. */
28
+ export async function runAgentWork(input: AgentWorkInput): Promise<StepResult> {
29
+ const step: StepResult = { summary: '', changes: [], deferred: [], status: 'unchanged', changedFiles: [], checks: [], error: null, failure: null }
30
+ try {
31
+ await inAgentWorktree(input.baseline, async worktree => {
32
+ const before = await captureTree(worktree.root)
33
+ await recordSessionResult(input, worktree.cwd, step)
34
+ const edited = await captureTree(worktree.root)
35
+ await recordAgentEdits(input, worktree, changes(before, edited), before, step)
36
+ if (step.status === 'failed' || !step.changedFiles.length) return
37
+ if (input.checks.length) {
38
+ await prepareCheckDependencies(input.baseline, worktree)
39
+ const beforeChecks = await captureTree(worktree.root)
40
+ await runChecks(worktree.cwd, input.checks, step.checks)
41
+ const changedByChecks = changes(beforeChecks, await captureTree(worktree.root))
42
+ if (changedByChecks.length) throw new Error(`Validation modified source files: ${changedByChecks.join(', ')}`)
43
+ }
44
+ await input.publish(async () => {
45
+ await mergeWorktree(input.baseline, worktree, step.changedFiles)
46
+ step.status = 'applied'
47
+ })
48
+ })
49
+ } catch (cause) {
50
+ markFailed(step, cause)
51
+ }
52
+ return step
53
+ }
54
+
55
+ /** Mark a step failed in place. Later errors append diagnostics and can record a cleanup
56
+ * failure while preserving the first error's code and outcome uncertainty. recordSessionResult and
57
+ * runAgentWork record caught errors here. Error conversion itself can throw for custom error objects. */
58
+ export function markFailed(step: StepResult, cause: unknown): void {
59
+ const observed = failure(cause)
60
+ if (step.failure) {
61
+ step.failure.cleanupFailed ||= observed.cleanupFailed
62
+ step.error += `\n${message(cause)}`
63
+ return
64
+ }
65
+ step.status = 'failed'
66
+ step.error = message(cause)
67
+ step.failure = observed
68
+ }
69
+
70
+ interface AgentWorkInput {
71
+ baseline: WorktreeBaseline
72
+ options: RefactorOptions
73
+ prompt: string
74
+ checks: readonly CheckCommand[]
75
+ publish: (operation: () => Promise<void>) => Promise<void>
76
+ /** Editable inventory for design or the validated assignment for a module. */
77
+ assignedFiles: readonly string[]
78
+ }
79
+
80
+ /** Merge the schema-validated response into the step after the workflow agent settles. Record
81
+ * session failure, including a missing result, so runAgentWork can still inspect the checkout. */
82
+ async function recordSessionResult({ options, prompt }: AgentWorkInput, cwd: string, step: StepResult): Promise<void> {
83
+ try {
84
+ const work = await agent(prompt, {
85
+ client: options.client, cwd, model: options.model,
86
+ permissionMode: options.reviewOnly ? options.readPermissionMode : options.editPermissionMode,
87
+ schema: workSchema, outputFallback: 'json-text',
88
+ })
89
+ if (!work) throw new Error('Agent returned no result')
90
+ Object.assign(step, work)
91
+ } catch (cause) {
92
+ markFailed(step, cause)
93
+ }
94
+ }
95
+
96
+ /** Record target-relative edits and reject writes outside the worktree assignment. */
97
+ async function recordAgentEdits(
98
+ { baseline, options, assignedFiles }: AgentWorkInput,
99
+ worktree: AgentWorktree,
100
+ touched: readonly string[],
101
+ before: ReadonlyMap<string, string>,
102
+ step: StepResult,
103
+ ): Promise<void> {
104
+ const scopePrefix = baseline.scope ? baseline.scope.split(sep).join('/') + '/' : ''
105
+ const changedFiles = touched.filter(file => file.startsWith(scopePrefix)).map(file => file.slice(scopePrefix.length))
106
+ step.changedFiles = changedFiles
107
+ if (touched.length !== changedFiles.length) throw new Error('Agent changed paths outside the refactor target')
108
+ if (options.reviewOnly && touched.length) throw new Error('Review-only agent modified files')
109
+ await validateModuleEdits({ assignedFiles, changedFiles, before, scopePrefix, cwd: worktree.cwd, options })
110
+ }
111
+
112
+ /** Allow assigned paths and newly added files that qualify as text source. Report every other
113
+ * edited path in diff order. Source inspection can also reject. */
114
+ async function validateModuleEdits(input: {
115
+ assignedFiles: readonly string[]
116
+ changedFiles: readonly string[]
117
+ before: ReadonlyMap<string, string>
118
+ scopePrefix: string
119
+ cwd: string
120
+ options: RefactorOptions
121
+ }): Promise<void> {
122
+ const { assignedFiles, changedFiles, before, scopePrefix, cwd, options } = input
123
+ const assigned = new Set(assignedFiles)
124
+ const violations: string[] = []
125
+ for (const file of changedFiles) {
126
+ if (assigned.has(file)) continue
127
+ if (!before.has(scopePrefix + file) && isSource(file, options.include, options.exclude)
128
+ && await isTextSource(cwd, file)) continue
129
+ violations.push(file)
130
+ }
131
+ if (violations.length) throw new Error(`Module edited paths outside its assignment: ${violations.join(', ')}`)
132
+ }
package/src/checks.ts ADDED
@@ -0,0 +1,70 @@
1
+ // Discovers and executes ordered validation commands for changed refactor steps.
2
+ import { readFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { message } from './errors'
5
+ import { exec } from './process'
6
+ import type { CheckResult } from './results'
7
+
8
+ /** Configure validation in the agent checkout. Strings go to the platform shell. Objects
9
+ * launch the named executable directly with literal arguments, defaulting to no arguments. */
10
+ export type CheckCommand = string | { executable: string; args?: readonly string[] }
11
+
12
+ /** Reject a blank command or executable, or a NUL in a command, executable or literal argument.
13
+ * refactorCode runs this before repository preflight and parseCliInput uses it before client
14
+ * creation. Omitted and empty lists pass this check. Only omission allows script discovery. */
15
+ export function validateChecks(commands: readonly CheckCommand[] | undefined, label = 'check'): void {
16
+ for (const command of commands ?? []) {
17
+ const executable = typeof command === 'string' ? command : command.executable
18
+ if (!executable.trim()) throw new Error(`${label} commands must be nonempty`)
19
+ if (executable.includes('\0') || (typeof command !== 'string' && command.args?.some(arg => arg.includes('\0')))) {
20
+ throw new Error(`${label} commands and arguments cannot contain NUL`)
21
+ }
22
+ }
23
+ }
24
+
25
+ /** Discover typecheck then test for refactorCode when checks are omitted outside review-only mode.
26
+ * Includes only string-valued scripts in the target package.json. A packageManager declaration
27
+ * starting with bun@, npm@, pnpm@ or yarn@ selects that runner; otherwise uses npm.
28
+ * Reads no parent packages and starts no process.
29
+ * Missing package.json yields no checks; malformed JSON and other filesystem errors reject. */
30
+ export async function defaultChecks(cwd: string): Promise<CheckCommand[]> {
31
+ let pkg: { packageManager?: string; scripts?: Record<string, unknown> }
32
+ try { pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')) }
33
+ catch (cause) {
34
+ if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return []
35
+ throw cause
36
+ }
37
+ const manager = /^(bun|npm|pnpm|yarn)@/.exec(pkg.packageManager ?? '')?.[1] ?? 'npm'
38
+ return ['typecheck', 'test'].filter(name => typeof pkg.scripts?.[name] === 'string').map(name =>
39
+ // Windows package managers other than Bun are commonly provided by .cmd shims.
40
+ process.platform === 'win32' && manager !== 'bun'
41
+ ? `${manager} run ${name}`
42
+ : { executable: manager, args: ['run', name] },
43
+ )
44
+ }
45
+
46
+ /** Execute validation commands serially, appending bounded output to the caller's results array.
47
+ * runAgentWork awaits this before merging and records rejection as a failed step.
48
+ * Commands may modify files or start other processes.
49
+ * Resolves void after all checks; the first failed command is recorded before rejection and stops
50
+ * later commands. Each process has a five-minute timeout and an eight-MiB
51
+ * limit on each output stream. Reports concatenate stdout then stderr, followed by the error
52
+ * message on failure, and retain only the final 4,000 characters. An empty command list resolves
53
+ * without changing results; existing entries are retained. */
54
+ export async function runChecks(cwd: string, commands: readonly CheckCommand[], results: CheckResult[]): Promise<void> {
55
+ const limits = { cwd, maxBuffer: 8 << 20, timeout: 300_000, windowsHide: true }
56
+ for (const command of commands) {
57
+ const display = typeof command === 'string' ? command : [command.executable, ...(command.args ?? [])]
58
+ .map(arg => /^[\w./:-]+$/.test(arg) ? arg : JSON.stringify(arg)).join(' ')
59
+ try {
60
+ const { stdout, stderr } = typeof command === 'string'
61
+ ? await exec(command, [], { ...limits, shell: true })
62
+ : await exec(command.executable, [...command.args ?? []], limits)
63
+ results.push({ command: display, status: 'passed', output: `${stdout}${stderr}`.slice(-4000) })
64
+ } catch (cause) {
65
+ const error = cause as { stdout?: string; stderr?: string }
66
+ results.push({ command: display, status: 'failed', output: `${error.stdout ?? ''}${error.stderr ?? ''}\n${message(cause)}`.slice(-4000) })
67
+ throw new Error(`Validation failed: ${display}`)
68
+ }
69
+ }
70
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,214 @@
1
+ // Admits CLI commands and owns the client used to execute them.
2
+ import { resolve } from 'node:path'
3
+ import { parseArgs, type ParseArgsOptionsConfig } from 'node:util'
4
+ import type { Client } from '@anureo/sdk'
5
+ import { validateChecks, type CheckCommand } from './checks'
6
+ import { createRefactorClient, harnessPermissions, refactorHarnesses, type HarnessSelection } from './client'
7
+ import { message } from './errors'
8
+ import type { GraphLoader } from './graph'
9
+ import { validateConcurrency, validateGraphOptions, type RefactorOptions } from './options'
10
+ import { refactorCode } from './refactor'
11
+ import { formatReport } from './report'
12
+
13
+ /** Run an installed CLI command with arguments after the executable path.
14
+ * bin/anureo-refactor.ts awaits the result as its exit code. Returns 0 for help or completion
15
+ * and 2 for incomplete runs or caught argument, run, output or cleanup failures.
16
+ * Help and argument errors acquire no client; disposal of an acquired client is awaited before this settles.
17
+ * Orchestration may edit files and start processes. Supplied output callbacks run synchronously,
18
+ * and an error diagnostic callback that throws still rejects. */
19
+ export async function runCli(args: string[], dependencies: CliDependencies = {}): Promise<number> {
20
+ const stdout = dependencies.stdout ?? (text => { process.stdout.write(text) })
21
+ const stderr = dependencies.stderr ?? (text => { process.stderr.write(text) })
22
+ try {
23
+ const command = parseCliInput(args, dependencies)
24
+ if (command.kind === 'help') { stdout(help); return 0 }
25
+ return await executeRefactor(command, dependencies, { stdout, stderr })
26
+ } catch (cause) {
27
+ stderr(`anureo-refactor: ${message(cause)}\n`)
28
+ return 2
29
+ }
30
+ }
31
+
32
+ /** Usage printed by runCli without loading the optional exporter. */
33
+ const help = `Usage: anureo-refactor [repository] [options]
34
+
35
+ One agent fixes design between modules, then module agents work concurrently in separate Git
36
+ worktrees. The host validates edits in each worktree and merges verified changes as they become
37
+ ready. Defaults to the current directory, which may be any directory inside a Git work tree.
38
+ Requires Bun, Git, and a configured harness. Graph export uses @youichi/repograph when installed.
39
+ Use CODEX_BIN, CLAUDE_BIN, HERMES_BIN or DSH_BIN to override an executable.
40
+
41
+ Options:
42
+ --harness <id> Backend (default: codex): ${refactorHarnesses.join(', ')}
43
+ --harness-command <exe> ACP or AHP stdio executable
44
+ --harness-arg <arg> ACP or AHP stdio argument (repeatable; use = for flags)
45
+ --harness-url <url> AHP WebSocket endpoint in place of a stdio command
46
+ --read-permission-mode <mode> Override the backend mode for planning and review-only sessions
47
+ --edit-permission-mode <mode> Override the backend mode for editing sessions
48
+ --review-only Ask agents to propose changes; enforcement depends on the backend mode
49
+ --model <name> Override the selected harness model (Codex also reads CODEX_MODEL)
50
+ --concurrency <number> Maximum simultaneous module tasks (default: all modules)
51
+ --repograph <entry> Override the installed repograph CLI with a JS/TS entry path
52
+ --no-graph Inspect source directly without exporting a graph
53
+ --include <glob> Select Git-relative text paths (repeatable, slash separators)
54
+ --exclude <glob> Skip matching paths (repeatable, slash separators)
55
+ --check <command> Validation command using the platform shell (repeatable)
56
+ --check-argv <json> Validation executable and arguments as a JSON string array (repeatable)
57
+ Default: root package.json typecheck/test scripts
58
+ --json Print the structured report
59
+ --help, -h Show help
60
+
61
+ Reports: <repository>/.anureo/refactor/<run-id>/report.json
62
+ Scope: Git-visible UTF-8 or BOM-marked UTF-16 text under the target directory. Excludes docs and draft
63
+ directories, dependencies, generated directories, and build/run output. Without --include, common
64
+ metadata and prose are skipped.
65
+ Runs start fresh. Verified edits already merged remain in the target after a failure.
66
+ Exit codes: 0 complete, 2 incomplete/error.
67
+ `
68
+
69
+ /** Internal overrides for runCli tests; omitted fields use production factories, paths and streams. */
70
+ interface CliDependencies {
71
+ /** Factory for the CLI-owned client; runCli awaits disposal even after execution fails. */
72
+ createClient?: (cwd: string, harness: HarnessSelection) => Promise<Client>
73
+ /** Supply a validated graph for the canonical target, finishing exporter cleanup before resolving. */
74
+ graphLoader?: GraphLoader
75
+ /** Base directory for relative repository and repograph paths; defaults to process.cwd(). */
76
+ cwd?: string
77
+ /** Environment for the fallback CODEX_MODEL lookup. Omit to read process.env.
78
+ * Client creation and subprocess launch still use the process environment. */
79
+ env?: Record<string, string | undefined>
80
+ /** Synchronous help/report sink; a thrown error enters CLI error reporting. */
81
+ stdout?: (text: string) => void
82
+ /** Synchronous progress/error sink; progress errors are recorded, error-reporting throws may reject runCli. */
83
+ stderr?: (text: string) => void
84
+ }
85
+
86
+ const cliOptions = {
87
+ help: { type: 'boolean', short: 'h' }, json: { type: 'boolean' }, 'review-only': { type: 'boolean' },
88
+ model: { type: 'string' }, repograph: { type: 'string' }, concurrency: { type: 'string' },
89
+ 'no-graph': { type: 'boolean' }, check: { type: 'string', multiple: true },
90
+ 'check-argv': { type: 'string', multiple: true },
91
+ include: { type: 'string', multiple: true }, exclude: { type: 'string', multiple: true },
92
+ harness: { type: 'string' }, 'harness-command': { type: 'string' },
93
+ 'harness-arg': { type: 'string', multiple: true }, 'harness-url': { type: 'string' },
94
+ 'read-permission-mode': { type: 'string' }, 'edit-permission-mode': { type: 'string' },
95
+ } as const satisfies ParseArgsOptionsConfig
96
+
97
+ /** Parse strict option syntax for runCli. Help bypasses run-only admission and path resolution.
98
+ * For runs, throw on invalid options or extra paths before runCli acquires a client. */
99
+ function parseCliInput(args: string[], dependencies: CliDependencies) {
100
+ const { values, positionals, tokens } = parseArgs({ args, strict: true, allowPositionals: true, tokens: true, options: cliOptions })
101
+ if (values.help) return { kind: 'help' as const }
102
+ if (positionals.length > 1) throw new Error('Expected at most one repository directory')
103
+ const concurrency = values.concurrency === undefined ? undefined : Number(values.concurrency)
104
+ validateConcurrency(concurrency, '--concurrency')
105
+ const requestedHarness = values.harness ?? 'codex'
106
+ const id = refactorHarnesses.find(id => id === requestedHarness)
107
+ if (!id) throw new Error(`Unknown harness: ${values.harness}. Available: ${refactorHarnesses.join(', ')}`)
108
+ const harness: HarnessSelection = { id, command: values['harness-command'], args: values['harness-arg'], url: values['harness-url'] }
109
+ validateHarness(harness)
110
+ validateGraphOptions(values['no-graph'], values.repograph !== undefined || Boolean(dependencies.graphLoader), '--no-graph')
111
+ return {
112
+ kind: 'refactor' as const, values, harness, concurrency, checks: parseChecks(tokens),
113
+ cwd: resolve(dependencies.cwd ?? process.cwd(), positionals[0] ?? '.'),
114
+ }
115
+ }
116
+
117
+ type CliTokens = ReturnType<typeof parseArgs<{ tokens: true; options: typeof cliOptions; allowPositionals: true }>>['tokens']
118
+
119
+ /** Read check flags in token order so shell commands and argv commands can be interleaved.
120
+ * Throw on malformed argv or invalid commands. Return undefined when the CLI should discover checks. */
121
+ function parseChecks(tokens: Readonly<CliTokens>): CheckCommand[] | undefined {
122
+ const checks: CheckCommand[] = []
123
+ for (const token of tokens) {
124
+ if (token.kind !== 'option') continue
125
+ if (token.name === 'check') checks.push(token.value)
126
+ if (token.name === 'check-argv') checks.push(parseCheckArgv(token.value))
127
+ }
128
+ validateChecks(checks, '--check')
129
+ return checks.length ? checks : undefined
130
+ }
131
+
132
+ /** Enforce CLI transport admission before passing the selection to the client factory.
133
+ * ACP requires stdio, and AHP requires stdio or a WebSocket URL. Invalid combinations throw. */
134
+ function validateHarness({ id, command, args, url }: HarnessSelection): void {
135
+ if (url !== undefined && (id !== 'ahp' || command !== undefined || args !== undefined || !url.trim())) {
136
+ throw new Error('--harness-url requires ahp and cannot be combined with stdio options')
137
+ }
138
+ if (command !== undefined && ((id !== 'ahp' && id !== 'acp') || !command.trim())) {
139
+ throw new Error('--harness-command requires acp or ahp and a nonempty executable')
140
+ }
141
+ if (args !== undefined && command === undefined) throw new Error('--harness-arg requires --harness-command')
142
+ if ((id === 'acp' || id === 'ahp') && command === undefined && url === undefined) {
143
+ throw new Error(`Harness ${id} requires --harness-command${id === 'ahp' ? ' or --harness-url' : ''}`)
144
+ }
145
+ }
146
+
147
+ /** Decode an argv check without interpreting shell syntax. Throw on invalid JSON or array shape.
148
+ * parseChecks validates the executable and arguments after decoding all argv flags. */
149
+ function parseCheckArgv(value: string): CheckCommand {
150
+ let argv: unknown
151
+ try { argv = JSON.parse(value) } catch {}
152
+ const [executable, ...args] = Array.isArray(argv) ? argv : []
153
+ if (typeof executable !== 'string' || !args.every(arg => typeof arg === 'string')) {
154
+ throw new Error('--check-argv requires a JSON array of strings beginning with the executable')
155
+ }
156
+ return { executable, args }
157
+ }
158
+
159
+ /** Validated execution input; help commands cannot acquire a client. */
160
+ type RefactorCommand = Extract<ReturnType<typeof parseCliInput>, { kind: 'refactor' }>
161
+
162
+ /** Output callbacks selected once by runCli and shared by report, progress and cleanup paths. */
163
+ interface CliOutput {
164
+ stdout: (text: string) => void
165
+ stderr: (text: string) => void
166
+ }
167
+
168
+ /** Run a validated command for runCli, print its report and return 0 for completion or 2 for an
169
+ * incomplete run. Acquire a client and await disposal after orchestration and report delivery.
170
+ * A disposal error rejects after a returned report, including an incomplete report. If execution
171
+ * throws, report a disposal error separately and preserve the execution error when that sink succeeds. */
172
+ async function executeRefactor(command: RefactorCommand, dependencies: CliDependencies, output: CliOutput): Promise<number> {
173
+ const { stdout, stderr } = output
174
+ const client = await (dependencies.createClient ?? createRefactorClient)(command.cwd, command.harness)
175
+ let executionThrew = false
176
+ try {
177
+ const report = await refactorCode(resolveRunOptions({ command, dependencies, client, stderr }))
178
+ stdout(command.values.json ? `${JSON.stringify(report, null, 2)}\n` : formatReport(report))
179
+ return report.status === 'incomplete' ? 2 : 0
180
+ } catch (cause) {
181
+ executionThrew = true
182
+ throw cause
183
+ } finally {
184
+ try { await client.dispose() }
185
+ catch (cause) {
186
+ if (!executionThrew) throw cause
187
+ stderr(`anureo-refactor: cleanup failed: ${message(cause)}\n`)
188
+ }
189
+ }
190
+ }
191
+
192
+ /** Resolve CLI defaults just before executeRefactor starts orchestration with an acquired client.
193
+ * Relative exporter paths use the invocation directory. An option resolution throw follows the
194
+ * same client cleanup path as a failed run. */
195
+ function resolveRunOptions({ command, dependencies, client, stderr }: {
196
+ command: RefactorCommand
197
+ dependencies: CliDependencies
198
+ client: Client
199
+ stderr: CliOutput['stderr']
200
+ }): RefactorOptions {
201
+ const { cwd, values, harness } = command
202
+ const permissions = harnessPermissions[harness.id]
203
+ return {
204
+ client, cwd, concurrency: command.concurrency, reviewOnly: values['review-only'],
205
+ model: values.model ?? (harness.id === 'codex' ? (dependencies.env ?? process.env).CODEX_MODEL : undefined),
206
+ readPermissionMode: values['read-permission-mode'] ?? permissions?.readPermissionMode,
207
+ editPermissionMode: values['edit-permission-mode'] ?? permissions?.editPermissionMode,
208
+ repographEntry: values.repograph === undefined ? undefined : resolve(dependencies.cwd ?? process.cwd(), values.repograph),
209
+ graphLoader: dependencies.graphLoader, noGraph: values['no-graph'], checks: command.checks,
210
+ include: values.include, exclude: values.exclude,
211
+ // Keep progress on stderr so stdout can be consumed as a single JSON document.
212
+ onProgress: event => stderr(`[refactor] ${event}\n`),
213
+ }
214
+ }
package/src/client.ts ADDED
@@ -0,0 +1,91 @@
1
+ // Selects CLI adapters and their default permission modes.
2
+ import { resolve } from 'node:path'
3
+ import { approveWithNarrowestScope, createClient, type Client } from '@anureo/sdk'
4
+ import { spawnHarnessProcess } from '@anureo/sdk/process'
5
+
6
+ /** Harness IDs accepted by the CLI, in the order shown in help and argument diagnostics. */
7
+ export const refactorHarnesses = ['codex', 'claude', 'hermes', 'pi', 'acp', 'ahp', 'dsh'] as const
8
+ /** An ID from the installed CLI's harness list. */
9
+ export type RefactorHarness = (typeof refactorHarnesses)[number]
10
+
11
+ /** Backend and peer settings passed by the CLI to its client factory after option admission. */
12
+ export interface HarnessSelection {
13
+ id: RefactorHarness
14
+ /** Stdio executable required for ACP and for AHP over stdio. */
15
+ command?: string
16
+ /** Literal peer arguments in command-line order. Requires command. */
17
+ args?: string[]
18
+ /** AHP WebSocket endpoint. Mutually exclusive with stdio settings. */
19
+ url?: string
20
+ }
21
+
22
+ /** Session modes executeRefactor uses when no explicit CLI override is given.
23
+ * An absent entry lets the adapter choose its defaults. */
24
+ export const harnessPermissions: Partial<Record<RefactorHarness, { readPermissionMode: string; editPermissionMode: string }>> = {
25
+ codex: { readPermissionMode: 'read-only', editPermissionMode: 'agent-full-access' },
26
+ claude: { readPermissionMode: 'plan', editPermissionMode: 'acceptEdits' },
27
+ pi: { readPermissionMode: 'read-only', editPermissionMode: 'agent-full-access' },
28
+ }
29
+
30
+ /** Initialize a client for the CLI's validated selection and absolute target directory.
31
+ * Resolves once the SDK client can open sessions. Adapter loading and SDK initialization failures
32
+ * reject. The CLI registers unattended approval using the narrowest advertised allow option.
33
+ * executeRefactor passes failures to runCli and awaits disposal of a returned client. */
34
+ export async function createRefactorClient(cwd: string, selection: HarnessSelection): Promise<Client> {
35
+ const adapter = await createAdapter(cwd, selection)
36
+ return createClient({
37
+ adapter,
38
+ identity: { adapterId: selection.id, runtimeConfigId: 'refactor' },
39
+ interactions: { approval: approveWithNarrowestScope },
40
+ })
41
+ }
42
+
43
+ const javaScriptEntry = /\.[cm]?js$/i
44
+
45
+ /** Load only the selected backend for createRefactorClient. Adapter import or construction
46
+ * failures reject. The SDK initializes the returned adapter and owns its lifecycle from there. */
47
+ async function createAdapter(cwd: string, { id, command, args, url }: HarnessSelection) {
48
+ switch (id) {
49
+ case 'codex': {
50
+ const { createCodexAdapter } = await import('@anureo/adapter-codex')
51
+ const executable = process.env.CODEX_BIN?.trim() || 'codex'
52
+ const script = javaScriptEntry.test(executable) ? resolve(cwd, executable) : undefined
53
+ return createCodexAdapter({
54
+ command: executable, cwd,
55
+ // The adapter uses this for version probes and session launches. Resolve the script
56
+ // against the CLI target so it still works when a session launches in a worktree.
57
+ processFactory: script ? options => spawnHarnessProcess({
58
+ ...options, command: process.execPath, args: [script, ...(options.args ?? [])],
59
+ }) : undefined,
60
+ })
61
+ }
62
+ case 'claude': {
63
+ const { createClaudeAdapter } = await import('@anureo/adapter-claude')
64
+ const executable = process.env.CLAUDE_BIN?.trim() || undefined
65
+ return createClaudeAdapter({
66
+ command: executable, defaultHome: true, env: process.env,
67
+ executableRuntime: executable && javaScriptEntry.test(executable) ? 'bun' : undefined,
68
+ })
69
+ }
70
+ case 'hermes': {
71
+ const { createHermesAdapter } = await import('@anureo/adapter-hermes')
72
+ return createHermesAdapter({ command: process.env.HERMES_BIN?.trim() || undefined })
73
+ }
74
+ case 'pi': {
75
+ const { createPiAdapter } = await import('@anureo/adapter-pi')
76
+ return createPiAdapter()
77
+ }
78
+ case 'acp': {
79
+ const { createAcpAdapter } = await import('@anureo/adapter-acp')
80
+ return createAcpAdapter({ command, args, cwd })
81
+ }
82
+ case 'ahp': {
83
+ const { createAhpAdapter, createWebSocketTransport } = await import('@anureo/adapter-ahp')
84
+ return createAhpAdapter(url ? { url, connect: createWebSocketTransport } : { command, args, cwd })
85
+ }
86
+ case 'dsh': {
87
+ const { createDshAcpAdapter } = await import('@anureo/adapter-acp')
88
+ return createDshAcpAdapter({ command: process.env.DSH_BIN?.trim() || undefined, cwd })
89
+ }
90
+ }
91
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,33 @@
1
+ // Normalizes caught errors for reports and diagnostics.
2
+ import type { Failure } from './results'
3
+
4
+ /** Convert a caught value for display using Error.message or String conversion.
5
+ * Custom accessors or conversions can throw. */
6
+ export function message(cause: unknown): string {
7
+ return cause instanceof Error ? cause.message : String(cause)
8
+ }
9
+
10
+ /** Extract execution and resource-release signals independently from a caught object.
11
+ * executeRun stores the result on the report. markFailed stores it on the first step failure
12
+ * and merges later cleanup signals into that failure. Primitives and functions yield a null code
13
+ * and false flags. Execution uncertainty requires an explicit true. Custom accessors can throw. */
14
+ export function failure(cause: unknown): Failure {
15
+ const error = (cause && typeof cause === 'object' ? cause : {}) as FailureSource
16
+ return {
17
+ code: typeof error.code === 'string' ? error.code : null,
18
+ outcomeUnknown: error.outcomeUnknown === true,
19
+ cleanupFailed: hasCleanupFailure(error),
20
+ }
21
+ }
22
+
23
+ interface FailureSource {
24
+ outcomeUnknown?: unknown
25
+ code?: unknown
26
+ details?: Record<string, unknown>
27
+ }
28
+
29
+ /** Recognize resource-release failures reported by code, explicit flag, or cleanup errors. */
30
+ function hasCleanupFailure(error: FailureSource): boolean {
31
+ return error.code === 'RESOURCE_RELEASE_FAILED' || error.details?.cleanupFailed === true
32
+ || (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
33
+ }
@@ -0,0 +1,47 @@
1
+ // Validates Git-relative paths and defines which paths belong in host snapshots.
2
+ import type { Stats } from 'node:fs'
3
+ import { lstat } from 'node:fs/promises'
4
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
5
+
6
+ /** Resolve a Git-relative slash path under cwd and inspect it one component at a time.
7
+ * A missing component or linked ancestor leaves info null. linkedAncestor distinguishes those
8
+ * cases so fileFingerprint and copyEntry can reject traversal while allowing a final symlink.
9
+ * Invalid paths and stat failures other than ENOENT reject. The result describes the inspection,
10
+ * so callers that read or copy the path afterwards need a stable tree. */
11
+ export async function inspectGitPath(cwd: string, file: string): Promise<{ path: string; info: Stats | null; linkedAncestor: boolean }> {
12
+ const parts = file.split('/')
13
+ const target = resolveGitPath(cwd, file, parts)
14
+ let entry = cwd
15
+ let info: Stats | null = null
16
+ for (const part of parts) {
17
+ entry = resolve(entry, part)
18
+ info = await lstat(entry).catch((cause: NodeJS.ErrnoException) => {
19
+ if (cause.code === 'ENOENT') return null
20
+ throw cause
21
+ })
22
+ if (!info || info.isSymbolicLink()) break
23
+ }
24
+ if (entry === target) return { path: target, info, linkedAncestor: false }
25
+ return { path: target, info: null, linkedAncestor: info?.isSymbolicLink() ?? false }
26
+ }
27
+
28
+ /** Decide whether a Git-relative path belongs in host snapshots, without filesystem access.
29
+ * Run storage must never count as an agent edit, even when force-added; Git metadata is also omitted.
30
+ * Other non-source files remain visible so host diffing can detect edits outside agent scope. */
31
+ export function isSnapshotPath(file: string): boolean {
32
+ return !file.split('/').some(part => ['.anureo', '.git'].includes(part.toLowerCase()))
33
+ }
34
+
35
+ /** Reject noncanonical Git path components before host path resolution, then check containment
36
+ * using the platform's path rules. This lexical check performs no filesystem access. */
37
+ function resolveGitPath(cwd: string, file: string, parts: readonly string[]): string {
38
+ if (isAbsolute(file) || file.includes('\\') || file.includes('\0')
39
+ || (process.platform === 'win32' && file.includes(':'))
40
+ || parts.some(part => !part || part === '.' || part === '..')) throw new Error(`Invalid source path: ${file}`)
41
+ const target = resolve(cwd, file)
42
+ const local = relative(cwd, target)
43
+ if (!local || local === '..' || local.startsWith(`..${sep}`) || isAbsolute(local)) {
44
+ throw new Error(`Source path escapes repository: ${file}`)
45
+ }
46
+ return target
47
+ }