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
//! 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 four 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, 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 BTreeMap;
use Read;
use ;
use ;
use ;
use ;
use Admission;
use DirtyWorktree;
/// 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 const PR_INDEX_LIMIT: usize = 400;
/// Environment variables that would point `gh`/`git` at a DIFFERENT repository.
///
/// Why: the same hazard `worktree_safety::GIT_REDIRECTING_ENV` documents —
/// `gh` resolves the repository through git, and an inherited `GIT_DIR` names
/// a repository the worktree under inspection has nothing to do with. A
/// work-destroying gate must not be steerable by ambient environment.
/// What: removed from the child environment so the repository is resolved from
/// `-C <registry_root>` alone.
/// Test: `gh_command_strips_repository_redirecting_env`.
const GH_STRIPPED_ENV: & = &;
/// The pull-request state of the branch a worktree has checked out (#2919).
///
/// Why: only ONE of these five states is evidence that the worktree's work has
/// landed and the directory is disposable. Modelling the other four 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` covers every
/// unanswerable case: `gh` missing, unauthenticated, erroring, a truncated
/// index, or a detached HEAD with no branch to attribute a PR to.
/// Test: `classify_blocks_open_pr`, `classify_blocks_closed_unmerged_pr`,
/// `classify_blocks_no_pr`, `classify_blocks_unknown_pr_state`.
pub
/// One row of `gh pr list --json number,headRefName,state,isCrossRepository`
/// (#2919).
/// 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.
/// 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_unavailable_makes_every_branch_unknown`.
pub
/// A `gh` invocation rooted at `dir` with a sanitised environment (#2919).
///
/// Why: `gh` resolves the repository from its WORKING DIRECTORY. It has no
/// global `-C` flag — that is a `git` habit, and carrying it across made every
/// call in this module fail at flag parsing with
/// `unknown shorthand flag: 'C' in -C` (verified against gh 2.96.0;
/// `gh --help` mentions no `-C`). The failure was silent by design: a failed
/// call yields [`PrIndex::unavailable`], every branch reads
/// [`BranchPrState::Unknown`], `classify` gate 4 blocks every candidate, and
/// the delete loop never executes — so `--merged-prs` reclaimed zero bytes
/// ALWAYS, and `tm doctor` blamed `gh auth status` for what was an argv bug.
/// Nothing in the test suite noticed, because no test ever ran a SUCCESSFUL
/// `gh` call. Hence `current_dir`, and hence
/// `gh_command_passes_no_dash_c_flag`.
///
/// The pager and prompt suppression are not cosmetic either — an interactive
/// prompt in a daemon-run probe hangs it forever. See [`GH_STRIPPED_ENV`] for
/// the environment scrub.
/// What: `gh` with its working directory set to `dir`, the repository-
/// redirecting variables removed, and pager/prompt/colour disabled.
/// Test: `gh_command_passes_no_dash_c_flag`,
/// `gh_command_runs_in_the_requested_directory`,
/// `gh_command_strips_repository_redirecting_env`.
/// The `--json` field set every `gh pr list` call in this module requests.
///
/// Why: named once so the bulk index and the per-branch fallback cannot drift
/// into asking for different facts. `isCrossRepository` is not optional — see
/// [`PrRow::is_cross_repository`]; a `gh` that does not understand the field
/// makes the whole call fail, which yields [`PrIndex::unavailable`] and blocks,
/// rather than silently returning rows with fork PRs indistinguishable from
/// local ones.
/// Test: `pr_index_skips_fork_pull_requests`.
const PR_JSON_FIELDS: &str = "number,headRefName,state,isCrossRepository";
/// Wall-clock ceiling for any single `gh` invocation (#2919).
///
/// Why: `gh pr list` is a NETWORK call. `std::process::Command::output()` has
/// no timeout, so a wedged or throttled request hangs the calling thread
/// forever — and because this runs inside `spawn_blocking`, which cannot be
/// cancelled, that hang propagates to runtime shutdown. This is the same
/// failure shape already fixed for the byte walk; a subprocess needs its own
/// bound for the same reason.
/// What: 10 seconds, after which the child is killed and the call reports
/// failure — which resolves to [`PrIndex::unavailable`] and therefore blocks.
/// Test: `run_with_timeout_kills_a_hung_child`.
const GH_TIMEOUT: Duration = from_secs;
/// Run `cmd`, killing it if it outlives `budget` (#2919).
///
/// Why: see [`GH_TIMEOUT`]. `Command::output()` waits indefinitely.
/// What: spawns the child with piped stdio and DRAINS both pipes on their own
/// threads — a child that fills a pipe buffer blocks forever if nobody reads
/// it, which would defeat the timeout it is meant to enforce (a 400-PR JSON
/// reply comfortably exceeds a 64 KiB pipe buffer). Polls `try_wait` until the
/// budget expires, then kills and reaps the child. Returns `None` on spawn
/// failure, timeout, or a wait error — every failure is indistinguishable to
/// the caller, and every one of them blocks reclamation.
/// Test: `run_with_timeout_captures_output`, `run_with_timeout_kills_a_hung_child`.
/// 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 --head <branch> --state all`. Fork rows are dropped by
/// [`PrIndex::from_json`] exactly as in the bulk path. Any failure or timeout
/// yields [`BranchPrState::Unknown`], which blocks.
/// Test: `pr_state_for_branch_maps_a_failed_call_to_unknown`.
pub
/// 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: mirrors `remove_session_worktree`'s two-tier ownership test — the
/// `.trusty-mpm-worktree` sentinel, or the `.worktrees/<name>` convention.
/// Test: `classify_blocks_a_worktree_trusty_mpm_does_not_own`,
/// `tm_provisioned_matches_the_removers_own_predicate`.
pub
/// 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 const NOT_INSPECTED_REASON: &str = "survey deadline reached before inspection";
/// Whether a worktree may be reclaimed, or the first reason it may not (#2919).
pub
/// 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: five gates, in this order.
/// 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 any session record still claims is never touched,
/// whatever that record's persisted state says (#4288).
/// 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. **Landing evidence** — only [`BranchPrState::Merged`] proceeds.
/// 5. **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.
///
/// Test: one refusal test per gate — `classify_blocks_non_admitted_worktree`,
/// `classify_blocks_live_session_workspace`,
/// `classify_blocks_a_worktree_trusty_mpm_does_not_own`, `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` for the one path that
/// says yes.
pub
/// One surveyed worktree and everything the survey learned about it (#2919).
pub
/// 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`.
pub
/// 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
/// Does any session still claim `path` (#2919)?
///
/// Why: `git worktree list` cannot see a live session, and a session record's
/// persisted state is bookkeeping rather than a liveness signal (#4288). The
/// only defensible test is containment in BOTH directions: a claimed path
/// inside the candidate means the candidate is a live session's parent, and a
/// candidate inside a claimed path means it is a live session's subdirectory.
/// What: compares canonical AND raw spellings of every claimed path — if
/// canonicalization fails on either side the raw form still protects, so a
/// failed observation can only ever spare a worktree, never expose one.
/// Test: `live_check_matches_exact_ancestor_and_descendant_paths`.
pub
/// 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`.
pub
/// What a reclamation run surveyed and (when permitted) removed (#2919).
pub