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
//! Tests for the `asset_tier` doctor probe (#4442).
//!
//! Why: the probe's whole value is that it FIRES on a shadowing project-tier
//! copy that every presence-only check reports green on, and stays silent on a
//! project's own agents — including one whose NAME collides with a bundled
//! agent but whose ledger entry proves the operator owns it. Both halves are
//! pinned here; delete the check and `project_tier_stub_on_a_bundled_name_fails`
//! fails.
//! What: end-to-end `check_asset_tier` cases against temp project/home trees,
//! plus the pure `verdict` branches and the roster construction.
//! Test: this file.

use super::*;
use trusty_agents_common::agents::manifest::{AgentManifest, ManifestEntry, Origin, checksum};
use trusty_agents_common::agents::provenance::Provenance;
use trusty_agents_common::agents::tier_audit::TierResidentClass;

/// A hermetic `FrameworkPaths` whose agent SOURCE dir is inside `base`.
///
/// `trusty_mpm_root` is cleared so `agent_source_dir()` cannot resolve to the
/// real repository's `agents/agents` submodule and leak host state into the
/// assertions (same guard `doctor_deploy_validate`'s tests use).
fn hermetic_paths(base: &Path) -> FrameworkPaths {
    let mut paths = FrameworkPaths::under(base);
    paths.trusty_mpm_root = None;
    paths
}

/// A minimal agent document declaring `name`.
fn doc(name: &str) -> String {
    format!("---\nname: {name}\nrole: engineer\n---\n\nBody.\n")
}

/// Write `<base>/.claude/agents/<file_name>` with the given content.
fn place_agent(base: &Path, file_name: &str, body: &str) {
    let dir = base.join(".claude").join("agents");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join(file_name), body).unwrap();
}

/// Claim `<base>/.claude/agents/<file_name>` in that tier's ownership ledger.
fn track(base: &Path, file_name: &str, origin: Origin) {
    let dir = base.join(".claude").join("agents");
    let mut manifest = AgentManifest::default();
    manifest.managed.insert(
        file_name.to_owned(),
        ManifestEntry {
            source_chain: vec![],
            checksum: checksum("whatever"),
            deployed_at: "2026-07-31T00:00:00Z".to_owned(),
            origin,
        },
    );
    manifest.save(&dir).unwrap();
}

/// Build a scan result for the pure `verdict` tests.
fn scan(label: &'static str, dir: &Path, names: &[&str]) -> TierScan {
    TierScan {
        label,
        dir: dir.to_path_buf(),
        outcome: TierOutcome::Scanned(
            names
                .iter()
                .map(|s| MisplacedAgent {
                    path: dir.join(format!("{s}.md")),
                    name: (*s).to_owned(),
                    class: TierResidentClass::ShadowsBundled,
                })
                .collect(),
        ),
    }
}

/// Build a scan that could not run, for the #5626 undetermined-tier tests.
fn unscannable(label: &'static str, dir: &Path) -> TierScan {
    TierScan {
        label,
        dir: dir.to_path_buf(),
        outcome: TierOutcome::Unscannable(format!(
            "cannot scan agent tier {}: Permission denied (os error 13)",
            dir.display()
        )),
    }
}

#[test]
fn project_tier_stub_on_a_bundled_name_fails() {
    // THE case: #4408's 32-byte project-tier stub resolving to a bundled name.
    // Presence-only checks see a perfect canonical deploy; this must Fail.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();
    place_agent(
        &project,
        "rust-engineer.md",
        "---\nname: rust-engineer\n---\n",
    );

    let paths = hermetic_paths(&home);
    let check = check_asset_tier(&paths, Some(&project), &home);

    assert_eq!(
        check.status,
        CheckStatus::Fail,
        "message: {}",
        check.message
    );
    assert!(check.message.contains("rust-engineer"), "{}", check.message);
    assert!(check.message.contains("project tier"), "{}", check.message);
}

#[test]
fn clean_project_tier_is_ok() {
    // The negative control: nothing outside the canonical tier, no noise.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();

    let paths = hermetic_paths(&home);
    let check = check_asset_tier(&paths, Some(&project), &home);

    assert_eq!(check.status, CheckStatus::Ok, "message: {}", check.message);
}

#[test]
fn custom_project_agent_does_not_fire() {
    // The anti-noise guarantee that lets #4443 ship project-custom agents: a
    // name tm does not bundle is the project's own and must never be reported.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();
    place_agent(
        &project,
        "acme-internal-reviewer.md",
        &doc("acme-internal-reviewer"),
    );

    let paths = hermetic_paths(&home);
    let check = check_asset_tier(&paths, Some(&project), &home);

    assert_eq!(check.status, CheckStatus::Ok, "message: {}", check.message);
}

#[test]
fn user_owned_project_agent_on_a_bundled_name_does_not_fire() {
    // Ownership beats a name collision end to end: the operator's own `qa.md`,
    // tracked `Origin::User`, on a name tm also ships. Flagging it would point
    // #4448 at a file it must never move.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();
    place_agent(&project, "qa.md", &doc("qa"));
    track(&project, "qa.md", Origin::User);

    let paths = hermetic_paths(&home);
    let check = check_asset_tier(&paths, Some(&project), &home);

    assert_eq!(check.status, CheckStatus::Ok, "message: {}", check.message);
}

#[test]
fn a_renamed_project_file_declaring_a_bundled_name_fails() {
    // Identity is the frontmatter name: `helper.md` declaring `name: qa`
    // shadows `qa`, and a stem-keyed predicate would miss it entirely.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();
    place_agent(&project, "helper.md", &doc("qa"));

    let paths = hermetic_paths(&home);
    let check = check_asset_tier(&paths, Some(&project), &home);

    assert_eq!(
        check.status,
        CheckStatus::Fail,
        "message: {}",
        check.message
    );
    assert!(check.message.contains("qa"), "{}", check.message);
}

#[test]
fn home_tier_copy_is_only_a_warn() {
    // A managed session relocates CLAUDE_CONFIG_DIR, so a `~/.claude/agents`
    // copy is stale rather than shadowing — real, but not the hard failure.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();
    place_agent(&home, "qa.md", &doc("qa"));

    let paths = hermetic_paths(&home);
    let check = check_asset_tier(&paths, Some(&project), &home);

    assert_eq!(
        check.status,
        CheckStatus::Warn,
        "message: {}",
        check.message
    );
    assert!(check.message.contains("qa"), "{}", check.message);
}

#[test]
fn canonical_tier_is_never_scanned() {
    // Every file in the canonical directory is tm-owned by definition; scanning
    // it would make the probe fire permanently on a healthy install.
    let tmp = tempfile::tempdir().unwrap();
    let home = tmp.path().join("home");
    std::fs::create_dir_all(&home).unwrap();
    let paths = hermetic_paths(&home);

    let canonical = paths.agent_deploy_dir();
    std::fs::create_dir_all(&canonical).unwrap();
    std::fs::write(canonical.join("rust-engineer.md"), doc("rust-engineer")).unwrap();

    let check = check_asset_tier(&paths, None, &home);
    assert_eq!(check.status, CheckStatus::Ok, "message: {}", check.message);
}

#[test]
fn roster_falls_back_to_the_embedded_bundle() {
    // With no agent source on disk (a binary-only install) the roster must
    // still be populated — an empty roster would classify every shadowing copy
    // as a legitimate custom agent and report a false green.
    let tmp = tempfile::tempdir().unwrap();
    let paths = hermetic_paths(tmp.path());
    assert!(!paths.agent_source_dir().is_dir());

    let roster = crate::core::bundled_roster::bundled_roster_with(
        &paths,
        &crate::core::content_source::test_support::repo_roster(),
    );
    assert!(
        roster.contains("rust-engineer"),
        "embedded roster missing rust-engineer: {roster:?}"
    );
}

#[test]
fn roster_keys_the_embedded_half_by_declared_name() {
    // `BASE-AGENT.md` declares `name: base-agent`. Keying the embedded half by
    // rel_path stem would put `BASE-AGENT` in the roster and silently exempt
    // the name the harness actually resolves.
    let tmp = tempfile::tempdir().unwrap();
    let paths = hermetic_paths(tmp.path());

    let roster = crate::core::bundled_roster::bundled_roster_with(
        &paths,
        &crate::core::content_source::test_support::repo_roster(),
    );
    assert!(roster.contains("base-agent"), "roster: {roster:?}");
    assert!(!roster.contains("BASE-AGENT"), "roster: {roster:?}");
}

#[test]
fn roster_includes_on_disk_source_names() {
    // A locally installed roster is the accurate authority — an agent added
    // there must classify even before the binary that bundles it ships.
    let tmp = tempfile::tempdir().unwrap();
    let paths = hermetic_paths(tmp.path());
    let source = paths.agent_source_dir();
    std::fs::create_dir_all(&source).unwrap();
    std::fs::write(source.join("whatever.md"), doc("locally-installed")).unwrap();

    assert!(
        crate::core::bundled_roster::bundled_roster_with(
            &paths,
            &crate::core::content_source::test_support::repo_roster(),
        )
        .contains("locally-installed")
    );
}

#[test]
fn verdict_project_hit_is_fail() {
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(&[scan("project", &dir, &["qa"])], &canonical, &[]);
    assert_eq!(check.status, CheckStatus::Fail);
}

#[test]
fn verdict_home_only_is_warn() {
    let dir = PathBuf::from("/h/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(&[scan("operator home", &dir, &["qa"])], &canonical, &[]);
    assert_eq!(check.status, CheckStatus::Warn);
}

#[test]
fn verdict_clean_is_ok() {
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(&[scan("project", &dir, &[])], &canonical, &[]);
    assert_eq!(check.status, CheckStatus::Ok);
    assert!(check.message.contains("/c/agents"), "{}", check.message);
}

#[test]
fn verdict_unscannable_tier_is_warn() {
    // #5626: the probe could not look, so it must not say it looked and found
    // nothing. Pre-fix the same input produced `Ok` with "(scanned: <dir>)".
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(&[unscannable("project", &dir)], &canonical, &[]);
    assert_eq!(check.status, CheckStatus::Warn, "{}", check.message);
    assert!(check.message.contains("UNDETERMINED"), "{}", check.message);
}

#[test]
fn verdict_unscannable_tier_is_not_reported_as_scanned() {
    // The `scanned:` list is a factual claim about which directories were read.
    // A tier that failed belongs in the failure detail, never in that list.
    let scanned_dir = PathBuf::from("/h/.claude/agents");
    let failed_dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(
        &[
            scan("operator home", &scanned_dir, &[]),
            unscannable("project", &failed_dir),
        ],
        &canonical,
        &[],
    );
    let scanned_clause = check
        .message
        .split("Scanned: ")
        .nth(1)
        .unwrap_or_else(|| panic!("no Scanned: clause in {}", check.message));
    assert!(
        scanned_clause.contains("/h/.claude/agents"),
        "the tier that WAS read must be listed: {}",
        check.message
    );
    assert!(
        !scanned_clause.contains("/w/.claude/agents"),
        "the tier that failed must not be claimed as scanned: {}",
        check.message
    );
}

#[test]
fn verdict_names_the_files_and_both_tiers() {
    // The message must be actionable without reading the source: which agents,
    // which directories, and what to run.
    let project = PathBuf::from("/w/.claude/agents");
    let home = PathBuf::from("/h/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(
        &[
            scan("project", &project, &["qa"]),
            scan("operator home", &home, &["engineer"]),
        ],
        &canonical,
        &[],
    );
    assert_eq!(check.status, CheckStatus::Fail);
    for needle in [
        "/w/.claude/agents",
        "/h/.claude/agents",
        "/c/agents",
        "qa",
        "engineer",
        "--reset-agents-workspaces",
    ] {
        assert!(
            check.message.contains(needle),
            "missing {needle}: {}",
            check.message
        );
    }
}

#[test]
fn verdict_summarises_a_long_list() {
    // Six offenders must not produce a six-name wall; the count survives.
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let names = ["a", "b", "c", "d", "e", "f"];
    let check = verdict(&[scan("project", &dir, &names)], &canonical, &[]);
    assert!(check.message.contains("(+1 more)"), "{}", check.message);
}

// ---------------------------------------------------------------------------
// #4698: a `provenance:` that contradicts the ledger reaches the operator.
// ---------------------------------------------------------------------------

/// One disagreement, as `audit_provenance` would return it.
fn disagreement(
    path: &str,
    declared: Provenance,
    ledger_framework_owned: bool,
) -> ProvenanceDisagreement {
    ProvenanceDisagreement {
        path: PathBuf::from(path),
        declared,
        ledger_framework_owned,
        detail: format!(
            "'{}' declares `provenance: {}` but the deployed-agent manifest records it as {}; \
             the manifest wins (#4698)",
            path,
            declared.as_str(),
            if ledger_framework_owned {
                "framework-owned"
            } else {
                "not framework-owned"
            }
        ),
    }
}

/// THE regression this exists for: nothing is misplaced, but a deployed file's
/// frontmatter contradicts its ledger row. Dropping the disagreement returns
/// this to `Ok` with no mention of the file, which is what shipped before the
/// critic caught it.
#[test]
fn verdict_disagreement_alone_is_warn_not_ok() {
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(
        &[scan("project", &dir, &[])],
        &canonical,
        &[disagreement(
            "/c/agents/rust-engineer.md",
            Provenance::UserAuthored,
            true,
        )],
    );
    assert_eq!(
        check.status,
        CheckStatus::Warn,
        "a clean placement scan with a contradicting declaration is not Ok: {}",
        check.message
    );
    for needle in [
        "/c/agents/rust-engineer.md",
        "user-authored",
        "framework-owned",
        "#4698",
    ] {
        assert!(
            check.message.contains(needle),
            "message must carry `{needle}`: {}",
            check.message
        );
    }
}

/// A disagreement never demotes a shadowing `Fail` — shadowing is the more
/// actionable finding — but it is still named in the same message.
#[test]
fn verdict_reports_a_provenance_disagreement_alongside_shadowing() {
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(
        &[scan("project", &dir, &["qa"])],
        &canonical,
        &[disagreement(
            "/c/agents/qa.md",
            Provenance::FrameworkOwned,
            false,
        )],
    );
    assert_eq!(check.status, CheckStatus::Fail, "{}", check.message);
    assert!(
        check.message.contains("/c/agents/qa.md"),
        "the disagreement is not dropped when shadowing also fires: {}",
        check.message
    );
}

/// No disagreements means the message says nothing about provenance — this
/// finding must not add noise to an otherwise clean run.
#[test]
fn verdict_clean_run_says_nothing_about_provenance() {
    let dir = PathBuf::from("/w/.claude/agents");
    let canonical = PathBuf::from("/c/agents");
    let check = verdict(&[scan("project", &dir, &[])], &canonical, &[]);
    assert_eq!(check.status, CheckStatus::Ok);
    assert!(
        !check.message.contains("provenance"),
        "no finding, no mention: {}",
        check.message
    );
}

/// End to end through the real probe: a hand-edited file in the CANONICAL tier
/// — the directory the shadowing scan deliberately skips — still produces a
/// finding. This is the case a `MisplacedAgent` field could never reach.
#[test]
fn check_asset_tier_reports_a_hand_edited_deployed_agent() {
    let home = tempfile::tempdir().unwrap();
    let project = tempfile::tempdir().unwrap();
    let paths = FrameworkPaths::for_managed_project(home.path(), project.path());
    let canonical = paths.agent_deploy_dir();
    std::fs::create_dir_all(&canonical).unwrap();

    // A deployed agent whose ledger row says the framework wrote it, but whose
    // frontmatter now claims otherwise.
    let body = "---\nname: qa\nrole: qa\nprovenance: user-authored\n---\n\nMine now.\n";
    std::fs::write(canonical.join("qa.md"), body).unwrap();
    // `track` appends `.claude/agents` to a base; the canonical deploy dir is
    // already a full path, so the ledger is written directly into it.
    let mut manifest = AgentManifest::default();
    manifest.managed.insert(
        "qa.md".to_owned(),
        ManifestEntry {
            source_chain: vec![],
            checksum: checksum(body),
            deployed_at: "2026-07-31T00:00:00Z".to_owned(),
            origin: Origin::Bundled,
        },
    );
    manifest.save(&canonical).unwrap();

    let check = check_asset_tier(&paths, Some(project.path()), home.path());
    assert_eq!(
        check.status,
        CheckStatus::Warn,
        "the canonical tier is scanned for disagreements: {}",
        check.message
    );
    assert!(
        check.message.contains("qa.md") && check.message.contains("user-authored"),
        "names the file and the declaration: {}",
        check.message
    );
}