@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/refactor.js DELETED
@@ -1,168 +0,0 @@
1
- // Sequences design, planning, concurrent module work and integration under the run lock.
2
- import { writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { agent } from '@anureo/workflow';
5
- import { inAgentWorktree, integrateAgentWork, markFailed, runAgentWork } from "./agent-work.js";
6
- import { defaultChecks, validateChecks } from "./checks.js";
7
- import { repositoryDirectory } from "./git.js";
8
- import { treeVersion } from "./git-tree.js";
9
- import { exportGraph } from "./graph-artifacts.js";
10
- import { validateConcurrency, validateGraphOptions } from "./options.js";
11
- import { validatePlan } from "./plan-validation.js";
12
- import { designPrompt, modulePrompt, planPrompt } from "./prompts.js";
13
- import { saveReport } from "./report-store.js";
14
- import { withRun } from "./run-lifecycle.js";
15
- import { modulePlanSchema } from "./schema.js";
16
- import { inventory } from "./source-inventory.js";
17
- import { withWorktreeBaseline } from "./worktree.js";
18
- /** Refactor a Git target by running design, planning the resulting tree, and editing modules in
19
- * concurrent detached worktrees. The host integrates module patches in plan order and runs checks
20
- * against the target after successful patch application. A failed design can leave a partial edit
21
- * in the target, and a failed check leaves the applied patch in place. Review-only runs produce no
22
- * integration or host checks.
23
- *
24
- * Returns a completed or incomplete report after final publication and writer-lock release. Phase
25
- * failures stop advancement and are recorded in the report. Invalid input, repository preflight,
26
- * lock acquisition, report initialization, final publication and lock cleanup failures reject.
27
- * Keep the supplied client usable until settlement and dispose it separately. */
28
- export async function refactorCode(input) {
29
- validateConcurrency(input.concurrency);
30
- validateChecks(input.checks);
31
- validateGraphOptions(input.noGraph, Boolean(input.repographEntry || input.graphLoader));
32
- const cwd = await repositoryDirectory(input.cwd);
33
- const options = { ...input, cwd };
34
- return withRun(options, async (report, progress) => {
35
- const checks = input.reviewOnly ? [] : input.checks ?? await defaultChecks(cwd);
36
- const context = { options, report, checks, progress };
37
- const design = await runDesign(context);
38
- await withWorktreeBaseline(cwd, async (baseline) => {
39
- const modules = await prepareModules(context, baseline, design);
40
- await runModules(context, baseline, modules);
41
- });
42
- });
43
- }
44
- /** Establish the baseline, run design and checkpoint its outcome before allowing planning.
45
- * refactorCode passes the result to prepareModules. Baseline, graph and report artifacts are
46
- * written under the writer lock. A failed step is published before rejection, and any applied
47
- * edits remain in the target. Inventory, export, baseline and publication errors also reject. */
48
- async function runDesign(context) {
49
- const { options, report, checks, progress } = context;
50
- const initial = await inventory(options);
51
- await writeFile(join(report.directory, 'baseline.json'), JSON.stringify(Object.fromEntries(initial.tree), null, 2));
52
- progress('graph: started');
53
- const graphFile = await exportGraph(context, 'design', initial.files);
54
- progress('design: started');
55
- const design = await withWorktreeBaseline(options.cwd, async (baseline) => {
56
- const step = await runAgentWork({
57
- baseline, options, patchPath: join(report.directory, 'design.patch'),
58
- prompt: designPrompt({
59
- files: initial.files, graphFile, version: treeVersion(initial.tree), checks,
60
- mode: options.reviewOnly ? 'read-only' : 'edit', isolated: true,
61
- }),
62
- });
63
- await integrateAgentWork({ phase: 'design', baseline, cwd: options.cwd, step, checks });
64
- return step;
65
- });
66
- report.design = design;
67
- await checkpointStep(context, 'design', design);
68
- if (design.status === 'failed')
69
- throw new Error(`Cross-module design failed: ${design.error}`);
70
- return { design, graphFile };
71
- }
72
- /** Reinventory after successful design, validate the plan and prepare its baseline graph.
73
- * refactorCode awaits this checkpoint before starting modules. Records the plan before refreshing
74
- * the graph, so a refresh failure can still leave the plan in the final incomplete report.
75
- * Inventory, planning, graph export and publication failures reject. */
76
- async function prepareModules(context, baseline, input) {
77
- const current = await inventory(context.options);
78
- const version = treeVersion(current.tree);
79
- const modulePlan = await plan(context.options, baseline, current.files, version);
80
- context.report.plan = modulePlan;
81
- const graphFile = input.design.changedFiles.length ? await exportGraph(context, 'modules', current.files) : input.graphFile;
82
- await saveReport(context.report);
83
- return { plan: modulePlan, graphFile, design: input.design.summary, version };
84
- }
85
- /** Dispatch modules against one baseline and pass their results to integration only after the
86
- * worker pool settles. Registers plan-ordered result slots in the report before dispatch. Worker
87
- * rejections skip integration, while returned failed steps are handled by integrateModules. */
88
- async function runModules(context, baseline, input) {
89
- const { options, report, checks, progress } = context;
90
- const results = input.plan.modules.map(module => ({ module, step: null }));
91
- report.modules = results;
92
- await runModuleWorkers(results, options.concurrency ?? results.length, async (result) => {
93
- const { module } = result;
94
- progress(`module/${module.id}: started`);
95
- result.step = await runAgentWork({
96
- baseline, options, assignedFiles: module.files, patchPath: join(report.directory, `module-${module.id}.patch`),
97
- prompt: modulePrompt({
98
- module, graphFile: input.graphFile, version: input.version, checks,
99
- mode: options.reviewOnly ? 'read-only' : 'edit', design: input.design, isolated: true,
100
- }),
101
- });
102
- progress(`module/${module.id}: finished`);
103
- });
104
- await integrateModules(context, baseline, results);
105
- }
106
- /** Integrate completed work in plan order. After the first failed step, preserve existing
107
- * failures and mark later patches blocked. Publish every recorded outcome before rejecting for
108
- * the first failed step. A publication failure stops the loop immediately. */
109
- async function integrateModules(context, baseline, results) {
110
- const { options, checks } = context;
111
- let failed;
112
- for (const result of results) {
113
- const { module, step } = result;
114
- if (!step)
115
- continue;
116
- if (!failed)
117
- await integrateAgentWork({ phase: 'module', baseline, cwd: options.cwd, step, checks });
118
- else if (step.patch && step.status !== 'failed') {
119
- markFailed(step, new Error(`Integration blocked by failed module ${failed.module.id}`));
120
- }
121
- if (step.status === 'failed')
122
- failed ??= result;
123
- await checkpointStep(context, `module/${module.id}`, step);
124
- }
125
- if (failed)
126
- throw new Error(`Module ${failed.module.id} failed: ${failed.step?.error}`);
127
- }
128
- /** Emit the status of a step already in the report, then save the report. runDesign and
129
- * integrateModules await publication before enforcing their failure gates. A save failure rejects first. */
130
- async function checkpointStep(context, label, step) {
131
- context.progress(`${label}: ${step.status}`);
132
- await saveReport(context.report);
133
- }
134
- /** Partition the post-design inventory for prepareModules. Supply the read permission mode
135
- * and await checkout removal before checking exact path coverage. A missing result, invalid
136
- * assignment, session failure or checkout failure rejects before the report can record a plan. */
137
- async function plan(options, baseline, files, version) {
138
- const result = await inAgentWorktree(baseline, ({ cwd }) => agent(planPrompt(files, version), {
139
- client: options.client, cwd, model: options.model, permissionMode: options.readPermissionMode,
140
- schema: modulePlanSchema, outputFallback: 'json-text',
141
- }));
142
- if (!result)
143
- throw new Error('Module planning returned no result');
144
- validatePlan(result, files);
145
- return result;
146
- }
147
- /** Claim each result slot once, with at most limit callbacks active. runModules supplies a callback
148
- * that records the step and emits progress. Drain every slot before propagating the earliest
149
- * callback rejection in plan order, so baseline cleanup cannot race a running worker. */
150
- async function runModuleWorkers(results, limit, run) {
151
- let next = 0;
152
- let rejection;
153
- const workers = Array.from({ length: Math.min(limit, results.length) }, async () => {
154
- while (next < results.length) {
155
- const index = next++;
156
- try {
157
- await run(results[index]);
158
- }
159
- catch (cause) {
160
- if (!rejection || index < rejection.index)
161
- rejection = { index, cause };
162
- }
163
- }
164
- });
165
- await Promise.all(workers);
166
- if (rejection)
167
- throw rejection.cause;
168
- }
@@ -1,9 +0,0 @@
1
- import type { RefactorReport } from "./results.js";
2
- /** Publish the current report as newline-terminated JSON and resolve after replacing report.json.
3
- * checkpointStep saves the design outcome before its failure gate, prepareModules saves the plan
4
- * before dispatch, and runModules saves each recorded outcome in integration order. finalizeRun
5
- * awaits the last publication attempt before releasing the lock.
6
- * The caller supplies an existing run directory and serializes writes under the writer lock
7
- * because all saves use the same sibling temporary file. Serialization and filesystem errors
8
- * reject. A failed write or rename may leave a temporary file beside the previous snapshot. */
9
- export declare function saveReport(report: RefactorReport): Promise<void>;
package/src/report.d.ts DELETED
@@ -1,6 +0,0 @@
1
- import type { RefactorReport } from "./results.js";
2
- /** Render a report from refactorCode as newline-terminated text, the format executeRefactor
3
- * prints in CLI text mode. Design appears before module results in plan order. The text includes
4
- * check statuses and observer errors. For check output and raw failure codes, read the report
5
- * fields directly. Formatting a valid report performs no I/O or mutation. */
6
- export declare function formatReport(report: RefactorReport): string;
package/src/report.js DELETED
@@ -1,52 +0,0 @@
1
- import { join } from 'node:path';
2
- /** Render a report from refactorCode as newline-terminated text, the format executeRefactor
3
- * prints in CLI text mode. Design appears before module results in plan order. The text includes
4
- * check statuses and observer errors. For check output and raw failure codes, read the report
5
- * fields directly. Formatting a valid report performs no I/O or mutation. */
6
- export function formatReport(report) {
7
- const lines = [
8
- `Refactor: ${report.status}${report.reviewOnly ? ' (review only)' : ''}`,
9
- `Directory: ${report.cwd}`,
10
- `Report: ${join(report.directory, 'report.json')}`,
11
- ];
12
- if (report.design) {
13
- lines.push('', 'Cross-module design');
14
- appendStep(lines, report.design);
15
- }
16
- for (const graph of report.graphCoverage ?? []) {
17
- const missing = graph.filesWithoutSymbols;
18
- lines.push('', `Graph (${graph.phase}): ${graph.status}${graph.error ? ` — ${graph.error}` : ''}`);
19
- if (missing.length)
20
- lines.push(`Files without indexed symbols: ${missing.join(', ')}`);
21
- }
22
- lines.push('', report.plan?.summary ?? 'Module planning did not complete.');
23
- for (const item of report.modules) {
24
- lines.push('', `${item.module.id}: ${item.module.name}`);
25
- if (item.step)
26
- appendStep(lines, item.step);
27
- }
28
- for (const error of report.errors)
29
- lines.push('', `Error: ${error}`);
30
- for (const error of report.progressErrors)
31
- lines.push('', `Progress reporting error: ${error}`);
32
- return `${lines.join('\n')}\n`;
33
- }
34
- /** Append a design or module result to formatReport's text buffer. Call out execution uncertainty
35
- * explicitly because the error text alone cannot tell a reader whether edits ran. */
36
- function appendStep(lines, step) {
37
- lines.push(`Result: ${step.status}. ${step.error ?? step.summary}`);
38
- if (step.failure?.outcomeUnknown)
39
- lines.push('Agent execution outcome is unknown; inspect source and backend execution before starting another run.');
40
- for (const change of step.changes)
41
- lines.push(`- ${change}`);
42
- if (step.changedFiles.length)
43
- lines.push(`Changed files: ${step.changedFiles.join(', ')}`);
44
- if (step.status === 'failed' && step.patch)
45
- lines.push(`Patch: ${step.patch}`);
46
- for (const item of step.deferred)
47
- lines.push(`Deferred ${item.title}: ${item.reason}`);
48
- for (const check of step.checks)
49
- lines.push(`Check ${check.status}: ${check.command}`);
50
- if (step.status === 'applied' && !step.checks.length)
51
- lines.push('No validation commands ran; runtime behavior was not tested.');
52
- }
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>;
@@ -1,56 +0,0 @@
1
- // Selects the paths and text eligible for review and editing.
2
- import { readFile } from 'node:fs/promises';
3
- import { posix } from 'node:path';
4
- import { inspectGitPath } from "./git-path.js";
5
- /** Match a Git-relative path against source scope rules without reading the filesystem.
6
- * Built-in path exclusions and explicit exclude globs take precedence over include globs.
7
- * With no includes, conventional supporting files are skipped. inventory and runAgentWork
8
- * follow a successful match with isTextSource before accepting a source path. */
9
- export function isSource(file, include = [], exclude = []) {
10
- if (isExcluded(file))
11
- return false;
12
- if (exclude.some(pattern => posix.matchesGlob(file, pattern)))
13
- return false;
14
- if (include.length)
15
- return include.some(pattern => posix.matchesGlob(file, pattern));
16
- return !supportingFile.test(posix.basename(file));
17
- }
18
- /** Check a Git-relative regular file for UTF-8 or BOM-marked UTF-16 text. inventory skips false
19
- * results, and runAgentWork treats them as assignment violations for new unassigned paths.
20
- * Missing paths, nonfiles, undecodable data and disallowed control characters return false.
21
- * Invalid paths, built-in exclusions, symlinks and filesystem failures other than missing
22
- * entries during inspection reject. Callers apply include and exclude globs through isSource. */
23
- export async function isTextSource(cwd, file) {
24
- if (isExcluded(file))
25
- throw new Error(`Invalid source path: ${file}`);
26
- const { path, info, linkedAncestor } = await inspectGitPath(cwd, file);
27
- if (linkedAncestor || info?.isSymbolicLink())
28
- throw new Error(`Symlink source paths are unsupported: ${file}`);
29
- if (!info?.isFile())
30
- return false;
31
- return isSupportedText(await readFile(path));
32
- }
33
- /** Exclude dependency, build, documentation and run artifacts from the editable scope. */
34
- const excluded = new Set(['.git', '.anureo', '.repograph', 'node_modules', 'dist', 'build', 'coverage', 'vendor', 'generated', 'draft', 'docs']);
35
- /** Repository metadata and conventional standalone prose. Explicit includes can select these files. */
36
- const supportingFile = /^(?:\.(?:gitignore|gitattributes|gitmodules|editorconfig)|package(?:-lock)?\.json|(?:bun|yarn|Cargo|uv|poetry)\.lockb?|pnpm-lock\.ya?ml|(?:README|LICENSE|LICENCE|COPYING|NOTICE|CHANGELOG|CONTRIBUTING|AGENTS)(?:\.(?:md|txt|rst|adoc))?)$/i;
37
- /** Match hard exclusions against any path component, regardless of case or glob settings. */
38
- function isExcluded(file) {
39
- return file.split('/').some(part => excluded.has(part.toLowerCase()));
40
- }
41
- /** Default to UTF-8 unless a UTF-16 byte-order mark is present. Decode strictly so invalid
42
- * byte sequences cannot pass through as replacement characters. */
43
- function isSupportedText(content) {
44
- let encoding = 'utf-8';
45
- if (content[0] === 0xff && content[1] === 0xfe)
46
- encoding = 'utf-16le';
47
- if (content[0] === 0xfe && content[1] === 0xff)
48
- encoding = 'utf-16be';
49
- try {
50
- const text = new TextDecoder(encoding, { fatal: true }).decode(content);
51
- return !/[\x00-\x08\x0b\x0e-\x1f]/.test(text);
52
- }
53
- catch {
54
- return false;
55
- }
56
- }
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>;