opencode-model-router 2.7.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +219 -0
  2. package/package.json +1 -1
  3. package/src/commands/approvals.ts +354 -0
  4. package/src/commands/output.ts +12 -1
  5. package/src/compat/v2-hooks.ts +255 -53
  6. package/src/index.ts +328 -37
  7. package/src/router/config.ts +48 -2
  8. package/src/router/dispatch-header.ts +95 -2
  9. package/src/router/git-tools.ts +165 -9
  10. package/src/router/protocol.ts +5 -1
  11. package/src/router/role-agents.ts +110 -3
  12. package/src/router/roles-config.ts +83 -0
  13. package/src/router/roles.ts +1 -1
  14. package/src/router/sessions.ts +11 -0
  15. package/src/routing/classify/route-line.ts +96 -5
  16. package/src/routing/classify/types.ts +26 -0
  17. package/src/routing/outcomes/signals.ts +17 -0
  18. package/src/routing/roles/admission.ts +1028 -0
  19. package/src/routing/roles/approvals.ts +876 -0
  20. package/src/routing/roles/binding.ts +17 -4
  21. package/src/routing/roles/check-placement.ts +112 -0
  22. package/src/routing/roles/git-root.ts +500 -0
  23. package/src/routing/roles/policy.ts +9 -0
  24. package/src/routing/roles/read-set.ts +325 -0
  25. package/src/routing/roles/work-root.ts +9 -1
  26. package/src/routing/wire/dispatch.ts +611 -18
  27. package/src/routing/wire/working-set.ts +58 -0
  28. package/src/util/linear-trim.ts +32 -0
  29. package/src/verify/batch.ts +7 -2
  30. package/src/verify/branch.ts +135 -0
  31. package/src/verify/deterministic.ts +232 -10
  32. package/src/verify/dispatch.ts +284 -9
  33. package/src/verify/dod.ts +46 -0
  34. package/src/verify/edges.ts +817 -0
  35. package/src/verify/gate.ts +349 -16
  36. package/src/verify/git-top.ts +43 -0
  37. package/src/verify/head.ts +107 -0
  38. package/src/verify/pending.ts +155 -8
  39. package/src/verify/perimeter.ts +1180 -0
  40. package/src/verify/pin.ts +109 -0
  41. package/src/verify/reference.ts +82 -6
  42. package/src/verify/risk.ts +16 -3
  43. package/src/verify/runner.ts +706 -32
  44. package/src/verify/tree.ts +347 -8
  45. package/src/verify/types.ts +57 -0
  46. package/src/verify/wiring.ts +1324 -35
@@ -18,19 +18,105 @@
18
18
  * deps; this module imports no fs/network/SDK.
19
19
  */
20
20
  import type { Verdict } from "./types";
21
- import type { DeterministicDeps } from "./types";
21
+ import type { CheckPlacement, DeterministicDeps } from "./types";
22
22
  import type { DoD } from "./dod";
23
23
  import { isCheckable } from "./dod";
24
24
  import { runDeterministic } from "./deterministic";
25
25
  import { incompleteVerdict, isIncompleteVerdict, runChecker } from "./checker";
26
26
  import type { ArtefactView, CheckerDeps } from "./checker";
27
27
  import type { BudgetSnapshot } from "../guard/enforce";
28
- import { isAbsolute } from "node:path";
28
+ import { isAbsolute, resolve } from "node:path";
29
29
  import { isWithinDir, resolveBaseDir } from "./paths";
30
+ import { toolLabel } from "./dispatch";
31
+ import { perimeterKey } from "./git-top";
32
+ import { crossLinkAliases } from "./perimeter";
33
+ import { displaySafe } from "../routing/roles/read-set";
34
+
35
+ /** Cross-repo P3 QA-1 M5: the longest repository text (a name or a root) the verified-scope line quotes; past it, cut with "…". */
36
+ export const SCOPE_TEXT_MAX = 256;
37
+
38
+ /**
39
+ * Cross-repo P3 QA-1 M5: repository text (a perimeter root's name or path, read from a manifest or the file system) as the
40
+ * verified-scope line quotes it: capped at SCOPE_TEXT_MAX characters (never splitting a surrogate pair), then escaped.
41
+ */
42
+ function scopeText(text: string): string {
43
+ let shown = text;
44
+ if (shown.length > SCOPE_TEXT_MAX) {
45
+ let end = SCOPE_TEXT_MAX - 1;
46
+ const last = shown.charCodeAt(end - 1);
47
+ if (last >= 0xd800 && last <= 0xdbff) end -= 1;
48
+ shown = `${shown.slice(0, end)}…`;
49
+ }
50
+ return displaySafe(shown);
51
+ }
52
+
53
+ /** How many outside paths the mixed-change-set reason names before "and N more". */
54
+ const MAX_OUTSIDE_LISTED = 5;
55
+
56
+ /** Cross-repo P1.8: one repository of a perimeter, as the gate names it. */
57
+ export interface PerimeterRepo {
58
+ readonly root: string;
59
+ readonly name: string;
60
+ readonly branch?: string;
61
+ readonly head?: string;
62
+ }
63
+
64
+ /**
65
+ * Cross-repo P1.8: an extra root of P and its change since the dispatch. "unobserved": no snapshot at either end, past the cap,
66
+ * or a perimeter that could not be planned (I4 refuses it when writers ran). "unadmitted" (QA-1 F4): a linked directory whose
67
+ * repository is not admitted, or that is not a git repository; never snapshotted, and only named in I8.
68
+ */
69
+ export interface PerimeterRoot extends PerimeterRepo {
70
+ readonly status: "changed" | "unchanged" | "unobserved" | "unadmitted";
71
+ /** QA-1 F11: a worktree of W's own repository; I4 suggests `branch=<branch>` rather than `repo=<name>`. */
72
+ readonly sameRepository?: boolean;
73
+ }
74
+
75
+ /** QA-1 F10: the name of the placeholder root a perimeter that could not be planned holds (fail closed). */
76
+ export const PERIMETER_UNPLANNED = "perimeter could not be planned";
77
+
78
+ /** Cross-repo P1.8 (I8): the perimeter P of a dispatch: W, then its other roots (at least one). */
79
+ export interface PerimeterObservation {
80
+ readonly w: PerimeterRepo;
81
+ readonly roots: readonly PerimeterRoot[];
82
+ /**
83
+ * Cross-repo P2b.3 (D6): working-set worktrees other than W whose `node_modules` link into W, found by `discoverConsumers`.
84
+ * Absent or empty: none known, no consumer caveat. Cross-repo P3c.5 (SD-P3c-5, F6): a `node_modules` consumer carries its
85
+ * link `entry`; one whose declared dependency edge leads into W carries `via` instead (the declaring file and its fixed label).
86
+ */
87
+ readonly consumers?: readonly { readonly root: string; readonly name?: string; readonly entry?: string; readonly via?: string }[];
88
+ /**
89
+ * Cross-repo QA-2 #2: working-set worktrees whose consumer discovery stopped on its entry budget before it finished. A
90
+ * repository there may link W unchecked, so a would-be pass with a change carries a caveat per entry.
91
+ */
92
+ readonly consumersIncomplete?: readonly { readonly root: string; readonly name?: string }[];
93
+ }
30
94
 
31
95
  /** The concrete, inspectable result of a delegation (artefact contract §3.3). */
32
96
  export interface Artefact {
33
97
  changeBaseline?: "available" | "unavailable";
98
+ /**
99
+ * The git top-level the change set was observed in (snapshot.root). Paths outside it (absolute, or relative ones that climb
100
+ * out with `..`), mixed with paths inside, make the verdict unverifiable (S4/F3). Absent: the effective base directory stands
101
+ * in for it.
102
+ */
103
+ changeRoot?: string;
104
+ /**
105
+ * I7 (P0.2, S9/S12): the working tree switched branch during the dispatch or since the producer returned; the reason, worded
106
+ * by the wiring (branch.ts branchSwitchReason / branchUnconfirmedReason). Present: the verdict is unverifiable with it on
107
+ * either verifier and nothing runs, since the change set and the checks would describe another branch.
108
+ */
109
+ branchSwitch?: string;
110
+ /**
111
+ * I5 (P0.3, S1/S3/S10): tools the producer lineage ran that can write files the router cannot observe (dispatch.ts
112
+ * isUnattributedWriter), sorted. With an empty, available change set, a pass carries a caveat and is never a verified pass.
113
+ */
114
+ unattributedWriters?: string[];
115
+ /**
116
+ * Cross-repo P1.8 (I4, I8): the perimeter P the wiring observed (wiring.ts observeChange): W, then each extra root with its
117
+ * change status since the dispatch. Absent: the dispatch has no perimeter (one repository), and nothing below changes.
118
+ */
119
+ perimeter?: PerimeterObservation;
34
120
  changedFiles: { path: string; status: string }[];
35
121
  finalReturnText: string;
36
122
  declaredOutputs: string[];
@@ -79,6 +165,16 @@ export interface Delegation {
79
165
  * the refusal names neither.
80
166
  */
81
167
  cwdSource?: "argument" | "acceptance";
168
+ /**
169
+ * Cross-repo P2.4: where each check of `dod.checks` runs, index-aligned (undefined: no `cwd=`/`scope=` key). Absent: every
170
+ * check runs in the base directory, and nothing below changes.
171
+ */
172
+ checkPlacements?: readonly (CheckPlacement | undefined)[];
173
+ /**
174
+ * Cross-repo P2.4 (SD4): the first check whose `cwd=` is outside the work root and its read set (`why: "outside"`) or whose
175
+ * `scope=` is not affected/full (`why: "scope"`); `index` is 0-based. With it the gate refuses (unverifiable, nothing runs).
176
+ */
177
+ refusedCheck?: { readonly index: number; readonly kind: string; readonly text: string; readonly why: "outside" | "scope" | "tier" };
82
178
  }
83
179
 
84
180
  export interface GateDeps {
@@ -243,37 +339,165 @@ export async function accept(
243
339
  // QA-P33F1-1-2: the caller decided containment with P2.3's rule (routing/roles/work-root.ts verificationScope); a refused cwd
244
340
  // is never resolved here (a UNC/device path reaches no filesystem call).
245
341
  if (workRoot !== undefined && delegation.refusedCwd !== undefined) return refuseCwd(delegation.refusedCwd);
342
+ // Cross-repo P2.4 (SD4): a check's `cwd=` outside the work root and its read set, or a `scope=` that is neither affected nor
343
+ // full: nothing runs, whichever verifier the DoD names.
344
+ if (delegation.refusedCheck !== undefined) {
345
+ const { index, kind, text, why } = delegation.refusedCheck;
346
+ // OD1=B: a tier dispatch (no routed role) honours no per-check `cwd=`; `text` is the cwd as written.
347
+ const reason = why === "outside"
348
+ ? `check ${index + 1} (${kind}) cwd=${text} is outside the work root ${workRoot ?? deps.deterministic.cwd} and its read set; nothing ran`
349
+ : why === "tier"
350
+ ? `check ${index + 1} (${kind}) cwd=${text}: a per-check cwd= is honoured only in roles mode; nothing ran`
351
+ : `check ${index + 1} (${kind}) scope=${text} is not affected or full; nothing ran`;
352
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
353
+ }
246
354
  const effectiveBaseDir = resolveBaseDir(
247
355
  delegation.cwd,
248
356
  workRoot ?? deps.deterministic.cwd,
249
357
  );
250
358
  // Backstop for a caller that did not check its cwd: lexical only (no filesystem call); a checked canonical cwd always passes.
251
359
  if (workRoot !== undefined && !isWithinDir(effectiveBaseDir, workRoot)) return refuseCwd(effectiveBaseDir);
360
+ // I7 (P0.2, S9/S12): the verified tree switched branch. The change set and either verifier would describe another branch, so
361
+ // nothing runs; before the all-outside and mixed checks, whose reasons would then be about the wrong change set.
362
+ if (artefact.branchSwitch !== undefined) {
363
+ const reason = artefact.branchSwitch;
364
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
365
+ }
366
+ // I4 (cross-repo P1.8): another repository of the perimeter changed during the dispatch (or could not be observed: fail
367
+ // closed), and the producer ran a tool whose writes cannot be attributed. The checks here cannot cover a write there.
368
+ const perimeterRefusal = perimeterChangeReasons(artefact, artefact.perimeter?.w.root ?? artefact.changeRoot ?? effectiveBaseDir);
369
+ if (perimeterRefusal.length > 0) {
370
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: perimeterRefusal, caveats: perimeterRefusal }, dodSource, deps.strictUnverifiable);
371
+ }
252
372
  const canonical = deps.canonicalPath ?? ((path: string) => path);
373
+ // S4/F3: some changes inside the change root and some absolute ones outside it. Neither verifier can see the outside ones
374
+ // (the runner drops them with a note; the grader checks against, and runs in, the working directory), so the change set
375
+ // cannot be verified as a whole. A relative path is root-relative, hence inside unless it climbs out (`../x`). The root is
376
+ // the observed git top-level, else the base directory.
377
+ const refuseMixedOutside = (): GateResult | undefined => {
378
+ // No absolute path and no `..` segment: nothing can be outside, and no canonicalisation (a filesystem call) is needed.
379
+ if (!artefact.changedFiles.some(({ path }) => isAbsolute(path) || path.split(/[\\/]/).includes(".."))) return undefined;
380
+ const root = artefact.changeRoot ?? effectiveBaseDir;
381
+ const canonicalRoot = canonical(root);
382
+ const outsideRoot = artefact.changedFiles
383
+ .map(({ path }) => path)
384
+ .filter(path => !isWithinDir(canonical(isAbsolute(path) ? path : resolve(root, path)), canonicalRoot));
385
+ if (outsideRoot.length === 0 || outsideRoot.length === artefact.changedFiles.length) return undefined;
386
+ const listed = outsideRoot.slice(0, MAX_OUTSIDE_LISTED).join(", ")
387
+ + (outsideRoot.length > MAX_OUTSIDE_LISTED ? ` and ${outsideRoot.length - MAX_OUTSIDE_LISTED} more` : "");
388
+ const reason = `the producer also changed files outside ${root}: ${listed}; checks scoped to ${root} cannot see them, so the change set cannot be verified as a whole. Verify those paths in their own repository, or dispatch that work separately.`;
389
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
390
+ };
253
391
 
254
- let verdict: Verdict;
255
- if (dod.kind === "deterministic") {
392
+ // Every change is outside the base directory (neither verifier can see any of them): an absolute path outside the canonical
393
+ // base, or a relative one that climbs out of it (`../x`, resolved against the base). Same refusal for both verifiers (C1).
394
+ const refuseAllOutside = (): GateResult | undefined => {
395
+ if (artefact.changedFiles.length === 0) return undefined;
396
+ // No absolute path and no `..` segment: nothing can be outside, and no canonicalisation (a filesystem call) is needed.
397
+ if (!artefact.changedFiles.some(({ path }) => isAbsolute(path) || path.split(/[\\/]/).includes(".."))) return undefined;
256
398
  const canonicalBase = canonical(effectiveBaseDir);
257
- if (artefact.changedFiles.length > 0 && artefact.changedFiles.every(
258
- ({ path }) => isAbsolute(path) && !isWithinDir(canonical(path), canonicalBase),
259
- )) {
260
- // QA-P33F1-1 nit 1: a cwd: narrower than the work root, with work elsewhere in the root → widen (or drop) the cwd:.
261
- const narrowed = workRoot !== undefined && !isWithinDir(canonical(workRoot), canonicalBase)
262
- && artefact.changedFiles.some(({ path }) => isWithinDir(canonical(path), canonical(workRoot)));
263
- const hint = workRoot === undefined
264
- ? `Add "cwd: <dir>" to the [acceptance] block to verify where the work landed.`
265
- : narrowed
266
- ? `The [acceptance] block's "cwd:" narrows verification to ${effectiveBaseDir} inside the work root ${workRoot}: widen "cwd:" to where the work landed, or remove it (the checks then run in the work root).`
267
- : `A role dispatch is verified only inside its work root ${workRoot}: the work belongs there.`;
268
- const reason = `the producer changed files only outside ${effectiveBaseDir} (e.g. ${artefact.changedFiles[0].path}); checks run there cannot see them. ${hint}`;
399
+ const isOutside = (path: string): boolean => {
400
+ if (isAbsolute(path)) return !isWithinDir(canonical(path), canonicalBase);
401
+ // A relative path without a `..` segment cannot leave the base: no canonicalisation (a filesystem call) is needed.
402
+ if (!path.split(/[\\/]/).includes("..")) return false;
403
+ return !isWithinDir(canonical(resolve(effectiveBaseDir, path)), canonicalBase);
404
+ };
405
+ if (!artefact.changedFiles.every(({ path }) => isOutside(path))) return undefined;
406
+ // QA-P33F1-1 nit 1: a cwd: narrower than the work root, with work elsewhere in the root → widen (or drop) the cwd:.
407
+ const narrowed = workRoot !== undefined && !isWithinDir(canonical(workRoot), canonicalBase)
408
+ && artefact.changedFiles.some(({ path }) => isAbsolute(path) && isWithinDir(canonical(path), canonical(workRoot)));
409
+ const hint = workRoot === undefined
410
+ ? `Add "cwd: <dir>" to the [acceptance] block to verify where the work landed.`
411
+ : narrowed
412
+ ? `The [acceptance] block's "cwd:" narrows verification to ${effectiveBaseDir} inside the work root ${workRoot}: widen "cwd:" to where the work landed, or remove it (the checks then run in the work root).`
413
+ : `A role dispatch is verified only inside its work root ${workRoot}: the work belongs there.`;
414
+ const reason = `the producer changed files only outside ${effectiveBaseDir} (e.g. ${artefact.changedFiles[0].path}); checks run there cannot see them. ${hint}`;
415
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
416
+ };
417
+
418
+ // Cross-repo P2.4 (I3, SD7): with placed checks, every changed path must lie inside some check root: the top of a placed check,
419
+ // or the change root for an unplaced one (an undefined top covers nothing). Otherwise part of the change is seen by no check.
420
+ const refuseUncoveredByCheckRoots = (): GateResult | undefined => {
421
+ const placements = delegation.checkPlacements;
422
+ if (placements === undefined || !placements.some(placement => placement !== undefined)) return undefined;
423
+ // QA-3 #1: an unavailable change baseline leaves the change list unknown (often []), not empty.
424
+ const baselineUnavailable = artefact.changeBaseline === "unavailable";
425
+ if (artefact.changedFiles.length === 0 && !baselineUnavailable) return undefined;
426
+ const changeRoot = artefact.changeRoot ?? effectiveBaseDir;
427
+ const tops: string[] = [];
428
+ for (let index = 0; index < (dod.checks ?? []).length; index++) {
429
+ const placement = placements[index];
430
+ // QA-3 #5: an unplaced check, or a non-foreign placement without a top, runs in (covers) the change root.
431
+ const top = placement === undefined || (placement.foreign !== true && placement.top === undefined) ? changeRoot : placement.top;
432
+ if (top !== undefined && !tops.includes(top)) tops.push(top);
433
+ }
434
+ // QA round 2 M1: coverage is decided by tops. A placement inside W whose top is a nested repository (submodule, vendored)
435
+ // does not run in the change root, so it does not cover it (the same placement is refused by I3 when the baseline is known).
436
+ const canonicalChangeRoot = canonical(changeRoot);
437
+ const coversChangeRoot = tops.some(top => isWithinDir(canonicalChangeRoot, canonical(top)));
438
+ if (baselineUnavailable && !coversChangeRoot) {
439
+ const reason = `the change in the work root could not be observed and no check runs there (${tops.length > 0 ? tops.join(", ") : "no check root"}); nothing ran`;
269
440
  return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
270
441
  }
442
+ if (artefact.changedFiles.length === 0) return undefined;
443
+ const canonicalTops = tops.map(top => canonical(top));
444
+ const uncovered = artefact.changedFiles
445
+ .map(({ path }) => path)
446
+ .filter(path => {
447
+ const absolute = canonical(isAbsolute(path) ? path : resolve(changeRoot, path));
448
+ return !canonicalTops.some(top => isWithinDir(absolute, top));
449
+ });
450
+ if (uncovered.length === 0) return undefined;
451
+ const listed = uncovered.slice(0, MAX_OUTSIDE_LISTED).join(", ")
452
+ + (uncovered.length > MAX_OUTSIDE_LISTED ? ` and ${uncovered.length - MAX_OUTSIDE_LISTED} more` : "");
453
+ const reason = `the change in ${listed} is not covered by any check root (${tops.length > 0 ? tops.join(", ") : "no check root"}); nothing ran`;
454
+ return gateResult({ pass: false, outcome: "unverifiable", method: "none", reasons: [reason], caveats: [reason] }, dodSource, deps.strictUnverifiable);
455
+ };
456
+
457
+ let verdict: Verdict;
458
+ if (dod.kind === "deterministic") {
459
+ const allOutside = refuseAllOutside();
460
+ if (allOutside) return allOutside;
461
+ const mixed = refuseMixedOutside();
462
+ if (mixed) return mixed;
463
+ const uncovered = refuseUncoveredByCheckRoots();
464
+ if (uncovered) return uncovered;
465
+ const placements = delegation.checkPlacements;
466
+ // F7: a check placed in another repository resolves relative changed paths against its own cwd, which is not where they were
467
+ // observed: with such a check, hand the runner absolute paths (against the change root).
468
+ const changed = deps.deterministic.changedFiles;
469
+ const hasForeign = placements?.some(placement => placement?.foreign === true) === true;
470
+ const changeRoot = artefact.changeRoot ?? effectiveBaseDir;
271
471
  verdict = await runDeterministic(dod, {
272
472
  ...deps.deterministic,
273
473
  cwd: effectiveBaseDir,
474
+ ...(hasForeign && changed !== undefined && changed !== "unavailable"
475
+ ? {
476
+ changedFiles: changed.map(file => ({
477
+ ...file,
478
+ path: isAbsolute(file.path) ? file.path : resolve(changeRoot, file.path),
479
+ ...(file.previousPath !== undefined
480
+ ? { previousPath: isAbsolute(file.previousPath) ? file.previousPath : resolve(changeRoot, file.previousPath) }
481
+ : {}),
482
+ })),
483
+ }
484
+ : {}),
485
+ ...(placements !== undefined ? { placements } : {}),
486
+ // Cross-repo P3a (SD-P3a-5, -10): with a foreign placement (v2 roles only), W's git top and the consumer link spellings of
487
+ // it, for a consumer testsPass with an explicit scope=affected (deterministic.ts). Never set without a foreign placement.
488
+ ...(hasForeign
489
+ ? {
490
+ changeRoot,
491
+ crossLinkAliases: deps.deterministic.crossLinkAliases ?? ((consumerCwd: string) => crossLinkAliases(consumerCwd, changeRoot)),
492
+ }
493
+ : {}),
274
494
  });
275
495
  } else {
276
496
  // "checker" is the only remaining checkable kind.
497
+ const allOutside = refuseAllOutside();
498
+ if (allOutside) return allOutside;
499
+ const mixed = refuseMixedOutside();
500
+ if (mixed) return mixed;
277
501
  verdict = await runChecker(
278
502
  {
279
503
  criteria: dod.criteria,
@@ -291,5 +515,114 @@ export async function accept(
291
515
  );
292
516
  }
293
517
 
518
+ // I5 (P0.3): nothing observed changed, but the producer ran a tool whose writes the router cannot see. The checks passed on
519
+ // a tree that may not hold the producer's work, so the pass is not a verified pass.
520
+ const writers = artefact.unattributedWriters ?? [];
521
+ if (writers.length > 0 && artefact.changeBaseline === "available" && artefact.changedFiles.length === 0
522
+ && (verdict.outcome ?? (verdict.pass ? "pass" : "fail")) === "pass") {
523
+ const caveat = unattributedWritersCaveat(artefact.changeRoot ?? effectiveBaseDir, writers);
524
+ verdict = { ...verdict, pass: false, outcome: "unverifiable", reasons: [...verdict.reasons, caveat], caveats: [...(verdict.caveats ?? []), caveat] };
525
+ }
526
+ // D6 (cross-repo P2b.4, OD2): a would-be pass with a change, where a working-set worktree links this work root (a consumer) and
527
+ // no testsPass/buildPasses/lintClean/run check is placed in it: nothing ran there, so the pass is not a verified pass.
528
+ const consumerCaveats = unverifiedConsumerCaveats(artefact, dod, delegation.checkPlacements);
529
+ if (consumerCaveats.length > 0 && (verdict.outcome ?? (verdict.pass ? "pass" : "fail")) === "pass") {
530
+ verdict = { ...verdict, pass: false, outcome: "unverifiable", reasons: [...verdict.reasons, ...consumerCaveats], caveats: [...(verdict.caveats ?? []), ...consumerCaveats] };
531
+ }
532
+ // I8 (cross-repo P1.8): a pass names the perimeter it was scoped to. Evidence only: the outcome is unchanged. QA-1 F6: a pass
533
+ // renders its notes, not its reasons (buildAcceptedSuffix), so the line is a note too; a note never makes the pass unverified.
534
+ if (artefact.perimeter !== undefined && artefact.perimeter.roots.length > 0
535
+ && (verdict.outcome ?? (verdict.pass ? "pass" : "fail")) === "pass") {
536
+ const scope = verifiedScopeLine(artefact.perimeter);
537
+ verdict = { ...verdict, reasons: [...verdict.reasons, scope], notes: [...(verdict.notes ?? []), scope] };
538
+ }
539
+
294
540
  return gateResult(verdict, dodSource, deps.strictUnverifiable);
295
541
  }
542
+
543
+ /** OD2: the check kinds that exercise a consumer; `fileExists` and `schemaMatch` do not. */
544
+ const CONSUMER_CHECK_KINDS: ReadonlySet<string> = new Set(["testsPass", "buildPasses", "lintClean", "run"]);
545
+
546
+ /**
547
+ * D6 (cross-repo P2b.4, OD2): one caveat per consumer of W (artefact.perimeter.consumers) that no consumer check is placed in
548
+ * (placement.top equals the consumer root, `perimeterKey` normalisation). [] when there is no perimeter, no consumer, or the
549
+ * change set is empty.
550
+ */
551
+ function unverifiedConsumerCaveats(
552
+ artefact: Artefact,
553
+ dod: DoD,
554
+ placements: readonly (CheckPlacement | undefined)[] | undefined,
555
+ ): string[] {
556
+ // QA-3 #1: an unavailable change baseline counts as a non-empty change set (the change is unknown, not absent).
557
+ if (artefact.changedFiles.length === 0 && artefact.changeBaseline !== "unavailable") return [];
558
+ const consumers = artefact.perimeter?.consumers ?? [];
559
+ const checks = dod.kind === "deterministic" ? dod.checks ?? [] : [];
560
+ const covered = new Set<string>();
561
+ checks.forEach((check, index) => {
562
+ const top = placements?.[index]?.top;
563
+ if (top !== undefined && CONSUMER_CHECK_KINDS.has(check.kind)) covered.add(perimeterKey(top));
564
+ });
565
+ // Cross-repo P3c.5 (SD-P3c-5, F6): a `node_modules` consumer keeps its pinned `(node_modules/<entry>)` literal; an edge consumer
566
+ // reads `(<via>)`, the declaring file and its fixed label through `displaySafe` (the raw spec is never echoed).
567
+ const linkOf = (consumer: { readonly entry?: string; readonly via?: string }): string =>
568
+ consumer.entry !== undefined || consumer.via === undefined
569
+ ? `links this work root (node_modules/${consumer.entry})`
570
+ : `links this work root (${displaySafe(consumer.via)})`;
571
+ const unchecked = consumers
572
+ .filter(consumer => !covered.has(perimeterKey(consumer.root)))
573
+ .map(consumer => `${consumer.name ?? consumer.root} at ${consumer.root} ${linkOf(consumer)} and no check ran there; add a check such as: check: testsPass cwd="${consumer.root}" scope=full`);
574
+ // QA-2 #2: discovery stopped on its budget; a repository there may link this work root unchecked.
575
+ // QA round 2 M2: cleared by the same coverage as a consumer (a consumer check placed with its top equal to that root).
576
+ const incomplete = (artefact.perimeter?.consumersIncomplete ?? [])
577
+ .filter(entry => !covered.has(perimeterKey(entry.root)))
578
+ .map(entry => `consumer discovery stopped before finishing ${entry.name ?? entry.root} at ${entry.root}; a repository there may link this work root unchecked; add a check such as: check: testsPass cwd="${entry.root}" scope=full`);
579
+ return [...unchecked, ...incomplete];
580
+ }
581
+
582
+ /** I5 (P0.3): the caveat for an empty change set when the producer ran tools whose writes the router cannot observe. */
583
+ export function unattributedWritersCaveat(root: string, writers: readonly string[]): string {
584
+ return `no change was observed in ${root} but the producer ran ${listedTools(writers)}; a write those tools made cannot be seen, so this is not a verified pass`;
585
+ }
586
+
587
+ /** At most MAX_OUTSIDE_LISTED tool names, sanitised (toolLabel), then "and N more". */
588
+ function listedTools(writers: readonly string[]): string {
589
+ return writers.slice(0, MAX_OUTSIDE_LISTED).map(toolLabel).join(", ")
590
+ + (writers.length > MAX_OUTSIDE_LISTED ? ` and ${writers.length - MAX_OUTSIDE_LISTED} more` : "");
591
+ }
592
+
593
+ /**
594
+ * I4 (cross-repo P1.8): one unverifiable reason per extra root of the perimeter that changed during the dispatch, or whose
595
+ * snapshot was unavailable at either end (fail closed), when the producer lineage ran an unattributable writer; [] otherwise.
596
+ * `w` names where the checks run.
597
+ */
598
+ export function perimeterChangeReasons(artefact: Pick<Artefact, "perimeter" | "unattributedWriters">, w: string): string[] {
599
+ const writers = artefact.unattributedWriters ?? [];
600
+ if (artefact.perimeter === undefined || writers.length === 0) return [];
601
+ const tools = listedTools(writers);
602
+ return artefact.perimeter.roots.filter(root => root.status === "changed" || root.status === "unobserved").map(root => {
603
+ if (root.name === PERIMETER_UNPLANNED) {
604
+ return `the verification ${PERIMETER_UNPLANNED} when the dispatch started, and the producer ran ${tools}; a write in another repository cannot be ruled out, so the checks in ${w} do not cover it. Re-dispatch, or verify it there.`;
605
+ }
606
+ const what = root.status === "changed" ? "also changed during the dispatch" : "could not be observed during the dispatch";
607
+ // QA-1 F11: another worktree of W's own repository is reached by its branch, not by the repository's name.
608
+ const target = root.sameRepository === true && root.branch !== undefined ? `branch=${root.branch}` : `repo=${root.name}`;
609
+ return `the repository ${root.name} at ${root.root} ${what}, and the producer ran ${tools}; a write there cannot be attributed, so the checks in ${w} do not cover it. Dispatch that work with ${target}, or verify it there.`;
610
+ });
611
+ }
612
+
613
+ /**
614
+ * I8 (cross-repo P1.8): the evidence line of a pass whose perimeter holds more than W. QA-1 F6 (I4 "otherwise → a note"): a root
615
+ * that changed without an unattributable writer is shown as changed.
616
+ */
617
+ export function verifiedScopeLine(perimeter: PerimeterObservation): string {
618
+ // P3 QA-1 M5: a name, a branch and a head come from the repositories (a manifest, a file system): escaped and capped.
619
+ const show = (repo: PerimeterRepo, suffix = ""): string =>
620
+ `${scopeText(repo.name)} (${scopeText(repo.branch ?? "detached")} @ ${repo.head !== undefined && repo.head !== "" ? scopeText(repo.head.slice(0, 7)) : "unknown"}${suffix})`;
621
+ const others = perimeter.roots.map(root => {
622
+ if (root.name === PERIMETER_UNPLANNED) return PERIMETER_UNPLANNED;
623
+ if (root.status === "unadmitted") return `${scopeText(root.name)} (not admitted)`;
624
+ if (root.status === "unobserved") return `${scopeText(root.name)} (not observed)`;
625
+ return root.status === "changed" ? show(root, ", changed during the dispatch") : show(root);
626
+ });
627
+ return `verified scope: ${show(perimeter.w)}; also observed: ${others.join(", ")}`;
628
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * src/verify/git-top.ts
3
+ *
4
+ * The git top level of a directory, found without running git (cross-repo QA-1 F3), shared by the verification perimeter
5
+ * (perimeter.ts) and the per-check placement resolver (routing/roles/check-placement.ts).
6
+ */
7
+ import { lstatSync } from "node:fs";
8
+ import * as path from "node:path";
9
+ import { isSlash, trimEndWhile } from "../util/linear-trim";
10
+
11
+ /** A comparison key: absolute, "/" separators, no trailing separator, case-folded on win32. */
12
+ export function perimeterKey(at: string): string {
13
+ const normalized = trimEndWhile(path.resolve(at).replace(/\\/g, "/"), isSlash); // linear: no `/\/+$/` (polynomial on a run of "/")
14
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
15
+ }
16
+
17
+ /** How many segments `child` lies below `parent`: 0 when equal, -1 when not inside. */
18
+ export function depthBelow(child: string, parent: string): number {
19
+ const c = perimeterKey(child);
20
+ const p = perimeterKey(parent);
21
+ if (c === p) return 0;
22
+ return c.startsWith(`${p}/`) ? c.slice(p.length + 1).split("/").length : -1;
23
+ }
24
+
25
+ /**
26
+ * QA-1 F3: the git top level of `dir` found without git: the nearest directory at or above it holding a `.git` entry (a
27
+ * directory, or a worktree's or submodule's `.git` file), strictly below `ceiling` when given. Undefined when there is none.
28
+ */
29
+ export function gitTopOf(dir: string, ceiling?: string): string | undefined {
30
+ let current = path.resolve(dir);
31
+ for (;;) {
32
+ if (ceiling !== undefined && !(depthBelow(current, ceiling) >= 1)) return undefined;
33
+ try {
34
+ lstatSync(path.join(current, ".git"));
35
+ return current;
36
+ } catch {
37
+ // No `.git` here: keep walking up.
38
+ }
39
+ const up = path.dirname(current);
40
+ if (up === current) return undefined;
41
+ current = up;
42
+ }
43
+ }
@@ -0,0 +1,107 @@
1
+ // Impure, cheap HEAD reader: where a working tree is checked out, and how many HEAD reflog entries it has.
2
+ // Kept apart from tree.ts on purpose: several tests mock that module with `snapshotTree` alone.
3
+ import { realpath } from "node:fs/promises";
4
+ import { execGit, gitExitCode } from "./tree";
5
+
6
+ /** What the branch-switch rule reads of a working tree (see branch.ts `treeMove`). */
7
+ export interface HeadState {
8
+ /** realpath of the toplevel, as snapshotTree reports it. */
9
+ readonly root: string;
10
+ readonly head: string;
11
+ /** The branch name without `refs/heads/`; null on a detached HEAD; any other ref kept whole. */
12
+ readonly branch: string | null;
13
+ /** Number of HEAD reflog entries (per worktree); absent when it could not be counted. */
14
+ readonly reflog?: number;
15
+ }
16
+
17
+ export interface HeadReadOptions {
18
+ readonly signal?: AbortSignal;
19
+ /** Each git process. Default 5000. */
20
+ readonly timeoutMs?: number;
21
+ readonly lowPriority?: boolean;
22
+ }
23
+
24
+ const DEFAULT_TIMEOUT_MS = 5000;
25
+ const MAX_BUFFER = 1024 * 1024;
26
+ const MAX_WINDOW = 1000;
27
+
28
+ function runner(cwd: string, opts: HeadReadOptions | undefined): (args: readonly string[]) => Promise<string> {
29
+ const signal = opts?.signal ?? new AbortController().signal;
30
+ return (args) => execGit(["--no-pager", "--no-optional-locks", ...args], {
31
+ cwd, signal, timeoutMs: opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer: MAX_BUFFER, lowPriority: opts?.lowPriority === true,
32
+ });
33
+ }
34
+
35
+ /**
36
+ * What a head read found: the state, `"none"` when git RAN and exited non-zero (not a repository, an unborn branch: there is
37
+ * no HEAD to compare), or undefined when the answer is unknown (timeout, abort, spawn failure, unparsable output).
38
+ */
39
+ export type HeadRead = HeadState | "none" | undefined;
40
+
41
+ /**
42
+ * The toplevel, HEAD and branch of the checkout at `cwd` (one git process), plus its HEAD reflog count (a second one).
43
+ * `"none"` only for a git exit code (never decided from git's localised message); every other failure is undefined. A failing
44
+ * count, or a count of 0 (reflogs disabled: `core.logAllRefUpdates=false`), only leaves `reflog` absent.
45
+ */
46
+ export async function readHead(cwd: string, opts?: HeadReadOptions): Promise<HeadRead> {
47
+ const git = runner(cwd, opts);
48
+ let root: string;
49
+ let head: string;
50
+ let branch: string | null;
51
+ try {
52
+ const lines = (await git(["rev-parse", "--show-toplevel", "HEAD", "--symbolic-full-name", "HEAD"])).split(/\r?\n/);
53
+ const top = (lines[0] ?? "").trim();
54
+ head = (lines[1] ?? "").trim();
55
+ const ref = (lines[2] ?? "").trim();
56
+ if (top === "" || !/^[0-9a-f]{40,64}$/i.test(head) || ref === "") return undefined;
57
+ branch = ref === "HEAD" ? null : ref.startsWith("refs/heads/") ? ref.slice("refs/heads/".length) : ref;
58
+ root = await realpath(top);
59
+ } catch (err) {
60
+ return gitExitCode(err) !== undefined ? "none" : undefined;
61
+ }
62
+ try {
63
+ const text = (await git(["rev-list", "--walk-reflogs", "--count", "HEAD"])).trim();
64
+ // HEAD exists, so a reflog of 0 entries means there is none (reflogs off), not an empty one.
65
+ if (/^\d+$/.test(text) && Number(text) > 0) return { root, head, branch, reflog: Number(text) };
66
+ } catch {
67
+ // The count is optional.
68
+ }
69
+ return { root, head, branch };
70
+ }
71
+
72
+ /** `readHead` for callers that treat "no repository / unborn" and "unknown" alike: undefined for both. */
73
+ export async function readHeadState(cwd: string, opts?: HeadReadOptions): Promise<HeadState | undefined> {
74
+ const read = await readHead(cwd, opts);
75
+ return read === "none" ? undefined : read;
76
+ }
77
+
78
+ /** One HEAD reflog entry: the commit HEAD pointed at after it, and its subject (`%gs`). */
79
+ export interface ReflogEntry {
80
+ readonly commit: string;
81
+ readonly subject: string;
82
+ }
83
+
84
+ /**
85
+ * The HEAD reflog window since a recorded count, read in ONE git process so it is anchored: `count` new entries plus the one
86
+ * that was newest at the earlier read, newest first. [] for count <= 0 without running git; undefined on failure, on a count
87
+ * above 1000, or when the output cannot be parsed.
88
+ */
89
+ export async function readReflogWindow(cwd: string, count: number, opts?: HeadReadOptions): Promise<ReflogEntry[] | undefined> {
90
+ if (!(count > 0)) return [];
91
+ const n = Math.floor(count);
92
+ if (n > MAX_WINDOW) return undefined;
93
+ try {
94
+ const lines = (await runner(cwd, opts)(["log", "-g", "-n", String(n + 1), "--format=%H%x09%gs", "HEAD"])).split(/\r?\n/);
95
+ if (lines[lines.length - 1] === "") lines.pop();
96
+ const entries: ReflogEntry[] = [];
97
+ for (const line of lines) {
98
+ const tab = line.indexOf("\t");
99
+ const commit = tab < 0 ? line : line.slice(0, tab);
100
+ if (!/^[0-9a-f]{40,64}$/i.test(commit)) return undefined;
101
+ entries.push({ commit, subject: tab < 0 ? "" : line.slice(tab + 1) });
102
+ }
103
+ return entries;
104
+ } catch {
105
+ return undefined;
106
+ }
107
+ }