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
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
//! Merged-PR worktree reclamation and disk accounting (#2919).
//!
//! Why: `.base/.claude/worktrees` reached **1.1 TiB across 77 entries** on
//! 2026-07-21, four days after a manual sweep had reclaimed the same 1.1 TiB.
//! Nothing was leaking — worktrees were simply never reclaimed, because the
//! merge of a workstream's PR (DOC-52 §3.4: "closing a workstream is THE
//! trigger for resource cleanup") fired no cleanup at all. `prune.rs` already
//! reclaims worktrees whose *session* is provably gone; it has no notion of a
//! *branch* whose PR merged, which is the far more common terminal state.
//! This module adds that missing signal, plus the disk accounting the
//! post-mortem asked for ("report real before/after numbers").
//!
//! What: a git-authoritative survey (ADR-0023 point 1 — `git worktree list
//! --porcelain` decides existence, never a directory walk) that pairs every
//! registered worktree with its branch's pull-request state and its on-disk
//! byte count, and classifies it [`Reclaimable`](ReclaimVerdict::Reclaimable)
//! ONLY when six independent gates all pass. Removal is a separate,
//! non-default [`ReclaimMode::Remove`] opt-in; the survey itself never deletes.
//!
//! FAIL-CLOSED, by construction: [`classify`] reaches `Reclaimable` only by
//! falling off the end of every gate. Each gate `return`s a `Blocked` verdict,
//! so a gate that errors, times out, or cannot answer produces a refusal — the
//! failure branch can never advance to deletion. In particular a PR state that
//! could not be determined ([`BranchPrState::Unknown`]) blocks, a lookup that
//! FAILED ([`BranchPrState::LookupFailed`], #6561) blocks and says why, and so
//! does an index that may have been TRUNCATED (an absent branch is only `NoPr`
//! when the index is known complete).
//!
//! Test: `worktree_reclaim_tests` — one refusal test per gate, each of which
//! fails if its gate is deleted.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

// #7889: gate 5's landed-content admission lives next door so this file stays
// under the SLOC cap; the re-export keeps `worktree_reclaim::LandedContentProbe`.
pub(crate) use super::worktree_reclaim_landed::LandedContentProbe;
use super::worktree_reclaim_landed::{
    merged_pr_verdict, no_pr_verdict, published_route_applies, published_verdict,
    unknown_pr_verdict,
};

// #6561: the `gh` runner lives next door so this file stays under the SLOC cap;
// the re-import keeps every call site (and `super::*` in the tests) unchanged.
use super::worktree_reclaim_gh::{
    GH_TIMEOUT, PR_JSON_FIELDS, gh_pr_list_command, resolve_daemon_gh_env, run_with_timeout,
};
// #6867: the single-flight + backoff gate every `gh` poll passes through.
use super::worktree_reclaim_gh_gate as gh_gate;
// #6927: the operator keep-list gate 0 consults.
pub(crate) use super::worktree_keep_list::KeepList;
use super::worktree_registry::Admission;
// #7057: the repository every `gh` call below is pinned to, read from the
// target directory's own `origin` rather than inferred by `gh`.
use super::worktree_repo_slug::repo_slug_for;
use super::worktree_safety::DirtyWorktree;
// #6507: the verdict vocabulary lives next door so this file stays under the
// SLOC cap; the re-export keeps every call site (and `super::*` in the tests)
// unchanged.
pub(crate) use super::worktree_reclaim_verdict::{ReclaimGate, ReclaimVerdict};
// #6806: gate 2's claim vocabulary, re-exported for the same reason.
pub(crate) use super::worktree_reclaim_claim::{
    ClaimLiveness, ClaimState, LiveClaims, WorkspaceClaim,
};

// #7652: gate 4 — both ownership halves and the agent probe type — lives next
// door for the SLOC cap; re-exported so every call site stays unchanged.
pub(crate) use super::worktree_reclaim_ownership::{
    AgentStateProbe, SessionOwners, agent_ownership_blocks, session_ownership_blocks,
    unattributed_nested_blocks,
};

/// How many pull requests one `gh pr list` call retrieves (#2919).
///
/// Why: the index is built once per repository rather than once per worktree —
/// 77 worktrees would otherwise mean 77 network round-trips. The limit has to
/// be large enough that a normal repository's whole PR history fits, because a
/// TRUNCATED index cannot tell "this branch has no PR" from "this branch's PR
/// fell off the end", and the safe reading of the latter is
/// [`BranchPrState::Unknown`].
/// What: 400. [`PrIndex::from_json`] marks the index INCOMPLETE when the reply
/// holds exactly this many rows, which downgrades every absent branch to
/// `Unknown` (i.e. blocks) instead of to `NoPr`.
/// Test: `pr_index_truncated_reply_makes_absent_branches_unknown`.
pub(crate) const PR_INDEX_LIMIT: usize = 400;

/// The pull-request state of the branch a worktree has checked out (#2919).
///
/// Why: only ONE of these six states is evidence that the worktree's work has
/// landed and the directory is disposable. Modelling the other five explicitly
/// — rather than as `Option<bool>` — is what keeps "we could not find out"
/// from collapsing into "there is nothing here", which is the fail-open shape
/// this repository keeps re-encountering.
/// What: `Merged` carries the PR number that proves the branch landed. `Open`
/// and `ClosedUnmerged` are active/abandoned-but-unlanded branches. `NoPr` is
/// asserted only against a KNOWN-COMPLETE index. `Unknown` is the answerable-
/// but-unanswered case: a truncated index, or a detached HEAD with no branch to
/// attribute a PR to. `LookupFailed` is the BROKEN case — `gh` missing,
/// unauthenticated, timing out, or erroring — and carries its reason (#6561).
/// Test: `classify_blocks_open_pr`, `classify_blocks_closed_unmerged_pr`,
/// `classify_blocks_no_pr`, `classify_blocks_unknown_pr_state`,
/// `classify_blocks_a_failed_lookup_and_names_the_reason`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub(crate) enum BranchPrState {
    /// A pull request for this branch was merged.
    Merged {
        /// The merged pull request's number.
        pr: u64,
    },
    /// A pull request for this branch is still open — work in flight.
    Open {
        /// The open pull request's number.
        pr: u64,
    },
    /// A pull request for this branch was closed WITHOUT merging.
    ClosedUnmerged {
        /// The closed pull request's number.
        pr: u64,
    },
    /// A known-complete index holds no pull request for this branch.
    NoPr,
    /// The state could not be determined — always blocks reclamation.
    Unknown,
    /// The lookup itself FAILED, carrying `gh`'s own one-line complaint (#6561).
    ///
    /// Why: this used to be `Unknown`, and the collapse hid a whole-workspace
    /// outage. The daemon carries neither `GH_TOKEN` nor `GH_CONFIG_DIR`, so
    /// `gh pr list` exited 4 with `To get started with GitHub CLI, please run:
    /// gh auth login` for all 261 registered worktrees; the survey reported
    /// `0 reclaimable` and named no cause. An unanswerable branch (a detached
    /// HEAD, a truncated index) and a broken lookup need opposite operator
    /// actions, so they are now separate states.
    /// Test: `pr_state_for_branch_reports_a_failed_call_as_lookup_failed`,
    /// `survey_counts_a_failed_lookup_apart_from_an_unknown_state`.
    LookupFailed {
        /// One line: the exit code plus `gh`'s first stderr line.
        reason: String,
    },
}

impl BranchPrState {
    /// How strongly this state BLOCKS reclamation — higher wins a collision.
    ///
    /// Why: a branch can carry several pull requests over its life (merge PR
    /// #1, push again, open PR #2). Reclaiming on the merged one while a newer
    /// one is open would delete live work, so when one branch maps to several
    /// rows the most blocking state must win, not the newest or the first.
    /// What: `Open` (3) > `ClosedUnmerged` (2) > `Merged` (1); `NoPr`,
    /// `Unknown` and `LookupFailed` never come from a row so they rank 0.
    /// Test: `pr_index_open_pr_beats_a_merged_one_on_the_same_branch`.
    fn block_rank(&self) -> u8 {
        match self {
            Self::Open { .. } => 3,
            Self::ClosedUnmerged { .. } => 2,
            Self::Merged { .. } => 1,
            Self::NoPr | Self::Unknown | Self::LookupFailed { .. } => 0,
        }
    }
}

/// One row of `gh pr list --json number,headRefName,state,isCrossRepository`
/// (#2919).
#[derive(Debug, Deserialize)]
struct PrRow {
    /// The pull request number.
    number: u64,
    /// The branch the pull request was opened FROM.
    #[serde(rename = "headRefName")]
    head_ref_name: String,
    /// `OPEN`, `CLOSED`, or `MERGED`.
    state: String,
    /// True when the head branch lives in a FORK, not this repository.
    ///
    /// Why: `headRefName` alone is not an identity. A fork's PR from a branch
    /// called `fix/foo` says nothing about a LOCAL worktree on `fix/foo` — they
    /// are different branches in different repositories that happen to share a
    /// name. Attributing a fork's merge to a local worktree would authorise
    /// deleting work that never landed anywhere. `#[serde(default)]` means a
    /// `gh` too old to report the field leaves this `false`, which is the
    /// pre-existing behaviour and is caught by the same-repo assumption the
    /// field exists to break — so the field is also requested explicitly in
    /// [`PrIndex::from_gh`], and a `gh` that cannot supply it fails the whole
    /// call, yielding [`PrIndex::unavailable_because`].
    #[serde(default, rename = "isCrossRepository")]
    is_cross_repository: bool,
}

/// Branch → pull-request state for one repository (#2919).
///
/// Why: one `gh` call per repository instead of one per worktree, and — more
/// importantly — one place that knows whether the answer set is trustworthy.
/// An index that failed to build, or that may have been truncated, must not
/// let an absent branch read as "no PR", because "no PR" would otherwise be
/// indistinguishable from a merged PR that fell off the end of the page. Since
/// #6561 the two are also kept apart from each other: a failed build carries
/// `gh`'s own reason and reports it, a truncated one does not.
/// What: the branch map plus a `complete` flag. [`state_for`](Self::state_for)
/// returns `NoPr` for an absent branch ONLY when `complete` holds; otherwise
/// `Unknown`.
/// Test: `pr_index_absent_branch_is_no_pr_when_complete`,
/// `pr_index_truncated_reply_makes_absent_branches_unknown`,
/// `pr_index_reports_a_failed_lookup_with_its_reason`.
#[derive(Debug, Default)]
pub(crate) struct PrIndex {
    /// Branch name → the most blocking state observed for it.
    by_branch: BTreeMap<String, BranchPrState>,
    /// True only when the reply is known to hold every pull request.
    complete: bool,
    /// Why the lookup FAILED, when it did — `None` means it answered (#6561).
    ///
    /// Distinguishes an index that could not be built from one that was merely
    /// truncated: both leave a branch unresolved, but only the first is a fault
    /// the operator can fix.
    failure: Option<String>,
}

impl PrIndex {
    /// An index that answers nothing BECAUSE the lookup failed (#6561).
    ///
    /// Why: [`unavailable`](Self::unavailable) says "no answers" and nothing
    /// about why. Every branch it cannot resolve now reads
    /// [`BranchPrState::LookupFailed`] carrying `reason`, so the survey can
    /// count and print the cause instead of reporting a bare zero.
    /// Test: `pr_index_reports_a_failed_lookup_with_its_reason`.
    pub(crate) fn unavailable_because(reason: String) -> Self {
        Self {
            by_branch: BTreeMap::new(),
            complete: false,
            failure: Some(reason),
        }
    }

    /// Parse a `gh pr list --json …` reply into an index (#2919).
    ///
    /// Why: keeping the parse pure means the truncation rule and the
    /// most-blocking-state-wins rule are testable without a network or a `gh`
    /// binary, which is the only way the refusal paths get real coverage.
    /// What: unparsable JSON yields [`unavailable`](Self::unavailable). A reply
    /// holding exactly `limit` rows is treated as TRUNCATED (`complete:
    /// false`). Rows collapse per branch by [`BranchPrState::block_rank`]; an
    /// unrecognised `state` string is skipped rather than guessed at, which
    /// leaves its branch absent and therefore blocking under a truncated index
    /// and `NoPr` under a complete one — the latter is safe because an
    /// unrecognised state is by definition not proof of a merge.
    /// Test: `pr_index_reads_merged_open_and_closed_rows`,
    /// `pr_index_truncated_reply_makes_absent_branches_unknown`,
    /// `pr_index_malformed_json_is_unavailable`.
    pub(crate) fn from_json(stdout: &str, limit: usize) -> Self {
        let Ok(rows) = serde_json::from_str::<Vec<PrRow>>(stdout) else {
            // #6561: a zero exit that printed something other than the JSON is
            // a failed lookup, not an empty repository — say which.
            return Self::unavailable_because(
                "`gh` printed output that is not the pull-request JSON".to_string(),
            );
        };
        // #2919: a full page is indistinguishable from a truncated one, so it
        // is treated as truncated. Erring the other way would let a merged PR
        // that fell off the page read as `NoPr` — which blocks too, but only
        // by luck; this makes it blocking by rule.
        let complete = rows.len() < limit;
        let mut by_branch: BTreeMap<String, BranchPrState> = BTreeMap::new();
        for row in rows {
            // #2919: a fork's branch is not this repository's branch. Skipping
            // the row leaves the local branch absent, which resolves to `NoPr`
            // (complete index) or `Unknown` (truncated) — both refuse.
            if row.is_cross_repository {
                continue;
            }
            let state = match row.state.as_str() {
                "MERGED" => BranchPrState::Merged { pr: row.number },
                "OPEN" => BranchPrState::Open { pr: row.number },
                "CLOSED" => BranchPrState::ClosedUnmerged { pr: row.number },
                _ => continue,
            };
            let entry = by_branch.entry(row.head_ref_name).or_insert(state.clone());
            if state.block_rank() > entry.block_rank() {
                *entry = state;
            }
        }
        Self {
            by_branch,
            complete,
            failure: None,
        }
    }

    /// Build the index by asking `gh` about `registry_root`'s repository.
    ///
    /// Why: this is the ONLY I/O in the module's classification path, isolated
    /// here so every gate above it is a pure function.
    /// What: `gh pr list --repo <owner/repo> --state all --limit
    /// <PR_INDEX_LIMIT> --json number,headRefName,state,isCrossRepository`, run
    /// with its WORKING DIRECTORY set to `registry_root` (never `-C`, which
    /// `gh` does not have — see
    /// [`gh_command`](super::worktree_reclaim_gh::gh_command)) and with the
    /// repository-redirecting environment stripped. #7057: the `--repo` slug
    /// comes from `registry_root`'s own `origin` remote, so the repository is
    /// STATED rather than inferred from the working directory; a root whose
    /// repository cannot be established refuses without spawning `gh` at all.
    /// A failure to spawn, a timeout, a non-zero exit, or
    /// unparsable output all yield
    /// [`unavailable_because`](Self::unavailable_because) carrying `gh`'s own
    /// one-line complaint (#6561) — never an empty-but-complete index, and
    /// since #6561 never a cause-free one either.
    /// Test: `gh_command_passes_no_dash_c_flag`,
    /// `gh_command_runs_in_the_requested_directory`,
    /// `gh_command_strips_repository_redirecting_env` (argv/env shape);
    /// `pr_index_from_gh_reads_this_repository` (a real successful call);
    /// `pr_index_malformed_json_is_unavailable` (failure-to-unavailable).
    pub(crate) fn from_gh(registry_root: &Path) -> Self {
        Self::from_gh_within(registry_root, GH_TIMEOUT)
    }

    /// [`from_gh`](Self::from_gh) with the `gh` subprocess bound to `timeout`.
    ///
    /// Why: a caller that is itself under a deadline cannot afford
    /// [`GH_TIMEOUT`]'s fixed ten seconds late in its own budget. The disk
    /// survey gates ENTRY to each worktree on its deadline but could not bound
    /// the lookup the admitted worktree then paid for, so a 20-second budget
    /// produced a pass past 30 and the console's stdio transport answered its
    /// Disk view with a 502 carrying no survey at all (#6929).
    /// What: identical to [`from_gh`](Self::from_gh) but for the subprocess
    /// bound. `timeout` is the caller's ceiling, never a floor — pass
    /// `GH_TIMEOUT` for the unbudgeted default.
    /// Test: `a_budgeted_survey_answers_within_its_budget`,
    /// `pr_index_from_gh_reads_this_repository`.
    pub(crate) fn from_gh_within(registry_root: &Path, timeout: Duration) -> Self {
        Self::from_gh_listing(registry_root, PR_INDEX_LIMIT, timeout)
    }

    /// [`from_gh_within`](Self::from_gh_within), asking for up to `limit` rows
    /// (#8301). The reclaim survey asks for every pull request in one call, so
    /// no branch needs a lookup of its own; see `worktree_reclaim_budget`.
    pub(crate) fn from_gh_listing(registry_root: &Path, limit: usize, timeout: Duration) -> Self {
        // #7057: WHICH repository, read from this root's own `origin` rather
        // than left to `gh` to infer from the working directory. Resolved
        // before the gate because a root whose repository cannot be
        // established must not spawn a poll at all.
        let repo = match repo_slug_for(registry_root) {
            Ok(repo) => repo,
            Err(reason) => {
                tracing::warn!(
                    root = %registry_root.display(),
                    reason = %reason,
                    "worktree-reclaim: the repository for this root could not be \
                     established — every branch under it will block (#7057)"
                );
                return Self::unavailable_because(reason);
            }
        };
        // #6867: through the gate, so a survey that overlaps another spawns no
        // second `gh`, and a root that has hung three times running is skipped
        // rather than polled again. The identity resolution sits INSIDE the
        // closure because it shells out to git — a suspended root must not pay
        // for that either.
        // #8301: keyed by the limit — a 400-row reply is not a full listing.
        let outcome = gh_gate::shared().poll(registry_root, &format!("index:{limit}"), || {
            // #6623: resolved once per registry root — the daemon's own gh
            // identity, since launchd hands it neither `GH_TOKEN` nor
            // `GH_CONFIG_DIR`.
            let gh_env = resolve_daemon_gh_env(registry_root, &repo)?;
            let identity = gh_env.describe();
            let mut cmd = gh_pr_list_command(registry_root, &gh_env, &repo);
            cmd.args(["--state", "all", "--limit"])
                .arg(limit.to_string())
                .args(["--json", PR_JSON_FIELDS]);
            // #6929: the caller's ceiling, so a lookup cannot outlive the
            // survey that asked for it.
            run_with_timeout(cmd, timeout).map_err(|f| f.with_identity(identity))
        });
        match outcome {
            Ok(stdout) => {
                let index = Self::from_json(&stdout, limit);
                // #2919: logged because "resolved 0 branches" is the signature
                // of a call that ran but answered nothing — the shape the bogus
                // `-C` flag produced, which was otherwise invisible.
                tracing::debug!(
                    root = %registry_root.display(),
                    repo = %repo,
                    branches = index.branch_count(),
                    complete = index.is_complete(),
                    "worktree-reclaim: built pull-request index (#2919)"
                );
                index
            }
            Err(failure) => {
                // #6561: WARN, not debug, and carrying the reason. A silent
                // debug line is why an auth failure across all 261 worktrees
                // surfaced only as "0 reclaimable". #6623: the resolved
                // identity rides along, so "used the wrong config dir" reads
                // differently from "used none at all".
                tracing::warn!(
                    root = %registry_root.display(),
                    repo = %repo,
                    reason = %failure,
                    identity = %failure.identity(),
                    "worktree-reclaim: the pull-request lookup failed — every branch \
                     will block, and the survey reports this reason (#6561, #6623)"
                );
                // #7057: the repository is part of the reason. A lookup aimed
                // at the wrong repository fails exactly like one aimed at the
                // right one, so the slug rides along to the operator.
                Self::unavailable_because(format!("{failure} (repository searched: {repo})"))
            }
        }
    }

    /// Is this index known to hold every pull request (#2919)?
    ///
    /// Why: the operator-facing output has to disclose when the answer set was
    /// truncated, because on this repository (4526 pull requests against a
    /// [`PR_INDEX_LIMIT`] of 400) it always is — so any worktree whose PR is
    /// older than the last 400 reads `Unknown` and can never be reclaimed from
    /// the bulk index alone. Silence about that would look like "nothing is
    /// reclaimable" rather than "we did not look far enough back".
    /// Test: `pr_index_truncated_reply_makes_absent_branches_unknown`.
    pub(crate) fn is_complete(&self) -> bool {
        self.complete
    }

    /// How many branches this index resolved (#2919).
    ///
    /// Why: a successful `gh` call against a repository with pull requests
    /// yields a non-zero count, so a zero count from a call that ANSWERED is
    /// the silently-blocking shape the `-C` bug produced.
    /// What: this counts branches only. A failed call also yields zero, so a
    /// caller distinguishing the two reads [`state_for`](Self::state_for) on an
    /// absent branch first — `pr_index_from_gh_reads_this_repository` does, and
    /// skips on `LookupFailed` rather than blaming the argv (#7038).
    /// Test: `pr_index_from_gh_reads_this_repository`.
    pub(crate) fn branch_count(&self) -> usize {
        self.by_branch.len()
    }

    /// The state this index reports for `branch`.
    ///
    /// Why: the one place the "absent means nothing only if we saw everything"
    /// rule lives.
    /// What: a detached worktree (`None`) is `Unknown` — there is no branch to
    /// attribute a pull request to, so nothing can prove its work landed. A
    /// present branch returns its recorded state; an absent one returns `NoPr`
    /// when the index is complete, [`BranchPrState::LookupFailed`] when the
    /// lookup itself failed (#6561), and `Unknown` when the index merely ran
    /// past its page limit.
    ///
    /// #7267: a branch the index does not hold under its own name is asked for
    /// again by ROUND STEM, via [`related_state`](Self::related_state) — a
    /// review round renames `<branch>` to `<branch>-r2` while the pull request
    /// keeps whichever spelling it was opened from, so the two names miss each
    /// other by exact match in both directions.
    /// Test: `pr_index_detached_worktree_is_unknown`,
    /// `pr_index_absent_branch_is_no_pr_when_complete`,
    /// `pr_index_reports_a_failed_lookup_with_its_reason`,
    /// `pr_index_resolves_a_round_sibling_by_stem`,
    /// `pr_index_resolves_a_stem_branch_from_its_round_sibling`,
    /// `pr_index_does_not_relate_an_unrelated_branch`.
    pub(crate) fn state_for(&self, branch: Option<&str>) -> BranchPrState {
        let Some(branch) = branch else {
            return BranchPrState::Unknown;
        };
        if let Some(state) = self.by_branch.get(branch) {
            return state.clone();
        }
        // #7267: before "absent" is read as an answer, the round siblings this
        // index DOES hold are consulted.
        if let Some(state) = self.related_state(branch) {
            return state;
        }
        if self.complete {
            return BranchPrState::NoPr;
        }
        // #6561: a branch the index could not answer BECAUSE the lookup failed
        // reports the failure; a merely truncated index still reports
        // `Unknown`.
        match &self.failure {
            Some(reason) => BranchPrState::LookupFailed {
                reason: reason.clone(),
            },
            None => BranchPrState::Unknown,
        }
    }

    /// The most blocking state this index holds for `branch`'s ROUND SIBLINGS
    /// (#7267).
    ///
    /// Why: `tm session prune-worktrees --merged-prs` matched a worktree to its
    /// pull request by exact branch name, and reclaimed 0 of 11 stale trees
    /// because a review round had renamed every one of them. `foo` and `foo-r2`
    /// are one workstream, related here by the same
    /// [`strip_round_suffix`](crate::core::pr_cleanup::plan::strip_round_suffix)
    /// stem `core::pr_cleanup` relates them by and the ADR-0057 removal guard
    /// applies — one implementation of that equivalence, not a second matcher.
    /// What: `None` when the index holds no sibling under a different name;
    /// otherwise the sibling state with the highest
    /// [`BranchPrState::block_rank`], so a MERGED sibling never outvotes an
    /// OPEN one. The lookup costs no network call: it reads rows the bulk index
    /// already holds.
    /// Test: `pr_index_resolves_a_round_sibling_by_stem`,
    /// `pr_index_resolves_a_stem_branch_from_its_round_sibling`,
    /// `pr_index_does_not_relate_an_unrelated_branch`,
    /// `pr_index_open_round_sibling_beats_a_merged_one`.
    fn related_state(&self, branch: &str) -> Option<BranchPrState> {
        let stem = crate::core::pr_cleanup::plan::strip_round_suffix(branch);
        self.by_branch
            .iter()
            .filter(|(name, _)| {
                name.as_str() != branch
                    && crate::core::pr_cleanup::plan::strip_round_suffix(name) == stem
            })
            .map(|(_, state)| state)
            .max_by_key(|state| state.block_rank())
            .cloned()
    }
}

/// Ask `gh` about ONE branch, for when the bulk index was truncated (#2919).
///
/// Why: [`PR_INDEX_LIMIT`] is always exceeded on this repository (4526 pull
/// requests), so the bulk index cannot reach the OLD worktrees — which are
/// exactly the ones a reclamation sweep is for. Falling back to a targeted
/// query for the branches the bulk index could not answer removes that ceiling
/// without paying one network call per worktree in the common case. It costs
/// one call per unresolved branch, so only the operator-invoked reclaim path
/// uses it; the `tm doctor` probe has a 3-second budget and discloses the
/// truncation instead.
/// What: `gh pr list --repo <owner/repo> --head <branch> --state all`, with the
/// slug read from `registry_root`'s own `origin` (#7057). Fork rows are dropped
/// by [`PrIndex::from_json`] exactly as in the bulk path. A failure or timeout
/// yields [`BranchPrState::LookupFailed`] carrying `gh`'s own first stderr line
/// and the repository that was searched (#6561, #7057); it used to yield a
/// cause-free `Unknown`. Either blocks.
///
/// #6561: this resolves a SQUASH-MERGED pull request whose head branch was
/// deleted at merge. `--head` matches the pull request's recorded
/// `headRefName`, which outlives the branch, so all three worktrees the issue
/// names answer `MERGED` here. The deleted branch was never the reason they
/// read unknown — the `gh` call was.
/// Test: `pr_state_for_branch_reports_a_failed_call_as_lookup_failed`,
/// `pr_index_resolves_a_squash_merged_pr_whose_head_branch_was_deleted`.
pub(crate) fn pr_state_for_branch(registry_root: &Path, branch: &str) -> BranchPrState {
    pr_state_for_branch_within(registry_root, branch, GH_TIMEOUT)
}

/// [`pr_state_for_branch`] with the `gh` subprocess bound to `timeout`.
///
/// Why: the same bound [`PrIndex::from_gh_within`] exists for, and it matters
/// more here — this is the SECOND `gh` call a worktree can pay for, so an
/// unbounded one doubles the overrun past a caller's deadline (#6929).
/// What: identical to [`pr_state_for_branch`] but for the subprocess bound.
/// Test: `a_budgeted_survey_answers_within_its_budget`,
/// `pr_state_for_branch_reports_a_failed_call_as_lookup_failed`.
pub(crate) fn pr_state_for_branch_within(
    registry_root: &Path,
    branch: &str,
    timeout: Duration,
) -> BranchPrState {
    const PER_BRANCH_LIMIT: usize = 50;
    // #7057: same per-directory resolution as the bulk index, and the same
    // refusal when it cannot be established.
    let repo = match repo_slug_for(registry_root) {
        Ok(repo) => repo,
        Err(reason) => {
            tracing::warn!(
                root = %registry_root.display(),
                branch = %branch,
                reason = %reason,
                "worktree-reclaim: the repository for this root could not be \
                 established — this branch will block (#7057)"
            );
            return BranchPrState::LookupFailed { reason };
        }
    };
    // #6867: keyed by the BRANCH, not merely the root — two branches do not
    // have the same answer, so sharing one call's stdout between them would
    // be a correctness bug rather than a saving.
    let outcome = gh_gate::shared().poll(registry_root, &format!("head:{branch}"), || {
        // #6623: same resolution as the bulk index — this call has its own
        // working directory and must not rely on the daemon's bare launchd
        // environment either.
        let gh_env = resolve_daemon_gh_env(registry_root, &repo)?;
        let identity = gh_env.describe();
        let mut cmd = gh_pr_list_command(registry_root, &gh_env, &repo);
        cmd.args(["--head", branch, "--state", "all", "--limit"])
            .arg(PER_BRANCH_LIMIT.to_string())
            .args(["--json", PR_JSON_FIELDS]);
        // #6929: bounded by the caller's remaining budget, not a fixed ceiling.
        run_with_timeout(cmd, timeout).map_err(|f| f.with_identity(identity))
    });
    match outcome {
        Ok(stdout) => PrIndex::from_json(&stdout, PER_BRANCH_LIMIT).state_for(Some(branch)),
        Err(failure) => {
            // #6507: WARN, matching `PrIndex::from_gh`. This arm used to be
            // silent at every level, so a per-branch failure — the path this
            // repository's 4526-PR history forces every older branch through —
            // left no trace in the log at all and the survey reported only a
            // count.
            tracing::warn!(
                root = %registry_root.display(),
                repo = %repo,
                branch = %branch,
                reason = %failure,
                identity = %failure.identity(),
                "worktree-reclaim: the per-branch pull-request lookup failed — this \
                 branch will block, and the survey reports this reason (#6507)"
            );
            BranchPrState::LookupFailed {
                // #7057: which repository was asked is part of the reason.
                reason: format!("{failure} (repository searched: {repo})"),
            }
        }
    }
}

/// Is `path` a worktree trusty-mpm provisioned and can therefore remove
/// (#2919)?
///
/// Why: `decommission::remove_session_worktree` refuses any path that carries
/// no ownership sentinel and does not sit under `.worktrees/` — so the
/// harness-owned `.claude/worktrees/` store (out of scope per ADR-0020) can
/// never actually be deleted by this path. Without this gate the survey
/// classified those worktrees `Reclaimable`, counted their bytes into
/// `reclaimable_bytes`, and `tm doctor` told the operator to run a command that
/// then failed with `removal_failed` and left every one of them on disk. On
/// this machine that is MOST of the 1.1 TiB. Advertising a remedy that cannot
/// fire is worse than reporting nothing, so the classifier now applies exactly
/// the predicate the remover applies.
/// What: CALLS the remover's own predicate
/// ([`super::decommission::removal_permitted`]) rather than restating it. It
/// used to restate it, and the restatement drifted (#6561): both copies excluded
/// the harness `.claude/worktrees/` store, so `--merged-prs` reported
/// `0 of 0 measured` against a store full of merged, clean agent worktrees while
/// `agent_worktree_reap` was removing trees from that same store on every agent
/// exit. The tier that admits them lives in `removal_permitted`; this function
/// is now a one-line forward so the classifier and the remover cannot disagree
/// again.
/// Test: `classify_blocks_a_worktree_trusty_mpm_does_not_own`,
/// `tm_provisioned_matches_the_removers_own_predicate`,
/// `worktree_7771_a_hand_made_tree_is_reclaimed`.
pub(crate) fn tm_provisioned(path: &Path) -> bool {
    super::decommission::removal_permitted(path)
}

/// The refusal reason a survey records for a worktree it ran out of time to
/// inspect (#2919).
///
/// Why: named rather than inlined so [`ReclaimSurvey::not_inspected`] can count
/// these WITHOUT the count and the message drifting apart — the whole point is
/// to distinguish "the probe ran out of time" from "the pull-request lookup
/// failed", which read identically before.
/// Test: `survey_separates_deadline_skips_from_lookup_failures`.
pub(crate) const NOT_INSPECTED_REASON: &str = "survey deadline reached before inspection";

/// Decide whether one worktree may be reclaimed (#2919).
///
/// Why: this is the whole safety argument in one function, deliberately
/// written so that `Reclaimable` is reachable ONLY by falling off the end.
/// Every gate `return`s, so no failure branch can advance toward deletion —
/// the fail-open/cursor-advance shape that has bitten this repository
/// repeatedly is structurally impossible here.
/// What: seven gates, in this order.
/// 0. **Owner keep-list** (#6927) — [`KeepList`]: the operator's standing veto,
///    checked before anything that costs a subprocess. DOC-73 §16.4 makes it
///    override every gate below, and it reports `Blocked` so a keep-listed
///    worktree stays VISIBLE in the survey with a reason, rather than being
///    filtered out and becoming indistinguishable from one that was never
///    registered.
/// 1. **Existence/eligibility** — git's own [`Admission`] verdict (ADR-0023
///    point 1). Excludes the main checkout, bare records, operator-LOCKED
///    worktrees, and anything outside the managed project.
/// 2. **Liveness** — a path a session record still claims is never touched,
///    whatever that record's persisted state says (#4288) — EXCEPT when the
///    only claimant is the calling session and the candidate sits inside that
///    session's workspace (#6806). See [`ClaimState`], which resolves that
///    distinction and words the refusal.
/// 3. **Removability** — [`tm_provisioned`]: the classifier applies exactly the
///    ownership predicate the REMOVER applies, so nothing is ever advertised as
///    reclaimable that `remove_session_worktree` would refuse.
/// 4. **Agent ownership** (#5661) — [`agent_ownership_blocks`]. Gate 2 reads
///    session records only, and a dispatched agent has none, so a live agent's
///    worktree was invisible to every gate above this one.
///
///    **4b. Session ownership** (#7652) — [`session_ownership_blocks`] with
///    `owners`. Gate 2 permits a live foreign session's project-root claim
///    over a nested worktree, so the sentinel is what attributes that tree; it
///    permits only an owner the store's tmux probe proves gone.
///
///    **4c. Unattributed nested tree** (#7652 critic round) —
///    [`unattributed_nested_blocks`]: a sentinel that names nobody leaves the
///    live foreign claim gate 2 permitted standing.
/// 5. **Landing evidence** — only [`BranchPrState::Merged`] proceeds.
/// 6. **Unsaved work** — `probe_dirt` is a closure rather than a precomputed
///    `Option` on purpose: passing the value would let a caller reach this gate
///    with a `None` that means "not checked" instead of "checked and clean".
///    The probe is [`inspect_dirt`], which fails toward DIRTY on every error.
///
/// `agent_state` is a closure for the same reason `probe_dirt` is: a caller with
/// no delegation registry to consult must say so by returning
/// [`super::worktree_ownership::AgentDelegationState::Unknown`], which refuses, rather than by handing over
/// an empty list that would read as "no agent claims this".
///
/// Test: one refusal test per gate — `classify_blocks_a_keep_listed_worktree`,
/// `classify_keep_list_outranks_a_merged_clean_worktree`,
/// `classify_blocks_non_admitted_worktree`,
/// `classify_blocks_live_session_workspace`,
/// `classify_allows_a_worktree_claimed_only_by_the_calling_session`,
/// `classify_names_the_foreign_session_that_blocked_a_candidate`,
/// `classify_blocks_a_worktree_trusty_mpm_does_not_own`,
/// `classify_blocks_a_live_agents_worktree`,
/// `classify_blocks_an_agent_the_harness_still_holds_after_a_restart`,
/// `classify_blocks_an_agent_store_worktree_with_an_unreadable_sentinel`,
/// `classify_records_an_agent_refusal_as_its_own_verdict_kind`,
/// `classify_blocks_open_pr`,
/// `classify_blocks_closed_unmerged_pr`, `classify_blocks_no_pr`,
/// `classify_blocks_unknown_pr_state`, `classify_blocks_dirty_worktree` —
/// plus `classify_allows_clean_pushed_merged_worktree` and
/// `classify_allows_a_finished_agents_merged_worktree` for the paths that say
/// yes; gate 4b in `worktree_7652_an_unread_owner_map_refuses` and
/// `worktree_reclaim_owner_liveness_tests`.
// #7652: `owners` is an eighth, required argument for the reason `agent_state`
// is one — a caller with no session store must hand over an UNREAD map.
#[allow(clippy::too_many_arguments)]
pub(crate) fn classify(
    path: &Path,
    admission: Admission,
    claim: &ClaimState,
    pr: &BranchPrState,
    probe_dirt: &dyn Fn(&Path) -> Option<DirtyWorktree>,
    agent_state: AgentStateProbe<'_>,
    owners: &SessionOwners,
    keep_list: &KeepList,
) -> ReclaimVerdict {
    // #7889: gate 5's landed-content admission is OPT-IN, because the predicate
    // behind it fetches. Every caller that does not offer one keeps the
    // pre-#7889 refusal verbatim.
    classify_with_landed_content(
        path,
        admission,
        claim,
        pr,
        probe_dirt,
        agent_state,
        owners,
        keep_list,
        None,
    )
}

/// [`classify`], with gate 5's landed-content admission supplied (#7889).
///
/// Why: the admission runs `git fetch` and `git merge-tree`, so it cannot be
/// reached implicitly by every surveyor — the doctor's unattended, read-only
/// pass must not fetch. Parameterised rather than made unconditional, and
/// spelled as a second entry point rather than a ninth argument on the first,
/// so the forty existing call sites keep their exact behaviour and their exact
/// shape.
/// What: as [`classify`], plus `landed_content`. See [`no_pr_verdict`] for what
/// gate 5 does with it.
/// Test: `worktree_7889_classify_admits_a_landed_tree_with_no_pull_request`,
/// `worktree_7889_classify_refuses_a_tree_holding_residue`,
/// `worktree_7889_classify_refuses_when_the_admission_is_unavailable`,
/// `worktree_7889_classify_refuses_a_dirty_tree_whose_content_is_landed`.
#[allow(clippy::too_many_arguments)]
pub(crate) fn classify_with_landed_content(
    path: &Path,
    admission: Admission,
    claim: &ClaimState,
    pr: &BranchPrState,
    probe_dirt: &dyn Fn(&Path) -> Option<DirtyWorktree>,
    agent_state: AgentStateProbe<'_>,
    owners: &SessionOwners,
    keep_list: &KeepList,
    landed_content: LandedContentProbe<'_>,
) -> ReclaimVerdict {
    // Gate 0 (#6927): the operator's own standing veto outranks every answer
    // the gates below could compute, so it is asked first — see DOC-73 §16.4.
    if let Some(kept) = keep_list.keeps(path) {
        return ReclaimVerdict::blocked(
            ReclaimGate::KeepList,
            format!("{} (#6927)", kept.detail()),
        );
    }
    // Gate 1 (#2919): git decides existence and eligibility, per ADR-0023.
    // #6561: a harness agent lock is a refusal the operator must be TOLD about
    // — it means an agent is working in that tree — so it leaves gate 1 as its
    // own verdict kind and reaches `ReclaimSurvey::agent_owned`. Every other
    // non-admitted verdict is an ordinary block, as before.
    // #7771: a harness lock whose pid is gone or reused is released; only a
    // live, matching holder (or an unjudgeable lock) still refuses here.
    let stale_lock = admission == Admission::HarnessAgentLock
        && match super::worktree_owner_gate::lock_liveness(path).refusal() {
            Some(why) => {
                let reason = format!("{} — {why}", admission.reason());
                return ReclaimVerdict::blocked_by_agent(ReclaimGate::Admission, reason);
            }
            None => true,
        };
    if admission != Admission::Admitted && !stale_lock {
        return ReclaimVerdict::blocked(ReclaimGate::Admission, admission.reason());
    }
    // Gate 2 (#2919): a live session can occupy a directory whose record reads
    // terminal — measured on this repo 2026-07-28. Never trust the state field.
    // #6806: the claim's OWNER decides, not merely its existence. A session
    // pruning worktrees it created inside its own workspace was refused by its
    // own claim, so the only escape was `git worktree remove --force`, which
    // bypasses every gate below this one.
    if let Some(reason) = claim.refusal(false) {
        return ReclaimVerdict::blocked(ReclaimGate::Liveness, reason);
    }
    // Gate 3 (#2919): only worktrees trusty-mpm provisioned can actually be
    // removed. Classifying one it cannot remove as `Reclaimable` made
    // `tm doctor` advertise a command that then failed and left the directory
    // on disk — see `tm_provisioned`.
    if !tm_provisioned(path) {
        // #6561: the harness `.claude/worktrees/` store is no longer named here
        // as out of scope — `removal_permitted` admits it and the remover can
        // now act on it. What remains excluded is a path with none of the three
        // ownership marks.
        return ReclaimVerdict::blocked(
            ReclaimGate::Removability,
            "not a trusty-mpm-removable worktree — no ownership sentinel, not under \
             `.worktrees/`, and not in the harness `.claude/worktrees/` store, so \
             `prune-worktrees` cannot remove it",
        );
    }
    // Gate 4 (#5661): a dispatched agent has no session record, so gate 2 is
    // blind to it, and gate 3 reads only whether a sentinel FILE exists — never
    // whose claim it carries. See `agent_ownership_blocks`.
    // #5829: recorded as its OWN verdict kind, because sparing a live agent's
    // tree is the one refusal the operator must be told about by name — see
    // `ReclaimVerdict::BlockedByAgent`.
    if let Some(reason) = agent_ownership_blocks(path, agent_state, owners) {
        return ReclaimVerdict::blocked_by_agent(ReclaimGate::AgentOwnership, reason);
    }
    // Gate 4b (#7652): gate 2 no longer refuses a live foreign session's
    // project-root claim, so the sentinel's session owner must be proven gone.
    if let Some(reason) = session_ownership_blocks(path, owners) {
        return ReclaimVerdict::blocked(ReclaimGate::SessionOwnership, reason);
    }
    // Gate 4c (#7652 critic round): gate 2 permitted a live foreign claim over
    // this tree because the sentinel attributes it; a sentinel that names nobody
    // leaves that claim standing. See `unattributed_nested_blocks`.
    if let Some(reason) = unattributed_nested_blocks(path, claim) {
        return ReclaimVerdict::blocked(ReclaimGate::Liveness, reason);
    }
    // Gate 5 (#2919): the merged PR is the landing evidence DOC-52 §3.4 makes
    // the reclamation trigger. Everything else — including "we could not find
    // out" — refuses. #7771 (f): with no PR found, every commit on an origin
    // ref is landing evidence too.
    // #8721: a detached HEAD's failed search is `LookupFailed`; still asked.
    if published_route_applies(path, pr)
        && let Some(verdict) = published_verdict(path, probe_dirt)
    {
        return verdict;
    }
    let merged_pr = match pr {
        BranchPrState::Merged { pr } => *pr,
        BranchPrState::Open { pr } => {
            return ReclaimVerdict::blocked(
                ReclaimGate::PrState,
                format!("PR #{pr} is still open"),
            );
        }
        BranchPrState::ClosedUnmerged { pr } => {
            return ReclaimVerdict::blocked(
                ReclaimGate::PrState,
                format!("PR #{pr} was closed without merging"),
            );
        }
        // #7889: the one refusal that is permanent for a tree holding nothing.
        // A donor branch fast-forwarded onto a sibling's head and squash-merged
        // under that name can never acquire a pull request of its own, so this
        // arm asks the landed-content question before it refuses. Owner ruling
        // 2026-09-22; the same predicate the ADR-0057 guard runs.
        BranchPrState::NoPr => {
            return no_pr_verdict(path, probe_dirt, landed_content);
        }
        // #7771: `Unknown` is a detached HEAD or a truncated index, never a
        // failed lookup (that is `LookupFailed`), so it does not blame `gh`.
        // #8721: a detached HEAD reaches the landing admission.
        BranchPrState::Unknown => {
            return unknown_pr_verdict(path, probe_dirt, landed_content);
        }
        // #6561: the lookup broke. Same refusal, but naming the cause — the
        // operator can act on `gh exited 4: … gh auth login`; they cannot act
        // on "could not be determined".
        BranchPrState::LookupFailed { reason } => {
            return ReclaimVerdict::blocked(
                ReclaimGate::PrState,
                format!("the pull-request lookup failed: {reason}"),
            );
        }
    };
    // Gate 6 (#2919): a merged PR does NOT prove the directory holds nothing
    // novel — the 2026-07-21 salvage found merged-PR worktrees carrying real
    // unpushed source. This is the last gate and it fails toward dirty.
    // #7889: commits-only dirt reaches the landing admission — see
    // `merged_pr_verdict`.
    merged_pr_verdict(path, merged_pr, probe_dirt, landed_content)
}

/// One surveyed worktree and everything the survey learned about it (#2919).
#[derive(Debug, Clone, Serialize)]
pub(crate) struct ReclaimCandidate {
    /// The worktree directory, as git reports it.
    pub path: PathBuf,
    /// Short branch name, or `None` when detached.
    pub branch: Option<String>,
    /// The checkout whose git registry listed this worktree.
    ///
    /// Carried so the reclaim loop can rebuild that repository's pull-request
    /// index FRESH before deleting, rather than reusing the survey's (#2919).
    #[serde(skip)]
    pub registry_root: PathBuf,
    /// Bytes on disk, or `None` when the directory could not be measured.
    pub bytes: Option<u64>,
    /// What the pull-request index said about [`branch`](Self::branch).
    pub pr: BranchPrState,
    /// Whether this worktree may be reclaimed, and if not, why not.
    pub verdict: ReclaimVerdict,
}

/// The whole-workspace disk and reclaimability picture (#2919).
///
/// Why: the post-mortem's eighth design constraint is "report real before/after
/// numbers … not merely a claim". These are those numbers.
/// What: every surveyed worktree plus the totals `tm doctor` renders.
/// `total_bytes` sums only what was measurable, so `unmeasured` must be read
/// alongside it — a large `unmeasured` means the total is an UNDERCOUNT.
/// Test: `survey_past_its_measure_deadline_still_classifies`.
#[derive(Debug, Clone, Default, Serialize)]
pub(crate) struct ReclaimSurvey {
    /// Every git-registered worktree under the managed repos root.
    pub candidates: Vec<ReclaimCandidate>,
    /// Sum of `bytes` over candidates that could be measured.
    pub total_bytes: u64,
    /// Sum of `bytes` over candidates whose verdict is `Reclaimable`.
    pub reclaimable_bytes: u64,
    /// How many candidates are reclaimable.
    pub reclaimable: usize,
    /// How many of the RECLAIMABLE candidates actually had their bytes measured.
    ///
    /// Why: `reclaimable_bytes` is a sum over this subset, not over
    /// `reclaimable`. When measurement is starved — and a single 17.8 GiB
    /// worktree can consume a 20-second budget by itself — the sum is a floor
    /// wearing the whole set's label. The `unmeasured` count does NOT cover
    /// this: it is a whole-survey figure, and a reader cannot subtract it to
    /// recover how much of the reclaimable set was measured. Every surface that
    /// prints `reclaimable_bytes` must print this beside it.
    /// Test: `survey_discloses_a_partially_measured_reclaimable_set`.
    pub reclaimable_measured: usize,
    /// How many candidates were refused.
    pub blocked: usize,
    /// How many candidates could not be measured (their bytes are missing).
    pub unmeasured: usize,
    /// How many candidates had an indeterminate pull-request state.
    ///
    /// This counts BOTH causes, so read it with `not_inspected`: subtracting
    /// that leaves the ones where the pull-request lookup itself could not
    /// answer. Separating them is not pedantry — a review round was spent
    /// establishing that 169 unknowns against the real store were repos the
    /// authenticated account cannot see plus detached HEADs, not a second bug.
    pub pr_state_unknown: usize,
    /// Worktrees spared because a DISPATCHED AGENT owns them, as
    /// `"<path>: <reason>"` (#5829).
    ///
    /// Why: gate 4 has refused these since #5661, but the refusal never left
    /// the daemon — the prune route returns counts plus the removed and
    /// re-check-refused lists, and a candidate blocked during CLASSIFICATION
    /// appears in none of them. So `--merged-prs --force` printed
    /// `reclaimed 0 worktree(s)` and named neither the worktree it protected
    /// nor the agent it protected it for. A guard the operator cannot observe
    /// cannot be trusted or debugged in the field, and #5829 asks for the skip
    /// to say why.
    /// Test: `survey_discloses_a_live_agents_spared_worktree`.
    pub agent_owned: Vec<String>,
    /// How many candidates the survey never inspected, because its classify
    /// deadline expired first.
    ///
    /// Why: these are `Unknown` for a completely different reason from a `gh`
    /// failure — the probe ran out of time, not out of answers. Reporting them
    /// as "pull-request state could not be determined" sends an operator to
    /// `gh auth status` for a problem that is really "raise the budget".
    /// Test: `survey_separates_deadline_skips_from_lookup_failures`.
    pub not_inspected: usize,
    /// How many candidates the pull-request lookup FAILED for (#6561).
    ///
    /// Why: distinct from `pr_state_unknown`, which now means only "inspected,
    /// and the answer was genuinely indeterminate". A failed lookup is a fault
    /// with a fix; an indeterminate answer is not. Conflating them produced the
    /// live report this issue is about — 261 of 261 unknown, `0 reclaimable`,
    /// and no cause anywhere in the output.
    /// Test: `survey_counts_a_failed_lookup_apart_from_an_unknown_state`.
    pub lookup_failed: usize,
    /// The FIRST failure reason observed, verbatim from `gh` (#6561).
    ///
    /// One reason rather than a list: every candidate under a broken `gh`
    /// fails identically, so 261 copies of one line would bury the count.
    /// Test: `survey_counts_a_failed_lookup_apart_from_an_unknown_state`.
    pub lookup_failure: Option<String>,
    /// One line per candidate refused by an ordinary [`ReclaimVerdict::Blocked`],
    /// as `"<path>: blocked at <gate>: <reason>"` (#6507).
    ///
    /// Why: `agent_owned` names gate 4's refusals and nothing else, so an
    /// ordinary `Blocked` — every other gate — reached no log line and no field
    /// of the prune reply. On 2026-09-03 that left a worktree whose work had
    /// fully landed sitting unreclaimed with nothing anywhere saying which gate
    /// refused it, and three verification passes attributed it by elimination
    /// to the wrong gate. A refusal the operator cannot read is a refusal
    /// nobody can debug.
    ///
    /// This list and `agent_owned` PARTITION the blocked set: every
    /// [`ReclaimVerdict::BlockedByAgent`] belongs to `agent_owned` alone, so a
    /// candidate appears in exactly one of them and their lengths sum to
    /// `blocked`. The exclusion is by VARIANT, never by gate — `BlockedByAgent`
    /// is constructed at gate 1 (the harness agent lock) as well as at gate 4,
    /// so excluding [`ReclaimGate::AgentOwnership`] would leave the harness-lock
    /// candidate in both lists.
    /// Test: `survey_names_the_gate_that_blocked_each_candidate`,
    /// `survey_lists_an_agent_held_candidate_in_exactly_one_place`.
    pub blocked_reasons: Vec<String>,
}

impl ReclaimSurvey {
    /// Fold `candidates` into the derived totals.
    ///
    /// Why: computing the totals anywhere but here would let a caller publish
    /// a figure that disagrees with the list it came from.
    /// What: one pass; `bytes: None` contributes to `unmeasured` and to no sum.
    /// Test: `survey_past_its_measure_deadline_still_classifies`.
    pub(crate) fn from_candidates(candidates: Vec<ReclaimCandidate>) -> Self {
        let mut out = Self {
            total_bytes: 0,
            reclaimable_bytes: 0,
            reclaimable: 0,
            reclaimable_measured: 0,
            not_inspected: 0,
            blocked: 0,
            unmeasured: 0,
            pr_state_unknown: 0,
            lookup_failed: 0,
            lookup_failure: None,
            agent_owned: Vec::new(),
            blocked_reasons: Vec::new(),
            candidates: Vec::new(),
        };
        for c in &candidates {
            // #6507: folded here, with the totals, for the same reason
            // `agent_owned` is — a disclosed line that is derived anywhere else
            // can disagree with the candidate list it claims to describe.
            // Matched on the VARIANT so every `BlockedByAgent` — gate 1's
            // harness lock as well as gate 4's — is left to `agent_owned` and
            // no candidate is disclosed twice.
            if let ReclaimVerdict::Blocked { gate, reason } = &c.verdict {
                out.blocked_reasons.push(format!(
                    "{}: blocked at {}: {reason}",
                    c.path.display(),
                    gate.label()
                ));
            }
            match c.bytes {
                Some(b) => {
                    out.total_bytes = out.total_bytes.saturating_add(b);
                    if c.verdict.is_reclaimable() {
                        out.reclaimable_bytes = out.reclaimable_bytes.saturating_add(b);
                    }
                }
                None => out.unmeasured += 1,
            }
            if c.verdict.is_reclaimable() {
                out.reclaimable += 1;
                if c.bytes.is_some() {
                    out.reclaimable_measured += 1;
                }
            } else {
                out.blocked += 1;
            }
            // #6561: an inspected-but-indeterminate state and a BROKEN lookup
            // are counted apart, and the first failure keeps its reason.
            match &c.pr {
                BranchPrState::Unknown => out.pr_state_unknown += 1,
                BranchPrState::LookupFailed { reason } => {
                    out.lookup_failed += 1;
                    out.lookup_failure.get_or_insert_with(|| reason.clone());
                }
                _ => {}
            }
            // #5829: collected here, with the totals, so the disclosed list can
            // never disagree with the candidate list it is derived from.
            if let ReclaimVerdict::BlockedByAgent { reason, .. } = &c.verdict {
                out.agent_owned
                    .push(format!("{}: {reason}", c.path.display()));
            }
            // #6507: the deadline skip is now a gate of its own, so the count no
            // longer depends on matching the refusal's wording.
            if matches!(
                &c.verdict,
                ReclaimVerdict::Blocked {
                    gate: ReclaimGate::Deadline,
                    ..
                }
            ) {
                out.not_inspected += 1;
            }
        }
        out.candidates = candidates;
        out
    }
}

/// How many walk entries pass between deadline checks (#2919).
///
/// Why: reading the clock once per file over a terabyte-scale tree is pure
/// overhead, but checking too rarely lets a single worktree blow the whole
/// survey's budget. 4096 entries is roughly a tenth of a second of walking.
/// Test: `measure_bytes_stops_at_an_expired_deadline`.
const DEADLINE_CHECK_INTERVAL: usize = 4096;

/// Bytes held by `path` and everything beneath it, bounded by `deadline`
/// (#2919).
///
/// Why (the measurement): each Rust worktree carries its own `target/` (3–63 GB
/// observed), so worktree COUNT is a useless proxy for disk pressure — bytes
/// are the number the 1.1 TiB post-mortem is actually about.
///
/// Why (the deadline): `tokio::time::timeout` cannot cancel a `spawn_blocking`
/// task. Wrapping the survey in an outer timeout returns a verdict on schedule
/// but leaves the walk running, and tokio's runtime shutdown then waits for
/// that thread. Measured while building this change: two doctor tests each left
/// a walk running over the operator's real ~1 TiB worktree store and the test
/// binary hung for over twenty minutes at shutdown. A blocking task must
/// therefore bound ITSELF; an outer timeout is not a bound, it is a report of
/// one.
///
/// What: a non-following walk summing regular-file lengths, polling the clock
/// every [`DEADLINE_CHECK_INTERVAL`] entries. Symlinks are never followed, so a
/// link out of the worktree cannot inflate the figure or loop. Returns `None`
/// when `path` is not a directory OR the deadline passed — both mean "could not
/// be measured", which the caller counts in `unmeasured` and the doctor check
/// discloses as an UNDERCOUNT. A `None` deadline never expires. Entries that
/// error mid-walk are skipped, which can undercount; that is acceptable because
/// this value is reported, never gated on — no deletion decision reads it.
/// Test: `measure_bytes_counts_file_contents`,
/// `measure_bytes_of_missing_path_is_none`,
/// `measure_bytes_stops_at_an_expired_deadline`.
pub(crate) fn measure_bytes_until(path: &Path, deadline: Option<Instant>) -> Option<u64> {
    if !path.is_dir() {
        return None;
    }
    let expired = |d: Option<Instant>| d.is_some_and(|d| Instant::now() >= d);
    if expired(deadline) {
        return None;
    }
    let mut total: u64 = 0;
    for (seen, entry) in walkdir::WalkDir::new(path)
        .follow_links(false)
        .into_iter()
        .filter_map(Result::ok)
        .enumerate()
    {
        if seen % DEADLINE_CHECK_INTERVAL == 0 && seen > 0 && expired(deadline) {
            return None;
        }
        if entry.file_type().is_file()
            && let Ok(md) = entry.metadata()
        {
            total = total.saturating_add(md.len());
        }
    }
    Some(total)
}

/// Whether a reclamation run may delete anything (#2919).
///
/// Why: the owner's directive asks for merge-triggered cleanup, but every
/// automatic caller uses [`Report`](Self::Report). Deletion is reachable only
/// from an operator action that opts in explicitly, so no timer, hook, or
/// daemon sweep can remove a worktree on evidence this module gathered.
/// What: `Report` surveys and returns; `Remove` additionally deletes the
/// worktrees that pass BOTH the survey and a fresh per-candidate re-check.
/// Test: `reclaim_report_mode_removes_nothing`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum ReclaimMode {
    /// Survey only — the default, and the only mode anything automatic uses.
    #[default]
    Report,
    /// Explicit operator opt-in: delete what the survey and re-check approve.
    Remove,
}

/// What a reclamation run surveyed and (when permitted) removed (#2919).
#[derive(Debug, Clone, Default, Serialize)]
pub(crate) struct ReclaimOutcome {
    /// The full survey, identical in both modes.
    pub survey: ReclaimSurvey,
    /// Worktrees actually deleted (always empty in `Report` mode).
    pub removed: Vec<PathBuf>,
    /// Bytes the removed worktrees held, per the survey's measurement.
    pub removed_bytes: u64,
    /// Candidates the survey approved but the FRESH re-check refused.
    pub refused_at_recheck: Vec<String>,
    /// Candidates the re-check approved but which are still on disk, each as
    /// `"<path>: <reason>"` (#4732 — the reason used to be dropped, and a
    /// deliberate `git worktree lock` refusal read as a transient error).
    pub removal_failed: Vec<String>,
    /// Candidates git failed on after deleting some or all of their content,
    /// each as `"<path>: <report>"` (#8782). Never counted as kept.
    pub partially_removed: Vec<String>,
}

#[cfg(test)]
#[path = "worktree_reclaim_tests.rs"]
mod worktree_reclaim_tests;