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