@anureo/refactor 0.0.0-stage → 0.3.0

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 (53) hide show
  1. package/LICENSE +201 -0
  2. package/bin/anureo-refactor.d.ts +2 -0
  3. package/bin/anureo-refactor.js +4 -0
  4. package/package.json +48 -4
  5. package/src/agent-work.d.ts +41 -0
  6. package/src/agent-work.js +131 -0
  7. package/src/checks.d.ts +26 -0
  8. package/src/checks.js +66 -0
  9. package/src/cli.d.ts +27 -0
  10. package/src/cli.js +189 -0
  11. package/src/client.d.ts +26 -0
  12. package/src/client.js +73 -0
  13. package/src/errors.d.ts +9 -0
  14. package/src/errors.js +22 -0
  15. package/src/git-path.d.ts +15 -0
  16. package/src/git-path.js +46 -0
  17. package/src/git-tree.d.ts +18 -0
  18. package/src/git-tree.js +56 -0
  19. package/src/git.d.ts +23 -0
  20. package/src/git.js +40 -0
  21. package/src/graph-artifacts.d.ts +19 -0
  22. package/src/graph-artifacts.js +58 -0
  23. package/src/graph.d.ts +47 -0
  24. package/src/graph.js +71 -0
  25. package/src/index.d.ts +11 -0
  26. package/src/index.js +4 -0
  27. package/src/options.d.ts +55 -0
  28. package/src/options.js +15 -0
  29. package/src/plan-validation.d.ts +10 -0
  30. package/src/plan-validation.js +38 -0
  31. package/src/process.d.ts +9 -0
  32. package/src/process.js +10 -0
  33. package/src/prompts.d.ts +47 -0
  34. package/src/prompts.js +256 -0
  35. package/src/refactor.d.ts +17 -0
  36. package/src/refactor.js +168 -0
  37. package/src/report-store.d.ts +9 -0
  38. package/src/report-store.js +15 -0
  39. package/src/report.d.ts +6 -0
  40. package/src/report.js +52 -0
  41. package/src/results.d.ts +80 -0
  42. package/src/results.js +0 -0
  43. package/src/run-lifecycle.d.ts +18 -0
  44. package/src/run-lifecycle.js +100 -0
  45. package/src/schema.d.ts +42 -0
  46. package/src/schema.js +31 -0
  47. package/src/source-inventory.d.ts +9 -0
  48. package/src/source-inventory.js +17 -0
  49. package/src/source-policy.d.ts +11 -0
  50. package/src/source-policy.js +56 -0
  51. package/src/worktree.d.ts +57 -0
  52. package/src/worktree.js +195 -0
  53. package/README.md +0 -3
package/src/cli.js ADDED
@@ -0,0 +1,189 @@
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
+ }
@@ -0,0 +1,26 @@
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 ADDED
@@ -0,0 +1,73 @@
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
+ }
@@ -0,0 +1,9 @@
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 ADDED
@@ -0,0 +1,22 @@
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
+ }
@@ -0,0 +1,15 @@
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;
@@ -0,0 +1,46 @@
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
+ }
@@ -0,0 +1,18 @@
1
+ /** Read Git-visible modes and contents into a path/fingerprint map for host diffing and provenance.
2
+ * inventory retains the whole tree for provenance before filtering eligible sources; runAgentWork compares
3
+ * whole trees so edits outside source scope remain observable. Launches Git, then reads entries
4
+ * serially in sorted path order without writing. Missing entries at inspection time are skipped.
5
+ * Process, inspection and read failures reject. Run storage and Git metadata are excluded by
6
+ * isSnapshotPath. Callers needing a stable baseline must coordinate writers during capture. */
7
+ export declare function captureTree(cwd: string): Promise<Map<string, string>>;
8
+ /** Fingerprint one Git-relative path or return undefined if it is missing at inspection time.
9
+ * applyWorktreePatch also probes ignored paths directly to detect local files in its way.
10
+ * Linked ancestors, invalid paths and inspection or content read failures reject. */
11
+ export declare function fileFingerprint(cwd: string, file: string): Promise<string | undefined>;
12
+ /** Return sorted added, removed or modified paths between two snapshots.
13
+ * Compares supplied fingerprints without filesystem access or mutation; has no expected errors. */
14
+ export declare function changes(before: ReadonlyMap<string, string>, after: ReadonlyMap<string, string>): string[];
15
+ /** Hash snapshot entries in iteration order for the source version in agent prompts.
16
+ * runDesign and prepareModules use inventory's sorted insertion order, so callers constructing
17
+ * equivalent snapshots must use the same order. Modes are included via fingerprints. */
18
+ export declare function treeVersion(tree: ReadonlyMap<string, string>): string;
@@ -0,0 +1,56 @@
1
+ // Captures and compares Git-visible tree fingerprints for provenance and edit detection.
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile, readlink } from 'node:fs/promises';
4
+ import { inspectGitPath, isSnapshotPath } from "./git-path.js";
5
+ import { gitFiles } from "./git.js";
6
+ /** Read Git-visible modes and contents into a path/fingerprint map for host diffing and provenance.
7
+ * inventory retains the whole tree for provenance before filtering eligible sources; runAgentWork compares
8
+ * whole trees so edits outside source scope remain observable. Launches Git, then reads entries
9
+ * serially in sorted path order without writing. Missing entries at inspection time are skipped.
10
+ * Process, inspection and read failures reject. Run storage and Git metadata are excluded by
11
+ * isSnapshotPath. Callers needing a stable baseline must coordinate writers during capture. */
12
+ export async function captureTree(cwd) {
13
+ const result = new Map();
14
+ for (const file of await gitFiles(cwd)) {
15
+ if (!isSnapshotPath(file))
16
+ continue;
17
+ const fingerprint = await fileFingerprint(cwd, file);
18
+ if (fingerprint !== undefined)
19
+ result.set(file, fingerprint);
20
+ }
21
+ return result;
22
+ }
23
+ /** Fingerprint one Git-relative path or return undefined if it is missing at inspection time.
24
+ * applyWorktreePatch also probes ignored paths directly to detect local files in its way.
25
+ * Linked ancestors, invalid paths and inspection or content read failures reject. */
26
+ export async function fileFingerprint(cwd, file) {
27
+ const { path, info, linkedAncestor } = await inspectGitPath(cwd, file);
28
+ if (linkedAncestor)
29
+ throw new Error(`Symlink ancestors are unsupported: ${file}`);
30
+ if (info)
31
+ return captureFingerprint(path, info);
32
+ }
33
+ /** Return sorted added, removed or modified paths between two snapshots.
34
+ * Compares supplied fingerprints without filesystem access or mutation; has no expected errors. */
35
+ export function changes(before, after) {
36
+ return [...new Set([...before.keys(), ...after.keys()])].filter(file => before.get(file) !== after.get(file)).sort();
37
+ }
38
+ /** Hash snapshot entries in iteration order for the source version in agent prompts.
39
+ * runDesign and prepareModules use inventory's sorted insertion order, so callers constructing
40
+ * equivalent snapshots must use the same order. Modes are included via fingerprints. */
41
+ export function treeVersion(tree) {
42
+ return createHash('sha256').update(JSON.stringify([...tree])).digest('hex');
43
+ }
44
+ /** Read one inspected path's mode/content fingerprint for fileFingerprint.
45
+ * Reads symlink text rather than its destination so broken/external links can be compared safely;
46
+ * non-file entries use their mode as content. Read failures propagate. */
47
+ async function captureFingerprint(path, info) {
48
+ let content;
49
+ if (info.isSymbolicLink())
50
+ content = await readlink(path);
51
+ else if (info.isFile())
52
+ content = await readFile(path);
53
+ else
54
+ content = String(info.mode);
55
+ return createHash('sha256').update(String(info.mode)).update('\0').update(content).digest('hex');
56
+ }
package/src/git.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ /** List sorted, unique tracked and unignored untracked paths under cwd via Git.
2
+ * Snapshot callers supply an in-repository directory; paths are relative to it, including when
3
+ * it is a subdirectory. Launches a read-only Git command; process/buffer failures reject. */
4
+ export declare function gitFiles(cwd: string): Promise<string[]>;
5
+ /** Run Git with cwd as its starting directory and resolve buffered text stdout on success.
6
+ * The command determines filesystem effects. Launch, nonzero exit and buffer failures reject
7
+ * with the child-process error. Repository-local environment overrides from hooks are removed. */
8
+ export declare function git(cwd: string, ...args: string[]): Promise<string>;
9
+ /** Build a fresh environment without inherited repository selectors so Git discovers the caller's
10
+ * checkout. git and diffPatchTrees use the same 64 MiB buffer limit for text and binary output. */
11
+ export declare function gitProcessOptions(): {
12
+ env: {
13
+ [key: string]: string | undefined;
14
+ TZ?: string;
15
+ NODE_ENV?: string;
16
+ };
17
+ maxBuffer: number;
18
+ };
19
+ /** Resolve a preflight target to its real absolute path and require Git's work-tree probe to return true.
20
+ * refactorCode uses the returned path before opening run storage, retaining any subdirectory
21
+ * scope. Filesystem resolution failures propagate. A false probe or process failure rejects
22
+ * with a repository diagnostic. */
23
+ export declare function repositoryDirectory(directory: string): Promise<string>;
package/src/git.js ADDED
@@ -0,0 +1,40 @@
1
+ // Runs Git with checkout-local environment overrides removed.
2
+ import { realpath } from 'node:fs/promises';
3
+ import { resolve } from 'node:path';
4
+ import { exec } from "./process.js";
5
+ /** List sorted, unique tracked and unignored untracked paths under cwd via Git.
6
+ * Snapshot callers supply an in-repository directory; paths are relative to it, including when
7
+ * it is a subdirectory. Launches a read-only Git command; process/buffer failures reject. */
8
+ export async function gitFiles(cwd) {
9
+ const stdout = await git(cwd, 'ls-files', '--cached', '--others', '--exclude-standard', '-z');
10
+ return [...new Set(stdout.split('\0').filter(Boolean))].sort();
11
+ }
12
+ /** Run Git with cwd as its starting directory and resolve buffered text stdout on success.
13
+ * The command determines filesystem effects. Launch, nonzero exit and buffer failures reject
14
+ * with the child-process error. Repository-local environment overrides from hooks are removed. */
15
+ export async function git(cwd, ...args) {
16
+ return (await exec('git', ['-C', cwd, ...args], gitProcessOptions())).stdout;
17
+ }
18
+ /** Build a fresh environment without inherited repository selectors so Git discovers the caller's
19
+ * checkout. git and diffPatchTrees use the same 64 MiB buffer limit for text and binary output. */
20
+ export function gitProcessOptions() {
21
+ const env = { ...process.env };
22
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX',
23
+ 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_IMPLICIT_WORK_TREE',
24
+ 'GIT_GRAFT_FILE', 'GIT_SHALLOW_FILE'])
25
+ delete env[key];
26
+ return { env, maxBuffer: 64 << 20 };
27
+ }
28
+ /** Resolve a preflight target to its real absolute path and require Git's work-tree probe to return true.
29
+ * refactorCode uses the returned path before opening run storage, retaining any subdirectory
30
+ * scope. Filesystem resolution failures propagate. A false probe or process failure rejects
31
+ * with a repository diagnostic. */
32
+ export async function repositoryDirectory(directory) {
33
+ const cwd = await realpath(resolve(directory));
34
+ // Keep the target directory rather than the Git root so subdirectory runs retain their scope.
35
+ const stdout = await git(cwd, 'rev-parse', '--is-inside-work-tree')
36
+ .catch(() => { throw new Error(`Not inside a Git work tree: ${cwd}`); });
37
+ if (stdout.trim() !== 'true')
38
+ throw new Error(`Not inside a Git work tree: ${cwd}`);
39
+ return cwd;
40
+ }
@@ -0,0 +1,19 @@
1
+ import type { RefactorOptions } from "./options.js";
2
+ import type { RefactorReport } from "./results.js";
3
+ /** Internal state shared by runDesign and prepareModules while withRun holds the writer lock. */
4
+ export interface GraphArtifactContext {
5
+ options: Pick<RefactorOptions, 'cwd' | 'noGraph' | 'graphLoader' | 'repographEntry'>;
6
+ report: Pick<RefactorReport, 'directory' | 'graphCoverage'>;
7
+ progress: (event: string) => void;
8
+ /** Cached default-exporter failure. A later phase records its own coverage without retrying. */
9
+ graphError?: string;
10
+ }
11
+ /** Record coverage for the phase's Git-relative source paths and return the written graph path.
12
+ * runDesign calls this before the design agent starts. prepareModules calls it after planning when
13
+ * design changed files, then passes the result to runModules for the module prompts. Disabled or
14
+ * unavailable default exports return null for source inspection. The first default-exporter failure
15
+ * is recorded before progress is reported. Configured exporter failures and artifact serialization
16
+ * or write failures reject and stop the pending agent work. Coverage records export availability
17
+ * before serialization so the report retains coverage even if the artifact cannot be written.
18
+ * Callers supply the existing report directory and serialize writes under the run lock. */
19
+ export declare function exportGraph(context: GraphArtifactContext, phase: string, files: string[]): Promise<string | null>;
@@ -0,0 +1,58 @@
1
+ // Records graph coverage and writes the graph supplied to each refactor phase.
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { isAbsolute, join, relative, sep } from 'node:path';
4
+ import { message } from "./errors.js";
5
+ import { loadGraph } from "./graph.js";
6
+ /** Record coverage for the phase's Git-relative source paths and return the written graph path.
7
+ * runDesign calls this before the design agent starts. prepareModules calls it after planning when
8
+ * design changed files, then passes the result to runModules for the module prompts. Disabled or
9
+ * unavailable default exports return null for source inspection. The first default-exporter failure
10
+ * is recorded before progress is reported. Configured exporter failures and artifact serialization
11
+ * or write failures reject and stop the pending agent work. Coverage records export availability
12
+ * before serialization so the report retains coverage even if the artifact cannot be written.
13
+ * Callers supply the existing report directory and serialize writes under the run lock. */
14
+ export async function exportGraph(context, phase, files) {
15
+ const { options, report, progress } = context;
16
+ if (options.noGraph) {
17
+ report.graphCoverage.push({ phase, status: 'disabled', filesWithoutSymbols: files });
18
+ return null;
19
+ }
20
+ if (context.graphError !== undefined) {
21
+ recordUnavailable(report.graphCoverage, { phase, files, error: context.graphError });
22
+ return null;
23
+ }
24
+ let graph;
25
+ try {
26
+ graph = options.graphLoader ? await options.graphLoader(options.cwd) : await loadGraph(options.cwd, options.repographEntry);
27
+ }
28
+ catch (cause) {
29
+ const error = message(cause);
30
+ recordUnavailable(report.graphCoverage, { phase, files, error });
31
+ if (options.graphLoader || options.repographEntry)
32
+ throw cause;
33
+ context.graphError = error;
34
+ progress(`graph/${phase}: unavailable; continuing with source`);
35
+ return null;
36
+ }
37
+ report.graphCoverage.push({ phase, status: 'available', filesWithoutSymbols: filesWithoutSymbols(graph, options.cwd, files) });
38
+ const file = join(report.directory, `graph-${phase}.json`);
39
+ await writeFile(file, JSON.stringify(graph));
40
+ return file;
41
+ }
42
+ /** Append unavailable coverage for exportGraph using the current phase's inventory, including on
43
+ * later phases that reuse a cached error. */
44
+ function recordUnavailable(coverage, { phase, files, error }) {
45
+ coverage.push({ phase, status: 'unavailable', filesWithoutSymbols: files, error });
46
+ }
47
+ /** Return inventory paths in input order that lack indexed symbols. Container labels alone
48
+ * establish that a path was seen, so exportGraph counts a node only if it has a non-container
49
+ * label. Convert absolute paths to target-relative paths and use slash separators to match Git. */
50
+ function filesWithoutSymbols(graph, cwd, files) {
51
+ const containerLabel = /^(file|folder|directory|package|project|module)$/i;
52
+ const symbols = graph.nodes.filter(node => node.labels.some(label => !containerLabel.test(label)));
53
+ const indexed = new Set(symbols.map(({ filePath }) => {
54
+ const targetPath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath;
55
+ return targetPath.split(sep).join('/');
56
+ }));
57
+ return files.filter(file => !indexed.has(file));
58
+ }