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