opencode-model-router 2.10.0 → 2.11.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 (47) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +3 -2
  3. package/package.json +8 -1
  4. package/src/compat/background.ts +5 -0
  5. package/src/compat/session-lookup.ts +21 -0
  6. package/src/compat/v2-hooks.ts +256 -88
  7. package/src/compat/v2-observations.ts +1 -0
  8. package/src/compat/v2-vocabulary.ts +14 -0
  9. package/src/executor/create.ts +3 -0
  10. package/src/executor/git.ts +110 -26
  11. package/src/executor/integrate/checks.ts +29 -11
  12. package/src/executor/integrate/queue.ts +95 -13
  13. package/src/executor/ledger.ts +16 -12
  14. package/src/executor/lfs-restore.ts +492 -0
  15. package/src/executor/paths.ts +7 -2
  16. package/src/executor/recovery.ts +2 -1
  17. package/src/executor/runtime.ts +1010 -226
  18. package/src/executor/slots/pool.ts +120 -19
  19. package/src/executor/slots/provision.ts +111 -23
  20. package/src/executor/slots/root.ts +81 -0
  21. package/src/executor/types.ts +28 -2
  22. package/src/executor/unattended.ts +6 -1
  23. package/src/executor/verify-trees.ts +507 -0
  24. package/src/guard/enforce.ts +2 -1
  25. package/src/guard/fingerprint.ts +9 -0
  26. package/src/guard/guards.ts +7 -1
  27. package/src/index.ts +107 -27
  28. package/src/router/answer-dedup.ts +198 -0
  29. package/src/router/common-dir.ts +241 -0
  30. package/src/router/config.ts +71 -12
  31. package/src/router/diff-handles.ts +322 -0
  32. package/src/router/diff-summary.ts +318 -0
  33. package/src/router/git-metadata-guard.ts +144 -7
  34. package/src/router/git-tools.ts +930 -73
  35. package/src/router/role-agents.ts +100 -36
  36. package/src/router/run-summary.ts +253 -0
  37. package/src/router/run-tools.ts +145 -23
  38. package/src/router/sessions.ts +14 -1
  39. package/src/routing/classify/rules.ts +93 -14
  40. package/src/routing/wire/hint.ts +9 -2
  41. package/src/v2.ts +3 -1
  42. package/src/verify/exec.ts +454 -2
  43. package/src/verify/plan-task.ts +86 -26
  44. package/src/verify/runner.ts +14 -6
  45. package/src/verify/tree.ts +5 -1
  46. package/src/verify/types.ts +44 -0
  47. package/src/verify/wiring.ts +87 -10
@@ -189,7 +189,10 @@ export function planTaskGit(): PlanTaskGit {
189
189
 
190
190
  /** QA-5.1-4: the reason of every verification cut by `dispose`. */
191
191
  export const PLAN_TASK_SHUTDOWN_REASON = "the plugin is shutting down";
192
- /** QA-5.1-4: how long `dispose` waits for the abort of one grader session. */
192
+ /**
193
+ * QA-5.1-4: how long `dispose` waits for the abort of one grader session. Recovery-R1-m2 (#190): it also bounds each grader
194
+ * abort of a cut, timed-out or failed gate pass, and the drain of that gate before its lease exemptions go.
195
+ */
193
196
  export const PLAN_TASK_ABORT_MS = 5_000;
194
197
 
195
198
  /** QA-5.1-4: a wait cut by the verifier's `dispose`. */
@@ -397,10 +400,13 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
397
400
  if (finalText !== undefined && finalText.trim() !== "") finalTexts.set(key, finalText);
398
401
  const record = records.get(key);
399
402
  // No begin record (a restart): verify takes the fail-closed fallback.
400
- if (record === undefined || record.observed !== undefined) return;
403
+ if (record === undefined) return;
401
404
  // The cached observation is process-wide (it outlives an attachment): only its WAIT is bound to the attachment, never
402
405
  // the observation itself, so an attachment cut cannot cache a failed observation that the next attachment would grade.
403
- record.observed = prepare(record, attempt);
406
+ record.observed ??= prepare(record, attempt);
407
+ // Phase-6.1 N1 (#190): every observe waits for the shared observation, also one an earlier attachment started, so the
408
+ // router's commit and cleanForChecks never run while its tree snapshot still reads the slot (bounded by the observation's
409
+ // own gate budget and by this attachment's signal).
404
410
  // QA-5.1-4: dispose never waits for an observation (its deadline is aborted; verify then cuts).
405
411
  try { await untilStopped(record.observed, ctx?.signal); } catch { /* cut by dispose or attachment change */ }
406
412
  }
@@ -466,10 +472,33 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
466
472
  return { ok: true, record, prepared: { ...observed.prepared, changedFiles: [], changeBaseline: "available" }, trusted: false };
467
473
  }
468
474
 
475
+ /**
476
+ * Recovery-R1-m2 (#190): waits for a cut, timed-out or failed gate to settle (its deadline is already aborted), at most
477
+ * PLAN_TASK_ABORT_MS; a gate still running then is left behind with one warning. Absent gate (never started): no wait.
478
+ * Whether the gate settled (true for an absent gate).
479
+ */
480
+ async function drainGate(gate: Promise<GateResult> | undefined, label: string): Promise<boolean> {
481
+ if (gate === undefined) return true;
482
+ let timer: ReturnType<typeof setTimeout> | undefined;
483
+ const bound = new Promise<"bound">((resolve) => {
484
+ timer = setTimeout(() => resolve("bound"), PLAN_TASK_ABORT_MS);
485
+ timer.unref?.();
486
+ });
487
+ try {
488
+ const settled = gate.then(() => "settled" as const, () => "settled" as const);
489
+ if ((await Promise.race([settled, bound])) === "settled") return true;
490
+ const name = scrubText(label).replace(/\s+/g, " ").trim().slice(0, 200);
491
+ warn(`plan-task verification gate for ${name} did not settle within ${PLAN_TASK_ABORT_MS} ms of its cut or timeout; its lease exemptions are released`);
492
+ return false;
493
+ } finally {
494
+ clearTimeout(timer);
495
+ }
496
+ }
497
+
469
498
  async function runPass(
470
499
  passDoD: DoD, budgetMs: number, record: AttemptRecord, task: TaskNode, slot: SlotLease, attempt: Attempt,
471
500
  artefact: Artefact, prepared: PreparedVerification, parent: string, signal?: AbortSignal,
472
- ): Promise<{ res: GateResult; cut: boolean }> {
501
+ ): Promise<{ res: GateResult; cut: boolean; settled: boolean }> {
473
502
  // Bind this pass's wait to its attachment as well as plugin shutdown; the gate remains directly awaited.
474
503
  const untilShutdown = <T>(work: Promise<T>): Promise<T> => untilStopped(work, signal);
475
504
  const cfg = deps.getConfig();
@@ -486,6 +515,8 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
486
515
  const child = attempt.childSessionID ?? "";
487
516
  const tree = prepared.snapshot?.root ?? slot.path;
488
517
  const releases = [tree, slot.path].map((root) => deps.exemptions.exempt(root, [child, leaseHolderID(record.planId, task.id)]));
518
+ // Recovery-R1-m2 (#190): the gate itself, so a cut or timed-out pass drains it before its exemptions go.
519
+ let gate: Promise<GateResult> | undefined;
489
520
  try {
490
521
  // QA-5.1-14: the grader is parented to the plan's CURRENT orchestrator, as the runtime read it for this verify (an
491
522
  // adopt moves the plan; verify refused an unknown one before any gate ran).
@@ -503,27 +534,29 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
503
534
  ...(placement.refused !== undefined ? { refusedCheck: placement.refused } : {}),
504
535
  };
505
536
  if (disposing || signal?.aborted) throw new PlanTaskShutdownError();
506
- const res = await untilShutdown(withTimeout(accept(delegation, artefact, gateDeps), deadline.remaining(), "verification gate"));
507
- return { res, cut: false };
537
+ gate = accept(delegation, artefact, gateDeps);
538
+ const res = await untilShutdown(withTimeout(gate, deadline.remaining(), "verification gate"));
539
+ return { res, cut: false, settled: true };
508
540
  } catch (error) {
509
- if (error instanceof PlanTaskShutdownError || disposing || signal?.aborted) {
510
- // QA-5.1-4: dispose aborted the deadline and owns the grader aborts; the pass judged nothing and is never re-run.
511
- deadline.abort(PLAN_TASK_SHUTDOWN_REASON);
512
- if (signal?.aborted && !disposing) await Promise.allSettled([...graders].map((sessionID) =>
513
- withTimeout(deps.abortSession(sessionID), PLAN_TASK_ABORT_MS, "grader abort")));
514
- return { res: unverifiableGateResult(PLAN_TASK_SHUTDOWN_REASON, passDoD.source, strict), cut: false };
515
- }
516
- const timedOut = error instanceof RouterTimeoutError;
517
- deadline.abort(timedOut ? "verification gate timed out" : "verification gate failed");
518
- for (const sessionID of graders) {
519
- try { await deps.abortSession(sessionID); } catch { /* best effort: the gate result stands either way */ }
520
- }
541
+ const cut = error instanceof PlanTaskShutdownError || disposing || signal?.aborted === true;
542
+ const timedOut = !cut && error instanceof RouterTimeoutError;
543
+ // Recovery-R1-m2 (#190): the deadline goes first; it cancels the gate's checks and every grader dispatch linked to it
544
+ // (buildGateDeps, `cancelGradersWithDeadline`), also one whose session is created only after this point.
545
+ deadline.abort(cut ? PLAN_TASK_SHUTDOWN_REASON : timedOut ? "verification gate timed out" : "verification gate failed");
546
+ // QA-5.1-4: dispose owns the grader aborts of its own cut. Every other cut, timeout or failure aborts the graders this
547
+ // pass knows (best effort, each bounded) while the gate drains: a rerun or the next attachment starts only after it.
548
+ const aborts = cut && disposing ? [] : [...graders].map((sessionID) =>
549
+ withTimeout(deps.abortSession(sessionID), PLAN_TASK_ABORT_MS, "grader abort").catch(() => undefined));
550
+ const [settled] = await Promise.all([drainGate(gate, `${task.id}#${attempt.n}`), Promise.all(aborts)]);
551
+ // The pass judged nothing and is never re-run.
552
+ if (cut) return { res: unverifiableGateResult(PLAN_TASK_SHUTDOWN_REASON, passDoD.source, strict), cut: false, settled };
521
553
  return {
522
554
  res: unverifiableGateResult(
523
555
  timedOut ? `verification gate timed out after ${budgetMs}ms` : `verification unavailable: ${scrubText(String(error))}`,
524
556
  passDoD.source, strict, completedFailures,
525
557
  ),
526
558
  cut: timedOut,
559
+ settled,
527
560
  };
528
561
  } finally {
529
562
  live.delete(entry);
@@ -533,11 +566,21 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
533
566
  }
534
567
  }
535
568
 
536
- async function verifyWithAttachment(signal: AbortSignal | undefined, task: TaskNode, slot: SlotLease, attempt: Attempt, parent: string,
537
- onDecided: (decided: PlanTaskVerdict) => void): Promise<PlanTaskVerdict> {
569
+ async function verifyWithAttachment(signal: AbortSignal | undefined, journal: PlanTaskContext["processJournal"], task: TaskNode, slot: SlotLease,
570
+ attempt: Attempt, parent: string, onDecided: (decided: PlanTaskVerdict) => void): Promise<PlanTaskVerdict> {
538
571
  const untilShutdown = <T>(work: Promise<T>): Promise<T> => untilStopped(work, signal);
539
572
  const key = keyOf(slot.planId, task.id, attempt.n);
540
573
  let record = records.get(key);
574
+ // Phase-6.1 N2 (#190): a record kept across a cut observed another slot when the task was re-provisioned since: it
575
+ // describes no tree of this slot, so it goes (its ids too) and this verification takes the restart fallback.
576
+ if (record !== undefined && planTreeKey(record.slotPath) !== planTreeKey(slot.path)) {
577
+ clearIds(record.id, null);
578
+ records.delete(key);
579
+ record = undefined;
580
+ }
581
+ // Phase-6.1 N2 (#190): the begin record this pipeline graded (null: the restart fallback's), and whether it decided.
582
+ const begun = record?.observed !== undefined ? record : null;
583
+ let decidedHere = false;
541
584
  let prepared: PreparedVerification;
542
585
  try {
543
586
  if (record?.observed !== undefined) {
@@ -599,11 +642,15 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
599
642
  const gatePrepared: PreparedVerification = {
600
643
  ...prepared,
601
644
  graderDispatchLabel: `${task.id}#${attempt.n}`,
645
+ // Recovery-R1-m2 (#190): a grader dispatch ends with its pass's deadline (cut, timeout), never outlives the gate.
646
+ cancelGradersWithDeadline: true,
602
647
  ...(boundService === undefined ? {} : { service: boundService }),
603
648
  changedFiles,
604
649
  // The union is complete: the observed files and every path the candidate commits over the reset commit.
605
650
  changeBaseline: prepared.branchSwitch !== undefined ? "unavailable" : "available",
606
651
  snapshot: fresh,
652
+ // #189 R2-pre-2: the gate's check seams record every root they spawn in the attempt's process journal.
653
+ ...(journal === undefined ? {} : { processJournal: journal }),
607
654
  };
608
655
  const child = attempt.childSessionID ?? "";
609
656
  const producerTier = planTaskProducerTier(task, cfg);
@@ -633,9 +680,11 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
633
680
  const current = record;
634
681
  const withReruns = async (passDoD: DoD, budgetMs: number): Promise<GateResult> => {
635
682
  for (;;) {
636
- const { res, cut } = await runPass(passDoD, budgetMs, current, task, slot, attempt, artefact, gatePrepared, parent, signal);
683
+ const { res, cut, settled } = await runPass(passDoD, budgetMs, current, task, slot, attempt, artefact, gatePrepared, parent, signal);
637
684
  if (signal?.aborted) return res;
638
- if (disposing || !isTransientPlanTaskResult(res, cut) || reruns >= PLAN_TASK_TRANSIENT_RERUNS) return res;
685
+ // Recovery-R1-m2 (#190): a gate that did not settle within its drain bound may still run checks or a grader in the
686
+ // slot: never re-run over it (the transient result stands).
687
+ if (disposing || !settled || !isTransientPlanTaskResult(res, cut) || reruns >= PLAN_TASK_TRANSIENT_RERUNS) return res;
639
688
  const reason = scrubText([...new Set([...res.verdict.reasons, ...(res.verdict.caveats ?? [])])].join("; "))
640
689
  .replace(/\s+/g, " ").trim().slice(0, 200);
641
690
  const label = scrubText(`${task.id}#${attempt.n}`).replace(/\s+/g, " ").trim().slice(0, 200);
@@ -670,6 +719,7 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
670
719
  res = applyDispatchCaveats(res, gatePrepared);
671
720
  // QA-5.1-21: from here the verdict is decided: `verify` returns it even when dispose cuts its wait afterwards.
672
721
  const decided = slotVerdictOf(res);
722
+ decidedHere = true;
673
723
  onDecided(decided);
674
724
  if (child !== "" && res.verdict.skipped !== true) {
675
725
  try { deps.onVerdict?.(child, res.verdict); } catch (error) { warn("plan-task verdict not ingested", error); }
@@ -678,9 +728,15 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
678
728
  } catch (error) {
679
729
  return unverifiable(`verification unavailable: ${scrubText(error instanceof Error ? error.message : String(error))}`, record?.dod);
680
730
  } finally {
681
- records.delete(key);
682
- finalTexts.delete(key);
683
- if (record !== undefined) clearIds(record.id, attempt.childSessionID);
731
+ // Phase-6.1 N2 (#190): an attachment cut that decided nothing keeps the begin record, the child's final text and the
732
+ // store ids, so the next same-process attachment grades the observed attempt (the runtime never calls begin again)
733
+ // instead of the restart fallback. A decided verdict, any other result, a fallback record and dispose clear them.
734
+ const keep = begun !== null && signal?.aborted === true && !disposing && !decidedHere && records.get(key) === begun;
735
+ if (!keep) {
736
+ records.delete(key);
737
+ finalTexts.delete(key);
738
+ if (record !== undefined) clearIds(record.id, attempt.childSessionID);
739
+ }
684
740
  }
685
741
  }
686
742
 
@@ -693,7 +749,7 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
693
749
  try {
694
750
  // Attachment cuts are handled inside the pipeline, including bounded grader abort/cleanup, before a new
695
751
  // attachment can verify this identity. Global dispose retains its prompt outer cut semantics.
696
- const verifyNow = verifyWithAttachment.bind(undefined, ctx?.signal);
752
+ const verifyNow = verifyWithAttachment.bind(undefined, ctx?.signal, ctx?.processJournal);
697
753
  const result = await untilStopped(verifyNow(task, slot, attempt, orchestrator(ctx), (v) => { decided = v; }));
698
754
  return ctx?.signal?.aborted && decided === null ? cut() : result;
699
755
  } catch (error) {
@@ -711,6 +767,10 @@ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVeri
711
767
  if (disposing) return;
712
768
  disposing = true;
713
769
  shutdown.abort();
770
+ // Phase-6.1 N2 (#190): records kept across an attachment cut never outlive the plugin.
771
+ for (const record of records.values()) clearIds(record.id, null);
772
+ records.clear();
773
+ finalTexts.clear();
714
774
  const sessions = new Set<string>();
715
775
  for (const entry of live) {
716
776
  entry.deadline.abort(PLAN_TASK_SHUTDOWN_REASON);
@@ -1210,6 +1210,19 @@ export const MAX_ARGV_CHARS = 30000;
1210
1210
  /** Report files: `${tmpdir}/omr-verify-<uuid>.json|.xml`. readResult touches nothing else. */
1211
1211
  export const REPORT_NAME_RE = /^omr-verify-[0-9a-f-]{36}\.(json|xml)$/;
1212
1212
 
1213
+ /**
1214
+ * readResult's report-path guard: `path` names a file directly in `tmpdir` (both absolute; compared case-folded on win32)
1215
+ * whose name matches `name`. Nothing else is read or unlinked. `router_run`'s `summary: "failures"` (#108) uses it with
1216
+ * its own report names.
1217
+ */
1218
+ export function reportPathAllowed(path: string, tmpdir: string, platform: NodeJS.Platform = process.platform,
1219
+ name: RegExp = REPORT_NAME_RE): boolean {
1220
+ const win = platform === "win32";
1221
+ const P = win ? nodePath.win32 : nodePath.posix;
1222
+ const key = (p: string) => (win ? p.toLowerCase() : p);
1223
+ return P.isAbsolute(tmpdir) && P.isAbsolute(path) && key(P.dirname(P.resolve(path))) === key(P.resolve(tmpdir)) && name.test(P.basename(path));
1224
+ }
1225
+
1213
1226
  // ---------------------------------------------------------------------------------------------
1214
1227
  // Types
1215
1228
  // ---------------------------------------------------------------------------------------------
@@ -5491,12 +5504,7 @@ export async function readResult(
5491
5504
  host?: Partial<RunnerHost>,
5492
5505
  ): Promise<RunResult> {
5493
5506
  const ctx = makeCtx(host);
5494
- const P = ctx.P;
5495
- const allowed =
5496
- P.isAbsolute(ctx.host.tmpdir) &&
5497
- P.isAbsolute(spec.reportPath) &&
5498
- ctx.key(P.dirname(P.resolve(spec.reportPath))) === ctx.key(P.resolve(ctx.host.tmpdir)) &&
5499
- REPORT_NAME_RE.test(P.basename(spec.reportPath));
5507
+ const allowed = reportPathAllowed(spec.reportPath, ctx.host.tmpdir, ctx.host.platform);
5500
5508
  try {
5501
5509
  if (!allowed) return crossLinkCompleteness(ctx, spec, textResult(ctx, spec, execResult, `report path rejected: ${spec.reportPath}`));
5502
5510
  let text: string | undefined;
@@ -521,7 +521,9 @@ export async function snapshotTree(cwd: string, signal: AbortSignal, options: Sn
521
521
  // fingerprint) but never runs a repository-configured fsmonitor, hook, ssh key command or transport (`workRootReadArgs()`).
522
522
  let prefix: readonly string[] = ["--no-pager", ...tools.workRootReadArgs()];
523
523
  let hardening: Pick<SnapshotGitOptions, "env" | "executable"> = {};
524
- type Stage = "root" | "drivers" | "head" | "status" | "diff-worktree" | "diff-index" | "index" | "untracked-list" | "hash" | "index-tags" | "ignored-list";
524
+ // #194: `harden` (the hardened snapshot's executable and inherited configuration) and `finalize` (the paths of the
525
+ // result) label failures outside a git call, which would otherwise carry the previous stage's label.
526
+ type Stage = "harden" | "root" | "drivers" | "head" | "status" | "diff-worktree" | "diff-index" | "index" | "untracked-list" | "hash" | "index-tags" | "ignored-list" | "finalize";
525
527
  let stage: Stage = "root";
526
528
  const git = (label: Stage, args: string[]) => {
527
529
  stage = label;
@@ -531,6 +533,7 @@ export async function snapshotTree(cwd: string, signal: AbortSignal, options: Sn
531
533
  };
532
534
  try {
533
535
  if (options.hardened === true) {
536
+ stage = "harden";
534
537
  const hardened = await hardenedGit(cwd);
535
538
  prefix = hardened.prefix;
536
539
  hardening = { env: hardened.env, executable: hardened.executable };
@@ -613,6 +616,7 @@ export async function snapshotTree(cwd: string, signal: AbortSignal, options: Sn
613
616
  options.maxIgnoredBytes ?? MAX_IGNORED_BYTES,
614
617
  );
615
618
  }
619
+ stage = "finalize";
616
620
  return {
617
621
  cwd: await realpath(cwd), root: await realpath(root), head, branch, fingerprint: hash.digest("hex"), dirty: files.length > 0, files, digests,
618
622
  ...(ignored !== undefined ? { ignored } : {}),
@@ -62,6 +62,22 @@ export interface ExecResult {
62
62
  timedOut?: boolean;
63
63
  }
64
64
 
65
+ /**
66
+ * #189 R2-pre-2: the root of one spawned process tree, as the process layer (exec.ts) reports it to `onSpawn`/`onSettle`.
67
+ */
68
+ export interface SpawnedProcess {
69
+ readonly pid: number;
70
+ /** Date.now() taken just before the spawn: the root's creation time is at or after it. */
71
+ readonly startedAtMs: number;
72
+ /** POSIX: the process group the root leads (it is spawned detached), so pgid === pid; null on Windows. */
73
+ readonly pgid: number | null;
74
+ /**
75
+ * The run's deadline in ms after `startedAtMs` (exec.ts `deadlineOf`); null without one (a signal-only run). A process
76
+ * the root started is created before `startedAtMs + deadlineMs + KILL_GRACE_MS`: by then the run killed its tree.
77
+ */
78
+ readonly deadlineMs: number | null;
79
+ }
80
+
65
81
  /** Options shared by every verification process seam (shell string or argv). */
66
82
  export interface ExecOptions {
67
83
  /** Optional v2 diagnostics; process adapters split preparation from the actual spawn/child lifetime. */
@@ -76,6 +92,34 @@ export interface ExecOptions {
76
92
  env?: Record<string, string>;
77
93
  /** `replace` uses only env (empty when omitted), without process.env or automatic slot-environment injection. */
78
94
  envMode?: "merge" | "replace";
95
+ /**
96
+ * #189 R2-pre-2 (v2 plan tasks only): called once, synchronously, right after a spawn that produced a pid. A throw is
97
+ * ignored: the hook never affects spawning, cancellation or settlement. Absent (v1, dispatches): nothing is reported.
98
+ */
99
+ onSpawn?: (root: SpawnedProcess) => void;
100
+ /**
101
+ * #189 R2-pre-2: called once when the root (the direct child) exits, with the time it was seen exiting; nothing it
102
+ * started can be created after that. A throw is ignored.
103
+ */
104
+ onExit?: (root: SpawnedProcess, exitedAtMs: number) => void;
105
+ /** #189 R2-pre-2: called once when the run whose spawn `onSpawn` reported settles; a throw is ignored. */
106
+ onSettle?: (root: SpawnedProcess) => void;
107
+ }
108
+
109
+ /**
110
+ * #189 R2-pre-2: where a plan-task verification records the process trees it spawns (one journal per attempt, written by
111
+ * the executor), so a restart can end the trees a dead server left running before it verifies again. Never throws.
112
+ */
113
+ export interface ProcessJournal {
114
+ /**
115
+ * A root was spawned. `command` is text the root's command line contains: the shell command of a shell run, the
116
+ * executable of an argv run.
117
+ */
118
+ spawned(root: SpawnedProcess, command: string): void;
119
+ /** `root` exited at `exitedAtMs` (its run may still be pending: a descendant can hold the pipes). */
120
+ exited(root: SpawnedProcess, exitedAtMs: number): void;
121
+ /** The run of `root` settled. */
122
+ settled(root: SpawnedProcess): void;
79
123
  }
80
124
 
81
125
  /** Execution-only seam; an adapter doing preparation must forward `service` to the instrumented process layer. */
@@ -102,7 +102,7 @@ import { REFERENCE_NONE } from "./baseline";
102
102
  import { scrubText } from "../guard/scrub";
103
103
  import { displaySafe } from "../routing/roles/read-set";
104
104
  import type { DoD } from "./dod";
105
- import type { ArgvSeam, CheckPlacement, Deadline, ExecOptions, ExecResult as SeamResult, ExecSeam, ReferenceState, TestsPassHook, Verdict } from "./types";
105
+ import type { ArgvSeam, CheckPlacement, Deadline, ExecOptions, ExecResult as SeamResult, ExecSeam, ProcessJournal, ReferenceState, TestsPassHook, Verdict } from "./types";
106
106
  import { planScopedRun, planStaticScoping, type ChangedPath, type RunnerFs, type StaticScoping, type StaticScopingInput, type TestSearchSeam } from "./runner";
107
107
  import {
108
108
  DEFAULT_GATE_BUDGET_MS,
@@ -181,6 +181,12 @@ export interface PreparedVerification {
181
181
  service?: ServiceObservation;
182
182
  /** Plan-task identity for v2 grader-dispatch failure logs, including when observations are off. */
183
183
  graderDispatchLabel?: string;
184
+ /**
185
+ * Recovery-R1-m2 (#190): buildGateDeps links each grader dispatch to the gate's deadline (`dispatchGrader`'s `cancel`), so
186
+ * a cut or timed-out gate also cancels a grader still starting. Plan-task gates opt in; v2 host runner only (the v1
187
+ * `client.session` path ignores it).
188
+ */
189
+ cancelGradersWithDeadline?: true;
184
190
  /**
185
191
  * The producer's changed files: the tool-observed paths of every attempt judged against this
186
192
  * dispatch (QA-2.1-1), the paths the current snapshot added since dispatch, and the paths dirty
@@ -228,6 +234,44 @@ export interface PreparedVerification {
228
234
  * (DeterministicDeps.dispatchStartedAt): only W's ignored modules modified since are cross-link inputs. Absent: none are.
229
235
  */
230
236
  dispatchStartedAt?: number;
237
+ /**
238
+ * #189 R2-pre-2 (v2 plan tasks only): the attempt's process journal. With it, buildGateDeps records every root its check
239
+ * seams spawn (ExecOptions.onSpawn/onSettle), so a restart can end the trees a dead server left running. Absent (v1,
240
+ * dispatches): the seams are the plain ones.
241
+ */
242
+ processJournal?: ProcessJournal;
243
+ }
244
+
245
+ /** #189 R2-pre-2: the spawn hooks of `opts`, forwarded only when set (the plain seams pass nothing new). */
246
+ function spawnHooksOf(opts: ExecOptions | undefined): Pick<ExecOptions, "onSpawn" | "onExit" | "onSettle"> {
247
+ return {
248
+ ...(opts?.onSpawn === undefined ? {} : { onSpawn: opts.onSpawn }),
249
+ ...(opts?.onExit === undefined ? {} : { onExit: opts.onExit }),
250
+ ...(opts?.onSettle === undefined ? {} : { onSettle: opts.onSettle }),
251
+ };
252
+ }
253
+
254
+ /**
255
+ * #189 R2-pre-2: `opts` with spawn hooks that record each root in `journal` under `command` (text its command line
256
+ * contains), after any hooks `opts` already carries. A throwing hook never stops the other.
257
+ */
258
+ export function journaledOptions(opts: ExecOptions | undefined, journal: ProcessJournal, command: string): ExecOptions {
259
+ const outer = spawnHooksOf(opts);
260
+ return {
261
+ ...opts,
262
+ onSpawn: (root) => {
263
+ try { outer.onSpawn?.(root); } catch { /* the journal still records the root */ }
264
+ journal.spawned(root, command);
265
+ },
266
+ onExit: (root, exitedAtMs) => {
267
+ try { outer.onExit?.(root, exitedAtMs); } catch { /* the journal still records the exit */ }
268
+ journal.exited(root, exitedAtMs);
269
+ },
270
+ onSettle: (root) => {
271
+ try { outer.onSettle?.(root); } catch { /* the journal still drops the root */ }
272
+ journal.settled(root);
273
+ },
274
+ };
231
275
  }
232
276
 
233
277
  /**
@@ -892,6 +936,15 @@ export function backgroundOutcomes(items: readonly HandleReport[]): BackgroundOu
892
936
  /** QA-2.1-11: how often a lease wait that ignores the producer's own holder probes the tree again. */
893
937
  const LEASE_WAIT_POLL_MS = 100;
894
938
 
939
+ /**
940
+ * #191 (v2 only): whether a gate's check waits for the lease gate. A lease gate scoped to held results (`"held"`,
941
+ * `routing.background.mode: "off"`) is waited for by the gate of a background finish only, so a foreground check keeps the
942
+ * timing and result it had without one; unscoped, by every check. Pure.
943
+ */
944
+ export function leaseWaitApplies(scope: "held" | undefined, backgroundFinish: boolean): boolean {
945
+ return scope !== "held" || backgroundFinish;
946
+ }
947
+
895
948
  /**
896
949
  * QA-2.1-11 (phase 2.1, v2 only): waits until no holder of `tree` other than the sessions in `exclude` edits it, or `deadlineMs`
897
950
  * passes. The producer's own leases stay until its completion is processed, after this gate, so waiting for them only delays
@@ -1157,7 +1210,7 @@ export interface VerificationWiring {
1157
1210
  * the changed files are "unavailable" and the reference is the untracked default. `deadline`
1158
1211
  * bounds every testsPass step (T3); without it each testsPass check owns one of gateBudgetMs.
1159
1212
  */
1160
- buildGateDeps(parentSessionID?: string, inFlight?: Set<string>, prepared?: PreparedVerification, deadline?: Deadline, forceLowPriority?: boolean, creatorSessionID?: string | null, serviceIdentity?: () => ServiceIdentity): GateDeps;
1213
+ buildGateDeps(parentSessionID?: string, inFlight?: Set<string>, prepared?: PreparedVerification, deadline?: Deadline, forceLowPriority?: boolean, creatorSessionID?: string | null, serviceIdentity?: () => ServiceIdentity, backgroundFinish?: boolean): GateDeps;
1161
1214
  /**
1162
1215
  * 2.2.3: the idle-TTL sweep's hook into the plugin's one S5 batch coordinator (batch.ts B11):
1163
1216
  * evicts windows with no live member and batches whose seam hung past BATCH_STALE_GRACE_MS.
@@ -1229,6 +1282,11 @@ export function createVerificationWiring(deps: {
1229
1282
  * Plugin verification runs in a tree wait for its holders first.
1230
1283
  */
1231
1284
  leaseGate?: Pick<import("../compat/background").LeaseGuard, "waitTreeFree">;
1285
+ /**
1286
+ * #191 (v2 only): read per gate. `"held"` (`routing.background.mode: "off"`): only a background finish (`buildGateDeps`
1287
+ * `backgroundFinish`) waits for `leaseGate`; absent: every check does (`leaseWaitApplies`).
1288
+ */
1289
+ leaseGateScope?: () => "held" | undefined;
1232
1290
  /** Test seams of the 2.4.5 background queue; used only when `background` is true. */
1233
1291
  background?: Pick<BackgroundQueueOptions, "now" | "timers" | "settleMs" | "retryBaseMs" | "maxAttempts" | "platform">;
1234
1292
  }): VerificationWiring {
@@ -1327,6 +1385,7 @@ export function createVerificationWiring(deps: {
1327
1385
  const abs = (p: string): string => (isAbsolute(p) ? p : join(directory, p));
1328
1386
 
1329
1387
  // QA-1.2-13: lowPriority and env reach the process; no per-call maxBuffer (QA-1.5-25).
1388
+ // #189 R2-pre-2: the spawn hooks reach it too (set only by a plan-task gate's journaled seams, see buildGateDeps).
1330
1389
  const execSeam: ExecSeam = (command: string, opts?: ExecOptions): Promise<ExecResult> =>
1331
1390
  runShell(command, {
1332
1391
  cwd: opts?.cwd ?? directory,
@@ -1335,6 +1394,7 @@ export function createVerificationWiring(deps: {
1335
1394
  lowPriority: opts?.lowPriority,
1336
1395
  env: opts?.env,
1337
1396
  ...(opts?.service === undefined ? {} : { service: opts.service }),
1397
+ ...spawnHooksOf(opts),
1338
1398
  });
1339
1399
 
1340
1400
  const argvSeam: ArgvSeam = (file, args, opts) =>
@@ -1345,6 +1405,7 @@ export function createVerificationWiring(deps: {
1345
1405
  lowPriority: opts?.lowPriority,
1346
1406
  env: opts?.env,
1347
1407
  ...(opts?.service === undefined ? {} : { service: opts.service }),
1408
+ ...spawnHooksOf(opts),
1348
1409
  });
1349
1410
 
1350
1411
  // T9 1.3: PlannerFs + unlink over fs.promises. realpath is the native one; fileExists accepts
@@ -1505,12 +1566,18 @@ export function createVerificationWiring(deps: {
1505
1566
  creatorSessionID: string | null = parentSessionID ?? null,
1506
1567
  service?: ServiceObservation,
1507
1568
  graderDispatchLabel?: string,
1569
+ /**
1570
+ * Recovery-R1-m2 (#190): ends the dispatch with its caller's gate (buildGateDeps passes the deadline's signal when the
1571
+ * prepared verification opts in). Already aborted: no session is created. v2 host runner only; v1 ignores it.
1572
+ */
1573
+ cancel?: AbortSignal,
1508
1574
  ): Promise<{ sessionID: string; text: string; model: string | null }> => {
1509
1575
  // #84 P3.3 fix 2: the model the grader is dispatched on travels with its answer (checker.ts GraderResult.model → the
1510
1576
  // verdict's `grader`), so the outcome signals can check its independence (plan §2.6). Null: the host's default model.
1511
1577
  const modelRef = (model: { providerID: string; modelID: string } | null): string | null =>
1512
1578
  model === null ? null : `${model.providerID}/${model.modelID}`;
1513
1579
  if (deps.childRunner) {
1580
+ cancel?.throwIfAborted();
1514
1581
  const cfg = getConfig();
1515
1582
  const controller = new AbortController();
1516
1583
  const model = tierModel(cfg, req.tier);
@@ -1523,7 +1590,7 @@ export function createVerificationWiring(deps: {
1523
1590
  model: model ?? undefined,
1524
1591
  system: req.system,
1525
1592
  prompt: req.prompt,
1526
- signal: controller.signal,
1593
+ signal: cancel === undefined ? controller.signal : AbortSignal.any([controller.signal, cancel]),
1527
1594
  ...(service === undefined ? {} : { service, onServiceStart: () => preparation?.end("completed") }),
1528
1595
  async onCreated(sessionID) {
1529
1596
  sid = sessionID;
@@ -1644,6 +1711,8 @@ export function createVerificationWiring(deps: {
1644
1711
  forceLowPriority = false,
1645
1712
  creatorSessionID: string | null = parentSessionID ?? null,
1646
1713
  serviceIdentity?: () => ServiceIdentity,
1714
+ // #191: the gate of a background finish (held or not); see `leaseWaitApplies`.
1715
+ backgroundFinish = false,
1647
1716
  ): GateDeps => {
1648
1717
  // A plan task's prepared verification already carries its service span; native dispatches carry none.
1649
1718
  const service = serviceIdentity === undefined ? prepared?.service : serviceObservation(deps.observations, serviceIdentity);
@@ -1652,15 +1721,20 @@ export function createVerificationWiring(deps: {
1652
1721
  // 2.4.5 (section 1.5-19): background runs are low priority whatever `lowPriority` says.
1653
1722
  // QA-2.4-5: and they never wait for the slot (waitMs 0): busy means back off and retry later.
1654
1723
  const budget: VerifyBudget = forceLowPriority ? { ...resolved, lowPriority: true, slotWaitMs: 0 } : resolved;
1724
+ // #189 R2-pre-2 (v2 plan tasks): with a process journal, every root the check seams spawn is recorded in it (the
1725
+ // shell command or the executable as the text its command line contains); without one, the plain seams.
1726
+ const journal = prepared?.processJournal;
1727
+ const gateExec: ExecSeam = journal === undefined ? execSeam : (command, opts) => execSeam(command, journaledOptions(opts, journal, command));
1728
+ const gateArgv: ArgvSeam = journal === undefined ? argvSeam : (file, args, opts) => argvSeam(file, args, journaledOptions(opts, journal, file));
1655
1729
  // QA-2.1-5: the recheck's git processes (GC, materialize, dispose) run at the configured
1656
1730
  // priority too, like the capture and the start-up GC (QA-1.2-13).
1657
- const referenceArgv: ArgvSeam = (file, args, opts) => argvSeam(file, args, { ...opts, lowPriority: budget.lowPriority });
1731
+ const referenceArgv: ArgvSeam = (file, args, opts) => gateArgv(file, args, { ...opts, lowPriority: budget.lowPriority });
1658
1732
  // QA-2 nit: materialize pins a link target as this gate's dispatch admitted it (its pins' admission); without pins, none.
1659
1733
  const gatePins = prepared?.reference?.kind === "captured" ? prepared.reference.reference.pins : undefined;
1660
1734
  const pinNow = pinNowFor(gatePins !== undefined ? pinAdmissions.get(gatePins) : undefined);
1661
1735
  const openScope = createScopeOpener({
1662
1736
  service,
1663
- argv: argvSeam, exec: execSeam, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
1737
+ argv: gateArgv, exec: gateExec, fs: fsSeam, budget, checkTimeoutMs: CHECK_TIMEOUT_MS,
1664
1738
  reference: { argv: referenceArgv, pinNow },
1665
1739
  });
1666
1740
  const currentTree = prepared?.snapshot !== undefined ? { currentTree: prepared.snapshot } : {};
@@ -1712,8 +1786,9 @@ export function createVerificationWiring(deps: {
1712
1786
  try {
1713
1787
  void background?.preempt();
1714
1788
  // Phase 2.1 (v2, leases on): wait for the holders of the tree, within a quarter of the gate budget; then run
1715
- // anyway, with the concurrent-dispatches caveat for the holders that remain.
1716
- if (deps.leaseGate !== undefined) {
1789
+ // anyway, with the concurrent-dispatches caveat for the holders that remain. #191: a lease gate scoped to held results
1790
+ // is waited for by a background finish only.
1791
+ if (deps.leaseGate !== undefined && leaseWaitApplies(deps.leaseGateScope?.(), backgroundFinish)) {
1717
1792
  const leaseWait = service?.start("service-wait", "lease");
1718
1793
  try {
1719
1794
  // QA-2.1-11: the producer's own leases never delay its own check.
@@ -1743,11 +1818,11 @@ export function createVerificationWiring(deps: {
1743
1818
  return {
1744
1819
  deterministic: {
1745
1820
  ...(service === undefined ? {} : { service }),
1746
- exec: execSeam,
1821
+ exec: gateExec,
1747
1822
  fs: fsSeam,
1748
1823
  cwd: directory,
1749
1824
  mutex,
1750
- argv: argvSeam,
1825
+ argv: gateArgv,
1751
1826
  budget,
1752
1827
  openScope,
1753
1828
  testsPass,
@@ -1759,8 +1834,10 @@ export function createVerificationWiring(deps: {
1759
1834
  ...(prepared?.dispatchStartedAt !== undefined ? { dispatchStartedAt: prepared.dispatchStartedAt } : {}),
1760
1835
  },
1761
1836
  checker: {
1837
+ // Recovery-R1-m2 (#190): an opted-in gate (plan-task) cancels its graders with its deadline (cut, timeout, expiry).
1762
1838
  dispatchGrader: (req: GraderRequest) =>
1763
- dispatchGrader(req, parentSessionID, inFlight, creatorSessionID, service, prepared?.graderDispatchLabel),
1839
+ dispatchGrader(req, parentSessionID, inFlight, creatorSessionID, service, prepared?.graderDispatchLabel,
1840
+ prepared?.cancelGradersWithDeadline === true ? deadline?.signal : undefined),
1764
1841
  ladder: ["fast", "medium", "heavy"],
1765
1842
  minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
1766
1843
  },