trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Unit tests for [`super::config`] — `~/.trusty-mpm/config.toml` parsing.
//!
//! Why: split out of `config.rs` (issue #5034) so the production file stays
//! under the 500-SLOC cap as sections are added, mirroring the
//! `project_hooks.rs` / `project_hooks_tests.rs` split already used in this
//! crate. No test was changed by the move.
//! What: covers absent/valid/malformed loading, every config section's
//! defaults, and the four-level model-resolution precedence.
//! Test: this module IS the test suite for `super`.

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);
    // #5034 zero-regression: absent [hooks] → prompt-context hook ON.
    assert!(cfg.hooks.prompt_context);
}

/// Why (#5034): the opt-out must be opt-OUT. A present-but-partial
/// `[hooks]` section, and a config that never mentions hooks at all, must
/// both leave the injection enabled — otherwise adding the section for some
/// future key would silently switch memory injection off.
#[test]
fn config_hooks_defaults_to_enabled() {
    let dir = tempfile::TempDir::new().unwrap();
    // Present-but-empty section.
    assert!(load_from_str(dir.path(), "[hooks]\n").hooks.prompt_context);
    // Unrelated section only.
    assert!(
        load_from_str(dir.path(), "[pm]\ncircuit_breaker = true\n")
            .hooks
            .prompt_context
    );
    assert!(HooksConfig::default().prompt_context);
}

/// Why (#7830 / ADR-0062): session-ref publishing is the ruling, so it must be
/// on for a host that never edits a config file. A present-but-empty section,
/// and a config that never mentions it, both leave it enabled — otherwise
/// adding the section for a future key would silently stop publishing session
/// history.
#[test]
fn config_session_refs_defaults_to_enabled() {
    let dir = tempfile::TempDir::new().unwrap();
    assert!(MpmConfig::load(dir.path()).session_refs.enabled);
    assert!(
        load_from_str(dir.path(), "[session_refs]\n")
            .session_refs
            .enabled
    );
    assert!(
        load_from_str(dir.path(), "[hooks]\nprompt_context = false\n")
            .session_refs
            .enabled
    );
    assert!(SessionRefsConfig::default().enabled);
}

/// Why (#7830): the off switch is the whole reason the section exists — an
/// operator who does not want machine data pushed to `origin` needs one
/// supported way to say so.
#[test]
fn config_session_refs_can_be_disabled() {
    let dir = tempfile::TempDir::new().unwrap();
    assert!(
        !load_from_str(dir.path(), "[session_refs]\nenabled = false\n")
            .session_refs
            .enabled
    );
}

/// #9018: a host that never mentions `[pm_guard]` keeps the guard — an absent
/// file, an empty section, and an unrelated section all mean enabled.
#[test]
fn config_pm_guard_defaults_to_enabled() {
    let dir = tempfile::TempDir::new().unwrap();
    assert!(MpmConfig::load(dir.path()).pm_guard.enabled);
    assert!(load_from_str(dir.path(), "[pm_guard]\n").pm_guard.enabled);
    assert!(
        load_from_str(dir.path(), "[hooks]\nprompt_context = false\n")
            .pm_guard
            .enabled
    );
}

/// #9018: `enabled = false` turns the guard off and touches no other section.
#[test]
fn config_pm_guard_can_be_disabled() {
    let dir = tempfile::TempDir::new().unwrap();
    let cfg = load_from_str(dir.path(), "[pm_guard]\nenabled = false\n");
    assert!(!cfg.pm_guard.enabled);
    assert_eq!(cfg.hooks, HooksConfig::default());
}

/// #8524, #7905: both operator lists parse, default empty, and a mistyped
/// list leaves them empty — the narrower rule never applies by accident.
#[test]
fn config_pm_guard_operator_checkout_lists() {
    let dir = tempfile::TempDir::new().unwrap();
    let cfg = load_from_str(
        dir.path(),
        "[pm_guard]\nruntime_checkouts = [\"/srv/cron\"]\ndocuments_repos = [\"/w\"]\n",
    );
    assert_eq!(
        cfg.pm_guard.runtime_checkouts,
        vec![PathBuf::from("/srv/cron")]
    );
    assert_eq!(cfg.pm_guard.documents_repos, vec![PathBuf::from("/w")]);
    assert!(cfg.pm_guard.enabled);
    let bad = load_from_str(dir.path(), "[pm_guard]\nruntime_checkouts = \"/srv\"\n");
    assert!(bad.pm_guard.runtime_checkouts.is_empty());
    assert!(MpmConfig::default().pm_guard.documents_repos.is_empty());
    // #7905: a mistyped documents list, or a file that does not parse, lists
    // nothing; the rest of the guard stays on.
    for raw in [
        "[pm_guard]\ndocuments_repos = \"/w\"\n",
        "[pm_guard]\ndocuments_repos = [1]\n",
        "[pm_guard\ndocuments_repos = [\"/w\"]\n",
    ] {
        let cfg = load_from_str(dir.path(), raw);
        assert!(cfg.pm_guard.documents_repos.is_empty(), "listed: {raw}");
        assert!(cfg.pm_guard.enabled, "guard off: {raw}");
    }
}

/// #9018 Fail-Open Check: a file that cannot be parsed — including one whose
/// only fault is a mistyped `enabled` — leaves the guard ON, never off.
#[test]
fn config_pm_guard_malformed_file_stays_enabled() {
    let dir = tempfile::TempDir::new().unwrap();
    assert!(
        load_from_str(dir.path(), "[pm_guard]\nenabled = \"no\"\n")
            .pm_guard
            .enabled
    );
    assert!(
        load_from_str(dir.path(), "[pm_guard\nenabled = false\n")
            .pm_guard
            .enabled
    );
    // Unreadable: `config.toml` is a directory, so the read itself fails.
    let unreadable = tempfile::TempDir::new().unwrap();
    std::fs::create_dir(unreadable.path().join("config.toml")).unwrap();
    assert!(MpmConfig::load(unreadable.path()).pm_guard.enabled);
}

/// #7688: the host default is OFF, and "off" is spelled `None` — the key
/// declines to decide so a project's own `.trusty-mpm.toml` can.
#[test]
fn config_prompt_self_improvement_defaults_to_none() {
    let dir = tempfile::TempDir::new().unwrap();
    assert!(
        load_from_str(dir.path(), "[pm]\ncircuit_breaker = true\n")
            .pm
            .prompt_self_improvement
            .is_none()
    );
    assert!(
        load_from_str(dir.path(), "")
            .pm
            .prompt_self_improvement
            .is_none()
    );
}

#[test]
fn config_prompt_self_improvement_parses() {
    let dir = tempfile::TempDir::new().unwrap();
    assert_eq!(
        load_from_str(dir.path(), "[pm]\nprompt_self_improvement = true\n")
            .pm
            .prompt_self_improvement,
        Some(true)
    );
    assert_eq!(
        load_from_str(dir.path(), "[pm]\nprompt_self_improvement = false\n")
            .pm
            .prompt_self_improvement,
        Some(false)
    );
}

/// Why (#5034): the key is the only supported way to suppress the
/// per-prompt `trusty-memory prompt-context` injection — there is
/// deliberately no CLI flag and no env var — so its parsing is load-bearing.
/// What: sets `[hooks] prompt_context = false` alongside another section and
/// asserts it parses through and leaves everything else at its default.
#[test]
fn config_hooks_prompt_context_off() {
    let dir = tempfile::TempDir::new().unwrap();
    let cfg = load_from_str(
        dir.path(),
        r#"
[models.tiers]
opus = "claude-opus-5"

[hooks]
prompt_context = false
"#,
    );
    assert!(!cfg.hooks.prompt_context);
    assert_eq!(cfg.models.tiers.opus.as_deref(), Some("claude-opus-5"));
    // Every other section stays default — the toggle is narrow.
    assert_eq!(cfg.pm, PmConfig::default());
    assert_eq!(cfg.catchup, CatchupConfig::default());
}

#[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 config_idle_nudge_section_parses() {
    // Absent → disabled defaults (#2621, zero behavior change); a full
    // section overrides every field; a partial section (only `enabled`)
    // keeps the caps and message at their conservative defaults.
    let dir = tempfile::TempDir::new().unwrap();
    let absent = load_from_str(dir.path(), "");
    assert!(!absent.idle_nudge.enabled, "must default to disabled");
    assert_eq!(absent.idle_nudge.max_nudges_per_session, 2);
    assert_eq!(absent.idle_nudge.cooldown_secs, 300);
    assert_eq!(
        absent.idle_nudge.message,
        crate::core::idle_nudge::DEFAULT_NUDGE_MESSAGE
    );
    let full = load_from_str(
        dir.path(),
        "[idle_nudge]\nenabled = true\nmax_nudges_per_session = 1\ncooldown_secs = 60\nmessage = \"resume now\"\n",
    );
    assert!(full.idle_nudge.enabled);
    assert_eq!(full.idle_nudge.max_nudges_per_session, 1);
    assert_eq!(full.idle_nudge.cooldown_secs, 60);
    assert_eq!(full.idle_nudge.message, "resume now");

    let partial = load_from_str(dir.path(), "[idle_nudge]\nenabled = true\n");
    assert!(partial.idle_nudge.enabled);
    assert_eq!(partial.idle_nudge.max_nudges_per_session, 2);
    assert_eq!(partial.idle_nudge.cooldown_secs, 300);
    assert_eq!(
        partial.idle_nudge.message,
        crate::core::idle_nudge::DEFAULT_NUDGE_MESSAGE
    );
}

#[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");
}

// ── default-model layering (#5207) ───────────────────────────────────────────
//
// Why: `TrustyToolsConfig::default_model` was written by the console Config tab
// and the `config_write` MCP tool and read by nothing. These pin the chain that
// now consumes it, and the project layer that outranks it.

/// `load_effective` reads the project file from disk and applies its layer.
///
/// Why: `project_default_model_tops_the_chain` asserts the layering on an
/// in-memory struct, which stays green even if the loader stops reading the
/// project file at all. This pins the whole path — real `config.toml`, real
/// `.trusty-mpm.toml` — so the refactor that moved the root resolution into
/// `load_effective_default` (#5207) cannot silently drop the project layer.
/// Asserting the PROJECT value keeps it independent of whatever host YAML the
/// developer's home directory happens to hold: the project layer outranks it.
/// Test: itself.
#[test]
fn load_effective_applies_the_project_layer() {
    let root = tempfile::TempDir::new().unwrap();
    let project = tempfile::TempDir::new().unwrap();
    std::fs::write(
        root.path().join("config.toml"),
        "[models]\ndefault = \"haiku\"\n",
    )
    .unwrap();
    std::fs::write(
        project
            .path()
            .join(crate::core::project_config::PROJECT_CONFIG_FILE),
        "default_model = \"opus\"\n",
    )
    .unwrap();

    let cfg = MpmConfig::load_effective(root.path(), Some(project.path()));

    assert_eq!(
        resolve_agent_model(&cfg, "nobody", None, None),
        "claude-opus-4-5",
        "the project file's default_model must beat the root config.toml's"
    );
}

/// The project's committed `.trusty-mpm.toml` tops the default-model chain.
/// Test: itself.
#[test]
fn project_default_model_tops_the_chain() {
    let cfg = MpmConfig {
        models: ModelsConfig {
            default: Some("haiku".into()),
            ..ModelsConfig::default()
        },
        ..MpmConfig::default()
    }
    .with_default_model_layers(Some("opus"), Some("sonnet"));

    assert_eq!(
        resolve_agent_model(&cfg, "nobody", None, None),
        "claude-opus-4-5",
        "the project layer must beat both host layers"
    );
}

/// The host YAML `default_model` beats the host TOML `[models] default`.
///
/// Why: that is the contract the field's own editor advertises — the console
/// placeholder reads "(unset — uses ~/.trusty-mpm/config.toml)", i.e. the TOML
/// is the FALLBACK for this field, so a set YAML value must win.
/// Test: itself.
#[test]
fn yaml_default_model_beats_toml_default() {
    let cfg = MpmConfig {
        models: ModelsConfig {
            default: Some("haiku".into()),
            ..ModelsConfig::default()
        },
        ..MpmConfig::default()
    }
    .with_default_model_layers(None, Some("opus"));

    assert_eq!(
        resolve_agent_model(&cfg, "nobody", None, None),
        "claude-opus-4-5"
    );
}

/// With neither new layer set, the TOML default is untouched — no regression.
/// Test: itself.
#[test]
fn default_model_layers_are_a_no_op_when_unset() {
    let base = MpmConfig {
        models: ModelsConfig {
            default: Some("haiku".into()),
            ..ModelsConfig::default()
        },
        ..MpmConfig::default()
    };
    let layered = base.clone().with_default_model_layers(None, None);
    assert_eq!(base, layered, "absent layers must change nothing");
}

/// A default — from any layer — still loses to the MORE SPECIFIC settings.
///
/// Why: `default_model` is a default, not an override. Wiring it must not let a
/// project silently outrank an operator's explicit `--model` or a per-agent
/// pin.
/// Test: itself.
#[test]
fn project_default_model_still_loses_to_more_specific_settings() {
    let mut models = ModelsConfig::default();
    models.agents.insert("engineer".into(), "haiku".into());
    let cfg = MpmConfig {
        models,
        ..MpmConfig::default()
    }
    .with_default_model_layers(Some("opus"), None);

    assert_eq!(
        resolve_agent_model(&cfg, "engineer", None, Some("sonnet")),
        "claude-sonnet-4-5",
        "an explicit --model must beat the project default"
    );
    assert_eq!(
        resolve_agent_model(&cfg, "engineer", None, None),
        "claude-haiku-4-5",
        "a per-agent pin must beat the project default"
    );
}