@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/results.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { ModulePlan, RefactorModule, Work } from './schema'
2
+
3
+ /** Result recorded when the host runs a validation command in a worktree before integration. */
4
+ export interface CheckResult {
5
+ command: string
6
+ status: 'passed' | 'failed'
7
+ /** Last 4,000 characters of stdout followed by stderr, with the error message appended on failure. */
8
+ output: string
9
+ }
10
+ /** Error signals to consult before retrying a failed step or run. */
11
+ export interface Failure {
12
+ /** String code on the caught object, or null when absent or not a string. */
13
+ code: string | null
14
+ /** The error explicitly reports that the execution outcome is unknown. */
15
+ outcomeUnknown: boolean
16
+ /** A resource-release error was reported, independently of execution outcome. */
17
+ cleanupFailed: boolean
18
+ }
19
+ /** Outcome of a design or module step, including host observations from integration and validation.
20
+ * The inherited summary, changes and deferred fields are the agent's account of the work. */
21
+ export interface StepResult extends Work {
22
+ /** Unchanged for an empty edit, applied after integration, or failed on an error. A cleanup
23
+ * failure can be reported after a verified merge. */
24
+ status: 'applied' | 'unchanged' | 'failed'
25
+ /** Sorted Git-visible paths changed by the isolated agent within the target directory. */
26
+ changedFiles: string[]
27
+ /** Paths confirmed transferred to the target, even if cleanup later failed. Absence conveys no confirmed transfer. */
28
+ appliedFiles?: string[]
29
+ /** Legacy report field containing the path to a historical patch artifact. */
30
+ patch?: string
31
+ /** Executed checks in command order; a failure stops subsequent checks. */
32
+ checks: CheckResult[]
33
+ /** Display text for the caught step error, or null when no error was caught. */
34
+ error: string | null
35
+ /** Classification of the first caught step error, with later cleanup failures merged in. */
36
+ failure: Failure | null
37
+ }
38
+ /** Planned module and its step record, paired in plan order before any module starts. */
39
+ export interface ModuleResult {
40
+ module: RefactorModule
41
+ /** Null until the worktree has finished validation, integration and cleanup. */
42
+ step: StepResult | null
43
+ }
44
+ /** Graph availability and declaration coverage for one phase's source inventory. */
45
+ export interface GraphCoverage {
46
+ phase: string
47
+ status: 'available' | 'unavailable' | 'disabled'
48
+ /** Paths with no indexed declarations, or the entire source inventory when no graph was available.
49
+ * Indexed files can still have unresolved relationships. */
50
+ filesWithoutSymbols: string[]
51
+ /** Export error text when graph data is unavailable. */
52
+ error?: string
53
+ }
54
+ /** Outcome returned by refactorCode after final publication and writer-lock release. During the
55
+ * run, report.json is updated at checkpoints and onProgress receives event strings. An incomplete
56
+ * report can include edits already applied to the target. The caller still owns the SDK client. */
57
+ export interface RefactorReport {
58
+ /** UUID allocated after writer-lock acquisition, also used as the run directory name. */
59
+ runId: string
60
+ /** Canonical target directory, which may be a subdirectory of a Git repository. */
61
+ cwd: string
62
+ /** Absolute storage directory for this run's reports, graphs and baseline. */
63
+ directory: string
64
+ /** Completed means every phase returned successfully; deferred work may still be listed. */
65
+ status: 'completed' | 'incomplete'
66
+ /** Agents were asked to avoid edits and host validation commands were disabled. */
67
+ reviewOnly: boolean
68
+ /** Cross-module design step, run before modules are planned. */
69
+ design: StepResult | null
70
+ /** Validated module assignments, or null until planning succeeds. */
71
+ plan: ModulePlan | null
72
+ /** Module records in plan order. Successful edits merge in readiness order. */
73
+ modules: ModuleResult[]
74
+ /** Graph availability and file coverage for the exports attempted during the run. */
75
+ graphCoverage: GraphCoverage[]
76
+ /** Run-level diagnostics. Consult each failed StepResult for its own error. */
77
+ errors: string[]
78
+ /** Classification of the run-level error, or null when none was caught. A failed-step gate
79
+ * throws a new error, so inspect the failed step for its original signals. */
80
+ failure: Failure | null
81
+ /** Display text for synchronous observer exceptions that were successfully converted, in delivery order. */
82
+ progressErrors: string[]
83
+ }
@@ -0,0 +1,117 @@
1
+ // Owns run identity, progress delivery and the lifetime of the checkout writer lock.
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdir, open, realpath, rm, writeFile } from 'node:fs/promises'
4
+ import type { FileHandle } from 'node:fs/promises'
5
+ import { dirname, join } from 'node:path'
6
+ import { failure, message } from './errors'
7
+ import { git } from './git'
8
+ import type { RefactorOptions } from './options'
9
+ import { saveReport } from './report-store'
10
+ import type { RefactorReport } from './results'
11
+
12
+ /** Run the phases supplied by refactorCode under the checkout's writer lock.
13
+ * Phase failures produce an incomplete report and synchronous observer errors are recorded
14
+ * separately. Setup, final publication and lock cleanup failures reject. */
15
+ export async function withRun(options: RefactorOptions & { cwd: string }, body: RunBody): Promise<RefactorReport> {
16
+ const writer = await acquireWriter(options.cwd)
17
+ const errors: unknown[] = []
18
+ try {
19
+ if (writer.root !== dirname(writer.lockPath)) await initializeStorage(writer.root)
20
+ const report = createReport(options, writer.root)
21
+ await mkdir(report.directory)
22
+ await executeRun(options, report, body).catch(cause => { errors.push(cause) })
23
+ await saveReport(report)
24
+ return report
25
+ } catch (cause) {
26
+ errors.push(cause)
27
+ throw cause
28
+ } finally {
29
+ await writer.lock.close().catch(cause => { errors.push(cause) })
30
+ await rm(writer.lockPath).catch(cause => { errors.push(cause) })
31
+ if (errors.length > 1) throw new AggregateError(errors, errors.map(message).join('\n'))
32
+ if (errors.length === 1) throw errors[0]
33
+ }
34
+ }
35
+
36
+ /** Resources owned by withRun after exclusive acquisition; the handle closes before path removal. */
37
+ interface RunWriter {
38
+ root: string
39
+ lockPath: string
40
+ lock: FileHandle
41
+ }
42
+
43
+ /** refactorCode supplies the design, planning and module phases as this callback. executeRun
44
+ * delivers the run event before invoking it. The callback can update the report, emit progress
45
+ * and publish intermediate checkpoints. Its settlement determines run status. */
46
+ type RunBody = (report: RefactorReport, progress: (event: string) => void) => Promise<void>
47
+
48
+ /** Acquire checkout-wide ownership while keeping report storage relative to the target. */
49
+ async function acquireWriter(cwd: string): Promise<RunWriter> {
50
+ const root = join(cwd, '.anureo', 'refactor')
51
+ const checkoutRoot = await realpath((await git(cwd, 'rev-parse', '--show-toplevel')).replace(/\r?\n$/, ''))
52
+ const lockRoot = join(checkoutRoot, '.anureo', 'refactor')
53
+ await initializeStorage(lockRoot)
54
+ const lockPath = join(lockRoot, 'writer.lock')
55
+ const lock = await open(lockPath, 'wx').catch((cause: NodeJS.ErrnoException) => {
56
+ if (cause.code !== 'EEXIST') throw cause
57
+ throw new Error(
58
+ `Cannot acquire refactor lock: ${lockPath}. Check for an active run before removing a stale lock.`,
59
+ { cause },
60
+ )
61
+ })
62
+ return { root, lockPath, lock }
63
+ }
64
+
65
+ /** Ignore tool artifacts while preserving any existing storage-specific ignore rules. */
66
+ async function initializeStorage(root: string): Promise<void> {
67
+ await mkdir(root, { recursive: true })
68
+ await writeFile(join(root, '.gitignore'), '*\n', { flag: 'wx' }).catch((cause: NodeJS.ErrnoException) => {
69
+ if (cause.code !== 'EEXIST') throw cause
70
+ })
71
+ }
72
+
73
+ /** Allocate the initial incomplete record for a locked run without creating its directory.
74
+ * withRun calls this after acquisition. UUID generation can throw. */
75
+ function createReport(options: RefactorOptions, root: string): RefactorReport {
76
+ const runId = randomUUID()
77
+ return {
78
+ runId,
79
+ cwd: options.cwd,
80
+ directory: join(root, runId),
81
+ status: 'incomplete',
82
+ reviewOnly: options.reviewOnly ?? false,
83
+ design: null,
84
+ plan: null,
85
+ modules: [],
86
+ graphCoverage: [],
87
+ errors: [],
88
+ failure: null,
89
+ progressErrors: [],
90
+ }
91
+ }
92
+
93
+ /** Report run progress and await orchestration, recording phase failures in the report. */
94
+ async function executeRun(options: RefactorOptions, report: RefactorReport, body: RunBody): Promise<void> {
95
+ const progress = createProgressReporter(options, report)
96
+ try {
97
+ progress(`run: ${report.directory}`)
98
+ await body(report, progress)
99
+ report.status = 'completed'
100
+ } catch (cause) {
101
+ report.errors.push(message(cause))
102
+ report.failure = failure(cause)
103
+ }
104
+ }
105
+
106
+ /** Give executeRun and its phase callback a synchronous progress function for this report.
107
+ * refactorCode supplies the observer through options. Record thrown observer errors so a failed
108
+ * display sink does not stop work. Observer return values are ignored. */
109
+ function createProgressReporter(options: RefactorOptions, report: RefactorReport): (event: string) => void {
110
+ return event => {
111
+ try {
112
+ options.onProgress?.(event)
113
+ } catch (cause) {
114
+ report.progressErrors.push(message(cause))
115
+ }
116
+ }
117
+ }
@@ -1,42 +1,48 @@
1
- import { z } from 'zod';
1
+ import { z } from 'zod'
2
+
2
3
  /**
3
4
  * Describe the required planning response for the workflow agent called by plan in refactor.ts.
4
5
  * All strings, the module list and each file list must be nonempty. Parsing preserves whitespace
5
6
  * and rejects unknown fields in the response and its modules. plan passes the parsed response
6
7
  * to validatePlan for ID safety and exact inventory coverage before prepareModules can publish it.
7
8
  */
8
- export declare const modulePlanSchema: z.ZodObject<{
9
- summary: z.ZodString;
10
- modules: z.ZodArray<z.ZodObject<{
11
- id: z.ZodString;
12
- name: z.ZodString;
13
- description: z.ZodString;
14
- files: z.ZodArray<z.ZodString>;
15
- }, z.core.$strict>>;
16
- }, z.core.$strict>;
9
+ export const modulePlanSchema = z.strictObject({
10
+ summary: z.string().min(1),
11
+ modules: z.array(z.strictObject({
12
+ /** Artifact filename component; syntax and uniqueness are checked separately by validatePlan. */
13
+ id: z.string().min(1),
14
+ name: z.string().min(1),
15
+ description: z.string().min(1),
16
+ /** Exact host inventory paths; validatePlan checks membership and exclusive assignment. */
17
+ files: z.array(z.string().min(1)).min(1),
18
+ })).min(1),
19
+ })
20
+
17
21
  /**
18
22
  * Describe the required design and module responses for the workflow agent called by runAgentWork.
19
23
  * Parsing preserves whitespace in nonempty strings, accepts empty change and deferral lists, and
20
24
  * rejects unknown fields in the response and its deferrals. runAgentWork copies valid responses
21
25
  * into its step result and records a failed step when agent validation rejects.
22
26
  */
23
- export declare const workSchema: z.ZodObject<{
24
- summary: z.ZodString;
25
- changes: z.ZodArray<z.ZodString>;
26
- deferred: z.ZodArray<z.ZodObject<{
27
- title: z.ZodString;
28
- reason: z.ZodString;
29
- }, z.core.$strict>>;
30
- }, z.core.$strict>;
27
+ export const workSchema = z.strictObject({
28
+ summary: z.string().min(1),
29
+ /** Agent-reported edits or proposals, which need not correspond to observed file changes. */
30
+ changes: z.array(z.string().min(1)),
31
+ /** Unresolved findings with reasons; these do not by themselves make the host step fail. */
32
+ deferred: z.array(z.strictObject({ title: z.string().min(1), reason: z.string().min(1) })),
33
+ })
34
+
31
35
  /** Read the planner's summary and validated assignments from RefactorReport.plan.
32
- * Modules appear in the order the planner supplied and the host uses that order for integration.
36
+ * Modules and report entries retain planner order. Verified edits are integrated in readiness order.
33
37
  * Constructing this type performs no validation. */
34
- export type ModulePlan = z.infer<typeof modulePlanSchema>;
38
+ export type ModulePlan = z.infer<typeof modulePlanSchema>
39
+
35
40
  /** Read a planned module from the report's plan or a ModuleResult. Its ID identifies the module in
36
- * progress events and patch filenames. Its file list describes the original assignment. Use
41
+ * progress events and reports. Its file list describes the original assignment. Use
37
42
  * StepResult.changedFiles for the paths the host observed the agent change. */
38
- export type RefactorModule = ModulePlan['modules'][number];
43
+ export type RefactorModule = ModulePlan['modules'][number]
44
+
39
45
  /** Read an agent's summary, reported changes or proposals, and deferred findings on a StepResult.
40
46
  * Use the step's status, changed files and check results for host-observed outcomes.
41
47
  * Empty change and deferral lists are valid. */
42
- export type Work = z.infer<typeof workSchema>;
48
+ export type Work = z.infer<typeof workSchema>
@@ -0,0 +1,17 @@
1
+ import { captureTree } from './git-tree'
2
+ import type { RefactorOptions } from './options'
3
+ import { isSource, isTextSource } from './source-policy'
4
+
5
+ /** Return the whole host fingerprint map and its eligible text paths in sorted Git order.
6
+ * runDesign persists the map and sends the eligible files to design. prepareModules uses a fresh
7
+ * inventory after design for planning and plan validation. Snapshot failures, unsafe eligible
8
+ * paths and an empty eligible list reject before the corresponding agent is dispatched. */
9
+ export async function inventory({ cwd, include, exclude }: Pick<RefactorOptions, 'cwd' | 'include' | 'exclude'>): Promise<{ tree: Map<string, string>; files: string[] }> {
10
+ const tree = await captureTree(cwd)
11
+ const files: string[] = []
12
+ for (const file of tree.keys()) {
13
+ if (isSource(file, include, exclude) && await isTextSource(cwd, file)) files.push(file)
14
+ }
15
+ if (!files.length) throw new Error('No eligible Git-visible source files found')
16
+ return { tree, files }
17
+ }
@@ -0,0 +1,50 @@
1
+ // Selects the paths and text eligible for review and editing.
2
+ import { readFile } from 'node:fs/promises'
3
+ import { posix } from 'node:path'
4
+ import { inspectGitPath, isSnapshotPath } from './git-path'
5
+
6
+ /** Match a Git-relative path against source scope rules without reading the filesystem.
7
+ * Built-in path exclusions and explicit exclude globs take precedence over include globs.
8
+ * With no includes, conventional supporting files are skipped. inventory and runAgentWork
9
+ * follow a successful match with isTextSource before accepting a source path. */
10
+ export function isSource(file: string, include: readonly string[] = [], exclude: readonly string[] = []): boolean {
11
+ if (isExcluded(file)) return false
12
+ if (exclude.some(pattern => posix.matchesGlob(file, pattern))) return false
13
+ if (include.length) return include.some(pattern => posix.matchesGlob(file, pattern))
14
+ return !supportingFile.test(posix.basename(file))
15
+ }
16
+
17
+ /** Check a Git-relative regular file for UTF-8 or BOM-marked UTF-16 text. inventory skips false
18
+ * results, and runAgentWork treats them as assignment violations for new unassigned paths.
19
+ * Missing paths, nonfiles, undecodable data and disallowed control characters return false.
20
+ * Invalid paths, built-in exclusions, symlinks and filesystem failures other than missing
21
+ * entries during inspection reject. Callers apply include and exclude globs through isSource. */
22
+ export async function isTextSource(cwd: string, file: string): Promise<boolean> {
23
+ if (isExcluded(file)) throw new Error(`Invalid source path: ${file}`)
24
+ const { path, info, linkedAncestor } = await inspectGitPath(cwd, file)
25
+ if (linkedAncestor || info?.isSymbolicLink()) throw new Error(`Symlink source paths are unsupported: ${file}`)
26
+ if (!info?.isFile()) return false
27
+ return isSupportedText(await readFile(path))
28
+ }
29
+
30
+ /** Exclude additional directories from edits while retaining them in snapshots. */
31
+ const sourceOnlyExclusions = new Set(['.repograph', 'node_modules', 'dist', 'build', 'coverage', 'vendor', 'generated', 'draft', 'docs'])
32
+ /** Repository metadata and conventional standalone prose. Explicit includes can select these files. */
33
+ const supportingFile = /^(?:\.(?:gitignore|gitattributes|gitmodules|editorconfig)|package(?:-lock)?\.json|(?:bun|yarn|Cargo|uv|poetry)\.lockb?|pnpm-lock\.ya?ml|(?:README|LICENSE|LICENCE|COPYING|NOTICE|CHANGELOG|CONTRIBUTING|AGENTS)(?:\.(?:md|txt|rst|adoc))?)$/i
34
+
35
+ /** Match hard exclusions against any path component, regardless of case or glob settings. */
36
+ function isExcluded(file: string): boolean {
37
+ return !isSnapshotPath(file) || file.split('/').some(part => sourceOnlyExclusions.has(part.toLowerCase()))
38
+ }
39
+
40
+ /** Default to UTF-8 unless a UTF-16 byte-order mark is present. Decode strictly so invalid
41
+ * byte sequences cannot pass through as replacement characters. */
42
+ function isSupportedText(content: Buffer): boolean {
43
+ let encoding = 'utf-8'
44
+ if (content[0] === 0xff && content[1] === 0xfe) encoding = 'utf-16le'
45
+ if (content[0] === 0xfe && content[1] === 0xff) encoding = 'utf-16be'
46
+ try {
47
+ const text = new TextDecoder(encoding, { fatal: true }).decode(content)
48
+ return !/[\x00-\x08\x0b\x0e-\x1f]/.test(text)
49
+ } catch { return false }
50
+ }
@@ -0,0 +1,322 @@
1
+ // Materializes Git-visible source and transfers edits between independent worktrees.
2
+ import { constants } from 'node:fs'
3
+ import { copyFile, cp, link, lstat, mkdir, mkdtemp, readdir, readlink, realpath, rename, rm, rmdir, symlink, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'
6
+ import { inspectGitPath, isSnapshotPath } from './git-path'
7
+ import { fileFingerprint } from './git-tree'
8
+ import { git, gitFiles } from './git'
9
+
10
+ /** Phase-owned snapshot shared by planning, agent checkouts and integration. */
11
+ export interface WorktreeBaseline {
12
+ /** Canonical Git repository root, used for registry updates and integration. */
13
+ root: string
14
+ /** Target directory relative to the root, empty when the target is the root. */
15
+ scope: string
16
+ /** Commit used to register detached worktrees, including a synthetic commit for an unborn branch. */
17
+ head: string
18
+ /** Scratch directory owned and removed by withWorktreeBaseline. */
19
+ directory: string
20
+ /** Root of the copied working files, before applying the target scope. */
21
+ source: string
22
+ /** Whether the scratch directory contains a copy of the repository's index. */
23
+ hasIndex: boolean
24
+ /** Name of the shared index file required by a split index, when present. */
25
+ sharedIndex?: string
26
+ /** Enqueue a Git registry mutation for this baseline and return its result or rejection.
27
+ * A rejected update still releases the next queued update. */
28
+ updateWorktreeRegistry: (update: () => Promise<string>) => Promise<string>
29
+ }
30
+
31
+ /** Linked checkout and scratch paths owned by the caller of createAgentWorktree. */
32
+ export interface AgentWorktree {
33
+ /** Scoped directory supplied to the agent session. */
34
+ cwd: string
35
+ /** Full checkout root used to detect changes outside the scope and unregister the checkout. */
36
+ root: string
37
+ /** Scratch parent containing the checkout. */
38
+ directory: string
39
+ }
40
+
41
+ /** Snapshot the index and Git-visible working files once before invoking a phase callback.
42
+ * runDesign uses its snapshot for the design session and integration. refactorCode takes a new
43
+ * one for planning, module work and ordered integration. The callback must await all worktree
44
+ * use and removal before settling. Capture is sequential and assumes a stable source tree.
45
+ * Returns the callback's result after scratch removal. Setup and callback failures reject, and
46
+ * a scratch removal failure takes precedence. */
47
+ export async function withWorktreeBaseline<T>(cwd: string, use: (baseline: WorktreeBaseline) => Promise<T>): Promise<T> {
48
+ const root = await realpath((await git(cwd, 'rev-parse', '--show-toplevel')).replace(/\r?\n$/, ''))
49
+ const scope = relative(root, cwd)
50
+ const directory = await temporary('baseline')
51
+ try {
52
+ const baseline = await snapshotBaseline({ root, scope, directory })
53
+ return await use(baseline)
54
+ } finally {
55
+ await rm(directory, { recursive: true, force: true })
56
+ }
57
+ }
58
+
59
+ /** Register a detached checkout, restore the frozen index if present and copy the frozen working files.
60
+ * Git skips checkout so hooks and filters cannot transform the copied files. inAgentWorktree passes
61
+ * the scoped cwd to planning, and runAgentWork fingerprints the full root before starting the agent.
62
+ * Both await removeAgentWorktree after use. Setup failures reject after attempting cleanup, and a
63
+ * cleanup failure takes precedence. */
64
+ export async function createAgentWorktree(baseline: WorktreeBaseline): Promise<AgentWorktree> {
65
+ const directory = await temporary('agent')
66
+ const root = join(directory, 'checkout')
67
+ const worktree = { cwd: join(root, baseline.scope), root, directory }
68
+ try {
69
+ await baseline.updateWorktreeRegistry(() => git(baseline.root, '-c', 'core.hooksPath=' + join(directory, 'hooks'),
70
+ 'worktree', 'add', '--detach', '--no-checkout', root, baseline.head))
71
+ } catch (cause) {
72
+ await rm(directory, { recursive: true, force: true })
73
+ throw cause
74
+ }
75
+ try {
76
+ if (baseline.hasIndex) {
77
+ const index = await gitIndexPath(root)
78
+ if (baseline.sharedIndex) {
79
+ await copyFile(join(baseline.directory, baseline.sharedIndex), join(dirname(index), baseline.sharedIndex))
80
+ }
81
+ await copyFile(join(baseline.directory, 'index'), index)
82
+ }
83
+ await cp(baseline.source, root, { recursive: true, verbatimSymlinks: true })
84
+ return worktree
85
+ } catch (cause) {
86
+ await removeAgentWorktree(baseline, worktree)
87
+ throw cause
88
+ }
89
+ }
90
+
91
+ /** Release a checkout after the session and any integration settle. Unregister it through Git
92
+ * before deleting its scratch directory. Failures reject with RESOURCE_RELEASE_FAILED and the
93
+ * original cause. runAgentWork records the cleanup failure on the step, while inAgentWorktree
94
+ * propagates it to planning. */
95
+ export async function removeAgentWorktree(baseline: WorktreeBaseline, worktree: AgentWorktree): Promise<void> {
96
+ try {
97
+ await baseline.updateWorktreeRegistry(() => git(baseline.root, 'worktree', 'remove', '--force', worktree.root))
98
+ await rm(worktree.directory, { recursive: true, force: true })
99
+ } catch (cause) {
100
+ throw Object.assign(new Error(`Could not remove refactor worktree at ${worktree.root}`, { cause }), {
101
+ code: 'RESOURCE_RELEASE_FAILED',
102
+ })
103
+ }
104
+ }
105
+
106
+ /** Copy installed dependencies for validation. Preserve local workspace links within the checkout. */
107
+ export async function prepareCheckDependencies(baseline: WorktreeBaseline, worktree: AgentWorktree): Promise<void> {
108
+ const directories = ['']
109
+ for (const directory of directories) {
110
+ for (const entry of await readdir(join(baseline.source, directory), { withFileTypes: true })) {
111
+ if (entry.isDirectory() && entry.name !== 'node_modules') directories.push(join(directory, entry.name))
112
+ }
113
+ const modulePath = join(directory, 'node_modules')
114
+ const from = join(baseline.root, modulePath)
115
+ const to = join(worktree.root, modulePath)
116
+ const installed = await lstat(from).catch((cause: NodeJS.ErrnoException) => {
117
+ if (cause.code !== 'ENOENT') throw cause
118
+ })
119
+ if (!installed) continue
120
+ if (installed.isSymbolicLink()) {
121
+ const resolved = await realpath(from)
122
+ const rebased = rebaseDependencyLink(resolved, baseline.root, worktree.root)
123
+ if (rebased !== resolved && rebased !== worktree.root) {
124
+ const local = relative(worktree.root, rebased).split(sep).join('/')
125
+ const { info, linkedAncestor } = await inspectGitPath(worktree.root, local)
126
+ if (linkedAncestor || (info && !info.isDirectory())) throw new Error(`Invalid dependency target: ${local}`)
127
+ if (!info) {
128
+ await mkdir(dirname(rebased), { recursive: true })
129
+ await copyDependencies(resolved, rebased, baseline.root, worktree.root)
130
+ }
131
+ }
132
+ await mkdir(dirname(to), { recursive: true })
133
+ const copied = await lstat(to).catch((cause: NodeJS.ErrnoException) => {
134
+ if (cause.code !== 'ENOENT') throw cause
135
+ })
136
+ if (copied?.isSymbolicLink()) await rm(to)
137
+ await symlink(rebased, to, 'junction')
138
+ } else if (installed.isDirectory()) {
139
+ await copyDependencies(from, to, baseline.root, worktree.root)
140
+ }
141
+ }
142
+ }
143
+
144
+ async function copyDependencies(from: string, to: string, sourceRoot: string, targetRoot: string): Promise<void> {
145
+ await cp(from, to, { recursive: true, verbatimSymlinks: true, mode: constants.COPYFILE_FICLONE })
146
+ await rebaseDependencyLinks(to, sourceRoot, targetRoot)
147
+ }
148
+
149
+ async function rebaseDependencyLinks(directory: string, source: string, target: string): Promise<void> {
150
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
151
+ const path = join(directory, entry.name)
152
+ if (entry.isDirectory()) await rebaseDependencyLinks(path, source, target)
153
+ else if (entry.isSymbolicLink()) {
154
+ const link = await readlink(path)
155
+ if (!isAbsolute(link)) continue
156
+ const absolute = await realpath(path).catch((cause: NodeJS.ErrnoException) => {
157
+ if (cause.code !== 'ENOENT' && cause.code !== 'ELOOP') throw cause
158
+ return link
159
+ })
160
+ const rebased = rebaseDependencyLink(absolute, source, target)
161
+ if (rebased === absolute) continue
162
+ await rm(path)
163
+ await symlink(rebased, path)
164
+ }
165
+ }
166
+ }
167
+
168
+ function rebaseDependencyLink(link: string, source: string, target: string): string {
169
+ const inside = relative(source, link)
170
+ return inside === '..' || inside.startsWith('..' + sep) || isAbsolute(inside) ? link : join(target, inside)
171
+ }
172
+
173
+ /** Transfer verified files directly from a live checkout. The caller serializes integration.
174
+ * Check every destination against its baseline before writing. Stage replacement contents on
175
+ * the target filesystem and back up originals so a failed transfer can roll back. */
176
+ export async function mergeWorktree(
177
+ baseline: WorktreeBaseline, worktree: AgentWorktree, files: readonly string[],
178
+ ): Promise<void> {
179
+ const target = join(baseline.root, baseline.scope)
180
+ const original = join(baseline.source, baseline.scope)
181
+ const entries = await Promise.all(files.map(async file => {
182
+ const before = await inspectGitPath(target, file)
183
+ const expected = await fileFingerprint(original, file)
184
+ if (await fileFingerprint(target, file) !== expected) {
185
+ throw new Error(`Source changed during refactor: ${file}`)
186
+ }
187
+ const after = await inspectGitPath(worktree.cwd, file)
188
+ if (after.linkedAncestor || (after.info && !after.info.isFile()) || (before.info && !before.info.isFile())) {
189
+ throw new Error(`Refactor merge requires regular files: ${file}`)
190
+ }
191
+ return { file, path: before.path, expected, replacement: !!after.info }
192
+ }))
193
+
194
+ const directory = await mkdtemp(join(target, '.anureo', 'refactor', 'merge-'))
195
+ const staged = join(directory, 'staged')
196
+ const backups = join(directory, 'backups')
197
+ const applied: { path: string; backup?: string; installed: boolean }[] = []
198
+ const createdDirectories: string[] = []
199
+ let keepRecovery = false
200
+ try {
201
+ for (const entry of entries) {
202
+ if (entry.replacement) await copyEntry(worktree.cwd, staged, entry.file)
203
+ }
204
+ for (const entry of entries) {
205
+ if (await fileFingerprint(target, entry.file) !== entry.expected) {
206
+ throw new Error(`Source changed during refactor: ${entry.file}`)
207
+ }
208
+ const backup = entry.expected !== undefined ? join(backups, entry.file) : undefined
209
+ if (backup) {
210
+ await mkdir(dirname(backup), { recursive: true })
211
+ await rename(entry.path, backup)
212
+ }
213
+ const write = { path: entry.path, backup, installed: false }
214
+ applied.push(write)
215
+ if (backup && await fileFingerprint(backups, entry.file) !== entry.expected) {
216
+ throw new Error(`Source changed during refactor: ${entry.file}`)
217
+ }
218
+ if (entry.replacement) {
219
+ const parent = dirname(entry.path)
220
+ const firstCreated = await mkdir(parent, { recursive: true })
221
+ if (firstCreated) {
222
+ for (let path = parent; path !== dirname(firstCreated); path = dirname(path)) createdDirectories.push(path)
223
+ }
224
+ await link(join(staged, entry.file), entry.path)
225
+ write.installed = true
226
+ }
227
+ }
228
+ } catch (cause) {
229
+ try {
230
+ for (let index = applied.length - 1; index >= 0; index--) {
231
+ const entry = applied[index]!
232
+ if (entry.backup) await rename(entry.backup, entry.path)
233
+ else if (entry.installed) await rm(entry.path, { force: true })
234
+ }
235
+ for (const path of [...new Set(createdDirectories)].sort((a, b) => b.length - a.length)) {
236
+ await rmdir(path)
237
+ }
238
+ } catch (rollbackError) {
239
+ keepRecovery = true
240
+ throw Object.assign(new AggregateError([cause, rollbackError], `Could not roll back refactor merge. Recovery files: ${directory}`), {
241
+ code: 'RESOURCE_RELEASE_FAILED',
242
+ })
243
+ }
244
+ throw cause
245
+ } finally {
246
+ if (!keepRecovery) await rm(directory, { recursive: true, force: true })
247
+ }
248
+ }
249
+
250
+ /** Allocate a scratch directory under the canonical temporary root. Callers own removal. */
251
+ async function temporary(kind: 'baseline' | 'agent'): Promise<string> {
252
+ return mkdtemp(join(await realpath(tmpdir()), `anureo-refactor-${kind}-`))
253
+ }
254
+
255
+ /** Populate the caller-owned scratch directory before exposing the baseline. Capture the index
256
+ * before walking the working files, preserving Git's tracked and unignored untracked view.
257
+ * Filesystem and Git failures reject so withWorktreeBaseline can remove partial snapshots. */
258
+ async function snapshotBaseline({ root, scope, directory }: Pick<WorktreeBaseline, 'root' | 'scope' | 'directory'>): Promise<WorktreeBaseline> {
259
+ const source = join(directory, 'source')
260
+ await mkdir(join(source, scope), { recursive: true })
261
+ const head = await baselineHead(root, directory)
262
+ const index = await gitIndexPath(root)
263
+ const hasIndex = await copyFile(index, join(directory, 'index')).then(() => true, (error: NodeJS.ErrnoException) => {
264
+ if (error.code === 'ENOENT') return false
265
+ throw error
266
+ })
267
+ const sharedPath = hasIndex ? (await git(root, 'rev-parse', '--path-format=absolute', '--shared-index-path')).replace(/\r?\n$/, '') : ''
268
+ const sharedIndex = sharedPath ? basename(sharedPath) : undefined
269
+ if (sharedIndex) await copyFile(sharedPath, join(directory, sharedIndex))
270
+ for (const file of await gitFiles(root)) {
271
+ if (isSnapshotPath(file)) await copyEntry(root, source, file)
272
+ }
273
+ return { root, scope, head, directory, source, hasIndex, sharedIndex, updateWorktreeRegistry: createRegistryQueue() }
274
+ }
275
+
276
+ /** Resolve the index for the specific checkout, since linked worktrees have their own index paths.
277
+ * Git failures reject. */
278
+ async function gitIndexPath(cwd: string): Promise<string> {
279
+ return (await git(cwd, 'rev-parse', '--path-format=absolute', '--git-path', 'index')).replace(/\r?\n$/, '')
280
+ }
281
+
282
+ /** Serialize worktree add and remove callbacks within one baseline. Give each caller its own
283
+ * outcome while allowing later registry operations to proceed after a rejection. */
284
+ function createRegistryQueue(): WorktreeBaseline['updateWorktreeRegistry'] {
285
+ let registryReady = Promise.resolve()
286
+ return update => {
287
+ const result = registryReady.then(update)
288
+ registryReady = result.then(() => {}, () => {})
289
+ return result
290
+ }
291
+ }
292
+
293
+ /** Resolve HEAD for snapshotBaseline. If Git reports it missing, write an empty tree and a
294
+ * synthetic commit to the repository object store so linked checkouts can detach at a commit.
295
+ * Ref pointers stay in place. Other Git and filesystem failures reject. */
296
+ async function baselineHead(root: string, directory: string): Promise<string> {
297
+ try {
298
+ return (await git(root, 'rev-parse', '--verify', '--quiet', 'HEAD')).trim()
299
+ } catch (cause) {
300
+ if ((cause as { code?: unknown }).code !== 1) throw cause
301
+ }
302
+ const empty = join(directory, 'empty')
303
+ await writeFile(empty, '')
304
+ const tree = (await git(root, 'hash-object', '-w', '-t', 'tree', empty)).trim()
305
+ return (await git(root, '-c', 'user.name=Anureo', '-c', 'user.email=anureo@localhost',
306
+ '-c', 'commit.gpgSign=false', 'commit-tree', tree, '-m', 'Empty refactor baseline')).trim()
307
+ }
308
+
309
+ /** Copy a Git path into a caller-owned staging tree, skipping missing entries so deletions stay
310
+ * visible. Preserve final symlink text and represent directory entries without recursing into
311
+ * submodules. Linked ancestors, unsupported entry types and filesystem failures reject. */
312
+ async function copyEntry(from: string, to: string, file: string): Promise<void> {
313
+ const { path, info, linkedAncestor } = await inspectGitPath(from, file)
314
+ if (linkedAncestor) throw new Error(`Symlink ancestors are unsupported: ${file}`)
315
+ if (!info) return
316
+ const destination = join(to, file)
317
+ await mkdir(dirname(destination), { recursive: true })
318
+ if (info.isFile()) await copyFile(path, destination)
319
+ else if (info.isSymbolicLink()) await symlink(await readlink(path), destination)
320
+ else if (info.isDirectory()) await mkdir(destination, { recursive: true, mode: info.mode })
321
+ else throw new Error(`Unsupported Git path: ${file}`)
322
+ }