supercode-harness 0.4.20

The optional native Supercode agent and tool harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! §2 module 26 `model.catalog` (`docs/composable-harness/
//! COMPOSABLE-HARNESS-DESIGN.md` §3.1 `[capabilities.model_catalog]`) — P4
//! of the composable-harness migration (design §5.2 phase **P4**: "aliases +
//! fallback chains (userconfig.rs:386-411) promoted into core" + the
//! `small_model` knob).
//!
//! **What moved here.** The CLI's `alias_table`/`resolve_model_alias`
//! (`crates/cli/src/userconfig.rs`) were CLI-only (design §1.10: "CLI model
//! aliases ✓ … `resolve_model_alias`, userconfig.rs:386-411"). This module is
//! the single source of truth now — [`DEFAULT_ALIASES`] is the exact same
//! eleven built-in aliases, byte-identical, so moving them here changes no
//! resolved slug for any existing caller. The CLI crate re-exports through
//! `userconfig::alias_table`/`resolve_model_alias` (zero call-site churn,
//! zero behavior change — see that module).
//!
//! **What's NEW (P4).** [`resolve_alias`] additionally accepts an
//! `extra` table (`[capabilities.model_catalog].aliases`, §3.1/§3.2:
//! "`capabilities.model_catalog.*` | CLI `alias_table` … + NEW
//! small-model/fallback") so a user's own config can add or override an
//! alias without recompiling — `extra` is checked BEFORE
//! [`DEFAULT_ALIASES`], so a user override always wins. [`resolve_fallback_chain`]
//! resolves a `[capabilities.model_catalog].fallback` list of aliases/slugs
//! into a plain slug list the SAME way, for the D-9-adjacent "failure
//! fallback chain" knob (catalog §4a: "Model aliases + failure fallback
//! chain (resolution table before request build)").
//!
//! **Scope note (S-sized, per design §5.2 P4).** This module lands the
//! RESOLUTION TABLE only — `Config::small_model`/`Config::model_fallback`
//! are knobs a caller can read, not a retry/failover LOOP that automatically
//! re-sends a failed request against the next model in the chain. Building
//! that loop is a distinct, larger change (closer to §1.10's "mid-session
//! model switch," itself called out in design §5.2 as its own M-sized item,
//! separate from this S-sized catalog item) and is out of scope here.

/// The built-in alias → full-slug table (byte-identical to the CLI's
/// original `userconfig::alias_table`, moved here as the single source of
/// truth — see the module doc).
pub const DEFAULT_ALIASES: &[(&str, &str)] = &[
    ("opus", "anthropic/claude-opus-4-8"),
    ("sonnet", "anthropic/claude-sonnet-4-6"),
    ("haiku", "anthropic/claude-haiku-4-5"),
    ("gpt", "openai/gpt-5.5"),
    ("gpt-5.5", "openai/gpt-5.5"),
    ("gpt-5", "openai/gpt-5"),
    ("gemini", "google/gemini-2.5-pro"),
    ("flash", "deepseek/deepseek-v4-flash"),
    ("deepseek-flash", "deepseek/deepseek-v4-flash"),
    ("deepseek", "deepseek/deepseek-v4-pro"),
    ("llama", "meta-llama/llama-4-maverick"),
];

/// Expand a friendly model alias to its full slug through the built-in
/// table alone — the no-config path, for callers that have no resolved
/// [`Routing`] in hand (an imported foreign session's recorded model name, a
/// help listing). Unknown values pass through unchanged so any real slug
/// still works. A caller that DOES have a config resolves through
/// [`Routing::resolve_alias`] instead, which additionally honours the
/// config's own alias table, its patterns, and its provider/account scopes.
pub fn resolve_alias(model: &str) -> String {
    Routing::default().resolve_alias(model)
}

/// Everything `[capabilities.model_catalog]` resolves into, alias-resolved:
/// the effective `core.model`, the `small_model` (if set), and the
/// `fallback` chain (if set). Shared by both resolution paths that carry a
/// `capabilities.<name>` table shaped like [`crate::configfile::CapabilityConfig`]
/// — the SDK's [`crate::configfile::HarnessConfig`] resolver
/// (`materialize_config`) and the CLI's own `FileConfig`-driven
/// `build_config` — so the alias/small-model/fallback resolution logic
/// lives in exactly one place.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Resolution {
    /// `base_model`, alias-resolved.
    pub model: String,
    /// `capabilities.model_catalog.small_model`, alias-resolved, if set to
    /// a non-empty string.
    pub small_model: Option<String>,
    /// `capabilities.model_catalog.fallback`, alias-resolved in order, if
    /// non-empty.
    pub fallback: Vec<String>,
    /// BP-5 (`capabilities.model_catalog.base_prompts`, catalog D2
    /// "Per-model-family base-prompt selection"): model-id glob → that
    /// family's base system prompt. Empty unless the config sets the table.
    pub base_prompts: std::collections::BTreeMap<String, String>,
    /// BP-13: the whole routing table (aliases, per-model rules, allow/deny
    /// lists) — carried forward onto [`crate::Config::model_routing`] so
    /// every later routing decision asks THIS value rather than re-reading
    /// the capability table behind this module's back.
    pub routing: Routing,
    /// BP-13: why `model` is refused by the config-layer allow/deny lists,
    /// or `None`. Reported by the resolver, never silently applied.
    pub refusal: Option<String>,
}

/// Resolve `[capabilities.model_catalog]` against `base_model` (typically
/// the already-computed `core.model` / CLI `--model`/config value).
/// Consulted regardless of `capabilities.model_catalog.enabled` — matching
/// the resolver's existing D-9 check (`configfile::validate_modules`),
/// which already reads `model_catalog.small_model` unconditionally: these
/// are data a caller resolves against, not an activation switch.
pub fn resolve(
    capabilities: &std::collections::BTreeMap<String, crate::configfile::CapabilityConfig>,
    base_model: &str,
) -> Resolution {
    let routing = Routing::from_capabilities(capabilities);

    let mut out = Resolution {
        model: if base_model.is_empty() {
            String::new()
        } else {
            routing.resolve_alias(base_model)
        },
        small_model: None,
        fallback: Vec::new(),
        base_prompts: std::collections::BTreeMap::new(),
        refusal: None,
        routing,
    };

    if let Some(cap) = capabilities.get("model_catalog") {
        if let Some(sm) = cap.settings.get("small_model").and_then(|v| v.as_str()) {
            if !sm.is_empty() {
                out.small_model = Some(out.routing.resolve_alias(sm));
            }
        }
        // BP-5: the per-family base-prompt table. Read here, next to
        // `small_model`/`fallback`, for the same reason those are: it is
        // DATA a caller resolves against, not an activation switch.
        if let Some(table) = cap.settings.get("base_prompts").and_then(|v| v.as_object()) {
            out.base_prompts = table
                .iter()
                .filter_map(|(pattern, body)| {
                    body.as_str()
                        .filter(|text| !text.is_empty())
                        .map(|text| (pattern.clone(), text.to_string()))
                })
                .collect();
        }
        if let Some(fb) = cap.settings.get("fallback").and_then(|v| v.as_array()) {
            out.fallback = fb
                .iter()
                .filter_map(|v| v.as_str())
                .map(|m| out.routing.resolve_alias(m))
                .collect();
        }
    }
    // The allow/deny lists bind every model this table hands out, not just
    // `core.model` — a fallback entry or a small model the org forbids is
    // exactly as forbidden as a main model it forbids.
    out.refusal = [Some(&out.model)]
        .into_iter()
        .flatten()
        .chain(out.small_model.iter())
        .chain(out.fallback.iter())
        .filter(|m| !m.is_empty())
        .find_map(|m| out.routing.refusal(m));
    out
}

/// BP-5 (catalog D2 "Per-model-family base-prompt selection", cx§2
/// "Per-model base instructions": "the system prompt is selected per model
/// family from bundled markdown"): the base prompt `model` should run
/// under, or `None` when no family pattern matches.
///
/// `prompts` is keyed by a [`crate::config::glob_match`] pattern over the
/// model id (`"*codex*"`, `"openai/gpt-5.*"`). The MOST SPECIFIC match wins,
/// specificity being the pattern's own length — a TOML table has no order to
/// rely on, so selection must not depend on one. Ties (equal-length patterns
/// both matching) break lexicographically, so the answer is total and
/// reproducible.
pub fn base_prompt_for<'a>(
    prompts: &'a std::collections::BTreeMap<String, String>,
    model: &str,
) -> Option<&'a str> {
    prompts
        .iter()
        .filter(|(pattern, _)| crate::config::glob_match(pattern, model))
        .max_by(|(a, _), (b, _)| a.len().cmp(&b.len()).then_with(|| b.cmp(a)))
        .map(|(_, body)| body.as_str())
}

// ---------------------------------------------------------------------------
// BP-13 — the ONE model-resolution path.
// ---------------------------------------------------------------------------
//
// Everything routing decides about a model — which slug a friendly name means,
// which reasoning effort and thinking budget the request carries, which service
// tier it asks for, which tool-shape capability bits the registry reads, and
// whether the model is allowed at all — resolves HERE, out of the same
// `[capabilities.model_catalog]` table the presets already set. There is no
// second table, no parallel registry, and no consumer that reads a raw setting
// behind this module's back: `configfile::materialize_config` folds this into
// `Config::model_routing`, and every consumer (`Agent`'s request build, its
// fallback pass, `ToolRegistry::from_config`, the CLI's `--model`/`/model`)
// asks the SAME `Routing` value.

/// The reasoning-effort ladder, weakest first. Spans both harnesses' own
/// vocabularies: Claude Code's `low|medium|high` and Codex's `none…ultra`
/// (cc§9, cx§6/§9). A level outside the ladder is not an error — it is
/// forwarded verbatim to the provider — but it cannot be RANKED, so an
/// effort cap can neither clamp it nor be fooled by it (see [`cap_effort`]).
pub const EFFORT_LADDER: &[&str] = &["none", "minimal", "low", "medium", "high", "xhigh", "ultra"];

/// Position of `level` on [`EFFORT_LADDER`], or `None` for a level this
/// build does not rank.
pub fn effort_rank(level: &str) -> Option<usize> {
    EFFORT_LADDER.iter().position(|l| *l == level)
}

/// Clamp `level` down to `cap`. Returns `level` unchanged when there is no
/// cap, when the cap does not bind, or when EITHER side is unrankable (an
/// unknown spelling must not be silently rewritten into a ladder value the
/// user never asked for).
pub fn cap_effort(level: Option<&str>, cap: Option<&str>) -> Option<String> {
    let level = level?;
    let Some(cap) = cap else {
        return Some(level.to_string());
    };
    match (effort_rank(level), effort_rank(cap)) {
        (Some(l), Some(c)) if l > c => Some(cap.to_string()),
        _ => Some(level.to_string()),
    }
}

/// Match `value` against a model PATTERN and return what the wildcard
/// captured.
///
/// A pattern is either an exact slug (matches by equality; the capture is
/// the whole value) or a single-`*` glob (`opus*`, `*[1m]`, `openai/gpt-5*`),
/// where `*` stands for any run of characters including the empty one. A
/// second `*` is not a pattern this build understands and never matches, so
/// a typo fails closed rather than matching everything.
pub fn pattern_capture(pattern: &str, value: &str) -> Option<String> {
    match pattern.split_once('*') {
        None => (pattern == value).then(|| value.to_string()),
        Some((prefix, suffix)) => {
            if suffix.contains('*') {
                return None;
            }
            if value.len() < prefix.len() + suffix.len() {
                return None;
            }
            if !value.starts_with(prefix) || !value.ends_with(suffix) {
                return None;
            }
            Some(value[prefix.len()..value.len() - suffix.len()].to_string())
        }
    }
}

/// How specific a pattern is: its literal (non-wildcard) length, with an
/// exact pattern always beating a glob of the same literal length. Used to
/// order overlays so the most specific rule wins.
fn pattern_specificity(pattern: &str) -> (usize, u8) {
    let literal = pattern.chars().filter(|c| *c != '*').count();
    (literal, u8::from(!pattern.contains('*')))
}

/// Per-model routing rules: what `[capabilities.model_catalog.models.<pattern>]`
/// (and the table's own top-level defaults) say about one model.
///
/// Every field is `Option` so "unset" and "set to the default value" stay
/// distinguishable — an unset field inherits, a set one overrides.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModelRules {
    /// Reasoning-effort level for this model — the per-model override of
    /// `[core] effort` (cc§9 effort levels, cx§9 tiers).
    pub effort: Option<String>,
    /// Ceiling on the effort level for this model. Applied AFTER `effort`
    /// and after `[core] effort`, so a cap binds whatever the level came
    /// from — the per-model half of the org effort cap.
    pub max_effort: Option<String>,
    /// Thinking-token budget (Claude Code's `MAX_THINKING_TOKENS`).
    pub thinking_budget: Option<u32>,
    /// Service tier / fast-mode variant asked for on the request
    /// (cc `/fast`, cx `model_service_tier`).
    pub service_tier: Option<String>,
    /// Capability bit: this model takes the freeform `apply_patch`
    /// envelope. `Some(false)` swaps the write surface to `edit_file` /
    /// `write_file` instead (cx§9 `apply_patch_tool_type`).
    pub apply_patch: Option<bool>,
    /// Capability bit: this model takes the dedicated search tool
    /// (cx§9 `supports_search_tool`).
    pub search_tool: Option<bool>,
}

impl ModelRules {
    /// Overlay `other`'s SET fields onto `self`; unset fields inherit.
    pub fn overlay(&mut self, other: &ModelRules) {
        if other.effort.is_some() {
            self.effort.clone_from(&other.effort);
        }
        if other.max_effort.is_some() {
            self.max_effort.clone_from(&other.max_effort);
        }
        if other.thinking_budget.is_some() {
            self.thinking_budget = other.thinking_budget;
        }
        if other.service_tier.is_some() {
            self.service_tier.clone_from(&other.service_tier);
        }
        if other.apply_patch.is_some() {
            self.apply_patch = other.apply_patch;
        }
        if other.search_tool.is_some() {
            self.search_tool = other.search_tool;
        }
    }

    fn from_settings(obj: &serde_json::Map<String, serde_json::Value>) -> ModelRules {
        let text = |key: &str| {
            obj.get(key)
                .and_then(|v| v.as_str())
                .filter(|s| !s.is_empty())
                .map(str::to_string)
        };
        ModelRules {
            effort: text("effort"),
            max_effort: text("max_effort"),
            thinking_budget: obj
                .get("thinking_budget")
                .and_then(|v| v.as_u64())
                .filter(|n| *n > 0)
                .map(|n| n as u32),
            service_tier: text("service_tier"),
            apply_patch: obj.get("apply_patch").and_then(|v| v.as_bool()),
            search_tool: obj.get("search_tool").and_then(|v| v.as_bool()),
        }
    }
}

/// The whole resolved routing table, carried on
/// [`crate::Config::model_routing`] and consulted by every routing decision.
///
/// It keeps the PATTERNS rather than one pre-resolved answer on purpose: a
/// mid-session model switch has to re-decide effort, budget, tier and tool
/// bits for the NEW model, and it does that by asking this same value again
/// ([`Routing::rules_for`]) rather than by re-reading config elsewhere.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Routing {
    /// Alias → slug entries from the config, in precedence order: the
    /// declared account's scope, then the declared provider's, then the flat
    /// table. Consulted before [`DEFAULT_ALIASES`]. A key may be a `*`
    /// pattern, in which case the value may contain `{}` — replaced by the
    /// captured stem after that stem is itself alias-resolved (Claude Code's
    /// `sonnet[1m]` shape).
    pub aliases: Vec<(String, String)>,
    /// `[capabilities.model_catalog.models.<pattern>]`, least specific
    /// first, so overlaying in order leaves the most specific rule winning.
    pub models: Vec<(String, ModelRules)>,
    /// The table's own top-level rules — the baseline every model inherits.
    pub defaults: ModelRules,
    /// `allowed_models`: when non-empty, a model matching NO entry is
    /// refused outright.
    pub allowed: Vec<String>,
    /// `denied_models`: a model matching any entry is refused outright.
    pub denied: Vec<String>,
    /// The declared provider whose alias scope is in force (`provider`).
    pub provider: Option<String>,
    /// The declared account/plan tier whose alias scope is in force
    /// (`account`) — Claude Code's account-type defaults (cc§9).
    pub account: Option<String>,
}

impl Routing {
    /// Expand a friendly model name to a full slug through this table, then
    /// [`DEFAULT_ALIASES`], then unchanged pass-through.
    ///
    /// Exact entries always beat patterns, and among patterns the most
    /// specific wins. A pattern's `{}` placeholder receives the captured
    /// stem RE-RESOLVED through this same function (depth-capped), which is
    /// what makes `sonnet[1m]` land on `anthropic/claude-sonnet-4-6[1m]`
    /// rather than on the literal text `sonnet[1m]`.
    pub fn resolve_alias(&self, model: &str) -> String {
        self.resolve_alias_depth(model, 0)
    }

    fn resolve_alias_depth(&self, model: &str, depth: usize) -> String {
        if depth > 4 {
            return model.to_string();
        }
        for (alias, slug) in &self.aliases {
            if !alias.contains('*') && alias == model {
                return slug.clone();
            }
        }
        if let Some((_, slug)) = DEFAULT_ALIASES.iter().find(|(a, _)| *a == model) {
            return (*slug).to_string();
        }
        let mut best: Option<(usize, u8, &str, String)> = None;
        for (alias, slug) in &self.aliases {
            if !alias.contains('*') {
                continue;
            }
            let Some(stem) = pattern_capture(alias, model) else {
                continue;
            };
            let (literal, exact) = pattern_specificity(alias);
            if best
                .as_ref()
                .is_none_or(|(l, e, _, _)| (literal, exact) > (*l, *e))
            {
                best = Some((literal, exact, slug.as_str(), stem));
            }
        }
        match best {
            Some((_, _, template, stem)) => {
                let expanded = self.resolve_alias_depth(&stem, depth + 1);
                template.replace("{}", &expanded)
            }
            None => model.to_string(),
        }
    }

    /// The rules in force for `model`: the table defaults with every
    /// matching `models.<pattern>` overlaid, least specific first.
    pub fn rules_for(&self, model: &str) -> ModelRules {
        let mut rules = self.defaults.clone();
        for (pattern, r) in &self.models {
            if pattern_capture(pattern, model).is_some() {
                rules.overlay(r);
            }
        }
        rules
    }

    /// The effort level to send for `model`, given the session's
    /// `[core] effort`: the per-model level if one is set, else the session
    /// level, clamped by whichever effort cap applies.
    pub fn effective_effort(&self, model: &str, session_effort: Option<&str>) -> Option<String> {
        let rules = self.rules_for(model);
        let level = rules.effort.as_deref().or(session_effort);
        cap_effort(level, rules.max_effort.as_deref())
    }

    /// Why `model` is refused, or `None` when it is allowed — the
    /// CONFIG-layer half of the org model allowlist. A denied model can
    /// never be selected, and with an allowlist set nothing outside it can.
    pub fn refusal(&self, model: &str) -> Option<String> {
        if let Some(pattern) = self
            .denied
            .iter()
            .find(|p| pattern_capture(p, model).is_some())
        {
            return Some(format!(
                "model `{model}` matches capabilities.model_catalog.denied_models entry `{pattern}`"
            ));
        }
        if !self.allowed.is_empty()
            && !self
                .allowed
                .iter()
                .any(|p| pattern_capture(p, model).is_some())
        {
            return Some(format!(
                "model `{model}` is not in capabilities.model_catalog.allowed_models ({})",
                self.allowed.join(", ")
            ));
        }
        None
    }

    /// Whether anything in this table restricts model choice at all.
    pub fn restricts_models(&self) -> bool {
        !self.allowed.is_empty() || !self.denied.is_empty()
    }

    /// Build the routing table from `[capabilities.model_catalog]`.
    ///
    /// Consulted regardless of the module's `enabled` flag, for the same
    /// reason [`resolve`] is: these are data a caller resolves against, not
    /// an activation switch (and the D-9 resolver check already reads
    /// `small_model` unconditionally).
    pub fn from_capabilities(
        capabilities: &std::collections::BTreeMap<String, crate::configfile::CapabilityConfig>,
    ) -> Routing {
        let Some(cap) = capabilities.get("model_catalog") else {
            return Routing::default();
        };
        let s = &cap.settings;
        let scope = |key: &str| {
            s.get(key)
                .and_then(|v| v.as_str())
                .filter(|p| !p.is_empty())
                .map(str::to_string)
        };
        let provider = scope("provider");
        let account = scope("account");

        // Alias scopes, most specific first: the declared account's table,
        // then the declared provider's, then the flat table.
        let mut aliases: Vec<(String, String)> = Vec::new();
        let provider_table = provider
            .as_deref()
            .and_then(|p| s.get("providers")?.as_object()?.get(p))
            .and_then(|v| v.as_object());
        if let (Some(pt), Some(account)) = (provider_table, account.as_deref()) {
            if let Some(at) = pt
                .get("accounts")
                .and_then(|v| v.as_object())
                .and_then(|a| a.get(account))
                .and_then(|v| v.as_object())
            {
                push_alias_table(at.get("aliases"), &mut aliases);
            }
        }
        if let Some(pt) = provider_table {
            push_alias_table(pt.get("aliases"), &mut aliases);
        }
        push_alias_table(s.get("aliases"), &mut aliases);

        let mut models: Vec<(String, ModelRules)> = s
            .get("models")
            .and_then(|v| v.as_object())
            .map(|o| {
                o.iter()
                    .filter_map(|(pattern, v)| {
                        Some((pattern.clone(), ModelRules::from_settings(v.as_object()?)))
                    })
                    .collect()
            })
            .unwrap_or_default();
        models.sort_by_key(|(pattern, _)| pattern_specificity(pattern));

        Routing {
            aliases,
            models,
            defaults: ModelRules::from_settings(s),
            allowed: string_list(s.get("allowed_models")),
            denied: string_list(s.get("denied_models")),
            provider,
            account,
        }
    }
}

fn push_alias_table(value: Option<&serde_json::Value>, out: &mut Vec<(String, String)>) {
    let Some(obj) = value.and_then(|v| v.as_object()) else {
        return;
    };
    let mut entries: Vec<(String, String)> = obj
        .iter()
        .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
        .collect();
    entries.sort();
    out.extend(entries);
}

fn string_list(value: Option<&serde_json::Value>) -> Vec<String> {
    value
        .and_then(|v| v.as_array())
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolve_alias_with_no_config_matches_every_built_in() {
        for (alias, slug) in DEFAULT_ALIASES {
            assert_eq!(resolve_alias(alias), *slug, "alias {alias}");
        }
        // A non-alias passes through unchanged.
        assert_eq!(resolve_alias("vendor/some-model"), "vendor/some-model");
    }

    fn routing(settings: serde_json::Value) -> Routing {
        let mut capabilities = std::collections::BTreeMap::new();
        capabilities.insert("model_catalog".to_string(), cap(settings));
        Routing::from_capabilities(&capabilities)
    }

    #[test]
    fn config_alias_table_overrides_a_built_in_and_adds_new_names() {
        let r = routing(serde_json::json!({
            "aliases": {"opus": "vendor/my-custom-opus", "fast": "vendor/fast-model"},
        }));
        assert_eq!(r.resolve_alias("opus"), "vendor/my-custom-opus");
        assert_eq!(r.resolve_alias("fast"), "vendor/fast-model");
        // Untouched aliases still resolve to the built-in, and an unknown
        // name still passes through.
        assert_eq!(r.resolve_alias("sonnet"), "anthropic/claude-sonnet-4-6");
        assert_eq!(r.resolve_alias("unknown-thing"), "unknown-thing");
    }

    /// The PATTERN half (cc§9's `[1m]` shape): the wildcard's capture is
    /// itself alias-resolved before it is substituted, so a suffix modifier
    /// composes with the alias table instead of shadowing it.
    #[test]
    fn a_pattern_alias_resolves_its_captured_stem_before_substituting() {
        let r = routing(serde_json::json!({"aliases": {"*[1m]": "{}[1m]"}}));
        assert_eq!(
            r.resolve_alias("sonnet[1m]"),
            "anthropic/claude-sonnet-4-6[1m]"
        );
        // A full slug carrying the same suffix works too.
        assert_eq!(r.resolve_alias("vendor/m[1m]"), "vendor/m[1m]");
        // An exact entry always beats a pattern.
        let r = routing(serde_json::json!({
            "aliases": {"*[1m]": "{}[1m]", "sonnet[1m]": "vendor/pinned"},
        }));
        assert_eq!(r.resolve_alias("sonnet[1m]"), "vendor/pinned");
    }

    /// Per-provider and per-account scopes: the SAME friendly name resolves
    /// to different slugs depending on which provider/plan the session
    /// declares (cc§9 "Account-type defaults").
    #[test]
    fn aliases_resolve_per_provider_and_per_account() {
        let table = |provider: &str, account: &str| {
            serde_json::json!({
                "provider": provider,
                "account": account,
                "aliases": {"default": "vendor/generic"},
                "providers": {
                    "anthropic": {
                        "aliases": {"default": "anthropic/claude-sonnet-4-6"},
                        "accounts": {
                            "max": {"aliases": {"default": "anthropic/claude-opus-4-8"}},
                        },
                    },
                    "openai": {"aliases": {"default": "openai/gpt-5.5"}},
                },
            })
        };
        assert_eq!(
            routing(table("anthropic", "max")).resolve_alias("default"),
            "anthropic/claude-opus-4-8"
        );
        // Same provider, a plan with no table of its own: the provider scope.
        assert_eq!(
            routing(table("anthropic", "pro")).resolve_alias("default"),
            "anthropic/claude-sonnet-4-6"
        );
        // Different provider entirely.
        assert_eq!(
            routing(table("openai", "max")).resolve_alias("default"),
            "openai/gpt-5.5"
        );
        // No scope declared at all: the flat table.
        assert_eq!(
            routing(serde_json::json!({"aliases": {"default": "vendor/generic"}}))
                .resolve_alias("default"),
            "vendor/generic"
        );
    }

    #[test]
    fn pattern_capture_is_exact_or_single_wildcard() {
        assert_eq!(pattern_capture("a/b", "a/b").as_deref(), Some("a/b"));
        assert_eq!(pattern_capture("a/b", "a/c"), None);
        assert_eq!(
            pattern_capture("openai/*", "openai/gpt-5").as_deref(),
            Some("gpt-5")
        );
        assert_eq!(
            pattern_capture("*[1m]", "opus[1m]").as_deref(),
            Some("opus")
        );
        assert_eq!(
            pattern_capture("*", "anything").as_deref(),
            Some("anything")
        );
        // A two-wildcard pattern is not understood, and fails closed.
        assert_eq!(pattern_capture("a*b*c", "axbyc"), None);
        // The wildcard may capture nothing.
        assert_eq!(pattern_capture("opus*", "opus").as_deref(), Some(""));
    }

    /// Per-model rules: the most specific matching pattern wins, and unset
    /// fields inherit from the table's own top-level defaults.
    #[test]
    fn per_model_rules_overlay_defaults_most_specific_last() {
        let r = routing(serde_json::json!({
            "effort": "medium",
            "thinking_budget": 4096,
            "models": {
                "anthropic/*": {"thinking_budget": 16384},
                "anthropic/claude-opus-4-8": {"effort": "high", "apply_patch": false},
                "openai/*": {"apply_patch": true},
            },
        }));
        let opus = r.rules_for("anthropic/claude-opus-4-8");
        assert_eq!(opus.effort.as_deref(), Some("high"));
        assert_eq!(opus.thinking_budget, Some(16384));
        assert_eq!(opus.apply_patch, Some(false));
        let haiku = r.rules_for("anthropic/claude-haiku-4-5");
        assert_eq!(haiku.effort.as_deref(), Some("medium"));
        assert_eq!(haiku.thinking_budget, Some(16384));
        assert_eq!(haiku.apply_patch, None);
        let gpt = r.rules_for("openai/gpt-5.5");
        assert_eq!(gpt.thinking_budget, Some(4096));
        assert_eq!(gpt.apply_patch, Some(true));
    }

    #[test]
    fn effective_effort_prefers_the_model_rule_then_the_session_then_clamps() {
        let r = routing(serde_json::json!({
            "models": {
                "anthropic/*": {"effort": "high"},
                "cheap/*": {"max_effort": "low"},
            },
        }));
        // Per-model level beats the session level.
        assert_eq!(
            r.effective_effort("anthropic/claude-opus-4-8", Some("medium"))
                .as_deref(),
            Some("high")
        );
        // No rule: the session level survives.
        assert_eq!(
            r.effective_effort("vendor/m", Some("medium")).as_deref(),
            Some("medium")
        );
        // A cap binds whatever the level came from.
        assert_eq!(
            r.effective_effort("cheap/m", Some("ultra")).as_deref(),
            Some("low")
        );
        // A cap that does not bind changes nothing.
        assert_eq!(
            r.effective_effort("cheap/m", Some("none")).as_deref(),
            Some("none")
        );
        // An unrankable spelling is forwarded verbatim, never rewritten.
        assert_eq!(
            r.effective_effort("cheap/m", Some("turbo")).as_deref(),
            Some("turbo")
        );
        // Nothing set at all stays unset.
        assert_eq!(r.effective_effort("vendor/m", None), None);
    }

    #[test]
    fn allow_and_deny_lists_refuse_by_pattern() {
        let r = routing(serde_json::json!({
            "allowed_models": ["anthropic/*"],
            "denied_models": ["anthropic/claude-opus-*"],
        }));
        assert!(r.restricts_models());
        assert!(r.refusal("anthropic/claude-sonnet-4-6").is_none());
        assert!(r
            .refusal("anthropic/claude-opus-4-8")
            .is_some_and(|d| d.contains("denied_models")));
        assert!(r
            .refusal("openai/gpt-5.5")
            .is_some_and(|d| d.contains("allowed_models")));
        // Nothing configured restricts nothing.
        assert!(!routing(serde_json::json!({})).restricts_models());
        assert!(routing(serde_json::json!({})).refusal("anything").is_none());
    }

    fn cap(settings: serde_json::Value) -> crate::configfile::CapabilityConfig {
        crate::configfile::CapabilityConfig {
            enabled: None,
            settings: settings.as_object().cloned().unwrap_or_default(),
        }
    }

    /// Default-off: no `[capabilities.model_catalog]` table at all resolves
    /// to the base model alias-resolved against the built-ins only, with no
    /// small_model/fallback — unchanged behavior for every config that
    /// doesn't set this table.
    #[test]
    fn resolve_with_no_model_catalog_table_is_alias_only() {
        let capabilities = std::collections::BTreeMap::new();
        let r = resolve(&capabilities, "opus");
        assert_eq!(r.model, "anthropic/claude-opus-4-8");
        assert_eq!(r.small_model, None);
        assert!(r.fallback.is_empty());
    }

    /// Happy path: small_model + fallback + a custom alias all resolve
    /// together through the one path, and `enabled` is irrelevant (matches
    /// the D-9 check's own precedent of reading `small_model`
    /// unconditionally).
    #[test]
    fn resolve_happy_path_reads_small_model_fallback_and_aliases_regardless_of_enabled() {
        let mut capabilities = std::collections::BTreeMap::new();
        capabilities.insert(
            "model_catalog".to_string(),
            cap(serde_json::json!({
                "small_model": "haiku",
                "fallback": ["sonnet", "vendor/already-a-slug"],
                "aliases": {"cheap": "vendor/cheap-model"},
            })),
        );
        let r = resolve(&capabilities, "cheap");
        assert_eq!(r.model, "vendor/cheap-model");
        assert_eq!(r.small_model.as_deref(), Some("anthropic/claude-haiku-4-5"));
        assert_eq!(
            r.fallback,
            vec![
                "anthropic/claude-sonnet-4-6".to_string(),
                "vendor/already-a-slug".to_string(),
            ]
        );
    }

    /// A resolved-slug `small_model` (already a full id, not an alias)
    /// passes through unchanged.
    #[test]
    fn resolve_small_model_already_a_slug_passes_through() {
        let mut capabilities = std::collections::BTreeMap::new();
        capabilities.insert(
            "model_catalog".to_string(),
            cap(serde_json::json!({"small_model": "anthropic/claude-haiku-4-5"})),
        );
        let r = resolve(&capabilities, "anthropic/claude-opus-4-8");
        assert_eq!(r.model, "anthropic/claude-opus-4-8");
        assert_eq!(r.small_model.as_deref(), Some("anthropic/claude-haiku-4-5"));
    }
}