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
@@ -8,8 +8,10 @@ import {
8
8
  writeFileSync,
9
9
  } from "node:fs";
10
10
  import { availableParallelism, homedir } from "node:os";
11
- import { dirname, isAbsolute, join, resolve as resolvePath } from "node:path";
11
+ import { dirname, isAbsolute, join, posix, resolve as resolvePath, win32 } from "node:path";
12
12
  import { fileURLToPath } from "node:url";
13
+ import { executorPlatformSupported } from "../executor/platform";
14
+ import { EXECUTOR_LIMITS, type ExecutorConfig, type RunCommandRef } from "../executor/types";
13
15
  import { formatRouterLine } from "./build-info";
14
16
  import { parseJsonc } from "./jsonc";
15
17
  import type { DelegateInstructionsPolicy } from "./instructions";
@@ -20,11 +22,17 @@ import { resolveRoleTable, type ExplorationConfig, type RunConfig } from "./role
20
22
  import {
21
23
  DEFAULT_RUN_COMMANDS,
22
24
  DEFAULT_RUN_SCRIPTS,
25
+ DEFAULT_REPO_APPROVAL_DAYS,
26
+ DEFAULT_REPO_DEPTH,
23
27
  DEFAULT_RUN_TIMEOUT_MS,
24
28
  ROLES_V1_NOTICE,
25
29
  collectRolesIssues,
26
30
  sanitizeDelegation,
27
31
  sanitizeExploration,
32
+ sanitizeRepoApprovalDays,
33
+ sanitizeRepoDepth,
34
+ sanitizeRepoExclude,
35
+ sanitizeRepoParents,
28
36
  sanitizeRoleAgents,
29
37
  sanitizeRun,
30
38
  sanitizeWorkRoots,
@@ -309,7 +317,45 @@ export interface AdvisorConfig {
309
317
  notify?: boolean;
310
318
  }
311
319
 
320
+ /** `routing.background.mode`: `auto` (router decides), `model` (the model decides), `off`. OpenCode v2 only. */
321
+ export type BackgroundMode = "auto" | "model" | "off";
322
+ /** `routing.leases.mode`: `enforce` or `off`. OpenCode v2 only. */
323
+ export type LeasesMode = "enforce" | "off";
324
+ /** `routing.leases.run`: how `router_run` treats a leased target. OpenCode v2 only. */
325
+ export type LeasesRunPolicy = "annotate" | "refuse";
326
+
327
+ export interface BackgroundConfig {
328
+ mode?: BackgroundMode;
329
+ /** Predicted duration (ms) from which `auto` runs a dispatch in the background. 0..3600000. */
330
+ minPredictedMs?: number;
331
+ }
332
+
333
+ export interface LeasesConfig {
334
+ mode?: LeasesMode;
335
+ run?: LeasesRunPolicy;
336
+ }
337
+
338
+ /** Stale role-child resumes (OpenCode v2 only). */
339
+ export interface OrphansConfig {
340
+ resume?: "refuse" | "allow";
341
+ }
342
+
343
+ /**
344
+ * `routing.executor` (OpenCode v2 only), as written: every field optional. The trusted keys
345
+ * (`slotsDir`, `integrationChecks`, `phaseSuite`, `provision`, `python`) are global only (D18).
346
+ */
347
+ export type ExecutorOverrides = Partial<Omit<ExecutorConfig, "circuitBreaker">> & {
348
+ circuitBreaker?: Partial<ExecutorConfig["circuitBreaker"]>;
349
+ };
350
+
351
+ export type RoleFloorMode = "strict" | "gated";
352
+
312
353
  export interface RoutingConfig {
354
+ background?: BackgroundConfig;
355
+ leases?: LeasesConfig;
356
+ orphans?: OrphansConfig;
357
+ /** OpenCode v2 only; v1 ignores the block (see configuredV2OnlyKeys). */
358
+ executor?: ExecutorOverrides;
313
359
  engine?: RoutingEngine;
314
360
  profile?: RoutingProfile;
315
361
  margin?: number;
@@ -323,12 +369,22 @@ export interface RoutingConfig {
323
369
  advisor?: AdvisorConfig;
324
370
  /** `tiers` (default) or `roles`; global and project layers. Inert on v1. */
325
371
  delegation?: DelegationMode;
372
+ /** Global only. Authority floor policy; default strict. Inert on v1. */
373
+ roleFloor?: RoleFloorMode;
326
374
  /** Global only. `rate` 0..0.2, default 0; `requireDetection` is fixed. Inert on v1. */
327
375
  exploration?: Partial<ExplorationConfig>;
328
376
  /** Global only. `router_run` allow-list. Inert on v1. */
329
377
  run?: Partial<RunConfig>;
330
378
  /** Global only. Absolute globs with a static long-form prefix; default none. */
331
379
  workRoots?: string[];
380
+ /** Global only. Literal absolute directories below which a git top level is an admissible work root (cross-repo, Phase 1). Inert on v1. */
381
+ repoParents?: string[];
382
+ /** Global only. Levels below a parent, 1–4; default 2. */
383
+ repoDepth?: number;
384
+ /** Global only. Absolute globs never admitted below a parent. */
385
+ repoExclude?: string[];
386
+ /** Global only. Days an approved repository outside the parents stays approved after its last use, 1–90; default 14. Inert on v1. */
387
+ repoApprovalDays?: number;
332
388
  }
333
389
 
334
390
  export interface RouterConfig {
@@ -505,6 +561,16 @@ function normalizeProjectDir(dir?: string): string {
505
561
  export interface ConfigNotice {
506
562
  source?: string;
507
563
  message: string;
564
+ /** About a key OpenCode v2 alone reads (QA-4.1-9): a v1 host does not log it, see {@link setConfigNoticeHost}. */
565
+ v2Only?: boolean;
566
+ }
567
+
568
+ /** The host whose plugin logs the config notices; `undefined` until index.ts sets it (logs them all). */
569
+ let configNoticeHost: RouterHost | undefined;
570
+
571
+ /** Set by index.ts at startup: on `v1` the `v2Only` notices are not logged (QA-4.1-9). */
572
+ export function setConfigNoticeHost(host: RouterHost | undefined): void {
573
+ configNoticeHost = host;
508
574
  }
509
575
 
510
576
  /**
@@ -513,7 +579,8 @@ export interface ConfigNotice {
513
579
  * the like. Empty when there are none. `/router` lists them.
514
580
  */
515
581
  export function getConfigNotices(dir?: string): readonly ConfigNotice[] {
516
- return _configCaches.get(normalizeProjectDir(dir))?.notices ?? [];
582
+ const notices = _configCaches.get(normalizeProjectDir(dir))?.notices ?? [];
583
+ return configNoticeHost === "v1" ? notices.filter((notice) => notice.v2Only !== true) : notices;
517
584
  }
518
585
 
519
586
  /**
@@ -1759,6 +1826,358 @@ function validateRoles(routing: Record<string, unknown>): Record<string, string[
1759
1826
  return out;
1760
1827
  }
1761
1828
 
1829
+ const BACKGROUND_MODES: readonly BackgroundMode[] = ["auto", "model", "off"];
1830
+ const LEASES_MODES: readonly LeasesMode[] = ["enforce", "off"];
1831
+ const LEASES_RUN_POLICIES: readonly LeasesRunPolicy[] = ["annotate", "refuse"];
1832
+ const BACKGROUND_MIN_PREDICTED_MAX_MS = 3_600_000;
1833
+
1834
+ interface TolerantBlock<T> {
1835
+ readonly value: T | undefined;
1836
+ readonly issues: string[];
1837
+ }
1838
+
1839
+ function showTolerant(value: unknown): string {
1840
+ const text = typeof value === "string" ? JSON.stringify(value) : (JSON.stringify(value) ?? String(value));
1841
+ return text.length <= 60 ? text : `${text.slice(0, 59)}…`;
1842
+ }
1843
+
1844
+ /** One tolerant enum key: an invalid value yields an issue and no value (the default applies). */
1845
+ function tolerantEnum<T extends string>(
1846
+ block: Record<string, unknown>,
1847
+ key: string,
1848
+ path: string,
1849
+ allowed: readonly T[],
1850
+ fallback: T,
1851
+ issues: string[],
1852
+ ): T | undefined {
1853
+ const raw = block[key];
1854
+ if (raw === undefined) return undefined;
1855
+ const hit = pickEnum(allowed, raw);
1856
+ if (hit !== undefined) return hit;
1857
+ issues.push(`${path}.${key} must be ${allowed.join("|")} (got ${showTolerant(raw)}); using ${fallback}`);
1858
+ return undefined;
1859
+ }
1860
+
1861
+ /**
1862
+ * `routing.background` (OpenCode v2 only). Tolerant like the roles keys: an invalid
1863
+ * entry never throws, it is reported in `issues` and the default applies.
1864
+ */
1865
+ function sanitizeBackground(value: unknown): TolerantBlock<BackgroundConfig> {
1866
+ const issues: string[] = [];
1867
+ if (value === undefined) return { value: undefined, issues };
1868
+ if (!isPlainObject(value)) {
1869
+ issues.push(`routing.background must be an object (got ${showTolerant(value)}); ignored`);
1870
+ return { value: undefined, issues };
1871
+ }
1872
+ const out: BackgroundConfig = {};
1873
+ const mode = tolerantEnum(value, "mode", "routing.background", BACKGROUND_MODES, ROUTING_DEFAULTS.background.mode, issues);
1874
+ if (mode !== undefined) out.mode = mode;
1875
+ const ms = value.minPredictedMs;
1876
+ if (ms !== undefined) {
1877
+ if (typeof ms === "number" && Number.isInteger(ms) && ms >= 0 && ms <= BACKGROUND_MIN_PREDICTED_MAX_MS) {
1878
+ out.minPredictedMs = ms;
1879
+ } else {
1880
+ issues.push(
1881
+ `routing.background.minPredictedMs must be an integer from 0 to ${BACKGROUND_MIN_PREDICTED_MAX_MS} (got ${showTolerant(ms)}); using ${ROUTING_DEFAULTS.background.minPredictedMs}`,
1882
+ );
1883
+ }
1884
+ }
1885
+ return { value: out, issues };
1886
+ }
1887
+
1888
+ /** `routing.roleFloor` (v2 roles only): an invalid value fails closed to strict, with an issue. */
1889
+ export function sanitizeRoleFloor(value: unknown): TolerantBlock<RoleFloorMode> {
1890
+ const issues: string[] = [];
1891
+ const mode = tolerantEnum({ roleFloor: value }, "roleFloor", "routing", ["strict", "gated"] as const, "strict", issues);
1892
+ return { value: mode ?? (value === undefined ? undefined : "strict"), issues };
1893
+ }
1894
+
1895
+ /** `routing.leases` (OpenCode v2 only); tolerant, see {@link sanitizeBackground}. */
1896
+ function sanitizeLeases(value: unknown): TolerantBlock<LeasesConfig> {
1897
+ const issues: string[] = [];
1898
+ if (value === undefined) return { value: undefined, issues };
1899
+ if (!isPlainObject(value)) {
1900
+ issues.push(`routing.leases must be an object (got ${showTolerant(value)}); ignored`);
1901
+ return { value: undefined, issues };
1902
+ }
1903
+ const out: LeasesConfig = {};
1904
+ const mode = tolerantEnum(value, "mode", "routing.leases", LEASES_MODES, ROUTING_DEFAULTS.leases.mode, issues);
1905
+ if (mode !== undefined) out.mode = mode;
1906
+ const run = tolerantEnum(value, "run", "routing.leases", LEASES_RUN_POLICIES, ROUTING_DEFAULTS.leases.run, issues);
1907
+ if (run !== undefined) out.run = run;
1908
+ return { value: out, issues };
1909
+ }
1910
+
1911
+ /** `routing.orphans` (OpenCode v2 only); tolerant, see {@link sanitizeBackground}. */
1912
+ function sanitizeOrphans(value: unknown): TolerantBlock<OrphansConfig> {
1913
+ const issues: string[] = [];
1914
+ if (value === undefined) return { value: undefined, issues };
1915
+ if (!isPlainObject(value)) {
1916
+ issues.push(`routing.orphans must be an object (got ${showTolerant(value)}); ignored`);
1917
+ return { value: undefined, issues };
1918
+ }
1919
+ const out: OrphansConfig = {};
1920
+ const resume = tolerantEnum(value, "resume", "routing.orphans", ["refuse", "allow"] as const, ROUTING_DEFAULTS.orphans.resume, issues);
1921
+ if (resume !== undefined) out.resume = resume;
1922
+ return { value: out, issues };
1923
+ }
1924
+
1925
+ const EXECUTOR_APPROVE_MODES = ["ask", "auto"] as const;
1926
+ const EXECUTOR_CROSS_PHASE_MODES = ["gate", "inferred"] as const;
1927
+ const EXECUTOR_LAND_MODES = ["ff-when-clean", "manual"] as const;
1928
+ const EXECUTOR_INTEGER_KEYS = [
1929
+ "maxParallel",
1930
+ "batchMax",
1931
+ "maxAttempts",
1932
+ "qaMaxRounds",
1933
+ "sharedContextChars",
1934
+ "capacityCooldownMs",
1935
+ "capacityPauseMs",
1936
+ "wakeDebounceMs",
1937
+ ] as const;
1938
+ const EXECUTOR_BREAKER_INTEGER_KEYS = ["minAttempts", "consecutiveFailures"] as const;
1939
+ const UNSAFE_OBJECT_KEYS: readonly string[] = ["__proto__", "constructor", "prototype"];
1940
+
1941
+ /** An inclusive-range number key; an invalid value yields an issue and no value (the default applies). */
1942
+ function tolerantRange(
1943
+ block: Record<string, unknown>,
1944
+ key: string,
1945
+ path: string,
1946
+ range: readonly [number, number],
1947
+ fallback: number,
1948
+ integer: boolean,
1949
+ issues: string[],
1950
+ ): number | undefined {
1951
+ const raw = block[key];
1952
+ if (raw === undefined) return undefined;
1953
+ if (typeof raw === "number" && Number.isFinite(raw) && (!integer || Number.isInteger(raw)) && raw >= range[0] && raw <= range[1]) {
1954
+ return raw;
1955
+ }
1956
+ issues.push(
1957
+ `${path}.${key} must be ${integer ? "an integer" : "a number"} from ${range[0]} to ${range[1]} (got ${showTolerant(raw)}); using ${fallback}`,
1958
+ );
1959
+ return undefined;
1960
+ }
1961
+
1962
+ /**
1963
+ * Repo-independent rules for `routing.executor.slotsDir`: an absolute drive path (`C:\…`), not a
1964
+ * drive root, not UNC / device, and free of `*`. Returns the problem, or `undefined` when valid.
1965
+ * The repository-relative rules are {@link validateSlotsDir}.
1966
+ */
1967
+ export function slotsDirProblem(value: string): string | undefined {
1968
+ if (value.includes("*")) return "must not contain '*'";
1969
+ if (/^[\\/]{2}/.test(value)) return "must not be a UNC or device path";
1970
+ if (!/^[A-Za-z]:[\\/]/.test(value)) return "must be an absolute path on a drive (like C:\\.omr-slots)";
1971
+ if (/^[A-Za-z]:[\\/]*$/.test(win32.normalize(value))) return "must not be a drive root";
1972
+ // QA-4.1-4: Win32 strips a trailing dot or space from a segment and expands an 8.3 short name,
1973
+ // so such a spelling can name another directory than the one the repository rules compared.
1974
+ const segments = value.slice(2).split(/[\\/]+/).filter((s) => s !== "");
1975
+ if (segments.some((s) => s.endsWith(".") || s.endsWith(" "))) return "must not have a path segment ending in '.' or a space";
1976
+ if (segments.some((s) => /~[0-9]+(\.[^.]*)?$/.test(s))) return "must not use an 8.3 short name (a '~N' segment)";
1977
+ return undefined;
1978
+ }
1979
+
1980
+ /**
1981
+ * Resolve links of the longest existing prefix of `p`; the missing tail is appended unchanged.
1982
+ * `realpathSync.native` (QA-4.1-4): on win32 it also resolves junctions and 8.3 short names.
1983
+ */
1984
+ function realpathOfExistingPrefix(p: string): string {
1985
+ const tail: string[] = [];
1986
+ let current = p;
1987
+ for (;;) {
1988
+ try {
1989
+ return tail.length === 0 ? realpathSync.native(current) : join(realpathSync.native(current), ...tail.reverse());
1990
+ } catch {
1991
+ const parent = dirname(current);
1992
+ if (parent === current) return p;
1993
+ tail.push(current.slice(parent.length).replace(/^[\\/]+/, ""));
1994
+ current = parent;
1995
+ }
1996
+ }
1997
+ }
1998
+
1999
+ export type SlotsDirCheck = { readonly ok: true } | { readonly ok: false; readonly reason: string };
2000
+
2001
+ /**
2002
+ * The repository-relative rules for `routing.executor.slotsDir` (D18), for approval, where the
2003
+ * repository is known (the approve-time call comes with the release that registers the executor,
2004
+ * Phase 5.1): `slotsDir` must pass {@link slotsDirProblem}, sit on the repository's drive, and be
2005
+ * neither inside nor an ancestor of `toplevel` (the repository's top-level directory). Native
2006
+ * realpaths (junctions, 8.3 names resolved) are compared, case-insensitively on win32.
2007
+ */
2008
+ export function validateSlotsDir(slotsDir: string, toplevel: string): SlotsDirCheck {
2009
+ const base = slotsDirProblem(slotsDir);
2010
+ if (base !== undefined) return { ok: false, reason: base };
2011
+ const fold = (p: string): string => (process.platform === "win32" ? p.toLowerCase() : p);
2012
+ const pathApi = process.platform === "win32" ? win32 : posix;
2013
+ const slots = fold(pathApi.resolve(realpathOfExistingPrefix(slotsDir)));
2014
+ const repo = fold(pathApi.resolve(realpathOfExistingPrefix(toplevel)));
2015
+ if (fold(pathApi.parse(slots).root) !== fold(pathApi.parse(repo).root)) {
2016
+ return { ok: false, reason: "must be on the repository's drive" };
2017
+ }
2018
+ const within = (outer: string, inner: string): boolean => {
2019
+ const rel = pathApi.relative(outer, inner);
2020
+ return rel === "" || !(rel === ".." || rel.startsWith(`..${pathApi.sep}`) || pathApi.isAbsolute(rel));
2021
+ };
2022
+ if (within(repo, slots)) return { ok: false, reason: "must not be inside the repository" };
2023
+ if (within(slots, repo)) return { ok: false, reason: "must not be an ancestor of the repository" };
2024
+ return { ok: true };
2025
+ }
2026
+
2027
+ /** A `[{script, args}]` list (a `router_run`-style reference); `undefined` when any entry is malformed. */
2028
+ function parseRunRefs(value: unknown): RunCommandRef[] | undefined {
2029
+ if (!Array.isArray(value)) return undefined;
2030
+ const out: RunCommandRef[] = [];
2031
+ for (const entry of value as unknown[]) {
2032
+ if (!isPlainObject(entry) || typeof entry.script !== "string" || entry.script.trim() === "") return undefined;
2033
+ const args = entry.args === undefined ? [] : entry.args;
2034
+ if (!Array.isArray(args) || !(args as unknown[]).every((a) => typeof a === "string")) return undefined;
2035
+ out.push({ script: entry.script, args: [...(args as string[])] });
2036
+ }
2037
+ return out;
2038
+ }
2039
+
2040
+ /** `{ <manager>: string[][] }` (argv arrays); `undefined` when malformed. */
2041
+ function parseProvision(value: unknown): Record<string, string[][]> | undefined {
2042
+ if (!isPlainObject(value)) return undefined;
2043
+ const out: Record<string, string[][]> = {};
2044
+ for (const [manager, argvs] of Object.entries(value)) {
2045
+ if (manager === "" || UNSAFE_OBJECT_KEYS.includes(manager) || !Array.isArray(argvs)) return undefined;
2046
+ const list: string[][] = [];
2047
+ for (const argv of argvs as unknown[]) {
2048
+ if (!Array.isArray(argv) || argv.length === 0) return undefined;
2049
+ if (!(argv as unknown[]).every((a) => typeof a === "string") || (argv as string[])[0] === "") return undefined;
2050
+ list.push([...(argv as string[])]);
2051
+ }
2052
+ out[manager] = list;
2053
+ }
2054
+ return out;
2055
+ }
2056
+
2057
+ /**
2058
+ * `routing.executor` (OpenCode v2 only), tolerant like {@link sanitizeBackground}: an invalid entry
2059
+ * never throws, it is reported in `issues` and the default applies. The trusted keys are dropped
2060
+ * from a project layer before this runs (`GLOBAL_ONLY_ROUTING_KEYS`).
2061
+ */
2062
+ function sanitizeExecutor(value: unknown): TolerantBlock<ExecutorOverrides> {
2063
+ const issues: string[] = [];
2064
+ if (value === undefined) return { value: undefined, issues };
2065
+ if (!isPlainObject(value)) {
2066
+ issues.push(`routing.executor must be an object (got ${showTolerant(value)}); ignored`);
2067
+ return { value: undefined, issues };
2068
+ }
2069
+ const p = "routing.executor";
2070
+ const d = ROUTING_DEFAULTS.executor;
2071
+ const out: ExecutorOverrides = {};
2072
+
2073
+ for (const key of EXECUTOR_INTEGER_KEYS) {
2074
+ const v = tolerantRange(value, key, p, EXECUTOR_LIMITS[key], d[key], true, issues);
2075
+ if (v !== undefined) out[key] = v;
2076
+ }
2077
+ const approve = tolerantEnum(value, "approve", p, EXECUTOR_APPROVE_MODES, d.approve, issues);
2078
+ if (approve !== undefined) out.approve = approve;
2079
+ const crossPhase = tolerantEnum(value, "crossPhase", p, EXECUTOR_CROSS_PHASE_MODES, d.crossPhase, issues);
2080
+ if (crossPhase !== undefined) out.crossPhase = crossPhase;
2081
+ const land = tolerantEnum(value, "land", p, EXECUTOR_LAND_MODES, d.land, issues);
2082
+ if (land !== undefined) out.land = land;
2083
+
2084
+ const slotsDir = value.slotsDir;
2085
+ if (slotsDir !== undefined) {
2086
+ const problem = slotsDir === null ? undefined : typeof slotsDir !== "string" ? "must be a string or null" : slotsDirProblem(slotsDir);
2087
+ if (problem === undefined) out.slotsDir = slotsDir as string | null;
2088
+ else issues.push(`${p}.slotsDir ${problem} (got ${showTolerant(slotsDir)}); using ${d.slotsDir}`);
2089
+ }
2090
+
2091
+ const checks = value.integrationChecks;
2092
+ if (checks !== undefined) {
2093
+ const refs = checks === "auto" ? "auto" : parseRunRefs(checks);
2094
+ if (refs !== undefined) out.integrationChecks = refs;
2095
+ else issues.push(`${p}.integrationChecks must be "auto" or an array of {script, args} (got ${showTolerant(checks)}); using ${d.integrationChecks}`);
2096
+ }
2097
+ const suite = value.phaseSuite;
2098
+ if (suite !== undefined) {
2099
+ const refs = suite === "auto" || suite === "off" ? suite : parseRunRefs(suite);
2100
+ if (refs !== undefined) out.phaseSuite = refs;
2101
+ else issues.push(`${p}.phaseSuite must be "auto", "off" or an array of {script, args} (got ${showTolerant(suite)}); using ${d.phaseSuite}`);
2102
+ }
2103
+ const provision = value.provision;
2104
+ if (provision !== undefined) {
2105
+ const parsed = provision === "auto" ? "auto" : parseProvision(provision);
2106
+ if (parsed !== undefined) out.provision = parsed;
2107
+ else issues.push(`${p}.provision must be "auto" or an object of argv arrays per manager (got ${showTolerant(provision)}); using ${d.provision}`);
2108
+ }
2109
+ const python = value.python;
2110
+ if (python !== undefined) {
2111
+ if (typeof python === "string" && (python === "auto" || (isAbsolute(python) && !python.includes("\0")))) out.python = python;
2112
+ else issues.push(`${p}.python must be "auto" or an absolute path (got ${showTolerant(python)}); using ${d.python}`);
2113
+ }
2114
+
2115
+ const breaker = value.circuitBreaker;
2116
+ if (breaker !== undefined) {
2117
+ if (!isPlainObject(breaker)) {
2118
+ issues.push(`${p}.circuitBreaker must be an object (got ${showTolerant(breaker)}); ignored`);
2119
+ } else {
2120
+ const bp = `${p}.circuitBreaker`;
2121
+ const b: Partial<ExecutorConfig["circuitBreaker"]> = {};
2122
+ const ratio = tolerantRange(breaker, "failureRatio", bp, EXECUTOR_LIMITS.failureRatio, d.circuitBreaker.failureRatio, false, issues);
2123
+ if (ratio !== undefined) b.failureRatio = ratio;
2124
+ for (const key of EXECUTOR_BREAKER_INTEGER_KEYS) {
2125
+ const v = tolerantRange(breaker, key, bp, EXECUTOR_LIMITS[key], d.circuitBreaker[key], true, issues);
2126
+ if (v !== undefined) b[key] = v;
2127
+ }
2128
+ out.circuitBreaker = b;
2129
+ }
2130
+ }
2131
+ return { value: out, issues };
2132
+ }
2133
+
2134
+ /**
2135
+ * The v2-only `routing` keys the raw config configures, as dotted paths in a fixed order.
2136
+ * `raw` is the config as written (its `routing` block is read) or the `routing` block
2137
+ * itself. A key counts when it is present and not `undefined`, whether or not its value is
2138
+ * valid. On v1, where they are ignored, `index.ts` logs ONE notice per process that names
2139
+ * every configured key (QA-2.1-32). A `routing.executor` that is not an object is named as
2140
+ * `routing.executor` (QA-4.1-19): v1 does not log its validation issue.
2141
+ */
2142
+ export function configuredV2OnlyKeys(raw: unknown): string[] {
2143
+ const routing = isPlainObject(raw) && isPlainObject(raw.routing) ? raw.routing : isPlainObject(raw) ? raw : undefined;
2144
+ if (routing === undefined) return [];
2145
+ const keys: string[] = [];
2146
+ const candidates: ReadonlyArray<readonly [string, readonly string[]]> = [
2147
+ ["background", ["mode", "minPredictedMs"]],
2148
+ ["leases", ["mode", "run"]],
2149
+ ["orphans", ["resume"]],
2150
+ ];
2151
+ for (const [block, children] of candidates) {
2152
+ const value = routing[block];
2153
+ if (!isPlainObject(value)) {
2154
+ if (block === "orphans" && value !== undefined) keys.push("routing.orphans");
2155
+ continue;
2156
+ }
2157
+ for (const child of children) {
2158
+ if (Object.hasOwn(value, child) && value[child] !== undefined) keys.push(`routing.${block}.${child}`);
2159
+ }
2160
+ }
2161
+ const executor = routing.executor;
2162
+ if (!isPlainObject(executor)) {
2163
+ // QA-4.1-19: an executor that is not an object is named whole; its validation issue is v2-only.
2164
+ if (Object.hasOwn(routing, "executor") && executor !== undefined) keys.push("routing.executor");
2165
+ } else {
2166
+ for (const child of ROUTING_KNOWN_KEYS.executor!) {
2167
+ if (!Object.hasOwn(executor, child) || executor[child] === undefined) continue;
2168
+ const nested = executor[child];
2169
+ if (child === "circuitBreaker" && isPlainObject(nested)) {
2170
+ for (const leaf of ROUTING_KNOWN_KEYS.circuitBreaker!) {
2171
+ if (Object.hasOwn(nested, leaf) && nested[leaf] !== undefined) keys.push(`routing.executor.circuitBreaker.${leaf}`);
2172
+ }
2173
+ } else {
2174
+ keys.push(`routing.executor.${child}`);
2175
+ }
2176
+ }
2177
+ }
2178
+ return keys;
2179
+ }
2180
+
1762
2181
  /**
1763
2182
  * Validate `routing` and return a snapshot of the validated values (or
1764
2183
  * `undefined` when absent). Defaults are NOT applied here; see resolveRouting.
@@ -1812,12 +2231,32 @@ function validateRouting(value: unknown): RoutingConfig | undefined {
1812
2231
  // Roles keys (#84): tolerant per entry, never throw (see roles-config.ts).
1813
2232
  const delegation = sanitizeDelegation(routing.delegation).value;
1814
2233
  if (delegation !== undefined) out.delegation = delegation;
2234
+ const roleFloor = sanitizeRoleFloor(routing.roleFloor).value;
2235
+ if (roleFloor !== undefined) out.roleFloor = roleFloor;
1815
2236
  const exploration = sanitizeExploration(routing.exploration).value;
1816
2237
  if (exploration !== undefined) out.exploration = exploration;
1817
2238
  const run = sanitizeRun(routing.run).value;
1818
2239
  if (run !== undefined) out.run = run;
1819
2240
  const workRoots = sanitizeWorkRoots(routing.workRoots).value;
1820
2241
  if (workRoots !== undefined) out.workRoots = workRoots;
2242
+ const repoParents = sanitizeRepoParents(routing.repoParents).value;
2243
+ if (repoParents !== undefined) out.repoParents = repoParents;
2244
+ const repoDepth = sanitizeRepoDepth(routing.repoDepth).value;
2245
+ if (repoDepth !== undefined) out.repoDepth = repoDepth;
2246
+ const repoExclude = sanitizeRepoExclude(routing.repoExclude).value;
2247
+ if (repoExclude !== undefined) out.repoExclude = repoExclude;
2248
+ const repoApprovalDays = sanitizeRepoApprovalDays(routing.repoApprovalDays).value;
2249
+ if (repoApprovalDays !== undefined) out.repoApprovalDays = repoApprovalDays;
2250
+
2251
+ // Phase 2.1 keys (OpenCode v2 only): tolerant, issues surface as notices.
2252
+ const background = sanitizeBackground(routing.background).value;
2253
+ if (background !== undefined) out.background = background;
2254
+ const leases = sanitizeLeases(routing.leases).value;
2255
+ if (leases !== undefined) out.leases = leases;
2256
+ const orphans = sanitizeOrphans(routing.orphans).value;
2257
+ if (orphans !== undefined) out.orphans = orphans;
2258
+ const executor = sanitizeExecutor(routing.executor).value;
2259
+ if (executor !== undefined) out.executor = executor;
1821
2260
 
1822
2261
  const outcomes = readBlock(routing, "outcomes", "routing");
1823
2262
  if (outcomes !== undefined) {
@@ -2205,10 +2644,26 @@ const GLOBAL_ONLY_ROUTING_KEYS: ReadonlyArray<readonly [block: string, key: stri
2205
2644
  ["classifier", "apiKeyEnv"],
2206
2645
  ["classifier", "presets"],
2207
2646
  ["outcomes", "path"],
2647
+ // D18: the plan executor runs these in the user's checkout and on its drive; a repository
2648
+ // must not choose its own slot directory, check commands, provisioning argv or interpreter.
2649
+ ["executor", "slotsDir"],
2650
+ ["executor", "integrationChecks"],
2651
+ ["executor", "phaseSuite"],
2652
+ ["executor", "provision"],
2653
+ ["executor", "python"],
2208
2654
  ];
2209
2655
 
2210
2656
  /** Roles keys (#84) a project layer must not carry; `routing.delegation` is allowed there. */
2211
- const GLOBAL_ONLY_ROLES_ROUTING_KEYS = ["exploration", "run", "workRoots"] as const;
2657
+ const GLOBAL_ONLY_ROLES_ROUTING_KEYS = [
2658
+ "roleFloor",
2659
+ "exploration",
2660
+ "run",
2661
+ "workRoots",
2662
+ "repoParents",
2663
+ "repoDepth",
2664
+ "repoExclude",
2665
+ "repoApprovalDays",
2666
+ ] as const;
2212
2667
 
2213
2668
  function stripGlobalOnlyRolesKeys(data: Record<string, unknown>): string[] {
2214
2669
  const dropped: string[] = [];
@@ -2229,12 +2684,24 @@ function stripGlobalOnlyRolesKeys(data: Record<string, unknown>): string[] {
2229
2684
  return dropped;
2230
2685
  }
2231
2686
 
2232
- /** Remove the global-only `routing` keys from a project layer; returns what was dropped. */
2687
+ /**
2688
+ * Remove the global-only `routing` keys from a project layer, and a `routing.executor` that is not
2689
+ * a plain object (QA-4.1-2); returns what was dropped.
2690
+ */
2233
2691
  function stripGlobalOnlyRoutingKeys(data: Record<string, unknown>): string[] {
2234
2692
  const routing = data.routing;
2235
2693
  if (!isPlainObject(routing)) return [];
2236
2694
  const dropped: string[] = [];
2237
2695
  const touched = new Set<string>();
2696
+ // QA-4.1-2: an `executor` that is not a plain object (`null`, `[]`, a scalar) would replace the
2697
+ // lower layer's block wholesale in deepMerge, and tolerant validation would then reset every
2698
+ // trusted executor key to its default. The project layer may not do that; the block goes.
2699
+ // QA-4.1-18: `executor` only. A non-object `classifier` or `outcomes` still fails validation,
2700
+ // which drops the project layer (fail closed, the v1 behaviour).
2701
+ if (Object.hasOwn(routing, "executor") && routing.executor !== undefined && !isPlainObject(routing.executor)) {
2702
+ delete routing.executor;
2703
+ dropped.push("routing.executor");
2704
+ }
2238
2705
  for (const [block, key] of GLOBAL_ONLY_ROUTING_KEYS) {
2239
2706
  const target = routing[block];
2240
2707
  if (isPlainObject(target) && Object.hasOwn(target, key)) {
@@ -2272,11 +2739,12 @@ function collectOverrideLayers(
2272
2739
  if (!data) continue;
2273
2740
  if (project) {
2274
2741
  const dropped = stripGlobalOnlyRoutingKeys(data);
2275
- if (dropped.length > 0) {
2276
- notices?.push({
2277
- source: p,
2278
- message: `ignoring ${dropped.join(", ")} from ${p}: only the global override may set it`,
2279
- });
2742
+ // QA-4.1-19: the executor keys get their own notice, flagged v2-only (a v1 host ignores the block).
2743
+ const isExecutorKey = (key: string): boolean => key === "routing.executor" || key.startsWith("routing.executor.");
2744
+ for (const [keys, v2Only] of [[dropped.filter((k) => !isExecutorKey(k)), false], [dropped.filter(isExecutorKey), true]] as const) {
2745
+ if (keys.length === 0) continue;
2746
+ const message = `ignoring ${keys.join(", ")} from ${p}: only the global override may set it`;
2747
+ notices?.push(v2Only ? { source: p, message, v2Only } : { source: p, message });
2280
2748
  }
2281
2749
  // #84: a repository may pick `routing.delegation`, but not customise role agents, grant
2282
2750
  // exploration, define `router_run` commands or widen the work roots.
@@ -2305,6 +2773,18 @@ function collectOverrideLayers(
2305
2773
  /** The notices of the build that produced each config object (the cache hands the same object back until a reload). */
2306
2774
  const noticesByConfig = new WeakMap<RouterConfig, readonly ConfigNotice[]>();
2307
2775
 
2776
+ /** The merged config as written (before validation) behind each built config object; see {@link configAsWritten}. */
2777
+ const rawByConfig = new WeakMap<RouterConfig, unknown>();
2778
+
2779
+ /**
2780
+ * The config `cfg` was validated from, as written: tiers.json with the override layers merged
2781
+ * (after the project-layer trust rules), or `cfg` itself when it was not built by loadConfig.
2782
+ * Validation drops an invalid tolerant entry from `cfg`; this still has it (QA-4.1-9).
2783
+ */
2784
+ export function configAsWritten(cfg: RouterConfig): unknown {
2785
+ return rawByConfig.has(cfg) ? rawByConfig.get(cfg) : cfg; // not built here (a test's literal): as validated
2786
+ }
2787
+
2308
2788
  /** Notice texts already logged in this process (bounded); see {@link warnConfigNotices}. */
2309
2789
  const loggedNoticeTexts = new Set<string>();
2310
2790
 
@@ -2322,6 +2802,7 @@ export function warnConfigNotices(
2322
2802
  ): void {
2323
2803
  if (cfg === undefined) return;
2324
2804
  for (const notice of noticesByConfig.get(cfg) ?? []) {
2805
+ if (configNoticeHost === "v1" && notice.v2Only === true) continue; // QA-4.1-9: the v1 notice names the key instead
2325
2806
  if (loggedNoticeTexts.has(notice.message)) continue;
2326
2807
  if (loggedNoticeTexts.size >= 256) loggedNoticeTexts.clear();
2327
2808
  loggedNoticeTexts.add(notice.message);
@@ -2509,10 +2990,42 @@ const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
2509
2990
  "sessionReuse",
2510
2991
  "advisor",
2511
2992
  "delegation",
2993
+ "roleFloor",
2512
2994
  "exploration",
2513
2995
  "run",
2514
2996
  "workRoots",
2997
+ "repoParents",
2998
+ "repoDepth",
2999
+ "repoExclude",
3000
+ "repoApprovalDays",
3001
+ "background",
3002
+ "leases",
3003
+ "orphans",
3004
+ "executor",
3005
+ ],
3006
+ background: ["mode", "minPredictedMs"],
3007
+ leases: ["mode", "run"],
3008
+ orphans: ["resume"],
3009
+ executor: [
3010
+ "maxParallel",
3011
+ "slotsDir",
3012
+ "approve",
3013
+ "crossPhase",
3014
+ "land",
3015
+ "batchMax",
3016
+ "maxAttempts",
3017
+ "qaMaxRounds",
3018
+ "integrationChecks",
3019
+ "phaseSuite",
3020
+ "provision",
3021
+ "python",
3022
+ "sharedContextChars",
3023
+ "capacityCooldownMs",
3024
+ "capacityPauseMs",
3025
+ "wakeDebounceMs",
3026
+ "circuitBreaker",
2515
3027
  ],
3028
+ circuitBreaker: ["failureRatio", "minAttempts", "consecutiveFailures"],
2516
3029
  detection: ["deterministic", "grader", "none"],
2517
3030
  classifier: ["backend", "model", "baseUrl", "apiKeyEnv", "timeoutMs", "samples", "maxStateChars", "presets"],
2518
3031
  preset: ["backend", "model"],
@@ -2535,10 +3048,17 @@ export function findUnknownRoutingKeys(routing: unknown): string[] {
2535
3048
  }
2536
3049
  };
2537
3050
  check(routing, ROUTING_KNOWN_KEYS.routing!, "routing");
2538
- for (const block of ["detection", "classifier", "outcomes", "sessionReuse", "advisor"] as const) {
3051
+ for (const block of ["detection", "classifier", "outcomes", "sessionReuse", "advisor", "background", "leases", "orphans"] as const) {
2539
3052
  const value = routing[block];
2540
3053
  if (isPlainObject(value)) check(value, ROUTING_KNOWN_KEYS[block]!, `routing.${block}`);
2541
3054
  }
3055
+ const executor = routing.executor;
3056
+ if (isPlainObject(executor)) {
3057
+ check(executor, ROUTING_KNOWN_KEYS.executor!, "routing.executor");
3058
+ if (isPlainObject(executor.circuitBreaker)) {
3059
+ check(executor.circuitBreaker, ROUTING_KNOWN_KEYS.circuitBreaker!, "routing.executor.circuitBreaker");
3060
+ }
3061
+ }
2542
3062
  const classifier = routing.classifier;
2543
3063
  const presets = isPlainObject(classifier) ? classifier.presets : undefined;
2544
3064
  if (isPlainObject(presets)) {
@@ -2565,10 +3085,38 @@ export const ROUTING_RESERVED_AGENTS = ["build", "plan", "title", "summary", "co
2565
3085
  * validated config.
2566
3086
  */
2567
3087
  export function collectRoutingNotices(rawRouting: unknown, cfg: RouterConfig): string[] {
3088
+ return collectTaggedRoutingNotices(rawRouting, cfg).map((notice) => notice.message);
3089
+ }
3090
+
3091
+ /** The v2-only `routing` blocks: a v1 host ignores them, and logs one notice naming their keys instead. */
3092
+ const V2_ONLY_ROUTING_BLOCKS = ["background", "leases", "orphans", "executor"] as const;
3093
+
3094
+ /**
3095
+ * {@link collectRoutingNotices}, each message tagged `v2Only` when it is about a v2-only block
3096
+ * (QA-4.1-9, QA-4.1-19): its validation issues and its unknown keys, which get their own message.
3097
+ */
3098
+ function collectTaggedRoutingNotices(rawRouting: unknown, cfg: RouterConfig): Array<{ message: string; v2Only: boolean }> {
3099
+ const tagged: Array<{ message: string; v2Only: boolean }> = [];
2568
3100
  const messages: string[] = [];
3101
+ const unknownMessage = (keys: readonly string[]): string =>
3102
+ `ignoring unknown routing key${keys.length === 1 ? "" : "s"}: ${keys.join(", ")}`;
3103
+ const inV2OnlyBlock = (key: string): boolean => V2_ONLY_ROUTING_BLOCKS.some((block) => key.startsWith(`routing.${block}.`));
2569
3104
  const unknown = findUnknownRoutingKeys(rawRouting);
2570
- if (unknown.length > 0) {
2571
- messages.push(`ignoring unknown routing key${unknown.length === 1 ? "" : "s"}: ${unknown.join(", ")}`);
3105
+ const unknownShared = unknown.filter((key) => !inV2OnlyBlock(key));
3106
+ const unknownV2Only = unknown.filter(inV2OnlyBlock);
3107
+ if (unknownShared.length > 0) tagged.push({ message: unknownMessage(unknownShared), v2Only: false });
3108
+ if (unknownV2Only.length > 0) tagged.push({ message: unknownMessage(unknownV2Only), v2Only: true });
3109
+ if (isPlainObject(rawRouting)) {
3110
+ for (const message of [
3111
+ ...sanitizeRoleFloor(rawRouting.roleFloor).issues,
3112
+ ...sanitizeBackground(rawRouting.background).issues,
3113
+ ...sanitizeLeases(rawRouting.leases).issues,
3114
+ ...sanitizeOrphans(rawRouting.orphans).issues,
3115
+ // QA-62C-2: the plan executor is inert off Windows (G-16), so its values are not validated there.
3116
+ ...(executorPlatformSupported() ? sanitizeExecutor(rawRouting.executor).issues : []),
3117
+ ]) {
3118
+ tagged.push({ message, v2Only: true });
3119
+ }
2572
3120
  }
2573
3121
  for (const [taskClass, agents] of Object.entries(cfg.routing?.roles ?? {})) {
2574
3122
  for (const agent of agents) {
@@ -2596,7 +3144,7 @@ export function collectRoutingNotices(rawRouting: unknown, cfg: RouterConfig): s
2596
3144
  );
2597
3145
  }
2598
3146
  }
2599
- return messages;
3147
+ return [...tagged, ...messages.map((message) => ({ message, v2Only: false }))];
2600
3148
  }
2601
3149
  /**
2602
3150
  * `routing.roles` is replaced wholesale by the highest-priority layer that sets
@@ -2615,10 +3163,113 @@ function replaceRolesWholesale(merged: unknown, layers: readonly OverrideLayer[]
2615
3163
  return merged;
2616
3164
  }
2617
3165
 
2618
- /** Merge an override while keeping project classifier budgets within the lower layers' bounds. */
3166
+ /** An inclusive-range number as {@link tolerantRange} accepts it. */
3167
+ function inRange(value: unknown, range: readonly [number, number], integer: boolean): value is number {
3168
+ return typeof value === "number" && Number.isFinite(value) && (!integer || Number.isInteger(value))
3169
+ && value >= range[0] && value <= range[1];
3170
+ }
3171
+
3172
+ /** The tightest value of each `routing.executor` mode key: the only one a project layer may pick (A-4.1-2). */
3173
+ const EXECUTOR_TIGHTEST_MODES = [
3174
+ ["approve", EXECUTOR_APPROVE_MODES, "ask"],
3175
+ ["land", EXECUTOR_LAND_MODES, "manual"],
3176
+ ["crossPhase", EXECUTOR_CROSS_PHASE_MODES, "gate"],
3177
+ ] as const;
3178
+
3179
+ /** The `routing.executor` budgets a project layer may only lower (A-4.1-2); the timing keys are not budgets. */
3180
+ const EXECUTOR_BUDGET_KEYS = ["maxParallel", "batchMax", "maxAttempts", "qaMaxRounds", "sharedContextChars"] as const;
3181
+
3182
+ /**
3183
+ * A-4.1-2 (the A35 precedent of the classifier budgets): a project layer may tighten the plan
3184
+ * executor's approval, landing, cross-phase, budget and circuit-breaker keys, never loosen them.
3185
+ * `merged` is the executor block after deepMerge, `requested` the project layer's block,
3186
+ * `inherited` the lower layers' block. A value counts as what sanitizeExecutor makes of it (an
3187
+ * invalid one is the default); a loosening one is dropped, so the lower-layer value stays, and
3188
+ * reported once per key. Returns a copy: deepMerge can share an override-only block.
3189
+ */
3190
+ function boundProjectExecutor(
3191
+ merged: Record<string, unknown>,
3192
+ requested: Record<string, unknown>,
3193
+ inherited: unknown,
3194
+ path: string,
3195
+ notices: ConfigNotice[],
3196
+ ): Record<string, unknown> {
3197
+ const lower = isPlainObject(inherited) ? inherited : {};
3198
+ const out: Record<string, unknown> = { ...merged };
3199
+ const d = ROUTING_DEFAULTS.executor;
3200
+ const drop = (target: Record<string, unknown>, source: Record<string, unknown>, key: string, name: string): void => {
3201
+ if (Object.hasOwn(source, key) && source[key] !== undefined) target[key] = source[key];
3202
+ else delete target[key];
3203
+ notices.push({
3204
+ source: path,
3205
+ message: `A18: ignoring routing.executor.${name} from ${path}: project overrides may only tighten the lower-layer value (A-4.1-2)`,
3206
+ v2Only: true,
3207
+ });
3208
+ };
3209
+ // Every budget and breaker value is tighter when lower: min(lower layer, project value).
3210
+ const bound = (
3211
+ target: Record<string, unknown>,
3212
+ source: Record<string, unknown>,
3213
+ block: Record<string, unknown>,
3214
+ key: string,
3215
+ name: string,
3216
+ range: readonly [number, number],
3217
+ integer: boolean,
3218
+ fallback: number,
3219
+ ): void => {
3220
+ const value = block[key];
3221
+ if (value === undefined) return;
3222
+ const ceiling = inRange(source[key], range, integer) ? source[key] : fallback;
3223
+ const effective = inRange(value, range, integer) ? value : fallback;
3224
+ if (effective > ceiling) drop(target, source, key, name);
3225
+ };
3226
+
3227
+ for (const key of EXECUTOR_BUDGET_KEYS) bound(out, lower, requested, key, key, EXECUTOR_LIMITS[key], true, d[key]);
3228
+ for (const [key, modes, tightest] of EXECUTOR_TIGHTEST_MODES) {
3229
+ const value = requested[key];
3230
+ if (value === undefined) continue;
3231
+ const valid = (v: unknown): v is string => typeof v === "string" && (modes as readonly string[]).includes(v);
3232
+ const ceiling = valid(lower[key]) ? lower[key] : d[key];
3233
+ const effective = valid(value) ? value : d[key];
3234
+ if (effective !== tightest && effective !== ceiling) drop(out, lower, key, key);
3235
+ }
3236
+
3237
+ const breaker = requested.circuitBreaker;
3238
+ if (breaker !== undefined) {
3239
+ if (!isPlainObject(breaker)) {
3240
+ // sanitizeExecutor would ignore the block, so the defaults would replace the lower values.
3241
+ if (lower.circuitBreaker !== undefined) drop(out, lower, "circuitBreaker", "circuitBreaker");
3242
+ } else {
3243
+ const lowerBreaker = isPlainObject(lower.circuitBreaker) ? lower.circuitBreaker : {};
3244
+ const b: Record<string, unknown> = isPlainObject(out.circuitBreaker) ? { ...out.circuitBreaker } : {};
3245
+ const db = d.circuitBreaker;
3246
+ bound(b, lowerBreaker, breaker, "failureRatio", "circuitBreaker.failureRatio", EXECUTOR_LIMITS.failureRatio, false, db.failureRatio);
3247
+ for (const key of EXECUTOR_BREAKER_INTEGER_KEYS) {
3248
+ bound(b, lowerBreaker, breaker, key, `circuitBreaker.${key}`, EXECUTOR_LIMITS[key], true, db[key]);
3249
+ }
3250
+ out.circuitBreaker = b;
3251
+ }
3252
+ }
3253
+ return out;
3254
+ }
3255
+
3256
+ /** Merge an override while keeping project classifier budgets and executor keys within the lower layers' bounds. */
2619
3257
  function mergeOverrideLayer(lower: unknown, layer: OverrideLayer, notices: ConfigNotice[]): unknown {
2620
3258
  const merged = deepMerge(lower, layer.data);
2621
3259
  if (!layer.project || !isPlainObject(merged) || !isPlainObject(merged.routing)) return merged;
3260
+ const projectRouting = layer.data.routing;
3261
+ const lowerRouting = isPlainObject(lower) ? lower.routing : undefined;
3262
+ const projectExecutor = isPlainObject(projectRouting) ? projectRouting.executor : undefined;
3263
+ const mergedExecutor = merged.routing.executor;
3264
+ const executorBounded = isPlainObject(mergedExecutor) && isPlainObject(projectExecutor)
3265
+ ? { ...merged, routing: { ...merged.routing, executor: boundProjectExecutor(mergedExecutor, projectExecutor, isPlainObject(lowerRouting) ? lowerRouting.executor : undefined, layer.path, notices) } }
3266
+ : merged;
3267
+ return boundProjectClassifier(executorBounded, lower, layer, notices);
3268
+ }
3269
+
3270
+ /** Keep the project classifier budgets within the lower layers' bounds (A35); `merged` already holds the project layer. */
3271
+ function boundProjectClassifier(merged: Record<string, unknown>, lower: unknown, layer: OverrideLayer, notices: ConfigNotice[]): unknown {
3272
+ if (!isPlainObject(merged.routing)) return merged;
2622
3273
  const classifier = merged.routing.classifier;
2623
3274
  const projectRouting = layer.data.routing;
2624
3275
  const projectClassifier = isPlainObject(projectRouting) ? projectRouting.classifier : undefined;
@@ -2663,21 +3314,27 @@ function buildConfig(
2663
3314
  let rawUsed: unknown = base;
2664
3315
 
2665
3316
  if (layers.length > 0) {
2666
- const merge = (ls: OverrideLayer[]): unknown =>
3317
+ // The merge notices (A18 clamps) of one attempt; only the attempt whose result is used
3318
+ // reports them, so a fallback merge does not push them twice (QA-4.1-21).
3319
+ const merge = (ls: OverrideLayer[], attemptNotices: ConfigNotice[]): unknown =>
2667
3320
  replaceRolesWholesale(
2668
- ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, notices), base),
3321
+ ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, attemptNotices), base),
2669
3322
  ls,
2670
3323
  );
2671
3324
 
2672
3325
  try {
2673
- const merged = merge(layers);
3326
+ const attemptNotices: ConfigNotice[] = [];
3327
+ const merged = merge(layers, attemptNotices);
2674
3328
  cfg = validateConfig(merged);
2675
3329
  rawUsed = merged;
3330
+ notices.push(...attemptNotices);
2676
3331
  } catch (err) {
2677
3332
  // A bad override must never brick startup, and one broken file must not
2678
- // discard a good one. Fall back to the highest-priority layer that
2679
- // validates on its own (so a broken personal/global file still lets a
2680
- // shared project file apply), else the bundled defaults.
3333
+ // discard a good one. Fall back to one layer that validates on its own,
3334
+ // else the bundled defaults. QA-4.1-21: the global layer is tried first, so
3335
+ // a project file cannot force a conflict with a value valid on its own and
3336
+ // so drop the user's whole global layer; a broken global file still lets a
3337
+ // project file apply.
2681
3338
  console.warn(
2682
3339
  `[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
2683
3340
  );
@@ -2686,11 +3343,17 @@ function buildConfig(
2686
3343
  source: layerPaths,
2687
3344
  message: `${layerPaths}: combined overrides are invalid — ${(err as Error).message}`,
2688
3345
  });
2689
- for (let i = layers.length - 1; i >= 0; i--) {
3346
+ const order = [
3347
+ ...layers.map((_, i) => i).filter((i) => !layers[i]!.project).reverse(),
3348
+ ...layers.map((_, i) => i).filter((i) => layers[i]!.project === true).reverse(),
3349
+ ];
3350
+ for (const i of order) {
2690
3351
  try {
2691
- const single = merge([layers[i]!]);
3352
+ const attemptNotices: ConfigNotice[] = [];
3353
+ const single = merge([layers[i]!], attemptNotices);
2692
3354
  cfg = validateConfig(single);
2693
3355
  rawUsed = single;
3356
+ notices.push(...attemptNotices);
2694
3357
  for (let j = 0; j < layers.length; j++) {
2695
3358
  if (j !== i) {
2696
3359
  console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
@@ -2755,12 +3418,17 @@ function buildConfig(
2755
3418
 
2756
3419
  applyTierDefaults(cfg);
2757
3420
  const rawRouting = isPlainObject(rawUsed) ? rawUsed.routing : undefined;
2758
- for (const message of collectRoutingNotices(rawRouting, cfg)) notices.push({ message });
3421
+ // QA-4.1-9, QA-4.1-19: a notice about a v2-only block (background, leases, executor) is not logged on v1
3422
+ // (warnConfigNotices); index.ts names the configured keys in its one notice instead.
3423
+ for (const { message, v2Only } of collectTaggedRoutingNotices(rawRouting, cfg)) {
3424
+ notices.push(v2Only ? { message, v2Only } : { message });
3425
+ }
2759
3426
  const rawRoleAgents = isPlainObject(rawUsed) ? rawUsed.roleAgents : undefined;
2760
3427
  for (const issue of collectRolesIssues(rawRouting, rawRoleAgents)) notices.push({ message: issue.message });
2761
3428
  dropIgnoredCandidates(cfg);
2762
3429
  applyPluginAgents(cfg, layers, notices);
2763
3430
  applyRoleNotices(cfg, notices);
3431
+ rawByConfig.set(cfg, rawUsed);
2764
3432
  return cfg;
2765
3433
  }
2766
3434
 
@@ -3039,6 +3707,30 @@ export const ROUTING_DEFAULTS = Object.freeze({
3039
3707
  outcomes: Object.freeze({ path: null, halfLifeDays: 14, maxEffectiveSamples: 50 }),
3040
3708
  sessionReuse: Object.freeze({ maxContextFraction: 0.6 }),
3041
3709
  advisor: Object.freeze({ enabled: true, noticeIntervalHours: 24, notify: true }),
3710
+ // OpenCode v2 only; v1 ignores these blocks (see configuredV2OnlyKeys).
3711
+ background: Object.freeze({ mode: "auto" as BackgroundMode, minPredictedMs: 45_000 }),
3712
+ leases: Object.freeze({ mode: "enforce" as LeasesMode, run: "annotate" as LeasesRunPolicy }),
3713
+ orphans: Object.freeze({ resume: "refuse" as const }),
3714
+ // OpenCode v2 only (plan executor); v1 ignores the block (see configuredV2OnlyKeys). Ranges: EXECUTOR_LIMITS.
3715
+ executor: Object.freeze({
3716
+ maxParallel: 4,
3717
+ slotsDir: null as string | null,
3718
+ approve: "ask" as ExecutorConfig["approve"],
3719
+ crossPhase: "gate" as ExecutorConfig["crossPhase"],
3720
+ land: "ff-when-clean" as ExecutorConfig["land"],
3721
+ batchMax: 4,
3722
+ maxAttempts: 3,
3723
+ qaMaxRounds: 3,
3724
+ integrationChecks: "auto" as ExecutorConfig["integrationChecks"],
3725
+ phaseSuite: "auto" as ExecutorConfig["phaseSuite"],
3726
+ provision: "auto" as ExecutorConfig["provision"],
3727
+ python: "auto",
3728
+ sharedContextChars: 12_000,
3729
+ capacityCooldownMs: 120_000,
3730
+ capacityPauseMs: 900_000,
3731
+ wakeDebounceMs: 5_000,
3732
+ circuitBreaker: Object.freeze({ failureRatio: 0.4, minAttempts: 5, consecutiveFailures: 3 }),
3733
+ }),
3042
3734
  });
3043
3735
 
3044
3736
  export interface ResolvedClassifier {
@@ -3077,6 +3769,11 @@ export interface ResolvedRouting {
3077
3769
  readonly outcomes: Readonly<{ path: string | null; halfLifeDays: number; maxEffectiveSamples: number }>;
3078
3770
  readonly sessionReuse: Readonly<Required<SessionReuseConfig>>;
3079
3771
  readonly advisor: Readonly<Required<AdvisorConfig>>;
3772
+ readonly background: Readonly<Required<BackgroundConfig>>;
3773
+ readonly leases: Readonly<Required<LeasesConfig>>;
3774
+ readonly orphans: Readonly<Required<OrphansConfig>>;
3775
+ /** Plan executor (v2 only); the defaults on v1, where the block is ignored. */
3776
+ readonly executor: Readonly<ExecutorConfig>;
3080
3777
  readonly applied: RoutingApplied;
3081
3778
  }
3082
3779
 
@@ -3088,13 +3785,73 @@ function expandHomePath(value: string | null): string | null {
3088
3785
  }
3089
3786
 
3090
3787
  let warnedEngineIgnoredOnV1 = false;
3788
+ const warnedRoutingIssues = new Set<string>();
3091
3789
 
3092
3790
  /** Test-only: re-arm the once-per-process "engine ignored on v1" notice. */
3093
3791
  export function resetRoutingWarnings(): void {
3094
3792
  warnedEngineIgnoredOnV1 = false;
3793
+ warnedRoutingIssues.clear();
3095
3794
  loggedNoticeTexts.clear();
3096
3795
  }
3097
3796
 
3797
+ const freezeRunRefs = (refs: ExecutorConfig["integrationChecks"]): ExecutorConfig["integrationChecks"] =>
3798
+ refs === "auto" ? refs : (Object.freeze(refs.map((ref) => Object.freeze({ script: ref.script, args: Object.freeze([...ref.args]) }))) as unknown as RunCommandRef[]);
3799
+
3800
+ /**
3801
+ * `routing.executor` with the defaults applied: deeply frozen, never aliasing the config. An invalid
3802
+ * value warns once per process (like `background`) and its default applies. `undefined` = all defaults.
3803
+ */
3804
+ function resolveExecutor(
3805
+ raw: ExecutorOverrides | undefined,
3806
+ logger: Pick<PluginLogger, "warn"> | undefined,
3807
+ ): Readonly<ExecutorConfig> {
3808
+ const d = ROUTING_DEFAULTS.executor;
3809
+ const sanitized = sanitizeExecutor(raw);
3810
+ // QA-62C-2: off Windows the executor is inert (G-16): invalid values still fall back to their defaults, silently.
3811
+ for (const issue of executorPlatformSupported() ? sanitized.issues : []) {
3812
+ if (warnedRoutingIssues.has(issue)) continue;
3813
+ warnedRoutingIssues.add(issue);
3814
+ if (logger) logger.warn(issue);
3815
+ else console.warn(`[model-router] ${issue}`);
3816
+ }
3817
+ const e = sanitized.value ?? {};
3818
+ const provision = e.provision ?? d.provision;
3819
+ const phaseSuite = e.phaseSuite ?? d.phaseSuite;
3820
+ return Object.freeze({
3821
+ maxParallel: e.maxParallel ?? d.maxParallel,
3822
+ slotsDir: e.slotsDir ?? d.slotsDir,
3823
+ approve: e.approve ?? d.approve,
3824
+ crossPhase: e.crossPhase ?? d.crossPhase,
3825
+ land: e.land ?? d.land,
3826
+ batchMax: e.batchMax ?? d.batchMax,
3827
+ maxAttempts: e.maxAttempts ?? d.maxAttempts,
3828
+ qaMaxRounds: e.qaMaxRounds ?? d.qaMaxRounds,
3829
+ integrationChecks: freezeRunRefs(e.integrationChecks ?? d.integrationChecks),
3830
+ phaseSuite: phaseSuite === "off" ? phaseSuite : freezeRunRefs(phaseSuite),
3831
+ provision:
3832
+ provision === "auto"
3833
+ ? provision
3834
+ : (Object.freeze(
3835
+ Object.fromEntries(
3836
+ Object.entries(provision).map(([manager, argvs]) => [
3837
+ manager,
3838
+ Object.freeze(argvs.map((argv) => Object.freeze([...argv]))),
3839
+ ]),
3840
+ ),
3841
+ ) as unknown as Record<string, string[][]>),
3842
+ python: e.python ?? d.python,
3843
+ sharedContextChars: e.sharedContextChars ?? d.sharedContextChars,
3844
+ capacityCooldownMs: e.capacityCooldownMs ?? d.capacityCooldownMs,
3845
+ capacityPauseMs: e.capacityPauseMs ?? d.capacityPauseMs,
3846
+ wakeDebounceMs: e.wakeDebounceMs ?? d.wakeDebounceMs,
3847
+ circuitBreaker: Object.freeze({
3848
+ failureRatio: e.circuitBreaker?.failureRatio ?? d.circuitBreaker.failureRatio,
3849
+ minAttempts: e.circuitBreaker?.minAttempts ?? d.circuitBreaker.minAttempts,
3850
+ consecutiveFailures: e.circuitBreaker?.consecutiveFailures ?? d.circuitBreaker.consecutiveFailures,
3851
+ }),
3852
+ });
3853
+ }
3854
+
3098
3855
  /** Roles as fresh, de-duplicated, frozen arrays; never aliases the config. */
3099
3856
  function freezeRoles(
3100
3857
  roles: Readonly<Record<string, readonly string[]>>,
@@ -3132,6 +3889,22 @@ export function resolveRouting(
3132
3889
  else console.warn(`[model-router] ${ROUTING_ENGINE_IGNORED_ON_V1}`);
3133
3890
  }
3134
3891
 
3892
+ // routing.background / routing.leases: an invalid value warns once and the default applies.
3893
+ const sanitizedBackground = sanitizeBackground(r.background);
3894
+ const sanitizedLeases = sanitizeLeases(r.leases);
3895
+ const sanitizedOrphans = sanitizeOrphans(host === "v2" ? r.orphans : undefined);
3896
+ const background = sanitizedBackground.value;
3897
+ const leases = sanitizedLeases.value;
3898
+ for (const issue of [...sanitizedBackground.issues, ...sanitizedLeases.issues, ...sanitizedOrphans.issues]) {
3899
+ if (warnedRoutingIssues.has(issue)) continue;
3900
+ warnedRoutingIssues.add(issue);
3901
+ if (logger) logger.warn(issue);
3902
+ else console.warn(`[model-router] ${issue}`);
3903
+ }
3904
+
3905
+ // routing.executor: v2 only. On v1 the block is ignored (one notice names the configured keys).
3906
+ const executor = resolveExecutor(host === "v2" ? r.executor : undefined, host === "v2" ? logger : undefined);
3907
+
3135
3908
  const c: ClassifierConfig = r.classifier ?? {};
3136
3909
  const presets: Record<string, Readonly<ClassifierPresetOverride>> = {};
3137
3910
  for (const [name, override] of Object.entries(c.presets ?? {})) {
@@ -3176,6 +3949,16 @@ export function resolveRouting(
3176
3949
  noticeIntervalHours: r.advisor?.noticeIntervalHours ?? d.advisor.noticeIntervalHours,
3177
3950
  notify: r.advisor?.notify ?? d.advisor.notify,
3178
3951
  }),
3952
+ background: Object.freeze({
3953
+ mode: background?.mode ?? d.background.mode,
3954
+ minPredictedMs: background?.minPredictedMs ?? d.background.minPredictedMs,
3955
+ }),
3956
+ leases: Object.freeze({
3957
+ mode: leases?.mode ?? d.leases.mode,
3958
+ run: leases?.run ?? d.leases.run,
3959
+ }),
3960
+ orphans: Object.freeze({ resume: sanitizedOrphans.value?.resume ?? d.orphans.resume }),
3961
+ executor,
3179
3962
  applied: Object.freeze({ host, requestedEngine, engineCoerced, rolesSource }),
3180
3963
  });
3181
3964
  }
@@ -3183,9 +3966,16 @@ export function resolveRouting(
3183
3966
  /** The roles keys with their defaults applied, for one host (#84). Never mutates `cfg`. */
3184
3967
  export interface ResolvedRolesRouting {
3185
3968
  readonly delegation: DelegationMode;
3969
+ readonly roleFloor: RoleFloorMode;
3186
3970
  readonly exploration: Readonly<ExplorationConfig>;
3187
3971
  readonly run: Readonly<RunConfig>;
3188
3972
  readonly workRoots: readonly string[];
3973
+ /** Cross-repo (Phase 1): admissible repositories lie 1..repoDepth levels below these directories. */
3974
+ readonly repoParents: readonly string[];
3975
+ readonly repoDepth: number;
3976
+ readonly repoExclude: readonly string[];
3977
+ /** Cross-repo (Phase 4): days an approval outside the parents lasts after its last use (1–90, default 14). */
3978
+ readonly repoApprovalDays: number;
3189
3979
  /** True on v1 when roles keys were set: they are validated but have no effect. */
3190
3980
  readonly inert: boolean;
3191
3981
  }
@@ -3198,9 +3988,9 @@ export function resetRolesWarnings(): void {
3198
3988
  }
3199
3989
 
3200
3990
  /**
3201
- * Defaults for `routing.delegation`, `exploration`, `run` and `workRoots`. On v1 (`routerHost`
3991
+ * Defaults for `routing.delegation`, `roleFloor`, `exploration`, `run` and `workRoots`. On v1 (`routerHost`
3202
3992
  * `v1`) delegation is always `tiers`, and one notice says so when any of delegation `roles`,
3203
- * `roleAgents`, `exploration`, `run` or `workRoots` was set. Exploration is off (rate 0) unless
3993
+ * `roleAgents`, `roleFloor`, `exploration`, `run` or `workRoots` was set. Exploration is off (rate 0) unless
3204
3994
  * the effective delegation is `roles`. Switching `delegation` is only a config value here;
3205
3995
  * registration follows a hot reload elsewhere. The plugin logs the v1 notice at start-up by
3206
3996
  * calling this with its logger next to `resolveRouting` (wired with the roles runtime, #84 P2.1).
@@ -3213,7 +4003,9 @@ export function resolveRolesRouting(
3213
4003
  const r: RoutingConfig = cfg?.routing ?? {};
3214
4004
  const requested = r.delegation ?? "tiers";
3215
4005
  const touched = requested === "roles" || cfg?.roleAgents !== undefined || r.exploration !== undefined
3216
- || r.run !== undefined || r.workRoots !== undefined;
4006
+ || r.run !== undefined || r.workRoots !== undefined
4007
+ || r.repoParents !== undefined || r.repoDepth !== undefined || r.repoExclude !== undefined
4008
+ || r.repoApprovalDays !== undefined || r.roleFloor !== undefined;
3217
4009
  const inert = host === "v1" && touched;
3218
4010
  if (inert && !warnedRolesInertOnV1) {
3219
4011
  warnedRolesInertOnV1 = true;
@@ -3223,6 +4015,7 @@ export function resolveRolesRouting(
3223
4015
  const delegation: DelegationMode = host === "v1" ? "tiers" : requested;
3224
4016
  return Object.freeze({
3225
4017
  delegation,
4018
+ roleFloor: host === "v1" ? "strict" : (r.roleFloor ?? "strict"),
3226
4019
  exploration: Object.freeze({
3227
4020
  rate: delegation === "roles" ? (r.exploration?.rate ?? 0) : 0,
3228
4021
  requireDetection: "deterministic" as const,
@@ -3233,6 +4026,10 @@ export function resolveRolesRouting(
3233
4026
  timeoutMs: r.run?.timeoutMs ?? DEFAULT_RUN_TIMEOUT_MS,
3234
4027
  }),
3235
4028
  workRoots: Object.freeze([...(r.workRoots ?? [])]),
4029
+ repoParents: Object.freeze([...(r.repoParents ?? [])]),
4030
+ repoDepth: r.repoDepth ?? DEFAULT_REPO_DEPTH,
4031
+ repoExclude: Object.freeze([...(r.repoExclude ?? [])]),
4032
+ repoApprovalDays: r.repoApprovalDays ?? DEFAULT_REPO_APPROVAL_DAYS,
3236
4033
  inert,
3237
4034
  });
3238
4035
  }