opencode-model-router 2.7.0 → 2.9.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 (111) hide show
  1. package/CHANGELOG.md +583 -0
  2. package/README.md +20 -0
  3. package/package.json +5 -1
  4. package/src/commands/approvals.ts +354 -0
  5. package/src/commands/output.ts +34 -1
  6. package/src/compat/background.ts +2439 -0
  7. package/src/compat/child-session.ts +6 -0
  8. package/src/compat/turn-state.ts +215 -0
  9. package/src/compat/v2-client.ts +136 -17
  10. package/src/compat/v2-hooks.ts +2853 -109
  11. package/src/compat/v2-observations.ts +328 -0
  12. package/src/executor/capacity.ts +362 -0
  13. package/src/executor/child-guards.ts +40 -0
  14. package/src/executor/command.ts +265 -0
  15. package/src/executor/compile/edges.ts +809 -0
  16. package/src/executor/compile/estimate.ts +158 -0
  17. package/src/executor/compile/footprint.ts +829 -0
  18. package/src/executor/compile/index.ts +1080 -0
  19. package/src/executor/compile/parse.ts +1492 -0
  20. package/src/executor/compile/residue.ts +706 -0
  21. package/src/executor/compile/validate.ts +280 -0
  22. package/src/executor/create.ts +672 -0
  23. package/src/executor/expand.ts +551 -0
  24. package/src/executor/git.ts +1214 -0
  25. package/src/executor/host-preamble.ts +17 -0
  26. package/src/executor/instructions.ts +35 -0
  27. package/src/executor/integrate/bisect.ts +73 -0
  28. package/src/executor/integrate/checks.ts +1086 -0
  29. package/src/executor/integrate/land.ts +177 -0
  30. package/src/executor/integrate/phase-suite.ts +407 -0
  31. package/src/executor/integrate/queue.ts +3083 -0
  32. package/src/executor/integrate/run-resolver.ts +19 -0
  33. package/src/executor/launch.ts +652 -0
  34. package/src/executor/ledger.ts +2208 -0
  35. package/src/executor/observations.ts +212 -0
  36. package/src/executor/paths.ts +159 -0
  37. package/src/executor/platform.ts +39 -0
  38. package/src/executor/process-identity.ts +19 -0
  39. package/src/executor/qa-loop.ts +470 -0
  40. package/src/executor/recovery.ts +403 -0
  41. package/src/executor/runtime.ts +6233 -0
  42. package/src/executor/schedule.ts +246 -0
  43. package/src/executor/slots/env.ts +145 -0
  44. package/src/executor/slots/pool.ts +1564 -0
  45. package/src/executor/slots/provision.ts +853 -0
  46. package/src/executor/tool.ts +534 -0
  47. package/src/executor/types.ts +2064 -0
  48. package/src/executor/unattended.ts +488 -0
  49. package/src/guard/store.ts +3 -1
  50. package/src/index.ts +1789 -288
  51. package/src/router/config.ts +823 -26
  52. package/src/router/dispatch-header.ts +95 -2
  53. package/src/router/git-tools.ts +266 -19
  54. package/src/router/leases.ts +1469 -0
  55. package/src/router/logger.ts +44 -32
  56. package/src/router/protocol.ts +44 -10
  57. package/src/router/role-agents.ts +334 -20
  58. package/src/router/roles-config.ts +93 -1
  59. package/src/router/roles.ts +1 -1
  60. package/src/router/run-tools.ts +56 -4
  61. package/src/router/sessions.ts +11 -0
  62. package/src/router/tool-paths.ts +308 -0
  63. package/src/router/work-roots.ts +86 -0
  64. package/src/routing/advisor/findings.ts +25 -5
  65. package/src/routing/classify/index.ts +7 -1
  66. package/src/routing/classify/route-line.ts +96 -5
  67. package/src/routing/classify/rules.ts +11 -0
  68. package/src/routing/classify/types.ts +26 -0
  69. package/src/routing/commands/stats.ts +2 -2
  70. package/src/routing/outcomes/durations.ts +225 -0
  71. package/src/routing/outcomes/index.ts +59 -2
  72. package/src/routing/outcomes/persist.ts +409 -0
  73. package/src/routing/outcomes/signals.ts +17 -0
  74. package/src/routing/outcomes/stats.ts +170 -11
  75. package/src/routing/outcomes/timings.ts +836 -0
  76. package/src/routing/outcomes/types.ts +98 -0
  77. package/src/routing/roles/admission.ts +1028 -0
  78. package/src/routing/roles/approvals.ts +957 -0
  79. package/src/routing/roles/binding.ts +116 -13
  80. package/src/routing/roles/check-placement.ts +112 -0
  81. package/src/routing/roles/git-root.ts +500 -0
  82. package/src/routing/roles/orphans.ts +68 -0
  83. package/src/routing/roles/policy.ts +30 -3
  84. package/src/routing/roles/read-set.ts +325 -0
  85. package/src/routing/roles/work-root.ts +12 -2
  86. package/src/routing/wire/dispatch.ts +697 -30
  87. package/src/routing/wire/hint.ts +56 -8
  88. package/src/routing/wire/working-set.ts +58 -0
  89. package/src/util/linear-trim.ts +32 -0
  90. package/src/v2.ts +94 -49
  91. package/src/verify/batch.ts +7 -2
  92. package/src/verify/branch.ts +141 -0
  93. package/src/verify/canonical-path.ts +35 -0
  94. package/src/verify/deterministic.ts +268 -17
  95. package/src/verify/dispatch.ts +348 -37
  96. package/src/verify/dod.ts +46 -0
  97. package/src/verify/edges.ts +817 -0
  98. package/src/verify/exec.ts +52 -9
  99. package/src/verify/gate.ts +349 -16
  100. package/src/verify/git-top.ts +43 -0
  101. package/src/verify/head.ts +107 -0
  102. package/src/verify/pending.ts +1846 -18
  103. package/src/verify/perimeter.ts +1186 -0
  104. package/src/verify/pin.ts +109 -0
  105. package/src/verify/plan-task.ts +729 -0
  106. package/src/verify/reference.ts +297 -8
  107. package/src/verify/risk.ts +16 -3
  108. package/src/verify/runner.ts +706 -32
  109. package/src/verify/tree.ts +372 -16
  110. package/src/verify/types.ts +66 -2
  111. package/src/verify/wiring.ts +1594 -46
@@ -13,19 +13,27 @@ import type { DoD, InferHints } from "./dod";
13
13
  import { isIncompleteReason } from "./checker";
14
14
  import { stripDispatchHeader } from "../router/dispatch-header";
15
15
  import { DEFAULT_IDLE_TTL_MS } from "../router/idle-sweep";
16
- import { basename, dirname, join, resolve } from "node:path";
17
- import { existsSync, realpathSync } from "node:fs";
16
+ import { resolve } from "node:path";
17
+ import { existsSync } from "node:fs";
18
+ import { canonicalPath } from "./canonical-path";
18
19
  import type { ReferenceState, Verdict } from "./types";
19
20
  import type { DispatchReference } from "./reference";
20
21
  import { REFERENCE_NONE } from "./baseline";
21
22
  import { neutralizeDirectives } from "./pending";
22
23
  import { withTimeout } from "./timeout";
24
+ import { applyPatchHeaderPaths } from "../router/tool-paths";
25
+ import type { HeadRead } from "./head";
23
26
 
24
27
  export interface TreeSnapshot {
25
28
  cwd: string;
26
29
  /** Real path of `git rev-parse --show-toplevel` at capture time. */
27
30
  root?: string;
28
31
  head: string;
32
+ /**
33
+ * I7 (P0.2): the branch checked out at capture (`git symbolic-ref -q HEAD`): its short name (`feat/x`), or null for a
34
+ * detached HEAD. Absent or undefined: unknown (the command failed, timed out or was aborted). branch.ts compares two.
35
+ */
36
+ branch?: string | null;
29
37
  fingerprint: string;
30
38
  dirty: boolean;
31
39
  files: ChangedFile[];
@@ -36,6 +44,12 @@ export interface TreeSnapshot {
36
44
  * "unavailable" (over the digest bounds, or unreadable) and absent both mean no per-file proof.
37
45
  */
38
46
  digests?: ReadonlyMap<string, string> | "unavailable";
47
+ /**
48
+ * Cross-repo P2.6 (SD11): a content digest of the repository's ignored files (path, size and content; nothing under a
49
+ * `node_modules` segment), so a linked package's ignored `dist/` can be pinned. "over-bounds": more files or bytes than the
50
+ * bounds allow. Absent: not requested (SnapshotOptions.ignoredDigest) or unavailable (any error).
51
+ */
52
+ ignored?: string | "over-bounds";
39
53
  }
40
54
 
41
55
  /** QA-2.1-2: the digest of a path that does not exist. */
@@ -54,37 +68,94 @@ export interface DispatchCaptureDeps {
54
68
  capture?: (cwd: string, signal: AbortSignal) => Promise<DispatchReference | undefined>;
55
69
  /** The reference when `capture` is absent. Default: none (REFERENCE_NONE.notRequested). */
56
70
  uncaptured?: ReferenceState;
57
- /** Bounds the snapshot and the capture, each (baselineTimeoutMs). */
71
+ /**
72
+ * The cheap head-state read (src/verify/head.ts readHead; "none": no repository or an unborn HEAD) the branch-switch rule
73
+ * compares at the gate. Independent of
74
+ * the snapshot: a snapshot that failed, timed out or was discarded does not lose it. Absent: no head baseline.
75
+ */
76
+ headState?: (cwd: string, signal: AbortSignal) => Promise<HeadRead>;
77
+ /**
78
+ * Cross-repo P1.8 (I13): the extra roots of the dispatch's perimeter P, each snapshotted with `snapshot` next to the change
79
+ * baseline and bounded by `timeoutMs`. Absent: no perimeter, and nothing else is snapshotted (I9).
80
+ */
81
+ perimeter?: DispatchPerimeter;
82
+ /** Cross-repo QA-1 F4 (I11): how an extra root of the perimeter is snapshotted (hardened git). Absent: `snapshot`. */
83
+ perimeterSnapshot?: (cwd: string, signal: AbortSignal) => Promise<TreeSnapshot | undefined>;
84
+ /** Bounds the snapshot, the head read and the capture, each (baselineTimeoutMs). */
58
85
  timeoutMs: number;
59
86
  }
60
87
 
88
+ /** Cross-repo P1.8: one extra root of a perimeter, as planned at dispatch (perimeter.ts planPerimeter). */
89
+ export interface PerimeterSeed {
90
+ /** Where it is snapshotted: a working-set worktree, or the real path of a package link of W. */
91
+ readonly at: string;
92
+ /** The repository's name when known (the working-set location's); else the basename of its git top level. */
93
+ readonly name?: string;
94
+ /** Link targets only: whether the git top level the snapshot names is admitted (checked at the gate). */
95
+ readonly admit?: (root: string) => boolean;
96
+ /**
97
+ * Cross-repo QA-1: a root that is never snapshotted, and the status the gate reports for it. "unobserved": past PERIMETER_MAX
98
+ * (F2), or the placeholder of a perimeter that could not be planned (F10); I4 refuses it when writers ran. "unadmitted" (F4):
99
+ * a linked directory whose repository is not admitted (`routing.repoParents` / `repoDepth` / `repoExclude`) or that is not a
100
+ * git repository; git never runs there (I11, I12), and I8 names it as not observed.
101
+ */
102
+ readonly fixed?: "unobserved" | "unadmitted";
103
+ /** QA-1 F11: a worktree of W's own repository (the same git common directory): I4 suggests `branch=`, not `repo=`. */
104
+ readonly sameRepository?: boolean;
105
+ /**
106
+ * Cross-repo P2b.3: where the root came from, set by `planPerimeter`: "working-set" (a working-set worktree other than W),
107
+ * "link" (a package link target of W), "edge" (cross-repo P3c.3, SD-P3c-2: the repository of a declared dependency edge of W
108
+ * outside `node_modules`, edges.ts; a link and an edge into one repository are one "link" seed). Consumer discovery scans only
109
+ * the working-set roots. An "edge" seed is observed like a link target (I4, I8) but never pinned (F3).
110
+ */
111
+ readonly origin?: "w" | "working-set" | "link" | "edge";
112
+ /**
113
+ * 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
114
+ * keeps its working-set semantics (consumer discovery, I13) and is pinned at dispatch like a link target.
115
+ */
116
+ readonly linked?: boolean;
117
+ /**
118
+ * 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
119
+ * into it). It keeps its working-set semantics; unlike `linked`, it is not pinned (F3).
120
+ */
121
+ readonly edged?: true;
122
+ }
123
+
124
+ /** Cross-repo P1.8: the perimeter P of a dispatch beyond W. */
125
+ export interface DispatchPerimeter {
126
+ /** W's repository name when the grant's location names it. */
127
+ readonly name?: string;
128
+ readonly roots: readonly PerimeterSeed[];
129
+ /**
130
+ * Cross-repo P3c.4 (SD-P3c-9): the admission W's package links and declared edges were read with (perimeter.ts
131
+ * `AdmissionData`: the parents in both spellings, depth, excludes, working set). A deferred perimeter freezes it so that
132
+ * `router_verify` reads W's dependency targets again as the dispatch did. Absent: none recorded (links only at router_verify).
133
+ */
134
+ readonly admission?: {
135
+ readonly parents: readonly string[];
136
+ readonly depth: number;
137
+ readonly exclude?: readonly string[];
138
+ readonly workingSet: readonly { readonly worktree: string; readonly name?: string }[];
139
+ };
140
+ }
141
+
142
+ /** Cross-repo P1.8: the dispatch-time state of one extra root of the perimeter. */
143
+ export interface PerimeterEntry {
144
+ readonly seed: PerimeterSeed;
145
+ /** Its dispatch snapshot is in flight. */
146
+ pending: boolean;
147
+ /** The first tool whose call may have written into this root while its snapshot was in flight: the snapshot is discarded. */
148
+ contaminatedBy?: string;
149
+ /** Settles once, never rejects; undefined when unavailable, timed out or discarded. */
150
+ snapshot: Promise<TreeSnapshot | undefined>;
151
+ }
152
+
61
153
  function none(reason: string): ReferenceState {
62
154
  return { kind: "none", reason };
63
155
  }
64
156
 
65
- /**
66
- * QA-2.1-8: the canonical spelling of `path`, so a Windows 8.3 short name (`C:\Users\MARQUI~1\…`),
67
- * a junction or symlink alias, and the long real path of one file key the same change-set entry.
68
- * The native realpath of the path, or of its nearest existing ancestor with the missing tail
69
- * appended (a deleted file keeps its directory's canonical spelling); lexical `resolve` when no
70
- * ancestor resolves.
71
- */
72
- export function canonicalPath(path: string): string {
73
- const absolute = resolve(path);
74
- let head = absolute;
75
- const tail: string[] = [];
76
- for (;;) {
77
- try {
78
- const real = realpathSync.native(head);
79
- return tail.length === 0 ? real : join(real, ...tail.reverse());
80
- } catch {
81
- const parent = dirname(head);
82
- if (parent === head) return absolute;
83
- tail.push(basename(head));
84
- head = parent;
85
- }
86
- }
87
- }
157
+ // QA-2.1-8 / QA-1.3-16: canonicalPath lives in the leaf module canonical-path.ts; re-exported for every caller.
158
+ export { canonicalPath };
88
159
 
89
160
  /** A change-set key: the canonical path with "/" separators, case-folded on win32. */
90
161
  function pathKey(path: string): string {
@@ -117,6 +188,54 @@ const NON_WRITING_TOOLS = new Set([
117
188
  "list_mcp_resources", "list_mcp_resource_templates", "read_mcp_resource",
118
189
  "delegate", "router_verify",
119
190
  ]);
191
+ /**
192
+ * P0.3: router tools that only read (copied, not imported: this module takes no plugin SDK; a pin
193
+ * test compares them with the sources). Exact names: a `context7_*` prefix would also admit a
194
+ * future write tool.
195
+ */
196
+ const READ_ONLY_ROUTER_TOOLS = new Set([
197
+ "router_git_status", "router_git_log", "router_git_diff", "router_git_show", "router_git_blame", "router_git_ls_files",
198
+ "router_request_authority",
199
+ ]);
200
+ const BRAVE_TOOLS = ["web_search", "local_search", "news_search", "image_search", "video_search", "summarizer", "llm_context"]
201
+ .map(t => `brave_${t}`);
202
+ const READ_ONLY_MCP_TOOLS = new Set([
203
+ "context7_resolve-library-id", "context7_query-docs", "context7_get-library-docs",
204
+ // The server may be mounted as `brave` with tools already named `brave_*`.
205
+ ...BRAVE_TOOLS, ...BRAVE_TOOLS.map(t => `brave_${t}`),
206
+ ]);
207
+
208
+ /** Whether `tool` is known never to write the workspace (case-insensitive). */
209
+ export function isNonWritingTool(tool: string): boolean {
210
+ const n = tool.toLowerCase();
211
+ return NON_WRITING_TOOLS.has(n) || READ_ONLY_ROUTER_TOOLS.has(n) || READ_ONLY_MCP_TOOLS.has(n);
212
+ }
213
+
214
+ /**
215
+ * P0.3 (invariant I5): a tool that may write but whose writes the router cannot attribute to files
216
+ * (shells, `router_run`, `execute`, MCP and custom tools). An empty change set from a producer
217
+ * that ran one of these is not proof that nothing changed.
218
+ */
219
+ export function isUnattributedWriter(tool: string): boolean {
220
+ const n = tool.toLowerCase();
221
+ // F2: a nested child's own writes are attributed to the child's session, not to this producer's lineage, so delegating
222
+ // tools count as writers here. They stay non-writing for observeEdit (they do not contaminate captures).
223
+ if (DELEGATING_TOOLS.has(n)) return true;
224
+ return !WRITE_TOOLS.has(n) && !isNonWritingTool(n);
225
+ }
226
+
227
+ /** F2: tools that start a child session whose writes are not in the caller's lineage. */
228
+ const DELEGATING_TOOLS = new Set(["task", "delegate", "subagent"]);
229
+
230
+ /**
231
+ * Whether a call to `tool` may write the workspace behind the router's back, so that it discards every in-flight snapshot,
232
+ * capture and link pin. The one rule for both contaminateCaptures and the onUnattributedWriter signal (M3: they must not drift).
233
+ * A delegating tool never does: its child session is observed on its own, and it writes nothing itself (it is only an
234
+ * unattributed writer for the producer's empty-change-set caveat, isUnattributedWriter).
235
+ */
236
+ function mayContaminate(tool: string): boolean {
237
+ return !isNonWritingTool(tool) && !DELEGATING_TOOLS.has(tool.toLowerCase());
238
+ }
120
239
 
121
240
  export interface ChangedFile {
122
241
  path: string;
@@ -125,9 +244,24 @@ export interface ChangedFile {
125
244
  previousPath?: string;
126
245
  }
127
246
 
247
+ /**
248
+ * Phase 2.1.4.b: the change set of a dispatch, computed when its child ends (captureDelta) so a background
249
+ * completion verifies what the child changed, not what the tree holds when the processor finally runs.
250
+ */
251
+ export interface DispatchDelta {
252
+ readonly callID: string;
253
+ readonly childSessionID: string;
254
+ /** Files attributed to the dispatch; "unavailable" when attribution failed (never [] for a failure). */
255
+ readonly files: readonly ChangedFile[] | "unavailable";
256
+ /** Set when a foreign write contaminated the dispatch's snapshot (the change set is then unavailable). */
257
+ readonly contaminatedBy?: string;
258
+ readonly capturedAt: number;
259
+ }
260
+
128
261
  /** Derive a {path,status} record from a write/edit tool call, or null. */
129
262
  export function extractChangedFile(tool: string, args: unknown): ChangedFile | null {
130
- if (!WRITE_TOOLS.has(tool)) return null;
263
+ const name = tool.toLowerCase();
264
+ if (!WRITE_TOOLS.has(name)) return null;
131
265
  const a = (args ?? {}) as Record<string, unknown>;
132
266
  const path =
133
267
  typeof a.filePath === "string"
@@ -138,7 +272,7 @@ export function extractChangedFile(tool: string, args: unknown): ChangedFile | n
138
272
  ? a.file
139
273
  : "";
140
274
  if (!path) return null;
141
- const status = tool === "write" ? "written" : "modified";
275
+ const status = name === "write" ? "written" : "modified";
142
276
  return { path, status };
143
277
  }
144
278
 
@@ -183,6 +317,11 @@ interface DispatchRecord {
183
317
  /** QA-3.1-2: this dispatch's lifetime, for concurrentDispatches. */
184
318
  window: DispatchWindow;
185
319
  snapshot?: TreeSnapshot;
320
+ /**
321
+ * The head state read when the dispatch began (branch-switch baseline). Never discarded on contamination: a write does not
322
+ * change what HEAD was. Resolves undefined when the read failed or timed out; never rejects.
323
+ */
324
+ head?: Promise<HeadRead>;
186
325
  capturePending: boolean;
187
326
  /** An overlapping edit was observed while the capture was in flight: the reference is none. */
188
327
  captureContaminated: boolean;
@@ -203,6 +342,15 @@ interface DispatchRecord {
203
342
  * gate judges the cumulative change since the reference, not only its own attempt's edits.
204
343
  */
205
344
  observed: Map<string, ChangedFile>;
345
+ /** P0.3: the unattributable writers (isUnattributedWriter) of every session in `producers`. */
346
+ writers: Set<string>;
347
+ /** Cross-repo P1.8 (I13): the extra roots of the dispatch's perimeter, by snapshot directory; absent: no perimeter. */
348
+ perimeter?: {
349
+ readonly name?: string;
350
+ readonly entries: Map<string, PerimeterEntry>;
351
+ /** Cross-repo P3c.4: the admission the perimeter was planned with (DispatchPerimeter.admission). */
352
+ readonly admission?: DispatchPerimeter["admission"];
353
+ };
206
354
  }
207
355
 
208
356
  /**
@@ -213,16 +361,49 @@ interface DispatchRecord {
213
361
  export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
214
362
  const now = options.now ?? Date.now;
215
363
  const bySession = new Map<string, Map<string, string>>();
364
+ /** P0.3: per session, the lowercased names of the unattributable writers it ran. */
365
+ const writersBySession = new Map<string, Set<string>>();
216
366
  const lastTouch = new Map<string, number>();
217
367
  const dispatches = new Map<string, DispatchRecord>();
218
368
 
369
+ /** Cross-repo QA-2 #9c: subscribers told when a call by an unattributable writer (isUnattributedWriter) is seen. */
370
+ const unattributedWriterListeners = new Set<(tool: string, sessionID?: string) => void>();
371
+ function onUnattributedWriter(listener: (tool: string, sessionID?: string) => void): () => void {
372
+ unattributedWriterListeners.add(listener);
373
+ return () => {
374
+ unattributedWriterListeners.delete(listener);
375
+ };
376
+ }
377
+ function notifyUnattributedWriter(tool: string, sessionID?: string): void {
378
+ // M3: the same rule as contaminateCaptures; a delegating tool counts as a writer for the tally, not for in-flight pins.
379
+ if (!isUnattributedWriter(tool) || !mayContaminate(tool)) return;
380
+ for (const listener of [...unattributedWriterListeners]) {
381
+ try {
382
+ listener(tool, sessionID);
383
+ } catch {
384
+ // a subscriber never breaks the store
385
+ }
386
+ }
387
+ }
388
+
219
389
  function observeEdit(tool: string, cwd?: string): void {
390
+ notifyUnattributedWriter(tool);
391
+ contaminateCaptures(tool, cwd);
392
+ }
393
+
394
+ function contaminateCaptures(tool: string, cwd?: string): void {
220
395
  // 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;
396
+ if (!mayContaminate(tool)) return;
222
397
  // Unknown directory is conservatively treated as overlapping every capture.
223
398
  const overlaps = (other: string) => !cwd || pathKey(cwd) === pathKey(other)
224
399
  || pathKey(cwd).startsWith(pathKey(other) + "/") || pathKey(other).startsWith(pathKey(cwd) + "/");
225
400
  for (const d of dispatches.values()) {
401
+ // Cross-repo P1.8: a write that may land in an extra root of the perimeter discards that root's in-flight snapshot.
402
+ // QA-1 F1: an unattributable writer's directory says nothing about where it writes (router_run's cwd is always W), so it
403
+ // discards every in-flight perimeter snapshot, whatever its cwd.
404
+ for (const entry of d.perimeter?.entries.values() ?? []) {
405
+ if (entry.pending && (isUnattributedWriter(tool) || overlaps(entry.seed.at))) entry.contaminatedBy ??= tool;
406
+ }
226
407
  if (!overlaps(d.cwd)) continue;
227
408
  if (d.snapshotPending) {
228
409
  d.snapshotContaminated = true;
@@ -253,6 +434,17 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
253
434
  lastTouch.set(sessionID, now());
254
435
  }
255
436
 
437
+ /**
438
+ * F1: notes, before a call runs, that `sessionID` is about to run a tool whose writes the router cannot attribute. A call
439
+ * that ends in error (or is bypassed) never reaches the after-hook's record(), so the tally is also kept here (a Set: idempotent).
440
+ */
441
+ function noteWriter(sessionID: string, tool: string): void {
442
+ if (!isUnattributedWriter(tool)) return;
443
+ const w = writersBySession.get(sessionID) ?? new Set<string>();
444
+ w.add(tool.toLowerCase());
445
+ writersBySession.set(sessionID, w);
446
+ }
447
+
256
448
  /** QA-2.1-1: folds one producer session's tool-observed files into its dispatch's lineage. */
257
449
  function fold(d: DispatchRecord, sessionID: string): void {
258
450
  for (const [path, status] of bySession.get(sessionID) ?? []) {
@@ -262,12 +454,14 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
262
454
  const prev = d.observed.get(key);
263
455
  d.observed.set(key, { path: absolute, status: prev?.status === "written" ? "written" : status });
264
456
  }
457
+ for (const tool of writersBySession.get(sessionID) ?? []) d.writers.add(tool);
265
458
  }
266
459
 
267
460
  function evict(sessionID: string): void {
268
461
  // A retry's session is cleared after its gate: keep its edits in every lineage it belongs to.
269
462
  for (const d of dispatches.values()) if (d.producers.has(sessionID)) fold(d, sessionID);
270
463
  bySession.delete(sessionID);
464
+ writersBySession.delete(sessionID);
271
465
  lastTouch.delete(sessionID);
272
466
  const d = dispatches.get(sessionID);
273
467
  d?.captureController.abort();
@@ -289,6 +483,7 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
289
483
  const existing = dispatches.get(id);
290
484
  if (existing) return existing.settled;
291
485
  bySession.delete(id);
486
+ writersBySession.delete(id);
292
487
  const window: DispatchWindow = { cwd, overlapping: new Set() };
293
488
  // QA-3.1-2: every live dispatch overlaps this one's window, and this one overlaps theirs.
294
489
  for (const other of dispatches.values()) {
@@ -302,7 +497,7 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
302
497
  reference: Promise.resolve(deps.uncaptured ?? none(REFERENCE_NONE.notRequested)),
303
498
  ready: Promise.resolve(), settled: Promise.resolve(),
304
499
  // The delegate ladder's dispatch id is its first producer session.
305
- producers: new Set([id]), observed: new Map(),
500
+ producers: new Set([id]), observed: new Map(), writers: new Set(),
306
501
  window,
307
502
  };
308
503
  dispatches.set(id, d);
@@ -321,6 +516,51 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
321
516
  if (snapshot?.root !== undefined) window.root = snapshot.root;
322
517
  if (snapshot && !d.snapshotContaminated && dispatches.get(id) === d) d.snapshot = snapshot;
323
518
  })();
519
+ // Cross-repo P1.8 (I13): P is fixed now; each extra root is snapshotted like the change baseline, with the same bound.
520
+ if (deps.perimeter !== undefined && deps.perimeter.roots.length > 0) {
521
+ const entries = new Map<string, PerimeterEntry>();
522
+ const snapshotRoot = deps.perimeterSnapshot ?? deps.snapshot;
523
+ for (const seed of deps.perimeter.roots) {
524
+ // QA-1 F2, F4, F10: a fixed root is kept (the gate reports it) but never snapshotted.
525
+ if (seed.fixed !== undefined) {
526
+ entries.set(seed.at, { seed, pending: false, snapshot: Promise.resolve(undefined) });
527
+ continue;
528
+ }
529
+ const entry: PerimeterEntry = { seed, pending: true, snapshot: Promise.resolve(undefined) };
530
+ entry.snapshot = (async (): Promise<TreeSnapshot | undefined> => {
531
+ const controller = new AbortController();
532
+ let snapshot: TreeSnapshot | undefined;
533
+ try {
534
+ snapshot = await withTimeout(snapshotRoot(seed.at, controller.signal), deps.timeoutMs, "perimeter fingerprint");
535
+ } catch {
536
+ snapshot = undefined; // Unavailable: the gate reports the root as not observed.
537
+ } finally {
538
+ entry.pending = false;
539
+ controller.abort();
540
+ }
541
+ return entry.contaminatedBy === undefined ? snapshot : undefined;
542
+ })();
543
+ entries.set(seed.at, entry);
544
+ }
545
+ d.perimeter = {
546
+ ...(deps.perimeter.name !== undefined ? { name: deps.perimeter.name } : {}),
547
+ entries,
548
+ ...(deps.perimeter.admission !== undefined ? { admission: deps.perimeter.admission } : {}),
549
+ };
550
+ }
551
+ const readHead = deps.headState;
552
+ if (readHead !== undefined) {
553
+ d.head = (async (): Promise<HeadRead> => {
554
+ const controller = new AbortController();
555
+ try {
556
+ return await withTimeout(readHead(cwd, controller.signal), deps.timeoutMs, "dispatch head");
557
+ } catch {
558
+ return undefined; // Unreadable at dispatch: the gate fails closed when the head is readable then.
559
+ } finally {
560
+ controller.abort();
561
+ }
562
+ })();
563
+ }
324
564
  const capture = deps.capture;
325
565
  if (capture !== undefined) {
326
566
  d.reference = (async (): Promise<ReferenceState> => {
@@ -339,10 +579,17 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
339
579
  return captured ? { kind: "captured", reference: captured } : none(REFERENCE_NONE.failed);
340
580
  })();
341
581
  }
342
- d.settled = Promise.all([d.ready, d.reference]).then(() => undefined);
582
+ const perimeterSnapshots = [...(d.perimeter?.entries.values() ?? [])].map(entry => entry.snapshot);
583
+ d.settled = Promise.all([d.ready, d.reference, d.head, ...perimeterSnapshots]).then(() => undefined);
343
584
  return d.settled;
344
585
  },
345
586
  observeEdit,
587
+ /**
588
+ * Cross-repo QA-2 #9c: subscribes `listener` to the calls of an unattributable writer (isUnattributedWriter): observeEdit
589
+ * (before a call, no session) and record (after it, with its session). Returns the unsubscribe function.
590
+ */
591
+ onUnattributedWriter,
592
+ noteWriter,
346
593
  /**
347
594
  * The dispatch's ReferenceState. An untracked (or swept) dispatch has none. `signal` bounds the
348
595
  * wait for a capture still in flight: once it aborts, the reference is none (gate budget).
@@ -377,7 +624,7 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
377
624
  current?: TreeSnapshot,
378
625
  fallbackCwd?: string,
379
626
  committed?: readonly ChangedFile[] | "unavailable",
380
- ): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable" } {
627
+ ): { changedFiles: ChangedFile[]; changeBaseline: "available" | "unavailable"; unattributedWriters: string[] } {
381
628
  const d = dispatches.get(id);
382
629
  const snapshot = d?.snapshot;
383
630
  const files = new Map<string, ChangedFile>();
@@ -442,12 +689,31 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
442
689
  else if (prev.previousPath === undefined && file.previousPath !== undefined) files.set(key, { ...prev, previousPath: file.previousPath });
443
690
  }
444
691
  }
445
- return { changedFiles: [...files.values()], changeBaseline: available ? "available" : "unavailable" };
692
+ const writers = d ? d.writers : (writersBySession.get(childID) ?? new Set<string>());
693
+ return {
694
+ changedFiles: [...files.values()],
695
+ changeBaseline: available ? "available" : "unavailable",
696
+ unattributedWriters: [...writers].sort(),
697
+ };
446
698
  },
447
699
  /** The dispatch-time snapshot (QA-2.1-2: the gate digests its listed paths); undefined until settled. */
448
700
  baselineSnapshot(id: string): TreeSnapshot | undefined {
449
701
  return dispatches.get(id)?.snapshot;
450
702
  },
703
+ /** The head state read when the dispatch began; undefined when untracked or no head reader was given. */
704
+ baselineHead(id: string): Promise<HeadRead> | undefined {
705
+ return dispatches.get(id)?.head;
706
+ },
707
+ /**
708
+ * QA-SYNC1-3: the unattributed writers `delta(id, childID)` would report (sorted), read without joining `childID` to the
709
+ * lineage: a held registration journals them, so the gate re-run after a restart keeps them.
710
+ */
711
+ unattributedWritersOf(id: string, childID: string): string[] {
712
+ const d = dispatches.get(id);
713
+ const writers = new Set<string>(d ? d.writers : []);
714
+ for (const producer of d ? [...d.producers, childID] : [childID]) for (const tool of writersBySession.get(producer) ?? []) writers.add(tool);
715
+ return [...writers].sort();
716
+ },
451
717
  /**
452
718
  * QA-3.1-2: how many other dispatches were live at some moment of this one's window so far and
453
719
  * work in the git tree at `root` (default: this dispatch's own root, else its cwd). Their edits
@@ -465,14 +731,26 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
465
731
  snapshotContaminatedBy(id: string): string | undefined {
466
732
  return dispatches.get(id)?.snapshotContaminatedBy;
467
733
  },
734
+ /** Cross-repo P1.8: the dispatch's perimeter beyond W, planned at dispatch; undefined when it has none or is untracked. */
735
+ perimeterOf(id: string): {
736
+ readonly name?: string;
737
+ readonly entries: ReadonlyMap<string, PerimeterEntry>;
738
+ readonly admission?: DispatchPerimeter["admission"];
739
+ } | undefined {
740
+ return dispatches.get(id)?.perimeter;
741
+ },
468
742
  record(sessionID: string, tool: string, args: unknown): void {
743
+ notifyUnattributedWriter(tool, sessionID);
469
744
  touch(sessionID);
470
- observeEdit(tool, dispatches.get(sessionID)?.cwd);
745
+ contaminateCaptures(tool, dispatches.get(sessionID)?.cwd);
746
+ if (isUnattributedWriter(tool)) {
747
+ const w = writersBySession.get(sessionID) ?? new Set<string>();
748
+ w.add(tool.toLowerCase());
749
+ writersBySession.set(sessionID, w);
750
+ }
471
751
  if (tool.toLowerCase() === "apply_patch") {
472
- const a = args && typeof args === "object" ? args as Record<string, unknown> : {};
473
- const patch = typeof a.patchText === "string" ? a.patchText : typeof a.patch === "string" ? a.patch : "";
474
752
  const files = bySession.get(sessionID) ?? new Map<string, string>();
475
- for (const match of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)) files.set(match[1].trim(), "modified");
753
+ for (const p of applyPatchHeaderPaths(args)) files.set(p, "modified");
476
754
  bySession.set(sessionID, files);
477
755
  }
478
756
  const cf = extractChangedFile(tool, args);
@@ -491,6 +769,39 @@ export function createChangedFileStore(options: ChangedFileStoreOptions = {}) {
491
769
  if (!m) return [];
492
770
  return [...m.entries()].map(([path, status]) => ({ path, status }));
493
771
  },
772
+ /**
773
+ * Phase 2.1.4.b: freezes the files the child changed so far (the tool calls observed in its session)
774
+ * at child end. A contaminated dispatch snapshot makes the set "unavailable", as the foreground gate
775
+ * treats it. Pure read: the child's record stays until clear(). QA-2.1-7: the dispatch record is keyed by its dispatch
776
+ * id (`task:<parent>:<callID>`), which the caller passes as `dispatchID`; it defaults to `callID`.
777
+ */
778
+ captureDelta(callID: string, childSessionID: string, dispatchID: string = callID): DispatchDelta {
779
+ const contaminatedBy = dispatches.get(dispatchID)?.snapshotContaminatedBy;
780
+ const files = contaminatedBy !== undefined ? "unavailable" : [...(bySession.get(childSessionID)?.entries() ?? [])].map(
781
+ ([path, status]): ChangedFile => ({ path, status }),
782
+ );
783
+ return {
784
+ callID,
785
+ childSessionID,
786
+ files,
787
+ ...(contaminatedBy !== undefined ? { contaminatedBy } : {}),
788
+ capturedAt: now(),
789
+ };
790
+ },
791
+ /**
792
+ * QA-2.1-17 (v2 only): a gate re-run after a restart has no observed tool calls for the child; the change set the
793
+ * restored pending entry persisted at child end is put back under the child's session, so the gate verifies what
794
+ * the child changed instead of a read-only delegation. Merges with anything recorded since.
795
+ */
796
+ seed(sessionID: string, files: readonly ChangedFile[]): void {
797
+ touch(sessionID);
798
+ let m = bySession.get(sessionID);
799
+ if (!m) {
800
+ m = new Map();
801
+ bySession.set(sessionID, m);
802
+ }
803
+ for (const file of files) if (!m.has(file.path)) m.set(file.path, file.status);
804
+ },
494
805
  clear(sessionID: string): void {
495
806
  evict(sessionID);
496
807
  },
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();