opencode-model-router 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,8 @@
1
1
  /**
2
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; bounded background
4
+ * the plugin-owned `delegate` tool). No network/SDK here, and no fs beyond the realpath
5
+ * that canonicalises change-set keys (QA-2.1-8); bounded background
5
6
  * work uses the shared timeout primitive, and the live adapters
6
7
  * (exec/fs/grader) are built in index.ts from PluginInput and injected.
7
8
  */
@@ -10,27 +11,82 @@ import { getActiveTiers } from "../router/protocol";
10
11
  import { parseDoDFromDispatch, inferDoD } from "./dod";
11
12
  import type { DoD, InferHints } from "./dod";
12
13
  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";
14
+ import { basename, dirname, join, resolve } from "node:path";
15
+ import { existsSync, realpathSync } from "node:fs";
16
+ import type { ReferenceState, Verdict } from "./types";
17
+ import type { DispatchReference } from "./reference";
18
+ import { REFERENCE_NONE } from "./baseline";
19
+ import { neutralizeDirectives } from "./pending";
16
20
  import { withTimeout } from "./timeout";
17
21
 
18
22
  export interface TreeSnapshot {
19
23
  cwd: string;
24
+ /** Real path of `git rev-parse --show-toplevel` at capture time. */
25
+ root?: string;
20
26
  head: string;
21
27
  fingerprint: string;
22
28
  dirty: boolean;
23
29
  files: ChangedFile[];
30
+ /**
31
+ * QA-2.1-2: a content identity per digested path (absolute, as in `files`): FILE_DIGEST_PREFIX +
32
+ * sha256, LINK_DIGEST_PREFIX + target, or ABSENT_DIGEST. A dispatch snapshot digests its listed
33
+ * (dirty or untracked) paths; a gate snapshot digests the dispatch snapshot's paths.
34
+ * "unavailable" (over the digest bounds, or unreadable) and absent both mean no per-file proof.
35
+ */
36
+ digests?: ReadonlyMap<string, string> | "unavailable";
24
37
  }
25
38
 
26
- export interface BaselineCaptureDeps {
39
+ /** QA-2.1-2: the digest of a path that does not exist. */
40
+ export const ABSENT_DIGEST = "absent";
41
+ export const FILE_DIGEST_PREFIX = "file:";
42
+ export const LINK_DIGEST_PREFIX = "link:";
43
+
44
+ /** What beginDispatch runs in the background for one dispatch (never a test command, G6). */
45
+ export interface DispatchCaptureDeps {
46
+ /** The change baseline: the tree snapshot `delta` compares against. */
27
47
  snapshot(cwd: string, signal: AbortSignal): Promise<TreeSnapshot | undefined>;
28
- run(command: string, cwd: string, signal: AbortSignal): Promise<ExecResult>;
48
+ /**
49
+ * The git-only dispatch reference (reference.ts captureReference); undefined = no reference.
50
+ * Absent: nothing is captured and the dispatch's reference is `uncaptured`.
51
+ */
52
+ capture?: (cwd: string, signal: AbortSignal) => Promise<DispatchReference | undefined>;
53
+ /** The reference when `capture` is absent. Default: none (REFERENCE_NONE.notRequested). */
54
+ uncaptured?: ReferenceState;
55
+ /** Bounds the snapshot and the capture, each (baselineTimeoutMs). */
29
56
  timeoutMs: number;
30
57
  }
31
58
 
59
+ function none(reason: string): ReferenceState {
60
+ return { kind: "none", reason };
61
+ }
62
+
63
+ /**
64
+ * QA-2.1-8: the canonical spelling of `path`, so a Windows 8.3 short name (`C:\Users\MARQUI~1\…`),
65
+ * a junction or symlink alias, and the long real path of one file key the same change-set entry.
66
+ * The native realpath of the path, or of its nearest existing ancestor with the missing tail
67
+ * appended (a deleted file keeps its directory's canonical spelling); lexical `resolve` when no
68
+ * ancestor resolves.
69
+ */
70
+ function canonicalPath(path: string): string {
71
+ const absolute = resolve(path);
72
+ let head = absolute;
73
+ const tail: string[] = [];
74
+ for (;;) {
75
+ try {
76
+ const real = realpathSync.native(head);
77
+ return tail.length === 0 ? real : join(real, ...tail.reverse());
78
+ } catch {
79
+ const parent = dirname(head);
80
+ if (parent === head) return absolute;
81
+ tail.push(basename(head));
82
+ head = parent;
83
+ }
84
+ }
85
+ }
86
+
87
+ /** A change-set key: the canonical path with "/" separators, case-folded on win32. */
32
88
  function pathKey(path: string): string {
33
- const normalized = resolve(path).replace(/\\/g, "/");
89
+ const normalized = canonicalPath(path).replace(/\\/g, "/");
34
90
  return process.platform === "win32" ? normalized.toLowerCase() : normalized;
35
91
  }
36
92
 
@@ -41,13 +97,30 @@ export interface ChangedFileStoreOptions {
41
97
 
42
98
  /** Tools that mutate the workspace (mirrors the guard taxonomy). */
43
99
  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"]);
100
+ /**
101
+ * E2E-3: the tools known never to write the workspace themselves. observeEdit treats EVERY other
102
+ * tool as a possible write: the shells (no command-level proof of read-onlyness), the write tools,
103
+ * and any tool it does not know. opencode fires tool.execute.before for MCP tools too (named
104
+ * `<server>_<tool>`) and for plugin and custom tools, so an MCP `write_file`, a custom editor or
105
+ * `batch` reach the plugin under names no allowlist of writers can list. Such an edit landing
106
+ * while a dispatch snapshot or capture is still in flight (VERIFY_WAIT:0s, or a snapshot slower
107
+ * than the wait) would seed the change baseline, which then hides it ("no changed files": a clean
108
+ * pass), or the reference, where the failure it causes looks pre-existing and is excused.
109
+ * `task` and `delegate` start producer sessions whose own tool calls are observed; `router_verify`
110
+ * only runs checks.
111
+ */
112
+ const NON_WRITING_TOOLS = new Set([
113
+ "read", "glob", "grep", "list", "ls", "codesearch", "webfetch", "websearch", "lsp",
114
+ "todoread", "todowrite", "question", "skill", "plan_enter", "plan_exit", "invalid", "task",
115
+ "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource",
116
+ "delegate", "router_verify",
117
+ ]);
47
118
 
48
119
  export interface ChangedFile {
49
120
  path: string;
50
121
  status: string;
122
+ /** Rename/copy source (absolute) when git status reports R or C. */
123
+ previousPath?: string;
51
124
  }
52
125
 
53
126
  /** Derive a {path,status} record from a write/edit tool call, or null. */
@@ -67,6 +140,69 @@ export function extractChangedFile(tool: string, args: unknown): ChangedFile | n
67
140
  return { path, status };
68
141
  }
69
142
 
143
+ /**
144
+ * QA-3.1-2: one dispatch's lifetime, from beginDispatch until its record is dropped. Two windows
145
+ * overlap exactly when one dispatch begins while the other is live, so beginDispatch links the new
146
+ * window with every live one, and a dropped window keeps being counted by the live ones it overlapped.
147
+ */
148
+ interface DispatchWindow {
149
+ readonly cwd: string;
150
+ /** The git top-level (TreeSnapshot.root) once the dispatch snapshot settled with one. */
151
+ root?: string;
152
+ /** The other windows that overlapped this one; emptied when this dispatch is dropped. */
153
+ readonly overlapping: Set<DispatchWindow>;
154
+ }
155
+
156
+ /**
157
+ * QA-3.1-3: a tool name as router text names it: [A-Za-z0-9_.-] kept, anything else as "?".
158
+ * QA-3.1-27: at most 64 characters in total; a longer name keeps 63 and ends in "…". Tool names
159
+ * reach the plugin from MCP servers and custom tools.
160
+ */
161
+ export function toolLabel(tool: string): string {
162
+ const label = tool.replace(/[^A-Za-z0-9_.-]/g, "?");
163
+ return label.length > 64 ? `${label.slice(0, 63)}…` : label;
164
+ }
165
+
166
+ /** QA-3.1-3: REFERENCE_NONE.contaminated, naming the tool whose call discarded the capture. */
167
+ export function contaminatedReferenceReason(tool: string): string {
168
+ return `${REFERENCE_NONE.contaminated} (tool "${toolLabel(tool)}")`;
169
+ }
170
+
171
+ /** One tracked dispatch: its change baseline and its reference (T2 P0). */
172
+ interface DispatchRecord {
173
+ cwd: string;
174
+ snapshotPending: boolean;
175
+ /** An overlapping edit was observed while the snapshot was in flight: the snapshot is discarded. */
176
+ snapshotContaminated: boolean;
177
+ /** QA-3.1-3: the first tool whose call discarded the snapshot. */
178
+ snapshotContaminatedBy?: string;
179
+ /** QA-3.1-3: the first tool whose call discarded the capture. */
180
+ captureContaminatedBy?: string;
181
+ /** QA-3.1-2: this dispatch's lifetime, for concurrentDispatches. */
182
+ window: DispatchWindow;
183
+ snapshot?: TreeSnapshot;
184
+ capturePending: boolean;
185
+ /** An overlapping edit was observed while the capture was in flight: the reference is none. */
186
+ captureContaminated: boolean;
187
+ captureController: AbortController;
188
+ /** Settles once; never rejects. */
189
+ reference: Promise<ReferenceState>;
190
+ /** The snapshot settled. */
191
+ ready: Promise<void>;
192
+ /** The snapshot and the reference settled. */
193
+ settled: Promise<void>;
194
+ /**
195
+ * QA-2.1-1: every producer session gated against this dispatch (its lineage: the first attempt,
196
+ * then each retry or escalation, all judged against the one reference).
197
+ */
198
+ producers: Set<string>;
199
+ /**
200
+ * QA-2.1-1: the tool-observed files of every session in `producers`, keyed by pathKey. A retry
201
+ * gate judges the cumulative change since the reference, not only its own attempt's edits.
202
+ */
203
+ observed: Map<string, ChangedFile>;
204
+ }
205
+
70
206
  /**
71
207
  * Per-session changed-file tracker. We attribute changed files to a delegation
72
208
  * by observing that session's own edit/write tool calls (ADR 0002 D3 — NOT a
@@ -76,108 +212,257 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
76
212
  const now = options.now ?? Date.now;
77
213
  const bySession = new Map<string, Map<string, string>>();
78
214
  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
- }>();
215
+ const dispatches = new Map<string, DispatchRecord>();
89
216
 
90
217
  function observeEdit(tool: string, cwd?: string): void {
91
- if (!MAY_WRITE_TOOLS.has(tool.toLowerCase())) return;
218
+ // E2E-3: fail closed. Only a tool known not to write leaves an in-flight snapshot or capture alone.
219
+ if (NON_WRITING_TOOLS.has(tool.toLowerCase())) return;
92
220
  // Unknown directory is conservatively treated as overlapping every capture.
93
221
  const overlaps = (other: string) => !cwd || pathKey(cwd) === pathKey(other)
94
222
  || 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;
223
+ for (const d of dispatches.values()) {
224
+ if (!overlaps(d.cwd)) continue;
225
+ if (d.snapshotPending) {
226
+ d.snapshotContaminated = true;
227
+ d.snapshotContaminatedBy ??= tool;
228
+ }
229
+ // The capture would describe a tree that already holds the edit: discard it, and stop it.
230
+ if (d.capturePending && !d.captureContaminated) {
231
+ d.captureContaminated = true;
232
+ d.captureContaminatedBy = tool;
233
+ d.captureController.abort();
234
+ }
235
+ }
236
+ }
237
+
238
+ /**
239
+ * QA-3.1-2: whether `w`'s dispatch worked in the git tree at `at`. Two known git roots must be the
240
+ * same; when either is unknown (a snapshot that found none: its cwd stands in), a directory that
241
+ * is the other, inside it or above it counts. Over-counting only adds a caveat.
242
+ */
243
+ function onRoot(w: DispatchWindow, at: string, atIsRoot: boolean): boolean {
244
+ const key = pathKey(at);
245
+ if (w.root !== undefined && atIsRoot) return pathKey(w.root) === key;
246
+ const its = pathKey(w.root ?? w.cwd);
247
+ return its === key || its.startsWith(key + "/") || key.startsWith(its + "/");
97
248
  }
98
249
 
99
250
  function touch(sessionID: string): void {
100
251
  lastTouch.set(sessionID, now());
101
252
  }
102
253
 
254
+ /** QA-2.1-1: folds one producer session's tool-observed files into its dispatch's lineage. */
255
+ function fold(d: DispatchRecord, sessionID: string): void {
256
+ for (const [path, status] of bySession.get(sessionID) ?? []) {
257
+ const absolute = resolve(d.cwd, path);
258
+ const key = pathKey(absolute);
259
+ // "written" (created) stays stickier than a later attempt's "modified", as in record().
260
+ const prev = d.observed.get(key);
261
+ d.observed.set(key, { path: absolute, status: prev?.status === "written" ? "written" : status });
262
+ }
263
+ }
264
+
103
265
  function evict(sessionID: string): void {
266
+ // A retry's session is cleared after its gate: keep its edits in every lineage it belongs to.
267
+ for (const d of dispatches.values()) if (d.producers.has(sessionID)) fold(d, sessionID);
104
268
  bySession.delete(sessionID);
105
269
  lastTouch.delete(sessionID);
270
+ const d = dispatches.get(sessionID);
271
+ d?.captureController.abort();
272
+ // QA-3.1-2: the live windows it overlapped keep counting it; its own list is no longer needed
273
+ // (and would otherwise chain every dropped window to the next).
274
+ d?.window.overlapping.clear();
106
275
  dispatches.delete(sessionID);
107
276
  }
108
277
 
109
278
  return {
110
- /** Non-blocking: fingerprint and test run are bounded background work. */
111
- beginDispatch(id: string, cwd: string, commands: string[], deps: BaselineCaptureDeps): void {
279
+ /**
280
+ * Starts the bounded background work of one dispatch: the tree snapshot (change baseline) and,
281
+ * when `deps.capture` is given, the git-only reference. Resolves once both settled; never
282
+ * rejects. A dispatch id that is already tracked keeps its ORIGINAL snapshot and reference, so
283
+ * a retry never turns a failed attempt into its own reference.
284
+ */
285
+ beginDispatch(id: string, cwd: string, deps: DispatchCaptureDeps): Promise<void> {
112
286
  touch(id);
287
+ const existing = dispatches.get(id);
288
+ if (existing) return existing.settled;
113
289
  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>>(),
290
+ const window: DispatchWindow = { cwd, overlapping: new Set() };
291
+ // QA-3.1-2: every live dispatch overlaps this one's window, and this one overlaps theirs.
292
+ for (const other of dispatches.values()) {
293
+ window.overlapping.add(other.window);
294
+ other.window.overlapping.add(window);
295
+ }
296
+ const d: DispatchRecord = {
297
+ cwd, snapshotPending: true, snapshotContaminated: false,
298
+ capturePending: deps.capture !== undefined, captureContaminated: false,
299
+ captureController: new AbortController(),
300
+ reference: Promise.resolve(deps.uncaptured ?? none(REFERENCE_NONE.notRequested)),
301
+ ready: Promise.resolve(), settled: Promise.resolve(),
302
+ // The delegate ladder's dispatch id is its first producer session.
303
+ producers: new Set([id]), observed: new Map(),
304
+ window,
118
305
  };
119
306
  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);
307
+ d.ready = (async (): Promise<void> => {
308
+ const controller = new AbortController();
309
+ let snapshot: TreeSnapshot | undefined;
310
+ try {
311
+ snapshot = await withTimeout(deps.snapshot(cwd, controller.signal), deps.timeoutMs, "dispatch fingerprint");
312
+ } catch {
313
+ snapshot = undefined; // Fingerprinting unavailable: keep the explicit missing-snapshot state.
314
+ } finally {
315
+ d.snapshotPending = false;
316
+ controller.abort();
317
+ }
318
+ // A discarded snapshot still tells which git tree the dispatch works in (QA-3.1-2).
319
+ if (snapshot?.root !== undefined) window.root = snapshot.root;
320
+ if (snapshot && !d.snapshotContaminated && dispatches.get(id) === d) d.snapshot = snapshot;
321
+ })();
322
+ const capture = deps.capture;
323
+ if (capture !== undefined) {
324
+ d.reference = (async (): Promise<ReferenceState> => {
325
+ let captured: DispatchReference | undefined;
326
+ try {
327
+ captured = await withTimeout(capture(cwd, d.captureController.signal), deps.timeoutMs, "dispatch reference");
328
+ } catch {
329
+ captured = undefined; // Timed out or failed: "no reference", never a blocked dispatch.
330
+ } finally {
331
+ d.capturePending = false;
332
+ d.captureController.abort();
333
+ }
334
+ if (d.captureContaminated) {
335
+ return none(d.captureContaminatedBy !== undefined ? contaminatedReferenceReason(d.captureContaminatedBy) : REFERENCE_NONE.contaminated);
151
336
  }
152
- })
153
- .catch(() => { /* Fingerprinting unavailable: retain explicit missing-snapshot state. */ })
154
- .finally(() => { d.pending = false; controller.abort(); });
337
+ return captured ? { kind: "captured", reference: captured } : none(REFERENCE_NONE.failed);
338
+ })();
339
+ }
340
+ d.settled = Promise.all([d.ready, d.reference]).then(() => undefined);
341
+ return d.settled;
155
342
  },
156
343
  observeEdit,
157
- async baseline(id: string, command: string, currentHead?: string): Promise<TestBaseline | undefined> {
344
+ /**
345
+ * The dispatch's ReferenceState. An untracked (or swept) dispatch has none. `signal` bounds the
346
+ * wait for a capture still in flight: once it aborts, the reference is none (gate budget).
347
+ */
348
+ reference(id: string, signal?: AbortSignal): Promise<ReferenceState> {
158
349
  const d = dispatches.get(id);
159
- if (!d) return undefined;
350
+ if (!d) return Promise.resolve(none(REFERENCE_NONE.untracked));
160
351
  touch(id);
161
- await d.ready;
162
- if (!currentHead || d.snapshot?.head !== currentHead) return undefined;
163
- return d.baselines.get(command);
352
+ if (!signal || !d.capturePending) return d.reference;
353
+ if (signal.aborted) return Promise.resolve(none(REFERENCE_NONE.gateBudget));
354
+ return new Promise<ReferenceState>(settle => {
355
+ const onAbort = (): void => settle(none(REFERENCE_NONE.gateBudget));
356
+ signal.addEventListener("abort", onAbort, { once: true });
357
+ void d.reference.then(state => {
358
+ signal.removeEventListener("abort", onAbort);
359
+ settle(state);
360
+ });
361
+ });
164
362
  },
165
- delta(id: string, childID: string, current?: TreeSnapshot, fallbackCwd?: string): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable" } {
363
+ /**
364
+ * The producer's change since the dispatch reference. `childID` joins the dispatch's lineage:
365
+ * the tool-observed files are those of EVERY producer session gated against `id` so far
366
+ * (QA-2.1-1), so a retry never drops a file an earlier attempt edited.
367
+ *
368
+ * `committed` (QA-2.1-12): the files of the commits made since the dispatch snapshot's head
369
+ * (absolute paths), which `git status` no longer lists; "unavailable" when HEAD moved and they
370
+ * could not be listed, which makes the whole change set unavailable. Absent: HEAD did not move.
371
+ */
372
+ delta(
373
+ id: string,
374
+ childID: string,
375
+ current?: TreeSnapshot,
376
+ fallbackCwd?: string,
377
+ committed?: readonly ChangedFile[] | "unavailable",
378
+ ): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable" } {
166
379
  const d = dispatches.get(id);
167
380
  const snapshot = d?.snapshot;
168
381
  const files = new Map<string, ChangedFile>();
169
- for (const [path, status] of bySession.get(childID) ?? []) {
382
+ const listed = new Map((current?.files ?? []).map(f => [pathKey(f.path), f] as const));
383
+ let observed: Iterable<[string, string]>;
384
+ if (d) {
385
+ d.producers.add(childID);
386
+ for (const producer of d.producers) fold(d, producer);
387
+ observed = [...d.observed.values()].map(f => [f.path, f.status] as [string, string]);
388
+ } else {
389
+ observed = bySession.get(childID) ?? [];
390
+ }
391
+ for (const [path, status] of observed) {
170
392
  const base = d?.cwd ?? current?.cwd ?? fallbackCwd;
171
393
  const absolute = base ? resolve(base, path) : path;
172
- files.set(base ? pathKey(absolute) : path, { path: absolute, status });
394
+ const key = base ? pathKey(absolute) : path;
395
+ // Tool-observed paths never carry deletions or rename sources: when the current snapshot
396
+ // lists the path, its status letters and previousPath win.
397
+ files.set(key, (base ? listed.get(key) : undefined) ?? { path: absolute, status });
173
398
  }
174
- const available = !!snapshot && !!current;
175
- if (available) {
399
+ let available = !!snapshot && !!current;
400
+ if (snapshot && current) {
176
401
  const before = new Set(snapshot.files.map(f => pathKey(f.path)));
177
402
  for (const file of current.files) if (!before.has(pathKey(file.path))) files.set(pathKey(file.path), file);
403
+ // QA-2.1-2: a path already dirty or untracked at dispatch is never "new" above, and a shell
404
+ // edit to it (sed, a formatter, git checkout, git rm) records nothing. An unchanged
405
+ // fingerprint proves no such edit; otherwise each dispatch-listed path whose content
406
+ // identity changed, or which left the listing, is part of the change.
407
+ if (snapshot.fingerprint !== current.fingerprint) {
408
+ const was = snapshot.digests;
409
+ const now = current.digests;
410
+ if (was === undefined || was === "unavailable" || now === undefined || now === "unavailable") {
411
+ // QA-2.1-14: no per-file proof (over the digest bounds). None of the dispatch-listed
412
+ // paths can be proven unchanged, so each is included (wider scope, fails safe) and the
413
+ // change set stays available: still listed, with its current status; left the listing
414
+ // (restored, committed, deleted), as modified or deleted by what is on disk now.
415
+ for (const file of snapshot.files) {
416
+ const key = pathKey(file.path);
417
+ files.set(key, listed.get(key) ?? files.get(key) ?? { path: file.path, status: existsSync(file.path) ? " M" : " D" });
418
+ }
419
+ } else {
420
+ const nowByKey = new Map([...now].map(([path, digest]) => [pathKey(path), digest] as const));
421
+ for (const [path, digest] of was) {
422
+ const key = pathKey(path);
423
+ const after = nowByKey.get(key);
424
+ if (after === digest && listed.has(key)) continue;
425
+ // An undigested path cannot be proven unchanged: it is included (wider scope).
426
+ files.set(key, listed.get(key) ?? files.get(key) ?? { path, status: after === ABSENT_DIGEST ? " D" : " M" });
427
+ }
428
+ }
429
+ }
430
+ }
431
+ // QA-2.1-12: a shell edit to a file clean at dispatch, then committed, leaves nothing in the
432
+ // tree listing. A path the current listing also holds keeps its current status (the newer
433
+ // state) and gains the commit's rename source when it has none.
434
+ if (committed === "unavailable") available = false;
435
+ else if (committed) {
436
+ for (const file of committed) {
437
+ const key = pathKey(file.path);
438
+ const prev = files.get(key);
439
+ if (!prev) files.set(key, file);
440
+ else if (prev.previousPath === undefined && file.previousPath !== undefined) files.set(key, { ...prev, previousPath: file.previousPath });
441
+ }
178
442
  }
179
443
  return { changedFiles: [...files.values()], changeBaseline: available ? "available" : "unavailable" };
180
444
  },
445
+ /** The dispatch-time snapshot (QA-2.1-2: the gate digests its listed paths); undefined until settled. */
446
+ baselineSnapshot(id: string): TreeSnapshot | undefined {
447
+ return dispatches.get(id)?.snapshot;
448
+ },
449
+ /**
450
+ * QA-3.1-2: how many other dispatches were live at some moment of this one's window so far and
451
+ * work in the git tree at `root` (default: this dispatch's own root, else its cwd). Their edits
452
+ * land in the same working tree, so they are part of this dispatch's tree delta. 0 when untracked.
453
+ */
454
+ concurrentDispatches(id: string, root?: string): number {
455
+ const d = dispatches.get(id);
456
+ if (!d) return 0;
457
+ const known = root ?? d.window.root;
458
+ let count = 0;
459
+ for (const w of d.window.overlapping) if (onRoot(w, known ?? d.cwd, known !== undefined)) count += 1;
460
+ return count;
461
+ },
462
+ /** QA-3.1-3: the tool whose call discarded this dispatch's snapshot (the change baseline), if one did. */
463
+ snapshotContaminatedBy(id: string): string | undefined {
464
+ return dispatches.get(id)?.snapshotContaminatedBy;
465
+ },
181
466
  record(sessionID: string, tool: string, args: unknown): void {
182
467
  touch(sessionID);
183
468
  observeEdit(tool, dispatches.get(sessionID)?.cwd);
@@ -209,15 +494,10 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
209
494
  },
210
495
  /** Evict every session idle for >= ttlMs. Future stamps are never evicted. */
211
496
  sweep(nowMs: number = now(), ttlMs: number = DEFAULT_IDLE_TTL_MS): void {
497
+ // A dispatch's reference lives on its record, so it follows the same TTL.
212
498
  for (const [sessionID, stamp] of [...lastTouch.entries()]) {
213
499
  if (nowMs - stamp >= ttlMs) evict(sessionID);
214
500
  }
215
- for (const [key, entry] of cache) {
216
- if (nowMs - entry.stamp >= ttlMs) {
217
- entry.controller.abort();
218
- cache.delete(key);
219
- }
220
- }
221
501
  },
222
502
  };
223
503
  }
@@ -308,14 +588,20 @@ export function shouldVerifyTask(
308
588
  return true;
309
589
  }
310
590
 
311
- /** Build the advisory forcing note appended to a task result the gate did not accept. */
591
+ /**
592
+ * Build the advisory forcing note appended to a task result the gate did not accept.
593
+ *
594
+ * QA-2.4-6: the reasons quote producer-controlled text (failing test ids), and an orchestrator may
595
+ * quote this note in its next dispatch before its own `VERIFY:` directive (the first valid one
596
+ * wins). So every directive key loses its colons (pending.ts neutralizeDirectives).
597
+ */
312
598
  export function buildForcingNote(
313
599
  reasons: string[],
314
600
  escalation?: { producerTier?: string; nextTier?: string | null },
315
601
  ): string {
316
602
  const body =
317
603
  reasons.length > 0
318
- ? reasons.map((r) => `- ${r}`).join("\n")
604
+ ? reasons.map((r) => `- ${neutralizeDirectives(r)}`).join("\n")
319
605
  : "- (no reasons provided)";
320
606
  const next =
321
607
  escalation?.nextTier
@@ -330,9 +616,24 @@ export function buildForcingNote(
330
616
  );
331
617
  }
332
618
 
333
- /** Suffix appended to an accepted delegate-tool result. */
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")}` : "");
619
+ /**
620
+ * Suffix appended to an accepted delegate-tool result. Caveats and notes can name producer test ids
621
+ * ("no worse than before; pre-existing failures: <ids>"), so directive keys lose their colons as in
622
+ * buildForcingNote (QA-2.4-6).
623
+ *
624
+ * Plan G2 (QA-3.1-21): only an outcome "pass" with no caveats reads `[router ✓ verified: <method>]`
625
+ * (QA-3.1-18). Anything else the gate let through (unverifiable, a skipped check, a pass carrying
626
+ * caveats) reads `[router ⚠ UNVERIFIED: <method>]` and is never labelled accepted or verified.
627
+ */
628
+ export function buildAcceptedSuffix(
629
+ method: string,
630
+ outcome: Verdict["outcome"],
631
+ caveats: string[] = [],
632
+ notes: string[] = [],
633
+ ): string {
634
+ const verified = outcome === "pass" && caveats.length === 0;
635
+ const label = verified ? `[router \u2713 verified: ${method}]` : `[router \u26a0 UNVERIFIED: ${method}]`;
636
+ return `\n\n${label}` + (caveats.length
637
+ ? `\nVerification caveats — NOT verified (acceptance is not a passing check):\n${caveats.map(r => `- ${neutralizeDirectives(r)}`).join("\n")}`
638
+ : "") + (notes.length ? `\nVerification notes:\n${notes.map(r => `- ${neutralizeDirectives(r)}`).join("\n")}` : "");
338
639
  }