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
691
692
693
//! Unit tests for trusty-mpm's `~/.trusty-tools/trusty-mpm/config.yaml`
//! settings and workspace-root resolution, split out of
//! `trusty_tools_config.rs` to keep that file under the 500-SLOC production
//! cap (#610) — the inline `mod tests` counted as production source.

use super::*;

/// Serialise env mutation so the env-reading tests cannot race each other
/// across the shared test process. Delegates to the crate-wide
/// [`super::env_test_lock`] so env tests in OTHER modules are serialised too.
fn env_lock() -> std::sync::MutexGuard<'static, ()> {
    super::env_test_lock()
}

/// Why (DOC-34): the managed `CLAUDE_CONFIG_DIR` MUST resolve under the
/// shared `~/.trusty-tools/trusty-mpm/` base (never `~/.trusty-mpm` or the
/// project). Pinning the exact layout guards the segregation guarantee.
/// Test: itself.
#[test]
fn managed_claude_config_dir_nests_under_trusty_tools() {
    let base = PathBuf::from("/home/bob");
    assert_eq!(
        managed_claude_config_dir_at(&base),
        PathBuf::from("/home/bob/.trusty-tools/trusty-mpm/claude-config")
    );
    // The production accessor, when home resolves, must agree with the
    // hermetic `_at` variant on the trailing `.trusty-tools/trusty-mpm/...`
    // segments regardless of the actual home directory.
    if let Some(dir) = managed_claude_config_dir() {
        assert!(
            dir.ends_with("trusty-mpm/claude-config"),
            "managed config dir must end with trusty-mpm/claude-config, got {}",
            dir.display()
        );
        assert!(
            dir.to_string_lossy().contains(".trusty-tools"),
            "managed config dir must live under .trusty-tools, got {}",
            dir.display()
        );
    }
}

/// Why: the built-in default (no env, no config) must be the #1220 path.
/// Test: itself.
#[test]
fn default_template_is_trusty_mpm_projects() {
    let _g = env_lock();
    // SAFETY: guarded by env_lock; restored below.
    unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
    let root = workspace_root(&TrustyToolsConfig::default());
    assert!(
        root.ends_with(DEFAULT_WORKSPACE_DIR),
        "expected …/{DEFAULT_WORKSPACE_DIR}, got {}",
        root.display()
    );
}

/// Why: the env var must win over both the config template and the default.
/// Test: itself.
#[test]
fn env_overrides_config_and_default() {
    let _g = env_lock();
    let cfg = TrustyToolsConfig {
        workspace_root_template: Some("~/from-config".into()),
        ..Default::default()
    };
    // SAFETY: guarded by env_lock; removed at end.
    unsafe { std::env::set_var(WORKSPACE_ROOT_ENV, "/explicit/env/root") };
    let root = workspace_root(&cfg);
    unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
    assert_eq!(root, PathBuf::from("/explicit/env/root"));
}

/// Why: with no env override, the config template must be used (and `~`
/// expanded), beating the built-in default.
/// Test: itself.
#[test]
fn config_template_used_when_no_env() {
    let _g = env_lock();
    unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
    let cfg = TrustyToolsConfig {
        workspace_root_template: Some("/custom/projects".into()),
        ..Default::default()
    };
    let root = workspace_root(&cfg);
    assert_eq!(root, PathBuf::from("/custom/projects"));
}

/// Why (#5204): making the worktree base configurable must not move it for the
/// operators who configure nothing — an unconfigured resolve has to stay
/// `.worktrees`, byte for byte, or every existing checkout's worktrees become
/// invisible to the remover, the pruner, and the indexer at once.
/// Test: itself.
#[test]
fn worktrees_dirname_defaults_to_dot_worktrees() {
    let _g = env_lock();
    // SAFETY: serialised by the crate-wide env lock.
    unsafe { std::env::remove_var(WORKTREES_DIRNAME_ENV) };
    let cfg = TrustyToolsConfig::default();
    assert_eq!(worktrees_dirname(&cfg), DEFAULT_WORKTREES_DIRNAME);
    assert_eq!(worktrees_dirname(&cfg), ".worktrees");
}

/// Why (#5204): the whole point of the feature — a base named in
/// `~/.trusty-tools/trusty-mpm/config.yaml` must be the one creation uses, and
/// the env var must still outrank it.
/// What: a configured value is returned as-is; the env var beats it; and a
/// reserved name is refused back to the default even when configured (the
/// `.claude/worktrees` guard, proven end to end in
/// `configured_base_can_never_claim_a_claude_agent_worktree`).
/// Test: itself.
#[test]
fn worktrees_dirname_honours_config() {
    let _g = env_lock();
    // SAFETY: serialised by the crate-wide env lock; cleared before returning.
    unsafe { std::env::remove_var(WORKTREES_DIRNAME_ENV) };

    // This file is compiled INTO the defining crate, so `#[non_exhaustive]`
    // does not forbid a struct literal here.
    let cfg = TrustyToolsConfig {
        worktrees_dirname: Some(".sessions".into()),
        ..Default::default()
    };
    assert_eq!(worktrees_dirname(&cfg), ".sessions");

    // SAFETY: as above.
    unsafe { std::env::set_var(WORKTREES_DIRNAME_ENV, ".from-env") };
    let observed_env = worktrees_dirname(&cfg);
    // SAFETY: as above.
    unsafe { std::env::remove_var(WORKTREES_DIRNAME_ENV) };
    assert_eq!(
        observed_env, ".from-env",
        "env must outrank the config value"
    );

    let reserved = TrustyToolsConfig {
        worktrees_dirname: Some("worktrees".into()),
        ..Default::default()
    };
    assert_eq!(
        worktrees_dirname(&reserved),
        DEFAULT_WORKTREES_DIRNAME,
        "a reserved name must be refused even when explicitly configured"
    );
}

/// Why: a leading `~` in a template must expand to the home directory.
/// Test: itself.
#[test]
fn tilde_expansion() {
    // #5203: expansion moved to the shared resolver in trusty-common; this
    // asserts the behaviour trusty-mpm still depends on.
    use trusty_common::workspace_layout::expand_tilde;
    let home = PathBuf::from("/home/bob");
    assert_eq!(
        expand_tilde("~/trusty-mpm-projects", &home),
        PathBuf::from("/home/bob/trusty-mpm-projects")
    );
    assert_eq!(expand_tilde("~", &home), home);
    assert_eq!(expand_tilde("/abs/path", &home), PathBuf::from("/abs/path"));
}

/// Why: the `github:` section must round-trip through YAML so an operator's
/// declarative binding survives load/save unchanged (and absent fields stay
/// absent rather than serialising as nulls).
/// Test: itself.
#[test]
fn github_config_yaml_round_trip() {
    let cfg = TrustyToolsConfig {
        github: Some(GithubConfig {
            config_dir: Some(PathBuf::from("/home/bob/.config/gh-work")),
            token_env: Some("WORK_GH_TOKEN".into()),
            account: Some("bob-work".into()),
            host: Some("github.example.com".into()),
        }),
        ..Default::default()
    };
    let yaml = serde_yaml::to_string(&cfg).expect("serialise");
    let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
    assert_eq!(cfg, back);
    // Absent top-level fields must not appear in the YAML.
    assert!(!yaml.contains("workspace_root_template"), "yaml: {yaml}");
    assert!(yaml.contains("github:"), "yaml: {yaml}");
}

/// Why: the #1265 no-plaintext-token guarantee — the config stores only the
/// NAME of the env var, never the secret value. A reviewer must be able to
/// assert this invariant mechanically.
/// Test: itself.
#[test]
fn github_config_stores_only_env_name() {
    let cfg = GithubConfig {
        token_env: Some("MY_GH_TOKEN".into()),
        ..Default::default()
    };
    // The struct field is named `token_env` and holds the var NAME; there is
    // no field that could hold a token value. Serialised form proves it.
    let yaml = serde_yaml::to_string(&cfg).expect("serialise");
    assert!(yaml.contains("token_env"), "yaml: {yaml}");
    assert!(yaml.contains("MY_GH_TOKEN"), "yaml: {yaml}");
    assert!(
        !yaml.contains("token:"),
        "must not have a bare token field: {yaml}"
    );
}

/// Why (#2081): a `projects:` entry's `gh_user` preference must round-trip
/// through YAML, and an absent `gh_user` must not serialise (matching every
/// other optional field on `ProjectConfig`) so existing configs deserialise
/// unchanged.
/// Test: itself.
#[test]
fn project_config_gh_user_yaml_round_trip() {
    let cfg = TrustyToolsConfig {
        projects: vec![ProjectConfig {
            name: "trusty-tools".into(),
            repo_url: "https://github.com/bobmatnyc/trusty-tools".into(),
            default_branch: Some("main".into()),
            stack_hint: None,
            tags: None,
            description: None,
            gh_user: Some("bobmatnyc".into()),
            gh_account: Some("bobmatnyc".into()),
            github: None,
            commit_name: None,
            commit_email: None,
            untracked_sync: None,
            worktree: None,
        }],
        ..Default::default()
    };
    let yaml = serde_yaml::to_string(&cfg).expect("serialise");
    assert!(yaml.contains("gh_user"), "yaml: {yaml}");
    assert!(yaml.contains("gh_account"), "yaml: {yaml}");
    let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
    assert_eq!(cfg, back);

    // Absent gh_user/gh_account must not serialise.
    let no_pref = TrustyToolsConfig {
        projects: vec![ProjectConfig {
            name: "other".into(),
            repo_url: "https://github.com/o/other".into(),
            default_branch: None,
            stack_hint: None,
            tags: None,
            description: None,
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
            untracked_sync: None,
            worktree: None,
        }],
        ..Default::default()
    };
    let yaml_no_pref = serde_yaml::to_string(&no_pref).expect("serialise");
    assert!(!yaml_no_pref.contains("gh_user"), "yaml: {yaml_no_pref}");
    assert!(!yaml_no_pref.contains("gh_account"), "yaml: {yaml_no_pref}");
}

/// Why (#2184): a project's per-project `github:` binding and commit
/// identity (`commit_name`/`commit_email`) must round-trip through YAML,
/// and absent fields must not serialise — matching every other optional
/// `ProjectConfig` field so existing configs deserialise unchanged.
/// Test: itself.
#[test]
fn project_config_github_and_commit_identity_yaml_round_trip() {
    let cfg = TrustyToolsConfig {
        projects: vec![ProjectConfig {
            name: "work-repo".into(),
            repo_url: "https://github.com/acme/work-repo".into(),
            default_branch: None,
            stack_hint: None,
            tags: None,
            description: None,
            gh_user: None,
            gh_account: None,
            github: Some(GithubConfig {
                config_dir: Some(PathBuf::from("/home/bob/.config/gh-work")),
                token_env: None,
                account: Some("bob-work".into()),
                host: None,
            }),
            commit_name: Some("Bob (work bot)".into()),
            commit_email: Some("bob@acme.example.com".into()),
            untracked_sync: None,
            worktree: None,
        }],
        ..Default::default()
    };
    let yaml = serde_yaml::to_string(&cfg).expect("serialise");
    assert!(yaml.contains("github:"), "yaml: {yaml}");
    assert!(yaml.contains("commit_name"), "yaml: {yaml}");
    assert!(yaml.contains("commit_email"), "yaml: {yaml}");
    let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
    assert_eq!(cfg, back);

    // Absent per-project github/commit fields must not serialise.
    let minimal = TrustyToolsConfig {
        projects: vec![ProjectConfig {
            name: "minimal".into(),
            repo_url: "https://github.com/o/minimal".into(),
            default_branch: None,
            stack_hint: None,
            tags: None,
            description: None,
            gh_user: None,
            gh_account: None,
            github: None,
            commit_name: None,
            commit_email: None,
            untracked_sync: None,
            worktree: None,
        }],
        ..Default::default()
    };
    let yaml_minimal = serde_yaml::to_string(&minimal).expect("serialise");
    assert!(!yaml_minimal.contains("github:"), "yaml: {yaml_minimal}");
    assert!(
        !yaml_minimal.contains("commit_name"),
        "yaml: {yaml_minimal}"
    );
    assert!(
        !yaml_minimal.contains("commit_email"),
        "yaml: {yaml_minimal}"
    );
}

/// Why: the `daemon:` section (#1836) must round-trip through YAML, and an
/// absent section must not serialise at all (matching every other optional
/// top-level section).
/// Test: itself.
#[test]
fn daemon_config_yaml_round_trip() {
    let cfg = TrustyToolsConfig {
        daemon: Some(DaemonConfig {
            allow_mcp_spawn: Some(true),
        }),
        ..Default::default()
    };
    let yaml = serde_yaml::to_string(&cfg).expect("serialise");
    let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
    assert_eq!(cfg, back);
    assert!(yaml.contains("allow_mcp_spawn"), "yaml: {yaml}");

    // Absent daemon section must not serialise.
    let empty = TrustyToolsConfig::default();
    let yaml_empty = serde_yaml::to_string(&empty).expect("serialise");
    assert!(!yaml_empty.contains("daemon"), "yaml: {yaml_empty}");
}

/// Why: the `tmux:` section (#2398) must round-trip through YAML, and an
/// absent section must not serialise at all (matching every other
/// optional top-level section).
/// Test: itself.
#[test]
fn tmux_config_yaml_round_trip() {
    let cfg = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(50_000),
            mouse: Some(false),
            alternate_screen: Some(false),
        }),
        ..Default::default()
    };
    let yaml = serde_yaml::to_string(&cfg).expect("serialise");
    let back: TrustyToolsConfig = serde_yaml::from_str(&yaml).expect("deserialise");
    assert_eq!(cfg, back);
    assert!(yaml.contains("history_limit"), "yaml: {yaml}");
    assert!(yaml.contains("mouse"), "yaml: {yaml}");
    assert!(yaml.contains("alternate_screen"), "yaml: {yaml}");

    // Absent tmux section must not serialise.
    let empty = TrustyToolsConfig::default();
    let yaml_empty = serde_yaml::to_string(&empty).expect("serialise");
    assert!(!yaml_empty.contains("tmux"), "yaml: {yaml_empty}");
}

/// Why: with no `tmux:` section at all, resolution must fall back to the
/// built-in defaults (10,000-line history-limit since #8404, mouse on,
/// alternate-screen off since #5364).
/// Test: itself.
#[test]
fn tmux_options_default_when_no_config() {
    let opts = resolve_tmux_options(&TrustyToolsConfig::default());
    assert_eq!(opts.history_limit, DEFAULT_TMUX_HISTORY_LIMIT);
    // #8404: pinned literally — 100,000 lagged every pane on the host.
    assert_eq!(opts.history_limit, 10_000);
    assert_eq!(opts.mouse, DEFAULT_TMUX_MOUSE);
    assert_eq!(opts.alternate_screen, DEFAULT_TMUX_ALTERNATE_SCREEN);
}

/// Why (#5364): the alternate screen is OFF by default, so a managed session
/// has working scrollback without the operator finding the knob first. An
/// absent section — and an absent field within a present section — must both
/// resolve to `false`. #5151 shipped this defaulting to `true` (tmux's factory
/// value), which left the unscrollable-session bug in place for everyone who
/// never opted in; that is the regression this test exists to catch.
/// Test: itself.
#[test]
fn tmux_options_alternate_screen_defaults_off() {
    // Compile-time tripwire: flipping the default is a deliberate act.
    const { assert!(!DEFAULT_TMUX_ALTERNATE_SCREEN) };
    assert!(!resolve_tmux_options(&TrustyToolsConfig::default()).alternate_screen);

    // A `tmux:` section that sets other fields but not this one still
    // falls back per-field.
    let partial = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(10_000),
            mouse: Some(false),
            alternate_screen: None,
        }),
        ..Default::default()
    };
    assert!(!resolve_tmux_options(&partial).alternate_screen);
}

/// Why (#5151): a configured `false` is the ONLY thing that turns the
/// alternate screen off, and it must be honoured verbatim — unlike
/// `history_limit`, neither value is pathological, so nothing is clamped
/// or corrected.
/// Test: itself.
#[test]
fn tmux_options_alternate_screen_config_override() {
    let off = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            alternate_screen: Some(false),
            ..Default::default()
        }),
        ..Default::default()
    };
    assert!(!resolve_tmux_options(&off).alternate_screen);

    let on = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            alternate_screen: Some(true),
            ..Default::default()
        }),
        ..Default::default()
    };
    assert!(resolve_tmux_options(&on).alternate_screen);
}

/// Why (#5151): the YAML key an operator actually types must deserialise.
/// A rename or serde-attribute slip would leave `alternate_screen: false`
/// silently ignored, which is indistinguishable from the feature not
/// working.
/// Test: itself.
#[test]
fn tmux_alternate_screen_parses_from_yaml() {
    let cfg: TrustyToolsConfig =
        serde_yaml::from_str("tmux:\n  alternate_screen: false\n").expect("deserialise");
    assert_eq!(
        cfg.tmux.as_ref().and_then(|t| t.alternate_screen),
        Some(false)
    );
    assert!(!resolve_tmux_options(&cfg).alternate_screen);
}

/// Why: an explicit `tmux:` section must override the built-in defaults,
/// field-by-field (a partial section still falls back per-field).
/// Test: itself.
#[test]
fn tmux_options_config_override() {
    let cfg = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(250_000),
            mouse: Some(false),
            alternate_screen: Some(false),
        }),
        ..Default::default()
    };
    let opts = resolve_tmux_options(&cfg);
    assert_eq!(opts.history_limit, 250_000);
    assert!(!opts.mouse);

    // Partial override: only history_limit set, mouse falls back to default.
    // #8404: 50_000, not 10_000 — the default is now 10_000, so an equal
    // value could not show the override won.
    let partial = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(50_000),
            mouse: None,
            alternate_screen: None,
        }),
        ..Default::default()
    };
    let opts = resolve_tmux_options(&partial);
    assert_eq!(opts.history_limit, 50_000);
    assert_eq!(opts.mouse, DEFAULT_TMUX_MOUSE);
}

/// Why (#2398 QA finding): `history-limit 0` means "no scrollback" in
/// tmux, not "unlimited" — a configured `0` must be clamped up to
/// [`MIN_TMUX_HISTORY_LIMIT`] rather than honoured verbatim, which would
/// silently reintroduce the unscrollable-session problem this feature
/// exists to fix.
/// Test: itself.
#[test]
fn tmux_options_clamps_zero_history_limit() {
    let cfg = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(0),
            mouse: None,
            alternate_screen: None,
        }),
        ..Default::default()
    };
    let opts = resolve_tmux_options(&cfg);
    assert_eq!(opts.history_limit, MIN_TMUX_HISTORY_LIMIT);
}

/// Why: any near-zero configured value below the floor is clamped, not
/// just the literal `0` case.
/// Test: itself.
#[test]
fn tmux_options_clamps_below_minimum() {
    let cfg = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(42),
            mouse: None,
            alternate_screen: None,
        }),
        ..Default::default()
    };
    let opts = resolve_tmux_options(&cfg);
    assert_eq!(opts.history_limit, MIN_TMUX_HISTORY_LIMIT);

    // A value AT the floor is left untouched (not bumped further).
    let at_floor = TrustyToolsConfig {
        tmux: Some(TmuxConfig {
            history_limit: Some(MIN_TMUX_HISTORY_LIMIT),
            mouse: None,
            alternate_screen: None,
        }),
        ..Default::default()
    };
    assert_eq!(
        resolve_tmux_options(&at_floor).history_limit,
        MIN_TMUX_HISTORY_LIMIT
    );
}

/// Why: the project subpath must nest `<owner>/<repo>` under the root in that
/// order (the #1220 layout the migration scan also relies on).
/// Test: itself.
#[test]
fn subpath_nests_owner_repo() {
    let _g = env_lock();
    unsafe { std::env::remove_var(WORKSPACE_ROOT_ENV) };
    let cfg = TrustyToolsConfig {
        workspace_root_template: Some("/projects".into()),
        ..Default::default()
    };
    let gh = GithubPath {
        owner: "bobmatnyc".into(),
        repo: "trusty-tools".into(),
    };
    assert_eq!(
        workspace_subpath(&cfg, &gh),
        PathBuf::from("/projects/bobmatnyc/trusty-tools")
    );
}

// untracked_sync (#2196) resolution + YAML round-trip tests live in
// `untracked_sync::tests` (split out to keep this file under the
// 500-SLOC cap; see that module's doc).

/// #6927: no `disk:` section means an EMPTY keep-list — nothing is kept, and
/// nothing is hard-coded to any operator's paths.
#[test]
fn disk_keep_list_defaults_to_empty() {
    let config = TrustyToolsConfig::default();
    assert!(config.disk.is_none());
    assert!(disk_keep_list_patterns(&config).is_empty());
}

/// #6927: the `disk:` section round-trips through the YAML the console Config
/// tab reads and writes.
#[test]
fn disk_config_yaml_round_trip() {
    let yaml = "disk:\n  keep_list:\n    - ~/work/hotstats\n    - '**/scratch-*'\n";
    let config: TrustyToolsConfig = serde_yaml::from_str(yaml).expect("parse the disk section");
    assert_eq!(
        disk_keep_list_patterns(&config),
        vec!["~/work/hotstats".to_string(), "**/scratch-*".to_string()]
    );
    let back = serde_yaml::to_string(&config).expect("serialize");
    assert!(back.contains("keep_list"), "{back}");
    assert!(back.contains("hotstats"), "{back}");
}

/// #7497: `disk.max_usage_pct` round-trips through the same section, and an
/// absent key stays absent rather than being written back as a number the
/// operator never chose.
#[test]
fn max_usage_pct_round_trips() {
    let yaml = "disk:\n  max_usage_pct: 85\n";
    let config: TrustyToolsConfig = serde_yaml::from_str(yaml).expect("parse the disk section");
    assert_eq!(
        config.disk.as_ref().and_then(|d| d.max_usage_pct),
        Some(85),
        "the operator's threshold must reach the gate"
    );
    let back = serde_yaml::to_string(&config).expect("serialize");
    assert!(back.contains("max_usage_pct: 85"), "{back}");

    let keep_only: TrustyToolsConfig = serde_yaml::from_str("disk:\n  keep_list:\n    - /a\n")
        .expect("parse a disk section without the key");
    assert_eq!(keep_only.disk.as_ref().and_then(|d| d.max_usage_pct), None);
    let back = serde_yaml::to_string(&keep_only).expect("serialize");
    assert!(
        !back.contains("max_usage_pct"),
        "an absent threshold must not be written back: {back}"
    );
}

/// Write `yaml` as the trusty-mpm config under a fake home, and return it.
///
/// Why: `load_disk_keep_list_at` is the hermetic half of the reader precisely
/// so a test can put a real file on disk without touching the operator's own.
fn config_home(yaml: &str) -> tempfile::TempDir {
    let home = tempfile::tempdir().expect("tempdir");
    let path = trusty_common::crate_config::crate_config_path_at(home.path(), CRATE_NAME);
    std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
    std::fs::write(&path, yaml).expect("write config");
    home
}

/// #6927: no config file at all is an EMPTY keep-list, which permits.
#[test]
fn an_absent_config_yields_an_empty_keep_list() {
    let home = tempfile::tempdir().expect("tempdir");
    let list = load_disk_keep_list_at(home.path());
    assert_eq!(
        list.error(),
        None,
        "an absent file is not an unreadable one"
    );
    assert!(list.patterns().is_empty());
    assert!(
        list.keeps(std::path::Path::new("/anything")).is_none(),
        "the documented default must keep nothing"
    );
}

/// #6927: a readable config yields exactly the operator's patterns.
#[test]
fn a_valid_config_yields_the_operators_patterns() {
    let home = config_home("disk:\n  keep_list:\n    - /work/hotstats\n");
    let list = load_disk_keep_list_at(home.path());
    assert_eq!(list.error(), None);
    assert_eq!(list.patterns(), ["/work/hotstats".to_string()]);
    assert!(
        list.keeps(std::path::Path::new("/work/hotstats/wt"))
            .is_some()
    );
}

/// #6927 — the fail-open the review found: a YAML error ANYWHERE in the file
/// used to yield an empty keep-list, because `TrustyToolsConfig::load`
/// collapses every parse failure to `Default`. The keep-list reader is
/// fallible for exactly this reason.
#[test]
fn an_unparseable_config_yields_an_unreadable_keep_list() {
    // A valid keep-list entry, and a typo in an UNRELATED key. `auto_resume`
    // is a bool, so this is the `crate_config::load_malformed_is_err` shape.
    let home =
        config_home("disk:\n  keep_list:\n    - /work/hotstats\nauto_resume: not-a-boolean\n");

    // What the LENIENT reader still does, and why it cannot be the one a
    // protective gate uses: `disk` is gone, so the patterns are empty.
    let lenient = trusty_common::crate_config::load_at::<TrustyToolsConfig>(
        &trusty_common::crate_config::crate_config_path_at(home.path(), CRATE_NAME),
    );
    assert!(lenient.is_err(), "the fixture must actually be malformed");

    let list = load_disk_keep_list_at(home.path());
    let error = list
        .error()
        .expect("an unparseable config must be reported, not silently defaulted");
    assert!(
        error.contains("YAML"),
        "the reason must name the parse failure: {error}"
    );
    assert!(
        list.keeps(std::path::Path::new("/anything/at/all"))
            .is_some(),
        "a keep-list that could not be read must keep EVERYTHING"
    );
}