opencode-model-router 2.3.0 → 2.4.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 (61) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/README.md +56 -10
  3. package/package.json +1 -1
  4. package/src/commands/output.ts +21 -1
  5. package/src/compat/v2-hooks.ts +1322 -18
  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/v2.ts +26 -1
  54. package/src/verify/checker.ts +249 -7
  55. package/src/verify/deterministic.ts +10 -1
  56. package/src/verify/dispatch.ts +63 -6
  57. package/src/verify/dod.ts +127 -10
  58. package/src/verify/gate.ts +75 -7
  59. package/src/verify/types.ts +12 -0
  60. package/src/verify/wiring.ts +55 -10
  61. package/tiers.json +13 -5
@@ -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() : "";
@@ -22,8 +22,9 @@ import type { DeterministicDeps } from "./types";
22
22
  import type { DoD } from "./dod";
23
23
  import { isCheckable } from "./dod";
24
24
  import { runDeterministic } from "./deterministic";
25
- import { runChecker } from "./checker";
25
+ import { incompleteVerdict, isIncompleteVerdict, runChecker } from "./checker";
26
26
  import type { ArtefactView, CheckerDeps } from "./checker";
27
+ import type { BudgetSnapshot } from "../guard/enforce";
27
28
  import { isAbsolute } from "node:path";
28
29
  import { isWithinDir, resolveBaseDir } from "./paths";
29
30
 
@@ -35,6 +36,15 @@ export interface Artefact {
35
36
  declaredOutputs: string[];
36
37
  producerSessionID: string;
37
38
  producerTier: string;
39
+ /** The producer follows the return contract (role agents, P2.1); absent = a router tier. */
40
+ returnContract?: boolean;
41
+ /**
42
+ * QA-P15-2-5: the producer's guard budget state captured when its task
43
+ * returned (enforce.ts captureBudget, with sessions.ts readCapReached). Absent:
44
+ * read live when the gate runs (the synchronous task path runs it right after
45
+ * the return).
46
+ */
47
+ budget?: BudgetSnapshot;
38
48
  }
39
49
 
40
50
  /** The delegation being judged: its DoD plus dispatch-time classification. */
@@ -51,6 +61,24 @@ export interface Delegation {
51
61
  * router's own directory", which is the pre-existing behaviour exactly.
52
62
  */
53
63
  cwd?: string;
64
+ /**
65
+ * #84 P3.3 DF2-F1: the validated work root of a ROLE dispatch (plan §2.2; `routedWorkRoot`). Present: verification runs in
66
+ * it — the default base when `cwd` is absent, the base a relative `cwd` resolves against — and a `cwd` outside it is refused
67
+ * (unverifiable, nothing runs). Absent (tier dispatches): unchanged (I1). Set from `verificationScope` (index.ts): the child's
68
+ * bound work root, else its canonical session directory (QA-P33F1-1-1, 1-3), with `cwd` the checked canonical directory.
69
+ */
70
+ workRoot?: string;
71
+ /**
72
+ * QA-P33F1-1-2: the `cwd:` the caller found outside `workRoot` by P2.3's containment rule (`verificationScope.refused`, as
73
+ * written). With `workRoot`, the gate refuses it (unverifiable) without resolving it.
74
+ */
75
+ refusedCwd?: string;
76
+ /**
77
+ * Fix-1 review nit: where the requested cwd (`cwd` / `refusedCwd`) came from — the call's own `cwd` argument or the
78
+ * `[acceptance]` block's `cwd:` (work-root.ts `requestedVerificationCwdSource`). Only names the source in a refusal; absent:
79
+ * the refusal names neither.
80
+ */
81
+ cwdSource?: "argument" | "acceptance";
54
82
  }
55
83
 
56
84
  export interface GateDeps {
@@ -82,7 +110,9 @@ export function gateResult(verdict: Verdict, dodSource: DoD["source"], strictUnv
82
110
  const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
83
111
  const caveats = verdict.caveats ?? (outcome === "unverifiable" ? verdict.reasons : []);
84
112
  return {
85
- accepted: outcome !== "fail" && !(strictUnverifiable && caveats.length > 0),
113
+ // QA-P15-1-1: an incomplete return (progress note, budget stop) is never accepted;
114
+ // as an unverifiable outcome it still gets no next-tier hint and moves no evidence.
115
+ accepted: outcome !== "fail" && !isIncompleteVerdict(verdict) && !(strictUnverifiable && caveats.length > 0),
86
116
  verdict: { ...verdict, outcome, ...(caveats.length ? { caveats } : {}) },
87
117
  dodSource,
88
118
  };
@@ -187,19 +217,55 @@ export async function accept(
187
217
  // THAT directory, not the router's. Both verifiers get the same effective
188
218
  // base dir so a deterministic check and a grader can never disagree about
189
219
  // where the work was supposed to land.
220
+ // QA-P15-1-2 / 2-6 / I7: a budget stop, or a contract follower's progress note,
221
+ // is incomplete under either verifier — never a failure, never a next-tier hint.
222
+ // Judged on the snapshot captured when the task returned (artefact.budget, 2-5).
223
+ const stopped = incompleteVerdict(artefact, {
224
+ progressNotes: true,
225
+ ladder: deps.checker.ladder,
226
+ budgetSnapshot: deps.checker.budgetSnapshot,
227
+ });
228
+ if (stopped) return gateResult(stopped, dodSource, deps.strictUnverifiable);
229
+
230
+ // DF2-F1: a role dispatch is verified in its work root (its default base, and the base of a relative cwd), never the router's.
231
+ const workRoot = delegation.workRoot;
232
+ const refuseCwd = (cwd: string): GateResult => {
233
+ // Refused like any path outside the role's work root (§2.2): no check runs and no grader is dispatched there.
234
+ // The text names where the cwd came from (fix-1 review nit): the call's `cwd` argument, or the [acceptance] block's `cwd:`.
235
+ const [subject, remedy] = delegation.cwdSource === "argument"
236
+ ? [`the call's cwd argument ${cwd}`, `Drop the "cwd" argument (the checks then run in the work root) or name a directory inside it.`]
237
+ : delegation.cwdSource === "acceptance"
238
+ ? [`the [acceptance] block's cwd ${cwd}`, `Remove "cwd:" (the checks then run in the work root) or name a directory inside it.`]
239
+ : [`the requested cwd ${cwd}`, `Name no cwd (the checks then run in the work root) or one inside it.`];
240
+ const reason = `${subject} is outside this role dispatch's work root ${workRoot}; the router verifies a role dispatch only inside its work root. ${remedy}`;
241
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
242
+ };
243
+ // QA-P33F1-1-2: the caller decided containment with P2.3's rule (routing/roles/work-root.ts verificationScope); a refused cwd
244
+ // is never resolved here (a UNC/device path reaches no filesystem call).
245
+ if (workRoot !== undefined && delegation.refusedCwd !== undefined) return refuseCwd(delegation.refusedCwd);
190
246
  const effectiveBaseDir = resolveBaseDir(
191
247
  delegation.cwd,
192
- deps.deterministic.cwd,
248
+ workRoot ?? deps.deterministic.cwd,
193
249
  );
250
+ // Backstop for a caller that did not check its cwd: lexical only (no filesystem call); a checked canonical cwd always passes.
251
+ if (workRoot !== undefined && !isWithinDir(effectiveBaseDir, workRoot)) return refuseCwd(effectiveBaseDir);
252
+ const canonical = deps.canonicalPath ?? ((path: string) => path);
194
253
 
195
254
  let verdict: Verdict;
196
255
  if (dod.kind === "deterministic") {
197
- const canonical = deps.canonicalPath ?? ((path: string) => path);
198
256
  const canonicalBase = canonical(effectiveBaseDir);
199
257
  if (artefact.changedFiles.length > 0 && artefact.changedFiles.every(
200
258
  ({ path }) => isAbsolute(path) && !isWithinDir(canonical(path), canonicalBase),
201
259
  )) {
202
- const reason = `the producer changed files only outside ${effectiveBaseDir} (e.g. ${artefact.changedFiles[0].path}); checks run there cannot see them. Add "cwd: <dir>" to the [acceptance] block to verify where the work landed.`;
260
+ // QA-P33F1-1 nit 1: a cwd: narrower than the work root, with work elsewhere in the root → widen (or drop) the cwd:.
261
+ const narrowed = workRoot !== undefined && !isWithinDir(canonical(workRoot), canonicalBase)
262
+ && artefact.changedFiles.some(({ path }) => isWithinDir(canonical(path), canonical(workRoot)));
263
+ const hint = workRoot === undefined
264
+ ? `Add "cwd: <dir>" to the [acceptance] block to verify where the work landed.`
265
+ : narrowed
266
+ ? `The [acceptance] block's "cwd:" narrows verification to ${effectiveBaseDir} inside the work root ${workRoot}: widen "cwd:" to where the work landed, or remove it (the checks then run in the work root).`
267
+ : `A role dispatch is verified only inside its work root ${workRoot}: the work belongs there.`;
268
+ const reason = `the producer changed files only outside ${effectiveBaseDir} (e.g. ${artefact.changedFiles[0].path}); checks run there cannot see them. ${hint}`;
203
269
  return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
204
270
  }
205
271
  verdict = await runDeterministic(dod, {
@@ -214,10 +280,12 @@ export async function accept(
214
280
  artefact: view(artefact),
215
281
  producerTier: artefact.producerTier,
216
282
  producerSessionID: artefact.producerSessionID,
217
- // Only when the delegation actually declared one. Passing the router's
283
+ ...(artefact.returnContract !== undefined ? { returnContract: artefact.returnContract } : {}),
284
+ ...(artefact.budget !== undefined ? { budget: artefact.budget } : {}),
285
+ // Only when the delegation actually declared one (or is a role dispatch: its work root, DF2-F1). Passing the router's
218
286
  // own directory here would scope every existing grader and add a
219
287
  // working-directory line to every existing prompt for no reason.
220
- ...(delegation.cwd ? { workingDir: effectiveBaseDir } : {}),
288
+ ...(delegation.cwd || workRoot !== undefined ? { workingDir: effectiveBaseDir } : {}),
221
289
  },
222
290
  deps.checker,
223
291
  );
@@ -26,6 +26,12 @@ export interface Verdict {
26
26
  * this verdict classified, concatenated across testsPass checks. Absent when no check classified.
27
27
  */
28
28
  failures?: FailureClassification;
29
+ /**
30
+ * #84 P3.3 fix 2 (plan §2.6, I6): the LLM grader that judged this verdict (checker.ts runChecker, only once a grader
31
+ * session answered): the tier the checker asked for and the model the grader was dispatched on (`provider/model`, null when
32
+ * the router does not know it). Outcome signals weigh such a verdict as a grader's, never as a deterministic check's.
33
+ */
34
+ grader?: { readonly tier: string; readonly model: string | null };
29
35
  }
30
36
 
31
37
  export interface ExecResult {
@@ -96,6 +102,12 @@ export interface DeterministicDeps {
96
102
  deadline?: Deadline;
97
103
  /** Preserve completed failures if an outer gate budget expires later. */
98
104
  onFailure?: (reason: string) => void;
105
+ /**
106
+ * #84 QA-G-B-2-1: set for a CARRIED acceptance (a role resume re-checking the block of an earlier attempt): a testsPass or
107
+ * lintClean check that ran no process (NoAffected: nothing of the change set maps to a test or a lintable file) is unverifiable
108
+ * with this reason, never a pass. Absent (every other gate, I1): NoAffected passes with its note, as before.
109
+ */
110
+ noAffectedUnverifiable?: string;
99
111
  exec: ExecSeam;
100
112
  /** Any FsSeam; lintClean scoping also uses the optional PlannerFs members when present. */
101
113
  fs: import("./runner").PlannerFs;
@@ -96,6 +96,8 @@ import { accept, gateResult, unverifiableGateResult, type GateDeps, type GateRes
96
96
  // wiring's narrower structural type silently discarded it, and the grader ran
97
97
  // against the router's directory while claiming to check the producer's.
98
98
  import type { GraderRequest } from "./checker";
99
+ import { isIncompleteVerdict } from "./checker";
100
+ import type { BudgetSnapshot } from "../guard/enforce";
99
101
  export type { GraderRequest };
100
102
 
101
103
  /**
@@ -396,8 +398,23 @@ export interface DeferredFinishInput {
396
398
  readonly cwd: string | undefined;
397
399
  readonly dod: DoD;
398
400
  readonly dispatchedAt: number;
401
+ /**
402
+ * #84 P2.1 (handoff 24, R7): the producer's guard budget state captured when its task returned (enforce.ts captureBudget with
403
+ * sessions.ts readCapReached). A later `router_verify` judges THIS snapshot, never the live state at verification time. Absent:
404
+ * the gate reads it live, as before.
405
+ */
406
+ readonly budget?: BudgetSnapshot;
407
+ /**
408
+ * #84 P3.3 DF2-F1 (fix-1 review nit): the role dispatch's verification root (the gate's `Delegation.workRoot`). `router_verify`
409
+ * hands it to its gate, which then re-checks the stored cwd's containment and gives the role's hints. Absent (tier dispatches):
410
+ * the gate runs as before (I1).
411
+ */
412
+ readonly workRoot?: string;
399
413
  }
400
414
 
415
+ /** Deferred budget snapshots kept for `router_verify` (by handle; oldest dropped first, like the pending registry's bound). */
416
+ export const MAX_DEFERRED_BUDGETS = 1000;
417
+
401
418
  /**
402
419
  * What finishDeferred decided. `deferred: false` means the delegation is NOT deferred and the
403
420
  * caller runs today's required gate on it (QA-2.4-4, QA-2.4-10): the dispatch record is left in the
@@ -668,7 +685,7 @@ export function formatVerifyReport(
668
685
  if (judged.accepted) {
669
686
  lines.push(indent(buildAcceptedSuffix(verdict.method, judged.verdict.outcome, judged.verdict.caveats, verdict.notes).trim()));
670
687
  } else {
671
- lines.push(indent(scrubText(buildForcingNote(verdict.reasons, { producerTier: item.producerTier, nextTier: result.nextTier ?? null }))));
688
+ lines.push(indent(scrubText(buildForcingNote(verdict.reasons, { producerTier: item.producerTier, nextTier: result.nextTier ?? null, incomplete: isIncompleteVerdict(verdict) }))));
672
689
  lines.push(indent(ROUTER_VERIFY_NO_RETRY_TEXT));
673
690
  }
674
691
  blocks.push(lines.join("\n"));
@@ -895,12 +912,12 @@ export interface VerificationWiring {
895
912
  graderSessions: Set<string>;
896
913
  /** Stop a plugin-created child; v1 deletes it, a host runner owns v2 cleanup. Never throws. */
897
914
  disposeChildSession(sid: string): Promise<void>;
898
- /** Run one grader turn, parented to the caller's session when given. */
915
+ /** Run one grader turn, parented to the caller's session when given. `model`: the model it was dispatched on (null = host default). */
899
916
  dispatchGrader(
900
917
  req: GraderRequest,
901
918
  parentSessionID?: string,
902
919
  inFlight?: Set<string>,
903
- ): Promise<{ sessionID: string; text: string }>;
920
+ ): Promise<{ sessionID: string; text: string; model?: string | null }>;
904
921
  /**
905
922
  * Deps for the acceptance gate; graders are parented to parentSessionID.
906
923
  *
@@ -1212,16 +1229,21 @@ export function createVerificationWiring(deps: {
1212
1229
  parentSessionID?: string,
1213
1230
  inFlight?: Set<string>,
1214
1231
  creatorSessionID: string | null = parentSessionID ?? null,
1215
- ): Promise<{ sessionID: string; text: string }> => {
1232
+ ): Promise<{ sessionID: string; text: string; model: string | null }> => {
1233
+ // #84 P3.3 fix 2: the model the grader is dispatched on travels with its answer (checker.ts GraderResult.model → the
1234
+ // verdict's `grader`), so the outcome signals can check its independence (plan §2.6). Null: the host's default model.
1235
+ const modelRef = (model: { providerID: string; modelID: string } | null): string | null =>
1236
+ model === null ? null : `${model.providerID}/${model.modelID}`;
1216
1237
  if (deps.childRunner) {
1217
1238
  const cfg = getConfig();
1218
1239
  const controller = new AbortController();
1240
+ const model = tierModel(cfg, req.tier);
1219
1241
  let sid: string | undefined;
1220
1242
  try {
1221
- return await withTimeout(deps.childRunner.run({
1243
+ const answer = await withTimeout(deps.childRunner.run({
1222
1244
  parentSessionID,
1223
1245
  cwd: req.cwd,
1224
- model: tierModel(cfg, req.tier) ?? undefined,
1246
+ model: model ?? undefined,
1225
1247
  system: req.system,
1226
1248
  prompt: req.prompt,
1227
1249
  signal: controller.signal,
@@ -1232,6 +1254,7 @@ export function createVerificationWiring(deps: {
1232
1254
  notifyChildCreated(sessionID, creatorSessionID);
1233
1255
  },
1234
1256
  }), graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs), "grader prompt");
1257
+ return { sessionID: answer.sessionID, text: answer.text, model: modelRef(model) };
1235
1258
  } finally {
1236
1259
  controller.abort();
1237
1260
  if (sid) {
@@ -1251,13 +1274,14 @@ export function createVerificationWiring(deps: {
1251
1274
  ...(req.cwd ? { query: { directory: req.cwd } } : {}),
1252
1275
  });
1253
1276
  const sid: string | undefined = created?.data?.id;
1254
- if (!sid) return { sessionID: "", text: "" };
1277
+ if (!sid) return { sessionID: "", text: "", model: null };
1255
1278
  graderSessions.add(sid);
1256
1279
  inFlight?.add(sid);
1257
1280
  notifyChildCreated(sid, creatorSessionID);
1258
1281
  try {
1259
1282
  const cfg = getConfig();
1260
- const model = tierModel(cfg, req.tier) ?? undefined;
1283
+ const tiered = tierModel(cfg, req.tier);
1284
+ const model = tiered ?? undefined;
1261
1285
  // Time-boxed for the same reason as the producer prompt, but with a
1262
1286
  // sharper edge: a grader that never answers must not be able to hold the
1263
1287
  // gate open. The RouterTimeoutError is deliberately allowed to propagate
@@ -1285,7 +1309,7 @@ export function createVerificationWiring(deps: {
1285
1309
  );
1286
1310
  const responseError = graderPromptResponseError(res);
1287
1311
  if (responseError) throw responseError;
1288
- return { sessionID: sid, text: extractAssistantText(res) };
1312
+ return { sessionID: sid, text: extractAssistantText(res), model: modelRef(tiered) };
1289
1313
  } finally {
1290
1314
  graderSessions.delete(sid);
1291
1315
  inFlight?.delete(sid);
@@ -1592,6 +1616,10 @@ export function createVerificationWiring(deps: {
1592
1616
  return plans.find(p => "unverifiable" in p) ?? plans[0] ?? unfinished;
1593
1617
  };
1594
1618
 
1619
+ /** #84 P2.1 (handoff 24): deferred budget snapshots by handle, read by `router_verify` (bounded, oldest out). */
1620
+ const deferredBudgets = new Map<string, BudgetSnapshot>();
1621
+ /** #84 P3.3 DF2-F1: the work roots of deferred role dispatches by handle, read by `router_verify` (same bound as the budgets). */
1622
+ const deferredWorkRoots = new Map<string, string>();
1595
1623
  const finishDeferred: VerificationWiring["finishDeferred"] = async (store, input) => {
1596
1624
  const producerTier = canonicalTier(input.producerTier);
1597
1625
  // The live reference promise (no signal: never awaited here). Its settled value at this moment
@@ -1658,6 +1686,17 @@ export function createVerificationWiring(deps: {
1658
1686
  return { deferred: false, reason: "unregistered", detail: `${reg.code}: ${reg.detail}` };
1659
1687
  }
1660
1688
  deferred = true;
1689
+ // #84 P2.1 (handoff 24, R7): the budget captured at return travels with the handle to `router_verify`.
1690
+ if (input.budget !== undefined) {
1691
+ deferredBudgets.delete(reg.handle);
1692
+ deferredBudgets.set(reg.handle, input.budget);
1693
+ while (deferredBudgets.size > MAX_DEFERRED_BUDGETS) deferredBudgets.delete(deferredBudgets.keys().next().value as string);
1694
+ }
1695
+ if (input.workRoot !== undefined) {
1696
+ deferredWorkRoots.delete(reg.handle);
1697
+ deferredWorkRoots.set(reg.handle, input.workRoot);
1698
+ while (deferredWorkRoots.size > MAX_DEFERRED_BUDGETS) deferredWorkRoots.delete(deferredWorkRoots.keys().next().value as string);
1699
+ }
1661
1700
  // 2.4.5 (pending.ts R14): queued, never awaited: the queue's own timer starts the run later.
1662
1701
  // An unattributed change set is not queued (nothing could run; it stays listed instead).
1663
1702
  if (background !== undefined && changedFiles !== "unavailable") {
@@ -1842,12 +1881,16 @@ export function createVerificationWiring(deps: {
1842
1881
  declaredOutputs: dod.deliverable ? [dod.deliverable] : [],
1843
1882
  producerSessionID: entry.producerSessionID,
1844
1883
  producerTier: entry.producerTier,
1884
+ // #84 P2.1 (handoff 24, R7): the snapshot captured when the task returned; absent → read live, as before.
1885
+ ...(deferredBudgets.has(entry.handle) ? { budget: deferredBudgets.get(entry.handle) as BudgetSnapshot } : {}),
1845
1886
  };
1846
1887
  let res: GateResult;
1847
1888
  let timedOut = false;
1889
+ // #84 P3.3 DF2-F1: a deferred role dispatch is judged in its work root, as its synchronous gate would be.
1890
+ const workRoot = deferredWorkRoots.get(entry.handle);
1848
1891
  try {
1849
1892
  res = await withTimeout(
1850
- accept({ dod, trivial: false, mode: "modeA", cwd: entry.cwd }, artefact, gateDeps),
1893
+ accept({ dod, trivial: false, mode: "modeA", cwd: entry.cwd, ...(workRoot !== undefined ? { workRoot } : {}) }, artefact, gateDeps),
1851
1894
  deadline.remaining(),
1852
1895
  "verification gate",
1853
1896
  );
@@ -2198,6 +2241,8 @@ export function createVerificationWiring(deps: {
2198
2241
  },
2199
2242
  disposeVerification: () => {
2200
2243
  dispatchStarts.clear();
2244
+ deferredBudgets.clear();
2245
+ deferredWorkRoots.clear();
2201
2246
  // 2.4.5: abort the background run first, so nothing re-queues while the coordinator stops.
2202
2247
  background?.dispose();
2203
2248
  return coordinator.dispose();