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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
//! Tests for #7660: decommission's `--force` excuse and kept-workspace reason.
//!
//! Why: `--force` narrows a data-safety gate, so every arm that must still keep
//! the workspace — user work, unpushed commits, a check that cannot run — needs
//! its own test against a real git worktree.
//! What: [`remove_in_project_worktree`] on [`GitWorktreeFixture`] trees dirtied
//! the way `tm session start` provisioning dirties them.
//! Test: this file IS the test module.

use std::path::{Path, PathBuf};

use super::*;
use crate::core::agent::DelegationId;
use crate::core::session::SessionId;
use crate::session_manager::decommission::WORKTREE_SENTINEL_FILE;
use crate::session_manager::provisioning_ledger;
use crate::session_manager::worktree_git_fixture::{GitWorktreeFixture, deny_all};
use crate::session_manager::worktree_ownership::{
    AgentWorktreeOwner, sentinel_payload_bytes, write_agent_sentinel,
};
use crate::session_manager::worktree_ownership_location::{
    admin_sentinel_path, write_sentinel_bytes,
};

/// Mark `wt` as tm-created the way provisioning does since #8511: the marker
/// goes into the git admin dir, never the working tree.
fn mark_owned(wt: &Path) {
    write_sentinel_bytes(wt, b"").expect("write the admin-dir marker");
}

/// The admin-dir marker path of `wt`, which must resolve.
fn admin_marker(wt: &Path) -> PathBuf {
    admin_sentinel_path(wt).expect("the admin dir resolves")
}

/// A pushed worktree carrying the ownership marker and a tracked
/// `.gitignore`, then dirtied exactly as the issue's `git status` showed:
/// ` M .gitignore`, `?? .claude/settings.json`, `?? .claude/settings.json.bak`,
/// `?? CLAUDE.md`. The provisioning ledger records those writes, as a launch
/// records them (#8540).
fn provisioned_tree(fx: &GitWorktreeFixture, name: &str) -> PathBuf {
    let wt = fx.add_worktree(name);
    std::fs::write(wt.join(".gitignore"), "target/\n").expect("write .gitignore");
    GitWorktreeFixture::commit_all_and_push(&wt, "track .gitignore");
    mark_owned(&wt);
    let before = provisioning_ledger::snapshot(&wt);
    // #7660: the real provisioning write, so the excused diff is the real one.
    crate::core::scaffold_gitignore::append_legacy_block(&wt);
    std::fs::create_dir_all(wt.join(".claude")).expect("mkdir .claude");
    std::fs::write(wt.join(".claude/settings.json"), "{}\n").expect("write settings");
    std::fs::write(wt.join(".claude/settings.json.bak"), "{}\n").expect("write settings bak");
    std::fs::write(wt.join("CLAUDE.md"), "# tm\n").expect("write CLAUDE.md");
    assert!(
        provisioning_ledger::record(&wt, &before).expect("record the ledger"),
        "premise: the worktree has an admin dir for the ledger"
    );
    wt
}

/// The provisioning ledger path of `wt` (#8540).
fn ledger_file(wt: &Path) -> PathBuf {
    admin_marker(wt)
        .parent()
        .expect("the marker has a parent")
        .join(provisioning_ledger::LEDGER_NAME)
}

/// A `.claude/settings.json` snapshot named the way `snapshot_then_prune`
/// names one (#8688).
const SETTINGS_SNAPSHOT: &str = ".claude/settings.json.20260926T140608Z.bak";

/// The session task every fixture record carries; `write_task_md` writes it
/// to `TASK.md` verbatim (#8688).
const TASK: &str = "Fix the bug\n";

/// [`provisioned_tree`] plus the two files a task-bearing spawn adds (#8688):
/// `TASK.md` holding [`TASK`] and a timestamped `.claude/settings.json`
/// snapshot.
fn task_bearing_tree(fx: &GitWorktreeFixture, name: &str) -> PathBuf {
    let wt = provisioned_tree(fx, name);
    std::fs::write(wt.join("TASK.md"), TASK).expect("write TASK.md");
    std::fs::write(wt.join(SETTINGS_SNAPSHOT), "{}\n").expect("write the snapshot");
    wt
}

/// The file count a kept reason states and the entries it lists (#8688).
fn count_and_list(reason: &str) -> (usize, Vec<String>) {
    let (head, _) = reason
        .split_once(" uncommitted/untracked file(s)")
        .expect("the reason states a file count");
    let count = head
        .rsplit(|c: char| !c.is_ascii_digit())
        .next()
        .and_then(|n| n.parse().ok())
        .expect("a numeric count");
    let listed = reason
        .split_once("unpushed commit(s): ")
        .and_then(|(_, rest)| rest.split_once(')'))
        .map(|(list, _)| list.split(", ").map(str::to_string).collect())
        .unwrap_or_default();
    (count, listed)
}

async fn remove(wt: &Path, policy: ProvisioningDirt) -> WorkspaceVerdict {
    remove_as(&ManagedSessionId::new(), wt, policy).await
}

/// [`remove`] as the session `id`, for the tests whose marker names an owner.
/// The session's record carries [`TASK`].
async fn remove_as(id: &ManagedSessionId, wt: &Path, policy: ProvisioningDirt) -> WorkspaceVerdict {
    remove_in_project_worktree(id, Some(TASK), wt, policy).await
}

#[test]
fn provisioning_entry_matches_only_the_four_paths_in_provisioning_states() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-entry-7660");
    let is = |line: &str| is_provisioning_entry(&wt, None, line);
    assert!(is(" M .gitignore"));
    assert!(is("?? .claude/settings.json"));
    assert!(is("?? .claude/settings.json.bak"));
    assert!(is("?? CLAUDE.md"));
    assert!(!is("M  .gitignore"), "a staged change is not provisioning");
    assert!(!is(" D CLAUDE.md"), "a deletion is not provisioning");
    assert!(
        !is(" M CLAUDE.md"),
        "an edit to a tracked CLAUDE.md is not provisioning"
    );
    assert!(
        !is(" M .claude/settings.json"),
        "an edit to a tracked settings file is not provisioning"
    );
    assert!(!is("?? .claude/"), "a collapsed directory hides its files");
    assert!(!is("?? src/main.rs"));
}

/// 🔴 #7660 critic HIGH-2: a repository that tracks `CLAUDE.md` shows an
/// agent's edit as ` M CLAUDE.md`, and `--force` must keep that tree. Fails
/// before the fix, which excused any ` M` on the four paths and removed it.
#[tokio::test]
async fn force_decommission_keeps_an_edited_tracked_claude_md() {
    let fx = GitWorktreeFixture::new();
    let wt = fx.add_worktree("decom-force-claude-md-7660");
    std::fs::write(wt.join("CLAUDE.md"), "# project rules\n").expect("write CLAUDE.md");
    GitWorktreeFixture::commit_all_and_push(&wt, "track CLAUDE.md");
    std::fs::write(wt.join("CLAUDE.md"), "# project rules\n- a new rule\n")
        .expect("edit CLAUDE.md");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(
        !verdict.removed,
        "an edited tracked CLAUDE.md must keep the tree"
    );
    assert_eq!(
        std::fs::read_to_string(wt.join("CLAUDE.md")).expect("read CLAUDE.md"),
        "# project rules\n- a new rule\n",
        "the edit must survive"
    );
    assert!(verdict.kept_reason.is_some());
}

/// 🔴 #7660 critic HIGH-2: a `.gitignore` diff carrying one line provisioning
/// never writes keeps the tree under `--force`. Fails before the fix, which
/// excused ` M .gitignore` whatever its diff held.
#[tokio::test]
async fn force_decommission_keeps_a_gitignore_with_a_non_provisioning_line() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-force-gitignore-7660");
    let mut body = std::fs::read_to_string(wt.join(".gitignore")).expect("read .gitignore");
    body.push_str("secrets.env\n");
    std::fs::write(wt.join(".gitignore"), &body).expect("append a user line");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(
        !verdict.removed,
        "a user's .gitignore line must keep the tree"
    );
    assert!(
        std::fs::read_to_string(wt.join(".gitignore"))
            .expect("read .gitignore")
            .contains("secrets.env"),
        "the user's line must survive"
    );
}

/// #7660 error arm: without `--force` the provisioned tree is kept, and the
/// reason names the blocker and the flag. Fails before #7660, which kept the
/// tree with no reason at all and let the CLI exit 0.
#[tokio::test]
async fn decommission_reports_why_it_kept_a_provisioned_worktree() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-refuse-7660");

    let verdict = remove(&wt, ProvisioningDirt::Refuse).await;

    assert!(!verdict.removed && wt.exists());
    let reason = verdict.kept_reason.expect("a kept workspace must say why");
    assert!(reason.contains("--force"), "reason: {reason}");
}

/// #8540: the plain refusal names the untracked `CLAUDE.md` and
/// `.claude/settings.json`, and no longer warns that `--force` deletes them
/// unread — `--force` now checks their content.
#[tokio::test]
async fn decommission_refusal_names_the_untracked_claude_files() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-refuse-names-8540");

    let verdict = remove(&wt, ProvisioningDirt::Refuse).await;

    assert!(!verdict.removed && wt.exists());
    let reason = verdict.kept_reason.expect("a kept workspace must say why");
    for entry in ["?? CLAUDE.md", "?? .claude/settings.json"] {
        assert!(reason.contains(entry), "reason: {reason}");
    }
    assert!(reason.contains("unedited CLAUDE.md"), "reason: {reason}");
    assert!(!reason.contains("WARNING"), "reason: {reason}");
}

/// #8540: the three ledger-checked files are excused only while their bytes
/// equal what the ledger recorded. Fails before #8540, which excused
/// `?? CLAUDE.md`, `?? .claude/settings.json` and `?? .claude/settings.json.bak`
/// by path whatever they held.
#[test]
fn provisioning_entry_excuses_claude_files_only_as_the_ledger_recorded_them() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-entry-ledger-8540");
    let is = |line: &str| is_provisioning_entry(&wt, None, line);
    for rel in [
        "CLAUDE.md",
        ".claude/settings.json",
        ".claude/settings.json.bak",
    ] {
        let line = format!("?? {rel}");
        assert!(is(&line), "premise: tm's own {rel} is excused");
        let mut body = std::fs::read(wt.join(rel)).expect("read");
        body.extend_from_slice(b"# a user's note\n");
        std::fs::write(wt.join(rel), &body).expect("edit");
        assert!(!is(&line), "an edited {rel} is not provisioning");
    }
}

/// FAIL-CLOSED (#8540 critic): a `CLAUDE.md` that is a FIFO or a symlink is
/// not the file tm wrote, and is never read. Fails before the regular-file
/// check, which blocked forever opening the FIFO and followed the symlink to
/// bytes matching the ledger.
#[test]
fn provisioning_entry_refuses_a_claude_md_that_is_not_a_regular_file() {
    use std::os::unix::ffi::OsStrExt as _;
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-entry-fifo-8540");
    let claude_md = wt.join("CLAUDE.md");
    std::fs::rename(&claude_md, wt.join("tm-wrote.md")).expect("move the bytes aside");
    std::os::unix::fs::symlink("tm-wrote.md", &claude_md).expect("symlink CLAUDE.md");
    assert!(
        !is_provisioning_entry(&wt, None, "?? CLAUDE.md"),
        "a symlink is not the file tm wrote"
    );
    std::fs::remove_file(&claude_md).expect("drop the symlink");
    let c = std::ffi::CString::new(claude_md.as_os_str().as_bytes()).expect("no NUL");
    // SAFETY: `c` is a valid NUL-terminated path that outlives the call.
    assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o600) }, 0, "mkfifo");
    let (tx, rx) = std::sync::mpsc::channel();
    let probe = wt.clone();
    std::thread::spawn(move || {
        let _ = tx.send(is_provisioning_entry(&probe, None, "?? CLAUDE.md"));
    });
    let answer = rx.recv_timeout(std::time::Duration::from_secs(10));
    if answer.is_err() {
        // Release the blocked reader so the thread can finish.
        let _ = std::fs::OpenOptions::new().write(true).open(&claude_md);
    }
    assert_eq!(answer, Ok(false), "a FIFO is refused without being opened");
}

/// 🔴 #8540: notes a user appended to an untracked `CLAUDE.md` (Claude Code's
/// `#` memory shortcut) keep the worktree under `--force`, survive
/// byte-for-byte, and the refusal says why. Fails at a791b467ee, which
/// excused `?? CLAUDE.md` by path and deleted the notes with the worktree.
#[tokio::test]
async fn force_decommission_keeps_notes_appended_to_an_untracked_claude_md() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-force-claude-notes-8540");
    let edited = "# tm\n- always run the gate twice\n";
    std::fs::write(wt.join("CLAUDE.md"), edited).expect("append a note");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(!verdict.removed, "an edited CLAUDE.md must keep the tree");
    assert_eq!(
        std::fs::read_to_string(wt.join("CLAUDE.md")).expect("CLAUDE.md survives"),
        edited,
        "the note survives untouched"
    );
    let reason = verdict.kept_reason.expect("a kept tree must say why");
    assert_eq!(
        count_and_list(&reason),
        (1, vec!["?? CLAUDE.md".to_string()]),
        "reason: {reason}"
    );
    assert!(
        reason.contains(
            "CLAUDE.md is not recorded in tm's provisioning ledger, or differs from what it \
             recorded, or the ledger could not be read, so --force kept the worktree and \
             deleted nothing"
        ),
        "reason: {reason}"
    );
}

/// FAIL-CLOSED (#8540): when the ledger cannot vouch for `CLAUDE.md` — it is
/// missing, corrupt, holds no entry for it, or `CLAUDE.md` cannot be read to
/// hash — `--force` keeps the worktree. Fails at a791b467ee, which never
/// consulted the ledger.
#[tokio::test]
async fn force_decommission_keeps_claude_md_when_the_ledger_cannot_vouch_for_it() {
    let fx = GitWorktreeFixture::new();
    for case in ["missing", "corrupt", "unrecorded", "unreadable"] {
        let wt = provisioned_tree(&fx, &format!("decom-force-ledger-{case}-8540"));
        let claude_md = wt.join("CLAUDE.md");
        let verdict = match case {
            "missing" => {
                std::fs::remove_file(ledger_file(&wt)).expect("drop the ledger");
                remove(&wt, ProvisioningDirt::Discard).await
            }
            "corrupt" => {
                std::fs::write(ledger_file(&wt), b"{not json").expect("corrupt the ledger");
                remove(&wt, ProvisioningDirt::Discard).await
            }
            "unrecorded" => {
                let bytes = std::fs::read(ledger_file(&wt)).expect("read the ledger");
                let mut ledger: serde_json::Value =
                    serde_json::from_slice(&bytes).expect("parse the ledger");
                let files = ledger["files"].as_object_mut().expect("a files map");
                assert!(
                    files.remove("CLAUDE.md").is_some(),
                    "premise: it was recorded"
                );
                std::fs::write(ledger_file(&wt), ledger.to_string()).expect("rewrite");
                remove(&wt, ProvisioningDirt::Discard).await
            }
            _ => {
                let _restore = deny_all(&claude_md);
                remove(&wt, ProvisioningDirt::Discard).await
            }
        };

        assert!(!verdict.removed, "{case}: the tree must be kept");
        assert_eq!(
            std::fs::read_to_string(&claude_md).expect("CLAUDE.md survives"),
            "# tm\n",
            "{case}"
        );
        let reason = verdict.kept_reason.expect("a kept tree must say why");
        assert!(reason.contains("?? CLAUDE.md"), "{case}: {reason}");
        assert!(reason.contains("deleted nothing"), "{case}: {reason}");
    }
}

/// The reported case: `--force` removes a tree dirty only from provisioning.
#[tokio::test]
async fn force_decommission_removes_a_provisioning_only_worktree() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-force-7660");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists(), "the workspace directory must be gone");
}

/// #8688: `TASK.md` and a timestamped settings snapshot are excused only
/// untracked, at their exact paths, in the snapshot's exact name shape.
#[test]
fn provisioning_entry_excuses_task_md_and_settings_snapshots_only_when_untracked() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-entry-8688");
    let is = |line: &str| is_provisioning_entry(&wt, Some(TASK), line);
    assert!(is("?? TASK.md"));
    assert!(is(&format!("?? {SETTINGS_SNAPSHOT}")));
    assert!(is("?? .claude/settings.json.20260926T140608Z-1.bak"));
    assert!(!is(" M TASK.md"), "an edit to a tracked TASK.md is work");
    assert!(!is("?? docs/TASK.md"));
    assert!(!is("?? .claude/settings.json.mine.bak"));
    assert!(!is("?? .claude/settings.local.json.20260926T140608Z.bak"));
    assert!(!is("?? settings.json.20260926T140608Z.bak"));
    assert!(!is("?? .claude/sub/settings.json.20260926T140608Z.bak"));
    assert!(!is(&format!(" M {SETTINGS_SNAPSHOT}")));
}

/// #8688: `?? TASK.md` is excused only when its bytes equal the session's
/// task — never with no record, an empty task, a different task, an edit, an
/// unreadable file, or a symlink in the file's place. Fails before the
/// content check, which excused `?? TASK.md` by path alone.
#[test]
fn provisioning_entry_excuses_task_md_only_when_it_equals_the_session_task() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-entry-task-8688");
    let task_md = wt.join("TASK.md");
    let is = |task: Option<&str>| is_provisioning_entry(&wt, task, "?? TASK.md");
    assert!(is(Some(TASK)));
    assert!(!is(None), "no record vouches for it");
    assert!(!is(Some("")), "a task-less record wrote no TASK.md");
    assert!(!is(Some("Fix the bug")), "one byte short is not tm's write");
    assert!(!is(Some("Another task\n")));
    {
        let _restore = deny_all(&task_md);
        assert!(!is(Some(TASK)), "an unreadable TASK.md is not excused");
    }
    std::fs::remove_file(&task_md).expect("drop TASK.md");
    std::fs::write(wt.join("brief.txt"), TASK).expect("write the link target");
    std::os::unix::fs::symlink("brief.txt", &task_md).expect("symlink TASK.md");
    assert!(!is(Some(TASK)), "a symlink is not the file tm wrote");
}

/// #8688 (c): the live report — a task-bearing managed worktree holding only
/// tm-written files, `TASK.md` still equal to the record's task, is removed
/// by `--force`. Fails before #8688, which kept it for `?? TASK.md` and
/// `?? .claude/settings.json.<ts>.bak`.
#[tokio::test]
async fn force_decommission_removes_a_worktree_holding_task_md_and_a_settings_snapshot() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-force-task-8688");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists(), "the workspace directory must be gone");
}

/// #8688 (a): notes an agent appended to `TASK.md` after spawn keep the
/// worktree under `--force`, and the refusal names the file. Fails before
/// the content check, which excused `?? TASK.md` by path and deleted them.
#[tokio::test]
async fn force_decommission_keeps_a_task_md_edited_after_spawn() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-force-task-edit-8688");
    let edited = format!("{TASK}\n## Notes\n- the cause is the stale cache\n");
    std::fs::write(wt.join("TASK.md"), &edited).expect("edit TASK.md");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(!verdict.removed, "an edited TASK.md must keep the worktree");
    let body = std::fs::read_to_string(wt.join("TASK.md")).expect("TASK.md survives");
    assert_eq!(body, edited, "the notes survive untouched");
    let reason = verdict.kept_reason.expect("reason");
    assert_eq!(
        count_and_list(&reason),
        (1, vec!["?? TASK.md".to_string()]),
        "reason: {reason}"
    );
}

/// #8688 (b): with no record to compare against, or a record with no task,
/// `TASK.md` keeps the worktree under `--force` and is named. Fails before
/// the content check, which excused `?? TASK.md` whatever the record held.
#[tokio::test]
async fn force_decommission_keeps_a_task_md_without_a_session_task() {
    let fx = GitWorktreeFixture::new();
    for (name, task) in [("none", None), ("empty", Some(""))] {
        let wt = task_bearing_tree(&fx, &format!("decom-force-task-{name}-8688"));

        let verdict = remove_in_project_worktree(
            &ManagedSessionId::new(),
            task,
            &wt,
            ProvisioningDirt::Discard,
        )
        .await;

        assert!(!verdict.removed && wt.join("TASK.md").exists(), "{name}");
        let reason = verdict.kept_reason.expect("reason");
        assert_eq!(
            count_and_list(&reason),
            (1, vec!["?? TASK.md".to_string()]),
            "{name}: {reason}"
        );
    }
}

/// `task` as `mark_errored` leaves the record's task after failing with `msg`
/// (#8688). The manager-level wire test drives the real `mark_errored`.
fn errored(task: &str, msg: &str) -> String {
    format!("{task} [error: {msg}]")
}

/// `--force` on `wt` as a session whose record's task is `task`.
async fn force_with_task(wt: &Path, task: &str) -> WorkspaceVerdict {
    remove_in_project_worktree(
        &ManagedSessionId::new(),
        Some(task),
        wt,
        ProvisioningDirt::Discard,
    )
    .await
}

/// #8688 round 3: `mark_errored` appends its note to the record's task after
/// `TASK.md` was written, so an errored session's unedited `TASK.md` never
/// equalled the task and kept the tree. Fails at 9465af6d2.
#[tokio::test]
async fn force_decommission_removes_a_once_errored_session_s_unedited_task_md() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-force-errored-8688");

    // A message holding `]` is still one note.
    let verdict = force_with_task(&wt, &errored(TASK, "launch spec [tm-x] unreadable")).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists(), "the workspace directory must be gone");
}

/// #8688 round 3: an errored session's `TASK.md` edited after spawn keeps the
/// tree. Passes at 9465af6d2, which kept every errored tree; it pins that the
/// errored candidate excuses only the bytes tm wrote.
#[tokio::test]
async fn force_decommission_keeps_a_once_errored_session_s_edited_task_md() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-force-errored-edit-8688");
    let edited = format!("{TASK}\n## Notes\n- the spawn failed on a stale spec\n");
    std::fs::write(wt.join("TASK.md"), &edited).expect("edit TASK.md");

    let verdict = force_with_task(&wt, &errored(TASK, "boom")).await;

    assert!(!verdict.removed, "an edited TASK.md must keep the worktree");
    let body = std::fs::read_to_string(wt.join("TASK.md")).expect("TASK.md survives");
    assert_eq!(body, edited, "the notes survive untouched");
    let reason = verdict.kept_reason.expect("reason");
    assert_eq!(
        count_and_list(&reason),
        (1, vec!["?? TASK.md".to_string()]),
        "reason: {reason}"
    );
}

/// #8688 round 3: without exactly one error marker, no prefix of the task is
/// known to be what tm wrote, so `TASK.md` keeps the tree. The rows pass at
/// 9465af6d2, which kept every errored tree. A `strip_error_notes` candidate
/// loses `strip-twice`, `strip-own-marker` and `straddle`; a cut at the first
/// marker loses `strip-twice`, `first-marker` and `straddle`; counting
/// markers without overlaps loses `straddle`.
#[tokio::test]
async fn force_decommission_keeps_a_repeatedly_errored_session_s_task_md() {
    use crate::session_manager::setters::strip_error_notes;
    let fx = GitWorktreeFixture::new();
    let noted = "Fix the parser [error: x]\n";
    let straddle = "Fix the bug [error:";
    let rows: [(&str, String, String); 5] = [
        // Two `mark_errored` calls; `TASK.md` unedited.
        (
            "strip-twice",
            errored(&errored(TASK, "a"), "b"),
            TASK.into(),
        ),
        // The task's own text holds a marker, errored once; unedited.
        ("own-marker", errored(noted, "boom"), noted.into()),
        // Edited to what `strip_error_notes` yields, which tm never wrote.
        (
            "strip-own-marker",
            errored(noted, "boom"),
            strip_error_notes(&errored(noted, "boom")),
        ),
        // Edited to the text before the first of two markers.
        (
            "first-marker",
            errored(noted, "boom"),
            "Fix the parser".into(),
        ),
        // The task ends in ` [error:`, whose space the note shares.
        ("straddle", errored(straddle, "boom"), "Fix the bug".into()),
    ];
    // Every row runs, so a failure names each row that lost its `TASK.md`.
    let mut removed = Vec::new();
    for (name, task, task_md) in rows {
        let wt = provisioned_tree(&fx, &format!("decom-force-errored-{name}-8688"));
        std::fs::write(wt.join("TASK.md"), &task_md).expect("write TASK.md");

        let verdict = force_with_task(&wt, &task).await;

        let Some(reason) = verdict.kept_reason.filter(|_| !verdict.removed) else {
            removed.push(name);
            continue;
        };
        assert_eq!(
            std::fs::read_to_string(wt.join("TASK.md")).expect("TASK.md survives"),
            task_md,
            "{name}"
        );
        assert_eq!(
            count_and_list(&reason),
            (1, vec!["?? TASK.md".to_string()]),
            "{name}: {reason}"
        );
    }
    assert!(
        removed.is_empty(),
        "TASK.md must keep the tree: {removed:?}"
    );
}

/// #8688: user work beside the tm-written files still blocks `--force`, and
/// the reason counts and names only that work.
#[tokio::test]
async fn force_decommission_keeps_user_work_beside_task_md() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-force-task-work-8688");
    std::fs::write(wt.join("notes.rs"), "// unsaved\n").expect("write user work");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(!verdict.removed && wt.join("notes.rs").exists());
    assert!(wt.join("TASK.md").exists(), "nothing is removed");
    let reason = verdict.kept_reason.expect("reason");
    assert_eq!(
        count_and_list(&reason),
        (1, vec!["?? notes.rs".to_string()]),
        "reason: {reason}"
    );
}

/// #8688: the plain refusal's count and its list agree. Fails before the
/// fix, which counted the untracked `.claude/` as one entry and listed each
/// of its three files.
#[tokio::test]
async fn decommission_refusal_count_matches_the_entries_it_lists() {
    let fx = GitWorktreeFixture::new();
    let wt = task_bearing_tree(&fx, "decom-refuse-count-8688");

    let verdict = remove(&wt, ProvisioningDirt::Refuse).await;

    assert!(!verdict.removed && wt.exists());
    let reason = verdict.kept_reason.expect("a kept workspace must say why");
    let (count, listed) = count_and_list(&reason);
    assert_eq!(count, listed.len(), "reason: {reason}");
    assert_eq!(count, 6, "reason: {reason}");
}

/// `--force` never discards a file provisioning did not write.
#[tokio::test]
async fn force_decommission_still_refuses_user_work() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-force-work-7660");
    std::fs::write(wt.join("notes.rs"), "// unsaved\n").expect("write user work");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(!verdict.removed && wt.join("notes.rs").exists());
    let reason = verdict.kept_reason.expect("reason");
    assert!(reason.contains("never discards"), "reason: {reason}");
    // #7660 round 2: the blocker is named, and the excused files are not.
    assert!(reason.contains("?? notes.rs"), "reason: {reason}");
    assert!(!reason.contains("?? CLAUDE.md"), "reason: {reason}");
}

/// `--force` never discards a commit that is on no remote.
#[tokio::test]
async fn force_decommission_still_refuses_unpushed_commits() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-force-unpushed-7660");
    GitWorktreeFixture::commit_unpushed(&wt);

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(!verdict.removed && wt.exists());
    assert!(verdict.kept_reason.is_some());
}

/// FAIL-CLOSED: a dirty check that cannot complete removes nothing, forced
/// or not. #7660 critic round 3: the index is denied, not `.git`, so the
/// ownership proof passes and the dirt check's own failure arm keeps the tree.
#[tokio::test]
async fn force_decommission_removes_nothing_when_the_dirty_check_cannot_complete() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-force-unreadable-7660");
    assert_eq!(
        force_blocker(&wt, &ManagedSessionId::new()),
        None,
        "premise: the blocker passes"
    );
    let index = fx
        .repo
        .join(".git/worktrees/decom-force-unreadable-7660/index");
    let verdict = {
        let _restore = deny_all(&index);
        remove(&wt, ProvisioningDirt::Discard).await
    };

    assert!(!verdict.removed, "an unanswered check must keep the tree");
    assert!(wt.join("CLAUDE.md").exists());
    let reason = verdict.kept_reason.expect("a kept tree must say why");
    assert!(reason.contains("dirty-check failed"), "reason: {reason}");
    assert!(!reason.contains("--force declined"), "reason: {reason}");
}

/// 🔴 #7660 critic round 3 (HIGH): since #8511 a tm-created worktree carries
/// its marker only in the git admin dir. `--force` honours it. Fails before
/// the fix, which read only the legacy in-tree marker and refused the tree.
#[tokio::test]
async fn force_decommission_honours_an_admin_dir_marker() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-admin-marker-7660");
    assert!(
        admin_marker(&wt).is_file(),
        "premise: the admin marker exists"
    );
    assert!(
        !wt.join(WORKTREE_SENTINEL_FILE).exists(),
        "premise: no legacy marker"
    );

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists());
}

/// #7660 critic round 3: a pre-#8511 tree whose marker still sits in the
/// working tree is honoured too.
#[tokio::test]
async fn force_decommission_honours_a_legacy_in_tree_marker() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-legacy-marker-7660");
    std::fs::remove_file(admin_marker(&wt)).expect("drop the admin marker");
    std::fs::write(wt.join(WORKTREE_SENTINEL_FILE), b"").expect("write legacy marker");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists());
}

/// 🔴 #7660 critic round 3: the marker reader follows symlinks, so a marker
/// that is a symlink is no proof of ownership. Fails before the fix, which
/// never looked at the admin marker and named no symlink.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_whose_marker_is_a_symlink() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-marker-symlink-7660");
    let marker = admin_marker(&wt);
    let target = fx.repo.join("elsewhere-7660");
    std::fs::write(&target, b"").expect("write symlink target");
    std::fs::remove_file(&marker).expect("drop the admin marker");
    std::os::unix::fs::symlink(&target, &marker).expect("symlink the marker");

    let reason = kept_under_force(&wt).await;

    assert!(reason.contains("not a regular file"), "reason: {reason}");
}

/// 🔴 #7660 critic round 3: on a clean tree `--force` is never stricter than
/// a plain decommission. A clean `.worktrees/` tree with no marker is removed
/// either way. Fails before the fix, where `--force` demanded the marker even
/// when there was no dirt to excuse.
#[tokio::test]
async fn force_decommission_is_never_stricter_than_plain_on_a_clean_tree() {
    let fx = GitWorktreeFixture::new();
    for (name, policy) in [
        ("decom-clean-plain-7660", ProvisioningDirt::Refuse),
        ("decom-clean-force-7660", ProvisioningDirt::Discard),
    ] {
        let wt = fx.add_worktree(name);

        let verdict = remove(&wt, policy).await;

        assert!(
            verdict.removed,
            "{policy:?} kept: {:?}",
            verdict.kept_reason
        );
        assert!(!wt.exists(), "{policy:?}: the tree must be gone");
    }
}

/// 🔴 #9444: decommission keeps a worktree a live process stands in, under
/// either policy, and reports the holder.
///
/// Why: the tree is the clean one
/// `force_decommission_is_never_stricter_than_plain_on_a_clean_tree` removes;
/// only a real `sleep` with its cwd at the tree root protects it.
/// Fails before the fix: no guard asked the OS, so `git worktree remove
/// --force` ran under the process.
#[tokio::test]
async fn decommission_keeps_a_worktree_a_live_process_stands_in_9444() {
    let fx = GitWorktreeFixture::new();
    for (name, policy) in [
        ("decom-live-plain-9444", ProvisioningDirt::Refuse),
        ("decom-live-force-9444", ProvisioningDirt::Discard),
    ] {
        let wt = fx.add_worktree(name);
        let holder = crate::session_manager::worktree_git_fixture::StandingProcess::in_dir(&wt);

        let verdict = remove(&wt, policy).await;

        assert!(
            !verdict.removed,
            "{policy:?} removed a tree a process stands in"
        );
        assert!(wt.exists(), "{policy:?}: the tree must stay");
        let reason = verdict.kept_reason.unwrap_or_default();
        assert!(holder.named_in(&reason), "{policy:?}: {reason}");
    }
}

/// 🔴 #9444 fail-open check: a holder probe that cannot answer keeps the
/// tree under either policy, and says why. Fails with the probe dropped from
/// the guard: the same clean tree is then removed.
#[tokio::test]
async fn decommission_keeps_a_worktree_when_the_holder_probe_fails_9444() {
    let fx = GitWorktreeFixture::new();
    for (name, policy) in [
        ("decom-probe-plain-9444", ProvisioningDirt::Refuse),
        ("decom-probe-force-9444", ProvisioningDirt::Discard),
    ] {
        let wt = fx.add_worktree(name);

        let verdict = remove_in_project_worktree_with(
            &ManagedSessionId::new(),
            Some(TASK),
            &wt,
            policy,
            crate::session_manager::worktree_git_fixture::probe_cannot_answer,
        )
        .await;

        assert!(
            !verdict.removed,
            "{policy:?} removed on an unanswered probe"
        );
        assert!(wt.exists(), "{policy:?}: the tree must stay");
        let reason = verdict.kept_reason.unwrap_or_default();
        assert!(
            reason.contains("could not run `lsof`"),
            "{policy:?}: {reason}"
        );
    }
}

/// A worktree whose repository has NO `.gitignore`, provisioned so tm's
/// scaffolding creates one: `?? .gitignore` holding only the managed block.
fn untracked_gitignore_tree(fx: &GitWorktreeFixture, name: &str) -> PathBuf {
    let wt = fx.add_worktree(name);
    mark_owned(&wt);
    let before = provisioning_ledger::snapshot(&wt);
    crate::core::scaffold_gitignore::append_legacy_block(&wt);
    std::fs::create_dir_all(wt.join(".claude")).expect("mkdir .claude");
    std::fs::write(wt.join(".claude/settings.json"), "{}\n").expect("write settings");
    std::fs::write(wt.join("CLAUDE.md"), "# tm\n").expect("write CLAUDE.md");
    provisioning_ledger::record(&wt, &before).expect("record the ledger");
    wt
}

/// #7660 round 2: an untracked `.gitignore` holding only tm's block is
/// provisioning, so `--force` removes the tree.
#[tokio::test]
async fn force_decommission_removes_a_tree_with_an_untracked_scaffold_gitignore() {
    let fx = GitWorktreeFixture::new();
    let wt = untracked_gitignore_tree(&fx, "decom-untracked-gi-7660");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists());
}

/// 🔴 #7660 round 2: an untracked `.gitignore` carrying one line tm never
/// writes keeps the tree. Fails if the untracked case is excused by path.
#[tokio::test]
async fn force_decommission_keeps_an_untracked_gitignore_with_a_user_line() {
    let fx = GitWorktreeFixture::new();
    let wt = untracked_gitignore_tree(&fx, "decom-untracked-gi-user-7660");
    let mut body = std::fs::read_to_string(wt.join(".gitignore")).expect("read .gitignore");
    body.push_str("secrets.env\n");
    std::fs::write(wt.join(".gitignore"), &body).expect("append a user line");

    let verdict = remove(&wt, ProvisioningDirt::Discard).await;

    assert!(
        !verdict.removed,
        "a user's .gitignore line must keep the tree"
    );
    assert!(wt.join(".gitignore").exists());
}

/// 🔴 #7660 round 2: FAIL-CLOSED — when the `.gitignore` diff cannot be read
/// (a corrupt index), ` M .gitignore` is not excused and the tree is kept.
/// Fails if an unreadable diff is treated as provisioning.
#[tokio::test]
async fn force_decommission_keeps_the_tree_when_the_gitignore_diff_cannot_be_read() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-corrupt-index-7660");
    let index = fx
        .repo
        .join(".git/worktrees/decom-corrupt-index-7660/index");
    assert!(index.exists(), "premise: the worktree's index lives here");
    std::fs::write(&index, b"not an index").expect("corrupt the index");

    assert!(
        !is_provisioning_entry(&wt, None, " M .gitignore"),
        "an unreadable diff must never excuse .gitignore"
    );
    let verdict = remove(&wt, ProvisioningDirt::Discard).await;
    assert!(!verdict.removed && wt.exists(), "the tree must be kept");
    // #7660 round 2: the status read failure itself is what kept it.
    let reason = verdict.kept_reason.expect("a kept tree must say why");
    assert!(reason.contains("dirty-check failed"), "reason: {reason}");
}

/// 🔴 #7660 round 2: inside a hunk, the added line `++ x` shows as `+++ x`;
/// it is a body line, not a header, and it is not provisioning. Fails before
/// the fix, which skipped every `+++ ` line as a header.
#[test]
fn gitignore_body_line_shaped_like_a_header_is_not_excused() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-header-shaped-7660");
    assert!(
        is_provisioning_entry(&wt, None, " M .gitignore"),
        "premise: the scaffold block alone is excused"
    );
    let mut body = std::fs::read_to_string(wt.join(".gitignore")).expect("read .gitignore");
    body.push_str("++ secrets.env\n");
    std::fs::write(wt.join(".gitignore"), &body).expect("append a header-shaped line");

    assert!(!is_provisioning_entry(&wt, None, " M .gitignore"));
}

/// The kept reason, asserting the tree stayed on disk.
async fn kept_under_force(wt: &Path) -> String {
    let verdict = remove(wt, ProvisioningDirt::Discard).await;
    assert!(!verdict.removed, "the tree must be kept");
    assert!(wt.exists(), "the tree must still be on disk");
    verdict.kept_reason.expect("a kept tree must say why")
}

/// #7660 round 2: `--force` needs proof tm created the tree. A provisioning-
/// dirty worktree with no ownership sentinel is kept. Fails on the 1.7.2 fix,
/// which excused the dirt and removed it.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_without_the_sentinel() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-no-sentinel-7660");
    std::fs::remove_file(admin_marker(&wt)).expect("drop the marker");

    let reason = kept_under_force(&wt).await;

    assert!(reason.contains("no ownership sentinel"), "reason: {reason}");
}

/// 🔴 #7660 critic round 3 MEDIUM-1: a marker naming ANOTHER session is no
/// licence for `--force`. Records A and B can name one worktree while B is
/// still `Provisioning`, which the foreign-`Active` claim check misses. Fails
/// before the fix, whose ownership check accepted any marker and removed it.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_another_session_owns() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-foreign-owner-7660");
    let other = ManagedSessionId::new();
    write_sentinel_bytes(&wt, &sentinel_payload_bytes(other)).expect("write the owner marker");

    let verdict = remove_as(&ManagedSessionId::new(), &wt, ProvisioningDirt::Discard).await;

    assert!(
        !verdict.removed && wt.exists(),
        "another session's tree must stay"
    );
    let reason = verdict.kept_reason.expect("a kept tree must say why");
    assert!(reason.contains("--force declined"), "reason: {reason}");
    assert!(reason.contains(&other.to_string()), "reason: {reason}");
}

/// #7660 critic round 3 MEDIUM-1: a marker naming a dispatched agent keeps the
/// tree under `--force`, and the reason names the agent.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_an_agent_owns() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-agent-owner-7660");
    let agent = AgentWorktreeOwner {
        agent_id: "agent-synthetic-7660".to_string(),
        delegation_id: DelegationId::new(),
        parent_session_id: SessionId::new(),
    };
    write_agent_sentinel(&wt, agent).expect("write the agent marker");

    let reason = kept_under_force(&wt).await;

    assert!(reason.contains("--force declined"), "reason: {reason}");
    assert!(reason.contains("agent-synthetic-7660"), "reason: {reason}");
}

/// #7660 critic round 3 MEDIUM-1: a marker naming the decommissioned session
/// itself is the proof `--force` needs, so the provisioning-dirty tree goes.
#[tokio::test]
async fn force_decommission_removes_a_worktree_its_own_session_owns() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-own-owner-7660");
    let me = ManagedSessionId::new();
    write_sentinel_bytes(&wt, &sentinel_payload_bytes(me)).expect("write the owner marker");

    let verdict = remove_as(&me, &wt, ProvisioningDirt::Discard).await;

    assert!(verdict.removed, "kept: {:?}", verdict.kept_reason);
    assert!(!wt.exists());
}

/// #7660 round 2, FAIL-CLOSED: a sentinel whose existence cannot be read is
/// no proof. Fails on the 1.7.2 fix, whose reason named no sentinel.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_whose_sentinel_cannot_be_read() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-sentinel-unreadable-7660");

    let reason = {
        let _restore = deny_all(&wt);
        kept_under_force(&wt).await
    };

    assert!(
        reason.contains("sentinel could not be read"),
        "reason: {reason}"
    );
}

/// 🔴 #7660 round 2: a repository's MAIN checkout parked under `.worktrees/`,
/// sentinel and provisioning dirt included, is never removed by `--force`.
/// Fails on the 1.7.2 fix, which never asked what kind of checkout it was.
#[tokio::test]
async fn force_decommission_keeps_a_main_checkout_under_the_worktrees_dir() {
    let fx = GitWorktreeFixture::new();
    let main = fx.repo.join(".worktrees").join("standalone-7660");
    std::fs::create_dir_all(&main).expect("mkdir standalone");
    let init = std::process::Command::new("git")
        .arg("-C")
        .arg(&main)
        .args(["init", "--initial-branch=main"])
        .output()
        .expect("run git init");
    assert!(init.status.success(), "git init failed");
    mark_owned(&main);
    std::fs::write(main.join("CLAUDE.md"), "# tm\n").expect("write CLAUDE.md");

    let reason = kept_under_force(&main).await;

    assert!(reason.contains("main checkout"), "reason: {reason}");
    assert!(main.join("CLAUDE.md").exists());
}

/// #7660 round 2, FAIL-CLOSED: a worktree git cannot resolve (a `.git` file
/// naming a missing admin dir) is kept, naming the failed proof. Since #8511
/// the marker itself lives behind that `.git`, so the marker read fails first.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_git_cannot_resolve() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-unresolvable-7660");
    std::fs::write(wt.join(".git"), "gitdir: /nonexistent/7660\n").expect("break .git");

    let reason = kept_under_force(&wt).await;

    assert!(
        reason.contains("cannot prove tm created it"),
        "reason: {reason}"
    );
    assert!(reason.contains("does not resolve"), "reason: {reason}");
}

/// #7660 critic round 3, FAIL-CLOSED: a marker that is present but does not
/// parse is no proof.
#[tokio::test]
async fn force_decommission_keeps_a_worktree_whose_marker_is_corrupt() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-marker-corrupt-7660");
    std::fs::write(admin_marker(&wt), b"not a marker").expect("corrupt the marker");

    let reason = kept_under_force(&wt).await;

    assert!(reason.contains("corrupt"), "reason: {reason}");
}

/// #7660 round 2: a `git worktree lock` keeps the tree, and the reason says
/// it is locked. #7660 round 3: the refusal must be tm's own — git's "cannot
/// remove a locked working tree" also names the lock, so without the
/// `--force declined` check this passed with the lock probe removed.
#[tokio::test]
async fn force_decommission_keeps_a_locked_worktree() {
    let fx = GitWorktreeFixture::new();
    let wt = provisioned_tree(&fx, "decom-locked-7660");
    fx.lock_worktree(&wt);

    let reason = kept_under_force(&wt).await;

    assert!(reason.contains("--force declined"), "reason: {reason}");
    assert!(reason.contains("locked"), "reason: {reason}");
}

/// #7660 round 3, FAIL-CLOSED: a plain directory under `.worktrees/` that
/// carries a legacy marker is not a worktree root — git answers for the
/// enclosing main checkout — so `--force` has no proof to act on. Fails on the
/// 1.7.2 fix, which ran no provenance check at all.
#[test]
fn force_blocker_refuses_a_directory_that_is_not_a_worktree_root() {
    let fx = GitWorktreeFixture::new();
    let plain = fx.repo.join(".worktrees").join("plain-7660");
    std::fs::create_dir_all(&plain).expect("mkdir plain");
    std::fs::write(plain.join(WORKTREE_SENTINEL_FILE), b"").expect("write legacy marker");

    let blocker =
        force_blocker(&plain, &ManagedSessionId::new()).expect("a non-root directory must block");

    assert!(blocker.contains("not a worktree root"), "{blocker}");
}

/// #7660 round 2, FAIL-CLOSED: a lock state that cannot be read (the git dir
/// is unsearchable) is reported as a blocker, never as "unlocked".
#[test]
fn lock_blocker_fails_closed_when_the_lock_state_cannot_be_read() {
    let dir = tempfile::tempdir().expect("tempdir");
    let git_dir = dir.path().join("worktrees").join("wt");
    std::fs::create_dir_all(&git_dir).expect("mkdir git dir");
    assert_eq!(lock_blocker(&git_dir), None, "premise: no lock file");

    let blocker = {
        let _restore = deny_all(&git_dir);
        lock_blocker(&git_dir)
    };

    let blocker = blocker.expect("an unreadable lock state must block");
    assert!(
        blocker.contains("lock state could not be read"),
        "{blocker}"
    );
}

/// #7660 round 2: a worktree already gone is neither removed nor kept, so
/// the CLI does not report a refusal for it.
#[tokio::test]
async fn decommission_of_an_absent_worktree_reports_nothing_kept() {
    let fx = GitWorktreeFixture::new();
    let absent = fx.repo.join(".worktrees").join("gone-7660");

    for policy in [ProvisioningDirt::Refuse, ProvisioningDirt::Discard] {
        let verdict = remove(&absent, policy).await;
        assert!(verdict.kept_reason.is_none(), "{:?}", verdict.kept_reason);
    }
}

/// #7660 round 2: the by-design reason names a main checkout, adds the
/// `--force` note only under `--force`, and is absent when nothing is on disk.
#[test]
fn unowned_kept_reason_names_a_main_checkout() {
    let fx = GitWorktreeFixture::new();

    let plain = unowned_kept_reason(&fx.repo, ProvisioningDirt::Refuse).expect("kept");
    assert!(plain.contains("main checkout"), "{plain}");
    assert!(!plain.contains("--force"), "{plain}");
    assert!(!plain.contains('\n'), "one line: {plain}");

    let forced = unowned_kept_reason(&fx.repo, ProvisioningDirt::Discard).expect("kept");
    assert!(forced.contains("--force does not apply"), "{forced}");

    let absent = fx.repo.join("no-such-dir-7660");
    assert_eq!(
        unowned_kept_reason(&absent, ProvisioningDirt::Discard),
        None
    );
}

/// #7660 critic round 3: the by-design reason names the other two kinds of
/// workspace tm never removes — a worktree tm did not create (`.git` is a
/// file) and a plain local-path or adopted directory (no `.git`).
#[test]
fn unowned_kept_reason_names_a_foreign_worktree_and_a_plain_directory() {
    let fx = GitWorktreeFixture::new();
    let foreign = fx.add_worktree("foreign-7660");
    let plain = tempfile::tempdir().expect("tempdir");

    for (ws, kind) in [
        (foreign.as_path(), "a git worktree tm did not create"),
        (plain.path(), "a local-path or adopted directory"),
    ] {
        let reason = unowned_kept_reason(ws, ProvisioningDirt::Refuse).expect("kept");
        assert!(reason.contains(kind), "{reason}");
        assert!(reason.starts_with("kept by design"), "{reason}");
    }
}