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
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
//! Tests for the `launchd_secrets` doctor row and its repair (#8236).
//!
//! Every fixture is a temp directory and every value an obvious fake. No test
//! here reads or writes `~/Library/LaunchAgents`, the real login Keychain, or
//! the real `~/.trusty-mpm`; the repair migrates into an injected
//! `MemoryKeyStore`.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use trusty_common::credentials::{KeyStore, KeyStoreError, MemoryKeyStore};

use super::*;
use crate::core::doctor_repair::{RepairMode, StepStatus};
use crate::daemon::doctor_launchd_secrets_repair::repair_with_store;

/// A fake OpenRouter-shaped key. Not a credential; the `FAKE` run is the point.
const FAKE_API_KEY: &str = "sk-or-v1-0000000000000000000000000000FAKE";

/// A fake Telegram bot-token-shaped value, for the no-vendor-prefix path.
const FAKE_BOT_TOKEN: &str = "1234567890:AAFAKEFAKEFAKEFAKEFAKEFAKEFAKEFAKEFAKE";

/// Assert a rendered row, step or error never carries a fixture value.
fn assert_value_never_echoed(text: &str) {
    for value in [FAKE_API_KEY, FAKE_BOT_TOKEN] {
        assert!(
            !text.contains(value),
            "output must name the key, never the value: {text}"
        );
    }
    assert!(!text.contains("sk-or-"), "credential prefix leaked: {text}");
}

/// A home directory with a `Library/LaunchAgents` in it.
fn home_with_agents() -> tempfile::TempDir {
    let home = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(home.path().join("Library/LaunchAgents")).expect("mkdir");
    home
}

/// Write `body` as `<home>/Library/LaunchAgents/<name>` and return its path.
fn install(home: &Path, name: &str, body: &str) -> PathBuf {
    let path = home.join("Library/LaunchAgents").join(name);
    std::fs::write(&path, body).expect("write plist");
    path
}

/// A unit carrying one registry-mapped credential among ordinary tunables.
fn plist_with_credential() -> String {
    format!(
        "<plist version=\"1.0\">\n<dict>\n  \
         <key>Label</key>\n  <string>com.trusty.mpm</string>\n  \
         <key>EnvironmentVariables</key>\n  <dict>\n    \
         <key>PATH</key>\n    <string>/usr/bin</string>\n    \
         <key>OPENROUTER_API_KEY</key>\n    <string>{FAKE_API_KEY}</string>\n    \
         <key>RUST_LOG</key>\n    <string>info</string>\n  \
         </dict>\n</dict>\n</plist>\n"
    )
}

/// A store that accepts every write and serves nothing back.
///
/// Why: the read-back confirmation is what licenses the strip. A backend that
/// accepts a write it cannot serve must NOT license one.
struct WriteOnlyStore;

impl KeyStore for WriteOnlyStore {
    fn get(&self, _provider: &str) -> Option<String> {
        None
    }
    fn set(&self, _provider: &str, _value: &str) -> Result<(), KeyStoreError> {
        Ok(())
    }
    fn unset(&self, _provider: &str) -> Result<(), KeyStoreError> {
        Ok(())
    }
    fn list(&self) -> Vec<String> {
        Vec::new()
    }
}

/// Why: the scan is the whole diagnostic; a finding that carried the value
/// would make `tm doctor` itself a disclosure.
/// Test: this test.
#[test]
fn scan_names_the_key_not_the_value() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );

    let findings = scan_launch_agents(home.path()).expect("scan");

    assert_eq!(findings.len(), 1);
    assert_eq!(
        findings[0].migratable,
        vec!["OPENROUTER_API_KEY".to_string()]
    );
    assert_value_never_echoed(&format!("{:?}", findings[0]));
}

/// Why (#8236 item 2): a key with no registry mapping has nowhere to migrate
/// to, so it must be classified apart from one that has.
/// Test: this test.
#[test]
fn scan_splits_registry_mapped_keys_from_unmapped_ones() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.agents.slack.plist",
        &format!(
            "<plist version=\"1.0\">\n<dict>\n  \
             <key>EnvironmentVariables</key>\n  <dict>\n    \
             <key>SLACK_APP_TOKEN</key>\n    <string>xapp-1-FAKEFAKEFAKEFAKE</string>\n    \
             <key>AWS_SECRET_ACCESS_KEY</key>\n    <string>{FAKE_BOT_TOKEN}</string>\n  \
             </dict>\n</dict>\n</plist>\n"
        ),
    );

    let findings = scan_launch_agents(home.path()).expect("scan");

    assert_eq!(findings[0].migratable, vec!["SLACK_APP_TOKEN".to_string()]);
    assert_eq!(
        findings[0].unmapped,
        vec!["AWS_SECRET_ACCESS_KEY".to_string()]
    );
}

/// Why (#8236 item 4): a binary plist decoded as text finds no `<key>`, so the
/// scanner would report the host CLEAN. Unknown with an actionable reason is
/// the only correct answer.
/// Test: this test.
#[test]
fn scan_reports_a_binary_plist_as_unknown() {
    let home = home_with_agents();
    let path = home
        .path()
        .join("Library/LaunchAgents/com.trusty.mpm.plist");
    let mut bytes = b"bplist00".to_vec();
    bytes.extend_from_slice(&[0xd1, 0x01, 0x02]);
    std::fs::write(&path, bytes).expect("write");

    let findings = scan_launch_agents(home.path()).expect("scan");
    let why = findings[0].unreadable.clone().expect("unreadable");

    assert!(why.contains("BINARY"), "{why}");
    assert!(why.contains("plutil -convert xml1"), "{why}");
    assert!(findings[0].binary_plist, "the binary flag drives the row");
    assert!(findings[0].migratable.is_empty());
}

/// Why: a plist the parser cannot finish is exactly the file that may hold the
/// secret; it must never render as clean.
/// Test: this test.
#[test]
fn scan_reports_an_unparseable_plist() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n<key>A</key>\n",
    );

    let findings = scan_launch_agents(home.path()).expect("scan");

    assert!(findings[0].unreadable.is_some());
    assert_value_never_echoed(&format!("{:?}", findings[0]));
}

/// Why: a file the scan cannot open at all is the same hazard as one it cannot
/// parse — it may hold the credential, and the one answer it must never get is
/// "clean". The scan reports it as unreadable with the I/O reason, and it is NOT
/// a binary plist, so the row treats it as unknown rather than as a failure with
/// a `plutil` remedy that would not help.
/// Test: this test.
#[test]
fn scan_reports_an_unreadable_plist() {
    let home = home_with_agents();
    // A directory under the plist's name: `std::fs::read` fails deterministically
    // on every platform, with no permission games.
    std::fs::create_dir(
        home.path()
            .join("Library/LaunchAgents/com.trusty.mpm.plist"),
    )
    .expect("mkdir");

    let findings = scan_launch_agents(home.path()).expect("scan");
    let why = findings[0].unreadable.clone().expect("unreadable");

    assert!(why.contains("could not read it"), "{why}");
    assert!(!findings[0].binary_plist, "not a binary plist: {why}");
    assert_eq!(
        check_launchd_plist_secrets(home.path()).status,
        CheckStatus::Unknown
    );
}

/// Why: a plist tm did not generate belongs to the operator.
/// Test: this test.
#[test]
fn scan_ignores_foreign_plists() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.example.other.plist",
        &plist_with_credential(),
    );

    assert!(scan_launch_agents(home.path()).expect("scan").is_empty());
}

/// Why: a host with no LaunchAgents has no exposure, and that is not an error.
/// Test: this test.
#[test]
fn scan_is_empty_without_a_launch_agents_dir() {
    let home = tempfile::tempdir().expect("tempdir");
    assert!(scan_launch_agents(home.path()).expect("scan").is_empty());
}

/// Why: a directory that cannot be listed means the scan did not run, which
/// the caller must hear as UNKNOWN rather than as a clean host.
/// Test: this test.
#[test]
fn scan_errors_when_the_directory_cannot_be_listed() {
    let home = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(home.path().join("Library")).expect("mkdir");
    std::fs::write(home.path().join("Library/LaunchAgents"), b"not a dir").expect("write");

    assert!(scan_launch_agents(home.path()).is_err());
}

/// Why: the row is the operator-visible half of the whole ticket.
/// Test: this test.
#[test]
fn row_fails_and_names_the_key_not_the_value() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );

    let row = check_launchd_plist_secrets(home.path());

    assert_eq!(row.status, CheckStatus::Fail);
    assert!(
        row.message.contains("OPENROUTER_API_KEY"),
        "{}",
        row.message
    );
    assert!(row.message.contains("ROTATE"), "{}", row.message);
    // #8563: point at the scoped repair, not the machine-wide `--fix` sweep.
    assert!(
        row.message
            .contains("Run `tm doctor --fix-launchd-secrets --yes`"),
        "{}",
        row.message
    );
    assert_value_never_echoed(&row.message);
}

/// Why (#8236 item 3): the row reports each plist's MODE, and flags anything
/// wider than `0600` — the #8236 host's plist was `0644`.
/// Test: this test.
#[cfg(unix)]
#[test]
fn row_flags_a_world_readable_plist() {
    use std::os::unix::fs::PermissionsExt;
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).expect("chmod");

    let row = check_launchd_plist_secrets(home.path());

    assert!(row.message.contains("0644"), "{}", row.message);
}

/// Why (#8236 item 2): the row has to SAY that an unmapped key will not be
/// stripped, or an operator reads a partial fix as a complete one.
/// Test: this test.
#[test]
fn row_says_an_unmapped_key_is_not_stripped() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n\
         <key>AWS_SECRET_ACCESS_KEY</key>\n<string>fake</string>\n</dict>\n</dict>\n</plist>\n",
    );

    let row = check_launchd_plist_secrets(home.path());

    assert_eq!(row.status, CheckStatus::Fail);
    assert!(row.message.contains("will NOT remove"), "{}", row.message);
}

/// Why: a clean host must report clean, or the row is noise.
/// Test: this test.
#[test]
fn row_is_ok_when_clean() {
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n\
         <key>PATH</key>\n<string>/usr/bin</string>\n</dict>\n</dict>\n</plist>\n",
    );
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).expect("chmod");
    }
    let _ = &path;

    assert_eq!(
        check_launchd_plist_secrets(home.path()).status,
        CheckStatus::Ok
    );
}

/// Why: "could not tell" must never render as healthy.
/// Test: this test.
#[test]
fn row_is_unknown_when_a_plist_cannot_be_parsed() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n<key>A</key>\n",
    );

    assert_eq!(
        check_launchd_plist_secrets(home.path()).status,
        CheckStatus::Unknown
    );
}

/// Why (#8236 item 4, owner ruling 2026-09-21): a binary plist is the one file
/// this round can neither judge nor repair. The row must FAIL — never pass,
/// never merely warn — and must name the one command that makes the file
/// readable, or the operator has a red row with no way out of it. A downgrade
/// of this arm to `Unknown`, `Warn` or `Ok`, or a message that drops the
/// remedy, fails here.
/// Test: this test.
#[test]
fn row_fails_on_a_binary_plist() {
    let home = home_with_agents();
    let path = home
        .path()
        .join("Library/LaunchAgents/com.trusty.mpm.plist");
    let mut bytes = b"bplist00".to_vec();
    bytes.extend_from_slice(&[0xd1, 0x01, 0x02]);
    std::fs::write(&path, bytes).expect("write");

    let row = check_launchd_plist_secrets(home.path());

    assert_eq!(row.status, CheckStatus::Fail, "{row:?}");
    assert!(row.message.contains("BINARY"), "{}", row.message);
    assert!(
        row.message.contains("plutil -convert xml1"),
        "the row must name the remedy: {}",
        row.message
    );
}

/// Why: same, for the directory-level failure.
/// Test: this test.
#[test]
fn row_is_unknown_when_the_directory_cannot_be_listed() {
    let home = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(home.path().join("Library")).expect("mkdir");
    std::fs::write(home.path().join("Library/LaunchAgents"), b"not a dir").expect("write");

    assert_eq!(
        check_launchd_plist_secrets(home.path()).status,
        CheckStatus::Unknown
    );
}

/// Why: ranking Fail above Unknown must not DROP the unjudged file.
/// Test: this test.
#[test]
fn row_fail_still_names_the_plists_it_could_not_judge() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    install(
        home.path(),
        "com.trusty.zebra.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n<key>A</key>\n",
    );

    let row = check_launchd_plist_secrets(home.path());

    assert_eq!(row.status, CheckStatus::Fail);
    assert!(
        row.message.contains("com.trusty.zebra.plist"),
        "{}",
        row.message
    );
}

/// Why: a dry run must plan and write nothing.
/// Test: this test.
#[test]
fn repair_plans_without_writing() {
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    let before = std::fs::read_to_string(&path).expect("read");

    let steps = repair_with_store(
        home.path(),
        RepairMode::DryRun,
        Arc::new(MemoryKeyStore::new()),
    );

    assert_eq!(steps.len(), 1);
    assert_eq!(steps[0].status, StepStatus::Planned);
    assert_eq!(std::fs::read_to_string(&path).expect("read"), before);
}

/// Why (#8236 items 1 and 2): the repair migrates the value into the store,
/// confirms it by read-back, and only then removes it — atomically.
/// Test: this test.
#[test]
fn repair_migrates_then_removes() {
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    let store = Arc::new(MemoryKeyStore::new());

    let steps = repair_with_store(home.path(), RepairMode::Apply, store.clone());

    assert_eq!(steps[0].status, StepStatus::Applied { backup: None });
    assert_eq!(store.get("openrouter").as_deref(), Some(FAKE_API_KEY));
    let after = std::fs::read_to_string(&path).expect("read");
    assert!(!after.contains("OPENROUTER_API_KEY"), "{after}");
    assert!(after.contains("RUST_LOG"), "{after}");
    assert_value_never_echoed(&after);
    assert_value_never_echoed(&format!("{:?}", steps[0]));
}

/// Why (#8236 item 2): an import that cannot be confirmed must leave the plist
/// byte-identical. `WriteOnlyStore` accepts the write and serves nothing back.
/// Test: this test.
#[test]
fn repair_leaves_the_plist_untouched_when_the_import_fails() {
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    let before = std::fs::read_to_string(&path).expect("read");

    let steps = repair_with_store(home.path(), RepairMode::Apply, Arc::new(WriteOnlyStore));

    assert!(
        matches!(steps[0].status, StepStatus::Failed(_)),
        "{:?}",
        steps[0].status
    );
    assert_eq!(std::fs::read_to_string(&path).expect("read"), before);
    assert_value_never_echoed(&format!("{:?}", steps[0]));
}

/// Why (#8236 item 2): stripping a key with no store entry breaks the feature
/// it configures, so the repair refuses and says why.
/// Test: this test.
#[test]
fn repair_keeps_an_unmapped_key_and_says_so() {
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n\
         <key>AWS_SECRET_ACCESS_KEY</key>\n<string>fake</string>\n</dict>\n</dict>\n</plist>\n",
    );
    let before = std::fs::read_to_string(&path).expect("read");

    let steps = repair_with_store(
        home.path(),
        RepairMode::Apply,
        Arc::new(MemoryKeyStore::new()),
    );

    assert!(
        matches!(steps[0].status, StepStatus::Refused(_)),
        "{:?}",
        steps[0].status
    );
    assert_eq!(std::fs::read_to_string(&path).expect("read"), before);
}

/// Why (#8236 item 4): `--fix` must refuse a binary plist rather than rewrite
/// it as text, which would destroy the unit.
/// Test: this test.
#[test]
fn repair_refuses_a_binary_plist() {
    let home = home_with_agents();
    let path = home
        .path()
        .join("Library/LaunchAgents/com.trusty.mpm.plist");
    let mut bytes = b"bplist00".to_vec();
    bytes.extend_from_slice(&[0xd1, 0x01]);
    std::fs::write(&path, &bytes).expect("write");

    let steps = repair_with_store(
        home.path(),
        RepairMode::Apply,
        Arc::new(MemoryKeyStore::new()),
    );

    let StepStatus::Failed(why) = &steps[0].status else {
        panic!(
            "a binary plist must be refused loudly: {:?}",
            steps[0].status
        );
    };
    // Owner ruling 2026-09-21: a refusal is acceptable this round only if it
    // names the way out. A refusal that just said "cannot" would leave the
    // operator with a red row and no next step.
    assert!(why.contains("BINARY"), "{why}");
    assert!(why.contains("plutil -convert xml1"), "{why}");
    assert!(why.contains(&path.display().to_string()), "{why}");
    assert!(why.contains("re-run `tm doctor`"), "{why}");
    assert_eq!(std::fs::read(&path).expect("read"), bytes);
}

/// Why: an unparseable plist is a failure, never a silent pass.
/// Test: this test.
#[test]
fn repair_fails_loudly_on_an_unparseable_plist() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n<key>A</key>\n",
    );

    let steps = repair_with_store(
        home.path(),
        RepairMode::Apply,
        Arc::new(MemoryKeyStore::new()),
    );

    assert!(matches!(steps[0].status, StepStatus::Failed(_)));
}

/// Why (#8236 item 1): a write that cannot land must leave the original intact
/// and report Failed — not a partial file.
/// Test: this test.
#[cfg(unix)]
#[test]
fn repair_fails_loudly_when_the_plist_is_unwritable() {
    use std::os::unix::fs::PermissionsExt;
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    let before = std::fs::read_to_string(&path).expect("read");
    let dir = home.path().join("Library/LaunchAgents");
    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o500)).expect("chmod");

    let steps = repair_with_store(
        home.path(),
        RepairMode::Apply,
        Arc::new(MemoryKeyStore::new()),
    );

    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).expect("chmod back");
    assert!(
        matches!(steps[0].status, StepStatus::Failed(_)),
        "{:?}",
        steps[0].status
    );
    assert_eq!(std::fs::read_to_string(&path).expect("read"), before);
}

/// Why: a directory that cannot be listed is a failure the operator must see.
/// Test: this test.
#[test]
fn repair_fails_loudly_when_the_directory_cannot_be_listed() {
    let home = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir_all(home.path().join("Library")).expect("mkdir");
    std::fs::write(home.path().join("Library/LaunchAgents"), b"not a dir").expect("write");

    let steps = repair_with_store(
        home.path(),
        RepairMode::Apply,
        Arc::new(MemoryKeyStore::new()),
    );

    assert_eq!(steps.len(), 1);
    assert!(matches!(steps[0].status, StepStatus::Failed(_)));
}

/// Why: a clean host must produce no steps, so `--fix` prints nothing for it.
/// Test: this test.
#[test]
fn repair_produces_no_steps_for_a_clean_host() {
    let home = home_with_agents();
    install(
        home.path(),
        "com.trusty.mpm.plist",
        "<plist>\n<dict>\n<key>EnvironmentVariables</key>\n<dict>\n\
         <key>PATH</key>\n<string>/usr/bin</string>\n</dict>\n</dict>\n</plist>\n",
    );

    assert!(
        repair_with_store(
            home.path(),
            RepairMode::Apply,
            Arc::new(MemoryKeyStore::new())
        )
        .is_empty()
    );
}

/// Why (#8236 item 2): running `--fix` twice must be a no-op the second time,
/// not a second rewrite or a failure.
/// Test: this test.
#[test]
fn repair_is_idempotent() {
    let home = home_with_agents();
    let path = install(
        home.path(),
        "com.trusty.mpm.plist",
        &plist_with_credential(),
    );
    let store = Arc::new(MemoryKeyStore::new());

    let first = repair_with_store(home.path(), RepairMode::Apply, store.clone());
    let after_first = std::fs::read_to_string(&path).expect("read");
    let second = repair_with_store(home.path(), RepairMode::Apply, store);

    assert_eq!(first[0].status, StepStatus::Applied { backup: None });
    assert!(second.is_empty(), "{second:?}");
    assert_eq!(std::fs::read_to_string(&path).expect("read"), after_first);
}

/// Why (#8236): `read` and `metadata` follow a symlink, so a linked plist would
/// be judged — and rewritten — through its target while the report named the
/// link. The scan has to see the link itself and refuse it.
/// Test: this test.
#[cfg(unix)]
#[test]
fn scan_reports_a_symlinked_plist_as_unreadable() {
    let home = home_with_agents();
    let outside = home.path().join("dotfiles-com.trusty.mpm.plist");
    std::fs::write(&outside, plist_with_credential()).expect("write target");
    let link = home
        .path()
        .join("Library/LaunchAgents/com.trusty.mpm.plist");
    std::os::unix::fs::symlink(&outside, &link).expect("symlink");

    let findings = scan_launch_agents(home.path()).expect("scan");
    let why = findings[0].unreadable.clone().expect("unreadable");

    assert!(why.contains("SYMLINK"), "{why}");
    assert!(why.contains(&outside.display().to_string()), "{why}");
    assert!(
        findings[0].migratable.is_empty() && findings[0].unmapped.is_empty(),
        "the scan judged the link's target: {:?}",
        findings[0]
    );
    assert!(!findings[0].binary_plist, "a link is not a binary plist");
    assert_value_never_echoed(&why);
}

/// Why (#8236): the row must not go green on a plist it could not judge, and a
/// symlink is exactly that case.
/// Test: this test.
#[cfg(unix)]
#[test]
fn row_is_unknown_for_a_symlinked_plist() {
    let home = home_with_agents();
    let outside = home.path().join("elsewhere.plist");
    std::fs::write(&outside, plist_with_credential()).expect("write target");
    std::os::unix::fs::symlink(
        &outside,
        home.path()
            .join("Library/LaunchAgents/com.trusty.mpm.plist"),
    )
    .expect("symlink");

    let check = check_launchd_plist_secrets(home.path());

    assert_eq!(check.status, CheckStatus::Unknown, "{check:?}");
    assert!(check.message.contains("SYMLINK"), "{}", check.message);
    assert_value_never_echoed(&check.message);
}

/// Why (#8236): the repair publishes with `rename(2)`, which replaces the LINK
/// with a plain file and severs it silently — the operator's real plist would
/// go stale while `--fix` reported success. It has to refuse, loudly, and leave
/// both the link and its target exactly as they were.
/// Test: this test.
#[cfg(unix)]
#[test]
fn repair_refuses_a_symlinked_plist() {
    let home = home_with_agents();
    let outside = home.path().join("dotfiles.plist");
    let body = plist_with_credential();
    std::fs::write(&outside, &body).expect("write target");
    let link = home
        .path()
        .join("Library/LaunchAgents/com.trusty.mpm.plist");
    std::os::unix::fs::symlink(&outside, &link).expect("symlink");

    let steps = repair_with_store(
        home.path(),
        RepairMode::Apply,
        Arc::new(MemoryKeyStore::new()),
    );

    let StepStatus::Failed(why) = &steps[0].status else {
        panic!(
            "a symlinked plist must be refused loudly: {:?}",
            steps[0].status
        );
    };
    assert!(why.contains("SYMLINK"), "{why}");
    assert!(
        std::fs::symlink_metadata(&link)
            .expect("stat")
            .file_type()
            .is_symlink(),
        "the repair replaced the link with a plain file"
    );
    assert_eq!(std::fs::read_to_string(&outside).expect("read"), body);
    assert_value_never_echoed(why);
}