@mmerterden/multi-agent-pipeline 23.5.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 (58) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +7 -6
  3. package/README.tr.md +7 -6
  4. package/docs/architecture.md +8 -6
  5. package/docs/ecosystem.md +15 -15
  6. package/docs/engineering.md +1 -1
  7. package/docs/facts.json +11 -10
  8. package/docs/features.md +1 -1
  9. package/package.json +1 -1
  10. package/pipeline/commands/multi-agent/SKILL.md +3 -2
  11. package/pipeline/commands/multi-agent/resume/SKILL.md +2 -0
  12. package/pipeline/commands/multi-agent/review-rounds/SKILL.md +94 -0
  13. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  14. package/pipeline/lib/usage-names.generated.mjs +12 -0
  15. package/pipeline/multi-agent-refs/_input-parser.md +1 -1
  16. package/pipeline/multi-agent-refs/component-dispatch.md +2 -2
  17. package/pipeline/multi-agent-refs/cross-cli-contract.md +3 -3
  18. package/pipeline/multi-agent-refs/features/autopilot-circuit-breaker.md +4 -4
  19. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  20. package/pipeline/multi-agent-refs/features/review-rounds.md +40 -0
  21. package/pipeline/multi-agent-refs/features/rework-escalation.md +5 -4
  22. package/pipeline/multi-agent-refs/features/usage-reporting.md +1 -1
  23. package/pipeline/multi-agent-refs/help/en.md +4 -2
  24. package/pipeline/multi-agent-refs/help/tr.md +4 -2
  25. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +1 -1
  26. package/pipeline/multi-agent-refs/outside-the-pipeline.md +2 -1
  27. package/pipeline/multi-agent-refs/phases/operations.md +1 -1
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +1 -1
  29. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  30. package/pipeline/multi-agent-refs/phases/phase-3-review.md +7 -3
  31. package/pipeline/multi-agent-refs/resume/details.md +2 -0
  32. package/pipeline/multi-agent-refs/toolkit-tools.md +1 -0
  33. package/pipeline/office/index.html +2 -2
  34. package/pipeline/office/toolkit.json +1 -1
  35. package/pipeline/rules/outside-the-pipeline.md +1 -1
  36. package/pipeline/schemas/agent-state.schema.json +19 -1
  37. package/pipeline/schemas/phases.json +2 -2
  38. package/pipeline/schemas/prefs.schema.json +15 -3
  39. package/pipeline/schemas/token-budget.json +2 -2
  40. package/pipeline/schemas/toolkit-path-params.json +40 -1
  41. package/pipeline/scripts/_stack-routing.mjs +1 -0
  42. package/pipeline/scripts/gen-facts.mjs +9 -4
  43. package/pipeline/scripts/health-report.mjs +35 -8
  44. package/pipeline/scripts/review-rounds.mjs +592 -0
  45. package/pipeline/scripts/rework-escalation.mjs +7 -3
  46. package/pipeline/scripts/usage-health.mjs +10 -1
  47. package/pipeline/scripts/validate-state.mjs +19 -11
  48. package/pipeline/skills/.skill-manifest.json +13 -5
  49. package/pipeline/skills/.skills-index.json +23 -1
  50. package/pipeline/skills/shared/README.md +7 -5
  51. package/pipeline/skills/shared/core/multi-agent/SKILL.md +3 -3
  52. package/pipeline/skills/shared/core/multi-agent-resume/SKILL.md +1 -1
  53. package/pipeline/skills/shared/core/multi-agent-review-rounds/SKILL.md +92 -0
  54. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  55. package/pipeline/skills/shared/external/ink-animation/SKILL.md +230 -0
  56. package/pipeline/skills/shared/external/ink-animation/evals/evals.json +41 -0
  57. package/pipeline/skills/skills-index.md +3 -1
  58. package/manifest.json +0 -2056
@@ -119,8 +119,12 @@ const result = (status, message, data) => ({
119
119
  message,
120
120
  data,
121
121
  });
122
- const joined = (parts) => msg("join.comma", { parts });
123
- const joinedSemi = (parts) => msg("join.semicolon", { parts });
122
+ /**
123
+ * A message made of several parts. `lead` is the id of the part that decides
124
+ * the section's colour: the one id the site receives for the whole sentence.
125
+ */
126
+ const joined = (parts, lead) => ({ ...msg("join.comma", { parts }), lead });
127
+ const joinedSemi = (parts, lead) => ({ ...msg("join.semicolon", { parts }), lead });
124
128
 
125
129
  // ---------------------------------------------------------------------------
126
130
  // services
@@ -176,7 +180,20 @@ export function servicesSection(inv) {
176
180
  : missing.length || unreachable.length || malformed.length
177
181
  ? "yellow"
178
182
  : "green";
179
- return result(status, joined(parts), { probed: Boolean(inv.probed), items });
183
+ const lead = refused.length
184
+ ? "services.refused"
185
+ : missing.length
186
+ ? "services.missing"
187
+ : unreachable.length
188
+ ? "services.unreachable"
189
+ : malformed.length
190
+ ? "services.malformed"
191
+ : inv.probed
192
+ ? "services.works"
193
+ : unset.length
194
+ ? "services.unset"
195
+ : "services.held";
196
+ return result(status, joined(parts, lead), { probed: Boolean(inv.probed), items });
180
197
  }
181
198
 
182
199
  // ---------------------------------------------------------------------------
@@ -388,9 +405,11 @@ export function hostVersions(home) {
388
405
  export function installSection({ versions, doctor }) {
389
406
  const statuses = [];
390
407
  const parts = [];
408
+ const decisive = [];
391
409
  if (!versions.claude) {
392
410
  statuses.push("red");
393
411
  parts.push(msg("install.none"));
412
+ decisive.push(["red", "install.none"]);
394
413
  } else {
395
414
  const others = ["copilot", "codex"].filter((h) => versions[h]);
396
415
  const behind = others.filter((h) => versions[h] !== versions.claude);
@@ -403,6 +422,7 @@ export function installSection({ versions, doctor }) {
403
422
  if (behind.length) {
404
423
  statuses.push("yellow");
405
424
  parts.push(msg("install.behind", { hosts: behind }));
425
+ decisive.push(["yellow", "install.behind"]);
406
426
  }
407
427
  }
408
428
  const blocking = (doctor?.blocking ?? []).filter((id) => CHECK_ID.test(id));
@@ -410,7 +430,10 @@ export function installSection({ versions, doctor }) {
410
430
  const [status, message] = doctorVerdict(doctor, blocking, warnings);
411
431
  if (status) statuses.push(status);
412
432
  parts.push(message);
413
- return result(worst(statuses), joinedSemi(parts), {
433
+ decisive.push([status ?? "green", message.id]);
434
+ const overall = worst(statuses);
435
+ const lead = decisive.find(([s]) => s === overall)[1];
436
+ return result(overall, joinedSemi(parts, lead), {
414
437
  versions,
415
438
  doctor: doctor?.ran ? { exit: doctor.exit, blocking, warnings } : null,
416
439
  });
@@ -506,7 +529,8 @@ export function sessionsSection({ sessions, usage }) {
506
529
  parts.push(msg("sessions.unpriced", { n: usage.unpricedModels.length }));
507
530
  }
508
531
  if (usage.truncatedFiles) parts.push(msg("sessions.partial", { n: usage.truncatedFiles }));
509
- return result(rows === null ? "yellow" : "green", joined(parts), { open, working, today });
532
+ const lead = rows === null ? "sessions.unreadable" : "sessions.open";
533
+ return result(rows === null ? "yellow" : "green", joined(parts, lead), { open, working, today });
510
534
  }
511
535
 
512
536
  // ---------------------------------------------------------------------------
@@ -546,7 +570,8 @@ export function autopilotSection(st, now = Date.now()) {
546
570
  ];
547
571
  if (awaiting) parts.push(msg("autopilot.waiting", { n: awaiting }));
548
572
  if (silent) parts.push(msg("autopilot.silent"));
549
- return result(silent || awaiting ? "yellow" : "green", joined(parts), data);
573
+ const lead = silent ? "autopilot.silent" : awaiting ? "autopilot.waiting" : "autopilot.on";
574
+ return result(silent || awaiting ? "yellow" : "green", joined(parts, lead), data);
550
575
  }
551
576
 
552
577
  export function officeSection(cur) {
@@ -580,11 +605,13 @@ export function diskSection(sys) {
580
605
  logsMb === null ? msg("disk.logsUnknown") : msg("disk.logs", { size: gb(logsMb) }),
581
606
  ];
582
607
  const statuses = [share < 0.1 ? "red" : share < 0.2 ? "yellow" : "green"];
583
- if (logsMb !== null && logsMb > 2 * MB) {
608
+ const prune = logsMb !== null && logsMb > 2 * MB;
609
+ if (prune) {
584
610
  statuses.push("yellow");
585
611
  parts.push(msg("disk.prune"));
586
612
  }
587
- return result(worst(statuses), joined(parts), data);
613
+ const lead = statuses[0] === "green" && prune ? "disk.prune" : "disk.free";
614
+ return result(worst(statuses), joined(parts, lead), data);
588
615
  }
589
616
 
590
617
  /** The newest green-gate stamp pre-push-check.sh left on this machine. */
@@ -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
+ }