@anureo/refactor 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/bin/anureo-refactor.ts +5 -0
  2. package/package.json +21 -23
  3. package/src/agent-work.ts +184 -0
  4. package/src/checks.ts +82 -0
  5. package/src/cli.ts +214 -0
  6. package/src/client.ts +93 -0
  7. package/src/errors.ts +70 -0
  8. package/src/git-path.ts +47 -0
  9. package/src/git-tree.ts +55 -0
  10. package/src/git.ts +55 -0
  11. package/src/graph-artifacts.ts +73 -0
  12. package/src/graph.ts +145 -0
  13. package/src/index.ts +40 -0
  14. package/src/options.ts +65 -0
  15. package/src/plan-validation.ts +38 -0
  16. package/src/{process.d.ts → process.ts} +4 -2
  17. package/src/{prompts.js → prompts.ts} +145 -67
  18. package/src/refactor.ts +191 -0
  19. package/src/{report-store.js → report-store.ts} +10 -8
  20. package/src/report.ts +60 -0
  21. package/src/results.ts +83 -0
  22. package/src/run-lifecycle.ts +117 -0
  23. package/src/{schema.d.ts → schema.ts} +29 -23
  24. package/src/source-inventory.ts +17 -0
  25. package/src/source-policy.ts +50 -0
  26. package/src/worktree.ts +322 -0
  27. package/tests/agent-contract.test.ts +180 -0
  28. package/tests/cli.test.ts +378 -0
  29. package/tests/fixtures/acp.mjs +38 -0
  30. package/tests/fixtures/ahp.mjs +50 -0
  31. package/tests/fixtures/answer.mjs +15 -0
  32. package/tests/fixtures/codex.mjs +44 -0
  33. package/tests/fixtures/repograph.ts +24 -0
  34. package/tests/graph.integration.test.ts +110 -0
  35. package/tests/helpers.ts +109 -0
  36. package/tests/refactor.test.ts +536 -0
  37. package/tests/run-lifecycle.test.ts +136 -0
  38. package/tests/tree.test.ts +210 -0
  39. package/tsconfig.json +12 -0
  40. package/LICENSE +0 -201
  41. package/bin/anureo-refactor.d.ts +0 -2
  42. package/bin/anureo-refactor.js +0 -4
  43. package/src/agent-work.d.ts +0 -41
  44. package/src/agent-work.js +0 -131
  45. package/src/checks.d.ts +0 -26
  46. package/src/checks.js +0 -66
  47. package/src/cli.d.ts +0 -27
  48. package/src/cli.js +0 -189
  49. package/src/client.d.ts +0 -26
  50. package/src/client.js +0 -73
  51. package/src/errors.d.ts +0 -9
  52. package/src/errors.js +0 -22
  53. package/src/git-path.d.ts +0 -15
  54. package/src/git-path.js +0 -46
  55. package/src/git-tree.d.ts +0 -18
  56. package/src/git-tree.js +0 -56
  57. package/src/git.d.ts +0 -23
  58. package/src/git.js +0 -40
  59. package/src/graph-artifacts.d.ts +0 -19
  60. package/src/graph-artifacts.js +0 -58
  61. package/src/graph.d.ts +0 -47
  62. package/src/graph.js +0 -71
  63. package/src/index.d.ts +0 -11
  64. package/src/index.js +0 -4
  65. package/src/options.d.ts +0 -55
  66. package/src/options.js +0 -15
  67. package/src/plan-validation.d.ts +0 -10
  68. package/src/plan-validation.js +0 -38
  69. package/src/process.js +0 -10
  70. package/src/prompts.d.ts +0 -47
  71. package/src/refactor.d.ts +0 -17
  72. package/src/refactor.js +0 -168
  73. package/src/report-store.d.ts +0 -9
  74. package/src/report.d.ts +0 -6
  75. package/src/report.js +0 -52
  76. package/src/results.d.ts +0 -80
  77. package/src/results.js +0 -0
  78. package/src/run-lifecycle.d.ts +0 -18
  79. package/src/run-lifecycle.js +0 -100
  80. package/src/schema.js +0 -31
  81. package/src/source-inventory.d.ts +0 -9
  82. package/src/source-inventory.js +0 -17
  83. package/src/source-policy.d.ts +0 -11
  84. package/src/source-policy.js +0 -56
  85. package/src/worktree.d.ts +0 -57
  86. package/src/worktree.js +0 -195
package/src/errors.ts ADDED
@@ -0,0 +1,70 @@
1
+ // Normalizes caught errors for reports and diagnostics.
2
+ import type { Failure } from './results'
3
+
4
+ declare module './results' {
5
+ interface Failure {
6
+ /** Whether the source error permits a retry. May be absent in older reports. */
7
+ retryable?: boolean
8
+ /** Field paths and rule codes from structured-output validation. */
9
+ issues?: Array<{ path: string | Array<string | number>; code: string }>
10
+ }
11
+ }
12
+
13
+ /** Convert a caught value for display, including values with throwing accessors or conversions. */
14
+ export function message(cause: unknown): string {
15
+ try {
16
+ return String(cause instanceof Error ? cause.message : cause)
17
+ } catch {
18
+ return 'Error details could not be displayed'
19
+ }
20
+ }
21
+
22
+ /** Extract execution and resource-release signals independently from a caught object.
23
+ * executeRun stores the result on the report. markFailed stores it on the first step failure
24
+ * and merges later cleanup signals into that failure. Primitives and functions yield a null code
25
+ * and false flags. Execution uncertainty requires an explicit true. Custom accessors can throw. */
26
+ export function failure(cause: unknown): Failure {
27
+ const error = (cause && typeof cause === 'object' ? cause : {}) as FailureSource
28
+ const issues = validationIssues(error.details?.issues)
29
+ return {
30
+ code: typeof error.code === 'string' ? error.code : null,
31
+ outcomeUnknown: error.outcomeUnknown === true,
32
+ cleanupFailed: hasCleanupFailure(error),
33
+ retryable: error.retryable === true,
34
+ ...(issues.length ? { issues } : {}),
35
+ }
36
+ }
37
+
38
+ interface FailureSource {
39
+ outcomeUnknown?: unknown
40
+ retryable?: unknown
41
+ code?: unknown
42
+ details?: Record<string, unknown>
43
+ }
44
+
45
+ /** Recognize resource-release failures reported by code, explicit flag, or cleanup errors. */
46
+ function hasCleanupFailure(error: FailureSource): boolean {
47
+ return error.code === 'RESOURCE_RELEASE_FAILED' || error.details?.cleanupFailed === true
48
+ || (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
49
+ }
50
+
51
+ /** Keep field locations and rule codes without copying other validation details. */
52
+ function validationIssues(candidates: unknown): NonNullable<Failure['issues']> {
53
+ const issues: NonNullable<Failure['issues']> = []
54
+ if (!Array.isArray(candidates)) return issues
55
+ for (const issue of candidates) {
56
+ if (!issue || typeof issue !== 'object') continue
57
+ const { path, code } = issue
58
+ if (typeof code !== 'string' || !code) continue
59
+ if (typeof path === 'string') {
60
+ issues.push({ path, code })
61
+ } else if (Array.isArray(path)) {
62
+ const parts = [...path]
63
+ if (parts.every(part => typeof part === 'string'
64
+ || (typeof part === 'number' && Number.isSafeInteger(part) && part >= 0))) {
65
+ issues.push({ path: parts, code })
66
+ }
67
+ }
68
+ }
69
+ return issues
70
+ }
@@ -0,0 +1,47 @@
1
+ // Validates Git-relative paths and defines which paths belong in host snapshots.
2
+ import type { Stats } from 'node:fs'
3
+ import { lstat } from 'node:fs/promises'
4
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
5
+
6
+ /** Resolve a Git-relative slash path under cwd and inspect it one component at a time.
7
+ * A missing component or linked ancestor leaves info null. linkedAncestor distinguishes those
8
+ * cases so fileFingerprint and copyEntry can reject traversal while allowing a final symlink.
9
+ * Invalid paths and stat failures other than ENOENT reject. The result describes the inspection,
10
+ * so callers that read or copy the path afterwards need a stable tree. */
11
+ export async function inspectGitPath(cwd: string, file: string): Promise<{ path: string; info: Stats | null; linkedAncestor: boolean }> {
12
+ const parts = file.split('/')
13
+ const target = resolveGitPath(cwd, file, parts)
14
+ let entry = cwd
15
+ let info: Stats | null = null
16
+ for (const part of parts) {
17
+ entry = resolve(entry, part)
18
+ info = await lstat(entry).catch((cause: NodeJS.ErrnoException) => {
19
+ if (cause.code === 'ENOENT') return null
20
+ throw cause
21
+ })
22
+ if (!info || info.isSymbolicLink()) break
23
+ }
24
+ if (entry === target) return { path: target, info, linkedAncestor: false }
25
+ return { path: target, info: null, linkedAncestor: info?.isSymbolicLink() ?? false }
26
+ }
27
+
28
+ /** Decide whether a Git-relative path belongs in host snapshots, without filesystem access.
29
+ * Run storage must never count as an agent edit, even when force-added; Git metadata is also omitted.
30
+ * Other non-source files remain visible so host diffing can detect edits outside agent scope. */
31
+ export function isSnapshotPath(file: string): boolean {
32
+ return !file.split('/').some(part => ['.anureo', '.git'].includes(part.toLowerCase()))
33
+ }
34
+
35
+ /** Reject noncanonical Git path components before host path resolution, then check containment
36
+ * using the platform's path rules. This lexical check performs no filesystem access. */
37
+ function resolveGitPath(cwd: string, file: string, parts: readonly string[]): string {
38
+ if (isAbsolute(file) || file.includes('\\') || file.includes('\0')
39
+ || (process.platform === 'win32' && file.includes(':'))
40
+ || parts.some(part => !part || part === '.' || part === '..')) throw new Error(`Invalid source path: ${file}`)
41
+ const target = resolve(cwd, file)
42
+ const local = relative(cwd, target)
43
+ if (!local || local === '..' || local.startsWith(`..${sep}`) || isAbsolute(local)) {
44
+ throw new Error(`Source path escapes repository: ${file}`)
45
+ }
46
+ return target
47
+ }
@@ -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,55 @@
1
+ // Runs Git with checkout-local environment overrides removed.
2
+ import { realpath } from 'node:fs/promises'
3
+ import { resolve } from 'node:path'
4
+ import { message } from './errors'
5
+ import { exec } from './process'
6
+
7
+ /** List sorted, unique tracked and unignored untracked paths under cwd via Git.
8
+ * Snapshot callers supply an in-repository directory; paths are relative to it, including when
9
+ * it is a subdirectory. Launches a read-only Git command; process/buffer failures reject. */
10
+ export async function gitFiles(cwd: string): Promise<string[]> {
11
+ const { stdout } = await exec('git', ['-C', cwd, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
12
+ ...gitProcessOptions(), encoding: 'buffer',
13
+ })
14
+ let paths: string
15
+ try {
16
+ paths = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(stdout)
17
+ } catch (cause) {
18
+ throw new Error(`Git reported a filename that is not valid UTF-8 in ${cwd}`, { cause })
19
+ }
20
+ return [...new Set(paths.split('\0').filter(Boolean))].sort()
21
+ }
22
+
23
+ /** Run Git with cwd as its starting directory and resolve buffered text stdout on success.
24
+ * The command determines filesystem effects. Launch, nonzero exit and buffer failures reject
25
+ * with the child-process error. Repository-local environment overrides from hooks are removed. */
26
+ export async function git(cwd: string, ...args: string[]): Promise<string> {
27
+ return (await exec('git', ['-C', cwd, ...args], gitProcessOptions())).stdout
28
+ }
29
+
30
+ /** Build a fresh environment so Git and validation commands discover their own checkout. */
31
+ export function checkoutEnvironment(): NodeJS.ProcessEnv {
32
+ const env = { ...process.env }
33
+ for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX',
34
+ 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_IMPLICIT_WORK_TREE',
35
+ 'GIT_GRAFT_FILE', 'GIT_SHALLOW_FILE']) delete env[key]
36
+ return env
37
+ }
38
+
39
+ /** Use the same 64 MiB buffer limit for text and binary Git output. */
40
+ export function gitProcessOptions() {
41
+ return { env: checkoutEnvironment(), maxBuffer: 64 << 20 }
42
+ }
43
+
44
+ /** Resolve a preflight target to its real absolute path and require Git's work-tree probe to return true.
45
+ * refactorCode uses the returned path before opening run storage, retaining any subdirectory
46
+ * scope. Filesystem resolution failures propagate. A false probe or process failure rejects
47
+ * with a repository diagnostic. */
48
+ export async function repositoryDirectory(directory: string): Promise<string> {
49
+ const cwd = await realpath(resolve(directory))
50
+ // Keep the target directory rather than the Git root so subdirectory runs retain their scope.
51
+ const stdout = await git(cwd, 'rev-parse', '--is-inside-work-tree')
52
+ .catch(cause => { throw new Error(`Could not check Git work tree at ${cwd}: ${message(cause)}`, { cause }) })
53
+ if (stdout.trim() !== 'true') throw new Error(`Not inside a Git work tree: ${cwd}`)
54
+ return cwd
55
+ }
@@ -0,0 +1,73 @@
1
+ // Records graph coverage and writes the graph supplied to each refactor phase.
2
+ import { writeFile } from 'node:fs/promises'
3
+ import { join, relative, resolve, sep } from 'node:path'
4
+ import { message } from './errors'
5
+ import { GraphCleanupError, loadGraph, RepographNotInstalledError, 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 optional-package lookup failure. */
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. Configured exporter failures,
22
+ * cleanup failures and artifact serialization or write failures stop the pending agent work.
23
+ * Coverage records export availability before serialization so the report retains coverage even
24
+ * 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
+ // The shared storage directory can have custom ignore rules. Always ignore this run's output.
29
+ await writeFile(join(report.directory, '.gitignore'), '*\n')
30
+ if (options.noGraph) {
31
+ report.graphCoverage.push({ phase, status: 'disabled', filesWithoutSymbols: files })
32
+ return null
33
+ }
34
+ if (context.graphError !== undefined) {
35
+ recordUnavailable(report.graphCoverage, { phase, files, error: context.graphError })
36
+ return null
37
+ }
38
+ let graph: RepositoryGraph
39
+ try {
40
+ graph = options.graphLoader ? await options.graphLoader(options.cwd) : await loadGraph(options.cwd, options.repographEntry)
41
+ } catch (cause) {
42
+ const error = message(cause)
43
+ recordUnavailable(report.graphCoverage, { phase, files, error })
44
+ if (options.graphLoader || options.repographEntry || cause instanceof GraphCleanupError) throw cause
45
+ if (cause instanceof RepographNotInstalledError) context.graphError = error
46
+ progress(`graph/${phase}: unavailable; continuing with source`)
47
+ return null
48
+ }
49
+ report.graphCoverage.push({ phase, status: 'available', filesWithoutSymbols: filesWithoutSymbols(graph, options.cwd, files) })
50
+ const file = join(report.directory, `graph-${phase}.json`)
51
+ await writeFile(file, JSON.stringify(graph))
52
+ return file
53
+ }
54
+
55
+ /** Append unavailable coverage for exportGraph using the current phase's inventory, including on
56
+ * later phases that reuse a cached error. */
57
+ function recordUnavailable(coverage: GraphCoverage[], { phase, files, error }: { phase: string; files: string[]; error: string }): void {
58
+ coverage.push({ phase, status: 'unavailable', filesWithoutSymbols: files, error })
59
+ }
60
+
61
+ /** Return inventory paths in input order that lack indexed symbols. Container labels alone
62
+ * establish that a path was seen, so exportGraph counts a node only if it has a non-container
63
+ * label. Resolve relative paths at the graph root and accept both spellings of the target. */
64
+ function filesWithoutSymbols(graph: RepositoryGraph, cwd: string, files: string[]): string[] {
65
+ const containerLabel = /^(file|folder|directory|package|project|module)$/i
66
+ const symbols = graph.nodes.filter(node => node.labels.some(label => !containerLabel.test(label)))
67
+ const roots = new Set([graph.repositoryPath, cwd])
68
+ const indexed = new Set(symbols.flatMap(({ filePath }) => {
69
+ const absolutePath = resolve(graph.repositoryPath, filePath)
70
+ return Array.from(roots, root => relative(root, absolutePath).split(sep).join('/'))
71
+ }))
72
+ return files.filter(file => !indexed.has(file))
73
+ }
package/src/graph.ts ADDED
@@ -0,0 +1,145 @@
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 { spawnHarnessProcess } from '@anureo/sdk/process'
8
+ import { z } from 'zod'
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
+ export class RepographNotInstalledError extends Error {}
24
+
25
+ export class GraphCleanupError extends Error {
26
+ readonly code = 'RESOURCE_RELEASE_FAILED'
27
+ }
28
+
29
+ /** Resolve the optional Repograph package's CLI entry for loadGraph's default and live tests.
30
+ * Throws if the package cannot be resolved. Deferring resolution allows source-only runs. */
31
+ export function resolveRepographEntry(): string {
32
+ try {
33
+ return join(dirname(createRequire(import.meta.url).resolve('@youichi/repograph')), 'cli.js')
34
+ } catch (cause) {
35
+ if ((cause as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw cause
36
+ throw new RepographNotInstalledError('Cannot resolve the optional @youichi/repograph package', { cause })
37
+ }
38
+ }
39
+
40
+ /** Keep the supplied path as the index key so repeated exports reuse the same project. */
41
+ export function repographProject(cwd: string): string {
42
+ return `anureo-refactor-${createHash('sha256').update(cwd).digest('hex').slice(0, 16)}`
43
+ }
44
+
45
+ /** Export a validated graph for an absolute target directory. Supply an absolute CLI entry to
46
+ * override the installed Repograph package. Both paths go unchanged to a subprocess started in
47
+ * an OS temporary directory. The promise settles after temporary-directory cleanup, retaining the
48
+ * external index for reuse. Serialize calls that share that index, whose key derives from the
49
+ * supplied target path. exportGraph does this under the run lock before writing the phase artifact.
50
+ * Package resolution, subprocess, filesystem, parse and validation errors reject. A cleanup
51
+ * failure takes precedence over an earlier error. */
52
+ export async function loadGraph(cwd: string, entry = resolveRepographEntry()): Promise<RepositoryGraph> {
53
+ const temporary = await mkdtemp(join(tmpdir(), 'anureo-refactor-graph-'))
54
+ try {
55
+ const graph = await exportRepositoryGraph({ cwd, entry, temporary })
56
+ await validateRepositoryGraph(graph, cwd)
57
+ return graph
58
+ } finally {
59
+ await rm(temporary, { recursive: true, force: true }).catch(cause => {
60
+ throw new GraphCleanupError(`Unable to remove temporary graph directory ${temporary}: ${cause.message}`, { cause })
61
+ })
62
+ }
63
+ }
64
+
65
+ /** Validate the core export fields and retain exporter and language-specific node metadata. */
66
+ const graphSchema = z.looseObject({
67
+ schemaVersion: z.literal(1), repositoryPath: z.string(), kind: z.literal('all'),
68
+ indexReport: z.record(z.string(), z.unknown()),
69
+ nodes: z.array(z.looseObject({
70
+ id: z.string(), name: z.string(), filePath: z.string(), labels: z.array(z.string()),
71
+ startLine: z.number().nullable(), endLine: z.number().nullable(),
72
+ // Upstream metrics (lines, complexity, cognitive, param_count, is_test...). Agents read them
73
+ // from the artifact to find large or tightly connected functions; do not drop them.
74
+ properties: z.record(z.string(), z.unknown()).optional(),
75
+ })),
76
+ edges: z.array(z.object({
77
+ id: z.string(), source: z.string(), target: z.string(), type: z.string(),
78
+ // CALLS: call line. IMPORTS: imported name (local_name). Both are used to locate evidence.
79
+ properties: z.record(z.string(), z.unknown()).optional(),
80
+ })),
81
+ })
82
+
83
+ const exportTimeout = 300_000
84
+ const outputLimit = 8 << 20
85
+
86
+ /** Return the parsed CLI payload after the exporter has exited and its process tree is disposed. */
87
+ async function exportRepositoryGraph(input: { cwd: string; entry: string; temporary: string }): Promise<RepositoryGraph> {
88
+ const { cwd, entry, temporary } = input
89
+ const output = join(temporary, 'graph.json')
90
+ const child = await spawnHarnessProcess({
91
+ command: process.execPath, cwd: temporary,
92
+ args: [entry, 'export', cwd, '--kind', 'all', '--project', repographProject(cwd), '--out', output],
93
+ })
94
+ let timer: ReturnType<typeof setTimeout> | undefined
95
+ try {
96
+ const completion = Promise.all([child.exited, drainOutput(child.stdout, 'stdout'), drainOutput(child.stderr, 'stderr')])
97
+ const deadline = new Promise<never>((_, reject) => {
98
+ timer = setTimeout(() => reject(new Error(`repograph export timed out after ${exportTimeout} ms`)), exportTimeout)
99
+ })
100
+ const [exit, , stderr] = await Promise.race([completion, deadline])
101
+ if (exit.code !== 0) {
102
+ const status = exit.signal ? `with signal ${exit.signal}` : `with code ${exit.code}`
103
+ throw new Error(`repograph exited ${status}${stderr ? `: ${stderr}` : ''}`)
104
+ }
105
+ } finally {
106
+ clearTimeout(timer)
107
+ await child.dispose().catch(cause => {
108
+ throw new GraphCleanupError(`Unable to dispose repograph process: ${cause.message}`, { cause })
109
+ })
110
+ }
111
+ return graphSchema.parse(JSON.parse(await readFile(output, 'utf8')))
112
+ }
113
+
114
+ /** Enforce a byte limit on each pipe and retain stderr for exit diagnostics. */
115
+ async function drainOutput(stream: AsyncIterable<Uint8Array>, name: 'stdout' | 'stderr'): Promise<string> {
116
+ let bytes = 0
117
+ const chunks: Uint8Array[] = []
118
+ for await (const chunk of stream) {
119
+ bytes += chunk.byteLength
120
+ if (bytes > outputLimit) throw new Error(`repograph ${name} exceeded the ${outputLimit}-byte output limit`)
121
+ if (name === 'stderr') chunks.push(chunk)
122
+ }
123
+ return Buffer.concat(chunks).toString('utf8')
124
+ }
125
+
126
+ /** Require a parsed graph to describe the same real directory and have unique node IDs and valid
127
+ * edge references. loadGraph awaits this read-only check before returning the graph. Filesystem,
128
+ * repository identity and graph integrity failures reject through loadGraph's cleanup. */
129
+ async function validateRepositoryGraph(graph: RepositoryGraph, cwd: string): Promise<void> {
130
+ if (await realpath(graph.repositoryPath) !== await realpath(cwd)) throw new Error('repograph returned a different repository')
131
+ const ids = new Set<string>()
132
+ let duplicateId: string | undefined
133
+ for (const node of graph.nodes) {
134
+ if (ids.has(node.id)) duplicateId ??= node.id
135
+ ids.add(node.id)
136
+ }
137
+ const edge = graph.edges.find(edge => !ids.has(edge.source) || !ids.has(edge.target))
138
+ const diagnostics: string[] = []
139
+ if (duplicateId !== undefined) diagnostics.push(`Duplicate node ID ${JSON.stringify(duplicateId)}`)
140
+ if (edge) {
141
+ const missingIds = [...new Set([edge.source, edge.target])].filter(id => !ids.has(id))
142
+ diagnostics.push(`Edge ${JSON.stringify(edge.id)} references missing node IDs ${JSON.stringify(missingIds)}`)
143
+ }
144
+ if (diagnostics.length) throw new Error(diagnostics.join('\n'))
145
+ }
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Refactor code with agents in isolated Git worktrees. The host validates edits before merging.
3
+ * The CLI requires Bun, Git and a configured harness. With Codex on PATH, run
4
+ * `anureo-refactor . --review-only` to inspect proposals without applying edits.
5
+ *
6
+ * Library callers supply and dispose an initialized client. Reports are saved under
7
+ * `<target>/.anureo/refactor/<run-id>/report.json`. A phase failure can return an incomplete
8
+ * report with edits already merged. Invalid input, run setup, final publication and lock
9
+ * cleanup failures reject the call.
10
+ *
11
+ * ```ts
12
+ * import { createCodexAdapter } from '@anureo/adapter-codex'
13
+ * import { createClient } from '@anureo/sdk'
14
+ * import { refactorCode } from '@anureo/refactor'
15
+ *
16
+ * const cwd = process.cwd()
17
+ * const client = await createClient({
18
+ * adapter: createCodexAdapter({ command: 'codex', cwd }),
19
+ * identity: { adapterId: 'codex', runtimeConfigId: 'refactor-example' },
20
+ * })
21
+ * try {
22
+ * const report = await refactorCode({ client, cwd, reviewOnly: true })
23
+ * console.log(report.status, report.directory)
24
+ * if (report.status === 'incomplete') process.exitCode = 2
25
+ * } finally {
26
+ * await client.dispose()
27
+ * }
28
+ * ```
29
+ */
30
+ export { refactorCode } from './refactor'
31
+ export type { RefactorOptions } from './options'
32
+ export type { CheckCommand } from './checks'
33
+ /** Host observations returned to callers, including partial edits and ordered validation outcomes. */
34
+ export type { RefactorReport, GraphCoverage, ModuleResult, StepResult, CheckResult, Failure } from './results'
35
+ /** Agent response shapes; work summaries, changes and deferrals are agent claims, distinct from
36
+ * host-observed step results. Types alone do not validate external output or module assignments. */
37
+ export type { ModulePlan, RefactorModule, Work } from './schema'
38
+ export { formatReport } from './report'
39
+ export { loadGraph } from './graph'
40
+ 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 on the prospective combined tree 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,38 @@
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. Report ID and assignment errors in traversal order, then omissions
9
+ * in inventory order.
10
+ */
11
+ export function validatePlan(plan: ModulePlan, files: readonly string[]): void {
12
+ const expectedFiles = new Set(files)
13
+ const assignments = new Map<string, string>()
14
+ const claimedIds = new Map<string, string>()
15
+ const issues: string[] = []
16
+ for (const [index, module] of plan.modules.entries()) {
17
+ const location = `modules[${index}]`
18
+ const key = module.id.toLowerCase()
19
+ const firstId = claimedIds.get(key)
20
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(module.id)) {
21
+ issues.push(`${location}.id: ${JSON.stringify(module.id)} must start with an ASCII letter or digit and contain at most 80 letters, digits, underscores or hyphens`)
22
+ }
23
+ if (firstId) issues.push(`${location}.id: ${JSON.stringify(module.id)} duplicates ${firstId} ignoring case`)
24
+ else claimedIds.set(key, `${location}.id`)
25
+ for (const [fileIndex, file] of module.files.entries()) {
26
+ const assignment = `${location}.files[${fileIndex}]`
27
+ const firstAssignment = assignments.get(file)
28
+ if (!expectedFiles.has(file)) {
29
+ issues.push(`${assignment}: ${JSON.stringify(file)} is absent from the inventory`)
30
+ }
31
+ if (firstAssignment) issues.push(`${assignment}: ${JSON.stringify(file)} was already assigned at ${firstAssignment}`)
32
+ else assignments.set(file, assignment)
33
+ }
34
+ }
35
+ const missing = files.filter(file => !assignments.has(file))
36
+ if (missing.length) issues.push(`Module plan omitted source files: ${missing.map(file => JSON.stringify(file)).join(', ')}`)
37
+ if (issues.length) throw new Error(issues.join('\n'))
38
+ }
@@ -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)