@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/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2026 Yoichi
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env bun
2
- export {};
@@ -1,4 +0,0 @@
1
- #!/usr/bin/env bun
2
- // Set the process exit code after the CLI has finished any client cleanup.
3
- import { runCli } from "../src/cli.js";
4
- process.exitCode = await runCli(process.argv.slice(2));
@@ -1,41 +0,0 @@
1
- import { type CheckCommand } from "./checks.js";
2
- import type { RefactorOptions } from "./options.js";
3
- import type { StepResult } from "./results.js";
4
- import { type AgentWorktree, type WorktreeBaseline } from "./worktree.js";
5
- /** Run one callback in a fresh checkout of the supplied baseline. The callback must await all
6
- * work that uses the checkout. Removal is awaited before returning its result or propagating its
7
- * error. Creation and removal failures propagate, and a removal failure takes precedence over
8
- * a callback failure. The caller owns the baseline. */
9
- export declare function inAgentWorktree<T>(baseline: WorktreeBaseline, use: (worktree: AgentWorktree) => Promise<T>): Promise<T>;
10
- /** Run a design or module session and return observed edits after checkout cleanup.
11
- * runDesign and runModules use the returned step to decide what can be integrated. Session,
12
- * capture, policy and checkout failures are recorded on the step. Capture still runs after a
13
- * session failure so any patch can be recovered. Review-only work and out-of-target edits
14
- * stop before writing a patch. The caller supplies the patch destination and owns the baseline
15
- * and client. A step with a patch still requires a separate integration decision. */
16
- export declare function runAgentWork(input: AgentWorkInput): Promise<StepResult>;
17
- /** Apply an available patch and record validation in the target checkout. Design can apply a failed
18
- * step's patch without running checks. Module integration skips failed steps with their patches
19
- * intact. Apply and check failures are recorded on the step without rolling back applied edits.
20
- * Callers serialize integration and publish the mutated step after this settles. */
21
- export declare function integrateAgentWork(input: {
22
- phase: 'design' | 'module';
23
- baseline: WorktreeBaseline;
24
- cwd: string;
25
- step: StepResult;
26
- checks: readonly CheckCommand[];
27
- }): Promise<void>;
28
- /** Mark a step failed in place. Later errors append diagnostics and can record a cleanup
29
- * failure while preserving the first error's code and outcome uncertainty. recordSessionResult,
30
- * runAgentWork and integrateAgentWork record caught errors here. integrateModules uses it when
31
- * an earlier failure blocks a patch. Error conversion itself can throw for custom error objects. */
32
- export declare function markFailed(step: StepResult, cause: unknown): void;
33
- interface AgentWorkInput {
34
- baseline: WorktreeBaseline;
35
- options: RefactorOptions;
36
- prompt: string;
37
- patchPath: string;
38
- /** Paths already assigned to this module. Omission skips module assignment validation. */
39
- assignedFiles?: readonly string[];
40
- }
41
- export {};
package/src/agent-work.js DELETED
@@ -1,131 +0,0 @@
1
- // Runs isolated agent sessions and integrates their observed changes.
2
- import { writeFile } from 'node:fs/promises';
3
- import { sep } from 'node:path';
4
- import { agent } from '@anureo/workflow';
5
- import { runChecks } from "./checks.js";
6
- import { failure, message } from "./errors.js";
7
- import { captureTree, changes } from "./git-tree.js";
8
- import { workSchema } from "./schema.js";
9
- import { isSource, isTextSource } from "./source-policy.js";
10
- import { applyWorktreePatch, captureWorktreePatch, createAgentWorktree, removeAgentWorktree } from "./worktree.js";
11
- /** Run one callback in a fresh checkout of the supplied baseline. The callback must await all
12
- * work that uses the checkout. Removal is awaited before returning its result or propagating its
13
- * error. Creation and removal failures propagate, and a removal failure takes precedence over
14
- * a callback failure. The caller owns the baseline. */
15
- export async function inAgentWorktree(baseline, use) {
16
- const worktree = await createAgentWorktree(baseline);
17
- try {
18
- return await use(worktree);
19
- }
20
- finally {
21
- await removeAgentWorktree(baseline, worktree);
22
- }
23
- }
24
- /** Run a design or module session and return observed edits after checkout cleanup.
25
- * runDesign and runModules use the returned step to decide what can be integrated. Session,
26
- * capture, policy and checkout failures are recorded on the step. Capture still runs after a
27
- * session failure so any patch can be recovered. Review-only work and out-of-target edits
28
- * stop before writing a patch. The caller supplies the patch destination and owns the baseline
29
- * and client. A step with a patch still requires a separate integration decision. */
30
- export async function runAgentWork(input) {
31
- const step = { summary: '', changes: [], deferred: [], status: 'unchanged', changedFiles: [], checks: [], error: null, failure: null };
32
- try {
33
- await inAgentWorktree(input.baseline, async (worktree) => {
34
- const before = await captureTree(worktree.root);
35
- await recordSessionResult(input, worktree.cwd, step);
36
- await recordAgentEdits(input, worktree, before, step);
37
- });
38
- }
39
- catch (cause) {
40
- markFailed(step, cause);
41
- }
42
- return step;
43
- }
44
- /** Apply an available patch and record validation in the target checkout. Design can apply a failed
45
- * step's patch without running checks. Module integration skips failed steps with their patches
46
- * intact. Apply and check failures are recorded on the step without rolling back applied edits.
47
- * Callers serialize integration and publish the mutated step after this settles. */
48
- export async function integrateAgentWork(input) {
49
- const { phase, baseline, cwd, step, checks } = input;
50
- if (!step.patch || (step.status === 'failed' && phase === 'module'))
51
- return;
52
- try {
53
- await applyWorktreePatch(baseline, step.changedFiles, step.patch);
54
- if (step.status === 'failed')
55
- return;
56
- step.status = 'applied';
57
- await runChecks(cwd, checks, step.checks);
58
- }
59
- catch (cause) {
60
- markFailed(step, cause);
61
- }
62
- }
63
- /** Mark a step failed in place. Later errors append diagnostics and can record a cleanup
64
- * failure while preserving the first error's code and outcome uncertainty. recordSessionResult,
65
- * runAgentWork and integrateAgentWork record caught errors here. integrateModules uses it when
66
- * an earlier failure blocks a patch. Error conversion itself can throw for custom error objects. */
67
- export function markFailed(step, cause) {
68
- const observed = failure(cause);
69
- if (step.failure) {
70
- step.failure.cleanupFailed ||= observed.cleanupFailed;
71
- step.error += `\n${message(cause)}`;
72
- return;
73
- }
74
- step.status = 'failed';
75
- step.error = message(cause);
76
- step.failure = observed;
77
- }
78
- /** Merge the schema-validated response into the step after the workflow agent settles. Record
79
- * session failure, including a missing result, so runAgentWork can still inspect the checkout. */
80
- async function recordSessionResult({ options, prompt }, cwd, step) {
81
- try {
82
- const work = await agent(prompt, {
83
- client: options.client, cwd, model: options.model,
84
- permissionMode: options.reviewOnly ? options.readPermissionMode : options.editPermissionMode,
85
- schema: workSchema, outputFallback: 'json-text',
86
- });
87
- if (!work)
88
- throw new Error('Agent returned no result');
89
- Object.assign(step, work);
90
- }
91
- catch (cause) {
92
- markFailed(step, cause);
93
- }
94
- }
95
- /** Compare the checkout with its pre-session snapshot and record target-relative paths. Reject
96
- * out-of-target and review-only writes before patch capture. Check the module assignment after
97
- * persisting the patch so a failed assignment still leaves the edits available for inspection. */
98
- async function recordAgentEdits({ baseline, options, patchPath, assignedFiles }, worktree, before, step) {
99
- const touched = changes(before, await captureTree(worktree.root));
100
- const scopePrefix = baseline.scope ? baseline.scope.split(sep).join('/') + '/' : '';
101
- const changedFiles = touched.filter(file => file.startsWith(scopePrefix)).map(file => file.slice(scopePrefix.length));
102
- step.changedFiles = changedFiles;
103
- if (touched.length !== changedFiles.length)
104
- throw new Error('Agent changed paths outside the refactor target');
105
- if (options.reviewOnly && touched.length)
106
- throw new Error('Review-only agent modified files');
107
- if (changedFiles.length) {
108
- await writeFile(patchPath, await captureWorktreePatch(baseline, worktree, changedFiles));
109
- step.patch = patchPath;
110
- }
111
- if (assignedFiles) {
112
- await validateModuleEdits({ assignedFiles, changedFiles, before, scopePrefix, cwd: worktree.cwd, options });
113
- }
114
- }
115
- /** Allow assigned paths and newly added files that qualify as text source. Report every other
116
- * edited path in diff order. Source inspection can also reject, leaving the patch available. */
117
- async function validateModuleEdits(input) {
118
- const { assignedFiles, changedFiles, before, scopePrefix, cwd, options } = input;
119
- const assigned = new Set(assignedFiles);
120
- const violations = [];
121
- for (const file of changedFiles) {
122
- if (assigned.has(file))
123
- continue;
124
- if (!before.has(scopePrefix + file) && isSource(file, options.include, options.exclude)
125
- && await isTextSource(cwd, file))
126
- continue;
127
- violations.push(file);
128
- }
129
- if (violations.length)
130
- throw new Error(`Module edited paths outside its assignment: ${violations.join(', ')}`);
131
- }
package/src/checks.d.ts DELETED
@@ -1,26 +0,0 @@
1
- import type { CheckResult } from "./results.js";
2
- /** Configure validation after an applied patch. Strings go to the platform shell. Objects
3
- * launch the named executable directly with literal arguments, defaulting to no arguments. */
4
- export type CheckCommand = string | {
5
- executable: string;
6
- args?: readonly string[];
7
- };
8
- /** Reject a blank command or executable, or a NUL in a command, executable or literal argument.
9
- * refactorCode runs this before repository preflight and parseCliInput uses it before client
10
- * creation. Omitted and empty lists pass this check. Only omission allows script discovery. */
11
- export declare function validateChecks(commands: readonly CheckCommand[] | undefined, label?: string): void;
12
- /** Discover typecheck then test for refactorCode when checks are omitted outside review-only mode.
13
- * Includes only string-valued scripts in the target package.json. A packageManager declaration
14
- * starting with bun@, npm@, pnpm@ or yarn@ selects that runner; otherwise uses npm.
15
- * Reads no parent packages and starts no process.
16
- * Missing package.json yields no checks; malformed JSON and other filesystem errors reject. */
17
- export declare function defaultChecks(cwd: string): Promise<CheckCommand[]>;
18
- /** Execute validation commands serially, appending bounded output to the caller's results array.
19
- * integrateAgentWork awaits this after applying a patch and converts rejection into a failed step.
20
- * Commands may modify files or start other processes.
21
- * Resolves void after all checks; the first failed command is recorded before rejection and stops
22
- * later commands. Each process has a five-minute timeout and an eight-MiB
23
- * limit on each output stream. Reports concatenate stdout then stderr, followed by the error
24
- * message on failure, and retain only the final 4,000 characters. An empty command list resolves
25
- * without changing results; existing entries are retained. */
26
- export declare function runChecks(cwd: string, commands: readonly CheckCommand[], results: CheckResult[]): Promise<void>;
package/src/checks.js DELETED
@@ -1,66 +0,0 @@
1
- // Discovers and executes ordered validation commands for changed refactor steps.
2
- import { readFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { message } from "./errors.js";
5
- import { exec } from "./process.js";
6
- /** Reject a blank command or executable, or a NUL in a command, executable or literal argument.
7
- * refactorCode runs this before repository preflight and parseCliInput uses it before client
8
- * creation. Omitted and empty lists pass this check. Only omission allows script discovery. */
9
- export function validateChecks(commands, label = 'check') {
10
- for (const command of commands ?? []) {
11
- const executable = typeof command === 'string' ? command : command.executable;
12
- if (!executable.trim())
13
- throw new Error(`${label} commands must be nonempty`);
14
- if (executable.includes('\0') || (typeof command !== 'string' && command.args?.some(arg => arg.includes('\0')))) {
15
- throw new Error(`${label} commands and arguments cannot contain NUL`);
16
- }
17
- }
18
- }
19
- /** Discover typecheck then test for refactorCode when checks are omitted outside review-only mode.
20
- * Includes only string-valued scripts in the target package.json. A packageManager declaration
21
- * starting with bun@, npm@, pnpm@ or yarn@ selects that runner; otherwise uses npm.
22
- * Reads no parent packages and starts no process.
23
- * Missing package.json yields no checks; malformed JSON and other filesystem errors reject. */
24
- export async function defaultChecks(cwd) {
25
- let pkg;
26
- try {
27
- pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8'));
28
- }
29
- catch (cause) {
30
- if (cause.code === 'ENOENT')
31
- return [];
32
- throw cause;
33
- }
34
- const manager = /^(bun|npm|pnpm|yarn)@/.exec(pkg.packageManager ?? '')?.[1] ?? 'npm';
35
- return ['typecheck', 'test'].filter(name => typeof pkg.scripts?.[name] === 'string').map(name =>
36
- // Windows package managers other than Bun are commonly provided by .cmd shims.
37
- process.platform === 'win32' && manager !== 'bun'
38
- ? `${manager} run ${name}`
39
- : { executable: manager, args: ['run', name] });
40
- }
41
- /** Execute validation commands serially, appending bounded output to the caller's results array.
42
- * integrateAgentWork awaits this after applying a patch and converts rejection into a failed step.
43
- * Commands may modify files or start other processes.
44
- * Resolves void after all checks; the first failed command is recorded before rejection and stops
45
- * later commands. Each process has a five-minute timeout and an eight-MiB
46
- * limit on each output stream. Reports concatenate stdout then stderr, followed by the error
47
- * message on failure, and retain only the final 4,000 characters. An empty command list resolves
48
- * without changing results; existing entries are retained. */
49
- export async function runChecks(cwd, commands, results) {
50
- const limits = { cwd, maxBuffer: 8 << 20, timeout: 300_000, windowsHide: true };
51
- for (const command of commands) {
52
- const display = typeof command === 'string' ? command : [command.executable, ...(command.args ?? [])]
53
- .map(arg => /^[\w./:-]+$/.test(arg) ? arg : JSON.stringify(arg)).join(' ');
54
- try {
55
- const { stdout, stderr } = typeof command === 'string'
56
- ? await exec(command, [], { ...limits, shell: true })
57
- : await exec(command.executable, [...command.args ?? []], limits);
58
- results.push({ command: display, status: 'passed', output: `${stdout}${stderr}`.slice(-4000) });
59
- }
60
- catch (cause) {
61
- const error = cause;
62
- results.push({ command: display, status: 'failed', output: `${error.stdout ?? ''}${error.stderr ?? ''}\n${message(cause)}`.slice(-4000) });
63
- throw new Error(`Validation failed: ${display}`);
64
- }
65
- }
66
- }
package/src/cli.d.ts DELETED
@@ -1,27 +0,0 @@
1
- import type { Client } from '@anureo/sdk';
2
- import { type HarnessSelection } from "./client.js";
3
- import type { GraphLoader } from "./graph.js";
4
- /** Run an installed CLI command with arguments after the executable path.
5
- * bin/anureo-refactor.ts awaits the result as its exit code. Returns 0 for help or completion
6
- * and 2 for incomplete runs or caught argument, run, output or cleanup failures.
7
- * Help and argument errors acquire no client; disposal of an acquired client is awaited before this settles.
8
- * Orchestration may edit files and start processes. Supplied output callbacks run synchronously,
9
- * and an error diagnostic callback that throws still rejects. */
10
- export declare function runCli(args: string[], dependencies?: CliDependencies): Promise<number>;
11
- /** Internal overrides for runCli tests; omitted fields use production factories, paths and streams. */
12
- interface CliDependencies {
13
- /** Factory for the CLI-owned client; runCli awaits disposal even after execution fails. */
14
- createClient?: (cwd: string, harness: HarnessSelection) => Promise<Client>;
15
- /** Supply a validated graph for the canonical target, finishing exporter cleanup before resolving. */
16
- graphLoader?: GraphLoader;
17
- /** Base directory for relative repository and repograph paths; defaults to process.cwd(). */
18
- cwd?: string;
19
- /** Environment for the fallback CODEX_MODEL lookup. Omit to read process.env.
20
- * Client creation and subprocess launch still use the process environment. */
21
- env?: Record<string, string | undefined>;
22
- /** Synchronous help/report sink; a thrown error enters CLI error reporting. */
23
- stdout?: (text: string) => void;
24
- /** Synchronous progress/error sink; progress errors are recorded, error-reporting throws may reject runCli. */
25
- stderr?: (text: string) => void;
26
- }
27
- export {};