@anureo/refactor 0.0.0-stage → 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.
package/src/results.ts ADDED
@@ -0,0 +1,81 @@
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
+ /** Legacy report field containing the path to a historical patch artifact. */
28
+ patch?: string
29
+ /** Executed checks in command order; a failure stops subsequent checks. */
30
+ checks: CheckResult[]
31
+ /** Display text for the caught step error, or null when no error was caught. */
32
+ error: string | null
33
+ /** Classification of the first caught step error, with later cleanup failures merged in. */
34
+ failure: Failure | null
35
+ }
36
+ /** Planned module and its step record, paired in plan order before any module starts. */
37
+ export interface ModuleResult {
38
+ module: RefactorModule
39
+ /** Null until the worktree has finished validation, integration and cleanup. */
40
+ step: StepResult | null
41
+ }
42
+ /** Graph availability and declaration coverage for one phase's source inventory. */
43
+ export interface GraphCoverage {
44
+ phase: string
45
+ status: 'available' | 'unavailable' | 'disabled'
46
+ /** Paths with no indexed declarations, or the entire source inventory when no graph was available.
47
+ * Indexed files can still have unresolved relationships. */
48
+ filesWithoutSymbols: string[]
49
+ /** Export error text when graph data is unavailable. */
50
+ error?: string
51
+ }
52
+ /** Outcome returned by refactorCode after final publication and writer-lock release. During the
53
+ * run, report.json is updated at checkpoints and onProgress receives event strings. An incomplete
54
+ * report can include edits already applied to the target. The caller still owns the SDK client. */
55
+ export interface RefactorReport {
56
+ /** UUID allocated after writer-lock acquisition, also used as the run directory name. */
57
+ runId: string
58
+ /** Canonical target directory, which may be a subdirectory of a Git repository. */
59
+ cwd: string
60
+ /** Absolute storage directory for this run's reports, graphs and baseline. */
61
+ directory: string
62
+ /** Completed means every phase returned successfully; deferred work may still be listed. */
63
+ status: 'completed' | 'incomplete'
64
+ /** Agents were asked to avoid edits and host validation commands were disabled. */
65
+ reviewOnly: boolean
66
+ /** Cross-module design step, run before modules are planned. */
67
+ design: StepResult | null
68
+ /** Validated module assignments, or null until planning succeeds. */
69
+ plan: ModulePlan | null
70
+ /** Module records in plan order. Successful edits merge in readiness order. */
71
+ modules: ModuleResult[]
72
+ /** Graph availability and file coverage for the exports attempted during the run. */
73
+ graphCoverage: GraphCoverage[]
74
+ /** Run-level diagnostics. Consult each failed StepResult for its own error. */
75
+ errors: string[]
76
+ /** Classification of the run-level error, or null when none was caught. A failed-step gate
77
+ * throws a new error, so inspect the failed step for its original signals. */
78
+ failure: Failure | null
79
+ /** Display text for synchronous observer exceptions that were successfully converted, in delivery order. */
80
+ progressErrors: string[]
81
+ }
@@ -0,0 +1,117 @@
1
+ // Owns run identity, progress delivery and the lifetime of the per-target writer lock.
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdir, open, rm } from 'node:fs/promises'
4
+ import type { FileHandle } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { failure, message } from './errors'
7
+ import type { RefactorOptions } from './options'
8
+ import { saveReport } from './report-store'
9
+ import type { RefactorReport } from './results'
10
+
11
+ /** Run the phases supplied by refactorCode under the target's writer lock.
12
+ * refactorCode supplies a canonical Git target. Its caller owns the SDK client.
13
+ * Directory setup and phase failures usually produce an incomplete report. Synchronous
14
+ * observer errors are recorded separately. Error conversion itself can throw.
15
+ * Resolves after publishing the final report, closing the lock handle and removing the lock path.
16
+ * Acquisition, report initialization, final publication and lock cleanup failures reject.
17
+ * Report initialization precedes the cleanup guard, so an initialization failure can leave the lock. */
18
+ export async function withRun(options: RefactorOptions & { cwd: string }, body: RunBody): Promise<RefactorReport> {
19
+ const writer = await acquireWriter(options.cwd)
20
+ const report = createReport(options, writer.root)
21
+ try {
22
+ await executeRun(options, report, body)
23
+ } finally {
24
+ await finalizeRun(report, writer)
25
+ }
26
+ return report
27
+ }
28
+
29
+ /** Resources owned by withRun after exclusive acquisition; the handle closes before path removal. */
30
+ interface RunWriter {
31
+ root: string
32
+ lockPath: string
33
+ lock: FileHandle
34
+ }
35
+
36
+ /** refactorCode supplies the design, planning and module phases as this callback. executeRun
37
+ * invokes it after creating the directory and delivering the run event. The callback can update
38
+ * the report, emit progress and publish intermediate checkpoints. Its settlement determines run
39
+ * status. withRun owns final publication and lock release. */
40
+ type RunBody = (report: RefactorReport, progress: (event: string) => void) => Promise<void>
41
+
42
+ /** Create the storage root and acquire exclusive ownership for withRun before allocating a run ID.
43
+ * Returns the open lock and its paths, transferring cleanup to withRun. Root creation errors
44
+ * propagate. Any open failure rejects with the lock diagnostic and leaves any existing lock alone. */
45
+ async function acquireWriter(cwd: string): Promise<RunWriter> {
46
+ const root = join(cwd, '.anureo', 'refactor')
47
+ await mkdir(root, { recursive: true })
48
+ const lockPath = join(root, 'writer.lock')
49
+ const lock = await open(lockPath, 'wx').catch(() => {
50
+ throw new Error(`Cannot acquire refactor lock: ${lockPath}. Check for an active run before removing a stale lock.`)
51
+ })
52
+ return { root, lockPath, lock }
53
+ }
54
+
55
+ /** Allocate the initial incomplete record for a locked run without creating its directory.
56
+ * withRun calls this after acquisition. UUID generation can throw. */
57
+ function createReport(options: RefactorOptions, root: string): RefactorReport {
58
+ const runId = randomUUID()
59
+ return {
60
+ runId,
61
+ cwd: options.cwd,
62
+ directory: join(root, runId),
63
+ status: 'incomplete',
64
+ reviewOnly: options.reviewOnly ?? false,
65
+ design: null,
66
+ plan: null,
67
+ modules: [],
68
+ graphCoverage: [],
69
+ errors: [],
70
+ failure: null,
71
+ progressErrors: [],
72
+ }
73
+ }
74
+
75
+ /** Create this run's directory and await orchestration, recording setup/body failures in report.
76
+ * Called by withRun while locked; progress precedes body dispatch and completion follows it.
77
+ * Ordinary setup/body errors are stored instead of rejecting; error conversion can still throw. */
78
+ async function executeRun(options: RefactorOptions, report: RefactorReport, body: RunBody): Promise<void> {
79
+ const progress = createProgressReporter(options, report)
80
+ try {
81
+ await mkdir(report.directory)
82
+ progress(`run: ${report.directory}`)
83
+ await body(report, progress)
84
+ report.status = 'completed'
85
+ } catch (cause) {
86
+ report.errors.push(message(cause))
87
+ report.failure = failure(cause)
88
+ }
89
+ }
90
+
91
+ /** Give executeRun and its phase callback a synchronous progress function for this report.
92
+ * refactorCode supplies the observer through options. Record thrown observer errors so a failed
93
+ * display sink does not stop work. Observer return values are ignored. Error conversion can throw. */
94
+ function createProgressReporter(options: RefactorOptions, report: RefactorReport): (event: string) => void {
95
+ return event => {
96
+ try {
97
+ options.onProgress?.(event)
98
+ } catch (cause) {
99
+ report.progressErrors.push(message(cause))
100
+ }
101
+ }
102
+ }
103
+
104
+ /** Publish the final snapshot, then attempt both lock-release operations for withRun.
105
+ * Publication stays under the lock so another writer cannot start before the snapshot attempt.
106
+ * Removal errors take precedence over close errors, which take precedence over publication errors. */
107
+ async function finalizeRun(report: RefactorReport, writer: RunWriter): Promise<void> {
108
+ try {
109
+ await saveReport(report)
110
+ } finally {
111
+ try {
112
+ await writer.lock.close()
113
+ } finally {
114
+ await rm(writer.lockPath)
115
+ }
116
+ }
117
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { z } from 'zod'
2
+
3
+ /**
4
+ * Describe the required planning response for the workflow agent called by plan in refactor.ts.
5
+ * All strings, the module list and each file list must be nonempty. Parsing preserves whitespace
6
+ * and rejects unknown fields in the response and its modules. plan passes the parsed response
7
+ * to validatePlan for ID safety and exact inventory coverage before prepareModules can publish it.
8
+ */
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
+
21
+ /**
22
+ * Describe the required design and module responses for the workflow agent called by runAgentWork.
23
+ * Parsing preserves whitespace in nonempty strings, accepts empty change and deferral lists, and
24
+ * rejects unknown fields in the response and its deferrals. runAgentWork copies valid responses
25
+ * into its step result and records a failed step when agent validation rejects.
26
+ */
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
+
35
+ /** Read the planner's summary and validated assignments from RefactorReport.plan.
36
+ * Modules appear in the order the planner supplied and the host uses that order for integration.
37
+ * Constructing this type performs no validation. */
38
+ export type ModulePlan = z.infer<typeof modulePlanSchema>
39
+
40
+ /** Read a planned module from the report's plan or a ModuleResult. Its ID identifies the module in
41
+ * progress events and reports. Its file list describes the original assignment. Use
42
+ * StepResult.changedFiles for the paths the host observed the agent change. */
43
+ export type RefactorModule = ModulePlan['modules'][number]
44
+
45
+ /** Read an agent's summary, reported changes or proposals, and deferred findings on a StepResult.
46
+ * Use the step's status, changed files and check results for host-observed outcomes.
47
+ * Empty change and deferral lists are valid. */
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 } 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 dependency, build, documentation and run artifacts from the editable scope. */
31
+ const excluded = new Set(['.git', '.anureo', '.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 file.split('/').some(part => excluded.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,287 @@
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 { 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
+ /** Enqueue a Git registry mutation for this baseline and return its result or rejection.
25
+ * A rejected update still releases the next queued update. */
26
+ updateWorktreeRegistry: (update: () => Promise<string>) => Promise<string>
27
+ }
28
+
29
+ /** Linked checkout and scratch paths owned by the caller of createAgentWorktree. */
30
+ export interface AgentWorktree {
31
+ /** Scoped directory supplied to the agent session. */
32
+ cwd: string
33
+ /** Full checkout root used to detect changes outside the scope and unregister the checkout. */
34
+ root: string
35
+ /** Scratch parent containing the checkout. */
36
+ directory: string
37
+ }
38
+
39
+ /** Snapshot the index and Git-visible working files once before invoking a phase callback.
40
+ * runDesign uses its snapshot for the design session and integration. refactorCode takes a new
41
+ * one for planning, module work and ordered integration. The callback must await all worktree
42
+ * use and removal before settling. Capture is sequential and assumes a stable source tree.
43
+ * Returns the callback's result after scratch removal. Setup and callback failures reject, and
44
+ * a scratch removal failure takes precedence. */
45
+ export async function withWorktreeBaseline<T>(cwd: string, use: (baseline: WorktreeBaseline) => Promise<T>): Promise<T> {
46
+ const root = await realpath((await git(cwd, 'rev-parse', '--show-toplevel')).replace(/\r?\n$/, ''))
47
+ const scope = relative(root, cwd)
48
+ const directory = await temporary('baseline')
49
+ try {
50
+ const baseline = await snapshotBaseline({ root, scope, directory })
51
+ return await use(baseline)
52
+ } finally {
53
+ await rm(directory, { recursive: true, force: true })
54
+ }
55
+ }
56
+
57
+ /** Register a detached checkout, restore the frozen index if present and copy the frozen working files.
58
+ * Git skips checkout so hooks and filters cannot transform the copied files. inAgentWorktree passes
59
+ * the scoped cwd to planning, and runAgentWork fingerprints the full root before starting the agent.
60
+ * Both await removeAgentWorktree after use. Setup failures reject after attempting cleanup, and a
61
+ * cleanup failure takes precedence. */
62
+ export async function createAgentWorktree(baseline: WorktreeBaseline): Promise<AgentWorktree> {
63
+ const directory = await temporary('agent')
64
+ const root = join(directory, 'checkout')
65
+ const worktree = { cwd: join(root, baseline.scope), root, directory }
66
+ try {
67
+ await baseline.updateWorktreeRegistry(() => git(baseline.root, '-c', 'core.hooksPath=' + join(directory, 'hooks'),
68
+ 'worktree', 'add', '--detach', '--no-checkout', root, baseline.head))
69
+ } catch (cause) {
70
+ await rm(directory, { recursive: true, force: true })
71
+ throw cause
72
+ }
73
+ try {
74
+ if (baseline.hasIndex) {
75
+ const index = await gitIndexPath(root)
76
+ await copyFile(join(baseline.directory, 'index'), index)
77
+ }
78
+ await cp(baseline.source, root, { recursive: true, verbatimSymlinks: true })
79
+ return worktree
80
+ } catch (cause) {
81
+ await removeAgentWorktree(baseline, worktree)
82
+ throw cause
83
+ }
84
+ }
85
+
86
+ /** Release a checkout after the session and any integration settle. Unregister it through Git
87
+ * before deleting its scratch directory. Failures reject with RESOURCE_RELEASE_FAILED and the
88
+ * original cause. runAgentWork records the cleanup failure on the step, while inAgentWorktree
89
+ * propagates it to planning. */
90
+ export async function removeAgentWorktree(baseline: WorktreeBaseline, worktree: AgentWorktree): Promise<void> {
91
+ try {
92
+ await baseline.updateWorktreeRegistry(() => git(baseline.root, 'worktree', 'remove', '--force', worktree.root))
93
+ await rm(worktree.directory, { recursive: true, force: true })
94
+ } catch (cause) {
95
+ throw Object.assign(new Error(`Could not remove refactor worktree at ${worktree.root}`, { cause }), {
96
+ code: 'RESOURCE_RELEASE_FAILED',
97
+ })
98
+ }
99
+ }
100
+
101
+ /** Copy installed dependencies for validation. Preserve local workspace links within the checkout. */
102
+ export async function prepareCheckDependencies(baseline: WorktreeBaseline, worktree: AgentWorktree): Promise<void> {
103
+ const directories = ['']
104
+ for (const directory of directories) {
105
+ for (const entry of await readdir(join(baseline.source, directory), { withFileTypes: true })) {
106
+ if (entry.isDirectory() && entry.name !== 'node_modules') directories.push(join(directory, entry.name))
107
+ }
108
+ const modulePath = join(directory, 'node_modules')
109
+ const from = join(baseline.root, modulePath)
110
+ const to = join(worktree.root, modulePath)
111
+ const installed = await lstat(from).catch((cause: NodeJS.ErrnoException) => {
112
+ if (cause.code !== 'ENOENT') throw cause
113
+ })
114
+ if (!installed) continue
115
+ if (installed.isSymbolicLink()) {
116
+ await mkdir(dirname(to), { recursive: true })
117
+ await symlink(rebaseDependencyLink(await realpath(from), baseline.root, worktree.root), to, 'junction')
118
+ } else if (installed.isDirectory()) {
119
+ await cp(from, to, { recursive: true, verbatimSymlinks: true, mode: constants.COPYFILE_FICLONE })
120
+ await rebaseDependencyLinks(to, baseline.root, worktree.root)
121
+ }
122
+ }
123
+ }
124
+
125
+ async function rebaseDependencyLinks(directory: string, source: string, target: string): Promise<void> {
126
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
127
+ const path = join(directory, entry.name)
128
+ if (entry.isDirectory()) await rebaseDependencyLinks(path, source, target)
129
+ else if (entry.isSymbolicLink()) {
130
+ const link = await readlink(path)
131
+ if (!isAbsolute(link)) continue
132
+ const absolute = await realpath(path).catch((cause: NodeJS.ErrnoException) => {
133
+ if (cause.code !== 'ENOENT' && cause.code !== 'ELOOP') throw cause
134
+ return link
135
+ })
136
+ const rebased = rebaseDependencyLink(absolute, source, target)
137
+ if (rebased === absolute) continue
138
+ await rm(path)
139
+ await symlink(rebased, path)
140
+ }
141
+ }
142
+ }
143
+
144
+ function rebaseDependencyLink(link: string, source: string, target: string): string {
145
+ const inside = relative(source, link)
146
+ return inside === '..' || inside.startsWith('..' + sep) || isAbsolute(inside) ? link : join(target, inside)
147
+ }
148
+
149
+ /** Transfer verified files directly from a live checkout. The caller serializes integration.
150
+ * Check every destination against its baseline before writing. Stage replacement contents on
151
+ * the target filesystem and back up originals so a failed transfer can roll back. */
152
+ export async function mergeWorktree(
153
+ baseline: WorktreeBaseline, worktree: AgentWorktree, files: readonly string[],
154
+ ): Promise<void> {
155
+ const target = join(baseline.root, baseline.scope)
156
+ const original = join(baseline.source, baseline.scope)
157
+ const entries = await Promise.all(files.map(async file => {
158
+ const before = await inspectGitPath(target, file)
159
+ if (await fileFingerprint(target, file) !== await fileFingerprint(original, file)) {
160
+ throw new Error(`Source changed during refactor: ${file}`)
161
+ }
162
+ const after = await inspectGitPath(worktree.cwd, file)
163
+ if (after.linkedAncestor || (after.info && !after.info.isFile()) || (before.info && !before.info.isFile())) {
164
+ throw new Error(`Refactor merge requires regular files: ${file}`)
165
+ }
166
+ return { file, path: before.path, existed: !!before.info, replacement: !!after.info }
167
+ }))
168
+
169
+ const directory = await mkdtemp(join(target, '.anureo', 'refactor', 'merge-'))
170
+ const staged = join(directory, 'staged')
171
+ const applied: { path: string; backup?: string; installed: boolean }[] = []
172
+ const createdDirectories: string[] = []
173
+ let keepRecovery = false
174
+ try {
175
+ for (const entry of entries) {
176
+ if (entry.replacement) await copyEntry(worktree.cwd, staged, entry.file)
177
+ }
178
+ for (const [index, entry] of entries.entries()) {
179
+ if (await fileFingerprint(target, entry.file) !== await fileFingerprint(original, entry.file)) {
180
+ throw new Error(`Source changed during refactor: ${entry.file}`)
181
+ }
182
+ const backup = entry.existed ? join(directory, String(index)) : undefined
183
+ if (backup) await rename(entry.path, backup)
184
+ const write = { path: entry.path, backup, installed: false }
185
+ applied.push(write)
186
+ if (entry.replacement) {
187
+ const parent = dirname(entry.path)
188
+ const firstCreated = await mkdir(parent, { recursive: true })
189
+ if (firstCreated) {
190
+ for (let path = parent; path !== dirname(firstCreated); path = dirname(path)) createdDirectories.push(path)
191
+ }
192
+ await link(join(staged, entry.file), entry.path)
193
+ write.installed = true
194
+ }
195
+ }
196
+ } catch (cause) {
197
+ try {
198
+ for (let index = applied.length - 1; index >= 0; index--) {
199
+ const entry = applied[index]!
200
+ if (entry.backup) await rename(entry.backup, entry.path)
201
+ else if (entry.installed) await rm(entry.path, { force: true })
202
+ }
203
+ for (const path of [...new Set(createdDirectories)].sort((a, b) => b.length - a.length)) {
204
+ await rmdir(path)
205
+ }
206
+ } catch (rollbackError) {
207
+ keepRecovery = true
208
+ throw Object.assign(new AggregateError([cause, rollbackError], `Could not roll back refactor merge. Recovery files: ${directory}`), {
209
+ code: 'RESOURCE_RELEASE_FAILED',
210
+ })
211
+ }
212
+ throw cause
213
+ } finally {
214
+ if (!keepRecovery) await rm(directory, { recursive: true, force: true })
215
+ }
216
+ }
217
+
218
+ /** Allocate a scratch directory under the canonical temporary root. Callers own removal. */
219
+ async function temporary(kind: 'baseline' | 'agent'): Promise<string> {
220
+ return mkdtemp(join(await realpath(tmpdir()), `anureo-refactor-${kind}-`))
221
+ }
222
+
223
+ /** Populate the caller-owned scratch directory before exposing the baseline. Capture the index
224
+ * before walking the working files, preserving Git's tracked and unignored untracked view.
225
+ * Filesystem and Git failures reject so withWorktreeBaseline can remove partial snapshots. */
226
+ async function snapshotBaseline({ root, scope, directory }: Pick<WorktreeBaseline, 'root' | 'scope' | 'directory'>): Promise<WorktreeBaseline> {
227
+ const source = join(directory, 'source')
228
+ await mkdir(join(source, scope), { recursive: true })
229
+ const head = await baselineHead(root, directory)
230
+ const index = await gitIndexPath(root)
231
+ const hasIndex = await copyFile(index, join(directory, 'index')).then(() => true, (error: NodeJS.ErrnoException) => {
232
+ if (error.code === 'ENOENT') return false
233
+ throw error
234
+ })
235
+ for (const file of await gitFiles(root)) {
236
+ if (isSnapshotPath(file)) await copyEntry(root, source, file)
237
+ }
238
+ return { root, scope, head, directory, source, hasIndex, updateWorktreeRegistry: createRegistryQueue() }
239
+ }
240
+
241
+ /** Resolve the index for the specific checkout, since linked worktrees have their own index paths.
242
+ * Git failures reject. */
243
+ async function gitIndexPath(cwd: string): Promise<string> {
244
+ return (await git(cwd, 'rev-parse', '--path-format=absolute', '--git-path', 'index')).replace(/\r?\n$/, '')
245
+ }
246
+
247
+ /** Serialize worktree add and remove callbacks within one baseline. Give each caller its own
248
+ * outcome while allowing later registry operations to proceed after a rejection. */
249
+ function createRegistryQueue(): WorktreeBaseline['updateWorktreeRegistry'] {
250
+ let registryReady = Promise.resolve()
251
+ return update => {
252
+ const result = registryReady.then(update)
253
+ registryReady = result.then(() => {}, () => {})
254
+ return result
255
+ }
256
+ }
257
+
258
+ /** Resolve HEAD for snapshotBaseline. If Git reports it missing, write an empty tree and a
259
+ * synthetic commit to the repository object store so linked checkouts can detach at a commit.
260
+ * Ref pointers stay in place. Other Git and filesystem failures reject. */
261
+ async function baselineHead(root: string, directory: string): Promise<string> {
262
+ try {
263
+ return (await git(root, 'rev-parse', '--verify', '--quiet', 'HEAD')).trim()
264
+ } catch (cause) {
265
+ if ((cause as { code?: unknown }).code !== 1) throw cause
266
+ }
267
+ const empty = join(directory, 'empty')
268
+ await writeFile(empty, '')
269
+ const tree = (await git(root, 'hash-object', '-w', '-t', 'tree', empty)).trim()
270
+ return (await git(root, '-c', 'user.name=Anureo', '-c', 'user.email=anureo@localhost',
271
+ '-c', 'commit.gpgSign=false', 'commit-tree', tree, '-m', 'Empty refactor baseline')).trim()
272
+ }
273
+
274
+ /** Copy a Git path into a caller-owned staging tree, skipping missing entries so deletions stay
275
+ * visible. Preserve final symlink text and represent directory entries without recursing into
276
+ * submodules. Linked ancestors, unsupported entry types and filesystem failures reject. */
277
+ async function copyEntry(from: string, to: string, file: string): Promise<void> {
278
+ const { path, info, linkedAncestor } = await inspectGitPath(from, file)
279
+ if (linkedAncestor) throw new Error(`Symlink ancestors are unsupported: ${file}`)
280
+ if (!info) return
281
+ const destination = join(to, file)
282
+ await mkdir(dirname(destination), { recursive: true })
283
+ if (info.isFile()) await copyFile(path, destination)
284
+ else if (info.isSymbolicLink()) await symlink(await readlink(path), destination)
285
+ else if (info.isDirectory()) await mkdir(destination, { recursive: true, mode: info.mode })
286
+ else throw new Error(`Unsupported Git path: ${file}`)
287
+ }