supercode-harness 0.4.21

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
//! BP-13 (catalog Domain 9, "Model routing") — the routing rows proved
//! through the RESOLVED `cc-parity` / `cx-parity` presets.
//!
//! Nothing here unit-tests an unwired function. Every assertion resolves the
//! preset TOML through [`supercode_harness::configfile::resolve`] and then
//! drives the real path: the [`Agent`] the CLI's own doors build, its
//! request build, its fallback pass, and
//! [`supercode_harness::tools::ToolRegistry::from_config`]'s own selection.
//! Where a row's capability is a per-invocation flag (`--fallback-model`,
//! `--model`), the test layers exactly that flag over the resolved preset,
//! which is the user path the harness it mirrors offers.
//!
//! Offline and hermetic: scripted in-process providers that record the wire
//! request, temp-directory stores, no real harness home, no model call.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use supercode_harness::configfile::{resolve, ResolveError, ResolveOptions};
use supercode_harness::model_catalog::Routing;
use supercode_harness::store::SessionStore;
use supercode_harness::tools::ToolRegistry;
use supercode_harness::{
    Agent, AgentEvent, ChatMessage, ChatRequest, Config, Error, Provider, Usage,
};

// ---------------------------------------------------------------------------
// The real path: a resolved preset, an Agent, a request recorder.
// ---------------------------------------------------------------------------

fn temp_root(tag: &str) -> std::path::PathBuf {
    let p = std::env::temp_dir().join(format!(
        "supercode-bp13-{tag}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&p).unwrap();
    p
}

/// The resolved parity preset, exactly as the CLI resolves it, with only
/// `cwd` moved into the test's own tree. `extra` is the caller's own config
/// layer — the equivalent of a user file or a `-c` override on top of the
/// preset, never a hand-built `Config`.
fn parity_config(preset: &str, cwd: &std::path::Path, extra: &str) -> Config {
    let mut resolved = resolve(
        &format!("extends = \"{preset}\"\n{extra}"),
        None,
        &ResolveOptions { strict: true },
    )
    .unwrap_or_else(|e| panic!("preset `{preset}` failed to resolve: {e}"));
    resolved.config.cwd = cwd.to_path_buf();
    resolved.config
}

/// The routing table a resolved preset produces — the one value every
/// routing consumer reads.
fn parity_routing(preset: &str) -> Routing {
    resolve(
        &format!("extends = \"{preset}\"\n"),
        None,
        &ResolveOptions { strict: true },
    )
    .unwrap()
    .config
    .model_routing
}

/// A provider that answers, recording every request it was handed.
struct Recording {
    seen: Arc<Mutex<Vec<ChatRequest>>>,
    /// Model id the response CLAIMS served it, if any.
    served: Option<String>,
}

impl Recording {
    fn new() -> (Self, Arc<Mutex<Vec<ChatRequest>>>) {
        let seen = Arc::new(Mutex::new(Vec::new()));
        (
            Recording {
                seen: seen.clone(),
                served: None,
            },
            seen,
        )
    }

    fn serving(model: &str) -> (Self, Arc<Mutex<Vec<ChatRequest>>>) {
        let (mut p, seen) = Recording::new();
        p.served = Some(model.to_string());
        (p, seen)
    }
}

#[async_trait]
impl Provider for Recording {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode_harness::Result<(ChatMessage, Usage)> {
        self.seen.lock().unwrap().push(req.clone());
        let mut reply = ChatMessage::assistant("done");
        if let Some(served) = &self.served {
            reply.metadata.insert(
                supercode_harness::SERVED_MODEL_KEY.to_string(),
                served.clone(),
            );
        }
        Ok((reply, Usage::default()))
    }
}

/// A provider that fails with `status` for every model in `failing`, and
/// answers for anything else — the overload the fallback chain exists for.
struct FailsFor {
    failing: Vec<String>,
    status: u16,
    seen: Arc<Mutex<Vec<String>>>,
    calls: AtomicUsize,
}

impl FailsFor {
    fn new(failing: &[&str], status: u16) -> (Self, Arc<Mutex<Vec<String>>>) {
        let seen = Arc::new(Mutex::new(Vec::new()));
        (
            FailsFor {
                failing: failing.iter().map(|m| (*m).to_string()).collect(),
                status,
                seen: seen.clone(),
                calls: AtomicUsize::new(0),
            },
            seen,
        )
    }
}

#[async_trait]
impl Provider for FailsFor {
    async fn complete(
        &self,
        req: &ChatRequest,
        _on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
    ) -> supercode_harness::Result<(ChatMessage, Usage)> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        self.seen.lock().unwrap().push(req.model.clone());
        if self.failing.iter().any(|m| *m == req.model) {
            return Err(Error::Provider {
                status: self.status,
                body: "overloaded".into(),
            });
        }
        Ok((ChatMessage::assistant("answered"), Usage::default()))
    }
}

// ---------------------------------------------------------------------------
// D9 — Model aliases / patterns (cc)
// ---------------------------------------------------------------------------

/// cc-parity declares an anthropic/max alias scope, so `default` and `best`
/// mean what CC's account-type defaults mean, `fast` means what the
/// PROVIDER scope says, and the `[1m]` SUFFIX pattern composes with the
/// alias table rather than shadowing it.
#[test]
fn cc_parity_resolves_account_provider_and_pattern_aliases() {
    let routing = parity_routing("cc-parity");
    assert_eq!(routing.provider.as_deref(), Some("anthropic"));
    assert_eq!(routing.account.as_deref(), Some("max"));

    // Account scope (cc§9 "Account-type defaults").
    assert_eq!(
        routing.resolve_alias("default"),
        "anthropic/claude-opus-4-8"
    );
    assert_eq!(routing.resolve_alias("best"), "anthropic/claude-opus-4-8");
    // Provider scope.
    assert_eq!(routing.resolve_alias("fast"), "anthropic/claude-haiku-4-5");
    // The built-in table still resolves underneath both scopes.
    assert_eq!(
        routing.resolve_alias("sonnet"),
        "anthropic/claude-sonnet-4-6"
    );
    // The pattern: the captured stem is itself alias-resolved first.
    assert_eq!(
        routing.resolve_alias("sonnet[1m]"),
        "anthropic/claude-sonnet-4-6[1m]"
    );
    assert_eq!(
        routing.resolve_alias("default[1m]"),
        "anthropic/claude-opus-4-8[1m]"
    );
    // An unknown name still passes through, so any real slug works.
    assert_eq!(routing.resolve_alias("vendor/whatever"), "vendor/whatever");

    // A DIFFERENT declared scope over the same preset resolves the same
    // friendly name differently — which is what "per account/provider"
    // means. This is the user's own config layer, not a hand-built table.
    let root = temp_root("aliases");
    let config = parity_config(
        "cc-parity",
        &root,
        r#"
[capabilities.model_catalog]
account = "pro"
[capabilities.model_catalog.providers.anthropic.accounts.pro.aliases]
default = "anthropic/claude-sonnet-4-6"
"#,
    );
    assert_eq!(
        config.model_routing.resolve_alias("default"),
        "anthropic/claude-sonnet-4-6"
    );
}

/// The resolved alias is what the REQUEST carries — the table is not a
/// display-only relabelling.
#[tokio::test]
async fn a_config_alias_reaches_the_wire_under_cc_parity() {
    let root = temp_root("alias-wire");
    let config = parity_config("cc-parity", &root, "[core]\nmodel = \"default[1m]\"\n");
    let (provider, seen) = Recording::new();
    let mut agent = Agent::with_provider(config, Box::new(provider));
    agent.send("hi").await.unwrap();
    assert_eq!(
        seen.lock().unwrap()[0].model,
        "anthropic/claude-opus-4-8[1m]"
    );
}

// ---------------------------------------------------------------------------
// D9 — Mid-session model switching (cc + cx)
// ---------------------------------------------------------------------------

/// Both presets arm the governed switch. The switch moves the model for the
/// next request, keeps the conversation, records itself in the append-only
/// session journal, and emits itself — and cx-parity additionally injects
/// the switch notice Codex injects, which cc-parity does not.
#[tokio::test]
async fn both_presets_switch_the_model_mid_session_without_losing_the_session() {
    for (preset, expects_notice) in [("cc-parity", false), ("cx-parity", true)] {
        let root = temp_root("switch");
        let store = SessionStore::open(root.join("sessions")).unwrap();
        let name = "sess-switch";
        let events: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let sink = events.clone();

        let mut config = parity_config(preset, &root, "");
        assert!(
            config.model_switch_allow_switch,
            "{preset} must set core.model_switch.allow_switch"
        );
        assert_eq!(
            config.model_switch_notice, expects_notice,
            "{preset}: switch-notice posture"
        );
        config.event_sink = Some(Box::new(move |event: AgentEvent| {
            if let AgentEvent::ModelChanged { from, to, reason } = event {
                sink.lock()
                    .unwrap()
                    .push(format!("{from}->{to} ({reason:?})"));
            }
        }));
        let (provider, seen) = Recording::new();
        let mut agent = Agent::with_provider(config, Box::new(provider));
        supercode_harness::session_journal::arm(&mut agent, &store, name);

        agent.send("first").await.unwrap();
        let before_model = agent.model().to_string();
        let before_len = agent.history().len();

        // The switch, through the same routing table every other door uses.
        let target = agent.config().model_routing.resolve_alias("haiku");
        agent.switch_model(target.clone());

        assert_eq!(agent.model(), "anthropic/claude-haiku-4-5");
        assert_ne!(agent.model(), before_model);
        assert!(
            agent.history().len() >= before_len,
            "{preset}: the switch must not shorten the conversation"
        );
        assert_eq!(
            events.lock().unwrap().len(),
            1,
            "{preset}: no event emitted"
        );

        // The typed record, and its persisted twin in the ONE routing log.
        let records = agent.model_change_records();
        assert_eq!(records.len(), 1, "{preset}");
        assert_eq!(records[0].from_model, before_model);
        assert_eq!(records[0].to_model, "anthropic/claude-haiku-4-5");
        assert!(records[0].reasoning_filtered, "{preset}: dep 8 must run");
        assert!(
            !records[0].automatic(),
            "{preset}: a user switch has no reason"
        );
        let journal = store.load_journal(name).unwrap().expect("journal");
        assert_eq!(journal.model_changes.len(), 1, "{preset}: journal record");
        assert_eq!(
            journal.model_changes[0].to_model,
            "anthropic/claude-haiku-4-5"
        );

        // Codex tells the conversation; Claude Code does not.
        let notices = agent
            .history()
            .iter()
            .filter(|m| {
                m.content
                    .as_deref()
                    .is_some_and(|c| c.starts_with("[model changed:"))
            })
            .count();
        assert_eq!(notices, usize::from(expects_notice), "{preset}: notice");

        // The NEXT request actually goes to the new model, over the same
        // conversation.
        agent.send("second").await.unwrap();
        let requests = seen.lock().unwrap();
        assert_eq!(requests[0].model, before_model, "{preset}");
        assert_eq!(requests[1].model, "anthropic/claude-haiku-4-5", "{preset}");
        assert!(
            requests[1].messages.len() > requests[0].messages.len(),
            "{preset}: the session was lost across the switch"
        );
    }
}

// ---------------------------------------------------------------------------
// D9 — Reasoning effort / thinking budgets (cc + cx)
// ---------------------------------------------------------------------------

/// The level, the per-model tier, the cap, the budget and the plan-mode
/// override are all decided by the SAME routing call, and all of them reach
/// the request the loop builds.
#[tokio::test]
async fn effort_tiers_budgets_and_caps_reach_the_request_under_both_presets() {
    for preset in ["cc-parity", "cx-parity"] {
        let root = temp_root("effort");
        // `thinking_budget` is the env-equivalent knob (CC's
        // MAX_THINKING_TOKENS) layered over the resolved preset.
        let config = parity_config(
            preset,
            &root,
            "[capabilities.model_catalog]\nthinking_budget = 12000\n",
        );
        assert_eq!(config.effort.as_deref(), Some("medium"), "{preset}");
        let (provider, seen) = Recording::new();
        let mut agent = Agent::with_provider(config, Box::new(provider));
        agent.send("hi").await.unwrap();
        {
            let requests = seen.lock().unwrap();
            assert_eq!(requests[0].effort.as_deref(), Some("medium"), "{preset}");
            assert_eq!(requests[0].thinking_budget, Some(12000), "{preset}");
        }

        // The per-model TIER: switching to the small model lowers the
        // effort, because the model's own rule caps it — no second knob.
        agent.switch_model("anthropic/claude-haiku-4-5");
        agent.send("again").await.unwrap();
        let requests = seen.lock().unwrap();
        let expected = if preset == "cc-parity" {
            // cc-parity caps Haiku at `low`.
            Some("low")
        } else {
            Some("medium")
        };
        assert_eq!(requests[1].effort.as_deref(), expected, "{preset}");
    }
}

/// cc-parity's plan mode runs at its own effort tier while the mode is
/// live, and hands the session level back when it leaves.
#[tokio::test]
async fn cc_parity_plan_mode_steers_the_effort_tier_while_it_is_active() {
    let root = temp_root("plan-effort");
    let config = parity_config("cc-parity", &root, "");
    assert_eq!(config.plan_mode_effort.as_deref(), Some("high"));
    let (provider, seen) = Recording::new();
    let mut agent = Agent::with_provider(config, Box::new(provider));

    agent.send("before").await.unwrap();
    agent.plan_mode().enter(Some("research first"));
    agent.send("during").await.unwrap();
    agent.plan_mode().exit();
    agent.send("after").await.unwrap();

    let requests = seen.lock().unwrap();
    assert_eq!(requests[0].effort.as_deref(), Some("medium"));
    assert_eq!(requests[1].effort.as_deref(), Some("high"));
    assert_eq!(requests[2].effort.as_deref(), Some("medium"));
}

// ---------------------------------------------------------------------------
// D9 — Failure fallback model chains (cc + cx)
// ---------------------------------------------------------------------------

/// The chain is EXECUTED: an overloaded model is abandoned for the next
/// entry mid-turn, the hop is recorded like any other mid-session switch
/// (journal included), and the model stays switched for the rest of the
/// session. A failure no other model could fix is never walked.
#[tokio::test]
async fn an_overloaded_model_walks_the_configured_chain_under_both_presets() {
    for preset in ["cc-parity", "cx-parity"] {
        let root = temp_root("fallback");
        let store = SessionStore::open(root.join("sessions")).unwrap();
        let name = "sess-fallback";
        // `--fallback-model sonnet --fallback-model haiku` — Claude Code's
        // own per-invocation shape for this row, layered over the preset.
        let config = parity_config(
            preset,
            &root,
            "[capabilities.model_catalog]\nfallback = [\"sonnet\", \"haiku\"]\n",
        );
        let main = config.model.clone();
        assert_eq!(
            config.model_fallback,
            vec![
                "anthropic/claude-sonnet-4-6".to_string(),
                "anthropic/claude-haiku-4-5".to_string(),
            ],
            "{preset}: the chain resolves through the alias table"
        );

        let (provider, attempts) = FailsFor::new(&[&main, "anthropic/claude-sonnet-4-6"], 529);
        let mut agent = Agent::with_provider(config, Box::new(provider));
        supercode_harness::session_journal::arm(&mut agent, &store, name);
        agent.send("hello").await.unwrap();

        assert_eq!(
            *attempts.lock().unwrap(),
            vec![
                main.clone(),
                "anthropic/claude-sonnet-4-6".to_string(),
                "anthropic/claude-haiku-4-5".to_string(),
            ],
            "{preset}: the chain must be walked in order"
        );
        assert_eq!(agent.model(), "anthropic/claude-haiku-4-5", "{preset}");
        let records = agent.model_change_records();
        assert_eq!(records.len(), 2, "{preset}: one record per hop");
        assert!(records[0].automatic(), "{preset}: a hop names its cause");
        assert!(records[1]
            .reason
            .as_deref()
            .is_some_and(|r| r.contains("529")));
        let journal = store.load_journal(name).unwrap().expect("journal");
        assert_eq!(journal.model_changes.len(), 2, "{preset}: persisted hops");
    }
}

/// A 4xx that is not a rate limit would fail identically against every
/// entry, so the chain is not walked and the caller sees the real error.
#[tokio::test]
async fn a_caller_error_never_walks_the_chain() {
    let root = temp_root("no-fallback");
    let config = parity_config(
        "cc-parity",
        &root,
        "[capabilities.model_catalog]\nfallback = [\"sonnet\"]\n",
    );
    let main = config.model.clone();
    let (provider, attempts) = FailsFor::new(&[&main], 400);
    let mut agent = Agent::with_provider(config, Box::new(provider));
    assert!(agent.send("hello").await.is_err());
    assert_eq!(*attempts.lock().unwrap(), vec![main.clone()]);
    assert_eq!(agent.model(), main);
    assert!(agent.model_change_records().is_empty());
}

// ---------------------------------------------------------------------------
// D9 — Per-model capability bits drive tools (cx)
// ---------------------------------------------------------------------------

/// cx-parity's catalog bits decide which WRITE SURFACE a model is offered,
/// inside `ToolRegistry::from_config`'s own selection: the family that takes
/// the freeform envelope gets `apply_patch` and never the edit/write pair;
/// the family that does not gets the pair and never `apply_patch` — even
/// though `[core.tools] enabled` lists neither.
#[test]
fn cx_parity_swaps_the_write_surface_per_model() {
    let root = temp_root("bits");
    let base = parity_config("cx-parity", &root, "");
    assert!(
        !base.core_tools_enabled.iter().any(|t| t == "edit_file"),
        "cx-parity's core tool list must not name edit_file"
    );

    let surface = |model: &str| {
        let config = parity_config(
            "cx-parity",
            &root,
            &format!("[core]\nmodel = \"{model}\"\n"),
        );
        let registry = ToolRegistry::from_config(&config);
        (
            registry.get("apply_patch").is_some(),
            registry.get("edit_file").is_some(),
            registry.get("write_file").is_some(),
        )
    };

    // The envelope family.
    assert_eq!(surface("openai/gpt-5.5"), (true, false, false));
    assert_eq!(surface("openai/gpt-5-codex"), (true, false, false));
    // The family the catalog marks as NOT taking it.
    assert_eq!(surface("openai/gpt-4.1"), (false, true, true));
    // A model no rule matches keeps the preset's own selection, so nothing
    // silently changes for a config that names no bits.
    assert_eq!(surface("vendor/unknown"), (true, false, false));
}

// ---------------------------------------------------------------------------
// D9 — Fast mode / service tiers (cc + cx)
// ---------------------------------------------------------------------------

/// Both presets put a service tier on the request, and the session-level
/// toggle (`/fast`) wins over the configured rule for every subsequent
/// request until it is cleared.
#[tokio::test]
async fn the_service_tier_rides_the_request_and_the_fast_toggle_wins() {
    for preset in ["cc-parity", "cx-parity"] {
        let root = temp_root("tier");
        let config = parity_config(preset, &root, "");
        let (provider, seen) = Recording::new();
        let mut agent = Agent::with_provider(config, Box::new(provider));

        agent.send("one").await.unwrap();
        agent.set_service_tier(Some("priority".into()));
        agent.send("two").await.unwrap();
        agent.set_service_tier(None);
        agent.send("three").await.unwrap();

        let requests = seen.lock().unwrap();
        assert_eq!(
            requests[0].service_tier.as_deref(),
            Some("auto"),
            "{preset}"
        );
        assert_eq!(
            requests[1].service_tier.as_deref(),
            Some("priority"),
            "{preset}"
        );
        assert_eq!(
            requests[2].service_tier.as_deref(),
            Some("auto"),
            "{preset}"
        );
    }
}

// ---------------------------------------------------------------------------
// D9 — Org model allowlists / effort caps (config layer)
// ---------------------------------------------------------------------------

/// The allow/deny lists REFUSE at resolve time — an error, never a warning —
/// and they bind every model the table hands out, not just `core.model`.
/// The effort cap clamps rather than refusing, because that is what a cap
/// means.
#[test]
fn the_allowlist_refuses_and_the_effort_cap_clamps_over_cc_parity() {
    let attempt = |extra: &str| {
        resolve(
            &format!("extends = \"cc-parity\"\n{extra}"),
            None,
            &ResolveOptions { strict: true },
        )
    };

    // A denied main model.
    let err = attempt(
        r#"
[capabilities.model_catalog]
denied_models = ["anthropic/claude-opus-*"]
"#,
    )
    .expect_err("a denied model must refuse");
    assert!(matches!(err, ResolveError::ModelNotAllowed(_)), "{err}");

    // An allowlist the preset's SMALL model falls outside of — the rule
    // binds every model the table hands out.
    let err = attempt(
        r#"
[capabilities.model_catalog]
allowed_models = ["anthropic/claude-opus-4-8"]
"#,
    )
    .expect_err("the small model is outside the allowlist");
    assert!(matches!(err, ResolveError::ModelNotAllowed(_)), "{err}");

    // Inside the list: resolves, unchanged.
    let ok = attempt(
        r#"
[capabilities.model_catalog]
allowed_models = ["anthropic/*"]
"#,
    )
    .expect("an allowed model resolves");
    assert_eq!(ok.config.model, "anthropic/claude-opus-4-8");

    // §3.3 monotonic tightening: a PROJECT layer can never lift a
    // restriction the user/global layer set — the restriction keys are
    // stripped from it, while its own aliases still land.
    let layered = supercode_harness::configfile::resolve(
        r#"
extends = "cc-parity"
[capabilities.model_catalog]
denied_models = ["anthropic/claude-opus-*"]
"#,
        Some(
            r#"
[capabilities.model_catalog]
denied_models = []
[capabilities.model_catalog.aliases]
house = "anthropic/claude-sonnet-4-6"
"#,
        ),
        &ResolveOptions { strict: false },
    );
    assert!(
        matches!(layered, Err(ResolveError::ModelNotAllowed(_))),
        "a project layer must not be able to lift the deny list"
    );

    // The cap clamps the session level and says so.
    let capped = attempt(
        r#"
[core]
effort = "ultra"
[capabilities.model_catalog]
max_effort = "low"
"#,
    )
    .expect("a cap clamps rather than refusing");
    assert!(
        capped.warnings.iter().any(|w| w.contains("max_effort")),
        "the clamp must be named: {:?}",
        capped.warnings
    );
    let routing = capped.config.model_routing;
    assert_eq!(
        routing
            .effective_effort("anthropic/claude-opus-4-8", Some("ultra"))
            .as_deref(),
        Some("low")
    );
}

// ---------------------------------------------------------------------------
// D9 — Model-served-vs-requested provenance (cc + cx)
// ---------------------------------------------------------------------------

/// The per-turn record carries BOTH sides, the divergence is visible, and
/// the log is on disk — through the session journal both presets arm, not a
/// save call nothing makes.
#[tokio::test]
async fn the_usage_record_shows_served_vs_requested_and_survives_the_process() {
    for preset in ["cc-parity", "cx-parity"] {
        let root = temp_root("provenance");
        let store = SessionStore::open(root.join("sessions")).unwrap();
        let name = "sess-provenance";
        let config = parity_config(preset, &root, "");
        let requested = config.model.clone();
        let (provider, _seen) = Recording::serving("anthropic/claude-opus-4-8-20260101");
        let mut agent = Agent::with_provider(config, Box::new(provider));
        supercode_harness::session_journal::arm(&mut agent, &store, name);
        agent.send("hi").await.unwrap();

        let records = agent.usage_records();
        assert_eq!(records.len(), 1, "{preset}");
        assert_eq!(records[0].model, requested, "{preset}");
        assert_eq!(
            records[0].served_model.as_deref(),
            Some("anthropic/claude-opus-4-8-20260101"),
            "{preset}"
        );
        assert!(records[0].diverged(), "{preset}");

        // Across a DROP: the agent is destroyed and the record is read back
        // off disk.
        drop(agent);
        let journal = store.load_journal(name).unwrap().expect("journal");
        assert_eq!(journal.usage.len(), 1, "{preset}: persisted usage record");
        assert_eq!(journal.usage[0].model, requested, "{preset}");
        assert_eq!(
            journal.usage[0].served_model.as_deref(),
            Some("anthropic/claude-opus-4-8-20260101"),
            "{preset}"
        );
    }
}

/// A provider that reports nothing leaves the record saying nothing — an
/// unknown is never recorded as agreement.
#[tokio::test]
async fn a_silent_provider_never_makes_the_record_claim_agreement() {
    let root = temp_root("provenance-silent");
    let config = parity_config("cc-parity", &root, "");
    let (provider, _seen) = Recording::new();
    let mut agent = Agent::with_provider(config, Box::new(provider));
    agent.send("hi").await.unwrap();
    let records = agent.usage_records();
    assert_eq!(records[0].served_model, None);
    assert!(!records[0].diverged());
}

// ---------------------------------------------------------------------------
// D9 — Small/utility model routing (cc + cx)
// ---------------------------------------------------------------------------

/// The cheap-model side-call is REACHABLE under both presets: both arm
/// compaction's own span summary, which routes to `small_model` with the
/// D-9 main-model fallback. cc-parity pins Haiku, so the side-call really
/// goes somewhere cheaper than the main model; cx-parity pins none, so it
/// falls back — Codex's own small-model consumers are its memory
/// extract/consolidation models, and cx-parity keeps `memory` off to match
/// `[features].memories = false`.
#[test]
fn the_small_model_side_call_is_armed_under_both_presets() {
    for preset in ["cc-parity", "cx-parity"] {
        let root = temp_root("small-model");
        let config = parity_config(preset, &root, "");
        // The gate the CLI's `SpanSummaryGate::capture` reads.
        assert!(config.compaction_summarize, "{preset}");
        assert!(config.compaction_enabled, "{preset}");
        assert!(
            config.compact_after_messages.is_some() || config.compaction_reserve_tokens.is_some(),
            "{preset}: compaction must be able to fire at all"
        );
        let routed = config
            .small_model
            .clone()
            .unwrap_or_else(|| config.model.clone());
        if preset == "cc-parity" {
            assert_eq!(routed, "anthropic/claude-haiku-4-5");
            assert_ne!(
                routed, config.model,
                "cc-parity must route somewhere cheaper"
            );
            // CC also titles a session on that same cheap model.
            assert!(config.auto_title, "cc-parity must arm the titler");
        } else {
            assert_eq!(routed, config.model, "cx-parity is the D-9 fallback case");
            assert!(
                !config
                    .module_activation
                    .is_active(supercode_harness::modules::ModuleId::Memory),
                "cx-parity keeps memories off"
            );
        }
    }
}