opencode-model-router 1.14.0 → 2.0.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
@@ -1,4 +1,6 @@
1
- import type { Plugin, PluginInput } from "@opencode-ai/plugin";
1
+ import type { Plugin } from "@opencode-ai/plugin";
2
+ import type { RouterPluginInput } from "./compat/child-session";
3
+ import { TASK_VERIFICATION } from "./compat/child-session";
2
4
 
3
5
  // Imports for internal use within this module
4
6
  import {
@@ -9,6 +11,8 @@ import {
9
11
  overridePath,
10
12
  localOverridePath,
11
13
  findProjectOverride,
14
+ resolveVerifyBudget,
15
+ warnDeprecatedVerifyKeys,
12
16
  } from "./router/config";
13
17
  import type { RouterConfig, TierConfig, Preset, ModeConfig } from "./router/config";
14
18
  import { buildAgentOptions, warnAgentOptionsEffortOnce } from "./router/agent-options";
@@ -47,6 +51,7 @@ import {
47
51
  CLAUDE_ORCHESTRATOR_PREFIX,
48
52
  CLAUDE_ANTI_NARRATION,
49
53
  assembleSystemPrompt,
54
+ DELEGATE_TOOL_DESCRIPTION,
50
55
  } from "./router/protocol";
51
56
  import { resolveEnforcementMode } from "./router/enforcement";
52
57
  import { createPluginLogger } from "./router/logger";
@@ -71,15 +76,15 @@ import { guardBeforeCall, guardAfterCall, formatScorecard } from "./guard/enforc
71
76
  import { mkdirSync, writeFileSync, existsSync } from "node:fs";
72
77
  import { tmpdir } from "node:os";
73
78
  import { join, isAbsolute } from "node:path";
74
- import { exec as nodeExec } from "node:child_process";
75
79
  import { access, readFile as fsReadFile } from "node:fs/promises";
76
80
  import { tool } from "@opencode-ai/plugin";
77
81
  import { scrubText } from "./guard/scrub";
78
82
  import { accept, unverifiableGateResult } from "./verify/gate";
79
- import { createVerificationWiring, extractAssistantText } from "./verify/wiring";
83
+ import { applyDispatchCaveats, createVerificationWiring, dispatchDirectiveText, extractAssistantText, parseRouterVerifyArgs, type DispatchStart } from "./verify/wiring";
84
+ import { appendRouterFooter, buildLateNoticeBlock, buildPendingListBlock } from "./verify/pending";
85
+ import { createDeadline } from "./verify/deterministic";
80
86
  import {
81
87
  DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS,
82
- DEFAULT_GATE_BUDGET_MS,
83
88
  RouterTimeoutError,
84
89
  timeoutMs,
85
90
  withTimeout,
@@ -235,7 +240,7 @@ function warnSessionLookupFailedOnce(): void {
235
240
  const SESSION_ROOT_MEMO_MAX = 500;
236
241
  const SESSION_LOOKUP_RETRY_MS = 30_000;
237
242
 
238
- const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
243
+ const ModelRouterPlugin: Plugin = async (ctx: RouterPluginInput) => {
239
244
  let cfg = loadConfig();
240
245
  const activeTiers = getActiveTiers(cfg);
241
246
 
@@ -273,7 +278,15 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
273
278
  * still cover the common cases, so the exposure is a rare, transient re-run of
274
279
  * the old behaviour rather than a permanent loss of function.
275
280
  */
276
- const resolveIsRootSession = async (sessionID: string): Promise<boolean> => {
281
+ const resolveIsRootSession = async (sessionID: string): Promise<boolean> =>
282
+ (await lookupRootSession(sessionID)) ?? true;
283
+
284
+ /**
285
+ * The lookup behind resolveIsRootSession: true (no parentID), false (a parentID), or undefined
286
+ * when it is not known (the lookup failed, or failed recently and is throttled). QA-2.4-2 treats
287
+ * undefined as NOT root (isProvenRootCaller), where the protocol injection treats it as root.
288
+ */
289
+ const lookupRootSession = async (sessionID: string): Promise<boolean | undefined> => {
277
290
  const memo = sessionRootMemo.get(sessionID);
278
291
  if (memo !== undefined) {
279
292
  if (!memo) sessionStore.markChildSession(sessionID);
@@ -281,7 +294,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
281
294
  }
282
295
  const failedAt = sessionLookupFailedAt.get(sessionID);
283
296
  if (failedAt !== undefined && Date.now() - failedAt < SESSION_LOOKUP_RETRY_MS) {
284
- return true;
297
+ return undefined;
285
298
  }
286
299
  try {
287
300
  const res = await ctx.client.session.get({ path: { id: sessionID } });
@@ -307,7 +320,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
307
320
  sessionLookupFailedAt.delete(oldest);
308
321
  }
309
322
  warnSessionLookupFailedOnce();
310
- return true;
323
+ return undefined;
311
324
  }
312
325
  };
313
326
 
@@ -333,17 +346,40 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
333
346
  () => guardStore.sweep(),
334
347
  () => trajectoryStore.sweep(),
335
348
  () => changedFileStore.sweep(),
349
+ // 2.2.3: the S5 batch coordinator's defensive eviction (batch.ts B11). Declared below; the
350
+ // sweeper only runs from chat.message, long after this factory has returned.
351
+ () => { sweepVerification(); },
352
+ // 2.4.2b: TTL eviction and reaping of the pending registry (pending.ts R7; no timer of its own).
353
+ () => { pending.sweep(); },
336
354
  ]);
337
355
 
338
356
  // Layer-2's impure corner: exec, fs, and the opencode client, built once and
339
357
  // read back through getConfig so a reloaded cfg (from /preset, /budget or
340
358
  // /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
- });
359
+ // Passive warnings go to opencode's log rather than stderr: console output
360
+ // from a plugin paints over the TUI. Falls back to console when the server
361
+ // has no /log endpoint. See src/router/logger.ts.
362
+ const logger = createPluginLogger(ctx.client);
363
+
364
+ const {
365
+ graderSessions, dispatchGrader, buildGateDeps, disposeChildSession,
366
+ prepareVerification, startReferenceGc,
367
+ sweepVerification, disposeVerification,
368
+ startDispatch, takeDispatch, isDeferred: wiringIsDeferred, finishDeferred, applyLineage, pending,
369
+ verifyHandles,
370
+ // 2.4.5: undefined unless `background: true` at plugin start (pending.ts R14).
371
+ background,
372
+ } = createVerificationWiring({
373
+ client: ctx.client,
374
+ childRunner: ctx.routerChildRunner,
375
+ directory: ctx.directory,
376
+ getConfig: () => cfg,
377
+ logger,
378
+ });
379
+ // 2.1.5b: sweep reference dirs a crashed instance left behind. Fire-and-forget; never throws.
380
+ // QA-2.1-11: deferred (unref'd timer), so plugin start never holds the project directory with a
381
+ // git child; dispose cancels it.
382
+ const stopReferenceGc = startReferenceGc();
347
383
 
348
384
  // Best-effort, secret-free delegate scorecard dump (counts only).
349
385
  const dumpDelegateScorecard = (
@@ -367,10 +403,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
367
403
  // current plugin lifetime (i.e., until OpenCode is restarted).
368
404
  let bypassed = false;
369
405
 
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);
406
+ warnDeprecatedVerifyKeys(cfg, logger);
374
407
 
375
408
  // Fetch and normalize opencode's live provider/model catalog. Best-effort:
376
409
  // returns null when the client call fails, e.g. the server is not ready yet.
@@ -421,18 +454,55 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
421
454
  cfg.experimental?.verifiedDelegateTool === true ||
422
455
  process.env.MODEL_ROUTER_VERIFIED_DELEGATE === "1";
423
456
 
457
+ // 2.4.3b (plan 2.4.3 "Registration"): `router_verify` is registered whenever verification is
458
+ // enabled at plugin start, independent of enableDelegateTool: verify.require is not "never" and
459
+ // a verifying path exists (the native `task` path needs an enforcement mode other than "off";
460
+ // the delegate tool verifies in every mode). The tool map is fixed at start.
461
+ let routerVerifyEnabled = false;
462
+ try {
463
+ const startMode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
464
+ routerVerifyEnabled = cfg.enforcement?.verify?.require !== "never" && (startMode !== "off" || enableDelegateTool);
465
+ } catch (error) {
466
+ logger.warn("[verify] router_verify not registered: the enforcement mode could not be resolved", { error: scrubText(String(error)) });
467
+ }
468
+ /**
469
+ * 2.4.2 + 2.4.3b: a delegation defers only when `router_verify` exists to verify it later. A
470
+ * footer never names a tool this instance did not register; without it the delegation keeps the
471
+ * synchronous gate (never weaker).
472
+ */
473
+ const isDeferred: typeof wiringIsDeferred = (dod, directives, trivial) => routerVerifyEnabled && wiringIsDeferred(dod, directives, trivial);
474
+ /**
475
+ * QA-2.4-2: a deferred entry is keyed to the dispatching session (pending.ts R6), and only a root
476
+ * orchestrator ever sees a pending list (the system transform returns early for every child). So
477
+ * only a PROVEN root orchestrator session may defer. A subagent dispatching `task` or `delegate`
478
+ * (a grader, a tracked subagent, a session with a parentID) gets today's synchronous gate and
479
+ * registers nothing, whatever its directives say; so does an unknown session (no id, or a failed
480
+ * lookup: fail safe).
481
+ */
482
+ const isProvenRootCaller = async (sessionID: unknown): Promise<boolean> => {
483
+ if (typeof sessionID !== "string" || sessionID === "") return false;
484
+ if (graderSessions.has(sessionID) || sessionStore.isSubagent(sessionID)) return false;
485
+ return (await lookupRootSession(sessionID)) === true;
486
+ };
487
+
424
488
  return {
425
489
  // Warnings post to /log fire-and-forget, which loses the message when the
426
490
  // process is about to exit — `opencode run` and `opencode debug` are short
427
491
  // enough for that to be the normal case. Verified against opencode 1.18.16
428
492
  // that dispose is both called and awaited, so flushing here is enough.
429
493
  dispose: async () => {
494
+ stopReferenceGc();
495
+ // 2.4.5: abort a background run and drop its queue and notices before the registry goes.
496
+ background?.dispose();
497
+ // 2.4.2b: evict every pending delegation; in-flight router_verify runs resolve (pending.ts R5).
498
+ pending.dispose();
499
+ // 2.2.3: settle batched testsPass requests and kill running batches (never rejects).
500
+ await disposeVerification();
430
501
  await logger.flush();
431
502
  },
432
503
  tool: {
433
504
  ...(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.",
505
+ description: DELEGATE_TOOL_DESCRIPTION,
436
506
  args: {
437
507
  task: tool.schema
438
508
  .string()
@@ -468,10 +538,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
468
538
  // early return or a throw skipped — otherwise each retry leaks another.
469
539
  const producerSessions: string[] = [];
470
540
  let baselineID: string | undefined;
541
+ /** 2.4.2c: the directives and start time of this delegation, from its first attempt. */
542
+ let dispatchStart: DispatchStart | undefined;
543
+ /**
544
+ * 2.4.2c: finishDeferred clears the dispatch record (baselineID) once its reference
545
+ * settled; clearing it in the finally below would abort a capture still in flight.
546
+ */
547
+ let deferredOwnsBaseline = false;
471
548
  try {
472
549
  let activeCfg = cfg;
473
550
  try {
474
551
  activeCfg = loadConfig();
552
+ warnDeprecatedVerifyKeys(activeCfg, logger);
475
553
  } catch {
476
554
  activeCfg = cfg;
477
555
  }
@@ -483,6 +561,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
483
561
  prompt: args.task,
484
562
  acceptance: args.acceptance,
485
563
  });
564
+ const effectiveCwd = typeof args.cwd === "string" && args.cwd.trim() ? args.cwd : dod.cwd;
486
565
 
487
566
  const policy = buildEscalatePolicy(activeCfg);
488
567
  let state = newLadderState(initialTier, policy);
@@ -516,30 +595,43 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
516
595
  sessionID: string;
517
596
  text: string;
518
597
  gateRes: Awaited<ReturnType<typeof accept>>;
598
+ } | {
599
+ sessionID: string;
600
+ text: string;
601
+ /** 2.4.2c: deferred; the section 1.5-16 footer to append to the result. */
602
+ deferredFooter: string;
519
603
  } | null> => {
520
604
  const taskText = forcingNote
521
605
  ? `${scrubText(forcingNote)}\n\n${args.task}`
522
606
  : args.task;
523
607
 
524
- const created: any = await ctx.client.session.create({
525
- body: {
526
- ...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
527
- },
528
- });
529
- const producerSid: string | undefined = created?.data?.id;
530
- if (!producerSid) return null;
531
- producerSessions.push(producerSid);
532
- // Keep the ORIGINAL dispatch reference across retries/escalations:
533
- // recapturing after a failed attempt would excuse its regression.
534
- if (!baselineID) {
535
- baselineID = producerSid;
536
- beginVerification(changedFileStore, baselineID, args.cwd, dod);
537
- }
538
- // Compose with Layer 1: guard the plugin-created producer session.
539
- try {
540
- sessionStore.registerProducerSession(producerSid, tier, activeCfg);
541
- } catch {
542
- // non-fatal
608
+ let producerSid: string | undefined;
609
+ const registerProducer = async (sid: string) => {
610
+ producerSid = sid;
611
+ producerSessions.push(sid);
612
+ // Keep the ORIGINAL dispatch reference across retries/escalations:
613
+ // recapturing after a failed attempt would excuse its regression.
614
+ if (!baselineID) {
615
+ baselineID = sid;
616
+ // Capture before the child gets its first prompt, on either API.
617
+ dispatchStart = await startDispatch(changedFileStore, baselineID, effectiveCwd, dod, args.task, false);
618
+ }
619
+ // Compose with Layer 1: guard the plugin-created producer session.
620
+ try {
621
+ sessionStore.registerProducerSession(sid, tier, activeCfg);
622
+ } catch {
623
+ // non-fatal
624
+ }
625
+ };
626
+ if (!ctx.routerChildRunner) {
627
+ const created: any = await ctx.client.session.create({
628
+ body: {
629
+ ...(toolCtx?.sessionID ? { parentID: toolCtx.sessionID } : {}),
630
+ },
631
+ });
632
+ const sid: string | undefined = created?.data?.id;
633
+ if (!sid) return null;
634
+ await registerProducer(sid);
543
635
  }
544
636
 
545
637
  const model = tierModel(activeCfg, tier) ?? undefined;
@@ -557,10 +649,18 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
557
649
  // the same failed-attempt path as any other producer error — it
558
650
  // is never an empty artefact that a lenient DoD could pass.
559
651
  let producerError: string | null = null;
652
+ const childAbort = ctx.routerChildRunner ? new AbortController() : undefined;
560
653
  try {
561
- const res: any = await withTimeout(
562
- ctx.client.session.prompt({
563
- path: { id: producerSid },
654
+ const res: any = await withTimeout<unknown>(
655
+ ctx.routerChildRunner ? ctx.routerChildRunner.run({
656
+ parentSessionID: toolCtx?.sessionID,
657
+ agent: tier,
658
+ model: model ? { ...model, variant: getActiveTiers(activeCfg)[tier]?.variant } : undefined,
659
+ prompt: taskText,
660
+ signal: childAbort!.signal,
661
+ onCreated: registerProducer,
662
+ }) : ctx.client.session.prompt({
663
+ path: { id: producerSid! },
564
664
  body: {
565
665
  ...(model ? { model } : {}),
566
666
  ...(tier ? { agent: tier } : {}),
@@ -573,14 +673,73 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
573
673
  ),
574
674
  "delegate producer prompt",
575
675
  );
576
- producerText = extractAssistantText(res);
676
+ producerText = ctx.routerChildRunner ? res.text : extractAssistantText(res);
577
677
  } catch (error) {
578
678
  producerError =
579
679
  error instanceof Error ? error.message : String(error);
580
680
  producerText = "";
681
+ } finally {
682
+ childAbort?.abort();
683
+ }
684
+ if (!producerSid || !baselineID) return null;
685
+ // pending.ts R11: the producer's changes landed by now.
686
+ const returnedAt = Date.now();
687
+
688
+ // 2.4.2c, section 1.5-16: a deferred delegation runs no gate and no ladder. A producer
689
+ // that failed outright produced nothing to verify later; it keeps today's
690
+ // failed-attempt path, which runs no verification process either.
691
+ const finish = dispatchStart !== undefined && producerError === null && isDeferred(dod, dispatchStart.directives) &&
692
+ await isProvenRootCaller(toolCtx?.sessionID)
693
+ ? await finishDeferred(changedFileStore, {
694
+ dispatchID: baselineID,
695
+ orchestratorSessionID: toolCtx?.sessionID ?? "",
696
+ producerSessionID: producerSid,
697
+ producerTier: tier,
698
+ description: args.task,
699
+ cwd: effectiveCwd,
700
+ dod,
701
+ dispatchedAt: dispatchStart.dispatchedAt,
702
+ })
703
+ : undefined;
704
+ // QA-2.4-4 / QA-2.4-10: a finish that did not defer falls through to the required gate
705
+ // (and its ladder) below, with the dispatch record still in the store.
706
+ if (finish?.deferred === true) {
707
+ deferredOwnsBaseline = true;
708
+ if (producerSid !== baselineID) changedFileStore.clear(producerSid);
709
+ try {
710
+ sessionStore.unregister(producerSid);
711
+ sessionRootMemo.delete(producerSid);
712
+ } catch {
713
+ // non-fatal
714
+ }
715
+ try {
716
+ guardStore.clear(producerSid);
717
+ } catch {
718
+ // non-fatal
719
+ }
720
+ await disposeChildSession(producerSid);
721
+ return { sessionID: producerSid, text: producerText, deferredFooter: finish.footer };
722
+ }
723
+ // Once a delegation is gated, every later attempt of its ladder is gated too.
724
+ if (finish !== undefined && dispatchStart !== undefined) {
725
+ dispatchStart = { ...dispatchStart, directives: { ...dispatchStart.directives, mode: "required" } };
581
726
  }
582
727
 
583
- const verification = await prepareVerification(changedFileStore, baselineID, producerSid, args.cwd);
728
+ const { gateBudgetMs } = resolveVerifyBudget(activeCfg);
729
+ // One deadline per gate invocation: every step inside the gate
730
+ // is bounded by it, and it is aborted (killing any spawned
731
+ // tree) when the gate's own withTimeout rejects. It exists
732
+ // before prepareVerification (T2 P0, QA-2.1-4), so the grade
733
+ // snapshot and the wait for a pending reference count against
734
+ // gateBudgetMs too.
735
+ const gateDeadline = createDeadline(gateBudgetMs);
736
+ let verification;
737
+ try {
738
+ verification = await prepareVerification(changedFileStore, baselineID, producerSid, effectiveCwd, gateDeadline);
739
+ } catch (error) {
740
+ gateDeadline.dispose();
741
+ throw error;
742
+ }
584
743
  const artefact = {
585
744
  changedFiles: verification.changedFiles,
586
745
  changeBaseline: verification.changeBaseline,
@@ -590,15 +749,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
590
749
  producerTier: tier,
591
750
  };
592
751
 
593
- const gateBudgetMs = timeoutMs(
594
- activeCfg.enforcement?.verify?.gateBudgetMs,
595
- DEFAULT_GATE_BUDGET_MS,
596
- );
597
752
  // Grader sessions opened by THIS accept() call, and only those.
598
753
  const gateGraderSessions = new Set<string>();
599
754
  const completedFailures: string[] = [];
600
- const gateDeps = buildGateDeps(toolCtx?.sessionID, gateGraderSessions);
601
- gateDeps.deterministic.testBaseline = verification.testBaseline;
755
+ const gateDeps = buildGateDeps(toolCtx?.sessionID, gateGraderSessions, verification, gateDeadline);
602
756
  gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
603
757
  let gateRes;
604
758
  try {
@@ -618,12 +772,13 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
618
772
  dod,
619
773
  trivial: false,
620
774
  mode: "modeA",
621
- ...(args.cwd ? { cwd: args.cwd } : {}),
775
+ ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
622
776
  },
623
777
  artefact,
624
778
  gateDeps,
625
779
  ),
626
- gateBudgetMs,
780
+ // What preparation left of the gate budget (QA-2.1-4).
781
+ gateDeadline.remaining(),
627
782
  "verification gate",
628
783
  );
629
784
  } catch (error) {
@@ -637,6 +792,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
637
792
  // someone else's delegation — reachable with the shipped
638
793
  // config, where a deterministic check may run a command for up
639
794
  // to 120s against a 90s gate budget.
795
+ gateDeadline.abort(
796
+ error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
797
+ );
640
798
  if (error instanceof RouterTimeoutError) {
641
799
  for (const gsid of gateGraderSessions) {
642
800
  try {
@@ -654,7 +812,23 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
654
812
  activeCfg.enforcement?.verify?.strictUnverifiable,
655
813
  completedFailures,
656
814
  );
815
+ } finally {
816
+ gateDeadline.dispose();
657
817
  }
818
+ // pending.ts R11, as on the native path. Within this ladder every attempt is judged
819
+ // against the first attempt's reference and dispatchedAt precedes every landedAt, so
820
+ // it only affects later delegations of the same session (a native re-dispatch of
821
+ // rejected delegate work is the T11 case too).
822
+ gateRes = applyLineage(gateRes, {
823
+ orchestratorSessionID: toolCtx?.sessionID ?? "",
824
+ root: verification.snapshot?.root,
825
+ dispatchID: baselineID,
826
+ dispatchedAt: dispatchStart?.dispatchedAt ?? returnedAt,
827
+ returnedAt,
828
+ strictUnverifiable: activeCfg.enforcement?.verify?.strictUnverifiable,
829
+ });
830
+ // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
831
+ gateRes = applyDispatchCaveats(gateRes, verification);
658
832
 
659
833
  // Per-attempt cleanup (drop producer session tracking + state).
660
834
  if (producerSid !== baselineID) changedFileStore.clear(producerSid);
@@ -689,6 +863,11 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
689
863
  return "[router] delegate failed: could not create a producer session.";
690
864
  }
691
865
  producerText = attempt.text;
866
+ if ("deferredFooter" in attempt) {
867
+ // Section 1.5-16: the result unchanged plus the footer, appended last. Never
868
+ // labelled accepted or verified, and never retried or escalated.
869
+ return appendRouterFooter(producerText, attempt.deferredFooter);
870
+ }
692
871
  const producerSid = attempt.sessionID;
693
872
  const gateRes = attempt.gateRes;
694
873
 
@@ -711,7 +890,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
711
890
  true,
712
891
  gateRes.verdict.method,
713
892
  );
714
- return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.caveats, gateRes.verdict.notes);
893
+ return producerText + buildAcceptedSuffix(gateRes.verdict.method, gateRes.verdict.outcome, gateRes.verdict.caveats, gateRes.verdict.notes);
715
894
  }
716
895
  if (action.action === "give_up") {
717
896
  dumpDelegateScorecard(
@@ -740,12 +919,44 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
740
919
  // disposeChildSession is fail-soft, so re-disposing an already
741
920
  // disposed session is harmless.
742
921
  for (const sid of producerSessions) {
743
- changedFileStore.clear(sid);
922
+ if (!(deferredOwnsBaseline && sid === baselineID)) changedFileStore.clear(sid);
744
923
  await disposeChildSession(sid);
745
924
  }
746
925
  }
747
926
  },
748
927
  }) } : {}),
928
+ // 2.4.3b, section 1.5-18: verify deferred delegations on the orchestrator's terms.
929
+ ...(routerVerifyEnabled ? { router_verify: tool({
930
+ description:
931
+ "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).",
932
+ args: {
933
+ handles: tool.schema
934
+ .array(tool.schema.string())
935
+ .optional()
936
+ .describe("The vrf_ handles from the delegations' [router] footers."),
937
+ pending: tool.schema
938
+ .boolean()
939
+ .optional()
940
+ .describe("true: verify every still-unverified delegation of this session."),
941
+ },
942
+ async execute(
943
+ args: { handles?: string[]; pending?: boolean },
944
+ toolCtx?: { sessionID?: string; abort?: AbortSignal },
945
+ ): Promise<string> {
946
+ // Never throws: every failure is a text answer (the tool result reaches the orchestrator).
947
+ try {
948
+ const target = parseRouterVerifyArgs(args);
949
+ if ("error" in target) return target.error;
950
+ // R6: handles are scoped by the calling session; without one, every handle is unknown.
951
+ const sessionID = typeof toolCtx?.sessionID === "string" ? toolCtx.sessionID : "";
952
+ const report = await verifyHandles(sessionID, target, toolCtx?.abort !== undefined ? { signal: toolCtx.abort } : {});
953
+ return report.text;
954
+ } catch (error) {
955
+ logger.warn("[verify] router_verify failed", { error: scrubText(String(error)) });
956
+ return `[router] router_verify failed; nothing was verified: ${scrubText(String(error))}`;
957
+ }
958
+ },
959
+ }) } : {}),
749
960
  },
750
961
 
751
962
  // -----------------------------------------------------------------------
@@ -770,7 +981,9 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
770
981
  try {
771
982
  if (input?.sessionID && graderSessions.has(input.sessionID)) {
772
983
  const graderTemperature = cfg.enforcement?.verify?.graderTemperature;
773
- if (graderTemperature !== undefined) {
984
+ if (graderTemperature === null) {
985
+ delete output.temperature;
986
+ } else if (graderTemperature !== undefined && input?.model?.capabilities?.temperature !== false) {
774
987
  output.temperature = graderTemperature;
775
988
  }
776
989
  }
@@ -784,6 +997,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
784
997
  // Re-read cfg so /preset switches take effect without restart
785
998
  try {
786
999
  cfg = loadConfig();
1000
+ warnDeprecatedVerifyKeys(cfg, logger);
787
1001
  } catch {}
788
1002
  try {
789
1003
  sweepIdleStores();
@@ -891,12 +1105,19 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
891
1105
  if (input?.tool === "task" && typeof input.callID === "string" && typeof input.sessionID === "string") {
892
1106
  const mode = resolveEnforcementMode({ config: cfg, env: process.env }).mode;
893
1107
  if (shouldVerifyTask("task", mode, cfg.enforcement?.verify?.require)) {
894
- beginVerification(changedFileStore, `task:${input.sessionID}:${input.callID}`,
895
- 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
- }));
1108
+ if (output && typeof output === "object") output[TASK_VERIFICATION] = true;
1109
+ const prompt = typeof output?.args?.prompt === "string" ? output.args.prompt : undefined;
1110
+ const description = typeof output?.args?.description === "string" ? output.args.description : undefined;
1111
+ const dod = buildDelegationDoD({ prompt, description });
1112
+ const effectiveCwd = typeof output?.args?.cwd === "string" && output.args.cwd.trim() ? output.args.cwd : dod.cwd;
1113
+ // 2.4.2b: the directives come from the orchestrator's own prompt, read here before the
1114
+ // dispatch header or any repair touches it, and are kept for the after hook. The capture
1115
+ // is awaited for at most VERIFY_WAIT (section 1.5-14) and continues in the background.
1116
+ await startDispatch(changedFileStore, `task:${input.sessionID}:${input.callID}`,
1117
+ effectiveCwd,
1118
+ dod,
1119
+ dispatchDirectiveText(prompt, description),
1120
+ true);
900
1121
  }
901
1122
  }
902
1123
  // A task call with no prompt (typically a forced delegation of a bare
@@ -1071,6 +1292,8 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1071
1292
  const requireMode = cfg.enforcement?.verify?.require;
1072
1293
  if (shouldVerifyTask(input.tool, mode, requireMode)) {
1073
1294
  try {
1295
+ // pending.ts R11: the producer's changes landed by now.
1296
+ const returnedAt = Date.now();
1074
1297
  const { finalReturnText, childSessionID } = parseTaskResult(output);
1075
1298
  const producerTier =
1076
1299
  typeof input?.args?.subagent_type === "string"
@@ -1080,8 +1303,53 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1080
1303
  prompt: input?.args?.prompt,
1081
1304
  description: input?.args?.description,
1082
1305
  });
1306
+ const effectiveCwd = typeof input?.args?.cwd === "string" && input.args.cwd.trim() ? input.args.cwd : dod.cwd;
1083
1307
  const dispatchID = `task:${input.sessionID}:${input.callID}`;
1084
- const verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", input?.args?.cwd);
1308
+ const orchestratorSessionID = typeof input.sessionID === "string" ? input.sessionID : "";
1309
+ const taskPrompt = typeof input?.args?.prompt === "string" ? input.args.prompt : undefined;
1310
+ const taskDescription = typeof input?.args?.description === "string" ? input.args.description : undefined;
1311
+ // 2.4.2b: the mode the orchestrator chose at dispatch (never the subagent's text).
1312
+ const start = takeDispatch(dispatchID, dispatchDirectiveText(taskPrompt, taskDescription));
1313
+ const trivial = childSessionID
1314
+ ? sessionStore.isTrivial(childSessionID)
1315
+ : false;
1316
+ // QA-2.4-10: `trivial` as the gate sees it below; a dispatch the gate would skip is not
1317
+ // deferred (isDeferred). QA-2.4-2: only a proven root orchestrator defers.
1318
+ if (isDeferred(dod, start.directives, trivial) && await isProvenRootCaller(orchestratorSessionID)) {
1319
+ // Section 1.5-16: no gate, no test process; the result goes back now with the
1320
+ // footer, which is appended last and never says accepted or verified.
1321
+ const finish = await finishDeferred(changedFileStore, {
1322
+ dispatchID,
1323
+ orchestratorSessionID,
1324
+ producerSessionID: childSessionID ?? "",
1325
+ producerTier,
1326
+ description: taskDescription?.trim() ? taskDescription : (taskPrompt ?? ""),
1327
+ cwd: effectiveCwd,
1328
+ dod,
1329
+ dispatchedAt: start.dispatchedAt,
1330
+ });
1331
+ if (finish.deferred) {
1332
+ output.output = appendRouterFooter(typeof output.output === "string" ? output.output : "", finish.footer);
1333
+ // The dispatch record is cleared by finishDeferred once its capture settled.
1334
+ if (childSessionID) changedFileStore.clear(childSessionID);
1335
+ return;
1336
+ }
1337
+ // QA-2.4-4 / QA-2.4-10: not deferred after all; today's required gate runs below.
1338
+ }
1339
+ // Same bound as the delegate gate: one deadline per invocation,
1340
+ // a withTimeout ceiling, and abort-on-reject so a hung check or
1341
+ // grader cannot hold the after-hook (and its process tree) open.
1342
+ // The deadline exists before prepareVerification (T2 P0,
1343
+ // QA-2.1-4), so preparation counts against gateBudgetMs.
1344
+ const { gateBudgetMs } = resolveVerifyBudget(cfg);
1345
+ const gateDeadline = createDeadline(gateBudgetMs);
1346
+ let verification;
1347
+ try {
1348
+ verification = await prepareVerification(changedFileStore, dispatchID, childSessionID ?? "", effectiveCwd, gateDeadline);
1349
+ } catch (error) {
1350
+ gateDeadline.dispose();
1351
+ throw error;
1352
+ }
1085
1353
  const artefact = {
1086
1354
  changedFiles: verification.changedFiles,
1087
1355
  changeBaseline: verification.changeBaseline,
@@ -1090,9 +1358,6 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1090
1358
  producerSessionID: childSessionID ?? "",
1091
1359
  producerTier,
1092
1360
  };
1093
- const trivial = childSessionID
1094
- ? sessionStore.isTrivial(childSessionID)
1095
- : false;
1096
1361
 
1097
1362
  // Read-only / research delegation: an auto-inferred, criteria-only DoD on a
1098
1363
  // native Task() that changed no files is exploration, not implementation.
@@ -1106,28 +1371,70 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1106
1371
  dod.kind === "checker" &&
1107
1372
  artefact.changedFiles.length === 0
1108
1373
  ) {
1374
+ gateDeadline.dispose();
1109
1375
  if (childSessionID) changedFileStore.clear(childSessionID);
1110
1376
  changedFileStore.clear(dispatchID);
1111
1377
  return;
1112
1378
  }
1113
1379
 
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
- );
1380
+ const gateGraderSessions = new Set<string>();
1381
+ const completedFailures: string[] = [];
1382
+ const gateDeps = buildGateDeps(undefined, gateGraderSessions, verification, gateDeadline);
1383
+ gateDeps.deterministic.onFailure = reason => completedFailures.push(reason);
1384
+ let res;
1385
+ try {
1386
+ res = await withTimeout(
1387
+ accept(
1388
+ {
1389
+ dod,
1390
+ trivial,
1391
+ mode: "modeA",
1392
+ // Native task has no cwd argument; the acceptance block can supply it.
1393
+ ...(effectiveCwd ? { cwd: effectiveCwd } : {}),
1394
+ },
1395
+ artefact,
1396
+ gateDeps,
1397
+ ),
1398
+ // What preparation left of the gate budget (QA-2.1-4).
1399
+ gateDeadline.remaining(),
1400
+ "verification gate",
1401
+ );
1402
+ } catch (error) {
1403
+ gateDeadline.abort(
1404
+ error instanceof RouterTimeoutError ? "verification gate timed out" : "verification gate failed",
1405
+ );
1406
+ if (error instanceof RouterTimeoutError) {
1407
+ for (const gsid of gateGraderSessions) {
1408
+ try {
1409
+ await ctx.client.session.abort({ path: { id: gsid } });
1410
+ } catch {
1411
+ // best-effort: the gate result stands either way
1412
+ }
1413
+ }
1414
+ }
1415
+ res = unverifiableGateResult(
1416
+ error instanceof RouterTimeoutError
1417
+ ? `verification gate timed out after ${gateBudgetMs}ms`
1418
+ : `verification unavailable: ${scrubText(String(error))}`,
1419
+ dod.source,
1420
+ cfg.enforcement?.verify?.strictUnverifiable,
1421
+ completedFailures,
1422
+ );
1423
+ } finally {
1424
+ gateDeadline.dispose();
1425
+ }
1426
+ // pending.ts R11: a proven-introduced rejection is recorded for this session; a pass
1427
+ // on ids an earlier rejection introduced becomes unverifiable (never a new pass/fail).
1428
+ res = applyLineage(res, {
1429
+ orchestratorSessionID,
1430
+ root: verification.snapshot?.root,
1431
+ dispatchID,
1432
+ dispatchedAt: start.dispatchedAt,
1433
+ returnedAt,
1434
+ strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
1435
+ });
1436
+ // QA-3.1-2 / QA-3.1-3: concurrent delegations in this tree; a tool that discarded the baseline.
1437
+ res = applyDispatchCaveats(res, verification);
1131
1438
  if (!res.accepted && !res.verdict.skipped) {
1132
1439
  const ladder = cfg.enforcement?.escalate?.ladder ?? ["fast", "medium", "heavy"];
1133
1440
  const li = ladder.indexOf(producerTier);
@@ -1138,8 +1445,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1138
1445
  ? output.output + "\n\n" + note
1139
1446
  : note;
1140
1447
  }
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);
1448
+ // QA-3.1-18: a clean pass also gets a line (`[router ✓ verified: …]`); a skipped
1449
+ // check stays silent unless it carries caveats or notes.
1450
+ if (res.accepted && (!res.verdict.skipped || res.verdict.caveats?.length || res.verdict.notes?.length)) {
1451
+ output.output += buildAcceptedSuffix(res.verdict.method, res.verdict.outcome, res.verdict.caveats, res.verdict.notes);
1143
1452
  }
1144
1453
  if (childSessionID) changedFileStore.clear(childSessionID);
1145
1454
  changedFileStore.clear(dispatchID);
@@ -1188,6 +1497,10 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1188
1497
  sessionRootMemo.delete(id);
1189
1498
  sessionLookupFailedAt.delete(id);
1190
1499
  sessionStore.unregister(id);
1500
+ // 2.4.2b: a deleted orchestrator's handles, tombstones and lineage records go with it.
1501
+ // 2.4.5: so do its background requests and late notices; its run in flight is aborted.
1502
+ background?.forgetSession(id);
1503
+ pending.forgetSession(id);
1191
1504
  }
1192
1505
  } catch {
1193
1506
  // best-effort: cleanup must never crash a real session
@@ -1385,7 +1698,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1385
1698
  "criteria: <plain-language success condition, when no deterministic check applies>",
1386
1699
  "deliverable: <path or short description>",
1387
1700
  "[/acceptance]",
1388
- "Prefer deterministic checks (testsPass/buildPasses/fileExists). Use a criteria line for design/explanatory tasks. Trivial read-only steps need no acceptance block.",
1701
+ "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
1702
  ].join("\n"),
1390
1703
  description:
1391
1704
  "Annotate a plan with [tier:fast/medium/heavy] delegation tags",
@@ -1407,6 +1720,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1407
1720
  if (bypassed) return;
1408
1721
  try {
1409
1722
  cfg = loadConfig(); // Returns cache unless invalidated
1723
+ warnDeprecatedVerifyKeys(cfg, logger);
1410
1724
  } catch {
1411
1725
  // Use last known config if file read fails
1412
1726
  }
@@ -1463,6 +1777,30 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1463
1777
  let enfOn = false;
1464
1778
  try { enfOn = resolveEnforcementMode({ config: cfg, env: process.env }).mode !== "off"; } catch {}
1465
1779
  output.system.push(assembleSystemPrompt(cfg, orchestratorModel, enfOn));
1780
+
1781
+ // 2.4.4, section 1.5-20: this orchestrator's still-unverified delegations (at most 5 shown,
1782
+ // newest first), as one short block. Nothing is pushed when the list is empty, so the prompt
1783
+ // does not grow for sessions that never defer. Orchestrator path only: every child returned
1784
+ // above. With background mode on, an entry the queue is verifying right now is still
1785
+ // unverified to the orchestrator, so it stays listed until its run settles.
1786
+ try {
1787
+ // QA-2.4-3: plus background verdicts that did not pass, until router_verify replays them.
1788
+ const open = pending.listPending(sessionID, { verifying: background !== undefined });
1789
+ const block = buildPendingListBlock(open);
1790
+ if (block !== undefined) output.system.push(block);
1791
+ } catch (error) {
1792
+ logger.warn("[verify] pending list not injected", { error: scrubText(String(error)) });
1793
+ }
1794
+ // 2.4.5, section 1.5-19 (`background: true` only): late notices of background runs that did
1795
+ // not pass, each delivered once (takeNotices marks them delivered).
1796
+ if (background !== undefined) {
1797
+ try {
1798
+ const late = buildLateNoticeBlock(background.takeNotices(sessionID));
1799
+ if (late !== undefined) output.system.push(late);
1800
+ } catch (error) {
1801
+ logger.warn("[verify] late notices not injected", { error: scrubText(String(error)) });
1802
+ }
1803
+ }
1466
1804
  },
1467
1805
 
1468
1806
  // -----------------------------------------------------------------------
@@ -1472,6 +1810,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1472
1810
  if (input.command === "tiers") {
1473
1811
  try {
1474
1812
  cfg = loadConfig();
1813
+ warnDeprecatedVerifyKeys(cfg, logger);
1475
1814
  } catch {}
1476
1815
  output.parts.push({
1477
1816
  type: "text" as const,
@@ -1482,6 +1821,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1482
1821
  if (input.command === "preset") {
1483
1822
  try {
1484
1823
  cfg = loadConfig();
1824
+ warnDeprecatedVerifyKeys(cfg, logger);
1485
1825
  } catch {}
1486
1826
  output.parts.push({
1487
1827
  type: "text" as const,
@@ -1507,6 +1847,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1507
1847
  if (input.command === "budget") {
1508
1848
  try {
1509
1849
  cfg = loadConfig();
1850
+ warnDeprecatedVerifyKeys(cfg, logger);
1510
1851
  } catch {}
1511
1852
  output.parts.push({
1512
1853
  type: "text" as const,
@@ -1517,6 +1858,7 @@ const ModelRouterPlugin: Plugin = async (ctx: PluginInput) => {
1517
1858
  if (input.command === "router") {
1518
1859
  try {
1519
1860
  cfg = loadConfig();
1861
+ warnDeprecatedVerifyKeys(cfg, logger);
1520
1862
  } catch {}
1521
1863
  const args = (input.arguments ?? "").trim();
1522
1864
  const parts = args.split(/\s+/).filter(Boolean);