@anureo/refactor 0.3.1 → 0.3.7
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/package.json +37 -37
- package/src/agent-work.ts +101 -49
- package/src/checks.ts +17 -5
- package/src/client.ts +5 -3
- package/src/errors.ts +40 -3
- package/src/git.ts +20 -7
- package/src/graph-artifacts.ts +16 -13
- package/src/graph.ts +73 -16
- package/src/index.ts +29 -1
- package/src/options.ts +1 -1
- package/src/plan-validation.ts +24 -25
- package/src/prompts.ts +8 -30
- package/src/refactor.ts +25 -20
- package/src/report-store.ts +1 -1
- package/src/report.ts +34 -18
- package/src/results.ts +2 -0
- package/src/run-lifecycle.ts +44 -44
- package/src/schema.ts +1 -1
- package/src/source-policy.ts +4 -4
- package/src/worktree.ts +46 -11
- package/tests/agent-contract.test.ts +18 -26
- package/tests/cli.test.ts +79 -14
- package/tests/fixtures/codex.mjs +0 -0
- package/tests/fixtures/repograph.ts +11 -4
- package/tests/graph.integration.test.ts +83 -10
- package/tests/helpers.ts +5 -1
- package/tests/refactor.test.ts +102 -3
- package/tests/run-lifecycle.test.ts +64 -10
- package/tests/tree.test.ts +115 -4
package/src/run-lifecycle.ts
CHANGED
|
@@ -1,29 +1,36 @@
|
|
|
1
|
-
// Owns run identity, progress delivery and the lifetime of the
|
|
1
|
+
// Owns run identity, progress delivery and the lifetime of the checkout writer lock.
|
|
2
2
|
import { randomUUID } from 'node:crypto'
|
|
3
|
-
import { mkdir, open, rm } from 'node:fs/promises'
|
|
3
|
+
import { mkdir, open, realpath, rm, writeFile } from 'node:fs/promises'
|
|
4
4
|
import type { FileHandle } from 'node:fs/promises'
|
|
5
|
-
import { join } from 'node:path'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
6
|
import { failure, message } from './errors'
|
|
7
|
+
import { git } from './git'
|
|
7
8
|
import type { RefactorOptions } from './options'
|
|
8
9
|
import { saveReport } from './report-store'
|
|
9
10
|
import type { RefactorReport } from './results'
|
|
10
11
|
|
|
11
|
-
/** Run the phases supplied by refactorCode under the
|
|
12
|
-
*
|
|
13
|
-
*
|
|
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. */
|
|
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. */
|
|
18
15
|
export async function withRun(options: RefactorOptions & { cwd: string }, body: RunBody): Promise<RefactorReport> {
|
|
19
16
|
const writer = await acquireWriter(options.cwd)
|
|
20
|
-
const
|
|
17
|
+
const errors: unknown[] = []
|
|
21
18
|
try {
|
|
22
|
-
|
|
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
|
|
23
28
|
} finally {
|
|
24
|
-
await
|
|
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]
|
|
25
33
|
}
|
|
26
|
-
return report
|
|
27
34
|
}
|
|
28
35
|
|
|
29
36
|
/** Resources owned by withRun after exclusive acquisition; the handle closes before path removal. */
|
|
@@ -34,24 +41,35 @@ interface RunWriter {
|
|
|
34
41
|
}
|
|
35
42
|
|
|
36
43
|
/** refactorCode supplies the design, planning and module phases as this callback. executeRun
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* status. withRun owns final publication and lock release. */
|
|
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. */
|
|
40
46
|
type RunBody = (report: RefactorReport, progress: (event: string) => void) => Promise<void>
|
|
41
47
|
|
|
42
|
-
/**
|
|
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. */
|
|
48
|
+
/** Acquire checkout-wide ownership while keeping report storage relative to the target. */
|
|
45
49
|
async function acquireWriter(cwd: string): Promise<RunWriter> {
|
|
46
50
|
const root = join(cwd, '.anureo', 'refactor')
|
|
47
|
-
await
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
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
|
+
)
|
|
51
61
|
})
|
|
52
62
|
return { root, lockPath, lock }
|
|
53
63
|
}
|
|
54
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
|
+
|
|
55
73
|
/** Allocate the initial incomplete record for a locked run without creating its directory.
|
|
56
74
|
* withRun calls this after acquisition. UUID generation can throw. */
|
|
57
75
|
function createReport(options: RefactorOptions, root: string): RefactorReport {
|
|
@@ -72,13 +90,10 @@ function createReport(options: RefactorOptions, root: string): RefactorReport {
|
|
|
72
90
|
}
|
|
73
91
|
}
|
|
74
92
|
|
|
75
|
-
/**
|
|
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. */
|
|
93
|
+
/** Report run progress and await orchestration, recording phase failures in the report. */
|
|
78
94
|
async function executeRun(options: RefactorOptions, report: RefactorReport, body: RunBody): Promise<void> {
|
|
79
95
|
const progress = createProgressReporter(options, report)
|
|
80
96
|
try {
|
|
81
|
-
await mkdir(report.directory)
|
|
82
97
|
progress(`run: ${report.directory}`)
|
|
83
98
|
await body(report, progress)
|
|
84
99
|
report.status = 'completed'
|
|
@@ -90,7 +105,7 @@ async function executeRun(options: RefactorOptions, report: RefactorReport, body
|
|
|
90
105
|
|
|
91
106
|
/** Give executeRun and its phase callback a synchronous progress function for this report.
|
|
92
107
|
* 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.
|
|
108
|
+
* display sink does not stop work. Observer return values are ignored. */
|
|
94
109
|
function createProgressReporter(options: RefactorOptions, report: RefactorReport): (event: string) => void {
|
|
95
110
|
return event => {
|
|
96
111
|
try {
|
|
@@ -100,18 +115,3 @@ function createProgressReporter(options: RefactorOptions, report: RefactorReport
|
|
|
100
115
|
}
|
|
101
116
|
}
|
|
102
117
|
}
|
|
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
CHANGED
|
@@ -33,7 +33,7 @@ export const workSchema = z.strictObject({
|
|
|
33
33
|
})
|
|
34
34
|
|
|
35
35
|
/** Read the planner's summary and validated assignments from RefactorReport.plan.
|
|
36
|
-
* Modules
|
|
36
|
+
* Modules and report entries retain planner order. Verified edits are integrated in readiness order.
|
|
37
37
|
* Constructing this type performs no validation. */
|
|
38
38
|
export type ModulePlan = z.infer<typeof modulePlanSchema>
|
|
39
39
|
|
package/src/source-policy.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Selects the paths and text eligible for review and editing.
|
|
2
2
|
import { readFile } from 'node:fs/promises'
|
|
3
3
|
import { posix } from 'node:path'
|
|
4
|
-
import { inspectGitPath } from './git-path'
|
|
4
|
+
import { inspectGitPath, isSnapshotPath } from './git-path'
|
|
5
5
|
|
|
6
6
|
/** Match a Git-relative path against source scope rules without reading the filesystem.
|
|
7
7
|
* Built-in path exclusions and explicit exclude globs take precedence over include globs.
|
|
@@ -27,14 +27,14 @@ export async function isTextSource(cwd: string, file: string): Promise<boolean>
|
|
|
27
27
|
return isSupportedText(await readFile(path))
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
/** Exclude
|
|
31
|
-
const
|
|
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
32
|
/** Repository metadata and conventional standalone prose. Explicit includes can select these files. */
|
|
33
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
34
|
|
|
35
35
|
/** Match hard exclusions against any path component, regardless of case or glob settings. */
|
|
36
36
|
function isExcluded(file: string): boolean {
|
|
37
|
-
return file.split('/').some(part =>
|
|
37
|
+
return !isSnapshotPath(file) || file.split('/').some(part => sourceOnlyExclusions.has(part.toLowerCase()))
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
/** Default to UTF-8 unless a UTF-16 byte-order mark is present. Decode strictly so invalid
|
package/src/worktree.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { constants } from 'node:fs'
|
|
3
3
|
import { copyFile, cp, link, lstat, mkdir, mkdtemp, readdir, readlink, realpath, rename, rm, rmdir, symlink, writeFile } from 'node:fs/promises'
|
|
4
4
|
import { tmpdir } from 'node:os'
|
|
5
|
-
import { dirname, isAbsolute, join, relative, sep } from 'node:path'
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path'
|
|
6
6
|
import { inspectGitPath, isSnapshotPath } from './git-path'
|
|
7
7
|
import { fileFingerprint } from './git-tree'
|
|
8
8
|
import { git, gitFiles } from './git'
|
|
@@ -21,6 +21,8 @@ export interface WorktreeBaseline {
|
|
|
21
21
|
source: string
|
|
22
22
|
/** Whether the scratch directory contains a copy of the repository's index. */
|
|
23
23
|
hasIndex: boolean
|
|
24
|
+
/** Name of the shared index file required by a split index, when present. */
|
|
25
|
+
sharedIndex?: string
|
|
24
26
|
/** Enqueue a Git registry mutation for this baseline and return its result or rejection.
|
|
25
27
|
* A rejected update still releases the next queued update. */
|
|
26
28
|
updateWorktreeRegistry: (update: () => Promise<string>) => Promise<string>
|
|
@@ -73,6 +75,9 @@ export async function createAgentWorktree(baseline: WorktreeBaseline): Promise<A
|
|
|
73
75
|
try {
|
|
74
76
|
if (baseline.hasIndex) {
|
|
75
77
|
const index = await gitIndexPath(root)
|
|
78
|
+
if (baseline.sharedIndex) {
|
|
79
|
+
await copyFile(join(baseline.directory, baseline.sharedIndex), join(dirname(index), baseline.sharedIndex))
|
|
80
|
+
}
|
|
76
81
|
await copyFile(join(baseline.directory, 'index'), index)
|
|
77
82
|
}
|
|
78
83
|
await cp(baseline.source, root, { recursive: true, verbatimSymlinks: true })
|
|
@@ -113,15 +118,34 @@ export async function prepareCheckDependencies(baseline: WorktreeBaseline, workt
|
|
|
113
118
|
})
|
|
114
119
|
if (!installed) continue
|
|
115
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
|
+
}
|
|
116
132
|
await mkdir(dirname(to), { recursive: true })
|
|
117
|
-
|
|
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')
|
|
118
138
|
} else if (installed.isDirectory()) {
|
|
119
|
-
await
|
|
120
|
-
await rebaseDependencyLinks(to, baseline.root, worktree.root)
|
|
139
|
+
await copyDependencies(from, to, baseline.root, worktree.root)
|
|
121
140
|
}
|
|
122
141
|
}
|
|
123
142
|
}
|
|
124
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
|
+
|
|
125
149
|
async function rebaseDependencyLinks(directory: string, source: string, target: string): Promise<void> {
|
|
126
150
|
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
127
151
|
const path = join(directory, entry.name)
|
|
@@ -156,18 +180,20 @@ export async function mergeWorktree(
|
|
|
156
180
|
const original = join(baseline.source, baseline.scope)
|
|
157
181
|
const entries = await Promise.all(files.map(async file => {
|
|
158
182
|
const before = await inspectGitPath(target, file)
|
|
159
|
-
|
|
183
|
+
const expected = await fileFingerprint(original, file)
|
|
184
|
+
if (await fileFingerprint(target, file) !== expected) {
|
|
160
185
|
throw new Error(`Source changed during refactor: ${file}`)
|
|
161
186
|
}
|
|
162
187
|
const after = await inspectGitPath(worktree.cwd, file)
|
|
163
188
|
if (after.linkedAncestor || (after.info && !after.info.isFile()) || (before.info && !before.info.isFile())) {
|
|
164
189
|
throw new Error(`Refactor merge requires regular files: ${file}`)
|
|
165
190
|
}
|
|
166
|
-
return { file, path: before.path,
|
|
191
|
+
return { file, path: before.path, expected, replacement: !!after.info }
|
|
167
192
|
}))
|
|
168
193
|
|
|
169
194
|
const directory = await mkdtemp(join(target, '.anureo', 'refactor', 'merge-'))
|
|
170
195
|
const staged = join(directory, 'staged')
|
|
196
|
+
const backups = join(directory, 'backups')
|
|
171
197
|
const applied: { path: string; backup?: string; installed: boolean }[] = []
|
|
172
198
|
const createdDirectories: string[] = []
|
|
173
199
|
let keepRecovery = false
|
|
@@ -175,14 +201,20 @@ export async function mergeWorktree(
|
|
|
175
201
|
for (const entry of entries) {
|
|
176
202
|
if (entry.replacement) await copyEntry(worktree.cwd, staged, entry.file)
|
|
177
203
|
}
|
|
178
|
-
for (const
|
|
179
|
-
if (await fileFingerprint(target, entry.file) !==
|
|
204
|
+
for (const entry of entries) {
|
|
205
|
+
if (await fileFingerprint(target, entry.file) !== entry.expected) {
|
|
180
206
|
throw new Error(`Source changed during refactor: ${entry.file}`)
|
|
181
207
|
}
|
|
182
|
-
const backup = entry.
|
|
183
|
-
if (backup)
|
|
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
|
+
}
|
|
184
213
|
const write = { path: entry.path, backup, installed: false }
|
|
185
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
|
+
}
|
|
186
218
|
if (entry.replacement) {
|
|
187
219
|
const parent = dirname(entry.path)
|
|
188
220
|
const firstCreated = await mkdir(parent, { recursive: true })
|
|
@@ -232,10 +264,13 @@ async function snapshotBaseline({ root, scope, directory }: Pick<WorktreeBaselin
|
|
|
232
264
|
if (error.code === 'ENOENT') return false
|
|
233
265
|
throw error
|
|
234
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))
|
|
235
270
|
for (const file of await gitFiles(root)) {
|
|
236
271
|
if (isSnapshotPath(file)) await copyEntry(root, source, file)
|
|
237
272
|
}
|
|
238
|
-
return { root, scope, head, directory, source, hasIndex, updateWorktreeRegistry: createRegistryQueue() }
|
|
273
|
+
return { root, scope, head, directory, source, hasIndex, sharedIndex, updateWorktreeRegistry: createRegistryQueue() }
|
|
239
274
|
}
|
|
240
275
|
|
|
241
276
|
/** Resolve the index for the specific checkout, since linked worktrees have their own index paths.
|
|
@@ -3,13 +3,13 @@ import { validatePlan } from '../src/plan-validation'
|
|
|
3
3
|
import { designPrompt, modulePrompt, planPrompt } from '../src/prompts'
|
|
4
4
|
import { plan } from './helpers'
|
|
5
5
|
|
|
6
|
-
/**
|
|
6
|
+
/** Verify the runner's prompt inputs across modes and check lists. */
|
|
7
7
|
test.each([
|
|
8
8
|
{ readOnly: false, checks: [] },
|
|
9
9
|
{ readOnly: false, checks: ['bun test', 'bun run typecheck'] },
|
|
10
10
|
{ readOnly: true, checks: [] },
|
|
11
11
|
{ readOnly: true, checks: ['bun test', 'bun run typecheck'] },
|
|
12
|
-
])('
|
|
12
|
+
])('prompts describe the mode and host validation for readOnly=$readOnly checks=$checks', ({ readOnly, checks }) => {
|
|
13
13
|
const files = plan.modules.flatMap(module => module.files)
|
|
14
14
|
const module = plan.modules[0]!
|
|
15
15
|
const context = { graphFile: 'graph.json', version: 'snapshot', checks, mode: readOnly ? 'read-only' as const : 'edit' as const }
|
|
@@ -17,22 +17,18 @@ test.each([
|
|
|
17
17
|
designPrompt({ ...context, files }),
|
|
18
18
|
modulePrompt({ ...context, module, design: 'Reviewed boundaries' }),
|
|
19
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
20
|
for (const prompt of prompts) {
|
|
25
21
|
expect(prompt).toContain(readOnly ? 'MODE: READ ONLY' : 'MODE: EDIT')
|
|
26
22
|
expect(prompt.includes('Validation commands:')).toBe(!readOnly && checks.length > 0)
|
|
27
23
|
if (!readOnly && checks.length > 0) {
|
|
28
|
-
expect(prompt).toContain(`Validation commands: ${JSON.stringify(checks)}.
|
|
24
|
+
expect(prompt).toContain(`Validation commands: ${JSON.stringify(checks)}. The host runs them on the combined tree before merging your edits.`)
|
|
29
25
|
}
|
|
30
26
|
}
|
|
31
27
|
})
|
|
32
28
|
|
|
33
29
|
/** Preserve the alternatives and their evidence requirements even when a graph is unavailable. */
|
|
34
30
|
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
|
|
31
|
+
const context = { graphFile: null, version: 'snapshot', checks: [], mode }
|
|
36
32
|
const design = designPrompt({ ...context, files: ['api.ts', 'types.ts'] })
|
|
37
33
|
const module = modulePrompt({ ...context, module: plan.modules[0]!, design: 'Keep the shared policy owner' })
|
|
38
34
|
for (const prompt of [design, module]) {
|
|
@@ -128,11 +124,11 @@ test.each(['read-only', 'edit'] as const)('declaration ordering reaches both pha
|
|
|
128
124
|
expect(prompts[1]).toContain('public class methods hidden below internal implementation helpers')
|
|
129
125
|
})
|
|
130
126
|
|
|
131
|
-
/** Verify that phase-specific scope survives shared guidance and
|
|
127
|
+
/** Verify that phase-specific scope survives shared guidance and checks stay with the host. */
|
|
132
128
|
test('documentation scope is phase-specific and planning remains inventory-only', () => {
|
|
133
129
|
const files = ['api.ts']
|
|
134
130
|
const context = {
|
|
135
|
-
graphFile: 'graph.json', version: 'snapshot', mode: 'edit' as const,
|
|
131
|
+
graphFile: 'graph.json', version: 'snapshot', mode: 'edit' as const,
|
|
136
132
|
checks: [{ executable: 'bun', args: ['run', 'typecheck'] }],
|
|
137
133
|
}
|
|
138
134
|
const design = designPrompt({ ...context, files })
|
|
@@ -150,13 +146,13 @@ test('documentation scope is phase-specific and planning remains inventory-only'
|
|
|
150
146
|
expect(planning).toContain('Plan against the existing inventory')
|
|
151
147
|
expect(planning).toContain('Assign every listed source file exactly once')
|
|
152
148
|
expect(planning).toContain('Do not review or edit yet')
|
|
153
|
-
const hostChecks = `Validation commands: ${JSON.stringify(context.checks)}. The host runs them
|
|
149
|
+
const hostChecks = `Validation commands: ${JSON.stringify(context.checks)}. The host runs them on the combined tree before merging your edits.`
|
|
154
150
|
for (const prompt of [design, module]) {
|
|
155
151
|
expect(prompt).toContain(hostChecks)
|
|
156
152
|
expect(prompt).not.toContain('Run them before returning')
|
|
157
153
|
}
|
|
158
|
-
expect(module).toContain('Other modules run concurrently.')
|
|
159
|
-
expect(design).not.toContain('Other modules run concurrently.')
|
|
154
|
+
expect(module).toContain('Other modules may run concurrently.')
|
|
155
|
+
expect(design).not.toContain('Other modules may run concurrently.')
|
|
160
156
|
})
|
|
161
157
|
|
|
162
158
|
/** Module IDs keep the existing alphabet and length boundaries, including uppercase letters and underscores. */
|
|
@@ -168,21 +164,17 @@ test.each(['a', 'A_0-module', 'a'.repeat(80)])('accepts safe module ID %s', id =
|
|
|
168
164
|
/** Reject path components and out-of-policy IDs before their values can reach reports. */
|
|
169
165
|
test.each(['', '../escape', 'a/b', 'a\\b', '_module', '-module', 'a.b', 'a b', 'a'.repeat(81)])('rejects unsafe module ID %s', id => {
|
|
170
166
|
const candidate = { ...plan, modules: [{ ...plan.modules[0]!, id }] }
|
|
171
|
-
expect(() => validatePlan(candidate, ['a.ts'])).toThrow(`
|
|
167
|
+
expect(() => validatePlan(candidate, ['a.ts'])).toThrow(`modules[0].id: ${JSON.stringify(id)} must start with an ASCII letter or digit`)
|
|
172
168
|
})
|
|
173
169
|
|
|
174
|
-
|
|
175
|
-
test('plan validation preserves error precedence and inventory ordering', () => {
|
|
170
|
+
test('plan validation reports all issues in traversal and inventory order', () => {
|
|
176
171
|
const first = plan.modules[0]!
|
|
177
172
|
const second = plan.modules[1]!
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
.
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
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')
|
|
173
|
+
const candidate = { ...plan, modules: [first, { ...second, id: 'A', files: ['extra.ts', 'a.ts'] }] }
|
|
174
|
+
expect(() => validatePlan(candidate, ['c.ts', 'a.ts', 'b.ts'])).toThrow([
|
|
175
|
+
'modules[1].id: "A" duplicates modules[0].id ignoring case',
|
|
176
|
+
'modules[1].files[0]: "extra.ts" is absent from the inventory',
|
|
177
|
+
'modules[1].files[1]: "a.ts" was already assigned at modules[0].files[0]',
|
|
178
|
+
'Module plan omitted source files: "c.ts", "b.ts"',
|
|
179
|
+
].join('\n'))
|
|
188
180
|
})
|
package/tests/cli.test.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { cp, mkdir, readFile, realpath, symlink, writeFile } from 'node:fs/promi
|
|
|
4
4
|
import { dirname, join } from 'node:path'
|
|
5
5
|
import { createRequire } from 'node:module'
|
|
6
6
|
import { fileURLToPath } from 'node:url'
|
|
7
|
+
import { HarnessSdkError } from '@anureo/sdk'
|
|
7
8
|
import { runCli } from '../src/cli'
|
|
8
9
|
import { refactorHarnesses } from '../src/client'
|
|
9
10
|
import { loadGraph } from '../src/graph'
|
|
@@ -205,6 +206,57 @@ test('CLI prints an incomplete report and cleans up its client', async () => {
|
|
|
205
206
|
expect(context.prompts).toHaveLength(0)
|
|
206
207
|
})
|
|
207
208
|
|
|
209
|
+
test('CLI text keeps agent text within each field and preserves raw report data', async () => {
|
|
210
|
+
const summary = 'Summary\x1b[2J\nResult: failed'
|
|
211
|
+
const context = await fixture(prompt => prompt.startsWith('PLAN') ? {
|
|
212
|
+
...plan, summary,
|
|
213
|
+
modules: plan.modules.map(module => ({ ...module, name: module.name + '\rName' })),
|
|
214
|
+
} : {
|
|
215
|
+
...unchanged, summary, changes: ['Change\ttext'],
|
|
216
|
+
deferred: [{ title: 'Title\x9b', reason: 'Reason\u2028Error: fake' }],
|
|
217
|
+
})
|
|
218
|
+
let output = ''
|
|
219
|
+
const code = await runCli([context.cwd, '--review-only', '--no-graph'], {
|
|
220
|
+
createClient: async () => context.client, stdout: text => { output += text }, stderr: () => {},
|
|
221
|
+
})
|
|
222
|
+
expect(code).toBe(0)
|
|
223
|
+
expect(output).toContain('Refactor: completed (review only)\n')
|
|
224
|
+
expect(output).toContain('Summary\\u001b[2J\\u000aResult: failed')
|
|
225
|
+
expect(output).toContain('a: A\\u000dName')
|
|
226
|
+
expect(output).toContain('- Change\\u0009text')
|
|
227
|
+
expect(output).toContain('Deferred Title\\u009b: Reason\\u2028Error: fake')
|
|
228
|
+
expect(output).not.toContain('\nResult: failed')
|
|
229
|
+
expect(output).not.toContain('\x1b')
|
|
230
|
+
const reportPath = /^Report: (.+)$/m.exec(output)![1]!
|
|
231
|
+
const report = JSON.parse(await readFile(reportPath, 'utf8'))
|
|
232
|
+
expect(report.plan.summary).toBe(summary)
|
|
233
|
+
expect(report.design.summary).toBe(summary)
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
test.each([
|
|
237
|
+
{
|
|
238
|
+
plannerOutput: new HarnessSdkError('RECEIPT_LOST', 'Planning outcome unavailable', true, true),
|
|
239
|
+
code: 'RECEIPT_LOST', retryable: true,
|
|
240
|
+
diagnostics: ['Agent execution outcome is unknown'],
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
plannerOutput: { summary: 123, modules: [] },
|
|
244
|
+
code: 'STRUCTURED_OUTPUT_INVALID', retryable: false,
|
|
245
|
+
diagnostics: ['Validation issue: /summary [type]', 'Validation issue: /modules [minItems]'],
|
|
246
|
+
},
|
|
247
|
+
])('CLI displays planning diagnostics for $code', async ({ plannerOutput, code, retryable, diagnostics }) => {
|
|
248
|
+
const context = await fixture(prompt => prompt.startsWith('PLAN') ? plannerOutput : unchanged)
|
|
249
|
+
let output = ''
|
|
250
|
+
const exitCode = await runCli([context.cwd, '--review-only', '--no-graph'], {
|
|
251
|
+
createClient: async () => context.client, stdout: text => { output += text }, stderr: () => {},
|
|
252
|
+
})
|
|
253
|
+
expect(exitCode).toBe(2)
|
|
254
|
+
for (const diagnostic of diagnostics) expect(output).toContain(diagnostic)
|
|
255
|
+
const reportPath = /^Report: (.+)$/m.exec(output)![1]!
|
|
256
|
+
const report = JSON.parse(await readFile(reportPath, 'utf8'))
|
|
257
|
+
expect(report).toMatchObject({ plan: null, failure: { code, retryable } })
|
|
258
|
+
})
|
|
259
|
+
|
|
208
260
|
/** Use the deterministic graph executable to verify transport/JSON handling without live indexing. */
|
|
209
261
|
test('graph adapter invokes the real subprocess interface and reads its JSON', async () => {
|
|
210
262
|
const context = await fixture()
|
|
@@ -274,21 +326,36 @@ test('installed CLI edits a mixed-language repository and runs ordered checks wi
|
|
|
274
326
|
expect(JSON.parse(await readFile(join(report.directory, 'report.json'), 'utf8'))).toEqual(report)
|
|
275
327
|
}, 25_000)
|
|
276
328
|
|
|
329
|
+
test.skipIf(process.platform === 'win32')('installed CLI resolves a native Codex override against the target', async () => {
|
|
330
|
+
const outside = await temporary()
|
|
331
|
+
const target = join(outside, 'target')
|
|
332
|
+
await mkdir(target)
|
|
333
|
+
await exec('git', ['init', '-q', target])
|
|
334
|
+
await writeFile(join(target, 'main.ts'), 'export {}\n')
|
|
335
|
+
await writeFile(join(outside, 'codex-peer'), '#!/bin/sh\nexec "$REFACTOR_TEST_BUN" "$REFACTOR_TEST_CODEX" "$@"\n', { mode: 0o755 })
|
|
336
|
+
const { stdout } = await runInstalledCli([target, '--no-graph', '--review-only', '--json'], {
|
|
337
|
+
cwd: outside,
|
|
338
|
+
env: { ...process.env, CODEX_BIN: '../codex-peer', REFACTOR_TEST_BUN: process.execPath, REFACTOR_TEST_CODEX: codexFixture },
|
|
339
|
+
})
|
|
340
|
+
expect(JSON.parse(stdout)).toMatchObject({ status: 'completed', modules: [{ step: { status: 'unchanged' } }] })
|
|
341
|
+
}, 25_000)
|
|
342
|
+
|
|
277
343
|
test('CLI automatically falls back when the optional graph package is absent', async () => {
|
|
278
344
|
const target = await temporary()
|
|
279
345
|
const isolated = await temporary()
|
|
280
346
|
await exec('git', ['init', '-q', target])
|
|
281
347
|
await writeFile(join(target, 'program.unknown-dsl'), 'do work\n')
|
|
282
|
-
const
|
|
283
|
-
|
|
348
|
+
const isolatedEntry = join(isolated, manifest.bin['anureo-refactor'])
|
|
349
|
+
await cp(join(packageDirectory, 'src'), join(isolated, 'src'), { recursive: true })
|
|
350
|
+
await mkdir(dirname(isolatedEntry), { recursive: true })
|
|
351
|
+
await cp(installedEntry, isolatedEntry)
|
|
284
352
|
await mkdir(join(isolated, 'node_modules', '@anureo'), { recursive: true })
|
|
285
|
-
const manifest = JSON.parse(await readFile(join(packageDirectory, 'package.json'), 'utf8'))
|
|
286
353
|
for (const name of Object.keys(manifest.dependencies)) {
|
|
287
354
|
const directory = await realpath(join(packageDirectory, 'node_modules', name))
|
|
288
355
|
await symlink(directory, join(isolated, 'node_modules', name), 'junction')
|
|
289
356
|
}
|
|
290
357
|
const { stdout, stderr } = await exec(process.execPath, [
|
|
291
|
-
|
|
358
|
+
isolatedEntry, target, '--review-only', '--json',
|
|
292
359
|
], { cwd: isolated, env: { ...process.env, CODEX_BIN: codexFixture }, timeout: 20_000 })
|
|
293
360
|
expect(JSON.parse(stdout)).toMatchObject({
|
|
294
361
|
status: 'completed',
|
|
@@ -298,16 +365,14 @@ test('CLI automatically falls back when the optional graph package is absent', a
|
|
|
298
365
|
}, 25_000)
|
|
299
366
|
|
|
300
367
|
const codexFixture = fileURLToPath(new URL('./fixtures/codex.mjs', import.meta.url))
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
return exec(process.execPath, [installedEntry(), ...args], { ...options, timeout: 20_000 })
|
|
368
|
+
const packageDirectory = fileURLToPath(new URL('../', import.meta.url))
|
|
369
|
+
const manifest = createRequire(import.meta.url)(join(packageDirectory, 'package.json')) as {
|
|
370
|
+
bin: { 'anureo-refactor': string }
|
|
371
|
+
dependencies: Record<string, string>
|
|
306
372
|
}
|
|
373
|
+
const installedEntry = join(packageDirectory, manifest.bin['anureo-refactor'])
|
|
307
374
|
|
|
308
|
-
/**
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const require = createRequire(import.meta.url)
|
|
312
|
-
return join(dirname(require.resolve('@anureo/refactor')), '../bin/anureo-refactor.ts')
|
|
375
|
+
/** Run the manifest-declared CLI in a child with a 20-second timeout. */
|
|
376
|
+
async function runInstalledCli(args: string[], options: { cwd?: string; env?: NodeJS.ProcessEnv; maxBuffer?: number } = {}) {
|
|
377
|
+
return exec(process.execPath, [installedEntry, ...args], { ...options, timeout: 20_000 })
|
|
313
378
|
}
|
package/tests/fixtures/codex.mjs
CHANGED
|
File without changes
|
|
@@ -1,17 +1,24 @@
|
|
|
1
1
|
// Stand-in subprocess for the CLI suite's direct loadGraph and installed-entry tests.
|
|
2
2
|
// Checks the export kind and output location, then writes a minimal graph without indexing.
|
|
3
|
-
import { writeFile } from 'node:fs/promises'
|
|
4
|
-
import { isAbsolute, relative, sep } from 'node:path'
|
|
3
|
+
import { realpath, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { isAbsolute, join, relative, sep } from 'node:path'
|
|
5
5
|
|
|
6
6
|
const args = process.argv.slice(2)
|
|
7
7
|
const [command, repositoryPath] = args
|
|
8
8
|
if (command !== 'export' || args[args.indexOf('--kind') + 1] !== 'all') process.exit(3)
|
|
9
9
|
const output = args[args.indexOf('--out') + 1]
|
|
10
|
+
const project = args[args.indexOf('--project') + 1]
|
|
10
11
|
// Keeping the export outside the target prevents a later export from indexing it.
|
|
11
12
|
const relativeOutput = relative(repositoryPath, output)
|
|
12
13
|
if (!isAbsolute(relativeOutput) && !relativeOutput.startsWith(`..${sep}`) && relativeOutput !== '..') process.exit(4)
|
|
13
14
|
await writeFile(output, JSON.stringify({
|
|
14
|
-
schemaVersion: 1, kind: 'all', repositoryPath,
|
|
15
|
+
schemaVersion: 1, kind: 'all', repositoryPath, project, generatedAt: new Date().toISOString(),
|
|
16
|
+
files: { 'main.ts': { lines: 1 } }, indexReport: { status: 'indexed' },
|
|
15
17
|
nodes: [{ id: 'main', name: 'main', filePath: 'main.ts', labels: ['Function'], startLine: 1, endLine: 1,
|
|
16
|
-
callable: { parameters: [], returnType: 'number' } }
|
|
18
|
+
callable: { parameters: [], returnType: 'number' } },
|
|
19
|
+
...[
|
|
20
|
+
['relative', './relative.ts'], ['absolute', join(repositoryPath, 'absolute.ts')],
|
|
21
|
+
['canonical', join(await realpath(repositoryPath), 'canonical.ts')],
|
|
22
|
+
].map(([name, filePath]) => ({ id: name, name, filePath, labels: ['Function'], startLine: 1, endLine: 1 }))],
|
|
23
|
+
edges: [],
|
|
17
24
|
}))
|