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
//! Auto-prune definitively-dead (`unresumable`) managed-session records at
//! listing time (owner request 2026-07-29; hardened per code-critic WARN,
//! PR #4384 review).
//!
//! Why: extracted out of `session_picker.rs` (which sits at the 500-SLOC
//! production cap, mirroring why `session_picker_render.rs`/
//! `session_picker_rename.rs` were split out before it). Before this module
//! existed, a session flagged `unresumable` (its workspace GC-pruned out from
//! under it) sat in the picker forever printing `DEAD: workspace removed; use
//! [d<N>] to remove the record` — the operator had to notice the row and type
//! the number themselves, every time.
//!
//! The critic's WARN (then BLOCK on re-review) identified this feature's
//! first cut as converting an advisory flag into an unconditional,
//! unconfirmed, uncapped, unverified destructive action. Four independent
//! hardenings close that gap:
//! 1. **Record-only removal** — [`decommission_dead_record`] calls the
//! `/decommission` route with `record_only=true`
//! (`SessionManager::decommission_record_only`), which touches neither the
//! filesystem nor the runtime. A remount between the listing-time probe and
//! this call can never lose data, because nothing is ever deleted here.
//! (#4728: the "nor the runtime" half was NOT true until that fix — the
//! teardown call sat above the `record_only` guard, so this sweep could
//! SIGTERM and kill a live pane whose name matched the record's. Treat
//! "record-only" as a claim that must stay pinned by tests, never as a
//! property the name guarantees.)
//! 2. **Two-sightings confirmation** — [`auto_prune_dead_records_at`] only
//! acts on a session id first seen dead at least
//! [`SIGHTING_MIN_AGE_SECS`] ago, tracked via a small persisted marker
//! file ([`load_seen`]/[`save_seen`]). A single-shot blip (one bad
//! listing) never triggers a prune, and neither does a tight loop of
//! them — the window is elapsed TIME, not a call count.
//! 3. **Per-call cap** — at most [`AUTO_PRUNE_CAP`] confirmed records are
//! decommissioned per call; the rest are reported as "pending
//! confirmation" rather than acted on. A bad-mount day cannot
//! mass-tombstone an entire fleet in one `tm ls`.
//! 4. **Response-body verification (a daemon/client version-skew guard)**
//! — `record_only=true` alone is not proof of safety: a daemon process
//! still running a build older than this fix has no
//! `Query<DecommissionQuery>` extractor on the route at all, silently
//! ignores the param (axum drops query params a handler doesn't
//! declare), and falls through to the OLD unconditional full-teardown
//! path — which ALSO returns 200. [`decommission_dead_record`] parses
//! the response body and requires `workspace_removed == false` before
//! counting a call as safe; anything else trips
//! [`STALE_DAEMON_MARKER_KEY`], which disables further auto-prune
//! attempts until the sentinel expires ([`STALE_DAEMON_TTL_SECS`], 1
//! hour) — self-healing: one probe per hour against a genuinely stale
//! daemon, not a permanent lockout once it's restarted. Records held
//! back by this gate fold into [`AutoPruneOutcome::pending`], as does a
//! record whose decommission was attempted and FAILED (#4995 review) —
//! neither may disappear from the reported count, because that count is
//! the only notice the operator gets that rows were withheld.
//!
//! What: [`prune_and_report`] is the production entry point (resolves the
//! marker file under `~/.trusty-mpm` and prints the operator summary);
//! [`auto_prune_dead_records_at`] is the testable core (explicit marker-file
//! path); [`AutoPruneOutcome`] is the three-part result (`kept`, `pruned`,
//! `pending`) it reports.
//!
//! Coverage (#4702) — this module used to fire from the interactive TTY picker
//! ONLY, and to act on the daemon-computed `unresumable` flag ONLY. Both
//! narrowings let dead records accumulate without bound:
//! * every piped / scripted / `--json` `tm ls` took `managed::session_ls`,
//! which never pruned — fixed by routing BOTH listing paths through
//! [`prune_and_report`];
//! * `unresumable` is computed daemon-side for records whose PERSISTED state
//! is `Stopped`/`Errored`. A zombie (persisted `Active`, tmux pane gone) is
//! DISPLAY-reconciled to `stopped` but never probed, so it reads
//! `unresumable == false` forever — fixed by
//! [`workspace_verified_gone`], a client-side probe of the same workdir
//! candidates the wire summary carries.
//!
//! Test: `auto_prune_dead_records_removes_confirmed_unresumable_records`,
//! `auto_prune_dead_records_first_sighting_is_not_pruned`,
//! `auto_prune_dead_records_keeps_workspace_present_records`,
//! `auto_prune_dead_records_is_noop_when_nothing_is_dead`,
//! `auto_prune_dead_records_honors_the_cap`,
//! `auto_prune_dead_records_stops_sweep_when_daemon_reports_workspace_removed`,
//! `auto_prune_dead_records_stale_daemon_sentinel_expires_after_ttl`,
//! `auto_prune_clears_stopped_record_whose_workspace_is_gone`,
//! `auto_prune_keeps_stopped_record_whose_workspace_still_exists`,
//! `auto_prune_never_touches_a_running_record`,
//! `auto_prune_never_touches_a_decommissioned_record`,
//! `auto_prune_always_requests_record_only_never_full_teardown`
//! in `tests_behavior_d_tests.rs`; the record-only server-side guarantee is
//! pinned by `decommission_record_only_never_removes_existing_workspace`
//! (`session_manager::tests`).
use ;
use ;
use ManagedSessionSummary;
/// Maximum number of CONFIRMED dead records one call may decommission (critic
/// HIGH finding #1, owner request 2026-07-29).
///
/// Why: "a bad-mount day must not mass-tombstone every session in one `tm
/// ls`" — even a session flagged dead on two consecutive listings might all
/// share one now-unmounted volume. Capping bounds the blast radius of any
/// single call regardless of how many records are confirmed-eligible.
const AUTO_PRUNE_CAP: usize = 5;
/// Basename of the two-sightings confirmation marker file, under the
/// framework root (`~/.trusty-mpm/` by default).
const SEEN_MARKER_FILENAME: &str = "auto-prune-seen.json";
/// Minimum elapsed time between a record's FIRST sighting as dead and the call
/// that may act on it: 10 minutes (#4702).
///
/// Why: "two sightings" is only a safeguard if the two are genuinely separated
/// in time. Before #4702 the check was `seen.contains_key(id)` — presence, never
/// age — so `tm ls; tm ls` confirmed instantly and [`AUTO_PRUNE_CAP`] degraded
/// from a rate limit to a per-call batch size a loop could defeat. Ten minutes
/// is long enough that no scripted or accidental double-listing clears anything,
/// and short enough that an operator's ordinary session-to-session usage still
/// reaps dead rows without ever running a manual command.
const SIGHTING_MIN_AGE_SECS: i64 = 10 * 60;
/// Reserved key inside the marker file recording "a stale daemon already
/// proved it ignores `record_only`" (critic CRITICAL finding, 2026-07-30
/// re-review of PR #4384).
///
/// Why: `?record_only=true` is read by a `Query<DecommissionQuery>`
/// extractor this feature ADDS to the `/decommission` handler. Axum silently
/// drops a query param a handler doesn't declare — a daemon process still
/// running a build older than this fix has no such extractor and falls
/// through to the OLD unconditional full-teardown `decommission()` for EVERY
/// auto-prune call, regardless of the query string sent. The HTTP status
/// alone cannot distinguish that from a genuine record-only success (both
/// return 200) — only the response body's `workspace_removed` field can
/// (see [`decommission_dead_record`]). Once that's observed, auto-prune must
/// stay off for the rest of THIS invocation — the daemon does not un-stale
/// itself mid-process, and the picker's own re-fetch loop calls
/// [`auto_prune_dead_records_at`] repeatedly within one process. Storing this
/// in the SAME marker file (rather than process-global state) keeps the
/// behavior scoped to `marker_path` — exactly like every other piece of
/// state this module tracks — so tests using distinct tempdir paths can
/// never bleed into each other despite `cargo test` running many tests in
/// one process.
/// What: an unlikely-to-collide sentinel key (real session ids are UUIDs);
/// its value is the RFC 3339 timestamp of first detection — checked against
/// [`STALE_DAEMON_TTL_SECS`] by [`stale_daemon_sentinel_active`], not merely
/// its presence.
/// Test: `auto_prune_dead_records_stops_sweep_when_daemon_reports_workspace_removed`,
/// `auto_prune_dead_records_stale_daemon_sentinel_expires_after_ttl`.
const STALE_DAEMON_MARKER_KEY: &str = "__stale_daemon_detected__";
/// TTL for the `STALE_DAEMON_MARKER_KEY` sentinel: 1 hour (owner request
/// 2026-07-30 follow-up).
///
/// Why: a daemon that was stale an hour ago may have been restarted since —
/// wedging auto-prune off permanently would defeat the point of a
/// self-healing safeguard once the operator (or the daemon's own restart
/// machinery) catches up. Expiring the sentinel lets the NEXT invocation
/// retry; if the daemon is STILL stale, [`decommission_dead_record`]'s
/// body-check trips again immediately and rewrites a fresh sentinel — one
/// probe per hour against a genuinely stale daemon, never a permanent
/// lockout.
const STALE_DAEMON_TTL_SECS: i64 = 60 * 60;
/// Result of one `auto_prune_dead_records` / [`auto_prune_dead_records_at`]
/// call.
///
/// Why: the caller (`fetch_live_sessions`) needs three independent numbers to
/// report honestly — what it removed, what it left alone because a
/// confirmation window or the cap wasn't met, and the surviving list to
/// render — rather than collapsing them into a single count.
pub
/// What one listing-time prune hands its caller (#4994).
///
/// Why: the display scoping needs BOTH halves — the surviving rows and which of
/// them the sweep classified dead — and they must come from the same call, or
/// the view is scoped against a classification some other invocation computed.
pub
/// Everything the prune needs from its environment, resolved once per
/// invocation (#4702).
///
/// Why: both inputs — the confirmation marker file and the live-tmux name set —
/// must be injectable, or a test silently depends on the developer's machine.
/// CI caught exactly that: the `session_ls_*` tests reached
/// [`live_tmux_session_names`] directly, so they passed locally (tmux present,
/// enumeration succeeds) and failed on a runner with no tmux, where the
/// fail-closed rule correctly pruned nothing. Bundling both into one value keeps
/// the seam at every layer without growing an eighth positional parameter on
/// `session_ls_at`.
/// What: [`PruneContext::production`] resolves both for real use;
/// `PruneContext::hermetic` takes explicit values for tests.
pub
/// Resolve the confirmation marker file under the default framework root.
///
/// Why: the framework root (`~/.trusty-mpm`) is where every other piece of
/// `tm`'s per-user state already lives (`FrameworkPaths::default`); resolving
/// it here (rather than inside the testable core) keeps the core injectable
/// for tests without touching the real home directory. Exposed to `managed.rs`
/// so `tm session ls`'s production wrapper resolves the SAME file the picker
/// path uses — two marker files would mean two independent confirmation
/// windows for one fleet (#4702).
/// What: `FrameworkPaths::default().root` joined with
/// [`SEEN_MARKER_FILENAME`].
pub
/// Production entry point for EVERY listing surface: prune, print the operator
/// summary, and hand back the surviving sessions (#4702).
///
/// Why: before #4702 the prune fired only where a caller had explicitly opted
/// in with `allow_auto_prune = true`, and the only callers that did were gated
/// on `stdin.is_terminal() && stdout.is_terminal()`. Every piped, scripted, and
/// `--json` invocation therefore accumulated dead records forever — 48 of 66
/// records stale on the reporting machine. The opt-in existed because
/// auto-prune was read as destructive; it is not, and cannot be: the ONLY
/// mutation it performs is [`decommission_dead_record`]'s `record_only=true`
/// call, verified against the response body, which never removes a git
/// worktree, a branch, or any file on disk. Consistency across invocations is
/// therefore strictly safer than an inconsistent opt-in that leaves the list
/// unusable as a picker.
/// What: [`auto_prune_dead_records_at`] against [`default_marker_path`], then
/// the two operator-facing stderr lines (stdout stays clean for `--json` and
/// for pipes), then `outcome.kept`.
/// Test: `session_ls_prunes_dead_records_on_piped_invocation`,
/// `session_ls_json_passthrough_prunes_dead_records`; the decision logic
/// itself via [`auto_prune_dead_records_at`] directly.
pub async
/// [`prune_and_report`] with an injected [`PruneContext`] — the testable core.
///
/// Why: a test must never write the operator's real
/// `~/.trusty-mpm/auto-prune-seen.json`, and must never depend on whether the
/// machine running it has tmux. See [`PruneContext`] for the CI failure that
/// made the second half of that non-negotiable.
/// What: see [`prune_and_report`].
/// Test: `session_ls_prunes_dead_records_on_piped_invocation`.
pub async
/// Build the "N more dead records pending confirmation" line, or `None` when
/// there is nothing to report (#4994; extracted #4995 review).
///
/// Why: this line is the ONLY notice an operator gets that rows were withheld
/// from the default view, so whether it prints is a behavior worth asserting
/// directly rather than through a proxy for it. As an `eprintln!` inline in
/// [`prune_and_report_at`] it could not be — a test could only check the
/// `pending` count the branch happens to key on, which is what let a failed
/// decommission suppress the banner unnoticed.
/// What: `None` when `pending == 0`. The "(hidden; …)" suffix appears only when
/// `hides_dead_rows` — `--json` and `--all` PRINT these rows, and claiming they
/// are hidden where they are visibly listed sends the operator looking for a
/// view they are already in.
/// Test: `auto_prune_counts_failed_decommissions_so_the_banner_still_prints`.
pub
/// The workdir candidates a LISTED session carries on the wire (#4702).
///
/// Why: `session_manager::resume_workdir::workdir_candidates` probes
/// `[last_cwd, workspace_path, cwd]` against the daemon's own `SessionRecord`.
/// `last_cwd` is not part of `ManagedSessionSummary`, so the client can only
/// see the other two — which is why [`workspace_verified_gone`] is deliberately
/// a NARROWER predicate than the daemon's `is_unresumable`, never a wider one:
/// a record this returns "gone" for would also be gone by the daemon's list.
/// What: `[workspace_path, cwd]`, `None`-filtered by the caller.
/// Independently verify, from the CLI, that a listed session has no workdir
/// left on disk (#4702).
///
/// Why: the daemon's `unresumable` flag is computed only for records whose
/// PERSISTED state is `Stopped`/`Errored`. The list endpoint then
/// DISPLAY-reconciles state against live tmux, so a zombie record (persisted
/// `Active`, its pane long gone) shows as `stopped` while its `unresumable`
/// flag was never computed at all — it reads `false` forever and no prune ever
/// touched it. That class is exactly what the reporter saw accumulating. This
/// probe closes the gap client-side rather than changing the daemon, so the fix
/// works against an ALREADY-RUNNING older daemon (a CLI upgrade never bounces
/// it).
///
/// 🔴 This predicate is the ONLY thing standing between a still-recoverable
/// stopped session and a tombstone, so it is deliberately FAIL-CLOSED-TOWARD-
/// KEEPING. `true` requires ALL of:
/// * at least one candidate path was present on the wire (a record carrying
/// none is unverifiable, and is kept);
/// * every candidate's probe came back a definitive `Ok(false)`. A probe
/// `Err` (permission denied, transient I/O) counts as "possibly present";
/// * every candidate's absence is CORROBORATED by a surviving directory above
/// it ([`absence_corroborated`]) — see below.
///
/// 🔴 The reachability check is not defensive padding, it is the whole point of
/// the word "verified". `try_exists("/Volumes/Unplugged/work/proj")` returns
/// `Ok(false)`, NOT `Err`, when the volume is not mounted — ENOENT on an
/// intermediate component is indistinguishable from ENOENT on the leaf. Without
/// it, unplugging an external drive reads as "verified gone" for every session
/// on it, and one `tm ls` tombstones the lot. The only thing we ever call gone
/// is a leaf missing from a directory we can still see. This errs toward
/// keeping — costing one stale row and risking nothing. Measured 2026-08-03:
/// 4 of 5 spot-checked stopped workspaces still existed on disk.
///
/// What: for each of [`workdir_candidates`], `tokio::fs::try_exists` on the path
/// itself, then [`absence_corroborated`] on the surviving tree above it.
/// Test: `auto_prune_clears_stopped_record_whose_workspace_is_gone`,
/// `auto_prune_keeps_stopped_record_whose_workspace_still_exists`,
/// `auto_prune_keeps_record_whose_parent_directory_is_unreachable`,
/// `auto_prune_clears_record_whose_worktree_root_survived_the_removal`,
/// `auto_prune_keeps_record_when_the_worktree_root_itself_is_gone`.
async
/// Directory-name pairs naming a git-worktree CONTAINER — the stable root under
/// which this project's worktrees are created and removed (#4872).
///
/// Why: `git worktree remove` unlinks the whole tree in one operation, so a
/// removed worktree's leaf, its parent and its grandparent all vanish together.
/// A parent-only probe therefore cannot distinguish "the worktree was removed"
/// from "the volume is unmounted", and #4872's four stuck records could never
/// advance. The container directory is not itself part of any worktree, so it
/// survives every removal and disappears only when the filesystem holding it is
/// genuinely unreachable — which is exactly the corroborating anchor the
/// immediate parent fails to be.
/// What: `(parent-dir-name, container-dir-name)` pairs matched against a
/// candidate's ancestors — `.base/.worktrees` (session worktrees) and
/// `.claude/worktrees` (the worktree root `CLAUDE.md` documents).
const WORKTREE_CONTAINER_MARKERS: =
;
/// Whether `dir` is a worktree CONTAINER — the directory that HOLDS worktrees,
/// never an individual worktree itself.
///
/// 🔴 Read the name literally: this is `true` for `.base/.worktrees` and
/// `.claude/worktrees`, and `false` for every worktree inside them. It is the
/// exact OPPOSITE of `session_manager::worktree_safety::is_worktree_root`, which
/// asks whether a path is the root of ONE worktree (`git rev-parse
/// --show-toplevel`). The two answer contradictory questions about the same
/// paths, so they must never share a name (PR #4874 review).
///
/// What: matches the LAST TWO path components against
/// [`WORKTREE_CONTAINER_MARKERS`], so it holds for any checkout location and for
/// nested worktrees alike.
///
/// #5204: the tm-session container's NAME is configurable, so that marker's
/// container component is compared through the shared resolver (configured name
/// OR the built-in `.worktrees`). The `.claude/worktrees` marker is Claude
/// Code's own agent-worktree store (ADR-0020) and deliberately stays a fixed
/// literal — retargeting tm's session base must never reclassify it.
/// Test: `auto_prune_clears_record_whose_worktree_root_survived_the_removal`.
/// Decide whether an absent `candidate` is absent because something was DELETED
/// (corroborated) or because its filesystem is unreachable (#4872).
///
/// Why: see [`WORKTREE_CONTAINER_MARKERS`]. This deliberately does NOT settle for
/// "some ancestor exists" — `/Volumes` survives every unmount, so that weaker
/// rule would reinstate exactly the mass-tombstone the guard was written to
/// prevent.
/// What: walks the ancestors nearest-first. When any [`is_worktree_container`]
/// ancestor still exists, the tree below it was removed — corroborated. When the
/// path has such an ancestor but NONE of them exist, the whole checkout is
/// unreachable — not corroborated. A path with no container ancestor at all
/// falls back to the original immediate-parent rule, unchanged.
/// Test: `auto_prune_clears_record_whose_worktree_root_survived_the_removal`,
/// `auto_prune_keeps_record_when_the_worktree_root_itself_is_gone`,
/// `auto_prune_keeps_record_whose_parent_directory_is_unreachable`.
async
/// Whether a record's lifecycle state makes it eligible for a record-only
/// clear at all (#4702).
///
/// Why: the auto-prune must stay strictly inside the "session is over" class.
/// `decommissioned` records (35 on the reporting machine) are explicitly out of
/// scope — nobody has assessed what discarding them costs — and a `deleted`
/// slot tombstone is a rendering placeholder, not a session. Anything running
/// (`active`, `provisioning`) is untouchable by construction, because the list
/// endpoint reconciles a live tmux pane back to `active` before the CLI ever
/// sees the row.
///
/// 🔴 `errored` records escape that reconciliation entirely:
/// `reconcile_live_state` only rewrites `state` for records persisted
/// `Active`/`Stopped`, so an `Errored` row is served with its persisted state
/// verbatim and a live pane never turns it back into `active`. Tombstoning such
/// a record is not cosmetic — `Decommissioned` is TERMINAL, so a running agent
/// silently becomes unreachable through `tm`: no resume, no reattach, hidden
/// from the picker.
///
/// `attached` alone does not close that: it proves a client is attached, not
/// that no pane exists, so a live-but-DETACHED errored session would still be
/// cleared. `live_tmux_names` closes it (PR #4725 review round 2) — the CLI
/// enumerates live tmux sessions itself and never clears a record whose name is
/// among them. Name membership is a weak signal, but here it is used to KEEP,
/// never to act: a name collision costs one stale row, whereas the same weak
/// signal used to KILL is exactly what made #4728 destructive. When the caller
/// could not enumerate tmux at all it passes an empty set only if it also
/// declines to prune — see [`auto_prune_dead_records_at`].
///
/// What: the DISPLAY state must be `stopped`/`errored`; the row must not be a
/// slot tombstone, must not be `attached`, and must not name a live tmux
/// session; and the PERSISTED state (when the daemon sends it) must not already
/// be terminal.
/// Test: `auto_prune_never_touches_a_running_record`,
/// `auto_prune_never_touches_a_decommissioned_record`,
/// `auto_prune_never_touches_an_attached_record`,
/// `auto_prune_never_touches_an_errored_record_with_a_live_detached_pane`.
/// Enumerate live tmux session names from the CLI (#4702, PR #4725 review).
///
/// Why: the wire summary carries no "this errored record's pane is alive but
/// detached" signal, and adding one would need a daemon change — which this fix
/// deliberately avoids, since a CLI upgrade never bounces the long-lived daemon.
/// Enumerating client-side gives the second liveness signal with no protocol
/// change at all.
/// What: routes through the crate's single tmux spawn point
/// (`core::tmux::run_tmux`, which owns the macOS TCC-disclaim wrapper) with the
/// shared `TmuxCommand::ListSessions` argv, and parses `SESSION_LIST_FORMAT`'s
/// `name:created:attached` rows. Returns `None` when tmux could not be
/// enumerated (not installed, no server, non-zero exit) — the caller treats
/// that as "cannot determine liveness" and prunes nothing, mirroring
/// `reconcile_against_tmux`'s fail-closed contract on the daemon side.
/// Test: `auto_prune_never_touches_an_errored_record_with_a_live_detached_pane`
/// covers the consuming predicate with an injected set; this thin adapter needs
/// a live tmux binary and is exercised in normal operation.
/// The full "this record is definitively dead" predicate (#4702).
///
/// Why: `unresumable` alone missed the majority of what operators see as dead
/// (see [`workspace_verified_gone`]). Widening it is half the fix; the other
/// half is that the daemon's verdict is no longer trusted ON ITS OWN.
///
/// 🔴 There is deliberately NO `if s.unresumable { return true }` short-circuit
/// (PR #4725 review). `is_unresumable` probes with a bare `try_exists`, which
/// answers `Ok(false)` for every path on an unmounted volume — so a daemon can
/// and will flag an entire unplugged external drive's worth of sessions dead. A
/// short-circuit on that flag would hand exactly the scenario
/// [`workspace_verified_gone`]'s parent check exists to prevent straight past
/// the check. Requiring the CLI's own confirmation for EVERY record closes that.
///
/// Dropping the short-circuit costs nothing in coverage: `is_unresumable`
/// requires all three of `last_cwd`/`workspace_path`/`cwd` absent, so any record
/// it flags is one this predicate also finds gone — provided the record carries
/// a path on the wire. A legacy record with neither `workspace_path` nor `cwd`
/// serialized is now kept rather than cleared; unverifiable is not dead.
///
/// What: `is_clearable_state(s, live) && workspace_verified_gone(s)`.
/// Test: the `auto_prune_*` suite in `tests_behavior_d_tests.rs`, in particular
/// `auto_prune_ignores_daemon_unresumable_when_parent_is_unreachable`.
async
/// Auto-prune definitively-dead (`unresumable`) session records at listing
/// time — the testable core (owner request 2026-07-29).
///
/// Why: before this, an operator had to notice the `DEAD: workspace removed`
/// row and manually type `d<N>` for every session whose workspace had been
/// GC-pruned out from under it — Bob's ask was for the picker to just clean
/// these up on its own. The critic's WARN required this to never be a
/// single-observation, uncapped, disk-mutating action — see the module doc's
/// three hardenings.
///
/// SAFETY BOUNDARY (#4344, `114de333`): a record whose worktree removal was
/// previously REFUSED because the tree was dirty keeps its `workspace_path`
/// pointed at a directory that still genuinely exists on disk. `unresumable`
/// (`session_manager::resume_workdir::is_unresumable`) probes that exact
/// path with `tokio::fs::try_exists` and returns `false` the instant ANY
/// candidate (`last_cwd`/`workspace_path`/`cwd`) is found present — so a
/// dirty-retained record can never read `unresumable == true` in the first
/// place, and never enters this function's `dead` partition at all.
///
/// What: partitions `sessions` into `(keep, dead)` by [`is_dead_record`] —
/// the daemon's `unresumable` verdict OR (#4702) a stopped/errored record whose
/// every wire-visible workdir candidate the CLI independently confirmed absent.
/// Any `keep` session that still has a confirmation-marker entry has recovered
/// (its workspace reappeared) — that entry is dropped so a later
/// re-appearance starts a fresh confirmation window. Each `dead` record is
/// then classified against the persisted marker file ([`load_seen`]): a
/// fresh id is recorded as a first sighting (NOT acted on this call); an id
/// already present (seen on a STRICTLY earlier call) is CONFIRMED-eligible.
/// At most [`AUTO_PRUNE_CAP`] confirmed records are decommissioned via
/// [`decommission_dead_record`] — the record-only route, never a raw
/// `fs::remove` or a hand-edited store entry. Everything else (healthy,
/// first-sighting, over-cap, or a failed decommission attempt) is returned
/// in `kept`. The marker file is persisted only when it actually changed.
/// Test: `auto_prune_dead_records_removes_confirmed_unresumable_records`,
/// `auto_prune_dead_records_first_sighting_is_not_pruned`,
/// `auto_prune_dead_records_keeps_workspace_present_records`,
/// `auto_prune_dead_records_is_noop_when_nothing_is_dead`,
/// `auto_prune_dead_records_honors_the_cap`,
/// `auto_prune_dead_records_stale_daemon_sentinel_expires_after_ttl`.
pub async
/// What the persisted marker says about one record's first sighting (#4702).
///
/// Why: the caller must distinguish three cases, not two. Collapsing "no usable
/// stamp" and "stamp present but too recent" into one `false` is what made the
/// window measure the gap between CONSECUTIVE LISTINGS instead of age since
/// first sighting (PR #4725 review): a too-recent entry was restamped with
/// `now` on every call, so any `tm ls` cadence tighter than
/// [`SIGHTING_MIN_AGE_SECS`] reset the clock forever and auto-prune could never
/// fire. On the machine #4702 was filed from, `tm ls` runs far more often than
/// every ten minutes — the feature would have been permanently inert.
/// Classify a stored first-sighting timestamp (#4702).
///
/// Why: see [`Sighting`]. The confirmation rule is "first seen dead at least
/// [`SIGHTING_MIN_AGE_SECS`] ago", which only holds if the ORIGINAL stamp
/// survives every intervening listing.
/// What: parses `ts` as RFC 3339 and compares its age. A missing or unparseable
/// value is [`Sighting::Absent`] — a corrupt marker must restart the window,
/// never satisfy it.
/// Test: `auto_prune_does_not_confirm_two_calls_in_quick_succession`,
/// `auto_prune_does_not_restamp_a_sighting_still_inside_the_window`,
/// `auto_prune_confirms_once_the_sighting_window_has_elapsed`,
/// `auto_prune_treats_an_unparseable_sighting_as_a_fresh_one`.
/// Whether the persisted `STALE_DAEMON_MARKER_KEY` sentinel is still within
/// its [`STALE_DAEMON_TTL_SECS`] TTL (owner request 2026-07-30 follow-up).
///
/// Why: see [`STALE_DAEMON_TTL_SECS`]'s doc — a permanent lockout would
/// outlive the daemon restart that fixes it.
/// What: `true` only when the sentinel is present AND parses as an RFC 3339
/// timestamp no more than [`STALE_DAEMON_TTL_SECS`] old. A missing, corrupt,
/// or expired sentinel returns `false` (retry allowed) — the caller is
/// responsible for clearing an expired entry from `seen` so it doesn't
/// linger.
/// Test: `auto_prune_dead_records_stale_daemon_sentinel_expires_after_ttl`.
/// Load the persisted first-sighting map, tolerating a missing or corrupt
/// file (treated as empty — a listing must never fail merely because its
/// confirmation marker couldn't be read).
///
/// What: `{ "<session-id>": "<rfc3339 first-sighting timestamp>" }`.
/// Best-effort persist of the first-sighting map; a write failure is logged
/// to stderr and never propagated (the listing must never fail merely
/// because the marker file couldn't be written).
/// Outcome of one [`decommission_dead_record`] call.
///
/// Why: an HTTP 200 alone is NOT proof that `record_only` was honored — a
/// stale daemon lacking the `Query<DecommissionQuery>` extractor also
/// returns 200 (from the OLD unconditional full-teardown path). Only the
/// response body's `workspace_removed` field can tell the two apart, so the
/// caller needs a THIRD outcome distinct from plain success/failure.
/// POST the existing `/decommission` route in RECORD-ONLY mode for one
/// confirmed-dead record, best-effort (critic HIGH finding #1; response-body
/// verification added per critic CRITICAL finding, 2026-07-30).
///
/// Why: kept as the single I/O primitive behind [`auto_prune_dead_records_at`]
/// so a per-record transport/HTTP failure can never abort the rest of the
/// listing — one stuck record must not hide every other session behind it.
/// POSTing `?record_only=true` alone is NOT sufficient proof of safety: a
/// daemon process still running a build that predates this route's
/// `Query<DecommissionQuery>` extractor silently ignores the param (axum
/// drops query params a handler doesn't declare) and falls through to the
/// OLD unconditional full-teardown `decommission()` — which also returns
/// 200. This project's daemon is long-lived by design (a CLI upgrade never
/// bounces it), so that version skew is the ROUTINE case, not an edge case.
/// What: POSTs `?record_only=true`; on a 2xx response, parses the JSON body
/// and requires `workspace_removed == false` before returning
/// [`DecommissionOutcome::Pruned`] — the ONLY outcome that proves nothing was
/// deleted. `workspace_removed == true`, a missing field, or an unparseable
/// body all return [`DecommissionOutcome::StaleDaemon`]. A non-2xx status or
/// a transport error is logged to stderr and returns
/// [`DecommissionOutcome::Failed`].
/// Test: `auto_prune_dead_records_removes_confirmed_unresumable_records`
/// drives the happy path through a real loopback daemon;
/// `auto_prune_dead_records_stops_sweep_when_daemon_reports_workspace_removed`
/// drives the stale-daemon path through a stub server that ignores
/// `record_only` and always reports `workspace_removed: true`.
async