trusty-mpm 0.19.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! User-facing configuration for the trusty-mpm framework.
//!
//! Why: trusty-mpm had no persistent configuration — every setting was either
//! hard-coded or supplied via environment variable, giving users no canonical
//! way to express preferences like "use haiku for the engineer agent". This
//! module canonicalizes `~/.trusty-mpm/config.toml` as the configuration file
//! and provides a typed loader with graceful fallback (absent file → defaults;
//! malformed file → logged warning + defaults).
//! What: [`MpmConfig`] is the top-level deserialization target for
//! `~/.trusty-mpm/config.toml`; [`MpmConfig::load`] reads and parses it.
//! [`resolve_agent_model`] implements the four-level model precedence used by
//! the session-launch path for issue #390.
//! Test: `config_absent_yields_defaults`, `config_valid_parsed`,
//! `config_malformed_falls_back`, `model_resolution_precedence`.

use std::collections::HashMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::core::sm::config::SessionManagerConfig;

// ──────────────────────────────────────────────
// Top-level config sections
// ──────────────────────────────────────────────

/// `[agents]` section — agent discovery sources.
///
/// Why: the framework can pull agents from multiple locations (bundled assets,
/// a user-local directory, an optional registry); this section controls which
/// are active.
/// What: a list of source labels. Recognised values: `"bundled"`, `"user"`,
/// `"registry"`. Unknown values are ignored.
/// Test: `config_valid_parsed` checks the parsed sources list.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct AgentsConfig {
    /// Ordered list of agent sources to consult.
    ///
    /// Typical default: `["bundled", "user"]`.
    #[serde(default)]
    pub sources: Vec<String>,
}

/// Per-tier model aliases under `[models]`.
///
/// Why: users want to write `tier = "haiku"` in their config rather than a
/// full model id like `claude-haiku-4-5`; the tier table maps short names to
/// the canonical ids used at launch time.
/// What: an optional string for each Claude model family; `None` means "use
/// the framework default for that tier".
/// Test: `config_valid_parsed` checks alias resolution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct TierAliases {
    /// Full model id (or alias) for the Haiku family.
    pub haiku: Option<String>,
    /// Full model id (or alias) for the Sonnet family.
    pub sonnet: Option<String>,
    /// Full model id (or alias) for the Opus family.
    pub opus: Option<String>,
}

/// `[models]` section — model selection and tier aliases.
///
/// Why: the framework needs a place to record which model to use per agent
/// (for issue #390) and what the user considers the canonical full id for each
/// tier alias.
/// What: `agents` maps agent names to a model id or tier alias; `tiers`
/// provides the alias → id expansion table; `default` is the fallback when
/// neither the agent override nor the frontmatter supplies a model.
/// Test: `config_valid_parsed`, `model_resolution_precedence`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ModelsConfig {
    /// Per-agent model overrides.
    ///
    /// Key: agent name (e.g. `"engineer"`, `"rust-engineer"`).
    /// Value: model id or tier alias (`"haiku"`, `"sonnet"`, `"opus"`,
    /// `"claude-sonnet-4-5"`, …).
    #[serde(default)]
    pub agents: HashMap<String, String>,

    /// Tier alias → canonical model id expansion table.
    ///
    /// Allows users to pin `haiku = "claude-haiku-4-5"` so short aliases in
    /// `agents.*` resolve to a specific model version.
    #[serde(default)]
    pub tiers: TierAliases,

    /// Default model used when no per-agent override or frontmatter model applies.
    pub default: Option<String>,
}

/// `[skills]` section — skill source configuration.
///
/// Why: forward-compatible placeholder so users can add skill-related config
/// in `config.toml` without breaking the loader.
/// What: currently a no-op struct; future versions will add `sources` and
/// per-skill toggles.
/// Test: `config_valid_parsed` confirms the section deserializes cleanly.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct SkillsConfig {
    /// Ordered list of skill sources (e.g. `["bundled", "user"]`).
    #[serde(default)]
    pub sources: Vec<String>,
}

/// `[manifest]` section — harness-manifest catalog source (HR-2 / DOC-17).
///
/// Why: HR-2 sources the catalog-layer harness manifest from a configurable
/// claude-mpm checkout. The repo/ref/TTL are already controllable via the
/// `TRUSTY_MPM_CATALOG_REPO` / `_REF` / `_TTL_HOURS` env vars
/// (`crate::content::CatalogSync`); this section gives operators a persistent,
/// file-based way to express the same choice (e.g. point at a user fork) without
/// exporting env vars on every launch. It is read by the catalog-sync
/// construction path; absent values fall back to the env vars, then the
/// compiled-in defaults.
/// What: an optional catalog repo URL, git ref, and TTL (hours). All `None` by
/// default, so an absent section changes nothing.
/// Test: `config_manifest_section_parses`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ManifestConfig {
    /// Catalog repo URL (overrides `TRUSTY_MPM_CATALOG_REPO`'s default).
    pub repo: Option<String>,
    /// Catalog git ref (overrides `TRUSTY_MPM_CATALOG_REF`'s default).
    pub git_ref: Option<String>,
    /// Catalog cache TTL in hours (overrides `TRUSTY_MPM_CATALOG_TTL_HOURS`).
    pub ttl_hours: Option<u64>,
}

/// `[idle_auto_stop]` section — opt-in idle auto-suspend feature (#1816).
///
/// Why: long-lived idle sessions consume Claude Max rate-limit slots and cloud
/// costs without doing useful work. This section lets operators enable a
/// background reaper that automatically stops idle sessions (keeping workspaces
/// intact and resumable) and decommissions done sessions.
/// What: boolean `enabled` flag (default `false`, zero-change), a `dry_run`
/// report-only gate (default `true` — mirrors trusty-search's auto-prune
/// convention, #1782/#1783: even after you enable the loop it only LOGS the
/// stop/decommission it *would* perform until you opt in by setting
/// `dry_run = false`), poll interval, and consecutive-hit thresholds for the
/// stop and decommission decisions.
/// Test: `config_idle_auto_stop_defaults`, `config_idle_auto_stop_section_parses`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IdleAutoStopConfig {
    /// Whether the idle auto-stop background loop is active.
    ///
    /// `false` (default) → feature is OFF, zero behavior change.
    /// `true` → background loop polls sessions and classifies idle ones.
    #[serde(default)]
    pub enabled: bool,

    /// Report-only (dry-run) gate — the second, teardown-safe opt-in.
    ///
    /// `true` (default) → when the loop is enabled it only LOGS the
    /// `stop`/`decommission` it *would* perform; no session is ever torn down.
    /// `false` → the loop actually stops idle sessions and decommissions done
    /// ones. This mirrors trusty-search's auto-prune "report-only by default,
    /// opt-in to actually act" convention (#1782): enabling the feature and
    /// enacting destructive teardown are two separate, deliberate steps so an
    /// operator can watch the classifier's decisions for a few cycles before
    /// letting it reap real sessions (#1783).
    #[serde(default = "IdleAutoStopConfig::default_dry_run")]
    pub dry_run: bool,

    /// How often (in seconds) to poll Active sessions and classify them.
    ///
    /// Default: 300 s (5 min). At `idle_consecutive_threshold = 3` this means
    /// sessions are stopped after ~15 min of continuous idleness.
    #[serde(default = "IdleAutoStopConfig::default_poll_interval_secs")]
    pub poll_interval_secs: u64,

    /// Number of consecutive `Idle` verdicts before a session is stopped.
    ///
    /// Default: 3 (at 5-min poll interval → ~15 min of continuous idleness).
    /// Reset to 0 whenever the verdict is NOT `Idle`.
    #[serde(default = "IdleAutoStopConfig::default_idle_consecutive_threshold")]
    pub idle_consecutive_threshold: u32,

    /// Number of consecutive `Done` verdicts before a session is decommissioned.
    ///
    /// Default: 1 (decommission on the first confirmed `Done` verdict).
    #[serde(default = "IdleAutoStopConfig::default_done_consecutive_threshold")]
    pub done_consecutive_threshold: u32,
}

impl IdleAutoStopConfig {
    fn default_dry_run() -> bool {
        true
    }
    fn default_poll_interval_secs() -> u64 {
        300
    }
    fn default_idle_consecutive_threshold() -> u32 {
        3
    }
    fn default_done_consecutive_threshold() -> u32 {
        1
    }
}

impl Default for IdleAutoStopConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            dry_run: Self::default_dry_run(),
            poll_interval_secs: Self::default_poll_interval_secs(),
            idle_consecutive_threshold: Self::default_idle_consecutive_threshold(),
            done_consecutive_threshold: Self::default_done_consecutive_threshold(),
        }
    }
}

/// `[catchup]` section — incremental catch-up runtime (DOC-28 / #1762).
///
/// Why: the catch-up runtime is opt-in and its behaviour (which sources to
/// query, how many items to surface) should be configurable without editing
/// code. This section provides a persistent, file-based alternative to env vars.
/// What: boolean and numeric fields controlling the three catch-up sources
/// (paused sessions, git commits, palace drawers) and the item limits for each.
/// `auto` enables automatic injection of the catch-up digest when a new
/// native `tm` session starts.
/// Test: `config_catchup_defaults_parse`, `config_catchup_section_parses`.
///
// CUTOVER BRIDGE — remove post-migration (#1762)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CatchupConfig {
    /// Whether to automatically inject the catch-up digest on session start.
    ///
    /// `true` → catch-up is generated and appended as seed context when a new
    /// `tm session start` is executed. `false` → only the manual
    /// `tm session catchup` command triggers a digest.
    pub auto: bool,
    /// Whether to include git commit history in the digest.
    pub include_git: bool,
    /// Whether to include palace drawer inspection in the digest.
    pub include_palace: bool,
    /// Maximum number of recent git commits to surface.
    pub git_limit: usize,
    /// Maximum number of recent palace drawers to surface.
    pub drawer_limit: usize,
}

impl Default for CatchupConfig {
    fn default() -> Self {
        Self {
            auto: true,
            include_git: true,
            include_palace: true,
            git_limit: 50,
            drawer_limit: 15,
        }
    }
}

/// `[pm]` section — PM-layer toggles.
///
/// Why: the circuit-breaker and other PM-layer features need user-facing
/// on/off knobs; this section provides them without requiring env-var
/// spelunking.
/// What: boolean toggles for the PM-layer features. Defaults leave all
/// features at their compiled-in settings.
/// Test: `config_valid_parsed` checks circuit-breaker toggle parsing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct PmConfig {
    /// Enable or disable the agent circuit breaker.
    ///
    /// `None` → use the compiled-in default (enabled). `Some(false)` disables
    /// it globally (not recommended for production).
    pub circuit_breaker: Option<bool>,
}

// ──────────────────────────────────────────────
// Root config
// ──────────────────────────────────────────────

/// The full contents of `~/.trusty-mpm/config.toml`.
///
/// Why: a single top-level struct makes `toml::from_str` the only parsing
/// call; every section has a `Default` impl so absent sections yield
/// sensible values without errors.
/// What: five optional sections (`[agents]`, `[models]`, `[skills]`,
/// `[pm]`, `[session_manager]`); absent sections produce their `Default`.
/// The `[session_manager]` section (DOC-14 spec §10) defaults to disabled, so
/// its mere presence in the struct never changes runtime behavior.
/// Test: `config_absent_yields_defaults`, `config_valid_parsed`,
/// `config_malformed_falls_back`, `config_session_manager_*`.
///
/// Note: `Eq` is intentionally NOT derived — [`SessionManagerConfig`] carries a
/// floating-point `temperature`, and `f32` is not `Eq`. `PartialEq` is retained
/// for the equality assertions in tests.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct MpmConfig {
    /// `[agents]` — agent discovery sources.
    #[serde(default)]
    pub agents: AgentsConfig,

    /// `[models]` — per-agent and tier model configuration.
    #[serde(default)]
    pub models: ModelsConfig,

    /// `[skills]` — skill source configuration.
    #[serde(default)]
    pub skills: SkillsConfig,

    /// `[manifest]` — harness-manifest catalog source (HR-2 / DOC-17).
    #[serde(default)]
    pub manifest: ManifestConfig,

    /// `[pm]` — PM-layer feature toggles.
    #[serde(default)]
    pub pm: PmConfig,

    /// `[session_manager]` — Session Manager agent config (DOC-14 §10).
    ///
    /// Defaults to `enabled = false`; absent or partial sections parse to spec
    /// defaults and leave the legacy overseer path untouched.
    #[serde(default)]
    pub session_manager: SessionManagerConfig,

    /// `[control_plane]` — SESSCTL auth + cost guardrails (SPEC-SESSCTL-01 §9,
    /// WI-5 #1596).
    ///
    /// Absent or partial section → spec defaults (concurrency cap 5, launch
    /// stagger 2000 ms, auth timeout 30 s, LLM classifier off). The daemon
    /// injects this into the control-plane `SessionRegistry`.
    #[serde(default)]
    pub control_plane: crate::control::config::ControlPlaneConfig,

    /// `[style]` — active output-style selection (HR-4 / DOC-17).
    ///
    /// Absent section → professional default (`trusty-mpm`). See
    /// [`crate::core::output_style::StyleConfig`].
    #[serde(default)]
    pub style: crate::core::output_style::StyleConfig,

    /// `[catchup]` — incremental catch-up runtime (DOC-28 / #1762).
    ///
    /// Absent section → all defaults (auto-inject on, all sources enabled,
    /// git_limit=50, drawer_limit=15). Present only during the migration
    /// window.
    // CUTOVER BRIDGE — remove post-migration (#1762)
    #[serde(default)]
    pub catchup: CatchupConfig,

    /// `[idle_auto_stop]` — opt-in idle auto-suspend feature (#1816).
    ///
    /// Absent section → `enabled = false` (feature OFF, zero behavior change).
    /// Set `enabled = true` to activate the background idle-reaper loop.
    #[serde(default)]
    pub idle_auto_stop: IdleAutoStopConfig,
}

// ──────────────────────────────────────────────
// Loader
// ──────────────────────────────────────────────

impl MpmConfig {
    /// Load the user config from `~/.trusty-mpm/config.toml`.
    ///
    /// Why: every daemon and CLI path that cares about user preferences calls
    /// this exactly once at startup so configuration is always available via
    /// [`DaemonState`](crate::daemon::state::DaemonState) or a passed-in
    /// reference.
    /// What: reads `<root>/config.toml`; a missing file silently returns
    /// [`MpmConfig::default`]; a malformed file logs a warning at `tracing::warn`
    /// level and returns [`MpmConfig::default`] so startup is never aborted by
    /// a bad config.
    /// Test: `config_absent_yields_defaults`, `config_valid_parsed`,
    /// `config_malformed_falls_back`.
    pub fn load(root: &Path) -> Self {
        let path = root.join("config.toml");
        match std::fs::read_to_string(&path) {
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                // Absent config is the expected state on a fresh install.
                tracing::debug!("no config.toml found at {}; using defaults", path.display());
                Self::default()
            }
            Err(err) => {
                tracing::warn!(
                    "could not read config.toml at {}: {err}; using defaults",
                    path.display()
                );
                Self::default()
            }
            Ok(raw) => match toml::from_str::<Self>(&raw) {
                Ok(cfg) => {
                    tracing::debug!("loaded config from {}", path.display());
                    cfg
                }
                Err(err) => {
                    tracing::warn!(
                        "config.toml at {} is malformed: {err}; using defaults",
                        path.display()
                    );
                    Self::default()
                }
            },
        }
    }

    /// Load the user config from the canonical `~/.trusty-mpm/` root.
    ///
    /// Why: most callers want the real user config, not a test-time override;
    /// this convenience method resolves the home directory and delegates to
    /// [`load`](Self::load).
    /// What: calls `dirs::home_dir()` to find `~/.trusty-mpm/`; if home is
    /// unavailable (stripped CI), returns [`MpmConfig::default`].
    /// Test: covered indirectly by `config_absent_yields_defaults` (which passes
    /// a temp dir to [`load`]).
    pub fn load_default() -> Self {
        match dirs::home_dir() {
            Some(home) => Self::load(&home.join(".trusty-mpm")),
            None => {
                tracing::warn!("home directory unavailable; using default config");
                Self::default()
            }
        }
    }

    /// Expand a tier alias or pass through a full model id.
    ///
    /// Why: users write short aliases (`"haiku"`, `"sonnet"`, `"opus"`) in
    /// `config.toml`; callers need the canonical model id before passing
    /// `--model` to `claude`.
    /// What: checks `[models.tiers]` for `"haiku"`, `"sonnet"`, `"opus"` and
    /// substitutes the configured id; otherwise returns the input unchanged.
    /// Test: `tier_alias_expansion`.
    pub fn expand_model_alias<'a>(&'a self, alias: &'a str) -> &'a str {
        match alias {
            "haiku" => self
                .models
                .tiers
                .haiku
                .as_deref()
                .unwrap_or("claude-haiku-4-5"),
            "sonnet" => self
                .models
                .tiers
                .sonnet
                .as_deref()
                .unwrap_or("claude-sonnet-4-5"),
            "opus" => self
                .models
                .tiers
                .opus
                .as_deref()
                .unwrap_or("claude-opus-4-5"),
            "auto" => "claude-sonnet-4-5",
            other => other,
        }
    }
}

// ──────────────────────────────────────────────
// Model resolution (issue #390)
// ──────────────────────────────────────────────

/// Resolve the Claude model id to use when launching an agent session.
///
/// Why: Claude Code silently ignores the `model:` field in agent frontmatter,
/// so trusty-mpm must inject the correct model via `--model` at launch time.
/// This function implements the four-level precedence so every call site
/// (CLI launch, daemon session-start, MCP agent_delegate) uses the same
/// resolution logic.
/// What: evaluates four sources in descending priority order:
///
/// 1. `explicit` — a model string explicitly specified by the caller (e.g.,
///    from the `tm session start --model` flag). If `Some`, wins immediately.
/// 2. `config.models.agents.<agent_name>` — the per-agent override in
///    `~/.trusty-mpm/config.toml`.
/// 3. `frontmatter_model` — the `model:` field from the agent's frontmatter
///    (as read from the composed agent `.md` file).
/// 4. `config.models.default` or the built-in tier default (`"sonnet"`).
///
/// All resolved values are expanded through [`MpmConfig::expand_model_alias`]
/// so short aliases (`"haiku"`, `"sonnet"`, `"opus"`) become the canonical
/// model id strings Claude Code accepts.
/// Test: `model_resolution_precedence`.
pub fn resolve_agent_model(
    config: &MpmConfig,
    agent_name: &str,
    frontmatter_model: Option<&str>,
    explicit: Option<&str>,
) -> String {
    // 1. Explicit override always wins.
    if let Some(m) = explicit {
        return config.expand_model_alias(m).to_string();
    }

    // 2. Per-agent config entry.
    if let Some(m) = config.models.agents.get(agent_name) {
        return config.expand_model_alias(m).to_string();
    }

    // 3. Frontmatter model hint.
    if let Some(m) = frontmatter_model {
        return config.expand_model_alias(m).to_string();
    }

    // 4. Config default or built-in fallback.
    let fallback = config
        .models
        .default
        .as_deref()
        .unwrap_or("claude-sonnet-4-5");
    config.expand_model_alias(fallback).to_string()
}

// ──────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────

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

    /// Helper: write `content` to `<dir>/config.toml` and load from `dir`.
    fn load_from_str(dir: &Path, content: &str) -> MpmConfig {
        std::fs::write(dir.join("config.toml"), content).unwrap();
        MpmConfig::load(dir)
    }

    #[test]
    fn config_absent_yields_defaults() {
        // An absent config.toml must silently yield the default struct.
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = MpmConfig::load(dir.path());
        assert_eq!(cfg, MpmConfig::default());
        assert!(cfg.agents.sources.is_empty());
        assert!(cfg.models.agents.is_empty());
        // SM-1 zero-regression: absent [session_manager] → disabled by default.
        assert!(!cfg.session_manager.enabled);
    }

    #[test]
    fn config_valid_parsed() {
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[agents]
sources = ["bundled", "user"]

[models]
default = "sonnet"

[models.agents]
engineer = "haiku"
rust-engineer = "opus"

[models.tiers]
haiku = "claude-haiku-4-5"
sonnet = "claude-sonnet-4-5"
opus = "claude-opus-4-5"

[skills]
sources = ["bundled"]

[pm]
circuit_breaker = true

[session_manager]
enabled = true

[session_manager.inference]
provider = "anthropic"
sm_model = "anthropic/claude-sonnet-4-6"
temperature = 0.4

[session_manager.memory]
palace = "session-manager"
recall_top_k = 8

[session_manager.rounds]
window = 12
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert_eq!(cfg.agents.sources, vec!["bundled", "user"]);
        assert_eq!(
            cfg.models.agents.get("engineer").map(|s| s.as_str()),
            Some("haiku")
        );
        assert_eq!(
            cfg.models.agents.get("rust-engineer").map(|s| s.as_str()),
            Some("opus")
        );
        assert_eq!(cfg.models.tiers.haiku.as_deref(), Some("claude-haiku-4-5"));
        assert_eq!(cfg.models.default.as_deref(), Some("sonnet"));
        assert_eq!(cfg.skills.sources, vec!["bundled"]);
        assert_eq!(cfg.pm.circuit_breaker, Some(true));
        // [session_manager] parses through MpmConfig (DOC-14 §10).
        assert!(cfg.session_manager.enabled);
        assert_eq!(cfg.session_manager.inference.provider, "anthropic");
        assert_eq!(cfg.session_manager.inference.temperature, 0.4);
        assert_eq!(cfg.session_manager.memory.recall_top_k, 8);
        assert_eq!(cfg.session_manager.rounds.window, 12);
        // A field omitted from the partial inference block keeps its spec default.
        assert_eq!(cfg.session_manager.inference.context_token_budget, 24_000);
    }

    #[test]
    fn config_session_manager_partial_takes_defaults() {
        // A [session_manager] section that sets only `enabled` must leave every
        // nested subsection at its spec §10 default.
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[session_manager]
enabled = true
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert!(cfg.session_manager.enabled);
        assert_eq!(cfg.session_manager.inference.provider, "auto");
        assert_eq!(cfg.session_manager.memory.palace, "session-manager");
        assert_eq!(cfg.session_manager.rounds.window, 10);
    }

    #[test]
    fn config_session_manager_absent_is_noop_default() {
        // No [session_manager] section at all → the whole struct defaults and
        // the SM is disabled (zero-regression proof for SM-1).
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[models.agents]
engineer = "haiku"
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert_eq!(
            cfg.session_manager,
            crate::core::sm::config::SessionManagerConfig::default()
        );
        assert!(!cfg.session_manager.enabled);
    }

    #[test]
    fn config_manifest_section_parses() {
        // HR-2: the [manifest] section must parse the catalog source overrides,
        // and an absent section must leave them all None (no behavior change).
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[manifest]
repo = "https://github.com/me/my-fork"
git_ref = "dev"
ttl_hours = 6
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert_eq!(
            cfg.manifest.repo.as_deref(),
            Some("https://github.com/me/my-fork")
        );
        assert_eq!(cfg.manifest.git_ref.as_deref(), Some("dev"));
        assert_eq!(cfg.manifest.ttl_hours, Some(6));

        // Absent section → all None.
        let empty = MpmConfig::load(tempfile::TempDir::new().unwrap().path());
        assert_eq!(empty.manifest, ManifestConfig::default());
    }

    #[test]
    fn config_malformed_falls_back() {
        // A malformed config.toml must log (tested by absence of panic) and
        // return defaults — the daemon must not crash on a bad file.
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = load_from_str(dir.path(), "this is not toml {{{{");
        assert_eq!(cfg, MpmConfig::default());
    }

    #[test]
    fn config_partial_sections_are_fine() {
        // Users should be able to configure only the sections they care about.
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[models.agents]
engineer = "haiku"
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert_eq!(
            cfg.models.agents.get("engineer").map(|s| s.as_str()),
            Some("haiku")
        );
        // Other sections must yield defaults.
        assert!(cfg.agents.sources.is_empty());
        assert!(cfg.pm.circuit_breaker.is_none());
    }

    #[test]
    fn tier_alias_expansion() {
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[models.tiers]
haiku = "claude-haiku-4-5"
sonnet = "claude-sonnet-4-7"
opus = "claude-opus-4-7"
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert_eq!(cfg.expand_model_alias("haiku"), "claude-haiku-4-5");
        assert_eq!(cfg.expand_model_alias("sonnet"), "claude-sonnet-4-7");
        assert_eq!(cfg.expand_model_alias("opus"), "claude-opus-4-7");
        // Full model ids pass through unchanged.
        assert_eq!(cfg.expand_model_alias("claude-opus-4-7"), "claude-opus-4-7");
        // "auto" maps to sonnet.
        assert_eq!(cfg.expand_model_alias("auto"), "claude-sonnet-4-5");
    }

    #[test]
    fn tier_alias_defaults_when_not_configured() {
        // Without explicit tier config, built-in defaults must apply.
        let cfg = MpmConfig::default();
        assert_eq!(cfg.expand_model_alias("haiku"), "claude-haiku-4-5");
        assert_eq!(cfg.expand_model_alias("sonnet"), "claude-sonnet-4-5");
        assert_eq!(cfg.expand_model_alias("opus"), "claude-opus-4-5");
    }

    #[test]
    fn config_catchup_defaults_parse() {
        // An absent [catchup] section must silently yield the default struct.
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = MpmConfig::load(dir.path());
        assert!(cfg.catchup.auto, "auto defaults to true");
        assert!(cfg.catchup.include_git, "include_git defaults to true");
        assert!(
            cfg.catchup.include_palace,
            "include_palace defaults to true"
        );
        assert_eq!(cfg.catchup.git_limit, 50);
        assert_eq!(cfg.catchup.drawer_limit, 15);
    }

    #[test]
    fn config_catchup_section_parses() {
        // A full [catchup] section must override all defaults.
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[catchup]
auto = false
include_git = false
include_palace = true
git_limit = 25
drawer_limit = 5
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert!(!cfg.catchup.auto);
        assert!(!cfg.catchup.include_git);
        assert!(cfg.catchup.include_palace);
        assert_eq!(cfg.catchup.git_limit, 25);
        assert_eq!(cfg.catchup.drawer_limit, 5);
    }

    #[test]
    fn config_idle_auto_stop_defaults() {
        // An absent [idle_auto_stop] section must yield disabled (false) with
        // sensible numeric defaults — the zero-change guarantee for #1816.
        let dir = tempfile::TempDir::new().unwrap();
        let cfg = MpmConfig::load(dir.path());
        assert!(
            !cfg.idle_auto_stop.enabled,
            "idle_auto_stop must default to disabled"
        );
        assert!(
            cfg.idle_auto_stop.dry_run,
            "idle_auto_stop must default to report-only (dry_run = true) — #1783"
        );
        assert_eq!(cfg.idle_auto_stop.poll_interval_secs, 300);
        assert_eq!(cfg.idle_auto_stop.idle_consecutive_threshold, 3);
        assert_eq!(cfg.idle_auto_stop.done_consecutive_threshold, 1);
    }

    #[test]
    fn config_idle_auto_stop_section_parses() {
        // A full [idle_auto_stop] section must override all defaults.
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[idle_auto_stop]
enabled = true
dry_run = false
poll_interval_secs = 120
idle_consecutive_threshold = 5
done_consecutive_threshold = 2
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert!(cfg.idle_auto_stop.enabled);
        assert!(
            !cfg.idle_auto_stop.dry_run,
            "explicit dry_run = false must disable report-only mode"
        );
        assert_eq!(cfg.idle_auto_stop.poll_interval_secs, 120);
        assert_eq!(cfg.idle_auto_stop.idle_consecutive_threshold, 5);
        assert_eq!(cfg.idle_auto_stop.done_consecutive_threshold, 2);
    }

    #[test]
    fn config_idle_auto_stop_enabled_only_keeps_defaults() {
        // Setting only `enabled = true` must leave numeric fields at defaults
        // AND keep dry_run at its report-only default (the teardown-safe gate).
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[idle_auto_stop]
enabled = true
"#;
        let cfg = load_from_str(dir.path(), toml);
        assert!(cfg.idle_auto_stop.enabled);
        assert!(
            cfg.idle_auto_stop.dry_run,
            "enabling the loop alone must NOT enact teardown — dry_run stays true (#1783)"
        );
        assert_eq!(cfg.idle_auto_stop.poll_interval_secs, 300);
        assert_eq!(cfg.idle_auto_stop.idle_consecutive_threshold, 3);
        assert_eq!(cfg.idle_auto_stop.done_consecutive_threshold, 1);
    }

    #[test]
    fn model_resolution_precedence() {
        let dir = tempfile::TempDir::new().unwrap();
        let toml = r#"
[models]
default = "sonnet"

[models.agents]
engineer = "haiku"
"#;
        let cfg = load_from_str(dir.path(), toml);

        // 1. Explicit override wins over everything.
        let m = resolve_agent_model(&cfg, "engineer", Some("opus"), Some("claude-opus-4-5"));
        assert_eq!(m, "claude-opus-4-5");

        // 2. Config per-agent override wins over frontmatter.
        let m = resolve_agent_model(&cfg, "engineer", Some("opus"), None);
        // "engineer" maps to "haiku" → default haiku id.
        assert_eq!(m, "claude-haiku-4-5");

        // 3. Frontmatter hint wins over config default.
        let m = resolve_agent_model(&cfg, "unknown-agent", Some("opus"), None);
        assert_eq!(m, "claude-opus-4-5");

        // 4. Config default is the final fallback for unknown agents.
        let m = resolve_agent_model(&cfg, "unknown-agent", None, None);
        // "sonnet" tier default expands.
        assert_eq!(m, "claude-sonnet-4-5");

        // 5. Built-in fallback when neither config default nor anything else matches.
        let cfg_empty = MpmConfig::default();
        let m = resolve_agent_model(&cfg_empty, "nobody", None, None);
        assert_eq!(m, "claude-sonnet-4-5");
    }
}