From ce129935e85fc11f44eb655e0b55b7b8a8440518 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Fri, 13 Nov 2026 02:34:47 -0600 Subject: [PATCH] Class fallback chains: second-pass escalation to specialist, guarded Drew 2026-11-13 (final edges + pinned semantics). Edges wired as the final targets of each class route: small -> speed; speed -> workhorse, summit, specialist; workhorse -> scout, specialist (scout first per main recommendation - failure mode is quota exhaustion, scout diversifies doors); summit -> specialist; specialist = sink; scout -> workhorse and background -> workhorse as marked PROPOSALS. Semantics: regular chain first and completely, fallback as second pass on exhaustion only, walked transitively under a per-call visited set (fork route expander prunes re-entry into a route already on the expansion path; exhausted subtrees resume the caller remaining edges), terminating at specialist. Guard extended: declared-chain drift check, sink reachability, simulated escalation walk, whole-graph composition cycle check excluding declared fallback pairs; tier resolver no longer reports declared fallback re-entries as cycles. Full per-route layout: .opencode/route-fallbacks.md (all 34 routes). No restart - rides the coordinated switch. --- .opencode/opencode.jsonc | 84 +++++++++++- .opencode/route-fallbacks.md | 93 +++++++++++++ bin/check-opencode-route-rules.mjs | 172 +++++++++++++++++++++++- bin/check-opencode-route-rules.test.mjs | 64 +++++++++ 4 files changed, 406 insertions(+), 7 deletions(-) create mode 100644 .opencode/route-fallbacks.md diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index d7b5c0e08a..be330e0859 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -2819,6 +2819,18 @@ }, "scout": { "name": "Scout - routine work: cheapest, fastest, smart enough", + // Class fallback (Drew 2026-11-13): on exhaustion this class + // escalates to the route(s) appended at the END of its targets. + // Per-call visited-set semantics: the route expander prunes + // re-entry into a route already on the expansion path, so + // escalation never re-enters a tried class and always + // terminates at specialist, the sink. Full layout: + // .opencode/route-fallbacks.md; guard: + // bin/check-opencode-route-rules.mjs (CLASS_FALLBACKS). + // Scout's own edge (workhorse) is a PROPOSAL (Drew has not + // ruled on scout yet, 2026-11-13): routine work that + // exhausts the free/cheap seats escalates to the standard + // tier rather than erroring. // 2026-11-11 (Drew, direct order): ordered selection, haiku-plan leg LAST (last resort). // 2026-11-11 (Drew): scout order — Beam ahead of DeepSeek Flash. // 2026-10-26 (pool remap review): all three routes addressed at #low — the rung every @@ -2838,13 +2850,26 @@ "targets": [ "opencode-route/beam-plan", "opencode-route/deepseek-flash-plan#low", - "opencode-route/haiku-plan#low" + "opencode-route/haiku-plan#low", + "opencode-route/workhorse" ], "selection": "ordered", "autonomy": "rules" }, "background": { "name": "Background - patient queue work: best value first, no latency contract", + // Class fallback (Drew 2026-11-13): on exhaustion this class + // escalates to the route(s) appended at the END of its targets. + // Per-call visited-set semantics: the route expander prunes + // re-entry into a route already on the expansion path, so + // escalation never re-enters a tried class and always + // terminates at specialist, the sink. Full layout: + // .opencode/route-fallbacks.md; guard: + // bin/check-opencode-route-rules.mjs (CLASS_FALLBACKS). + // Background's own edge (workhorse) is a PROPOSAL (Drew + // has not ruled on background yet, 2026-11-13): patient + // queue work that exhausts the value seats escalates to + // the standard tier rather than erroring. // NEW 2026-10-27 (pool redesign): the tier for machinery-dispatched // work no human watches — repo sweeps, issue-queue workers, // stewardship cycles, batch classification. Ordered chain in value @@ -2897,7 +2922,8 @@ "model": "opencode-route/deepseek-flash-plan#high", "window": "deepseek-peak-early" }, - "opencode-route/mimo-flash-plan" + "opencode-route/mimo-flash-plan", + "opencode-route/workhorse" ], "selection": "ordered", "autonomy": "rules" @@ -3110,6 +3136,21 @@ }, "workhorse": { "name": "Workhorse - standard work: Flash primary, weighted relief pool behind it, Fable #low last resort if all else is down", + // Class fallback (Drew 2026-11-13): on exhaustion this class + // escalates to the route(s) appended at the END of its targets. + // Per-call visited-set semantics: the route expander prunes + // re-entry into a route already on the expansion path, so + // escalation never re-enters a tried class and always + // terminates at specialist, the sink. Full layout: + // .opencode/route-fallbacks.md; guard: + // bin/check-opencode-route-rules.mjs (CLASS_FALLBACKS). + // Workhorse's chain: scout FIRST (its failure mode is + // quota exhaustion; scout diversifies onto different + // doors - free Beam via CommandCode, DeepSeek #low, + // Haiku #low), then specialist (the sink). Reached FROM + // speed or scout, the visited-set pruning skips the + // scout edge's re-entry and the call lands on + // specialist. // 2026-10-27 pool redesign (Drew's structure): incremental — // DeepSeek Flash #high is the primary every session tries first; // the weighted relief pool (workhorse-weighted) absorbs failover @@ -3145,7 +3186,9 @@ "opencode-route/workhorse-ordered", "opencode-route/workhorse-primary", "opencode-route/workhorse-weighted", - "opencode-route/workhorse-last-resort" + "opencode-route/workhorse-last-resort", + "opencode-route/scout", + "opencode-route/specialist" ], "selection": "ordered", "autonomy": "rules", @@ -3351,6 +3394,10 @@ }, "specialist": { "name": "Specialist - hard work: quality first, Fable #low head, then Claude Sonnet, Argon, Meta Spark, OpenAI", + // Class fallback (Drew 2026-11-13): specialist is the + // SINK - no class fallback out of specialist. If every + // specialist leg is down, the call errors; there is no + // cheaper class to fall back to and nothing above it. // 2026-11-10 (Drew, direct order): Fable #low (fable-plan, // _claude door) takes the HEAD of this chain. AA v5 #low // II 53.9 tops every member it now leads (the former head, @@ -3392,6 +3439,15 @@ }, "summit": { "name": "Summit - very complex design only, deliberate use: Fable #low head, then Opus, Argon, Hydrogen, Wonder, Sol", + // Class fallback (Drew 2026-11-13): on exhaustion this class + // escalates to the route(s) appended at the END of its targets. + // Per-call visited-set semantics: the route expander prunes + // re-entry into a route already on the expansion path, so + // escalation never re-enters a tried class and always + // terminates at specialist, the sink. Full layout: + // .opencode/route-fallbacks.md; guard: + // bin/check-opencode-route-rules.mjs (CLASS_FALLBACKS). + // Summit's only edge: specialist (the sink). // 2026-11-11 (Drew, direct order): fable-plan leg low -> medium. // 2026-11-10 (Drew, direct order): Fable #low (fable-plan, // _claude door) takes the HEAD of this chain. AA v5 #low @@ -3429,13 +3485,24 @@ "opencode-route/argon-plan#high", "_antigravity/gemini-4-hydrogen#high", "_muse/muse-wonder-1.0-contributor#xhigh", - "opencode-route/sol-plan#xhigh" + "opencode-route/sol-plan#xhigh", + "opencode-route/specialist" ], "selection": "ordered", "autonomy": "rules" }, "speed": { "name": "Speed - fastest seats at or above the Haiku bar, for latency-bound work", + // Class fallback (Drew 2026-11-13): on exhaustion this class + // escalates to the route(s) appended at the END of its targets. + // Per-call visited-set semantics: the route expander prunes + // re-entry into a route already on the expansion path, so + // escalation never re-enters a tried class and always + // terminates at specialist, the sink. Full layout: + // .opencode/route-fallbacks.md; guard: + // bin/check-opencode-route-rules.mjs (CLASS_FALLBACKS). + // Speed's chain: workhorse first (cheaper, more + // available), then summit, then specialist (the sink). // 2026-11-11 (Drew, direct order): ordered selection, haiku-plan leg LAST (last resort). // 2026-10-26 pass 3 (AA figures re-baselined to v5 2026-10-31, #1673): a latency pool is judged on // time-to-first-token as much as decode — Spark contributor #xhigh / TTFT 19.1s / @@ -3469,7 +3536,10 @@ "_muse/muse-spark-1.3-contributor#xhigh", "opencode-route/deepseek-flash-plan#high", "opencode-route/gemini-hydrogen-plan#high", - "opencode-route/haiku-plan#high" + "opencode-route/haiku-plan#high", + "opencode-route/workhorse", + "opencode-route/summit", + "opencode-route/specialist" ], "selection": "ordered", "autonomy": "rules" @@ -3560,7 +3630,9 @@ // 2026-10-27 from luna-haiku-100k; the pre-2026-11-13 // shape seated luna-plan#xhigh + haiku-plan#high under // a 200k route cap. - "targets": ["opencode-route/limited"], + // Class fallback (Drew 2026-11-13): small -> speed (see + // the scout route's note + route-fallbacks.md). + "targets": ["opencode-route/limited", "opencode-route/speed"], "selection": "ordered", "autonomy": "rules" } diff --git a/.opencode/route-fallbacks.md b/.opencode/route-fallbacks.md new file mode 100644 index 0000000000..e97f62e6ea --- /dev/null +++ b/.opencode/route-fallbacks.md @@ -0,0 +1,93 @@ +# Route fallback layout (Drew, 2026-11-13) + +The complete fallback layout for every route in `.opencode/opencode.jsonc`. +The class edges are wired as the FINAL targets of each class route and are +guarded by `bin/check-opencode-route-rules.mjs` (`CLASS_FALLBACKS` there must +match this table and the config; the guard fails on drift). + +## Semantics (Drew 2026-11-13) + +1. **Regular chain first.** A pool's own regular chain always runs first and + completely — ordered targets, weighted draws, and door failover inside the + *-plan pools included. Class fallback never interleaves with or + short-circuits the regular chain. +2. **Fallback is a second pass.** Fallback is a per-pool property and engages + only after that pool's full regular chain is exhausted (all legs failed or + quota-walled; a 100%-walled leg is never attempted — it counts as + exhausted immediately). The fallback class brings its own seats and + purpose. +3. **Walked down the chain, no repeats.** Entering a fallback class runs THAT + class's full regular chain first, then its own fallback if it too + exhausts — subject to a per-call visited set: a class already tried in + this call is skipped, never re-entered. The class set is finite and each + escalation consumes one, so every walk terminates at **specialist**, the + sink. (Mechanism: the fork's route expander carries the expansion path + and prunes re-entry into a route already on it, so the legal pairs + workhorse → scout / scout → workhorse cannot loop.) + +## Class routes (confirmed by Drew, except the two marked PROPOSAL) + +| Route | Regular chain (in order) | Class fallback | Why | +| --- | --- | --- | --- | +| small | limited (the per-member pool) | → speed | Light tier escalates to the latency tier. | +| speed | Spark #xhigh → deepseek-flash-plan #high → gemini-hydrogen-plan #high → haiku-plan #high | → workhorse → summit → specialist | Cheaper / more-available first, quality next, sink last. | +| workhorse | workhorse-ordered → workhorse-primary (empty stage) → workhorse-weighted → workhorse-last-resort | → scout → specialist | Workhorse's failure mode is quota exhaustion; scout diversifies onto different doors (free Beam via CommandCode, DeepSeek #low, Haiku #low). Scout-first was main's recommendation, wired 2026-11-13 pending Drew's pick. | +| summit | fable-plan #medium → opus-plan #high → argon-plan #high → Hydrogen #high (direct) → Wonder #xhigh (direct) → sol-plan #xhigh | → specialist | Confirmed: the deliberate tier falls back to the hard-work tier. | +| specialist | fable-plan #low → sonnet-plan #high → argon-plan #high → spark-plan #xhigh → sol-plan #medium | — (SINK) | No class fallback out of specialist; if every leg is down the call errors. | +| scout | beam-plan → deepseek-flash-plan #low → haiku-plan #low | → workhorse (PROPOSAL) | Drew has not ruled on scout yet (2026-11-13): routine work that exhausts the free/cheap seats escalates to the standard tier. | +| background | MiMo Flash / DeepSeek Flash #high, peak-window aware (see config) | → workhorse (PROPOSAL) | Drew has not ruled on background yet (2026-11-13): patient queue work escalates to the standard tier. | + +## Workhorse stages and trial routes (no own class edges — escalation is workhorse's) + +| Route | Targets | Fallback | +| --- | --- | --- | +| workhorse-ordered | deepseek-effort-rr | Inherits workhorse (stage 1 of its chain). | +| workhorse-primary | — (deliberately empty; contributes nothing) | Inherits workhorse (stage 2). | +| workhorse-weighted | luna-effort-rr w10, Spark contributor #high w10, Hydrogen #low w10, Sonnet 5.5 #medium (direct _antigravity) w10 | Inherits workhorse (stage 3). | +| workhorse-last-resort | Sonnet 5.5 #medium (direct _claude) → fable-plan #low | Inherits workhorse (stage 4, last before the class fallback). | +| deepseek-effort-rr | deepseek-flash-plan #high w3 / #low w1 (weighted trial, PR #9381) | Inherits workhorse via workhorse-ordered. | +| luna-effort-rr | openai-plan Luna #medium / #high (round-robin trial, PR #9018) | Inherits its consumers (workhorse-weighted). | +| limited | Luna @100k #medium → Terra @388k #low → MiMo/DeepSeek-small peak-aware → Haiku @388k #medium | Inherits small. | +| deepseek-flash | deepseek-flash-plan (pass-through wrapper) | Inherits its consumers. | + +## *-plan pools (no class edges — fallback is internal door failover) + +Class escalation is inherited from the consuming class route above; a plan +never escalates on its own. "Doors" are the providers the pool fails over +between, in the pool's selection order. + +| Pool | Doors (selection) | Note | +| --- | --- | --- | +| deepseek-flash-plan | OpenCode Go (3 workspaces) → ClinePass → OpenDesign → CommandCode → Mistral plan (round-robin) | The fleet's main DeepSeek pool. | +| deepseek-pro-plan | OpenCode Go → ClinePass → OpenDesign → CommandCode (round-robin) | Pro sibling of the flash pool. | +| luna-plan | openai-plan → OpenDesign → OpenCode Go (round-robin) | Legs present different contexts (200k vs 1.05M native). | +| terra-plan | openai-plan only (round-robin over its 2 doors) | Single-plan pool; door failover is openai-plan's. | +| sol-plan | openai-plan → OpenDesign → CommandCode (round-robin) | | +| fable-plan | _claude only | **Single door — no internal failover.** If _claude is down, consumers fall through to their next seat. | +| haiku-plan | _claude only | **Single door — no internal failover** (same fall-through). | +| sonnet-plan | _claude → Antigravity (round-robin) | | +| opus-plan | _claude → Antigravity (ordered) | | +| spark-plan | OpenCode Go → CommandCode → ClinePass → _muse (ordered) | Meta Spark across four doors. | +| argon-plan | OpenCode Go → Antigravity (round-robin) | | +| gemini-hydrogen-plan | Antigravity only | **Single door — no internal failover.** | +| beam-plan | CommandCode (beam:free) → OpenCode Go (beam-free) (round-robin) | The free-tier pool behind scout. | +| mimo-flash-plan | OpenCode Go → ClinePass → OpenDesign → CommandCode (round-robin) | | +| glm-5-3-plan | _vibe (Mistral) only | **Single door — no internal failover.** | +| glm-5-3-flash-plan | _vibe (Mistral) only | **Single door — no internal failover.** | + +## Provider routes (door sets, expanded per model) + +| Provider route | Doors | +| --- | --- | +| openai-plan | _openai.alt, _openai.main (server-side round-robin) | +| mistral-plan | _vibe, mistral | +| opencode-go-plans | opencode-go.drewrypope, opencode-go.popesdrew, opencode-go.developing-today-0 | + +## Guard + +`bin/check-opencode-route-rules.mjs` enforces: (a) each class route's targets +end with exactly its declared fallback chain (drift fails); (b) every class +can reach specialist through the fallback graph; (c) a simulated escalation +walk from every class terminates at specialist without revisiting a class; +(d) the composition graph (all route→route edges EXCEPT the declared +fallback pairs) is acyclic — a composition cycle is reported with its path. diff --git a/bin/check-opencode-route-rules.mjs b/bin/check-opencode-route-rules.mjs index 35fd072a62..d3dc968ed1 100644 --- a/bin/check-opencode-route-rules.mjs +++ b/bin/check-opencode-route-rules.mjs @@ -14,6 +14,158 @@ import { isMeteredModel } from './check-opencode-metered-providers.mjs'; export const DEFAULT_CONFIG = '.opencode/opencode.jsonc'; export const REQUIRED_TIERS = ['scout', 'workhorse', 'specialist', 'summit']; + +// Class-level fallback layout (Drew 2026-11-13; full table in +// .opencode/route-fallbacks.md). Semantics: a class route's own regular +// chain always runs first and completely; the fallback targets appended +// after it are a second pass that engages only on exhaustion, walked +// transitively under a per-call visited set (a class already tried in +// the call is never re-entered), terminating at specialist, the sink. +// The pairs workhorse->scout / scout->workhorse are therefore legal +// fallback edges, NOT cycles: the runtime route expander prunes +// re-entry into a route already on the expansion path. scout's and +// background's edges are proposals Drew has not ruled on yet +// (2026-11-13); the rest are his confirmed edges. Keep this table and +// the config in lockstep - check (a) below fails on drift. +export const CLASS_FALLBACKS = { + small: ['speed'], + speed: ['workhorse', 'summit', 'specialist'], + workhorse: ['scout', 'specialist'], + summit: ['specialist'], + specialist: [], + scout: ['workhorse'], + background: ['workhorse'], +}; +const CLASS_FALLBACK_PAIRS = new Set( + Object.entries(CLASS_FALLBACKS).flatMap(([from, targets]) => targets.map((to) => `${from}->${to}`)), +); + +function routeTargetIds(route, modelRoutes) { + if (!isObject(route) || !Array.isArray(route.targets)) return []; + const ids = []; + for (const target of route.targets) { + const reference = typeof target === 'string' ? target : isObject(target) ? target.model : null; + if (typeof reference !== 'string') continue; + const parsed = splitModelReference(reference); + if (parsed && parsed.provider === 'opencode-route' && isObject(modelRoutes?.[parsed.model])) { + ids.push(parsed.model); + } + } + return ids; +} + +function cycleKey(cyclePath) { + return [...new Set(cyclePath)].sort().join(','); +} + +// Validates the class fallback layout (checks a-c) and the static +// composition graph (check d) for a parsed model_routes map. +// fallbacks defaults to CLASS_FALLBACKS; tests pass doctored tables to +// prove the reachability/walk checks fire. reportedCycleKeys holds +// canonical keys of cycles the tier resolver already reported, so a +// composition cycle is never double-reported. +export function inspectFallbackLayout(modelRoutes, fallbacks = CLASS_FALLBACKS, reportedCycleKeys = new Set()) { + const issues = []; + if (!isObject(modelRoutes)) return issues; + const fallbackPairs = new Set( + Object.entries(fallbacks).flatMap(([from, targets]) => targets.map((to) => `${from}->${to}`)), + ); + + // (a) Config drift: when every class route exists, each class route's + // route-typed targets must END with its declared fallback chain, in + // order. Partial configs (unit fixtures) skip the layout checks. + const classes = Object.keys(fallbacks); + if (classes.every((name) => isObject(modelRoutes[name]))) { + for (const name of classes) { + const declared = fallbacks[name]; + const ids = routeTargetIds(modelRoutes[name], modelRoutes); + const tail = ids.slice(ids.length - declared.length); + if (JSON.stringify(tail) !== JSON.stringify(declared)) { + issues.push( + `fallback: route "${name}" must end with its class fallback chain [${declared.join(', ')}] as its final route targets (found route targets [${ids.join(', ')}])`, + ); + } + } + + // (b) Reachability: every class can reach specialist, the sink, + // through the fallback graph. + for (const name of classes) { + const seen = new Set([name]); + const queue = [name]; + while (queue.length > 0) { + const current = queue.shift(); + for (const next of fallbacks[current] ?? []) { + if (!seen.has(next)) { + seen.add(next); + queue.push(next); + } + } + } + if (!seen.has('specialist')) { + issues.push(`fallback: class "${name}" cannot reach specialist through the fallback graph`); + } + } + + // (c) Escalation walk: simulate the router's depth-first walk of + // the fallback chains under the per-call visited set. Entering a + // class runs its regular chain, then its fallback edges in order; + // a class already visited in this call is never re-entered, and + // when a fallback subtree yields nothing the walk resumes the + // caller's remaining edges (exactly how the appended targets sit + // in each class route's target list). The walk must reach + // specialist from every class. + const walkReachesSpecialist = (start) => { + const visited = new Set(); + const dfs = (current) => { + if (current === 'specialist') return true; + visited.add(current); + for (const next of fallbacks[current] ?? []) { + if (visited.has(next)) continue; + if (dfs(next)) return true; + } + return false; + }; + return dfs(start); + }; + for (const name of classes) { + if (!walkReachesSpecialist(name)) { + issues.push( + `fallback: escalation walk from "${name}" never reaches specialist under the per-call visited set`, + ); + } + } + } + + // (d) Composition cycles: walk every route->route edge EXCEPT the + // declared class fallback pairs. A cycle here is a real defect class + // (nested composition must be a DAG); fallback pairs are governed by + // the per-call visited set instead. + const state = new Map(); // route -> 'open' | 'done' + const stack = []; + const visit = (routeId) => { + state.set(routeId, 'open'); + stack.push(routeId); + for (const next of routeTargetIds(modelRoutes[routeId], modelRoutes)) { + if (fallbackPairs.has(`${routeId}->${next}`)) continue; + if (state.get(next) === 'open') { + const cycle = [...stack.slice(stack.indexOf(next)), next]; + if (!reportedCycleKeys.has(cycleKey(cycle))) { + issues.push(`route composition cycle: ${cycle.join(' -> ')}`); + reportedCycleKeys.add(cycleKey(cycle)); + } + continue; + } + if (!state.has(next)) visit(next); + } + stack.pop(); + state.set(routeId, 'done'); + }; + for (const routeId of Object.keys(modelRoutes).sort()) { + if (!state.has(routeId)) visit(routeId); + } + + return issues; +} // Keep aligned with bin/opencode-route-proxy.mjs BUILTIN_PROVIDERS. These // concrete provider ids take precedence over a same-named provider route. const BUILTIN_PROVIDER_IDS = new Set(['opencode-go', 'openai', 'deepseek', 'groq', 'openrouter', 'meta']); @@ -132,7 +284,14 @@ export function inspectRouteRules(config) { return []; } if (stack.includes(parsed.model)) { - addIssue(`${tier}: model-route cycle ${[...stack, parsed.model].join(' -> ')}`); + // Re-entry through a declared class fallback edge (e.g. + // workhorse -> scout -> workhorse) is the designed per-call + // visited-set semantics, not a cycle: the runtime expander + // prunes the re-entry. The traversal itself is bounded by + // the seen set below either way. + if (!CLASS_FALLBACK_PAIRS.has(`${stack.at(-1)}->${parsed.model}`)) { + addIssue(`${tier}: model-route cycle ${[...stack, parsed.model].join(' -> ')}`); + } return []; } // Match runtime resolveRoute: one shared seen set per tier @@ -297,6 +456,17 @@ export function inspectRouteRules(config) { }; } + // Class fallback layout + whole-graph composition cycle pass. + // Cycles the tier resolver already reported are not repeated. + const reportedCycleKeys = new Set(); + for (const issue of issues) { + const match = /model-route cycle (.+)$/.exec(issue); + if (match) reportedCycleKeys.add(cycleKey(match[1].split(' -> '))); + } + for (const issue of inspectFallbackLayout(modelRoutes, CLASS_FALLBACKS, reportedCycleKeys)) { + addIssue(issue); + } + return { tiers, issues }; } diff --git a/bin/check-opencode-route-rules.test.mjs b/bin/check-opencode-route-rules.test.mjs index 3c92f3d537..1fdf6b52db 100644 --- a/bin/check-opencode-route-rules.test.mjs +++ b/bin/check-opencode-route-rules.test.mjs @@ -227,3 +227,67 @@ test('canonical OpenCode config satisfies the route rules', () => { const source = fs.readFileSync('.opencode/opencode.jsonc', 'utf8'); assert.deepEqual(checkRouteRules(source), []); }); + +// --- class fallback layout (Drew 2026-11-13) --- +import { CLASS_FALLBACKS, inspectFallbackLayout } from './check-opencode-route-rules.mjs'; + +function configWithFallbacks(overrides = {}) { + const config = configWith({ + scout: ['good/model#low', 'opencode-route/workhorse'], + workhorse: ['good/model#high', 'opencode-route/scout', 'opencode-route/specialist'], + summit: ['plan/model#high', 'opencode-route/specialist'], + ...overrides, + }); + const routes = config.experimental.model_routes; + routes.small = { targets: ['good/model#low', 'opencode-route/speed'] }; + routes.speed = { + targets: ['good/model#high', 'opencode-route/workhorse', 'opencode-route/summit', 'opencode-route/specialist'], + }; + routes.background = { targets: ['good/model#low', 'opencode-route/workhorse'] }; + return config; +} + +test('class fallback layout passes and the workhorse<->scout pair is not a cycle', () => { + const result = inspectRouteRules(configWithFallbacks()); + assert.deepEqual(result.issues, []); +}); + +test('class fallback drift between config and the declared chain is flagged', () => { + const config = configWithFallbacks({ + workhorse: ['good/model#high', 'opencode-route/scout'], + }); + const issues = inspectRouteRules(config).issues; + assert.ok( + issues.some((issue) => issue.includes('fallback') && issue.includes('"workhorse"') && issue.includes('class fallback chain')), + `expected a workhorse fallback drift issue, got: ${JSON.stringify(issues)}`, + ); +}); + +test('a composition cycle between non-class routes is flagged with its path', () => { + const config = configWithFallbacks(); + config.experimental.model_routes.cycA = { targets: ['opencode-route/cycB'] }; + config.experimental.model_routes.cycB = { targets: ['opencode-route/cycA'] }; + const issues = inspectRouteRules(config).issues; + assert.ok( + issues.some((issue) => issue.includes('route composition cycle: cycA -> cycB -> cycA')), + `expected a composition cycle issue, got: ${JSON.stringify(issues)}`, + ); +}); + +test('fallback reachability check fires when a class cannot reach specialist', () => { + const routes = configWithFallbacks().experimental.model_routes; + const issues = inspectFallbackLayout(routes, { ...CLASS_FALLBACKS, summit: [] }); + assert.ok( + issues.some((issue) => issue.includes('"summit"') && issue.includes('cannot reach specialist')), + `expected a reachability issue, got: ${JSON.stringify(issues)}`, + ); +}); + +test('fallback escalation walk fires when the chain loops without reaching specialist', () => { + const routes = configWithFallbacks().experimental.model_routes; + const issues = inspectFallbackLayout(routes, { ...CLASS_FALLBACKS, speed: ['summit'], summit: ['speed'] }); + assert.ok( + issues.some((issue) => issue.includes('escalation walk') && issue.includes('never reaches specialist')), + `expected an escalation walk issue, got: ${JSON.stringify(issues)}`, + ); +});