@anureo/refactor 0.0.0-stage → 0.3.0

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 (53) hide show
  1. package/LICENSE +201 -0
  2. package/bin/anureo-refactor.d.ts +2 -0
  3. package/bin/anureo-refactor.js +4 -0
  4. package/package.json +48 -4
  5. package/src/agent-work.d.ts +41 -0
  6. package/src/agent-work.js +131 -0
  7. package/src/checks.d.ts +26 -0
  8. package/src/checks.js +66 -0
  9. package/src/cli.d.ts +27 -0
  10. package/src/cli.js +189 -0
  11. package/src/client.d.ts +26 -0
  12. package/src/client.js +73 -0
  13. package/src/errors.d.ts +9 -0
  14. package/src/errors.js +22 -0
  15. package/src/git-path.d.ts +15 -0
  16. package/src/git-path.js +46 -0
  17. package/src/git-tree.d.ts +18 -0
  18. package/src/git-tree.js +56 -0
  19. package/src/git.d.ts +23 -0
  20. package/src/git.js +40 -0
  21. package/src/graph-artifacts.d.ts +19 -0
  22. package/src/graph-artifacts.js +58 -0
  23. package/src/graph.d.ts +47 -0
  24. package/src/graph.js +71 -0
  25. package/src/index.d.ts +11 -0
  26. package/src/index.js +4 -0
  27. package/src/options.d.ts +55 -0
  28. package/src/options.js +15 -0
  29. package/src/plan-validation.d.ts +10 -0
  30. package/src/plan-validation.js +38 -0
  31. package/src/process.d.ts +9 -0
  32. package/src/process.js +10 -0
  33. package/src/prompts.d.ts +47 -0
  34. package/src/prompts.js +256 -0
  35. package/src/refactor.d.ts +17 -0
  36. package/src/refactor.js +168 -0
  37. package/src/report-store.d.ts +9 -0
  38. package/src/report-store.js +15 -0
  39. package/src/report.d.ts +6 -0
  40. package/src/report.js +52 -0
  41. package/src/results.d.ts +80 -0
  42. package/src/results.js +0 -0
  43. package/src/run-lifecycle.d.ts +18 -0
  44. package/src/run-lifecycle.js +100 -0
  45. package/src/schema.d.ts +42 -0
  46. package/src/schema.js +31 -0
  47. package/src/source-inventory.d.ts +9 -0
  48. package/src/source-inventory.js +17 -0
  49. package/src/source-policy.d.ts +11 -0
  50. package/src/source-policy.js +56 -0
  51. package/src/worktree.d.ts +57 -0
  52. package/src/worktree.js +195 -0
  53. package/README.md +0 -3
@@ -0,0 +1,57 @@
1
+ /** Phase-owned snapshot shared by planning, agent checkouts and patch integration. */
2
+ export interface WorktreeBaseline {
3
+ /** Canonical Git repository root, used for registry updates and patch application. */
4
+ root: string;
5
+ /** Target directory relative to the root, empty when the target is the root. */
6
+ scope: string;
7
+ /** Commit used to register detached worktrees, including a synthetic commit for an unborn branch. */
8
+ head: string;
9
+ /** Scratch directory owned and removed by withWorktreeBaseline. */
10
+ directory: string;
11
+ /** Root of the copied working files, before applying the target scope. */
12
+ source: string;
13
+ /** Whether the scratch directory contains a copy of the repository's index. */
14
+ hasIndex: boolean;
15
+ /** Enqueue a Git registry mutation for this baseline and return its result or rejection.
16
+ * A rejected update still releases the next queued update. */
17
+ updateWorktreeRegistry: (update: () => Promise<string>) => Promise<string>;
18
+ }
19
+ /** Linked checkout and scratch paths owned by the caller of createAgentWorktree. */
20
+ export interface AgentWorktree {
21
+ /** Scoped directory supplied to the agent session. */
22
+ cwd: string;
23
+ /** Full checkout root used to detect changes outside the scope and unregister the checkout. */
24
+ root: string;
25
+ /** Scratch parent containing the checkout and any patch staging files. */
26
+ directory: string;
27
+ }
28
+ /** Snapshot the index and Git-visible working files once before invoking a phase callback.
29
+ * runDesign uses its snapshot for the design session and integration. refactorCode takes a new
30
+ * one for planning, module work and ordered integration. The callback must await all worktree
31
+ * use and removal before settling. Capture is sequential and assumes a stable source tree.
32
+ * Returns the callback's result after scratch removal. Setup and callback failures reject, and
33
+ * a scratch removal failure takes precedence. */
34
+ export declare function withWorktreeBaseline<T>(cwd: string, use: (baseline: WorktreeBaseline) => Promise<T>): Promise<T>;
35
+ /** Register a detached checkout, restore the frozen index if present and copy the frozen working files.
36
+ * Git skips checkout so hooks and filters cannot transform the copied files. inAgentWorktree passes
37
+ * the scoped cwd to planning, and runAgentWork fingerprints the full root before starting the agent.
38
+ * Both await removeAgentWorktree after use. Setup failures reject after attempting cleanup, and a
39
+ * cleanup failure takes precedence. */
40
+ export declare function createAgentWorktree(baseline: WorktreeBaseline): Promise<AgentWorktree>;
41
+ /** Release a checkout after the session and any patch capture settle. Unregister it through Git
42
+ * before deleting its scratch directory. Failures reject with RESOURCE_RELEASE_FAILED and the
43
+ * original cause. runAgentWork records the cleanup failure on the step, while inAgentWorktree
44
+ * propagates it to planning. */
45
+ export declare function removeAgentWorktree(baseline: WorktreeBaseline, worktree: AgentWorktree): Promise<void>;
46
+ /** Compare only the supplied scope-relative paths against the frozen baseline and return Git patch bytes.
47
+ * For observed edits in edit mode, runAgentWork persists those bytes before removing the checkout,
48
+ * even if the agent failed.
49
+ * Requires a fresh checkout scratch directory for the before/after trees. Copy/diff failures and
50
+ * empty output reject. The caller owns scratch cleanup through removeAgentWorktree. */
51
+ export declare function captureWorktreePatch(baseline: WorktreeBaseline, worktree: AgentWorktree, files: readonly string[]): Promise<Buffer>;
52
+ /** Apply a saved patch to the scoped working files after checking the supplied paths against the
53
+ * baseline, including ignored local paths. The caller must pair the patch with its observed path
54
+ * list and coordinate writers through the check and apply. Fingerprint errors, mismatches and
55
+ * Git failures reject. integrateAgentWork records failures on the step and only runs checks after
56
+ * a successful apply to a successful step. */
57
+ export declare function applyWorktreePatch(baseline: WorktreeBaseline, files: readonly string[], patchPath: string): Promise<void>;
@@ -0,0 +1,195 @@
1
+ // Materializes Git-visible source and transfers edits between independent worktrees.
2
+ import { copyFile, cp, mkdir, mkdtemp, readlink, realpath, rm, symlink, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join, relative, sep } from 'node:path';
5
+ import { inspectGitPath, isSnapshotPath } from "./git-path.js";
6
+ import { fileFingerprint } from "./git-tree.js";
7
+ import { git, gitFiles, gitProcessOptions } from "./git.js";
8
+ import { exec } from "./process.js";
9
+ /** Snapshot the index and Git-visible working files once before invoking a phase callback.
10
+ * runDesign uses its snapshot for the design session and integration. refactorCode takes a new
11
+ * one for planning, module work and ordered integration. The callback must await all worktree
12
+ * use and removal before settling. Capture is sequential and assumes a stable source tree.
13
+ * Returns the callback's result after scratch removal. Setup and callback failures reject, and
14
+ * a scratch removal failure takes precedence. */
15
+ export async function withWorktreeBaseline(cwd, use) {
16
+ const root = await realpath((await git(cwd, 'rev-parse', '--show-toplevel')).replace(/\r?\n$/, ''));
17
+ const scope = relative(root, cwd);
18
+ const directory = await temporary('baseline');
19
+ try {
20
+ const baseline = await snapshotBaseline({ root, scope, directory });
21
+ return await use(baseline);
22
+ }
23
+ finally {
24
+ await rm(directory, { recursive: true, force: true });
25
+ }
26
+ }
27
+ /** Register a detached checkout, restore the frozen index if present and copy the frozen working files.
28
+ * Git skips checkout so hooks and filters cannot transform the copied files. inAgentWorktree passes
29
+ * the scoped cwd to planning, and runAgentWork fingerprints the full root before starting the agent.
30
+ * Both await removeAgentWorktree after use. Setup failures reject after attempting cleanup, and a
31
+ * cleanup failure takes precedence. */
32
+ export async function createAgentWorktree(baseline) {
33
+ const directory = await temporary('agent');
34
+ const root = join(directory, 'checkout');
35
+ const worktree = { cwd: join(root, baseline.scope), root, directory };
36
+ try {
37
+ await baseline.updateWorktreeRegistry(() => git(baseline.root, '-c', 'core.hooksPath=' + join(directory, 'hooks'), 'worktree', 'add', '--detach', '--no-checkout', root, baseline.head));
38
+ }
39
+ catch (cause) {
40
+ await rm(directory, { recursive: true, force: true });
41
+ throw cause;
42
+ }
43
+ try {
44
+ if (baseline.hasIndex) {
45
+ const index = await gitIndexPath(root);
46
+ await copyFile(join(baseline.directory, 'index'), index);
47
+ }
48
+ await cp(baseline.source, root, { recursive: true, verbatimSymlinks: true });
49
+ return worktree;
50
+ }
51
+ catch (cause) {
52
+ await removeAgentWorktree(baseline, worktree);
53
+ throw cause;
54
+ }
55
+ }
56
+ /** Release a checkout after the session and any patch capture settle. Unregister it through Git
57
+ * before deleting its scratch directory. Failures reject with RESOURCE_RELEASE_FAILED and the
58
+ * original cause. runAgentWork records the cleanup failure on the step, while inAgentWorktree
59
+ * propagates it to planning. */
60
+ export async function removeAgentWorktree(baseline, worktree) {
61
+ try {
62
+ await baseline.updateWorktreeRegistry(() => git(baseline.root, 'worktree', 'remove', '--force', worktree.root));
63
+ await rm(worktree.directory, { recursive: true, force: true });
64
+ }
65
+ catch (cause) {
66
+ throw Object.assign(new Error(`Could not remove refactor worktree at ${worktree.root}`, { cause }), {
67
+ code: 'RESOURCE_RELEASE_FAILED',
68
+ });
69
+ }
70
+ }
71
+ /** Compare only the supplied scope-relative paths against the frozen baseline and return Git patch bytes.
72
+ * For observed edits in edit mode, runAgentWork persists those bytes before removing the checkout,
73
+ * even if the agent failed.
74
+ * Requires a fresh checkout scratch directory for the before/after trees. Copy/diff failures and
75
+ * empty output reject. The caller owns scratch cleanup through removeAgentWorktree. */
76
+ export async function captureWorktreePatch(baseline, worktree, files) {
77
+ const before = join(worktree.directory, 'before');
78
+ const after = join(worktree.directory, 'after');
79
+ const source = join(baseline.source, baseline.scope);
80
+ await mkdir(before);
81
+ await mkdir(after);
82
+ for (const file of files) {
83
+ await copyEntry(source, before, file);
84
+ await copyEntry(worktree.cwd, after, file);
85
+ }
86
+ const patch = await diffPatchTrees(worktree.directory);
87
+ if (!patch.length)
88
+ throw new Error('Git could not represent the observed worktree changes');
89
+ return patch;
90
+ }
91
+ /** Apply a saved patch to the scoped working files after checking the supplied paths against the
92
+ * baseline, including ignored local paths. The caller must pair the patch with its observed path
93
+ * list and coordinate writers through the check and apply. Fingerprint errors, mismatches and
94
+ * Git failures reject. integrateAgentWork records failures on the step and only runs checks after
95
+ * a successful apply to a successful step. */
96
+ export async function applyWorktreePatch(baseline, files, patchPath) {
97
+ const target = join(baseline.root, baseline.scope);
98
+ const source = join(baseline.source, baseline.scope);
99
+ for (const file of files) {
100
+ if (await fileFingerprint(target, file) !== await fileFingerprint(source, file)) {
101
+ throw new Error(`Source changed during refactor: ${file}`);
102
+ }
103
+ }
104
+ const scope = baseline.scope ? ['--directory=' + baseline.scope.split(sep).join('/')] : [];
105
+ await git(baseline.root, 'apply', '-p2', ...scope, '--whitespace=nowarn', patchPath);
106
+ }
107
+ /** Allocate a scratch directory under the canonical temporary root. Callers own removal. */
108
+ async function temporary(kind) {
109
+ return mkdtemp(join(await realpath(tmpdir()), `anureo-refactor-${kind}-`));
110
+ }
111
+ /** Populate the caller-owned scratch directory before exposing the baseline. Capture the index
112
+ * before walking the working files, preserving Git's tracked and unignored untracked view.
113
+ * Filesystem and Git failures reject so withWorktreeBaseline can remove partial snapshots. */
114
+ async function snapshotBaseline({ root, scope, directory }) {
115
+ const source = join(directory, 'source');
116
+ await mkdir(join(source, scope), { recursive: true });
117
+ const head = await baselineHead(root, directory);
118
+ const index = await gitIndexPath(root);
119
+ const hasIndex = await copyFile(index, join(directory, 'index')).then(() => true, (error) => {
120
+ if (error.code === 'ENOENT')
121
+ return false;
122
+ throw error;
123
+ });
124
+ for (const file of await gitFiles(root)) {
125
+ if (isSnapshotPath(file))
126
+ await copyEntry(root, source, file);
127
+ }
128
+ return { root, scope, head, directory, source, hasIndex, updateWorktreeRegistry: createRegistryQueue() };
129
+ }
130
+ /** Resolve the index for the specific checkout, since linked worktrees have their own index paths.
131
+ * Git failures reject. */
132
+ async function gitIndexPath(cwd) {
133
+ return (await git(cwd, 'rev-parse', '--path-format=absolute', '--git-path', 'index')).replace(/\r?\n$/, '');
134
+ }
135
+ /** Serialize worktree add and remove callbacks within one baseline. Give each caller its own
136
+ * outcome while allowing later registry operations to proceed after a rejection. */
137
+ function createRegistryQueue() {
138
+ let registryReady = Promise.resolve();
139
+ return update => {
140
+ const result = registryReady.then(update);
141
+ registryReady = result.then(() => { }, () => { });
142
+ return result;
143
+ };
144
+ }
145
+ /** Resolve HEAD for snapshotBaseline. If Git reports it missing, write an empty tree and a
146
+ * synthetic commit to the repository object store so linked checkouts can detach at a commit.
147
+ * Ref pointers stay in place. Other Git and filesystem failures reject. */
148
+ async function baselineHead(root, directory) {
149
+ try {
150
+ return (await git(root, 'rev-parse', '--verify', '--quiet', 'HEAD')).trim();
151
+ }
152
+ catch (cause) {
153
+ if (cause.code !== 1)
154
+ throw cause;
155
+ }
156
+ const empty = join(directory, 'empty');
157
+ await writeFile(empty, '');
158
+ const tree = (await git(root, 'hash-object', '-w', '-t', 'tree', empty)).trim();
159
+ return (await git(root, '-c', 'user.name=Anureo', '-c', 'user.email=anureo@localhost', '-c', 'commit.gpgSign=false', 'commit-tree', tree, '-m', 'Empty refactor baseline')).trim();
160
+ }
161
+ /** Copy a Git path into a caller-owned staging tree, skipping missing entries so deletions stay
162
+ * visible. Preserve final symlink text and represent directory entries without recursing into
163
+ * submodules. Linked ancestors, unsupported entry types and filesystem failures reject. */
164
+ async function copyEntry(from, to, file) {
165
+ const { path, info, linkedAncestor } = await inspectGitPath(from, file);
166
+ if (linkedAncestor)
167
+ throw new Error(`Symlink ancestors are unsupported: ${file}`);
168
+ if (!info)
169
+ return;
170
+ const destination = join(to, file);
171
+ await mkdir(dirname(destination), { recursive: true });
172
+ if (info.isFile())
173
+ await copyFile(path, destination);
174
+ else if (info.isSymbolicLink())
175
+ await symlink(await readlink(path), destination);
176
+ else if (info.isDirectory())
177
+ await mkdir(destination, { recursive: true, mode: info.mode });
178
+ else
179
+ throw new Error(`Unsupported Git path: ${file}`);
180
+ }
181
+ /** Diff the before/after trees for captureWorktreePatch. Git status 1 denotes a difference and
182
+ * returns the buffered patch bytes. Other process failures propagate. */
183
+ async function diffPatchTrees(cwd) {
184
+ try {
185
+ const { stdout } = await exec('git', ['diff', '--no-index', '--no-renames', '--no-ext-diff',
186
+ '--no-textconv', '--no-color', '--binary', '--src-prefix=a/', '--dst-prefix=b/', '--', 'before', 'after'], { ...gitProcessOptions(), cwd, encoding: 'buffer' });
187
+ return stdout;
188
+ }
189
+ catch (cause) {
190
+ const error = cause;
191
+ if (error.code === 1 && Buffer.isBuffer(error.stdout))
192
+ return error.stdout;
193
+ throw cause;
194
+ }
195
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.