@anureo/refactor 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/bin/anureo-refactor.ts +5 -0
  2. package/package.json +21 -23
  3. package/src/agent-work.ts +184 -0
  4. package/src/checks.ts +82 -0
  5. package/src/cli.ts +214 -0
  6. package/src/client.ts +93 -0
  7. package/src/errors.ts +70 -0
  8. package/src/git-path.ts +47 -0
  9. package/src/git-tree.ts +55 -0
  10. package/src/git.ts +55 -0
  11. package/src/graph-artifacts.ts +73 -0
  12. package/src/graph.ts +145 -0
  13. package/src/index.ts +40 -0
  14. package/src/options.ts +65 -0
  15. package/src/plan-validation.ts +38 -0
  16. package/src/{process.d.ts → process.ts} +4 -2
  17. package/src/{prompts.js → prompts.ts} +145 -67
  18. package/src/refactor.ts +191 -0
  19. package/src/{report-store.js → report-store.ts} +10 -8
  20. package/src/report.ts +60 -0
  21. package/src/results.ts +83 -0
  22. package/src/run-lifecycle.ts +117 -0
  23. package/src/{schema.d.ts → schema.ts} +29 -23
  24. package/src/source-inventory.ts +17 -0
  25. package/src/source-policy.ts +50 -0
  26. package/src/worktree.ts +322 -0
  27. package/tests/agent-contract.test.ts +180 -0
  28. package/tests/cli.test.ts +378 -0
  29. package/tests/fixtures/acp.mjs +38 -0
  30. package/tests/fixtures/ahp.mjs +50 -0
  31. package/tests/fixtures/answer.mjs +15 -0
  32. package/tests/fixtures/codex.mjs +44 -0
  33. package/tests/fixtures/repograph.ts +24 -0
  34. package/tests/graph.integration.test.ts +110 -0
  35. package/tests/helpers.ts +109 -0
  36. package/tests/refactor.test.ts +536 -0
  37. package/tests/run-lifecycle.test.ts +136 -0
  38. package/tests/tree.test.ts +210 -0
  39. package/tsconfig.json +12 -0
  40. package/LICENSE +0 -201
  41. package/bin/anureo-refactor.d.ts +0 -2
  42. package/bin/anureo-refactor.js +0 -4
  43. package/src/agent-work.d.ts +0 -41
  44. package/src/agent-work.js +0 -131
  45. package/src/checks.d.ts +0 -26
  46. package/src/checks.js +0 -66
  47. package/src/cli.d.ts +0 -27
  48. package/src/cli.js +0 -189
  49. package/src/client.d.ts +0 -26
  50. package/src/client.js +0 -73
  51. package/src/errors.d.ts +0 -9
  52. package/src/errors.js +0 -22
  53. package/src/git-path.d.ts +0 -15
  54. package/src/git-path.js +0 -46
  55. package/src/git-tree.d.ts +0 -18
  56. package/src/git-tree.js +0 -56
  57. package/src/git.d.ts +0 -23
  58. package/src/git.js +0 -40
  59. package/src/graph-artifacts.d.ts +0 -19
  60. package/src/graph-artifacts.js +0 -58
  61. package/src/graph.d.ts +0 -47
  62. package/src/graph.js +0 -71
  63. package/src/index.d.ts +0 -11
  64. package/src/index.js +0 -4
  65. package/src/options.d.ts +0 -55
  66. package/src/options.js +0 -15
  67. package/src/plan-validation.d.ts +0 -10
  68. package/src/plan-validation.js +0 -38
  69. package/src/process.js +0 -10
  70. package/src/prompts.d.ts +0 -47
  71. package/src/refactor.d.ts +0 -17
  72. package/src/refactor.js +0 -168
  73. package/src/report-store.d.ts +0 -9
  74. package/src/report.d.ts +0 -6
  75. package/src/report.js +0 -52
  76. package/src/results.d.ts +0 -80
  77. package/src/results.js +0 -0
  78. package/src/run-lifecycle.d.ts +0 -18
  79. package/src/run-lifecycle.js +0 -100
  80. package/src/schema.js +0 -31
  81. package/src/source-inventory.d.ts +0 -9
  82. package/src/source-inventory.js +0 -17
  83. package/src/source-policy.d.ts +0 -11
  84. package/src/source-policy.js +0 -56
  85. package/src/worktree.d.ts +0 -57
  86. package/src/worktree.js +0 -195
@@ -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,6 @@
1
1
  {
2
2
  "name": "@anureo/refactor",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Graph-assisted code refactoring with parallel agents in separate Git worktrees",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -13,38 +13,36 @@
13
13
  },
14
14
  "type": "module",
15
15
  "exports": {
16
- ".": {
17
- "types": "./src/index.d.ts",
18
- "import": "./src/index.js",
19
- "default": "./src/index.js"
20
- }
16
+ ".": "./src/index.ts"
21
17
  },
22
18
  "bin": {
23
- "anureo-refactor": "./bin/anureo-refactor.js"
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"
24
25
  },
25
26
  "dependencies": {
26
- "@anureo/adapter-acp": "0.3.0",
27
- "@anureo/adapter-ahp": "0.3.0",
28
- "@anureo/adapter-claude": "0.3.0",
29
- "@anureo/adapter-codex": "0.3.0",
30
- "@anureo/adapter-hermes": "0.3.0",
31
- "@anureo/adapter-pi": "0.3.0",
32
- "@anureo/sdk": "0.3.0",
33
- "@anureo/workflow": "0.3.0",
27
+ "@anureo/adapter-acp": "0.3.2",
28
+ "@anureo/adapter-ahp": "0.3.2",
29
+ "@anureo/adapter-claude": "0.3.2",
30
+ "@anureo/adapter-codex": "0.3.2",
31
+ "@anureo/adapter-hermes": "0.3.2",
32
+ "@anureo/adapter-pi": "0.3.2",
33
+ "@anureo/sdk": "0.3.2",
34
+ "@anureo/workflow": "0.3.2",
34
35
  "zod": "4.6.7"
35
36
  },
36
37
  "optionalDependencies": {
37
38
  "@youichi/repograph": "0.1.1"
38
39
  },
40
+ "devDependencies": {
41
+ "@anureo/conformance": "0.3.2",
42
+ "@anureo/protocol": "0.3.2"
43
+ },
39
44
  "engines": {
40
45
  "node": ">=22",
41
46
  "bun": ">=1.4.2"
42
- },
43
- "files": [
44
- "src",
45
- "bin",
46
- "schema",
47
- "protocol",
48
- "examples"
49
- ]
47
+ }
50
48
  }
@@ -0,0 +1,184 @@
1
+ // Runs isolated agent sessions and integrates their observed changes.
2
+ import { mkdir } from 'node:fs/promises'
3
+ import { join, sep } from 'node:path'
4
+ import { agent } from '@anureo/workflow'
5
+ import { runChecks, type CheckCommand } from './checks'
6
+ import { failure, message } from './errors'
7
+ import { inspectGitPath } from './git-path'
8
+ import { captureTree, changes, fileFingerprint } from './git-tree'
9
+ import type { RefactorOptions } from './options'
10
+ import type { StepResult } from './results'
11
+ import { workSchema } from './schema'
12
+ import { isSource, isTextSource } from './source-policy'
13
+ import { createAgentWorktree, mergeWorktree, prepareCheckDependencies, removeAgentWorktree, withWorktreeBaseline, type AgentWorktree, type WorktreeBaseline } from './worktree'
14
+
15
+ /** Run one callback in a fresh checkout of the supplied baseline. The callback must await all
16
+ * work that uses the checkout. Removal is awaited before returning its result or propagating its
17
+ * error. If the callback and removal both fail, preserve primary diagnostics and report both
18
+ * errors. The caller owns the baseline. */
19
+ export async function inAgentWorktree<T>(baseline: WorktreeBaseline, use: (worktree: AgentWorktree) => Promise<T>): Promise<T> {
20
+ const worktree = await createAgentWorktree(baseline)
21
+ let result: T
22
+ try {
23
+ result = await use(worktree)
24
+ } catch (primary) {
25
+ try {
26
+ await removeAgentWorktree(baseline, worktree)
27
+ } catch (cleanup) {
28
+ const { code, outcomeUnknown, retryable, issues } = failure(primary)
29
+ throw Object.assign(new AggregateError([primary, cleanup], `${message(primary)}\n${message(cleanup)}`), {
30
+ code, outcomeUnknown, retryable, details: { issues, cleanupErrors: [message(cleanup)] },
31
+ })
32
+ }
33
+ throw primary
34
+ }
35
+ await removeAgentWorktree(baseline, worktree)
36
+ return result
37
+ }
38
+
39
+ /** Run a session, then validate and merge its edits on the caller's writer queue.
40
+ * Cleanup is awaited. Return null when dispatch stops during checkout setup. */
41
+ export async function runAgentWork(input: AgentWorkInput): Promise<StepResult | null> {
42
+ const step: StepResult = { summary: '', changes: [], deferred: [], status: 'unchanged', changedFiles: [], checks: [], error: null, failure: null }
43
+ const recordFailure = (cause: unknown) => {
44
+ markFailed(step, cause)
45
+ if (input.dispatch && (step.failure?.outcomeUnknown || step.failure?.cleanupFailed)) input.dispatch.stopped = true
46
+ }
47
+ try {
48
+ return await inAgentWorktree(input.baseline, async worktree => {
49
+ const before = await captureTree(worktree.root)
50
+ if (input.dispatch?.stopped) return null
51
+ try {
52
+ const { options, prompt } = input
53
+ const work = await agent(prompt, {
54
+ client: options.client, cwd: worktree.cwd, model: options.model,
55
+ permissionMode: options.reviewOnly ? options.readPermissionMode : options.editPermissionMode,
56
+ schema: workSchema, outputFallback: 'json-text',
57
+ })
58
+ if (!work) throw new Error('Agent returned no result')
59
+ Object.assign(step, work)
60
+ } catch (cause) {
61
+ recordFailure(cause)
62
+ }
63
+ const edited = await captureTree(worktree.root)
64
+ await recordAgentEdits(input, worktree, changes(before, edited), before, step)
65
+ if (step.status !== 'failed' && step.changedFiles.length) {
66
+ await input.publish(() => validateAndMerge(input, worktree, step)).catch(recordFailure)
67
+ }
68
+ return step
69
+ })
70
+ } catch (cause) {
71
+ recordFailure(cause)
72
+ return step
73
+ }
74
+ }
75
+
76
+ /** Validate the candidate on the current target snapshot while holding the writer queue. */
77
+ async function validateAndMerge(input: AgentWorkInput, candidate: AgentWorktree, step: StepResult): Promise<void> {
78
+ const { baseline, checks, options } = input
79
+ const apply = async (destination: WorktreeBaseline, source: AgentWorktree) => {
80
+ await mergeWorktree(destination, source, step.changedFiles)
81
+ step.appliedFiles = [...step.changedFiles]
82
+ step.status = 'applied'
83
+ }
84
+ if (!checks.length) return apply(baseline, candidate)
85
+
86
+ await withWorktreeBaseline(options.cwd, fresh => inAgentWorktree(
87
+ { ...fresh, updateWorktreeRegistry: baseline.updateWorktreeRegistry },
88
+ async validation => {
89
+ const target = join(fresh.root, fresh.scope)
90
+ for (const file of step.changedFiles) {
91
+ // Ignored paths can exist in the target even when absent from both snapshots.
92
+ if (await fileFingerprint(target, file) !== await fileFingerprint(validation.cwd, file)) {
93
+ throw new Error(`Source changed during refactor: ${file}`)
94
+ }
95
+ }
96
+ const beforeOverlay = await captureTree(validation.root)
97
+ await mkdir(join(validation.cwd, '.anureo', 'refactor'), { recursive: true })
98
+ await mergeWorktree({ ...baseline, root: validation.root }, candidate, step.changedFiles)
99
+ await prepareCheckDependencies(fresh, validation)
100
+ const beforeChecks = await captureTree(validation.root)
101
+ const checkedFiles = await Promise.all(step.changedFiles.map(file => fileFingerprint(validation.cwd, file)))
102
+ await runChecks(validation.cwd, checks, step.checks)
103
+ const changedByChecks = changes(beforeChecks, await captureTree(validation.root))
104
+ for (const [index, file] of step.changedFiles.entries()) {
105
+ if (await fileFingerprint(validation.cwd, file) !== checkedFiles[index]) {
106
+ changedByChecks.push(fresh.scope ? join(fresh.scope, file).split(sep).join('/') : file)
107
+ }
108
+ }
109
+ if (changedByChecks.length) throw new Error(`Validation modified source files: ${[...new Set(changedByChecks)].sort().join(', ')}`)
110
+ const changedDuringChecks = changes(beforeOverlay, await captureTree(fresh.root))
111
+ if (changedDuringChecks.length) throw new Error(`Source changed during refactor: ${changedDuringChecks.join(', ')}`)
112
+ await apply(fresh, validation)
113
+ },
114
+ ))
115
+ }
116
+
117
+ /** Preserve the first error's classification and append any later cleanup diagnostics. */
118
+ function markFailed(step: StepResult, cause: unknown): void {
119
+ const observed = failure(cause)
120
+ if (step.failure) {
121
+ step.failure.cleanupFailed ||= observed.cleanupFailed
122
+ step.error += `\n${message(cause)}`
123
+ return
124
+ }
125
+ step.status = 'failed'
126
+ step.error = message(cause)
127
+ if (step.appliedFiles?.length) step.error += ` (Files already applied: ${step.appliedFiles.join(', ')})`
128
+ step.failure = observed
129
+ }
130
+
131
+ interface AgentWorkInput {
132
+ baseline: WorktreeBaseline
133
+ options: RefactorOptions
134
+ prompt: string
135
+ checks: readonly CheckCommand[]
136
+ publish: (operation: () => Promise<void>) => Promise<void>
137
+ /** Shared module admission state. Active sessions still settle and record their results. */
138
+ dispatch?: { stopped: boolean }
139
+ /** Editable inventory for design or the validated assignment for a module. */
140
+ assignedFiles: readonly string[]
141
+ }
142
+
143
+ /** Record target-relative edits and reject writes outside the worktree assignment. */
144
+ async function recordAgentEdits(
145
+ { baseline, options, assignedFiles }: AgentWorkInput,
146
+ worktree: AgentWorktree,
147
+ touched: readonly string[],
148
+ before: ReadonlyMap<string, string>,
149
+ step: StepResult,
150
+ ): Promise<void> {
151
+ const scopePrefix = baseline.scope ? baseline.scope.split(sep).join('/') + '/' : ''
152
+ const changedFiles = touched.filter(file => file.startsWith(scopePrefix)).map(file => file.slice(scopePrefix.length))
153
+ step.changedFiles = changedFiles
154
+ if (touched.length !== changedFiles.length) throw new Error('Agent changed paths outside the refactor target')
155
+ if (options.reviewOnly && touched.length) throw new Error('Review-only agent modified files')
156
+ await validateModuleEdits({ assignedFiles, changedFiles, before, scopePrefix, cwd: worktree.cwd, options })
157
+ }
158
+
159
+ /** Allow assigned deletions and edits or additions that qualify as text source. */
160
+ async function validateModuleEdits(input: {
161
+ assignedFiles: readonly string[]
162
+ changedFiles: readonly string[]
163
+ before: ReadonlyMap<string, string>
164
+ scopePrefix: string
165
+ cwd: string
166
+ options: RefactorOptions
167
+ }): Promise<void> {
168
+ const { assignedFiles, changedFiles, before, scopePrefix, cwd, options } = input
169
+ const assigned = new Set(assignedFiles)
170
+ const violations: string[] = []
171
+ const nonText: string[] = []
172
+ for (const file of changedFiles) {
173
+ if (assigned.has(file)) {
174
+ const { info, linkedAncestor } = await inspectGitPath(cwd, file)
175
+ if ((info || linkedAncestor) && !await isTextSource(cwd, file)) nonText.push(file)
176
+ continue
177
+ }
178
+ if (!before.has(scopePrefix + file) && isSource(file, options.include, options.exclude)
179
+ && await isTextSource(cwd, file)) continue
180
+ violations.push(file)
181
+ }
182
+ if (violations.length) throw new Error(`Module edited paths outside its assignment: ${violations.join(', ')}`)
183
+ if (nonText.length) throw new Error(`Assigned files must remain text source: ${nonText.join(', ')}`)
184
+ }
package/src/checks.ts ADDED
@@ -0,0 +1,82 @@
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 { checkoutEnvironment } from './git'
6
+ import { exec } from './process'
7
+ import type { CheckResult } from './results'
8
+
9
+ /** Configure validation in the agent checkout. Strings go to the platform shell. Objects
10
+ * launch the named executable directly with literal arguments, defaulting to no arguments. */
11
+ export type CheckCommand = string | { executable: string; args?: readonly string[] }
12
+
13
+ /** Reject a blank command or executable, or a NUL in a command, executable or literal argument.
14
+ * refactorCode runs this before repository preflight and parseCliInput uses it before client
15
+ * creation. Omitted and empty lists pass this check. Only omission allows script discovery. */
16
+ export function validateChecks(commands: readonly CheckCommand[] | undefined, label = 'check'): void {
17
+ const issues: string[] = []
18
+ let hasBlankCommand = false
19
+ for (const [index, command] of (commands ?? []).entries()) {
20
+ const location = `${label} #${index + 1}`
21
+ const executable = typeof command === 'string' ? command : command.executable
22
+ if (!executable.trim()) {
23
+ hasBlankCommand = true
24
+ issues.push(`${location} is blank`)
25
+ }
26
+ if (executable.includes('\0')) issues.push(`${location} contains NUL`)
27
+ if (typeof command !== 'string') {
28
+ for (const [position, arg] of (command.args ?? []).entries()) {
29
+ if (arg.includes('\0')) issues.push(`${location} argument #${position + 1} contains NUL`)
30
+ }
31
+ }
32
+ }
33
+ if (hasBlankCommand) issues.unshift(`${label} commands must be nonempty`)
34
+ if (issues.length) throw new Error(issues.join('\n'))
35
+ }
36
+
37
+ /** Discover typecheck then test for refactorCode when checks are omitted outside review-only mode.
38
+ * Includes only string-valued scripts in the target package.json. A packageManager declaration
39
+ * starting with bun@, npm@, pnpm@ or yarn@ selects that runner; otherwise uses npm.
40
+ * Reads no parent packages and starts no process.
41
+ * Missing package.json yields no checks; malformed JSON and other filesystem errors reject. */
42
+ export async function defaultChecks(cwd: string): Promise<CheckCommand[]> {
43
+ let pkg: { packageManager?: string; scripts?: Record<string, unknown> }
44
+ try { pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')) }
45
+ catch (cause) {
46
+ if ((cause as NodeJS.ErrnoException).code === 'ENOENT') return []
47
+ throw cause
48
+ }
49
+ const manager = /^(bun|npm|pnpm|yarn)@/.exec(pkg.packageManager ?? '')?.[1] ?? 'npm'
50
+ return ['typecheck', 'test'].filter(name => typeof pkg.scripts?.[name] === 'string').map(name =>
51
+ // Windows package managers other than Bun are commonly provided by .cmd shims.
52
+ process.platform === 'win32' && manager !== 'bun'
53
+ ? `${manager} run ${name}`
54
+ : { executable: manager, args: ['run', name] },
55
+ )
56
+ }
57
+
58
+ /** Execute validation commands serially, appending bounded output to the caller's results array.
59
+ * runAgentWork awaits this before merging and records rejection as a failed step.
60
+ * Commands may modify files or start other processes.
61
+ * Resolves void after all checks; the first failed command is recorded before rejection and stops
62
+ * later commands. Each process has a five-minute timeout and an eight-MiB
63
+ * limit on each output stream. Reports concatenate stdout then stderr, followed by the error
64
+ * message on failure, and retain only the final 4,000 characters. An empty command list resolves
65
+ * without changing results; existing entries are retained. */
66
+ export async function runChecks(cwd: string, commands: readonly CheckCommand[], results: CheckResult[]): Promise<void> {
67
+ const limits = { cwd, env: checkoutEnvironment(), maxBuffer: 8 << 20, timeout: 300_000, killSignal: 'SIGKILL' as const, windowsHide: true }
68
+ for (const command of commands) {
69
+ const display = typeof command === 'string' ? command : [command.executable, ...(command.args ?? [])]
70
+ .map(arg => /^[\w./:-]+$/.test(arg) ? arg : JSON.stringify(arg)).join(' ')
71
+ try {
72
+ const { stdout, stderr } = typeof command === 'string'
73
+ ? await exec(command, [], { ...limits, shell: true })
74
+ : await exec(command.executable, [...command.args ?? []], limits)
75
+ results.push({ command: display, status: 'passed', output: `${stdout}${stderr}`.slice(-4000) })
76
+ } catch (cause) {
77
+ const error = cause as { stdout?: string; stderr?: string }
78
+ results.push({ command: display, status: 'failed', output: `${error.stdout ?? ''}${error.stderr ?? ''}\n${message(cause)}`.slice(-4000) })
79
+ throw new Error(`Validation failed: ${display}`)
80
+ }
81
+ }
82
+ }
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,93 @@
1
+ // Selects CLI adapters and their default permission modes.
2
+ import { basename, 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
+ // Allow the DSH preset's 120-second native initialize request plus subprocess startup.
37
+ return createClient({
38
+ adapter,
39
+ identity: { adapterId: selection.id, runtimeConfigId: 'refactor' },
40
+ interactions: { approval: approveWithNarrowestScope },
41
+ }, selection.id === 'dsh' ? { timeoutMs: 125_000 } : undefined)
42
+ }
43
+
44
+ const javaScriptEntry = /\.[cm]?js$/i
45
+
46
+ /** Load only the selected backend for createRefactorClient. Adapter import or construction
47
+ * failures reject. The SDK initializes the returned adapter and owns its lifecycle from there. */
48
+ async function createAdapter(cwd: string, { id, command, args, url }: HarnessSelection) {
49
+ switch (id) {
50
+ case 'codex': {
51
+ const { createCodexAdapter } = await import('@anureo/adapter-codex')
52
+ const executable = process.env.CODEX_BIN?.trim() || 'codex'
53
+ const script = javaScriptEntry.test(executable) ? resolve(cwd, executable) : undefined
54
+ return createCodexAdapter({
55
+ command: basename(executable) === executable ? executable : resolve(cwd, executable),
56
+ cwd,
57
+ // The adapter uses this for version probes and session launches. Resolve the script
58
+ // against the CLI target so it still works when a session launches in a worktree.
59
+ processFactory: script ? options => spawnHarnessProcess({
60
+ ...options, command: process.execPath, args: [script, ...(options.args ?? [])],
61
+ }) : undefined,
62
+ })
63
+ }
64
+ case 'claude': {
65
+ const { createClaudeAdapter } = await import('@anureo/adapter-claude')
66
+ const executable = process.env.CLAUDE_BIN?.trim() || undefined
67
+ return createClaudeAdapter({
68
+ command: executable, defaultHome: true, env: process.env,
69
+ executableRuntime: executable && javaScriptEntry.test(executable) ? 'bun' : undefined,
70
+ })
71
+ }
72
+ case 'hermes': {
73
+ const { createHermesAdapter } = await import('@anureo/adapter-hermes')
74
+ return createHermesAdapter({ command: process.env.HERMES_BIN?.trim() || undefined })
75
+ }
76
+ case 'pi': {
77
+ const { createPiAdapter } = await import('@anureo/adapter-pi')
78
+ return createPiAdapter()
79
+ }
80
+ case 'acp': {
81
+ const { createAcpAdapter } = await import('@anureo/adapter-acp')
82
+ return createAcpAdapter({ command, args, cwd })
83
+ }
84
+ case 'ahp': {
85
+ const { createAhpAdapter, createWebSocketTransport } = await import('@anureo/adapter-ahp')
86
+ return createAhpAdapter(url ? { url, connect: createWebSocketTransport } : { command, args, cwd })
87
+ }
88
+ case 'dsh': {
89
+ const { createDshAcpAdapter } = await import('@anureo/adapter-acp')
90
+ return createDshAcpAdapter({ command: process.env.DSH_BIN?.trim() || undefined, cwd })
91
+ }
92
+ }
93
+ }