opencode-model-router 2.3.0 → 2.5.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 (68) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +86 -11
  3. package/package.json +6 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1374 -24
  6. package/src/escalate/ladder.ts +12 -0
  7. package/src/guard/enforce.ts +186 -22
  8. package/src/guard/guards.ts +132 -6
  9. package/src/guard/store.ts +5 -0
  10. package/src/index.ts +718 -29
  11. package/src/router/config.ts +247 -1
  12. package/src/router/dispatch-header.ts +46 -4
  13. package/src/router/git-tools.ts +1152 -0
  14. package/src/router/guard-profile.ts +100 -0
  15. package/src/router/plugin-agents.ts +433 -0
  16. package/src/router/prompts.ts +26 -1
  17. package/src/router/protocol.ts +133 -0
  18. package/src/router/read-only.ts +149 -0
  19. package/src/router/role-agents.ts +409 -0
  20. package/src/router/roles-config.ts +429 -0
  21. package/src/router/roles.ts +600 -0
  22. package/src/router/run-tools.ts +913 -0
  23. package/src/router/sensitive-paths.ts +101 -0
  24. package/src/router/sessions.ts +92 -0
  25. package/src/router/subagents.ts +28 -1
  26. package/src/routing/advisor/findings.ts +193 -1
  27. package/src/routing/advisor/index.ts +13 -5
  28. package/src/routing/classify/index.ts +23 -5
  29. package/src/routing/classify/route-line.ts +67 -3
  30. package/src/routing/classify/rules.ts +80 -20
  31. package/src/routing/classify/types.ts +34 -4
  32. package/src/routing/commands/stats.ts +3 -0
  33. package/src/routing/engine/kernel.ts +163 -0
  34. package/src/routing/engine/ladders.ts +242 -1
  35. package/src/routing/engine/protocol-line.ts +17 -0
  36. package/src/routing/engine/roles-taxonomy.ts +52 -0
  37. package/src/routing/engine/types.ts +99 -1
  38. package/src/routing/outcomes/beta.ts +10 -4
  39. package/src/routing/outcomes/index.ts +44 -1
  40. package/src/routing/outcomes/ingest.ts +163 -15
  41. package/src/routing/outcomes/persist.ts +23 -1
  42. package/src/routing/outcomes/signals.ts +650 -0
  43. package/src/routing/outcomes/stats.ts +273 -2
  44. package/src/routing/outcomes/store.ts +25 -5
  45. package/src/routing/outcomes/types.ts +145 -6
  46. package/src/routing/roles/authority.ts +495 -0
  47. package/src/routing/roles/binding.ts +543 -0
  48. package/src/routing/roles/policy.ts +416 -0
  49. package/src/routing/roles/work-root.ts +132 -0
  50. package/src/routing/wire/dispatch.ts +1306 -17
  51. package/src/routing/wire/hint.ts +14 -0
  52. package/src/routing/wire/runtime.ts +117 -28
  53. package/src/tui/effort-channel.ts +220 -0
  54. package/src/tui/effort-rpc.ts +60 -0
  55. package/src/tui/host-types.ts +154 -0
  56. package/src/tui/opentui-solid.d.ts +16 -0
  57. package/src/tui/plugin.ts +1007 -0
  58. package/src/tui/status-model.ts +561 -0
  59. package/src/v2.ts +26 -1
  60. package/src/verify/checker.ts +249 -7
  61. package/src/verify/deterministic.ts +10 -1
  62. package/src/verify/dispatch.ts +63 -6
  63. package/src/verify/dod.ts +127 -10
  64. package/src/verify/gate.ts +75 -7
  65. package/src/verify/types.ts +12 -0
  66. package/src/verify/wiring.ts +55 -10
  67. package/tiers.json +13 -5
  68. package/tui.ts +4 -0
@@ -7,6 +7,184 @@
7
7
 
8
8
  import type { Verdict } from "./types";
9
9
  import { scrubText } from "../guard/scrub";
10
+ import { CRITERIA_BUDGET_CHARS, fitCriteria, omittedCriteriaText } from "./dod";
11
+ import { captureBudget } from "../guard/enforce";
12
+ import type { BudgetSnapshot } from "../guard/enforce";
13
+ import { parseReturnPrefix } from "../routing/outcomes/signals";
14
+ import { oneLineReason } from "../routing/roles/authority";
15
+
16
+ // ---------------------------------------------------------------------------
17
+ // Incomplete returns (§2.9 E8, I7)
18
+ // ---------------------------------------------------------------------------
19
+
20
+ /** Verdict reason: the return is a progress note. Matched exactly, never by prefix (QA-P15-1-6). */
21
+ export const INCOMPLETE_REASON =
22
+ "incomplete: the delegate returned a progress note (no DONE:, NEED MORE: or ESCALATE:), not a result; resume the same delegation to let it finish";
23
+
24
+ /** Verdict reason: the producer stopped at its tool-call budget (I7: never a tier failure). */
25
+ export const BUDGET_INCOMPLETE_REASON =
26
+ "incomplete: the delegate stopped at its tool-call budget (NEED MORE: budget), not with a result; resume the same delegation to let it finish";
27
+
28
+ const INCOMPLETE_REASONS: ReadonlySet<string> = new Set([INCOMPLETE_REASON, BUDGET_INCOMPLETE_REASON]);
29
+
30
+ /** One of the router's own incomplete reasons (a grader reason "incomplete: …" is not). */
31
+ export function isIncompleteReason(reason: string): boolean {
32
+ return INCOMPLETE_REASONS.has(reason);
33
+ }
34
+
35
+ /**
36
+ * QA-P15-2-4: a verdict carries `incomplete: true` structurally (set only by
37
+ * incompleteVerdict), so caveats appended later (wiring.ts applyDispatchCaveats)
38
+ * never turn it back into an ordinary unverifiable result.
39
+ */
40
+ export type IncompleteFlag = { incomplete?: boolean };
41
+
42
+ /** An incomplete verdict (the structured flag). Never accepted (gate.ts gateResult). */
43
+ export function isIncompleteVerdict(verdict: object): boolean {
44
+ return (verdict as IncompleteFlag).incomplete === true;
45
+ }
46
+
47
+ /** A return-contract marker at the start of a line (markdown emphasis and quotes allowed). */
48
+ const CONTRACT_MARKER_RE = /^[ \t>*_#`-]*(?:DONE|NEED MORE|NEED CONTEXT|SCOPE GROWTH|ESCALATE)[*_]*[ \t]*:/m;
49
+
50
+ /** `NEED MORE: budget` at the start of a line (QA-P15-1-2); the fallback when the first line carries no prefix. */
51
+ const NEED_MORE_BUDGET_LINE_RE = /^[ \t>*_#`-]*NEED MORE[*_]*[ \t]*:[ \t*_`]*budget\b/im;
52
+
53
+ /** A `SCOPE GROWTH:` / `NEED CONTEXT:` first line: a contract prefix unknown to parseReturnPrefix that still decides. */
54
+ const OTHER_CONTRACT_FIRST_LINE_RE = /^(?:NEED[\s_-]*CONTEXT|SCOPE[\s_-]*GROWTH)\b[*_`\s]*:/i;
55
+
56
+ /** The first non-empty line, past a leading `task_id:` / `<task_result>` envelope, with leading decoration stripped. */
57
+ function firstLine(text: string): string {
58
+ for (const raw of text.split(/\r?\n/)) {
59
+ const line = raw.replace(/^\s*<task_result>/i, "");
60
+ if (line.trim() === "" || /^\s*task_id\s*:/i.test(line)) continue;
61
+ return line.replace(/^[^\p{L}\p{N}]+/u, "").replace(/^\d+[.)]\s+/, "");
62
+ }
63
+ return "";
64
+ }
65
+
66
+ /**
67
+ * Two contract definitions coexist on purpose. CONTRACT_MARKER_RE (above) is an any-line test that also knows
68
+ * NEED CONTEXT / SCOPE GROWTH; the stop branch keeps it so a guard-stopped producer that wrote any marker
69
+ * anywhere is not forced to "incomplete" over a result it did state. parseReturnPrefix (signals.ts) is the
70
+ * FIRST-line contract (DONE / NEED MORE / ESCALATE) used for the claim decision below.
71
+ *
72
+ * `NEED MORE: budget` is claimed by the return prefix (the first non-empty line after unwrapping the task
73
+ * envelope and markdown/list decoration; DF-1 fix). A DONE:/ESCALATE: first line decides: a later line
74
+ * quoting the claim is never one. When the first line carries no prefix (a progress summary before the
75
+ * claim, as the guard's own message asks for), a line-start `NEED MORE: budget` still counts (I7).
76
+ */
77
+ function claimsNeedMoreBudget(text: string): boolean {
78
+ const contract = parseReturnPrefix(text);
79
+ if (contract === null) return false;
80
+ if (contract.prefix === "none") return !OTHER_CONTRACT_FIRST_LINE_RE.test(firstLine(text)) && NEED_MORE_BUDGET_LINE_RE.test(text);
81
+ return contract.prefix === "need-more" && contract.claim === "budget";
82
+ }
83
+
84
+ /** A first-person announcement of finishing or continuing the work (QA-P15-1-1). */
85
+ const ANNOUNCE_RE = /\b(?:I(?:'|\u2019)ll|I will|let me|I(?:'|\u2019)m going to|I am going to)\s+(?:now\s+|then\s+|next\s+)?(?:finish|continue)\b/i;
86
+
87
+ /**
88
+ * Deferral to separate work, or a conditional offer ("If you'd like, I'll
89
+ * continue…", "I'll continue once you confirm…", QA-P15-2-7): a finished
90
+ * result, not a progress note.
91
+ */
92
+ const DEFERRAL_RE = /\b(?:follow[- ]?up|later|separately|another (?:PR|change|task)|next (?:PR|release)|if|once|when|unless|would|want)\b/i;
93
+
94
+ const SENTENCE_END = new Set([".", "!", "?", "\u2026"]);
95
+
96
+ /** The last sentence of a text: after the last sentence end or line break that is followed by more text. */
97
+ function finalSentence(text: string): string {
98
+ let end = text.length;
99
+ while (end > 0 && (SENTENCE_END.has(text[end - 1]!) || /\s/.test(text[end - 1]!))) end--;
100
+ let start = end;
101
+ while (start > 0) {
102
+ const ch = text[start - 1]!;
103
+ if (ch === "\n" || (/\s/.test(ch) && start >= 2 && SENTENCE_END.has(text[start - 2]!))) break;
104
+ start--;
105
+ }
106
+ return text.slice(start, end);
107
+ }
108
+
109
+ /**
110
+ * A progress-note return (QA-P15-1-1): no return-contract marker on any line,
111
+ * and its FINAL sentence is a first-person announcement of finishing or
112
+ * continuing ("I'll finish the tests next", "let me continue with …") that is
113
+ * not a deferral to separate work. Applied only to agents that follow the
114
+ * return contract (runChecker), never in place of grading for others.
115
+ */
116
+ export function isProgressNote(text: string): boolean {
117
+ const trimmed = text.trim();
118
+ if (trimmed.length === 0 || CONTRACT_MARKER_RE.test(trimmed)) return false;
119
+ // QA-P15-2-7: a final question ("Shall I continue?") asks; it does not announce.
120
+ if (trimmed.endsWith("?")) return false;
121
+ const last = finalSentence(trimmed);
122
+ return ANNOUNCE_RE.test(last) && !DEFERRAL_RE.test(last);
123
+ }
124
+
125
+ const DEFAULT_LADDER = ["fast", "medium", "heavy"];
126
+
127
+ function incomplete(reason: string): Verdict {
128
+ const verdict: Verdict & IncompleteFlag = {
129
+ pass: false, outcome: "unverifiable", method: "checker", reasons: [reason], caveats: [reason], incomplete: true,
130
+ };
131
+ return verdict;
132
+ }
133
+
134
+ /**
135
+ * The guard state a `NEED MORE: budget` claim is checked against (QA-P15-2-2):
136
+ * honoured when the guard did not track the session (enforcement off: nothing
137
+ * can be checked), or the budget/refusals were used up, or the read-only cap
138
+ * was reached. Any other claim is graded normally (P1.4 §2.6 scores it).
139
+ */
140
+ function claimHonoured(snapshot: BudgetSnapshot): boolean {
141
+ return !snapshot.tracked || snapshot.usedUp || snapshot.readCapReached === true;
142
+ }
143
+
144
+ /**
145
+ * QA-G-A3-1 (I7, §2.6): a budget stop the guard did not enforce. In advisory mode (the shipped default) nothing is refused, so
146
+ * the guard never records a stop: its banner only TELLS a child out of budget to return `NEED MORE: budget`. Such a return is
147
+ * an observed budget stop when the gate would honour the claim (`claimsNeedMoreBudget` + `claimHonoured`) on a session the guard
148
+ * TRACKED — its budget or refusals used up, or its read cap reached. An untracked session backs no claim here (nothing was
149
+ * observed; the outcome signals keep it `unobserved`).
150
+ */
151
+ export function budgetClaimObserved(text: string | null | undefined, snapshot: BudgetSnapshot): boolean {
152
+ return snapshot.tracked && typeof text === "string" && claimsNeedMoreBudget(text) && claimHonoured(snapshot);
153
+ }
154
+
155
+ /**
156
+ * The incomplete verdict of a return, or null (§2.9 E8, I7), judged on the
157
+ * budget snapshot captured when the task returned (`budget`, QA-P15-2-5; absent
158
+ * → read now through `budgetSnapshot`, default the live guard):
159
+ * - budget: the guard STOPPED the producer in that round (enforced) and it
160
+ * returned no contract marker, or a `NEED MORE: budget` claim (return prefix, or, with no prefix, a line) the snapshot
161
+ * backs (claimHonoured) — for every agent;
162
+ * - progress note (only when `progressNotes`): for an agent that follows the
163
+ * return contract — `returnContract`, else a router tier of the ladder.
164
+ * Incomplete is never accepted, never escalates and never moves evidence.
165
+ */
166
+ export function incompleteVerdict(
167
+ input: {
168
+ finalReturnText: string;
169
+ producerSessionID: string;
170
+ producerTier: string;
171
+ returnContract?: boolean;
172
+ budget?: BudgetSnapshot;
173
+ },
174
+ opts: { progressNotes: boolean; ladder?: readonly string[]; budgetSnapshot?: (sessionID: string) => BudgetSnapshot },
175
+ ): Verdict | null {
176
+ const text = input.finalReturnText;
177
+ const snapshot = input.budget ?? (opts.budgetSnapshot ?? captureBudget)(input.producerSessionID);
178
+ if (
179
+ (snapshot.stopped && !CONTRACT_MARKER_RE.test(text)) ||
180
+ (claimsNeedMoreBudget(text) && claimHonoured(snapshot))
181
+ ) {
182
+ return incomplete(BUDGET_INCOMPLETE_REASON);
183
+ }
184
+ const contract = input.returnContract ?? (opts.ladder ?? DEFAULT_LADDER).includes(input.producerTier);
185
+ if (opts.progressNotes && contract && isProgressNote(text)) return incomplete(INCOMPLETE_REASON);
186
+ return null;
187
+ }
10
188
 
11
189
  // ---------------------------------------------------------------------------
12
190
  // Public types
@@ -34,6 +212,11 @@ export interface GraderRequest {
34
212
  export interface GraderResult {
35
213
  sessionID: string;
36
214
  text: string;
215
+ /**
216
+ * #84 P3.3 fix 2: the model the grader session was dispatched on (`provider/model`), when the dispatcher chose one; absent or
217
+ * null = the host's default (unknown to the router). Carried on the verdict (`Verdict.grader`) for the outcome signals.
218
+ */
219
+ model?: string | null;
37
220
  }
38
221
 
39
222
  /** MUST create a FRESH session each call */
@@ -45,6 +228,8 @@ export interface CheckerDeps {
45
228
  dispatchGrader: GraderDispatch;
46
229
  ladder?: string[]; // default ["fast","medium","heavy"]
47
230
  minGraderTier?: string | null; // optional floor
231
+ /** The guard's budget state of a producer session when no snapshot was captured. Default: the live guard (captureBudget). */
232
+ budgetSnapshot?: (sessionID: string) => BudgetSnapshot;
48
233
  }
49
234
 
50
235
  export interface CheckerInput {
@@ -54,6 +239,10 @@ export interface CheckerInput {
54
239
  producerSessionID: string;
55
240
  /** Effective producer working directory; scopes the grader + informs its prompt. */
56
241
  workingDir?: string;
242
+ /** The producer follows the DONE:/NEED MORE:/ESCALATE: return contract (role agents); absent = a router tier of the ladder. */
243
+ returnContract?: boolean;
244
+ /** The producer's budget state captured when its task returned (QA-P15-2-5). */
245
+ budget?: BudgetSnapshot;
57
246
  }
58
247
 
59
248
  // ---------------------------------------------------------------------------
@@ -111,6 +300,11 @@ function sanitizeOneLine(value: string): string {
111
300
  : cleaned;
112
301
  }
113
302
 
303
+ /** The note for criteria over the verification budget (prompt line and verdict caveat). */
304
+ function omittedNote(omitted: number): string {
305
+ return `(${omittedCriteriaText(omitted)}: over the ${CRITERIA_BUDGET_CHARS}-character verification budget; not graded)`;
306
+ }
307
+
114
308
  export function buildGradingPrompt(input: CheckerInput): { system: string; prompt: string } {
115
309
  const lines: string[] = [];
116
310
 
@@ -122,9 +316,12 @@ export function buildGradingPrompt(input: CheckerInput): { system: string; promp
122
316
  }
123
317
 
124
318
  lines.push("## Acceptance criteria (ALL must be satisfied)");
125
- for (let i = 0; i < input.criteria.length; i++) {
126
- lines.push(`${i + 1}. ${input.criteria[i]}`);
319
+ // §2.9 E8: whole criteria only; those over the budget are named as omitted, not graded.
320
+ const { criteria, omitted } = fitCriteria(input.criteria);
321
+ for (let i = 0; i < criteria.length; i++) {
322
+ lines.push(`${i + 1}. ${criteria[i]}`);
127
323
  }
324
+ if (omitted > 0) lines.push(omittedNote(omitted));
128
325
 
129
326
  lines.push("");
130
327
  lines.push("## Artefact to evaluate");
@@ -204,6 +401,26 @@ export function parseGraderVerdict(text: string): { pass: boolean; reasons: stri
204
401
  }
205
402
  }
206
403
 
404
+ /** QA-G-A3-5: the most grader reasons a verdict keeps; the rest are counted in one closing reason. */
405
+ export const GRADER_REASONS_MAX = 20;
406
+
407
+ /**
408
+ * QA-G-A3-5: one grader-written text as one reason — scrubbed first (a cut never leaves half a secret), then `cleanReason`'s line
409
+ * rule (`oneLineReason`, authority.ts): one line, at most 500 characters. The grader's text is model output the producer's
410
+ * artefact can steer, so it never reaches the parent's result as several lines (a line of its own could pose as a router note).
411
+ * Its characters are kept (`[REDACTED]`, `a[0]`): a one-line reason within the cap reads as before, in tiers mode too.
412
+ */
413
+ function graderText(text: string): string {
414
+ return oneLineReason(scrubText(text));
415
+ }
416
+
417
+ /** QA-G-A3-5: the grader's reasons, each {@link graderText}, at most {@link GRADER_REASONS_MAX} (then one count of the rest). */
418
+ function graderReasons(reasons: readonly string[]): string[] {
419
+ const kept = reasons.slice(0, GRADER_REASONS_MAX).map(graderText);
420
+ const rest = reasons.length - kept.length;
421
+ return rest > 0 ? [...kept, `(${rest} more grader reason${rest === 1 ? "" : "s"} omitted)`] : kept;
422
+ }
423
+
207
424
  // ---------------------------------------------------------------------------
208
425
  // Main
209
426
  // ---------------------------------------------------------------------------
@@ -214,6 +431,21 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
214
431
  return { pass: false, method: "none", skipped: true, reasons: ["no criteria to grade"] };
215
432
  }
216
433
 
434
+ // 1b. §2.9 E8 / I7: a budget stop, or a contract follower's progress note, is
435
+ // incomplete — never accepted, never escalated, never outcome evidence.
436
+ const stopped = incompleteVerdict(
437
+ { ...input, finalReturnText: input.artefact.finalReturnText },
438
+ { progressNotes: true, ladder: deps.ladder, budgetSnapshot: deps.budgetSnapshot },
439
+ );
440
+ if (stopped) return stopped;
441
+
442
+ // 1c. §2.9 E8: every criterion is over the verification budget — nothing gradable.
443
+ const { criteria: gradable, omitted } = fitCriteria(input.criteria);
444
+ if (gradable.length === 0) {
445
+ const reason = `no criterion fits the verification budget ${omittedNote(omitted)}`;
446
+ return { pass: false, outcome: "unverifiable", method: "checker", reasons: [reason], caveats: [reason] };
447
+ }
448
+
217
449
  // 2. Determine grader tier
218
450
  const graderTier = atLeastProducerTier(input.producerTier, {
219
451
  ladder: deps.ladder,
@@ -241,6 +473,9 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
241
473
  };
242
474
  }
243
475
 
476
+ // #84 P3.3 fix 2 (plan §2.6, I6): who judged — the outcome signals weigh it as a grader verdict, never a deterministic one.
477
+ const grader = { tier: graderTier, model: typeof res.model === "string" && res.model.trim() !== "" ? res.model : null };
478
+
244
479
  // 5. Independence check (fail-closed)
245
480
  if (res.sessionID === input.producerSessionID || !res.sessionID) {
246
481
  return {
@@ -249,6 +484,8 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
249
484
  reasons: [
250
485
  "grader session is not independent of the producer (producer=grader); refusing to accept",
251
486
  ],
487
+ // The producer judged itself: its model is the producer's, so the outcome signals give this verdict no mass.
488
+ grader: { tier: graderTier, model: null },
252
489
  };
253
490
  }
254
491
 
@@ -260,17 +497,22 @@ export async function runChecker(input: CheckerInput, deps: CheckerDeps): Promis
260
497
  method: "checker",
261
498
  reasons: [
262
499
  "could not parse grader verdict; defaulting to FAIL",
263
- scrubText(res.text.slice(0, 300)),
500
+ graderText(res.text.slice(0, 300)),
264
501
  ],
502
+ grader,
265
503
  };
266
504
  }
267
505
 
268
- // 7. Return verdict
506
+ // 7. Return verdict. Criteria omitted from grading (§2.9 E8) make a pass
507
+ // unverifiable with a caveat: what was not graded is not verified.
508
+ const partial = omitted > 0;
269
509
  return {
270
- pass: parsed.pass === true,
271
- outcome: parsed.pass ? "pass" : "fail",
510
+ pass: parsed.pass === true && !partial,
511
+ outcome: parsed.pass ? (partial ? "unverifiable" : "pass") : "fail",
272
512
  method: "checker",
273
- reasons: parsed.reasons.map(scrubText),
513
+ reasons: graderReasons(parsed.reasons),
274
514
  evidence: scrubText("grader=" + graderTier),
515
+ ...(partial ? { caveats: [omittedNote(omitted)] } : {}),
516
+ grader,
275
517
  };
276
518
  }
@@ -1508,6 +1508,10 @@ async function runTestsPass(command: string, deps: DeterministicDeps, timeoutMs:
1508
1508
  reference: deps.reference ?? defaultReference(deps),
1509
1509
  deadline,
1510
1510
  });
1511
+ // QA-G-B-2-1: a carried acceptance never passes on a run that never happened.
1512
+ if (deps.noAffectedUnverifiable !== undefined && run.scoped.kind === "no-affected") {
1513
+ return { ok: false, unverifiable: true, reason: `${deps.noAffectedUnverifiable} (testsPass: ${run.scoped.note})` };
1514
+ }
1511
1515
  return fromJudgement(judgeScoped(run.scoped, run.recheck));
1512
1516
  });
1513
1517
  } catch (err) {
@@ -1561,7 +1565,12 @@ async function runCommandCheck(
1561
1565
  if (kind === "lintClean" && deps.openScope) {
1562
1566
  // T8: NoAffected passes with its note and takes no slot; Unscoped runs the command as today.
1563
1567
  const plan = await planLint(command, deps);
1564
- if (isNoAffected(plan)) return { ok: true, note: `lintClean: ${plan.note}` };
1568
+ if (isNoAffected(plan)) {
1569
+ // QA-G-B-2-1: a carried acceptance never passes on a lint that never ran.
1570
+ return deps.noAffectedUnverifiable !== undefined
1571
+ ? { ok: false, unverifiable: true, reason: `${deps.noAffectedUnverifiable} (lintClean: ${plan.note})` }
1572
+ : { ok: true, note: `lintClean: ${plan.note}` };
1573
+ }
1565
1574
  if (!isUnscoped(plan)) {
1566
1575
  launch = (scope, deadline) => scope.runLint(plan, deadline);
1567
1576
  scopedTo = plan.inputs.length;
@@ -10,6 +10,8 @@ import type { RouterConfig } from "../router/config";
10
10
  import { getActiveTiers } from "../router/protocol";
11
11
  import { parseDoDFromDispatch, inferDoD } from "./dod";
12
12
  import type { DoD, InferHints } from "./dod";
13
+ import { isIncompleteReason } from "./checker";
14
+ import { stripDispatchHeader } from "../router/dispatch-header";
13
15
  import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
14
16
  import { basename, dirname, join, resolve } from "node:path";
15
17
  import { existsSync, realpathSync } from "node:fs";
@@ -553,10 +555,13 @@ export function buildDelegationDoD(
553
555
  args: { prompt?: string; description?: string; acceptance?: string },
554
556
  hints: InferHints = {},
555
557
  ): DoD {
556
- const blockSource = args.acceptance ?? args.prompt ?? args.description ?? "";
558
+ // R6/P-15 (§2.9 E8): the router's dispatch header is a directive, never a
559
+ // criterion — parse and infer from the orchestrator's prompt behind it.
560
+ const prompt = typeof args.prompt === "string" ? stripDispatchHeader(args.prompt) : args.prompt;
561
+ const blockSource = args.acceptance ?? prompt ?? args.description ?? "";
557
562
  const explicit = parseDoDFromDispatch(blockSource);
558
563
  if (explicit) return explicit;
559
- const dispatch = args.prompt ?? args.description ?? "";
564
+ const dispatch = prompt ?? args.description ?? "";
560
565
  return inferDoD(dispatch, "", hints);
561
566
  }
562
567
 
@@ -588,6 +593,46 @@ export function shouldVerifyTask(
588
593
  return true;
589
594
  }
590
595
 
596
+ /** QA-G-A3-5: the most reasons (caveats, notes) one rendered list shows; the rest are counted in one closing line. */
597
+ export const RENDERED_REASONS_MAX = 20;
598
+
599
+ /** QA-G-A3-2-1: one line break of any kind. */
600
+ const LINE_BREAK = /\r\n|[\r\n\u000b\u000c\u0085\u2028\u2029]/;
601
+
602
+ /**
603
+ * QA-G-A3-2-1: `text` on one line — every line break, with the blanks (space, tab) around it, becomes one space, and a run of
604
+ * breaks (blank lines) one space too; every other character is kept. A text without a line break is returned as it is. Linear
605
+ * (no backtracking regex on producer-derived text).
606
+ */
607
+ function joinLines(text: string): string {
608
+ const parts = text.split(LINE_BREAK);
609
+ if (parts.length === 1) return text;
610
+ const blank = (c: string | undefined): boolean => c === " " || c === "\t";
611
+ const kept: string[] = [];
612
+ parts.forEach((part, i) => {
613
+ let start = 0;
614
+ let end = part.length;
615
+ if (i > 0) while (start < end && blank(part[start])) start++;
616
+ if (i < parts.length - 1) while (end > start && blank(part[end - 1])) end--;
617
+ if (end > start) kept.push(part.slice(start, end));
618
+ });
619
+ return kept.join(" ");
620
+ }
621
+
622
+ /**
623
+ * QA-G-A3-5 / QA-G-A3-2-1: a list of reasons as `- ` lines: each reason on ONE line — its line breaks (with the blanks around them)
624
+ * joined into one space, since a line of its own could pose as a router note — and nothing else changed: the router's own reasons
625
+ * (baseline.ts failure-id lists, "suite is NOT green") are never cut; a grader's text was already cut to 500 characters where it
626
+ * entered the verdict (checker.ts `graderReasons`). Directive keys lose their colons (QA-2.4-6); at most
627
+ * {@link RENDERED_REASONS_MAX} lines plus a count of the rest. A list of at most that many one-line reasons renders as before.
628
+ */
629
+ function reasonLines(reasons: readonly string[]): string {
630
+ const shown = reasons.slice(0, RENDERED_REASONS_MAX).map((r) => `- ${neutralizeDirectives(joinLines(r))}`);
631
+ const rest = reasons.length - shown.length;
632
+ if (rest > 0) shown.push(`- (${rest} more not shown)`);
633
+ return shown.join("\n");
634
+ }
635
+
591
636
  /**
592
637
  * Build the advisory forcing note appended to a task result the gate did not accept.
593
638
  *
@@ -597,12 +642,24 @@ export function shouldVerifyTask(
597
642
  */
598
643
  export function buildForcingNote(
599
644
  reasons: string[],
600
- escalation?: { producerTier?: string; nextTier?: string | null },
645
+ escalation?: { producerTier?: string; nextTier?: string | null; incomplete?: boolean },
601
646
  ): string {
602
647
  const body =
603
648
  reasons.length > 0
604
- ? reasons.map((r) => `- ${neutralizeDirectives(r)}`).join("\n")
649
+ ? reasonLines(reasons)
605
650
  : "- (no reasons provided)";
651
+ // §2.9 E8 / I7: a progress note or a budget stop is incomplete, not a failed result.
652
+ // QA-P15-2-4: the verdict's structured flag (`incomplete`); a caller that cannot
653
+ // pass it is recognised by the router's own incomplete reason among the reasons,
654
+ // matched exactly (QA-P15-1-6: a grader's "incomplete: …" stays a failure), so a
655
+ // caveat appended after it does not change the rendering.
656
+ if (escalation?.incomplete === true || reasons.some(isIncompleteReason)) {
657
+ return (
658
+ `[router \u26a0 INCOMPLETE] The delegate stopped before a final result:\n` +
659
+ `${body}\n` +
660
+ `NEXT: resume the same delegation so it can finish; do not treat the prior result as complete.`
661
+ );
662
+ }
606
663
  const next =
607
664
  escalation?.nextTier
608
665
  ? `NEXT: address the above, then re-run via \`Task(subagent_type="${escalation.nextTier}")\`` +
@@ -634,6 +691,6 @@ export function buildAcceptedSuffix(
634
691
  const verified = outcome === "pass" && caveats.length === 0;
635
692
  const label = verified ? `[router \u2713 verified: ${method}]` : `[router \u26a0 UNVERIFIED: ${method}]`;
636
693
  return `\n\n${label}` + (caveats.length
637
- ? `\nVerification caveats — NOT verified (acceptance is not a passing check):\n${caveats.map(r => `- ${neutralizeDirectives(r)}`).join("\n")}`
638
- : "") + (notes.length ? `\nVerification notes:\n${notes.map(r => `- ${neutralizeDirectives(r)}`).join("\n")}` : "");
694
+ ? `\nVerification caveats — NOT verified (acceptance is not a passing check):\n${reasonLines(caveats)}`
695
+ : "") + (notes.length ? `\nVerification notes:\n${reasonLines(notes)}` : "");
639
696
  }
package/src/verify/dod.ts CHANGED
@@ -54,16 +54,133 @@ const CLOSE_TAG_RE = /^\s*\[\/(acceptance|dod)\]\s*$/i;
54
54
  // summarizeDispatch
55
55
  // ---------------------------------------------------------------------------
56
56
 
57
- export function summarizeDispatch(text: string): string {
57
+ /**
58
+ * Router-protocol lines (§2.9 E8, QA-P15-1-8): a `[router]` / `[route …]` line and
59
+ * the whole-line directives `CAP:<n|none>`, `VERIFY:<word>`, `VERIFY_WAIT:<value>`;
60
+ * `reason:` only when a CAP line is present. They steer the router, they are
61
+ * never the task's outcome. "Verify: …" / "Reason: …" task lines stay criteria.
62
+ */
63
+ const ROUTER_LINE_RE = /^(?:\[router\]|\[route(?:\s[^\]]*)?\]$)/i;
64
+ const CAP_LINE_RE = /^CAP\s*:\s*(?:\d+|none)\s*$/i;
65
+ const VERIFY_LINE_RE = /^VERIFY:\s*\w+\s*$/;
66
+ const VERIFY_WAIT_LINE_RE = /^VERIFY_WAIT:\s*\S+\s*$/;
67
+ const REASON_LINE_RE = /^reason\s*:/i;
68
+
69
+ const WRAPPERS = new Set(["*", "_", "`"]);
70
+ const TRAILING_PUNCTUATION = new Set([".", ",", ";", "!"]);
71
+
72
+ /**
73
+ * QA-P15-2-10: a directive wrapped in markdown (`**VERIFY:required**`,
74
+ * `` `CAP:8` ``) or ending in punctuation (`VERIFY:required.`) is still a
75
+ * directive. Linear scans, no backtracking.
76
+ */
77
+ function unwrapDirective(line: string): string {
78
+ let start = 0;
79
+ let end = line.length;
80
+ while (start < end && WRAPPERS.has(line[start]!)) start++;
81
+ while (end > start && (WRAPPERS.has(line[end - 1]!) || TRAILING_PUNCTUATION.has(line[end - 1]!))) end--;
82
+ return line.slice(start, end).trim();
83
+ }
84
+
85
+ function isCapLine(line: string): boolean {
86
+ return CAP_LINE_RE.test(unwrapDirective(line));
87
+ }
88
+
89
+ function isDirectiveLine(line: string, hasCap: boolean): boolean {
90
+ const bare = unwrapDirective(line);
91
+ return (
92
+ ROUTER_LINE_RE.test(bare) ||
93
+ CAP_LINE_RE.test(bare) ||
94
+ VERIFY_LINE_RE.test(bare) ||
95
+ VERIFY_WAIT_LINE_RE.test(bare) ||
96
+ (hasCap && REASON_LINE_RE.test(bare))
97
+ );
98
+ }
99
+
100
+ const SENTENCE_ENDS = new Set([".", "!", "?", "\u2026"]);
101
+
102
+ /**
103
+ * QA-P15-1-7: a line over the budget keeps its leading WHOLE sentences that fit
104
+ * (cut only between sentences: a sentence end followed by a space); "" when even
105
+ * the first sentence does not fit.
106
+ */
107
+ function leadingSentences(line: string, budget: number): string {
108
+ if (codePointLength(line) <= budget) return line;
109
+ let kept = 0;
110
+ let points = 0;
111
+ let segment = 0;
112
+ for (let i = 0; i < line.length; i++) {
113
+ if (!SENTENCE_ENDS.has(line[i]!) || line[i + 1] !== " ") continue;
114
+ points += codePointLength(line.slice(segment, i + 1));
115
+ if (points > budget) break;
116
+ kept = i + 1;
117
+ segment = i + 1;
118
+ }
119
+ return line.slice(0, kept);
120
+ }
121
+
122
+ /**
123
+ * The dispatch's first non-empty line that is not a router directive,
124
+ * whitespace-collapsed and never cut mid-sentence (§2.9 E8): whole when it fits
125
+ * the verification budget, else its leading whole sentences that fit.
126
+ */
127
+ export function summarizeDispatch(text: string, budget: number = CRITERIA_BUDGET_CHARS): string {
128
+ const line = firstTaskLine(text);
129
+ return line ? leadingSentences(line, budget) : "";
130
+ }
131
+
132
+ /** The dispatch's first non-empty line that is not a router directive, whitespace-collapsed; "" if none. */
133
+ function firstTaskLine(text: string): string {
58
134
  if (!text) return "";
59
- const lines = text.split("\n");
135
+ const lines = text.split("\n").map((line) => line.trim().replace(/\s+/g, " "));
136
+ const hasCap = lines.some(isCapLine);
60
137
  for (const line of lines) {
61
- const trimmed = line.trim().replace(/\s+/g, " ");
62
- if (trimmed) return trimmed.slice(0, 120);
138
+ if (line && !isDirectiveLine(line, hasCap)) return line;
63
139
  }
64
140
  return "";
65
141
  }
66
142
 
143
+ // ---------------------------------------------------------------------------
144
+ // fitCriteria — the verification text budget (§2.9 E8)
145
+ // ---------------------------------------------------------------------------
146
+
147
+ /** Budget for the criteria text sent to a grader, in code points. */
148
+ export const CRITERIA_BUDGET_CHARS = 4000;
149
+
150
+ /** Length in code points (a surrogate pair counts once), so the budget is multi-byte safe. */
151
+ export function codePointLength(text: string): number {
152
+ return Array.from(text).length;
153
+ }
154
+
155
+ /**
156
+ * Whole criteria only: each criterion, in order, is kept when it fits in what is
157
+ * left of the budget, otherwise omitted (never cut). One criterion longer than
158
+ * the whole budget is omitted. `omitted` criteria are not graded.
159
+ */
160
+ export function fitCriteria(
161
+ criteria: readonly string[],
162
+ budget: number = CRITERIA_BUDGET_CHARS,
163
+ ): { criteria: string[]; omitted: number } {
164
+ const kept: string[] = [];
165
+ let used = 0;
166
+ let omitted = 0;
167
+ for (const criterion of criteria) {
168
+ const length = codePointLength(criterion);
169
+ if (used + length <= budget) {
170
+ kept.push(criterion);
171
+ used += length;
172
+ } else {
173
+ omitted += 1;
174
+ }
175
+ }
176
+ return { criteria: kept, omitted };
177
+ }
178
+
179
+ /** "1 criterion omitted" / "n criteria omitted". */
180
+ export function omittedCriteriaText(omitted: number): string {
181
+ return `${omitted} ${omitted === 1 ? "criterion" : "criteria"} omitted`;
182
+ }
183
+
67
184
  // ---------------------------------------------------------------------------
68
185
  // normalizeDoD
69
186
  // ---------------------------------------------------------------------------
@@ -252,12 +369,12 @@ export function inferDoD(dispatchText: string, tier: string, hints: InferHints):
252
369
  const criteria: string[] = [];
253
370
 
254
371
  if (checks.length === 0) {
255
- const summary = summarizeDispatch(dispatchText);
256
- criteria.push(
257
- summary.length > 0
258
- ? summary
259
- : "the delegated task is completed as described in the dispatch",
260
- );
372
+ const line = firstTaskLine(dispatchText);
373
+ const summary = line ? leadingSentences(line, CRITERIA_BUDGET_CHARS) : "";
374
+ // QA-P15-2-11: a first sentence over the budget is kept whole, never replaced
375
+ // by the generic text; the grader budget (fitCriteria) omits it, so no
376
+ // criterion is graded and the verdict is unverifiable.
377
+ criteria.push(summary || line || "the delegated task is completed as described in the dispatch");
261
378
  }
262
379
 
263
380
  const rawPath = hints.declaredPath != null ? hints.declaredPath.trim() : "";