@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
@@ -0,0 +1,55 @@
1
+ // Captures and compares Git-visible tree fingerprints for provenance and edit detection.
2
+ import { createHash } from 'node:crypto'
3
+ import type { Stats } from 'node:fs'
4
+ import { readFile, readlink } from 'node:fs/promises'
5
+ import { inspectGitPath, isSnapshotPath } from './git-path'
6
+ import { gitFiles } from './git'
7
+
8
+ /** Read Git-visible modes and contents into a path/fingerprint map for host diffing and provenance.
9
+ * inventory retains the whole tree for provenance before filtering eligible sources; runAgentWork compares
10
+ * whole trees so edits outside source scope remain observable. Launches Git, then reads entries
11
+ * serially in sorted path order without writing. Missing entries at inspection time are skipped.
12
+ * Process, inspection and read failures reject. Run storage and Git metadata are excluded by
13
+ * isSnapshotPath. Callers needing a stable baseline must coordinate writers during capture. */
14
+ export async function captureTree(cwd: string): Promise<Map<string, string>> {
15
+ const result = new Map<string, string>()
16
+ for (const file of await gitFiles(cwd)) {
17
+ if (!isSnapshotPath(file)) continue
18
+ const fingerprint = await fileFingerprint(cwd, file)
19
+ if (fingerprint !== undefined) result.set(file, fingerprint)
20
+ }
21
+ return result
22
+ }
23
+
24
+ /** Fingerprint one Git-relative path or return undefined if it is missing at inspection time.
25
+ * mergeWorktree also probes ignored paths directly to detect local files in its way.
26
+ * Linked ancestors, invalid paths and inspection or content read failures reject. */
27
+ export async function fileFingerprint(cwd: string, file: string): Promise<string | undefined> {
28
+ const { path, info, linkedAncestor } = await inspectGitPath(cwd, file)
29
+ if (linkedAncestor) throw new Error(`Symlink ancestors are unsupported: ${file}`)
30
+ if (info) return captureFingerprint(path, info)
31
+ }
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: ReadonlyMap<string, string>, after: ReadonlyMap<string, string>): string[] {
36
+ return [...new Set([...before.keys(), ...after.keys()])].filter(file => before.get(file) !== after.get(file)).sort()
37
+ }
38
+
39
+ /** Hash snapshot entries in iteration order for the source version in agent prompts.
40
+ * runDesign and prepareModules use inventory's sorted insertion order, so callers constructing
41
+ * equivalent snapshots must use the same order. Modes are included via fingerprints. */
42
+ export function treeVersion(tree: ReadonlyMap<string, string>): string {
43
+ return createHash('sha256').update(JSON.stringify([...tree])).digest('hex')
44
+ }
45
+
46
+ /** Read one inspected path's mode/content fingerprint for fileFingerprint.
47
+ * Reads symlink text rather than its destination so broken/external links can be compared safely;
48
+ * non-file entries use their mode as content. Read failures propagate. */
49
+ async function captureFingerprint(path: string, info: Stats): Promise<string> {
50
+ let content: string | Buffer
51
+ if (info.isSymbolicLink()) content = await readlink(path)
52
+ else if (info.isFile()) content = await readFile(path)
53
+ else content = String(info.mode)
54
+ return createHash('sha256').update(String(info.mode)).update('\0').update(content).digest('hex')
55
+ }
package/src/git.ts ADDED
@@ -0,0 +1,42 @@
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'
5
+
6
+ /** List sorted, unique tracked and unignored untracked paths under cwd via Git.
7
+ * Snapshot callers supply an in-repository directory; paths are relative to it, including when
8
+ * it is a subdirectory. Launches a read-only Git command; process/buffer failures reject. */
9
+ export async function gitFiles(cwd: string): Promise<string[]> {
10
+ const stdout = await git(cwd, 'ls-files', '--cached', '--others', '--exclude-standard', '-z')
11
+ return [...new Set(stdout.split('\0').filter(Boolean))].sort()
12
+ }
13
+
14
+ /** Run Git with cwd as its starting directory and resolve buffered text stdout on success.
15
+ * The command determines filesystem effects. Launch, nonzero exit and buffer failures reject
16
+ * with the child-process error. Repository-local environment overrides from hooks are removed. */
17
+ export async function git(cwd: string, ...args: string[]): Promise<string> {
18
+ return (await exec('git', ['-C', cwd, ...args], gitProcessOptions())).stdout
19
+ }
20
+
21
+ /** Build a fresh environment without inherited repository selectors so Git discovers the caller's
22
+ * checkout. git and diffPatchTrees use the same 64 MiB buffer limit for text and binary output. */
23
+ export function gitProcessOptions() {
24
+ const env = { ...process.env }
25
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX',
26
+ 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_IMPLICIT_WORK_TREE',
27
+ 'GIT_GRAFT_FILE', 'GIT_SHALLOW_FILE']) delete env[key]
28
+ return { env, maxBuffer: 64 << 20 }
29
+ }
30
+
31
+ /** Resolve a preflight target to its real absolute path and require Git's work-tree probe to return true.
32
+ * refactorCode uses the returned path before opening run storage, retaining any subdirectory
33
+ * scope. Filesystem resolution failures propagate. A false probe or process failure rejects
34
+ * with a repository diagnostic. */
35
+ export async function repositoryDirectory(directory: string): Promise<string> {
36
+ const cwd = await realpath(resolve(directory))
37
+ // Keep the target directory rather than the Git root so subdirectory runs retain their scope.
38
+ const stdout = await git(cwd, 'rev-parse', '--is-inside-work-tree')
39
+ .catch(() => { throw new Error(`Not inside a Git work tree: ${cwd}`) })
40
+ if (stdout.trim() !== 'true') throw new Error(`Not inside a Git work tree: ${cwd}`)
41
+ return cwd
42
+ }
@@ -0,0 +1,70 @@
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'
5
+ import { loadGraph, type RepositoryGraph } from './graph'
6
+ import type { RefactorOptions } from './options'
7
+ import type { GraphCoverage, RefactorReport } from './results'
8
+
9
+ /** Internal state shared by runDesign and prepareModules while withRun holds the writer lock. */
10
+ export interface GraphArtifactContext {
11
+ options: Pick<RefactorOptions, 'cwd' | 'noGraph' | 'graphLoader' | 'repographEntry'>
12
+ report: Pick<RefactorReport, 'directory' | 'graphCoverage'>
13
+ progress: (event: string) => void
14
+ /** Cached default-exporter failure. A later phase records its own coverage without retrying. */
15
+ graphError?: string
16
+ }
17
+
18
+ /** Record coverage for the phase's Git-relative source paths and return the written graph path.
19
+ * runDesign calls this before the design agent starts. prepareModules calls it after planning when
20
+ * design changed files, then passes the result to runModules for the module prompts. Disabled or
21
+ * unavailable default exports return null for source inspection. The first default-exporter failure
22
+ * is recorded before progress is reported. Configured exporter failures and artifact serialization
23
+ * or write failures reject and stop the pending agent work. Coverage records export availability
24
+ * before serialization so the report retains coverage even if the artifact cannot be written.
25
+ * Callers supply the existing report directory and serialize writes under the run lock. */
26
+ export async function exportGraph(context: GraphArtifactContext, phase: string, files: string[]): Promise<string | null> {
27
+ const { options, report, progress } = context
28
+ if (options.noGraph) {
29
+ report.graphCoverage.push({ phase, status: 'disabled', filesWithoutSymbols: files })
30
+ return null
31
+ }
32
+ if (context.graphError !== undefined) {
33
+ recordUnavailable(report.graphCoverage, { phase, files, error: context.graphError })
34
+ return null
35
+ }
36
+ let graph: RepositoryGraph
37
+ try {
38
+ graph = options.graphLoader ? await options.graphLoader(options.cwd) : await loadGraph(options.cwd, options.repographEntry)
39
+ } catch (cause) {
40
+ const error = message(cause)
41
+ recordUnavailable(report.graphCoverage, { phase, files, error })
42
+ if (options.graphLoader || options.repographEntry) throw cause
43
+ context.graphError = error
44
+ progress(`graph/${phase}: unavailable; continuing with source`)
45
+ return null
46
+ }
47
+ report.graphCoverage.push({ phase, status: 'available', filesWithoutSymbols: filesWithoutSymbols(graph, options.cwd, files) })
48
+ const file = join(report.directory, `graph-${phase}.json`)
49
+ await writeFile(file, JSON.stringify(graph))
50
+ return file
51
+ }
52
+
53
+ /** Append unavailable coverage for exportGraph using the current phase's inventory, including on
54
+ * later phases that reuse a cached error. */
55
+ function recordUnavailable(coverage: GraphCoverage[], { phase, files, error }: { phase: string; files: string[]; error: string }): void {
56
+ coverage.push({ phase, status: 'unavailable', filesWithoutSymbols: files, error })
57
+ }
58
+
59
+ /** Return inventory paths in input order that lack indexed symbols. Container labels alone
60
+ * establish that a path was seen, so exportGraph counts a node only if it has a non-container
61
+ * label. Convert absolute paths to target-relative paths and use slash separators to match Git. */
62
+ function filesWithoutSymbols(graph: RepositoryGraph, cwd: string, files: string[]): string[] {
63
+ const containerLabel = /^(file|folder|directory|package|project|module)$/i
64
+ const symbols = graph.nodes.filter(node => node.labels.some(label => !containerLabel.test(label)))
65
+ const indexed = new Set(symbols.map(({ filePath }) => {
66
+ const targetPath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath
67
+ return targetPath.split(sep).join('/')
68
+ }))
69
+ return files.filter(file => !indexed.has(file))
70
+ }
package/src/graph.ts ADDED
@@ -0,0 +1,88 @@
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'
9
+
10
+ /** Shape of a Repograph `--kind all` export. Node and edge properties can carry exporter metadata
11
+ * such as symbol metrics, call lines and imported names. startLine and endLine allow null for
12
+ * nodes without a source range. loadGraph validates repository identity, node IDs and endpoints
13
+ * in addition to parsing this shape. */
14
+ export type RepositoryGraph = z.infer<typeof graphSchema>
15
+
16
+ /** Supply a validated graph for the canonical, absolute target directory as RefactorOptions.graphLoader.
17
+ * exportGraph awaits the callback under the run lock and writes its result to the phase artifact.
18
+ * A rejection blocks the pending design or module work and is recorded as an incomplete run.
19
+ * Implementations own validation and any processes, indexes or temporary resources they use.
20
+ * Finish temporary cleanup before the returned promise settles. */
21
+ export type GraphLoader = (cwd: string) => Promise<RepositoryGraph>
22
+
23
+ /** Resolve the optional Repograph package's CLI entry for loadGraph's default and live tests.
24
+ * Throws if the package cannot be resolved. Deferring resolution allows source-only runs. */
25
+ export function resolveRepographEntry(): string {
26
+ return join(dirname(createRequire(import.meta.url).resolve('@youichi/repograph')), 'cli.js')
27
+ }
28
+
29
+ /** Export a validated graph for an absolute target directory. Supply an absolute CLI entry to
30
+ * override the installed Repograph package. Both paths go unchanged to a subprocess started in
31
+ * an OS temporary directory. The promise settles after temporary-directory cleanup, retaining the
32
+ * external index for reuse. Serialize calls that share that index, whose key derives from the
33
+ * supplied target path. exportGraph does this under the run lock before writing the phase artifact.
34
+ * Package resolution, subprocess, filesystem, parse and validation errors reject. A cleanup
35
+ * failure takes precedence over an earlier error. */
36
+ export async function loadGraph(cwd: string, entry = resolveRepographEntry()): Promise<RepositoryGraph> {
37
+ const temporary = await mkdtemp(join(tmpdir(), 'anureo-refactor-graph-'))
38
+ try {
39
+ const graph = await exportRepositoryGraph({ cwd, entry, temporary })
40
+ await validateRepositoryGraph(graph, cwd)
41
+ return graph
42
+ } finally {
43
+ await rm(temporary, { recursive: true, force: true })
44
+ }
45
+ }
46
+
47
+ /** Validate the core export fields and retain language-specific node metadata. */
48
+ const graphSchema = z.object({
49
+ schemaVersion: z.literal(1), repositoryPath: z.string(), kind: z.literal('all'),
50
+ indexReport: z.record(z.string(), z.unknown()),
51
+ nodes: z.array(z.looseObject({
52
+ id: z.string(), name: z.string(), filePath: z.string(), labels: z.array(z.string()),
53
+ startLine: z.number().nullable(), endLine: z.number().nullable(),
54
+ // Upstream metrics (lines, complexity, cognitive, param_count, is_test...). Agents read them
55
+ // from the artifact to find large or tightly connected functions; do not drop them.
56
+ properties: z.record(z.string(), z.unknown()).optional(),
57
+ })),
58
+ edges: z.array(z.object({
59
+ id: z.string(), source: z.string(), target: z.string(), type: z.string(),
60
+ // CALLS: call line. IMPORTS: imported name (local_name). Both are used to locate evidence.
61
+ properties: z.record(z.string(), z.unknown()).optional(),
62
+ })),
63
+ })
64
+
65
+ /** Return the parsed CLI payload for loadGraph to validate. Await the subprocess before reading
66
+ * graph.json from loadGraph's temporary directory. The subprocess has a five-minute timeout and
67
+ * an 8 MiB output buffer limit. Process, filesystem, JSON and schema errors reject to loadGraph,
68
+ * which removes the directory in either case. */
69
+ async function exportRepositoryGraph(input: { cwd: string; entry: string; temporary: string }): Promise<RepositoryGraph> {
70
+ const { cwd, entry, temporary } = input
71
+ const output = join(temporary, 'graph.json')
72
+ // Keep the supplied path as the index key so repeated exports reuse the same project.
73
+ const project = `anureo-refactor-${createHash('sha256').update(cwd).digest('hex').slice(0, 16)}`
74
+ await exec(process.execPath, [entry, 'export', cwd, '--kind', 'all', '--project', project, '--out', output],
75
+ { cwd: temporary, maxBuffer: 8 << 20, timeout: 300_000 })
76
+ return graphSchema.parse(JSON.parse(await readFile(output, 'utf8')))
77
+ }
78
+
79
+ /** Require a parsed graph to describe the same real directory and have unique node IDs and valid
80
+ * edge references. loadGraph awaits this read-only check before returning the graph. Filesystem,
81
+ * repository identity and graph integrity failures reject through loadGraph's cleanup. */
82
+ async function validateRepositoryGraph(graph: RepositoryGraph, cwd: string): Promise<void> {
83
+ if (await realpath(graph.repositoryPath) !== await realpath(cwd)) throw new Error('repograph returned a different repository')
84
+ const ids = new Set(graph.nodes.map(node => node.id))
85
+ if (ids.size !== graph.nodes.length || graph.edges.some(edge => !ids.has(edge.source) || !ids.has(edge.target))) {
86
+ throw new Error('repograph returned duplicate nodes or missing edge endpoints')
87
+ }
88
+ }
package/src/index.ts ADDED
@@ -0,0 +1,12 @@
1
+ // Library entry point for running refactors, presenting reports and supplying repository graphs.
2
+ export { refactorCode } from './refactor'
3
+ export type { RefactorOptions } from './options'
4
+ export type { CheckCommand } from './checks'
5
+ /** Host observations returned to callers, including partial edits and ordered validation outcomes. */
6
+ export type { RefactorReport, GraphCoverage, ModuleResult, StepResult, CheckResult, Failure } from './results'
7
+ /** Agent response shapes; work summaries, changes and deferrals are agent claims, distinct from
8
+ * host-observed step results. Types alone do not validate external output or module assignments. */
9
+ export type { ModulePlan, RefactorModule, Work } from './schema'
10
+ export { formatReport } from './report'
11
+ export { loadGraph } from './graph'
12
+ export type { RepositoryGraph, GraphLoader } from './graph'
package/src/options.ts ADDED
@@ -0,0 +1,65 @@
1
+ // Defines caller configuration and preflight shared by refactorCode and the CLI.
2
+ import type { Client } from '@anureo/sdk'
3
+ import type { CheckCommand } from './checks'
4
+ import type { GraphLoader } from './graph'
5
+
6
+ /** Configure a refactorCode run. Keep the supplied client usable until the call settles and await
7
+ * its disposal separately. Invalid concurrency, checks or graph combinations reject before run setup. */
8
+ export interface RefactorOptions {
9
+ /** Initialized SDK client used for all agent sessions. */
10
+ client: Client
11
+ /** Target directory inside a Git work tree, relative to process.cwd() or absolute. Canonicalized
12
+ * before run storage or agents start; a subdirectory target retains its own scope. */
13
+ cwd: string
14
+ /** Agent model override for all phases. Omit to use the supplied client's backend default. */
15
+ model?: string
16
+ /** Maximum module tasks active at once, as a positive safe integer. Omit to run all concurrently. */
17
+ concurrency?: number
18
+ /** Ask agents to avoid edits and skip integration and host checks. Backend enforcement
19
+ * depends on readPermissionMode. The host fails steps that modify their review worktree. */
20
+ reviewOnly?: boolean
21
+ /** Backend-specific permission mode for planning and review-only sessions. Omit for the backend default. */
22
+ readPermissionMode?: string
23
+ /** Backend-specific permission mode for design/module edits. Omit for the backend default. */
24
+ editPermissionMode?: string
25
+ /** Skip graph export and inspect source directly. Defaults to false. An explicit graph loader
26
+ * or nonempty repograph entry is incompatible with true. */
27
+ noGraph?: boolean
28
+ /** Override the installed @youichi/repograph CLI. Supply an absolute JS/TS entry path because the
29
+ * exporter starts in a temporary directory. Omit the field to use the installed exporter.
30
+ * When graphLoader is supplied, it takes precedence. */
31
+ repographEntry?: string
32
+ /** Export a validated graph for the canonical target under the run lock, bypassing the default
33
+ * subprocess and repographEntry. A rejection is recorded as a run failure. The loader owns
34
+ * temporary resources and must clean them up before settling. */
35
+ graphLoader?: GraphLoader
36
+ /** Commands run serially in each edited worktree before integration. The first failure
37
+ * stops later checks. An empty list disables checks. Omission discovers typecheck then test in
38
+ * the target's own package.json. Blank executables or NUL bytes reject before the run, including
39
+ * in reviewOnly mode, which skips execution. */
40
+ checks?: readonly CheckCommand[]
41
+ /** Target-relative slash globs selecting eligible Git-visible text. Omission or an empty list
42
+ * uses default discovery across languages and skips common metadata and prose. */
43
+ include?: readonly string[]
44
+ /** Target-relative slash globs excluded from the editable scope, including explicit includes. */
45
+ exclude?: readonly string[]
46
+ /** Synchronous progress observer; thrown errors are recorded in report.progressErrors without
47
+ * stopping the run. Returned promises are not awaited. */
48
+ onProgress?: (message: string) => void
49
+ }
50
+
51
+ /** Accept an omitted limit or a positive safe integer. Throw synchronously with the caller's
52
+ * label otherwise. CLI admission checks this before creating a client and refactorCode checks
53
+ * it before opening a run. */
54
+ export function validateConcurrency(value: number | undefined, label = 'concurrency'): void {
55
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 1)) {
56
+ throw new Error(`${label} must be a positive integer`)
57
+ }
58
+ }
59
+
60
+ /** Throw synchronously if graph export is disabled and the caller detected an explicit exporter.
61
+ * The CLI treats presence of --repograph as explicit even when its argument is empty. refactorCode
62
+ * tests the supplied entry or loader for truthiness. Both check before starting their run. */
63
+ export function validateGraphOptions(noGraph: boolean | undefined, hasExporter: boolean, label = 'noGraph'): void {
64
+ if (noGraph && hasExporter) throw new Error(`${label} cannot be combined with a graph exporter`)
65
+ }
@@ -0,0 +1,39 @@
1
+ import type { ModulePlan } from './schema'
2
+
3
+ /**
4
+ * Require case-insensitively unique, filename-safe module IDs and one assignment per inventory path.
5
+ * After the planning worktree is released, plan in refactor.ts supplies the schema-validated
6
+ * response and the inventory it sent to the agent. A thrown Error leaves the plan unpublished
7
+ * and stops module dispatch. The run lifecycle records that error in the incomplete report.
8
+ * Compare paths literally. Check each module's ID before its files, and throw on the first invalid
9
+ * ID or assignment. Report omissions in inventory order after checking all assignments.
10
+ */
11
+ export function validatePlan(plan: ModulePlan, files: readonly string[]): void {
12
+ const expectedFiles = new Set(files)
13
+ const assignedFiles = new Set<string>()
14
+ const claimedIds = new Set<string>()
15
+ for (const module of plan.modules) {
16
+ claimModuleId(module.id, claimedIds)
17
+ for (const file of module.files) {
18
+ if (!expectedFiles.has(file) || assignedFiles.has(file)) {
19
+ throw new Error(`Unlisted or duplicate module file: ${file}`)
20
+ }
21
+ assignedFiles.add(file)
22
+ }
23
+ }
24
+ const missing = files.filter(file => !assignedFiles.has(file))
25
+ if (missing.length) throw new Error(`Module plan omitted source files: ${missing.join(', ')}`)
26
+ }
27
+
28
+ /**
29
+ * Reserve an ID in validatePlan's set of lowercase keys. IDs are 1–80 ASCII characters
30
+ * and start with a letter or digit. Later characters can also be underscores or hyphens.
31
+ * Throw on an unsafe or repeated ID so runModules can report each assignment using a unique ID.
32
+ */
33
+ function claimModuleId(id: string, claimedIds: Set<string>): void {
34
+ const key = id.toLowerCase()
35
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(id) || claimedIds.has(key)) {
36
+ throw new Error(`Invalid or duplicate module id: ${id}`)
37
+ }
38
+ claimedIds.add(key)
39
+ }
@@ -1,4 +1,6 @@
1
- import { execFile } from 'node:child_process';
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+
2
4
  /** Await a child executable's completion and resolve buffered stdout/stderr using Node's execFile contract.
3
5
  * runChecks records process failures before rejecting; exportRepositoryGraph propagates them through
4
6
  * loadGraph's awaited temporary-file cleanup. Callers supply cwd, timeouts, buffer limits and
@@ -6,4 +8,4 @@ import { execFile } from 'node:child_process';
6
8
  * The executable owns its effects; launch, nonzero exit, timeout, buffer and cancellation failures reject
7
9
  * with Node's process errors and captured output. Shell interpretation requires an explicit shell
8
10
  * option or executable. */
9
- export declare const exec: typeof execFile.__promisify__;
11
+ export const exec = promisify(execFile)