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
//! Tests for [`super`] — cargo install-ledger parsing and the `#4033`
//! provenance verdict table.
//!
//! Why: every branch of [`super::provenance_report`] is a claim `tm doctor`
//! makes to an operator about whether the binary they are testing is the one
//! they think it is; each therefore needs its own mutation-proof case,
//! including the two that must report `Unknown` rather than `Ok`.
//! What: source-classification cases, ledger-parse cases, then one case per
//! verdict branch.
//! Test: this file.

use super::*;

/// A `.crates2.json` document mirroring the real one's shape.
const LEDGER: &str = r#"{
  "installs": {
    "trusty-mpm 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)": {
      "version_req": null,
      "bins": ["tm"],
      "features": [],
      "all_features": false,
      "no_default_features": false,
      "profile": "release",
      "target": "aarch64-apple-darwin",
      "rustc": "rustc 1.90.0",
      "supports_options": true
    },
    "trusty-search 0.39.0 (path+file:///Users/masa/tmp/ts/crates/trusty-search)": {
      "bins": ["trusty-search"]
    },
    "trusty-channels 0.1.0 (git+ssh://git@github.com/bobmatnyc/trusty-tools.git#b45f2ad)": {
      "bins": ["slack-mcp", "telegram-mcp"]
    }
  }
}"#;

fn always_exists(_: &Path) -> bool {
    true
}

/// The cargo bin directory the fixtures pretend to install into.
const CARGO_BIN: &str = "/Users/masa/.cargo/bin";

/// Path of a binary that IS the cargo install.
fn installed(bin: &str) -> PathBuf {
    PathBuf::from(CARGO_BIN).join(bin)
}

fn never_exists(_: &Path) -> bool {
    false
}

#[test]
fn parses_a_real_ledger() {
    // The three source shapes cargo actually writes must all round-trip into
    // typed records keyed by the BINARY names doctor asks about.
    let installs = parse_cargo_installs(LEDGER).expect("ledger should parse");
    assert_eq!(installs.len(), 3);

    let mpm = installs.iter().find(|i| i.package == "trusty-mpm").unwrap();
    assert_eq!(mpm.version, "1.3.1");
    assert_eq!(mpm.source, InstallSource::Registry);
    assert_eq!(mpm.bins, vec!["tm".to_string()]);

    let channels = installs
        .iter()
        .find(|i| i.package == "trusty-channels")
        .unwrap();
    assert_eq!(channels.bins.len(), 2);
}

#[test]
fn parse_returns_none_for_garbage() {
    // An unparseable ledger must be None — the caller reports UNKNOWN. An
    // empty Vec would read as "cargo installed nothing", which is a claim.
    assert!(parse_cargo_installs("not json").is_none());
}

#[test]
fn parse_skips_malformed_keys() {
    // A key that is not a package-id spec is skipped, never guessed at.
    let installs = parse_cargo_installs(r#"{"installs":{"nonsense":{"bins":["x"]}}}"#).unwrap();
    assert!(installs.is_empty());
}

#[test]
fn classifies_registry_source() {
    assert_eq!(
        classify_source("registry+https://github.com/rust-lang/crates.io-index"),
        InstallSource::Registry
    );
}

#[test]
fn classifies_path_source() {
    assert_eq!(
        classify_source("path+file:///Users/masa/tmp/x"),
        InstallSource::Path(PathBuf::from("/Users/masa/tmp/x"))
    );
}

#[test]
fn classifies_git_source() {
    assert!(matches!(
        classify_source("git+ssh://git@example.com/x.git#abc"),
        InstallSource::Git(_)
    ));
}

#[test]
fn classifies_unknown_source() {
    // An unrecognised source is carried as-is, never silently normalised into
    // one of the known kinds.
    assert!(matches!(
        classify_source("sparse+https://example.invalid"),
        InstallSource::Other(_)
    ));
}

#[test]
fn unknown_without_a_ledger() {
    // No ledger = nothing learned. UNKNOWN, never Ok (the whole point of #4033).
    let (status, msg) = provenance_report(
        "tm",
        "1.3.1",
        &installed("tm"),
        Path::new(CARGO_BIN),
        None,
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Unknown, "message: {msg}");
    assert!(msg.contains("cannot verify"), "message: {msg}");
}

#[test]
fn unknown_when_bin_is_not_in_the_ledger() {
    // A prebuilt-installer drop into ~/.local/bin is real and common; doctor
    // must say it cannot verify it rather than call it clean.
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "tctl",
        "0.4.3",
        Path::new("/Users/masa/.local/bin/tctl"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Unknown, "message: {msg}");
    assert!(msg.contains("not recorded"), "message: {msg}");
}

#[test]
fn fails_on_duplicate_installs() {
    // The #4033 trusty-channels case: the same binary from two different
    // sources, whichever wrote last winning.
    let ledger = vec![
        CargoInstall {
            package: "trusty-channels".into(),
            version: "0.1.0".into(),
            source: InstallSource::Path(PathBuf::from("/a")),
            bins: vec!["slack-mcp".into()],
        },
        CargoInstall {
            package: "trusty-channels".into(),
            version: "0.1.1".into(),
            source: InstallSource::Path(PathBuf::from("/b")),
            bins: vec!["slack-mcp".into()],
        },
    ];
    let (status, msg) = provenance_report(
        "slack-mcp",
        "0.1.0",
        &installed("slack-mcp"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Fail, "message: {msg}");
    assert!(msg.contains("2 separate installs"), "message: {msg}");
}

#[test]
fn fails_on_version_disagreement() {
    // The running binary is OLDER than the version cargo recorded at the same
    // path: an older file is sitting on top of a newer install, so an upgrade
    // the ledger says landed is not what executes. #4964 keeps this a Fail.
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "tm",
        "1.2.3",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Fail, "message: {msg}");
    assert!(msg.contains("1.2.3"), "message: {msg}");
    assert!(msg.contains("1.3.1"), "message: {msg}");
    assert!(
        msg.contains("OLDER"),
        "message must name the direction: {msg}"
    );
}

/// #4964's new provenance class: the prebuilt downloader placed a NEWER binary
/// at the exact path a stale cargo record describes.
///
/// Why: after #4964 Phase 1 (daemon upgrades stop invoking cargo) and Phase 3
/// (destination flips to `$CARGO_HOME/bin`), this is what a clean, successful,
/// cargo-free `tctl upgrade` leaves behind. Before this change the path match
/// succeeded, the versions disagreed, and doctor reported `Fail` on exactly the
/// upgrade those phases exist to produce.
/// Test: this test.
#[test]
fn unknown_when_downloader_replaced_the_cargo_install() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    // Ledger records tm 1.3.1; the downloader wrote 1.4.0 over it in place.
    let (status, msg) = provenance_report(
        "tm",
        "1.4.0",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(
        status,
        CheckStatus::Unknown,
        "a successful cargo-free upgrade must not read as a health failure: {msg}"
    );
    assert!(
        msg.contains("NEWER"),
        "message must name the direction: {msg}"
    );
    assert!(
        msg.contains("prebuilt installer"),
        "message must name the likely writer: {msg}"
    );
    assert!(msg.contains("#4964"), "message: {msg}");
}

/// #8482: the same arm must not claim the binary is fresh.
///
/// Why: this message read "The binary is NOT stale" on the strength of a semver
/// comparison against cargo's registry ledger — and said it while the running
/// 1.7.0 lagged the source tree by nine hours and the daemon kept deploying
/// pre-fix skill assets. A check that confidently denies a live defect is worse
/// than one that stays quiet, so the claim is narrowed to what the comparison
/// actually reads and defers the source-tree question to `bundled_asset_lag`.
/// Reverting the message text fails here.
/// Test: this test.
#[test]
fn ledger_stale_message_claims_no_source_tree_freshness() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (_status, msg) = provenance_report(
        "tm",
        "1.4.0",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert!(
        !msg.contains("NOT stale"),
        "the row must not assert freshness it never checked: {msg}"
    );
    assert!(
        msg.contains("bundled_asset_lag"),
        "the row must name where the source-tree question is answered: {msg}"
    );
    assert!(msg.contains("#8482"), "message: {msg}");
}

/// The verdict must not change merely because #4964 moves the destination.
///
/// Why: the same downloader-placed file reports `Unknown` today from
/// `~/.local/bin` (it fails the path match). After Phase 3 it sits in
/// `$CARGO_HOME/bin` instead. Its provenance is exactly as verifiable in both
/// places — nothing about the binary changed — so the severity must not either.
/// This is the property that keeps Phase 3 from turning the owner's daily-driver
/// `tm doctor` red.
/// Test: this test.
#[test]
fn downloader_placed_binary_is_unknown_in_either_directory() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (before, before_msg) = provenance_report(
        "tm",
        "1.4.0",
        Path::new("/Users/masa/.local/bin/tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    let (after, after_msg) = provenance_report(
        "tm",
        "1.4.0",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(before, CheckStatus::Unknown, "pre-Phase-3: {before_msg}");
    assert_eq!(after, CheckStatus::Unknown, "post-Phase-3: {after_msg}");
    assert_eq!(
        before, after,
        "the destination flip must not change severity"
    );
}

/// A version pair that is not orderable stays a `Fail` — an unverifiable
/// mismatch is still a mismatch, and guessing a direction would be a claim.
#[test]
fn fails_when_versions_cannot_be_ordered() {
    let ledger = vec![CargoInstall {
        package: "trusty-mpm".into(),
        version: "not-a-version".into(),
        source: InstallSource::Registry,
        bins: vec!["tm".into()],
    }];
    let (status, msg) = provenance_report(
        "tm",
        "1.4.0",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Fail, "message: {msg}");
    assert!(msg.contains("cannot be ordered"), "message: {msg}");
}

#[test]
fn skew_is_ledger_stale_when_running_is_newer() {
    assert_eq!(
        classify_version_skew("1.3.1", "1.4.0"),
        VersionSkew::LedgerStale
    );
}

#[test]
fn skew_is_running_stale_when_ledger_is_newer() {
    assert_eq!(
        classify_version_skew("1.4.0", "1.3.1"),
        VersionSkew::RunningStale
    );
}

#[test]
fn skew_is_unordered_for_unparseable_versions() {
    // Either side unparseable, or an equal pair the caller should never send:
    // all three are "no direction", never a guessed one.
    assert_eq!(
        classify_version_skew("1.3", "1.4.0"),
        VersionSkew::Unordered,
        "a two-component version is not semver and must not be guessed at"
    );
    assert_eq!(
        classify_version_skew("1.3.1", "wat"),
        VersionSkew::Unordered
    );
    assert_eq!(
        classify_version_skew("1.3.1", "1.3.1"),
        VersionSkew::Unordered
    );
}

/// Pre-release ordering must follow semver, not string comparison.
///
/// Why: `1.4.0-rc.1` sorts AFTER `1.4.0` as a string and BEFORE it as a
/// version. A downgrade from `1.4.0` to `1.4.0-rc.1` is a real regression and
/// must stay `Fail`, not be excused as a stale ledger.
/// Test: this test.
#[test]
fn skew_orders_prereleases_by_semver_not_string() {
    assert_eq!(
        classify_version_skew("1.4.0", "1.4.0-rc.1"),
        VersionSkew::RunningStale
    );
    assert_eq!(
        classify_version_skew("1.4.0-rc.1", "1.4.0"),
        VersionSkew::LedgerStale
    );
}

#[test]
fn fails_when_path_source_is_gone() {
    // The `/Users/masa/tmp/` case: macOS reaped the source, so there is no
    // provenance AND no way to rebuild.
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "trusty-search",
        "0.39.0",
        &installed("trusty-search"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &never_exists,
    );
    assert_eq!(status, CheckStatus::Fail, "message: {msg}");
    assert!(msg.contains("NO LONGER EXISTS"), "message: {msg}");
}

#[test]
fn warns_for_a_live_path_install() {
    // Source still there: it works, but it bypasses update detection.
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "trusty-search",
        "0.39.0",
        &installed("trusty-search"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Warn, "message: {msg}");
    assert!(
        msg.contains("invisible to registry update"),
        "message: {msg}"
    );
}

#[test]
fn warns_for_a_git_install() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "slack-mcp",
        "0.1.0",
        &installed("slack-mcp"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Warn, "message: {msg}");
    assert!(msg.contains("git"), "message: {msg}");
}

#[test]
fn ok_for_a_matching_registry_install() {
    // The only clean state: registry source, versions agree.
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "tm",
        "1.3.1",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Ok, "message: {msg}");
    assert!(msg.contains("crates.io"), "message: {msg}");
}

/// #4622 review HIGH-2: a foreign binary must NOT inherit cargo's provenance.
///
/// Why: attribution was by BASENAME alone — `running_exe` only ever went into
/// the message string. On the #4033 host `which -a tm` returns
/// `~/.cargo/bin/tm` (1.3.1, the cargo install) and `~/.local/bin/tm` (0.19.29,
/// a prebuilt-installer drop). This test pins the harder half of that scenario:
/// the foreign binary's version COINCIDES with the ledger's, so the version
/// comparison cannot save the check. Before the fix it reported
/// `Ok — installed from crates.io; cargo's ledger agrees`.
/// Test: this test.
#[test]
fn unknown_when_running_binary_is_not_the_cargo_install() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    // Same basename, same version — only the PATH differs.
    let (status, msg) = provenance_report(
        "tm",
        "1.3.1",
        Path::new("/Users/masa/.local/bin/tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );

    assert_eq!(
        status,
        CheckStatus::Unknown,
        "a binary cargo did not install must never inherit the cargo record: {msg}"
    );
    assert!(msg.contains("/Users/masa/.local/bin/tm"), "message: {msg}");
    assert!(msg.contains("/Users/masa/.cargo/bin/tm"), "message: {msg}");
    assert!(
        msg.contains("which -a"),
        "message must name the diagnosis: {msg}"
    );
}

/// The control for the proof above: identical inputs except the running path,
/// which now IS the cargo install — the same ledger then reports Ok.
#[test]
fn ok_when_running_binary_is_the_cargo_install() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, msg) = provenance_report(
        "tm",
        "1.3.1",
        &installed("tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Ok, "message: {msg}");
}

/// A dev build run straight out of `target/debug` is also not the cargo
/// install, and must report UNKNOWN rather than borrow the record.
#[test]
fn unknown_for_a_build_run_in_place() {
    let ledger = parse_cargo_installs(LEDGER).unwrap();
    let (status, _msg) = provenance_report(
        "tm",
        "1.3.1",
        Path::new("/repo/target/debug/tm"),
        Path::new(CARGO_BIN),
        Some(&ledger),
        &always_exists,
    );
    assert_eq!(status, CheckStatus::Unknown);
}