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
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
//! Behaviour tests for the `tm reinstall` asset engine (see `reinstall.rs`).
//!
//! Why: the whole point of the command is that it reaches EVERY destination and
//! says what it did at each. Both halves need pinning — a target list that
//! silently drops the standalone tier, or a report that shows zeros where a
//! deploy was declined, is the failure the command exists to end.
//! What: target enumeration, the hop-1 refresh, the ownership matrix
//! (preserved without `--force`, replaced with it, corruption repaired either
//! way), a missing destination, a failed destination, and the ledger-lock
//! serialisation that keeps a concurrent daemon deploy from racing it.
//! Test: this file IS the test module.

use super::*;
use crate::core::content_source::test_support::rc;
use tempfile::TempDir;

/// A minimal source agent, and a base it extends.
const BASE_AGENT: &str = "---\nname: base-agent\nrole: base\n---\n\n# Base\n\nBase content.\n";
const ENGINEER: &str = "---\nname: engineer\nrole: engineer\nextends: base-agent\n---\n\n# Engineer\n\nEngineer content.\n";
/// A minimal source skill.
const DEMO_SKILL: &str = "---\nname: demo-skill\n---\n\n# Demo\n\nBundled skill text.\n";

/// A framework layout under `base` holding two agents and one skill, with both
/// bundle stamps pinned as already-current.
///
/// Why: pinning the stamps is what stops [`reinstall_assets`]'s hop-1 self-heal
/// materializing the REAL compiled-in bundle over this fixture — the same trick
/// #4873 used for its skill fixture. Without it every ownership assertion below
/// would be made against ~110 real assets instead of three known ones.
/// Test: used by every `reinstall_*` test except
/// `reinstall_refreshes_the_source_first`, which deliberately leaves the stamps
/// absent.
fn seeded(base: &std::path::Path) -> FrameworkPaths {
    let paths = FrameworkPaths::under(base);
    std::fs::create_dir_all(&paths.agents).unwrap();
    std::fs::write(paths.agents.join("base-agent.md"), BASE_AGENT).unwrap();
    std::fs::write(paths.agents.join("engineer.md"), ENGINEER).unwrap();
    std::fs::write(
        paths
            .agents
            .join(crate::core::agent_source::STAMP_FILE_NAME),
        crate::core::agent_source::agent_bundle_stamp(
            &crate::core::content_source::test_support::repo_roster(),
        ),
    )
    .unwrap();

    std::fs::create_dir_all(&paths.skills).unwrap();
    std::fs::write(paths.skills.join("demo-skill.md"), DEMO_SKILL).unwrap();
    std::fs::write(
        paths
            .skills
            .join(crate::core::skill_source::STAMP_FILE_NAME),
        crate::core::skill_source::skill_bundle_stamp(rc()),
    )
    .unwrap();
    paths
}

/// The standalone driver's config dir, under the same hermetic base.
fn standalone_dir(base: &std::path::Path) -> std::path::PathBuf {
    base.join(".trusty-mpm").join("claude-config")
}

/// A minimal USER-custom skill, in the operator's own `<root>/skills` tier.
///
/// Why (#7783): the bundled roster now reaches the managed config tier alone,
/// so a test that needs a skill written at one of the OTHER destinations — to
/// prove the destination is provisioned, served, or locked — has to use the
/// tier that still deploys everywhere. The operator's own opt-in is that tier.
/// Test: used by `reinstall_creates_a_missing_destination`,
/// `reinstall_reports_a_failed_destination_and_serves_the_others`,
/// `reinstall_serialises_against_a_held_skill_ledger_lock`,
/// `reinstall_does_not_fail_the_command_for_an_optional_destination`.
fn seed_user_skill(paths: &FrameworkPaths) {
    let dir = paths.user_skill_source_dir();
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("my-skill.md"),
        "---\nname: my-skill\n---\n\n# Mine\n\nUser-custom skill text.\n",
    )
    .unwrap();
}

/// Find one tier report by label.
fn tier<'a>(report: &'a ReinstallReport, label: &str) -> &'a TierReport {
    report
        .tiers
        .iter()
        .find(|t| t.label == label)
        .unwrap_or_else(|| panic!("no `{label}` tier in {:?}", report.tiers))
}

#[test]
fn targets_cover_the_standalone_tier() {
    // #4849: `tm run`/`load`/`login` deploy into `~/.trusty-mpm/claude-config`,
    // which `skill_deploy_tiers` — and therefore every command built on it —
    // structurally cannot reach. It is the reason this target list exists.
    let base = TempDir::new().unwrap();
    let paths = FrameworkPaths::under(base.path());
    let sa = standalone_dir(base.path());

    let targets = reinstall_targets(&paths, &sa, None);

    let standalone = targets
        .iter()
        .find(|t| t.label == "standalone")
        .expect("the standalone tier must be covered");
    assert_eq!(standalone.skills_dir, sa.join("skills"));
    assert_eq!(standalone.agents_dir, Some(sa.join("agents")));
}

#[test]
fn targets_attach_agents_to_two_destinations_only() {
    // #4409 pins framework-owned agents to the tm-managed config dir. The only
    // other place they legitimately land is the standalone driver's own config
    // dir; the operator's `~/.claude/agents` and any project must stay clear.
    let base = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = FrameworkPaths::under(base.path());

    let targets = reinstall_targets(&paths, &standalone_dir(base.path()), Some(project.path()));

    let with_agents: Vec<&str> = targets
        .iter()
        .filter(|t| t.agents_dir.is_some())
        .map(|t| t.label.as_str())
        .collect();
    assert_eq!(with_agents, vec!["managed config", "standalone"]);
    assert_eq!(
        tier_dir(&targets, "managed config"),
        Some(paths.agent_deploy_dir())
    );
}

/// The agents directory of a labelled target, for a one-line assertion.
fn tier_dir(targets: &[ReinstallTarget], label: &str) -> Option<std::path::PathBuf> {
    targets
        .iter()
        .find(|t| t.label == label)
        .and_then(|t| t.agents_dir.clone())
}

#[test]
fn targets_deduplicate() {
    // A machine whose standalone root IS the managed config dir must be served
    // once, not twice — a second pass would deploy over its own output and
    // double every count.
    let base = TempDir::new().unwrap();
    let paths = FrameworkPaths::under(base.path());
    let managed_config = paths.agent_deploy_dir().parent().unwrap().to_path_buf();

    let targets = reinstall_targets(&paths, &managed_config, None);

    assert!(
        !targets.iter().any(|t| t.label == "standalone"),
        "the standalone tier duplicates the managed one here: {targets:?}"
    );
}

#[test]
fn reinstall_reports_every_target() {
    // The command's contract: one report per destination, each naming what it
    // actually did there. A tier reporting all zeros because it was never
    // visited is exactly the silent no-op this replaces.
    let base = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let backups = base.path().join("backups");
    // The project tier is only served when it already exists — see
    // `targets_omit_the_project_tier_until_it_exists`.
    std::fs::create_dir_all(project.path().join(".claude").join("skills")).unwrap();

    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        Some(project.path()),
        false,
        &backups,
    );

    assert!(!report.has_failures(), "{report:?}");
    assert_eq!(report.tiers.len(), 4, "{:?}", report.tiers);
    // #7783: the bundled skill is reported and written at the managed tier
    // only; the other three are visited and report an honest zero.
    let managed = tier(&report, "managed config");
    assert_eq!(managed.skills.deployed, 1, "{managed:?}");
    assert!(
        managed
            .skills_dir
            .join("demo-skill")
            .join("SKILL.md")
            .is_file()
    );
    for label in ["operator home", "project", "standalone"] {
        let t = tier(&report, label);
        assert_eq!(t.skills.deployed, 0, "{label}: {t:?}");
    }
    for label in ["managed config", "standalone"] {
        let t = tier(&report, label);
        assert_eq!(t.agents.deployed, 2, "{label}: {t:?}");
        let dir = t.agents_dir.as_ref().unwrap();
        assert!(dir.join("engineer.md").is_file());
    }
    // #4409: agents never land in the operator home or the project.
    assert!(!paths.claude_agents_dir().join("engineer.md").exists());
    assert!(
        !project
            .path()
            .join(".claude")
            .join("agents")
            .join("engineer.md")
            .exists()
    );
}

#[test]
fn reinstall_deploys_the_bundled_roster_to_the_managed_tier_only() {
    // #7783: `deploy_skills_into` passed `|_| true` at every destination, so a
    // reinstall wrote the whole bundled roster into the operator's
    // `~/.claude/skills`, the project tier, and the standalone config dir —
    // the exact duplication the 2026-09-01 ruling (#6586) ended for `tm
    // install` and for session launch. The user-custom tier is the control:
    // it must still reach all four.
    let base = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = seeded(base.path());
    seed_user_skill(&paths);
    std::fs::create_dir_all(project.path().join(".claude").join("skills")).unwrap();

    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        Some(project.path()),
        false,
        &base.path().join("backups"),
    );

    assert!(!report.has_failures(), "{report:?}");
    assert_eq!(report.tiers.len(), 4, "{:?}", report.tiers);
    assert!(
        paths
            .skill_deploy_dir()
            .join("demo-skill")
            .join("SKILL.md")
            .is_file(),
        "the managed tier must still receive the bundled roster"
    );
    for label in ["operator home", "project", "standalone"] {
        let t = tier(&report, label);
        assert!(
            !t.skills_dir.join("demo-skill").exists(),
            "{label} must receive no bundled skill: {t:?}"
        );
        assert!(
            t.skills_dir.join("my-skill").join("SKILL.md").is_file(),
            "{label} must still receive the user-custom tier: {t:?}"
        );
    }
}

#[test]
fn reinstall_creates_a_missing_destination() {
    // A machine that has never run the standalone driver has no
    // `claude-config/` at all. Hop 2 must provision it rather than skip it.
    // #7783: the skill it is provisioned with is the user-custom one — the
    // bundled roster stops at the managed tier.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    seed_user_skill(&paths);
    let sa = standalone_dir(base.path());
    assert!(!sa.exists());

    let report = reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));

    assert!(!report.has_failures(), "{report:?}");
    assert!(sa.join("agents").join("engineer.md").is_file());
    assert!(
        sa.join("skills")
            .join("my-skill")
            .join("SKILL.md")
            .is_file()
    );
}

#[test]
fn reinstall_refreshes_the_source_first() {
    // Hop 1 is the half that makes a compiled-in asset change reach disk at all
    // (#4840/#1917). Without the pinned stamps the source is stale by
    // definition, so a run against a bare base must report a refresh — and the
    // real bundled roster must then be what lands.
    let base = TempDir::new().unwrap();
    let paths = FrameworkPaths::under(base.path());

    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        None,
        false,
        &base.path().join("backups"),
    );

    assert!(report.agent_source_refreshed, "{report:?}");
    assert!(report.skill_source_refreshed, "{report:?}");
    assert!(paths.agents.join("engineer.md").is_file());
    assert!(paths.skills.join("tm-doctor.md").is_file());
    assert!(tier(&report, "managed config").agents.deployed > 0);
}

#[test]
fn reinstall_preserves_a_customized_agent_without_force() {
    // Ownership: an agent file the manifest does not track and that differs
    // from the fresh composition may be the operator's, so the deployer
    // conservatively preserves it. It survives a reinstall byte-for-byte, and
    // the report says so rather than counting it as deployed.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let dest = paths.agent_deploy_dir();
    let custom = "---\nname: engineer\n---\n\nMINE — KEEP ME\n";
    seed_untracked_agent(&dest, custom);

    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        None,
        false,
        &base.path().join("backups"),
    );

    let t = tier(&report, "managed config");
    assert_eq!(t.agents.preserved, 1, "{t:?}");
    assert_eq!(
        std::fs::read_to_string(dest.join("engineer.md")).unwrap(),
        custom
    );
    assert!(
        t.notes.iter().any(|n| n.contains("tm reinstall --force")),
        "the preserved note must name the escape hatch: {:?}",
        t.notes
    );
}

#[test]
fn reinstall_replaces_a_customized_agent_with_force() {
    // `--force` is the explicit clobber. The bundled composition wins, and the
    // operator's copy is backed up in place rather than lost.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let dest = paths.agent_deploy_dir();
    seed_untracked_agent(&dest, "---\nname: engineer\n---\n\nMINE\n");

    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        None,
        true,
        &base.path().join("backups"),
    );

    let t = tier(&report, "managed config");
    assert_eq!(t.agents.preserved, 0, "{t:?}");
    let deployed = std::fs::read_to_string(dest.join("engineer.md")).unwrap();
    assert!(deployed.contains("Engineer content."), "{deployed}");
    let backups: Vec<_> = std::fs::read_dir(&dest)
        .unwrap()
        .flatten()
        .filter(|e| e.file_name().to_string_lossy().contains(".bak-"))
        .collect();
    assert_eq!(backups.len(), 1, "the overwrite must be backed up");
}

#[test]
fn reinstall_repairs_a_corrupt_agent_without_force() {
    // #4408's carve-out, which must not regress: a FRAMEWORK-owned file whose
    // frontmatter has been mangled is corruption, not customization. It is
    // repaired with no `--force`, and reported as repaired rather than as an
    // ordinary refresh.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let sa = standalone_dir(base.path());
    let dest = paths.agent_deploy_dir();

    // First run establishes framework ownership in the manifest.
    reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));
    // The literal #4408 stub: `name:`-only frontmatter, no `description:`.
    std::fs::write(dest.join("engineer.md"), "---\nname: engineer\n---\n\nv1\n").unwrap();

    let report = reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));

    let t = tier(&report, "managed config");
    assert_eq!(t.agents.repaired, 1, "{t:?}");
    assert_eq!(t.agents.preserved, 0, "{t:?}");
    assert!(
        std::fs::read_to_string(dest.join("engineer.md"))
            .unwrap()
            .contains("Engineer content.")
    );
}

/// Write `content` as `engineer.md` at `dest` with NO manifest entry for it.
///
/// Why: this is the customized-agent state production actually reaches. The
/// deployer's other preserve branch keys on `Origin::User`, and NO production
/// path writes that origin — every deploy records `Origin::Bundled`
/// (`agents::deployer::deploy_agents_locked`), and no shipped artifact uses the
/// `SeedOnce` tier the `User` origin belongs to (`install.rs`, #3381). A test
/// hand-seeding `Origin::User` would prove preservation through a branch that
/// cannot occur, which is coverage in appearance only; that branch is already
/// pinned at the unit level by `deploy_preserves_modified_user_owned_entry` in
/// `trusty-agents-common`. UNTRACKED-and-differing is the reachable state: an
/// agent file the operator hand-placed or edited before per-file manifest
/// tracking existed, which the deployer conservatively skips and flags in
/// `untracked_modified`.
/// What: creates `dest`, writes `engineer.md`, and writes no manifest at all.
/// Test: used by the two agent-ownership tests around it.
fn seed_untracked_agent(dest: &std::path::Path, content: &str) {
    std::fs::create_dir_all(dest).unwrap();
    std::fs::write(dest.join("engineer.md"), content).unwrap();
}

#[test]
fn reinstall_preserves_a_customized_skill_without_force() {
    // The skill half of the ownership rule. A hand-edited deployed skill is
    // frozen by the deployer on purpose; the reinstall must respect that and
    // say it did.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let sa = standalone_dir(base.path());
    let dest = paths.agent_deploy_dir().parent().unwrap().join("skills");

    reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));
    let deployed = dest.join("demo-skill").join("SKILL.md");
    std::fs::write(&deployed, "MY OWN TEXT\n").unwrap();

    let report = reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));

    let t = tier(&report, "managed config");
    assert_eq!(t.skills.preserved, 1, "{t:?}");
    assert_eq!(std::fs::read_to_string(&deployed).unwrap(), "MY OWN TEXT\n");
}

#[test]
fn reinstall_replaces_a_customized_skill_with_force() {
    // `--force` re-stamps the frozen skill and lets the very next deploy write
    // the bundled text over it — with the original copied under `backup_root`
    // first, which is this module's non-negotiable condition for clobbering.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let sa = standalone_dir(base.path());
    let backups = base.path().join("backups");
    let dest = paths.agent_deploy_dir().parent().unwrap().join("skills");

    reinstall_assets(&paths, &sa, None, false, &backups);
    let deployed = dest.join("demo-skill").join("SKILL.md");
    std::fs::write(&deployed, "MY OWN TEXT\n").unwrap();

    let report = reinstall_assets(&paths, &sa, None, true, &backups);

    let t = tier(&report, "managed config");
    assert_eq!(t.skills.preserved, 0, "{t:?}");
    assert!(
        std::fs::read_to_string(&deployed)
            .unwrap()
            .contains("Bundled skill text.")
    );
    assert!(
        backups.join("moved-paths.log").is_file(),
        "the clobber must leave a backup ledger under {}",
        backups.display()
    );
}

#[test]
fn force_leaves_an_operator_skill_alone() {
    // The roster is the only admission test. A skill whose name matches nothing
    // bundled is the operator's, and `--force` is not licence to touch it.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let sa = standalone_dir(base.path());
    let dest = paths.agent_deploy_dir().parent().unwrap().join("skills");
    let mine = dest.join("my-own-skill");
    std::fs::create_dir_all(&mine).unwrap();
    std::fs::write(mine.join("SKILL.md"), "OPERATOR CONTENT\n").unwrap();

    reinstall_assets(&paths, &sa, None, true, &base.path().join("backups"));

    assert_eq!(
        std::fs::read_to_string(mine.join("SKILL.md")).unwrap(),
        "OPERATOR CONTENT\n"
    );
}

#[test]
fn reinstall_reports_a_failed_destination_and_serves_the_others() {
    // A destination that cannot be written must not abandon the rest of the
    // run — abandoning two tiers because the third is read-only is the silent
    // partial deploy this command exists to end.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    seed_user_skill(&paths);
    let sa = standalone_dir(base.path());
    // A regular FILE where the managed skills directory belongs: every write
    // into it fails, on every platform, without depending on permission bits.
    let managed_skills = paths.agent_deploy_dir().parent().unwrap().join("skills");
    std::fs::create_dir_all(managed_skills.parent().unwrap()).unwrap();
    std::fs::write(&managed_skills, "not a directory").unwrap();

    let report = reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));

    assert!(report.has_failures(), "{report:?}");
    // #7783: the standalone tier serves the user-custom tier, not the bundled
    // roster — that is what "the others are still served" means there now.
    assert_eq!(tier(&report, "standalone").skills.deployed, 1);
    assert!(
        sa.join("skills")
            .join("my-skill")
            .join("SKILL.md")
            .is_file()
    );
}

#[test]
fn reinstall_serialises_against_a_held_skill_ledger_lock() {
    // The concurrency answer (#4881): `tm reinstall` can plausibly run while
    // the daemon deploys for a session spawn. It takes no lock of its own — it
    // routes every write through the deployers, which hold the target
    // directory's exclusive ledger lock — so a reinstall must BLOCK on a lock
    // another writer holds rather than racing its manifest.
    use std::sync::mpsc;
    use trusty_agents_common::agents::manifest::ManifestError;

    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    // #7783: the standalone tier receives the user-custom tier only, so the
    // file whose appearance marks "the deploy ran" is that tier's.
    seed_user_skill(&paths);
    let sa = standalone_dir(base.path());
    let dest = sa.join("skills");
    std::fs::create_dir_all(&dest).unwrap();

    let (tx, rx) = mpsc::channel();
    let paths_moved = paths.clone();
    let sa_moved = sa.clone();
    let backups = base.path().join("backups");
    let marker = dest.join("my-skill").join("SKILL.md");

    // The handle leaves the critical section rather than being joined inside
    // it: the reinstall cannot finish until we release.
    let handle = trusty_agents_common::skills::manifest::with_skill_manifest_lock::<
        _,
        ManifestError,
        _,
    >(&dest, || {
        let handle = std::thread::spawn(move || {
            tx.send(reinstall_assets(
                &paths_moved,
                &sa_moved,
                None,
                false,
                &backups,
            ))
            .ok();
        });
        assert!(
            rx.recv_timeout(std::time::Duration::from_secs(2)).is_err(),
            "the reinstall finished while another writer held the skill ledger lock"
        );
        assert!(
            !marker.exists(),
            "the reinstall wrote a skill file while the ledger lock was held"
        );
        Ok(handle)
    })
    .unwrap();

    handle.join().unwrap();
    let report = rx
        .recv_timeout(std::time::Duration::from_secs(30))
        .expect("the reinstall must complete once the lock is released");
    assert!(marker.is_file(), "{report:?}");
}

#[test]
fn preserved_note_is_empty_when_nothing_was_preserved() {
    assert_eq!(preserved_note("agent", &[], ""), None);
}

#[test]
fn preserved_note_names_the_force_flag() {
    // The note has to point at the flag on the command the operator just ran,
    // not at `tm install --reset-agents`, which is a different command.
    let note = preserved_note("skill", &["a.md".to_string()], "a.md").unwrap();
    assert!(note.contains("1 skill file(s)"), "{note}");
    assert!(note.contains("tm reinstall --force"), "{note}");
}

// ── #4605: the outcome that appears in none of the deploy counts ────────────

#[test]
fn reinstall_surfaces_a_shadowed_bundled_skill() {
    // The silent skip this command exists to end, in its exact form: a bundled
    // skill the destination does not track is classified project-custom by the
    // tier planner and dropped before the deployer runs, so it is neither
    // deployed, preserved, unchanged, nor failed. Reporting only those four
    // prints zeros for it.
    let base = TempDir::new().unwrap();
    let paths = seeded(base.path());
    let sa = standalone_dir(base.path());
    let dest = paths.agent_deploy_dir().parent().unwrap().join("skills");
    // Untracked, bundled-named, already on disk — no manifest anywhere.
    let stray = dest.join("demo-skill");
    std::fs::create_dir_all(&stray).unwrap();
    std::fs::write(stray.join("SKILL.md"), "LOST TRACKING\n").unwrap();

    let report = reinstall_assets(&paths, &sa, None, false, &base.path().join("backups"));

    let t = tier(&report, "managed config");
    assert_eq!(t.skills.deployed, 0, "{t:?}");
    assert_eq!(t.skills.preserved, 0, "{t:?}");
    assert_eq!(t.skills.unchanged, 0, "{t:?}");
    assert_eq!(
        t.skills.shadowed, 1,
        "a skill in none of the other counts must be counted as shadowed: {t:?}"
    );
    assert!(
        t.notes.iter().any(|n| n.contains("demo-skill")),
        "the report must NAME it, not just count it: {:?}",
        t.notes
    );
    assert!(
        t.notes.iter().any(|n| n.contains("tm reinstall --force")),
        "a bundled-named untracked skill is #4605 and has a remedy: {:?}",
        t.notes
    );
    // And `--force` is that remedy: it adopts and refreshes the same skill.
    let forced = reinstall_assets(&paths, &sa, None, true, &base.path().join("backups"));
    assert_eq!(tier(&forced, "managed config").skills.shadowed, 0);
    assert!(
        std::fs::read_to_string(stray.join("SKILL.md"))
            .unwrap()
            .contains("Bundled skill text.")
    );
}

#[test]
fn shadowed_note_is_empty_when_nothing_was_shadowed() {
    assert_eq!(shadowed_note(&[], &BTreeSet::new()), None);
}

#[test]
fn shadowed_note_points_at_force_only_for_a_bundled_name() {
    // A deliberate user-tier override is the tier system working and must not
    // be prodded with a remedy; a project-shadowed BUNDLED name is #4605 and
    // must be. The two share one line, so the distinction has to hold inside it.
    use trusty_agents_common::skills::tiers::{Shadow, SkillTier};

    let bundled: BTreeSet<String> = ["demo-skill".to_string()].into_iter().collect();
    let deliberate = [Shadow {
        stem: "demo-skill".to_string(),
        winner: SkillTier::User,
        loser: SkillTier::Bundled,
    }];
    let note = shadowed_note(&deliberate, &bundled).unwrap();
    assert!(note.contains("kept by user-custom"), "{note}");
    assert!(!note.contains("tm reinstall --force"), "{note}");

    let orphaned = [Shadow {
        stem: "demo-skill".to_string(),
        winner: SkillTier::Project,
        loser: SkillTier::Bundled,
    }];
    let note = shadowed_note(&orphaned, &bundled).unwrap();
    assert!(note.contains("tm reinstall --force"), "{note}");

    // An operator-authored skill matching no bundled name gets no pointer —
    // the same admission rule `force_adopt_bundled_skills` applies.
    let operators = [Shadow {
        stem: "my-own-skill".to_string(),
        winner: SkillTier::Project,
        loser: SkillTier::Bundled,
    }];
    let note = shadowed_note(&operators, &bundled).unwrap();
    assert!(!note.contains("tm reinstall --force"), "{note}");
}

// ── the working directory is never written to ───────────────────────────────

#[test]
fn targets_omit_the_project_tier_until_it_exists() {
    // `project_dir` is the process's cwd. Including it unconditionally would
    // make a flagless `tm reinstall` from `$HOME` or `/tmp` materialize the
    // whole skill roster there — the #4409 contamination, one asset class over.
    let base = TempDir::new().unwrap();
    let bare = TempDir::new().unwrap();
    let paths = FrameworkPaths::under(base.path());
    let sa = standalone_dir(base.path());

    let targets = reinstall_targets(&paths, &sa, Some(bare.path()));
    assert!(
        !targets.iter().any(|t| t.label == "project"),
        "a bare directory is not a project tier: {targets:?}"
    );

    // A directory that already HAS a deployed skill tier is one, and it is
    // marked optional.
    std::fs::create_dir_all(bare.path().join(".claude").join("skills")).unwrap();
    let targets = reinstall_targets(&paths, &sa, Some(bare.path()));
    let project = targets
        .iter()
        .find(|t| t.label == "project")
        .expect("an existing project tier must be refreshed");
    assert!(project.optional, "{project:?}");
    assert_eq!(project.agents_dir, None, "#4409: never agents in a project");
}

#[test]
fn reinstall_never_writes_into_a_bare_working_directory() {
    // The end-to-end form of the guard above: run with a bare directory as the
    // "project" and prove nothing whatsoever was created in it.
    let base = TempDir::new().unwrap();
    let bare = TempDir::new().unwrap();
    let paths = seeded(base.path());

    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        Some(bare.path()),
        false,
        &base.path().join("backups"),
    );

    assert!(!report.has_failures(), "{report:?}");
    assert!(
        !bare.path().join(".claude").exists(),
        "a bare working directory must be left completely untouched"
    );
    assert_eq!(
        std::fs::read_dir(bare.path()).unwrap().count(),
        0,
        "nothing at all may be created in an arbitrary cwd"
    );
}

#[test]
fn reinstall_does_not_fail_the_command_for_an_optional_destination() {
    // An unwritable project tier must not report a failed reinstall after all
    // three machine-global destinations succeeded — but it must still be
    // REPORTED, so the operator sees it.
    let base = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = seeded(base.path());
    // #7783: the project tier receives the user-custom tier only, so that is
    // the skill whose deploy is made to fail below.
    seed_user_skill(&paths);
    // A project tier that exists (so it is included) but whose skills path is a
    // regular file, so every write into it fails on every platform.
    std::fs::create_dir_all(project.path().join(".claude").join("skills")).unwrap();
    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        Some(project.path()),
        false,
        &base.path().join("backups"),
    );
    assert!(!report.has_failures(), "healthy baseline: {report:?}");

    // Keep `skills/` a real directory — otherwise the tier is excluded rather
    // than included-and-failing, and this would test the wrong thing. A regular
    // file where the deployer must create `<dest>/demo-skill/` fails its
    // `create_dir_all` on every platform, without depending on permission bits.
    let deployed_dir = project
        .path()
        .join(".claude")
        .join("skills")
        .join("my-skill");
    std::fs::remove_dir_all(&deployed_dir).unwrap();
    std::fs::write(&deployed_dir, "not a directory").unwrap();
    let report = reinstall_assets(
        &paths,
        &standalone_dir(base.path()),
        Some(project.path()),
        false,
        &base.path().join("backups"),
    );

    let t = tier(&report, "project");
    assert!(t.errored, "the failure must still be reported: {t:?}");
    assert!(
        !report.has_failures(),
        "an optional destination must not fail the command: {report:?}"
    );
    // The real destinations are untouched by the project tier's failure. This
    // is the second run, so the skill is already current — assert it is SERVED,
    // not that it was rewritten.
    let standalone = tier(&report, "standalone");
    assert!(!standalone.errored, "{standalone:?}");
    assert!(
        standalone
            .skills_dir
            .join("my-skill")
            .join("SKILL.md")
            .is_file()
    );
}

#[test]
fn shadowed_note_counts_one_skill_once() {
    // `plan_skill_tiers` emits one record per LOSING tier, so a stem all three
    // tiers carry yields TWO records for ONE skill. Counting records would say
    // "2 skill(s)" and "2 of them" for a single name — the same wrong-output
    // defect as the silent zero this reporting exists to fix, inverted.
    use trusty_agents_common::skills::tiers::{Shadow, SkillTier};

    let bundled: BTreeSet<String> = ["demo-skill".to_string()].into_iter().collect();
    let both_losers = [
        Shadow {
            stem: "demo-skill".to_string(),
            winner: SkillTier::Project,
            loser: SkillTier::User,
        },
        Shadow {
            stem: "demo-skill".to_string(),
            winner: SkillTier::Project,
            loser: SkillTier::Bundled,
        },
    ];

    assert_eq!(distinct_shadowed(&both_losers).len(), 1);
    let note = shadowed_note(&both_losers, &bundled).unwrap();
    assert!(note.contains("1 skill(s) were NOT deployed"), "{note}");
    assert!(note.contains("1 of them carry a BUNDLED"), "{note}");
    assert_eq!(
        note.matches("demo-skill").count(),
        2,
        "once in the name list, once in the actionable list — never twice in either: {note}"
    );
}