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