hotl 0.6.2

Human-on-the-loop terminal AI agent: steering TUI + headless mode, gated tools under a kernel sandbox floor, session resume + undo, MCP/ACP, any Anthropic or OpenAI-compatible model — plus `hotl watch`, a tmux dashboard for the agents you already run.
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
//! The single config file: `~/.config/hotl/config.toml`.
//!
//! One place for every hand-editable setting — provider, context/compaction,
//! behavior, retention, network egress — plus the domain sections (`[[allow]]`, `[[mcp]]`,
//! `[[hook]]`, `[diagnostics]`) that used to live in their own files. The
//! prose/data that isn't really "settings" stays separate: `system-prompt.md`,
//! `memory/`, `skills/`, and the machine-written `trust.toml`.
//!
//! Precedence for scalar settings: **environment variable > config.toml >
//! built-in default**, so existing `HOTL_*`-based setups and CI keep working.
//! For the domain sections, config.toml wins if it defines them; otherwise the
//! legacy standalone file (`permissions.toml`, `mcp.toml`, `hooks.toml`) is
//! read as a fallback so no one's setup breaks.

use std::path::Path;

use serde::Deserialize;

#[derive(Debug, Default, Deserialize)]
pub struct Config {
    #[serde(default)]
    pub provider: ProviderCfg,
    #[serde(default)]
    pub context: ContextCfg,
    #[serde(default)]
    pub behavior: BehaviorCfg,
    #[serde(default)]
    pub retention: RetentionCfg,
    #[serde(default)]
    pub history: HistoryCfg,
    #[serde(default)]
    pub network: NetworkCfg,
    #[serde(default)]
    pub permissions: PermissionsCfg,
    #[serde(default)]
    pub skills: SkillsCfg,
    #[serde(default)]
    pub agents: AgentsCfg,
    #[serde(default)]
    pub concurrency: ConcurrencyCfg,
    /// Raw document, for reserializing the domain sections to their loaders.
    #[serde(skip)]
    raw: Option<toml::Value>,
}

#[derive(Debug, Default, Deserialize)]
pub struct SkillsCfg {
    /// `false` stops reading Claude Code skill roots (`~/.claude/skills`,
    /// the plugin cache). Default: read them when present.
    pub claude: Option<bool>,
    /// `[skills.marketplaces]` — extra skill sources: name → local path
    /// (read in place) or git URL (managed checkout; `hotl skills add`).
    #[serde(default)]
    pub marketplaces: std::collections::BTreeMap<String, String>,
}

impl SkillsCfg {
    /// Resolve `[skills.marketplaces]` to discovery roots: a local path is
    /// read in place (`~` expanded), a git URL maps to its managed checkout
    /// under `<config_dir>/marketplaces/<name>`. An invalid name is skipped
    /// with a warning — fail-closed, a bad entry never loads skills.
    pub fn marketplace_roots(
        &self,
        config_dir: &Path,
    ) -> (Vec<(String, std::path::PathBuf)>, Vec<String>) {
        let mut roots = Vec::new();
        let mut warnings = Vec::new();
        for (name, source) in &self.marketplaces {
            let Some(name) = hotl_tools::skills::normalize_marketplace_name(name) else {
                warnings.push(format!(
                    "[skills.marketplaces] `{name}` is not a valid marketplace name \
                     (letters, digits, `.`/`_`/`-`, alphanumeric first char, ≤ 64 chars) \
                     — entry skipped"
                ));
                continue;
            };
            let dir = if is_git_url(source) {
                config_dir.join("marketplaces").join(&name)
            } else {
                expand_home(source)
            };
            roots.push((name, dir));
        }
        (roots, warnings)
    }
}

/// `[agents]` — user-defined subagent shapes (tier-1 gap #6). Mirrors
/// `[skills] claude` exactly: hotl always reads its own `agents/*.md`;
/// `~/.claude/agents/*.md` loads too unless opted out.
#[derive(Debug, Default, Deserialize)]
pub struct AgentsCfg {
    /// `false` stops reading `~/.claude/agents`. Default: read it when
    /// present.
    pub claude: Option<bool>,
}

/// A git URL as opposed to a local path: a fetch scheme, an scp-style
/// `git@` prefix, or a trailing `.git`.
pub fn is_git_url(source: &str) -> bool {
    source.starts_with("http://")
        || source.starts_with("https://")
        || source.starts_with("git@")
        || source.starts_with("ssh://")
        || source.ends_with(".git")
}

/// Expand a leading `~/` against `$HOME`.
fn expand_home(path: &str) -> std::path::PathBuf {
    if let Some(rest) = path.strip_prefix("~/") {
        if let Some(home) = std::env::var_os("HOME") {
            return std::path::PathBuf::from(home).join(rest);
        }
    }
    std::path::PathBuf::from(path)
}

#[derive(Debug, Default, Deserialize)]
pub struct PermissionsCfg {
    /// `"auto"` (default — no ordinary prompts) | `"ask"`.
    pub mode: Option<String>,
}

impl PermissionsCfg {
    /// Resolve the mode: env (`HOTL_PERMISSIONS`) > config > default `auto`.
    /// An unknown value fails **closed** to `Ask` with a warning — a typo
    /// must never silently mean "don't prompt".
    pub fn resolve(
        &self,
        env: Option<&str>,
    ) -> (hotl_tools::rules::PermissionMode, Option<String>) {
        use hotl_tools::rules::PermissionMode;
        let source = env.or(self.mode.as_deref());
        match source {
            None => (PermissionMode::Auto, None),
            Some(s) => match PermissionMode::from_str(s) {
                Some(m) => (m, None),
                None => (
                    PermissionMode::Ask,
                    Some(format!(
                        "[permissions].mode = \"{s}\" is not a mode (ask | auto | plan | dontask) — failing closed to \"ask\""
                    )),
                ),
            },
        }
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct ProviderCfg {
    /// `provider/model`, e.g. `openai/gpt-5` or `anthropic/claude-opus-4-8`.
    pub model: Option<String>,
    /// Endpoint for the active provider. `openai/…` has always used this;
    /// `anthropic/…` honors it too, so any Anthropic-shaped endpoint (a local
    /// bridge, a gateway) is reachable. Only one provider is active at a time,
    /// so one key serves both.
    pub base_url: Option<String>,
    /// `"api_key"` (default) | `"subscription"`. Under `subscription` hotl
    /// holds no credential — the endpoint authenticates upstream on its own —
    /// and `base_url` is required. Provider-neutral: it reads the same for
    /// `anthropic/…` and `openai/…`.
    pub auth: Option<String>,
    /// Cheap model for compaction summaries.
    pub fast_model: Option<String>,
    /// Command whose stdout (trimmed) is the API key. When set, it beats the
    /// static key env vars: configuring a helper is a deliberate act.
    pub api_key_helper: Option<String>,
    /// Re-run the helper when the cached key is older than this. Absent =
    /// refresh only at startup and on auth failure.
    pub api_key_helper_ttl_secs: Option<u64>,
}

#[derive(Debug, Default, Deserialize)]
pub struct ContextCfg {
    pub window: Option<u64>,
    pub compaction_reset: Option<bool>,
    pub show_used_pct: Option<bool>,
    pub evict_tokens: Option<u64>,
}

// Dead until `agent.rs::engine_config` calls these — decision-log request #1
// of specs/exec-plans/active/0014-remediation-model-registry.md, owned by R10.
// `hotl` is a bin-only crate, so `pub` confers no reachability and the lint
// fires despite the tests below exercising both. Remove this attribute when
// that call site lands; the lint then holds the seam honest again.
#[allow(dead_code)]
impl ContextCfg {
    /// Resolve the compaction context window, in tokens.
    ///
    /// Precedence, highest first: `HOTL_CONTEXT_WINDOW` (passed as `env`) >
    /// `[context] window` > the model's catalogued window >
    /// [`hotl_provider::catalog::FALLBACK_CONTEXT_WINDOW`]. The explicit tiers
    /// still win: a gateway that trims the window is a real configuration and
    /// the catalog must never overrule the person who said so.
    ///
    /// The second element is a startup warning, present only when an
    /// uncatalogued model fell through to the fallback. Silence there is the
    /// original defect: a 1M-window model compacting at 160K, or an 8K local
    /// model overflowing on turn two, with nothing on screen either way.
    ///
    /// INVARIANT: an explicit `[context] window` or `HOTL_CONTEXT_WINDOW` is
    /// always honored verbatim. Enforced by
    /// `explicit_config_and_env_still_beat_the_catalog`.
    pub fn resolve_window(&self, model: &str, env: Option<&str>) -> (u64, Option<String>) {
        if let Some(window) = env.and_then(|v| v.parse::<u64>().ok()).or(self.window) {
            return (window, None);
        }
        match hotl_provider::catalog::context_window(model) {
            Some(window) => (window, None),
            None => (
                hotl_provider::catalog::FALLBACK_CONTEXT_WINDOW,
                Some(format!(
                    "hotl: `{model}` is not in the model catalog — assuming a \
                     {} token context window. If that is wrong, set \
                     `[context] window` in config.toml (or HOTL_CONTEXT_WINDOW); \
                     too high overflows the model, too low compacts early.",
                    hotl_provider::catalog::FALLBACK_CONTEXT_WINDOW
                )),
            ),
        }
    }

    /// The token-estimation profile for `model`. An uncatalogued model gets
    /// the conservative default rather than a guessed ratio — overcounting is
    /// the only safe direction (see `hotl_context::tokens`).
    pub fn token_profile(&self, model: &str) -> hotl_context::TokenProfile {
        match hotl_provider::catalog::lookup(model) {
            Some(info) => {
                hotl_context::TokenProfile::from_chars_per_token(info.ascii_chars_per_token)
            }
            None => hotl_context::TokenProfile::CONSERVATIVE,
        }
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct BehaviorCfg {
    /// `false` disables the bash sandbox floor.
    pub sandbox: Option<bool>,
    /// Vim-style keys in the console's input editor. Resolve via
    /// [`BehaviorCfg::vim_mode`] — absent means **off**.
    pub vim_mode: Option<bool>,
    /// Model samples one prompt may spend before the turn is cut short with
    /// `turn limit reached`. A tool round-trip costs one, so this is the
    /// agent loop's step budget. `-1` = unlimited (run until the model stops
    /// on its own). Absent = the engine default.
    pub max_turns: Option<i64>,
}

impl BehaviorCfg {
    /// Default **off**: a modal editor is a trap for anyone who doesn't
    /// already have the muscle memory — one stray `Esc` and typing stops
    /// inserting. Vim users opt in with `[behavior] vim_mode = true`.
    ///
    /// This is deliberately the opposite of `hotl watch`'s `[settings]
    /// vim_mode`, which stays on: there the letter keys are *additive* over a
    /// read-only list (arrows, `enter`, `q`, and `r` work either way), so
    /// leaving them on strands nobody.
    pub fn vim_mode(&self) -> bool {
        self.vim_mode.unwrap_or(false)
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct RetentionCfg {
    pub max_age_days: Option<u64>,
    pub max_sessions: Option<usize>,
}

/// `[history]` — the interactive console's prompt history: a size-bounded,
/// on-disk recall file. Every field is optional; the getters below carry the
/// product defaults (on, 1000 entries, 2 MiB).
#[derive(Debug, Default, Deserialize)]
pub struct HistoryCfg {
    pub enabled: Option<bool>,
    pub path: Option<String>,
    pub max_entries: Option<usize>,
    pub max_bytes: Option<u64>,
}

impl HistoryCfg {
    /// Default on — recall is the expected console behavior.
    pub fn is_enabled(&self) -> bool {
        self.enabled.unwrap_or(true)
    }

    pub fn max_entries(&self) -> usize {
        self.max_entries.unwrap_or(1000)
    }

    pub fn max_bytes(&self) -> u64 {
        self.max_bytes.unwrap_or(2 * 1024 * 1024)
    }

    /// The resolved history file: a user `path` (with `~/` expanded), else
    /// `<data_dir>/history.jsonl` (history is state/data, not config).
    pub fn resolved_path(&self, data_dir: &Path) -> std::path::PathBuf {
        match &self.path {
            Some(p) => expand_home(p),
            None => data_dir.join("history.jsonl"),
        }
    }
}

/// `[concurrency]` — the Layer-B resource governors (`hotl_tools::concurrency`
/// index spec) plus the two Layer-C runtime-pool knobs. `agents`/`requests`/
/// `subprocs` feed `ConcurrencyLimits` (env `HOTL_CONCURRENCY_*` > this >
/// the fixed default; `0`/absent falls back to the default, never to zero).
///
/// Of the two Layer-C knobs, only `blocking_threads` is actually wired:
/// `main.rs::block_on` calls `.max_blocking_threads()` on hotl's existing
/// `current_thread` runtime builder — a call valid on any runtime flavor —
/// sizing the pool `glob`'s `spawn_blocking` tree walk (the sole real
/// blocking-pool user) draws from. `worker_threads` stays deliberately
/// inert: it only applies to a `multi_thread` runtime, and hotl runs a
/// single `current_thread` runtime everywhere (`main.rs::block_on` drives
/// every subcommand including the TUI and `acp_main`; `doctor.rs` builds its
/// own `current_thread` runtime too) by design — switching flavors to honor
/// it risks breaking `!Send` futures across the TUI/actor code, which is out
/// of scope here. `agent::layer_c_warning` surfaces that inertness at
/// startup so a configured `worker_threads` is visible, not a silent no-op.
#[derive(Debug, Default, Deserialize)]
pub struct ConcurrencyCfg {
    /// Concurrent sub-agent LLM sessions — governs `spawn`'s fan-out.
    pub agents: Option<usize>,
    /// Concurrent `web_fetch`/`web_search` HTTP requests — governs
    /// `web_fetch`'s multi-URL batch today.
    pub requests: Option<usize>,
    /// Concurrent `bash`/`grep`/hook child processes (unused until a
    /// subprocess-fan-out plan lands).
    pub subprocs: Option<usize>,
    /// Reserved: tokio worker-thread pool size (`0` = num_cpus). Parsed, but
    /// deliberately inert — see the struct doc.
    pub worker_threads: Option<usize>,
    /// `spawn_blocking` pool cap (index default 16; tokio's own default is
    /// 512 if unset). Wired: `main.rs::block_on` applies it to the
    /// `current_thread` runtime's blocking pool.
    pub blocking_threads: Option<usize>,
}

#[derive(Debug, Default, Deserialize)]
pub struct NetworkCfg {
    /// `"open"` (default) | `"off"` | `"allowlist"`.
    pub egress: Option<String>,
    /// Hosts reachable in allowlist mode (`"github.com"`, `"*.crates.io"`).
    #[serde(default)]
    pub allow: Vec<String>,
}

impl NetworkCfg {
    /// Resolve `[network]` to the process egress policy. An unknown mode
    /// fails **closed** to `Off` with a loud warning — a typo must never
    /// mean "open".
    pub fn egress_policy(&self) -> (hotl_tools::net::EgressPolicy, Option<String>) {
        use hotl_tools::net::EgressPolicy;
        match self.egress.as_deref() {
            None | Some("open") => (EgressPolicy::Open, None),
            Some("off") => (EgressPolicy::Off, None),
            Some("allowlist") => (EgressPolicy::Allowlist(self.allow.clone()), None),
            Some(other) => (
                EgressPolicy::Off,
                Some(format!(
                    "config.toml [network].egress = \"{other}\" is not a mode \
                     (open | off | allowlist) — failing closed to \"off\""
                )),
            ),
        }
    }
}

impl Config {
    /// Load `config.toml`; a malformed file warns and yields defaults
    /// (fail-closed: a typo never silently changes a setting).
    pub fn load(config_dir: &Path) -> Self {
        let path = config_dir.join("config.toml");
        let Ok(text) = std::fs::read_to_string(&path) else {
            return Self::default();
        };
        match text.parse::<toml::Value>() {
            Ok(raw) => {
                // Parse the typed settings from the same source string (no
                // deep clone of the raw document just to deserialize it).
                let mut cfg: Config = toml::from_str(&text).unwrap_or_default();
                cfg.raw = Some(raw);
                cfg
            }
            Err(e) => {
                eprintln!("hotl: config.toml ignored (parse error): {e}");
                Self::default()
            }
        }
    }

    /// The `[[allow]]` rules as a standalone TOML string (for `Rules::from_toml`),
    /// or `None` if config.toml has no `allow` section (→ fall back to the file).
    pub fn allow_toml(&self) -> Option<String> {
        self.section_as_toml("allow")
    }

    /// The `[[mcp]]` servers as a `[[server]]`-shaped TOML string (matching the
    /// legacy `mcp.toml` schema), or `None`.
    pub fn mcp_toml(&self) -> Option<String> {
        let servers = self.raw.as_ref()?.get("mcp")?;
        toml::to_string(&toml::toml! { server = (servers.clone()) }).ok()
    }

    /// The `[[retrieval]]` backends as a `[[backend]]`-shaped TOML string
    /// (for `hotl_retrieval::config::RetrievalConfig`), or `None`.
    pub fn retrieval_toml(&self) -> Option<String> {
        let backends = self.raw.as_ref()?.get("retrieval")?;
        toml::to_string(&toml::toml! { backend = (backends.clone()) }).ok()
    }

    /// The `[web]` section's *contents* (for `hotl_tools::web::WebConfig`,
    /// whose `search` field sits at the document's top level — unlike
    /// `retrieval`/`mcp`, no key rename is needed, so this reserializes the
    /// inner table directly rather than re-wrapping it under `web`), or
    /// `None` when absent — `web_fetch` registers regardless (it needs no
    /// backend); `web_search` simply never gets built.
    pub fn web_toml(&self) -> Option<String> {
        let web = self.raw.as_ref()?.get("web")?;
        toml::to_string(web).ok()
    }

    /// The `[[hook]]` + `[diagnostics]` as a `hooks.toml`-shaped string, or None.
    pub fn hooks_toml(&self) -> Option<String> {
        let raw = self.raw.as_ref()?;
        let hooks = raw.get("hook");
        let diags = raw.get("diagnostics");
        if hooks.is_none() && diags.is_none() {
            return None;
        }
        let mut doc = toml::map::Map::new();
        if let Some(h) = hooks {
            doc.insert("hook".into(), h.clone());
        }
        if let Some(d) = diags {
            doc.insert("diagnostics".into(), d.clone());
        }
        toml::to_string(&toml::Value::Table(doc)).ok()
    }

    fn section_as_toml(&self, key: &str) -> Option<String> {
        let value = self.raw.as_ref()?.get(key)?;
        let mut doc = toml::map::Map::new();
        doc.insert(key.into(), value.clone());
        toml::to_string(&toml::Value::Table(doc)).ok()
    }
}

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

    fn cfg_with(toml: &str) -> Config {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("config.toml"), toml).unwrap();
        Config::load(dir.path())
    }

    #[test]
    fn window_resolves_from_the_catalog_when_unconfigured() {
        // The headline fix: the 1M-window default model stops compacting at
        // 160K because someone hardcoded 200_000.
        let (window, warning) = cfg_with("").context.resolve_window("claude-opus-4-8", None);
        assert_eq!(window, 1_000_000);
        assert!(warning.is_none());

        // A small model gets its small window, so default config stops
        // guaranteeing an overflow on it.
        let (window, _) = cfg_with("")
            .context
            .resolve_window("claude-haiku-4-5", None);
        assert_eq!(window, 200_000);
    }

    #[test]
    fn explicit_config_and_env_still_beat_the_catalog() {
        let cfg = cfg_with("[context]\nwindow = 64000\n");
        // config.toml over the catalog…
        assert_eq!(
            cfg.context.resolve_window("claude-opus-4-8", None).0,
            64_000
        );
        // …and env over config.toml (unchanged project-wide precedence).
        assert_eq!(
            cfg.context
                .resolve_window("claude-opus-4-8", Some("32000"))
                .0,
            32_000
        );
        // A garbage env value is ignored, not fatal — config still wins.
        assert_eq!(
            cfg.context
                .resolve_window("claude-opus-4-8", Some("banana"))
                .0,
            64_000
        );
    }

    #[test]
    fn an_uncatalogued_model_falls_back_loudly_not_silently() {
        let (window, warning) = cfg_with("").context.resolve_window("openai/llama3", None);
        assert_eq!(window, hotl_provider::catalog::FALLBACK_CONTEXT_WINDOW);
        let warning = warning.expect("must warn — a silent wrong window is the bug we are fixing");
        assert!(warning.contains("llama3"), "{warning}");
        assert!(
            warning.contains("[context] window"),
            "name the knob: {warning}"
        );
        // Configured explicitly: no warning, the user has answered the question.
        let cfg = cfg_with("[context]\nwindow = 8192\n");
        let (window, warning) = cfg.context.resolve_window("openai/llama3", None);
        assert_eq!(window, 8192);
        assert!(warning.is_none());
    }

    #[test]
    fn token_profile_follows_the_model() {
        let cfg = cfg_with("");
        // A catalogued model gets its own ratio…
        let opus = cfg.context.token_profile("claude-opus-4-8");
        assert_eq!(opus, hotl_context::TokenProfile::from_chars_per_token(3.0));
        // …and an unknown one gets the conservative default, never a guess.
        assert_eq!(
            cfg.context.token_profile("llama3"),
            hotl_context::TokenProfile::CONSERVATIVE
        );
    }

    #[test]
    fn default_model_matches_the_anthropic_provider() {
        // Pin, not a fix: `DEFAULT_MODEL` is defined three times
        // (catalog, hotl-provider-anthropic/src/lib.rs:23,
        // hotl-engine/src/lib.rs:80). The latter two belong to R3 and R2, who
        // have decision-log requests to re-export the catalog's. Until they
        // land, this fails loudly the moment the copies drift.
        assert_eq!(
            hotl_provider::catalog::DEFAULT_MODEL,
            hotl_provider_anthropic::DEFAULT_MODEL
        );
        // And the default model must itself be catalogued.
        assert!(hotl_provider::catalog::lookup(hotl_provider::catalog::DEFAULT_MODEL).is_some());
    }

    #[test]
    fn parses_settings_and_domain_sections() {
        let cfg = cfg_with(
            r#"
            [provider]
            model = "openai/gpt-5"
            base_url = "http://localhost:11434/v1"

            [context]
            window = 128000
            evict_tokens = 5000

            [behavior]
            vim_mode = false

            [retention]
            max_age_days = 30
            max_sessions = 100

            [[allow]]
            tool = "bash"
            prefix = "cargo "

            [[mcp]]
            name = "docs"
            command = "/bin/docs"
            description = "d"

            [[hook]]
            event = "pre_tool"
            command = "/bin/guard"

            [diagnostics]
            rs = "cargo check"
            "#,
        );
        assert_eq!(cfg.provider.model.as_deref(), Some("openai/gpt-5"));
        assert_eq!(cfg.context.window, Some(128_000));
        assert_eq!(cfg.behavior.vim_mode, Some(false));
        assert_eq!(cfg.retention.max_age_days, Some(30));
        assert_eq!(cfg.retention.max_sessions, Some(100));
        // Domain sections reserialize to their loaders' shapes.
        assert!(cfg.allow_toml().unwrap().contains("prefix = \"cargo \""));
        assert!(
            cfg.mcp_toml().unwrap().contains("[[server]]")
                && cfg.mcp_toml().unwrap().contains("docs")
        );
        let hooks = cfg.hooks_toml().unwrap();
        assert!(hooks.contains("pre_tool") && hooks.contains("cargo check"));
    }

    #[test]
    fn behavior_max_turns_parses_including_the_unlimited_sentinel() {
        assert_eq!(
            cfg_with("[behavior]\nmax_turns = 250\n").behavior.max_turns,
            Some(250)
        );
        // `-1` is the opt-in "no cap" posture — it must survive parsing as a
        // negative, not be rejected or clamped.
        assert_eq!(
            cfg_with("[behavior]\nmax_turns = -1\n").behavior.max_turns,
            Some(-1)
        );
        assert_eq!(cfg_with("").behavior.max_turns, None);
    }

    #[test]
    fn retrieval_section_reserializes_for_the_loader() {
        let cfg =
            cfg_with("[[retrieval]]\nname = \"notes\"\nkind = \"mcp\"\ncommand = \"/bin/rag\"\n");
        let t = cfg.retrieval_toml().unwrap();
        assert!(t.contains("[[backend]]") && t.contains("notes"));
        assert!(cfg_with("").retrieval_toml().is_none());
    }

    #[test]
    fn concurrency_section_parses_and_defaults_absent() {
        let cfg = cfg_with(
            "[concurrency]\nagents = 2\nrequests = 3\nsubprocs = 6\nworker_threads = 4\nblocking_threads = 32\n",
        );
        assert_eq!(cfg.concurrency.agents, Some(2));
        assert_eq!(cfg.concurrency.requests, Some(3));
        assert_eq!(cfg.concurrency.subprocs, Some(6));
        assert_eq!(cfg.concurrency.worker_threads, Some(4));
        assert_eq!(cfg.concurrency.blocking_threads, Some(32));
        let absent = cfg_with("");
        assert_eq!(absent.concurrency.agents, None);
        assert_eq!(absent.concurrency.requests, None);
        assert_eq!(absent.concurrency.subprocs, None);
    }

    #[test]
    fn web_section_passes_through_for_the_search_tool_loader() {
        let cfg = cfg_with(
            "[web]\n[web.search]\nurl = \"https://s.example/api\"\napi_key_env = \"SEARCH_KEY\"\n",
        );
        let t = cfg.web_toml().unwrap();
        assert!(t.contains("[search]"), "was: {t}");
        assert!(t.contains("https://s.example/api"));
        assert!(t.contains("SEARCH_KEY"));
        // Absent [web] section: None — web_fetch registers regardless (it
        // needs no config), web_search simply never gets built.
        assert!(cfg_with("").web_toml().is_none());
    }

    #[test]
    fn provider_helper_keys_parse() {
        let cfg = cfg_with(
            "[provider]\napi_key_helper = \"mint-key --gw\"\napi_key_helper_ttl_secs = 300\n",
        );
        assert_eq!(
            cfg.provider.api_key_helper.as_deref(),
            Some("mint-key --gw")
        );
        assert_eq!(cfg.provider.api_key_helper_ttl_secs, Some(300));
    }

    #[test]
    fn network_egress_parses_and_unknown_fails_closed() {
        use hotl_tools::net::EgressPolicy;
        // Absent section: Open, no warning (the default is today's behavior).
        let (policy, warning) = cfg_with("").network.egress_policy();
        assert_eq!(policy, EgressPolicy::Open);
        assert!(warning.is_none());
        // Explicit modes.
        let (policy, warning) = cfg_with("[network]\negress = \"off\"\n")
            .network
            .egress_policy();
        assert_eq!(policy, EgressPolicy::Off);
        assert!(warning.is_none());
        let cfg = cfg_with(
            "[network]\negress = \"allowlist\"\nallow = [\"github.com\", \"*.crates.io\"]\n",
        );
        let (policy, warning) = cfg.network.egress_policy();
        assert_eq!(
            policy,
            EgressPolicy::Allowlist(vec!["github.com".into(), "*.crates.io".into()])
        );
        assert!(warning.is_none());
        // Unknown value: fail closed to Off, loudly — never open.
        let (policy, warning) = cfg_with("[network]\negress = \"opne\"\n")
            .network
            .egress_policy();
        assert_eq!(policy, EgressPolicy::Off);
        assert!(warning.unwrap().contains("opne"));
    }

    #[test]
    fn permissions_mode_resolves_with_env_and_fails_closed() {
        use hotl_tools::rules::PermissionMode;
        // Absent → the product default: auto, no warning.
        let (m, w) = cfg_with("").permissions.resolve(None);
        assert_eq!(m, PermissionMode::Auto);
        assert!(w.is_none());
        // Explicit ask.
        let (m, _) = cfg_with("[permissions]\nmode = \"ask\"\n")
            .permissions
            .resolve(None);
        assert_eq!(m, PermissionMode::Ask);
        // Env beats config.
        let (m, _) = cfg_with("[permissions]\nmode = \"ask\"\n")
            .permissions
            .resolve(Some("auto"));
        assert_eq!(m, PermissionMode::Auto);
        // Typo fails closed to ask, loudly — never silently auto.
        let (m, w) = cfg_with("[permissions]\nmode = \"atuo\"\n")
            .permissions
            .resolve(None);
        assert_eq!(m, PermissionMode::Ask);
        assert!(w.unwrap().contains("atuo"));
        // plan and dontask parse from config…
        let (m, w) = cfg_with("[permissions]\nmode = \"plan\"\n")
            .permissions
            .resolve(None);
        assert_eq!(m, PermissionMode::Plan);
        assert!(w.is_none());
        let (m, w) = cfg_with("[permissions]\nmode = \"dontask\"\n")
            .permissions
            .resolve(None);
        assert_eq!(m, PermissionMode::DontAsk);
        assert!(w.is_none());
        // …and from HOTL_PERMISSIONS.
        let (m, _) = cfg_with("").permissions.resolve(Some("plan"));
        assert_eq!(m, PermissionMode::Plan);
        let (m, _) = cfg_with("").permissions.resolve(Some("dontask"));
        assert_eq!(m, PermissionMode::DontAsk);
    }

    #[test]
    fn vim_mode_parses_and_defaults() {
        let cfg = cfg_with("[behavior]\nvim_mode = false\n");
        assert_eq!(cfg.behavior.vim_mode, Some(false));
        assert_eq!(cfg_with("").behavior.vim_mode, None);
    }

    #[test]
    fn vim_mode_resolves_off_unless_opted_in() {
        // Absent section, and an explicit `false`: plain insert-mode editing.
        assert!(!cfg_with("").behavior.vim_mode());
        assert!(!cfg_with("[behavior]\nvim_mode = false\n")
            .behavior
            .vim_mode());
        // Only an explicit `true` turns the modal editor on.
        assert!(cfg_with("[behavior]\nvim_mode = true\n")
            .behavior
            .vim_mode());
    }

    #[test]
    fn history_parses_and_falls_back_to_defaults() {
        // Absent section: the product defaults (on, 1000 entries, 2 MiB).
        let cfg = cfg_with("");
        assert!(cfg.history.is_enabled());
        assert_eq!(cfg.history.max_entries(), 1000);
        assert_eq!(cfg.history.max_bytes(), 2 * 1024 * 1024);

        // Explicit values override.
        let cfg = cfg_with(
            "[history]\nenabled = false\nmax_entries = 5\nmax_bytes = 4096\npath = \"~/h.jsonl\"\n",
        );
        assert!(!cfg.history.is_enabled());
        assert_eq!(cfg.history.max_entries(), 5);
        assert_eq!(cfg.history.max_bytes(), 4096);
    }

    #[test]
    fn history_path_expands_home_and_defaults_under_data_dir() {
        let data = std::path::Path::new("/data/hotl");
        // No path → <data-dir>/history.jsonl.
        assert_eq!(
            cfg_with("").history.resolved_path(data),
            data.join("history.jsonl")
        );
        // A `~/`-path expands against HOME.
        let cfg = cfg_with("[history]\npath = \"~/notes/h.jsonl\"\n");
        let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap());
        assert_eq!(cfg.history.resolved_path(data), home.join("notes/h.jsonl"));
    }

    #[test]
    fn skills_marketplaces_parse_and_resolve() {
        let cfg = cfg_with(
            "[skills.marketplaces]\n\
             acme = \"https://github.com/acme/skills.git\"\n\
             team = \"/abs/team-skills\"\n\
             \"bad:name\" = \"/x\"\n",
        );
        let dir = std::path::Path::new("/cfg");
        let (roots, warnings) = cfg.skills.marketplace_roots(dir);
        assert_eq!(
            roots,
            vec![
                ("acme".to_string(), dir.join("marketplaces/acme")),
                (
                    "team".to_string(),
                    std::path::PathBuf::from("/abs/team-skills")
                ),
            ]
        );
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("bad:name"), "{warnings:?}");

        // `~/` expands against HOME; absent section resolves empty.
        let cfg = cfg_with("[skills.marketplaces]\nhome = \"~/team-skills\"\n");
        let (roots, _) = cfg.skills.marketplace_roots(dir);
        let home = std::path::PathBuf::from(std::env::var_os("HOME").unwrap());
        assert_eq!(roots, vec![("home".to_string(), home.join("team-skills"))]);
        assert!(cfg_with("").skills.marketplace_roots(dir).0.is_empty());
    }

    #[test]
    fn git_url_detection() {
        for url in [
            "https://github.com/a/b.git",
            "http://host/repo",
            "git@github.com:a/b.git",
            "ssh://host/repo",
            "/local/path/origin.git",
        ] {
            assert!(is_git_url(url), "{url}");
        }
        for path in ["~/skills", "/abs/dir", "relative/dir"] {
            assert!(!is_git_url(path), "{path}");
        }
    }

    #[test]
    fn empty_or_absent_config_is_defaults_and_none_sections() {
        let cfg = Config::load(std::path::Path::new("/no/such/dir"));
        assert!(cfg.provider.model.is_none());
        assert!(
            cfg.allow_toml().is_none() && cfg.mcp_toml().is_none() && cfg.hooks_toml().is_none()
        );
        assert!(cfg.retention.max_age_days.is_none());
    }
}