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
838
839
840
841
842
843
844
845
846
//! Unit tests for catalog staleness detection (HR-3).
//!
//! Why: DOC-17 §HR-3 requires deterministic, offline staleness detection — these
//! tests pin the contract (stale on change, not-stale on identical, unknown when
//! never synced, selection filtering, change-list cap) without any network or a
//! live `claude`.
//! What: seed a catalog source tree on disk, build a deployed manifest whose
//! checksums match (or do not match) the composed/raw content, and assert the
//! [`StalenessReport`] flags + change list.
//! Test: this IS the test module.

use super::*;
use crate::core::agent_manifest::{AgentManifest, ManifestEntry, Origin, checksum};
use crate::core::skill_manifest::{SkillManifest, SkillManifestEntry};
use std::fs;
use std::path::Path;
use tempfile::TempDir;

/// Write a single self-contained (no `extends:`) agent file into `dir`.
fn write_agent(dir: &Path, stem: &str, body: &str) {
    fs::create_dir_all(dir).unwrap();
    fs::write(
        dir.join(format!("{stem}.md")),
        format!("---\nname: {stem}\nrole: {stem}\n---\n\n# {stem}\n\n{body}\n"),
    )
    .unwrap();
}

/// Write a flat skill file into `dir`.
fn write_skill(dir: &Path, stem: &str, body: &str) {
    fs::create_dir_all(dir).unwrap();
    fs::write(
        dir.join(format!("{stem}.md")),
        format!("# {stem}\n\n{body}\n"),
    )
    .unwrap();
}

/// Build a deployed agent manifest whose entry matches the COMPOSED catalog
/// agent (i.e. as if it had just been deployed from this exact catalog).
fn deployed_agent_matching(catalog_agents: &Path, stem: &str) -> AgentManifest {
    // #4698: the ledger records what the DEPLOYER wrote, stamp included.
    let composed = compose_agent_for_deploy(stem, catalog_agents, &std::env::temp_dir()).unwrap();
    let mut m = AgentManifest::default();
    m.managed.insert(
        format!("{stem}.md"),
        ManifestEntry {
            source_chain: vec![stem.to_owned()],
            checksum: checksum(&composed),
            deployed_at: "2026-06-17T00:00:00Z".to_owned(),
            origin: Origin::Bundled,
        },
    );
    m
}

/// Build a deployed skill manifest whose entry matches the RAW catalog skill.
fn deployed_skill_matching(catalog_skills: &Path, stem: &str) -> SkillManifest {
    let body = fs::read_to_string(catalog_skills.join(format!("{stem}.md"))).unwrap();
    let mut m = SkillManifest::default();
    m.managed.insert(
        stem.to_owned(),
        SkillManifestEntry {
            checksum: checksum(&body),
            deployed_at: "2026-06-17T00:00:00Z".to_owned(),
        },
    );
    m
}

#[test]
fn detect_unknown_when_never_synced() {
    // No catalog source trees exist (never synced). The report must be
    // `unknown` and NOT stale — DOC-17: never fabricate staleness, never block.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("repo/.claude/agents");
    let skills = root.path().join("repo/.claude/skills");

    let report = detect_staleness(
        &agents,
        &skills,
        &AgentManifest::default(),
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.unknown, "never-synced must be unknown");
    assert!(!report.stale, "never-synced must not be stale");
    assert!(report.changes.is_empty());
}

#[test]
fn detect_not_stale_when_identical() {
    // A catalog whose content exactly matches the deployed checksums is NOT
    // stale, even though the source trees exist (so not `unknown` either).
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    let skills = root.path().join("skills");
    write_agent(&agents, "rust-engineer", "ENGINEER BODY");
    write_skill(&skills, "tm-doctor", "DOCTOR BODY");

    let dep_agents = deployed_agent_matching(&agents, "rust-engineer");
    let dep_skills = deployed_skill_matching(&skills, "tm-doctor");

    let report = detect_staleness(
        &agents,
        &skills,
        &dep_agents,
        &dep_skills,
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(!report.unknown, "synced catalog is not unknown");
    assert!(!report.stale, "identical content is not stale: {report:?}");
    assert!(report.changes.is_empty());
}

#[test]
fn detect_flags_changed_agent() {
    // Deploy matches the catalog, THEN the catalog agent changes upstream. The
    // report must be stale with a single `agent ...: changed` entry.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    let skills = root.path().join("skills");
    write_agent(&agents, "rust-engineer", "ORIGINAL BODY");

    // Baseline deploy matches the original catalog content.
    let dep_agents = deployed_agent_matching(&agents, "rust-engineer");

    // Upstream edit: the catalog agent body changes.
    write_agent(&agents, "rust-engineer", "UPSTREAM EDIT — NEW BEHAVIOUR");

    let report = detect_staleness(
        &agents,
        &skills,
        &dep_agents,
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.stale, "changed agent must be stale");
    assert!(!report.unknown);
    assert_eq!(report.changes.len(), 1, "exactly one change: {report:?}");
    assert_eq!(report.changes[0].artifact, "agent");
    assert_eq!(report.changes[0].name, "rust-engineer");
    assert_eq!(report.changes[0].kind, ChangeKind::Changed);
}

#[test]
fn detect_flags_new_agent() {
    // A catalog agent absent from the deployed manifest is `new` → stale.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "newcomer", "BRAND NEW");

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"),
        &AgentManifest::default(),
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.stale);
    assert_eq!(report.changes[0].kind, ChangeKind::New);
    assert_eq!(report.changes[0].name, "newcomer");
}

#[test]
fn detect_flags_new_skill() {
    // A catalog skill absent from the deployed skill manifest is `new` → stale.
    let root = TempDir::new().unwrap();
    let skills = root.path().join("skills");
    write_skill(&skills, "fresh-skill", "NEW SKILL");

    let report = detect_staleness(
        &root.path().join("agents"),
        &skills,
        &AgentManifest::default(),
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.stale);
    assert_eq!(report.changes.len(), 1);
    assert_eq!(report.changes[0].artifact, "skill");
    assert_eq!(report.changes[0].name, "fresh-skill");
    assert_eq!(report.changes[0].kind, ChangeKind::New);
}

#[test]
fn detect_flags_changed_skill() {
    // Deploy matches, then the catalog skill body changes → `skill ...: changed`.
    let root = TempDir::new().unwrap();
    let skills = root.path().join("skills");
    write_skill(&skills, "tm-doctor", "ORIGINAL");
    let dep_skills = deployed_skill_matching(&skills, "tm-doctor");
    write_skill(&skills, "tm-doctor", "UPSTREAM CHANGED");

    let report = detect_staleness(
        &root.path().join("agents"),
        &skills,
        &AgentManifest::default(),
        &dep_skills,
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.stale);
    assert_eq!(report.changes[0].kind, ChangeKind::Changed);
    assert_eq!(report.changes[0].artifact, "skill");
}

#[test]
fn detect_respects_selection() {
    // An agent the selection predicate REJECTS must not count toward staleness,
    // even when it differs from (here: is absent from) the deployed manifest.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "rust-engineer", "BODY");
    write_agent(&agents, "php-engineer", "BODY");

    // Deploy matches rust-engineer; php-engineer is new BUT deselected.
    let dep_agents = deployed_agent_matching(&agents, "rust-engineer");

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"),
        &dep_agents,
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |name| name == "rust-engineer", // exclude php-engineer
        |_| true,
        |_| false,
    );
    assert!(
        !report.stale,
        "a deselected new agent must not make the harness stale: {report:?}"
    );
}

#[test]
fn detect_respects_ignore_staleness() {
    // Issue #2462: an agent matched by `ignore_staleness` must not count toward
    // staleness, even though it is fully SELECTED (unlike `detect_respects_
    // selection`, which tests the deploy-roster predicate). This is the
    // narrower, deploy-preserving exemption `AgentSet::ignore_staleness` adds.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "rust-engineer", "BODY");
    write_agent(&agents, "engineer", "BODY");

    // Deploy matches rust-engineer; engineer is new (never deployed) but the
    // operator has flagged it as a known, intentional customization.
    let dep_agents = deployed_agent_matching(&agents, "rust-engineer");

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"),
        &dep_agents,
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true, // both agents SELECTED (deploy roster unaffected)
        |_| true,
        |name| name == "engineer", // but staleness-exempt
    );
    assert!(
        !report.stale,
        "an ignore_staleness agent must not make the harness stale: {report:?}"
    );
}

#[test]
fn detect_caps_change_list() {
    // Many new agents must still set `stale`, but the change list is capped at
    // MAX_CHANGES so the health payload stays small.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    for i in 0..(MAX_CHANGES + 8) {
        write_agent(&agents, &format!("agent{i:02}"), "BODY");
    }

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"),
        &AgentManifest::default(),
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.stale);
    assert_eq!(
        report.changes.len(),
        MAX_CHANGES,
        "change list must be capped"
    );
}

#[test]
fn summary_lines_render_kind_and_name() {
    // The human summary must read `<artifact> <name>: <kind>`.
    let report = StalenessReport {
        stale: true,
        unknown: false,
        changes: vec![
            CatalogChange {
                artifact: "agent",
                name: "rust-engineer".into(),
                kind: ChangeKind::Changed,
            },
            CatalogChange {
                artifact: "skill",
                name: "tm-doctor".into(),
                kind: ChangeKind::New,
            },
        ],
    };
    let lines = report.summary_lines();
    assert_eq!(lines[0], "agent rust-engineer: changed");
    assert_eq!(lines[1], "skill tm-doctor: new");
}

#[test]
fn detect_for_framework_unknown_without_catalog() {
    // With the compiled-in default manifest (bundled sources) and an empty
    // framework root, the catalog source trees do not exist, so the framework-
    // level detection reports `unknown` — never a fabricated staleness.
    let fw_root = TempDir::new().unwrap();
    let fw = crate::core::paths::FrameworkPaths::under(fw_root.path());
    let report = detect_for_framework(&fw, fw_root.path());
    assert!(
        report.unknown,
        "bundled default with no catalog must be unknown: {report:?}"
    );
    assert!(!report.stale);
}

#[test]
fn detect_unknown_when_only_one_tree_missing_is_not_unknown() {
    // If at least ONE source tree exists, the catalog has been synced; the report
    // is a real comparison (not `unknown`) over whichever tree is present.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "solo", "BODY"); // skills tree absent

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"), // does not exist
        &AgentManifest::default(),
        &SkillManifest::default(),
        &root.path().join("dep-agents"),
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(
        !report.unknown,
        "one present tree means synced, not unknown"
    );
    assert!(report.stale, "the present agent is new → stale");
}

/// Write the COMPOSED catalog agent to a deployment dir, simulating a file tm
/// deployed WITHOUT recording a manifest entry (the #1940 root-cause scenario).
fn deploy_agent_on_disk(catalog_agents: &Path, deployed_dir: &Path, stem: &str) {
    // #4698: simulate the deployer's bytes, stamp included.
    let composed = compose_agent_for_deploy(stem, catalog_agents, &std::env::temp_dir()).unwrap();
    fs::create_dir_all(deployed_dir).unwrap();
    fs::write(deployed_dir.join(format!("{stem}.md")), composed).unwrap();
}

/// Write the RAW catalog skill to `<deployed_dir>/<stem>/SKILL.md`, matching the
/// skill deployer's on-disk layout, again WITHOUT a manifest entry.
fn deploy_skill_on_disk(catalog_skills: &Path, deployed_dir: &Path, stem: &str) {
    let body = fs::read_to_string(catalog_skills.join(format!("{stem}.md"))).unwrap();
    let skill_dir = deployed_dir.join(stem);
    fs::create_dir_all(&skill_dir).unwrap();
    fs::write(skill_dir.join("SKILL.md"), body).unwrap();
}

#[test]
fn detect_reconciles_deployed_but_unmanifested() {
    // #1940: an agent/skill already deployed on disk with the current catalog
    // content but ABSENT from the checksum manifest must NOT be reported as `new`.
    // A fully-deployed roster reports 0 changes even with an empty manifest.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    let skills = root.path().join("skills");
    write_agent(&agents, "rust-engineer", "ENGINEER BODY");
    write_skill(&skills, "tm-doctor", "DOCTOR BODY");

    let dep_agents_dir = root.path().join("dep-agents");
    let dep_skills_dir = root.path().join("dep-skills");
    deploy_agent_on_disk(&agents, &dep_agents_dir, "rust-engineer");
    deploy_skill_on_disk(&skills, &dep_skills_dir, "tm-doctor");

    // Manifests are EMPTY — the deploy path never recorded them (the live bug).
    let report = detect_staleness(
        &agents,
        &skills,
        &AgentManifest::default(),
        &SkillManifest::default(),
        &dep_agents_dir,
        &dep_skills_dir,
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(!report.unknown);
    assert!(
        !report.stale,
        "deployed-but-unmanifested roster must reconcile to 0 changes: {report:?}"
    );
    assert!(report.changes.is_empty());
}

#[test]
fn detect_user_owned_on_disk_not_reported() {
    // A file on disk that differs from the catalog content and is NOT managed is
    // user-owned; `apply` skips it, so it must not be reported as drift.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "rust-engineer", "CATALOG BODY");

    let dep_agents_dir = root.path().join("dep-agents");
    fs::create_dir_all(&dep_agents_dir).unwrap();
    fs::write(
        dep_agents_dir.join("rust-engineer.md"),
        "USER-OWNED DIFFERENT CONTENT",
    )
    .unwrap();

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"),
        &AgentManifest::default(),
        &SkillManifest::default(),
        &dep_agents_dir,
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(
        !report.stale,
        "a user-owned on-disk file `apply` never touches must not be drift: {report:?}"
    );
}

#[test]
fn detect_user_modified_managed_not_reported() {
    // A MANAGED agent whose catalog content changed, but whose on-disk copy the
    // user has since edited (differs from the recorded checksum), must NOT be
    // reported — `apply` preserves the user's edit rather than refreshing it.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "rust-engineer", "ORIGINAL");
    let dep_agents = deployed_agent_matching(&agents, "rust-engineer");
    // Upstream edit: catalog content changes.
    write_agent(&agents, "rust-engineer", "UPSTREAM CHANGED");
    // On disk the user has hand-edited it (matches neither recorded nor catalog).
    let dep_agents_dir = root.path().join("dep-agents");
    fs::create_dir_all(&dep_agents_dir).unwrap();
    fs::write(dep_agents_dir.join("rust-engineer.md"), "USER HAND-EDIT").unwrap();

    let report = detect_staleness(
        &agents,
        &root.path().join("skills"),
        &dep_agents,
        &SkillManifest::default(),
        &dep_agents_dir,
        &root.path().join("dep-skills"),
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(
        !report.stale,
        "a user-modified managed file `apply` skips must not be drift: {report:?}"
    );
}

#[test]
fn classify_drift_reconciles_on_disk() {
    // Unit-level: on-disk content matching the catalog hash is never drift, even
    // with no manifest entry; a managed+unmodified changed file is Changed.
    // #4322: the third argument is now the on-disk CHECKSUM, not the on-disk
    // content — the hashing moved to the call site so a fleet-wide caller can
    // hash the shared deployed-agent tree once instead of once per session.
    let cat = checksum("catalog content");
    // Deployed-but-unmanifested and current → None (reconcile).
    assert_eq!(
        super::classify_drift(&cat, None, Some(&checksum("catalog content"))),
        None
    );
    // Managed, unmodified on disk, catalog changed → Changed.
    let recorded = checksum("old content");
    assert_eq!(
        super::classify_drift(&cat, Some(&recorded), Some(&checksum("old content"))),
        Some(ChangeKind::Changed)
    );
    // Managed, user-modified on disk, catalog changed → None (apply skips).
    assert_eq!(
        super::classify_drift(&cat, Some(&recorded), Some(&checksum("user edit"))),
        None
    );
}

#[test]
fn classify_drift_new_when_absent() {
    // Nothing on disk and no manifest entry → genuinely new (apply deploys it).
    let cat = checksum("catalog content");
    assert_eq!(
        super::classify_drift(&cat, None, None),
        Some(ChangeKind::New)
    );
    // Manifest already records the catalog content → not drift regardless of disk.
    assert_eq!(super::classify_drift(&cat, Some(&cat), None), None);
}

// ── #2444 review: CatalogHashes sharing (MEDIUM finding) ──────────────────────

#[test]
fn compute_agent_catalog_hashes_skips_compose_failures() {
    // A malformed agent (unterminated frontmatter) must be absent from the
    // map, not cause the whole computation to fail — mirrors the pre-existing
    // `agent_changes` skip-on-compose-failure behavior.
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "good", "v1");
    fs::write(agents.join("broken.md"), "---\nunterminated").unwrap();

    let hashes = compute_agent_catalog_hashes(&agents, &std::env::temp_dir());
    assert!(hashes.contains_key("good"));
    assert!(
        !hashes.contains_key("broken"),
        "a compose failure must be skipped, not panic or poison the map"
    );
}

#[test]
fn compute_skill_catalog_hashes_reads_bodies() {
    let root = TempDir::new().unwrap();
    let skills = root.path().join("skills");
    write_skill(&skills, "tm-doctor", "v1");
    let hashes = compute_skill_catalog_hashes(&skills);
    assert_eq!(
        hashes.get("tm-doctor"),
        Some(&checksum("# tm-doctor\n\nv1\n"))
    );
}

#[test]
fn catalog_hashes_compute_is_unknown_without_either_source() {
    let root = TempDir::new().unwrap();
    let cache = CatalogHashes::compute(
        &root.path().join("no-agents"),
        &root.path().join("no-skills"),
        &std::env::temp_dir(),
    );
    let report = cache.detect(
        &DeployedAgentHashes::with_manifest(
            AgentManifest::default(),
            &root.path().join("dep-agents"),
            &cache,
        ),
        &SkillManifest::default(),
        &root.path().join("dep-skills"),
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(report.unknown);
    assert!(!report.stale);
}

/// #7727 review: a relative skills root makes the cache `unknown` instead of
/// computing an agent map with every agent silently missing.
#[test]
fn catalog_hashes_compute_is_unknown_for_an_unresolvable_skills_root() {
    let root = TempDir::new().unwrap();
    let agents = root.path().join("agents");
    write_agent(&agents, "rust-engineer", "v1");
    let cache = CatalogHashes::compute(
        &agents,
        &root.path().join("no-skills"),
        Path::new("relative"),
    );
    assert!(cache.unknown, "an unresolvable root must not read as known");
}

/// #7727 review: a deployed body carrying `{{TM_SKILLS}}` hashes as fresh
/// against the root it was deployed with, and as stale against any other.
///
/// Why: every staleness fixture used placeholder-free bodies, so passing the
/// wrong root to the catalog hash would have gone unnoticed while every real
/// deployed agent read as permanently stale.
/// What: deploys a placeholder-bearing catalog agent through the real
/// deployer with `fw.skill_deploy_dir()`, asserts `detect_for_framework` is
/// fresh, then detects against a catalog hashed with a different root.
/// Test: this test.
#[test]
fn placeholder_body_is_fresh_only_against_its_deployed_skills_root() {
    use crate::core::agent_deployer::deploy_agents_filtered;
    use trusty_agents_common::agents::skill_root::SKILLS_ROOT_PLACEHOLDER;

    let fw_root = TempDir::new().unwrap();
    let fw = crate::core::paths::FrameworkPaths::under(fw_root.path());
    let catalog_root = crate::content::catalog_root_for(&fw.root);
    let sources = crate::core::manifest::ManifestSources::resolve(fw_root.path(), &catalog_root);
    let manifest = crate::core::manifest::resolve_manifest(&sources);
    let plan = crate::core::manifest::HarnessPlan::from_manifest(&manifest, &fw, &catalog_root);
    write_agent(
        &plan.agent_source,
        "rust-engineer",
        &format!("Read `{SKILLS_ROOT_PLACEHOLDER}/self-improvement-loop/SKILL.md`."),
    );
    let deployed = deploy_agents_filtered(
        &plan.agent_source,
        &fw.agent_deploy_dir(),
        &fw.skill_deploy_dir(),
        |_| true,
    )
    .unwrap();
    assert_eq!(deployed.deployed.len(), 1, "{deployed:?}");

    let report = detect_for_framework(&fw, fw_root.path());
    assert!(!report.unknown, "{report:?}");
    assert!(
        !report.stale,
        "deployed with its own root must be fresh: {report:?}"
    );

    let other_root = fw_root.path().join("other-skills");
    let catalog = CatalogHashes::compute(&plan.agent_source, &plan.skill_source, &other_root);
    let agents_dir = fw.agent_deploy_dir();
    let report = catalog.detect(
        &DeployedAgentHashes::read(&agents_dir, &catalog),
        &SkillManifest::default(),
        &fw.claude_skills_dir(),
        |name| name == "rust-engineer",
        |_| false,
        |_| false,
    );
    assert!(
        report.stale,
        "a different skills root must read as stale: {report:?}"
    );
}

/// Issue #2444 review: the whole point of [`CatalogHashes`] — compute ONCE,
/// `detect` against TWO independent deployed targets, and confirm each
/// target's report is exactly what a fresh [`detect_staleness`] call would
/// have produced for it (i.e. sharing the cache changes nothing about
/// correctness, only how many times the catalog side is recomposed).
#[test]
fn catalog_hashes_shared_across_two_deployed_targets() {
    let root = TempDir::new().unwrap();
    let catalog_agents = root.path().join("catalog/agents");
    let catalog_skills = root.path().join("catalog/skills");
    write_agent(&catalog_agents, "rust-engineer", "v1");
    write_skill(&catalog_skills, "tm-doctor", "v1");

    // Target A: freshly deployed, matches the catalog exactly → not stale.
    let a_agents_dir = root.path().join("a/agents");
    let a_skills_dir = root.path().join("a/skills");
    let a_agent_manifest = deployed_agent_matching(&catalog_agents, "rust-engineer");
    let a_skill_manifest = deployed_skill_matching(&catalog_skills, "tm-doctor");

    // Target B: deployed from an OLDER catalog version → stale.
    let b_agents_dir = root.path().join("b/agents");
    let b_skills_dir = root.path().join("b/skills");
    let mut b_agent_manifest = AgentManifest::default();
    b_agent_manifest.managed.insert(
        "rust-engineer.md".to_string(),
        crate::core::agent_manifest::ManifestEntry {
            source_chain: vec!["rust-engineer".to_string()],
            checksum: checksum("stale composed content"),
            deployed_at: "2026-01-01T00:00:00Z".to_string(),
            origin: crate::core::agent_manifest::Origin::Bundled,
        },
    );
    fs::create_dir_all(&b_agents_dir).unwrap();
    fs::write(
        b_agents_dir.join("rust-engineer.md"),
        "stale composed content",
    )
    .unwrap();
    let b_skill_manifest = SkillManifest::default();

    // Compute the catalog side EXACTLY ONCE, then detect against both targets.
    let cache = CatalogHashes::compute(&catalog_agents, &catalog_skills, &std::env::temp_dir());

    let report_a = cache.detect(
        &DeployedAgentHashes::with_manifest(a_agent_manifest.clone(), &a_agents_dir, &cache),
        &a_skill_manifest,
        &a_skills_dir,
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(
        !report_a.stale,
        "target A matches the catalog: {report_a:?}"
    );

    let report_b = cache.detect(
        &DeployedAgentHashes::with_manifest(b_agent_manifest.clone(), &b_agents_dir, &cache),
        &b_skill_manifest,
        &b_skills_dir,
        |_| true,
        |_| true,
        |_| false,
    );
    assert!(
        report_b.stale,
        "target B's agent is stale relative to the shared catalog: {report_b:?}"
    );
    assert!(
        report_b.changes.iter().any(|c| c.name == "rust-engineer"),
        "the stale agent must be named: {report_b:?}"
    );

    // Sanity: results must match what fresh, unshared `detect_staleness` calls
    // would independently produce for each target.
    let fresh_a = detect_staleness(
        &catalog_agents,
        &catalog_skills,
        &a_agent_manifest,
        &a_skill_manifest,
        &a_agents_dir,
        &a_skills_dir,
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert_eq!(fresh_a.stale, report_a.stale);
    let fresh_b = detect_staleness(
        &catalog_agents,
        &catalog_skills,
        &b_agent_manifest,
        &b_skill_manifest,
        &b_agents_dir,
        &b_skills_dir,
        &std::env::temp_dir(),
        |_| true,
        |_| true,
        |_| false,
    );
    assert_eq!(fresh_b.stale, report_b.stale);
}

/// Issue #4619 review (MEDIUM): a SINGLE-target caller must not read more
/// deployed agent files than its predicates actually select.
///
/// Why: #4322 pre-hashes the deployed agent tree so the fleet path can share
/// ONE read across N sessions. Applied indiscriminately, that would be a read
/// INCREASE for every single-target caller (`/health`, `tm catalog apply`, the
/// single-session `GET …/managed/{id}`) whose manifest selects a subset:
/// before, `agent_changes` read only the selected stems; an eager snapshot
/// reads every catalog stem. Those callers share their read with nobody, so the
/// eagerness buys nothing and costs real I/O. `DeployedAgentHashes::lazy` keeps
/// their behavior byte-for-byte identical, and this pins it — a perf change
/// that quietly regresses another call shape is misreported, not neutral.
/// What: a 4-agent catalog with a predicate selecting exactly ONE, run through
/// `detect_staleness` (the single-target entry point), asserting exactly one
/// deployed agent file was read. Switching `detect_staleness` back to the eager
/// `with_manifest` form makes this observe 4 and fail.
#[test]
fn single_target_detect_reads_only_selected_agents() {
    let root = TempDir::new().unwrap();
    let catalog_agents = root.path().join("single-target/catalog/agents");
    let catalog_skills = root.path().join("single-target/catalog/skills");
    let deployed_agents_dir = root.path().join("single-target/deployed/agents");
    let deployed_skills_dir = root.path().join("single-target/deployed/skills");
    for stem in ["alpha", "beta", "gamma", "delta"] {
        write_agent(&catalog_agents, stem, "v1");
        write_agent(&deployed_agents_dir, stem, "v1");
    }
    write_skill(&catalog_skills, "tm-doctor", "v1");

    // #5040: deliberately NO `reset_deployed_read_log()`. The log is
    // process-global, so a clear performed by one test erases entries another
    // test has already recorded. Isolation here comes from
    // `deployed_reads_under`'s prefix filter against this test's own temp dir,
    // which is zero before the call below by construction.
    let _ = detect_staleness(
        &catalog_agents,
        &catalog_skills,
        &AgentManifest::default(),
        &SkillManifest::default(),
        &deployed_agents_dir,
        &deployed_skills_dir,
        &std::env::temp_dir(),
        // Selects exactly one of the four catalog agents.
        |name| name == "alpha",
        |_| true,
        |_| false,
    );

    assert_eq!(
        super::deployed_reads_under(&deployed_agents_dir),
        1,
        "a single-target caller selecting 1 of 4 catalog agents must read \
         exactly 1 deployed agent file. Observing 4 means the eager fleet-path \
         snapshot leaked onto the single-target path and increased its I/O \
         (#4619 review MEDIUM)"
    );
}