trusty-mpm 1.5.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
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
//! Tests for [`super`] — the `tm doctor --fix` repair driver (issue #4948).
//!
//! Why: this command deletes and rewrites operator state, so each of its three
//! safety rules gets a test that fails if the rule is removed — dry run writes
//! nothing, a file tm does not own is refused, and `legacy_sources` findings
//! are never deleted. The "it actually repairs" tests are the easy half; the
//! refusals are the half worth having.
//! What: per repair, one apply test and one dry-run test, plus the ownership
//! refusals.
//! Test: this file.

use super::*;
use std::fs;

/// A settings file carrying one tm hook entry and one foreign (claude-mpm) one.
///
/// Why: the interesting case is the mixed file — the repair must strip tm's
/// entry and leave the other harness's alone. A tm-only fixture cannot show
/// that.
fn write_mixed_settings(project: &Path) -> PathBuf {
    let claude = project.join(".claude");
    fs::create_dir_all(&claude).unwrap();
    let path = claude.join("settings.json");
    fs::write(
        &path,
        serde_json::json!({
            "model": "opus",
            "hooks": {
                "PreToolUse": [
                    { "hooks": [{ "type": "command", "command": "tm hook" }] },
                    { "hooks": [{ "type": "command", "command": "claude-mpm hook" }] }
                ]
            }
        })
        .to_string(),
    )
    .unwrap();
    path
}

/// Create a real, minimal git repo in a hermetic temp dir.
///
/// Why: `push_guard` resolves its hooks directory by shelling out to `git
/// rev-parse --git-common-dir`, so a plain temp directory cannot exercise it.
/// Mirrors `core::push_guard`'s own helper, including the `None` return when
/// git is unavailable.
fn temp_repo() -> Option<(tempfile::TempDir, PathBuf)> {
    let dir = crate::test_support::hermetic_temp_dir();
    let path = dir.path().to_path_buf();
    let ok = std::process::Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .arg(&path)
        .status()
        .ok()?;
    ok.success().then_some((dir, path))
}

#[test]
fn mode_defaults_to_dry_run() {
    // The whole safety posture rests on this one conversion: a `--fix` with no
    // `--yes` must never reach a write path.
    assert_eq!(RepairMode::from_apply_flag(false), RepairMode::DryRun);
    assert_eq!(RepairMode::from_apply_flag(true), RepairMode::Apply);
}

#[test]
fn hooks_repair_applies_and_backs_up() {
    let tmp = tempfile::tempdir().unwrap();
    let path = write_mixed_settings(tmp.path());

    let steps = repair_hooks_contamination(tmp.path(), RepairMode::Apply);
    assert_eq!(steps.len(), 1, "{steps:?}");
    assert_eq!(steps[0].check, "hooks_contamination");
    assert_eq!(steps[0].path, path);
    assert!(steps[0].changed(), "{:?}", steps[0]);

    // Verified from disk, not from the repair's own claim.
    let after: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
    let groups = after["hooks"]["PreToolUse"].as_array().unwrap();
    let commands: Vec<&str> = groups
        .iter()
        .flat_map(|g| g["hooks"].as_array().unwrap())
        .map(|e| e["command"].as_str().unwrap())
        .collect();
    assert_eq!(
        commands,
        vec!["claude-mpm hook"],
        "only tm's own entry may be removed"
    );
    assert_eq!(after["model"], "opus", "unrelated keys must survive");

    // The backup the step reports must exist and hold the pre-repair bytes.
    let StepStatus::Applied { backup: Some(bak) } = &steps[0].status else {
        panic!("expected a backup path, got {:?}", steps[0].status);
    };
    assert!(
        fs::read_to_string(bak).unwrap().contains("tm hook"),
        "the backup must carry what was removed"
    );
}

#[test]
fn hooks_repair_dry_run_changes_nothing() {
    let tmp = tempfile::tempdir().unwrap();
    let path = write_mixed_settings(tmp.path());
    let before = fs::read(&path).unwrap();

    let steps = repair_hooks_contamination(tmp.path(), RepairMode::DryRun);
    assert_eq!(steps.len(), 1, "{steps:?}");
    assert_eq!(steps[0].status, StepStatus::Planned);
    assert!(!steps[0].changed());
    assert!(
        steps[0].what.contains("PreToolUse"),
        "the preview must name what it would remove: {}",
        steps[0].what
    );

    assert_eq!(fs::read(&path).unwrap(), before, "dry run rewrote the file");
    // And it must not have left a backup behind either — a backup is a write.
    let stray: Vec<_> = fs::read_dir(tmp.path().join(".claude"))
        .unwrap()
        .flatten()
        .filter(|e| e.file_name().to_string_lossy().contains(".bak"))
        .collect();
    assert!(stray.is_empty(), "dry run wrote a backup: {stray:?}");
}

#[test]
fn hooks_repair_leaves_foreign_entries_alone() {
    // A project carrying ONLY another harness's hooks has no tm contamination,
    // so the repair must produce no step at all — never a step that would
    // remove somebody else's configuration.
    let tmp = tempfile::tempdir().unwrap();
    let claude = tmp.path().join(".claude");
    fs::create_dir_all(&claude).unwrap();
    let path = claude.join("settings.json");
    let body = serde_json::json!({
        "hooks": { "Stop": [{ "hooks": [{ "command": "claude-mpm hook" }] }] }
    })
    .to_string();
    fs::write(&path, &body).unwrap();

    let steps = repair_hooks_contamination(tmp.path(), RepairMode::Apply);
    assert!(steps.is_empty(), "{steps:?}");
    assert_eq!(fs::read_to_string(&path).unwrap(), body);
}

#[test]
fn push_guard_repair_installs_when_missing() {
    let Some((_dir, repo)) = temp_repo() else {
        return;
    };
    let steps = repair_push_guard(&repo, RepairMode::Apply);
    assert_eq!(steps.len(), 1, "{steps:?}");
    assert_eq!(steps[0].check, "push_guard");
    assert!(steps[0].changed(), "{:?}", steps[0]);
    assert!(
        fs::read_to_string(&steps[0].path)
            .unwrap()
            .contains(crate::core::push_guard::HOOK_MARKER),
        "the guard must actually be on disk at the reported path"
    );

    // Idempotent: a second run has nothing to report.
    assert!(repair_push_guard(&repo, RepairMode::Apply).is_empty());
}

#[test]
fn push_guard_repair_dry_run_writes_nothing() {
    let Some((_dir, repo)) = temp_repo() else {
        return;
    };
    let steps = repair_push_guard(&repo, RepairMode::DryRun);
    assert_eq!(steps.len(), 1, "{steps:?}");
    assert_eq!(steps[0].status, StepStatus::Planned);
    assert!(
        !steps[0].path.exists(),
        "dry run installed the hook at {}",
        steps[0].path.display()
    );
}

#[test]
fn push_guard_repair_refuses_a_foreign_hook() {
    // The ownership rule: a `pre-push` tm did not write is never overwritten,
    // in either mode. This is the same judgement `inspect_pre_push_guard`
    // makes for the read-only doctor check, which is why there is one of it.
    let Some((_dir, repo)) = temp_repo() else {
        return;
    };
    let hooks = crate::core::push_guard::effective_hooks_dir(&repo).unwrap();
    fs::create_dir_all(&hooks).unwrap();
    let hook = hooks.join("pre-push");
    fs::write(&hook, "#!/bin/sh\n# somebody else's hook\n").unwrap();

    for mode in [RepairMode::DryRun, RepairMode::Apply] {
        let steps = repair_push_guard(&repo, mode);
        assert_eq!(steps.len(), 1, "{steps:?}");
        assert!(
            matches!(steps[0].status, StepStatus::Refused(_)),
            "{mode:?} must refuse a foreign hook, got {:?}",
            steps[0].status
        );
    }
    assert_eq!(
        fs::read_to_string(&hook).unwrap(),
        "#!/bin/sh\n# somebody else's hook\n",
        "the foreign hook was modified"
    );
}

#[test]
fn legacy_sources_are_refused_never_deleted() {
    // The check whose obvious repair must not ship. Every finding is reported
    // with its path and a reason, and every file survives — including one
    // hand-edited copy, which is precisely the case a name-based delete could
    // not have distinguished.
    let tmp = tempfile::tempdir().unwrap();
    let skills = tmp.path().join(".claude").join("skills");
    for stem in ["tm-workflow", "tm-doctor"] {
        let dir = skills.join(stem);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("SKILL.md"), "hand-edited by the operator").unwrap();
    }
    fs::create_dir_all(tmp.path().join(".trusty-mpm").join("claude-config")).unwrap();

    let steps = refuse_legacy_sources(tmp.path());
    assert_eq!(steps.len(), 3, "{steps:?}");
    for step in &steps {
        assert_eq!(step.check, "legacy_sources");
        assert!(
            matches!(step.status, StepStatus::Refused(_)),
            "every legacy_sources finding must be refused, got {:?}",
            step.status
        );
        assert!(!step.changed());
        assert!(step.path.exists(), "{} was deleted", step.path.display());
    }
    assert!(
        skills.join("tm-workflow").join("SKILL.md").is_file(),
        "the hand-edited copy must survive verbatim"
    );
}

#[test]
fn legacy_sources_ignores_a_foreign_skill() {
    // Only `tm-*` entries are trusty-mpm's. An unrelated user skill in the
    // same directory must not even be mentioned.
    let tmp = tempfile::tempdir().unwrap();
    let skills = tmp.path().join(".claude").join("skills");
    fs::create_dir_all(skills.join("my-own-skill")).unwrap();

    assert!(refuse_legacy_sources(tmp.path()).is_empty());
}

#[test]
fn legacy_sources_is_empty_on_a_clean_home() {
    let tmp = tempfile::tempdir().unwrap();
    assert!(refuse_legacy_sources(tmp.path()).is_empty());
}

// ── #5866: the output-style repair ──────────────────────────────────────────

/// Deploy every bundled style into `<home>/.claude/output-styles/`.
fn deploy_styles(home: &Path) {
    crate::core::output_style_deployer::deploy_output_styles(&home.join(".claude")).unwrap();
}

/// The path of one bundled style under `<home>/.claude/output-styles/`.
fn style_path(home: &Path, index: usize) -> PathBuf {
    home.join(".claude")
        .join("output-styles")
        .join(crate::core::bundle::OUTPUT_STYLES[index].file_name)
}

/// The remedy string and the repair that honours it must not drift apart.
#[test]
fn output_style_remedy_names_the_fix_command() {
    assert_eq!(OUTPUT_STYLE_REMEDY, "tm doctor --fix --yes");
    assert!(
        !OUTPUT_STYLE_REMEDY.contains("tm install"),
        "#5866: `tm install` has no output-style step"
    );
}

#[test]
fn output_style_repair_is_empty_when_in_sync() {
    let home = tempfile::tempdir().unwrap();
    deploy_styles(home.path());
    assert!(
        repair_output_style(home.path(), RepairMode::DryRun).is_empty(),
        "an in-sync tier produces no step, so `--fix` prints nothing about it"
    );
}

#[test]
fn output_style_repair_plans_the_drifted_file() {
    let home = tempfile::tempdir().unwrap();
    deploy_styles(home.path());
    let target = style_path(home.path(), 0);
    fs::write(&target, "stale text").unwrap();

    let steps = repair_output_style(home.path(), RepairMode::DryRun);
    assert_eq!(steps.len(), 1, "{steps:?}");
    assert_eq!(steps[0].check, "output_style_staleness");
    assert_eq!(steps[0].path, target);
    assert_eq!(steps[0].status, StepStatus::Planned);
}

#[test]
fn output_style_repair_dry_run_writes_nothing() {
    let home = tempfile::tempdir().unwrap();
    deploy_styles(home.path());
    let target = style_path(home.path(), 0);
    fs::write(&target, "stale text").unwrap();

    repair_output_style(home.path(), RepairMode::DryRun);

    assert_eq!(
        fs::read_to_string(&target).unwrap(),
        "stale text",
        "a dry run must leave the file exactly as it found it"
    );
}

/// The repair reports from DISK, and it fixes an absent file too — the state
/// `check_output_style`'s own remedy string pointed at `tm install` for.
#[test]
fn output_style_repair_applies_and_reports_from_disk() {
    let home = tempfile::tempdir().unwrap();
    deploy_styles(home.path());
    let drifted = style_path(home.path(), 0);
    let missing = style_path(home.path(), 1);
    fs::write(&drifted, "stale text").unwrap();
    fs::remove_file(&missing).unwrap();

    let steps = repair_output_style(home.path(), RepairMode::Apply);

    assert_eq!(steps.len(), 2, "{steps:?}");
    assert!(
        steps.iter().all(RepairStep::changed),
        "both a drifted and an absent style must be written: {steps:?}"
    );
    assert_eq!(
        fs::read_to_string(&drifted).unwrap(),
        crate::core::bundle::OUTPUT_STYLES[0].content
    );
    assert_eq!(
        fs::read_to_string(&missing).unwrap(),
        crate::core::bundle::OUTPUT_STYLES[1].content
    );
    assert!(
        repair_output_style(home.path(), RepairMode::DryRun).is_empty(),
        "the repair must actually clear the finding it reported"
    );
}

/// A write that succeeded must report as a write, whatever a sibling did.
///
/// Why (#5866): the repair took the deploy's whole-batch `Err` as every step's
/// status, so one unreadable style made a DIFFERENT style read `Failed` after
/// being correctly rewritten to bundled content on disk. That is #5865's
/// complaint — a report that contradicts the disk, leaving an operator re-running
/// `tm doctor --fix` against a status that will not move — reintroduced by the
/// #5866 fix.
/// What: drifts `OUTPUT_STYLES[0]`, makes `OUTPUT_STYLES[1]` unreadable, applies
/// the repair, and asserts the drifted step is `Applied` with bundled content on
/// disk while only the unreadable one is refused.
/// Test: this function IS the test.
#[cfg(unix)]
#[test]
fn one_unreadable_style_does_not_fail_a_sibling_that_was_written() {
    use std::os::unix::fs::PermissionsExt;
    let home = tempfile::tempdir().unwrap();
    deploy_styles(home.path());
    let drifted = style_path(home.path(), 0);
    let blocked = style_path(home.path(), 1);
    fs::write(&drifted, "stale text").unwrap();
    fs::set_permissions(&blocked, fs::Permissions::from_mode(0o000)).unwrap();
    if fs::read(&blocked).is_ok() {
        eprintln!("skipping: cannot deny read on this platform/privilege level");
        return;
    }

    let steps = repair_output_style(home.path(), RepairMode::Apply);
    let _ = fs::set_permissions(&blocked, fs::Permissions::from_mode(0o600));

    let drifted_step = steps
        .iter()
        .find(|s| s.path == drifted)
        .unwrap_or_else(|| panic!("the drifted style must produce a step: {steps:?}"));
    assert_eq!(
        drifted_step.status,
        StepStatus::Applied { backup: None },
        "a style that was rewritten must report as written: {steps:?}"
    );
    assert_eq!(
        fs::read_to_string(&drifted).unwrap(),
        crate::core::bundle::OUTPUT_STYLES[0].content,
        "and the report must match what is on disk"
    );

    let blocked_step = steps
        .iter()
        .find(|s| s.path == blocked)
        .unwrap_or_else(|| panic!("the unreadable style must produce a step: {steps:?}"));
    assert!(
        matches!(blocked_step.status, StepStatus::Refused(_)),
        "the unreadable style owns its own outcome: {steps:?}"
    );
    assert!(
        !steps
            .iter()
            .any(|s| matches!(s.status, StepStatus::Failed(_))),
        "no step may inherit a sibling's failure: {steps:?}"
    );
}

/// Fail-open guard: a read failure is not evidence of staleness, so the repair
/// refuses rather than overwriting a file it could not inspect.
#[cfg(unix)]
#[test]
fn output_style_repair_refuses_an_unreadable_file() {
    use std::os::unix::fs::PermissionsExt;
    let home = tempfile::tempdir().unwrap();
    deploy_styles(home.path());
    let target = style_path(home.path(), 0);
    fs::set_permissions(&target, fs::Permissions::from_mode(0o000)).unwrap();
    if fs::read(&target).is_ok() {
        eprintln!("skipping: cannot deny read on this platform/privilege level");
        return;
    }

    let steps = repair_output_style(home.path(), RepairMode::Apply);
    let _ = fs::set_permissions(&target, fs::Permissions::from_mode(0o600));

    assert_eq!(steps.len(), 1, "{steps:?}");
    assert!(
        matches!(steps[0].status, StepStatus::Refused(_)),
        "an unreadable file must be refused, never overwritten: {steps:?}"
    );
    assert!(!steps[0].changed());
}