opencode-model-router 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
@@ -20,12 +20,18 @@ import type { DispatchReference } from "./reference";
20
20
  import { REFERENCE_NONE } from "./baseline";
21
21
  import { neutralizeDirectives } from "./pending";
22
22
  import { withTimeout } from "./timeout";
23
+ import type { HeadRead } from "./head";
23
24
 
24
25
  export interface TreeSnapshot {
25
26
  cwd: string;
26
27
  /** Real path of `git rev-parse --show-toplevel` at capture time. */
27
28
  root?: string;
28
29
  head: string;
30
+ /**
31
+ * I7 (P0.2): the branch checked out at capture (`git symbolic-ref -q HEAD`): its short name (`feat/x`), or null for a
32
+ * detached HEAD. Absent or undefined: unknown (the command failed, timed out or was aborted). branch.ts compares two.
33
+ */
34
+ branch?: string | null;
29
35
  fingerprint: string;
30
36
  dirty: boolean;
31
37
  files: ChangedFile[];
@@ -36,6 +42,12 @@ export interface TreeSnapshot {
36
42
  * "unavailable" (over the digest bounds, or unreadable) and absent both mean no per-file proof.
37
43
  */
38
44
  digests?: ReadonlyMap<string, string> | "unavailable";
45
+ /**
46
+ * Cross-repo P2.6 (SD11): a content digest of the repository's ignored files (path, size and content; nothing under a
47
+ * `node_modules` segment), so a linked package's ignored `dist/` can be pinned. "over-bounds": more files or bytes than the
48
+ * bounds allow. Absent: not requested (SnapshotOptions.ignoredDigest) or unavailable (any error).
49
+ */
50
+ ignored?: string | "over-bounds";
39
51
  }
40
52
 
41
53
  /** QA-2.1-2: the digest of a path that does not exist. */
@@ -54,10 +66,88 @@ export interface DispatchCaptureDeps {
54
66
  capture?: (cwd: string, signal: AbortSignal) => Promise<DispatchReference | undefined>;
55
67
  /** The reference when `capture` is absent. Default: none (REFERENCE_NONE.notRequested). */
56
68
  uncaptured?: ReferenceState;
57
- /** Bounds the snapshot and the capture, each (baselineTimeoutMs). */
69
+ /**
70
+ * The cheap head-state read (src/verify/head.ts readHead; "none": no repository or an unborn HEAD) the branch-switch rule
71
+ * compares at the gate. Independent of
72
+ * the snapshot: a snapshot that failed, timed out or was discarded does not lose it. Absent: no head baseline.
73
+ */
74
+ headState?: (cwd: string, signal: AbortSignal) => Promise<HeadRead>;
75
+ /**
76
+ * Cross-repo P1.8 (I13): the extra roots of the dispatch's perimeter P, each snapshotted with `snapshot` next to the change
77
+ * baseline and bounded by `timeoutMs`. Absent: no perimeter, and nothing else is snapshotted (I9).
78
+ */
79
+ perimeter?: DispatchPerimeter;
80
+ /** Cross-repo QA-1 F4 (I11): how an extra root of the perimeter is snapshotted (hardened git). Absent: `snapshot`. */
81
+ perimeterSnapshot?: (cwd: string, signal: AbortSignal) => Promise<TreeSnapshot | undefined>;
82
+ /** Bounds the snapshot, the head read and the capture, each (baselineTimeoutMs). */
58
83
  timeoutMs: number;
59
84
  }
60
85
 
86
+ /** Cross-repo P1.8: one extra root of a perimeter, as planned at dispatch (perimeter.ts planPerimeter). */
87
+ export interface PerimeterSeed {
88
+ /** Where it is snapshotted: a working-set worktree, or the real path of a package link of W. */
89
+ readonly at: string;
90
+ /** The repository's name when known (the working-set location's); else the basename of its git top level. */
91
+ readonly name?: string;
92
+ /** Link targets only: whether the git top level the snapshot names is admitted (checked at the gate). */
93
+ readonly admit?: (root: string) => boolean;
94
+ /**
95
+ * Cross-repo QA-1: a root that is never snapshotted, and the status the gate reports for it. "unobserved": past PERIMETER_MAX
96
+ * (F2), or the placeholder of a perimeter that could not be planned (F10); I4 refuses it when writers ran. "unadmitted" (F4):
97
+ * a linked directory whose repository is not admitted (`routing.repoParents` / `repoDepth` / `repoExclude`) or that is not a
98
+ * git repository; git never runs there (I11, I12), and I8 names it as not observed.
99
+ */
100
+ readonly fixed?: "unobserved" | "unadmitted";
101
+ /** QA-1 F11: a worktree of W's own repository (the same git common directory): I4 suggests `branch=`, not `repo=`. */
102
+ readonly sameRepository?: boolean;
103
+ /**
104
+ * Cross-repo P2b.3: where the root came from, set by `planPerimeter`: "working-set" (a working-set worktree other than W),
105
+ * "link" (a package link target of W), "edge" (cross-repo P3c.3, SD-P3c-2: the repository of a declared dependency edge of W
106
+ * outside `node_modules`, edges.ts; a link and an edge into one repository are one "link" seed). Consumer discovery scans only
107
+ * the working-set roots. An "edge" seed is observed like a link target (I4, I8) but never pinned (F3).
108
+ */
109
+ readonly origin?: "w" | "working-set" | "link" | "edge";
110
+ /**
111
+ * Cross-repo QA-1 #9a: a working-set root that is also a package link target of W (the link was de-duplicated into it). It
112
+ * keeps its working-set semantics (consumer discovery, I13) and is pinned at dispatch like a link target.
113
+ */
114
+ readonly linked?: boolean;
115
+ /**
116
+ * Cross-repo P3c.3 (SD-P3c-2): a working-set root that a declared dependency edge of W leads into (the edge was de-duplicated
117
+ * into it). It keeps its working-set semantics; unlike `linked`, it is not pinned (F3).
118
+ */
119
+ readonly edged?: true;
120
+ }
121
+
122
+ /** Cross-repo P1.8: the perimeter P of a dispatch beyond W. */
123
+ export interface DispatchPerimeter {
124
+ /** W's repository name when the grant's location names it. */
125
+ readonly name?: string;
126
+ readonly roots: readonly PerimeterSeed[];
127
+ /**
128
+ * Cross-repo P3c.4 (SD-P3c-9): the admission W's package links and declared edges were read with (perimeter.ts
129
+ * `AdmissionData`: the parents in both spellings, depth, excludes, working set). A deferred perimeter freezes it so that
130
+ * `router_verify` reads W's dependency targets again as the dispatch did. Absent: none recorded (links only at router_verify).
131
+ */
132
+ readonly admission?: {
133
+ readonly parents: readonly string[];
134
+ readonly depth: number;
135
+ readonly exclude?: readonly string[];
136
+ readonly workingSet: readonly { readonly worktree: string; readonly name?: string }[];
137
+ };
138
+ }
139
+
140
+ /** Cross-repo P1.8: the dispatch-time state of one extra root of the perimeter. */
141
+ export interface PerimeterEntry {
142
+ readonly seed: PerimeterSeed;
143
+ /** Its dispatch snapshot is in flight. */
144
+ pending: boolean;
145
+ /** The first tool whose call may have written into this root while its snapshot was in flight: the snapshot is discarded. */
146
+ contaminatedBy?: string;
147
+ /** Settles once, never rejects; undefined when unavailable, timed out or discarded. */
148
+ snapshot: Promise<TreeSnapshot | undefined>;
149
+ }
150
+
61
151
  function none(reason: string): ReferenceState {
62
152
  return { kind: "none", reason };
63
153
  }
@@ -117,6 +207,54 @@ const NON_WRITING_TOOLS = new Set([
117
207
  "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource",
118
208
  "delegate", "router_verify",
119
209
  ]);
210
+ /**
211
+ * P0.3: router tools that only read (copied, not imported: this module takes no plugin SDK; a pin
212
+ * test compares them with the sources). Exact names: a `context7_*` prefix would also admit a
213
+ * future write tool.
214
+ */
215
+ const READ_ONLY_ROUTER_TOOLS = new Set([
216
+ "router_git_status", "router_git_log", "router_git_diff", "router_git_show", "router_git_blame", "router_git_ls_files",
217
+ "router_request_authority",
218
+ ]);
219
+ const BRAVE_TOOLS = ["web_search", "local_search", "news_search", "image_search", "video_search", "summarizer", "llm_context"]
220
+ .map(t => `brave_${t}`);
221
+ const READ_ONLY_MCP_TOOLS = new Set([
222
+ "context7_resolve-library-id", "context7_query-docs", "context7_get-library-docs",
223
+ // The server may be mounted as `brave` with tools already named `brave_*`.
224
+ ...BRAVE_TOOLS, ...BRAVE_TOOLS.map(t => `brave_${t}`),
225
+ ]);
226
+
227
+ /** Whether `tool` is known never to write the workspace (case-insensitive). */
228
+ export function isNonWritingTool(tool: string): boolean {
229
+ const n = tool.toLowerCase();
230
+ return NON_WRITING_TOOLS.has(n) || READ_ONLY_ROUTER_TOOLS.has(n) || READ_ONLY_MCP_TOOLS.has(n);
231
+ }
232
+
233
+ /**
234
+ * P0.3 (invariant I5): a tool that may write but whose writes the router cannot attribute to files
235
+ * (shells, `router_run`, `execute`, MCP and custom tools). An empty change set from a producer
236
+ * that ran one of these is not proof that nothing changed.
237
+ */
238
+ export function isUnattributedWriter(tool: string): boolean {
239
+ const n = tool.toLowerCase();
240
+ // F2: a nested child's own writes are attributed to the child's session, not to this producer's lineage, so delegating
241
+ // tools count as writers here. They stay non-writing for observeEdit (they do not contaminate captures).
242
+ if (DELEGATING_TOOLS.has(n)) return true;
243
+ return !WRITE_TOOLS.has(n) && !isNonWritingTool(n);
244
+ }
245
+
246
+ /** F2: tools that start a child session whose writes are not in the caller's lineage. */
247
+ const DELEGATING_TOOLS = new Set(["task", "delegate", "subagent"]);
248
+
249
+ /**
250
+ * Whether a call to `tool` may write the workspace behind the router's back, so that it discards every in-flight snapshot,
251
+ * capture and link pin. The one rule for both contaminateCaptures and the onUnattributedWriter signal (M3: they must not drift).
252
+ * A delegating tool never does: its child session is observed on its own, and it writes nothing itself (it is only an
253
+ * unattributed writer for the producer's empty-change-set caveat, isUnattributedWriter).
254
+ */
255
+ function mayContaminate(tool: string): boolean {
256
+ return !isNonWritingTool(tool) && !DELEGATING_TOOLS.has(tool.toLowerCase());
257
+ }
120
258
 
121
259
  export interface ChangedFile {
122
260
  path: string;
@@ -127,7 +265,8 @@ export interface ChangedFile {
127
265
 
128
266
  /** Derive a {path,status} record from a write/edit tool call, or null. */
129
267
  export function extractChangedFile(tool: string, args: unknown): ChangedFile | null {
130
- if (!WRITE_TOOLS.has(tool)) return null;
268
+ const name = tool.toLowerCase();
269
+ if (!WRITE_TOOLS.has(name)) return null;
131
270
  const a = (args ?? {}) as Record<string, unknown>;
132
271
  const path =
133
272
  typeof a.filePath === "string"
@@ -138,7 +277,7 @@ export function extractChangedFile(tool: string, args: unknown): ChangedFile | n
138
277
  ? a.file
139
278
  : "";
140
279
  if (!path) return null;
141
- const status = tool === "write" ? "written" : "modified";
280
+ const status = name === "write" ? "written" : "modified";
142
281
  return { path, status };
143
282
  }
144
283
 
@@ -183,6 +322,11 @@ interface DispatchRecord {
183
322
  /** QA-3.1-2: this dispatch's lifetime, for concurrentDispatches. */
184
323
  window: DispatchWindow;
185
324
  snapshot?: TreeSnapshot;
325
+ /**
326
+ * The head state read when the dispatch began (branch-switch baseline). Never discarded on contamination: a write does not
327
+ * change what HEAD was. Resolves undefined when the read failed or timed out; never rejects.
328
+ */
329
+ head?: Promise<HeadRead>;
186
330
  capturePending: boolean;
187
331
  /** An overlapping edit was observed while the capture was in flight: the reference is none. */
188
332
  captureContaminated: boolean;
@@ -203,6 +347,15 @@ interface DispatchRecord {
203
347
  * gate judges the cumulative change since the reference, not only its own attempt's edits.
204
348
  */
205
349
  observed: Map<string, ChangedFile>;
350
+ /** P0.3: the unattributable writers (isUnattributedWriter) of every session in `producers`. */
351
+ writers: Set<string>;
352
+ /** Cross-repo P1.8 (I13): the extra roots of the dispatch's perimeter, by snapshot directory; absent: no perimeter. */
353
+ perimeter?: {
354
+ readonly name?: string;
355
+ readonly entries: Map<string, PerimeterEntry>;
356
+ /** Cross-repo P3c.4: the admission the perimeter was planned with (DispatchPerimeter.admission). */
357
+ readonly admission?: DispatchPerimeter["admission"];
358
+ };
206
359
  }
207
360
 
208
361
  /**
@@ -213,16 +366,49 @@ interface DispatchRecord {
213
366
  export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
214
367
  const now = options.now ?? Date.now;
215
368
  const bySession = new Map<string, Map<string, string>>();
369
+ /** P0.3: per session, the lowercased names of the unattributable writers it ran. */
370
+ const writersBySession = new Map<string, Set<string>>();
216
371
  const lastTouch = new Map<string, number>();
217
372
  const dispatches = new Map<string, DispatchRecord>();
218
373
 
374
+ /** Cross-repo QA-2 #9c: subscribers told when a call by an unattributable writer (isUnattributedWriter) is seen. */
375
+ const unattributedWriterListeners = new Set<(tool: string, sessionID?: string) => void>();
376
+ function onUnattributedWriter(listener: (tool: string, sessionID?: string) => void): () => void {
377
+ unattributedWriterListeners.add(listener);
378
+ return () => {
379
+ unattributedWriterListeners.delete(listener);
380
+ };
381
+ }
382
+ function notifyUnattributedWriter(tool: string, sessionID?: string): void {
383
+ // M3: the same rule as contaminateCaptures; a delegating tool counts as a writer for the tally, not for in-flight pins.
384
+ if (!isUnattributedWriter(tool) || !mayContaminate(tool)) return;
385
+ for (const listener of [...unattributedWriterListeners]) {
386
+ try {
387
+ listener(tool, sessionID);
388
+ } catch {
389
+ // a subscriber never breaks the store
390
+ }
391
+ }
392
+ }
393
+
219
394
  function observeEdit(tool: string, cwd?: string): void {
395
+ notifyUnattributedWriter(tool);
396
+ contaminateCaptures(tool, cwd);
397
+ }
398
+
399
+ function contaminateCaptures(tool: string, cwd?: string): void {
220
400
  // E2E-3: fail closed. Only a tool known not to write leaves an in-flight snapshot or capture alone.
221
- if (NON_WRITING_TOOLS.has(tool.toLowerCase())) return;
401
+ if (!mayContaminate(tool)) return;
222
402
  // Unknown directory is conservatively treated as overlapping every capture.
223
403
  const overlaps = (other: string) => !cwd || pathKey(cwd) === pathKey(other)
224
404
  || pathKey(cwd).startsWith(pathKey(other) + "/") || pathKey(other).startsWith(pathKey(cwd) + "/");
225
405
  for (const d of dispatches.values()) {
406
+ // Cross-repo P1.8: a write that may land in an extra root of the perimeter discards that root's in-flight snapshot.
407
+ // QA-1 F1: an unattributable writer's directory says nothing about where it writes (router_run's cwd is always W), so it
408
+ // discards every in-flight perimeter snapshot, whatever its cwd.
409
+ for (const entry of d.perimeter?.entries.values() ?? []) {
410
+ if (entry.pending && (isUnattributedWriter(tool) || overlaps(entry.seed.at))) entry.contaminatedBy ??= tool;
411
+ }
226
412
  if (!overlaps(d.cwd)) continue;
227
413
  if (d.snapshotPending) {
228
414
  d.snapshotContaminated = true;
@@ -253,6 +439,17 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
253
439
  lastTouch.set(sessionID, now());
254
440
  }
255
441
 
442
+ /**
443
+ * F1: notes, before a call runs, that `sessionID` is about to run a tool whose writes the router cannot attribute. A call
444
+ * that ends in error (or is bypassed) never reaches the after-hook's record(), so the tally is also kept here (a Set: idempotent).
445
+ */
446
+ function noteWriter(sessionID: string, tool: string): void {
447
+ if (!isUnattributedWriter(tool)) return;
448
+ const w = writersBySession.get(sessionID) ?? new Set<string>();
449
+ w.add(tool.toLowerCase());
450
+ writersBySession.set(sessionID, w);
451
+ }
452
+
256
453
  /** QA-2.1-1: folds one producer session's tool-observed files into its dispatch's lineage. */
257
454
  function fold(d: DispatchRecord, sessionID: string): void {
258
455
  for (const [path, status] of bySession.get(sessionID) ?? []) {
@@ -262,12 +459,14 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
262
459
  const prev = d.observed.get(key);
263
460
  d.observed.set(key, { path: absolute, status: prev?.status === "written" ? "written" : status });
264
461
  }
462
+ for (const tool of writersBySession.get(sessionID) ?? []) d.writers.add(tool);
265
463
  }
266
464
 
267
465
  function evict(sessionID: string): void {
268
466
  // A retry's session is cleared after its gate: keep its edits in every lineage it belongs to.
269
467
  for (const d of dispatches.values()) if (d.producers.has(sessionID)) fold(d, sessionID);
270
468
  bySession.delete(sessionID);
469
+ writersBySession.delete(sessionID);
271
470
  lastTouch.delete(sessionID);
272
471
  const d = dispatches.get(sessionID);
273
472
  d?.captureController.abort();
@@ -289,6 +488,7 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
289
488
  const existing = dispatches.get(id);
290
489
  if (existing) return existing.settled;
291
490
  bySession.delete(id);
491
+ writersBySession.delete(id);
292
492
  const window: DispatchWindow = { cwd, overlapping: new Set() };
293
493
  // QA-3.1-2: every live dispatch overlaps this one's window, and this one overlaps theirs.
294
494
  for (const other of dispatches.values()) {
@@ -302,7 +502,7 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
302
502
  reference: Promise.resolve(deps.uncaptured ?? none(REFERENCE_NONE.notRequested)),
303
503
  ready: Promise.resolve(), settled: Promise.resolve(),
304
504
  // The delegate ladder's dispatch id is its first producer session.
305
- producers: new Set([id]), observed: new Map(),
505
+ producers: new Set([id]), observed: new Map(), writers: new Set(),
306
506
  window,
307
507
  };
308
508
  dispatches.set(id, d);
@@ -321,6 +521,51 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
321
521
  if (snapshot?.root !== undefined) window.root = snapshot.root;
322
522
  if (snapshot && !d.snapshotContaminated && dispatches.get(id) === d) d.snapshot = snapshot;
323
523
  })();
524
+ // Cross-repo P1.8 (I13): P is fixed now; each extra root is snapshotted like the change baseline, with the same bound.
525
+ if (deps.perimeter !== undefined && deps.perimeter.roots.length > 0) {
526
+ const entries = new Map<string, PerimeterEntry>();
527
+ const snapshotRoot = deps.perimeterSnapshot ?? deps.snapshot;
528
+ for (const seed of deps.perimeter.roots) {
529
+ // QA-1 F2, F4, F10: a fixed root is kept (the gate reports it) but never snapshotted.
530
+ if (seed.fixed !== undefined) {
531
+ entries.set(seed.at, { seed, pending: false, snapshot: Promise.resolve(undefined) });
532
+ continue;
533
+ }
534
+ const entry: PerimeterEntry = { seed, pending: true, snapshot: Promise.resolve(undefined) };
535
+ entry.snapshot = (async (): Promise<TreeSnapshot | undefined> => {
536
+ const controller = new AbortController();
537
+ let snapshot: TreeSnapshot | undefined;
538
+ try {
539
+ snapshot = await withTimeout(snapshotRoot(seed.at, controller.signal), deps.timeoutMs, "perimeter fingerprint");
540
+ } catch {
541
+ snapshot = undefined; // Unavailable: the gate reports the root as not observed.
542
+ } finally {
543
+ entry.pending = false;
544
+ controller.abort();
545
+ }
546
+ return entry.contaminatedBy === undefined ? snapshot : undefined;
547
+ })();
548
+ entries.set(seed.at, entry);
549
+ }
550
+ d.perimeter = {
551
+ ...(deps.perimeter.name !== undefined ? { name: deps.perimeter.name } : {}),
552
+ entries,
553
+ ...(deps.perimeter.admission !== undefined ? { admission: deps.perimeter.admission } : {}),
554
+ };
555
+ }
556
+ const readHead = deps.headState;
557
+ if (readHead !== undefined) {
558
+ d.head = (async (): Promise<HeadRead> => {
559
+ const controller = new AbortController();
560
+ try {
561
+ return await withTimeout(readHead(cwd, controller.signal), deps.timeoutMs, "dispatch head");
562
+ } catch {
563
+ return undefined; // Unreadable at dispatch: the gate fails closed when the head is readable then.
564
+ } finally {
565
+ controller.abort();
566
+ }
567
+ })();
568
+ }
324
569
  const capture = deps.capture;
325
570
  if (capture !== undefined) {
326
571
  d.reference = (async (): Promise<ReferenceState> => {
@@ -339,10 +584,17 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
339
584
  return captured ? { kind: "captured", reference: captured } : none(REFERENCE_NONE.failed);
340
585
  })();
341
586
  }
342
- d.settled = Promise.all([d.ready, d.reference]).then(() => undefined);
587
+ const perimeterSnapshots = [...(d.perimeter?.entries.values() ?? [])].map(entry => entry.snapshot);
588
+ d.settled = Promise.all([d.ready, d.reference, d.head, ...perimeterSnapshots]).then(() => undefined);
343
589
  return d.settled;
344
590
  },
345
591
  observeEdit,
592
+ /**
593
+ * Cross-repo QA-2 #9c: subscribes `listener` to the calls of an unattributable writer (isUnattributedWriter): observeEdit
594
+ * (before a call, no session) and record (after it, with its session). Returns the unsubscribe function.
595
+ */
596
+ onUnattributedWriter,
597
+ noteWriter,
346
598
  /**
347
599
  * The dispatch's ReferenceState. An untracked (or swept) dispatch has none. `signal` bounds the
348
600
  * wait for a capture still in flight: once it aborts, the reference is none (gate budget).
@@ -377,7 +629,7 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
377
629
  current?: TreeSnapshot,
378
630
  fallbackCwd?: string,
379
631
  committed?: readonly ChangedFile[] | "unavailable",
380
- ): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable" } {
632
+ ): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable"; unattributedWriters: string[] } {
381
633
  const d = dispatches.get(id);
382
634
  const snapshot = d?.snapshot;
383
635
  const files = new Map<string, ChangedFile>();
@@ -442,12 +694,21 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
442
694
  else if (prev.previousPath === undefined && file.previousPath !== undefined) files.set(key, { ...prev, previousPath: file.previousPath });
443
695
  }
444
696
  }
445
- return { changedFiles: [...files.values()], changeBaseline: available ? "available" : "unavailable" };
697
+ const writers = d ? d.writers : (writersBySession.get(childID) ?? new Set<string>());
698
+ return {
699
+ changedFiles: [...files.values()],
700
+ changeBaseline: available ? "available" : "unavailable",
701
+ unattributedWriters: [...writers].sort(),
702
+ };
446
703
  },
447
704
  /** The dispatch-time snapshot (QA-2.1-2: the gate digests its listed paths); undefined until settled. */
448
705
  baselineSnapshot(id: string): TreeSnapshot | undefined {
449
706
  return dispatches.get(id)?.snapshot;
450
707
  },
708
+ /** The head state read when the dispatch began; undefined when untracked or no head reader was given. */
709
+ baselineHead(id: string): Promise<HeadRead> | undefined {
710
+ return dispatches.get(id)?.head;
711
+ },
451
712
  /**
452
713
  * QA-3.1-2: how many other dispatches were live at some moment of this one's window so far and
453
714
  * work in the git tree at `root` (default: this dispatch's own root, else its cwd). Their edits
@@ -465,9 +726,23 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
465
726
  snapshotContaminatedBy(id: string): string | undefined {
466
727
  return dispatches.get(id)?.snapshotContaminatedBy;
467
728
  },
729
+ /** Cross-repo P1.8: the dispatch's perimeter beyond W, planned at dispatch; undefined when it has none or is untracked. */
730
+ perimeterOf(id: string): {
731
+ readonly name?: string;
732
+ readonly entries: ReadonlyMap<string, PerimeterEntry>;
733
+ readonly admission?: DispatchPerimeter["admission"];
734
+ } | undefined {
735
+ return dispatches.get(id)?.perimeter;
736
+ },
468
737
  record(sessionID: string, tool: string, args: unknown): void {
738
+ notifyUnattributedWriter(tool, sessionID);
469
739
  touch(sessionID);
470
- observeEdit(tool, dispatches.get(sessionID)?.cwd);
740
+ contaminateCaptures(tool, dispatches.get(sessionID)?.cwd);
741
+ if (isUnattributedWriter(tool)) {
742
+ const w = writersBySession.get(sessionID) ?? new Set<string>();
743
+ w.add(tool.toLowerCase());
744
+ writersBySession.set(sessionID, w);
745
+ }
471
746
  if (tool.toLowerCase() === "apply_patch") {
472
747
  const a = args && typeof args === "object" ? args as Record<string, unknown> : {};
473
748
  const patch = typeof a.patchText === "string" ? a.patchText : typeof a.patch === "string" ? a.patch : "";
package/src/verify/dod.ts CHANGED
@@ -14,6 +14,8 @@ export interface Check {
14
14
  expect?: string; // run: expected substring in output (optional)
15
15
  path?: string; // fileExists/schemaMatch
16
16
  schema?: string; // schemaMatch: inline JSON or a path
17
+ cwd?: string; // per-check working directory, raw trimmed text (absent when empty)
18
+ scope?: string; // per-check scope, raw trimmed text; validated by a later task
17
19
  }
18
20
 
19
21
  export type DoDKind = "deterministic" | "checker" | "none";
@@ -217,6 +219,47 @@ function parseKvPairs(s: string): Record<string, string> {
217
219
  return result;
218
220
  }
219
221
 
222
+ /**
223
+ * Per-check `cwd=` / `scope=` keys (cross-repo P2.1). Unlike parseKvPairs, a key
224
+ * counts only at a token boundary (start of the text or after whitespace) and
225
+ * outside any double-quoted span, so `--cwd=x` or `command="npm --cwd=x test"`
226
+ * are never read as keys. The last occurrence wins; an empty value is absent.
227
+ */
228
+ function parseCheckScopeKeys(s: string): { cwd?: string; scope?: string } {
229
+ const found: { cwd?: string; scope?: string } = {};
230
+ let inQuote = false;
231
+ let i = 0;
232
+ while (i < s.length) {
233
+ if (s[i] === '"') {
234
+ inQuote = !inQuote;
235
+ i++;
236
+ continue;
237
+ }
238
+ const m = !inQuote && (i === 0 || /\s/.test(s[i - 1]!)) ? /^(cwd|scope)=/.exec(s.slice(i)) : null;
239
+ if (!m) {
240
+ i++;
241
+ continue;
242
+ }
243
+ const key = m[1] as "cwd" | "scope";
244
+ i += m[0].length;
245
+ let value: string;
246
+ const close = s[i] === '"' ? s.indexOf('"', i + 1) : -1;
247
+ if (close !== -1) {
248
+ value = s.slice(i + 1, close);
249
+ i = close + 1;
250
+ } else {
251
+ let end = i;
252
+ while (end < s.length && !/\s/.test(s[end]!)) end++;
253
+ value = s.slice(i, end);
254
+ i = end;
255
+ }
256
+ value = value.trim();
257
+ if (value) found[key] = value;
258
+ else delete found[key];
259
+ }
260
+ return found;
261
+ }
262
+
220
263
  // ---------------------------------------------------------------------------
221
264
  // parseAcceptanceBlock
222
265
  // ---------------------------------------------------------------------------
@@ -272,6 +315,9 @@ export function parseAcceptanceBlock(text: string, source: DoDSource = "explicit
272
315
  if (kvPairs["expect"] !== undefined) check.expect = kvPairs["expect"];
273
316
  if (kvPairs["path"] !== undefined) check.path = kvPairs["path"];
274
317
  if (kvPairs["schema"] !== undefined) check.schema = kvPairs["schema"];
318
+ const scoped = parseCheckScopeKeys(remainder);
319
+ if (scoped.cwd !== undefined) check.cwd = scoped.cwd;
320
+ if (scoped.scope !== undefined) check.scope = scoped.scope;
275
321
  checks.push(check);
276
322
  } else if (lline.startsWith("cwd:")) {
277
323
  const rest = line.slice("cwd:".length).trim().replace(/^(["'])(.*)\1$/, "$2").trim();