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
@@ -20,7 +20,8 @@ import { resolveActiveTiers, resolveRolesRouting, type RouterConfig, type TierCo
20
20
  import { GIT_TOOL_NAMES, gitEnvironment, gitExecutable, hardeningArgs, inheritedSafeDirectoryArgs, spawnBounded } from "./git-tools";
21
21
  import { positiveBudget, REFUSAL_CAP, ROUTE_BUDGET_RAISE_MAX, TIER_GUARD_BUDGET } from "./guard-profile";
22
22
  import { PLUGIN_AGENT, pluginAgentMarker, pluginAgentPolicy, type PluginAgentMarker } from "./plugin-agents";
23
- import { CONTEXT7_DOC_TOOLS, type PermissionMap } from "./read-only";
23
+ import { CONTEXT7_DOC_TOOLS, permissionMatches, type PermissionMap } from "./read-only";
24
+ import { isApprovalValid, type RepoApproval } from "../routing/roles/approvals";
24
25
  import { ACTION_CLASS, HOST_NATIVE_ROLE_NAMES, resolveRoleTable, SHIPPED_ROLE_SPECS, type AuthorityAction, type RoleSpec, type RoleTable } from "./roles";
25
26
  import { workRootProblem } from "./roles-config";
26
27
 
@@ -205,6 +206,28 @@ export function worktreeRootPattern(root: string, realpath: Realpath = nativeRea
205
206
  return workRootProblem(canonical) === undefined ? join(canonical, "*") : undefined;
206
207
  }
207
208
 
209
+ /**
210
+ * The `external_directory` allow pattern of one approved repository (cross-repo Phase 4, SD-P4-15):
211
+ * `<path><sep>*` built like {@link worktreeRootPattern}, but only when the stored path still is its
212
+ * own canonical long form (`realpathSync.native(path)` equals `path` as text, case-insensitive on
213
+ * win32: a moved, replaced or junctioned folder gets no pattern) and both forms pass the P1.1 rules
214
+ * ({@link workRootProblem}). Undefined, with the reason, otherwise: fail closed. No git.
215
+ */
216
+ export function approvedRootPattern(path: string, realpath: Realpath = nativeRealpath): { pattern?: string; problem?: string } {
217
+ const problem = workRootProblem(path);
218
+ if (problem !== undefined) return { problem };
219
+ let canonical: string;
220
+ try {
221
+ canonical = realpath(path);
222
+ } catch {
223
+ return { problem: "does not resolve to a directory" };
224
+ }
225
+ const same = process.platform === "win32" ? canonical.toLowerCase() === path.toLowerCase() : canonical === path;
226
+ if (!same) return { problem: `resolves to ${canonical}, not the approved path` };
227
+ const after = workRootProblem(canonical);
228
+ return after === undefined ? { pattern: join(canonical, "*") } : { problem: `canonical form ${canonical} ${after}` };
229
+ }
230
+
208
231
  /**
209
232
  * The `external_directory` allow pattern of one `routing.workRoots` entry (P-11): the static
210
233
  * directory before the first wildcard in its canonical long form, then the glob tail verbatim
@@ -243,6 +266,8 @@ export function externalDirectoryPatterns(
243
266
  worktrees: readonly string[],
244
267
  workRoots: readonly string[],
245
268
  realpath: Realpath = nativeRealpath,
269
+ parents: readonly string[] = [],
270
+ approved: readonly string[] = [],
246
271
  ): { patterns: string[]; problems: string[] } {
247
272
  const patterns: string[] = [];
248
273
  const problems: string[] = [];
@@ -259,9 +284,83 @@ export function externalDirectoryPatterns(
259
284
  if (result.pattern === undefined) problems.push(`routing.workRoots entry ${entry} ${result.problem ?? "is not usable"}; not granted`);
260
285
  else add(result.pattern);
261
286
  }
287
+ // P1.6: one `<parent><sep>*` per `routing.repoParents` entry; the host's `*` crosses separators, so it covers every depth.
288
+ const parentDirs: string[] = [...parents];
289
+ for (const parent of parents) {
290
+ const result = workRootPattern(`${parent.replace(/[\\/]+$/, "")}/*`, realpath);
291
+ if (result.pattern === undefined) problems.push(`routing.repoParents entry ${parent} ${result.problem ?? "is not usable"}; not granted`);
292
+ else {
293
+ add(result.pattern);
294
+ parentDirs.push(result.pattern.replace(/[\\/]?\*$/, ""));
295
+ }
296
+ }
297
+ // Cross-repo Phase 4 (SD-P4-15): one `<path><sep>*` per approved repository, only with parents (I9); the caller passes
298
+ // approvals already checked for expiry and exclusion ({@link approvedRootsInForce}). Phase 4 QA (m3): never one that is or
299
+ // contains a parent (text or canonical form): its rule would be wider than the parents, and admission refuses it anyway.
300
+ if (parents.length > 0) {
301
+ for (const path of approved) {
302
+ const result = approvedRootPattern(path, realpath);
303
+ if (result.pattern === undefined) {
304
+ problems.push(`approved repository ${path} ${result.problem ?? "is not usable"}; not granted`);
305
+ continue;
306
+ }
307
+ const approvedDir = result.pattern.replace(/[\\/]?\*$/, "");
308
+ const held = parentDirs.find((dir) => dir.trim() !== "" && (isOrContains(path, dir) || isOrContains(approvedDir, dir)));
309
+ if (held !== undefined) problems.push(`approved repository ${path} is or contains routing.repoParents entry ${held}; not granted`);
310
+ else add(result.pattern);
311
+ }
312
+ }
262
313
  return { patterns, problems };
263
314
  }
264
315
 
316
+ /** Comparison form of a directory for the parent checks: `/` separators, no trailing one, case-folded on win32. Text only. */
317
+ function dirKey(p: string): string {
318
+ const unified = p.replace(/\\/g, "/").replace(/\/+$/, "");
319
+ return process.platform === "win32" ? unified.toLowerCase() : unified;
320
+ }
321
+
322
+ /** Whether directory `outer` is directory `inner` or contains it ({@link dirKey} forms; a filesystem root contains all). */
323
+ function isOrContains(outer: string, inner: string): boolean {
324
+ const o = dirKey(outer);
325
+ const i = dirKey(inner);
326
+ return o === "" || o === i || i.startsWith(`${o}/`);
327
+ }
328
+
329
+ /** One store entry as registration sees it (cross-repo Phase 4): read without git. */
330
+ export type ApprovedRoot = Pick<RepoApproval, "path" | "approvedAt" | "lastUsedAt">;
331
+
332
+ /**
333
+ * The approved repository paths registration may grant (SD-P4-15): none without `routing.repoParents` (I9); otherwise each
334
+ * approval that has not expired ({@link isApprovalValid} with `routing.repoApprovalDays`) and whose path text no
335
+ * `routing.repoExclude` glob matches (exclusion wins over an approval) and that is not, and does not contain, a
336
+ * `routing.repoParents` entry (Phase 4 QA m3: text, case-insensitive on win32; such an approval would be granted wider than
337
+ * the parents). Excluded and parent-holding ones are reported in `problems`; expired ones are dropped silently. No filesystem
338
+ * access, no git.
339
+ */
340
+ export function approvedRootsInForce(
341
+ approved: readonly ApprovedRoot[],
342
+ routing: { readonly repoParents: readonly string[]; readonly repoExclude: readonly string[]; readonly repoApprovalDays: number },
343
+ now: number,
344
+ ): { paths: string[]; problems: string[] } {
345
+ const paths: string[] = [];
346
+ const problems: string[] = [];
347
+ if (routing.repoParents.length === 0) return { paths, problems };
348
+ for (const entry of approved) {
349
+ if (typeof entry.path !== "string" || entry.path === "") continue;
350
+ if (!isApprovalValid(entry, routing.repoApprovalDays, now)) continue;
351
+ const held = routing.repoParents.find((parent) => parent.trim() !== "" && isOrContains(entry.path, parent));
352
+ if (held !== undefined) {
353
+ problems.push(`approved repository ${entry.path} is or contains routing.repoParents entry ${held}; not granted`);
354
+ continue;
355
+ }
356
+ const forms = process.platform === "win32" && entry.path.includes("/") ? [entry.path, entry.path.replace(/\//g, "\\")] : [entry.path];
357
+ const excluded = routing.repoExclude.find((glob) => glob.trim() !== "" && forms.some((form) => permissionMatches(form, glob)));
358
+ if (excluded !== undefined) problems.push(`approved repository ${entry.path} is excluded by routing.repoExclude (${excluded}); not granted`);
359
+ else if (!paths.includes(entry.path)) paths.push(entry.path);
360
+ }
361
+ return { paths, problems };
362
+ }
363
+
265
364
  // ---------------------------------------------------------------------------
266
365
  // Registration
267
366
  // ---------------------------------------------------------------------------
@@ -292,10 +391,17 @@ export interface RoleRegistrationOptions {
292
391
  seed: Readonly<Record<string, Record<string, unknown>>>;
293
392
  /** Logs `message` once per `key`. */
294
393
  warn: (key: string, message: string) => void;
394
+ /**
395
+ * Cross-repo Phase 4 (SD-P4-15): the entries of the repository approvals store, read without git. Each one in force
396
+ * ({@link approvedRootsInForce}) whose path is still its own canonical form gets a `<path><sep>*` rule. Absent: none.
397
+ */
398
+ approvedRoots?: readonly ApprovedRoot[];
295
399
  /** Injection points (tests). */
296
400
  listWorktrees?: (directory: string) => Promise<string[]>;
297
401
  resolveTable?: (cfg: RouterConfig, host: "v1" | "v2", opts: { context7?: boolean }) => RoleTable;
298
402
  realpath?: Realpath;
403
+ /** Clock in epoch ms for the approval expiry; default `Date.now`. */
404
+ now?: () => number;
299
405
  }
300
406
 
301
407
  const PREFIX = "roles mode (OpenCode v2 only): ";
@@ -344,8 +450,9 @@ export async function registerRoleAgents(
344
450
  opts.warn("roles:worktrees", `${PREFIX}the repository's worktrees could not be listed (${errorText(error)}); role agents get no worktree external_directory rule`);
345
451
  }
346
452
  }
347
- const found = externalDirectoryPatterns(worktrees, routing.workRoots, opts.realpath ?? nativeRealpath);
348
- for (const problem of found.problems) opts.warn(`roles:external:${problem}`, `${PREFIX}${problem}`);
453
+ const approved = approvedRootsInForce(opts.approvedRoots ?? [], routing, (opts.now ?? Date.now)());
454
+ const found = externalDirectoryPatterns(worktrees, routing.workRoots, opts.realpath ?? nativeRealpath, routing.repoParents, approved.paths);
455
+ for (const problem of [...approved.problems, ...found.problems]) opts.warn(`roles:external:${problem}`, `${PREFIX}${problem}`);
349
456
  externalDirectory = found.patterns;
350
457
  built = new Map();
351
458
  for (const [name, spec] of table.roles) {
@@ -40,6 +40,8 @@ export const DEFAULT_RUN_COMMANDS: RunConfig["commands"] = Object.freeze({
40
40
  }),
41
41
  });
42
42
  export const DEFAULT_RUN_TIMEOUT_MS = 600_000;
43
+ /** `routing.repoDepth` default: repositories one or two levels below a parent (`D:/git/x`, `D:/git/org/x`). */
44
+ export const DEFAULT_REPO_DEPTH = 2;
43
45
  export const RUN_TIMEOUT_BOUNDS = { min: 1_000, max: 3_600_000 } as const;
44
46
  export const ROLES_V1_NOTICE = "roles delegation requires OpenCode v2; using tiers";
45
47
 
@@ -243,6 +245,83 @@ export function sanitizeWorkRoots(value: unknown): Sanitized<string[]> {
243
245
  return { value: out, issues };
244
246
  }
245
247
 
248
+ /**
249
+ * A `routing.repoParents` entry (cross-repo, Phase 1): a literal, local, absolute directory in canonical long form. No glob
250
+ * (a parent is one directory), no network or device path, then {@link workRootProblem}'s rules (static prefix, no `.`/`..`,
251
+ * no 8.3 segment).
252
+ */
253
+ export function repoParentProblem(entry: string): string | undefined {
254
+ // Network and device paths first: `\\?\C:\x` carries a `?` but is refused for what it is.
255
+ if (/^[\\/]{2}/.test(entry)) return "is a network or device path; use a local directory";
256
+ if (/[*?[\]{}]/.test(entry)) return "contains a glob character; a parent is a literal directory";
257
+ return workRootProblem(entry);
258
+ }
259
+
260
+ function sanitizePathList(
261
+ key: "repoParents" | "repoExclude",
262
+ value: unknown,
263
+ problemOf: (entry: string) => string | undefined,
264
+ what: string,
265
+ ): Sanitized<string[]> {
266
+ const issues: RolesIssue[] = [];
267
+ if (value === undefined) return { value: undefined, issues };
268
+ if (!Array.isArray(value)) {
269
+ issues.push({ path: `routing.${key}`, message: `routing.${key} must be an array of ${what} (got ${show(value)}); ignored` });
270
+ return { value: undefined, issues };
271
+ }
272
+ const out: string[] = [];
273
+ value.forEach((entry: unknown, i) => {
274
+ const path = `routing.${key}[${i}]`;
275
+ if (typeof entry !== "string") {
276
+ issues.push({ path, message: `${path} must be a string (got ${show(entry)}); entry dropped` });
277
+ return;
278
+ }
279
+ const problem = problemOf(entry);
280
+ if (problem !== undefined) {
281
+ issues.push({ path, message: `${path} ${show(entry)} ${problem}; entry dropped` });
282
+ return;
283
+ }
284
+ if (!out.includes(entry)) out.push(entry);
285
+ });
286
+ return { value: out, issues };
287
+ }
288
+
289
+ export function sanitizeRepoParents(value: unknown): Sanitized<string[]> {
290
+ return sanitizePathList("repoParents", value, repoParentProblem, "absolute directories");
291
+ }
292
+
293
+ export function sanitizeRepoExclude(value: unknown): Sanitized<string[]> {
294
+ return sanitizePathList("repoExclude", value, workRootProblem, "absolute globs");
295
+ }
296
+
297
+ export function sanitizeRepoDepth(value: unknown): Sanitized<number> {
298
+ if (value === undefined) return { value: undefined, issues: [] };
299
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 4) return { value, issues: [] };
300
+ return {
301
+ value: undefined,
302
+ issues: [{ path: "routing.repoDepth", message: `routing.repoDepth must be an integer from 1 to 4 (got ${show(value)}); ignored` }],
303
+ };
304
+ }
305
+
306
+ /** Days an approval of a repository outside the parents lasts after its last use (global only). */
307
+ export const DEFAULT_REPO_APPROVAL_DAYS = 14;
308
+ /** Hard cap: an approval never lasts longer than this many days after it was given, used or not. */
309
+ export const REPO_APPROVAL_CAP_DAYS = 90;
310
+
311
+ export function sanitizeRepoApprovalDays(value: unknown): Sanitized<number> {
312
+ if (value === undefined) return { value: undefined, issues: [] };
313
+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= REPO_APPROVAL_CAP_DAYS) {
314
+ return { value, issues: [] };
315
+ }
316
+ return {
317
+ value: undefined,
318
+ issues: [{
319
+ path: "routing.repoApprovalDays",
320
+ message: `routing.repoApprovalDays must be an integer from 1 to ${REPO_APPROVAL_CAP_DAYS} (got ${show(value)}); ignored`,
321
+ }],
322
+ };
323
+ }
324
+
246
325
  export function sanitizeRoleAgents(value: unknown): Sanitized<Record<string, RoleAgentCustomisation>> {
247
326
  const issues: RolesIssue[] = [];
248
327
  if (value === undefined) return { value: undefined, issues };
@@ -424,6 +503,10 @@ export function collectRolesIssues(rawRouting: unknown, rawRoleAgents: unknown):
424
503
  ...sanitizeExploration(r.exploration).issues,
425
504
  ...sanitizeRun(r.run).issues,
426
505
  ...sanitizeWorkRoots(r.workRoots).issues,
506
+ ...sanitizeRepoParents(r.repoParents).issues,
507
+ ...sanitizeRepoDepth(r.repoDepth).issues,
508
+ ...sanitizeRepoExclude(r.repoExclude).issues,
509
+ ...sanitizeRepoApprovalDays(r.repoApprovalDays).issues,
427
510
  ...sanitizeRoleAgents(rawRoleAgents).issues,
428
511
  ];
429
512
  }
@@ -163,7 +163,7 @@ const CANONICAL_TIERS: readonly string[] = ["fast", "medium", "heavy"];
163
163
 
164
164
  /** Work-root rule (§2.2, R3/R4) carried by every shipped role prompt. */
165
165
  export const WORK_ROOT_RULE =
166
- "Work root: work only inside this dispatch's work root, named in ENVIRONMENT or by `root=`; without one it is the session directory. Paths anywhere else are denied. If you have `router_run`, pass `cwd` = the work root.";
166
+ "Work root: work only inside this dispatch's work root, named on the router's `Working directory:` line, else in ENVIRONMENT; without either it is the session directory. Paths anywhere else are denied. If you have `router_run`, pass `cwd` = the work root.";
167
167
  /** Return contract carried by every shipped role prompt. */
168
168
  export const RETURN_CONTRACT =
169
169
  "Return: start with `DONE:`, `NEED MORE:` or `ESCALATE:`, then the result with evidence as `file:line`.";
@@ -643,6 +643,12 @@ export interface VerificationBaseline {
643
643
  readonly reference: ReferenceState;
644
644
  /** Every file the child changed in that attempt and every later one under the block; "unavailable" once any set was unknown. */
645
645
  readonly changed: readonly ChangedFile[] | "unavailable";
646
+ /** The tree the introducing attempt was gated on (`branch` absent: unknown; null: detached). Absent: no snapshot at that gate. */
647
+ readonly tree?: { readonly head: string; readonly branch?: string | null; readonly root?: string };
648
+ /** A branch-switch reason already found in an earlier attempt of this lineage; carried attempts inherit it. */
649
+ readonly switched?: string;
650
+ /** I5 (P0.3): tools the lineage ran whose writes the router cannot observe (sorted); carried attempts are judged with them. */
651
+ readonly writers?: readonly string[];
646
652
  }
647
653
 
648
654
  export interface DispatchInput {
@@ -810,6 +816,11 @@ function frozenVerification(v: CarriedVerification): CarriedVerification {
810
816
  baseline: Object.freeze({
811
817
  reference: v.baseline.reference,
812
818
  changed: v.baseline.changed === "unavailable" ? "unavailable" as const : Object.freeze(v.baseline.changed.map((f) => Object.freeze({ ...f }))),
819
+ ...(v.baseline.tree === undefined ? {} : { tree: Object.freeze({ head: v.baseline.tree.head,
820
+ ...(v.baseline.tree.branch === undefined ? {} : { branch: v.baseline.tree.branch }),
821
+ ...(v.baseline.tree.root === undefined ? {} : { root: v.baseline.tree.root }) }) }),
822
+ ...(v.baseline.switched === undefined ? {} : { switched: v.baseline.switched }),
823
+ ...(v.baseline.writers === undefined ? {} : { writers: Object.freeze([...v.baseline.writers]) }),
813
824
  }),
814
825
  }),
815
826
  });
@@ -19,6 +19,7 @@ import {
19
19
  SCOPES,
20
20
  TASK_CLASSES,
21
21
  type Detection,
22
+ type InvalidCrossRepo,
22
23
  type Need,
23
24
  type Risk,
24
25
  type RouteLine,
@@ -61,6 +62,28 @@ function isWorkRootPath(value: string): boolean {
61
62
  return WORK_ROOT_RE.test(value) && !PARENT_SEGMENT_RE.test(value) && !value.includes("\0");
62
63
  }
63
64
 
65
+ const REPO_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
66
+ /** Never in a git branch name (`git check-ref-format`): ASCII control, DEL, space, `~ ^ : ? * [ \`. */
67
+ const BRANCH_FORBIDDEN_RE = /[\u0000-\u001f\u007f ~^:?*[\\]/;
68
+ const BRANCH_MAX_CHARS = 200;
69
+
70
+ /** `repo=` value: a single directory name (no separators), not `.` / `..`. Case is kept. */
71
+ function isRepoName(value: string): boolean {
72
+ return REPO_NAME_RE.test(value) && value !== "." && value !== "..";
73
+ }
74
+
75
+ /**
76
+ * `branch=` value: a name `git check-ref-format --branch` accepts (QA round 1, F3). Case is kept; declare-then-check happens
77
+ * later. The value is only compared with `git worktree list --porcelain` output, never passed to git as an argument.
78
+ */
79
+ function isBranchRef(value: string): boolean {
80
+ if (value.length < 1 || value.length > BRANCH_MAX_CHARS) return false;
81
+ if (BRANCH_FORBIDDEN_RE.test(value)) return false;
82
+ if (value === "@" || value.includes("@{") || value.includes("..") || value.includes("//")) return false;
83
+ if (value.startsWith("-") || value.startsWith("/") || value.endsWith("/") || value.endsWith(".")) return false;
84
+ return value.split("/").every((component) => !component.startsWith(".") && !component.endsWith(".lock"));
85
+ }
86
+
64
87
  function isMember<T extends string>(values: readonly T[], value: string): value is T {
65
88
  return (values as readonly string[]).includes(value);
66
89
  }
@@ -87,6 +110,13 @@ function parseNeeds(value: string): readonly Need[] | undefined {
87
110
  return NEEDS.filter((need) => found.has(need));
88
111
  }
89
112
 
113
+ /** The `root=` value as written: a quoted path from `quotedRoots`, else the token's value; undefined for a bare `root`. */
114
+ function rootCandidate(rawValue: string | null, quotedRoots: readonly string[]): string | undefined {
115
+ if (rawValue === null) return undefined;
116
+ const q = QUOTED_PLACEHOLDER_RE.exec(stripTail(rawValue.toLowerCase()));
117
+ return q ? quotedRoots[Number(q[1])] : stripTail(rawValue);
118
+ }
119
+
90
120
  /** L2: the fields of one route line body. */
91
121
  function parseFields(body: string): RouteLine {
92
122
  let taskClass: TaskClass | undefined;
@@ -98,7 +128,10 @@ function parseFields(body: string): RouteLine {
98
128
  let tier: string | undefined;
99
129
  let budget: number | undefined;
100
130
  let root: string | undefined;
131
+ let repo: string | undefined;
132
+ let branch: string | undefined;
101
133
  const ignored: string[] = [];
134
+ const invalidCrossRepo: InvalidCrossRepo[] = [];
102
135
  const seen = new Set<string>();
103
136
 
104
137
  const quotedRoots: string[] = [];
@@ -119,6 +152,8 @@ function parseFields(body: string): RouteLine {
119
152
  }
120
153
  if (seen.has(key)) {
121
154
  ignored.push(`dup:${key}`);
155
+ if (key === "repo" || key === "branch") invalidCrossRepo.push({ key, value: rawValue === null ? "" : stripTail(rawValue) });
156
+ else if (key === "root") invalidCrossRepo.push({ key, value: rootCandidate(rawValue, quotedRoots) ?? "" });
122
157
  continue;
123
158
  }
124
159
  seen.add(key);
@@ -162,10 +197,31 @@ function parseFields(body: string): RouteLine {
162
197
  break;
163
198
  }
164
199
  case "root": {
165
- const q = value === null ? null : QUOTED_PLACEHOLDER_RE.exec(value);
166
- const candidate = q ? quotedRoots[Number(q[1])] : rawValue === null ? undefined : stripTail(rawValue);
200
+ const candidate = rootCandidate(rawValue, quotedRoots);
167
201
  if (candidate !== undefined && isWorkRootPath(candidate)) root = candidate;
168
- else ignored.push(key);
202
+ else {
203
+ // A declared work root that cannot be accepted is an invalid declaration, never "nothing declared".
204
+ ignored.push(key);
205
+ invalidCrossRepo.push({ key, value: candidate ?? "" });
206
+ }
207
+ break;
208
+ }
209
+ case "repo": {
210
+ const candidate = rawValue === null ? undefined : stripTail(rawValue);
211
+ if (candidate !== undefined && isRepoName(candidate)) repo = candidate;
212
+ else {
213
+ ignored.push(key);
214
+ invalidCrossRepo.push({ key, value: candidate ?? "" });
215
+ }
216
+ break;
217
+ }
218
+ case "branch": {
219
+ const candidate = rawValue === null ? undefined : stripTail(rawValue);
220
+ if (candidate !== undefined && isBranchRef(candidate)) branch = candidate;
221
+ else {
222
+ ignored.push(key);
223
+ invalidCrossRepo.push({ key, value: candidate ?? "" });
224
+ }
169
225
  break;
170
226
  }
171
227
  default:
@@ -182,6 +238,9 @@ function parseFields(body: string): RouteLine {
182
238
  ...(tier ? { tier } : {}),
183
239
  ...(budget !== undefined ? { budget } : {}),
184
240
  ...(root ? { root } : {}),
241
+ ...(repo ? { repo } : {}),
242
+ ...(branch ? { branch } : {}),
243
+ ...(invalidCrossRepo.length > 0 ? { invalidCrossRepo } : {}),
185
244
  pin,
186
245
  ignored,
187
246
  };
@@ -207,7 +266,25 @@ function isRecognisable(line: string, inFence: boolean): boolean {
207
266
  }
208
267
 
209
268
  function canonical(line: RouteLine): string {
210
- return JSON.stringify([line.class, line.risk, line.scope, line.needs, line.detection, line.pin, line.tier, line.budget, line.root]);
269
+ // Invalid `root=` entries are not compared: a tier dispatch's conflict detection stays what it was before they were
270
+ // recorded (an invalid root was only an `ignored` key). They are merged into the effective line instead (mergeInvalidRoots).
271
+ const invalid = line.invalidCrossRepo?.filter((entry) => entry.key !== "root");
272
+ return JSON.stringify([line.class, line.risk, line.scope, line.needs, line.detection, line.pin, line.tier, line.budget, line.root, line.repo, line.branch, invalid !== undefined && invalid.length > 0 ? invalid : undefined]);
273
+ }
274
+
275
+ /**
276
+ * Several route lines that agree on every compared field: the first line, with the invalid `root=` declarations of
277
+ * every line (a declared-but-invalid work root on any line is never silently dropped).
278
+ */
279
+ function mergeInvalidRoots(lines: readonly RouteLine[]): RouteLine {
280
+ const first = lines[0]!;
281
+ const merged: InvalidCrossRepo[] = [...(first.invalidCrossRepo ?? [])];
282
+ for (const l of lines.slice(1)) {
283
+ for (const entry of l.invalidCrossRepo ?? []) {
284
+ if (!merged.some((seenEntry) => seenEntry.key === entry.key && seenEntry.value === entry.value)) merged.push(entry);
285
+ }
286
+ }
287
+ return merged.length === (first.invalidCrossRepo?.length ?? 0) ? first : { ...first, invalidCrossRepo: merged };
211
288
  }
212
289
 
213
290
  /**
@@ -242,7 +319,18 @@ function resolveConflict(lines: readonly RouteLine[]): RouteLine {
242
319
  const tier = keep("tier", first.tier, (l) => l.tier);
243
320
  const budget = keep("budget", first.budget, (l) => l.budget);
244
321
  const root = keep("root", first.root, (l) => l.root);
322
+ const repo = keep("repo", first.repo, (l) => l.repo);
323
+ const branch = keep("branch", first.branch, (l) => l.branch);
245
324
  if (lines.some((l) => l.detection !== undefined)) ignored.push("conflict:d");
325
+ // QA round 1 (F3): a declaration that no line can carry is declared-but-invalid, never a silent fallback to the session directory.
326
+ const invalidCrossRepo: InvalidCrossRepo[] = [];
327
+ const mark = (entry: InvalidCrossRepo): void => {
328
+ if (!invalidCrossRepo.some((seenEntry) => seenEntry.key === entry.key && seenEntry.value === entry.value)) invalidCrossRepo.push(entry);
329
+ };
330
+ for (const l of lines) for (const entry of l.invalidCrossRepo ?? []) mark(entry);
331
+ if (first.repo !== undefined && repo === undefined) mark({ key: "repo", value: first.repo });
332
+ if (first.branch !== undefined && branch === undefined) mark({ key: "branch", value: first.branch });
333
+ if (first.root !== undefined && root === undefined) mark({ key: "root", value: first.root });
246
334
  return {
247
335
  ...(taskClass ? { class: taskClass } : {}),
248
336
  ...(risk ? { risk } : {}),
@@ -251,6 +339,9 @@ function resolveConflict(lines: readonly RouteLine[]): RouteLine {
251
339
  ...(tier ? { tier } : {}),
252
340
  ...(budget !== undefined ? { budget } : {}),
253
341
  ...(root ? { root } : {}),
342
+ ...(repo ? { repo } : {}),
343
+ ...(branch ? { branch } : {}),
344
+ ...(invalidCrossRepo.length > 0 ? { invalidCrossRepo } : {}),
254
345
  // The first line is the directive; a later line cannot take its pin away or add one (A22).
255
346
  pin: first.pin,
256
347
  ignored,
@@ -326,7 +417,7 @@ export function parseRouteLine(text: string, options: RouteLineOptions = {}): Ro
326
417
  const conflict = new Set(parsed.map(canonical)).size > 1;
327
418
  return {
328
419
  // QA-P12-2-2: the flag lives on the parse result only; the line's `ignored` list is the tier-mode one.
329
- line: conflict ? resolveConflict(parsed) : parsed[0]!,
420
+ line: conflict ? resolveConflict(parsed) : mergeInvalidRoots(parsed),
330
421
  count: parsed.length,
331
422
  stripped: kept.join(""),
332
423
  conflict,
@@ -273,6 +273,13 @@ export type FetchLike = (
273
273
  /** Environment lookup (process.env in production, a plain object in tests). */
274
274
  export type EnvLike = Readonly<Record<string, string | undefined>>;
275
275
 
276
+ /** A `repo=` / `branch=` / `root=` declaration of a route line that was not accepted (see {@link RouteLine.invalidCrossRepo}). */
277
+ export interface InvalidCrossRepo {
278
+ readonly key: "repo" | "branch" | "root";
279
+ /** The value as written (empty for a bare key). */
280
+ readonly value: string;
281
+ }
282
+
276
283
  /** Parsed `[route …]` line (D13). Absent fields were missing or invalid. */
277
284
  export interface RouteLine {
278
285
  readonly class?: TaskClass;
@@ -297,6 +304,25 @@ export interface RouteLine {
297
304
  * `git worktree list --porcelain` BEFORE any filesystem call on it; no match → no work root.
298
305
  */
299
306
  readonly root?: string;
307
+ /**
308
+ * `repo=<name>`: cross-repo (Phase 1): a repository name below `routing.repoParents`, as written (case kept).
309
+ * One directory name, `[A-Za-z0-9][A-Za-z0-9._-]{0,99}`, not `.` / `..`; separators are rejected at parse.
310
+ * Parse and validation only: resolution against `routing.repoParents` happens later.
311
+ */
312
+ readonly repo?: string;
313
+ /**
314
+ * `branch=<ref>`: the branch whose worktree to bind; declare-then-check (the declared branch is verified against
315
+ * the worktree later). Case kept. 1..200 chars, git `check-ref-format` rules for a branch name: no ASCII control,
316
+ * space, `~ ^ : ? * [ \`; rejected at parse: `..`, `@{`, `@` alone, `//`, a leading `-` or `/`, a trailing `/` or
317
+ * `.`, a component starting with `.` or ending in `.lock`. The value is only ever compared with porcelain output.
318
+ */
319
+ readonly branch?: string;
320
+ /**
321
+ * `repo=` / `branch=` / `root=` the line declared but the parser could not accept (invalid value, bare key, duplicate or
322
+ * conflicting key), with the value as written (a quoted `root=` without its quotes). The route flow gives such a dispatch NO work root and a note: an
323
+ * invalid declaration never falls back to the session directory. Absent when every declaration was valid.
324
+ */
325
+ readonly invalidCrossRepo?: readonly InvalidCrossRepo[];
300
326
  /** Bare `pin` flag (or `pin=true|yes|1`). */
301
327
  readonly pin: boolean;
302
328
  /** Keys that were unknown or whose values were invalid (for logging only). */
@@ -14,6 +14,7 @@
14
14
  // child's own `NEED MORE: budget` / `ESCALATE: authority` claim is not an exemption, only the guard's state is.
15
15
  // ---------------------------------------------------------------------------
16
16
 
17
+ import type { DoD } from "../../verify/dod";
17
18
  import type {
18
19
  DecisionFacts,
19
20
  DecisionRow,
@@ -333,6 +334,22 @@ export function runSignal(input: RunSignalInput): SignalObservation | null {
333
334
  return observe("run", "pass", SIGNAL_WEIGHTS.run);
334
335
  }
335
336
 
337
+ /** Exact npm forms of a deterministic check's command → the `routing.run` script it names (`npm test`, `npm run <name>`). */
338
+ const NPM_SCRIPT_RE = /^npm(?:\.cmd)?\s+(?:(test|t)|run(?:-script)?\s+([A-Za-z0-9_][A-Za-z0-9_.:@+-]*))$/;
339
+
340
+ /**
341
+ * The acceptance commands of a dispatch's DoD as `routing.run` names (handoff 13): only exact npm script forms count.
342
+ * P2c.2: a check with its own `cwd` does not run in the work root, so the dispatch gets no run signal at all (`[]`).
343
+ */
344
+ export function acceptanceScriptsOf(dod: DoD): string[] {
345
+ if (dod.kind !== "deterministic") return [];
346
+ if (dod.checks.some((check) => check.cwd !== undefined)) return [];
347
+ return dod.checks.flatMap((check) => {
348
+ const match = typeof check.command === "string" ? NPM_SCRIPT_RE.exec(check.command.trim()) : null;
349
+ return match === null ? [] : [match[1] !== undefined ? "test" : (match[2] as string)];
350
+ });
351
+ }
352
+
336
353
  // ---------------------------------------------------------------------------
337
354
  // Re-dispatch of the same task to a higher tier
338
355
  // ---------------------------------------------------------------------------