@anureo/refactor 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/bin/anureo-refactor.ts +5 -0
  2. package/package.json +21 -23
  3. package/src/agent-work.ts +132 -0
  4. package/src/checks.ts +70 -0
  5. package/src/cli.ts +214 -0
  6. package/src/client.ts +91 -0
  7. package/src/errors.ts +33 -0
  8. package/src/git-path.ts +47 -0
  9. package/src/git-tree.ts +55 -0
  10. package/src/git.ts +42 -0
  11. package/src/graph-artifacts.ts +70 -0
  12. package/src/graph.ts +88 -0
  13. package/src/index.ts +12 -0
  14. package/src/options.ts +65 -0
  15. package/src/plan-validation.ts +39 -0
  16. package/src/{process.d.ts → process.ts} +4 -2
  17. package/src/{prompts.js → prompts.ts} +162 -62
  18. package/src/refactor.ts +186 -0
  19. package/src/{report-store.js → report-store.ts} +9 -7
  20. package/src/report.ts +44 -0
  21. package/src/results.ts +81 -0
  22. package/src/run-lifecycle.ts +117 -0
  23. package/src/{schema.d.ts → schema.ts} +28 -22
  24. package/src/source-inventory.ts +17 -0
  25. package/src/{source-policy.js → source-policy.ts} +31 -37
  26. package/src/worktree.ts +287 -0
  27. package/tests/agent-contract.test.ts +188 -0
  28. package/tests/cli.test.ts +313 -0
  29. package/tests/fixtures/acp.mjs +38 -0
  30. package/tests/fixtures/ahp.mjs +50 -0
  31. package/tests/fixtures/answer.mjs +15 -0
  32. package/tests/fixtures/codex.mjs +44 -0
  33. package/tests/fixtures/repograph.ts +17 -0
  34. package/tests/graph.integration.test.ts +37 -0
  35. package/tests/helpers.ts +105 -0
  36. package/tests/refactor.test.ts +437 -0
  37. package/tests/run-lifecycle.test.ts +82 -0
  38. package/tests/tree.test.ts +99 -0
  39. package/tsconfig.json +12 -0
  40. package/LICENSE +0 -201
  41. package/bin/anureo-refactor.d.ts +0 -2
  42. package/bin/anureo-refactor.js +0 -4
  43. package/src/agent-work.d.ts +0 -41
  44. package/src/agent-work.js +0 -131
  45. package/src/checks.d.ts +0 -26
  46. package/src/checks.js +0 -66
  47. package/src/cli.d.ts +0 -27
  48. package/src/cli.js +0 -189
  49. package/src/client.d.ts +0 -26
  50. package/src/client.js +0 -73
  51. package/src/errors.d.ts +0 -9
  52. package/src/errors.js +0 -22
  53. package/src/git-path.d.ts +0 -15
  54. package/src/git-path.js +0 -46
  55. package/src/git-tree.d.ts +0 -18
  56. package/src/git-tree.js +0 -56
  57. package/src/git.d.ts +0 -23
  58. package/src/git.js +0 -40
  59. package/src/graph-artifacts.d.ts +0 -19
  60. package/src/graph-artifacts.js +0 -58
  61. package/src/graph.d.ts +0 -47
  62. package/src/graph.js +0 -71
  63. package/src/index.d.ts +0 -11
  64. package/src/index.js +0 -4
  65. package/src/options.d.ts +0 -55
  66. package/src/options.js +0 -15
  67. package/src/plan-validation.d.ts +0 -10
  68. package/src/plan-validation.js +0 -38
  69. package/src/process.js +0 -10
  70. package/src/prompts.d.ts +0 -47
  71. package/src/refactor.d.ts +0 -17
  72. package/src/refactor.js +0 -168
  73. package/src/report-store.d.ts +0 -9
  74. package/src/report.d.ts +0 -6
  75. package/src/report.js +0 -52
  76. package/src/results.d.ts +0 -80
  77. package/src/results.js +0 -0
  78. package/src/run-lifecycle.d.ts +0 -18
  79. package/src/run-lifecycle.js +0 -100
  80. package/src/schema.js +0 -31
  81. package/src/source-inventory.d.ts +0 -9
  82. package/src/source-inventory.js +0 -17
  83. package/src/source-policy.d.ts +0 -11
  84. package/src/worktree.d.ts +0 -57
  85. package/src/worktree.js +0 -195
@@ -0,0 +1,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
+ }
@@ -0,0 +1,188 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { validatePlan } from '../src/plan-validation'
3
+ import { designPrompt, modulePrompt, planPrompt } from '../src/prompts'
4
+ import { plan } from './helpers'
5
+
6
+ /** Compare both prompt APIs across modes and check lists so migrating callers cannot alter instructions. */
7
+ test.each([
8
+ { readOnly: false, checks: [] },
9
+ { readOnly: false, checks: ['bun test', 'bun run typecheck'] },
10
+ { readOnly: true, checks: [] },
11
+ { readOnly: true, checks: ['bun test', 'bun run typecheck'] },
12
+ ])('named and positional prompts agree for readOnly=$readOnly checks=$checks', ({ readOnly, checks }) => {
13
+ const files = plan.modules.flatMap(module => module.files)
14
+ const module = plan.modules[0]!
15
+ const context = { graphFile: 'graph.json', version: 'snapshot', checks, mode: readOnly ? 'read-only' as const : 'edit' as const }
16
+ const prompts = [
17
+ designPrompt({ ...context, files }),
18
+ modulePrompt({ ...context, module, design: 'Reviewed boundaries' }),
19
+ ]
20
+ expect(prompts).toEqual([
21
+ designPrompt(files, context.graphFile, context.version, checks, readOnly),
22
+ modulePrompt(module, context.graphFile, context.version, checks, readOnly, 'Reviewed boundaries'),
23
+ ])
24
+ for (const prompt of prompts) {
25
+ expect(prompt).toContain(readOnly ? 'MODE: READ ONLY' : 'MODE: EDIT')
26
+ expect(prompt.includes('Validation commands:')).toBe(!readOnly && checks.length > 0)
27
+ if (!readOnly && checks.length > 0) {
28
+ expect(prompt).toContain(`Validation commands: ${JSON.stringify(checks)}. Run them before returning and fix failures.`)
29
+ }
30
+ }
31
+ })
32
+
33
+ /** Preserve the alternatives and their evidence requirements even when a graph is unavailable. */
34
+ test.each(['read-only', 'edit'] as const)('structural decisions compare keeping, consolidation and extraction in %s mode', mode => {
35
+ const context = { graphFile: null, version: 'snapshot', checks: [], mode, isolated: true }
36
+ const design = designPrompt({ ...context, files: ['api.ts', 'types.ts'] })
37
+ const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Keep the shared policy owner' })
38
+ for (const prompt of [design, module]) {
39
+ const instructions = prompt.replace(/\s+/g, ' ')
40
+ expect(instructions).toContain('compare keeping it, consolidating it into an existing owner and extracting it')
41
+ expect(instructions).toContain('Describe the current reading/editing path')
42
+ expect(instructions).toContain('Prefer an existing cohesive module before creating a new file')
43
+ expect(instructions).toContain('Preserve small modules with useful independent contracts')
44
+ expect(instructions).toContain('Keep related types with their owning feature')
45
+ expect(instructions).toContain('Set no target file count')
46
+ expect(instructions).toContain('An unchanged structure is a valid outcome')
47
+ expect(prompt.split('Optimize for the cost of understanding and changing the code.')).toHaveLength(2)
48
+ expect(prompt).toContain('Static graph unavailable.')
49
+ }
50
+ expect(design).not.toContain('Give each\n its own file')
51
+ expect(design).not.toContain('Split by group')
52
+ expect(design).toContain('Later module agents receive this summary')
53
+ expect(design).toContain('the existing layout from proposed boundaries')
54
+ expect(module).not.toContain('Extract each phase')
55
+ expect(module).toContain('Read the design summary before changing structure')
56
+ expect(module).toContain('explain any revision supported by new source evidence')
57
+ expect(module).toContain('Keep short, cohesive sequences together')
58
+ expect(module).toContain('Keep simple one-use expressions inline')
59
+ expect(module).toContain('Consolidate or split code within this module')
60
+ expect(module).toContain('Preserve the existing-file assignment')
61
+ expect(module).toContain('Edit only the files assigned to this module')
62
+ if (mode === 'read-only') expect(module).toContain('describe resulting edits as proposals')
63
+ })
64
+
65
+ /** Both editing phases receive the same audience/language policy, even when only proposing changes. */
66
+ test.each(['read-only', 'edit'] as const)('documentation guidance reaches both phases in %s mode', mode => {
67
+ const context = { graphFile: 'graph.json', version: 'snapshot', checks: [], mode }
68
+ const prompts = [
69
+ designPrompt({ ...context, files: ['api.ts', 'worker.py'] }),
70
+ modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' }),
71
+ ]
72
+ for (const prompt of prompts) {
73
+ const documentation = prompt.replace(/\s+/g, ' ')
74
+ expect(documentation).toContain('An exported declaration is not automatically a supported public API')
75
+ expect(documentation).toContain('an extension interface can be public')
76
+ expect(documentation).toContain('Lead public API comments with the consumer\'s task')
77
+ expect(documentation).toContain('a short contract can be one sentence')
78
+ expect(documentation).toContain('Select the documentation convention for each declaration from its language')
79
+ expect(documentation).toContain('In mixed-language files')
80
+ expect(documentation).toContain('Preserve the exact documentation dialect across phases and moved declarations')
81
+ expect(documentation).toContain('Record identified conventions in the summary')
82
+ expect(documentation).toContain('Examples are not a language allowlist')
83
+ expect(documentation).toContain('For any other language or DSL')
84
+ expect(documentation).toContain('ordinary native comments if no structured convention is established')
85
+ expect(documentation).toContain('Documentation tags are convention-specific, not a universal @ syntax')
86
+ expect(documentation).toContain('Do not transplant TSDoc tags or restrictions into another convention')
87
+ expect(documentation).toContain('Go uses doc comments and prose')
88
+ expect(documentation).toContain('docstrings with the project\'s Sphinx, Google or NumPy style')
89
+ expect(documentation).toContain('C# uses XML documentation')
90
+ expect(documentation).toContain('Do not infer support or release stage')
91
+ expect(documentation).toContain('Verify these claims')
92
+ expect(documentation).toContain('review comments against the final code')
93
+ expect(documentation).toContain('Record documentation changes or proposals in "changes"')
94
+ expect(documentation).toContain('concrete unresolved gaps in "deferred"')
95
+ expect(documentation).toContain('Do not claim unavailable tooling was run')
96
+ expect(documentation).toContain('Correct stale names, unsupported tags and misleading descriptions')
97
+ expect(documentation).toContain('Type annotations, braces, delimiters and tag placement must follow that exact dialect')
98
+ expect(documentation).toContain('Do not describe a returned failure as a thrown exception')
99
+ expect(documentation).toContain('A parser pass alone does not establish semantic accuracy')
100
+ expect(prompt.indexOf('Documentation conventions and tags:')).toBe(prompt.lastIndexOf('Documentation conventions and tags:'))
101
+ if (mode === 'read-only') expect(prompt).toContain('apply this review to proposed comments without editing')
102
+ }
103
+ })
104
+
105
+ /** Both phases prioritize actual API definitions while preserving executable declaration order. */
106
+ test.each(['read-only', 'edit'] as const)('declaration ordering reaches both phases in %s mode', mode => {
107
+ const context = { graphFile: 'graph.json', version: 'snapshot', checks: [], mode }
108
+ const prompts = [
109
+ designPrompt({ ...context, files: ['api.ts'] }),
110
+ modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' }),
111
+ ]
112
+ for (const prompt of prompts) {
113
+ const instructions = prompt.replace(/\s+/g, ' ')
114
+ expect(instructions).toContain('Keep license/file comments and imports at the beginning')
115
+ expect(instructions).toContain('exported types/interfaces, functions and classes before unexported implementation helpers')
116
+ expect(instructions).toContain('move the actual declaration, not just its export statement')
117
+ expect(instructions).toContain('constructor and public methods/accessors first')
118
+ expect(instructions).toContain('Include implicitly public members and static public methods')
119
+ expect(instructions).toContain('do not change visibility')
120
+ expect(instructions).toContain('Preserve overload order')
121
+ expect(instructions).toContain('field initialization order, static blocks, computed names and decorator evaluation')
122
+ expect(instructions).toContain('report the concrete constraint in "deferred"')
123
+ expect(instructions).toContain('do not skip safe ordering changes elsewhere')
124
+ expect(prompt.indexOf('Declaration order:')).toBe(prompt.lastIndexOf('Declaration order:'))
125
+ if (mode === 'read-only') expect(prompt).toContain('propose the reordering without editing files')
126
+ }
127
+ expect(prompts[0]).toContain('Apply declaration ordering to files affected by boundary changes')
128
+ expect(prompts[1]).toContain('public class methods hidden below internal implementation helpers')
129
+ })
130
+
131
+ /** Verify that phase-specific scope survives shared guidance and that isolated checks stay with the host. */
132
+ test('documentation scope is phase-specific and planning remains inventory-only', () => {
133
+ const files = ['api.ts']
134
+ const context = {
135
+ graphFile: 'graph.json', version: 'snapshot', mode: 'edit' as const, isolated: true,
136
+ checks: [{ executable: 'bun', args: ['run', 'typecheck'] }],
137
+ }
138
+ const design = designPrompt({ ...context, files })
139
+ const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Reviewed boundaries' })
140
+ expect(design).toContain('preserve contract comments on moved declarations')
141
+ expect(design).toContain('Do not perform a repository-wide comment rewrite')
142
+ expect(design).not.toContain('Module documentation scope:')
143
+ expect(module).toContain('including declarations\nwhose implementation stays unchanged')
144
+ expect(module).toContain('keep accurate concise comments without cosmetic rewrites')
145
+ expect(module).not.toContain('Design documentation scope:')
146
+ const planning = planPrompt(files, 'snapshot')
147
+ expect(planning).not.toContain('Documentation conventions and tags:')
148
+ expect(planning).toContain('cohesive review/edit task groups')
149
+ expect(planning).toContain('Keep files that require coordinated edits in the same assignment')
150
+ expect(planning).toContain('Plan against the existing inventory')
151
+ expect(planning).toContain('Assign every listed source file exactly once')
152
+ expect(planning).toContain('Do not review or edit yet')
153
+ const hostChecks = `Validation commands: ${JSON.stringify(context.checks)}. The host runs them in your worktree before merging your edits.`
154
+ for (const prompt of [design, module]) {
155
+ expect(prompt).toContain(hostChecks)
156
+ expect(prompt).not.toContain('Run them before returning')
157
+ }
158
+ expect(module).toContain('Other modules run concurrently.')
159
+ expect(design).not.toContain('Other modules run concurrently.')
160
+ })
161
+
162
+ /** Module IDs keep the existing alphabet and length boundaries, including uppercase letters and underscores. */
163
+ test.each(['a', 'A_0-module', 'a'.repeat(80)])('accepts safe module ID %s', id => {
164
+ const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
165
+ expect(() => validatePlan(candidate, ['a.ts'])).not.toThrow()
166
+ })
167
+
168
+ /** Reject path components and out-of-policy IDs before their values can reach reports. */
169
+ test.each(['', '../escape', 'a/b', 'a\\b', '_module', '-module', 'a.b', 'a b', 'a'.repeat(81)])('rejects unsafe module ID %s', id => {
170
+ const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
171
+ expect(() => validatePlan(candidate, ['a.ts'])).toThrow(`Invalid or duplicate module id: ${id}`)
172
+ })
173
+
174
+ /** Plans fail in traversal order, with omissions delayed until all explicit assignments are checked. */
175
+ test('plan validation preserves error precedence and inventory ordering', () => {
176
+ const first = plan.modules[0]!
177
+ const second = plan.modules[1]!
178
+ expect(() => validatePlan({ ...plan, modules: [first, { ...second, id: first.id, files: ['extra.ts'] }] }, ['a.ts', 'b.ts']))
179
+ .toThrow('Invalid or duplicate module id: a')
180
+ expect(() => validatePlan({ ...plan, modules: [first, { ...second, id: first.id.toUpperCase(), files: ['extra.ts'] }] }, ['a.ts', 'b.ts']))
181
+ .toThrow('Invalid or duplicate module id: A')
182
+ expect(() => validatePlan({ ...plan, modules: [{ ...first, files: ['extra.ts'] }, { ...second, id: '../unsafe' }] }, ['a.ts', 'b.ts']))
183
+ .toThrow('Unlisted or duplicate module file: extra.ts')
184
+ expect(() => validatePlan({ ...plan, modules: [first, { ...second, files: ['a.ts'] }] }, ['a.ts', 'b.ts']))
185
+ .toThrow('Unlisted or duplicate module file: a.ts')
186
+ expect(() => validatePlan({ ...plan, modules: [first] }, ['c.ts', 'a.ts', 'b.ts']))
187
+ .toThrow('Module plan omitted source files: c.ts, b.ts')
188
+ })