@anureo/refactor 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +11 -11
- 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/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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anureo/refactor",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Graph-assisted code refactoring with parallel agents in separate Git worktrees",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -24,22 +24,22 @@
|
|
|
24
24
|
"test": "bun test tests"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@anureo/adapter-acp": "0.3.
|
|
28
|
-
"@anureo/adapter-ahp": "0.3.
|
|
29
|
-
"@anureo/adapter-claude": "0.3.
|
|
30
|
-
"@anureo/adapter-codex": "0.3.
|
|
31
|
-
"@anureo/adapter-hermes": "0.3.
|
|
32
|
-
"@anureo/adapter-pi": "0.3.
|
|
33
|
-
"@anureo/sdk": "0.3.
|
|
34
|
-
"@anureo/workflow": "0.3.
|
|
27
|
+
"@anureo/adapter-acp": "0.3.2",
|
|
28
|
+
"@anureo/adapter-ahp": "0.3.2",
|
|
29
|
+
"@anureo/adapter-claude": "0.3.2",
|
|
30
|
+
"@anureo/adapter-codex": "0.3.2",
|
|
31
|
+
"@anureo/adapter-hermes": "0.3.2",
|
|
32
|
+
"@anureo/adapter-pi": "0.3.2",
|
|
33
|
+
"@anureo/sdk": "0.3.2",
|
|
34
|
+
"@anureo/workflow": "0.3.2",
|
|
35
35
|
"zod": "4.6.7"
|
|
36
36
|
},
|
|
37
37
|
"optionalDependencies": {
|
|
38
38
|
"@youichi/repograph": "0.1.1"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|
|
41
|
-
"@anureo/conformance": "0.3.
|
|
42
|
-
"@anureo/protocol": "0.3.
|
|
41
|
+
"@anureo/conformance": "0.3.2",
|
|
42
|
+
"@anureo/protocol": "0.3.2"
|
|
43
43
|
},
|
|
44
44
|
"engines": {
|
|
45
45
|
"node": ">=22",
|
package/src/agent-work.ts
CHANGED
|
@@ -1,61 +1,121 @@
|
|
|
1
1
|
// Runs isolated agent sessions and integrates their observed changes.
|
|
2
|
-
import {
|
|
2
|
+
import { mkdir } from 'node:fs/promises'
|
|
3
|
+
import { join, sep } from 'node:path'
|
|
3
4
|
import { agent } from '@anureo/workflow'
|
|
4
5
|
import { runChecks, type CheckCommand } from './checks'
|
|
5
6
|
import { failure, message } from './errors'
|
|
6
|
-
import {
|
|
7
|
+
import { inspectGitPath } from './git-path'
|
|
8
|
+
import { captureTree, changes, fileFingerprint } from './git-tree'
|
|
7
9
|
import type { RefactorOptions } from './options'
|
|
8
10
|
import type { StepResult } from './results'
|
|
9
11
|
import { workSchema } from './schema'
|
|
10
12
|
import { isSource, isTextSource } from './source-policy'
|
|
11
|
-
import { createAgentWorktree, mergeWorktree, prepareCheckDependencies, removeAgentWorktree, type AgentWorktree, type WorktreeBaseline } from './worktree'
|
|
13
|
+
import { createAgentWorktree, mergeWorktree, prepareCheckDependencies, removeAgentWorktree, withWorktreeBaseline, type AgentWorktree, type WorktreeBaseline } from './worktree'
|
|
12
14
|
|
|
13
15
|
/** Run one callback in a fresh checkout of the supplied baseline. The callback must await all
|
|
14
16
|
* work that uses the checkout. Removal is awaited before returning its result or propagating its
|
|
15
|
-
* error.
|
|
16
|
-
*
|
|
17
|
+
* error. If the callback and removal both fail, preserve primary diagnostics and report both
|
|
18
|
+
* errors. The caller owns the baseline. */
|
|
17
19
|
export async function inAgentWorktree<T>(baseline: WorktreeBaseline, use: (worktree: AgentWorktree) => Promise<T>): Promise<T> {
|
|
18
20
|
const worktree = await createAgentWorktree(baseline)
|
|
21
|
+
let result: T
|
|
19
22
|
try {
|
|
20
|
-
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
+
result = await use(worktree)
|
|
24
|
+
} catch (primary) {
|
|
25
|
+
try {
|
|
26
|
+
await removeAgentWorktree(baseline, worktree)
|
|
27
|
+
} catch (cleanup) {
|
|
28
|
+
const { code, outcomeUnknown, retryable, issues } = failure(primary)
|
|
29
|
+
throw Object.assign(new AggregateError([primary, cleanup], `${message(primary)}\n${message(cleanup)}`), {
|
|
30
|
+
code, outcomeUnknown, retryable, details: { issues, cleanupErrors: [message(cleanup)] },
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
throw primary
|
|
23
34
|
}
|
|
35
|
+
await removeAgentWorktree(baseline, worktree)
|
|
36
|
+
return result
|
|
24
37
|
}
|
|
25
38
|
|
|
26
|
-
/** Run a session, validate its edits
|
|
27
|
-
*
|
|
28
|
-
export async function runAgentWork(input: AgentWorkInput): Promise<StepResult> {
|
|
39
|
+
/** Run a session, then validate and merge its edits on the caller's writer queue.
|
|
40
|
+
* Cleanup is awaited. Return null when dispatch stops during checkout setup. */
|
|
41
|
+
export async function runAgentWork(input: AgentWorkInput): Promise<StepResult | null> {
|
|
29
42
|
const step: StepResult = { summary: '', changes: [], deferred: [], status: 'unchanged', changedFiles: [], checks: [], error: null, failure: null }
|
|
43
|
+
const recordFailure = (cause: unknown) => {
|
|
44
|
+
markFailed(step, cause)
|
|
45
|
+
if (input.dispatch && (step.failure?.outcomeUnknown || step.failure?.cleanupFailed)) input.dispatch.stopped = true
|
|
46
|
+
}
|
|
30
47
|
try {
|
|
31
|
-
await inAgentWorktree(input.baseline, async worktree => {
|
|
48
|
+
return await inAgentWorktree(input.baseline, async worktree => {
|
|
32
49
|
const before = await captureTree(worktree.root)
|
|
33
|
-
|
|
50
|
+
if (input.dispatch?.stopped) return null
|
|
51
|
+
try {
|
|
52
|
+
const { options, prompt } = input
|
|
53
|
+
const work = await agent(prompt, {
|
|
54
|
+
client: options.client, cwd: worktree.cwd, model: options.model,
|
|
55
|
+
permissionMode: options.reviewOnly ? options.readPermissionMode : options.editPermissionMode,
|
|
56
|
+
schema: workSchema, outputFallback: 'json-text',
|
|
57
|
+
})
|
|
58
|
+
if (!work) throw new Error('Agent returned no result')
|
|
59
|
+
Object.assign(step, work)
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
recordFailure(cause)
|
|
62
|
+
}
|
|
34
63
|
const edited = await captureTree(worktree.root)
|
|
35
64
|
await recordAgentEdits(input, worktree, changes(before, edited), before, step)
|
|
36
|
-
if (step.status
|
|
37
|
-
|
|
38
|
-
await prepareCheckDependencies(input.baseline, worktree)
|
|
39
|
-
const beforeChecks = await captureTree(worktree.root)
|
|
40
|
-
await runChecks(worktree.cwd, input.checks, step.checks)
|
|
41
|
-
const changedByChecks = changes(beforeChecks, await captureTree(worktree.root))
|
|
42
|
-
if (changedByChecks.length) throw new Error(`Validation modified source files: ${changedByChecks.join(', ')}`)
|
|
65
|
+
if (step.status !== 'failed' && step.changedFiles.length) {
|
|
66
|
+
await input.publish(() => validateAndMerge(input, worktree, step)).catch(recordFailure)
|
|
43
67
|
}
|
|
44
|
-
|
|
45
|
-
await mergeWorktree(input.baseline, worktree, step.changedFiles)
|
|
46
|
-
step.status = 'applied'
|
|
47
|
-
})
|
|
68
|
+
return step
|
|
48
69
|
})
|
|
49
70
|
} catch (cause) {
|
|
50
|
-
|
|
71
|
+
recordFailure(cause)
|
|
72
|
+
return step
|
|
51
73
|
}
|
|
52
|
-
return step
|
|
53
74
|
}
|
|
54
75
|
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
76
|
+
/** Validate the candidate on the current target snapshot while holding the writer queue. */
|
|
77
|
+
async function validateAndMerge(input: AgentWorkInput, candidate: AgentWorktree, step: StepResult): Promise<void> {
|
|
78
|
+
const { baseline, checks, options } = input
|
|
79
|
+
const apply = async (destination: WorktreeBaseline, source: AgentWorktree) => {
|
|
80
|
+
await mergeWorktree(destination, source, step.changedFiles)
|
|
81
|
+
step.appliedFiles = [...step.changedFiles]
|
|
82
|
+
step.status = 'applied'
|
|
83
|
+
}
|
|
84
|
+
if (!checks.length) return apply(baseline, candidate)
|
|
85
|
+
|
|
86
|
+
await withWorktreeBaseline(options.cwd, fresh => inAgentWorktree(
|
|
87
|
+
{ ...fresh, updateWorktreeRegistry: baseline.updateWorktreeRegistry },
|
|
88
|
+
async validation => {
|
|
89
|
+
const target = join(fresh.root, fresh.scope)
|
|
90
|
+
for (const file of step.changedFiles) {
|
|
91
|
+
// Ignored paths can exist in the target even when absent from both snapshots.
|
|
92
|
+
if (await fileFingerprint(target, file) !== await fileFingerprint(validation.cwd, file)) {
|
|
93
|
+
throw new Error(`Source changed during refactor: ${file}`)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const beforeOverlay = await captureTree(validation.root)
|
|
97
|
+
await mkdir(join(validation.cwd, '.anureo', 'refactor'), { recursive: true })
|
|
98
|
+
await mergeWorktree({ ...baseline, root: validation.root }, candidate, step.changedFiles)
|
|
99
|
+
await prepareCheckDependencies(fresh, validation)
|
|
100
|
+
const beforeChecks = await captureTree(validation.root)
|
|
101
|
+
const checkedFiles = await Promise.all(step.changedFiles.map(file => fileFingerprint(validation.cwd, file)))
|
|
102
|
+
await runChecks(validation.cwd, checks, step.checks)
|
|
103
|
+
const changedByChecks = changes(beforeChecks, await captureTree(validation.root))
|
|
104
|
+
for (const [index, file] of step.changedFiles.entries()) {
|
|
105
|
+
if (await fileFingerprint(validation.cwd, file) !== checkedFiles[index]) {
|
|
106
|
+
changedByChecks.push(fresh.scope ? join(fresh.scope, file).split(sep).join('/') : file)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (changedByChecks.length) throw new Error(`Validation modified source files: ${[...new Set(changedByChecks)].sort().join(', ')}`)
|
|
110
|
+
const changedDuringChecks = changes(beforeOverlay, await captureTree(fresh.root))
|
|
111
|
+
if (changedDuringChecks.length) throw new Error(`Source changed during refactor: ${changedDuringChecks.join(', ')}`)
|
|
112
|
+
await apply(fresh, validation)
|
|
113
|
+
},
|
|
114
|
+
))
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Preserve the first error's classification and append any later cleanup diagnostics. */
|
|
118
|
+
function markFailed(step: StepResult, cause: unknown): void {
|
|
59
119
|
const observed = failure(cause)
|
|
60
120
|
if (step.failure) {
|
|
61
121
|
step.failure.cleanupFailed ||= observed.cleanupFailed
|
|
@@ -64,6 +124,7 @@ export function markFailed(step: StepResult, cause: unknown): void {
|
|
|
64
124
|
}
|
|
65
125
|
step.status = 'failed'
|
|
66
126
|
step.error = message(cause)
|
|
127
|
+
if (step.appliedFiles?.length) step.error += ` (Files already applied: ${step.appliedFiles.join(', ')})`
|
|
67
128
|
step.failure = observed
|
|
68
129
|
}
|
|
69
130
|
|
|
@@ -73,26 +134,12 @@ interface AgentWorkInput {
|
|
|
73
134
|
prompt: string
|
|
74
135
|
checks: readonly CheckCommand[]
|
|
75
136
|
publish: (operation: () => Promise<void>) => Promise<void>
|
|
137
|
+
/** Shared module admission state. Active sessions still settle and record their results. */
|
|
138
|
+
dispatch?: { stopped: boolean }
|
|
76
139
|
/** Editable inventory for design or the validated assignment for a module. */
|
|
77
140
|
assignedFiles: readonly string[]
|
|
78
141
|
}
|
|
79
142
|
|
|
80
|
-
/** Merge the schema-validated response into the step after the workflow agent settles. Record
|
|
81
|
-
* session failure, including a missing result, so runAgentWork can still inspect the checkout. */
|
|
82
|
-
async function recordSessionResult({ options, prompt }: AgentWorkInput, cwd: string, step: StepResult): Promise<void> {
|
|
83
|
-
try {
|
|
84
|
-
const work = await agent(prompt, {
|
|
85
|
-
client: options.client, cwd, model: options.model,
|
|
86
|
-
permissionMode: options.reviewOnly ? options.readPermissionMode : options.editPermissionMode,
|
|
87
|
-
schema: workSchema, outputFallback: 'json-text',
|
|
88
|
-
})
|
|
89
|
-
if (!work) throw new Error('Agent returned no result')
|
|
90
|
-
Object.assign(step, work)
|
|
91
|
-
} catch (cause) {
|
|
92
|
-
markFailed(step, cause)
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
|
|
96
143
|
/** Record target-relative edits and reject writes outside the worktree assignment. */
|
|
97
144
|
async function recordAgentEdits(
|
|
98
145
|
{ baseline, options, assignedFiles }: AgentWorkInput,
|
|
@@ -109,8 +156,7 @@ async function recordAgentEdits(
|
|
|
109
156
|
await validateModuleEdits({ assignedFiles, changedFiles, before, scopePrefix, cwd: worktree.cwd, options })
|
|
110
157
|
}
|
|
111
158
|
|
|
112
|
-
/** Allow assigned
|
|
113
|
-
* edited path in diff order. Source inspection can also reject. */
|
|
159
|
+
/** Allow assigned deletions and edits or additions that qualify as text source. */
|
|
114
160
|
async function validateModuleEdits(input: {
|
|
115
161
|
assignedFiles: readonly string[]
|
|
116
162
|
changedFiles: readonly string[]
|
|
@@ -122,11 +168,17 @@ async function validateModuleEdits(input: {
|
|
|
122
168
|
const { assignedFiles, changedFiles, before, scopePrefix, cwd, options } = input
|
|
123
169
|
const assigned = new Set(assignedFiles)
|
|
124
170
|
const violations: string[] = []
|
|
171
|
+
const nonText: string[] = []
|
|
125
172
|
for (const file of changedFiles) {
|
|
126
|
-
if (assigned.has(file))
|
|
173
|
+
if (assigned.has(file)) {
|
|
174
|
+
const { info, linkedAncestor } = await inspectGitPath(cwd, file)
|
|
175
|
+
if ((info || linkedAncestor) && !await isTextSource(cwd, file)) nonText.push(file)
|
|
176
|
+
continue
|
|
177
|
+
}
|
|
127
178
|
if (!before.has(scopePrefix + file) && isSource(file, options.include, options.exclude)
|
|
128
179
|
&& await isTextSource(cwd, file)) continue
|
|
129
180
|
violations.push(file)
|
|
130
181
|
}
|
|
131
182
|
if (violations.length) throw new Error(`Module edited paths outside its assignment: ${violations.join(', ')}`)
|
|
183
|
+
if (nonText.length) throw new Error(`Assigned files must remain text source: ${nonText.join(', ')}`)
|
|
132
184
|
}
|
package/src/checks.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { readFile } from 'node:fs/promises'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { message } from './errors'
|
|
5
|
+
import { checkoutEnvironment } from './git'
|
|
5
6
|
import { exec } from './process'
|
|
6
7
|
import type { CheckResult } from './results'
|
|
7
8
|
|
|
@@ -13,13 +14,24 @@ export type CheckCommand = string | { executable: string; args?: readonly string
|
|
|
13
14
|
* refactorCode runs this before repository preflight and parseCliInput uses it before client
|
|
14
15
|
* creation. Omitted and empty lists pass this check. Only omission allows script discovery. */
|
|
15
16
|
export function validateChecks(commands: readonly CheckCommand[] | undefined, label = 'check'): void {
|
|
16
|
-
|
|
17
|
+
const issues: string[] = []
|
|
18
|
+
let hasBlankCommand = false
|
|
19
|
+
for (const [index, command] of (commands ?? []).entries()) {
|
|
20
|
+
const location = `${label} #${index + 1}`
|
|
17
21
|
const executable = typeof command === 'string' ? command : command.executable
|
|
18
|
-
if (!executable.trim())
|
|
19
|
-
|
|
20
|
-
|
|
22
|
+
if (!executable.trim()) {
|
|
23
|
+
hasBlankCommand = true
|
|
24
|
+
issues.push(`${location} is blank`)
|
|
25
|
+
}
|
|
26
|
+
if (executable.includes('\0')) issues.push(`${location} contains NUL`)
|
|
27
|
+
if (typeof command !== 'string') {
|
|
28
|
+
for (const [position, arg] of (command.args ?? []).entries()) {
|
|
29
|
+
if (arg.includes('\0')) issues.push(`${location} argument #${position + 1} contains NUL`)
|
|
30
|
+
}
|
|
21
31
|
}
|
|
22
32
|
}
|
|
33
|
+
if (hasBlankCommand) issues.unshift(`${label} commands must be nonempty`)
|
|
34
|
+
if (issues.length) throw new Error(issues.join('\n'))
|
|
23
35
|
}
|
|
24
36
|
|
|
25
37
|
/** Discover typecheck then test for refactorCode when checks are omitted outside review-only mode.
|
|
@@ -52,7 +64,7 @@ export async function defaultChecks(cwd: string): Promise<CheckCommand[]> {
|
|
|
52
64
|
* message on failure, and retain only the final 4,000 characters. An empty command list resolves
|
|
53
65
|
* without changing results; existing entries are retained. */
|
|
54
66
|
export async function runChecks(cwd: string, commands: readonly CheckCommand[], results: CheckResult[]): Promise<void> {
|
|
55
|
-
const limits = { cwd, maxBuffer: 8 << 20, timeout: 300_000, windowsHide: true }
|
|
67
|
+
const limits = { cwd, env: checkoutEnvironment(), maxBuffer: 8 << 20, timeout: 300_000, killSignal: 'SIGKILL' as const, windowsHide: true }
|
|
56
68
|
for (const command of commands) {
|
|
57
69
|
const display = typeof command === 'string' ? command : [command.executable, ...(command.args ?? [])]
|
|
58
70
|
.map(arg => /^[\w./:-]+$/.test(arg) ? arg : JSON.stringify(arg)).join(' ')
|
package/src/client.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Selects CLI adapters and their default permission modes.
|
|
2
|
-
import { resolve } from 'node:path'
|
|
2
|
+
import { basename, resolve } from 'node:path'
|
|
3
3
|
import { approveWithNarrowestScope, createClient, type Client } from '@anureo/sdk'
|
|
4
4
|
import { spawnHarnessProcess } from '@anureo/sdk/process'
|
|
5
5
|
|
|
@@ -33,11 +33,12 @@ export const harnessPermissions: Partial<Record<RefactorHarness, { readPermissio
|
|
|
33
33
|
* executeRefactor passes failures to runCli and awaits disposal of a returned client. */
|
|
34
34
|
export async function createRefactorClient(cwd: string, selection: HarnessSelection): Promise<Client> {
|
|
35
35
|
const adapter = await createAdapter(cwd, selection)
|
|
36
|
+
// Allow the DSH preset's 120-second native initialize request plus subprocess startup.
|
|
36
37
|
return createClient({
|
|
37
38
|
adapter,
|
|
38
39
|
identity: { adapterId: selection.id, runtimeConfigId: 'refactor' },
|
|
39
40
|
interactions: { approval: approveWithNarrowestScope },
|
|
40
|
-
})
|
|
41
|
+
}, selection.id === 'dsh' ? { timeoutMs: 125_000 } : undefined)
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
const javaScriptEntry = /\.[cm]?js$/i
|
|
@@ -51,7 +52,8 @@ async function createAdapter(cwd: string, { id, command, args, url }: HarnessSel
|
|
|
51
52
|
const executable = process.env.CODEX_BIN?.trim() || 'codex'
|
|
52
53
|
const script = javaScriptEntry.test(executable) ? resolve(cwd, executable) : undefined
|
|
53
54
|
return createCodexAdapter({
|
|
54
|
-
command: executable
|
|
55
|
+
command: basename(executable) === executable ? executable : resolve(cwd, executable),
|
|
56
|
+
cwd,
|
|
55
57
|
// The adapter uses this for version probes and session launches. Resolve the script
|
|
56
58
|
// against the CLI target so it still works when a session launches in a worktree.
|
|
57
59
|
processFactory: script ? options => spawnHarnessProcess({
|
package/src/errors.ts
CHANGED
|
@@ -1,10 +1,22 @@
|
|
|
1
1
|
// Normalizes caught errors for reports and diagnostics.
|
|
2
2
|
import type { Failure } from './results'
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
4
|
+
declare module './results' {
|
|
5
|
+
interface Failure {
|
|
6
|
+
/** Whether the source error permits a retry. May be absent in older reports. */
|
|
7
|
+
retryable?: boolean
|
|
8
|
+
/** Field paths and rule codes from structured-output validation. */
|
|
9
|
+
issues?: Array<{ path: string | Array<string | number>; code: string }>
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Convert a caught value for display, including values with throwing accessors or conversions. */
|
|
6
14
|
export function message(cause: unknown): string {
|
|
7
|
-
|
|
15
|
+
try {
|
|
16
|
+
return String(cause instanceof Error ? cause.message : cause)
|
|
17
|
+
} catch {
|
|
18
|
+
return 'Error details could not be displayed'
|
|
19
|
+
}
|
|
8
20
|
}
|
|
9
21
|
|
|
10
22
|
/** Extract execution and resource-release signals independently from a caught object.
|
|
@@ -13,15 +25,19 @@ export function message(cause: unknown): string {
|
|
|
13
25
|
* and false flags. Execution uncertainty requires an explicit true. Custom accessors can throw. */
|
|
14
26
|
export function failure(cause: unknown): Failure {
|
|
15
27
|
const error = (cause && typeof cause === 'object' ? cause : {}) as FailureSource
|
|
28
|
+
const issues = validationIssues(error.details?.issues)
|
|
16
29
|
return {
|
|
17
30
|
code: typeof error.code === 'string' ? error.code : null,
|
|
18
31
|
outcomeUnknown: error.outcomeUnknown === true,
|
|
19
32
|
cleanupFailed: hasCleanupFailure(error),
|
|
33
|
+
retryable: error.retryable === true,
|
|
34
|
+
...(issues.length ? { issues } : {}),
|
|
20
35
|
}
|
|
21
36
|
}
|
|
22
37
|
|
|
23
38
|
interface FailureSource {
|
|
24
39
|
outcomeUnknown?: unknown
|
|
40
|
+
retryable?: unknown
|
|
25
41
|
code?: unknown
|
|
26
42
|
details?: Record<string, unknown>
|
|
27
43
|
}
|
|
@@ -31,3 +47,24 @@ function hasCleanupFailure(error: FailureSource): boolean {
|
|
|
31
47
|
return error.code === 'RESOURCE_RELEASE_FAILED' || error.details?.cleanupFailed === true
|
|
32
48
|
|| (Array.isArray(error.details?.cleanupErrors) && error.details.cleanupErrors.length > 0)
|
|
33
49
|
}
|
|
50
|
+
|
|
51
|
+
/** Keep field locations and rule codes without copying other validation details. */
|
|
52
|
+
function validationIssues(candidates: unknown): NonNullable<Failure['issues']> {
|
|
53
|
+
const issues: NonNullable<Failure['issues']> = []
|
|
54
|
+
if (!Array.isArray(candidates)) return issues
|
|
55
|
+
for (const issue of candidates) {
|
|
56
|
+
if (!issue || typeof issue !== 'object') continue
|
|
57
|
+
const { path, code } = issue
|
|
58
|
+
if (typeof code !== 'string' || !code) continue
|
|
59
|
+
if (typeof path === 'string') {
|
|
60
|
+
issues.push({ path, code })
|
|
61
|
+
} else if (Array.isArray(path)) {
|
|
62
|
+
const parts = [...path]
|
|
63
|
+
if (parts.every(part => typeof part === 'string'
|
|
64
|
+
|| (typeof part === 'number' && Number.isSafeInteger(part) && part >= 0))) {
|
|
65
|
+
issues.push({ path: parts, code })
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return issues
|
|
70
|
+
}
|
package/src/git.ts
CHANGED
|
@@ -1,14 +1,23 @@
|
|
|
1
1
|
// Runs Git with checkout-local environment overrides removed.
|
|
2
2
|
import { realpath } from 'node:fs/promises'
|
|
3
3
|
import { resolve } from 'node:path'
|
|
4
|
+
import { message } from './errors'
|
|
4
5
|
import { exec } from './process'
|
|
5
6
|
|
|
6
7
|
/** List sorted, unique tracked and unignored untracked paths under cwd via Git.
|
|
7
8
|
* Snapshot callers supply an in-repository directory; paths are relative to it, including when
|
|
8
9
|
* it is a subdirectory. Launches a read-only Git command; process/buffer failures reject. */
|
|
9
10
|
export async function gitFiles(cwd: string): Promise<string[]> {
|
|
10
|
-
const stdout = await git
|
|
11
|
-
|
|
11
|
+
const { stdout } = await exec('git', ['-C', cwd, 'ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
|
|
12
|
+
...gitProcessOptions(), encoding: 'buffer',
|
|
13
|
+
})
|
|
14
|
+
let paths: string
|
|
15
|
+
try {
|
|
16
|
+
paths = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(stdout)
|
|
17
|
+
} catch (cause) {
|
|
18
|
+
throw new Error(`Git reported a filename that is not valid UTF-8 in ${cwd}`, { cause })
|
|
19
|
+
}
|
|
20
|
+
return [...new Set(paths.split('\0').filter(Boolean))].sort()
|
|
12
21
|
}
|
|
13
22
|
|
|
14
23
|
/** Run Git with cwd as its starting directory and resolve buffered text stdout on success.
|
|
@@ -18,14 +27,18 @@ export async function git(cwd: string, ...args: string[]): Promise<string> {
|
|
|
18
27
|
return (await exec('git', ['-C', cwd, ...args], gitProcessOptions())).stdout
|
|
19
28
|
}
|
|
20
29
|
|
|
21
|
-
/** Build a fresh environment
|
|
22
|
-
|
|
23
|
-
export function gitProcessOptions() {
|
|
30
|
+
/** Build a fresh environment so Git and validation commands discover their own checkout. */
|
|
31
|
+
export function checkoutEnvironment(): NodeJS.ProcessEnv {
|
|
24
32
|
const env = { ...process.env }
|
|
25
33
|
for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX',
|
|
26
34
|
'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_IMPLICIT_WORK_TREE',
|
|
27
35
|
'GIT_GRAFT_FILE', 'GIT_SHALLOW_FILE']) delete env[key]
|
|
28
|
-
return
|
|
36
|
+
return env
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Use the same 64 MiB buffer limit for text and binary Git output. */
|
|
40
|
+
export function gitProcessOptions() {
|
|
41
|
+
return { env: checkoutEnvironment(), maxBuffer: 64 << 20 }
|
|
29
42
|
}
|
|
30
43
|
|
|
31
44
|
/** Resolve a preflight target to its real absolute path and require Git's work-tree probe to return true.
|
|
@@ -36,7 +49,7 @@ export async function repositoryDirectory(directory: string): Promise<string> {
|
|
|
36
49
|
const cwd = await realpath(resolve(directory))
|
|
37
50
|
// Keep the target directory rather than the Git root so subdirectory runs retain their scope.
|
|
38
51
|
const stdout = await git(cwd, 'rev-parse', '--is-inside-work-tree')
|
|
39
|
-
.catch(
|
|
52
|
+
.catch(cause => { throw new Error(`Could not check Git work tree at ${cwd}: ${message(cause)}`, { cause }) })
|
|
40
53
|
if (stdout.trim() !== 'true') throw new Error(`Not inside a Git work tree: ${cwd}`)
|
|
41
54
|
return cwd
|
|
42
55
|
}
|
package/src/graph-artifacts.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Records graph coverage and writes the graph supplied to each refactor phase.
|
|
2
2
|
import { writeFile } from 'node:fs/promises'
|
|
3
|
-
import {
|
|
3
|
+
import { join, relative, resolve, sep } from 'node:path'
|
|
4
4
|
import { message } from './errors'
|
|
5
|
-
import { loadGraph, type RepositoryGraph } from './graph'
|
|
5
|
+
import { GraphCleanupError, loadGraph, RepographNotInstalledError, type RepositoryGraph } from './graph'
|
|
6
6
|
import type { RefactorOptions } from './options'
|
|
7
7
|
import type { GraphCoverage, RefactorReport } from './results'
|
|
8
8
|
|
|
@@ -11,20 +11,22 @@ export interface GraphArtifactContext {
|
|
|
11
11
|
options: Pick<RefactorOptions, 'cwd' | 'noGraph' | 'graphLoader' | 'repographEntry'>
|
|
12
12
|
report: Pick<RefactorReport, 'directory' | 'graphCoverage'>
|
|
13
13
|
progress: (event: string) => void
|
|
14
|
-
/** Cached
|
|
14
|
+
/** Cached optional-package lookup failure. */
|
|
15
15
|
graphError?: string
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
/** Record coverage for the phase's Git-relative source paths and return the written graph path.
|
|
19
19
|
* runDesign calls this before the design agent starts. prepareModules calls it after planning when
|
|
20
20
|
* design changed files, then passes the result to runModules for the module prompts. Disabled or
|
|
21
|
-
* unavailable default exports return null for source inspection.
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
21
|
+
* unavailable default exports return null for source inspection. Configured exporter failures,
|
|
22
|
+
* cleanup failures and artifact serialization or write failures stop the pending agent work.
|
|
23
|
+
* Coverage records export availability before serialization so the report retains coverage even
|
|
24
|
+
* if the artifact cannot be written.
|
|
25
25
|
* Callers supply the existing report directory and serialize writes under the run lock. */
|
|
26
26
|
export async function exportGraph(context: GraphArtifactContext, phase: string, files: string[]): Promise<string | null> {
|
|
27
27
|
const { options, report, progress } = context
|
|
28
|
+
// The shared storage directory can have custom ignore rules. Always ignore this run's output.
|
|
29
|
+
await writeFile(join(report.directory, '.gitignore'), '*\n')
|
|
28
30
|
if (options.noGraph) {
|
|
29
31
|
report.graphCoverage.push({ phase, status: 'disabled', filesWithoutSymbols: files })
|
|
30
32
|
return null
|
|
@@ -39,8 +41,8 @@ export async function exportGraph(context: GraphArtifactContext, phase: string,
|
|
|
39
41
|
} catch (cause) {
|
|
40
42
|
const error = message(cause)
|
|
41
43
|
recordUnavailable(report.graphCoverage, { phase, files, error })
|
|
42
|
-
if (options.graphLoader || options.repographEntry) throw cause
|
|
43
|
-
context.graphError = error
|
|
44
|
+
if (options.graphLoader || options.repographEntry || cause instanceof GraphCleanupError) throw cause
|
|
45
|
+
if (cause instanceof RepographNotInstalledError) context.graphError = error
|
|
44
46
|
progress(`graph/${phase}: unavailable; continuing with source`)
|
|
45
47
|
return null
|
|
46
48
|
}
|
|
@@ -58,13 +60,14 @@ function recordUnavailable(coverage: GraphCoverage[], { phase, files, error }: {
|
|
|
58
60
|
|
|
59
61
|
/** Return inventory paths in input order that lack indexed symbols. Container labels alone
|
|
60
62
|
* establish that a path was seen, so exportGraph counts a node only if it has a non-container
|
|
61
|
-
* label.
|
|
63
|
+
* label. Resolve relative paths at the graph root and accept both spellings of the target. */
|
|
62
64
|
function filesWithoutSymbols(graph: RepositoryGraph, cwd: string, files: string[]): string[] {
|
|
63
65
|
const containerLabel = /^(file|folder|directory|package|project|module)$/i
|
|
64
66
|
const symbols = graph.nodes.filter(node => node.labels.some(label => !containerLabel.test(label)))
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
67
|
+
const roots = new Set([graph.repositoryPath, cwd])
|
|
68
|
+
const indexed = new Set(symbols.flatMap(({ filePath }) => {
|
|
69
|
+
const absolutePath = resolve(graph.repositoryPath, filePath)
|
|
70
|
+
return Array.from(roots, root => relative(root, absolutePath).split(sep).join('/'))
|
|
68
71
|
}))
|
|
69
72
|
return files.filter(file => !indexed.has(file))
|
|
70
73
|
}
|