agent-doc 0.32.3

Interactive document sessions with AI agents
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
//! # Module: model_tier
//!
//! ## Spec
//! - Defines `Tier`: a harness-agnostic complexity bucket (`Auto`, `Low`, `Med`, `High`)
//!   used to classify task complexity and gate model selection.
//! - `Tier` derives `PartialOrd` such that `Auto < Low < Med < High`. Gating is a simple
//!   `>` comparison: a task whose effective tier exceeds the running model's tier should
//!   prompt the user to switch.
//! - Defines `ModelConfig` (under `[model]` in the global TOML config) and `TierMap` (per-harness
//!   tier→model name resolution under `[model.tiers.<harness>]`).
//! - `detect_harness()` reads environment variables (`CLAUDE_CODE_SESSION`, `CODEX_SESSION`)
//!   to identify the active agent harness, falling back to `"default"`.
//! - `resolve_tier_to_model(tier, harness, config)` maps a `Tier` to the concrete model name
//!   configured for the given harness, falling back to built-in defaults for the
//!   `claude-code`, `codex`, and `default` harnesses.
//! - `tier_from_model_name(name, harness, config)` is the reverse lookup: given a concrete
//!   model name (e.g., `"opus"`), find the tier it belongs to in the harness mapping.
//! - `Tier::FromStr` accepts case-insensitive `auto | low | med | high`.
//!
//! ## Agentic Contracts
//! - **Total ordering**: `Tier` implements `PartialOrd` deterministically; gating logic
//!   is a single comparison and can be safely executed by any model tier.
//! - **Auto is the lowest**: `Tier::Auto` represents "no preference" and compares less than
//!   `Low`. The `effective_tier` composition treats `Auto` as "fall through to next source."
//! - **Built-in defaults**: when no `[model.tiers.<harness>]` section is present, the
//!   resolver falls back to compiled-in maps for known harnesses. This means a fresh
//!   install needs zero config for the common case.
//! - **Reverse lookup is partial**: `tier_from_model_name` returns `None` if the model
//!   name doesn't appear in any tier slot for the harness. Callers should treat `None`
//!   as "unknown — leave tier as Auto."
//!
//! ## Evals
//! - `tier_ordering`: `Auto < Low < Med < High` holds for `<`, `>`, `<=`, `>=`.
//! - `tier_from_str_case_insensitive`: `"LOW"`, `"low"`, `"Low"` all parse to `Tier::Low`.
//! - `tier_from_str_invalid`: unknown strings return `Err`.
//! - `harness_detection_default`: with no env vars set, `detect_harness()` returns `"default"`.
//! - `resolve_builtin_claude_code`: `resolve_tier_to_model(Tier::High, "claude-code", &Config::default())`
//!   returns `Some("opus")`.
//! - `resolve_unknown_harness_uses_default`: an unknown harness falls through to the
//!   `"default"` built-in map.
//! - `tier_from_model_name_roundtrip`: `tier_from_model_name("opus", "claude-code", ...)`
//!   returns `Some(Tier::High)`.

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::str::FromStr;

/// Harness-agnostic model complexity tier.
///
/// Ordering: `Auto < Low < Med < High`. Gating logic uses a simple `>` comparison —
/// a task whose effective tier exceeds the running model's tier should prompt the
/// user to switch models.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Tier {
    /// No preference; fall through to next source in the precedence chain.
    #[default]
    Auto,
    /// Cheap, fast model — small content additions, simple questions.
    Low,
    /// Default working model — multi-section edits, planning, moderate diffs.
    Med,
    /// Powerful model — complex debugging, architecture decisions, large code changes.
    High,
}

impl std::fmt::Display for Tier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Auto => write!(f, "auto"),
            Self::Low => write!(f, "low"),
            Self::Med => write!(f, "med"),
            Self::High => write!(f, "high"),
        }
    }
}

impl FromStr for Tier {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "auto" => Ok(Self::Auto),
            "low" => Ok(Self::Low),
            "med" | "medium" => Ok(Self::Med),
            "high" => Ok(Self::High),
            other => Err(anyhow!(
                "invalid tier `{}`: expected one of auto|low|med|high",
                other
            )),
        }
    }
}

/// Per-harness tier → concrete model name map.
///
/// Configured under `[model.tiers.<harness>]` in the global config.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct TierMap {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub low: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub med: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub high: Option<String>,
}

impl TierMap {
    pub fn get(&self, tier: Tier) -> Option<&str> {
        match tier {
            Tier::Auto => None,
            Tier::Low => self.low.as_deref(),
            Tier::Med => self.med.as_deref(),
            Tier::High => self.high.as_deref(),
        }
    }

    /// Reverse lookup: find which tier a concrete model name belongs to.
    pub fn tier_of(&self, model_name: &str) -> Option<Tier> {
        if self.low.as_deref() == Some(model_name) {
            Some(Tier::Low)
        } else if self.med.as_deref() == Some(model_name) {
            Some(Tier::Med)
        } else if self.high.as_deref() == Some(model_name) {
            Some(Tier::High)
        } else {
            None
        }
    }
}

/// Global `[model]` config section.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
    /// Whether automatic tier-based recommendations are enabled (default: true).
    #[serde(default = "default_auto")]
    pub auto: bool,
    /// Per-harness tier → model name maps. Key is the harness name
    /// (e.g., `claude-code`, `codex`, `default`).
    #[serde(default)]
    pub tiers: BTreeMap<String, TierMap>,
}

fn default_auto() -> bool {
    true
}

/// Built-in tier map for the `claude-code` harness.
fn builtin_claude_code() -> TierMap {
    TierMap {
        low: Some("haiku".to_string()),
        med: Some("sonnet".to_string()),
        high: Some("opus".to_string()),
    }
}

/// Built-in tier map for the `codex` harness.
fn builtin_codex() -> TierMap {
    TierMap {
        low: Some("gpt-4o-mini".to_string()),
        med: Some("gpt-4o".to_string()),
        high: Some("o3".to_string()),
    }
}

/// Built-in fallback tier map.
fn builtin_default() -> TierMap {
    TierMap {
        low: Some("haiku".to_string()),
        med: Some("sonnet".to_string()),
        high: Some("opus".to_string()),
    }
}

/// Return the built-in tier map for a known harness, or `default` for unknowns.
fn builtin_for(harness: &str) -> TierMap {
    match harness {
        "claude-code" => builtin_claude_code(),
        "codex" => builtin_codex(),
        _ => builtin_default(),
    }
}

/// Detect the active harness from environment variables.
///
/// Returns `"claude-code"` if `CLAUDE_CODE_SESSION` is set, `"codex"` if `CODEX_SESSION`
/// is set, otherwise `"default"`.
pub fn detect_harness() -> String {
    if std::env::var("CLAUDE_CODE_SESSION").is_ok() || std::env::var("CLAUDECODE").is_ok() {
        "claude-code".to_string()
    } else if std::env::var("CODEX_SESSION").is_ok() {
        "codex".to_string()
    } else {
        "default".to_string()
    }
}

/// Resolve a `Tier` to a concrete model name for the given harness.
///
/// Tries the user's `[model.tiers.<harness>]` config first, then falls back to the
/// built-in map for the harness. Returns `None` for `Tier::Auto`.
pub fn resolve_tier_to_model(
    tier: Tier,
    harness: &str,
    model_config: &ModelConfig,
) -> Option<String> {
    if matches!(tier, Tier::Auto) {
        return None;
    }
    if let Some(map) = model_config.tiers.get(harness)
        && let Some(name) = map.get(tier)
    {
        return Some(name.to_string());
    }
    builtin_for(harness).get(tier).map(|s| s.to_string())
}

/// Reverse lookup: given a concrete model name, find its tier in the harness's mapping.
///
/// Tries the user's config first, then falls back to the built-in map. Returns `None`
/// if the model name doesn't appear in any tier slot for the harness.
pub fn tier_from_model_name(
    model_name: &str,
    harness: &str,
    model_config: &ModelConfig,
) -> Option<Tier> {
    if let Some(map) = model_config.tiers.get(harness)
        && let Some(t) = map.tier_of(model_name)
    {
        return Some(t);
    }
    builtin_for(harness).tier_of(model_name)
}

/// Extract the value inside a `<!-- agent:model -->...<!-- /agent:model -->` component.
///
/// Returns the trimmed inner content if the component is present, `None` otherwise.
/// This uses the existing component parser, so guards against fenced code blocks
/// and inline code apply automatically.
pub fn extract_model_component(content: &str) -> Option<String> {
    let comps = crate::component::parse(content).ok()?;
    let comp = comps.into_iter().find(|c| c.name == "model")?;
    let inner = &content[comp.open_end..comp.close_start];
    let trimmed = inner.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Resolve a `<!-- agent:model -->` component value to a `Tier`.
///
/// Accepts tier names (`auto|low|med|high`) or concrete model names (resolved
/// via the harness's tier map). Returns `None` if the value is unrecognized.
pub fn component_value_to_tier(
    value: &str,
    harness: &str,
    model_config: &ModelConfig,
) -> Option<Tier> {
    if let Ok(tier) = Tier::from_str(value) {
        return Some(tier);
    }
    tier_from_model_name(value, harness, model_config)
}

/// Compute a `suggested_tier` from structural diff signals.
///
/// This is the deterministic, harness-agnostic heuristic used when no explicit
/// tier source (inline command, component, frontmatter) is present.
///
/// Inputs:
/// - `diff_type`: classification string from `diff::classify_diff` (e.g., `"simple_question"`)
/// - `lines_added`: count of `+` lines in the unified diff (excluding `+++`)
/// - `doc_path`: relative document path; certain prefixes bump the tier
///
/// Mapping (primary):
/// - `simple_question`, `approval`, `boundary_artifact`, `annotation` → `Low`
/// - `content_addition` < 10 lines → `Low`; ≥ 10 lines → `Med`
/// - `multi_topic`, `structural_change` → `Med`
/// - unknown / missing → `Med` (safe default)
///
/// Path boost: `tasks/software/` and `src/**/specs/` paths bump one tier (cap `High`).
pub fn suggested_tier(diff_type: Option<&str>, lines_added: usize, doc_path: &std::path::Path) -> Tier {
    let base = match diff_type {
        Some("simple_question") | Some("approval") | Some("boundary_artifact") | Some("annotation") => {
            Tier::Low
        }
        Some("content_addition") => {
            if lines_added < 10 {
                Tier::Low
            } else {
                Tier::Med
            }
        }
        Some("multi_topic") | Some("structural_change") => Tier::Med,
        _ => Tier::Med,
    };

    // Path boost: tasks/software/ → bump one tier (cap at High).
    let path_str = doc_path.to_string_lossy();
    let boost = path_str.contains("tasks/software/")
        || path_str.contains("/specs/")
        || path_str.contains("agent-doc-bugs")
        || path_str.contains("plan-")
        || path_str.contains("/plan.md");
    if boost {
        match base {
            Tier::Auto | Tier::Low => Tier::Med,
            Tier::Med => Tier::High,
            Tier::High => Tier::High,
        }
    } else {
        base
    }
}

/// Result of scanning a unified diff for an inline `/model <x>` command.
#[derive(Debug, Clone)]
pub struct ModelSwitchScan {
    /// The concrete model name from `/model <name>` (e.g., `"opus"`).
    pub model_switch: Option<String>,
    /// The resolved tier for the model switch (e.g., `Tier::High` for `opus`).
    pub model_switch_tier: Option<Tier>,
    /// The diff text with the `/model <x>` command line(s) stripped.
    pub stripped_diff: String,
}

/// Scan a unified diff for an inline `/model <x>` command in user-added lines.
///
/// Behavior:
/// - Only matches `+` lines (user additions), excluding `+++` headers.
/// - Skips lines inside fenced code blocks (``` or ~~~).
/// - Skips blockquote lines (`+>`).
/// - Pattern: line content matches `/model <arg>` (whitespace allowed).
/// - On match, the line is removed from the returned diff so it does not
///   propagate to classification or response generation.
/// - Only the first match is captured; subsequent `/model` lines are still stripped.
///
/// The `arg` is parsed via `parse_model_arg`, which accepts both tier names
/// (`low|med|high`) and concrete model names (`opus|sonnet|...`).
pub fn scan_model_switch(
    diff: &str,
    harness: &str,
    model_config: &ModelConfig,
) -> ModelSwitchScan {
    let mut model_switch: Option<String> = None;
    let mut model_switch_tier: Option<Tier> = None;
    let mut kept_lines: Vec<&str> = Vec::with_capacity(diff.lines().count());

    let mut in_fence = false;
    let mut fence_char = '`';
    let mut fence_len = 0usize;

    for line in diff.lines() {
        // Skip unified diff meta-lines unchanged.
        if line.starts_with("---") || line.starts_with("+++") || line.starts_with("@@") {
            kept_lines.push(line);
            continue;
        }

        // Strip leading diff marker to inspect content.
        let content = if line.starts_with('+') || line.starts_with('-') || line.starts_with(' ') {
            &line[1..]
        } else {
            line
        };

        // Track code-fence state across all lines.
        let trimmed = content.trim_start();
        if !in_fence {
            let fc = trimmed.chars().next().unwrap_or('\0');
            if (fc == '`' || fc == '~')
                && let fl = trimmed.chars().take_while(|&c| c == fc).count()
                && fl >= 3
            {
                in_fence = true;
                fence_char = fc;
                fence_len = fl;
                kept_lines.push(line);
                continue;
            }
        } else {
            let fc = trimmed.chars().next().unwrap_or('\0');
            if fc == fence_char {
                let fl = trimmed.chars().take_while(|&c| c == fc).count();
                if fl >= fence_len && trimmed[fl..].trim().is_empty() {
                    in_fence = false;
                    kept_lines.push(line);
                    continue;
                }
            }
        }

        // Only consider `+` lines (excluding `+++`) for stripping.
        let is_added = line.starts_with('+') && !line.starts_with("+++");
        if !is_added {
            kept_lines.push(line);
            continue;
        }

        // In a fence — keep as-is (no stripping inside fences).
        if in_fence {
            kept_lines.push(line);
            continue;
        }

        // Skip blockquotes.
        if content.starts_with('>') {
            kept_lines.push(line);
            continue;
        }

        // Match `/model <arg>` pattern.
        let stripped = content.trim_end();
        if let Some(rest) = stripped.strip_prefix("/model")
            && let Some(arg) = rest.split_whitespace().next()
            && !arg.is_empty()
        {
            // Parse the arg into (tier, concrete_name).
            if let Some((tier, name)) = parse_model_arg(arg, harness, model_config) {
                if model_switch.is_none() {
                    model_switch = Some(name);
                    model_switch_tier = Some(tier);
                }
                // Drop the line from the diff regardless (always strip /model).
                continue;
            }
            // Unknown arg — still strip the line to avoid /model leaking through.
            continue;
        }

        kept_lines.push(line);
    }

    ModelSwitchScan {
        model_switch,
        model_switch_tier,
        stripped_diff: kept_lines.join("\n"),
    }
}

/// Compose the final `effective_tier` from all available sources.
///
/// Precedence (highest wins): inline `/model` command, then `<!-- agent:model -->`
/// component, then `agent_doc_model_tier` frontmatter, then diff heuristic.
/// `Tier::Auto` is a no-preference sentinel and falls through to the next source.
pub fn compose_effective_tier(
    model_switch_tier: Option<Tier>,
    component_tier: Option<Tier>,
    frontmatter_tier: Option<Tier>,
    suggested: Tier,
) -> Tier {
    for candidate in [model_switch_tier, component_tier, frontmatter_tier] {
        if let Some(t) = candidate
            && !matches!(t, Tier::Auto)
        {
            return t;
        }
    }
    suggested
}

/// Parse a `/model <arg>` argument: either a tier name (`low|med|high`) or a concrete
/// model name (`opus|sonnet|...`).
///
/// Returns the resolved `Tier` and the concrete model name (the original arg if it
/// was already a concrete name; the resolved name from config/built-ins if it was a
/// tier name).
pub fn parse_model_arg(
    arg: &str,
    harness: &str,
    model_config: &ModelConfig,
) -> Option<(Tier, String)> {
    let trimmed = arg.trim();
    // Try parsing as a tier name first.
    if let Ok(tier) = Tier::from_str(trimmed) {
        if matches!(tier, Tier::Auto) {
            return None;
        }
        let name = resolve_tier_to_model(tier, harness, model_config)
            .unwrap_or_else(|| trimmed.to_string());
        return Some((tier, name));
    }
    // Otherwise treat as a concrete model name and reverse-lookup the tier.
    if let Some(tier) = tier_from_model_name(trimmed, harness, model_config) {
        return Some((tier, trimmed.to_string()));
    }
    // Unknown — accept the name but leave tier as Auto so it doesn't gate.
    None
}

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

    #[test]
    fn tier_ordering() {
        assert!(Tier::Auto < Tier::Low);
        assert!(Tier::Low < Tier::Med);
        assert!(Tier::Med < Tier::High);
        assert!(Tier::High > Tier::Low);
        assert!(Tier::Med >= Tier::Med);
    }

    #[test]
    fn tier_from_str_case_insensitive() {
        assert_eq!("LOW".parse::<Tier>().unwrap(), Tier::Low);
        assert_eq!("low".parse::<Tier>().unwrap(), Tier::Low);
        assert_eq!("Low".parse::<Tier>().unwrap(), Tier::Low);
        assert_eq!("AUTO".parse::<Tier>().unwrap(), Tier::Auto);
        assert_eq!("med".parse::<Tier>().unwrap(), Tier::Med);
        assert_eq!("medium".parse::<Tier>().unwrap(), Tier::Med);
        assert_eq!("HIGH".parse::<Tier>().unwrap(), Tier::High);
    }

    #[test]
    fn tier_from_str_invalid() {
        assert!("ultra".parse::<Tier>().is_err());
        assert!("".parse::<Tier>().is_err());
        assert!("opus".parse::<Tier>().is_err());
    }

    #[test]
    fn tier_display() {
        assert_eq!(Tier::Low.to_string(), "low");
        assert_eq!(Tier::Med.to_string(), "med");
        assert_eq!(Tier::High.to_string(), "high");
        assert_eq!(Tier::Auto.to_string(), "auto");
    }

    #[test]
    fn harness_detection_returns_known_value() {
        // Don't mutate env (Rust 2024 marks env mutators unsafe + tests may run
        // in parallel). Just assert the function returns one of the known values.
        let h = detect_harness();
        assert!(
            matches!(h.as_str(), "claude-code" | "codex" | "default"),
            "unexpected harness: {h}"
        );
    }

    #[test]
    fn resolve_builtin_claude_code() {
        let cfg = ModelConfig::default();
        assert_eq!(
            resolve_tier_to_model(Tier::High, "claude-code", &cfg).as_deref(),
            Some("opus")
        );
        assert_eq!(
            resolve_tier_to_model(Tier::Med, "claude-code", &cfg).as_deref(),
            Some("sonnet")
        );
        assert_eq!(
            resolve_tier_to_model(Tier::Low, "claude-code", &cfg).as_deref(),
            Some("haiku")
        );
        assert_eq!(resolve_tier_to_model(Tier::Auto, "claude-code", &cfg), None);
    }

    #[test]
    fn resolve_builtin_codex() {
        let cfg = ModelConfig::default();
        assert_eq!(
            resolve_tier_to_model(Tier::High, "codex", &cfg).as_deref(),
            Some("o3")
        );
        assert_eq!(
            resolve_tier_to_model(Tier::Low, "codex", &cfg).as_deref(),
            Some("gpt-4o-mini")
        );
    }

    #[test]
    fn resolve_unknown_harness_uses_default() {
        let cfg = ModelConfig::default();
        // Unknown harness falls through to the `default` built-in map.
        assert_eq!(
            resolve_tier_to_model(Tier::High, "junie", &cfg).as_deref(),
            Some("opus")
        );
    }

    #[test]
    fn user_config_overrides_builtin() {
        let mut cfg = ModelConfig::default();
        let mut tiers = BTreeMap::new();
        tiers.insert(
            "claude-code".to_string(),
            TierMap {
                low: Some("haiku-3".to_string()),
                med: Some("sonnet-4".to_string()),
                high: Some("opus-4-1".to_string()),
            },
        );
        cfg.tiers = tiers;
        assert_eq!(
            resolve_tier_to_model(Tier::High, "claude-code", &cfg).as_deref(),
            Some("opus-4-1")
        );
    }

    #[test]
    fn tier_from_model_name_builtin() {
        let cfg = ModelConfig::default();
        assert_eq!(
            tier_from_model_name("opus", "claude-code", &cfg),
            Some(Tier::High)
        );
        assert_eq!(
            tier_from_model_name("sonnet", "claude-code", &cfg),
            Some(Tier::Med)
        );
        assert_eq!(
            tier_from_model_name("haiku", "claude-code", &cfg),
            Some(Tier::Low)
        );
        assert_eq!(tier_from_model_name("unknown", "claude-code", &cfg), None);
    }

    #[test]
    fn parse_model_arg_tier_name() {
        let cfg = ModelConfig::default();
        let (tier, name) = parse_model_arg("high", "claude-code", &cfg).unwrap();
        assert_eq!(tier, Tier::High);
        assert_eq!(name, "opus");
    }

    #[test]
    fn parse_model_arg_concrete_name() {
        let cfg = ModelConfig::default();
        let (tier, name) = parse_model_arg("opus", "claude-code", &cfg).unwrap();
        assert_eq!(tier, Tier::High);
        assert_eq!(name, "opus");
    }

    #[test]
    fn parse_model_arg_unknown() {
        let cfg = ModelConfig::default();
        assert!(parse_model_arg("xyz-3000", "claude-code", &cfg).is_none());
    }

    #[test]
    fn parse_model_arg_auto_rejected() {
        let cfg = ModelConfig::default();
        assert!(parse_model_arg("auto", "claude-code", &cfg).is_none());
    }

    #[test]
    fn extract_model_component_present() {
        let doc = "# Title\n\n<!-- agent:model -->\nhigh\n<!-- /agent:model -->\n\nbody\n";
        assert_eq!(extract_model_component(doc).as_deref(), Some("high"));
    }

    #[test]
    fn extract_model_component_absent() {
        let doc = "# Title\n\nbody only\n";
        assert_eq!(extract_model_component(doc), None);
    }

    #[test]
    fn extract_model_component_empty_inner() {
        let doc = "<!-- agent:model -->\n<!-- /agent:model -->\n";
        assert_eq!(extract_model_component(doc), None);
    }

    #[test]
    fn extract_model_component_concrete_name() {
        let doc = "<!-- agent:model -->\nopus\n<!-- /agent:model -->\n";
        assert_eq!(extract_model_component(doc).as_deref(), Some("opus"));
    }

    #[test]
    fn component_value_to_tier_tier_name() {
        let cfg = ModelConfig::default();
        assert_eq!(
            component_value_to_tier("high", "claude-code", &cfg),
            Some(Tier::High)
        );
    }

    #[test]
    fn component_value_to_tier_concrete_name() {
        let cfg = ModelConfig::default();
        assert_eq!(
            component_value_to_tier("opus", "claude-code", &cfg),
            Some(Tier::High)
        );
    }

    #[test]
    fn component_value_to_tier_unknown() {
        let cfg = ModelConfig::default();
        assert_eq!(component_value_to_tier("xyz", "claude-code", &cfg), None);
    }

    #[test]
    fn suggested_tier_simple_question() {
        let path = std::path::Path::new("tasks/research/x.md");
        assert_eq!(suggested_tier(Some("simple_question"), 1, path), Tier::Low);
    }

    #[test]
    fn suggested_tier_small_addition() {
        let path = std::path::Path::new("tasks/research/x.md");
        assert_eq!(suggested_tier(Some("content_addition"), 5, path), Tier::Low);
    }

    #[test]
    fn suggested_tier_large_addition() {
        let path = std::path::Path::new("tasks/research/x.md");
        assert_eq!(suggested_tier(Some("content_addition"), 50, path), Tier::Med);
    }

    #[test]
    fn suggested_tier_default_for_unknown() {
        let path = std::path::Path::new("tasks/research/x.md");
        assert_eq!(suggested_tier(None, 0, path), Tier::Med);
    }

    #[test]
    fn suggested_tier_path_boost_software() {
        let path = std::path::Path::new("tasks/software/foo.md");
        // Low gets boosted to Med
        assert_eq!(
            suggested_tier(Some("simple_question"), 1, path),
            Tier::Med
        );
        // Med gets boosted to High
        assert_eq!(
            suggested_tier(Some("content_addition"), 50, path),
            Tier::High
        );
    }

    #[test]
    fn suggested_tier_path_boost_caps_at_high() {
        let path = std::path::Path::new("tasks/software/foo.md");
        // Already High stays High
        let t = suggested_tier(Some("content_addition"), 50, path);
        assert_eq!(t, Tier::High);
    }

    #[test]
    fn compose_effective_tier_model_switch_wins() {
        let t = compose_effective_tier(
            Some(Tier::High),
            Some(Tier::Low),
            Some(Tier::Med),
            Tier::Low,
        );
        assert_eq!(t, Tier::High);
    }

    #[test]
    fn compose_effective_tier_component_beats_frontmatter() {
        let t = compose_effective_tier(None, Some(Tier::High), Some(Tier::Low), Tier::Med);
        assert_eq!(t, Tier::High);
    }

    #[test]
    fn compose_effective_tier_frontmatter_beats_heuristic() {
        let t = compose_effective_tier(None, None, Some(Tier::High), Tier::Low);
        assert_eq!(t, Tier::High);
    }

    #[test]
    fn compose_effective_tier_falls_through_to_heuristic() {
        let t = compose_effective_tier(None, None, None, Tier::Med);
        assert_eq!(t, Tier::Med);
    }

    #[test]
    fn scan_model_switch_concrete_name() {
        let cfg = ModelConfig::default();
        let diff = "@@ -1,3 +1,4 @@\n context\n+/model opus\n+real edit\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch.as_deref(), Some("opus"));
        assert_eq!(result.model_switch_tier, Some(Tier::High));
        assert!(!result.stripped_diff.contains("/model opus"));
        assert!(result.stripped_diff.contains("real edit"));
    }

    #[test]
    fn scan_model_switch_tier_name() {
        let cfg = ModelConfig::default();
        let diff = "+/model high\n+other line\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch_tier, Some(Tier::High));
        assert_eq!(result.model_switch.as_deref(), Some("opus"));
        assert!(!result.stripped_diff.contains("/model high"));
    }

    #[test]
    fn scan_model_switch_haiku() {
        let cfg = ModelConfig::default();
        let diff = "+/model haiku\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch_tier, Some(Tier::Low));
    }

    #[test]
    fn scan_model_switch_inside_fenced_code_ignored() {
        let cfg = ModelConfig::default();
        let diff = "+```\n+/model opus\n+```\n+real line\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch, None);
        assert!(result.stripped_diff.contains("/model opus"));
    }

    #[test]
    fn scan_model_switch_inside_blockquote_ignored() {
        let cfg = ModelConfig::default();
        let diff = "+> /model opus\n+real line\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch, None);
        assert!(result.stripped_diff.contains("/model opus"));
    }

    #[test]
    fn scan_model_switch_only_added_lines() {
        let cfg = ModelConfig::default();
        // Context line with /model is NOT a user addition.
        let diff = " /model opus\n+real line\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch, None);
    }

    #[test]
    fn scan_model_switch_no_match() {
        let cfg = ModelConfig::default();
        let diff = "+just a normal line\n+another\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch, None);
        // Diff is unchanged (modulo trailing newline normalization).
        assert!(result.stripped_diff.contains("just a normal line"));
        assert!(result.stripped_diff.contains("another"));
    }

    #[test]
    fn scan_model_switch_unknown_arg_still_stripped() {
        let cfg = ModelConfig::default();
        // Unknown arg → no tier captured but line still stripped.
        let diff = "+/model xyz-3000\n+real line\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch, None);
        assert!(!result.stripped_diff.contains("/model xyz-3000"));
        assert!(result.stripped_diff.contains("real line"));
    }

    #[test]
    fn scan_model_switch_first_match_wins() {
        let cfg = ModelConfig::default();
        let diff = "+/model opus\n+/model haiku\n";
        let result = scan_model_switch(diff, "claude-code", &cfg);
        assert_eq!(result.model_switch.as_deref(), Some("opus"));
        // Both lines stripped.
        assert!(!result.stripped_diff.contains("/model"));
    }

    #[test]
    fn compose_effective_tier_auto_falls_through() {
        // Auto values should fall through to next source.
        let t = compose_effective_tier(
            Some(Tier::Auto),
            Some(Tier::Auto),
            Some(Tier::High),
            Tier::Low,
        );
        assert_eq!(t, Tier::High);
    }
}