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
//! Tests for the git-native worktree registry (#4207 slice 1).
//!
//! Why: the module's whole claim is that git — not a path shape — decides what
//! a worktree is and who owns it, so every test that matters here drives REAL
//! `git worktree add`. A mocked git would test the mock.
//! What: the pure porcelain parse, registry-root resolution (the replacement
//! for grandparent inference), and the enumeration contract — including the
//! two cases the five-shape walk got wrong.
//! Test: this file IS the test module.

use super::*;

use crate::session_manager::worktree_git_fixture::GitWorktreeFixture;

/// Every admitted path under `repos_root`, unscoped: the `_in` form under
/// `WorktreeScope::all()` (#8782), reduced to its paths.
fn enumerate_all(repos_root: &std::path::Path, adopted: &[PathBuf]) -> Vec<PathBuf> {
    enumerate_registered_worktrees_in(repos_root, adopted, &WorktreeScope::all())
        .into_iter()
        .map(|row| row.path)
        .collect()
}

// ── the pure parser ──────────────────────────────────────────────────────

#[test]
fn parse_worktree_list_reads_porcelain_records() {
    let stdout = "\
worktree /repos/owner/repo
HEAD abc123
branch refs/heads/main

worktree /repos/owner/repo/.worktrees/session-a
HEAD def456
branch refs/heads/session/session-a

worktree /somewhere/detached
HEAD 0f0f0f
detached

worktree /repos/owner/repo/.base
bare

worktree /gone
HEAD 111111
prunable gitdir file points to non-existent location
";
    let got = parse_worktree_list(stdout);
    assert_eq!(got.len(), 5, "one record per stanza; got {got:?}");

    assert_eq!(got[0].path, std::path::PathBuf::from("/repos/owner/repo"));
    assert_eq!(got[0].branch.as_deref(), Some("main"));
    assert!(got[0].is_main, "git lists the main worktree first");

    assert_eq!(got[1].branch.as_deref(), Some("session/session-a"));
    assert!(!got[1].is_main);

    assert_eq!(got[2].branch, None, "a detached worktree has no branch");
    assert!(got[3].bare, "the `bare` attribute line must be read");
    assert!(
        got[4].prunable,
        "`prunable <reason>` must set the flag, not just the bare word"
    );
}

#[test]
fn parse_worktree_list_marks_only_the_first_record_main() {
    let stdout = "worktree /a\n\nworktree /b\n\nworktree /c\n";
    let got = parse_worktree_list(stdout);
    let mains: Vec<_> = got.iter().filter(|w| w.is_main).collect();
    assert_eq!(mains.len(), 1, "exactly one main record; got {got:?}");
    assert_eq!(mains[0].path, std::path::PathBuf::from("/a"));
}

#[test]
fn parse_worktree_list_empty_input_is_empty() {
    assert!(parse_worktree_list("").is_empty());
}

/// `locked` is git's removal veto and must be read in BOTH spellings the
/// porcelain format emits — bare, and with an operator-supplied reason.
#[test]
fn parse_worktree_list_reads_locked_with_and_without_reason() {
    let stdout = "\
worktree /repos/owner/repo
HEAD abc123
branch refs/heads/main

worktree /repos/owner/repo/.worktrees/bare-lock
HEAD def456
locked

worktree /repos/owner/repo/.worktrees/lock-with-reason
HEAD 789abc
locked keeping this for the postmortem

worktree /repos/owner/repo/.worktrees/unlocked
HEAD 000111
";
    let got = parse_worktree_list(stdout);
    assert_eq!(got.len(), 4, "one record per stanza; got {got:?}");
    assert!(got[1].locked, "the bare `locked` line must set the flag");
    assert!(
        got[2].locked,
        "`locked <reason>` must set the flag too, not just the bare word"
    );
    assert!(
        !got[3].locked,
        "control: a worktree with no `locked` line must not be flagged"
    );
}

// ── registry_root_for: the replacement for grandparent inference ─────────

/// A linked worktree resolves to the checkout that REGISTERED it, whatever
/// directory it happens to live in.
///
/// Why: this is the fact the grandparent rule was standing in for. The
/// fixture parks the worktree at `<repo>/.worktrees/<name>`, whose grandparent
/// coincidentally IS `<repo>` — so this test alone does not distinguish the
/// two rules. `registry_root_for_ignores_where_the_worktree_is_parked` does.
#[test]
fn registry_root_for_linked_worktree_is_the_owning_checkout() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("session-root-test");
    let root = registry_root_for(&wt).expect("a real worktree must resolve a registry root");
    assert_eq!(
        std::fs::canonicalize(&root).unwrap_or(root),
        std::fs::canonicalize(&fixture.repo).unwrap_or_else(|_| fixture.repo.clone()),
    );
}

/// The owning checkout is resolved from git's registry, NOT from the
/// candidate's position on disk — the #4207 defect stated as a test.
///
/// Why: fourteen worktrees on this machine live under `<repo>/.base/…` but are
/// registered to `<repo>`. Grandparent inference answered `.base`, which
/// disowns them, and every downstream git call was then aimed at the wrong
/// repository. Here the worktree is parked three levels deep in a directory
/// with no relationship to the owning repo, so the grandparent of the
/// candidate is emphatically not its root.
#[test]
fn registry_root_for_ignores_where_the_worktree_is_parked() {
    let fixture = GitWorktreeFixture::new();
    let parked = fixture.add_worktree_at(
        &fixture.repo.join("deeply").join("nested").join("elsewhere"),
        "parked",
    );
    let grandparent = parked
        .parent()
        .and_then(|p| p.parent())
        .expect("candidate has a grandparent");
    assert_ne!(
        grandparent,
        fixture.repo.as_path(),
        "test invariant: the grandparent must NOT be the owning checkout, or \
         this test cannot distinguish the two rules"
    );

    let root = registry_root_for(&parked).expect("registry root");
    assert_eq!(
        std::fs::canonicalize(&root).unwrap_or(root),
        std::fs::canonicalize(&fixture.repo).unwrap_or_else(|_| fixture.repo.clone()),
        "the owning checkout must be derived from git, not from the path shape"
    );
}

#[test]
fn registry_root_for_non_repo_is_none() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert!(
        registry_root_for(tmp.path()).is_none(),
        "a directory outside any repository must resolve to None, never a guess"
    );
}

// ── list_registered_worktrees ────────────────────────────────────────────

#[test]
fn list_registered_worktrees_reports_a_real_worktree() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("listed");
    // Anchor on the WORKTREE itself, which is how `git_worktree_list_agrees`
    // now calls this — git resolves the repository from the candidate.
    let listed = list_registered_worktrees(&wt).expect("list");
    let canonical_wt = std::fs::canonicalize(&wt).unwrap_or_else(|_| wt.clone());
    assert!(
        listed.iter().any(
            |w| std::fs::canonicalize(&w.path).unwrap_or_else(|_| w.path.clone()) == canonical_wt
        ),
        "the worktree must appear in its own repository's registry; got {listed:?}"
    );
}

#[test]
fn list_registered_worktrees_none_outside_a_repo() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert!(
        list_registered_worktrees(tmp.path()).is_none(),
        "an unanswerable probe must be None, never an empty list that reads as \
         `no worktrees exist`"
    );
}

// ── enumerate_registered_worktrees ───────────────────────────────────────

/// THE #4207 slice-1 regression test: a registered worktree at a location NONE
/// of the five hard-coded shapes covered is discovered.
///
/// Why: the removed walk probed `.worktrees/`, `.base/.worktrees/`,
/// `.claude/worktrees/`, `.base/.claude/worktrees/`, and
/// `.base/.worktrees/<id>/.claude/worktrees/`. This worktree sits at
/// `<repo>/agents/scratch/wt-1`, which matches none of them, so the walk
/// returned it under no circumstances. Reverting `find_orphaned_worktrees` to
/// the shape walk makes this test fail.
#[test]
fn enumerate_finds_worktree_at_an_unwalked_location() {
    let fixture = GitWorktreeFixture::new();
    let parked = fixture.add_worktree_at(&fixture.repo.join("agents").join("scratch"), "wt-1");
    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical = std::fs::canonicalize(&parked).unwrap_or_else(|_| parked.clone());
    assert!(
        found.contains(&canonical),
        "a registered worktree must be found wherever it lives; got {found:?}"
    );
}

/// The `.base` bare clone is the SECOND registry a managed project can own,
/// and worktrees registered to it must be enumerated too.
#[test]
fn enumerate_finds_worktree_registered_to_base_clone() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_base_clone_worktree("session-in-base");
    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical = std::fs::canonicalize(&wt).unwrap_or_else(|_| wt.clone());
    assert!(
        found.contains(&canonical),
        "a worktree registered to the .base clone must be enumerated; got {found:?}"
    );
}

/// A plain directory sitting in a worktree-shaped location is NOT a worktree
/// and must not be proposed as a reclaim candidate.
///
/// Why: this is the deliberate narrowing derive-not-walk buys. The old walk
/// collected any leaf directory under a `.worktrees/` parent, so a `mkdir`
/// was indistinguishable from a checkout git actually created.
#[test]
fn enumerate_ignores_plain_directory_that_is_not_a_worktree() {
    let fixture = GitWorktreeFixture::new();
    let fake = fixture.repo.join(".worktrees").join("just-a-mkdir");
    std::fs::create_dir_all(&fake).expect("mkdir");
    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical = std::fs::canonicalize(&fake).unwrap_or_else(|_| fake.clone());
    assert!(
        !found.contains(&canonical),
        "a plain directory is not a registered worktree; got {found:?}"
    );
}

/// The main checkout is never a reclaim candidate.
#[test]
fn enumerate_excludes_the_main_checkout() {
    let fixture = GitWorktreeFixture::new();
    fixture.add_worktree("some-session");
    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical_repo =
        std::fs::canonicalize(&fixture.repo).unwrap_or_else(|_| fixture.repo.clone());
    assert!(
        !found.contains(&canonical_repo),
        "the main checkout must never be enumerated for reclaim; got {found:?}"
    );
}

// ── the structural containment boundary (#4224 review, HIGH) ─────────────
//
// Deriving from git widened what is SEEN from five path shapes to anything
// registered under `repos_root`. Replayed against the dogfood machine that
// admitted five of the operator's own long-lived checkouts, leaving the #3649
// sentinel as the only thing between enumeration and an unattended
// `remove_dir_all`. The rule these tests pin is that a candidate must be a
// STRICT DESCENDANT of the managed project directory whose registry named it.
//
// Each test below asserts the negative AND a positive control that must be
// enumerated in the same call, so none of them can pass because enumeration
// returned nothing at all — the way this module fails when git rejects a flag
// or the anchor check regresses.

/// An operator checkout the operator parked at the project-slot position, next
/// to a managed project, is NOT a reclaim candidate.
///
/// Why: this is the live shape the #4224 review measured —
/// `<owner>/ft-follow-links`, `<owner>/trusty-tools-main-build` and
/// `<owner>/gb-connect-card` are all real linked worktrees of a managed project
/// that the operator parked beside it, and all three became enumerable the
/// moment discovery stopped being shape-based. They are excluded by POSITION:
/// a candidate must live inside the project that owns it, which no checkout
/// parked as a sibling can ever satisfy, whatever it is named.
#[test]
fn enumerate_excludes_a_sibling_checkout_of_the_same_repo() {
    let fixture = GitWorktreeFixture::new();
    let owner_dir = fixture.repo.parent().expect("<repos_root>/<owner>");
    let sibling = fixture.add_worktree_at(owner_dir, "operator-checkout");
    // Positive control: an ordinary in-project worktree in the SAME call.
    let control = fixture.add_worktree("control-session");

    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical_control = std::fs::canonicalize(&control).unwrap_or_else(|_| control.clone());
    assert!(
        found.contains(&canonical_control),
        "control: an in-project worktree MUST still be enumerated, or this test \
         proves nothing; got {found:?}"
    );

    let canonical_sibling = std::fs::canonicalize(&sibling).unwrap_or_else(|_| sibling.clone());
    assert!(
        !found.contains(&canonical_sibling),
        "a checkout parked beside the managed project must never be a reclaim \
         candidate; got {found:?}"
    );
    assert!(sibling.exists(), "the sibling checkout must be untouched");
}

/// A worktree in a sibling DIRECTORY whose name merely shares a string prefix
/// with the project is NOT a candidate.
///
/// Why: two things at once. It is the live
/// `<owner>/trusty-tools-worktrees/wt-*` shape — the operator's own worktree
/// parking lot, three of which the review measured as newly enumerable. And it
/// is the string-prefix trap: `repo-worktrees` starts with `repo` as a string,
/// so a containment check written on strings rather than on PATH COMPONENTS
/// would admit every one of them. `Path::starts_with` is component-wise; this
/// test is what stops someone "simplifying" it into a `to_string_lossy()`
/// comparison.
#[test]
fn enumerate_excludes_a_worktree_parked_beside_the_project() {
    let fixture = GitWorktreeFixture::new();
    let owner_dir = fixture.repo.parent().expect("<repos_root>/<owner>");
    let parking_lot = owner_dir.join("repo-worktrees");
    let parked = fixture.add_worktree_at(&parking_lot, "wt-1");
    let control = fixture.add_worktree("control-session");

    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical_control = std::fs::canonicalize(&control).unwrap_or_else(|_| control.clone());
    assert!(
        found.contains(&canonical_control),
        "control: an in-project worktree MUST still be enumerated; got {found:?}"
    );

    let canonical_parked = std::fs::canonicalize(&parked).unwrap_or_else(|_| parked.clone());
    assert!(
        !found.contains(&canonical_parked),
        "`<owner>/repo-worktrees/wt-1` merely shares a string prefix with the \
         project `<owner>/repo` and must NOT be enumerated; got {found:?}"
    );
    assert!(parked.exists(), "the parked worktree must be untouched");
}

/// Containment is STRICT: a path equal to its own containment boundary is
/// never a candidate.
///
/// Why: `starts_with` alone is reflexive — `p.starts_with(p)` is `true` — so
/// without the explicit `!=` a path equal to the boundary satisfies its own
/// containment test.
///
/// Scope honestly: on every topology observed today it is `is_main`, NOT this
/// `!=`, that keeps the operator's project checkout unselectable — git lists a
/// project's own root as the main record, and main records are already
/// filtered. Zero instances on this machine reach the `!=`. It is kept as
/// defence in depth for the case `is_main` does not cover: a project directory
/// that is itself a NON-main linked worktree of some other registry being
/// interrogated, which is reachable in principle and would otherwise put the
/// operator's checkout on a deletion list.
///
/// That same masking is why the strictness is pinned HERE rather than through
/// [`enumerate_registered_worktrees`] — an enumeration-level test would keep
/// passing with the `!=` deleted, making it a guard no test defends. Driving
/// [`scan_from_anchor`] directly lets the boundary be set to a path that IS
/// in the registry, so the `!=` is the only thing that can exclude it.
///
/// #4288 strengthened this: the scan now carries the verdict as a VALUE, so the
/// test asserts the exclusion RULE that fired ([`Admission::OutsideProject`])
/// rather than mere absence from a set — a much harder assertion to satisfy by
/// accident.
#[test]
fn scan_from_anchor_never_admits_the_containment_boundary_itself() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("session-a");
    let canonical_wt = std::fs::canonicalize(&wt).unwrap_or_else(|_| wt.clone());
    let canonical_root = std::fs::canonicalize(&fixture.repos_root).expect("canonical root");
    let canonical_repo = std::fs::canonicalize(&fixture.repo).expect("canonical repo");

    let admission_under_boundary = |boundary: &std::path::Path| -> Admission {
        let mut collected = std::collections::BTreeSet::new();
        scan_from_anchor(&fixture.repo, &canonical_root, boundary, &mut collected);
        collected
            .into_iter()
            .find(|(path, _, _)| path == &canonical_wt)
            .map(|(_, _, key)| key.admission)
            .expect("the worktree must be SCANNED under either boundary")
    };

    // Control: bounded by the real project, the worktree IS admitted — so the
    // exclusion below cannot be attributed to the anchor or the registry.
    assert_eq!(
        admission_under_boundary(&canonical_repo),
        Admission::Admitted,
        "control: bounded by the project, a real in-project worktree must be admitted"
    );

    // Now make the worktree its OWN boundary: it is no longer a STRICT
    // descendant, and must not be admitted.
    assert_eq!(
        admission_under_boundary(&canonical_wt),
        Admission::OutsideProject,
        "a path equal to its containment boundary must never be a candidate — \
         this is what keeps the operator's project checkout unselectable"
    );
}

/// A git-`locked` worktree — the operator's explicit "do not remove this" — is
/// never a candidate.
///
/// Why: NOT because `--force` overrides the lock — it does not. Git refuses a
/// single `--force` on a locked worktree (exit 128, "use 'remove -f -f' to
/// override or unlock first") and leaves the directory intact. The problem was
/// that `decommission::remove_session_worktree` read that refusal as a generic
/// git failure and fell back to `std::fs::remove_dir_all`, deleting the
/// directory anyway and orphaning git's registry entry — the veto defeated
/// through the error path (#4732, since fixed). Keeping a locked worktree out
/// of the candidate list is the first of the two defences.
#[test]
fn enumerate_excludes_a_locked_worktree() {
    let fixture = GitWorktreeFixture::new();
    let locked = fixture.add_worktree("locked-by-operator");
    fixture.lock_worktree(&locked);
    let control = fixture.add_worktree("not-locked");

    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical_control = std::fs::canonicalize(&control).unwrap_or_else(|_| control.clone());
    assert!(
        found.contains(&canonical_control),
        "control: an identically-placed UNLOCKED worktree must be enumerated, so \
         the exclusion below is attributable to the lock and nothing else; got {found:?}"
    );

    let canonical_locked = std::fs::canonicalize(&locked).unwrap_or_else(|_| locked.clone());
    assert!(
        !found.contains(&canonical_locked),
        "a git-locked worktree must never be enumerated for reclaim; got {found:?}"
    );
}

/// A worktree registered to a repo under `repos_root` but living OUTSIDE it is
/// not enumerated.
///
/// Why: git will happily report a worktree parked in `/tmp`; enumerating it
/// would put the sweep's blast radius outside the managed workspace entirely.
/// Since #4224 the strict-descendant rule already rejects this path (a `/tmp`
/// worktree is not inside the project either), so the `repos_root` check this
/// test names is now the OUTER of two independent bounds rather than the only
/// one — it still matters for a project directory that symlinks out of the
/// managed root, which is the only way the two can disagree.
#[test]
fn enumerate_excludes_worktrees_outside_the_repos_root() {
    let fixture = GitWorktreeFixture::new();
    let outside_parent = tempfile::tempdir().expect("tempdir");
    let outside = fixture.add_worktree_at(outside_parent.path(), "far-away");
    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical = std::fs::canonicalize(&outside).unwrap_or_else(|_| outside.clone());
    assert!(
        !found.contains(&canonical),
        "a worktree outside the managed repos root must not be enumerated; got {found:?}"
    );
}

/// A registered worktree whose DIRECTORY is gone is never proposed.
///
/// Why: the asymmetry this module commits to is that a failed observation may
/// only ever SHRINK what is proposed for deletion, never enlarge it. A path
/// that will not resolve cannot be compared against the active-session set, so
/// offering it would risk offering a live worktree. Here the directory is
/// removed behind git's back — git still lists the entry (as `prunable`) and
/// the path no longer canonicalizes — and neither route may yield a candidate.
#[test]
fn enumerate_ignores_a_worktree_whose_directory_is_gone() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("vanished");
    let canonical = std::fs::canonicalize(&wt).unwrap_or_else(|_| wt.clone());
    std::fs::remove_dir_all(&wt).expect("remove the worktree directory");

    let found = enumerate_all(&fixture.repos_root, &[]);
    assert!(
        !found.contains(&canonical),
        "a worktree with no directory left is not a deletion candidate; got {found:?}"
    );
}

#[test]
fn enumerate_missing_repos_root_is_empty() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert!(enumerate_all(&tmp.path().join("nope"), &[]).is_empty());
}

// ── the full scan and its exclusion reasons (#4288) ──────────────────────

/// Every registered worktree the scan drops must come back with the reason it
/// was dropped (#4288 in-scope item 2).
///
/// Why: `enumerate_registered_worktrees` returns only admitted paths, so 33 of
/// the 118 registered worktrees on the dogfood machine — including the two
/// landmines #4288 documents, six of them holding uncommitted work — are
/// invisible to every operator surface. Reconciliation cannot report what
/// enumeration silently discards. This asserts the scan reports BOTH sets and
/// names the rule that fired, not just a count.
#[test]
fn scan_reports_the_excluded_set_with_reasons() {
    let fixture = GitWorktreeFixture::new();
    let admitted = fixture.add_worktree("admitted-one");
    let locked = fixture.add_worktree("locked-one");
    fixture.lock_worktree(&locked);
    let outside = fixture.add_worktree_at(&fixture.repos_root.join("owner"), "beside-the-project");

    let scan = scan_registered_worktrees(&fixture.repos_root, &[]);
    let verdict = |p: &std::path::Path| -> Admission {
        let c = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
        scan.iter()
            .find(|s| s.path == c)
            .unwrap_or_else(|| panic!("scan must report {}; got {scan:?}", c.display()))
            .admission
    };

    assert_eq!(verdict(&admitted), Admission::Admitted);
    assert_eq!(verdict(&locked), Admission::Locked);
    assert_eq!(verdict(&outside), Admission::OutsideProject);
    assert_eq!(verdict(&fixture.repo), Admission::MainCheckout);
    assert_eq!(
        Admission::Locked.reason(),
        "excluded: git-locked by the operator"
    );

    // The admitted subset is exactly what `enumerate` still returns — the scan
    // widened what is REPORTED, never what is proposed for deletion.
    let enumerated = enumerate_all(&fixture.repos_root, &[]);
    let admitted_from_scan: Vec<_> = scan
        .iter()
        .filter(|s| s.admission == Admission::Admitted)
        .map(|s| s.path.clone())
        .collect();
    assert_eq!(admitted_from_scan.len(), 1, "got {admitted_from_scan:?}");
    assert_eq!(enumerated.len(), 1, "got {enumerated:?}");
    assert_eq!(enumerated[0], admitted_from_scan[0]);
}

/// Two worktrees under the SAME path prefix, registered in DIFFERENT
/// registries, are each attributed to the registry that actually holds them
/// (#4288).
///
/// Why: this is the decisive counterexample from #4288 — path shape
/// misclassifies 29% of worktrees, and the proof is two sibling directories
/// inside `.base/.worktrees/` whose registries differ. A rule reading `/.base/`
/// out of the path maps both to the base clone and is wrong about one of them.
#[test]
fn scan_reports_both_registries_for_the_same_path_prefix() {
    let fixture = GitWorktreeFixture::new();
    let base_owned = fixture.add_base_clone_worktree("in-base-registry");
    let base_worktrees_dir = fixture.repo.join(".base").join(".worktrees");
    let repo_owned = fixture.add_worktree_at(&base_worktrees_dir, "in-repo-registry");

    let scan = scan_registered_worktrees(&fixture.repos_root, &[]);
    let registry_of = |p: &std::path::Path| -> std::path::PathBuf {
        let c = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
        scan.iter()
            .find(|s| s.path == c)
            .unwrap_or_else(|| panic!("scan must report {}", c.display()))
            .registry_root
            .clone()
    };

    let base_root = std::fs::canonicalize(fixture.repo.join(".base")).expect("canonical .base");
    let repo_root = std::fs::canonicalize(&fixture.repo).expect("canonical repo");
    assert_eq!(registry_of(&base_owned), base_root);
    assert_eq!(registry_of(&repo_owned), repo_root);
    assert_ne!(
        base_root, repo_root,
        "the two registries must genuinely differ, or this test proves nothing"
    );
}

/// A worktree nested inside another worktree is enumerated BEFORE its
/// container (#4288 in-scope item 4).
///
/// Why: the pre-#4288 order came out of a `BTreeSet<PathBuf>`, which sorts a
/// parent before its children. Nine registered worktrees on the dogfood machine
/// sit inside another registered worktree; removing the parent first takes the
/// child's directory with it and leaves git holding a dangling registry entry.
#[test]
fn enumerate_orders_nested_worktree_before_its_parent() {
    let fixture = GitWorktreeFixture::new();
    let parent = fixture.add_worktree("outer");
    let child = fixture.add_nested_worktree(&parent, ".claude/worktrees", "inner");

    let found = enumerate_all(&fixture.repos_root, &[]);
    let canonical = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.into());
    let idx = |p: &std::path::Path| {
        found
            .iter()
            .position(|f| f == &canonical(p))
            .unwrap_or_else(|| panic!("{} must be enumerated; got {found:?}", p.display()))
    };
    assert!(
        idx(&child) < idx(&parent),
        "the nested worktree must precede its container; got {found:?}"
    );
}

// ── harness agent lock vs operator lock (#6561) ──────────────────────────

/// The porcelain parse keeps the lock REASON, not just the flag (#6561).
///
/// Fails before #6561: `lock_reason` did not exist, and the reason text was
/// dropped by a `starts_with("locked ")` arm that set only the boolean — so
/// nothing downstream could tell the harness's agent-lifetime lock from an
/// operator's standing veto.
#[test]
fn parse_worktree_list_keeps_the_harness_agent_lock_reason() {
    let stdout = "\
worktree /repos/owner/repo
HEAD abc123
branch refs/heads/main

worktree /repos/owner/repo/.claude/worktrees/agent-a1c
HEAD def456
branch refs/heads/worktree-agent-a1c
locked claude agent agent-a1c (pid 11002 start Mon Aug 31 20:33:51 2026)

worktree /repos/owner/repo/.worktrees/kept
HEAD 999999
branch refs/heads/session/kept
locked
";
    let got = parse_worktree_list(stdout);
    assert_eq!(got.len(), 3, "one record per stanza; got {got:?}");
    assert!(got[1].locked);
    assert_eq!(
        got[1].lock_reason.as_deref(),
        Some("claude agent agent-a1c (pid 11002 start Mon Aug 31 20:33:51 2026)"),
        "the reason must survive the parse"
    );
    assert!(got[2].locked, "a bare `locked` line still locks");
    assert_eq!(
        got[2].lock_reason, None,
        "and carries no reason to misread as the harness's"
    );
}

#[test]
fn harness_agent_lock_reason_matches_the_harness_shape() {
    assert!(is_harness_agent_lock_reason(
        "claude agent agent-a1c (pid 11002 start Mon Aug 31 20:33:51 2026)"
    ));
    assert!(
        is_harness_agent_lock_reason("Claude Agent agent-a1c (pid 1)"),
        "the shape is what matters, not the casing"
    );
}

#[test]
fn harness_agent_lock_reason_rejects_an_operator_lock() {
    assert!(!is_harness_agent_lock_reason(""));
    assert!(!is_harness_agent_lock_reason(
        "do not remove - salvaging work"
    ));
    assert!(
        !is_harness_agent_lock_reason("held for review by claude agent later"),
        "a mention further along the string is not the harness's own reason"
    );
}

/// #7974: the pid comes out of the measured reason shape, and only out of a
/// harness reason.
/// Test: this function IS the test.
#[test]
fn harness_lock_pid_reads_the_measured_reason_shape() {
    assert_eq!(
        harness_lock_pid_in_reason(
            "claude agent agent-a92efd8de8a9e6960 (pid 17167 start Mon Sep 14 15:30:46 2026)"
        ),
        Some(17167)
    );
}

/// #7974: an operator's lock names no dispatched process, so reading a pid out
/// of one would attribute a stranger's process to the harness.
/// Test: this function IS the test.
#[test]
fn harness_lock_pid_rejects_an_operator_lock() {
    assert_eq!(
        harness_lock_pid_in_reason("do not remove (pid 17167)"),
        None
    );
}

/// #7974: a harness reason whose pid is missing or unparsable yields `None`
/// rather than a guess — silence refuses at the adoption gate.
/// Test: this function IS the test.
#[test]
fn harness_lock_pid_is_none_when_the_reason_names_no_pid() {
    assert_eq!(harness_lock_pid_in_reason("claude agent agent-a1c"), None);
    assert_eq!(
        harness_lock_pid_in_reason("claude agent agent-a1c (pid notanumber)"),
        None
    );
}

/// #7974: a path git does not list is not a locked worktree, and must not be
/// read as one.
/// Test: this function IS the test.
#[test]
fn harness_lock_pid_of_a_non_worktree_is_none() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert_eq!(harness_agent_lock_pid(tmp.path()), None);
}

/// #7974: the tri-state pid probe separates running, gone, and unanswerable.
///
/// Why a spawned-and-reaped child rather than a large constant: a hard-coded
/// "surely unused" pid is only probably unused, and a test that passes because
/// nothing happened to hold that number is not a test. Waiting on the child
/// reaps the zombie, so the pid is genuinely free at the moment it is probed.
/// Test: this function IS the test.
#[test]
fn pid_liveness_separates_running_gone_and_undeterminable() {
    assert_eq!(
        pid_liveness(std::process::id()),
        Some(true),
        "this process is running"
    );

    let mut child = std::process::Command::new("true")
        .spawn()
        .expect("spawn a process that exits immediately");
    let dead = child.id();
    child.wait().expect("reap the child");
    assert_eq!(
        pid_liveness(dead),
        Some(false),
        "a reaped child's pid is gone"
    );

    assert_eq!(pid_liveness(0), None, "0 is a process group, not a process");
    assert_eq!(
        pid_liveness(u32::MAX),
        None,
        "a pid outside positive pid_t is not a process"
    );
}

/// #7974: `EPERM` means the kernel FOUND the process and refused the signal, so
/// it is evidence of life — folding it into "gone" would let adoption take a
/// tree from an agent running under another uid.
/// Test: this function IS the test.
#[test]
fn classify_kill_probe_reads_eperm_as_running() {
    assert_eq!(
        classify_kill_probe(Err(nix::errno::Errno::EPERM)),
        Some(true),
        "a permission refusal is an answer about a process that exists"
    );
}

/// #7974, the fail-closed arm (ADR-0045): an errno this probe does not
/// recognise has proven nothing, so it must answer `None` and leave the
/// adoption gate refusing — never `Some(false)`.
/// Test: this function IS the test.
#[test]
fn classify_kill_probe_reads_an_unrecognised_errno_as_undeterminable() {
    assert_eq!(
        classify_kill_probe(Err(nix::errno::Errno::EINVAL)),
        None,
        "an unrecognised errno must not be coerced into death"
    );
}

/// #7974: the extracted classifier is the SAME classification the live probe
/// makes, so the two errno tests above are about `pid_liveness`'s behaviour and
/// not about a parallel function that has drifted from it.
/// Test: this function IS the test.
#[test]
fn classify_kill_probe_agrees_with_the_live_probe_on_ok_and_esrch() {
    assert_eq!(
        classify_kill_probe(Ok(())),
        pid_liveness(std::process::id()),
        "the Ok arm must agree with a live probe of this process"
    );

    let mut child = std::process::Command::new("true")
        .spawn()
        .expect("spawn a process that exits immediately");
    let dead = child.id();
    child.wait().expect("reap the child");
    assert_eq!(
        classify_kill_probe(Err(nix::errno::Errno::ESRCH)),
        pid_liveness(dead),
        "the ESRCH arm must agree with a live probe of a reaped pid"
    );
}

/// The scan reports the harness's agent lock as its OWN admission verdict
/// (#6561).
///
/// Fails before #6561: both worktrees came back `Admission::Locked`, so the
/// merged-PR sweep dropped a live agent's tree at gate 1 with a message naming
/// the operator, and the operator was never told an agent had been spared.
#[test]
fn scan_separates_a_harness_agent_lock_from_an_operator_lock() {
    let fixture = GitWorktreeFixture::new();
    let store = fixture.repo.join(".claude").join("worktrees");
    let agent = fixture.add_worktree_at(&store, "agent-6561");
    let session = fixture.add_worktree("operator-held");
    fixture.harness_lock_worktree(&agent, "agent-6561");
    fixture.lock_worktree(&session);

    let scanned = scan_registered_worktrees(&fixture.repos_root, &[]);
    let canonical = |p: &std::path::Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.into());
    let verdict = |p: &std::path::Path| {
        scanned
            .iter()
            .find(|s| s.path == canonical(p))
            .unwrap_or_else(|| panic!("{} must be scanned; got {scanned:?}", p.display()))
            .admission
    };
    assert_eq!(verdict(&agent), Admission::HarnessAgentLock);
    assert_eq!(verdict(&session), Admission::Locked);
}

#[test]
fn harness_lock_state_reports_a_harness_locked_tree_held() {
    let fixture = GitWorktreeFixture::new();
    let store = fixture.repo.join(".claude").join("worktrees");
    let agent = fixture.add_worktree_at(&store, "agent-held");
    fixture.harness_lock_worktree(&agent, "agent-held");
    assert_eq!(harness_lock_state(&agent), HarnessLockState::Held);
}

/// An unlocked registered worktree is POSITIVE evidence the harness let go
/// (#6561) — the one answer that permits reclamation past an empty registry.
#[test]
fn harness_lock_state_reports_an_unlocked_tree_released() {
    let fixture = GitWorktreeFixture::new();
    let store = fixture.repo.join(".claude").join("worktrees");
    let agent = fixture.add_worktree_at(&store, "agent-released");
    assert_eq!(harness_lock_state(&agent), HarnessLockState::Released);
}

/// An OPERATOR lock says nothing about the harness either way, so it is
/// undeterminable rather than released (#6561).
#[test]
fn harness_lock_state_of_an_operator_locked_tree_is_undeterminable() {
    let fixture = GitWorktreeFixture::new();
    let store = fixture.repo.join(".claude").join("worktrees");
    let agent = fixture.add_worktree_at(&store, "agent-operator-held");
    fixture.lock_worktree(&agent);
    assert_eq!(harness_lock_state(&agent), HarnessLockState::Undeterminable);
}

#[test]
fn harness_lock_state_of_a_non_worktree_is_undeterminable() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert_eq!(
        harness_lock_state(tmp.path()),
        HarnessLockState::Undeterminable,
        "git cannot be asked here, and silence is never `Released`"
    );
}

// ── adopted project anchors (#7357) ──────────────────────────────────────

/// A project checkout OUTSIDE the repos root contributes its worktrees once it
/// has been adopted.
///
/// Why: this is the #7357 bug in one assertion. The repos-root walk reaches a
/// project only at `<repos_root>/<owner>/<repo>`, so a checkout anywhere else
/// produced ZERO rows — reconcile, the reclaim sweep, `tm doctor` and the Disk
/// survey all read this one function, which is why the operator had no
/// sanctioned way to reclaim six merged worktrees.
#[test]
fn scan_admits_a_worktree_under_an_adopted_checkout() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("adopted-one");
    let canonical = std::fs::canonicalize(&wt).expect("canonical worktree");
    // An unrelated, empty repos root: the walk can find nothing at all.
    let elsewhere = tempfile::tempdir().expect("tempdir");

    let without = scan_registered_worktrees(elsewhere.path(), &[]);
    assert!(
        without.is_empty(),
        "without an adopted anchor the walk sees nothing; got {without:?}"
    );

    let with = scan_registered_worktrees(elsewhere.path(), std::slice::from_ref(&fixture.repo));
    let row = with
        .iter()
        .find(|s| s.path == canonical)
        .unwrap_or_else(|| panic!("adopted worktree must be scanned; got {with:?}"));
    assert_eq!(
        row.admission,
        Admission::Admitted,
        "an adopted project bounds its own candidates"
    );
}

/// The admitted subset reaches `prune` through `enumerate`, so it must widen
/// the same way.
#[test]
fn enumerate_admits_a_worktree_under_an_adopted_checkout() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("adopted-two");
    let canonical = std::fs::canonicalize(&wt).expect("canonical worktree");
    let elsewhere = tempfile::tempdir().expect("tempdir");

    let found = enumerate_all(elsewhere.path(), std::slice::from_ref(&fixture.repo));
    assert!(
        found.contains(&canonical),
        "an adopted checkout's worktree must be enumerable; got {found:?}"
    );
}

/// An adopted checkout that the walk already covers is skipped, so one path can
/// never end up attributed to two projects.
#[test]
fn scan_ignores_an_adopted_checkout_inside_the_repos_root() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("walked-and-adopted");
    let canonical = std::fs::canonicalize(&wt).expect("canonical worktree");

    let rows = scan_registered_worktrees(&fixture.repos_root, std::slice::from_ref(&fixture.repo));
    let matching: Vec<&ScannedWorktree> = rows.iter().filter(|s| s.path == canonical).collect();
    assert_eq!(
        matching.len(),
        1,
        "the walk owns a checkout under the repos root; got {matching:?}"
    );
}

/// The same anchor listed twice still yields one row per worktree.
#[test]
fn scan_does_not_duplicate_a_repeated_adopted_checkout() {
    let fixture = GitWorktreeFixture::new();
    let wt = fixture.add_worktree("adopted-twice");
    let canonical = std::fs::canonicalize(&wt).expect("canonical worktree");
    let elsewhere = tempfile::tempdir().expect("tempdir");

    let rows = scan_registered_worktrees(
        elsewhere.path(),
        &[fixture.repo.clone(), fixture.repo.clone()],
    );
    assert_eq!(
        rows.iter().filter(|s| s.path == canonical).count(),
        1,
        "a repeated anchor must not restate a path; got {rows:?}"
    );
}