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
//! Tests for [`super`] — `tm doctor --fix-skills`.
//!
//! Why: the three owner constraints on a fix mode (never silently overwrite a
//! frozen skill, always back up, always verify from disk) are safety rules, so
//! each gets a test that fails if the rule is removed. The deletion boundary is
//! asserted too: nothing this module touches may disappear.
//! What: one test per constraint plus the ordinary repair path.
//! Test: this file.

use super::*;
use crate::core::skill_deployer::deploy_skills;
use crate::core::skill_drift::{deployed_path, skill_reference};
use std::collections::BTreeMap;
use std::fs;
use tempfile::TempDir;

/// Build a reference map from literal (stem, content) pairs.
fn reference_of(pairs: &[(&str, &str)]) -> SkillReference {
    SkillReference {
        assets: pairs
            .iter()
            .map(|(s, c)| (s.to_string(), c.to_string()))
            .collect::<BTreeMap<_, _>>(),
        origin: "this binary's embedded bundled assets".to_string(),
    }
}

/// Deploy `stem` into `dest` THROUGH THE REAL DEPLOYER (#4622 review, HIGH-1).
///
/// Why: the previous helper hand-wrote bare-stem manifest keys, a shape
/// production never produces — `deploy_skills` also records nested
/// `<stem>/references/<file>.md` keys. A repair fixture that cannot contain one
/// cannot prove the repair writes them to the right place.
/// What: writes the source tree, runs the real deploy, returns the source dir.
/// Test: every test in this file.
fn deploy_real(dest: &Path, stem: &str, body: &str, reference: Option<(&str, &str)>) -> TempDir {
    let src = TempDir::new().unwrap();
    fs::write(src.path().join(format!("{stem}.md")), body).unwrap();
    if let Some((ref_name, ref_body)) = reference {
        let refs = src.path().join(stem).join("references");
        fs::create_dir_all(&refs).unwrap();
        fs::write(refs.join(ref_name), ref_body).unwrap();
    }
    deploy_skills(src.path(), dest).unwrap();
    src
}

/// Hand-edit a deployed file after a real deploy — the only honest way to
/// construct the FROZEN state (the manifest still records what tm wrote).
fn hand_edit(dest: &Path, manifest_key: &str, new_content: &str) {
    fs::write(deployed_path(dest, manifest_key), new_content).unwrap();
}

/// A `FrameworkPaths` rooted entirely under one temp dir, with no submodule.
fn paths_under(tmp: &TempDir) -> FrameworkPaths {
    let mut paths = FrameworkPaths::under(tmp.path());
    paths.trusty_mpm_root = None;
    paths
}

/// #7423: `tm doctor --fix` deploys a bundled skill that reached NO tier, into
/// the managed tier and nowhere else.
///
/// Why: the audit only knew the on-disk ledger, so a brand-new bundled skill was
/// invisible to the repair — `tm-prose-style` shipped in 1.5.29 and landed
/// nowhere. The second half of the assertion is the #6586 ruling: the operator
/// home must stay empty of it. Fails on `origin/main`, where no outcome is
/// produced for the skill at all.
/// Test: this test.
#[test]
fn repair_deploys_a_bundled_skill_that_reached_no_tier() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let managed = paths.skill_deploy_dir();
    // Both tiers exist and are tm-owned, but neither holds the new skill.
    let _managed_src = deploy_real(&managed, "tm-workflow", "v1", None);
    let _home_src = deploy_real(&paths.claude_skills_dir(), "tm-workflow", "v1", None);

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v1"), ("tm-prose-style", "brand new")]),
        &paths,
        None,
        false,
        backups.path(),
    );

    let written: Vec<&RepairOutcome> = outcomes
        .iter()
        .filter(|o| o.stem == "tm-prose-style" && o.changed())
        .collect();
    assert_eq!(written.len(), 1, "outcomes: {outcomes:?}");
    assert_eq!(written[0].tier, "managed config");
    assert_eq!(
        fs::read_to_string(managed.join("tm-prose-style").join("SKILL.md")).unwrap(),
        "brand new"
    );
    // #6586: bundled skills are user-tier only — the repair must not start
    // deploying them into the operator's own `~/.claude/skills`.
    assert!(
        !paths.claude_skills_dir().join("tm-prose-style").exists(),
        "the repair must not deploy a bundled skill to the operator home tier"
    );
    // And the written copy is tm-owned, so the next audit reads it Fresh rather
    // than frozen.
    assert!(
        SkillManifest::load(&managed)
            .unwrap()
            .checksum_matches("tm-prose-style", "brand new")
    );
}

#[test]
fn repair_rewrites_drifted_and_verifies() {
    // The ordinary case: tm still owns the file, so the redeploy is safe. The
    // outcome is only `Repaired` because the content was READ BACK and matched.
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        false,
        backups.path(),
    );
    let repaired: Vec<&RepairOutcome> = outcomes.iter().filter(|o| o.changed()).collect();
    assert_eq!(repaired.len(), 1, "outcomes: {outcomes:?}");
    assert_eq!(repaired[0].stem, "tm-workflow");

    // Verified independently of the fix's own claim.
    let on_disk = fs::read_to_string(dest.join("tm-workflow").join("SKILL.md")).unwrap();
    assert_eq!(on_disk, "v2");

    // And the manifest was updated, so the file is tm-owned again rather than
    // reading as frozen on the next audit.
    assert!(
        SkillManifest::load(&dest)
            .unwrap()
            .checksum_matches("tm-workflow", "v2")
    );
}

/// #4622 review HIGH-1: a drifted REFERENCE FILE must be repaired at its own
/// nested path, not at `<stem>/SKILL.md`.
///
/// Why: manifest keys come in two shapes and the repair used to assume one.
/// Writing a `<stem>/references/<file>.md` key to `<stem>/SKILL.md` would
/// destroy the entry point while leaving the drifted reference untouched — a
/// repair that corrupts what it claims to fix.
/// Test: this test.
#[test]
fn repair_writes_a_nested_reference_key_to_its_own_path() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(
        &dest,
        "documentation-style",
        "entry v1",
        Some(("spec.md", "reference v1")),
    );

    // Only the reference sibling moved on in the binary.
    let outcomes = repair_skills(
        &reference_of(&[
            ("documentation-style", "entry v1"),
            ("documentation-style/references/spec.md", "reference v2"),
        ]),
        &paths,
        None,
        false,
        backups.path(),
    );

    let repaired: Vec<&RepairOutcome> = outcomes.iter().filter(|o| o.changed()).collect();
    assert_eq!(repaired.len(), 1, "outcomes: {outcomes:?}");
    assert_eq!(repaired[0].stem, "documentation-style/references/spec.md");

    // The reference file was rewritten at its OWN path…
    assert_eq!(
        fs::read_to_string(deployed_path(
            &dest,
            "documentation-style/references/spec.md"
        ))
        .unwrap(),
        "reference v2"
    );
    // …and the entry point was not touched.
    assert_eq!(
        fs::read_to_string(deployed_path(&dest, "documentation-style")).unwrap(),
        "entry v1"
    );
}

/// #4622 review: a tier whose ownership ledger cannot be parsed is never
/// written to.
///
/// Why: rebuilding a manifest over an unreadable one would reclassify every file
/// there as tm-owned, so the next ordinary deploy would overwrite the operator's
/// hand-edits — defeating the frozen-skill protection this whole mode exists to
/// respect.
/// Test: this test.
#[test]
fn repair_refuses_a_tier_with_an_unreadable_manifest() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);
    fs::write(
        dest.join(crate::core::skill_manifest::SKILL_MANIFEST_FILE),
        "{ not json",
    )
    .unwrap();

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        true,
        backups.path(),
    );

    assert!(
        outcomes.iter().all(|o| !o.changed()),
        "nothing may be written into a tier with an unreadable ledger: {outcomes:?}"
    );
    assert_eq!(
        fs::read_to_string(deployed_path(&dest, "tm-workflow")).unwrap(),
        "v1",
        "the deployed file must be untouched"
    );
}

/// CONSTRAINT 1: a frozen skill is NEVER silently overwritten.
#[test]
fn repair_never_touches_a_frozen_skill_by_default() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "what tm wrote", None);
    hand_edit(&dest, "tm-workflow", "hand-edited by the operator");

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        /* include_frozen */ false,
        backups.path(),
    );
    assert_eq!(outcomes.len(), 1);
    assert_eq!(outcomes[0].action, RepairAction::SkippedFrozen);

    // The operator's edit survives, byte for byte.
    let on_disk = fs::read_to_string(dest.join("tm-workflow").join("SKILL.md")).unwrap();
    assert_eq!(on_disk, "hand-edited by the operator");
}

/// CONSTRAINT 1 (opt-in half) + CONSTRAINT 2: with the explicit flag the frozen
/// file IS repaired, and the hand-edited content is backed up first.
#[test]
fn repair_backs_up_before_overwriting() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "what tm wrote", None);
    hand_edit(&dest, "tm-workflow", "hand-edited by the operator");

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        /* include_frozen */ true,
        backups.path(),
    );
    let RepairAction::Repaired { backup } = &outcomes[0].action else {
        panic!("expected a repair, got {:?}", outcomes[0].action);
    };
    let backup = backup.as_ref().expect("an existing file must be backed up");
    assert_eq!(
        fs::read_to_string(backup).unwrap(),
        "hand-edited by the operator",
        "the backup must hold the operator's original content"
    );
    assert_eq!(
        fs::read_to_string(dest.join("tm-workflow").join("SKILL.md")).unwrap(),
        "v2"
    );
}

/// CONSTRAINT 3: the repair verifies from DISK, so a write that did not land is
/// reported as a failure rather than as success.
///
/// Why: reporting success from a write's return value — without re-reading — is
/// the exact failure that produced #4604. Here the skill directory is made
/// unwritable, so the audit still classifies the skill as `Drifted` (the file
/// reads fine) but the write cannot land; the outcome must be `Failed`.
#[cfg(unix)]
#[test]
fn repair_reports_verification_failure() {
    use std::os::unix::fs::PermissionsExt;

    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);

    let skill_dir = dest.join("tm-workflow");
    fs::set_permissions(&skill_dir, fs::Permissions::from_mode(0o500)).unwrap();
    // Precondition: the environment must actually be able to deny the write
    // (running as root defeats mode bits). If it cannot, the scenario under
    // test does not exist here, so restore and skip rather than assert a
    // failure that could not occur.
    let deniable = fs::write(skill_dir.join(".probe"), "x").is_err();
    if !deniable {
        let _ = fs::remove_file(skill_dir.join(".probe"));
        fs::set_permissions(&skill_dir, fs::Permissions::from_mode(0o755)).unwrap();
        return;
    }

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        true,
        backups.path(),
    );
    fs::set_permissions(&skill_dir, fs::Permissions::from_mode(0o755)).unwrap();

    assert!(
        matches!(outcomes[0].action, RepairAction::Failed(_)),
        "got {:?}",
        outcomes[0].action
    );
    assert!(!outcomes[0].changed());
    // And the original content is still there — a failed repair destroys nothing.
    assert_eq!(
        fs::read_to_string(skill_dir.join("SKILL.md")).unwrap(),
        "v1"
    );
}

/// An unverifiable skill is never repaired — there is nothing to write.
#[test]
fn repair_skips_unverifiable_skills() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "my-custom-skill", "operator content", None);

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        true,
        backups.path(),
    );
    assert!(
        matches!(outcomes[0].action, RepairAction::SkippedUnverifiable(_)),
        "got {:?}",
        outcomes[0].action
    );
    assert_eq!(
        fs::read_to_string(dest.join("my-custom-skill").join("SKILL.md")).unwrap(),
        "operator content"
    );
}

/// A fresh skill produces no outcome and no write at all.
#[test]
fn repair_is_a_noop_when_everything_matches() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let _src = deploy_real(&paths.claude_skills_dir(), "tm-workflow", "v2", None);

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        false,
        backups.path(),
    );
    assert!(outcomes.is_empty(), "outcomes: {outcomes:?}");
    assert!(
        !backups.path().join("operator-home").exists(),
        "a no-op run must not create backup directories"
    );
}

/// HARD BOUNDARY: the repair never removes anything.
///
/// Why: `tm doctor` reports orphaned worktrees and undercounted worktree disk;
/// those stay report-only. On 2026-07-21 an `rm -rf .base/*` orphaned ~70
/// worktrees across concurrent sessions. This asserts the fix path leaves every
/// pre-existing file in place, including files it does not manage.
#[test]
fn repair_deletes_nothing() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);
    // A bystander file and a bystander directory the repair has no business with.
    fs::write(dest.join("README.md"), "operator note").unwrap();
    fs::create_dir_all(dest.join("unrelated-dir")).unwrap();
    fs::write(dest.join("unrelated-dir").join("keep.txt"), "keep").unwrap();

    repair_skills(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        true,
        backups.path(),
    );

    assert!(dest.join("README.md").exists());
    assert!(dest.join("unrelated-dir").join("keep.txt").exists());
    assert!(dest.join("tm-workflow").join("SKILL.md").exists());
}

#[test]
fn backup_root_follows_the_remediation_convention() {
    let now = chrono::DateTime::parse_from_rfc3339("2026-08-02T13:45:06Z")
        .unwrap()
        .with_timezone(&chrono::Utc);
    let root = backup_root_for(Path::new("/home/x"), now);
    assert_eq!(
        root,
        Path::new("/home/x/.trusty-mpm/backup-doctor-remediation-20260802-134506")
    );
}

/// The real embedded reference must be usable by the repair path, not just the
/// literal fixtures the other tests use.
#[test]
fn embedded_reference_is_usable_as_a_repair_source() {
    let reference = skill_reference(None, Some(crate::core::content_source::test_support::rc()));
    assert!(
        reference.assets.contains_key("tm-workflow"),
        "the binary must embed tm-workflow for --fix-skills to repair it"
    );
    assert!(!reference.assets["tm-workflow"].is_empty());
}

/// #4881: a tier directory that does not exist must stay non-existent.
///
/// Why: taking the ledger lock creates the directory and a lock sidecar. A
/// repair over a project with no `.claude/skills/` would then leave both behind
/// in a tree `tm doctor` was only inspecting. Such a tier has no ledger and so
/// no findings — skipping it before the lock is behaviour-preserving.
#[test]
fn repair_leaves_a_missing_tier_directory_alone() {
    let home = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = paths_under(&home);
    let backups = TempDir::new().unwrap();

    let outcomes = repair_skills(
        &reference_of(&[("tm-workflow", "v1")]),
        &paths,
        Some(project.path()),
        false,
        backups.path(),
    );

    assert!(
        outcomes.is_empty(),
        "a tier with no directory has no findings: {outcomes:?}"
    );
    let skills_dir = project.path().join(".claude").join("skills");
    assert!(
        !skills_dir.exists(),
        "repair must not create a skills directory it was only inspecting"
    );
}

/// #4948: a dry run reports exactly the set an apply would rewrite.
///
/// Why: the preview is only worth trusting if it is produced by the code that
/// performs the repair. This asserts the two agree on the SET — same tiers,
/// same stems, same order — which is what a separate planner would eventually
/// get wrong.
#[test]
fn dry_run_reports_the_same_set_it_would_repair() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);
    let reference = reference_of(&[("tm-workflow", "v2")]);

    let previewed = repair_skills_in_mode(
        &reference,
        &paths,
        None,
        false,
        backups.path(),
        RepairMode::DryRun,
    );
    assert_eq!(previewed.len(), 1, "{previewed:?}");
    assert_eq!(
        previewed[0].action,
        RepairAction::WouldRepair { existed: true }
    );
    assert_eq!(previewed[0].path, dest.join("tm-workflow").join("SKILL.md"));
    assert!(
        !previewed[0].changed(),
        "a preview never counts as a change"
    );

    let applied = repair_skills(&reference, &paths, None, false, backups.path());
    let previewed_keys: Vec<_> = previewed
        .iter()
        .map(|o| (o.tier, &o.stem, &o.path))
        .collect();
    let applied_keys: Vec<_> = applied.iter().map(|o| (o.tier, &o.stem, &o.path)).collect();
    assert_eq!(
        previewed_keys, applied_keys,
        "the preview and the apply disagreed about what to repair"
    );
}

/// #4948: the dry run writes NOTHING — not the skill, not a backup, not the
/// ledger.
///
/// Why: `--fix` defaults to this mode, so "changes nothing" is the entire
/// safety claim. It is asserted against the filesystem, not against the
/// function's own report.
#[test]
fn dry_run_writes_absolutely_nothing() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);

    let skill = dest.join("tm-workflow").join("SKILL.md");
    let manifest_before =
        fs::read(dest.join(crate::core::skill_manifest::SKILL_MANIFEST_FILE)).unwrap();

    repair_skills_in_mode(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        true,
        backups.path(),
        RepairMode::DryRun,
    );

    assert_eq!(
        fs::read_to_string(&skill).unwrap(),
        "v1",
        "the dry run rewrote the skill"
    );
    assert_eq!(
        fs::read(dest.join(crate::core::skill_manifest::SKILL_MANIFEST_FILE)).unwrap(),
        manifest_before,
        "the dry run rewrote the ownership ledger"
    );
    assert!(
        !backups.path().join("operator-home").exists(),
        "the dry run took a backup, which is itself a write"
    );
}

/// #4948: a FROZEN (hand-edited) skill is refused in the preview too.
///
/// Why: the preview must not promise a repair the apply path would skip — an
/// operator reading "would be overwritten" about their own hand-edited file
/// and then finding it untouched has been told two wrong things at once.
#[test]
fn dry_run_still_refuses_a_frozen_skill() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = paths.claude_skills_dir();
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);
    hand_edit(&dest, "tm-workflow", "the operator's own edit");

    let previewed = repair_skills_in_mode(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        None,
        false,
        backups.path(),
        RepairMode::DryRun,
    );
    assert_eq!(previewed.len(), 1, "{previewed:?}");
    assert_eq!(previewed[0].action, RepairAction::SkippedFrozen);
    assert_eq!(
        fs::read_to_string(dest.join("tm-workflow").join("SKILL.md")).unwrap(),
        "the operator's own edit"
    );
}

/// #6586 critic HIGH: a stem the stray sweep is removing must not be rewritten
/// by the redeploy that runs immediately after it.
///
/// Fails before this fix: the repair had no deferral, so the project-tier copy
/// was overwritten from the bundled asset and its ledger checksum re-stamped.
#[test]
fn a_deferred_project_stem_is_not_refreshed() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let dest = crate::core::skill_deploy_tiers::project_skill_tier(project.path());
    let _src = deploy_real(&dest, "tm-workflow", "v1", None);

    let deferred: BTreeSet<String> = ["tm-workflow".to_string()].into_iter().collect();
    let outcomes = repair_skills_in_mode_deferring(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        Some(project.path()),
        false,
        backups.path(),
        RepairMode::Apply,
        &deferred,
    );

    let deferred_outcome = outcomes
        .iter()
        .find(|o| o.stem == "tm-workflow" && o.tier == "project")
        .unwrap_or_else(|| panic!("expected a project-tier outcome: {outcomes:?}"));
    assert_eq!(
        deferred_outcome.action,
        RepairAction::SkippedUnverifiable(DEFERRED_TO_STRAY_SWEEP.to_string()),
        "{outcomes:?}"
    );
    assert_eq!(
        fs::read_to_string(deployed_path(&dest, "tm-workflow")).unwrap(),
        "v1",
        "the copy the sweep is removing must keep the bytes the sweep verified"
    );
    assert!(
        fs::read_dir(backups.path())
            .expect("backup root")
            .next()
            .is_none(),
        "a deferred stem is never backed up, because it is never overwritten"
    );
}

/// The deferral is scoped to the tier the sweep touches — the same stem
/// deployed at the operator's own tier is still repaired there.
#[test]
fn a_deferred_stem_is_still_repaired_at_the_user_tier() {
    let tmp = TempDir::new().unwrap();
    let backups = TempDir::new().unwrap();
    let project = TempDir::new().unwrap();
    let paths = paths_under(&tmp);
    let home = paths.claude_skills_dir();
    let _home_src = deploy_real(&home, "tm-workflow", "v1", None);
    let project_dest = crate::core::skill_deploy_tiers::project_skill_tier(project.path());
    let _project_src = deploy_real(&project_dest, "tm-workflow", "v1", None);

    let deferred: BTreeSet<String> = ["tm-workflow".to_string()].into_iter().collect();
    let outcomes = repair_skills_in_mode_deferring(
        &reference_of(&[("tm-workflow", "v2")]),
        &paths,
        Some(project.path()),
        false,
        backups.path(),
        RepairMode::Apply,
        &deferred,
    );

    assert_eq!(
        fs::read_to_string(deployed_path(&home, "tm-workflow")).unwrap(),
        "v2",
        "the user-tier copy is nobody's stray and must still be repaired: {outcomes:?}"
    );
    assert_eq!(
        fs::read_to_string(deployed_path(&project_dest, "tm-workflow")).unwrap(),
        "v1",
        "the project-tier copy is the deferred one: {outcomes:?}"
    );
}