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
@@ -1,9 +1,11 @@
1
1
  // Impure, bounded Git fingerprint adapter. Never interpolates paths into a shell.
2
2
  import { execFile, spawn, type ChildProcess } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { lstat, readFile, readlink, realpath } from "node:fs/promises";
4
+ import { lstat, readdir, readFile, readlink, realpath, stat } from "node:fs/promises";
5
5
  import { constants as osConstants, setPriority } from "node:os";
6
- import { join, resolve } from "node:path";
6
+ import { extname, join, resolve } from "node:path";
7
+ import { scrubText } from "../guard/scrub";
8
+ import * as tools from "../router/git-tools";
7
9
  import { ABSENT_DIGEST, FILE_DIGEST_PREFIX, LINK_DIGEST_PREFIX, type TreeSnapshot, type ChangedFile } from "./dispatch";
8
10
 
9
11
  /** Each git process of a snapshot. */
@@ -19,6 +21,10 @@ export interface SnapshotGitOptions {
19
21
  readonly maxBuffer: number;
20
22
  /** QA-3.1-8: below-normal OS priority (VerifyBudget.lowPriority), like every other verification process. */
21
23
  readonly lowPriority: boolean;
24
+ /** Cross-repo QA-1 F4 (SnapshotOptions.hardened): the environment git runs with. Absent: the process's own (unchanged). */
25
+ readonly env?: NodeJS.ProcessEnv;
26
+ /** Cross-repo QA-1 F4: the git executable, by absolute path. Absent: `git`, looked up as before. */
27
+ readonly executable?: string;
22
28
  }
23
29
 
24
30
  /**
@@ -64,6 +70,22 @@ function killGitTree(child: ChildProcess): void {
64
70
  }
65
71
  }
66
72
 
73
+ /**
74
+ * A git process that ran and exited non-zero (I7, P0.2). `exitCode` tells an expected exit apart from a failure without
75
+ * parsing the message (`symbolic-ref -q HEAD` exits 1 on a detached HEAD). The message is the one execGit always used.
76
+ */
77
+ export class GitExitError extends Error {
78
+ constructor(readonly exitCode: number) {
79
+ super(`git exited with code ${exitCode}`);
80
+ }
81
+ }
82
+
83
+ /** The exit code a SnapshotGit rejection carries (a GitExitError, or a seam's error with a numeric `exitCode`); else undefined. */
84
+ export function gitExitCode(err: unknown): number | undefined {
85
+ const code = err && typeof err === "object" && "exitCode" in err ? (err as { exitCode: unknown }).exitCode : undefined;
86
+ return typeof code === "number" ? code : undefined;
87
+ }
88
+
67
89
  /**
68
90
  * The default SnapshotGit. QA-3.1-8: `lowPriority` applies exec.ts's rule: on POSIX
69
91
  * `nice -n 10 -- git …` (inherited from birth), on Windows PRIORITY_BELOW_NORMAL set on the child
@@ -76,10 +98,12 @@ export const execGit: SnapshotGit = (args, opts) => new Promise<string>((ok, fai
76
98
  return;
77
99
  }
78
100
  const nice = opts.lowPriority && !isWin;
101
+ const git = opts.executable ?? "git";
79
102
  let child: ChildProcess;
80
103
  try {
81
- child = spawn(nice ? "nice" : "git", nice ? ["-n", "10", "--", "git", ...args] : [...args], {
104
+ child = spawn(nice ? "nice" : git, nice ? ["-n", "10", "--", git, ...args] : [...args], {
82
105
  cwd: opts.cwd, windowsHide: true, detached: !isWin, stdio: ["ignore", "pipe", "ignore"],
106
+ ...(opts.env !== undefined ? { env: opts.env } : {}),
83
107
  });
84
108
  } catch (e) {
85
109
  fail(e);
@@ -113,7 +137,7 @@ export const execGit: SnapshotGit = (args, opts) => new Promise<string>((ok, fai
113
137
  child.on("error", (e) => settle(e));
114
138
  child.on("close", (code, signal) => {
115
139
  if (code === 0) settle(undefined, Buffer.concat(chunks).toString("utf8"));
116
- else settle(new Error(`git exited with ${code === null ? signal : `code ${code}`}`));
140
+ else settle(code === null ? new Error(`git exited with ${signal}`) : new GitExitError(code));
117
141
  });
118
142
  });
119
143
 
@@ -141,8 +165,280 @@ export interface SnapshotOptions {
141
165
  * VerifyBudget.lowPriority (default true). Default false.
142
166
  */
143
167
  lowPriority?: boolean;
168
+ /**
169
+ * Cross-repo QA-1 F4 (I11): run every git process of the snapshot hardened, as the router's other git calls in a repository
170
+ * it does not own (git-tools.ts): `hardeningArgs()` (no fsmonitor, no hooks, no pager, no external diff, no optional locks),
171
+ * the user's `safe.directory` values and inherited line-ending settings (`core.autocrlf` …), `gitEnvironment()` (no inherited GIT_*, no system or global config) and git by absolute
172
+ * path outside the snapshotted tree. The perimeter's extra roots use it. Default false: the snapshot of W is unchanged.
173
+ */
174
+ hardened?: boolean;
144
175
  /** The git process seam (tests). Default execGit. */
145
176
  git?: SnapshotGit;
177
+ /** Optional failure diagnostic: scrubbed, single-line, at most 200 chars. Callback errors are ignored. */
178
+ onError?: (reason: string) => void;
179
+ /**
180
+ * Cross-repo P2.6 (SD11): also compute `TreeSnapshot.ignored`, a bounded digest of the repository's ignored files (nothing
181
+ * under a `node_modules` segment), with the snapshot's own git runner (hardened when `hardened`). QA-2 #9b: "over-bounds" when
182
+ * the index holds a skip-worktree or assume-unchanged entry (the fingerprint cannot see edits there). Default false: no extra
183
+ * git process, no extra read, no `ignored` field.
184
+ */
185
+ ignoredDigest?: boolean;
186
+ /** Default MAX_IGNORED_FILES. */
187
+ maxIgnoredFiles?: number;
188
+ /** Default MAX_IGNORED_BYTES. */
189
+ maxIgnoredBytes?: number;
190
+ }
191
+
192
+ /** Cross-repo P2.6: mirrors reference.ts MAX_UNTRACKED_FILES / MAX_UNTRACKED_BYTES (not imported: tree.ts stays free of reference.ts). */
193
+ export const MAX_IGNORED_FILES = 5_000;
194
+ export const MAX_IGNORED_BYTES = 64 * 1024 * 1024;
195
+
196
+ /**
197
+ * Cross-repo QA-2 #4: how the ignored files are listed. `--directory` reports a wholly ignored directory (an ignored
198
+ * `node_modules` above all) as one `dir/` entry without walking it; the pathspec excludes keep any file under a `node_modules`
199
+ * (top-level or nested) out of the listing. ignoredFilesDigest drops the `node_modules/` entries and walks the other reported
200
+ * directories itself, bounded, never into a `node_modules`.
201
+ */
202
+ export const IGNORED_LIST_ARGS: readonly string[] = [
203
+ "ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z",
204
+ "--", ".", ":(exclude,glob)**/node_modules", ":(exclude,glob)**/node_modules/**",
205
+ ];
206
+
207
+ /** Cross-repo QA-2 #9b: lists the index with its tags (`S` skip-worktree, lowercase assume-unchanged). */
208
+ export const INDEX_TAGS_ARGS: readonly string[] = ["ls-files", "-v", "-z"];
209
+
210
+ /**
211
+ * Cross-repo P3a (D23, OD-P3a-2 b): bounds of the git-ignored module list a cross-link run adds to its related
212
+ * inputs (`listIgnoredModules`). Over either bound the list is refused (`overBounds`), never truncated.
213
+ */
214
+ export const MAX_IGNORED_MODULES = 2_000;
215
+ export const MAX_IGNORED_MODULE_PATH_BYTES = 256 * 1024;
216
+ /** Cross-repo P3a (D23): the directory entries `listIgnoredModules` reads while walking ignored directories, any kind. */
217
+ export const MAX_IGNORED_WALK_ENTRIES = 50_000;
218
+ /** Cross-repo P3a (D23): the extensions of the ignored files that can be modules a consumer loads (`dist/`). */
219
+ export const IGNORED_MODULE_EXTENSIONS: readonly string[] = [".js", ".cjs", ".mjs", ".ts", ".cts", ".mts", ".tsx", ".jsx", ".json"];
220
+
221
+ /**
222
+ * Cross-repo P3a (D23, QA round 2 M-A): the tool-state directories `listIgnoredModules` never lists nor walks, at any depth
223
+ * (a `node_modules`, so `node_modules/.vite`, is never walked either): a check of the linked repository run earlier by the gate
224
+ * can write fresh files there, which are neither build output nor modules a consumer loads.
225
+ */
226
+ export const IGNORED_TOOL_STATE_DIRS: readonly string[] = ["coverage", ".nyc_output", ".vitest", ".cache"];
227
+
228
+ /**
229
+ * Cross-repo P3a (D23): what `listIgnoredModules` found: the absolute paths (sorted, deduplicated), or why there is no list.
230
+ * The file bounds count only the kept files (after the extension, declaration and `since` filters); the walk bound counts
231
+ * every directory entry read, a skipped nested repository's included.
232
+ * `newestMtimeByDir` (QA round 2 M-A): per ignored directory that contributed files, the newest own mtime (lstat, ms) of
233
+ * its listed files. The key is the directory git reports (`--directory`, e.g. `dist`), relative to the root with `/`
234
+ * separators and no trailing slash; a file git lists on its own is keyed by its parent directory (`.` at the root).
235
+ * `overBounds`: past MAX_IGNORED_MODULES, MAX_IGNORED_MODULE_PATH_BYTES or MAX_IGNORED_WALK_ENTRIES (never truncated).
236
+ * `unavailable`: not a repository, a git failure, an unreadable directory or an abort (fail closed).
237
+ */
238
+ export type IgnoredModules =
239
+ | { readonly files: readonly string[]; readonly newestMtimeByDir: Readonly<Record<string, number>> }
240
+ | { readonly overBounds: true }
241
+ | { readonly unavailable: true };
242
+
243
+ export interface ListIgnoredModulesOptions {
244
+ readonly signal: AbortSignal;
245
+ /** VerifyBudget.lowPriority, as the snapshot's git processes. Default false. */
246
+ readonly lowPriority?: boolean;
247
+ /** Default MAX_IGNORED_MODULES. */
248
+ readonly maxFiles?: number;
249
+ /** Default MAX_IGNORED_MODULE_PATH_BYTES: the UTF-8 bytes of the returned absolute paths, summed. */
250
+ readonly maxPathBytes?: number;
251
+ /** Default MAX_IGNORED_WALK_ENTRIES. */
252
+ readonly maxWalkEntries?: number;
253
+ /**
254
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): a ms epoch (the dispatch start). When set, only the files whose own
255
+ * mtime (lstat, a link never followed) is at or after it are listed: a build output older than the dispatch is stale for
256
+ * the change and is never a run input. Absent: no mtime filter (the hook never calls without it).
257
+ */
258
+ readonly since?: number;
259
+ /** The git process seam (tests). Default execGit. */
260
+ readonly git?: SnapshotGit;
261
+ }
262
+
263
+ /** Cross-repo P3a (QA M4): declaration files are never modules a consumer loads at run time. */
264
+ const DECLARATION_FILE = /\.d\.[cm]?ts$/i;
265
+
266
+ /** Cross-repo P3a (D23, QA round 2 M-A): a `node_modules` or tool-state (IGNORED_TOOL_STATE_DIRS) path segment, any case for the latter. */
267
+ function isSkippedIgnoredSegment(segment: string): boolean {
268
+ return segment === "node_modules" || IGNORED_TOOL_STATE_DIRS.includes(segment.toLowerCase());
269
+ }
270
+
271
+ /**
272
+ * Cross-repo P2.6: a digest of the ignored files `git ls-files` lists (IGNORED_LIST_ARGS), minus any path with a
273
+ * `node_modules` segment: sha256 over the sorted paths with their size and content (a link: its target). "over-bounds"
274
+ * above `maxFiles` paths or `maxBytes` bytes (sizes come from lstat before anything is read); undefined on any error
275
+ * (a nested repository included).
276
+ */
277
+ async function ignoredFilesDigest(
278
+ root: string,
279
+ list: () => Promise<string>,
280
+ signal: AbortSignal,
281
+ maxFiles: number,
282
+ maxBytes: number,
283
+ ): Promise<string | "over-bounds" | undefined> {
284
+ try {
285
+ // `--directory`: git reports a wholly ignored directory as `dir/` without walking it (so never a `node_modules` tree);
286
+ // the other ignored directories are walked here, bounded by `maxFiles`, and never into a `node_modules`.
287
+ const listed = (await list()).split("\0").filter(Boolean)
288
+ .filter(path => !path.split(/[\\/]/).includes("node_modules"));
289
+ const paths: string[] = [];
290
+ for (const path of listed) {
291
+ if (!/[\\/]$/.test(path)) {
292
+ paths.push(path);
293
+ if (paths.length > maxFiles) return "over-bounds";
294
+ continue;
295
+ }
296
+ const pending = [path.replace(/[\\/]+$/, "")];
297
+ while (pending.length > 0) {
298
+ if (signal.aborted) return undefined;
299
+ const dir = pending.pop() as string;
300
+ for (const entry of await readdir(resolve(root, dir), { withFileTypes: true })) {
301
+ if (entry.name === "node_modules") continue;
302
+ if (entry.name === ".git") return undefined; // A nested repository has no content identity here.
303
+ const child = `${dir}/${entry.name}`;
304
+ if (entry.isDirectory()) {
305
+ pending.push(child);
306
+ continue;
307
+ }
308
+ paths.push(child);
309
+ if (paths.length > maxFiles) return "over-bounds";
310
+ }
311
+ }
312
+ }
313
+ paths.sort();
314
+ const sized: [string, "file" | "link", number][] = [];
315
+ let bytes = 0;
316
+ for (const path of paths) {
317
+ const stat = await lstat(resolve(root, path));
318
+ if (stat.isSymbolicLink()) sized.push([path, "link", stat.size]);
319
+ else if (stat.isFile()) {
320
+ bytes += stat.size;
321
+ if (bytes > maxBytes) return "over-bounds";
322
+ sized.push([path, "file", stat.size]);
323
+ } else return undefined; // A directory (nested repository) has no content identity here.
324
+ }
325
+ const hash = createHash("sha256");
326
+ for (const [path, kind, size] of sized) {
327
+ if (signal.aborted) return undefined;
328
+ hash.update(JSON.stringify([path, kind, size]));
329
+ hash.update(kind === "link" ? await readlink(resolve(root, path)) : await readFile(resolve(root, path), { signal }));
330
+ }
331
+ return hash.digest("hex");
332
+ } catch {
333
+ return undefined; // Unlisted, vanished or unreadable: no digest, never a throw.
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Cross-repo P3a (D23, OD-P3a-2 b, finding X6): the git-ignored JS/TS/JSON files under `root` (IGNORED_MODULE_EXTENSIONS),
339
+ * as absolute paths under `root` as given, so a consumer that loads the linked repository's build output (`dist/`) is
340
+ * selected by a cross-link `vitest related` run. Listed as the ignored digest lists (IGNORED_LIST_ARGS, `--directory`),
341
+ * always hardened (`hardenedGit`: no hooks, no fsmonitor, no optional locks, so no index refresh; read-only), the reported
342
+ * directories walked here, bounded, never into a `node_modules` nor into a directory holding a `.git` entry (a nested
343
+ * repository or worktree, skipped entirely). Declaration files (`.d.ts`, `.d.mts`, `.d.cts`) are dropped; with `since`, so is
344
+ * every file whose own mtime is before it (D23 as amended 2026-10-12: only the modules modified during the dispatch). The
345
+ * tool-state directories (IGNORED_TOOL_STATE_DIRS) are neither listed nor walked, and each listed file's mtime feeds
346
+ * `newestMtimeByDir` (QA round 2 M-A). Never throws.
347
+ */
348
+ export async function listIgnoredModules(root: string, opts: ListIgnoredModulesOptions): Promise<IgnoredModules> {
349
+ const run = opts.git ?? execGit;
350
+ const maxFiles = opts.maxFiles ?? MAX_IGNORED_MODULES;
351
+ const maxPathBytes = opts.maxPathBytes ?? MAX_IGNORED_MODULE_PATH_BYTES;
352
+ const maxWalk = opts.maxWalkEntries ?? MAX_IGNORED_WALK_ENTRIES;
353
+ const unavailable: IgnoredModules = { unavailable: true };
354
+ const overBounds: IgnoredModules = { overBounds: true };
355
+ try {
356
+ if (opts.signal.aborted) return unavailable;
357
+ const hardened = await hardenedGit(root);
358
+ const listing = await run([...hardened.prefix, ...IGNORED_LIST_ARGS], {
359
+ cwd: root, signal: opts.signal, timeoutMs: SNAPSHOT_GIT_TIMEOUT_MS, maxBuffer: SNAPSHOT_GIT_MAX_BUFFER,
360
+ lowPriority: opts.lowPriority === true, env: hardened.env, executable: hardened.executable,
361
+ });
362
+ const files = new Set<string>();
363
+ const newest = new Map<string, number>();
364
+ const since = opts.since;
365
+ let bytes = 0;
366
+ let walked = 0;
367
+ /** False once a bound is passed. `dir`: the newestMtimeByDir key the file counts toward. */
368
+ const add = async (relative: string, dir: string): Promise<boolean> => {
369
+ if (!IGNORED_MODULE_EXTENSIONS.includes(extname(relative).toLowerCase())) return true;
370
+ if (DECLARATION_FILE.test(relative)) return true; // QA M4: `.d.ts`, `.d.mts`, `.d.cts` are never loaded.
371
+ const absolute = resolve(root, relative);
372
+ if (files.has(absolute)) return true;
373
+ // QA C1: a file not modified since the dispatch start is stale for the change (lstat: a link's own mtime).
374
+ const mtime = (await lstat(absolute)).mtimeMs;
375
+ if (since !== undefined && !(mtime >= since)) return true;
376
+ files.add(absolute);
377
+ // QA round 2 M-A: the newest listed file per ignored directory, for the hook's build-staleness check.
378
+ if (!(mtime <= (newest.get(dir) ?? -Infinity))) newest.set(dir, mtime);
379
+ bytes += Buffer.byteLength(absolute, "utf8");
380
+ return files.size <= maxFiles && bytes <= maxPathBytes;
381
+ };
382
+ for (const path of listing.split("\0")) {
383
+ if (path === "" || path.split(/[\\/]/).some(isSkippedIgnoredSegment)) continue;
384
+ if (!/[\\/]$/.test(path)) {
385
+ const slash = path.search(/[\\/][^\\/]*$/);
386
+ if (!(await add(path, slash < 0 ? "." : path.slice(0, slash).replace(/\\/g, "/")))) return overBounds;
387
+ continue;
388
+ }
389
+ // `--directory`: a wholly ignored directory (`dist/`) is reported once; walk it. Links are entries, never followed.
390
+ const top = path.replace(/[\\/]+$/, "");
391
+ const key = top.replace(/\\/g, "/");
392
+ const pending = [top];
393
+ while (pending.length > 0) {
394
+ if (opts.signal.aborted) return unavailable;
395
+ const dir = pending.pop() as string;
396
+ const entries = await readdir(resolve(root, dir), { withFileTypes: true });
397
+ walked += entries.length;
398
+ if (walked > maxWalk) return overBounds;
399
+ // QA M4: a directory holding a `.git` entry (a nested repository or worktree) is skipped entirely, its subtree too.
400
+ if (entries.some(entry => entry.name === ".git")) continue;
401
+ for (const entry of entries) {
402
+ if (isSkippedIgnoredSegment(entry.name)) continue;
403
+ const child = `${dir}/${entry.name}`;
404
+ if (entry.isDirectory()) pending.push(child);
405
+ else if (!(await add(child, key))) return overBounds;
406
+ }
407
+ }
408
+ }
409
+ if (opts.signal.aborted) return unavailable;
410
+ const newestMtimeByDir: Record<string, number> = {};
411
+ for (const dir of [...newest.keys()].sort()) newestMtimeByDir[dir] = newest.get(dir) as number;
412
+ return { files: [...files].sort(), newestMtimeByDir };
413
+ } catch {
414
+ return unavailable; // Not a repository, git failed or timed out, a directory vanished or is unreadable: fail closed.
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Cross-repo P3a (D23, QA round 2 M-A): a changed source's mtime in ms (stat: a link's target, whose content the build reads),
420
+ * undefined when it does not exist (ENOENT, ENOTDIR). Any other error throws (the testsPass hook counts it as newer than
421
+ * any build: fail closed).
422
+ */
423
+ export async function fileMtimeMs(path: string): Promise<number | undefined> {
424
+ try {
425
+ return (await stat(path)).mtimeMs;
426
+ } catch (err) {
427
+ const code = errorCode(err);
428
+ if (code === "ENOENT" || code === "ENOTDIR") return undefined;
429
+ throw err;
430
+ }
431
+ }
432
+
433
+ /** QA-1 F4: the argument prefix and process options of a hardened snapshot of `cwd` (SnapshotOptions.hardened). */
434
+ async function hardenedGit(cwd: string): Promise<{ prefix: string[]; env: NodeJS.ProcessEnv; executable: string }> {
435
+ const executable = tools.gitExecutable(tools.workRootGuards(cwd));
436
+ const trusted = await tools.inheritedSafeDirectoryArgs(executable);
437
+ const base = [...tools.hardeningArgs(), ...trusted];
438
+ // The inherited line-ending settings (inspectGit's allowlist): a CRLF checkout must not read as modified because the
439
+ // environment hides the user's `core.autocrlf`.
440
+ const inherited = await tools.inheritedConfigArgs(executable, cwd, base);
441
+ return { prefix: [...base, ...inherited], env: tools.gitEnvironment(), executable };
146
442
  }
147
443
 
148
444
  function errorCode(err: unknown): unknown {
@@ -198,20 +494,47 @@ async function digestPaths(
198
494
  }
199
495
  }
200
496
 
497
+ /**
498
+ * I7 (P0.2): the checked-out branch from line 2 of `git rev-parse HEAD --symbolic-full-name HEAD`: the short name
499
+ * (`feat/x` from `refs/heads/feat/x`); null on a detached HEAD (`HEAD`); another ref kept whole; undefined when the line is
500
+ * missing or empty.
501
+ */
502
+ function parseBranchLine(line: string | undefined): string | null | undefined {
503
+ const ref = line?.trim();
504
+ if (ref === undefined || ref === "") return undefined;
505
+ if (ref === "HEAD") return null;
506
+ return ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
507
+ }
508
+
201
509
  export async function snapshotTree(cwd: string, signal: AbortSignal, options: SnapshotOptions = {}): Promise<TreeSnapshot | undefined> {
202
510
  let gitCwd = cwd;
203
511
  const run = options.git ?? execGit;
204
512
  const lowPriority = options.lowPriority === true;
205
- const git = (args: string[]) => run(["--no-pager", ...args], {
206
- cwd: gitCwd, signal, timeoutMs: SNAPSHOT_GIT_TIMEOUT_MS, maxBuffer: SNAPSHOT_GIT_MAX_BUFFER, lowPriority,
207
- });
513
+ let prefix: readonly string[] = ["--no-pager"];
514
+ let hardening: Pick<SnapshotGitOptions, "env" | "executable"> = {};
515
+ type Stage = "root" | "head" | "status" | "diff-worktree" | "diff-index" | "index" | "untracked-list" | "hash" | "index-tags" | "ignored-list";
516
+ let stage: Stage = "root";
517
+ const git = (label: Stage, args: string[]) => {
518
+ stage = label;
519
+ return run([...prefix, ...args], {
520
+ cwd: gitCwd, signal, timeoutMs: SNAPSHOT_GIT_TIMEOUT_MS, maxBuffer: SNAPSHOT_GIT_MAX_BUFFER, lowPriority, ...hardening,
521
+ });
522
+ };
208
523
  try {
209
- const root = (await git(["rev-parse", "--show-toplevel"])).trim();
524
+ if (options.hardened === true) {
525
+ const hardened = await hardenedGit(cwd);
526
+ prefix = hardened.prefix;
527
+ hardening = { env: hardened.env, executable: hardened.executable };
528
+ }
529
+ const root = (await git("root", ["rev-parse", "--show-toplevel"])).trim();
210
530
  // ls-files otherwise scopes untracked contents to a subdirectory cwd,
211
531
  // missing same-path edits in sibling packages that tests may import.
212
532
  gitCwd = root;
213
- const head = (await git(["rev-parse", "HEAD"])).trim();
214
- const status = await git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
533
+ // One process, so HEAD and its branch describe the same checkout.
534
+ const [headLine, refLine] = (await git("head", ["rev-parse", "HEAD", "--symbolic-full-name", "HEAD"])).split(/\r?\n/);
535
+ const head = (headLine ?? "").trim();
536
+ const branch = parseBranchLine(refLine);
537
+ const status = await git("status", ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
215
538
  const files: ChangedFile[] = [];
216
539
  const records = status.split("\0");
217
540
  for (let i = 0; i < records.length; i++) {
@@ -226,13 +549,14 @@ export async function snapshotTree(cwd: string, signal: AbortSignal, options: Sn
226
549
  files.push(file);
227
550
  }
228
551
  const hash = createHash("sha256").update(status);
229
- hash.update(await git(["diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv"]));
230
- hash.update(await git(["diff", "--cached", "--binary", "--no-ext-diff", "--no-textconv"]));
552
+ hash.update(await git("diff-worktree", ["diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv"]));
553
+ hash.update(await git("diff-index", ["diff", "--cached", "--binary", "--no-ext-diff", "--no-textconv"]));
231
554
  // A submodule's dirty marker does not describe its content. Refuse rather
232
555
  // than cache a fingerprint that would excuse unmeasured changes there.
233
- if (/^160000 /m.test(await git(["ls-files", "--stage"]))) return undefined;
234
- const untracked = (await git(["ls-files", "--others", "--exclude-standard", "--full-name", "-z"]))
556
+ if (/^160000 /m.test(await git("index", ["ls-files", "--stage"]))) return undefined;
557
+ const untracked = (await git("untracked-list", ["ls-files", "--others", "--exclude-standard", "--full-name", "-z"]))
235
558
  .split("\0").filter(Boolean).sort();
559
+ stage = "hash";
236
560
  for (const path of untracked) {
237
561
  const absolute = resolve(root, path);
238
562
  const stat = await lstat(absolute);
@@ -248,9 +572,41 @@ export async function snapshotTree(cwd: string, signal: AbortSignal, options: Sn
248
572
  options.maxDigestBytes ?? MAX_DIGEST_BYTES,
249
573
  );
250
574
  if (signal.aborted) return undefined;
251
- return { cwd: await realpath(cwd), root: await realpath(root), head, fingerprint: hash.digest("hex"), dirty: files.length > 0, files, digests };
252
- } catch {
575
+ let ignored: string | "over-bounds" | undefined;
576
+ if (options.ignoredDigest === true) {
577
+ // Cross-repo QA-2 #9b: a skip-worktree (`S`) or assume-unchanged (lowercase) entry hides its edits from `status` and
578
+ // `diff`, so the fingerprint cannot vouch for it: the digest is unusable ("over-bounds"), as reference.ts treats it for W.
579
+ // A failed listing leaves `ignored` absent and the snapshot intact, as a failed ignored listing does.
580
+ const hidden = await git("index-tags", [...INDEX_TAGS_ARGS]).then(
581
+ tags => tags.split("\0").some(record => record !== "" && (record[0] === "S" || record[0] !== record[0]?.toUpperCase())),
582
+ () => undefined,
583
+ );
584
+ ignored = hidden === undefined
585
+ ? undefined
586
+ : hidden
587
+ ? "over-bounds"
588
+ : await ignoredFilesDigest(
589
+ root,
590
+ () => git("ignored-list", [...IGNORED_LIST_ARGS]),
591
+ signal,
592
+ options.maxIgnoredFiles ?? MAX_IGNORED_FILES,
593
+ options.maxIgnoredBytes ?? MAX_IGNORED_BYTES,
594
+ );
595
+ }
596
+ return {
597
+ cwd: await realpath(cwd), root: await realpath(root), head, branch, fingerprint: hash.digest("hex"), dirty: files.length > 0, files, digests,
598
+ ...(ignored !== undefined ? { ignored } : {}),
599
+ };
600
+ } catch (error) {
253
601
  // Not a Git checkout, unreadable file, timeout or concurrent deletion: no baseline.
602
+ try {
603
+ if (options.onError !== undefined) {
604
+ const code = errorCode(error);
605
+ const message = error instanceof Error ? error.message : String(error);
606
+ const reason = `${stage}: ${typeof code === "string" || typeof code === "number" ? `${code}: ` : ""}${message}`;
607
+ options.onError(scrubText(reason).replace(/\s+/g, " ").trim().slice(0, 200) || "snapshot failed");
608
+ }
609
+ } catch { /* Diagnostics never turn an unavailable snapshot into a throw. */ }
254
610
  return undefined;
255
611
  }
256
612
  }
@@ -8,6 +8,27 @@ import type { DispatchReference, InexactReason } from "./reference";
8
8
 
9
9
  export type VerifyMethod = "deterministic" | "checker" | "none";
10
10
 
11
+ /**
12
+ * Cross-repo P2.2: where one check of a role dispatch runs. `cwd` is canonical; `top` is the git top level of `cwd` (undefined
13
+ * when unknown); `foreign` is set when that top differs from the top of the dispatch's work root; `scope` is the check's
14
+ * normalized `scope=` key.
15
+ */
16
+ export interface CheckPlacement {
17
+ readonly cwd: string;
18
+ readonly top: string | undefined;
19
+ readonly foreign: boolean;
20
+ readonly scope?: "affected" | "full";
21
+ }
22
+
23
+ /**
24
+ * The placements of a DoD's checks, index-aligned with `dod.checks` (undefined for a check with neither `cwd=` nor `scope=`);
25
+ * absent when no check has a key. `refused` names the first check whose key is not accepted.
26
+ */
27
+ export interface PlacementResolution {
28
+ readonly placements?: readonly (CheckPlacement | undefined)[];
29
+ readonly refused?: { readonly index: number; readonly kind: string; readonly text: string; readonly why: "outside" | "scope" };
30
+ }
31
+
11
32
  export interface Verdict {
12
33
  pass: boolean;
13
34
  /** Absent on legacy verdicts: derive from pass. Unverifiable is not failure. */
@@ -43,21 +64,26 @@ export interface ExecResult {
43
64
 
44
65
  /** Options shared by every verification process seam (shell string or argv). */
45
66
  export interface ExecOptions {
67
+ /** Optional v2 diagnostics; process adapters split preparation from the actual spawn/child lifetime. */
68
+ service?: import("../executor/observations").ServiceExecution;
46
69
  cwd?: string;
47
70
  timeoutMs?: number;
48
71
  /** Aborting kills the whole process tree; an already-aborted signal never spawns. */
49
72
  signal?: AbortSignal;
50
73
  /** Run the process (and its descendants) at below-normal OS priority. */
51
74
  lowPriority?: boolean;
52
- /** Merged over process.env; never replaces it. */
75
+ /** Merged over process.env by default; see envMode for a complete, sanitized environment. */
53
76
  env?: Record<string, string>;
77
+ /** `replace` uses only env (empty when omitted), without process.env or automatic slot-environment injection. */
78
+ envMode?: "merge" | "replace";
54
79
  }
55
80
 
81
+ /** Execution-only seam; an adapter doing preparation must forward `service` to the instrumented process layer. */
56
82
  export interface ExecSeam {
57
83
  (command: string, opts?: ExecOptions): Promise<ExecResult>;
58
84
  }
59
85
 
60
- /** Spawn `file` with `args` and no shell: arguments reach the child byte-for-byte. */
86
+ /** Spawn `file` with `args` and no shell: arguments reach the child byte-for-byte. Adapters preserve `service`. */
61
87
  export interface ArgvSeam {
62
88
  (file: string, args: readonly string[], opts?: ExecOptions): Promise<ExecResult>;
63
89
  }
@@ -72,6 +98,8 @@ export interface MutexRegistry {
72
98
  }
73
99
 
74
100
  export interface DeterministicDeps {
101
+ /** Read-only v2 intrinsic-execution diagnostics; absent on v1/off. */
102
+ service?: import("../executor/observations").ServiceObservation;
75
103
  /**
76
104
  * S5 (deterministic.ts header, T2 P2-P7): plans, runs and rechecks one testsPass request. Called
77
105
  * outside `mutex`. Absent -> testsPass is unverifiable, never a run (G5).
@@ -102,6 +130,28 @@ export interface DeterministicDeps {
102
130
  deadline?: Deadline;
103
131
  /** Preserve completed failures if an outer gate budget expires later. */
104
132
  onFailure?: (reason: string) => void;
133
+ /**
134
+ * Cross-repo P2.4: per-check placements, index-aligned with `dod.checks` (undefined: the check runs in `cwd` with the budget's
135
+ * scope, as without this field). A foreign placement's failure is unverifiable, never "fail", and never reaches `onFailure`.
136
+ */
137
+ placements?: readonly (CheckPlacement | undefined)[];
138
+ /**
139
+ * Cross-repo P3a (SD-P3a-1, -5): W's git top (the gate's `artefact.changeRoot`, else its effective base dir). Set only with
140
+ * foreign placements (v2 roles). With it, a foreign testsPass whose placement says an explicit `scope=affected` runs scoped
141
+ * through the link (`TestsPassRequest.crossLinkRoot`) instead of being refused; absent: the refusal as before.
142
+ */
143
+ changeRoot?: string;
144
+ /**
145
+ * Cross-repo P3a (SD-P3a-2 amended): for a consumer cwd, other spellings of `changeRoot`'s directory (the JS fs.realpathSync of
146
+ * each consumer link into W). Called only for a cross-link testsPass; fail-soft (errors give no aliases).
147
+ */
148
+ crossLinkAliases?: (consumerCwd: string) => readonly string[];
149
+ /**
150
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): when the dispatch began (ms epoch; the original start for a deferred
151
+ * verification, never the router_verify time). Forwarded to a cross-link testsPass request (`TestsPassRequest.dispatchStartedAt`)
152
+ * so only W's ignored modules modified during the dispatch are inputs; absent: none are.
153
+ */
154
+ dispatchStartedAt?: number;
105
155
  /**
106
156
  * #84 QA-G-B-2-1: set for a CARRIED acceptance (a role resume re-checking the block of an earlier attempt): a testsPass or
107
157
  * lintClean check that ran no process (NoAffected: nothing of the change set maps to a test or a lintable file) is unverifiable
@@ -345,6 +395,20 @@ export interface TestsPassRequest {
345
395
  readonly changedFiles: readonly ChangedPath[] | "unavailable";
346
396
  readonly reference: ReferenceState;
347
397
  readonly deadline: Deadline;
398
+ /**
399
+ * Cross-repo P3a (runner.ts G.4b): the git top of the repository the change lies in when it is
400
+ * not cwd's (W, SD-P3a-5). Forwarded to planScopedRun only when set; a request with it is never
401
+ * batched (batch.ts submit).
402
+ */
403
+ readonly crossLinkRoot?: string;
404
+ /** Other spellings of crossLinkRoot's directory (runner.ts PlanScopedRunInput); used only with crossLinkRoot. */
405
+ readonly crossLinkAliases?: readonly string[];
406
+ /**
407
+ * Cross-repo P3a (D23 as amended 2026-10-12, QA C1): when the dispatch began (ms epoch), the original start even for a
408
+ * deferred verification. With crossLinkRoot, only W's ignored modules modified at or after it are added to the run's inputs;
409
+ * absent: none are (never a stale build output).
410
+ */
411
+ readonly dispatchStartedAt?: number;
348
412
  }
349
413
 
350
414
  /** What the S5 hook returns for one request; judgeScoped turns it into the check result. */