opencode-model-router 2.8.0 → 2.9.1

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 (91) hide show
  1. package/CHANGELOG.md +372 -0
  2. package/README.md +22 -2
  3. package/package.json +5 -1
  4. package/src/commands/output.ts +23 -1
  5. package/src/compat/background.ts +2439 -0
  6. package/src/compat/child-session.ts +6 -0
  7. package/src/compat/turn-state.ts +215 -0
  8. package/src/compat/v2-client.ts +136 -17
  9. package/src/compat/v2-hooks.ts +2656 -114
  10. package/src/compat/v2-observations.ts +328 -0
  11. package/src/executor/capacity.ts +362 -0
  12. package/src/executor/child-guards.ts +40 -0
  13. package/src/executor/command.ts +265 -0
  14. package/src/executor/compile/edges.ts +809 -0
  15. package/src/executor/compile/estimate.ts +158 -0
  16. package/src/executor/compile/footprint.ts +829 -0
  17. package/src/executor/compile/index.ts +1080 -0
  18. package/src/executor/compile/parse.ts +1492 -0
  19. package/src/executor/compile/residue.ts +706 -0
  20. package/src/executor/compile/validate.ts +280 -0
  21. package/src/executor/create.ts +672 -0
  22. package/src/executor/expand.ts +551 -0
  23. package/src/executor/git.ts +1214 -0
  24. package/src/executor/host-preamble.ts +17 -0
  25. package/src/executor/instructions.ts +35 -0
  26. package/src/executor/integrate/bisect.ts +73 -0
  27. package/src/executor/integrate/checks.ts +1086 -0
  28. package/src/executor/integrate/land.ts +177 -0
  29. package/src/executor/integrate/phase-suite.ts +407 -0
  30. package/src/executor/integrate/queue.ts +3083 -0
  31. package/src/executor/integrate/run-resolver.ts +19 -0
  32. package/src/executor/launch.ts +652 -0
  33. package/src/executor/ledger.ts +2208 -0
  34. package/src/executor/observations.ts +212 -0
  35. package/src/executor/paths.ts +159 -0
  36. package/src/executor/platform.ts +39 -0
  37. package/src/executor/process-identity.ts +19 -0
  38. package/src/executor/qa-loop.ts +470 -0
  39. package/src/executor/recovery.ts +403 -0
  40. package/src/executor/runtime.ts +6233 -0
  41. package/src/executor/schedule.ts +246 -0
  42. package/src/executor/slots/env.ts +145 -0
  43. package/src/executor/slots/pool.ts +1564 -0
  44. package/src/executor/slots/provision.ts +853 -0
  45. package/src/executor/tool.ts +534 -0
  46. package/src/executor/types.ts +2064 -0
  47. package/src/executor/unattended.ts +488 -0
  48. package/src/guard/store.ts +3 -1
  49. package/src/index.ts +1498 -288
  50. package/src/router/config.ts +776 -25
  51. package/src/router/git-tools.ts +106 -15
  52. package/src/router/leases.ts +1469 -0
  53. package/src/router/logger.ts +44 -32
  54. package/src/router/protocol.ts +40 -10
  55. package/src/router/role-agents.ts +224 -17
  56. package/src/router/roles-config.ts +10 -1
  57. package/src/router/roles.ts +1 -1
  58. package/src/router/run-tools.ts +56 -4
  59. package/src/router/tool-paths.ts +308 -0
  60. package/src/router/work-roots.ts +86 -0
  61. package/src/routing/advisor/findings.ts +25 -5
  62. package/src/routing/classify/index.ts +7 -1
  63. package/src/routing/classify/rules.ts +11 -0
  64. package/src/routing/commands/stats.ts +2 -2
  65. package/src/routing/outcomes/durations.ts +225 -0
  66. package/src/routing/outcomes/index.ts +59 -2
  67. package/src/routing/outcomes/persist.ts +409 -0
  68. package/src/routing/outcomes/stats.ts +170 -11
  69. package/src/routing/outcomes/timings.ts +836 -0
  70. package/src/routing/outcomes/types.ts +98 -0
  71. package/src/routing/roles/approvals.ts +86 -5
  72. package/src/routing/roles/binding.ts +99 -9
  73. package/src/routing/roles/orphans.ts +68 -0
  74. package/src/routing/roles/policy.ts +21 -3
  75. package/src/routing/roles/work-root.ts +3 -1
  76. package/src/routing/wire/dispatch.ts +86 -12
  77. package/src/routing/wire/hint.ts +56 -8
  78. package/src/v2.ts +94 -49
  79. package/src/verify/branch.ts +8 -2
  80. package/src/verify/canonical-path.ts +35 -0
  81. package/src/verify/deterministic.ts +38 -9
  82. package/src/verify/dispatch.ts +64 -28
  83. package/src/verify/exec.ts +52 -9
  84. package/src/verify/pending.ts +1691 -10
  85. package/src/verify/perimeter.ts +12 -6
  86. package/src/verify/plan-task.ts +729 -0
  87. package/src/verify/reference.ts +216 -3
  88. package/src/verify/tree.ts +30 -13
  89. package/src/verify/types.ts +9 -2
  90. package/src/verify/wiring.ts +290 -31
  91. package/tiers.json +5 -5
@@ -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";
@@ -315,7 +317,45 @@ export interface AdvisorConfig {
315
317
  notify?: boolean;
316
318
  }
317
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
+
318
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;
319
359
  engine?: RoutingEngine;
320
360
  profile?: RoutingProfile;
321
361
  margin?: number;
@@ -329,6 +369,8 @@ export interface RoutingConfig {
329
369
  advisor?: AdvisorConfig;
330
370
  /** `tiers` (default) or `roles`; global and project layers. Inert on v1. */
331
371
  delegation?: DelegationMode;
372
+ /** Global only. Authority floor policy; default strict. Inert on v1. */
373
+ roleFloor?: RoleFloorMode;
332
374
  /** Global only. `rate` 0..0.2, default 0; `requireDetection` is fixed. Inert on v1. */
333
375
  exploration?: Partial<ExplorationConfig>;
334
376
  /** Global only. `router_run` allow-list. Inert on v1. */
@@ -519,6 +561,16 @@ function normalizeProjectDir(dir?: string): string {
519
561
  export interface ConfigNotice {
520
562
  source?: string;
521
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;
522
574
  }
523
575
 
524
576
  /**
@@ -527,7 +579,8 @@ export interface ConfigNotice {
527
579
  * the like. Empty when there are none. `/router` lists them.
528
580
  */
529
581
  export function getConfigNotices(dir?: string): readonly ConfigNotice[] {
530
- 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;
531
584
  }
532
585
 
533
586
  /**
@@ -1773,6 +1826,358 @@ function validateRoles(routing: Record<string, unknown>): Record<string, string[
1773
1826
  return out;
1774
1827
  }
1775
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
+
1776
2181
  /**
1777
2182
  * Validate `routing` and return a snapshot of the validated values (or
1778
2183
  * `undefined` when absent). Defaults are NOT applied here; see resolveRouting.
@@ -1826,6 +2231,8 @@ function validateRouting(value: unknown): RoutingConfig | undefined {
1826
2231
  // Roles keys (#84): tolerant per entry, never throw (see roles-config.ts).
1827
2232
  const delegation = sanitizeDelegation(routing.delegation).value;
1828
2233
  if (delegation !== undefined) out.delegation = delegation;
2234
+ const roleFloor = sanitizeRoleFloor(routing.roleFloor).value;
2235
+ if (roleFloor !== undefined) out.roleFloor = roleFloor;
1829
2236
  const exploration = sanitizeExploration(routing.exploration).value;
1830
2237
  if (exploration !== undefined) out.exploration = exploration;
1831
2238
  const run = sanitizeRun(routing.run).value;
@@ -1841,6 +2248,16 @@ function validateRouting(value: unknown): RoutingConfig | undefined {
1841
2248
  const repoApprovalDays = sanitizeRepoApprovalDays(routing.repoApprovalDays).value;
1842
2249
  if (repoApprovalDays !== undefined) out.repoApprovalDays = repoApprovalDays;
1843
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;
2260
+
1844
2261
  const outcomes = readBlock(routing, "outcomes", "routing");
1845
2262
  if (outcomes !== undefined) {
1846
2263
  const o: OutcomesConfig = {};
@@ -2227,10 +2644,18 @@ const GLOBAL_ONLY_ROUTING_KEYS: ReadonlyArray<readonly [block: string, key: stri
2227
2644
  ["classifier", "apiKeyEnv"],
2228
2645
  ["classifier", "presets"],
2229
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"],
2230
2654
  ];
2231
2655
 
2232
2656
  /** Roles keys (#84) a project layer must not carry; `routing.delegation` is allowed there. */
2233
2657
  const GLOBAL_ONLY_ROLES_ROUTING_KEYS = [
2658
+ "roleFloor",
2234
2659
  "exploration",
2235
2660
  "run",
2236
2661
  "workRoots",
@@ -2259,12 +2684,24 @@ function stripGlobalOnlyRolesKeys(data: Record<string, unknown>): string[] {
2259
2684
  return dropped;
2260
2685
  }
2261
2686
 
2262
- /** 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
+ */
2263
2691
  function stripGlobalOnlyRoutingKeys(data: Record<string, unknown>): string[] {
2264
2692
  const routing = data.routing;
2265
2693
  if (!isPlainObject(routing)) return [];
2266
2694
  const dropped: string[] = [];
2267
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
+ }
2268
2705
  for (const [block, key] of GLOBAL_ONLY_ROUTING_KEYS) {
2269
2706
  const target = routing[block];
2270
2707
  if (isPlainObject(target) && Object.hasOwn(target, key)) {
@@ -2302,11 +2739,12 @@ function collectOverrideLayers(
2302
2739
  if (!data) continue;
2303
2740
  if (project) {
2304
2741
  const dropped = stripGlobalOnlyRoutingKeys(data);
2305
- if (dropped.length > 0) {
2306
- notices?.push({
2307
- source: p,
2308
- message: `ignoring ${dropped.join(", ")} from ${p}: only the global override may set it`,
2309
- });
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 });
2310
2748
  }
2311
2749
  // #84: a repository may pick `routing.delegation`, but not customise role agents, grant
2312
2750
  // exploration, define `router_run` commands or widen the work roots.
@@ -2335,6 +2773,18 @@ function collectOverrideLayers(
2335
2773
  /** The notices of the build that produced each config object (the cache hands the same object back until a reload). */
2336
2774
  const noticesByConfig = new WeakMap<RouterConfig, readonly ConfigNotice[]>();
2337
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
+
2338
2788
  /** Notice texts already logged in this process (bounded); see {@link warnConfigNotices}. */
2339
2789
  const loggedNoticeTexts = new Set<string>();
2340
2790
 
@@ -2352,6 +2802,7 @@ export function warnConfigNotices(
2352
2802
  ): void {
2353
2803
  if (cfg === undefined) return;
2354
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
2355
2806
  if (loggedNoticeTexts.has(notice.message)) continue;
2356
2807
  if (loggedNoticeTexts.size >= 256) loggedNoticeTexts.clear();
2357
2808
  loggedNoticeTexts.add(notice.message);
@@ -2539,6 +2990,7 @@ const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
2539
2990
  "sessionReuse",
2540
2991
  "advisor",
2541
2992
  "delegation",
2993
+ "roleFloor",
2542
2994
  "exploration",
2543
2995
  "run",
2544
2996
  "workRoots",
@@ -2546,7 +2998,34 @@ const ROUTING_KNOWN_KEYS: Readonly<Record<string, readonly string[]>> = {
2546
2998
  "repoDepth",
2547
2999
  "repoExclude",
2548
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",
2549
3027
  ],
3028
+ circuitBreaker: ["failureRatio", "minAttempts", "consecutiveFailures"],
2550
3029
  detection: ["deterministic", "grader", "none"],
2551
3030
  classifier: ["backend", "model", "baseUrl", "apiKeyEnv", "timeoutMs", "samples", "maxStateChars", "presets"],
2552
3031
  preset: ["backend", "model"],
@@ -2569,10 +3048,17 @@ export function findUnknownRoutingKeys(routing: unknown): string[] {
2569
3048
  }
2570
3049
  };
2571
3050
  check(routing, ROUTING_KNOWN_KEYS.routing!, "routing");
2572
- 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) {
2573
3052
  const value = routing[block];
2574
3053
  if (isPlainObject(value)) check(value, ROUTING_KNOWN_KEYS[block]!, `routing.${block}`);
2575
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
+ }
2576
3062
  const classifier = routing.classifier;
2577
3063
  const presets = isPlainObject(classifier) ? classifier.presets : undefined;
2578
3064
  if (isPlainObject(presets)) {
@@ -2599,10 +3085,38 @@ export const ROUTING_RESERVED_AGENTS = ["build", "plan", "title", "summary", "co
2599
3085
  * validated config.
2600
3086
  */
2601
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 }> = [];
2602
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}.`));
2603
3104
  const unknown = findUnknownRoutingKeys(rawRouting);
2604
- if (unknown.length > 0) {
2605
- 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
+ }
2606
3120
  }
2607
3121
  for (const [taskClass, agents] of Object.entries(cfg.routing?.roles ?? {})) {
2608
3122
  for (const agent of agents) {
@@ -2630,7 +3144,7 @@ export function collectRoutingNotices(rawRouting: unknown, cfg: RouterConfig): s
2630
3144
  );
2631
3145
  }
2632
3146
  }
2633
- return messages;
3147
+ return [...tagged, ...messages.map((message) => ({ message, v2Only: false }))];
2634
3148
  }
2635
3149
  /**
2636
3150
  * `routing.roles` is replaced wholesale by the highest-priority layer that sets
@@ -2649,10 +3163,113 @@ function replaceRolesWholesale(merged: unknown, layers: readonly OverrideLayer[]
2649
3163
  return merged;
2650
3164
  }
2651
3165
 
2652
- /** 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. */
2653
3257
  function mergeOverrideLayer(lower: unknown, layer: OverrideLayer, notices: ConfigNotice[]): unknown {
2654
3258
  const merged = deepMerge(lower, layer.data);
2655
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;
2656
3273
  const classifier = merged.routing.classifier;
2657
3274
  const projectRouting = layer.data.routing;
2658
3275
  const projectClassifier = isPlainObject(projectRouting) ? projectRouting.classifier : undefined;
@@ -2697,21 +3314,27 @@ function buildConfig(
2697
3314
  let rawUsed: unknown = base;
2698
3315
 
2699
3316
  if (layers.length > 0) {
2700
- 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 =>
2701
3320
  replaceRolesWholesale(
2702
- ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, notices), base),
3321
+ ls.reduce<unknown>((acc, l) => mergeOverrideLayer(acc, l, attemptNotices), base),
2703
3322
  ls,
2704
3323
  );
2705
3324
 
2706
3325
  try {
2707
- const merged = merge(layers);
3326
+ const attemptNotices: ConfigNotice[] = [];
3327
+ const merged = merge(layers, attemptNotices);
2708
3328
  cfg = validateConfig(merged);
2709
3329
  rawUsed = merged;
3330
+ notices.push(...attemptNotices);
2710
3331
  } catch (err) {
2711
3332
  // A bad override must never brick startup, and one broken file must not
2712
- // discard a good one. Fall back to the highest-priority layer that
2713
- // validates on its own (so a broken personal/global file still lets a
2714
- // 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.
2715
3338
  console.warn(
2716
3339
  `[model-router] combined overrides are invalid (${(err as Error).message}); dropping conflicting layer(s)`,
2717
3340
  );
@@ -2720,11 +3343,17 @@ function buildConfig(
2720
3343
  source: layerPaths,
2721
3344
  message: `${layerPaths}: combined overrides are invalid — ${(err as Error).message}`,
2722
3345
  });
2723
- 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) {
2724
3351
  try {
2725
- const single = merge([layers[i]!]);
3352
+ const attemptNotices: ConfigNotice[] = [];
3353
+ const single = merge([layers[i]!], attemptNotices);
2726
3354
  cfg = validateConfig(single);
2727
3355
  rawUsed = single;
3356
+ notices.push(...attemptNotices);
2728
3357
  for (let j = 0; j < layers.length; j++) {
2729
3358
  if (j !== i) {
2730
3359
  console.warn(`[model-router] dropped override layer ${layers[j]!.path}`);
@@ -2789,12 +3418,17 @@ function buildConfig(
2789
3418
 
2790
3419
  applyTierDefaults(cfg);
2791
3420
  const rawRouting = isPlainObject(rawUsed) ? rawUsed.routing : undefined;
2792
- 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
+ }
2793
3426
  const rawRoleAgents = isPlainObject(rawUsed) ? rawUsed.roleAgents : undefined;
2794
3427
  for (const issue of collectRolesIssues(rawRouting, rawRoleAgents)) notices.push({ message: issue.message });
2795
3428
  dropIgnoredCandidates(cfg);
2796
3429
  applyPluginAgents(cfg, layers, notices);
2797
3430
  applyRoleNotices(cfg, notices);
3431
+ rawByConfig.set(cfg, rawUsed);
2798
3432
  return cfg;
2799
3433
  }
2800
3434
 
@@ -3073,6 +3707,30 @@ export const ROUTING_DEFAULTS = Object.freeze({
3073
3707
  outcomes: Object.freeze({ path: null, halfLifeDays: 14, maxEffectiveSamples: 50 }),
3074
3708
  sessionReuse: Object.freeze({ maxContextFraction: 0.6 }),
3075
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
+ }),
3076
3734
  });
3077
3735
 
3078
3736
  export interface ResolvedClassifier {
@@ -3111,6 +3769,11 @@ export interface ResolvedRouting {
3111
3769
  readonly outcomes: Readonly<{ path: string | null; halfLifeDays: number; maxEffectiveSamples: number }>;
3112
3770
  readonly sessionReuse: Readonly<Required<SessionReuseConfig>>;
3113
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>;
3114
3777
  readonly applied: RoutingApplied;
3115
3778
  }
3116
3779
 
@@ -3122,13 +3785,73 @@ function expandHomePath(value: string | null): string | null {
3122
3785
  }
3123
3786
 
3124
3787
  let warnedEngineIgnoredOnV1 = false;
3788
+ const warnedRoutingIssues = new Set<string>();
3125
3789
 
3126
3790
  /** Test-only: re-arm the once-per-process "engine ignored on v1" notice. */
3127
3791
  export function resetRoutingWarnings(): void {
3128
3792
  warnedEngineIgnoredOnV1 = false;
3793
+ warnedRoutingIssues.clear();
3129
3794
  loggedNoticeTexts.clear();
3130
3795
  }
3131
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
+
3132
3855
  /** Roles as fresh, de-duplicated, frozen arrays; never aliases the config. */
3133
3856
  function freezeRoles(
3134
3857
  roles: Readonly<Record<string, readonly string[]>>,
@@ -3166,6 +3889,22 @@ export function resolveRouting(
3166
3889
  else console.warn(`[model-router] ${ROUTING_ENGINE_IGNORED_ON_V1}`);
3167
3890
  }
3168
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
+
3169
3908
  const c: ClassifierConfig = r.classifier ?? {};
3170
3909
  const presets: Record<string, Readonly<ClassifierPresetOverride>> = {};
3171
3910
  for (const [name, override] of Object.entries(c.presets ?? {})) {
@@ -3210,6 +3949,16 @@ export function resolveRouting(
3210
3949
  noticeIntervalHours: r.advisor?.noticeIntervalHours ?? d.advisor.noticeIntervalHours,
3211
3950
  notify: r.advisor?.notify ?? d.advisor.notify,
3212
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,
3213
3962
  applied: Object.freeze({ host, requestedEngine, engineCoerced, rolesSource }),
3214
3963
  });
3215
3964
  }
@@ -3217,6 +3966,7 @@ export function resolveRouting(
3217
3966
  /** The roles keys with their defaults applied, for one host (#84). Never mutates `cfg`. */
3218
3967
  export interface ResolvedRolesRouting {
3219
3968
  readonly delegation: DelegationMode;
3969
+ readonly roleFloor: RoleFloorMode;
3220
3970
  readonly exploration: Readonly<ExplorationConfig>;
3221
3971
  readonly run: Readonly<RunConfig>;
3222
3972
  readonly workRoots: readonly string[];
@@ -3238,9 +3988,9 @@ export function resetRolesWarnings(): void {
3238
3988
  }
3239
3989
 
3240
3990
  /**
3241
- * Defaults for `routing.delegation`, `exploration`, `run` and `workRoots`. On v1 (`routerHost`
3991
+ * Defaults for `routing.delegation`, `roleFloor`, `exploration`, `run` and `workRoots`. On v1 (`routerHost`
3242
3992
  * `v1`) delegation is always `tiers`, and one notice says so when any of delegation `roles`,
3243
- * `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
3244
3994
  * the effective delegation is `roles`. Switching `delegation` is only a config value here;
3245
3995
  * registration follows a hot reload elsewhere. The plugin logs the v1 notice at start-up by
3246
3996
  * calling this with its logger next to `resolveRouting` (wired with the roles runtime, #84 P2.1).
@@ -3255,7 +4005,7 @@ export function resolveRolesRouting(
3255
4005
  const touched = requested === "roles" || cfg?.roleAgents !== undefined || r.exploration !== undefined
3256
4006
  || r.run !== undefined || r.workRoots !== undefined
3257
4007
  || r.repoParents !== undefined || r.repoDepth !== undefined || r.repoExclude !== undefined
3258
- || r.repoApprovalDays !== undefined;
4008
+ || r.repoApprovalDays !== undefined || r.roleFloor !== undefined;
3259
4009
  const inert = host === "v1" && touched;
3260
4010
  if (inert && !warnedRolesInertOnV1) {
3261
4011
  warnedRolesInertOnV1 = true;
@@ -3265,6 +4015,7 @@ export function resolveRolesRouting(
3265
4015
  const delegation: DelegationMode = host === "v1" ? "tiers" : requested;
3266
4016
  return Object.freeze({
3267
4017
  delegation,
4018
+ roleFloor: host === "v1" ? "strict" : (r.roleFloor ?? "strict"),
3268
4019
  exploration: Object.freeze({
3269
4020
  rate: delegation === "roles" ? (r.exploration?.rate ?? 0) : 0,
3270
4021
  requireDetection: "deterministic" as const,