opencode-model-router 1.11.1 → 1.12.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.
@@ -1,7 +1,8 @@
1
1
  /**
2
- * src/verify/dispatch.ts — PURE helpers shared by both Layer-2 wirings
2
+ * src/verify/dispatch.ts — shared helpers and TTL-managed dispatch state
3
3
  * (Option (i) verify-dispatch around the built-in `task` tool, and Option (ii)
4
- * the plugin-owned `delegate` tool). No fs/network/SDK here; the live adapters
4
+ * the plugin-owned `delegate` tool). No fs/network/SDK here; bounded background
5
+ * work uses the shared timeout primitive, and the live adapters
5
6
  * (exec/fs/grader) are built in index.ts from PluginInput and injected.
6
7
  */
7
8
  import type { RouterConfig } from "../router/config";
@@ -9,6 +10,29 @@ import { getActiveTiers } from "../router/protocol";
9
10
  import { parseDoDFromDispatch, inferDoD } from "./dod";
10
11
  import type { DoD, InferHints } from "./dod";
11
12
  import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
13
+ import { resolve } from "node:path";
14
+ import type { ExecResult } from "./types";
15
+ import { observeTests, type TestBaseline } from "./baseline";
16
+ import { withTimeout } from "./timeout";
17
+
18
+ export interface TreeSnapshot {
19
+ cwd: string;
20
+ head: string;
21
+ fingerprint: string;
22
+ dirty: boolean;
23
+ files: ChangedFile[];
24
+ }
25
+
26
+ export interface BaselineCaptureDeps {
27
+ snapshot(cwd: string, signal: AbortSignal): Promise<TreeSnapshot | undefined>;
28
+ run(command: string, cwd: string, signal: AbortSignal): Promise<ExecResult>;
29
+ timeoutMs: number;
30
+ }
31
+
32
+ function pathKey(path: string): string {
33
+ const normalized = resolve(path).replace(/\\/g, "/");
34
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
35
+ }
12
36
 
13
37
  export interface ChangedFileStoreOptions {
14
38
  /** Injectable clock (tests). Defaults to Date.now. */
@@ -16,7 +40,10 @@ export interface ChangedFileStoreOptions {
16
40
  }
17
41
 
18
42
  /** Tools that mutate the workspace (mirrors the guard taxonomy). */
19
- const WRITE_TOOLS = new Set(["write", "edit", "patch", "multiedit"]);
43
+ const WRITE_TOOLS = new Set(["write", "edit", "patch", "multiedit", "apply_patch"]);
44
+ // Shell commands can edit too. Without a command-level proof of read-onlyness,
45
+ // discarding a capture is safer than allowing an unobserved shell edit to seed it.
46
+ const MAY_WRITE_TOOLS = new Set([...WRITE_TOOLS, "bash", "shell", "powershell", "exec"]);
20
47
 
21
48
  export interface ChangedFile {
22
49
  path: string;
@@ -49,6 +76,25 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
49
76
  const now = options.now ?? Date.now;
50
77
  const bySession = new Map<string, Map<string, string>>();
51
78
  const lastTouch = new Map<string, number>();
79
+ const dispatches = new Map<string, {
80
+ cwd: string; pending: boolean; contaminated: boolean;
81
+ snapshot?: TreeSnapshot;
82
+ ready: Promise<void>;
83
+ baselines: Map<string, Promise<TestBaseline | undefined>>;
84
+ }>();
85
+ const cache = new Map<string, {
86
+ cwd: string; pending: boolean; contaminated: boolean; stamp: number;
87
+ controller: AbortController; result: Promise<TestBaseline | undefined>;
88
+ }>();
89
+
90
+ function observeEdit(tool: string, cwd?: string): void {
91
+ if (!MAY_WRITE_TOOLS.has(tool.toLowerCase())) return;
92
+ // Unknown directory is conservatively treated as overlapping every capture.
93
+ const overlaps = (other: string) => !cwd || pathKey(cwd) === pathKey(other)
94
+ || pathKey(cwd).startsWith(pathKey(other) + "/") || pathKey(other).startsWith(pathKey(cwd) + "/");
95
+ for (const d of dispatches.values()) if (d.pending && overlaps(d.cwd)) d.contaminated = true;
96
+ for (const c of cache.values()) if (c.pending && overlaps(c.cwd)) c.contaminated = true;
97
+ }
52
98
 
53
99
  function touch(sessionID: string): void {
54
100
  lastTouch.set(sessionID, now());
@@ -57,11 +103,91 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
57
103
  function evict(sessionID: string): void {
58
104
  bySession.delete(sessionID);
59
105
  lastTouch.delete(sessionID);
106
+ dispatches.delete(sessionID);
60
107
  }
61
108
 
62
109
  return {
110
+ /** Non-blocking: fingerprint and test run are bounded background work. */
111
+ beginDispatch(id: string, cwd: string, commands: string[], deps: BaselineCaptureDeps): void {
112
+ touch(id);
113
+ bySession.delete(id);
114
+ const controller = new AbortController();
115
+ const d = {
116
+ cwd, pending: true, contaminated: false, snapshot: undefined as TreeSnapshot | undefined,
117
+ ready: Promise.resolve(), baselines: new Map<string, Promise<TestBaseline | undefined>>(),
118
+ };
119
+ dispatches.set(id, d);
120
+ d.ready = withTimeout(deps.snapshot(cwd, controller.signal), deps.timeoutMs, "dispatch fingerprint")
121
+ .then(snapshot => {
122
+ if (!snapshot || d.contaminated || dispatches.get(id) !== d) return;
123
+ d.snapshot = snapshot;
124
+ for (const command of new Set(commands)) {
125
+ const key = JSON.stringify([pathKey(snapshot.cwd), snapshot.head, snapshot.fingerprint, command]);
126
+ let entry = cache.get(key);
127
+ if (!entry) {
128
+ const capture = {
129
+ cwd, pending: true, contaminated: false, stamp: now(),
130
+ controller: new AbortController(), result: Promise.resolve<TestBaseline | undefined>(undefined),
131
+ };
132
+ cache.set(key, capture);
133
+ capture.result = withTimeout((async () => {
134
+ const result = await deps.run(command, cwd, capture.controller.signal);
135
+ if (result.timedOut || capture.contaminated) return undefined;
136
+ const end = await deps.snapshot(cwd, capture.controller.signal);
137
+ if (!end || capture.contaminated || end.head !== snapshot.head || end.fingerprint !== snapshot.fingerprint) return undefined;
138
+ return { observation: observeTests(result), dirty: snapshot.dirty };
139
+ })(), deps.timeoutMs, "test baseline")
140
+ .catch(() => undefined)
141
+ .then(result => {
142
+ capture.pending = false;
143
+ capture.controller.abort();
144
+ if (!result && cache.get(key) === capture) cache.delete(key);
145
+ return result;
146
+ });
147
+ entry = capture;
148
+ }
149
+ entry.stamp = now();
150
+ d.baselines.set(command, entry.result);
151
+ }
152
+ })
153
+ .catch(() => { /* Fingerprinting unavailable: retain explicit missing-snapshot state. */ })
154
+ .finally(() => { d.pending = false; controller.abort(); });
155
+ },
156
+ observeEdit,
157
+ async baseline(id: string, command: string, currentHead?: string): Promise<TestBaseline | undefined> {
158
+ const d = dispatches.get(id);
159
+ if (!d) return undefined;
160
+ touch(id);
161
+ await d.ready;
162
+ if (!currentHead || d.snapshot?.head !== currentHead) return undefined;
163
+ return d.baselines.get(command);
164
+ },
165
+ delta(id: string, childID: string, current?: TreeSnapshot, fallbackCwd?: string): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable" } {
166
+ const d = dispatches.get(id);
167
+ const snapshot = d?.snapshot;
168
+ const files = new Map<string, ChangedFile>();
169
+ for (const [path, status] of bySession.get(childID) ?? []) {
170
+ const base = d?.cwd ?? current?.cwd ?? fallbackCwd;
171
+ const absolute = base ? resolve(base, path) : path;
172
+ files.set(base ? pathKey(absolute) : path, { path: absolute, status });
173
+ }
174
+ const available = !!snapshot && !!current;
175
+ if (available) {
176
+ const before = new Set(snapshot.files.map(f => pathKey(f.path)));
177
+ for (const file of current.files) if (!before.has(pathKey(file.path))) files.set(pathKey(file.path), file);
178
+ }
179
+ return { changedFiles: [...files.values()], changeBaseline: available ? "available" : "unavailable" };
180
+ },
63
181
  record(sessionID: string, tool: string, args: unknown): void {
64
182
  touch(sessionID);
183
+ observeEdit(tool, dispatches.get(sessionID)?.cwd);
184
+ if (tool.toLowerCase() === "apply_patch") {
185
+ const a = args && typeof args === "object" ? args as Record<string, unknown> : {};
186
+ const patch = typeof a.patchText === "string" ? a.patchText : typeof a.patch === "string" ? a.patch : "";
187
+ const files = bySession.get(sessionID) ?? new Map<string, string>();
188
+ for (const match of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)) files.set(match[1].trim(), "modified");
189
+ bySession.set(sessionID, files);
190
+ }
65
191
  const cf = extractChangedFile(tool, args);
66
192
  if (!cf) return;
67
193
  let m = bySession.get(sessionID);
@@ -86,6 +212,12 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
86
212
  for (const [sessionID, stamp] of [...lastTouch.entries()]) {
87
213
  if (nowMs - stamp >= ttlMs) evict(sessionID);
88
214
  }
215
+ for (const [key, entry] of cache) {
216
+ if (nowMs - entry.stamp >= ttlMs) {
217
+ entry.controller.abort();
218
+ cache.delete(key);
219
+ }
220
+ }
89
221
  },
90
222
  };
91
223
  }
@@ -199,6 +331,8 @@ export function buildForcingNote(
199
331
  }
200
332
 
201
333
  /** Suffix appended to an accepted delegate-tool result. */
202
- export function buildAcceptedSuffix(method: string): string {
203
- return `\n\n[router \u2713 accepted: ${method}]`;
334
+ export function buildAcceptedSuffix(method: string, caveats: string[] = [], notes: string[] = []): string {
335
+ return `\n\n[router \u2713 accepted: ${method}]` + (caveats.length
336
+ ? `\nVerification caveats — NOT verified (acceptance is not a passing check):\n${caveats.map(r => `- ${r}`).join("\n")}`
337
+ : "") + (notes.length ? `\nVerification notes:\n${notes.map(r => `- ${r}`).join("\n")}` : "");
204
338
  }
@@ -9,7 +9,8 @@
9
9
  * so there is exactly ONE accept/verify code path (GA-5).
10
10
  *
11
11
  * Design invariants:
12
- * - FAIL-CLOSED: a verification error never yields acceptance.
12
+ * - The former "FAIL-CLOSED: a verification error never yields acceptance"
13
+ * policy is available via strictUnverifiable; default acceptance has caveats.
13
14
  * - NEVER silently accept a non-trivial delegation that has no checkable DoD.
14
15
  * - producer != grader and grader >= producer are enforced inside runChecker;
15
16
  * the gate never grades anything itself.
@@ -27,6 +28,7 @@ import { resolveBaseDir } from "./paths";
27
28
 
28
29
  /** The concrete, inspectable result of a delegation (artefact contract §3.3). */
29
30
  export interface Artefact {
31
+ changeBaseline?: "available" | "unavailable";
30
32
  changedFiles: { path: string; status: string }[];
31
33
  finalReturnText: string;
32
34
  declaredOutputs: string[];
@@ -59,6 +61,7 @@ export interface GateDeps {
59
61
  * checkable and apply the no-DoD policy otherwise.
60
62
  */
61
63
  require?: "never" | "whenDoDPresent" | "always";
64
+ strictUnverifiable?: boolean;
62
65
  }
63
66
 
64
67
  export interface GateResult {
@@ -68,18 +71,40 @@ export interface GateResult {
68
71
  dodSource: DoD["source"];
69
72
  }
70
73
 
74
+ export function gateResult(verdict: Verdict, dodSource: DoD["source"], strictUnverifiable = false): GateResult {
75
+ const outcome = verdict.outcome ?? (verdict.pass ? "pass" : "fail");
76
+ const caveats = verdict.caveats ?? (outcome === "unverifiable" ? verdict.reasons : []);
77
+ return {
78
+ accepted: outcome !== "fail" && !(strictUnverifiable && caveats.length > 0),
79
+ verdict: { ...verdict, outcome, ...(caveats.length ? { caveats } : {}) },
80
+ dodSource,
81
+ };
82
+ }
83
+
84
+ export function unverifiableGateResult(reason: string, dodSource: DoD["source"], strictUnverifiable = false, completedFailures: string[] = []): GateResult {
85
+ // An outer timeout must never erase a genuine failure already observed.
86
+ return gateResult({
87
+ pass: false,
88
+ outcome: completedFailures.length ? "fail" : "unverifiable",
89
+ method: "none",
90
+ reasons: [...completedFailures, reason],
91
+ caveats: [reason],
92
+ }, dodSource, strictUnverifiable);
93
+ }
94
+
71
95
  function view(artefact: Artefact): ArtefactView {
72
96
  return {
73
97
  finalReturnText: artefact.finalReturnText,
74
98
  changedFiles: artefact.changedFiles,
99
+ changeBaseline: artefact.changeBaseline,
75
100
  declaredOutputs: artefact.declaredOutputs,
76
101
  };
77
102
  }
78
103
 
79
104
  /**
80
105
  * Decide whether a delegation's artefact meets its DoD.
81
- * Returns { accepted, verdict, dodSource }; accepted is true ONLY when a
82
- * verifier returned pass===true (or the gate is explicitly disabled).
106
+ * Returns acceptance separately from successful verification: unavailable
107
+ * checks carry caveats and reject only under strictUnverifiable.
83
108
  */
84
109
  export async function accept(
85
110
  delegation: Delegation,
@@ -149,11 +174,8 @@ export async function accept(
149
174
  // Checkable DoD: dispatch on the normalized kind. normalizeDoD() guarantees
150
175
  // a checkable DoD is "deterministic" (when any checks exist) or "checker"
151
176
  // (criteria only), which realises verify.preferDeterministic at
152
- // DoD-construction time. Both verifiers are contractually FAIL-CLOSED: they
153
- // catch their own errors and return a non-passing Verdict, never throwing.
154
- // The two wirings (Option i verify-dispatch / Option ii delegate tool) still
155
- // wrap accept() defensively so that any unexpected throw surfaces as a
156
- // visible failure (forcing note / honest status), never a silent accept.
177
+ // DoD-construction time. Verifier limitations are distinct from failed checks;
178
+ // the gate applies strictUnverifiable centrally, without fabricating a pass.
157
179
  // A delegation that declared a working directory must be verified against
158
180
  // THAT directory, not the router's. Both verifiers get the same effective
159
181
  // base dir so a deterministic check and a grader can never disagree about
@@ -186,5 +208,5 @@ export async function accept(
186
208
  );
187
209
  }
188
210
 
189
- return { accepted: verdict.pass === true, verdict, dodSource };
211
+ return gateResult(verdict, dodSource, deps.strictUnverifiable);
190
212
  }
@@ -25,6 +25,14 @@
25
25
  export const DEFAULT_DELEGATE_PROMPT_TIMEOUT_MS = 600_000;
26
26
  /** Ceiling for one grader `session.prompt` turn (1 minute). */
27
27
  export const DEFAULT_GRADER_PROMPT_TIMEOUT_MS = 60_000;
28
+ /** Per-tier grader ceilings; unknown/custom tiers receive the heavy ceiling. */
29
+ export const GRADER_TIMEOUT_MS_BY_TIER: Readonly<Record<string, number>> = {
30
+ fast: 60_000, medium: 180_000, heavy: 600_000,
31
+ };
32
+
33
+ export function graderTimeoutMs(tier: string, override?: number): number {
34
+ return timeoutMs(override, GRADER_TIMEOUT_MS_BY_TIER[tier] ?? GRADER_TIMEOUT_MS_BY_TIER.heavy!);
35
+ }
28
36
  /** Ceiling for the whole acceptance gate, grader ladder included (90 s). */
29
37
  export const DEFAULT_GATE_BUDGET_MS = 90_000;
30
38
 
@@ -0,0 +1,52 @@
1
+ // Impure, bounded Git fingerprint adapter. Never interpolates paths into a shell.
2
+ import { execFile } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { lstat, readFile, readlink, realpath } from "node:fs/promises";
5
+ import { resolve } from "node:path";
6
+ import type { TreeSnapshot, ChangedFile } from "./dispatch";
7
+
8
+ export async function snapshotTree(cwd: string, signal: AbortSignal): Promise<TreeSnapshot | undefined> {
9
+ let gitCwd = cwd;
10
+ const git = (args: string[]) => new Promise<string>((ok, fail) => {
11
+ execFile("git", ["--no-pager", ...args], {
12
+ cwd: gitCwd, signal, timeout: 10000, maxBuffer: 32 * 1024 * 1024, windowsHide: true,
13
+ }, (error, stdout) => error ? fail(error) : ok(stdout));
14
+ });
15
+ try {
16
+ const root = (await git(["rev-parse", "--show-toplevel"])).trim();
17
+ // ls-files otherwise scopes untracked contents to a subdirectory cwd,
18
+ // missing same-path edits in sibling packages that tests may import.
19
+ gitCwd = root;
20
+ const head = (await git(["rev-parse", "HEAD"])).trim();
21
+ const status = await git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
22
+ const files: ChangedFile[] = [];
23
+ const records = status.split("\0");
24
+ for (let i = 0; i < records.length; i++) {
25
+ const record = records[i];
26
+ if (!record) continue;
27
+ files.push({ path: resolve(root, record.slice(3)), status: record.slice(0, 2) });
28
+ if (/[RC]/.test(record.slice(0, 2))) i++; // -z rename destination precedes source.
29
+ }
30
+ const hash = createHash("sha256").update(status);
31
+ hash.update(await git(["diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv"]));
32
+ hash.update(await git(["diff", "--cached", "--binary", "--no-ext-diff", "--no-textconv"]));
33
+ // A submodule's dirty marker does not describe its content. Refuse rather
34
+ // than cache a fingerprint that would excuse unmeasured changes there.
35
+ if (/^160000 /m.test(await git(["ls-files", "--stage"]))) return undefined;
36
+ const untracked = (await git(["ls-files", "--others", "--exclude-standard", "--full-name", "-z"]))
37
+ .split("\0").filter(Boolean).sort();
38
+ for (const path of untracked) {
39
+ const absolute = resolve(root, path);
40
+ const stat = await lstat(absolute);
41
+ hash.update(JSON.stringify([path, stat.mode, stat.size]));
42
+ if (stat.isSymbolicLink()) hash.update(await readlink(absolute));
43
+ else if (stat.isFile()) hash.update(await readFile(absolute, { signal }));
44
+ else return undefined;
45
+ }
46
+ if (signal.aborted) return undefined;
47
+ return { cwd: await realpath(cwd), head, fingerprint: hash.digest("hex"), dirty: files.length > 0, files };
48
+ } catch {
49
+ // Not a Git checkout, unreadable file, timeout or concurrent deletion: no baseline.
50
+ return undefined;
51
+ }
52
+ }
@@ -5,6 +5,12 @@ export type VerifyMethod = "deterministic" | "checker" | "none";
5
5
 
6
6
  export interface Verdict {
7
7
  pass: boolean;
8
+ /** Absent on legacy verdicts: derive from pass. Unverifiable is not failure. */
9
+ outcome?: "pass" | "fail" | "unverifiable";
10
+ /** Checks that could not be performed; never evidence of producer failure. */
11
+ caveats?: string[];
12
+ /** Successful comparisons that must not be mistaken for a green suite. */
13
+ notes?: string[];
8
14
  method: VerifyMethod;
9
15
  reasons: string[];
10
16
  evidence?: string;
@@ -33,6 +39,10 @@ export interface MutexRegistry {
33
39
  }
34
40
 
35
41
  export interface DeterministicDeps {
42
+ /** Bound to the original dispatch, not looked up using the after-state diff. */
43
+ testBaseline?: (command: string) => Promise<import("./baseline").TestBaseline | undefined>;
44
+ /** Preserve completed failures if an outer gate budget expires later. */
45
+ onFailure?: (reason: string) => void;
36
46
  exec: ExecSeam;
37
47
  fs: FsSeam;
38
48
  cwd: string;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The impure corner of Layer 2.
3
3
  *
4
- * Everything else under src/verify/ is pure: the gate, the DoD schema, the
4
+ * Together with tree.ts this owns verification I/O. The gate, the DoD schema, the
5
5
  * deterministic checks and the grader protocol all take their side effects as
6
6
  * injected deps. This module is where those deps are actually built out of a
7
7
  * child_process, a filesystem and an opencode client, so the impurity lives in
@@ -15,12 +15,14 @@
15
15
  */
16
16
  import { exec as nodeExec } from "node:child_process";
17
17
  import { access, readFile as fsReadFile } from "node:fs/promises";
18
- import { isAbsolute, join } from "node:path";
19
- import { createMutexRegistry } from "./deterministic";
20
- import { tierModel } from "./dispatch";
18
+ import { isAbsolute, join, resolve } from "node:path";
19
+ import { createMutexRegistry, DEFAULT_ALLOWLIST, isCommandAllowed, resolveRepoCommand } from "./deterministic";
20
+ import { tierModel, type createChangedFileStore } from "./dispatch";
21
+ import { snapshotTree } from "./tree";
22
+ import type { DoD } from "./dod";
23
+ import type { DeterministicDeps } from "./types";
21
24
  import {
22
- DEFAULT_GRADER_PROMPT_TIMEOUT_MS,
23
- timeoutMs,
25
+ graderTimeoutMs,
24
26
  withTimeout,
25
27
  } from "./timeout";
26
28
  import type { RouterConfig } from "../router/config";
@@ -61,6 +63,12 @@ export function extractAssistantText(res: any): string {
61
63
  }
62
64
 
63
65
  export interface VerificationWiring {
66
+ beginVerification(store: ReturnType<typeof createChangedFileStore>, id: string, cwd: string | undefined, dod: DoD): void;
67
+ prepareVerification(store: ReturnType<typeof createChangedFileStore>, id: string, childID: string, cwd?: string): Promise<{
68
+ changedFiles: { path: string; status: string }[];
69
+ changeBaseline: "available" | "unavailable";
70
+ testBaseline: NonNullable<DeterministicDeps["testBaseline"]>;
71
+ }>;
64
72
  /** Session ids currently running a grader prompt, so hooks can skip them. */
65
73
  graderSessions: Set<string>;
66
74
  /** Abort then delete a plugin-created child session. Never throws. */
@@ -97,7 +105,7 @@ export function createVerificationWiring(deps: {
97
105
 
98
106
  const execSeam = (
99
107
  command: string,
100
- opts?: { cwd?: string; timeoutMs?: number },
108
+ opts?: { cwd?: string; timeoutMs?: number; signal?: AbortSignal },
101
109
  ): Promise<ExecResult> =>
102
110
  new Promise((resolve) => {
103
111
  try {
@@ -108,6 +116,7 @@ export function createVerificationWiring(deps: {
108
116
  timeout: opts?.timeoutMs ?? 120000,
109
117
  maxBuffer: 10 * 1024 * 1024,
110
118
  windowsHide: true,
119
+ signal: opts?.signal,
111
120
  },
112
121
  (err: any, stdout: any, stderr: any) => {
113
122
  const timedOut = !!(err && err.killed && err.signal === "SIGTERM");
@@ -202,10 +211,9 @@ export function createVerificationWiring(deps: {
202
211
  // Time-boxed for the same reason as the producer prompt, but with a
203
212
  // sharper edge: a grader that never answers must not be able to hold the
204
213
  // gate open. The RouterTimeoutError is deliberately allowed to propagate
205
- // to runChecker, whose fail-closed catch turns it into a non-passing
206
- // verdict naming the timeout. Explicitly NOT modelled as "inconclusive",
207
- // because an inconclusive grader that releases the gate is a fabricated
208
- // pass wearing a hedge.
214
+ // to runChecker, which returns unverifiable with the timeout reason.
215
+ // The gate decides acceptance using strictUnverifiable; no producer
216
+ // escalation is warranted when the grader itself could not finish.
209
217
  //
210
218
  // No abort is issued here: the finally below already calls
211
219
  // disposeChildSession, which aborts before it deletes, so a second abort
@@ -222,10 +230,7 @@ export function createVerificationWiring(deps: {
222
230
  parts: [{ type: "text", text: req.prompt }],
223
231
  },
224
232
  }),
225
- timeoutMs(
226
- cfg.enforcement?.verify?.graderTimeoutMs,
227
- DEFAULT_GRADER_PROMPT_TIMEOUT_MS,
228
- ),
233
+ graderTimeoutMs(req.tier, cfg.enforcement?.verify?.graderTimeoutMs),
229
234
  "grader prompt",
230
235
  );
231
236
  return { sessionID: sid, text: extractAssistantText(res) };
@@ -255,10 +260,42 @@ export function createVerificationWiring(deps: {
255
260
  minGraderTier: cfg.enforcement?.verify?.minGraderTier ?? null,
256
261
  },
257
262
  require: cfg.enforcement?.verify?.require,
263
+ strictUnverifiable: cfg.enforcement?.verify?.strictUnverifiable,
258
264
  };
259
265
  };
260
266
 
261
267
  return {
268
+ beginVerification(store, id, cwd, dod) {
269
+ const verify = getConfig().enforcement?.verify;
270
+ const base = resolve(directory, cwd || ".");
271
+ const checks = dod.checks.filter(c => c.kind === "testsPass");
272
+ // Read-only dispatches warm the default-command cache for later producers.
273
+ const commands = (checks.length ? checks : [{ kind: "testsPass" as const }])
274
+ .map(c => resolveRepoCommand(c, "testsPass", undefined))
275
+ .filter(c => isCommandAllowed(c, DEFAULT_ALLOWLIST));
276
+ const budget = verify?.baselineTimeoutMs ?? 60000;
277
+ store.beginDispatch(id, base, verify?.testBaseline === false || verify?.require === "never" ? [] : commands, {
278
+ snapshot: snapshotTree,
279
+ run: (command, cwd, signal) => execSeam(command, { cwd, timeoutMs: budget, signal }),
280
+ timeoutMs: budget,
281
+ });
282
+ },
283
+ async prepareVerification(store, id, childID, cwd) {
284
+ const controller = new AbortController();
285
+ let current;
286
+ try {
287
+ current = await withTimeout(snapshotTree(resolve(directory, cwd || "."), controller.signal), 10000, "grade fingerprint");
288
+ } catch {
289
+ current = undefined; // Explicit unavailable disclaimer, never a raw tree.
290
+ } finally {
291
+ controller.abort();
292
+ }
293
+ return {
294
+ ...store.delta(id, childID, current, resolve(directory, cwd || ".")),
295
+ testBaseline: command => getConfig().enforcement?.verify?.testBaseline === false
296
+ ? Promise.resolve(undefined) : store.baseline(id, command, current?.head),
297
+ };
298
+ },
262
299
  graderSessions,
263
300
  disposeChildSession,
264
301
  dispatchGrader,