opencode-model-router 2.8.0 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -0,0 +1,470 @@
1
+ // QaLoop (phase 4.2.3): parse findings, create fix and re-review tasks, close the QA gate.
2
+ import {
3
+ canonicalFindingsJson, ExecutorError, fixTaskId, formatInboxId, isFindingsReport, nextInboxNumber, QA_CAP_OPTIONS,
4
+ QA_ROUND_LIMIT, reviewTaskId,
5
+ type Clock, type Edge, type ExecutorEventInput, type Finding, type FindingsReport, type InboxItem, type LedgerV1,
6
+ type LedgerWriter, type PhaseId, type PhaseRecord, type QaCapChoice, type QaLoop, type TaskId, type TaskNode,
7
+ type Waker,
8
+ } from "./types.js";
9
+ import { pathsOverlap } from "./schedule.js";
10
+
11
+ /** The part of the executor logger this module uses. */
12
+ export interface QaLoopLog { warn(message: string): void }
13
+
14
+ export interface QaLoopDeps { writer: LedgerWriter; waker: Waker; clock: Clock; log: QaLoopLog }
15
+
16
+ const FENCE_RE = /```json[ \t]*\r?\n([\s\S]*?)```/g;
17
+ const PARSE_ERROR_MAX = 500;
18
+
19
+ function boundError(s: string): string {
20
+ return s.length > PARSE_ERROR_MAX ? `${s.slice(0, PARSE_ERROR_MAX - 1)}…` : s;
21
+ }
22
+
23
+ /** The last ```json fenced block of `text`, else the whole text (types.ts extraction rule). */
24
+ export function extractFindingsText(text: string): string {
25
+ let last: string | null = null;
26
+ for (const m of text.matchAll(FENCE_RE)) last = m[1] ?? "";
27
+ return last ?? text;
28
+ }
29
+
30
+ export function parseFindings(text: string): { ok: true; report: FindingsReport } | { ok: false; error: string } {
31
+ const body = extractFindingsText(text).trim();
32
+ let v: unknown;
33
+ try {
34
+ v = JSON.parse(body);
35
+ } catch (e) {
36
+ return { ok: false, error: boundError(`findings are not valid JSON: ${e instanceof Error ? e.message : String(e)}`) };
37
+ }
38
+ if (!isFindingsReport(v)) return { ok: false, error: boundError("findings do not match FINDINGS_FORMAT") };
39
+ return { ok: true, report: v };
40
+ }
41
+
42
+ type Outcome = "passed" | "next-round" | "cap-reached";
43
+
44
+ function inboxItem(l: Readonly<LedgerV1>, offset: number, i: Omit<InboxItem, "id">): ExecutorEventInput {
45
+ return { type: "inbox-added", item: { id: formatInboxId("qa-cap", nextInboxNumber(l) + offset), ...i } };
46
+ }
47
+
48
+ function openCapItems(l: Readonly<LedgerV1>): InboxItem[] {
49
+ return l.inbox.filter((x) => x.kind === "qa-cap" && x.severity === "critical" && x.answer === null);
50
+ }
51
+
52
+ function isPhaseTask(l: Readonly<LedgerV1>, phaseId: PhaseId, taskId: TaskId | null): boolean {
53
+ if (taskId === null) return false;
54
+ const t = taskOf(l, taskId);
55
+ return t !== null && t.phase === phaseId;
56
+ }
57
+
58
+ export function createQaLoop(d: QaLoopDeps): QaLoop {
59
+ const { writer, waker, clock, log } = d;
60
+
61
+ /** Deferred minor/nit findings as closed info items (Q3). */
62
+ function deferredEvents(l: Readonly<LedgerV1>, phaseId: PhaseId, taskId: TaskId, deferred: readonly Finding[], base: number): ExecutorEventInput[] {
63
+ void phaseId;
64
+ return deferred.map((f, i) =>
65
+ inboxItem(l, base + i, {
66
+ kind: "qa-cap", severity: "info", taskId, options: [], answer: "deferred", createdAt: clock.iso(),
67
+ text: boundText(`deferred ${f.severity} ${f.id}: ${f.problem} [${f.files.join(", ")}]`),
68
+ }));
69
+ }
70
+
71
+ /** Fix tasks for `groups`, then the re-review task, with the edges (Q5-Q7). */
72
+ function roundTasks(l: Readonly<LedgerV1>, phase: PhaseRecord, qaTask: TaskNode, round: number,
73
+ groups: ReturnType<typeof groupFindings>, previous: readonly Finding[]): ExecutorEventInput[] {
74
+ const out: ExecutorEventInput[] = [];
75
+ const template = taskOf(l, `${phase.id}.FIX`);
76
+ const fixIds: TaskId[] = [];
77
+ const filelessIds: TaskId[] = [];
78
+ groups.forEach((g, idx) => {
79
+ const id = fixTaskId(phase.id, round, idx + 1);
80
+ const fileless = g.writes.length === 0;
81
+ (fileless ? filelessIds : fixIds).push(id);
82
+ const root = template === null ? phaseRootToken(l, phase.id) : null;
83
+ const line = template !== null ? template.route.line : `[route ${DEFAULT_FIX_ROUTE_LINE}${root === null ? "" : ` ${root}`}]`;
84
+ const route = template !== null ? { ...template.route } : { line, role: FIX_ROLE_AGENT, tier: "medium" as const, pin: true };
85
+ out.push({
86
+ type: "task-created",
87
+ task: {
88
+ id, title: `Fix QA round ${round} findings (${idx + 1})`, phase: phase.id, kind: "fix",
89
+ text: `TASK ${id}: fix the QA findings below. Touch only: ${g.writes.length === 0 ? "(no file named; request a lease with NEED MORE: lease <path>)" : g.writes.join(", ")}\n${bodyJson(g.findings)}`,
90
+ subtasks: [], route,
91
+ verify: template !== null ? template.verify : "required",
92
+ acceptance: template !== null ? template.acceptance : null,
93
+ footprint: { writes: [...g.writes], reads: [], confidence: "explicit", sources: ["writes-line"] },
94
+ estimate: template !== null ? { ...template.estimate } : { p50: 0, p90: 0, source: "qa-loop" },
95
+ state: "pending", attempts: [], slot: null, branch: null, integrated: null,
96
+ },
97
+ });
98
+ });
99
+ const reviewId = reviewTaskId(phase.id, round + 1);
100
+ out.push({
101
+ type: "task-created",
102
+ task: {
103
+ id: reviewId, title: `QA round ${round + 1}`, phase: phase.id, kind: "qa",
104
+ text: `TASK ${reviewId}: re-review phase ${phase.id} after the round ${round} fixes. Previous findings:\n${bodyJson(previous)}\n${REVIEW_INSTRUCTION_MARKER}\n${originalReviewText(qaTask.text)}`,
105
+ subtasks: [], route: { ...qaTask.route }, verify: qaTask.verify, acceptance: qaTask.acceptance,
106
+ footprint: { writes: [], reads: [], confidence: "explicit", sources: ["writes-line"] },
107
+ estimate: { ...qaTask.estimate }, state: "pending", attempts: [], slot: null, branch: null, integrated: null,
108
+ },
109
+ });
110
+ const edge = (from: TaskId, to: TaskId): ExecutorEventInput => ({
111
+ type: "edge-added",
112
+ edge: { from, to, kind: "structural", confidence: "high", evidence: `qa round ${round}` } satisfies Edge,
113
+ });
114
+ for (const f of filelessIds) for (const o of fixIds) out.push(edge(o, f));
115
+ for (const f of [...fixIds, ...filelessIds]) out.push(edge(f, reviewId));
116
+ return out;
117
+ }
118
+
119
+ function derive(l: Readonly<LedgerV1>, phase: PhaseRecord, taskId: TaskId): Outcome {
120
+ if (phase.gate === "passed") return "passed";
121
+ const t = taskOf(l, taskId);
122
+ let round = 1;
123
+ for (let r = 1; r <= phase.qaRound; r++) if (isRoundQaTask(l, phase.id, r, taskId)) round = r;
124
+ if (t !== null && phase.qaRound > round) return "next-round";
125
+ if (l.inbox.some((x) => x.kind === "qa-cap" && x.severity === "critical" && x.answer === null && x.taskId === taskId)) return "cap-reached";
126
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", "QA result cannot be applied: the gate is not qa-running", { taskId, gate: phase.gate });
127
+ }
128
+
129
+ async function onQaResult(taskId: TaskId, report: FindingsReport): Promise<Outcome> {
130
+ const l0 = writer.ledger;
131
+ const t0 = taskOf(l0, taskId);
132
+ if (t0 === null || t0.kind !== "qa" || t0.phase === null || phaseOf(l0, t0.phase) === null) {
133
+ throw new ExecutorError("E_INVALID_INPUT", "not a qa task of a phase", { taskId });
134
+ }
135
+ let outcome: Outcome = "passed";
136
+ let wrote = false;
137
+ let capId: string | null = null;
138
+ await writer.append((l) => {
139
+ wrote = false;
140
+ capId = null;
141
+ const t = taskOf(l, taskId);
142
+ const phase = t === null || t.phase === null ? null : phaseOf(l, t.phase);
143
+ if (t === null || phase === null) throw new ExecutorError("E_INVALID_INPUT", "not a qa task of a phase", { taskId });
144
+ const round = phase.qaRound;
145
+ if (phase.gate !== "qa-running" || !isRoundQaTask(l, phase.id, round, taskId)) {
146
+ outcome = derive(l, phase, taskId);
147
+ return [];
148
+ }
149
+ wrote = true;
150
+ const max = Math.min(l.config.qaMaxRounds, QA_ROUND_LIMIT);
151
+ const dec = decideRound(report, round, max);
152
+ const gate = (to: "passed" | "pending" | "awaiting-qa", trigger: "qa-clean" | "qa-next-round" | "qa-cap", qaRound: number): ExecutorEventInput =>
153
+ ({ type: "gate-changed", phaseId: phase.id, from: "qa-running", to, trigger, qaRound });
154
+ if (dec.kind === "clean") {
155
+ outcome = "passed";
156
+ return [...deferredEvents(l, phase.id, taskId, dec.deferred, 0), gate("passed", "qa-clean", round)];
157
+ }
158
+ if (dec.kind === "next-round") {
159
+ outcome = "next-round";
160
+ return [
161
+ gate("pending", "qa-next-round", round + 1),
162
+ ...roundTasks(l, phase, t, round, dec.groups, report.findings),
163
+ ...deferredEvents(l, phase.id, taskId, dec.deferred, 0),
164
+ ];
165
+ }
166
+ outcome = "cap-reached";
167
+ capId = formatInboxId("qa-cap", nextInboxNumber(l));
168
+ const lines = dec.remaining.map(findingLine).join("\n");
169
+ return [
170
+ gate("awaiting-qa", "qa-cap", round),
171
+ ...(phase.paused ? [] : [{ type: "phase-paused", phaseId: phase.id, paused: true, reason: "qa-cap" } satisfies ExecutorEventInput]),
172
+ inboxItem(l, 0, {
173
+ kind: "qa-cap", severity: "critical", taskId, answer: null, createdAt: clock.iso(),
174
+ options: round < QA_ROUND_LIMIT ? [...QA_CAP_OPTIONS] : ["accept"],
175
+ text: boundText(`phase ${phase.id} QA round ${round} of ${max} still has blocking findings:\n${lines}`),
176
+ }),
177
+ ];
178
+ });
179
+ if (wrote && capId !== null) await wakeInbox(capId);
180
+ return outcome;
181
+ }
182
+
183
+ async function wakeInbox(id: string): Promise<void> {
184
+ try {
185
+ await waker.wake("inbox", `inbox:${id}`);
186
+ } catch (e) {
187
+ log.warn(`qa-loop: wake for ${id} failed: ${e instanceof Error ? e.message : String(e)}`);
188
+ }
189
+ }
190
+
191
+ async function onAwaitingQa(phaseId: PhaseId): Promise<void> {
192
+ await writer.append((l) => {
193
+ const phase = phaseOf(l, phaseId);
194
+ if (phase === null || phase.gate !== "awaiting-qa") return [];
195
+ const open = Object.values(l.tasks).filter((t) => t.phase === phaseId && t.kind === "qa" && t.state !== "done" && t.state !== "cancelled");
196
+ if (open.length > 0) return [];
197
+ if (openCapItems(l).some((x) => isPhaseTask(l, phaseId, x.taskId))) return [];
198
+ return [{ type: "gate-changed", phaseId, from: "awaiting-qa", to: "passed", trigger: "no-open-qa", qaRound: phase.qaRound }];
199
+ });
200
+ }
201
+
202
+ async function onCapAnswer(inboxId: string, choice: QaCapChoice): Promise<"passed" | "next-round"> {
203
+ const l0 = writer.ledger;
204
+ const item0 = l0.inbox.find((x) => x.id === inboxId);
205
+ if (item0 === undefined || item0.kind !== "qa-cap" || item0.severity !== "critical" || item0.taskId === null) {
206
+ throw new ExecutorError("E_INVALID_INPUT", "not a critical qa-cap item", { inboxId });
207
+ }
208
+ if (!item0.options.includes(choice)) throw new ExecutorError("E_INVALID_INPUT", "answer is not an option", { inboxId, choice });
209
+ let outcome: "passed" | "next-round" = choice === "accept" ? "passed" : "next-round";
210
+ await writer.append((l) => {
211
+ const item = l.inbox.find((x) => x.id === inboxId);
212
+ if (item === undefined || item.taskId === null) throw new ExecutorError("E_INVALID_INPUT", "not a critical qa-cap item", { inboxId });
213
+ if (item.answer !== null) return [];
214
+ const qa = taskOf(l, item.taskId);
215
+ const phase = qa === null || qa.phase === null ? null : phaseOf(l, qa.phase);
216
+ if (qa === null || phase === null) throw new ExecutorError("E_INVALID_INPUT", "qa task of the item is missing", { inboxId });
217
+ const round = phase.qaRound;
218
+ if (phase.gate !== "awaiting-qa" || !isRoundQaTask(l, phase.id, round, qa.id)) {
219
+ throw new ExecutorError("E_ILLEGAL_TRANSITION", "the gate no longer waits on this cap item", { inboxId, gate: phase.gate });
220
+ }
221
+ const last = qa.attempts.at(-1);
222
+ const parsed = parseFindings(last === undefined ? "" : last.context);
223
+ if (!parsed.ok) throw new ExecutorError("E_INVALID_INPUT", "round findings cannot be re-read", { inboxId, error: parsed.error });
224
+ const findings = parsed.report.findings;
225
+ const answered: ExecutorEventInput = { type: "inbox-answered", id: inboxId, answer: choice };
226
+ const othersCritical = l.inbox.some((x) => x.id !== inboxId && x.severity === "critical" && x.answer === null && (
227
+ isPhaseTask(l, phase.id, x.taskId)));
228
+ const unpause: ExecutorEventInput[] = phase.paused && !othersCritical
229
+ ? [{ type: "phase-paused", phaseId: phase.id, paused: false, reason: `qa-cap ${choice}` }] : [];
230
+ if (choice === "accept") {
231
+ outcome = "passed";
232
+ return [
233
+ answered,
234
+ ...deferredEvents(l, phase.id, qa.id, findings, 0),
235
+ { type: "gate-changed", phaseId: phase.id, from: "awaiting-qa", to: "passed", trigger: "cap-accepted", qaRound: round },
236
+ ...unpause,
237
+ ];
238
+ }
239
+ outcome = "next-round";
240
+ const blocking = findings.filter((f) => isBlockingSeverity(f.severity));
241
+ return [
242
+ answered,
243
+ { type: "gate-changed", phaseId: phase.id, from: "awaiting-qa", to: "pending", trigger: "cap-fix", qaRound: round + 1 },
244
+ ...roundTasks(l, phase, qa, round, groupFindings(blocking), findings),
245
+ ...unpause,
246
+ ];
247
+ });
248
+ return outcome;
249
+ }
250
+
251
+ return { parse: parseFindings, onQaResult, onAwaitingQa, onCapAnswer };
252
+ }
253
+
254
+ export type QaDecision =
255
+ | { kind: "clean"; deferred: Finding[] }
256
+ | { kind: "next-round"; groups: ReturnType<typeof groupFindings>; deferred: Finding[] }
257
+ | { kind: "cap"; remaining: Finding[] };
258
+
259
+ /**
260
+ * Q4 decision table. r = `round` (1-based), `qaMaxRounds` = max. Rounds 1-2 (with room left) fix every finding; from
261
+ * round 3 only blocking/critical/major are fixed and minor/nit are deferred. At the cap (round >= max) blocking
262
+ * findings give `cap`; minor/nit alone pass and are deferred (X8).
263
+ */
264
+ export function decideRound(r: FindingsReport, round: number, qaMaxRounds: number): QaDecision {
265
+ const blocking = r.findings.filter((x) => isBlockingSeverity(x.severity));
266
+ const minor = r.findings.filter((x) => !isBlockingSeverity(x.severity));
267
+ const atCap = round >= qaMaxRounds;
268
+ if (blocking.length > 0) {
269
+ if (atCap) return { kind: "cap", remaining: [...r.findings] };
270
+ if (round <= 2) return { kind: "next-round", groups: groupFindings(r.findings), deferred: [] };
271
+ return { kind: "next-round", groups: groupFindings(blocking), deferred: minor };
272
+ }
273
+ if (minor.length === 0) return { kind: "clean", deferred: [] };
274
+ if (atCap || round >= 3) return { kind: "clean", deferred: minor };
275
+ return { kind: "next-round", groups: groupFindings(minor), deferred: [] };
276
+ }
277
+
278
+ /** U3: at most this many characters of an inbox text, then an ellipsis. */
279
+ const INBOX_TEXT_LIMIT = 4000;
280
+ /**
281
+ * Body of the default fix route line; the caller appends the phase root token and wraps it in `[route ...]`,
282
+ * as renderRouteLine requires a whole bracketed line.
283
+ */
284
+ const DEFAULT_FIX_ROUTE_LINE = "class=implement d=deterministic tier=medium pin";
285
+ /**
286
+ * The role agent a default fix task runs as (QA-4.2-11): class `implement` maps to the role KIND `implement`
287
+ * (CLASS_ROLE_KIND) whose agent is `implementer` (ROLES.md), the one holding edit grants. Not the kind name.
288
+ */
289
+ export const FIX_ROLE_AGENT = "implementer";
290
+
291
+ function boundText(s: string): string {
292
+ return s.length > INBOX_TEXT_LIMIT ? `${s.slice(0, INBOX_TEXT_LIMIT)}…` : s;
293
+ }
294
+
295
+ function hasOwn(o: object, k: string): boolean {
296
+ return Object.prototype.hasOwnProperty.call(o, k);
297
+ }
298
+
299
+ function taskOf(l: Readonly<LedgerV1>, id: TaskId): TaskNode | null {
300
+ return hasOwn(l.tasks, id) ? (l.tasks[id] as TaskNode) : null;
301
+ }
302
+
303
+ function phaseOf(l: Readonly<LedgerV1>, id: PhaseId): PhaseRecord | null {
304
+ return l.phases.find((p) => p.id === id) ?? null;
305
+ }
306
+
307
+ function escapeRe(s: string): string {
308
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
309
+ }
310
+
311
+ /** True iff `taskId` is the qa task of round `round` of `phaseId` (QA1). */
312
+ function isRoundQaTask(l: Readonly<LedgerV1>, phaseId: PhaseId, round: number, taskId: TaskId): boolean {
313
+ const t = taskOf(l, taskId);
314
+ if (t === null || t.kind !== "qa" || t.phase !== phaseId) return false;
315
+ if (round >= 2) return taskId === reviewTaskId(phaseId, round);
316
+ return !new RegExp(`^${escapeRe(phaseId)}\\.QA\\d+$`).test(taskId);
317
+ }
318
+
319
+ function roundQaTask(l: Readonly<LedgerV1>, phaseId: PhaseId, round: number): TaskNode | null {
320
+ for (const t of Object.values(l.tasks)) if (isRoundQaTask(l, phaseId, round, t.id)) return t;
321
+ return null;
322
+ }
323
+
324
+ const ROOT_TOKEN_RE = /\broot\s*=\s*(?:"([^"]*)"|([^\s]+))/i;
325
+
326
+ /** A route root must not introduce brackets, quotes, separators or control characters into the generated line. */
327
+ function routeRoot(root: string): string | null {
328
+ if (!/^(?:[A-Za-z]:[\\/]|\/(?![\\/]))[^\x00-\x1f\x7f\u2028\u2029[\]",;]*$/.test(root)
329
+ || /(?:^|[\\/])\.\.(?:[\\/]|$)/.test(root)) return null;
330
+ return /\s/.test(root) ? `root="${root}"` : `root=${root}`;
331
+ }
332
+
333
+ /** The `root=` token of the first route line of the phase's tasks, else one built from the repo toplevel. */
334
+ function phaseRootToken(l: Readonly<LedgerV1>, phaseId: PhaseId): string | null {
335
+ for (const t of Object.values(l.tasks)) {
336
+ if (t.phase !== phaseId) continue;
337
+ // Remove only the route's closing delimiter, not a bracket inside the root value.
338
+ const line = t.route.line.trim();
339
+ const body = line.startsWith("[") && line.endsWith("]") ? line.slice(0, -1) : line;
340
+ const m = ROOT_TOKEN_RE.exec(body);
341
+ if (m !== null) return routeRoot(m[1] ?? m[2] ?? "");
342
+ }
343
+ return routeRoot(l.repo.toplevel);
344
+ }
345
+
346
+ /** Separates the previous findings from the original phase review instruction in a re-review task text. */
347
+ export const REVIEW_INSTRUCTION_MARKER = "--- original phase review instruction ---";
348
+ const REREVIEW_HEAD_RE = /^TASK [^\n]*: re-review phase [^\n]* after the round \d+ fixes\. Previous findings:\n/;
349
+
350
+ /**
351
+ * The original phase review instruction of a qa task text. A re-review text built by `roundTasks` carries it after
352
+ * `REVIEW_INSTRUCTION_MARKER`; that part is reused so a later round embeds the instruction once, not the whole
353
+ * previous task text (which would grow every round). Any other text is the original instruction itself.
354
+ */
355
+ export function originalReviewText(text: string): string {
356
+ if (!REREVIEW_HEAD_RE.test(text)) return text;
357
+ const at = text.indexOf(`\n${REVIEW_INSTRUCTION_MARKER}\n`);
358
+ return at < 0 ? text : text.slice(at + REVIEW_INSTRUCTION_MARKER.length + 2);
359
+ }
360
+
361
+ function bodyJson(findings: readonly Finding[]): string {
362
+ return canonicalFindingsJson({ findings: [...findings] });
363
+ }
364
+
365
+ function findingLine(f: Finding): string {
366
+ return `${f.severity} ${f.id}: ${f.problem} [${f.files.join(", ")}]`;
367
+ }
368
+
369
+ const BLOCKING_SEVERITIES: ReadonlySet<string> = new Set(["blocking", "critical", "major"]);
370
+ const OVERFLOW_LIMIT = 999;
371
+
372
+ export function isBlockingSeverity(s: Finding["severity"]): boolean {
373
+ return BLOCKING_SEVERITIES.has(s);
374
+ }
375
+
376
+ /** `\` to `/`, leading `./` stripped; null for absolute paths, `..` segments or empty paths. */
377
+ export function normalizeFindingPath(p: string): string | null {
378
+ let s = p.replace(/\\/g, "/");
379
+ while (s.startsWith("./")) s = s.slice(2);
380
+ s = s.replace(/\/{2,}/g, "/");
381
+ if (s.length > 1 && s.endsWith("/")) s = s.replace(/\/+$/, "");
382
+ if (s === "" || s === "." || s.startsWith("/") || /^[A-Za-z]:/.test(s)) return null;
383
+ const segs = s.split("/");
384
+ if (segs.some((x) => x === ".." || x === "" )) return null;
385
+ const kept = segs.filter((x) => x !== ".");
386
+ return kept.length === 0 ? null : kept.join("/");
387
+ }
388
+
389
+ /**
390
+ * Q5: components of findings that share a file; each component is one group with writes = the union of its files
391
+ * (sorted). Components are ordered by their smallest path; findings without a usable file form one extra group with
392
+ * `writes: []` (last). More than 999 file groups: the overflow is merged into the last one.
393
+ */
394
+ export function groupFindings(f: readonly Finding[]): Array<{ writes: string[]; findings: Finding[] }> {
395
+ const parent = new Map<string, string>();
396
+ const find = (x: string): string => {
397
+ let r = x;
398
+ while (parent.get(r) !== r) r = parent.get(r) as string;
399
+ let c = x;
400
+ while (parent.get(c) !== r) {
401
+ const next = parent.get(c) as string;
402
+ parent.set(c, r);
403
+ c = next;
404
+ }
405
+ return r;
406
+ };
407
+ const union = (a: string, b: string): void => {
408
+ const ra = find(a);
409
+ const rb = find(b);
410
+ if (ra === rb) return;
411
+ if (ra < rb) parent.set(rb, ra);
412
+ else parent.set(ra, rb);
413
+ };
414
+ const filesOf = (x: Finding): string[] => {
415
+ const out = new Set<string>();
416
+ for (const p of x.files) {
417
+ const n = normalizeFindingPath(p);
418
+ if (n !== null) out.add(n);
419
+ }
420
+ return [...out].sort();
421
+ };
422
+ const withFiles: Array<{ finding: Finding; files: string[] }> = [];
423
+ const fileless: Finding[] = [];
424
+ for (const x of f) {
425
+ const files = filesOf(x);
426
+ if (files.length === 0) {
427
+ fileless.push(x);
428
+ continue;
429
+ }
430
+ withFiles.push({ finding: x, files });
431
+ for (const p of files) if (!parent.has(p)) parent.set(p, p);
432
+ for (let i = 1; i < files.length; i++) union(files[0] as string, files[i] as string);
433
+ }
434
+ // The scheduler serialises tasks whose footprints overlap (case-insensitive, directory prefix): one group, not two.
435
+ const known = [...parent.keys()].sort();
436
+ for (let i = 0; i < known.length; i++) {
437
+ for (let j = i + 1; j < known.length; j++) {
438
+ if (pathsOverlap(known[i] as string, known[j] as string)) union(known[i] as string, known[j] as string);
439
+ }
440
+ }
441
+ const comps = new Map<string, { writes: Set<string>; findings: Finding[] }>();
442
+ for (const { finding, files } of withFiles) {
443
+ const root = find(files[0] as string);
444
+ let c = comps.get(root);
445
+ if (c === undefined) {
446
+ c = { writes: new Set(), findings: [] };
447
+ comps.set(root, c);
448
+ }
449
+ for (const p of files) c.writes.add(p);
450
+ c.findings.push(finding);
451
+ }
452
+ let groups = [...comps.values()]
453
+ .map((c) => ({ writes: [...c.writes].sort(), findings: c.findings }))
454
+ .sort((a, b) => ((a.writes[0] as string) < (b.writes[0] as string) ? -1 : (a.writes[0] as string) > (b.writes[0] as string) ? 1 : 0));
455
+ // The file-less task takes one of the 999 indices of the round, so the file groups leave it room.
456
+ const fileGroupLimit = fileless.length > 0 ? OVERFLOW_LIMIT - 1 : OVERFLOW_LIMIT;
457
+ if (groups.length > fileGroupLimit) {
458
+ const head = groups.slice(0, fileGroupLimit - 1);
459
+ const tail = groups.slice(fileGroupLimit - 1);
460
+ const writes = new Set<string>();
461
+ const findings: Finding[] = [];
462
+ for (const g of tail) {
463
+ for (const w of g.writes) writes.add(w);
464
+ findings.push(...g.findings);
465
+ }
466
+ groups = [...head, { writes: [...writes].sort(), findings }];
467
+ }
468
+ if (fileless.length > 0) groups.push({ writes: [], findings: fileless });
469
+ return groups;
470
+ }