@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/graph.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import { z } from 'zod';
2
- /** Shape of a Repograph `--kind all` export. Node and edge properties can carry exporter metadata
3
- * such as symbol metrics, call lines and imported names. startLine and endLine allow null for
4
- * nodes without a source range. loadGraph validates repository identity, node IDs and endpoints
5
- * in addition to parsing this shape. */
6
- export type RepositoryGraph = z.infer<typeof graphSchema>;
7
- /** Supply a validated graph for the canonical, absolute target directory as RefactorOptions.graphLoader.
8
- * exportGraph awaits the callback under the run lock and writes its result to the phase artifact.
9
- * A rejection blocks the pending design or module work and is recorded as an incomplete run.
10
- * Implementations own validation and any processes, indexes or temporary resources they use.
11
- * Finish temporary cleanup before the returned promise settles. */
12
- export type GraphLoader = (cwd: string) => Promise<RepositoryGraph>;
13
- /** Resolve the optional Repograph package's CLI entry for loadGraph's default and live tests.
14
- * Throws if the package cannot be resolved. Deferring resolution allows source-only runs. */
15
- export declare function resolveRepographEntry(): string;
16
- /** Export a validated graph for an absolute target directory. Supply an absolute CLI entry to
17
- * override the installed Repograph package. Both paths go unchanged to a subprocess started in
18
- * an OS temporary directory. The promise settles after temporary-directory cleanup, retaining the
19
- * external index for reuse. Serialize calls that share that index, whose key derives from the
20
- * supplied target path. exportGraph does this under the run lock before writing the phase artifact.
21
- * Package resolution, subprocess, filesystem, parse and validation errors reject. A cleanup
22
- * failure takes precedence over an earlier error. */
23
- export declare function loadGraph(cwd: string, entry?: string): Promise<RepositoryGraph>;
24
- /** Validate the core export fields and retain language-specific node metadata. */
25
- declare const graphSchema: z.ZodObject<{
26
- schemaVersion: z.ZodLiteral<1>;
27
- repositoryPath: z.ZodString;
28
- kind: z.ZodLiteral<"all">;
29
- indexReport: z.ZodRecord<z.ZodString, z.ZodUnknown>;
30
- nodes: z.ZodArray<z.ZodObject<{
31
- id: z.ZodString;
32
- name: z.ZodString;
33
- filePath: z.ZodString;
34
- labels: z.ZodArray<z.ZodString>;
35
- startLine: z.ZodNullable<z.ZodNumber>;
36
- endLine: z.ZodNullable<z.ZodNumber>;
37
- properties: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
38
- }, z.core.$loose>>;
39
- edges: z.ZodArray<z.ZodObject<{
40
- id: z.ZodString;
41
- source: z.ZodString;
42
- target: z.ZodString;
43
- type: z.ZodString;
44
- properties: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
45
- }, z.core.$strip>>;
46
- }, z.core.$strip>;
47
- export {};
package/src/graph.js DELETED
@@ -1,71 +0,0 @@
1
- // Owns repograph CLI exports, graph validation and temporary export cleanup.
2
- import { mkdtemp, readFile, rm, realpath } from 'node:fs/promises';
3
- import { tmpdir } from 'node:os';
4
- import { dirname, join } from 'node:path';
5
- import { createRequire } from 'node:module';
6
- import { createHash } from 'node:crypto';
7
- import { z } from 'zod';
8
- import { exec } from "./process.js";
9
- /** Resolve the optional Repograph package's CLI entry for loadGraph's default and live tests.
10
- * Throws if the package cannot be resolved. Deferring resolution allows source-only runs. */
11
- export function resolveRepographEntry() {
12
- return join(dirname(createRequire(import.meta.url).resolve('@youichi/repograph')), 'cli.js');
13
- }
14
- /** Export a validated graph for an absolute target directory. Supply an absolute CLI entry to
15
- * override the installed Repograph package. Both paths go unchanged to a subprocess started in
16
- * an OS temporary directory. The promise settles after temporary-directory cleanup, retaining the
17
- * external index for reuse. Serialize calls that share that index, whose key derives from the
18
- * supplied target path. exportGraph does this under the run lock before writing the phase artifact.
19
- * Package resolution, subprocess, filesystem, parse and validation errors reject. A cleanup
20
- * failure takes precedence over an earlier error. */
21
- export async function loadGraph(cwd, entry = resolveRepographEntry()) {
22
- const temporary = await mkdtemp(join(tmpdir(), 'anureo-refactor-graph-'));
23
- try {
24
- const graph = await exportRepositoryGraph({ cwd, entry, temporary });
25
- await validateRepositoryGraph(graph, cwd);
26
- return graph;
27
- }
28
- finally {
29
- await rm(temporary, { recursive: true, force: true });
30
- }
31
- }
32
- /** Validate the core export fields and retain language-specific node metadata. */
33
- const graphSchema = z.object({
34
- schemaVersion: z.literal(1), repositoryPath: z.string(), kind: z.literal('all'),
35
- indexReport: z.record(z.string(), z.unknown()),
36
- nodes: z.array(z.looseObject({
37
- id: z.string(), name: z.string(), filePath: z.string(), labels: z.array(z.string()),
38
- startLine: z.number().nullable(), endLine: z.number().nullable(),
39
- // Upstream metrics (lines, complexity, cognitive, param_count, is_test...). Agents read them
40
- // from the artifact to find large or tightly connected functions; do not drop them.
41
- properties: z.record(z.string(), z.unknown()).optional(),
42
- })),
43
- edges: z.array(z.object({
44
- id: z.string(), source: z.string(), target: z.string(), type: z.string(),
45
- // CALLS: call line. IMPORTS: imported name (local_name). Both are used to locate evidence.
46
- properties: z.record(z.string(), z.unknown()).optional(),
47
- })),
48
- });
49
- /** Return the parsed CLI payload for loadGraph to validate. Await the subprocess before reading
50
- * graph.json from loadGraph's temporary directory. The subprocess has a five-minute timeout and
51
- * an 8 MiB output buffer limit. Process, filesystem, JSON and schema errors reject to loadGraph,
52
- * which removes the directory in either case. */
53
- async function exportRepositoryGraph(input) {
54
- const { cwd, entry, temporary } = input;
55
- const output = join(temporary, 'graph.json');
56
- // Keep the supplied path as the index key so repeated exports reuse the same project.
57
- const project = `anureo-refactor-${createHash('sha256').update(cwd).digest('hex').slice(0, 16)}`;
58
- await exec(process.execPath, [entry, 'export', cwd, '--kind', 'all', '--project', project, '--out', output], { cwd: temporary, maxBuffer: 8 << 20, timeout: 300_000 });
59
- return graphSchema.parse(JSON.parse(await readFile(output, 'utf8')));
60
- }
61
- /** Require a parsed graph to describe the same real directory and have unique node IDs and valid
62
- * edge references. loadGraph awaits this read-only check before returning the graph. Filesystem,
63
- * repository identity and graph integrity failures reject through loadGraph's cleanup. */
64
- async function validateRepositoryGraph(graph, cwd) {
65
- if (await realpath(graph.repositoryPath) !== await realpath(cwd))
66
- throw new Error('repograph returned a different repository');
67
- const ids = new Set(graph.nodes.map(node => node.id));
68
- if (ids.size !== graph.nodes.length || graph.edges.some(edge => !ids.has(edge.source) || !ids.has(edge.target))) {
69
- throw new Error('repograph returned duplicate nodes or missing edge endpoints');
70
- }
71
- }
package/src/index.d.ts DELETED
@@ -1,11 +0,0 @@
1
- export { refactorCode } from "./refactor.js";
2
- export type { RefactorOptions } from "./options.js";
3
- export type { CheckCommand } from "./checks.js";
4
- /** Host observations returned to callers, including partial edits and ordered validation outcomes. */
5
- export type { RefactorReport, GraphCoverage, ModuleResult, StepResult, CheckResult, Failure } from "./results.js";
6
- /** Agent response shapes; work summaries, changes and deferrals are agent claims, distinct from
7
- * host-observed step results. Types alone do not validate external output or module assignments. */
8
- export type { ModulePlan, RefactorModule, Work } from "./schema.js";
9
- export { formatReport } from "./report.js";
10
- export { loadGraph } from "./graph.js";
11
- export type { RepositoryGraph, GraphLoader } from "./graph.js";
package/src/index.js DELETED
@@ -1,4 +0,0 @@
1
- // Library entry point for running refactors, presenting reports and supplying repository graphs.
2
- export { refactorCode } from "./refactor.js";
3
- export { formatReport } from "./report.js";
4
- export { loadGraph } from "./graph.js";
package/src/options.d.ts DELETED
@@ -1,55 +0,0 @@
1
- import type { Client } from '@anureo/sdk';
2
- import type { CheckCommand } from "./checks.js";
3
- import type { GraphLoader } from "./graph.js";
4
- /** Configure a refactorCode run. Keep the supplied client usable until the call settles and await
5
- * its disposal separately. Invalid concurrency, checks or graph combinations reject before run setup. */
6
- export interface RefactorOptions {
7
- /** Initialized SDK client used for all agent sessions. */
8
- client: Client;
9
- /** Target directory inside a Git work tree, relative to process.cwd() or absolute. Canonicalized
10
- * before run storage or agents start; a subdirectory target retains its own scope. */
11
- cwd: string;
12
- /** Agent model override for all phases. Omit to use the supplied client's backend default. */
13
- model?: string;
14
- /** Maximum module tasks active at once, as a positive safe integer. Omit to run all concurrently. */
15
- concurrency?: number;
16
- /** Ask agents to avoid edits and skip patch integration and host checks. Backend enforcement
17
- * depends on readPermissionMode. The host fails steps that modify their review worktree. */
18
- reviewOnly?: boolean;
19
- /** Backend-specific permission mode for planning and review-only sessions. Omit for the backend default. */
20
- readPermissionMode?: string;
21
- /** Backend-specific permission mode for design/module edits. Omit for the backend default. */
22
- editPermissionMode?: string;
23
- /** Skip graph export and inspect source directly. Defaults to false. An explicit graph loader
24
- * or nonempty repograph entry is incompatible with true. */
25
- noGraph?: boolean;
26
- /** Override the installed @youichi/repograph CLI. Supply an absolute JS/TS entry path because the
27
- * exporter starts in a temporary directory. Omit the field to use the installed exporter.
28
- * When graphLoader is supplied, it takes precedence. */
29
- repographEntry?: string;
30
- /** Export a validated graph for the canonical target under the run lock, bypassing the default
31
- * subprocess and repographEntry. A rejection is recorded as a run failure. The loader owns
32
- * temporary resources and must clean them up before settling. */
33
- graphLoader?: GraphLoader;
34
- /** Commands run serially in the target after successful patch integration. The first failure
35
- * stops later checks. An empty list disables checks. Omission discovers typecheck then test in
36
- * the target's own package.json. Blank executables or NUL bytes reject before the run, including
37
- * in reviewOnly mode, which skips execution. */
38
- checks?: readonly CheckCommand[];
39
- /** Target-relative slash globs selecting eligible Git-visible text. Omission or an empty list
40
- * uses default discovery across languages and skips common metadata and prose. */
41
- include?: readonly string[];
42
- /** Target-relative slash globs excluded from the editable scope, including explicit includes. */
43
- exclude?: readonly string[];
44
- /** Synchronous progress observer; thrown errors are recorded in report.progressErrors without
45
- * stopping the run. Returned promises are not awaited. */
46
- onProgress?: (message: string) => void;
47
- }
48
- /** Accept an omitted limit or a positive safe integer. Throw synchronously with the caller's
49
- * label otherwise. CLI admission checks this before creating a client and refactorCode checks
50
- * it before opening a run. */
51
- export declare function validateConcurrency(value: number | undefined, label?: string): void;
52
- /** Throw synchronously if graph export is disabled and the caller detected an explicit exporter.
53
- * The CLI treats presence of --repograph as explicit even when its argument is empty. refactorCode
54
- * tests the supplied entry or loader for truthiness. Both check before starting their run. */
55
- export declare function validateGraphOptions(noGraph: boolean | undefined, hasExporter: boolean, label?: string): void;
package/src/options.js DELETED
@@ -1,15 +0,0 @@
1
- /** Accept an omitted limit or a positive safe integer. Throw synchronously with the caller's
2
- * label otherwise. CLI admission checks this before creating a client and refactorCode checks
3
- * it before opening a run. */
4
- export function validateConcurrency(value, label = 'concurrency') {
5
- if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
6
- throw new Error(`${label} must be a positive integer`);
7
- }
8
- }
9
- /** Throw synchronously if graph export is disabled and the caller detected an explicit exporter.
10
- * The CLI treats presence of --repograph as explicit even when its argument is empty. refactorCode
11
- * tests the supplied entry or loader for truthiness. Both check before starting their run. */
12
- export function validateGraphOptions(noGraph, hasExporter, label = 'noGraph') {
13
- if (noGraph && hasExporter)
14
- throw new Error(`${label} cannot be combined with a graph exporter`);
15
- }
@@ -1,10 +0,0 @@
1
- import type { ModulePlan } from "./schema.js";
2
- /**
3
- * Require case-insensitively unique, filename-safe module IDs and one assignment per inventory path.
4
- * After the planning worktree is released, plan in refactor.ts supplies the schema-validated
5
- * response and the inventory it sent to the agent. A thrown Error leaves the plan unpublished
6
- * and stops module dispatch. The run lifecycle records that error in the incomplete report.
7
- * Compare paths literally. Check each module's ID before its files, and throw on the first invalid
8
- * ID or assignment. Report omissions in inventory order after checking all assignments.
9
- */
10
- export declare function validatePlan(plan: ModulePlan, files: readonly string[]): void;
@@ -1,38 +0,0 @@
1
- /**
2
- * Require case-insensitively unique, filename-safe module IDs and one assignment per inventory path.
3
- * After the planning worktree is released, plan in refactor.ts supplies the schema-validated
4
- * response and the inventory it sent to the agent. A thrown Error leaves the plan unpublished
5
- * and stops module dispatch. The run lifecycle records that error in the incomplete report.
6
- * Compare paths literally. Check each module's ID before its files, and throw on the first invalid
7
- * ID or assignment. Report omissions in inventory order after checking all assignments.
8
- */
9
- export function validatePlan(plan, files) {
10
- const expectedFiles = new Set(files);
11
- const assignedFiles = new Set();
12
- const claimedIds = new Set();
13
- for (const module of plan.modules) {
14
- claimModuleId(module.id, claimedIds);
15
- for (const file of module.files) {
16
- if (!expectedFiles.has(file) || assignedFiles.has(file)) {
17
- throw new Error(`Unlisted or duplicate module file: ${file}`);
18
- }
19
- assignedFiles.add(file);
20
- }
21
- }
22
- const missing = files.filter(file => !assignedFiles.has(file));
23
- if (missing.length)
24
- throw new Error(`Module plan omitted source files: ${missing.join(', ')}`);
25
- }
26
- /**
27
- * Reserve an ID in validatePlan's set of lowercase keys. IDs are 1–80 ASCII characters
28
- * and start with a letter or digit. Later characters can also be underscores or hyphens.
29
- * Throw on an unsafe or repeated ID so runModules can use the original spelling in patch names
30
- * without collisions on case-insensitive filesystems.
31
- */
32
- function claimModuleId(id, claimedIds) {
33
- const key = id.toLowerCase();
34
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(id) || claimedIds.has(key)) {
35
- throw new Error(`Invalid or duplicate module id: ${id}`);
36
- }
37
- claimedIds.add(key);
38
- }
package/src/process.js DELETED
@@ -1,10 +0,0 @@
1
- import { execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
- /** Await a child executable's completion and resolve buffered stdout/stderr using Node's execFile contract.
4
- * runChecks records process failures before rejecting; exportRepositoryGraph propagates them through
5
- * loadGraph's awaited temporary-file cleanup. Callers supply cwd, timeouts, buffer limits and
6
- * cancellation as needed; omitted options retain Node's defaults. Adds no retries or error translation.
7
- * The executable owns its effects; launch, nonzero exit, timeout, buffer and cancellation failures reject
8
- * with Node's process errors and captured output. Shell interpretation requires an explicit shell
9
- * option or executable. */
10
- export const exec = promisify(execFile);
package/src/prompts.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import type { CheckCommand } from "./checks.js";
2
- import type { RefactorModule } from "./schema.js";
3
- /** Context runDesign supplies before the planner partitions the inventory. */
4
- export interface DesignPromptInput extends PromptContext {
5
- /** Complete eligible source inventory at the design snapshot. */
6
- files: string[];
7
- }
8
- /** Context runModules supplies after design and plan validation. */
9
- export interface ModulePromptInput extends PromptContext {
10
- /** Assignment already checked against the host inventory by validatePlan. */
11
- module: RefactorModule;
12
- /** Completed design step's summary, included so the module agent can preserve boundary decisions. */
13
- design: string;
14
- }
15
- /** Build read-only partition instructions for the post-design snapshot. plan in refactor.ts submits
16
- * the text to a schema-backed agent in a separate worktree.
17
- * The caller must validate its response against the same inventory before dispatching module work.
18
- * Construction only serializes the supplied inventory; serialization errors throw synchronously. */
19
- export declare function planPrompt(files: string[], version: string): string;
20
- /** Build cross-file design instructions for runDesign to pass to runAgentWork before planning.
21
- * Supply the snapshot inventory and its graph path, or null to request direct source inspection.
22
- * runAgentWork configures session permissions separately. JSON serialization errors throw synchronously. */
23
- export declare function designPrompt(input: DesignPromptInput): string;
24
- /** Build the same design instructions from positional arguments. Passing true for readOnly requests
25
- * read-only instructions. JSON serialization errors throw synchronously. */
26
- export declare function designPrompt(files: string[], graphFile: string, version: string, checks: readonly CheckCommand[], readOnly: boolean): string;
27
- /** Build instructions for runModules to pass to runAgentWork for one validated assignment.
28
- * Supply the module snapshot, its graph path or null, and the completed design summary.
29
- * runAgentWork configures session permissions separately. JSON serialization errors throw synchronously. */
30
- export declare function modulePrompt(input: ModulePromptInput): string;
31
- /** Build the same module instructions from positional arguments. Passing true for readOnly requests
32
- * read-only instructions. JSON serialization errors throw synchronously. */
33
- export declare function modulePrompt(module: RefactorModule, graphFile: string, version: string, checks: readonly CheckCommand[], readOnly: boolean, design: string): string;
34
- /** Host-supplied execution context for pure design/module prompt construction; no artifacts are opened. */
35
- interface PromptContext {
36
- /** Host-exported graph for this snapshot, or null to use direct source inspection. */
37
- graphFile: string | null;
38
- /** Snapshot identifier used to tie instructions to the current source tree. */
39
- version: string;
40
- /** Commands to include in edit instructions. An empty list omits the validation section. */
41
- checks: readonly CheckCommand[];
42
- /** Instruction mode. The caller configures the agent session's permissions. */
43
- mode: 'read-only' | 'edit';
44
- /** True tells module agents to edit only assigned existing files and leaves edit checks to the host. */
45
- isolated?: boolean;
46
- }
47
- export {};
package/src/refactor.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { type RefactorOptions } from "./options.js";
2
- import type { RefactorReport } from "./results.js";
3
- /** Run configuration, including the client the caller keeps and disposes. */
4
- export type { RefactorOptions } from "./options.js";
5
- /** Overall run report and the step, validation and failure records it contains. */
6
- export type { RefactorReport, ModuleResult, StepResult, CheckResult, Failure } from "./results.js";
7
- /** Refactor a Git target by running design, planning the resulting tree, and editing modules in
8
- * concurrent detached worktrees. The host integrates module patches in plan order and runs checks
9
- * against the target after successful patch application. A failed design can leave a partial edit
10
- * in the target, and a failed check leaves the applied patch in place. Review-only runs produce no
11
- * integration or host checks.
12
- *
13
- * Returns a completed or incomplete report after final publication and writer-lock release. Phase
14
- * failures stop advancement and are recorded in the report. Invalid input, repository preflight,
15
- * lock acquisition, report initialization, final publication and lock cleanup failures reject.
16
- * Keep the supplied client usable until settlement and dispose it separately. */
17
- export declare function refactorCode(input: RefactorOptions): Promise<RefactorReport>;
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
- }