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
@@ -37,6 +37,7 @@ import type {
37
37
  RunnerHost,
38
38
  RunResult,
39
39
  TestSearchSeam,
40
+ Unverifiable,
40
41
  } from "./runner";
41
42
  import type { DispatchReference, MaterializedReference, ReferenceDeps } from "./reference";
42
43
  import type { TreeSnapshot } from "./dispatch";
@@ -47,6 +48,7 @@ import { resolveAgainst } from "./paths";
47
48
  import { isAbsolute, posix as pathPosix, win32 as pathWin32 } from "node:path";
48
49
  import { judgeScoped, observeTests, REFERENCE_NONE } from "./baseline";
49
50
  import {
51
+ crossLinkIgnoredS6,
50
52
  detectRunner,
51
53
  isNoAffected,
52
54
  isUnscoped,
@@ -58,8 +60,10 @@ import {
58
60
  resolveEntry,
59
61
  } from "./runner";
60
62
  import { fileKeyOfId } from "./baseline";
63
+ import { isTestPath } from "./risk";
61
64
  import { DEFAULT_MATERIALIZE_TIMEOUT_MS, gcStaleReferences, materialize, nodeReferenceFs } from "./reference";
62
65
  import { acquireSlot, type SlotHandle } from "./slot";
66
+ import type { ServiceObservation } from "../executor/observations";
63
67
 
64
68
  // ---------------------------------------------------------------------------
65
69
  // MutexRegistry — per-key serialization via promise-chaining
@@ -845,6 +849,7 @@ export interface CheckScope extends VerificationScope {
845
849
  export type OpenCheckScope = (meta: Parameters<OpenVerificationScope>[0]) => CheckScope;
846
850
 
847
851
  export interface ScopeOpenerDeps {
852
+ service?: ServiceObservation;
848
853
  argv: ArgvSeam;
849
854
  exec: ExecSeam;
850
855
  fs: RunnerFs;
@@ -955,6 +960,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
955
960
  // at the deadline, even when the wait's own timer fires a few ms before remaining() reads 0.
956
961
  const waitMs = deadline.bound(budget.slotWaitMs);
957
962
  const cutByDeadline = waitMs < budget.slotWaitMs;
963
+ const wait = deps.service?.start("service-wait", "verification-slot");
958
964
  try {
959
965
  const r = await acquire({
960
966
  max: budget.maxConcurrentVerifications,
@@ -964,21 +970,25 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
964
970
  onLost,
965
971
  });
966
972
  if ("busy" in r) {
973
+ wait?.end("busy");
967
974
  return {
968
975
  ok: false,
969
976
  outcome: { kind: "slot-busy", waitedMs: Math.max(0, now() - started), deadlineCut: cutByDeadline || deadline.remaining() === 0 },
970
977
  };
971
978
  }
979
+ wait?.end("acquired");
972
980
  return { ok: true, handle: r };
973
981
  } catch (err) {
974
982
  return { ok: false, outcome: { kind: "error", reason: `verification slot failed: ${errorText(err)}` } };
975
- }
983
+ } finally { wait?.end("error"); }
976
984
  };
977
985
 
978
986
  const attempt = async (
979
987
  deadline: Deadline,
980
988
  launch: (opts: ExecOptions) => Promise<ExecResult>,
981
989
  ownMs: number = checkTimeoutMs,
990
+ stage = "command",
991
+ candidate?: string,
982
992
  ): Promise<Blocked | Spawned> => {
983
993
  if (closed) return { kind: "error", reason: "verification scope already closed" };
984
994
  holdP ??= acquireHold(deadline);
@@ -994,12 +1004,15 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
994
1004
  deadline.signal.addEventListener("abort", onAbort, { once: true });
995
1005
  let execResult: ExecResult;
996
1006
  let threw: string | undefined;
1007
+ const service = deps.service?.execution(stage, candidate);
997
1008
  try {
998
- execResult = await launch({ lowPriority: budget.lowPriority, signal: run.signal, timeoutMs: boundMs });
1009
+ execResult = await launch({ lowPriority: budget.lowPriority, signal: run.signal, timeoutMs: boundMs,
1010
+ ...(service === undefined ? {} : { service }) });
1011
+ service?.end(run.signal.aborted ? "interrupted" : execResult.timedOut ? "timed-out" : execResult.code === 0 ? "pass" : "fail");
999
1012
  } catch (err) {
1000
1013
  threw = errorText(err);
1001
1014
  execResult = { code: -1, stdout: "", stderr: threw };
1002
- }
1015
+ } finally { service?.end("error"); }
1003
1016
  deadline.signal.removeEventListener("abort", onAbort);
1004
1017
  if (threw !== undefined || execResult.timedOut === true) {
1005
1018
  run.abort(new Error(threw ?? `run exceeded its ${boundMs}ms bound`));
@@ -1057,6 +1070,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1057
1070
  liveCwd: string,
1058
1071
  failingFiles: readonly string[],
1059
1072
  rd: Deadline,
1073
+ candidate: string,
1060
1074
  ): Promise<RecheckOutcome> => {
1061
1075
  if (!ref.exact) return { kind: "approximate", inexactReasons: ref.inexactReasons };
1062
1076
  const platform = host?.platform ?? process.platform;
@@ -1095,7 +1109,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1095
1109
  const a = await attempt(
1096
1110
  rd,
1097
1111
  opts => argv(spec.file, spec.args, { ...opts, cwd: spec.cwd, env: { ...spec.env } }),
1098
- budget.recheckTimeoutMs,
1112
+ budget.recheckTimeoutMs, "recheck", candidate,
1099
1113
  );
1100
1114
  if (a.kind === "aborted") return { kind: "skipped-deadline", remainingMs: rd.remaining() };
1101
1115
  if (a.kind === "slot-busy") return unusable("error", "the verification slot was not available for the recheck");
@@ -1150,6 +1164,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1150
1164
  }
1151
1165
 
1152
1166
  const rd = deriveDeadline(deadline, budget.recheckTimeoutMs, { now });
1167
+ const preparation = deps.service?.start("service-prep", "reference-materialization");
1153
1168
  try {
1154
1169
  // QA-1.5-10: GC, then materialize, both inside the hold.
1155
1170
  const gc = await seams.gcStaleReferences(reference.root, { ...refDeps, timeoutMs: rd.bound(RECHECK_GC_MS) });
@@ -1167,13 +1182,15 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1167
1182
  : unusable("materialize-failed", `materialize ${m.reason}: ${m.detail}`);
1168
1183
  }
1169
1184
  const ref = m.reference;
1185
+ preparation?.end("completed");
1170
1186
  try {
1171
- return await rerunAt(ref, runner, liveCwd, failingFiles, rd);
1187
+ return await rerunAt(ref, runner, liveCwd, failingFiles, rd, reference.commit);
1172
1188
  } finally {
1173
1189
  // T4.l: the rerun tree has exited here; close() waits for this before releasing the slot.
1174
1190
  track(ref.dispose().catch((err: unknown) => logger?.warn(`reference dispose failed: ${errorText(err)}`)));
1175
1191
  }
1176
1192
  } finally {
1193
+ preparation?.end("error");
1177
1194
  rd.dispose();
1178
1195
  }
1179
1196
  };
@@ -1228,6 +1245,7 @@ export function createScopeOpener(deps: ScopeOpenerDeps): OpenCheckScope {
1228
1245
  // -----------------------------------------------------------------------------------------------
1229
1246
 
1230
1247
  export interface DirectTestsPassHookDeps {
1248
+ service?: ServiceObservation;
1231
1249
  openScope: OpenCheckScope;
1232
1250
  /** Built in wiring.ts (2.1.3, T9). */
1233
1251
  plannerFs: PlannerFs;
@@ -1238,6 +1256,19 @@ export interface DirectTestsPassHookDeps {
1238
1256
  currentTree?: TreeSnapshot;
1239
1257
  /** Planner seam; default planScopedRun. */
1240
1258
  plan?: typeof planScopedRun;
1259
+ /**
1260
+ * Cross-repo P3a (D23, OD-P3a-2 b): lists the linked repository's git-ignored modules (tree.ts listIgnoredModules), added to a
1261
+ * cross-link request's changed files so a consumer that loads W's build output (`dist/`) is selected. Called only for a request
1262
+ * with `crossLinkRoot`, a `dispatchStartedAt` (`since`: only the files modified at or after it, D23 as amended 2026-10-12)
1263
+ * and a non-empty change set; absent: nothing is added (as before).
1264
+ */
1265
+ listIgnored?: (root: string, signal: AbortSignal, since: number) => Promise<import("./tree").IgnoredModules>;
1266
+ /**
1267
+ * Cross-repo P3a (D23, QA round 2 M-A): a changed source's mtime in ms (tree.ts fileMtimeMs), undefined when the file does not
1268
+ * exist. Compared with the newest listed ignored module of each ignored directory; absent, or a throw, counts as newer than
1269
+ * any build (fail closed: S6 cross-link-build-stale).
1270
+ */
1271
+ mtimeOf?: (path: string) => Promise<number | undefined>;
1241
1272
  logger?: Pick<PluginLogger, "warn">;
1242
1273
  }
1243
1274
 
@@ -1274,6 +1305,78 @@ async function synthesizeFullResult(
1274
1305
  };
1275
1306
  }
1276
1307
 
1308
+ /** Cross-repo P3a (D23, QA round 2 M-A): declaration files are never build inputs whose edit leaves the build output stale. */
1309
+ const DECLARATION_SOURCE = /\.d\.[cm]?ts$/i;
1310
+
1311
+ /**
1312
+ * Cross-repo P3a (D23, QA round 2 M-A): mirrors tree.ts IGNORED_TOOL_STATE_DIRS (not imported: this module stays pure). A path
1313
+ * relative to W with a `node_modules` (so `node_modules/.vite`) or tool-state segment, any case for the latter.
1314
+ */
1315
+ const TOOL_STATE_DIRS: readonly string[] = ["coverage", ".nyc_output", ".vitest", ".cache"];
1316
+ function isToolStatePath(relative: string): boolean {
1317
+ return relative.split(/[\\/]/).some(segment => segment === "node_modules" || TOOL_STATE_DIRS.includes(segment.toLowerCase()));
1318
+ }
1319
+
1320
+ /** A deleted status: a porcelain XY code with D in either column, else (`D`, `deleted`) its first letter (as risk.ts). */
1321
+ function isDeletedStatus(status: string | undefined): boolean {
1322
+ if (status === undefined) return false;
1323
+ return /^[ MADRCU?!]{2}$/.test(status) ? status.includes("D") : /^d/i.test(status);
1324
+ }
1325
+
1326
+ /**
1327
+ * Cross-repo P3a (D23, QA round 2 M-A): S6 `cross-link-build-stale` when a changed source of W is newer than the newest listed
1328
+ * ignored module of an ignored directory (`newestByDir`, tree.ts newestMtimeByDir), else undefined. The sources: the request's
1329
+ * changed files under `root` that are not tests (risk.ts isTestPath, on the W-relative path), not declaration files, not
1330
+ * deleted and not ignored (`!!`). A source that no longer exists (`mtimeOf` undefined) is skipped; a source whose mtime cannot
1331
+ * be read (a throw, or no `mtimeOf`) counts as newer than any build (fail closed). The newest source names the S6; the
1332
+ * directories are compared in sorted order.
1333
+ */
1334
+ async function buildStaleness(
1335
+ req: TestsPassRequest,
1336
+ root: string,
1337
+ newestByDir: Readonly<Record<string, number>>,
1338
+ mtimeOf: ((path: string) => Promise<number | undefined>) | undefined,
1339
+ host: Partial<RunnerHost> | undefined,
1340
+ ): Promise<Unverifiable | undefined> {
1341
+ if (req.changedFiles === "unavailable") return undefined;
1342
+ const P = (host?.platform ?? process.platform) === "win32" ? pathWin32 : pathPosix;
1343
+ let newestSource: { rel: string; mtime: number } | undefined;
1344
+ const sources = req.changedFiles
1345
+ .filter(f => f.status !== "!!" && !isDeletedStatus(f.status))
1346
+ .map(f => {
1347
+ const absolute = P.isAbsolute(f.path) ? f.path : P.resolve(req.cwd, f.path);
1348
+ return { absolute, rel: P.relative(root, absolute).replace(/\\/g, "/") };
1349
+ })
1350
+ .filter(s => s.rel !== "" && s.rel !== ".." && !s.rel.startsWith("../") && !P.isAbsolute(s.rel))
1351
+ .filter(s => !isTestPath(s.rel) && !DECLARATION_SOURCE.test(s.rel))
1352
+ .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
1353
+ for (const source of sources) {
1354
+ let mtime: number | undefined;
1355
+ try {
1356
+ mtime = mtimeOf === undefined ? Infinity : await mtimeOf(source.absolute);
1357
+ } catch {
1358
+ mtime = Infinity;
1359
+ }
1360
+ if (mtime === undefined) continue; // Gone: no content of it can be newer than the build.
1361
+ if (Number.isNaN(mtime)) mtime = Infinity; // Unreadable: fail closed.
1362
+ if (newestSource === undefined || mtime > newestSource.mtime) newestSource = { rel: source.rel, mtime };
1363
+ }
1364
+ if (newestSource === undefined) return undefined;
1365
+ for (const dir of Object.keys(newestByDir).sort()) {
1366
+ if (newestSource.mtime > newestByDir[dir]) {
1367
+ const where = dir === "." ? root : `${root}/${dir}`;
1368
+ return {
1369
+ unverifiable: true,
1370
+ code: "cross-link-build-stale",
1371
+ reason:
1372
+ `the build output in ${where} is older than ${newestSource.rel} changed in the linked repository; ` +
1373
+ "rebuild it (e.g. a buildPasses check in the linked repository before this one) or use scope=full",
1374
+ };
1375
+ }
1376
+ }
1377
+ return undefined;
1378
+ }
1379
+
1277
1380
  /**
1278
1381
  * S5 as a direct call (2.1.2.4; 2.2 swaps in the batch coordinator): plan, run under ONE scope,
1279
1382
  * recheck the failing files at the dispatch reference, close the scope. Never rejects.
@@ -1300,29 +1403,89 @@ export function createDirectTestsPassHook(deps: DirectTestsPassHookDeps): TestsP
1300
1403
  return scope.rechecker(req.command, req.cwd, deps.currentTree)(ref.reference, scoped.result.failingFiles, req.deadline);
1301
1404
  };
1302
1405
 
1406
+ /**
1407
+ * Cross-repo P3a (D23, OD-P3a-2 b, finding X6): with `crossLinkRoot` and a lister, W's git-ignored modules are appended to the
1408
+ * changed files (exact-path duplicates dropped; status `!!`, git's code for an ignored file), so a consumer that loads W's
1409
+ * build output (`dist/`) is selected. Over the bounds, unlisted or a throwing lister → S6 (fail closed), before any plan.
1410
+ * Otherwise (no cross-link root, no lister, unavailable changed files, nothing ignored) the request's own changed files.
1411
+ *
1412
+ * D23 as amended (2026-10-12, QA C1/M4): only the modules whose own mtime is at or after the dispatch start are listed (lister
1413
+ * `since` = the request's `dispatchStartedAt`, the original start of a deferred one; tool-state directories such as
1414
+ * `coverage/` never), so a build output older than the dispatch is never a run input. A module written during the dispatch
1415
+ * is still stale when W's source changed again after it (QA round 2 M-A): when any changed source of W (buildStaleness) is
1416
+ * newer than the newest listed module of an ignored directory that contributed modules (`dist/`), the request is S6
1417
+ * `cross-link-build-stale` (fail closed), before any plan. No start time, or no change of W's in the request: the lister is
1418
+ * not called and nothing is added; nothing listed: nothing is added and nothing is compared (toward zero selection, never
1419
+ * toward stale inputs).
1420
+ */
1421
+ const withIgnoredModules = async (req: TestsPassRequest): Promise<{ files: TestsPassRequest["changedFiles"] } | Unverifiable> => {
1422
+ if (req.crossLinkRoot === undefined || deps.listIgnored === undefined || req.changedFiles === "unavailable") {
1423
+ return { files: req.changedFiles };
1424
+ }
1425
+ const since = req.dispatchStartedAt;
1426
+ if (since === undefined || !Number.isFinite(since) || req.changedFiles.length === 0) return { files: req.changedFiles };
1427
+ const root = req.crossLinkRoot;
1428
+ let listed: import("./tree").IgnoredModules;
1429
+ try {
1430
+ listed = await deps.listIgnored(root, req.deadline.signal, since);
1431
+ } catch {
1432
+ listed = { unavailable: true };
1433
+ }
1434
+ if ("overBounds" in listed) return crossLinkIgnoredS6("over-bounds", root);
1435
+ if (!("files" in listed)) return crossLinkIgnoredS6("unavailable", root);
1436
+ // QA round 2 M-A: tool-state files (`coverage/`, ...) are neither inputs nor build output, whatever the lister answers.
1437
+ const P = (deps.host?.platform ?? process.platform) === "win32" ? pathWin32 : pathPosix;
1438
+ const modules = listed.files.filter(path => !isToolStatePath(P.relative(root, path)));
1439
+ if (modules.length > 0) {
1440
+ const newestByDir: Record<string, number> = {};
1441
+ for (const [dir, mtime] of Object.entries(listed.newestMtimeByDir)) if (!isToolStatePath(dir)) newestByDir[dir] = mtime;
1442
+ const stale = await buildStaleness(req, root, newestByDir, deps.mtimeOf, deps.host);
1443
+ if (stale !== undefined) return stale;
1444
+ }
1445
+ const seen = new Set(req.changedFiles.map(f => f.path));
1446
+ const added: { path: string; status: string }[] = [];
1447
+ for (const path of modules) {
1448
+ if (seen.has(path)) continue;
1449
+ seen.add(path);
1450
+ added.push({ path, status: "!!" });
1451
+ }
1452
+ return { files: added.length === 0 ? req.changedFiles : [...req.changedFiles, ...added] };
1453
+ };
1454
+
1303
1455
  return async (req): Promise<TestsPassRun> => {
1304
1456
  let scope: CheckScope | undefined;
1305
1457
  let scoped: ScopedOutcome | undefined;
1458
+ const preparation = deps.service?.start("service-prep", "test-planning");
1306
1459
  try {
1307
1460
  if (req.testScope === "full") {
1308
1461
  scope = deps.openScope({ cwd: req.cwd, command: req.command });
1462
+ preparation?.end("completed");
1309
1463
  scoped = await runFull(req, scope);
1310
1464
  } else {
1465
+ // Cross-repo P3a (D23): a cross-link request also passes W's ignored modules (its build output), or is S6 without them.
1466
+ const changedFiles = await withIgnoredModules(req);
1467
+ if ("unverifiable" in changedFiles) {
1468
+ return { scoped: { kind: "unverifiable", code: changedFiles.code, reason: changedFiles.reason }, recheck: undefined };
1469
+ }
1311
1470
  // P2/P3: planning outcomes take no slot and spawn nothing.
1312
1471
  const planned = await plan({
1313
1472
  command: req.command,
1314
1473
  cwd: req.cwd,
1315
- changedFiles: req.changedFiles,
1474
+ changedFiles: changedFiles.files,
1316
1475
  budget: { maxWorkers: deps.budget.maxWorkers },
1317
1476
  fs: deps.plannerFs,
1318
1477
  search: deps.search,
1319
1478
  ...(deps.host !== undefined ? { host: deps.host } : {}),
1479
+ // Cross-repo P3a (runner.ts G.4b): only when set, so a request without them plans as before.
1480
+ ...(req.crossLinkRoot !== undefined ? { crossLinkRoot: req.crossLinkRoot } : {}),
1481
+ ...(req.crossLinkAliases !== undefined ? { crossLinkAliases: req.crossLinkAliases } : {}),
1320
1482
  });
1321
1483
  if (isNoAffected(planned)) return { scoped: { kind: "no-affected", note: planned.note }, recheck: undefined };
1322
1484
  if (isUnverifiable(planned)) {
1323
1485
  return { scoped: { kind: "unverifiable", code: planned.code, reason: planned.reason }, recheck: undefined };
1324
1486
  }
1325
1487
  scope = deps.openScope({ cwd: req.cwd, command: req.command });
1488
+ preparation?.end("completed");
1326
1489
  scoped = await scope.execute(planned, req.deadline);
1327
1490
  }
1328
1491
  return { scoped, recheck: await recheckFor(req, scope, scoped) };
@@ -1331,6 +1494,7 @@ export function createDirectTestsPassHook(deps: DirectTestsPassHookDeps): TestsP
1331
1494
  if (scoped !== undefined) return { scoped, recheck: { kind: "unusable", cause: "error", reason: `the reference recheck errored: ${reason}` } };
1332
1495
  return { scoped: { kind: "error", reason: `testsPass hook errored: ${reason}` }, recheck: undefined };
1333
1496
  } finally {
1497
+ preparation?.end(scoped === undefined ? "no-run" : "error");
1334
1498
  if (scope !== undefined) await closeWithinDeadline(scope, req.deadline, deps.logger);
1335
1499
  }
1336
1500
  };
@@ -1486,12 +1650,44 @@ function fromJudgement(j: TestsPassJudgement): CheckResult {
1486
1650
  };
1487
1651
  }
1488
1652
 
1653
+ /** Cross-repo P2.4: the reference of a check placed in another repository (the dispatch captured the work root only). */
1654
+ export const FOREIGN_REFERENCE_NONE = "the check runs in another repository; the dispatch reference covers the work root only";
1655
+
1489
1656
  function defaultReference(deps: DeterministicDeps): ReferenceState {
1490
1657
  return deps.budget?.failureRecheck === false ? { kind: "disabled" } : { kind: "none", reason: REFERENCE_NONE.untracked };
1491
1658
  }
1492
1659
 
1660
+ /**
1661
+ * Cross-repo P3a (SD-P3a-1, -2, -5): the cross-link inputs of a foreign testsPass with an explicit scope=affected: W's git top
1662
+ * and the other spellings of it seen from the consumer (`DeterministicDeps.crossLinkAliases`).
1663
+ */
1664
+ interface CrossLinkTarget {
1665
+ readonly root: string;
1666
+ readonly aliases?: readonly string[];
1667
+ }
1668
+
1669
+ /** The cross-link target for a consumer cwd; the alias provider is fail-soft (an error or a non-array gives no aliases). */
1670
+ function crossLinkTarget(deps: DeterministicDeps, root: string, consumerCwd: string): CrossLinkTarget {
1671
+ let aliases: readonly string[] | undefined;
1672
+ if (deps.crossLinkAliases !== undefined) {
1673
+ try {
1674
+ const given = deps.crossLinkAliases(consumerCwd);
1675
+ if (Array.isArray(given)) aliases = given.filter((alias): alias is string => typeof alias === "string" && alias !== "");
1676
+ } catch {
1677
+ aliases = undefined;
1678
+ }
1679
+ }
1680
+ return { root, ...(aliases !== undefined ? { aliases } : {}) };
1681
+ }
1682
+
1493
1683
  /** P0-P8 for one testsPass check whose command already passed the allowlist (P1). Never rejects. */
1494
- async function runTestsPass(command: string, deps: DeterministicDeps, timeoutMs: number): Promise<CheckResult> {
1684
+ async function runTestsPass(
1685
+ command: string,
1686
+ deps: DeterministicDeps,
1687
+ timeoutMs: number,
1688
+ scope?: "affected" | "full",
1689
+ crossLink?: CrossLinkTarget,
1690
+ ): Promise<CheckResult> {
1495
1691
  if (!deps.testsPass) return { ok: false, unverifiable: true, reason: `${NO_TESTS_PASS_HOOK}: ${command}` };
1496
1692
  if (!deps.cwd || !isAbsolute(deps.cwd)) {
1497
1693
  return { ok: false, unverifiable: true, reason: `testsPass cannot run without an absolute working directory: ${command}` };
@@ -1503,10 +1699,14 @@ async function runTestsPass(command: string, deps: DeterministicDeps, timeoutMs:
1503
1699
  const run = await hook({
1504
1700
  command,
1505
1701
  cwd,
1506
- testScope: deps.budget?.testScope ?? "affected",
1702
+ testScope: scope ?? deps.budget?.testScope ?? "affected",
1507
1703
  changedFiles: deps.changedFiles ?? "unavailable",
1508
1704
  reference: deps.reference ?? defaultReference(deps),
1509
1705
  deadline,
1706
+ ...(crossLink !== undefined ? { crossLinkRoot: crossLink.root } : {}),
1707
+ ...(crossLink?.aliases !== undefined ? { crossLinkAliases: crossLink.aliases } : {}),
1708
+ // D23 as amended (QA C1): the dispatch start, so only W's ignored modules modified during the dispatch are inputs.
1709
+ ...(crossLink !== undefined && deps.dispatchStartedAt !== undefined ? { dispatchStartedAt: deps.dispatchStartedAt } : {}),
1510
1710
  });
1511
1711
  // QA-G-B-2-1: a carried acceptance never passes on a run that never happened.
1512
1712
  if (deps.noAffectedUnverifiable !== undefined && run.scoped.kind === "no-affected") {
@@ -1525,6 +1725,8 @@ async function runCommandCheck(
1525
1725
  deps: DeterministicDeps,
1526
1726
  allowlist: string[],
1527
1727
  timeoutMs: number,
1728
+ scope?: "affected" | "full",
1729
+ crossLink?: CrossLinkTarget,
1528
1730
  ): Promise<CheckResult> {
1529
1731
  let command = resolveRepoCommand(check, kind, deps.defaults);
1530
1732
  if (kind === "buildPasses" && !check.command && !deps.defaults?.buildCommand) {
@@ -1552,7 +1754,7 @@ async function runCommandCheck(
1552
1754
  if (!isCommandAllowed(command, allowlist)) {
1553
1755
  return { ok: false, unverifiable: true, reason: `command not allowlisted: ${command}` };
1554
1756
  }
1555
- return runTestsPass(command, deps, timeoutMs);
1757
+ return runTestsPass(command, deps, timeoutMs, scope, crossLink);
1556
1758
  }
1557
1759
 
1558
1760
  const fn = async (): Promise<CheckResult> => {
@@ -1562,7 +1764,8 @@ async function runCommandCheck(
1562
1764
  }
1563
1765
  let launch: Launch = (scope, deadline) => scope.runShell(command, deps.cwd, deadline);
1564
1766
  let scopedTo: number | undefined;
1565
- if (kind === "lintClean" && deps.openScope) {
1767
+ // Cross-repo P2.4: scope=full runs the lint unscoped.
1768
+ if (kind === "lintClean" && deps.openScope && scope !== "full") {
1566
1769
  // T8: NoAffected passes with its note and takes no slot; Unscoped runs the command as today.
1567
1770
  const plan = await planLint(command, deps);
1568
1771
  if (isNoAffected(plan)) {
@@ -1666,24 +1869,59 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
1666
1869
  const results: CheckResult[] = [];
1667
1870
 
1668
1871
  // Sequential for deterministic mutex semantics and stable evidence order.
1669
- for (const check of checks) {
1872
+ for (const [index, check] of checks.entries()) {
1670
1873
  let result: CheckResult;
1874
+ // Cross-repo P2.4: a placed check runs with its own cwd (also the mutex key and the base of relative paths); a foreign one
1875
+ // has no dispatch reference. Without a placement `cd` is `deps` itself.
1876
+ const placement = deps.placements?.[index];
1877
+ const cd: DeterministicDeps = placement
1878
+ ? { ...deps, cwd: placement.cwd, ...(placement.foreign ? { reference: { kind: "none", reason: FOREIGN_REFERENCE_NONE } satisfies ReferenceState } : {}) }
1879
+ : deps;
1880
+
1881
+ // Cross-repo P3a (SD-P3a-1, D22): a consumer testsPass with an explicit scope=affected runs `related` through the link into
1882
+ // W (deps.changeRoot, set by the gate only with foreign placements); without changeRoot it keeps the refusal below.
1883
+ const crossLink =
1884
+ placement?.foreign === true && check.kind === "testsPass" && placement.scope === "affected" && deps.changeRoot !== undefined
1885
+ ? crossLinkTarget(deps, deps.changeRoot, placement.cwd)
1886
+ : undefined;
1887
+
1888
+ // A test or lint check in a consumer repository must use scope=full (except the cross-link testsPass above): the change under
1889
+ // verification is in the work root, so an affected-only run cannot be attributed to it. Unverifiable without running; never a
1890
+ // recorded failure.
1891
+ if (placement?.foreign === true && (check.kind === "testsPass" || check.kind === "lintClean") && placement.scope !== "full" && crossLink === undefined) {
1892
+ results.push({
1893
+ ok: false,
1894
+ unverifiable: true,
1895
+ reason: `check ${index + 1} (${check.kind}) runs in another repository (${placement.cwd}) and must use scope=full: affected tests cannot be attributed to a change in the work root`,
1896
+ });
1897
+ continue;
1898
+ }
1671
1899
 
1672
1900
  switch (check.kind) {
1673
- case "fileExists":
1674
- result = await runFileExists(check, deps);
1901
+ case "fileExists": {
1902
+ const service = cd.service?.start("service", "file-exists");
1903
+ try {
1904
+ result = await runFileExists(check, cd);
1905
+ service?.end(result.ok ? "pass" : result.unverifiable ? "unverifiable" : "fail");
1906
+ } finally { service?.end("error"); }
1675
1907
  break;
1908
+ }
1676
1909
  case "run":
1677
- result = await runRun(check, deps, allowlist, timeoutMs);
1910
+ result = await runRun(check, cd, allowlist, timeoutMs);
1678
1911
  break;
1679
1912
  case "testsPass":
1680
1913
  case "buildPasses":
1681
1914
  case "lintClean":
1682
- result = await runCommandCheck(check, check.kind, deps, allowlist, timeoutMs);
1915
+ result = await runCommandCheck(check, check.kind, cd, allowlist, timeoutMs, placement?.scope, crossLink);
1683
1916
  break;
1684
- case "schemaMatch":
1685
- result = await runSchemaMatch(check, deps);
1917
+ case "schemaMatch": {
1918
+ const service = cd.service?.start("service", "schema-match");
1919
+ try {
1920
+ result = await runSchemaMatch(check, cd);
1921
+ service?.end(result.ok ? "pass" : result.unverifiable ? "unverifiable" : "fail");
1922
+ } finally { service?.end("error"); }
1686
1923
  break;
1924
+ }
1687
1925
  default: {
1688
1926
  // Defensive: TypeScript proves this is unreachable; guards runtime extensions.
1689
1927
  const exhaustive: never = check.kind;
@@ -1692,6 +1930,19 @@ export async function runDeterministic(dod: DoD, deps: DeterministicDeps): Promi
1692
1930
  }
1693
1931
  }
1694
1932
 
1933
+ // F6: the change under verification is in the work root, so a failure in a foreign repository is the consumer's:
1934
+ // unverifiable, never recorded as a failure (gate.ts turns a recorded failure into "fail").
1935
+ if (placement?.foreign === true && !result.ok && !result.unverifiable) {
1936
+ // The failing ids are dropped with the verdict: nothing in the work root's reference says whom they belong to.
1937
+ result = {
1938
+ ok: false,
1939
+ unverifiable: true,
1940
+ ...(result.note !== undefined ? { note: result.note } : {}),
1941
+ ...(result.evidence !== undefined ? { evidence: result.evidence } : {}),
1942
+ reason: `a check in another repository (${placement.cwd}) failed; the change under verification is in the work root, so this failure can be neither excused nor attributed: ${result.reason ?? "check failed"}`,
1943
+ };
1944
+ }
1945
+
1695
1946
  results.push(result);
1696
1947
  if (!result.ok && !result.unverifiable) {
1697
1948
  deps.onFailure?.(scrubText(result.reason ?? "check failed"));