opencode-model-router 1.13.0 → 1.15.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.
package/src/index.ts CHANGED
@@ -9,6 +9,8 @@ import {
9
9
  overridePath,
10
10
  localOverridePath,
11
11
  findProjectOverride,
12
+ resolveVerifyBudget,
13
+ warnDeprecatedVerifyKeys,
12
14
  } from "./router/config";
13
15
  import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
14
16
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
@@ -47,6 +49,7 @@ import {
47
49
  CLAUDE_ORCHESTRATOR_PREFIX,
48
50
  CLAUDE_ANTI_NARRATION,
49
51
  assembleSystemPrompt,
52
+ DELEGATE_TOOL_DESCRIPTION,
50
53
  } from "./router/protocol";
51
54
  import { resolveEnforcementMode } from "./router/enforcement";
52
55
  import { createPluginLogger } from "./router/logger";
@@ -71,15 +74,15 @@ import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforc
71
74
  import { mkdirSync, writeFileSync, existsSync } from "node:fs";
72
75
  import { tmpdir } from "node:os";
73
76
  import { join, isAbsolute } from "node:path";
74
- import { exec as nodeExec } from "node:child_process";
75
77
  import { access, readFile as fsReadFile } from "node:fs/promises";
76
78
  import { tool } from "@opencode-ai/plugin";
77
79
  import { scrubText } from "./guard/scrub";
78
80
  import { accept, unverifiableGateResult } from "./verify/gate";
79
- import { createVerificationWiring, extractAssistantText } from "./verify/wiring";
81
+ import { applyDispatchCaveats, createVerificationWiring, dispatchDirectiveText, extractAssistantText, parseRouterVerifyArgs, type DispatchStart } from "./verify/wiring";
82
+ import { appendRouterFooter, buildLateNoticeBlock, buildPendingListBlock } from "./verify/pending";
83
+ import { createDeadline } from "./verify/deterministic";
80
84
  import {
81
85
  DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
82
- DEFAULT_GATE_BUDGET_MS,
83
86
  RouterTimeoutError,
84
87
  timeoutMs,
85
88
  withTimeout,
@@ -273,7 +276,15 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
273
276
  * still cover the common cases, so the exposure is a rare, transient re-run of
274
277
  * the old behaviour rather than a permanent loss of function.
275
278
  */
276
- const resolveIsRootSession = async (sessionID: string): Promise<boolean> => {
279
+ const resolveIsRootSession = async (sessionID: string): Promise<boolean> =>
280
+ (await lookupRootSession(sessionID)) ?? true;
281
+
282
+ /**
283
+ * The lookup behind resolveIsRootSession: true (no parentID), false (a parentID), or undefined
284
+ * when it is not known (the lookup failed, or failed recently and is throttled). QA-2.4-2 treats
285
+ * undefined as NOT root (isProvenRootCaller), where the protocol injection treats it as root.
286
+ */
287
+ const lookupRootSession = async (sessionID: string): Promise<boolean | undefined> => {
277
288
  const memo = sessionRootMemo.get(sessionID);
278
289
  if (memo !== undefined) {
279
290
  if (!memo) sessionStore.markChildSession(sessionID);
@@ -281,7 +292,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
281
292
  }
282
293
  const failedAt = sessionLookupFailedAt.get(sessionID);
283
294
  if (failedAt !== undefined && Date.now() - failedAt < SESSION_LOOKUP_RETRY_MS) {
284
- return true;
295
+ return undefined;
285
296
  }
286
297
  try {
287
298
  const res = await ctx.client.session.get({ path: { id: sessionID } });
@@ -307,7 +318,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
307
318
  sessionLookupFailedAt.delete(oldest);
308
319
  }
309
320
  warnSessionLookupFailedOnce();
310
- return true;
321
+ return undefined;
311
322
  }
312
323
  };
313
324
 
@@ -333,17 +344,39 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
333
344
  () => guardStore.sweep(),
334
345
  () => trajectoryStore.sweep(),
335
346
  () => changedFileStore.sweep(),
347
+ // 2.2.3: the S5 batch coordinator's defensive eviction (batch.ts B11). Declared below; the
348
+ // sweeper only runs from chat.message, long after this factory has returned.
349
+ () => { sweepVerification(); },
350
+ // 2.4.2b: TTL eviction and reaping of the pending registry (pending.ts R7; no timer of its own).
351
+ () => { pending.sweep(); },
336
352
  ]);
337
353
 
338
354
  // Layer-2's impure corner: exec, fs, and the opencode client, built once and
339
355
  // read back through getConfig so a reloaded cfg (from /preset, /budget or
340
356
  // /router enforce) applies to graded work too.
341
- const { graderSessions, dispatchGrader, buildGateDeps, disposeChildSession, beginVerification, prepareVerification } =
342
- createVerificationWiring({
343
- client: ctx.client,
344
- directory: ctx.directory,
345
- getConfig: () => cfg,
346
- });
357
+ // Passive warnings go to opencode's log rather than stderr: console output
358
+ // from a plugin paints over the TUI. Falls back to console when the server
359
+ // has no /log endpoint. See src/router/logger.ts.
360
+ const logger = createPluginLogger(ctx.client);
361
+
362
+ const {
363
+ graderSessions, dispatchGrader, buildGateDeps, disposeChildSession,
364
+ prepareVerification, startReferenceGc,
365
+ sweepVerification, disposeVerification,
366
+ startDispatch, takeDispatch, isDeferred: wiringIsDeferred, finishDeferred, applyLineage, pending,
367
+ verifyHandles,
368
+ // 2.4.5: undefined unless `background: true` at plugin start (pending.ts R14).
369
+ background,
370
+ } = createVerificationWiring({
371
+ client: ctx.client,
372
+ directory: ctx.directory,
373
+ getConfig: () => cfg,
374
+ logger,
375
+ });
376
+ // 2.1.5b: sweep reference dirs a crashed instance left behind. Fire-and-forget; never throws.
377
+ // QA-2.1-11: deferred (unref'd timer), so plugin start never holds the project directory with a
378
+ // git child; dispose cancels it.
379
+ const stopReferenceGc = startReferenceGc();
347
380
 
348
381
  // Best-effort, secret-free delegate scorecard dump (counts only).
349
382
  const dumpDelegateScorecard = (
@@ -367,10 +400,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
367
400
  // current plugin lifetime (i.e., until OpenCode is restarted).
368
401
  let bypassed = false;
369
402
 
370
- // Passive warnings go to opencode's log rather than stderr: console output
371
- // from a plugin paints over the TUI. Falls back to console when the server
372
- // has no /log endpoint. See src/router/logger.ts.
373
- const logger = createPluginLogger(ctx.client);
403
+ warnDeprecatedVerifyKeys(cfg, logger);
374
404
 
375
405
  // Fetch and normalize opencode's live provider/model catalog. Best-effort:
376
406
  // returns null when the client call fails, e.g. the server is not ready yet.
@@ -421,18 +451,55 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
421
451
  cfg.experimental?.verifiedDelegateTool === true ||
422
452
  process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
423
453
 
454
+ // 2.4.3b (plan 2.4.3 "Registration"): `router_verify` is registered whenever verification is
455
+ // enabled at plugin start, independent of enableDelegateTool: verify.require is not "never" and
456
+ // a verifying path exists (the native `task` path needs an enforcement mode other than "off";
457
+ // the delegate tool verifies in every mode). The tool map is fixed at start.
458
+ let routerVerifyEnabled = false;
459
+ try {
460
+ const startMode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
461
+ routerVerifyEnabled = cfg.enforcement?.verify?.require !== "never" && (startMode !== "off" || enableDelegateTool);
462
+ } catch (error) {
463
+ logger.warn("[verify] router_verify not registered: the enforcement mode could not be resolved", { error: scrubText(String(error)) });
464
+ }
465
+ /**
466
+ * 2.4.2 + 2.4.3b: a delegation defers only when `router_verify` exists to verify it later. A
467
+ * footer never names a tool this instance did not register; without it the delegation keeps the
468
+ * synchronous gate (never weaker).
469
+ */
470
+ const isDeferred: typeof wiringIsDeferred = (dod, directives, trivial) => routerVerifyEnabled && wiringIsDeferred(dod, directives, trivial);
471
+ /**
472
+ * QA-2.4-2: a deferred entry is keyed to the dispatching session (pending.ts R6), and only a root
473
+ * orchestrator ever sees a pending list (the system transform returns early for every child). So
474
+ * only a PROVEN root orchestrator session may defer. A subagent dispatching `task` or `delegate`
475
+ * (a grader, a tracked subagent, a session with a parentID) gets today's synchronous gate and
476
+ * registers nothing, whatever its directives say; so does an unknown session (no id, or a failed
477
+ * lookup: fail safe).
478
+ */
479
+ const isProvenRootCaller = async (sessionID: unknown): Promise<boolean> => {
480
+ if (typeof sessionID !== "string" || sessionID === "") return false;
481
+ if (graderSessions.has(sessionID) || sessionStore.isSubagent(sessionID)) return false;
482
+ return (await lookupRootSession(sessionID)) === true;
483
+ };
484
+
424
485
  return {
425
486
  // Warnings post to /log fire-and-forget, which loses the message when the
426
487
  // process is about to exit — `opencode run` and `opencode debug` are short
427
488
  // enough for that to be the normal case. Verified against opencode 1.18.16
428
489
  // that dispose is both called and awaited, so flushing here is enough.
429
490
  dispose: async () => {
491
+ stopReferenceGc();
492
+ // 2.4.5: abort a background run and drop its queue and notices before the registry goes.
493
+ background?.dispose();
494
+ // 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
495
+ pending.dispose();
496
+ // 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
497
+ await disposeVerification();
430
498
  await logger.flush();
431
499
  },
432
500
  tool: {
433
501
  ...(enableDelegateTool ? { delegate: tool({
434
- description:
435
- "Delegate a task to a tier subagent (fast | medium | heavy). The subagent's result is INDEPENDENTLY VERIFIED (deterministic checks, or an independent grader at >= the producer tier in a fresh session) before it is returned. Returns an accepted result on PASS, or an honest 'unmet' status on FAIL — never a self-reported completion. Optionally pass an [acceptance]...[/acceptance] block to define the Definition of Done.",
502
+ description: DELEGATE_TOOL_DESCRIPTION,
436
503
  args: {
437
504
  task: tool.schema
438
505
  .string()
@@ -468,10 +535,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
468
535
  // early return or a throw skipped — otherwise each retry leaks another.
469
536
  const producerSessions: string[] = [];
470
537
  let baselineID: string | undefined;
538
+ /** 2.4.2c: the directives and start time of this delegation, from its first attempt. */
539
+ let dispatchStart: DispatchStart | undefined;
540
+ /**
541
+ * 2.4.2c: finishDeferred clears the dispatch record (baselineID) once its reference
542
+ * settled; clearing it in the finally below would abort a capture still in flight.
543
+ */
544
+ let deferredOwnsBaseline = false;
471
545
  try {
472
546
  let activeCfg = cfg;
473
547
  try {
474
548
  activeCfg = loadConfig();
549
+ warnDeprecatedVerifyKeys(activeCfg, logger);
475
550
  } catch {
476
551
  activeCfg = cfg;
477
552
  }
@@ -516,6 +591,11 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
516
591
  sessionID: string;
517
592
  text: string;
518
593
  gateRes: Awaited<ReturnType<typeof accept>>;
594
+ } | {
595
+ sessionID: string;
596
+ text: string;
597
+ /** 2.4.2c: deferred; the section 1.5-16 footer to append to the result. */
598
+ deferredFooter: string;
519
599
  } | null> => {
520
600
  const taskText = forcingNote
521
601
  ? `${scrubText(forcingNote)}\n\n${args.task}`
@@ -533,7 +613,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
533
613
  // recapturing after a failed attempt would excuse its regression.
534
614
  if (!baselineID) {
535
615
  baselineID = producerSid;
536
- beginVerification(changedFileStore, baselineID, args.cwd, dod);
616
+ // 2.4.2c: the directives come from the orchestrator's `task` argument only; the
617
+ // capture is awaited for at most VERIFY_WAIT and continues in the background.
618
+ dispatchStart = await startDispatch(changedFileStore, baselineID, args.cwd, dod, args.task, false);
537
619
  }
538
620
  // Compose with Layer 1: guard the plugin-created producer session.
539
621
  try {
@@ -579,8 +661,64 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
579
661
  error instanceof Error ? error.message : String(error);
580
662
  producerText = "";
581
663
  }
664
+ // pending.ts R11: the producer's changes landed by now.
665
+ const returnedAt = Date.now();
666
+
667
+ // 2.4.2c, section 1.5-16: a deferred delegation runs no gate and no ladder. A producer
668
+ // that failed outright produced nothing to verify later; it keeps today's
669
+ // failed-attempt path, which runs no verification process either.
670
+ const finish = dispatchStart !== undefined && producerError === null && isDeferred(dod, dispatchStart.directives) &&
671
+ await isProvenRootCaller(toolCtx?.sessionID)
672
+ ? await finishDeferred(changedFileStore, {
673
+ dispatchID: baselineID,
674
+ orchestratorSessionID: toolCtx?.sessionID ?? "",
675
+ producerSessionID: producerSid,
676
+ producerTier: tier,
677
+ description: args.task,
678
+ cwd: args.cwd,
679
+ dod,
680
+ dispatchedAt: dispatchStart.dispatchedAt,
681
+ })
682
+ : undefined;
683
+ // QA-2.4-4 / QA-2.4-10: a finish that did not defer falls through to the required gate
684
+ // (and its ladder) below, with the dispatch record still in the store.
685
+ if (finish?.deferred === true) {
686
+ deferredOwnsBaseline = true;
687
+ if (producerSid !== baselineID) changedFileStore.clear(producerSid);
688
+ try {
689
+ sessionStore.unregister(producerSid);
690
+ sessionRootMemo.delete(producerSid);
691
+ } catch {
692
+ // non-fatal
693
+ }
694
+ try {
695
+ guardStore.clear(producerSid);
696
+ } catch {
697
+ // non-fatal
698
+ }
699
+ await disposeChildSession(producerSid);
700
+ return { sessionID: producerSid, text: producerText, deferredFooter: finish.footer };
701
+ }
702
+ // Once a delegation is gated, every later attempt of its ladder is gated too.
703
+ if (finish !== undefined && dispatchStart !== undefined) {
704
+ dispatchStart = { ...dispatchStart, directives: { ...dispatchStart.directives, mode: "required" } };
705
+ }
582
706
 
583
- const verification = await prepareVerification(changedFileStore, baselineID, producerSid, args.cwd);
707
+ const { gateBudgetMs } = resolveVerifyBudget(activeCfg);
708
+ // One deadline per gate invocation: every step inside the gate
709
+ // is bounded by it, and it is aborted (killing any spawned
710
+ // tree) when the gate's own withTimeout rejects. It exists
711
+ // before prepareVerification (T2 P0, QA-2.1-4), so the grade
712
+ // snapshot and the wait for a pending reference count against
713
+ // gateBudgetMs too.
714
+ const gateDeadline = createDeadline(gateBudgetMs);
715
+ let verification;
716
+ try {
717
+ verification = await prepareVerification(changedFileStore, baselineID, producerSid, args.cwd, gateDeadline);
718
+ } catch (error) {
719
+ gateDeadline.dispose();
720
+ throw error;
721
+ }
584
722
  const artefact = {
585
723
  changedFiles: verification.changedFiles,
586
724
  changeBaseline: verification.changeBaseline,
@@ -590,15 +728,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
590
728
  producerTier: tier,
591
729
  };
592
730
 
593
- const gateBudgetMs = timeoutMs(
594
- activeCfg.enforcement?.verify?.gateBudgetMs,
595
- DEFAULT_GATE_BUDGET_MS,
596
- );
597
731
  // Grader sessions opened by THIS accept() call, and only those.
598
732
  const gateGraderSessions = new Set<string>();
599
733
  const completedFailures: string[] = [];
600
- const gateDeps = buildGateDeps(toolCtx?.sessionID, gateGraderSessions);
601
- gateDeps.deterministic.testBaseline = verification.testBaseline;
734
+ const gateDeps = buildGateDeps(toolCtx?.sessionID, gateGraderSessions, verification, gateDeadline);
602
735
  gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
603
736
  let gateRes;
604
737
  try {
@@ -623,7 +756,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
623
756
  artefact,
624
757
  gateDeps,
625
758
  ),
626
- gateBudgetMs,
759
+ // What preparation left of the gate budget (QA-2.1-4).
760
+ gateDeadline.remaining(),
627
761
  "verification gate",
628
762
  );
629
763
  } catch (error) {
@@ -637,6 +771,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
637
771
  // someone else's delegation — reachable with the shipped
638
772
  // config, where a deterministic check may run a command for up
639
773
  // to 120s against a 90s gate budget.
774
+ gateDeadline.abort(
775
+ error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
776
+ );
640
777
  if (error instanceof RouterTimeoutError) {
641
778
  for (const gsid of gateGraderSessions) {
642
779
  try {
@@ -654,7 +791,23 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
654
791
  activeCfg.enforcement?.verify?.strictUnverifiable,
655
792
  completedFailures,
656
793
  );
794
+ } finally {
795
+ gateDeadline.dispose();
657
796
  }
797
+ // pending.ts R11, as on the native path. Within this ladder every attempt is judged
798
+ // against the first attempt's reference and dispatchedAt precedes every landedAt, so
799
+ // it only affects later delegations of the same session (a native re-dispatch of
800
+ // rejected delegate work is the T11 case too).
801
+ gateRes = applyLineage(gateRes, {
802
+ orchestratorSessionID: toolCtx?.sessionID ?? "",
803
+ root: verification.snapshot?.root,
804
+ dispatchID: baselineID,
805
+ dispatchedAt: dispatchStart?.dispatchedAt ?? returnedAt,
806
+ returnedAt,
807
+ strictUnverifiable: activeCfg.enforcement?.verify?.strictUnverifiable,
808
+ });
809
+ // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
810
+ gateRes = applyDispatchCaveats(gateRes, verification);
658
811
 
659
812
  // Per-attempt cleanup (drop producer session tracking + state).
660
813
  if (producerSid !== baselineID) changedFileStore.clear(producerSid);
@@ -689,6 +842,11 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
689
842
  return "[router] delegate failed: could not create a producer session.";
690
843
  }
691
844
  producerText = attempt.text;
845
+ if ("deferredFooter" in attempt) {
846
+ // Section 1.5-16: the result unchanged plus the footer, appended last. Never
847
+ // labelled accepted or verified, and never retried or escalated.
848
+ return appendRouterFooter(producerText, attempt.deferredFooter);
849
+ }
692
850
  const producerSid = attempt.sessionID;
693
851
  const gateRes = attempt.gateRes;
694
852
 
@@ -711,7 +869,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
711
869
  true,
712
870
  gateRes.verdict.method,
713
871
  );
714
- return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.caveats, gateRes.verdict.notes);
872
+ return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.outcome, gateRes.verdict.caveats, gateRes.verdict.notes);
715
873
  }
716
874
  if (action.action === "give_up") {
717
875
  dumpDelegateScorecard(
@@ -740,12 +898,44 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
740
898
  // disposeChildSession is fail-soft, so re-disposing an already
741
899
  // disposed session is harmless.
742
900
  for (const sid of producerSessions) {
743
- changedFileStore.clear(sid);
901
+ if (!(deferredOwnsBaseline && sid === baselineID)) changedFileStore.clear(sid);
744
902
  await disposeChildSession(sid);
745
903
  }
746
904
  }
747
905
  },
748
906
  }) } : {}),
907
+ // 2.4.3b, section 1.5-18: verify deferred delegations on the orchestrator's terms.
908
+ ...(routerVerifyEnabled ? { router_verify: tool({
909
+ description:
910
+ "Verify delegations that returned 'unverified' with a vrf_ handle. Runs the same checks as a required verification (affected tests, batched, under the verification slot and one gate deadline) and returns one verdict per handle: pass, fail (with the introduced failures and a suggested next tier) or unverifiable. Nothing is retried or escalated for you. Pass exactly one of `handles` or `pending: true` (every unverified delegation of this session).",
911
+ args: {
912
+ handles: tool.schema
913
+ .array(tool.schema.string())
914
+ .optional()
915
+ .describe("The vrf_ handles from the delegations' [router] footers."),
916
+ pending: tool.schema
917
+ .boolean()
918
+ .optional()
919
+ .describe("true: verify every still-unverified delegation of this session."),
920
+ },
921
+ async execute(
922
+ args: { handles?: string[]; pending?: boolean },
923
+ toolCtx?: { sessionID?: string; abort?: AbortSignal },
924
+ ): Promise<string> {
925
+ // Never throws: every failure is a text answer (the tool result reaches the orchestrator).
926
+ try {
927
+ const target = parseRouterVerifyArgs(args);
928
+ if ("error" in target) return target.error;
929
+ // R6: handles are scoped by the calling session; without one, every handle is unknown.
930
+ const sessionID = typeof toolCtx?.sessionID === "string" ? toolCtx.sessionID : "";
931
+ const report = await verifyHandles(sessionID, target, toolCtx?.abort !== undefined ? { signal: toolCtx.abort } : {});
932
+ return report.text;
933
+ } catch (error) {
934
+ logger.warn("[verify] router_verify failed", { error: scrubText(String(error)) });
935
+ return `[router] router_verify failed; nothing was verified: ${scrubText(String(error))}`;
936
+ }
937
+ },
938
+ }) } : {}),
749
939
  },
750
940
 
751
941
  // -----------------------------------------------------------------------
@@ -784,6 +974,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
784
974
  // Re-read cfg so /preset switches take effect without restart
785
975
  try {
786
976
  cfg = loadConfig();
977
+ warnDeprecatedVerifyKeys(cfg, logger);
787
978
  } catch {}
788
979
  try {
789
980
  sweepIdleStores();
@@ -891,12 +1082,16 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
891
1082
  if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string") {
892
1083
  const mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
893
1084
  if (shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) {
894
- beginVerification(changedFileStore, `task:${input.sessionID}:${input.callID}`,
1085
+ const prompt = typeof output?.args?.prompt === "string" ? output.args.prompt : undefined;
1086
+ const description = typeof output?.args?.description === "string" ? output.args.description : undefined;
1087
+ // 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
1088
+ // dispatch header or any repair touches it, and are kept for the after hook. The capture
1089
+ // is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
1090
+ await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
895
1091
  typeof output?.args?.cwd === "string" ? output.args.cwd : undefined,
896
- buildDelegationDoD({
897
- prompt: typeof output?.args?.prompt === "string" ? output.args.prompt : undefined,
898
- description: typeof output?.args?.description === "string" ? output.args.description : undefined,
899
- }));
1092
+ buildDelegationDoD({ prompt, description }),
1093
+ dispatchDirectiveText(prompt, description),
1094
+ true);
900
1095
  }
901
1096
  }
902
1097
  // A task call with no prompt (typically a forced delegation of a bare
@@ -1071,6 +1266,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1071
1266
  const requireMode = cfg.enforcement?.verify?.require;
1072
1267
  if (shouldVerifyTask(input.tool, mode, requireMode)) {
1073
1268
  try {
1269
+ // pending.ts R11: the producer's changes landed by now.
1270
+ const returnedAt = Date.now();
1074
1271
  const { finalReturnText, childSessionID } = parseTaskResult(output);
1075
1272
  const producerTier =
1076
1273
  typeof input?.args?.subagent_type === "string"
@@ -1081,7 +1278,51 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1081
1278
  description: input?.args?.description,
1082
1279
  });
1083
1280
  const dispatchID = `task:${input.sessionID}:${input.callID}`;
1084
- const verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", input?.args?.cwd);
1281
+ const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
1282
+ const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
1283
+ const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
1284
+ // 2.4.2b: the mode the orchestrator chose at dispatch (never the subagent's text).
1285
+ const start = takeDispatch(dispatchID, dispatchDirectiveText(taskPrompt, taskDescription));
1286
+ const trivial = childSessionID
1287
+ ? sessionStore.isTrivial(childSessionID)
1288
+ : false;
1289
+ // QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
1290
+ // deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
1291
+ if (isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
1292
+ // Section 1.5-16: no gate, no test process; the result goes back now with the
1293
+ // footer, which is appended last and never says accepted or verified.
1294
+ const finish = await finishDeferred(changedFileStore, {
1295
+ dispatchID,
1296
+ orchestratorSessionID,
1297
+ producerSessionID: childSessionID ?? "",
1298
+ producerTier,
1299
+ description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
1300
+ cwd: typeof input?.args?.cwd === "string" ? input.args.cwd : undefined,
1301
+ dod,
1302
+ dispatchedAt: start.dispatchedAt,
1303
+ });
1304
+ if (finish.deferred) {
1305
+ output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
1306
+ // The dispatch record is cleared by finishDeferred once its capture settled.
1307
+ if (childSessionID) changedFileStore.clear(childSessionID);
1308
+ return;
1309
+ }
1310
+ // QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
1311
+ }
1312
+ // Same bound as the delegate gate: one deadline per invocation,
1313
+ // a withTimeout ceiling, and abort-on-reject so a hung check or
1314
+ // grader cannot hold the after-hook (and its process tree) open.
1315
+ // The deadline exists before prepareVerification (T2 P0,
1316
+ // QA-2.1-4), so preparation counts against gateBudgetMs.
1317
+ const { gateBudgetMs } = resolveVerifyBudget(cfg);
1318
+ const gateDeadline = createDeadline(gateBudgetMs);
1319
+ let verification;
1320
+ try {
1321
+ verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", input?.args?.cwd, gateDeadline);
1322
+ } catch (error) {
1323
+ gateDeadline.dispose();
1324
+ throw error;
1325
+ }
1085
1326
  const artefact = {
1086
1327
  changedFiles: verification.changedFiles,
1087
1328
  changeBaseline: verification.changeBaseline,
@@ -1090,9 +1331,6 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1090
1331
  producerSessionID: childSessionID ?? "",
1091
1332
  producerTier,
1092
1333
  };
1093
- const trivial = childSessionID
1094
- ? sessionStore.isTrivial(childSessionID)
1095
- : false;
1096
1334
 
1097
1335
  // Read-only / research delegation: an auto-inferred, criteria-only DoD on a
1098
1336
  // native Task() that changed no files is exploration, not implementation.
@@ -1106,28 +1344,74 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1106
1344
  dod.kind === "checker" &&
1107
1345
  artefact.changedFiles.length === 0
1108
1346
  ) {
1347
+ gateDeadline.dispose();
1109
1348
  if (childSessionID) changedFileStore.clear(childSessionID);
1110
1349
  changedFileStore.clear(dispatchID);
1111
1350
  return;
1112
1351
  }
1113
1352
 
1114
- const gateDeps = buildGateDeps();
1115
- gateDeps.deterministic.testBaseline = verification.testBaseline;
1116
- const res = await accept(
1117
- {
1118
- dod,
1119
- trivial,
1120
- mode: "modeA",
1121
- // The built-in task tool declares no cwd of its own, but if a
1122
- // caller supplies one it scopes verification the same way the
1123
- // delegate tool's does.
1124
- ...(typeof input?.args?.cwd === "string" && input.args.cwd
1125
- ? { cwd: input.args.cwd }
1126
- : {}),
1127
- },
1128
- artefact,
1129
- gateDeps,
1130
- );
1353
+ const gateGraderSessions = new Set<string>();
1354
+ const completedFailures: string[] = [];
1355
+ const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline);
1356
+ gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
1357
+ let res;
1358
+ try {
1359
+ res = await withTimeout(
1360
+ accept(
1361
+ {
1362
+ dod,
1363
+ trivial,
1364
+ mode: "modeA",
1365
+ // The built-in task tool declares no cwd of its own, but if a
1366
+ // caller supplies one it scopes verification the same way the
1367
+ // delegate tool's does.
1368
+ ...(typeof input?.args?.cwd === "string" && input.args.cwd
1369
+ ? { cwd: input.args.cwd }
1370
+ : {}),
1371
+ },
1372
+ artefact,
1373
+ gateDeps,
1374
+ ),
1375
+ // What preparation left of the gate budget (QA-2.1-4).
1376
+ gateDeadline.remaining(),
1377
+ "verification gate",
1378
+ );
1379
+ } catch (error) {
1380
+ gateDeadline.abort(
1381
+ error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
1382
+ );
1383
+ if (error instanceof RouterTimeoutError) {
1384
+ for (const gsid of gateGraderSessions) {
1385
+ try {
1386
+ await ctx.client.session.abort({ path: { id: gsid } });
1387
+ } catch {
1388
+ // best-effort: the gate result stands either way
1389
+ }
1390
+ }
1391
+ }
1392
+ res = unverifiableGateResult(
1393
+ error instanceof RouterTimeoutError
1394
+ ? `verification gate timed out after ${gateBudgetMs}ms`
1395
+ : `verification unavailable: ${scrubText(String(error))}`,
1396
+ dod.source,
1397
+ cfg.enforcement?.verify?.strictUnverifiable,
1398
+ completedFailures,
1399
+ );
1400
+ } finally {
1401
+ gateDeadline.dispose();
1402
+ }
1403
+ // pending.ts R11: a proven-introduced rejection is recorded for this session; a pass
1404
+ // on ids an earlier rejection introduced becomes unverifiable (never a new pass/fail).
1405
+ res = applyLineage(res, {
1406
+ orchestratorSessionID,
1407
+ root: verification.snapshot?.root,
1408
+ dispatchID,
1409
+ dispatchedAt: start.dispatchedAt,
1410
+ returnedAt,
1411
+ strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
1412
+ });
1413
+ // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
1414
+ res = applyDispatchCaveats(res, verification);
1131
1415
  if (!res.accepted && !res.verdict.skipped) {
1132
1416
  const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
1133
1417
  const li = ladder.indexOf(producerTier);
@@ -1138,8 +1422,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1138
1422
  ? output.output + "\n\n" + note
1139
1423
  : note;
1140
1424
  }
1141
- if (res.accepted && (res.verdict.caveats?.length || res.verdict.notes?.length)) {
1142
- output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.caveats, res.verdict.notes);
1425
+ // QA-3.1-18: a clean pass also gets a line (`[router ✓ verified: …]`); a skipped
1426
+ // check stays silent unless it carries caveats or notes.
1427
+ if (res.accepted && (!res.verdict.skipped || res.verdict.caveats?.length || res.verdict.notes?.length)) {
1428
+ output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.outcome, res.verdict.caveats, res.verdict.notes);
1143
1429
  }
1144
1430
  if (childSessionID) changedFileStore.clear(childSessionID);
1145
1431
  changedFileStore.clear(dispatchID);
@@ -1188,6 +1474,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1188
1474
  sessionRootMemo.delete(id);
1189
1475
  sessionLookupFailedAt.delete(id);
1190
1476
  sessionStore.unregister(id);
1477
+ // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
1478
+ // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
1479
+ background?.forgetSession(id);
1480
+ pending.forgetSession(id);
1191
1481
  }
1192
1482
  } catch {
1193
1483
  // best-effort: cleanup must never crash a real session
@@ -1385,7 +1675,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1385
1675
  "criteria: <plain-language success condition, when no deterministic check applies>",
1386
1676
  "deliverable: <path or short description>",
1387
1677
  "[/acceptance]",
1388
- "Prefer deterministic checks (testsPass/buildPasses/fileExists). Use a criteria line for design/explanatory tasks. Trivial read-only steps need no acceptance block.",
1678
+ "Prefer deterministic checks (testsPass/buildPasses/fileExists). testsPass means the tests affected by the producer's changes pass (the full suite is CI's job), so prefer it over a hand-written full-suite run command. Use a criteria line for design/explanatory tasks. Trivial read-only steps need no acceptance block.",
1389
1679
  ].join("\n"),
1390
1680
  description:
1391
1681
  "Annotate a plan with [tier:fast/medium/heavy] delegation tags",
@@ -1407,6 +1697,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1407
1697
  if (bypassed) return;
1408
1698
  try {
1409
1699
  cfg = loadConfig(); // Returns cache unless invalidated
1700
+ warnDeprecatedVerifyKeys(cfg, logger);
1410
1701
  } catch {
1411
1702
  // Use last known config if file read fails
1412
1703
  }
@@ -1463,6 +1754,30 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1463
1754
  let enfOn = false;
1464
1755
  try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
1465
1756
  output.system.push(assembleSystemPrompt(cfg, orchestratorModel, enfOn));
1757
+
1758
+ // 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
1759
+ // newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
1760
+ // does not grow for sessions that never defer. Orchestrator path only: every child returned
1761
+ // above. With background mode on, an entry the queue is verifying right now is still
1762
+ // unverified to the orchestrator, so it stays listed until its run settles.
1763
+ try {
1764
+ // QA-2.4-3: plus background verdicts that did not pass, until router_verify replays them.
1765
+ const open = pending.listPending(sessionID, { verifying: background !== undefined });
1766
+ const block = buildPendingListBlock(open);
1767
+ if (block !== undefined) output.system.push(block);
1768
+ } catch (error) {
1769
+ logger.warn("[verify] pending list not injected", { error: scrubText(String(error)) });
1770
+ }
1771
+ // 2.4.5, section 1.5-19 (`background: true` only): late notices of background runs that did
1772
+ // not pass, each delivered once (takeNotices marks them delivered).
1773
+ if (background !== undefined) {
1774
+ try {
1775
+ const late = buildLateNoticeBlock(background.takeNotices(sessionID));
1776
+ if (late !== undefined) output.system.push(late);
1777
+ } catch (error) {
1778
+ logger.warn("[verify] late notices not injected", { error: scrubText(String(error)) });
1779
+ }
1780
+ }
1466
1781
  },
1467
1782
 
1468
1783
  // -----------------------------------------------------------------------
@@ -1472,6 +1787,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1472
1787
  if (input.command === "tiers") {
1473
1788
  try {
1474
1789
  cfg = loadConfig();
1790
+ warnDeprecatedVerifyKeys(cfg, logger);
1475
1791
  } catch {}
1476
1792
  output.parts.push({
1477
1793
  type: "text" as const,
@@ -1482,6 +1798,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1482
1798
  if (input.command === "preset") {
1483
1799
  try {
1484
1800
  cfg = loadConfig();
1801
+ warnDeprecatedVerifyKeys(cfg, logger);
1485
1802
  } catch {}
1486
1803
  output.parts.push({
1487
1804
  type: "text" as const,
@@ -1507,6 +1824,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1507
1824
  if (input.command === "budget") {
1508
1825
  try {
1509
1826
  cfg = loadConfig();
1827
+ warnDeprecatedVerifyKeys(cfg, logger);
1510
1828
  } catch {}
1511
1829
  output.parts.push({
1512
1830
  type: "text" as const,
@@ -1517,6 +1835,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1517
1835
  if (input.command === "router") {
1518
1836
  try {
1519
1837
  cfg = loadConfig();
1838
+ warnDeprecatedVerifyKeys(cfg, logger);
1520
1839
  } catch {}
1521
1840
  const args = (input.arguments ?? "").trim();
1522
1841
  const parts = args.split(/\s+/).filter(Boolean);