@anureo/refactor 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/bin/anureo-refactor.ts +5 -0
  2. package/package.json +21 -23
  3. package/src/agent-work.ts +132 -0
  4. package/src/checks.ts +70 -0
  5. package/src/cli.ts +214 -0
  6. package/src/client.ts +91 -0
  7. package/src/errors.ts +33 -0
  8. package/src/git-path.ts +47 -0
  9. package/src/git-tree.ts +55 -0
  10. package/src/git.ts +42 -0
  11. package/src/graph-artifacts.ts +70 -0
  12. package/src/graph.ts +88 -0
  13. package/src/index.ts +12 -0
  14. package/src/options.ts +65 -0
  15. package/src/plan-validation.ts +39 -0
  16. package/src/{process.d.ts → process.ts} +4 -2
  17. package/src/{prompts.js → prompts.ts} +162 -62
  18. package/src/refactor.ts +186 -0
  19. package/src/{report-store.js → report-store.ts} +9 -7
  20. package/src/report.ts +44 -0
  21. package/src/results.ts +81 -0
  22. package/src/run-lifecycle.ts +117 -0
  23. package/src/{schema.d.ts → schema.ts} +28 -22
  24. package/src/source-inventory.ts +17 -0
  25. package/src/{source-policy.js → source-policy.ts} +31 -37
  26. package/src/worktree.ts +287 -0
  27. package/tests/agent-contract.test.ts +188 -0
  28. package/tests/cli.test.ts +313 -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 +17 -0
  34. package/tests/graph.integration.test.ts +37 -0
  35. package/tests/helpers.ts +105 -0
  36. package/tests/refactor.test.ts +437 -0
  37. package/tests/run-lifecycle.test.ts +82 -0
  38. package/tests/tree.test.ts +99 -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/worktree.d.ts +0 -57
  85. package/src/worktree.js +0 -195
package/src/results.d.ts DELETED
@@ -1,80 +0,0 @@
1
- import type { ModulePlan, RefactorModule, Work } from "./schema.js";
2
- /** Result recorded when the host runs a validation command after integrating a patch. */
3
- export interface CheckResult {
4
- command: string;
5
- status: 'passed' | 'failed';
6
- /** Last 4,000 characters of stdout followed by stderr, with the error message appended on failure. */
7
- output: string;
8
- }
9
- /** Error signals to consult before retrying a failed step or run. */
10
- export interface Failure {
11
- /** String code on the caught object, or null when absent or not a string. */
12
- code: string | null;
13
- /** The error explicitly reports that the execution outcome is unknown. */
14
- outcomeUnknown: boolean;
15
- /** A resource-release error was reported, independently of execution outcome. */
16
- cleanupFailed: boolean;
17
- }
18
- /** Outcome of a design or module step, including host observations from integration and validation.
19
- * The inherited summary, changes and deferred fields are the agent's account of the work. */
20
- export interface StepResult extends Work {
21
- /** Unchanged until a patch is applied, applied after integration succeeds, or failed when an
22
- * error is recorded or integration is blocked. A failed step can still have applied edits. */
23
- status: 'applied' | 'unchanged' | 'failed';
24
- /** Sorted Git-visible paths changed by the isolated agent within the target directory. */
25
- changedFiles: string[];
26
- /** Absolute path to a saved patch, when one was captured. May include changes left unapplied. */
27
- patch?: string;
28
- /** Executed checks in command order; a failure stops subsequent checks. */
29
- checks: CheckResult[];
30
- /** Display text for the caught step error, or null when no error was caught. */
31
- error: string | null;
32
- /** Classification of the first caught step error, with later cleanup failures merged in. */
33
- failure: Failure | null;
34
- }
35
- /** Planned module and its step record, paired in plan order before any module starts. */
36
- export interface ModuleResult {
37
- module: RefactorModule;
38
- /** Null until the worker records its session result. Integration and checks can update it later. */
39
- step: StepResult | null;
40
- }
41
- /** Graph availability and declaration coverage for one phase's source inventory. */
42
- export interface GraphCoverage {
43
- phase: string;
44
- status: 'available' | 'unavailable' | 'disabled';
45
- /** Paths with no indexed declarations, or the entire source inventory when no graph was available.
46
- * Indexed files can still have unresolved relationships. */
47
- filesWithoutSymbols: string[];
48
- /** Export error text when graph data is unavailable. */
49
- error?: string;
50
- }
51
- /** Outcome returned by refactorCode after final publication and writer-lock release. During the
52
- * run, report.json is updated at checkpoints and onProgress receives event strings. An incomplete
53
- * report can include edits already applied to the target. The caller still owns the SDK client. */
54
- export interface RefactorReport {
55
- /** UUID allocated after writer-lock acquisition, also used as the run directory name. */
56
- runId: string;
57
- /** Canonical target directory, which may be a subdirectory of a Git repository. */
58
- cwd: string;
59
- /** Absolute storage directory for this run's reports, graphs and baseline. */
60
- directory: string;
61
- /** Completed means every phase returned successfully; deferred work may still be listed. */
62
- status: 'completed' | 'incomplete';
63
- /** Agents were asked to avoid edits and host validation commands were disabled. */
64
- reviewOnly: boolean;
65
- /** Cross-module design step, run before modules are planned. */
66
- design: StepResult | null;
67
- /** Validated module assignments, or null until planning succeeds. */
68
- plan: ModulePlan | null;
69
- /** Module records in plan order, which can include completed worker results awaiting integration. */
70
- modules: ModuleResult[];
71
- /** Graph availability and file coverage for the exports attempted during the run. */
72
- graphCoverage: GraphCoverage[];
73
- /** Run-level diagnostics. Consult each failed StepResult for its own error. */
74
- errors: string[];
75
- /** Classification of the run-level error, or null when none was caught. A failed-step gate
76
- * throws a new error, so inspect the failed step for its original signals. */
77
- failure: Failure | null;
78
- /** Display text for synchronous observer exceptions that were successfully converted, in delivery order. */
79
- progressErrors: string[];
80
- }
package/src/results.js DELETED
File without changes
@@ -1,18 +0,0 @@
1
- import type { RefactorOptions } from "./options.js";
2
- import type { RefactorReport } from "./results.js";
3
- /** Run the phases supplied by refactorCode under the target's writer lock.
4
- * refactorCode supplies a canonical Git target. Its caller owns the SDK client.
5
- * Directory setup and phase failures usually produce an incomplete report. Synchronous
6
- * observer errors are recorded separately. Error conversion itself can throw.
7
- * Resolves after publishing the final report, closing the lock handle and removing the lock path.
8
- * Acquisition, report initialization, final publication and lock cleanup failures reject.
9
- * Report initialization precedes the cleanup guard, so an initialization failure can leave the lock. */
10
- export declare function withRun(options: RefactorOptions & {
11
- cwd: string;
12
- }, body: RunBody): Promise<RefactorReport>;
13
- /** refactorCode supplies the design, planning and module phases as this callback. executeRun
14
- * invokes it after creating the directory and delivering the run event. The callback can update
15
- * the report, emit progress and publish intermediate checkpoints. Its settlement determines run
16
- * status. withRun owns final publication and lock release. */
17
- type RunBody = (report: RefactorReport, progress: (event: string) => void) => Promise<void>;
18
- export {};
@@ -1,100 +0,0 @@
1
- // Owns run identity, progress delivery and the lifetime of the per-target writer lock.
2
- import { randomUUID } from 'node:crypto';
3
- import { mkdir, open, rm } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
- import { failure, message } from "./errors.js";
6
- import { saveReport } from "./report-store.js";
7
- /** Run the phases supplied by refactorCode under the target's writer lock.
8
- * refactorCode supplies a canonical Git target. Its caller owns the SDK client.
9
- * Directory setup and phase failures usually produce an incomplete report. Synchronous
10
- * observer errors are recorded separately. Error conversion itself can throw.
11
- * Resolves after publishing the final report, closing the lock handle and removing the lock path.
12
- * Acquisition, report initialization, final publication and lock cleanup failures reject.
13
- * Report initialization precedes the cleanup guard, so an initialization failure can leave the lock. */
14
- export async function withRun(options, body) {
15
- const writer = await acquireWriter(options.cwd);
16
- const report = createReport(options, writer.root);
17
- try {
18
- await executeRun(options, report, body);
19
- }
20
- finally {
21
- await finalizeRun(report, writer);
22
- }
23
- return report;
24
- }
25
- /** Create the storage root and acquire exclusive ownership for withRun before allocating a run ID.
26
- * Returns the open lock and its paths, transferring cleanup to withRun. Root creation errors
27
- * propagate. Any open failure rejects with the lock diagnostic and leaves any existing lock alone. */
28
- async function acquireWriter(cwd) {
29
- const root = join(cwd, '.anureo', 'refactor');
30
- await mkdir(root, { recursive: true });
31
- const lockPath = join(root, 'writer.lock');
32
- const lock = await open(lockPath, 'wx').catch(() => {
33
- throw new Error(`Cannot acquire refactor lock: ${lockPath}. Check for an active run before removing a stale lock.`);
34
- });
35
- return { root, lockPath, lock };
36
- }
37
- /** Allocate the initial incomplete record for a locked run without creating its directory.
38
- * withRun calls this after acquisition. UUID generation can throw. */
39
- function createReport(options, root) {
40
- const runId = randomUUID();
41
- return {
42
- runId,
43
- cwd: options.cwd,
44
- directory: join(root, runId),
45
- status: 'incomplete',
46
- reviewOnly: options.reviewOnly ?? false,
47
- design: null,
48
- plan: null,
49
- modules: [],
50
- graphCoverage: [],
51
- errors: [],
52
- failure: null,
53
- progressErrors: [],
54
- };
55
- }
56
- /** Create this run's directory and await orchestration, recording setup/body failures in report.
57
- * Called by withRun while locked; progress precedes body dispatch and completion follows it.
58
- * Ordinary setup/body errors are stored instead of rejecting; error conversion can still throw. */
59
- async function executeRun(options, report, body) {
60
- const progress = createProgressReporter(options, report);
61
- try {
62
- await mkdir(report.directory);
63
- progress(`run: ${report.directory}`);
64
- await body(report, progress);
65
- report.status = 'completed';
66
- }
67
- catch (cause) {
68
- report.errors.push(message(cause));
69
- report.failure = failure(cause);
70
- }
71
- }
72
- /** Give executeRun and its phase callback a synchronous progress function for this report.
73
- * refactorCode supplies the observer through options. Record thrown observer errors so a failed
74
- * display sink does not stop work. Observer return values are ignored. Error conversion can throw. */
75
- function createProgressReporter(options, report) {
76
- return event => {
77
- try {
78
- options.onProgress?.(event);
79
- }
80
- catch (cause) {
81
- report.progressErrors.push(message(cause));
82
- }
83
- };
84
- }
85
- /** Publish the final snapshot, then attempt both lock-release operations for withRun.
86
- * Publication stays under the lock so another writer cannot start before the snapshot attempt.
87
- * Removal errors take precedence over close errors, which take precedence over publication errors. */
88
- async function finalizeRun(report, writer) {
89
- try {
90
- await saveReport(report);
91
- }
92
- finally {
93
- try {
94
- await writer.lock.close();
95
- }
96
- finally {
97
- await rm(writer.lockPath);
98
- }
99
- }
100
- }
package/src/schema.js DELETED
@@ -1,31 +0,0 @@
1
- import { z } from 'zod';
2
- /**
3
- * Describe the required planning response for the workflow agent called by plan in refactor.ts.
4
- * All strings, the module list and each file list must be nonempty. Parsing preserves whitespace
5
- * and rejects unknown fields in the response and its modules. plan passes the parsed response
6
- * to validatePlan for ID safety and exact inventory coverage before prepareModules can publish it.
7
- */
8
- export const modulePlanSchema = z.strictObject({
9
- summary: z.string().min(1),
10
- modules: z.array(z.strictObject({
11
- /** Artifact filename component; syntax and uniqueness are checked separately by validatePlan. */
12
- id: z.string().min(1),
13
- name: z.string().min(1),
14
- description: z.string().min(1),
15
- /** Exact host inventory paths; validatePlan checks membership and exclusive assignment. */
16
- files: z.array(z.string().min(1)).min(1),
17
- })).min(1),
18
- });
19
- /**
20
- * Describe the required design and module responses for the workflow agent called by runAgentWork.
21
- * Parsing preserves whitespace in nonempty strings, accepts empty change and deferral lists, and
22
- * rejects unknown fields in the response and its deferrals. runAgentWork copies valid responses
23
- * into its step result and records a failed step when agent validation rejects.
24
- */
25
- export const workSchema = z.strictObject({
26
- summary: z.string().min(1),
27
- /** Agent-reported edits or proposals, which need not correspond to observed file changes. */
28
- changes: z.array(z.string().min(1)),
29
- /** Unresolved findings with reasons; these do not by themselves make the host step fail. */
30
- deferred: z.array(z.strictObject({ title: z.string().min(1), reason: z.string().min(1) })),
31
- });
@@ -1,9 +0,0 @@
1
- import type { RefactorOptions } from "./options.js";
2
- /** Return the whole host fingerprint map and its eligible text paths in sorted Git order.
3
- * runDesign persists the map and sends the eligible files to design. prepareModules uses a fresh
4
- * inventory after design for planning and plan validation. Snapshot failures, unsafe eligible
5
- * paths and an empty eligible list reject before the corresponding agent is dispatched. */
6
- export declare function inventory({ cwd, include, exclude }: Pick<RefactorOptions, 'cwd' | 'include' | 'exclude'>): Promise<{
7
- tree: Map<string, string>;
8
- files: string[];
9
- }>;
@@ -1,17 +0,0 @@
1
- import { captureTree } from "./git-tree.js";
2
- import { isSource, isTextSource } from "./source-policy.js";
3
- /** Return the whole host fingerprint map and its eligible text paths in sorted Git order.
4
- * runDesign persists the map and sends the eligible files to design. prepareModules uses a fresh
5
- * inventory after design for planning and plan validation. Snapshot failures, unsafe eligible
6
- * paths and an empty eligible list reject before the corresponding agent is dispatched. */
7
- export async function inventory({ cwd, include, exclude }) {
8
- const tree = await captureTree(cwd);
9
- const files = [];
10
- for (const file of tree.keys()) {
11
- if (isSource(file, include, exclude) && await isTextSource(cwd, file))
12
- files.push(file);
13
- }
14
- if (!files.length)
15
- throw new Error('No eligible Git-visible source files found');
16
- return { tree, files };
17
- }
@@ -1,11 +0,0 @@
1
- /** Match a Git-relative path against source scope rules without reading the filesystem.
2
- * Built-in path exclusions and explicit exclude globs take precedence over include globs.
3
- * With no includes, conventional supporting files are skipped. inventory and runAgentWork
4
- * follow a successful match with isTextSource before accepting a source path. */
5
- export declare function isSource(file: string, include?: readonly string[], exclude?: readonly string[]): boolean;
6
- /** Check a Git-relative regular file for UTF-8 or BOM-marked UTF-16 text. inventory skips false
7
- * results, and runAgentWork treats them as assignment violations for new unassigned paths.
8
- * Missing paths, nonfiles, undecodable data and disallowed control characters return false.
9
- * Invalid paths, built-in exclusions, symlinks and filesystem failures other than missing
10
- * entries during inspection reject. Callers apply include and exclude globs through isSource. */
11
- export declare function isTextSource(cwd: string, file: string): Promise<boolean>;
package/src/worktree.d.ts DELETED
@@ -1,57 +0,0 @@
1
- /** Phase-owned snapshot shared by planning, agent checkouts and patch integration. */
2
- export interface WorktreeBaseline {
3
- /** Canonical Git repository root, used for registry updates and patch application. */
4
- root: string;
5
- /** Target directory relative to the root, empty when the target is the root. */
6
- scope: string;
7
- /** Commit used to register detached worktrees, including a synthetic commit for an unborn branch. */
8
- head: string;
9
- /** Scratch directory owned and removed by withWorktreeBaseline. */
10
- directory: string;
11
- /** Root of the copied working files, before applying the target scope. */
12
- source: string;
13
- /** Whether the scratch directory contains a copy of the repository's index. */
14
- hasIndex: boolean;
15
- /** Enqueue a Git registry mutation for this baseline and return its result or rejection.
16
- * A rejected update still releases the next queued update. */
17
- updateWorktreeRegistry: (update: () => Promise<string>) => Promise<string>;
18
- }
19
- /** Linked checkout and scratch paths owned by the caller of createAgentWorktree. */
20
- export interface AgentWorktree {
21
- /** Scoped directory supplied to the agent session. */
22
- cwd: string;
23
- /** Full checkout root used to detect changes outside the scope and unregister the checkout. */
24
- root: string;
25
- /** Scratch parent containing the checkout and any patch staging files. */
26
- directory: string;
27
- }
28
- /** Snapshot the index and Git-visible working files once before invoking a phase callback.
29
- * runDesign uses its snapshot for the design session and integration. refactorCode takes a new
30
- * one for planning, module work and ordered integration. The callback must await all worktree
31
- * use and removal before settling. Capture is sequential and assumes a stable source tree.
32
- * Returns the callback's result after scratch removal. Setup and callback failures reject, and
33
- * a scratch removal failure takes precedence. */
34
- export declare function withWorktreeBaseline<T>(cwd: string, use: (baseline: WorktreeBaseline) => Promise<T>): Promise<T>;
35
- /** Register a detached checkout, restore the frozen index if present and copy the frozen working files.
36
- * Git skips checkout so hooks and filters cannot transform the copied files. inAgentWorktree passes
37
- * the scoped cwd to planning, and runAgentWork fingerprints the full root before starting the agent.
38
- * Both await removeAgentWorktree after use. Setup failures reject after attempting cleanup, and a
39
- * cleanup failure takes precedence. */
40
- export declare function createAgentWorktree(baseline: WorktreeBaseline): Promise<AgentWorktree>;
41
- /** Release a checkout after the session and any patch capture settle. Unregister it through Git
42
- * before deleting its scratch directory. Failures reject with RESOURCE_RELEASE_FAILED and the
43
- * original cause. runAgentWork records the cleanup failure on the step, while inAgentWorktree
44
- * propagates it to planning. */
45
- export declare function removeAgentWorktree(baseline: WorktreeBaseline, worktree: AgentWorktree): Promise<void>;
46
- /** Compare only the supplied scope-relative paths against the frozen baseline and return Git patch bytes.
47
- * For observed edits in edit mode, runAgentWork persists those bytes before removing the checkout,
48
- * even if the agent failed.
49
- * Requires a fresh checkout scratch directory for the before/after trees. Copy/diff failures and
50
- * empty output reject. The caller owns scratch cleanup through removeAgentWorktree. */
51
- export declare function captureWorktreePatch(baseline: WorktreeBaseline, worktree: AgentWorktree, files: readonly string[]): Promise<Buffer>;
52
- /** Apply a saved patch to the scoped working files after checking the supplied paths against the
53
- * baseline, including ignored local paths. The caller must pair the patch with its observed path
54
- * list and coordinate writers through the check and apply. Fingerprint errors, mismatches and
55
- * Git failures reject. integrateAgentWork records failures on the step and only runs checks after
56
- * a successful apply to a successful step. */
57
- export declare function applyWorktreePatch(baseline: WorktreeBaseline, files: readonly string[], patchPath: string): Promise<void>;
package/src/worktree.js DELETED
@@ -1,195 +0,0 @@
1
- // Materializes Git-visible source and transfers edits between independent worktrees.
2
- import { copyFile, cp, mkdir, mkdtemp, readlink, realpath, rm, symlink, writeFile } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import { dirname, join, relative, sep } from 'node:path';
5
- import { inspectGitPath, isSnapshotPath } from "./git-path.js";
6
- import { fileFingerprint } from "./git-tree.js";
7
- import { git, gitFiles, gitProcessOptions } from "./git.js";
8
- import { exec } from "./process.js";
9
- /** Snapshot the index and Git-visible working files once before invoking a phase callback.
10
- * runDesign uses its snapshot for the design session and integration. refactorCode takes a new
11
- * one for planning, module work and ordered integration. The callback must await all worktree
12
- * use and removal before settling. Capture is sequential and assumes a stable source tree.
13
- * Returns the callback's result after scratch removal. Setup and callback failures reject, and
14
- * a scratch removal failure takes precedence. */
15
- export async function withWorktreeBaseline(cwd, use) {
16
- const root = await realpath((await git(cwd, 'rev-parse', '--show-toplevel')).replace(/\r?\n$/, ''));
17
- const scope = relative(root, cwd);
18
- const directory = await temporary('baseline');
19
- try {
20
- const baseline = await snapshotBaseline({ root, scope, directory });
21
- return await use(baseline);
22
- }
23
- finally {
24
- await rm(directory, { recursive: true, force: true });
25
- }
26
- }
27
- /** Register a detached checkout, restore the frozen index if present and copy the frozen working files.
28
- * Git skips checkout so hooks and filters cannot transform the copied files. inAgentWorktree passes
29
- * the scoped cwd to planning, and runAgentWork fingerprints the full root before starting the agent.
30
- * Both await removeAgentWorktree after use. Setup failures reject after attempting cleanup, and a
31
- * cleanup failure takes precedence. */
32
- export async function createAgentWorktree(baseline) {
33
- const directory = await temporary('agent');
34
- const root = join(directory, 'checkout');
35
- const worktree = { cwd: join(root, baseline.scope), root, directory };
36
- try {
37
- await baseline.updateWorktreeRegistry(() => git(baseline.root, '-c', 'core.hooksPath=' + join(directory, 'hooks'), 'worktree', 'add', '--detach', '--no-checkout', root, baseline.head));
38
- }
39
- catch (cause) {
40
- await rm(directory, { recursive: true, force: true });
41
- throw cause;
42
- }
43
- try {
44
- if (baseline.hasIndex) {
45
- const index = await gitIndexPath(root);
46
- await copyFile(join(baseline.directory, 'index'), index);
47
- }
48
- await cp(baseline.source, root, { recursive: true, verbatimSymlinks: true });
49
- return worktree;
50
- }
51
- catch (cause) {
52
- await removeAgentWorktree(baseline, worktree);
53
- throw cause;
54
- }
55
- }
56
- /** Release a checkout after the session and any patch capture settle. Unregister it through Git
57
- * before deleting its scratch directory. Failures reject with RESOURCE_RELEASE_FAILED and the
58
- * original cause. runAgentWork records the cleanup failure on the step, while inAgentWorktree
59
- * propagates it to planning. */
60
- export async function removeAgentWorktree(baseline, worktree) {
61
- try {
62
- await baseline.updateWorktreeRegistry(() => git(baseline.root, 'worktree', 'remove', '--force', worktree.root));
63
- await rm(worktree.directory, { recursive: true, force: true });
64
- }
65
- catch (cause) {
66
- throw Object.assign(new Error(`Could not remove refactor worktree at ${worktree.root}`, { cause }), {
67
- code: 'RESOURCE_RELEASE_FAILED',
68
- });
69
- }
70
- }
71
- /** Compare only the supplied scope-relative paths against the frozen baseline and return Git patch bytes.
72
- * For observed edits in edit mode, runAgentWork persists those bytes before removing the checkout,
73
- * even if the agent failed.
74
- * Requires a fresh checkout scratch directory for the before/after trees. Copy/diff failures and
75
- * empty output reject. The caller owns scratch cleanup through removeAgentWorktree. */
76
- export async function captureWorktreePatch(baseline, worktree, files) {
77
- const before = join(worktree.directory, 'before');
78
- const after = join(worktree.directory, 'after');
79
- const source = join(baseline.source, baseline.scope);
80
- await mkdir(before);
81
- await mkdir(after);
82
- for (const file of files) {
83
- await copyEntry(source, before, file);
84
- await copyEntry(worktree.cwd, after, file);
85
- }
86
- const patch = await diffPatchTrees(worktree.directory);
87
- if (!patch.length)
88
- throw new Error('Git could not represent the observed worktree changes');
89
- return patch;
90
- }
91
- /** Apply a saved patch to the scoped working files after checking the supplied paths against the
92
- * baseline, including ignored local paths. The caller must pair the patch with its observed path
93
- * list and coordinate writers through the check and apply. Fingerprint errors, mismatches and
94
- * Git failures reject. integrateAgentWork records failures on the step and only runs checks after
95
- * a successful apply to a successful step. */
96
- export async function applyWorktreePatch(baseline, files, patchPath) {
97
- const target = join(baseline.root, baseline.scope);
98
- const source = join(baseline.source, baseline.scope);
99
- for (const file of files) {
100
- if (await fileFingerprint(target, file) !== await fileFingerprint(source, file)) {
101
- throw new Error(`Source changed during refactor: ${file}`);
102
- }
103
- }
104
- const scope = baseline.scope ? ['--directory=' + baseline.scope.split(sep).join('/')] : [];
105
- await git(baseline.root, 'apply', '-p2', ...scope, '--whitespace=nowarn', patchPath);
106
- }
107
- /** Allocate a scratch directory under the canonical temporary root. Callers own removal. */
108
- async function temporary(kind) {
109
- return mkdtemp(join(await realpath(tmpdir()), `anureo-refactor-${kind}-`));
110
- }
111
- /** Populate the caller-owned scratch directory before exposing the baseline. Capture the index
112
- * before walking the working files, preserving Git's tracked and unignored untracked view.
113
- * Filesystem and Git failures reject so withWorktreeBaseline can remove partial snapshots. */
114
- async function snapshotBaseline({ root, scope, directory }) {
115
- const source = join(directory, 'source');
116
- await mkdir(join(source, scope), { recursive: true });
117
- const head = await baselineHead(root, directory);
118
- const index = await gitIndexPath(root);
119
- const hasIndex = await copyFile(index, join(directory, 'index')).then(() => true, (error) => {
120
- if (error.code === 'ENOENT')
121
- return false;
122
- throw error;
123
- });
124
- for (const file of await gitFiles(root)) {
125
- if (isSnapshotPath(file))
126
- await copyEntry(root, source, file);
127
- }
128
- return { root, scope, head, directory, source, hasIndex, updateWorktreeRegistry: createRegistryQueue() };
129
- }
130
- /** Resolve the index for the specific checkout, since linked worktrees have their own index paths.
131
- * Git failures reject. */
132
- async function gitIndexPath(cwd) {
133
- return (await git(cwd, 'rev-parse', '--path-format=absolute', '--git-path', 'index')).replace(/\r?\n$/, '');
134
- }
135
- /** Serialize worktree add and remove callbacks within one baseline. Give each caller its own
136
- * outcome while allowing later registry operations to proceed after a rejection. */
137
- function createRegistryQueue() {
138
- let registryReady = Promise.resolve();
139
- return update => {
140
- const result = registryReady.then(update);
141
- registryReady = result.then(() => { }, () => { });
142
- return result;
143
- };
144
- }
145
- /** Resolve HEAD for snapshotBaseline. If Git reports it missing, write an empty tree and a
146
- * synthetic commit to the repository object store so linked checkouts can detach at a commit.
147
- * Ref pointers stay in place. Other Git and filesystem failures reject. */
148
- async function baselineHead(root, directory) {
149
- try {
150
- return (await git(root, 'rev-parse', '--verify', '--quiet', 'HEAD')).trim();
151
- }
152
- catch (cause) {
153
- if (cause.code !== 1)
154
- throw cause;
155
- }
156
- const empty = join(directory, 'empty');
157
- await writeFile(empty, '');
158
- const tree = (await git(root, 'hash-object', '-w', '-t', 'tree', empty)).trim();
159
- return (await git(root, '-c', 'user.name=Anureo', '-c', 'user.email=anureo@localhost', '-c', 'commit.gpgSign=false', 'commit-tree', tree, '-m', 'Empty refactor baseline')).trim();
160
- }
161
- /** Copy a Git path into a caller-owned staging tree, skipping missing entries so deletions stay
162
- * visible. Preserve final symlink text and represent directory entries without recursing into
163
- * submodules. Linked ancestors, unsupported entry types and filesystem failures reject. */
164
- async function copyEntry(from, to, file) {
165
- const { path, info, linkedAncestor } = await inspectGitPath(from, file);
166
- if (linkedAncestor)
167
- throw new Error(`Symlink ancestors are unsupported: ${file}`);
168
- if (!info)
169
- return;
170
- const destination = join(to, file);
171
- await mkdir(dirname(destination), { recursive: true });
172
- if (info.isFile())
173
- await copyFile(path, destination);
174
- else if (info.isSymbolicLink())
175
- await symlink(await readlink(path), destination);
176
- else if (info.isDirectory())
177
- await mkdir(destination, { recursive: true, mode: info.mode });
178
- else
179
- throw new Error(`Unsupported Git path: ${file}`);
180
- }
181
- /** Diff the before/after trees for captureWorktreePatch. Git status 1 denotes a difference and
182
- * returns the buffered patch bytes. Other process failures propagate. */
183
- async function diffPatchTrees(cwd) {
184
- try {
185
- const { stdout } = await exec('git', ['diff', '--no-index', '--no-renames', '--no-ext-diff',
186
- '--no-textconv', '--no-color', '--binary', '--src-prefix=a/', '--dst-prefix=b/', '--', 'before', 'after'], { ...gitProcessOptions(), cwd, encoding: 'buffer' });
187
- return stdout;
188
- }
189
- catch (cause) {
190
- const error = cause;
191
- if (error.code === 1 && Buffer.isBuffer(error.stdout))
192
- return error.stdout;
193
- throw cause;
194
- }
195
- }