@mmerterden/multi-agent-pipeline 23.6.0 → 23.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +6 -5
  3. package/README.tr.md +6 -5
  4. package/docs/architecture.md +7 -5
  5. package/docs/ecosystem.md +6 -6
  6. package/docs/engineering.md +1 -1
  7. package/docs/facts.json +4 -3
  8. package/package.json +1 -1
  9. package/pipeline/commands/multi-agent/SKILL.md +3 -2
  10. package/pipeline/commands/multi-agent/resume/SKILL.md +2 -0
  11. package/pipeline/commands/multi-agent/review-rounds/SKILL.md +94 -0
  12. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  13. package/pipeline/lib/usage-names.generated.mjs +3 -0
  14. package/pipeline/multi-agent-refs/_input-parser.md +1 -1
  15. package/pipeline/multi-agent-refs/component-dispatch.md +2 -2
  16. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  17. package/pipeline/multi-agent-refs/features/autopilot-circuit-breaker.md +4 -4
  18. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  19. package/pipeline/multi-agent-refs/features/review-rounds.md +40 -0
  20. package/pipeline/multi-agent-refs/features/rework-escalation.md +5 -4
  21. package/pipeline/multi-agent-refs/help/en.md +3 -1
  22. package/pipeline/multi-agent-refs/help/tr.md +3 -1
  23. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +1 -1
  24. package/pipeline/multi-agent-refs/phases/operations.md +1 -1
  25. package/pipeline/multi-agent-refs/phases/phase-0-init.md +1 -1
  26. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  27. package/pipeline/multi-agent-refs/phases/phase-3-review.md +7 -3
  28. package/pipeline/multi-agent-refs/resume/details.md +2 -0
  29. package/pipeline/office/index.html +2 -2
  30. package/pipeline/schemas/agent-state.schema.json +19 -1
  31. package/pipeline/schemas/phases.json +2 -2
  32. package/pipeline/schemas/prefs.schema.json +15 -3
  33. package/pipeline/schemas/token-budget.json +2 -2
  34. package/pipeline/scripts/gen-facts.mjs +9 -4
  35. package/pipeline/scripts/review-rounds.mjs +592 -0
  36. package/pipeline/scripts/rework-escalation.mjs +7 -3
  37. package/pipeline/scripts/validate-state.mjs +19 -11
  38. package/pipeline/skills/.skill-manifest.json +9 -5
  39. package/pipeline/skills/.skills-index.json +12 -1
  40. package/pipeline/skills/shared/README.md +4 -3
  41. package/pipeline/skills/shared/core/multi-agent/SKILL.md +3 -3
  42. package/pipeline/skills/shared/core/multi-agent-resume/SKILL.md +1 -1
  43. package/pipeline/skills/shared/core/multi-agent-review-rounds/SKILL.md +92 -0
  44. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  45. package/pipeline/skills/skills-index.md +2 -1
@@ -0,0 +1,592 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file review-rounds.mjs - how many times review may send work back to
4
+ * development, resolved in one place.
5
+ *
6
+ * With limit N, review may send work back to development N times, every rework
7
+ * is reviewed again, and the run stops when a review still has accepted
8
+ * findings after N reworks: N reworks, at most N + 1 reviews. The range is 1 to
9
+ * 3 (3 is the ceiling: the cap on `phases["2"].reworkCount`) and the default is
10
+ * 2. `phases["2"].reworkCount` counts those reworks; `retryCount` counts build
11
+ * retries and is a separate counter.
12
+ *
13
+ * Precedence, first valid value wins:
14
+ * flag `state.reviewRounds`, recorded from `--review-rounds N` for one run
15
+ * repo `prefs.projects.<project>.maxReworkCycles`
16
+ * global `prefs.global.review.maxReworkCycles`
17
+ * default 2
18
+ * In an autopilot run (`state.autopilot`, or MULTI_AGENT_UNATTENDED=1) with the
19
+ * circuit-breaker enabled, `prefs.global.autopilotCircuitBreaker.maxReworkCycles`
20
+ * lowers the result (source `breaker`); it never raises it. A stored value
21
+ * outside 1..3 is ignored and reported, never clamped.
22
+ *
23
+ * The project key is the main repository's folder name as is (the value of
24
+ * `state.project`), the same key on the command side and on the run side.
25
+ *
26
+ * Usage:
27
+ * review-rounds.mjs get [--json | --value] [--state <agent-state.json>] [--project <key>]
28
+ * review-rounds.mjs set <1|2|3> [--repo [--project <key>]]
29
+ * review-rounds.mjs reset [--repo [--project <key>]]
30
+ * review-rounds.mjs parse <modifier text>
31
+ * review-rounds.mjs record --state <agent-state.json> --rounds <1|2|3>
32
+ * review-rounds.mjs next --state <agent-state.json> [--peek] [--json]
33
+ *
34
+ * get the effective limit and where it came from; --value prints the
35
+ * bare integer; --state also reads the run flag, project and mode
36
+ * set write the preference atomically (global, or this repo with --repo)
37
+ * reset remove that override
38
+ * parse the value of `--review-rounds N` in the text; prints nothing when
39
+ * the flag is absent; a repeated flag or a bad value exits 2
40
+ * record store a run's value in its state file
41
+ * next what review does with accepted findings: prints `rework` after
42
+ * recording one more rework in `phases["2"].reworkCount` and the
43
+ * review iteration it was decided for (`reworkForIteration`, the
44
+ * length of `reviewIterations`), or `rule` when the reworks done have
45
+ * reached the limit and the open findings must be ruled on
46
+ * (`rework-rulings.mjs`). Asked again for the same review iteration
47
+ * it answers `rework` without recording again, so a resumed or
48
+ * re-run Step 4 never spends a second rework. --peek records nothing.
49
+ *
50
+ * `--repo` scopes to the current repository, or to `--project <key>`; a scoped
51
+ * write that cannot resolve its key exits 2 and never writes the global value.
52
+ * `--project` without `--repo` exits 2 on set and reset. MULTI_AGENT_PREFS
53
+ * overrides the preferences file.
54
+ *
55
+ * Exit: 0 done, 2 usage or a value outside 1..3, 3 the preferences or state
56
+ * file is missing, unreadable, not an object, or holds a count outside 0..3
57
+ * (nothing written).
58
+ *
59
+ * @module pipeline/scripts/review-rounds
60
+ */
61
+
62
+ import { statSync } from "node:fs";
63
+ import { ArgsError, parseArgs } from "../lib/args.mjs";
64
+ import { exitOnHelp } from "../lib/cli-help.mjs";
65
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
66
+ import { updateJsonFileSync } from "../lib/json-file-lock.mjs";
67
+ import { prefsPath, readPrefsFile } from "../lib/prefs-value.mjs";
68
+ import { readRegularJson } from "../lib/regular-file.mjs";
69
+ import { repoName } from "../lib/slug.mjs";
70
+ import { isUnattended } from "../lib/unattended.mjs";
71
+ import { messages, outputLanguage } from "../lib/user-facing.mjs";
72
+
73
+ exitOnHelp(import.meta.url);
74
+
75
+ export const MIN_ROUNDS = 1;
76
+ export const MAX_ROUNDS = 3;
77
+ export const DEFAULT_ROUNDS = 2;
78
+
79
+ const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype", ".", ".."]);
80
+ const FLAG = "--review-rounds";
81
+ const QUOTED = /"(?:\\.|[^"\\])*"/g;
82
+
83
+ const TEXT = {
84
+ en: {
85
+ rounds: (n, label) => `Review rework rounds: ${n} (${label})`,
86
+ range: (lo, hi, def) =>
87
+ `Range ${lo} to ${hi}, default ${def}. ${hi} is the hard ceiling (the cap on reworkCount).`,
88
+ sources: {
89
+ flag: "set by --review-rounds for this run",
90
+ repo: "this repository's setting",
91
+ global: "your global setting",
92
+ default: "default, nothing set",
93
+ breaker: "lowered by the autopilot circuit-breaker setting",
94
+ },
95
+ ignored: (source, value) => `Ignored a ${source} value outside the range: ${value}`,
96
+ outside: (v) => `Review rework rounds must be a whole number from 1 to 3, got ${v}.`,
97
+ noPrefs: (file) => `preferences file not found at ${file}; run /multi-agent:setup first`,
98
+ badPrefs: (file) => `preferences file ${file} is not readable JSON; nothing was written`,
99
+ badState: (file) => `${file} is not readable JSON; nothing was written`,
100
+ badProject: (slug) => `project "${slug}" is not a valid project key`,
101
+ repoUnresolved:
102
+ "--repo could not resolve this repository's key; run it inside the repository or pass --project <key>. Nothing was written.",
103
+ projectNeedsRepo: "--project needs --repo; nothing was written.",
104
+ badCount: (file, v) =>
105
+ `${file}: phases.2.reworkCount must be a whole number from 0 to 3, got ${v}; nothing was recorded`,
106
+ flagValue: "--review-rounds needs one whole number from 1 to 3, given once",
107
+ saved: "Saved.",
108
+ cleared: "Override removed.",
109
+ usage:
110
+ "usage: review-rounds.mjs get|set <1|2|3>|reset|parse <text>|record --state <file> --rounds <n>|next --state <file>",
111
+ },
112
+ tr: {
113
+ rounds: (n, label) => `Review rework turu: ${n} (${label})`,
114
+ range: (lo, hi, def) =>
115
+ `Aralık ${lo} ile ${hi}, varsayılan ${def}. ${hi}, reworkCount sınırının koyduğu üst sınırdır.`,
116
+ sources: {
117
+ flag: "bu koşu için --review-rounds ile verildi",
118
+ repo: "bu reponun ayarı",
119
+ global: "genel ayarın",
120
+ default: "varsayılan, hiçbir şey ayarlanmamış",
121
+ breaker: "autopilot circuit-breaker ayarı düşürdü",
122
+ },
123
+ ignored: (source, value) => `${source} kaynağındaki aralık dışı değer yok sayıldı: ${value}`,
124
+ outside: (v) => `Review rework turu 1 ile 3 arasında bir tam sayı olmalı, gelen: ${v}.`,
125
+ noPrefs: (file) => `tercih dosyası bulunamadı: ${file}; önce /multi-agent:setup çalıştır`,
126
+ badPrefs: (file) => `tercih dosyası ${file} okunabilir JSON değil; hiçbir şey yazılmadı`,
127
+ badState: (file) => `${file} okunabilir JSON değil; hiçbir şey yazılmadı`,
128
+ badProject: (slug) => `"${slug}" geçerli bir proje anahtarı değil`,
129
+ repoUnresolved:
130
+ "--repo bu reponun anahtarını çözemedi; repo içinde çalıştır ya da --project <anahtar> ver. Hiçbir şey yazılmadı.",
131
+ projectNeedsRepo: "--project için --repo gerekir; hiçbir şey yazılmadı.",
132
+ badCount: (file, v) =>
133
+ `${file}: phases.2.reworkCount 0 ile 3 arasında bir tam sayı olmalı, gelen: ${v}; hiçbir şey kaydedilmedi`,
134
+ flagValue: "--review-rounds 1 ile 3 arasında, bir kez verilen tek bir tam sayı ister",
135
+ saved: "Kaydedildi.",
136
+ cleared: "Geçersiz kılma kaldırıldı.",
137
+ usage:
138
+ "kullanım: review-rounds.mjs get|set <1|2|3>|reset|parse <metin>|record --state <dosya> --rounds <n>|next --state <dosya>",
139
+ },
140
+ };
141
+
142
+ /** Raised for a refused value or an unusable file; `code` is the CLI exit code. */
143
+ class RoundsError extends Error {
144
+ /** @param {string} message @param {number} code */
145
+ constructor(message, code) {
146
+ super(message);
147
+ this.name = "RoundsError";
148
+ this.code = code;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * A whole number from 1 to 3, given as a number or as digits without padding.
154
+ *
155
+ * @param {unknown} v
156
+ * @returns {{ok: true, value: number} | {ok: false}}
157
+ */
158
+ export function parseRounds(v) {
159
+ const n =
160
+ typeof v === "number" ? v : typeof v === "string" && /^[1-9]$/.test(v) ? Number(v) : NaN;
161
+ return Number.isInteger(n) && n >= MIN_ROUNDS && n <= MAX_ROUNDS
162
+ ? { ok: true, value: n }
163
+ : { ok: false };
164
+ }
165
+
166
+ /**
167
+ * The `--review-rounds` flag in a modifier string or token list. Words inside
168
+ * a double-quoted task are not modifiers. A repeated flag is reported as
169
+ * `duplicate`, never resolved to one of its values.
170
+ *
171
+ * @param {string | string[]} input
172
+ * @returns {{present: false} | {present: true, ok: boolean, value?: number, duplicate?: boolean}}
173
+ */
174
+ export function roundsFlag(input) {
175
+ const text = Array.isArray(input) ? input.join(" ") : String(input ?? "");
176
+ const tokens = text.replace(QUOTED, " ").split(/\s+/).filter(Boolean);
177
+ const found = [];
178
+ for (let i = 0; i < tokens.length; i++) {
179
+ const t = tokens[i];
180
+ if (t === FLAG) found.push(tokens[i + 1]?.startsWith("--") ? undefined : tokens[i + 1]);
181
+ else if (t.startsWith(`${FLAG}=`)) found.push(t.slice(FLAG.length + 1));
182
+ }
183
+ if (found.length === 0) return { present: false };
184
+ if (found.length > 1) return { present: true, ok: false, duplicate: true };
185
+ const r = parseRounds(found[0]);
186
+ return r.ok ? { present: true, ok: true, value: r.value } : { present: true, ok: false };
187
+ }
188
+
189
+ /**
190
+ * A project key as stored under `prefs.projects`: the repository's folder name
191
+ * as is. Null for anything empty, over-long, containing a path separator or NUL,
192
+ * or naming a prototype property.
193
+ *
194
+ * @param {unknown} key
195
+ * @returns {string | null}
196
+ */
197
+ export function projectKey(key) {
198
+ if (typeof key !== "string" || key.length === 0 || key.length > 255) return null;
199
+ if (/[/\\\0]/.test(key) || UNSAFE_KEYS.has(key)) return null;
200
+ return key;
201
+ }
202
+
203
+ /**
204
+ * The project a run belongs to: `state.project`, else the first entry of a
205
+ * multi-repo run.
206
+ *
207
+ * @param {any} state
208
+ * @returns {string | null}
209
+ */
210
+ export function stateProject(state) {
211
+ if (!state || typeof state !== "object") return null;
212
+ if (typeof state.project === "string") return projectKey(state.project);
213
+ const first = Array.isArray(state.projects) ? state.projects[0] : null;
214
+ return typeof first?.name === "string" ? projectKey(first.name) : null;
215
+ }
216
+
217
+ /**
218
+ * The effective limit. With `autopilot` and an enabled circuit-breaker, the
219
+ * breaker's `maxReworkCycles` lowers it (source `breaker`); it never raises it.
220
+ * `configured` is the value before that bound.
221
+ *
222
+ * @param {{prefs?: any, state?: any, project?: string|null, autopilot?: boolean}} [input]
223
+ * @returns {{value: number, configured: number, source: "flag"|"repo"|"global"|"default"|"breaker",
224
+ * min: number, max: number, default: number, breakerCap: number,
225
+ * ignored: {source: string, value: unknown}[]}}
226
+ */
227
+ export function resolveRounds({
228
+ prefs = {},
229
+ state = null,
230
+ project = null,
231
+ autopilot = false,
232
+ } = {}) {
233
+ const own =
234
+ project && Object.hasOwn(prefs?.projects ?? {}, project) ? prefs.projects[project] : null;
235
+ const layers = [
236
+ ["flag", state?.reviewRounds],
237
+ ["repo", own?.maxReworkCycles],
238
+ ["global", prefs?.global?.review?.maxReworkCycles],
239
+ ];
240
+ const ignored = [];
241
+ let configured = DEFAULT_ROUNDS;
242
+ let source = "default";
243
+ for (const [name, raw] of layers) {
244
+ if (raw === undefined) continue;
245
+ if (Number.isInteger(raw) && parseRounds(raw).ok) {
246
+ configured = raw;
247
+ source = name;
248
+ break;
249
+ }
250
+ ignored.push({ source: name, value: raw });
251
+ }
252
+ const breakerPrefs = prefs?.global?.autopilotCircuitBreaker;
253
+ const stored = breakerPrefs?.maxReworkCycles;
254
+ const breaker = Number.isInteger(stored) ? parseRounds(stored) : { ok: false };
255
+ const breakerCap = breaker.ok ? Math.min(configured, breaker.value) : configured;
256
+ const lowered = autopilot && breakerPrefs?.enabled !== false && breakerCap < configured;
257
+ return {
258
+ value: lowered ? breakerCap : configured,
259
+ configured,
260
+ source: lowered ? "breaker" : source,
261
+ min: MIN_ROUNDS,
262
+ max: MAX_ROUNDS,
263
+ default: DEFAULT_ROUNDS,
264
+ breakerCap,
265
+ ignored,
266
+ };
267
+ }
268
+
269
+ /**
270
+ * The limit for a run: its state's flag and project, its autopilot mode, and
271
+ * the circuit-breaker bound that mode brings.
272
+ *
273
+ * @param {{prefs?: any, state?: any, project?: string|null, env?: Record<string,string|undefined>}} input
274
+ */
275
+ export function resolveForRun({ prefs = {}, state = null, project = null, env = process.env }) {
276
+ return resolveRounds({
277
+ prefs,
278
+ state,
279
+ project: project ?? stateProject(state),
280
+ autopilot: state?.autopilot === true || isUnattended(env),
281
+ });
282
+ }
283
+
284
+ /**
285
+ * Whether review must rule on its open findings now instead of sending work
286
+ * back: true once the reworks already done have reached the limit.
287
+ *
288
+ * @param {{reworkCount: number, limit: number}} input
289
+ * @returns {boolean}
290
+ */
291
+ export function shouldRule({ reworkCount, limit }) {
292
+ if (!Number.isInteger(reworkCount) || reworkCount < 0) {
293
+ throw new RangeError(`reworkCount must be a whole number from 0, got ${reworkCount}`);
294
+ }
295
+ if (!Number.isInteger(limit) || limit < MIN_ROUNDS || limit > MAX_ROUNDS) {
296
+ throw new RangeError(
297
+ `limit must be a whole number from ${MIN_ROUNDS} to ${MAX_ROUNDS}, got ${limit}`,
298
+ );
299
+ }
300
+ return reworkCount >= limit;
301
+ }
302
+
303
+ function requireValue(v, t) {
304
+ const r = parseRounds(v);
305
+ if (!r.ok) throw new RoundsError(t.outside(JSON.stringify(v)), 2);
306
+ return r.value;
307
+ }
308
+
309
+ function requireProject(project, t) {
310
+ if (project != null && projectKey(project) === null) {
311
+ throw new RoundsError(t.badProject(project), 2);
312
+ }
313
+ }
314
+
315
+ function loadChecked(file, t) {
316
+ const r = readPrefsFile(file);
317
+ if (r.status === "missing") throw new RoundsError(t.noPrefs(file), 3);
318
+ const isObject = r.prefs && typeof r.prefs === "object" && !Array.isArray(r.prefs);
319
+ if (r.status !== "ok" || !isObject) throw new RoundsError(t.badPrefs(file), 3);
320
+ return r.prefs;
321
+ }
322
+
323
+ function modeOf(file) {
324
+ try {
325
+ return statSync(file).mode & 0o777;
326
+ } catch {
327
+ return 0o600;
328
+ }
329
+ }
330
+
331
+ function mutatePrefs(file, t, change) {
332
+ loadChecked(file, t);
333
+ updateJsonFileSync(
334
+ file,
335
+ (cur) => {
336
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) {
337
+ throw new RoundsError(t.badPrefs(file), 3);
338
+ }
339
+ return change(cur);
340
+ },
341
+ { mode: modeOf(file), followSymlink: true },
342
+ );
343
+ return loadChecked(file, t);
344
+ }
345
+
346
+ /**
347
+ * Write the limit to the preferences file: `projects.<project>` when a project
348
+ * is given, else `global.review`. Everything else in the file is kept.
349
+ *
350
+ * @param {string} file
351
+ * @param {unknown} value
352
+ * @param {{project?: string|null, lang?: "en"|"tr"}} [opts]
353
+ */
354
+ export function setRounds(file, value, { project = null, lang = outputLanguage(file) } = {}) {
355
+ const t = messages(TEXT, lang);
356
+ const n = requireValue(value, t);
357
+ requireProject(project, t);
358
+ const prefs = mutatePrefs(file, t, (cur) => {
359
+ if (project) {
360
+ const projects = { ...(cur.projects ?? {}) };
361
+ projects[project] = { ...(projects[project] ?? {}), maxReworkCycles: n };
362
+ return { ...cur, projects };
363
+ }
364
+ const global = { ...(cur.global ?? {}) };
365
+ global.review = { ...(global.review ?? {}), maxReworkCycles: n };
366
+ return { ...cur, global };
367
+ });
368
+ return resolveRounds({ prefs, project });
369
+ }
370
+
371
+ /**
372
+ * Remove the override `setRounds` wrote, and the containers it leaves empty.
373
+ *
374
+ * @param {string} file
375
+ * @param {{project?: string|null, lang?: "en"|"tr"}} [opts]
376
+ */
377
+ export function resetRounds(file, { project = null, lang = outputLanguage(file) } = {}) {
378
+ const t = messages(TEXT, lang);
379
+ requireProject(project, t);
380
+ const prefs = mutatePrefs(file, t, (cur) => {
381
+ if (project) {
382
+ if (!cur.projects?.[project] || !("maxReworkCycles" in cur.projects[project])) return cur;
383
+ const { maxReworkCycles: _gone, ...rest } = cur.projects[project];
384
+ const projects = { ...cur.projects, [project]: rest };
385
+ return { ...cur, projects };
386
+ }
387
+ if (!cur.global?.review || !("maxReworkCycles" in cur.global.review)) return cur;
388
+ const { maxReworkCycles: _gone, ...rest } = cur.global.review;
389
+ const global = { ...cur.global };
390
+ if (Object.keys(rest).length) global.review = rest;
391
+ else delete global.review;
392
+ return { ...cur, global };
393
+ });
394
+ return resolveRounds({ prefs, project });
395
+ }
396
+
397
+ /**
398
+ * Store a run's limit in its state file as `reviewRounds`.
399
+ *
400
+ * @param {string} stateFile
401
+ * @param {unknown} value
402
+ * @param {{lang?: "en"|"tr"}} [opts]
403
+ */
404
+ export function recordRun(stateFile, value, { lang = outputLanguage() } = {}) {
405
+ const t = messages(TEXT, lang);
406
+ const n = requireValue(value, t);
407
+ const cur = readRegularJson(stateFile, null);
408
+ if (!cur || typeof cur !== "object" || Array.isArray(cur)) {
409
+ throw new RoundsError(t.badState(stateFile), 3);
410
+ }
411
+ updateJsonFileSync(stateFile, (doc) => ({ ...doc, reviewRounds: n }), {
412
+ mode: modeOf(stateFile),
413
+ });
414
+ return n;
415
+ }
416
+
417
+ function loadState(file, t) {
418
+ const doc = readRegularJson(file, null);
419
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) {
420
+ throw new RoundsError(t.badState(file), 3);
421
+ }
422
+ return doc;
423
+ }
424
+
425
+ /**
426
+ * What review does with accepted findings now, and the bookkeeping that goes
427
+ * with it: `rework` records one more rework in `phases["2"].reworkCount`,
428
+ * `rule` records nothing. `peek` never records.
429
+ *
430
+ * @param {string} stateFile
431
+ * @param {{peek?: boolean, prefs?: any, env?: Record<string,string|undefined>, lang?: "en"|"tr"}} [opts]
432
+ * @returns {{action: "rework"|"rule", reworkCount: number, limit: number, source: string}}
433
+ */
434
+ function nextStep(
435
+ stateFile,
436
+ { peek = false, prefs = {}, env = process.env, lang = outputLanguage() } = {},
437
+ ) {
438
+ const t = messages(TEXT, lang);
439
+ const state = loadState(stateFile, t);
440
+ const two = state.phases?.["2"] ?? {};
441
+ const stored = two.reworkCount ?? 0;
442
+ if (!Number.isInteger(stored) || stored < 0 || stored > MAX_ROUNDS) {
443
+ throw new RoundsError(t.badCount(stateFile, JSON.stringify(stored)), 3);
444
+ }
445
+ const iteration = Array.isArray(state.reviewIterations) ? state.reviewIterations.length : 0;
446
+ const r = resolveForRun({ prefs, state, env });
447
+ const answer = (action, reworkCount, repeated) => ({
448
+ action,
449
+ reworkCount,
450
+ limit: r.value,
451
+ source: r.source,
452
+ iteration,
453
+ repeated,
454
+ });
455
+ if (two.reworkForIteration === iteration && iteration > 0) {
456
+ return answer("rework", stored, true);
457
+ }
458
+ if (shouldRule({ reworkCount: stored, limit: r.value })) return answer("rule", stored, false);
459
+ if (peek) return answer("rework", stored, false);
460
+ const written = updateJsonFileSync(
461
+ stateFile,
462
+ (doc) => {
463
+ const phases = { ...(doc.phases ?? {}) };
464
+ const next = { ...(phases["2"] ?? {}) };
465
+ const count = Number.isInteger(next.reworkCount) ? next.reworkCount : 0;
466
+ if (count !== stored) throw new RoundsError(t.badCount(stateFile, JSON.stringify(count)), 3);
467
+ next.reworkCount = count + 1;
468
+ next.reworkForIteration = iteration;
469
+ phases["2"] = next;
470
+ return { ...doc, phases };
471
+ },
472
+ { mode: modeOf(stateFile) },
473
+ );
474
+ return answer("rework", written.phases["2"].reworkCount, false);
475
+ }
476
+
477
+ function report(r, lang) {
478
+ const t = messages(TEXT, lang);
479
+ const lines = [t.rounds(r.value, t.sources[r.source]), t.range(r.min, r.max, r.default)];
480
+ for (const i of r.ignored) lines.push(t.ignored(i.source, JSON.stringify(i.value)));
481
+ return lines.join("\n") + "\n";
482
+ }
483
+
484
+ function scopedKey(flags, t) {
485
+ if (flags.project !== undefined && flags.repo !== true) {
486
+ throw new RoundsError(t.projectNeedsRepo, 2);
487
+ }
488
+ if (flags.repo !== true) return null;
489
+ if (flags.project !== undefined) {
490
+ const key = projectKey(flags.project);
491
+ if (key === null) throw new RoundsError(t.badProject(flags.project), 2);
492
+ return key;
493
+ }
494
+ const key = projectKey(repoName({ fallback: "" }));
495
+ if (key === null) throw new RoundsError(t.repoUnresolved, 2);
496
+ return key;
497
+ }
498
+
499
+ function run(argv, out, err) {
500
+ const file = prefsPath();
501
+ const lang = outputLanguage(file);
502
+ const t = messages(TEXT, lang);
503
+ const [sub, ...rest] = argv;
504
+
505
+ if (sub === "parse") {
506
+ const f = roundsFlag(rest);
507
+ if (!f.present) return 0;
508
+ if (!f.ok) {
509
+ err(`${t.flagValue}\n`);
510
+ return 2;
511
+ }
512
+ out(`${f.value}\n`);
513
+ return 0;
514
+ }
515
+
516
+ let args;
517
+ try {
518
+ args = parseArgs(rest, {
519
+ booleans: ["json", "value", "repo", "peek"],
520
+ strings: ["state", "project", "rounds"],
521
+ unknown: "error",
522
+ });
523
+ } catch (e) {
524
+ if (!(e instanceof ArgsError)) throw e;
525
+ err(`${e.message}\n`);
526
+ return 2;
527
+ }
528
+ const { flags, positionals } = args;
529
+
530
+ try {
531
+ if (sub === "get") {
532
+ if (positionals.length) throw new RoundsError(t.usage, 2);
533
+ const state = flags.state ? loadState(flags.state, t) : null;
534
+ let project = stateProject(state) ?? projectKey(repoName({ fallback: "" }));
535
+ if (flags.project !== undefined) {
536
+ project = projectKey(flags.project);
537
+ if (project === null) throw new RoundsError(t.badProject(flags.project), 2);
538
+ }
539
+ const r = resolveForRun({ prefs: readPrefsFile(file).prefs ?? {}, state, project });
540
+ if (flags.value) out(`${r.value}\n`);
541
+ else if (flags.json) out(`${JSON.stringify(r)}\n`);
542
+ else out(report(r, lang));
543
+ return 0;
544
+ }
545
+ if (sub === "set") {
546
+ if (positionals.length !== 1) throw new RoundsError(t.usage, 2);
547
+ const project = scopedKey(flags, t);
548
+ const r = setRounds(file, positionals[0], { project, lang });
549
+ out(`${t.saved}\n${report(r, lang)}`);
550
+ return 0;
551
+ }
552
+ if (sub === "reset") {
553
+ if (positionals.length) throw new RoundsError(t.usage, 2);
554
+ const project = scopedKey(flags, t);
555
+ const r = resetRounds(file, { project, lang });
556
+ out(`${t.cleared}\n${report(r, lang)}`);
557
+ return 0;
558
+ }
559
+ if (sub === "record") {
560
+ if (!flags.state || flags.rounds === undefined || positionals.length) {
561
+ throw new RoundsError(t.usage, 2);
562
+ }
563
+ recordRun(flags.state, flags.rounds, { lang });
564
+ return 0;
565
+ }
566
+ if (sub === "next") {
567
+ if (!flags.state || positionals.length) throw new RoundsError(t.usage, 2);
568
+ const r = nextStep(flags.state, {
569
+ peek: flags.peek === true,
570
+ prefs: readPrefsFile(file).prefs ?? {},
571
+ lang,
572
+ });
573
+ out(flags.json ? `${JSON.stringify(r)}\n` : `${r.action}\n`);
574
+ return 0;
575
+ }
576
+ throw new RoundsError(t.usage, 2);
577
+ } catch (e) {
578
+ if (!(e instanceof RoundsError)) throw e;
579
+ err(`${e.message}\n`);
580
+ return e.code;
581
+ }
582
+ }
583
+
584
+ if (invokedDirectly(import.meta.url)) {
585
+ process.exit(
586
+ run(
587
+ process.argv.slice(2),
588
+ (s) => process.stdout.write(s),
589
+ (s) => process.stderr.write(s),
590
+ ),
591
+ );
592
+ }
@@ -55,6 +55,7 @@ import { invokedDirectly } from "../lib/invoked-directly.mjs";
55
55
  import { readRegularJson } from "../lib/regular-file.mjs";
56
56
  import { gatesActive } from "../lib/unattended.mjs";
57
57
  import { updateState } from "./gate-ledger.mjs";
58
+ import { DEFAULT_ROUNDS, resolveForRun } from "./review-rounds.mjs";
58
59
  import { prefsPath } from "../lib/prefs-value.mjs";
59
60
  import { ArgsError, parseArgs } from "../lib/args.mjs";
60
61
  import { exitOnHelp } from "../lib/cli-help.mjs";
@@ -63,7 +64,6 @@ exitOnHelp(import.meta.url);
63
64
 
64
65
  export const LADDER = Object.freeze(["fable", "opus", "sonnet", "haiku"]);
65
66
  export const DEFAULT_MAX_TIER = "opus";
66
- export const DEFAULT_MAX_ITERATIONS = 3;
67
67
  const BUDGET_OK = new Set(["ok", "disabled"]);
68
68
 
69
69
  /**
@@ -98,7 +98,7 @@ function settings(prefs) {
98
98
  */
99
99
  export function decide({
100
100
  iteration,
101
- maxIterations = DEFAULT_MAX_ITERATIONS,
101
+ maxIterations = DEFAULT_ROUNDS,
102
102
  stillPresent = 0,
103
103
  currentTier,
104
104
  ladder = LADDER,
@@ -231,9 +231,13 @@ async function main(argv) {
231
231
  const iteration = int(opts, "iteration", undefined);
232
232
  if (iteration === undefined) throw new UsageError("--iteration is required");
233
233
  const prefs = readRegularJson(opts.prefs || prefsPath(), {}) || {};
234
+ const limit = resolveForRun({
235
+ prefs,
236
+ state: opts.state ? readRegularJson(opts.state, null) : null,
237
+ }).value;
234
238
  const decision = decide({
235
239
  iteration,
236
- maxIterations: int(opts, "max-iterations", DEFAULT_MAX_ITERATIONS),
240
+ maxIterations: int(opts, "max-iterations", limit),
237
241
  stillPresent: int(opts, "still-present", 0),
238
242
  currentTier: opts["current-tier"],
239
243
  budget:
@@ -126,21 +126,29 @@ async function main() {
126
126
  errors.push(`phases["${k}"] must be an object`);
127
127
  continue;
128
128
  }
129
- // The rework cap. Every phase doc says "hard-kill at retryCount === 3"
130
- // and the schema writes `maximum: 3`, but nothing read either: a fourth
131
- // round produced a state that violates the schema and passed this
132
- // validator, which is the one place that could have said so.
133
- //
134
- // What this does NOT do is stop the loop - that is the orchestrator's
135
- // job and it stays prose. What it does is make an over-cap state fail
136
- // instead of being carried forward as if it were fine.
137
- if (v.retryCount !== undefined) {
138
- if (!Number.isInteger(v.retryCount) || v.retryCount < 0 || v.retryCount > 3) {
129
+ // retryCount counts build retries (cap 3); reworkCount counts review
130
+ // reworks (cap 3, the ceiling of the review limit). Both are the
131
+ // schema's integer 0..3, checked here because a state that violates
132
+ // them must fail resume instead of being carried forward.
133
+ for (const [field, what] of [
134
+ ["retryCount", "the build-retry cap"],
135
+ ["reworkCount", "the review rework cap"],
136
+ ]) {
137
+ if (v[field] === undefined) continue;
138
+ if (!Number.isInteger(v[field]) || v[field] < 0 || v[field] > 3) {
139
139
  errors.push(
140
- `phases["${k}"].retryCount must be integer 0..3 (the rework cap), got ${JSON.stringify(v.retryCount)}`,
140
+ `phases["${k}"].${field} must be integer 0..3 (${what}), got ${JSON.stringify(v[field])}`,
141
141
  );
142
142
  }
143
143
  }
144
+ if (
145
+ v.reworkForIteration !== undefined &&
146
+ (!Number.isInteger(v.reworkForIteration) || v.reworkForIteration < 0)
147
+ ) {
148
+ errors.push(
149
+ `phases["${k}"].reworkForIteration must be a whole number from 0, got ${JSON.stringify(v.reworkForIteration)}`,
150
+ );
151
+ }
144
152
  }
145
153
  }
146
154
  }