iterate-plugin 2.5.0 → 2.7.0

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.
@@ -0,0 +1,337 @@
1
+ /**
2
+ * The iterate skill prompt injected into the system prompt.
3
+ *
4
+ * This teaches the model how to write a correct `workflow` script that
5
+ * performs the iterate autonomous closed-loop (or dry-run pure review),
6
+ * using the registered tools via subagents.
7
+ */
8
+ export const ITERATE_SKILL_PROMPT = `
9
+ ## Iterate Workflow (autonomous code iteration)
10
+
11
+ You have the iterate plugin installed, which registers these tools:
12
+ - \`iterate_config\` — read iterate.config.yaml (dimensions, validation commands, personalization) or write a validated partial update (operation:"write", with automatic backup + rollback)
13
+ - \`iterate_validate\` — run a whitelisted validation command
14
+ - \`iterate_decision_log\` — append to the decision log, or read entries back for review
15
+ - \`iterate_context\` — read SKILL.md / ITERATE.md project context
16
+ - \`iterate_review\` — deterministic review engine: \`plan\` builds the review plan; \`aggregate\` dedupes/merges findings and computes convergence. Purely computational.
17
+ - \`iterate_triage\` — manage "known_intentional" entries in the config (list / apply, with dedupe + backup + rollback)
18
+ - \`iterate_fix\` — apply ONE atomic fix: backs up the file, enforces the atomic max_lines threshold, writes the new content, and records the fix (id + diff summary) in \`.iterate/fixes/registry.json\`
19
+ - \`iterate_diff\` — show the accumulated diff for a fixed file (vs its original backup) or a per-file summary of all fixes
20
+ - \`iterate_rollback\` — revert a fix by id: restore the file from its backup, remove the fix from the registry, log a \`revert\` entry. Use when a round's validation fails
21
+ - \`iterate_checkpoint\` — save / load / clear an iteration checkpoint (\`.iterate/checkpoint.json\`) so a long run can resume where it left off
22
+ - \`iterate_status\` — summarize the current run: mode, round, fixes applied, architectural remaining, decision-log size, checkpoint presence
23
+
24
+ ### When to use
25
+ When the user asks to review or iterate on the project (e.g. "review this project", "iterate on error handling", "check the codebase for issues", "dry-run review", "反复审查"), run an iterate **workflow** by calling the \`workflow\` tool.
26
+ - If the user says "review only" / "dry run" / "不要改文件" / "反复审查" → use \`mode: "dry-run"\`.
27
+ - Otherwise → use \`mode: "normal"\`.
28
+
29
+ ### Workflow script contract
30
+ Write a plain-JS script (top-level await, ends with \`return <json>\`). Available globals:
31
+ - \`agent(prompt, opts?): Promise<value>\` — spawn a subagent. \`opts.schema\` gives structured output (object-rooted JSON Schema: type/properties/required/additionalProperties/items/enum/const/oneOf only). Resolves \`null\` on child failure. Other opts: \`label\`, \`phase\`.
32
+ - \`parallel(thunks): Promise<value[]>\` — run zero-arg async functions concurrently, await all.
33
+ - \`phase(title)\`, \`log(message)\` — progress narration.
34
+ - \`args\` — the args object passed to the workflow tool.
35
+
36
+ The script CANNOT call tools directly. Subagents are the ones who call tools.
37
+
38
+ ### Dry-run mode workflow (pure review — the ONLY mode that never touches files)
39
+ This is iterate's read-only health-check: repeated review rounds until findings converge,
40
+ then produce an auditable report, then audit the report itself (meta-review) and give a
41
+ final review report. NO file writes, NO git, NO branches, NO worktree.
42
+
43
+ Canonical script — reproduce this structure exactly (adjust dims via the plan):
44
+
45
+ \`\`\`js
46
+ phase('plan')
47
+ const planRes = await agent(
48
+ 'Call iterate_review({operation:"plan", mode:"dry-run"}) and return the plan JSON.',
49
+ { label: 'review:plan' }
50
+ )
51
+ const plan = (planRes && planRes.plan) ? planRes.plan : null
52
+ if (!plan || !Array.isArray(plan.dimensions)) throw new Error('plan failed: iterate_review did not return a valid plan')
53
+ const dims = plan.dimensions.map(d => d.id)
54
+ const maxRounds = plan.maxReviewRounds
55
+ const knownIntentional = (plan.knownIntentional || []) // config personalization filter, applied in aggregate
56
+ let known = [] // cumulative DEDUPED findings fed back to reviewers
57
+ const rounds = [] // raw per-round findings
58
+
59
+ phase('review')
60
+ for (let r = 1; r <= maxRounds; r++) {
61
+ log('round ' + r + ' of ' + maxRounds + ' — finding NEW issues only')
62
+ const raw = await parallel(dims.map(dim => () => agent(
63
+ 'Review dimension "' + dim + '". Already-known findings (do NOT re-report): ' +
64
+ JSON.stringify(known) + '\\nReturn the findings JSON object.',
65
+ { label: 'review:' + dim + ':r' + r, schema: plan.dimensions.find(x => x.id === dim).findingsSchema }
66
+ )))
67
+ const thisRound = { round: r, findings: [].concat(...raw.map(x => x && x.findings ? x.findings : [])) }
68
+ rounds.push(thisRound)
69
+ // Deterministic aggregate: cross-round dedupe + known_intentional filter + severity sort.
70
+ const agg = await agent(
71
+ 'Call iterate_review({operation:"aggregate", mode:"dry-run", rounds:' + JSON.stringify(rounds) + ', maxReviewRounds:' + maxRounds + ', knownIntentional:' + JSON.stringify(knownIntentional) + '}) and return the report JSON.',
72
+ { label: 'review:aggregate:r' + r }
73
+ )
74
+ // Feed the DEDUPED + already-filtered set back (not raw findings) so the known
75
+ // list stays bounded and reviewers never see the same issue twice.
76
+ if (agg && agg.report && Array.isArray(agg.report.findings)) known = agg.report.findings
77
+ if (agg && agg.report && agg.report.convergence && agg.report.convergence.findingsByRound[r-1] === 0) {
78
+ log('round ' + r + ' found 0 new findings — converged')
79
+ break
80
+ }
81
+ }
82
+
83
+ phase('report')
84
+ const finalAgg = await agent(
85
+ 'Call iterate_review({operation:"aggregate", mode:"dry-run", rounds:' + JSON.stringify(rounds) + ', maxReviewRounds:' + maxRounds + ', knownIntentional:' + JSON.stringify(knownIntentional) + '}) and return the report JSON.',
86
+ { label: 'review:aggregate:final' }
87
+ )
88
+ const report = (finalAgg && finalAgg.report) ? finalAgg.report : null
89
+ if (!report || !report.convergence) throw new Error('aggregate failed: no valid report was produced')
90
+ await agent(
91
+ 'Call iterate_decision_log({operation:"append", type:"report", round:' + report.convergence.totalRounds + ', data:{mode:"dry-run", totalFindings:' + report.summary.totalFindings + '}})',
92
+ { label: 'review:log' }
93
+ )
94
+
95
+ phase('meta-review')
96
+ // Audit the report itself for internal consistency, then produce the final report.
97
+ const metaRes = await agent(
98
+ 'Call iterate_review({operation:"meta-review", report:' + JSON.stringify(report) + '}) and return the finalReport JSON.',
99
+ { label: 'review:meta' }
100
+ )
101
+ const finalReport = metaRes && metaRes.finalReport ? metaRes.finalReport : null
102
+ const metaAudit = finalReport && finalReport.metaReview ? finalReport.metaReview : null
103
+
104
+ return {
105
+ mode: 'dry-run',
106
+ goal: report.goal,
107
+ rounds: rounds.length,
108
+ converged: report.convergence.converged,
109
+ stoppedReason: report.convergence.stoppedReason,
110
+ findingsByRound: report.convergence.findingsByRound,
111
+ totalFindings: report.summary.totalFindings,
112
+ bySeverity: { critical: report.summary.critical, high: report.summary.high, medium: report.summary.medium, low: report.summary.low },
113
+ byDimension: report.summary.byDimension,
114
+ report,
115
+ metaReview: metaAudit ? { verdict: finalReport.verdict, issues: metaAudit.issues || [], checksRun: metaAudit.checksRun || 0 } : null,
116
+ finalReport
117
+ }
118
+ \`\`\`
119
+
120
+ Key rules for dry-run:
121
+ - **NEVER call a fixer / never edit files / never create branches or worktree.** Reviewers read only.
122
+ - Each round feeds the already-known findings to reviewers so they hunt NEW issues only → that is what drives convergence.
123
+ - Stop when a round reports 0 new findings (converged) or maxReviewRounds is reached.
124
+ - The report (with per-round convergence stats + suggested fix priorities) is the deliverable.
125
+ - **Meta-review**: after building the report, audit it with \`iterate_review({operation:"meta-review"})\` for internal consistency (counts, severity buckets, dimension sums, sort order, convergence math). The \`finalReport.verdict\` is \`approved\` only when the report passes every check; otherwise \`needs_revision\`. Surface the final report and its verdict as the closing deliverable.
126
+ - Only a single \`report\` entry may be appended to the decision log; nothing else is written.
127
+
128
+ ### Normal-mode workflow (autonomous closed loop)
129
+ Set \`args.mode = "normal"\`. Loop: resume → plan → parallel review ×N → atomic fixes via \`iterate_fix\` → validate → rollback on failure → checkpoint → loop → auto-stop when zero findings remain.
130
+ Canonical script — reproduce this structure exactly (adjust dims via the plan):
131
+
132
+ \`\`\`js
133
+ // args = { mode: "normal", maxRounds? }
134
+ phase('resume')
135
+ // If a previous run was interrupted, resume from its checkpoint instead of restarting.
136
+ const ckRes = await agent(
137
+ 'Call iterate_checkpoint({ operation: "load" }) and return the checkpoint JSON.',
138
+ { label: 'checkpoint:load' }
139
+ )
140
+ const checkpoint = (ckRes && ckRes.checkpoint) ? ckRes.checkpoint : null
141
+ const startRound = (checkpoint && typeof checkpoint.round === 'number') ? checkpoint.round + 1 : 1
142
+
143
+ phase('plan')
144
+ const configRes = await agent(
145
+ 'Call iterate_config({ validate: true }) and return the config JSON.',
146
+ { label: 'config:read' }
147
+ )
148
+ const cfg = (configRes && configRes.config) ? configRes.config : null
149
+ const atomicMaxLines = (cfg && cfg.atomic && cfg.atomic.max_lines) ? cfg.atomic.max_lines : 20
150
+ const planRes = await agent(
151
+ 'Call iterate_review({operation:"plan", mode:"normal", maxReviewRounds:' + (args.maxRounds || 3) + '}) and return the plan JSON.',
152
+ { label: 'review:plan' }
153
+ )
154
+ const plan = (planRes && planRes.plan) ? planRes.plan : null
155
+ if (!plan || !Array.isArray(plan.dimensions)) throw new Error('plan failed: iterate_review did not return a valid plan')
156
+ const knownIntentional = (plan.knownIntentional || []) // config personalization filter, applied in aggregate
157
+ const dims = plan.dimensions.map(d => d.id)
158
+ const maxRounds = plan.maxReviewRounds
159
+ const rounds = [] // findings per review round (each on the then-current code state)
160
+ const architectural = [] // findings deliberately left unfixed (reported at the end)
161
+ let fixedCount = (checkpoint && typeof checkpoint.fixedCount === 'number') ? checkpoint.fixedCount : 0
162
+ let converged = false
163
+ let abortedByValidation = false
164
+ let failedCommands = []
165
+
166
+ phase('loop')
167
+ for (let r = startRound; r <= maxRounds; r++) {
168
+ log('round ' + r + ' of ' + maxRounds + ' — review current state, fix atomics via iterate_fix, validate')
169
+ const raw = await parallel(dims.map(dim => () => agent(
170
+ 'Review dimension "' + dim + '" on the CURRENT code state (previous atomic findings are fixed). ' +
171
+ 'Do NOT re-report already-known architectural findings: ' + JSON.stringify(architectural) + '\\nReturn the findings JSON object.',
172
+ { label: 'review:' + dim + ':r' + r, schema: plan.dimensions.find(x => x.id === dim).findingsSchema }
173
+ )))
174
+ const thisRound = { round: r, findings: [].concat(...raw.map(x => x && x.findings ? x.findings : [])) }
175
+ rounds.push(thisRound)
176
+
177
+ // Deterministic dedupe / known_intentional filter / severity sort for this round.
178
+ const agg = await agent(
179
+ 'Call iterate_review({operation:"aggregate", mode:"normal", rounds:' + JSON.stringify([thisRound]) + ', knownIntentional:' + JSON.stringify(knownIntentional) + '}) and return the report JSON.',
180
+ { label: 'review:aggregate:r' + r }
181
+ )
182
+ const findings = (agg && agg.report && agg.report.findings) ? agg.report.findings : thisRound.findings
183
+ const atomic = findings.filter(f => f.is_atomic === true)
184
+ const remaining = findings.filter(f => f.is_atomic !== true)
185
+
186
+ const roundFixIds = []
187
+ if (atomic.length > 0) {
188
+ // Group atomic fixes by file. One fixer agent handles a whole file serially —
189
+ // calling iterate_fix per finding (the ONLY sanctioned writer), then
190
+ // iterate_diff to verify — so the same file is never edited concurrently;
191
+ // different files still run in parallel.
192
+ const byFile = {}
193
+ atomic.forEach(f => { (byFile[f.file] = byFile[f.file] || []).push(f) })
194
+ const fixRes = await parallel(Object.keys(byFile).map(file => () => agent(
195
+ 'Apply the fixes for ' + file + ' using iterate_fix. For EACH finding in this list, ' +
196
+ 'read the current file, compute the edited full content (change <= ' + atomicMaxLines + ' lines), and call ' +
197
+ 'iterate_fix({ file: "' + file + '", content: <full new file content>, finding: <that finding>, round: ' + r + ' }). ' +
198
+ 'Apply the findings IN ORDER. After all fixes, call iterate_diff({ file: "' + file + '" }) to verify the accumulated diff. ' +
199
+ 'Findings: ' + JSON.stringify(byFile[file]) + '. Return the array of {id, ok, error} per iterate_fix call.',
200
+ { label: 'fix:' + file, phase: 'fix', schema: {
201
+ type: 'object', additionalProperties: false,
202
+ properties: {
203
+ fixes: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: { type: 'string' }, ok: { type: 'boolean' }, error: { type: 'string' } }, required: ['id', 'ok'] } }
204
+ },
205
+ required: ['fixes'] } }
206
+ )))
207
+ for (const res of fixRes) {
208
+ if (res && Array.isArray(res.fixes)) {
209
+ for (const fx of res.fixes) {
210
+ if (fx && fx.ok === true) { fixedCount += 1; roundFixIds.push(fx.id) }
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ // Cross-round dedupe of architectural findings before accumulating.
217
+ const seenKeys = architectural.map(a => a.file + '|' + a.dimension + '|' + a.summary)
218
+ for (const f of remaining) {
219
+ const key = f.file + '|' + f.dimension + '|' + f.summary
220
+ if (seenKeys.indexOf(key) < 0) { architectural.push(f); seenKeys.push(key) }
221
+ }
222
+
223
+ // Validate every configured command; on ANY failure roll back this round's fixes.
224
+ const valRes = await agent(
225
+ 'Read iterate.config.yaml validation.commands, then call iterate_validate({ command: <cmd> }) for EACH configured command ' +
226
+ '(one tool call per command). Return all results as {command, exitCode} entries.',
227
+ { label: 'validate:r' + r, phase: 'validate', schema: {
228
+ type: 'object', additionalProperties: false,
229
+ properties: {
230
+ results: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { command: { type: 'string' }, exitCode: { type: 'integer' } }, required: ['command', 'exitCode'] } }
231
+ },
232
+ required: ['results'] } }
233
+ )
234
+ failedCommands = (valRes && Array.isArray(valRes.results)) ? valRes.results.filter(v => v.exitCode !== 0).map(v => v.command) : []
235
+ if (failedCommands.length > 0) {
236
+ log('round ' + r + ' validation FAILED on: ' + failedCommands.join(', ') + ' — rolling back this round')
237
+ abortedByValidation = true
238
+ if (roundFixIds.length > 0) {
239
+ await agent(
240
+ 'Call iterate_rollback({ id: <id> }) for EACH of these fix ids (one call per id): ' + JSON.stringify(roundFixIds) + '. Return the array of {id, ok, error}.',
241
+ { label: 'rollback:r' + r, phase: 'rollback', schema: {
242
+ type: 'object', additionalProperties: false,
243
+ properties: {
244
+ results: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { id: { type: 'string' }, ok: { type: 'boolean' }, error: { type: 'string' } }, required: ['id', 'ok'] } }
245
+ },
246
+ required: ['results'] } }
247
+ )
248
+ }
249
+ await agent(
250
+ 'Call iterate_decision_log({operation:"append", type:"round_failed", round:' + r + ', data:{failedCommands:' + JSON.stringify(failedCommands) + ', rolledBack:' + roundFixIds.length + '}})',
251
+ { label: 'log:failed:r' + r }
252
+ )
253
+ break
254
+ }
255
+
256
+ await agent(
257
+ 'Call iterate_decision_log({operation:"append", type:"review_result", round:' + r +
258
+ ', data:{atomic:' + atomic.length + ', architectural:' + remaining.length + ', fixedSoFar:' + fixedCount + '}})',
259
+ { label: 'log:r' + r }
260
+ )
261
+
262
+ // Persist progress so an interrupted run can resume from the next round.
263
+ await agent(
264
+ 'Call iterate_checkpoint({ operation: "save", mode: "normal", round:' + r + ', maxRounds:' + maxRounds + ', fixedCount:' + fixedCount + ', architecturalCount:' + architectural.length + ', findings:' + JSON.stringify(architectural) + ' }) and return the checkpoint JSON.',
265
+ { label: 'checkpoint:save:r' + r }
266
+ )
267
+
268
+ if (atomic.length === 0 && remaining.length === 0) {
269
+ log('round ' + r + ' found nothing to fix — converged')
270
+ converged = true
271
+ break
272
+ }
273
+ }
274
+
275
+ phase('report')
276
+ await agent(
277
+ 'Call iterate_decision_log({operation:"append", type:"report", round:' + rounds.length +
278
+ ', data:{mode:"normal", fixed:' + fixedCount + ', architectural:' + architectural.length + '}})',
279
+ { label: 'report:log' }
280
+ )
281
+ const statusRes = await agent(
282
+ 'Call iterate_status() and return the status JSON.',
283
+ { label: 'status:final' }
284
+ )
285
+ const status = (statusRes && statusRes.ok) ? statusRes : null
286
+ if (!abortedByValidation) {
287
+ // Iteration finished cleanly → clear the checkpoint so the next run starts fresh.
288
+ await agent(
289
+ 'Call iterate_checkpoint({ operation: "clear" }) and return {ok, existed}.',
290
+ { label: 'checkpoint:clear' }
291
+ )
292
+ }
293
+ return {
294
+ mode: 'normal',
295
+ goal: plan.goal,
296
+ roundsExecuted: rounds.length,
297
+ maxRounds: maxRounds,
298
+ converged: converged,
299
+ abortedByValidation: abortedByValidation,
300
+ failedCommands: failedCommands,
301
+ findingsFixed: fixedCount,
302
+ remainingArchitecturalCount: architectural.length,
303
+ remainingArchitectural: architectural,
304
+ status: status ? {
305
+ currentRound: status.currentRound,
306
+ totalRounds: status.totalRounds,
307
+ fixedCount: status.fixedCount,
308
+ architecturalCount: status.architecturalCount,
309
+ findingsCount: status.findingsCount,
310
+ hasCheckpoint: status.hasCheckpoint
311
+ } : null
312
+ }
313
+ \`\`\`
314
+
315
+ Key rules for normal mode:
316
+ - Fixers are the ONLY agents allowed to write files, and they must go through \`iterate_fix\` — never edit files directly. That is what gives every change a backup, a diff, and a rollback path. Reviewers read only. Architectural findings are reported, never auto-fixed.
317
+ - Aggregate the current round deterministically (\`report.findings\`) before fixing, so fixes act on deduped/filtered/sorted findings.
318
+ - Apply atomic fixes **per file**: one fixer agent handles all findings for a given file serially (so the same file is never edited concurrently); different files are fixed in parallel.
319
+ - **Resume**: load the checkpoint first; if a previous run left one, continue from \`checkpoint.round + 1\` (its \`fixedCount\` and deduped \`findings\` are carried forward).
320
+ - **Validate after every round** of fixes; on ANY validation failure, roll back the round's fixes via \`iterate_rollback\` and stop (the checkpoint is left in place so the run can be resumed).
321
+ - **Checkpoint after every round**; clear it only when the iteration completes cleanly.
322
+ - Stop when a round produces nothing to fix (converged) or maxReviewRounds is reached.
323
+ - Every round, every rollback, and the final report go to the append-only decision log.
324
+ - Close with \`iterate_status\` metrics and surface the convergence indicators (fixed count, remaining architectural count, abort reason) in the final summary.
325
+
326
+ ### Finding schema (for reviewer agents)
327
+ { "dimension": string, "file": string (relative path), "line": number (optional),
328
+ "severity": "critical" | "high" | "medium" | "low", "summary": string (one line),
329
+ "failure_scenario": string (how/when it fails), "suggested_fix": string (the concrete fix),
330
+ "is_atomic": boolean (true if fix ≤ max_lines within a single file/function) }
331
+ Atomic = is_atomic true (single file, single function, ≤ config.atomic.max_lines lines change). Architectural = everything else.
332
+
333
+ ### Workflow meta
334
+ Always pass \`meta: { name: "iterate", description: "Autonomous iterate loop" }\`.
335
+
336
+ Always end with a clear summary: total findings, count by severity, fixes applied (normal) or convergence stats (dry-run), and remaining architectural findings.
337
+ `;
@@ -0,0 +1,260 @@
1
+ /**
2
+ * src/tools/checkpoint.ts — iteration checkpoint + status tools.
3
+ *
4
+ * iterate_checkpoint — save / load / clear a resume checkpoint so a long
5
+ * iteration can continue where it left off.
6
+ * iterate_status — summarize the current iteration state from the
7
+ * decision log, fix registry, and checkpoint.
8
+ *
9
+ * Checkpoint layout: `.iterate/checkpoint.json`.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
12
+ import { defineTool } from '@deepseek-ai/dsh-tools';
13
+ import { resolveProjectRoot } from "../config-loader.js";
14
+ import { checkpointPath, iterateDir } from "../paths.js";
15
+ import { readRegistry } from "./fix.js";
16
+ import { readDecisionEntries } from "./decision-log.js";
17
+ // ─── Pure helpers (exported for unit tests) ─────────────────────────────────
18
+ /** Read a checkpoint from disk (missing/corrupt → null). */
19
+ export function readCheckpoint(projectRoot) {
20
+ const file = checkpointPath(projectRoot);
21
+ if (!existsSync(file))
22
+ return null;
23
+ try {
24
+ const parsed = JSON.parse(readFileSync(file, 'utf-8'));
25
+ if (!parsed || typeof parsed !== 'object')
26
+ return null;
27
+ if (parsed.mode !== 'dry-run' && parsed.mode !== 'normal')
28
+ return null;
29
+ if (typeof parsed.round !== 'number')
30
+ return null;
31
+ return parsed;
32
+ }
33
+ catch {
34
+ return null;
35
+ }
36
+ }
37
+ /** Validate a checkpoint payload (returns error string or null). */
38
+ export function validateCheckpoint(input) {
39
+ if (input.mode !== 'dry-run' && input.mode !== 'normal') {
40
+ return 'mode must be "dry-run" or "normal"';
41
+ }
42
+ if (typeof input.round !== 'number' || !Number.isInteger(input.round) || input.round < 0) {
43
+ return 'round must be a non-negative integer';
44
+ }
45
+ if (typeof input.maxRounds !== 'number' || !Number.isInteger(input.maxRounds) || input.maxRounds < 1) {
46
+ return 'maxRounds must be a positive integer';
47
+ }
48
+ if (typeof input.fixedCount !== 'number' || !Number.isInteger(input.fixedCount) || input.fixedCount < 0) {
49
+ return 'fixedCount must be a non-negative integer';
50
+ }
51
+ if (typeof input.architecturalCount !== 'number' || !Number.isInteger(input.architecturalCount) || input.architecturalCount < 0) {
52
+ return 'architecturalCount must be a non-negative integer';
53
+ }
54
+ return null;
55
+ }
56
+ /**
57
+ * Compute a status summary from the runtime artifacts.
58
+ * Pure (no I/O) — all reads are injected, so it is unit-testable.
59
+ */
60
+ export function computeStatus(input) {
61
+ const checkpoint = input.checkpoint;
62
+ const entries = input.decisionEntries;
63
+ const registry = input.fixRegistry;
64
+ const lastEntry = entries.length > 0 ? entries[entries.length - 1] : null;
65
+ const lastUpdated = lastEntry?.timestamp ?? checkpoint?.updatedAt ?? null;
66
+ // Round = checkpoint.round (explicit) or max round seen in the decision log.
67
+ let currentRound = checkpoint?.round ?? 0;
68
+ if (!checkpoint) {
69
+ for (const e of entries) {
70
+ if (typeof e.round === 'number' && e.round > currentRound)
71
+ currentRound = e.round;
72
+ }
73
+ }
74
+ const totalRounds = checkpoint?.maxRounds ?? currentRound;
75
+ const registryFixed = registry.rounds.reduce((sum, r) => sum + r.fixedCount, 0);
76
+ const failedCount = registry.rounds.reduce((sum, r) => sum + r.failedCount, 0);
77
+ // When a checkpoint exists, its snapshot fields are authoritative for resume
78
+ // (fixedCount / architecturalCount / findings); otherwise derive from the
79
+ // live fix registry and decision log.
80
+ const fixedCount = checkpoint ? checkpoint.fixedCount : registryFixed;
81
+ const architecturalCount = checkpoint?.architecturalCount ?? 0;
82
+ return {
83
+ mode: checkpoint?.mode ?? null,
84
+ currentRound,
85
+ totalRounds,
86
+ fixedCount,
87
+ architecturalCount,
88
+ findingsCount: checkpoint?.findings.length ?? 0,
89
+ totalDecisionLogEntries: entries.length,
90
+ hasCheckpoint: checkpoint !== null,
91
+ checkpoint,
92
+ lastUpdated,
93
+ };
94
+ }
95
+ // ─── iterate_checkpoint ──────────────────────────────────────────────────────
96
+ /**
97
+ * Register the `iterate_checkpoint` tool.
98
+ * Saves progress so the orchestrator can resume a long iteration.
99
+ */
100
+ export function registerCheckpointTool(ctx) {
101
+ ctx.tools.register(defineTool({
102
+ name: 'iterate_checkpoint',
103
+ description: 'Save / load / clear the iteration checkpoint. The workflow saves a checkpoint at the start of ' +
104
+ 'each round (so a long run can resume) and clears it when the iteration completes.',
105
+ parameters: {
106
+ operation: {
107
+ type: 'string',
108
+ required: true,
109
+ description: '"save" to persist the current progress, "load" to read it back, "clear" to remove it.',
110
+ enum: ['save', 'load', 'clear'],
111
+ },
112
+ mode: { type: 'string', description: 'Required for save: "dry-run" or "normal".' },
113
+ round: { type: 'integer', description: 'Required for save: current round number (0 = none started).' },
114
+ maxRounds: { type: 'integer', description: 'Required for save: total round cap.' },
115
+ fixedCount: { type: 'integer', description: 'Required for save: number of fixes applied so far.' },
116
+ architecturalCount: { type: 'integer', description: 'Required for save: architectural findings left unfixed.' },
117
+ findings: { type: 'json', description: 'Optional for save: the current deduped findings to resume from.' },
118
+ path: { type: 'string', description: 'Project root directory (default: current working directory).' },
119
+ },
120
+ output: {
121
+ schema: {
122
+ type: 'object',
123
+ additionalProperties: false,
124
+ properties: {
125
+ operation: { type: 'string', required: true },
126
+ ok: { type: 'boolean', required: true },
127
+ checkpoint: { type: 'json' },
128
+ existed: { type: 'boolean' },
129
+ error: { type: 'string' },
130
+ },
131
+ },
132
+ render: (_args, value) => [
133
+ { type: 'text', text: JSON.stringify(value, null, 2) },
134
+ ],
135
+ },
136
+ async execute(args) {
137
+ const resolved = resolveProjectRoot(args.path);
138
+ if (!resolved.ok)
139
+ return { operation: args.operation, ok: false, error: resolved.reason };
140
+ const projectRoot = resolved.root;
141
+ if (args.operation === 'load') {
142
+ const checkpoint = readCheckpoint(projectRoot);
143
+ return { operation: 'load', ok: true, checkpoint: checkpoint ?? undefined };
144
+ }
145
+ if (args.operation === 'clear') {
146
+ const existed = existsSync(checkpointPath(projectRoot));
147
+ if (existed) {
148
+ try {
149
+ rmSync(checkpointPath(projectRoot), { force: true });
150
+ }
151
+ catch (err) {
152
+ return { operation: 'clear', ok: false, existed, error: `failed to clear checkpoint: ${String(err)}` };
153
+ }
154
+ }
155
+ return { operation: 'clear', ok: true, existed };
156
+ }
157
+ if (args.operation === 'save') {
158
+ const invalid = validateCheckpoint({
159
+ mode: args.mode,
160
+ round: args.round,
161
+ maxRounds: args.maxRounds,
162
+ fixedCount: args.fixedCount,
163
+ architecturalCount: args.architecturalCount,
164
+ });
165
+ if (invalid)
166
+ return { operation: 'save', ok: false, error: invalid };
167
+ const checkpoint = {
168
+ mode: args.mode,
169
+ round: args.round,
170
+ maxRounds: args.maxRounds,
171
+ fixedCount: args.fixedCount,
172
+ architecturalCount: args.architecturalCount,
173
+ findings: (Array.isArray(args.findings) ? args.findings : []),
174
+ startedAt: readCheckpoint(projectRoot)?.startedAt ?? new Date().toISOString(),
175
+ updatedAt: new Date().toISOString(),
176
+ };
177
+ try {
178
+ mkdirSync(iterateDir(projectRoot), { recursive: true });
179
+ writeFileSync(checkpointPath(projectRoot), JSON.stringify(checkpoint, null, 2), 'utf-8');
180
+ }
181
+ catch (err) {
182
+ return { operation: 'save', ok: false, error: `failed to write checkpoint: ${String(err)}` };
183
+ }
184
+ return { operation: 'save', ok: true, checkpoint: checkpoint };
185
+ }
186
+ return { operation: args.operation, ok: false, error: 'unknown operation. Use "save", "load", or "clear".' };
187
+ },
188
+ }));
189
+ }
190
+ // ─── iterate_status ──────────────────────────────────────────────────────────
191
+ /**
192
+ * Register the `iterate_status` tool.
193
+ * Summarizes the current iteration state (mode, round, fixed count, findings).
194
+ */
195
+ export function registerStatusTool(ctx) {
196
+ ctx.tools.register(defineTool({
197
+ name: 'iterate_status',
198
+ description: 'Summarize the current iterate run: mode, current round vs total, fixes applied, architectural ' +
199
+ 'findings remaining, decision-log size, and whether a resume checkpoint exists.',
200
+ parameters: {
201
+ path: { type: 'string', description: 'Project root directory (default: current working directory).' },
202
+ },
203
+ output: {
204
+ schema: {
205
+ type: 'object',
206
+ additionalProperties: false,
207
+ properties: {
208
+ ok: { type: 'boolean', required: true },
209
+ mode: { type: 'string' },
210
+ currentRound: { type: 'integer' },
211
+ totalRounds: { type: 'integer' },
212
+ fixedCount: { type: 'integer' },
213
+ architecturalCount: { type: 'integer' },
214
+ findingsCount: { type: 'integer' },
215
+ totalDecisionLogEntries: { type: 'integer' },
216
+ hasCheckpoint: { type: 'boolean' },
217
+ lastUpdated: { type: 'string' },
218
+ error: { type: 'string' },
219
+ },
220
+ },
221
+ render: (_args, value) => {
222
+ if (!value.ok)
223
+ return [{ type: 'text', text: `status failed: ${value.error}` }];
224
+ const lines = [
225
+ `Mode: ${value.mode ?? 'none'}`,
226
+ `Round: ${value.currentRound} / ${value.totalRounds}`,
227
+ `Fixed: ${value.fixedCount} · Architectural remaining: ${value.architecturalCount}`,
228
+ `Findings in checkpoint: ${value.findingsCount}`,
229
+ `Decision-log entries: ${value.totalDecisionLogEntries}`,
230
+ `Checkpoint: ${value.hasCheckpoint ? 'yes' : 'no'}`,
231
+ value.lastUpdated ? `Last updated: ${value.lastUpdated}` : '',
232
+ ];
233
+ return [{ type: 'text', text: lines.filter(Boolean).join('\n') }];
234
+ },
235
+ },
236
+ async execute(args) {
237
+ const resolved = resolveProjectRoot(args.path);
238
+ if (!resolved.ok)
239
+ return { ok: false, error: resolved.reason };
240
+ const projectRoot = resolved.root;
241
+ const status = computeStatus({
242
+ checkpoint: readCheckpoint(projectRoot),
243
+ decisionEntries: readDecisionEntries(projectRoot),
244
+ fixRegistry: readRegistry(projectRoot),
245
+ });
246
+ return {
247
+ ok: true,
248
+ mode: status.mode ?? undefined,
249
+ currentRound: status.currentRound,
250
+ totalRounds: status.totalRounds,
251
+ fixedCount: status.fixedCount,
252
+ architecturalCount: status.architecturalCount,
253
+ findingsCount: status.findingsCount,
254
+ totalDecisionLogEntries: status.totalDecisionLogEntries,
255
+ hasCheckpoint: status.hasCheckpoint,
256
+ lastUpdated: status.lastUpdated ?? undefined,
257
+ };
258
+ },
259
+ }));
260
+ }