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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
//! Bare `tm` guided default mode — session picker (#1705, #1708).
//!
//! Why: typing `tm` alone — with no subcommand — should do the most useful
//! thing for the operator's current context. Inside a GitHub-backed git
//! repository with a reachable daemon, the guided default (#1705) queries the
//! daemon for existing sessions bound to the detected `owner/repo`, shows them
//! in a numbered list, and lets the operator resume or launch with a single key.
//! When the daemon is unreachable or the project is not GitHub-backed, the
//! protected fallback (#1724) ensures the live checkout is never touched.
//!
//! What: [`run_guided_default`] orchestrates detection, listing, and dispatch.
//! [`derive_project`] derives the `source_id`, managed workspace, and git root.
//! [`fallback_protected`] is the three-way dispatch for the daemon-unreachable
//! path; it is also the target for non-GitHub projects. [`non_github_refusal_message`]
//! is the pure helper that produces the accurate refusal text for the
//! non-GitHub-remote case (see #1777). The TTY picker is split into a pure
//! `parse_picker_choice` + an I/O driver `run_tty_picker`.
//!
//! Test: unit tests for detection and fallback live in `tests_behavior_b_tests.rs`
//! (#1724 regression suite) and `tests_behavior_c_tests.rs` (#1705 new UX suite);
//! the managed-spawn integration path is exercised by `tests/session_manager_mvp.rs`.
use Context as _;
use IsTerminal as _;
pub use github_host;
// #3714 line-cap follow-up: the resolver + tie-break logic moved to the
// sibling `guided_resolver` module (mirrors `guided_autostart`/
// `guided_inplace`'s own extraction pattern) — imported here (not
// re-exported) since `nested_managed_match` is only called internally by
// `nested_session_guard` below; nothing outside this crate's tests
// addresses it via `guided::nested_managed_match`.
use nested_managed_match;
use crateDaemonInfo;
// ── Entry point ──────────────────────────────────────────────────────────────
/// Bare `tm` guided default — detect project, list sessions, and offer a picker.
///
/// Why: operators who type `tm` from inside a project directory should not
/// have to remember `tm session new`, `tm connect`, or `tm attach <name>` —
/// the guided default derives the project identity, shows existing sessions,
/// and lets them resume or launch in one step. The live checkout is NEVER
/// written to; all managed sessions run in the protected base-clone workspace.
/// What: (0) an operator-supplied `--url` / `TRUSTY_MPM_URL` that is
/// unreachable errors out immediately (issue #1737 — see below) before any
/// of the following runs; (1) tries the rich picker UX when the daemon is
/// reachable and the CWD is a GitHub-backed git project; (2) falls through to
/// [`fallback_protected`] for every other case (daemon unreachable, non-GitHub
/// remote, non-git directory). Non-TTY piped invocations print project + session
/// info and exit 0 without hanging for input (#1705 AC-7). Subdir launches
/// pass the git root as `repo_url` so the daemon sets `source_id` correctly.
///
/// #1737: `url` is the already-resolved string every caller downstream of
/// here uses (unchanged); `explicit` carries the ORIGINAL `Option::is_some`
/// signal — `Some` iff the operator actually supplied `--url` /
/// `TRUSTY_MPM_URL` (never a clap default, per the #2487 discipline — see
/// `core::discovery`'s module doc). This function is the one LIVE,
/// empirically-confirmed instance of the #1737 silent-fallback bug:
/// [`super::guided_autostart::ensure_daemon_started`]'s auto-start step
/// intentionally ignores whatever URL it is handed and always re-resolves
/// IMPLICITLY (lock file → default) once *some* daemon is confirmed healthy
/// — exactly right for the ordinary "daemon not started yet" first-run UX
/// this function exists to smooth over, but it means an unreachable EXPLICIT
/// `--url` silently ended up auto-starting (or reconnecting to) a completely
/// different, real daemon and showing ITS live session list instead of
/// erroring. Probing `explicit` up front — before in-place relaunch, the
/// nested-session guard, the picker, or auto-start ever run — closes that
/// gap without touching the implicit (unset URL) path at all.
/// Test: `guided_derive_project_returns_none_for_non_git_dir`,
/// `guided_non_tty_gate_returns_false_skips_stdin`,
/// `guided_fallback_never_pollutes_github_git_checkout` (#1724);
/// `tests/tm_guided_default_explicit_url.rs` end-to-end (#1737).
pub async
/// Attempt to list sessions and display the interactive picker for a GitHub project.
///
/// Why: the same "list sessions → two-panel-banner → picker" sequence is needed
/// both on the initial attempt and after a successful auto-start. A shared helper
/// keeps `run_guided_default` DRY and avoids divergence between the two call sites.
/// What: fetches the project's live sessions via the shared
/// [`super::session_picker::fetch_live_sessions`] (decommissioned tombstones
/// already filtered, #1809), runs the tty-gate, renders the two-panel daily
/// banner (#1808), then hands off to [`super::session_picker::run_tty_picker`].
/// Returns `None` when the daemon is unreachable so the caller can try
/// auto-start; returns `Some(result)` once the daemon responded.
/// Test: indirectly covered by guided-default e2e tests; the pure sub-functions
/// (`tty_gate`, `parse_picker_choice`, `is_live_session_state`) are unit-tested
/// independently.
async
// ── Project derivation ───────────────────────────────────────────────────────
/// Derive the GitHub `source_id`, managed workspace, and git root from `cwd`.
///
/// Why: the picker needs the `owner/repo` identity (for filtering sessions by
/// `source_id`), the managed workspace path (for display), and the git root
/// path (to pass as `repo_url` so the daemon sets `source_id` correctly even
/// when `tm` is invoked from a subdirectory — #1705 LOW fix).
/// What: finds a *usable* git root (via [`usable_git_root`] — an ancestor `.git`
/// is trusted only when `cwd` is genuinely part of that repo's tracked tree, so
/// an untracked directory nested inside another repo does NOT inherit that
/// repo's identity — #2534), reads `remote.origin.url`, guards that it is a
/// GitHub URL, parses `owner/repo` via `parse_github_path`, and returns
/// `(source_id, workspace_path, git_root)` where `source_id = "owner/repo"`,
/// `workspace_path = ~/trusty-mpm-projects/<owner>/<repo>` (the canonical base),
/// and `git_root` is the absolute path of the repository root.
/// Test: `guided_derive_project_returns_none_for_non_git_dir`,
/// `guided_derive_project_rejects_non_github_remote`,
/// `guided_derive_project_accepts_github_https_remote`,
/// `guided_derive_project_returns_some_from_subdir`,
/// `guided_derive_project_returns_none_for_untracked_ancestor_subdir`.
pub
// ── Nested-session guard (#2157 item 4) ──────────────────────────────────────
/// I/O driver for the nested-session guard: resolve the current tmux context,
/// fetch every managed session (unfiltered — a record's `source_id` may be
/// missing, see #2157 item 5), and apply [`nested_managed_match`].
///
/// Why: extracted from [`run_guided_default`] so the "gather the two matching
/// keys, ask the daemon, apply the pure predicate" sequence is one readable
/// unit. Fetches the FULL session list (no `?source_id=` filter) rather than
/// reusing `list_project_sessions` — the whole point of this guard is to catch
/// a managed record the project-filtered list would MISS (e.g. one whose
/// `source_id` write never landed, #2157 item 5's failure mode).
/// What: short-circuits to `None` when not inside tmux (nothing to guard
/// against) or when the daemon is unreachable/errors (fail-open — matches
/// every other daemon round-trip in this file, which falls through to the
/// picker/autostart rather than blocking on a down daemon). The fetch goes
/// through [`guard_managed_sessions`], which (#4335) asks for the SLIM listing
/// — the guard never reads `stale_assets` — allows 8 seconds rather than 2,
/// and LOGS the failure arm instead of discarding it. Before that, a cold
/// daemon's per-session staleness pass regularly blew the 2s bound and the
/// guard silently no-opped, so bare `tm` after a backgrounded Claude Code fell
/// to the picker and dead-ended on the #2678 refusal until a second run.
/// Test: the pure decision is `nested_managed_match_*` in
/// `tests_behavior_c_tests.rs`; the fail-open arm is
/// `guard_managed_sessions_returns_none_when_the_list_call_errors`; the rest of
/// this I/O wrapper is exercised by manual smoke tests and the e2e suite
/// (requires a live daemon + tmux).
async
/// Pure predicate (#2456 review finding 1, ROUND 2 — the round-1 env-var
/// gate was empirically disproven): does the CURRENT pane's own stable tmux
/// `pane_id` confirm THIS pane is the one bound to `record_pane_id` — as
/// opposed to [`nested_managed_match`] having matched purely on tmux SESSION
/// name (a signal every window/pane in that session shares)?
///
/// Why: the round-1 fix compared `TM_MANAGED_SESSION_ID` process env values,
/// reasoning that env var was pane/process-scoped. That premise was proven
/// FALSE against a live tmux 3.6b: `mark_runtime_exited_stopped`'s healing
/// step calls `tmux set-environment -t <session>` — SESSION-scoped — and
/// tmux applies a session's stored environment to the process env of every
/// NEW pane/window created in that session AFTERWARD. tmux's own `pane_id`
/// (e.g. `"%5"`, distinct from `pane_pid`, which the OS can reuse across a
/// pane's lifetime) is NEVER inherited across panes — see
/// [`SessionRecord::pane_id`](trusty_mpm::session_manager::SessionRecord::pane_id)'s
/// doc for the full rationale and [`super::tmux_attach::current_tmux_pane_id`]
/// for how the CURRENT pane's id is resolved.
/// What: moved to [`super::pane_identity::pane_identity_confirmed`] (issue
/// #3600) — that module is now the ONE shared cross-check primitive used by
/// this guard AND by `rename.rs`/`pm_guard_deny_by_default.rs`, so the same
/// hijack this guard fixed here doesn't rot back into a divergent (or
/// missing) copy elsewhere. Re-exported so existing imports of
/// `crate::commands::guided::pane_identity_confirmed` keep resolving.
/// Test: see `super::pane_identity`'s module doc for the full test list.
pub use pane_identity_confirmed;
/// The action the nested-session guard takes when it matched a record by tmux
/// SESSION name but could NOT confirm pane-level identity
/// ([`pane_identity_confirmed`] was `false`).
///
/// Why: the pre-#2777 fallback ALWAYS reconnected (switch-client) to the matched
/// session. That is correct when the session has a live runtime in a sibling
/// window — the switch brings it forward. But when the session is DEAD
/// (decommissioned/stopped/errored), there is no live runtime anywhere in that
/// tmux session, so a switch-client to the session the operator is already
/// inside is a guaranteed no-op dead-end (the reported bug: bare `tm` inside a
/// `decommissioned` `tm-apex-01` printed "switching client to session
/// 'tm-apex-01'" and stranded the operator in the bare shell). Splitting the two
/// cases lets the dead case relaunch the agent in place instead.
pub
/// Pure decision for the nested-guard fallback: relaunch-in-place vs reconnect,
/// derived solely from the matched record's `state`.
///
/// Why: isolating the classification from the daemon/tmux I/O makes the
/// dead-vs-live decision exhaustively unit-testable (#2777), mirroring the
/// `switch_decision`-style pure seam pattern (#2680).
/// What: dead/tombstone states with no live runtime
/// (`decommissioned`/`stopped`/`errored`) →
/// [`NestedFallbackAction::RelaunchInPlace`]; every other state
/// (`active`/`provisioning`/`running`/unknown) → the safe default
/// [`NestedFallbackAction::Reconnect`], preserving the pre-#2777 behavior for a
/// possibly-live sibling window.
/// Test: `nested_fallback_action_relaunches_dead_states`,
/// `nested_fallback_action_reconnects_live_states` in `tests_behavior_c_tests.rs`.
pub
/// Build the operator-facing notice for the nested-session guard's fallback
/// path — reused by both call sites that print it before falling through to
/// [`super::guided_resume::resume_guided_session`].
///
/// Why: the two call sites previously printed "…refusing to launch a nested
/// session here." as a standalone line, immediately followed by a SEPARATE
/// "reconnecting to '{name}' instead…" line. When the subsequent reconcile
/// (or plain restart) succeeds, that reads as a contradiction: the operator
/// sees "refusing" — which sounds like a hard failure — immediately followed
/// by a session that comes up fine anyway. Nothing was actually refused: `tm`
/// deliberately chose the reconnect path over nesting a new session, and that
/// choice went on to work. Folding both lines into one, reworded message
/// removes the false "this failed" signal without hiding WHY a fresh session
/// was not launched here.
/// What: returns the single-sentence notice — "not nesting a new session
/// here; reconnecting to '{name}' instead…" — that replaces both the old
/// "refusing…" line and the old separate "reconnecting…" line.
/// Test: `nested_guard_notice_never_says_refusing`,
/// `nested_guard_notice_mentions_reconnect_target`.
pub
/// Actionable hint (#2789, corrected #2794) printed when bare `tm` runs inside
/// a managed session's OWN pane (pane identity confirmed) but the in-place
/// relaunch could not proceed.
///
/// Why: reconnecting to the very session whose pane the operator is already
/// inside is a `switch-client` no-op that strands them in a bare shell — the
/// reported dead-end (`tm-cto-01` transcript). When the in-place relaunch
/// cannot run (a genuinely live sibling window, a daemon predating the
/// caller-pane reconcile, or a failed `exec`), the honest response is to tell
/// the operator how to relaunch the agent themselves. #2794: the prior wording
/// suggested a bare `claude` (or `claude --resume <id>`), which is WRONG — a
/// raw `claude` launches OUTSIDE the managed session, dropping the tm-owned
/// `CLAUDE_CONFIG_DIR`, the agent roster, and the persona (the DOC-34 managed
/// config). The managed relaunch is `tm sessions resume <id>`, which re-spawns
/// the runtime with the full managed environment intact — that is the only
/// correct advice, so the hint always points there.
/// What: a single-line hint suggesting `tm sessions resume <managed-id>`
/// (`record.id`, the managed session id — NOT the claude conversation id). Pure
/// — takes an already-fetched record, returns the string.
/// Test: `inplace_self_relaunch_hint_suggests_managed_resume`,
/// `inplace_self_relaunch_hint_never_suggests_bare_claude`.
pub
/// Fetch EVERY managed session, unfiltered — `GET /api/v1/sessions/managed`
/// with no `?source_id=` query.
///
/// Why: [`nested_session_guard`] must find a match even when the record's
/// `source_id` is missing (#2157 item 5's failure mode), so it cannot reuse the
/// source_id-filtered picker fetch ([`super::session_picker::fetch_live_sessions`]).
/// What: GETs the managed-list endpoint with no `?source_id=` query, with
/// `?slim=true` and an 8-second timeout (#4335 — both explained below).
///
/// `?slim=true` (#4335, folds into #4322): the guard reads `name`, `pane_id`,
/// `state`, and `id` — never `stale_assets`. That flag is the most expensive
/// thing the endpoint computes (a filesystem-bound catalog compose plus a
/// per-session manifest/on-disk comparison), so the guard was paying for a
/// field it discards. Opting out is the actual fix; the timeout below is the
/// belt to its braces.
///
/// The timeout is 8s, not the 2s this shared the `guided_inplace` probe
/// convention with. On a COLD daemon the per-session `stale_assets` pass over
/// a large fleet exceeded 2s, the request was cancelled, and the guard's
/// `.ok()?` swallowed it without a single log line — so bare `tm` after a
/// backgrounded Claude Code fell through to the picker and dead-ended on the
/// #2678 switch-client refusal, while a second invocation (warm daemon) worked.
/// A guard that silently stops guarding is worse than a slow one: the 2s bound
/// existed to keep a HUNG daemon from stalling bare `tm`, and 8s still bounds
/// that while clearing a cold-start listing.
/// Test: I/O path; the fail-open decision is
/// `guard_managed_sessions_returns_none_when_the_list_call_errors`.
async
/// [`list_all_managed_sessions`] for [`nested_session_guard`], with the
/// fail-open arm LOGGED rather than silently swallowed (#4335).
///
/// Why: the guard used a bare `.ok()?`, so every failure mode — timeout,
/// daemon down, malformed body — produced the identical observable behaviour
/// as "no sessions matched": the guard no-opped and the flow fell through to
/// the picker. #4335 took a live repro plus a code read to establish that the
/// guard had not run at all, because there was nothing in any log to say so.
/// One `tracing::debug!` on the error arm makes the difference between "guard
/// ran, found nothing" and "guard never ran" visible under `RUST_LOG=debug`.
/// What: `Some(sessions)` on success; `None` after logging the error. Keeps
/// the fail-open contract — a down daemon must not block bare `tm` — but stops
/// it from being invisible.
/// Test: `guard_managed_sessions_returns_none_when_the_list_call_errors`,
/// `guard_managed_sessions_returns_sessions_on_success`.
pub async
// ── Display / TTY-gate helpers ────────────────────────────────────────────────
/// Print project context and decide whether to run the interactive picker.
///
/// Why: a testable seam over `std::io::stdin().is_terminal()`. By injecting
/// `is_tty`, callers in tests can exercise the non-TTY branch without a live
/// stdin — confirming that the branch returns `false` (no picker needed) and
/// thus prevents any attempt to read from stdin (#1705 AC-7 / HIGH-2b).
/// What: always calls [`print_project_context`]. If `is_tty = false`, also
/// calls [`print_non_tty_hint`] and returns `false`. If `is_tty = true`,
/// returns `true` (caller should invoke [`super::session_picker::run_tty_picker`]).
/// Test: `guided_non_tty_gate_returns_false_skips_stdin`,
/// `guided_tty_gate_returns_true_for_tty`.
pub
/// Format one project-context session row (#3741: no `tm:` prefix, leads
/// with the `[N]` index — matching `session_picker_render::format_session_row`'s
/// convention for the interactive picker's rows).
///
/// Why: extracted to a pure, directly assertable function rather than only
/// exercised via `print_project_context`'s `eprintln!` side effect — the
/// #3741 code-critic finding was exactly this row silently drifting back to
/// the old `tm: [N] …` shape with no test pinning its exact text.
/// What: `[{i+1}] {name} state={state} last={activity}` — `i+1` is this
/// listing's plain 1-based position (deliberately NOT the picker's stable
/// `shown_slot` numbering; unifying the two is out of scope for #3741).
/// Test: `guided_format_project_context_row_*` in `tests_behavior_c_tests.rs`.
pub
/// Print the detected project and session list to stderr.
///
/// Why: the operator needs to see at a glance which project was detected, where
/// the managed workspace lives (so it is clear the live checkout is untouched),
/// and which sessions are available before being prompted.
/// What: prints the source_id, workspace path, and a numbered session list (or
/// "(none)" when empty). All output goes to stderr (stdout stays clean). Row
/// text comes from [`format_project_context_row`] (#3741: no `tm:` prefix).
/// Test: `guided_print_project_context_does_not_panic_no_sessions`,
/// `guided_print_project_context_does_not_panic_with_sessions`,
/// `guided_format_project_context_row_*`.
pub
/// Print a non-TTY degradation notice and actionable hints.
///
/// Why: when stdin is not a TTY (CI, pipes, scripts), hanging for input would
/// block the caller forever; print the context and exit cleanly instead (#1705 AC-7).
/// What: emits one-line notice + resume/launch hints to stderr. The caller
/// returns `Ok(())` immediately after.
/// Test: `guided_print_non_tty_hint_does_not_panic_no_sessions`,
/// `guided_print_non_tty_hint_does_not_panic_with_sessions`,
/// `guided_non_tty_gate_returns_false_skips_stdin`.
pub
// ── Guided resume/restart ────────────────────────────────────────────────────
//
// The resume/restart flow (zombie auto-reconcile, daemon /resume, attach) lives
// in the sibling `guided_resume` module (#2001) to keep both files under the
// 500-SLOC production cap. The picker calls
// `super::guided_resume::resume_guided_session`; the pure seams
// (`needs_restart`, `is_zombie`, `plan_resume`, `ResumeAction`) are unit-tested
// there directly.
// ── Fallback (daemon-unreachable / non-GitHub) path ─────────────────────────
/// Build the user-facing refusal notice for a non-GitHub-remote refusal.
///
/// Why: the non-GitHub-remote branch of [`fallback_protected`] previously
/// printed "daemon unreachable" wording, which is wrong when the daemon IS
/// running — the refusal is purely because `tm` only auto-manages GitHub
/// repositories. Extracting the message into a pure helper makes it
/// unit-testable without capturing stderr.
/// What: returns a three-line notice that names the non-GitHub remote as the
/// reason for refusal and reassures the operator that the live checkout was
/// not modified. The caller prints via `eprintln!` and then bails.
/// Test: `guided_non_github_refusal_message_*` in `tests_behavior_c_tests.rs`.
pub
/// Return true when the remote URL targets GitHub (any transport or SSH alias).
///
/// Why: `parse_github_path` from `trusty-common` accepts *any* git remote URL,
/// not just GitHub ones. We need a host-specific guard so that non-GitHub git
/// projects (Gitea, GitLab, bare SSH, etc.) are refused rather than having a
/// clone attempt made against an unrecognised host (#1724 residual gap). We
/// also need to recognise GitHub repos accessed via multi-account SSH host
/// aliases (e.g. `git@github-duetto:owner/repo.git` via `~/.ssh/config`).
/// What: extracts the host via [`github_host`], then accepts it when:
/// (a) host == `"github.com"` (the canonical GitHub host), OR
/// (b) host starts with `"github-"` or `"github_"` (SSH alias convention —
/// e.g. `github-duetto`, `github-work`, `github_personal`).
/// Decision — GitHub Enterprise (`github.mycompany.com`): NOT matched. GHE
/// uses a dot separator after `github`, and the broader managed-clone
/// infrastructure is not tested against GHE; erring on the side of safety
/// avoids an unexpected redirect for GHE users.
/// Does NOT match: `githubusercontent.com` (the `u` after `github` is
/// alphanumeric, so neither rule fires), `gitlab.com`, `bitbucket.org`, or
/// any other host.
/// Test: `is_github_remote_*` unit tests in `tests_behavior_c_tests.rs`;
/// `guided_fallback_never_pollutes_github_git_checkout` (real `github.com` URL);
/// `guided_fallback_blocks_non_github_git_checkout` (Gitea URL must be blocked).
pub
/// Detect the git working-tree root at any depth by shelling to git.
///
/// Why: `cwd.join(".git").exists()` only fires when `cwd` IS the repo root.
/// Operators commonly run `tm` from a nested subdirectory (e.g. `~/project/src/`);
/// the shallow check would miss the repo, bypass the live-checkout guard, and
/// allow `launch(None)` to write framework files into that subdir (#1724 gap).
/// What: runs `git -C <cwd> rev-parse --show-toplevel`; returns the absolute
/// repo root on success, `None` when cwd is not inside any git working tree
/// (plain directory or bare repo). Bare repos (`--git-dir` succeeds but
/// `--show-toplevel` does not) are treated as non-git — deploying into a bare
/// repo has no live-checkout to protect.
///
/// `pub(crate)` since #4300: `managed_workspace::provision_for_launch` must
/// resolve the repo root the SAME way this path does. `tm launch` has no
/// `classify_cwd_project` pre-pass, so without a shared definition the two CLI
/// entry points answered "which directory is this project?" differently and
/// `tm launch` from a subdirectory deployed into that subdirectory.
/// Test: `guided_fallback_blocks_github_git_from_subdirectory` calls
/// `fallback_protected` from a nested subdir and asserts the protection fires;
/// `provision_for_launch_from_subdirectory_targets_repo_root` covers the
/// `tm launch` side.
pub
// ── Ancestor-repo trust guard (#2534) ────────────────────────────────────────
/// Classification of `cwd` with respect to the nearest enclosing git working tree.
///
/// Why: [`find_git_root`] happily walks *up* to an ancestor `.git`. That is
/// correct for a subdirectory the operator actually committed, but WRONG when
/// `cwd` is an unrelated directory that merely happens to live inside another
/// repository's working-tree span — e.g. an untracked notes folder `~/Duetto/cto`
/// that case-folds onto the enclosing repo's tracked `CTO/` dir on a
/// case-insensitive filesystem (APFS). Trusting the ancestor there made bare
/// `tm` silently resolve to the ancestor repo's project and offer its sessions
/// (#2534). This enum lets both `cwd → project` resolution paths distinguish the
/// three cases with a single git query.
/// What: `Usable` = `cwd` is the repo root itself, or a subdirectory that IS part
/// of the tracked tree — safe to inherit the repo's identity. `UntrackedInsideAncestor`
/// = `cwd` is a strict subdirectory of a git working tree but is NOT in its
/// tracked tree — must be treated as a non-project. `NotGit` = `cwd` is not inside
/// any git working tree.
/// Test: `guided_classify_cwd_usable_for_tracked_subdir`,
/// `guided_classify_cwd_untracked_for_uncommitted_subdir`,
/// `guided_classify_cwd_not_git_for_plain_dir`.
pub
/// Does `cwd` directly own a `.git` entry — i.e. is `cwd` itself a working-tree
/// root, whose identity must never be inherited from an enclosing ancestor?
///
/// Why: the own-repo-wins guard (#2542). A `.git` entry is either a directory
/// (normal repository) or a *file* (a linked-worktree / submodule gitlink whose
/// content is `gitdir: <path>`) — BOTH mean `cwd` is a working-tree root. The
/// match MUST be on the EXACT entry name `.git`: a `.git`-prefixed sibling such as
/// `.git.hotstats-backup-20260713` (a preserved gitdir from a rescue) is NOT a
/// repo marker and must be ignored, so a `starts_with(".git")`/glob test would be
/// a bug. `Path::join(".git")` composes the exact name and `try_exists` follows a
/// `.git` symlink to its target while still reporting a broken/absent entry as
/// not-owned.
/// What: returns `true` when `cwd/.git` exists as any file-system entry (dir,
/// file, or a symlink resolving to one), `false` when it is absent or a query
/// error occurs (fail-open to the git-walk path — never falsely claim ownership).
/// Test: `guided_cwd_owns_git_entry_true_for_dir`,
/// `guided_cwd_owns_git_entry_true_for_pointer_file`,
/// `guided_cwd_owns_git_entry_false_for_dotgit_prefixed_sibling`,
/// `guided_cwd_owns_git_entry_false_when_absent`.
pub
/// Classify `cwd` against its nearest enclosing git working tree, verifying
/// tracked-tree membership before trusting an *ancestor* repo's identity.
///
/// Why: closes the ancestor-`.git` trust gap (#2534) AND the inverse gap where a
/// directory that DOES own its repo was wrongly adopted into an ancestor (#2542).
/// `find_git_root` alone cannot tell an intentionally-nested tracked subdirectory
/// apart from an unrelated directory that merely falls inside a repo's path span
/// (the APFS case-fold collision that made `~/Duetto/cto` resolve to the enclosing
/// `hotstats/hotstats-knowledgebase` repo). The tracked-tree check does.
/// Separately, `git rev-parse --show-toplevel` walks *past* a `cwd/.git` that is
/// present but transiently invalid (e.g. a partially-reconstructed gitdir left by
/// a concurrent `git` rescue) all the way up to an ancestor repo — observed live
/// as `~/Duetto/cto` (its own repo) being reported as "inside another repository's
/// working tree (`~/Duetto`)". A directory that physically contains a `.git` entry
/// IS a working-tree root; its identity is its OWN repo, never an ancestor's.
/// What: (0) OWN-REPO-WINS — if `cwd` directly contains a `.git` entry (a
/// directory for a normal repo, or a worktree/submodule gitlink *file*; matched by
/// EXACT name via [`cwd_owns_git_entry`], never a `.git`-prefixed sibling such as
/// `.git.backup`), classify `Usable(cwd)` immediately without consulting git's
/// upward walk. Otherwise (1) resolve the git root; when the root IS `cwd` it is
/// trusted unconditionally; when the root is a strict ancestor, `cwd`'s relative
/// path is checked for tracked-tree membership via [`cwd_is_tracked_within`] — a
/// hit is `Usable`, a miss is `UntrackedInsideAncestor`. A prefix mismatch (e.g.
/// symlink canonicalisation differences) conservatively trusts the root
/// (`Usable`) rather than newly refusing a previously-working checkout.
/// Test: `guided_classify_cwd_own_git_wins_over_ancestor` (#2542 differential),
/// `guided_classify_cwd_own_git_ignores_dotgit_prefixed_sibling` (#2542),
/// `guided_classify_cwd_own_git_worktree_pointer_file` (#2542 gitlink file),
/// `guided_classify_cwd_usable_for_tracked_subdir`,
/// `guided_classify_cwd_untracked_for_uncommitted_subdir`,
/// `guided_classify_cwd_usable_for_repo_root`.
pub
/// Return the git root for `cwd` only when `cwd` genuinely belongs to that repo.
///
/// Why: thin adapter so the `cwd → project` derivation paths that only care about
/// the *usable* root (e.g. [`derive_project`]) need not match the full
/// [`CwdProject`] enum. Both an untracked-ancestor `cwd` and a non-git `cwd`
/// collapse to `None` — neither should inherit a git identity.
/// What: returns `Some(root)` for [`CwdProject::Usable`], `None` otherwise.
/// Test: covered transitively via `guided_derive_project_returns_none_for_untracked_ancestor_subdir`
/// and the `classify_cwd_project` unit tests.
/// Is `relpath` (a strict subdirectory of `git_root`) part of the repo's
/// tracked tree?
///
/// Why: the authoritative test for the ancestor-trust guard (#2534). Git's
/// index/tree is case-SENSITIVE, so on a case-insensitive filesystem an untracked
/// `cto` directory that shadows a tracked `CTO` still produces NO tree entry for
/// `cto` — exactly the discriminator needed to reject the case-fold collision.
/// What: shells `git -C <git_root> ls-tree -d --name-only HEAD -- <relpath>` and
/// delegates the yes/no decision to the pure [`ls_tree_reports_tracked_dir`].
/// Fails CLOSED (returns `false`) when git errors or the repo has no `HEAD`
/// (e.g. a commit-less repo has no tracked tree to belong to), so an
/// unverifiable ancestor is never trusted.
/// Test: decision logic is unit-tested via [`ls_tree_reports_tracked_dir`]; the
/// live-git path is exercised by `guided_classify_cwd_*` integration tests.
/// Pure predicate: does `git ls-tree -d --name-only HEAD -- <relpath>` stdout
/// indicate the queried path is a tracked directory?
///
/// Why: isolates the decision from the git shell-out so the tracked-vs-untracked
/// rule is exhaustively unit-testable without a live repo (mirrors the
/// `is_github_remote` pure-helper pattern). `ls-tree` emits one line naming the
/// path only when a matching tracked tree object exists; it emits nothing for an
/// untracked (or case-mismatched) path.
/// What: returns `true` when any output line is non-empty after trimming, `false`
/// otherwise. Empty stdout ⇒ untracked ⇒ `false`.
/// Test: `guided_ls_tree_reports_tracked_dir_true_for_named_entry`,
/// `guided_ls_tree_reports_tracked_dir_false_for_empty`,
/// `guided_ls_tree_reports_tracked_dir_false_for_blank_lines`.
pub
/// Build the operator-facing notice for the untracked-ancestor case (#2534).
///
/// Why: when `cwd` sits inside another repository's working tree but is not part
/// of it, silently launching that ancestor repo's project is the bug we are
/// fixing. The operator needs to know WHY `tm` declined to adopt the enclosing
/// repo — extracting the wording into a pure helper keeps it unit-testable.
/// What: returns a two-line stderr notice naming the enclosing `git_root` as the
/// reason `tm` is not launching that project, and reassuring the operator that
/// nothing was written.
/// Test: `guided_untracked_ancestor_message_names_root`,
/// `guided_untracked_ancestor_message_does_not_claim_launch`.
pub
/// Decision for the non-git-project branch of [`fallback_protected`]: does an
/// env-resolved managed-session id mean the "not in a git project" verdict is
/// premature (#4061)?
///
/// Why: `derive_project`/`classify_cwd_project` finding no usable git root is
/// exactly right for a genuinely unmanaged directory — but it says nothing
/// about whether THIS pane is a managed session's own pane whose daemon
/// record simply has not settled the Active -> Stopped race yet (the same
/// race [`super::guided_inplace::fetch_managed_session_until_stopped`] bounds
/// for `try_inplace_relaunch`'s own gate at the top of `run_guided_default`).
/// Separating this decision from the I/O (the env lookup, and the retry
/// itself) keeps it exhaustively unit-testable.
/// What: `Some(id)` — [`super::guided_inplace::resolve_env_managed_session_id`]
/// found a managed-session id in either the process or tmux SESSION
/// environment — means retry [`super::guided_inplace::try_inplace_relaunch`]
/// once more (real wall-clock time has elapsed since its first attempt at the
/// top of `run_guided_default`, doing the nested-session-guard round trip and
/// project detection in between) before ever printing a message that blames
/// "not a git project". `None` — no signal at all — is the ordinary,
/// unaffected fast path: print [`super::misc::NON_GIT_FALLBACK_HINT`]
/// immediately, no extra daemon round trip, no added latency.
/// Test: `plan_non_git_fallback_retries_when_env_id_present`,
/// `plan_non_git_fallback_ordinary_when_no_env_id`.
pub
/// Pure decision behind [`NonGitFallbackPlan`] — see its doc for the full
/// rationale.
///
/// Test: `plan_non_git_fallback_retries_when_env_id_present`,
/// `plan_non_git_fallback_ordinary_when_no_env_id`.
pub
/// Build the operator-facing notice printed when a managed-session id WAS
/// found in the environment (#4061) but the retried
/// [`super::guided_inplace::try_inplace_relaunch`] still could not confirm
/// the in-place relaunch — e.g. the daemon's Active -> Stopped settle race is
/// taking longer than both bounded attempts combined, or the daemon is
/// genuinely unreachable.
///
/// Why: printing [`super::misc::NON_GIT_FALLBACK_HINT`] here would actively
/// mislead the operator — this cwd may well not be a git project, but that is
/// NOT why nothing happened; the pane is a known managed one whose record
/// just has not settled yet. An honest, actionable message names the session
/// id and tells the operator the one thing that reliably works: try again.
/// What: a single-line notice naming `id`. Pure — the caller prints it via
/// `eprintln!` and returns `Ok(())`, exactly like every other fallback notice
/// in this module.
/// Test: `managed_pane_settle_pending_message_names_id`.
pub
/// Daemon-unreachable fallback that protects ALL live git checkouts (#1724).
///
/// Why: the guided default MUST NOT deploy framework files into ANY git
/// project's live checkout, even when the daemon is down. The invariant is:
/// if cwd is inside a git working tree (at ANY depth), it is never written to.
/// What: three-way dispatch on cwd:
/// (1) Inside a GitHub-backed git working tree → delegate to
/// [`launch_protected_workspace`] which provisions (or reuses) the protected
/// base clone and per-session worktree, then calls `launch()` against THAT
/// workspace, never the live checkout. Uses the repo ROOT (not cwd) to
/// read the origin remote — correct even from subdirectories. #4300: a
/// project registered with `worktree: false` (#3455) gets neither clone
/// nor worktree and launches in the repo root instead, matching what the
/// daemon's `spawn_managed_on_main` would have done had it been up.
/// (2) Inside a non-GitHub git working tree (non-GitHub remote or no remote)
/// → return an actionable `Err`; the live checkout is never touched.
/// (3) Not inside any git working tree (plain directory or bare repo) →
/// classic `tm launch` path; there is no live checkout to protect,
/// consistent with the daemon's local-path fast path.
/// Test: `guided_fallback_never_pollutes_github_git_checkout`,
/// `guided_fallback_blocks_non_github_git_checkout`,
/// `guided_fallback_blocks_github_git_from_subdirectory`,
/// `guided_fallback_untracked_ancestor_does_not_redirect`,
/// `guided_fallback_redirect_success_worktree_not_live_checkout`,
/// `guided_fallback_non_git_dir_reaches_launch_path` (fast path unaffected),
/// `guided_fallback_non_git_dir_no_managed_env_is_fast`,
/// `guided_fallback_non_git_dir_with_managed_env_settles_quickly_returns_promptly`,
/// and `guided_fallback_non_git_dir_with_managed_env_unreachable_daemon_does_not_hang`
/// (#4061 race) in `tests_behavior_b_tests.rs`.
pub async
/// Launch the guided-default fallback in the workspace this project is
/// entitled to — the protected managed clone, or its own main checkout.
///
/// Why: when the daemon is unreachable and the current directory is a GitHub-backed
/// git project, framework files must go into the managed-clone workspace
/// (`~/trusty-mpm-projects/<owner>/<repo>/.worktrees/<session-id>/`), never
/// into the operator's live checkout (#1724, #1803) — UNLESS the project is
/// registered with `worktree: false` (#3455), which is the operator saying
/// "run in my main checkout" and which the daemon honours via
/// `spawn_managed_on_main`. Before #4300 this path never consulted that
/// setting, so the opt-out silently held only while the daemon was up.
/// What: delegates the whole decision to
/// [`super::managed_workspace::provision_for_fallback`] — which reads the
/// registry BEFORE `ensure_base_clone`, so an opted-out project gets neither a
/// clone nor a worktree — then calls `launch()` against the resolved workspace.
/// On any failure (unparseable URL, clone error, worktree error) it returns
/// `Err` with an actionable message and the live checkout is never touched.
/// Test: `guided_fallback_never_pollutes_github_git_checkout`,
/// `guided_fallback_redirect_success_worktree_not_live_checkout`; the #4300
/// opt-out cases live in `managed_workspace_tests.rs`.
async