@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
package/src/results.ts ADDED
@@ -0,0 +1,81 @@
1
+ import type { ModulePlan, RefactorModule, Work } from './schema'
2
+
3
+ /** Result recorded when the host runs a validation command in a worktree before integration. */
4
+ export interface CheckResult {
5
+ command: string
6
+ status: 'passed' | 'failed'
7
+ /** Last 4,000 characters of stdout followed by stderr, with the error message appended on failure. */
8
+ output: string
9
+ }
10
+ /** Error signals to consult before retrying a failed step or run. */
11
+ export interface Failure {
12
+ /** String code on the caught object, or null when absent or not a string. */
13
+ code: string | null
14
+ /** The error explicitly reports that the execution outcome is unknown. */
15
+ outcomeUnknown: boolean
16
+ /** A resource-release error was reported, independently of execution outcome. */
17
+ cleanupFailed: boolean
18
+ }
19
+ /** Outcome of a design or module step, including host observations from integration and validation.
20
+ * The inherited summary, changes and deferred fields are the agent's account of the work. */
21
+ export interface StepResult extends Work {
22
+ /** Unchanged for an empty edit, applied after integration, or failed on an error. A cleanup
23
+ * failure can be reported after a verified merge. */
24
+ status: 'applied' | 'unchanged' | 'failed'
25
+ /** Sorted Git-visible paths changed by the isolated agent within the target directory. */
26
+ changedFiles: string[]
27
+ /** Legacy report field containing the path to a historical patch artifact. */
28
+ patch?: string
29
+ /** Executed checks in command order; a failure stops subsequent checks. */
30
+ checks: CheckResult[]
31
+ /** Display text for the caught step error, or null when no error was caught. */
32
+ error: string | null
33
+ /** Classification of the first caught step error, with later cleanup failures merged in. */
34
+ failure: Failure | null
35
+ }
36
+ /** Planned module and its step record, paired in plan order before any module starts. */
37
+ export interface ModuleResult {
38
+ module: RefactorModule
39
+ /** Null until the worktree has finished validation, integration and cleanup. */
40
+ step: StepResult | null
41
+ }
42
+ /** Graph availability and declaration coverage for one phase's source inventory. */
43
+ export interface GraphCoverage {
44
+ phase: string
45
+ status: 'available' | 'unavailable' | 'disabled'
46
+ /** Paths with no indexed declarations, or the entire source inventory when no graph was available.
47
+ * Indexed files can still have unresolved relationships. */
48
+ filesWithoutSymbols: string[]
49
+ /** Export error text when graph data is unavailable. */
50
+ error?: string
51
+ }
52
+ /** Outcome returned by refactorCode after final publication and writer-lock release. During the
53
+ * run, report.json is updated at checkpoints and onProgress receives event strings. An incomplete
54
+ * report can include edits already applied to the target. The caller still owns the SDK client. */
55
+ export interface RefactorReport {
56
+ /** UUID allocated after writer-lock acquisition, also used as the run directory name. */
57
+ runId: string
58
+ /** Canonical target directory, which may be a subdirectory of a Git repository. */
59
+ cwd: string
60
+ /** Absolute storage directory for this run's reports, graphs and baseline. */
61
+ directory: string
62
+ /** Completed means every phase returned successfully; deferred work may still be listed. */
63
+ status: 'completed' | 'incomplete'
64
+ /** Agents were asked to avoid edits and host validation commands were disabled. */
65
+ reviewOnly: boolean
66
+ /** Cross-module design step, run before modules are planned. */
67
+ design: StepResult | null
68
+ /** Validated module assignments, or null until planning succeeds. */
69
+ plan: ModulePlan | null
70
+ /** Module records in plan order. Successful edits merge in readiness order. */
71
+ modules: ModuleResult[]
72
+ /** Graph availability and file coverage for the exports attempted during the run. */
73
+ graphCoverage: GraphCoverage[]
74
+ /** Run-level diagnostics. Consult each failed StepResult for its own error. */
75
+ errors: string[]
76
+ /** Classification of the run-level error, or null when none was caught. A failed-step gate
77
+ * throws a new error, so inspect the failed step for its original signals. */
78
+ failure: Failure | null
79
+ /** Display text for synchronous observer exceptions that were successfully converted, in delivery order. */
80
+ progressErrors: string[]
81
+ }
@@ -0,0 +1,117 @@
1
+ // Owns run identity, progress delivery and the lifetime of the per-target writer lock.
2
+ import { randomUUID } from 'node:crypto'
3
+ import { mkdir, open, rm } from 'node:fs/promises'
4
+ import type { FileHandle } from 'node:fs/promises'
5
+ import { join } from 'node:path'
6
+ import { failure, message } from './errors'
7
+ import type { RefactorOptions } from './options'
8
+ import { saveReport } from './report-store'
9
+ import type { RefactorReport } from './results'
10
+
11
+ /** Run the phases supplied by refactorCode under the target's writer lock.
12
+ * refactorCode supplies a canonical Git target. Its caller owns the SDK client.
13
+ * Directory setup and phase failures usually produce an incomplete report. Synchronous
14
+ * observer errors are recorded separately. Error conversion itself can throw.
15
+ * Resolves after publishing the final report, closing the lock handle and removing the lock path.
16
+ * Acquisition, report initialization, final publication and lock cleanup failures reject.
17
+ * Report initialization precedes the cleanup guard, so an initialization failure can leave the lock. */
18
+ export async function withRun(options: RefactorOptions & { cwd: string }, body: RunBody): Promise<RefactorReport> {
19
+ const writer = await acquireWriter(options.cwd)
20
+ const report = createReport(options, writer.root)
21
+ try {
22
+ await executeRun(options, report, body)
23
+ } finally {
24
+ await finalizeRun(report, writer)
25
+ }
26
+ return report
27
+ }
28
+
29
+ /** Resources owned by withRun after exclusive acquisition; the handle closes before path removal. */
30
+ interface RunWriter {
31
+ root: string
32
+ lockPath: string
33
+ lock: FileHandle
34
+ }
35
+
36
+ /** refactorCode supplies the design, planning and module phases as this callback. executeRun
37
+ * invokes it after creating the directory and delivering the run event. The callback can update
38
+ * the report, emit progress and publish intermediate checkpoints. Its settlement determines run
39
+ * status. withRun owns final publication and lock release. */
40
+ type RunBody = (report: RefactorReport, progress: (event: string) => void) => Promise<void>
41
+
42
+ /** Create the storage root and acquire exclusive ownership for withRun before allocating a run ID.
43
+ * Returns the open lock and its paths, transferring cleanup to withRun. Root creation errors
44
+ * propagate. Any open failure rejects with the lock diagnostic and leaves any existing lock alone. */
45
+ async function acquireWriter(cwd: string): Promise<RunWriter> {
46
+ const root = join(cwd, '.anureo', 'refactor')
47
+ await mkdir(root, { recursive: true })
48
+ const lockPath = join(root, 'writer.lock')
49
+ const lock = await open(lockPath, 'wx').catch(() => {
50
+ throw new Error(`Cannot acquire refactor lock: ${lockPath}. Check for an active run before removing a stale lock.`)
51
+ })
52
+ return { root, lockPath, lock }
53
+ }
54
+
55
+ /** Allocate the initial incomplete record for a locked run without creating its directory.
56
+ * withRun calls this after acquisition. UUID generation can throw. */
57
+ function createReport(options: RefactorOptions, root: string): RefactorReport {
58
+ const runId = randomUUID()
59
+ return {
60
+ runId,
61
+ cwd: options.cwd,
62
+ directory: join(root, runId),
63
+ status: 'incomplete',
64
+ reviewOnly: options.reviewOnly ?? false,
65
+ design: null,
66
+ plan: null,
67
+ modules: [],
68
+ graphCoverage: [],
69
+ errors: [],
70
+ failure: null,
71
+ progressErrors: [],
72
+ }
73
+ }
74
+
75
+ /** Create this run's directory and await orchestration, recording setup/body failures in report.
76
+ * Called by withRun while locked; progress precedes body dispatch and completion follows it.
77
+ * Ordinary setup/body errors are stored instead of rejecting; error conversion can still throw. */
78
+ async function executeRun(options: RefactorOptions, report: RefactorReport, body: RunBody): Promise<void> {
79
+ const progress = createProgressReporter(options, report)
80
+ try {
81
+ await mkdir(report.directory)
82
+ progress(`run: ${report.directory}`)
83
+ await body(report, progress)
84
+ report.status = 'completed'
85
+ } catch (cause) {
86
+ report.errors.push(message(cause))
87
+ report.failure = failure(cause)
88
+ }
89
+ }
90
+
91
+ /** Give executeRun and its phase callback a synchronous progress function for this report.
92
+ * refactorCode supplies the observer through options. Record thrown observer errors so a failed
93
+ * display sink does not stop work. Observer return values are ignored. Error conversion can throw. */
94
+ function createProgressReporter(options: RefactorOptions, report: RefactorReport): (event: string) => void {
95
+ return event => {
96
+ try {
97
+ options.onProgress?.(event)
98
+ } catch (cause) {
99
+ report.progressErrors.push(message(cause))
100
+ }
101
+ }
102
+ }
103
+
104
+ /** Publish the final snapshot, then attempt both lock-release operations for withRun.
105
+ * Publication stays under the lock so another writer cannot start before the snapshot attempt.
106
+ * Removal errors take precedence over close errors, which take precedence over publication errors. */
107
+ async function finalizeRun(report: RefactorReport, writer: RunWriter): Promise<void> {
108
+ try {
109
+ await saveReport(report)
110
+ } finally {
111
+ try {
112
+ await writer.lock.close()
113
+ } finally {
114
+ await rm(writer.lockPath)
115
+ }
116
+ }
117
+ }
@@ -1,42 +1,48 @@
1
- import { z } from 'zod';
1
+ import { z } from 'zod'
2
+
2
3
  /**
3
4
  * Describe the required planning response for the workflow agent called by plan in refactor.ts.
4
5
  * All strings, the module list and each file list must be nonempty. Parsing preserves whitespace
5
6
  * and rejects unknown fields in the response and its modules. plan passes the parsed response
6
7
  * to validatePlan for ID safety and exact inventory coverage before prepareModules can publish it.
7
8
  */
8
- export declare const modulePlanSchema: z.ZodObject<{
9
- summary: z.ZodString;
10
- modules: z.ZodArray<z.ZodObject<{
11
- id: z.ZodString;
12
- name: z.ZodString;
13
- description: z.ZodString;
14
- files: z.ZodArray<z.ZodString>;
15
- }, z.core.$strict>>;
16
- }, z.core.$strict>;
9
+ export const modulePlanSchema = z.strictObject({
10
+ summary: z.string().min(1),
11
+ modules: z.array(z.strictObject({
12
+ /** Artifact filename component; syntax and uniqueness are checked separately by validatePlan. */
13
+ id: z.string().min(1),
14
+ name: z.string().min(1),
15
+ description: z.string().min(1),
16
+ /** Exact host inventory paths; validatePlan checks membership and exclusive assignment. */
17
+ files: z.array(z.string().min(1)).min(1),
18
+ })).min(1),
19
+ })
20
+
17
21
  /**
18
22
  * Describe the required design and module responses for the workflow agent called by runAgentWork.
19
23
  * Parsing preserves whitespace in nonempty strings, accepts empty change and deferral lists, and
20
24
  * rejects unknown fields in the response and its deferrals. runAgentWork copies valid responses
21
25
  * into its step result and records a failed step when agent validation rejects.
22
26
  */
23
- export declare const workSchema: z.ZodObject<{
24
- summary: z.ZodString;
25
- changes: z.ZodArray<z.ZodString>;
26
- deferred: z.ZodArray<z.ZodObject<{
27
- title: z.ZodString;
28
- reason: z.ZodString;
29
- }, z.core.$strict>>;
30
- }, z.core.$strict>;
27
+ export const workSchema = z.strictObject({
28
+ summary: z.string().min(1),
29
+ /** Agent-reported edits or proposals, which need not correspond to observed file changes. */
30
+ changes: z.array(z.string().min(1)),
31
+ /** Unresolved findings with reasons; these do not by themselves make the host step fail. */
32
+ deferred: z.array(z.strictObject({ title: z.string().min(1), reason: z.string().min(1) })),
33
+ })
34
+
31
35
  /** Read the planner's summary and validated assignments from RefactorReport.plan.
32
36
  * Modules appear in the order the planner supplied and the host uses that order for integration.
33
37
  * Constructing this type performs no validation. */
34
- export type ModulePlan = z.infer<typeof modulePlanSchema>;
38
+ export type ModulePlan = z.infer<typeof modulePlanSchema>
39
+
35
40
  /** Read a planned module from the report's plan or a ModuleResult. Its ID identifies the module in
36
- * progress events and patch filenames. Its file list describes the original assignment. Use
41
+ * progress events and reports. Its file list describes the original assignment. Use
37
42
  * StepResult.changedFiles for the paths the host observed the agent change. */
38
- export type RefactorModule = ModulePlan['modules'][number];
43
+ export type RefactorModule = ModulePlan['modules'][number]
44
+
39
45
  /** Read an agent's summary, reported changes or proposals, and deferred findings on a StepResult.
40
46
  * Use the step's status, changed files and check results for host-observed outcomes.
41
47
  * Empty change and deferral lists are valid. */
42
- export type Work = z.infer<typeof workSchema>;
48
+ export type Work = z.infer<typeof workSchema>
@@ -0,0 +1,17 @@
1
+ import { captureTree } from './git-tree'
2
+ import type { RefactorOptions } from './options'
3
+ import { isSource, isTextSource } from './source-policy'
4
+
5
+ /** Return the whole host fingerprint map and its eligible text paths in sorted Git order.
6
+ * runDesign persists the map and sends the eligible files to design. prepareModules uses a fresh
7
+ * inventory after design for planning and plan validation. Snapshot failures, unsafe eligible
8
+ * paths and an empty eligible list reject before the corresponding agent is dispatched. */
9
+ export async function inventory({ cwd, include, exclude }: Pick<RefactorOptions, 'cwd' | 'include' | 'exclude'>): Promise<{ tree: Map<string, string>; files: string[] }> {
10
+ const tree = await captureTree(cwd)
11
+ const files: string[] = []
12
+ for (const file of tree.keys()) {
13
+ if (isSource(file, include, exclude) && await isTextSource(cwd, file)) files.push(file)
14
+ }
15
+ if (!files.length) throw new Error('No eligible Git-visible source files found')
16
+ return { tree, files }
17
+ }
@@ -1,56 +1,50 @@
1
1
  // Selects the paths and text eligible for review and editing.
2
- import { readFile } from 'node:fs/promises';
3
- import { posix } from 'node:path';
4
- import { inspectGitPath } from "./git-path.js";
2
+ import { readFile } from 'node:fs/promises'
3
+ import { posix } from 'node:path'
4
+ import { inspectGitPath } from './git-path'
5
+
5
6
  /** Match a Git-relative path against source scope rules without reading the filesystem.
6
7
  * Built-in path exclusions and explicit exclude globs take precedence over include globs.
7
8
  * With no includes, conventional supporting files are skipped. inventory and runAgentWork
8
9
  * follow a successful match with isTextSource before accepting a source path. */
9
- export function isSource(file, include = [], exclude = []) {
10
- if (isExcluded(file))
11
- return false;
12
- if (exclude.some(pattern => posix.matchesGlob(file, pattern)))
13
- return false;
14
- if (include.length)
15
- return include.some(pattern => posix.matchesGlob(file, pattern));
16
- return !supportingFile.test(posix.basename(file));
10
+ export function isSource(file: string, include: readonly string[] = [], exclude: readonly string[] = []): boolean {
11
+ if (isExcluded(file)) return false
12
+ if (exclude.some(pattern => posix.matchesGlob(file, pattern))) return false
13
+ if (include.length) return include.some(pattern => posix.matchesGlob(file, pattern))
14
+ return !supportingFile.test(posix.basename(file))
17
15
  }
16
+
18
17
  /** Check a Git-relative regular file for UTF-8 or BOM-marked UTF-16 text. inventory skips false
19
18
  * results, and runAgentWork treats them as assignment violations for new unassigned paths.
20
19
  * Missing paths, nonfiles, undecodable data and disallowed control characters return false.
21
20
  * Invalid paths, built-in exclusions, symlinks and filesystem failures other than missing
22
21
  * entries during inspection reject. Callers apply include and exclude globs through isSource. */
23
- export async function isTextSource(cwd, file) {
24
- if (isExcluded(file))
25
- throw new Error(`Invalid source path: ${file}`);
26
- const { path, info, linkedAncestor } = await inspectGitPath(cwd, file);
27
- if (linkedAncestor || info?.isSymbolicLink())
28
- throw new Error(`Symlink source paths are unsupported: ${file}`);
29
- if (!info?.isFile())
30
- return false;
31
- return isSupportedText(await readFile(path));
22
+ export async function isTextSource(cwd: string, file: string): Promise<boolean> {
23
+ if (isExcluded(file)) throw new Error(`Invalid source path: ${file}`)
24
+ const { path, info, linkedAncestor } = await inspectGitPath(cwd, file)
25
+ if (linkedAncestor || info?.isSymbolicLink()) throw new Error(`Symlink source paths are unsupported: ${file}`)
26
+ if (!info?.isFile()) return false
27
+ return isSupportedText(await readFile(path))
32
28
  }
29
+
33
30
  /** Exclude dependency, build, documentation and run artifacts from the editable scope. */
34
- const excluded = new Set(['.git', '.anureo', '.repograph', 'node_modules', 'dist', 'build', 'coverage', 'vendor', 'generated', 'draft', 'docs']);
31
+ const excluded = new Set(['.git', '.anureo', '.repograph', 'node_modules', 'dist', 'build', 'coverage', 'vendor', 'generated', 'draft', 'docs'])
35
32
  /** Repository metadata and conventional standalone prose. Explicit includes can select these files. */
36
- 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;
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
+
37
35
  /** Match hard exclusions against any path component, regardless of case or glob settings. */
38
- function isExcluded(file) {
39
- return file.split('/').some(part => excluded.has(part.toLowerCase()));
36
+ function isExcluded(file: string): boolean {
37
+ return file.split('/').some(part => excluded.has(part.toLowerCase()))
40
38
  }
39
+
41
40
  /** Default to UTF-8 unless a UTF-16 byte-order mark is present. Decode strictly so invalid
42
41
  * byte sequences cannot pass through as replacement characters. */
43
- function isSupportedText(content) {
44
- let encoding = 'utf-8';
45
- if (content[0] === 0xff && content[1] === 0xfe)
46
- encoding = 'utf-16le';
47
- if (content[0] === 0xfe && content[1] === 0xff)
48
- encoding = 'utf-16be';
49
- try {
50
- const text = new TextDecoder(encoding, { fatal: true }).decode(content);
51
- return !/[\x00-\x08\x0b\x0e-\x1f]/.test(text);
52
- }
53
- catch {
54
- return false;
55
- }
42
+ function isSupportedText(content: Buffer): boolean {
43
+ let encoding = 'utf-8'
44
+ if (content[0] === 0xff && content[1] === 0xfe) encoding = 'utf-16le'
45
+ if (content[0] === 0xfe && content[1] === 0xff) encoding = 'utf-16be'
46
+ try {
47
+ const text = new TextDecoder(encoding, { fatal: true }).decode(content)
48
+ return !/[\x00-\x08\x0b\x0e-\x1f]/.test(text)
49
+ } catch { return false }
56
50
  }