opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -0,0 +1,729 @@
1
+ // Plan-task verification over the dispatch verification engine (Phase 5.1, D8-D11, A-5.1-4/-8/-9/-12/-13).
2
+ import { realpathSync } from "node:fs";
3
+ import { isAbsolute, posix, resolve, win32 } from "node:path";
4
+ import type { PlanTaskContext, PlanTaskVerdict, PlanTaskVerifier } from "../executor/runtime";
5
+ import { stripOrchestratorShell, leaseHolderID, type Attempt, type SlotLease, type TaskNode, type Verdict as SlotVerdict } from "../executor/types";
6
+ import { createGitRunner } from "../executor/git";
7
+ import { hardeningArgs } from "../router/git-tools";
8
+ import type { HeadState } from "./head";
9
+ import { snapshotTree } from "./tree";
10
+ import type { Artefact, Delegation, GateDeps, GateResult } from "./gate";
11
+ import { accept, unverifiableGateResult } from "./gate";
12
+ import { applyDispatchCaveats, isRetryableVerdict, parseNameStatusZ, type PreparedVerification, type VerificationWiring } from "./wiring";
13
+ import { normalizeDoD, type DoD } from "./dod";
14
+ import { buildDelegationDoD } from "./dispatch";
15
+ import { atLeastProducerTier, isIncompleteVerdict } from "./checker";
16
+ import { createDeadline } from "./deterministic";
17
+ import { graderTimeoutMs, RouterTimeoutError, withTimeout } from "./timeout";
18
+ import { neutralizeDirectives } from "./pending";
19
+ import { scrubText } from "../guard/scrub";
20
+ import type { BudgetSnapshot } from "../guard/enforce";
21
+ import { resolveRolesRouting, resolveVerifyBudget, type RouterConfig } from "../router/config";
22
+ import { PLAN_TASK_PERIMETER_ID, planPerimeter } from "./perimeter";
23
+ import { resolveRoles } from "../router/roles";
24
+ import { verificationScope } from "../routing/roles/work-root";
25
+ import { resolveCheckPlacements } from "../routing/roles/check-placement";
26
+
27
+ /** The change store the wiring's begin/prepare share with the dispatch path (index.ts `changedFileStore`). */
28
+ type ChangeStore = Parameters<VerificationWiring["prepareVerification"]>[0];
29
+
30
+ /** A git invocation in the slot through the router's hardened argv (index.ts supplies it). */
31
+ export type PlanTaskGit = (args: readonly string[], cwd: string, timeoutMs: number) => Promise<{ code: number | null; stdout: string; stderr: string }>;
32
+
33
+ /** The ports of the dispatch verification engine one plugin instance hands to its plan-task verifier (D8). */
34
+ export interface PlanTaskVerifierDeps {
35
+ changedFileStore: ChangeStore;
36
+ beginVerificationBounded: VerificationWiring["beginVerificationBounded"];
37
+ prepareVerification: VerificationWiring["prepareVerification"];
38
+ buildGateDeps: VerificationWiring["buildGateDeps"];
39
+ /** Handoff 24: the producer's guard budget when the task returned. */
40
+ captureBudget(childSessionID: string, capReached: boolean | undefined): BudgetSnapshot | undefined;
41
+ readCapReached(childSessionID: string): boolean | undefined;
42
+ /** M6: a real verdict of the task's child feeds the outcome store, as a dispatch verdict does. */
43
+ onVerdict?(childSessionID: string, verdict: GateResult["verdict"]): void;
44
+ /** Best-effort abort of a grader session after a gate timeout. */
45
+ abortSession(sessionID: string): Promise<void>;
46
+ getConfig(): RouterConfig;
47
+ git: PlanTaskGit;
48
+ exemptions: LeaseSelfExemptions;
49
+ /** Restart fallback: whether a perimeter would be planned for this id in the slot (index.ts: perimeter.ts planPerimeter). */
50
+ perimeterPlanned?(id: string, slotPath: string): boolean | Promise<boolean>;
51
+ /** A-5.1-9 backoff; injectable for tests. */
52
+ sleep?(ms: number): Promise<void>;
53
+ now?(): number;
54
+ log?(message: string, detail?: unknown): void;
55
+ }
56
+
57
+ /** A-5.1-9: the checks pass of a plan-task gate gets at least ten minutes. */
58
+ export const PLAN_TASK_CHECKS_MIN_MS = 600_000;
59
+ /** A-5.1-9: the grader pass gets the grader timeout plus one minute of slack. */
60
+ export const PLAN_TASK_GRADER_SLACK_MS = 60_000;
61
+ /** A-5.1-9: at most two internal re-runs of a transient unverifiable. */
62
+ export const PLAN_TASK_TRANSIENT_RERUNS = 2;
63
+ /** A-5.1-9: backoff before the first and the second re-run. */
64
+ export const PLAN_TASK_RERUN_BACKOFF_MS: readonly number[] = [30_000, 60_000];
65
+ /** Findings returned to the runtime are capped. */
66
+ export const PLAN_TASK_FINDINGS_MAX = 4000;
67
+ /** The child's final text handed to the grader as its return text is capped (the grader prompt scrubs it again). */
68
+ export const PLAN_TASK_RETURN_TEXT_MAX = 32_000;
69
+
70
+ /**
71
+ * Phase 5.1 (a): the artefact's `finalReturnText`: the child's own final text (trimmed as a dispatch's `<task_result>` is,
72
+ * scrubbed, capped at PLAN_TASK_RETURN_TEXT_MAX), else the fixed description of the router's commit.
73
+ */
74
+ export function planTaskReturnText(finalText: string | undefined, fallback: string): string {
75
+ const text = finalText === undefined ? "" : scrubText(finalText.trim());
76
+ if (text === "") return fallback;
77
+ return text.length > PLAN_TASK_RETURN_TEXT_MAX ? `${text.slice(0, PLAN_TASK_RETURN_TEXT_MAX - 1)}…` : text;
78
+ }
79
+
80
+ /**
81
+ * D8: a gate result as the runtime's slot verdict. Only an accepted pass passes; a fail fails; everything else (unverifiable,
82
+ * accepted or not, an incomplete return, a pass strict-rejected for its caveats, a skip without a checkable DoD) is unverifiable.
83
+ * Findings: reasons, then caveats, then notes (deduplicated, scrubbed, directive-neutralized), capped at PLAN_TASK_FINDINGS_MAX.
84
+ * Ref: the verdict's method, with the grader tier when a grader judged.
85
+ */
86
+ export function slotVerdictOf(res: GateResult): { verdict: SlotVerdict; findings: string; ref: string } {
87
+ const v = res.verdict;
88
+ const outcome = v.outcome ?? (v.pass ? "pass" : "fail");
89
+ const verdict: SlotVerdict = v.skipped === true
90
+ ? "unverifiable"
91
+ : outcome === "fail"
92
+ ? "fail"
93
+ : outcome === "pass" && res.accepted && !isIncompleteVerdict(v)
94
+ ? "pass"
95
+ : "unverifiable";
96
+ const lines: string[] = [];
97
+ for (const line of [...v.reasons, ...(v.caveats ?? []), ...(v.notes ?? [])]) {
98
+ const text = neutralizeDirectives(scrubText(line)).trim();
99
+ if (text !== "" && !lines.includes(text)) lines.push(text);
100
+ }
101
+ if (verdict === "unverifiable" && outcome === "pass" && !res.accepted && v.skipped !== true) {
102
+ lines.push("the pass carries caveats and enforcement.verify.strictUnverifiable rejects it");
103
+ }
104
+ let findings = lines.join("\n");
105
+ if (findings.length > PLAN_TASK_FINDINGS_MAX) findings = `${findings.slice(0, PLAN_TASK_FINDINGS_MAX - 1)}…`;
106
+ const ref = v.grader !== undefined ? `${v.method}:${v.grader.tier}` : v.method;
107
+ return { verdict, findings, ref };
108
+ }
109
+
110
+ /** `plan:<orchestratorSessionID>:<planId>/<taskId>#<n>`: the change-store and perimeter id of one plan-task attempt. */
111
+ export function planTaskVerificationID(orchestratorSessionID: string, planId: string, taskId: string, attempt: number): string {
112
+ return `plan:${orchestratorSessionID}:${planId}/${taskId}#${attempt}`;
113
+ }
114
+
115
+ /** Whether `id` is a plan-task verification id (A-5.1-12). */
116
+ export function isPlanTaskVerificationID(id: string): boolean {
117
+ return PLAN_TASK_PERIMETER_ID.test(id);
118
+ }
119
+
120
+ /**
121
+ * D11: during a plan-task gate, the task's own lease holders (its child and `plan:<plan>:<task>`) are excluded from the
122
+ * testsPass lease wait for that slot tree only. index.ts's `leaseGate` wrapper reads this registry; holders of other plans,
123
+ * and every holder of any other tree, are still waited for.
124
+ */
125
+ export interface LeaseSelfExemptions {
126
+ /** Exempts `holders` for the tree `root` until the returned release is called (idempotent). */
127
+ exempt(root: string, holders: readonly string[]): () => void;
128
+ /** The holders currently exempt for exactly the tree `root`; empty for any other tree. */
129
+ exemptFor(root: string): ReadonlySet<string>;
130
+ }
131
+
132
+ /** The comparison key of a tree path: resolved, no trailing separator, case-folded on Windows (git reports `D:/x`, the pool `D:\x`). */
133
+ export function planTreeKey(root: string, platform: NodeJS.Platform = process.platform): string {
134
+ const resolved = (platform === "win32" ? win32.resolve(root) : posix.resolve(root)).replace(/[\\/]+$/, "");
135
+ return platform === "win32" ? resolved.toLowerCase() : resolved;
136
+ }
137
+
138
+ /** `keyOf` canonicalizes a tree path (index.ts: `planTreeKey`). */
139
+ export function createLeaseSelfExemptions(keyOf: (root: string) => string): LeaseSelfExemptions {
140
+ const byRoot = new Map<string, Map<symbol, readonly string[]>>();
141
+ const empty: ReadonlySet<string> = new Set<string>();
142
+ return {
143
+ exempt(root, holders) {
144
+ const key = keyOf(root);
145
+ const token = Symbol("plan-task gate");
146
+ const entries = byRoot.get(key) ?? new Map<symbol, readonly string[]>();
147
+ entries.set(token, holders.filter((holder) => holder !== ""));
148
+ byRoot.set(key, entries);
149
+ return () => {
150
+ const current = byRoot.get(key);
151
+ if (current === undefined) return;
152
+ current.delete(token);
153
+ if (current.size === 0) byRoot.delete(key);
154
+ };
155
+ },
156
+ exemptFor(root) {
157
+ const entries = byRoot.get(keyOf(root));
158
+ if (entries === undefined) return empty;
159
+ return new Set([...entries.values()].flat());
160
+ },
161
+ };
162
+ }
163
+
164
+ /** The DoD of a plan task: its child-checkable acceptance, else the dispatch DoD inference over its text (A-5.1-4). */
165
+ export function planTaskDoD(task: Pick<TaskNode, "text" | "acceptance" | "title">): DoD {
166
+ const acceptance = task.acceptance !== null && task.acceptance.trim() !== ""
167
+ ? (/\[acceptance\]/i.test(task.acceptance) ? task.acceptance : `[acceptance]\n${task.acceptance}\n[/acceptance]`)
168
+ : undefined;
169
+ const dod = buildDelegationDoD({ prompt: task.text, description: task.title, ...(acceptance !== undefined ? { acceptance } : {}) });
170
+ const criteria = dod.criteria.flatMap((line) => {
171
+ const { kept } = stripOrchestratorShell(line);
172
+ return kept === null ? [] : [kept];
173
+ });
174
+ const stripped = normalizeDoD({ ...dod, criteria });
175
+ if (stripped.criteria.length > 0 || stripped.checks.length > 0) return stripped;
176
+ // An empty child-checkable block is not a free pass. Remove embedded blocks too so inference cannot parse
177
+ // the same shell-only block again; judge the dispatch exactly as a task with no acceptance block.
178
+ const prompt = task.text.replace(/^\s*\[(acceptance|dod)\]\s*\r?\n[\s\S]*?^\s*\[\/\1\]\s*$/gim, "").trim();
179
+ return buildDelegationDoD({ prompt, description: task.title });
180
+ }
181
+
182
+ /** The router's hardened git argv (no hooks, no user config side effects), run in `cwd`. */
183
+ export function planTaskGit(): PlanTaskGit {
184
+ return async (args, cwd, timeoutMs) => {
185
+ const result = await createGitRunner({ mode: "hardened", toplevel: cwd }).run([...hardeningArgs(), ...args], { cwd, timeoutMs });
186
+ return { code: result.code, stdout: result.stdout, stderr: result.stderr };
187
+ };
188
+ }
189
+
190
+ /** QA-5.1-4: the reason of every verification cut by `dispose`. */
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. */
193
+ export const PLAN_TASK_ABORT_MS = 5_000;
194
+
195
+ /** QA-5.1-4: a wait cut by the verifier's `dispose`. */
196
+ class PlanTaskShutdownError extends Error {
197
+ constructor() {
198
+ super(PLAN_TASK_SHUTDOWN_REASON);
199
+ this.name = "PlanTaskShutdownError";
200
+ }
201
+ }
202
+
203
+ /** A-5.1-9: the checks pass deadline. */
204
+ export function planTaskChecksBudgetMs(gateBudgetMs: number): number {
205
+ return Math.max(gateBudgetMs, PLAN_TASK_CHECKS_MIN_MS);
206
+ }
207
+
208
+ /** A-5.1-9: the grader pass deadline. */
209
+ export function planTaskGraderBudgetMs(gateBudgetMs: number, graderTier: string, override?: number): number {
210
+ return Math.max(gateBudgetMs, graderTimeoutMs(graderTier, override) + PLAN_TASK_GRADER_SLACK_MS);
211
+ }
212
+
213
+ /** The grader ladder buildGateDeps hands the checker. */
214
+ const GRADER_LADDER = ["fast", "medium", "heavy"];
215
+
216
+ /**
217
+ * The artefact's `producerTier` of a plan task: its role agent's name, as a role dispatch names its `subagent_type`. A role
218
+ * producer is not on the grader ladder, so it ranks unknown and the grader is the top tier (checker.ts tierRank); the routed
219
+ * tier would lower the grader. An unresolvable role keeps its role name (also unknown to the ladder).
220
+ */
221
+ export function planTaskProducerTier(task: Pick<TaskNode, "route">, cfg: RouterConfig): string {
222
+ try {
223
+ const role = resolveRoles(cfg, "v2").get(task.route.role);
224
+ if (role !== undefined && role.agent !== "") return role.agent;
225
+ } catch {
226
+ // The role name stands in.
227
+ }
228
+ return task.route.role;
229
+ }
230
+
231
+ /** The tier the checker grades a plan task on (checker.ts atLeastProducerTier: never below the producer or minGraderTier). */
232
+ export function graderTierFor(producerTier: string, cfg: RouterConfig): string {
233
+ return atLeastProducerTier(producerTier, { ladder: GRADER_LADDER, minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null });
234
+ }
235
+
236
+ /** A-5.1-9: a transient unverifiable, re-run internally (never a fail, never a pass). */
237
+ export function isTransientPlanTaskResult(res: GateResult, cut = false): boolean {
238
+ const v = res.verdict;
239
+ if ((v.outcome ?? (v.pass ? "pass" : "fail")) !== "unverifiable" || v.skipped === true) return false;
240
+ return isRetryableVerdict(v, cut) || [...v.reasons, ...(v.caveats ?? [])].some((reason) => reason.startsWith("grader dispatch failed:"));
241
+ }
242
+
243
+ /** D9: two passes of a mixed block combine to the stricter result; a pass needs both. */
244
+ export function combineMixedPasses(checks: GateResult, grader: GateResult): GateResult {
245
+ // A skipped pass judged nothing: never a fail (gate.ts skips carry no outcome), never a pass.
246
+ const outcome = (r: GateResult): string => r.verdict.skipped === true ? "unverifiable" : r.verdict.outcome ?? (r.verdict.pass ? "pass" : "fail");
247
+ if (outcome(checks) === "fail" || checks.verdict.skipped === true) return checks;
248
+ if (outcome(grader) === "fail") return grader;
249
+ const reasons = [...checks.verdict.reasons, ...grader.verdict.reasons];
250
+ const caveats = [...(checks.verdict.caveats ?? []), ...(grader.verdict.caveats ?? [])];
251
+ const notes = [...(checks.verdict.notes ?? []), ...(grader.verdict.notes ?? [])];
252
+ const passed = outcome(checks) === "pass" && outcome(grader) === "pass";
253
+ const verdict: GateResult["verdict"] = {
254
+ ...grader.verdict,
255
+ pass: passed,
256
+ outcome: passed ? "pass" : "unverifiable",
257
+ reasons,
258
+ ...(caveats.length > 0 ? { caveats } : {}),
259
+ ...(notes.length > 0 ? { notes } : {}),
260
+ ...(grader.verdict.skipped === true ? { skipped: true } : {}),
261
+ };
262
+ return { accepted: checks.accepted && grader.accepted, verdict, dodSource: checks.dodSource };
263
+ }
264
+
265
+ /** One attempt's observation state (begin, then observe before the router's commit). */
266
+ interface AttemptRecord {
267
+ readonly id: string;
268
+ readonly planId: string;
269
+ readonly taskId: string;
270
+ readonly n: number;
271
+ readonly orchestratorSessionID: string;
272
+ readonly base: string;
273
+ readonly slotPath: string;
274
+ readonly dod: DoD;
275
+ readonly startedAt: number;
276
+ observed?: Promise<{ ok: true; prepared: PreparedVerification } | { ok: false; reason: string }>;
277
+ }
278
+
279
+ const GIT_MS = 30_000;
280
+
281
+ /** D8: the plan-task verifier over one plugin instance's dispatch verification engine. */
282
+ export function createPlanTaskVerifier(deps: PlanTaskVerifierDeps): PlanTaskVerifier {
283
+ const records = new Map<string, AttemptRecord>();
284
+ /** The child's final text `observe` received per attempt (the latest non-empty one); independent of a begin record. */
285
+ const finalTexts = new Map<string, string>();
286
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => { const t = setTimeout(resolve, ms); t.unref?.(); }));
287
+ const now = deps.now ?? Date.now;
288
+ const keyOf = (planId: string, taskId: string, n: number): string => `${planId}/${taskId}#${n}`;
289
+ const warn = (message: string, detail?: unknown): void => { try { deps.log?.(message, detail); } catch { /* logging never fails a gate */ } };
290
+ const git = async (args: readonly string[], cwd: string): Promise<{ code: number | null; stdout: string; stderr: string }> => {
291
+ try { return await deps.git(args, cwd, GIT_MS); }
292
+ catch (error) { return { code: null, stdout: "", stderr: error instanceof Error ? error.message : String(error) }; }
293
+ };
294
+ const revParse = async (rev: string, cwd: string): Promise<string | null> => {
295
+ const r = await git(["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], cwd);
296
+ const sha = r.stdout.trim();
297
+ return r.code === 0 && /^[0-9a-f]{7,64}$/i.test(sha) ? sha : null;
298
+ };
299
+ const clearIds = (id: string, child: string | null): void => {
300
+ try { if (child !== null && child !== "") deps.changedFileStore.clear(child); } catch { /* best effort */ }
301
+ try { deps.changedFileStore.clear(id); } catch { /* best effort */ }
302
+ };
303
+ /** QA-5.1-6/-14: the plan's orchestrator as the runtime read it from its ledger for this call; "" when unknown. */
304
+ const orchestrator = (ctx: PlanTaskContext | undefined): string => {
305
+ const id: unknown = ctx?.orchestratorSessionID;
306
+ return typeof id === "string" ? id : "";
307
+ };
308
+ // QA-5.1-4: dispose cuts every in-flight deadline (prepare and gate passes), grader session and backoff sleep.
309
+ let disposing = false;
310
+ const shutdown = new AbortController();
311
+ const live = new Set<{ deadline: ReturnType<typeof createDeadline>; graders: ReadonlySet<string> }>();
312
+ /** Races `work` against dispose: rejects with PlanTaskShutdownError once dispose is called (already called: at once). */
313
+ const untilStopped = async <T>(work: Promise<T>, signal?: AbortSignal): Promise<T> => {
314
+ let onAbort = (): void => {};
315
+ const stop = new Promise<never>((_resolve, reject) => {
316
+ onAbort = () => reject(new PlanTaskShutdownError());
317
+ if (shutdown.signal.aborted || signal?.aborted) onAbort();
318
+ else {
319
+ shutdown.signal.addEventListener("abort", onAbort, { once: true });
320
+ signal?.addEventListener("abort", onAbort, { once: true });
321
+ }
322
+ });
323
+ try {
324
+ return await Promise.race([work, stop]);
325
+ } finally {
326
+ shutdown.signal.removeEventListener("abort", onAbort);
327
+ signal?.removeEventListener("abort", onAbort);
328
+ }
329
+ };
330
+ const unverifiable = (reason: string, dod?: DoD): { verdict: SlotVerdict; findings: string; ref: string } =>
331
+ slotVerdictOf(unverifiableGateResult(reason, dod?.source ?? "inferred", false));
332
+ /** QA-5.1-21: a verification dispose cut before it decided anything; the runtime discards it (never journaled). */
333
+ const cutVerdict = (dod?: DoD): PlanTaskVerdict => ({ ...unverifiable(PLAN_TASK_SHUTDOWN_REASON, dod), cut: true });
334
+ /** The wiring's own planning rule (A-5.1-12) under the current config; a planning error counts as planned (fail closed). */
335
+ const perimeterWouldBePlanned = (id: string, slotPath: string): boolean => {
336
+ try {
337
+ return planPerimeter(id, slotPath, () => {
338
+ const routing = resolveRolesRouting(deps.getConfig(), "v2");
339
+ return { parents: routing.repoParents, depth: routing.repoDepth, exclude: routing.repoExclude };
340
+ }) !== undefined;
341
+ } catch {
342
+ return true;
343
+ }
344
+ };
345
+
346
+ async function prepare(record: AttemptRecord, attempt: Attempt, restoredHead?: Parameters<VerificationWiring["prepareVerification"]>[6], signal?: AbortSignal): Promise<{ ok: true; prepared: PreparedVerification } | { ok: false; reason: string }> {
347
+ const deadline = createDeadline(resolveVerifyBudget(deps.getConfig()).gateBudgetMs);
348
+ const entry = { deadline, graders: new Set<string>() };
349
+ live.add(entry);
350
+ const abort = (): void => deadline.abort(PLAN_TASK_SHUTDOWN_REASON);
351
+ signal?.addEventListener("abort", abort, { once: true });
352
+ if (disposing || signal?.aborted) abort();
353
+ try {
354
+ const prepared = await untilStopped(deps.prepareVerification(
355
+ deps.changedFileStore, record.id, attempt.childSessionID ?? "", record.slotPath, deadline, record.startedAt, restoredHead,
356
+ record.orchestratorSessionID, () => ({ source: "plan-task-change", callID: attempt.callID ?? record.id }),
357
+ () => ({ planId: record.planId, taskId: record.taskId, attempt: record.n, phaseId: null, entryId: null,
358
+ taskIds: [record.taskId], component: "verify", candidate: restoredHead?.head ?? null }),
359
+ ), signal);
360
+ return { ok: true, prepared };
361
+ } catch (error) {
362
+ return { ok: false, reason: `the change observation failed: ${scrubText(error instanceof Error ? error.message : String(error))}` };
363
+ } finally {
364
+ live.delete(entry);
365
+ signal?.removeEventListener("abort", abort);
366
+ deadline.dispose();
367
+ }
368
+ }
369
+
370
+ async function begin(task: TaskNode, slot: SlotLease, attempt: Attempt, ctx?: PlanTaskContext): Promise<void> {
371
+ const key = keyOf(slot.planId, task.id, attempt.n);
372
+ const stale = records.get(key);
373
+ if (stale !== undefined) clearIds(stale.id, null);
374
+ records.delete(key);
375
+ finalTexts.delete(key);
376
+ // Never rejects: the runtime launches right after begin, and a missing record only means verify's fail-closed fallback.
377
+ try {
378
+ // The change-store and perimeter id of the attempt names the orchestrator at begin; verify reads the current one.
379
+ const orchestratorSessionID = orchestrator(ctx);
380
+ const id = planTaskVerificationID(orchestratorSessionID, slot.planId, task.id, attempt.n);
381
+ const dod = planTaskDoD(task);
382
+ const base = (await revParse("HEAD", slot.path)) ?? slot.commit;
383
+ const startedAt = now();
384
+ const record: AttemptRecord = { id, planId: slot.planId, taskId: task.id, n: attempt.n, orchestratorSessionID, base, slotPath: slot.path, dod, startedAt };
385
+ records.set(key, record);
386
+ // Reference capture under captureDepsFor's rules (wiring); bounded; never rejects.
387
+ await deps.beginVerificationBounded(deps.changedFileStore, id, slot.path, dod);
388
+ } catch (error) {
389
+ records.delete(key);
390
+ warn("plan-task verification could not begin; the attempt is verified fail closed", error);
391
+ }
392
+ }
393
+
394
+ async function observe(task: TaskNode, slot: SlotLease, attempt: Attempt, finalText?: string, ctx?: PlanTaskContext): Promise<void> {
395
+ const key = keyOf(slot.planId, task.id, attempt.n);
396
+ // The child's claim is kept even without a begin record: verify's restart fallback grades it too.
397
+ if (finalText !== undefined && finalText.trim() !== "") finalTexts.set(key, finalText);
398
+ const record = records.get(key);
399
+ // No begin record (a restart): verify takes the fail-closed fallback.
400
+ if (record === undefined || record.observed !== undefined) return;
401
+ // The cached observation is process-wide (it outlives an attachment): only its WAIT is bound to the attachment, never
402
+ // the observation itself, so an attachment cut cannot cache a failed observation that the next attachment would grade.
403
+ record.observed = prepare(record, attempt);
404
+ // QA-5.1-4: dispose never waits for an observation (its deadline is aborted; verify then cuts).
405
+ try { await untilStopped(record.observed, ctx?.signal); } catch { /* cut by dispose or attachment change */ }
406
+ }
407
+
408
+ async function forget(planId: string, taskId: string, n: number): Promise<void> {
409
+ const key = keyOf(planId, taskId, n);
410
+ const record = records.get(key);
411
+ records.delete(key);
412
+ finalTexts.delete(key);
413
+ if (record !== undefined) clearIds(record.id, null);
414
+ }
415
+
416
+ /** D8 pre-checks and the change set between base and candidate. */
417
+ async function candidateOf(task: TaskNode, slotPath: string, base: string): Promise<{ ok: true; candidate: string } | { ok: false; reason: string }> {
418
+ if (task.branch === null) return { ok: false, reason: `task ${task.id} has no branch; the router's commit cannot be verified` };
419
+ const head = await git(["symbolic-ref", "--quiet", "HEAD"], slotPath);
420
+ if (head.code !== 0 || head.stdout.trim() !== `refs/heads/${task.branch}`) {
421
+ return { ok: false, reason: `the slot ${slotPath} is not on the task branch ${task.branch}; nothing ran` };
422
+ }
423
+ const candidate = await revParse("HEAD", slotPath);
424
+ if (candidate === null) return { ok: false, reason: `the slot ${slotPath} has no readable HEAD; nothing ran` };
425
+ const ancestor = await git(["merge-base", "--is-ancestor", base, candidate], slotPath);
426
+ if (ancestor.code !== 0) return { ok: false, reason: `the slot reset commit ${base} is not an ancestor of ${candidate}; nothing ran` };
427
+ return { ok: true, candidate };
428
+ }
429
+
430
+ async function committedFiles(slotPath: string, root: string, base: string, candidate: string): Promise<PreparedVerification["changedFiles"] | undefined> {
431
+ const diff = await git(["diff", "--name-status", "-z", "-M", base, candidate, "--"], slotPath);
432
+ if (diff.code !== 0) return undefined;
433
+ return parseNameStatusZ(diff.stdout, root);
434
+ }
435
+
436
+ /** The restart fallback (no begin/observe record): fail closed, never a weaker gate. */
437
+ async function fallback(task: TaskNode, slot: SlotLease, attempt: Attempt, orchestratorSessionID: string, signal?: AbortSignal): Promise<{ ok: true; record: AttemptRecord; prepared: PreparedVerification; trusted: false } | { ok: false; reason: string; dod: DoD }> {
438
+ const dod = planTaskDoD(task);
439
+ const id = planTaskVerificationID(orchestratorSessionID, slot.planId, task.id, attempt.n);
440
+ const head = await revParse("HEAD", slot.path);
441
+ if (head === null) return { ok: false, reason: `the slot ${slot.path} has no readable HEAD after a restart; nothing ran`, dod };
442
+ // 1. The attempt trailer: the router's own commit of this attempt (runtime D11) is HEAD.
443
+ const message = await git(["log", "-1", "--format=%B", head], slot.path);
444
+ const trailer = message.code === 0 && attempt.nonce !== "" && message.stdout.includes(attempt.nonce);
445
+ // 2. HEAD^1 == base: the router's commit sits directly on the reset commit, so the child committed nothing of its own.
446
+ const base = slot.commit;
447
+ const preCommit = trailer ? await revParse(`${head}^1`, slot.path) : head;
448
+ if (preCommit === null || preCommit !== base) {
449
+ return { ok: false, reason: `the attempt's observation was lost in a restart and the slot holds commits other than the router's (${preCommit ?? "unknown"} is not the reset commit ${base}); unverifiable`, dod };
450
+ }
451
+ // 3. Otherwise the restored head: the tree as the router left it is the dispatch-time head (the router's own switch is no switch).
452
+ const top = await git(["rev-parse", "--show-toplevel"], slot.path);
453
+ let root = slot.path;
454
+ try { if (top.code === 0 && top.stdout.trim() !== "") root = realpathSync.native(top.stdout.trim()); } catch { /* the slot path stands in */ }
455
+ const restoredHead: HeadState = { root, head, branch: task.branch };
456
+ const record: AttemptRecord = { id, planId: slot.planId, taskId: task.id, n: attempt.n, orchestratorSessionID, base, slotPath: slot.path, dod, startedAt: Date.parse(attempt.startedAt) || now() };
457
+ if (await (deps.perimeterPlanned ?? perimeterWouldBePlanned)(id, slot.path)) {
458
+ return { ok: false, reason: "the attempt's observation was lost in a restart and its perimeter would be planned; the other repositories cannot be judged; unverifiable", dod };
459
+ }
460
+ const observed = await prepare(record, attempt, restoredHead, signal);
461
+ if (!observed.ok) return { ok: false, reason: observed.reason, dod };
462
+ if (observed.prepared.perimeter !== undefined && observed.prepared.perimeter.roots.length > 0) {
463
+ return { ok: false, reason: "the attempt's observation was lost in a restart and its perimeter would be planned; the other repositories cannot be judged; unverifiable", dod };
464
+ }
465
+ // The observed files are lost; the commit diff (unioned by verify) is the whole change of a single router commit.
466
+ return { ok: true, record, prepared: { ...observed.prepared, changedFiles: [], changeBaseline: "available" }, trusted: false };
467
+ }
468
+
469
+ async function runPass(
470
+ passDoD: DoD, budgetMs: number, record: AttemptRecord, task: TaskNode, slot: SlotLease, attempt: Attempt,
471
+ artefact: Artefact, prepared: PreparedVerification, parent: string, signal?: AbortSignal,
472
+ ): Promise<{ res: GateResult; cut: boolean }> {
473
+ // Bind this pass's wait to its attachment as well as plugin shutdown; the gate remains directly awaited.
474
+ const untilShutdown = <T>(work: Promise<T>): Promise<T> => untilStopped(work, signal);
475
+ const cfg = deps.getConfig();
476
+ const strict = cfg.enforcement?.verify?.strictUnverifiable;
477
+ const scope = verificationScope(passDoD.cwd, slot.path);
478
+ const placement = resolveCheckPlacements(passDoD, scope, {});
479
+ const deadline = createDeadline(budgetMs);
480
+ const graders = new Set<string>();
481
+ const entry = { deadline, graders };
482
+ live.add(entry);
483
+ const abort = (): void => deadline.abort(PLAN_TASK_SHUTDOWN_REASON);
484
+ signal?.addEventListener("abort", abort, { once: true });
485
+ const completedFailures: string[] = [];
486
+ const child = attempt.childSessionID ?? "";
487
+ const tree = prepared.snapshot?.root ?? slot.path;
488
+ const releases = [tree, slot.path].map((root) => deps.exemptions.exempt(root, [child, leaseHolderID(record.planId, task.id)]));
489
+ try {
490
+ // QA-5.1-14: the grader is parented to the plan's CURRENT orchestrator, as the runtime read it for this verify (an
491
+ // adopt moves the plan; verify refused an unknown one before any gate ran).
492
+ // The verify service observer rides on `prepared.service`, bound to this attempt's checked candidate.
493
+ const gateDeps = deps.buildGateDeps(parent, graders, prepared, deadline, false, parent);
494
+ gateDeps.deterministic.onFailure = (reason) => completedFailures.push(reason);
495
+ const delegation: Delegation = {
496
+ dod: passDoD,
497
+ trivial: false,
498
+ mode: "modeA",
499
+ ...(scope.requested ? { cwd: scope.requested } : {}),
500
+ ...(scope.workRoot !== undefined ? { workRoot: scope.workRoot } : {}),
501
+ ...(scope.refused !== undefined ? { refusedCwd: scope.refused, cwdSource: "acceptance" as const } : {}),
502
+ ...(placement.placements !== undefined ? { checkPlacements: placement.placements } : {}),
503
+ ...(placement.refused !== undefined ? { refusedCheck: placement.refused } : {}),
504
+ };
505
+ 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 };
508
+ } 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
+ }
521
+ return {
522
+ res: unverifiableGateResult(
523
+ timedOut ? `verification gate timed out after ${budgetMs}ms` : `verification unavailable: ${scrubText(String(error))}`,
524
+ passDoD.source, strict, completedFailures,
525
+ ),
526
+ cut: timedOut,
527
+ };
528
+ } finally {
529
+ live.delete(entry);
530
+ signal?.removeEventListener("abort", abort);
531
+ deadline.dispose();
532
+ for (const release of releases) release();
533
+ }
534
+ }
535
+
536
+ async function verifyWithAttachment(signal: AbortSignal | undefined, task: TaskNode, slot: SlotLease, attempt: Attempt, parent: string,
537
+ onDecided: (decided: PlanTaskVerdict) => void): Promise<PlanTaskVerdict> {
538
+ const untilShutdown = <T>(work: Promise<T>): Promise<T> => untilStopped(work, signal);
539
+ const key = keyOf(slot.planId, task.id, attempt.n);
540
+ let record = records.get(key);
541
+ let prepared: PreparedVerification;
542
+ try {
543
+ if (record?.observed !== undefined) {
544
+ const observed = await untilShutdown(record.observed);
545
+ if (!observed.ok) return unverifiable(observed.reason, record.dod);
546
+ prepared = observed.prepared;
547
+ } else {
548
+ const restored = await fallback(task, slot, attempt, parent, signal);
549
+ if (!restored.ok) return unverifiable(restored.reason, restored.dod);
550
+ record = restored.record;
551
+ prepared = restored.prepared;
552
+ }
553
+ // Fail closed: without the plan's orchestrator the id names no working set, so the perimeter could not be planned; and
554
+ // without its current orchestrator the grader has no parent.
555
+ if (record.orchestratorSessionID === "" || parent === "") return unverifiable(`the orchestrator of plan ${record.planId} could not be read; nothing ran`, record.dod);
556
+ const checked = await candidateOf(task, slot.path, record.base);
557
+ if (!checked.ok) return unverifiable(checked.reason, record.dod);
558
+ const cfg = deps.getConfig();
559
+ const budget = resolveVerifyBudget(cfg);
560
+ if (disposing || signal?.aborted) return cutVerdict(record.dod);
561
+ // A fresh snapshot after cleanForChecks: the tree the checks run on (materialize's drift check, the lease wait's tree).
562
+ const controller = new AbortController();
563
+ let fresh: PreparedVerification["snapshot"];
564
+ let snapshotReason: string | undefined;
565
+ const preparation = prepared.service?.start("service-prep", "slot-snapshot", checked.candidate);
566
+ try {
567
+ fresh = await withTimeout(snapshotTree(slot.path, AbortSignal.any([controller.signal, ...(signal === undefined ? [] : [signal])]), {
568
+ lowPriority: budget.lowPriority,
569
+ onError: (reason) => { snapshotReason = reason; },
570
+ }), GIT_MS, "slot snapshot");
571
+ preparation?.end("completed");
572
+ } catch (error) {
573
+ snapshotReason = error instanceof Error ? error.message : String(error);
574
+ fresh = undefined;
575
+ } finally {
576
+ preparation?.end("error");
577
+ controller.abort();
578
+ }
579
+ if (fresh === undefined) {
580
+ const reason = snapshotReason === undefined ? "" : ` (${scrubText(snapshotReason).replace(/\s+/g, " ").trim().slice(0, 200)})`;
581
+ return unverifiable(`the slot ${slot.path} could not be snapshotted after cleanForChecks${reason}; nothing ran`, record.dod);
582
+ }
583
+ const root = fresh.root ?? prepared.snapshot?.root ?? slot.path;
584
+ const committed = await committedFiles(slot.path, root, record.base, checked.candidate);
585
+ if (committed === undefined) return unverifiable(`the change between ${record.base} and ${checked.candidate} could not be read; nothing ran`, record.dod);
586
+ const seen = new Set<string>();
587
+ const changedFiles: PreparedVerification["changedFiles"] = [];
588
+ for (const file of [...prepared.changedFiles, ...committed]) {
589
+ const k = planTreeKey(isAbsolute(file.path) ? file.path : resolve(root, file.path));
590
+ if (seen.has(k)) continue;
591
+ seen.add(k);
592
+ changedFiles.push(file);
593
+ }
594
+ const service = prepared.service;
595
+ const boundService: PreparedVerification["service"] = service === undefined ? undefined : {
596
+ start: (kind, stage, candidate = checked.candidate) => service.start(kind, stage, candidate),
597
+ execution: (stage, candidate = checked.candidate) => service.execution(stage, candidate),
598
+ };
599
+ const gatePrepared: PreparedVerification = {
600
+ ...prepared,
601
+ graderDispatchLabel: `${task.id}#${attempt.n}`,
602
+ ...(boundService === undefined ? {} : { service: boundService }),
603
+ changedFiles,
604
+ // The union is complete: the observed files and every path the candidate commits over the reset commit.
605
+ changeBaseline: prepared.branchSwitch !== undefined ? "unavailable" : "available",
606
+ snapshot: fresh,
607
+ };
608
+ const child = attempt.childSessionID ?? "";
609
+ const producerTier = planTaskProducerTier(task, cfg);
610
+ const childText = finalTexts.get(key);
611
+ // QA-5.1-3: the child's own final text is held to the return contract, as a role dispatch's is (a progress note is
612
+ // incomplete, never graded to a pass); the router's commit description is not a child return.
613
+ const fromChild = childText !== undefined && planTaskReturnText(childText, "") !== "";
614
+ const artefact: Artefact = {
615
+ changedFiles: gatePrepared.changedFiles,
616
+ changeBaseline: gatePrepared.changeBaseline,
617
+ changeRoot: root,
618
+ ...(prepared.branchSwitch !== undefined ? { branchSwitch: prepared.branchSwitch } : {}),
619
+ ...(prepared.unattributedWriters !== undefined && prepared.unattributedWriters.length > 0 ? { unattributedWriters: prepared.unattributedWriters } : {}),
620
+ ...(prepared.perimeter !== undefined ? { perimeter: prepared.perimeter } : {}),
621
+ // Phase 5.1 (a): the grader judges the child's own claim, as a dispatch grader does; the commit description otherwise.
622
+ finalReturnText: planTaskReturnText(childText,
623
+ `plan task ${task.id} attempt ${attempt.n}: the router committed the slot's change as ${checked.candidate} over ${record.base}`),
624
+ ...(fromChild ? { returnContract: true } : {}),
625
+ declaredOutputs: record.dod.deliverable ? [record.dod.deliverable] : [],
626
+ producerSessionID: child,
627
+ producerTier,
628
+ ...(child !== "" ? (() => { const b = deps.captureBudget(child, deps.readCapReached(child)); return b === undefined ? {} : { budget: b }; })() : {}),
629
+ };
630
+ const override = cfg.enforcement?.verify?.graderTimeoutMs;
631
+ const graderTier = graderTierFor(producerTier, cfg);
632
+ let reruns = 0;
633
+ const current = record;
634
+ const withReruns = async (passDoD: DoD, budgetMs: number): Promise<GateResult> => {
635
+ for (;;) {
636
+ const { res, cut } = await runPass(passDoD, budgetMs, current, task, slot, attempt, artefact, gatePrepared, parent, signal);
637
+ if (signal?.aborted) return res;
638
+ if (disposing || !isTransientPlanTaskResult(res, cut) || reruns >= PLAN_TASK_TRANSIENT_RERUNS) return res;
639
+ const reason = scrubText([...new Set([...res.verdict.reasons, ...(res.verdict.caveats ?? [])])].join("; "))
640
+ .replace(/\s+/g, " ").trim().slice(0, 200);
641
+ const label = scrubText(`${task.id}#${attempt.n}`).replace(/\s+/g, " ").trim().slice(0, 200);
642
+ warn(`plan-task verification retry ${reruns + 1} for ${label}: ${reason}`);
643
+ // QA-5.1-4: dispose cancels the backoff (the transient result stands; verify already resolved as cut).
644
+ const backoff = prepared.service?.start("service-wait", "retry-backoff", checked.candidate);
645
+ let interrupted = true;
646
+ try {
647
+ try { await untilShutdown(sleep(PLAN_TASK_RERUN_BACKOFF_MS[reruns])); } catch { return res; }
648
+ interrupted = false;
649
+ } finally { backoff?.end(interrupted ? "interrupted" : "completed"); }
650
+ reruns += 1;
651
+ }
652
+ };
653
+ const dod = record.dod;
654
+ let res: GateResult;
655
+ if (dod.kind === "deterministic" && dod.checks.length > 0) {
656
+ res = await withReruns(dod, planTaskChecksBudgetMs(budget.gateBudgetMs));
657
+ // D9: checks first; on a pass, the grader judges the criteria; a check fail dispatches no grader.
658
+ const outcome = res.verdict.outcome ?? (res.verdict.pass ? "pass" : "fail");
659
+ if (dod.criteria.length > 0 && outcome === "pass" && res.verdict.skipped !== true) {
660
+ const graded = await withReruns(normalizeDoD({ ...dod, checks: [] }), planTaskGraderBudgetMs(budget.gateBudgetMs, graderTier, override));
661
+ res = combineMixedPasses(res, graded);
662
+ }
663
+ } else {
664
+ res = await withReruns(dod, planTaskGraderBudgetMs(budget.gateBudgetMs, graderTier, override));
665
+ }
666
+ // QA-5.1-4: a gate cut by dispose judged nothing: no verdict reaches the outcome store.
667
+ // QA-5.1-21: it is marked as a cut, which the runtime discards; nothing below runs for it (no `onVerdict`).
668
+ if (disposing || signal?.aborted) return cutVerdict(record.dod);
669
+ // D10 (A-5.1-13): no R11 lineage. QA-3.1-2 / QA-3.1-3 caveats as on a dispatch.
670
+ res = applyDispatchCaveats(res, gatePrepared);
671
+ // QA-5.1-21: from here the verdict is decided: `verify` returns it even when dispose cuts its wait afterwards.
672
+ const decided = slotVerdictOf(res);
673
+ onDecided(decided);
674
+ if (child !== "" && res.verdict.skipped !== true) {
675
+ try { deps.onVerdict?.(child, res.verdict); } catch (error) { warn("plan-task verdict not ingested", error); }
676
+ }
677
+ return decided;
678
+ } catch (error) {
679
+ return unverifiable(`verification unavailable: ${scrubText(error instanceof Error ? error.message : String(error))}`, record?.dod);
680
+ } finally {
681
+ records.delete(key);
682
+ finalTexts.delete(key);
683
+ if (record !== undefined) clearIds(record.id, attempt.childSessionID);
684
+ }
685
+ }
686
+
687
+ /** QA-5.1-6/-14: the orchestrator is the one the runtime read for THIS call (the grader's parent after an adopt too). */
688
+ async function verify(task: TaskNode, slot: SlotLease, attempt: Attempt, ctx?: PlanTaskContext): Promise<PlanTaskVerdict> {
689
+ const cut = (): PlanTaskVerdict => cutVerdict(records.get(keyOf(slot.planId, task.id, attempt.n))?.dod);
690
+ if (disposing || ctx?.signal?.aborted) return cut();
691
+ // QA-5.1-21: a verdict decided before dispose cut the wait (and already handed to `onVerdict`) is returned, never a cut.
692
+ let decided: PlanTaskVerdict | null = null;
693
+ try {
694
+ // Attachment cuts are handled inside the pipeline, including bounded grader abort/cleanup, before a new
695
+ // attachment can verify this identity. Global dispose retains its prompt outer cut semantics.
696
+ const verifyNow = verifyWithAttachment.bind(undefined, ctx?.signal);
697
+ const result = await untilStopped(verifyNow(task, slot, attempt, orchestrator(ctx), (v) => { decided = v; }));
698
+ return ctx?.signal?.aborted && decided === null ? cut() : result;
699
+ } catch (error) {
700
+ if (error instanceof PlanTaskShutdownError) return decided ?? cut();
701
+ throw error;
702
+ }
703
+ }
704
+
705
+ /**
706
+ * QA-5.1-4: cuts every in-flight verification at once (synchronously, before the first await): each pending `verify` and
707
+ * `observe` resolves, every gate and observation deadline is aborted and every backoff sleep cancelled; then the grader
708
+ * sessions of the cut gates are aborted, each bounded by PLAN_TASK_ABORT_MS. Idempotent.
709
+ */
710
+ async function dispose(): Promise<void> {
711
+ if (disposing) return;
712
+ disposing = true;
713
+ shutdown.abort();
714
+ const sessions = new Set<string>();
715
+ for (const entry of live) {
716
+ entry.deadline.abort(PLAN_TASK_SHUTDOWN_REASON);
717
+ for (const sessionID of entry.graders) sessions.add(sessionID);
718
+ }
719
+ await Promise.allSettled([...sessions].map((sessionID) =>
720
+ withTimeout(deps.abortSession(sessionID), PLAN_TASK_ABORT_MS, "grader abort").catch((error: unknown) => {
721
+ warn("grader abort on dispose failed", error);
722
+ })));
723
+ }
724
+
725
+ return {
726
+ begin, observe, forget, verify, dispose,
727
+ get disposing() { return disposing; },
728
+ };
729
+ }