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
@@ -12,13 +12,23 @@
12
12
  * The hint and the generated `R:` line come from the same kernel, but the hint is only emitted when the kernel says
13
13
  * `switched` for the class's static tier, i.e. when it agrees with a move the line itself could make (QA focus: a hint
14
14
  * must never contradict the `R:` line). Errors are logged and the system prompt stays as the legacy hook built it.
15
+ *
16
+ * Roles mode (`routing.delegation: "roles"`, plan #84 T2.2.1): nothing is added or rewritten — no per-turn hint, no tier
17
+ * `R:` line, no route-line paragraph. The roles protocol carries its own class → role line and route-line keys, and a
18
+ * hint or a tier line would name tiers; a system part that changes per turn would also cost the orchestrator its
19
+ * prompt cache. The check is the roles protocol's heading among the router's own parts, i.e. the text the orchestrator
20
+ * actually carries: a roles config with no enabled role falls back to the tiers protocol, augmented as in tiers mode.
15
21
  */
16
22
 
17
23
  import {
18
24
  DELEGATION_PROTOCOL_HEADING,
25
+ ROLES_PROTOCOL_HEADING,
19
26
  buildRouteLineProtocol,
20
27
  swapTaxonomyLine,
21
28
  } from "../../router/protocol";
29
+ /** The roles heading only counts at the start of a line (QA-P22-2-4): a part that merely quotes it mid-line is not the roles protocol. */
30
+ const ROLES_HEADING_LINE = /^## Role Delegation Protocol \(MANDATORY\)$/m;
31
+
22
32
  import { classify } from "../classify";
23
33
  import { CLASS_STATIC_TIER, type TaskFacts } from "../classify/types";
24
34
  import { buildLadder, decide, floorRankOf, generateTaxonomy, resolveChosen } from "../engine";
@@ -175,6 +185,10 @@ export function createSystemAugmenter(deps: SystemAugmenterDeps): SystemAugmente
175
185
  return {
176
186
  async augment(input, system, added): Promise<void> {
177
187
  try {
188
+ // Roles mode: no hint part, and the protocol text stays exactly as the legacy hook built it. Keyed on the roles
189
+ // protocol the orchestrator actually carries (QA-P22-1-5): `delegation: "roles"` with no enabled role keeps the
190
+ // tiers protocol, which is then augmented like tiers mode.
191
+ if (system.some((text) => added.has(text) && ROLES_HEADING_LINE.test(text))) return;
178
192
  const protocolAt: number[] = [];
179
193
  system.forEach((text, index) => {
180
194
  if (added.has(text) && text.includes(DELEGATION_PROTOCOL_HEADING)) protocolAt.push(index);
@@ -15,11 +15,13 @@
15
15
  import type { LadderSessionPolicyInput } from "../../escalate/ladder";
16
16
  import {
17
17
  resolveClassifierForPreset,
18
+ resolveRolesRouting,
18
19
  resolveRouting,
19
20
  resolveVariantSteps,
20
21
  type ResolvedRouting,
21
22
  type RouterConfig,
22
23
  } from "../../router/config";
24
+ import { resolveRoles, type RoleSpec } from "../../router/roles";
23
25
  import { createClassifierBackend, type ClassifyDeps } from "../classify";
24
26
  import type { ClassifierBackend, ClassifierSettings, HostGenerate } from "../classify/types";
25
27
  import type { EngineStoreView } from "../engine/types";
@@ -74,12 +76,42 @@ export interface Prepared {
74
76
  readonly enqueue: (row: LogRow) => void;
75
77
  }
76
78
 
79
+ /**
80
+ * Everything one ROLE dispatch needs (#84 P2.1 T2.1.2). Unlike {@link Prepared} it exists in every engine mode, `static`
81
+ * included: a role dispatch always gets a router-set model (I2). Only `routing.delegation: "roles"` on v2 produces one.
82
+ */
83
+ export interface RolePrepared {
84
+ readonly cfg: RouterConfig;
85
+ /** The resolved role table (`resolveRoles(cfg, "v2")`). */
86
+ readonly roles: ReadonlyMap<string, RoleSpec>;
87
+ /** The dispatched role. */
88
+ readonly spec: RoleSpec;
89
+ readonly routing: ResolvedRouting;
90
+ /** `routing.engine`: `static` decides the static default and writes no row. */
91
+ readonly engine: ResolvedRouting["engine"];
92
+ /** `routing.exploration.rate` (0 unless roles mode; the kernel clamps it). */
93
+ readonly exploration: number;
94
+ readonly catalog: WireCatalog;
95
+ readonly session: LadderSessionPolicyInput;
96
+ /** The outcome store (posteriors); `null` when the engine is static. */
97
+ readonly store: EngineStoreView | null;
98
+ /** The decision-log queue; `null` when the engine is static (no rows). */
99
+ readonly enqueue: ((row: LogRow) => void) | null;
100
+ readonly classifyDeps: ClassifyDeps;
101
+ }
102
+
77
103
  export interface EngineRuntime {
78
104
  /**
79
105
  * `null` when the engine is static (or the host is not v2): nothing was touched. Never throws. `cfg` is the config the caller
80
106
  * already loaded (one `loadConfig` per hook call); without it the runtime loads its own.
81
107
  */
82
108
  prepare(cfg?: RouterConfig): Promise<Prepared | null>;
109
+ /**
110
+ * #84 P2.1: `null` unless `agent` is an enabled role agent of `routing.delegation: "roles"` on v2 (tiers mode: `null` before any
111
+ * host call). For a role agent it THROWS when the dispatch cannot be prepared: the caller refuses the role dispatch (fail closed).
112
+ * Optional so that hand-made runtimes keep compiling; `createEngineRuntime` always provides it.
113
+ */
114
+ prepareRoles?(agent: string, cfg?: RouterConfig): Promise<RolePrepared | null>;
83
115
  /** The dispatching session's view of the host's agents (evaluated permissions included). */
84
116
  agents(parentAgent: string | undefined, sessionRules: readonly PermissionRule[]): Promise<AgentView | null>;
85
117
  /** The classifier dependencies for this config (backend memoized). */
@@ -146,7 +178,48 @@ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
146
178
  return routingMemo.routing;
147
179
  };
148
180
 
149
- return {
181
+ const classifyDepsFor = (cfg: RouterConfig, routing: ResolvedRouting): ClassifyDeps => {
182
+ const settings = resolveClassifierForPreset(routing.classifier, cfg.activePreset);
183
+ const key = JSON.stringify([
184
+ settings.backend, settings.model, settings.baseUrl, settings.apiKeyEnv, settings.timeoutMs, settings.samples, settings.maxStateChars,
185
+ ]);
186
+ if (classifierMemo === null || classifierMemo.key !== key) {
187
+ const memoSettings: ClassifierSettings = {
188
+ backend: settings.backend,
189
+ model: settings.model,
190
+ baseUrl: settings.baseUrl,
191
+ apiKeyEnv: settings.apiKeyEnv,
192
+ timeoutMs: settings.timeoutMs,
193
+ samples: settings.samples,
194
+ maxStateChars: settings.maxStateChars,
195
+ };
196
+ classifierMemo = {
197
+ key,
198
+ settings: memoSettings,
199
+ backend: createClassifierBackend(memoSettings, {
200
+ ...(deps.generate === undefined ? {} : { generate: deps.generate }),
201
+ logger: deps.logger,
202
+ }),
203
+ };
204
+ }
205
+ return {
206
+ cfg,
207
+ settings: classifierMemo.settings,
208
+ minClassConfidence: routing.minClassConfidence,
209
+ backend: classifierMemo.backend,
210
+ logger: deps.logger,
211
+ };
212
+ };
213
+
214
+ const sessionPolicyOf = (cfg: RouterConfig, routing: ResolvedRouting): LadderSessionPolicyInput => ({
215
+ host: "v2",
216
+ variantSteps: resolveVariantSteps(cfg, "v2"),
217
+ maxContextFraction: routing.sessionReuse.maxContextFraction,
218
+ catalog: (model) => catalog.entry(model),
219
+ warn: (message) => deps.logger.warn(message),
220
+ });
221
+
222
+ const self: EngineRuntime = {
150
223
  async prepare(given): Promise<Prepared | null> {
151
224
  try {
152
225
  const cfg = given ?? deps.loadConfig();
@@ -209,35 +282,50 @@ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
209
282
  },
210
283
 
211
284
  classifyDeps(prepared): ClassifyDeps {
212
- const settings = resolveClassifierForPreset(prepared.routing.classifier, prepared.cfg.activePreset);
213
- const key = JSON.stringify([
214
- settings.backend, settings.model, settings.baseUrl, settings.apiKeyEnv, settings.timeoutMs, settings.samples, settings.maxStateChars,
215
- ]);
216
- if (classifierMemo === null || classifierMemo.key !== key) {
217
- const memoSettings: ClassifierSettings = {
218
- backend: settings.backend,
219
- model: settings.model,
220
- baseUrl: settings.baseUrl,
221
- apiKeyEnv: settings.apiKeyEnv,
222
- timeoutMs: settings.timeoutMs,
223
- samples: settings.samples,
224
- maxStateChars: settings.maxStateChars,
225
- };
226
- classifierMemo = {
227
- key,
228
- settings: memoSettings,
229
- backend: createClassifierBackend(memoSettings, {
230
- ...(deps.generate === undefined ? {} : { generate: deps.generate }),
231
- logger: deps.logger,
232
- }),
233
- };
285
+ return classifyDepsFor(prepared.cfg, prepared.routing);
286
+ },
287
+
288
+ async prepareRoles(agent, given): Promise<RolePrepared | null> {
289
+ if (disposed) return null;
290
+ let cfg: RouterConfig;
291
+ let roles: ReadonlyMap<string, RoleSpec>;
292
+ try {
293
+ cfg = given ?? deps.loadConfig();
294
+ // Tiers mode (and v1, which never reaches this v2 runtime): an empty table before any host call (I1).
295
+ roles = resolveRoles(cfg, "v2");
296
+ } catch (error) {
297
+ // Not known to be a role dispatch: the tier path decides (and fails safe) as before.
298
+ deps.logger.warn("[router] routing: the role table could not be resolved", { error: describeError(error) });
299
+ return null;
300
+ }
301
+ const spec = roles.get(agent);
302
+ if (spec === undefined) return null;
303
+ const routing = routingOf(cfg);
304
+ let store: EngineStoreView | null = null;
305
+ let enqueue: ((row: LogRow) => void) | null = null;
306
+ if (routing.engine !== "static") {
307
+ // The tier engine's own preparation: the same store and decision-log queue (A3: one writer per process).
308
+ const prepared = await self.prepare(cfg);
309
+ if (prepared !== null) {
310
+ store = prepared.store;
311
+ enqueue = prepared.enqueue;
312
+ }
313
+ } else {
314
+ await catalog.ensure(); // static: no store, no rows, but the catalog decides whether a tier variant exists
234
315
  }
316
+ if (disposed) return null;
235
317
  return {
236
- cfg: prepared.cfg,
237
- settings: classifierMemo.settings,
238
- minClassConfidence: prepared.routing.minClassConfidence,
239
- backend: classifierMemo.backend,
240
- logger: deps.logger,
318
+ cfg,
319
+ roles,
320
+ spec,
321
+ routing,
322
+ engine: routing.engine,
323
+ exploration: resolveRolesRouting(cfg, "v2").exploration.rate,
324
+ catalog,
325
+ session: sessionPolicyOf(cfg, routing),
326
+ store,
327
+ enqueue,
328
+ classifyDeps: classifyDepsFor(cfg, routing),
241
329
  };
242
330
  },
243
331
 
@@ -251,6 +339,7 @@ export function createEngineRuntime(deps: RuntimeDeps): EngineRuntime {
251
339
  while (releasing.size > 0) await Promise.allSettled([...releasing]);
252
340
  },
253
341
  };
342
+ return self;
254
343
  }
255
344
 
256
345
  /** The session's own permission rules (`Session.Info.permissions`). */
package/src/v2.ts CHANGED
@@ -4,6 +4,7 @@ import ModelRouterPlugin from "./index";
4
4
  import { createV2Runtime } from "./compat/v2-client";
5
5
  import { registerV2Hooks } from "./compat/v2-hooks";
6
6
  import type { Ingest } from "./routing/outcomes/ingest";
7
+ import type { BudgetSnapshot } from "./guard/enforce";
7
8
 
8
9
  /** Keep the routing engine shared; translate only the host API at this boundary. */
9
10
  export default {
@@ -14,6 +15,16 @@ export default {
14
15
  // The engine consumes directory/client only. V2 has no legacy HTTP server
15
16
  // URL or Bun shell context; do not invent either for the adapter.
16
17
  let ingest: Ingest | undefined;
18
+ // #84 P2.1: the plugin's `/bypass` state, read by the role dispatch path (the router's own gate will not run while bypassed, S10/P-9).
19
+ let isBypassed: (() => boolean) | undefined;
20
+ let budgetSnapshot: ((childSessionID: string) => BudgetSnapshot) | undefined;
21
+ // #84 P2.1 (handoff 22): the host's own stops of role children (step limit, context overflow), observed by the adapter from the
22
+ // event stream and folded into the plugin's budget signals. The adapter hands its observer back once registered.
23
+ let observeHostBudget: ((childSessionID: string, stepLimit: number | null) => boolean | "unobserved") | undefined;
24
+ let roleLive: ((agent: string) => boolean) | undefined;
25
+ let verifyEnabled: (() => boolean) | undefined;
26
+ // QA-G-A3-2: the plugin's count of a role child's call refused outside its guard (role-authority refusals, permission denials).
27
+ let recordRefusal: ((sessionID: string, agent: string | undefined, tool: string, args: unknown) => string | undefined) | undefined;
17
28
  const input = {
18
29
  directory: ctx.location.directory,
19
30
  worktree: ctx.location.project.directory,
@@ -32,8 +43,22 @@ export default {
32
43
  await ctx.session.synthetic({ sessionID: notice.sessionID, text: notice.text, description: notice.description, resume: false });
33
44
  },
34
45
  routerOnIngest: (created: Ingest) => { ingest = created; },
46
+ routerOnBypassState: (read: () => boolean) => { isBypassed = read; },
47
+ // QA-P21-1-3: the plugin's budget snapshot (guard state + read-only CAP state) for the adapter's budget notice.
48
+ routerOnBudgetSnapshot: (read: (childSessionID: string) => BudgetSnapshot) => { budgetSnapshot = read; },
49
+ routerHostBudget: (childSessionID: string, stepLimit: number | null) => observeHostBudget?.(childSessionID, stepLimit),
50
+ // QA-P21-2-4: the adapter's "this role agent is registered" check; QA-P21-2 nit 3: whether router_verify is registered.
51
+ routerRoleLive: (agent: string) => roleLive?.(agent),
52
+ routerOnVerifyEnabled: (read: () => boolean) => { verifyEnabled = read; },
53
+ routerOnRefusal: (record: NonNullable<typeof recordRefusal>) => { recordRefusal = record; },
35
54
  };
36
55
  const hooks = await ModelRouterPlugin(input as unknown as PluginInput);
37
- return registerV2Hooks(ctx, hooks, runtime, ingest ? { ingest } : {});
56
+ return registerV2Hooks(ctx, hooks, runtime, {
57
+ ...(ingest ? { ingest } : {}), ...(isBypassed ? { isBypassed } : {}), ...(budgetSnapshot ? { budgetSnapshot } : {}),
58
+ ...(verifyEnabled ? { routerVerifyEnabled: verifyEnabled } : {}),
59
+ ...(recordRefusal ? { recordRefusal } : {}),
60
+ onHostBudget: (observe) => { observeHostBudget = observe; },
61
+ onRoleLive: (isLive) => { roleLive = isLive; },
62
+ });
38
63
  },
39
64
  } satisfies Plugin.Plugin & { server: typeof ModelRouterPlugin };
@@ -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;