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
//! Bare-`tm` in-pane relaunch of the CURRENT managed session (#2023 component C).
//!
//! Why: components A and B (already landed) leave a managed pane alive as a
//! bare shell when its `claude` process exits, with `TM_MANAGED_SESSION_ID`
//! exported into that shell's live environment. If the operator then types
//! bare `tm` from inside THAT pane, the ordinary guided flow would be wrong on
//! two counts: (1) it would show a picker/attach flow for a session the
//! operator is already sitting inside, and (2) if it happened to select
//! "restart", the daemon's `/resume` route unconditionally kills any surviving
//! tmux session and creates a fresh one — which would tear down the very pane
//! the operator is running `tm` from. This module detects that specific
//! situation and relaunches `claude` directly back into the CURRENT process's
//! pane via `exec`, bypassing the daemon kill+recreate path entirely.
//!
//! What: [`try_inplace_relaunch`] is the top-level entry point `guided::
//! run_guided_default` calls FIRST, before any project detection or picker
//! logic. [`plan_inplace`] is the pure decision (env var present AND the
//! fetched record's state is `"stopped"` → [`super::guided_resume::
//! ResumeAction::InPlace`]; otherwise `None`, meaning "fall through to the
//! normal guided flow"). The record is fetched via
//! [`fetch_managed_session_until_stopped`] (#2148), which retries
//! [`fetch_managed_session`] over a short bounded budget so a record that is
//! still transitioning `Active` -> `Stopped` (the `SessionEnd` stop racing this
//! exact invocation) is not mistaken for "not stopped" on a single unlucky
//! read. [`reactivate_managed_session`] and the process-replacing exec
//! ([`exec_claude_in_place`]) are the rest of the I/O driver, sequenced by
//! [`run_inplace_relaunch`] as: resolve the `claude` binary + build the resume
//! command (pure, local — can fail on a missing binary before anything is
//! mutated) → reactivate on the daemon (network — a 404/409/unreachable
//! daemon ABORTS the whole in-place path and falls through to the picker,
//! never exec'ing against an unconfirmed record) → exec.
//!
//! Why the ordering matters (safety boundary, code-critic WARN on #2027): a
//! stale/leaked `TM_MANAGED_SESSION_ID` (e.g. inherited into an unrelated
//! subshell) must never cause this process to chdir+exec `claude` into the
//! wrong workspace. Two gates enforce that: (1) [`plan_inplace`] only selects
//! `InPlace` when the fetched record's state is CONFIRMED `"stopped"` — an
//! Active/Errored/Decommissioned/unresolved id all fall through to the
//! ordinary picker; (2) the daemon's own `mark_reactivated` Stopped-only guard
//! is honored by actually checking the reactivate response — a 404/409/network
//! failure aborts rather than proceeding to exec regardless.
//!
//! Test: `plan_inplace_*` cover the pure decision; `reactivate_managed_session`'s
//! success/409/404 outcomes are exercised against a local one-shot `TcpListener`
//! mock (#2027, mirroring `core::sm::providers`' mock convention — no external
//! mock-server crate); the full exec path is not unit-tested — it requires a
//! live daemon and a real `claude` binary, mirroring the rest of the
//! guided-resume I/O surface.
//!
//! #2157 item 2/6: [`try_inplace_relaunch`] no longer trusts the process
//! environment alone for `TM_MANAGED_SESSION_ID` — a sibling pane/window in the
//! same tmux session (or a pane spawned before the durable `tmux
//! set-environment` publish existed) never had the export line run in its
//! shell. [`read_tmux_env_managed_session_id`] falls back to `tmux
//! show-environment` when the process env is empty; its parsing half,
//! [`parse_show_environment_value`], is pure and exhaustively unit-tested. Every
//! rejected gate now also emits a `tracing::debug!` so a stuck-in-the-picker
//! report is diagnosable from `RUST_LOG=debug` output without code archaeology.
//!
//! #2453: [`run_inplace_relaunch`] and [`InPlaceOutcome`] are `pub(crate)` so
//! `super::guided::run_guided_default`'s nested-session guard can drive this
//! SAME primitive for a second, distinct entry point, independent of
//! [`try_inplace_relaunch`]'s env-var + Stopped-state gate. This closes the
//! bare-`tm` self-switch (no-op) bug: previously that call site trusted a
//! possibly-stale `record.state == "active"` and unconditionally attached/
//! switch-cliented, which is a guaranteed no-op when the operator is already
//! sitting in that exact pane. See `run_inplace_relaunch`'s doc for the safety
//! argument (the daemon's reactivate round-trip remains the sole authority).
//! CORRECTION (#2456 review finding 1, ROUND 2): the nested-session guard's
//! OWN match is by tmux SESSION name alone — every window/pane in a tmux
//! session shares the same session name, so that match is NOT pane-level
//! identity. A first attempt at closing this gap re-derived the process-scoped
//! `TM_MANAGED_SESSION_ID` env var this module's own primary gate
//! ([`read_env_managed_session_id`]) uses — that was EMPIRICALLY DISPROVEN:
//! the healing step in `SessionManager::mark_runtime_exited_stopped` 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 — a genuinely different sibling window
//! inherits the SAME env value, defeating an env-var-only gate. `guided.rs`
//! now compares tmux's own stable `pane_id` (`super::tmux_attach::
//! current_tmux_pane_id`) against the matched record's `pane_id`
//! (`SessionRecord::pane_id`, captured at spawn/reconcile time) — a signal
//! that is NEVER inherited across panes — before calling
//! [`run_inplace_relaunch`] at all. A session-name-only match, a missing
//! `pane_id` (legacy record), or a pane_id mismatch all fall back to the
//! pre-existing refuse+switch-client behavior instead.
use Context as _;
use workspace_liveness;
use ResumeAction;
/// Per-request timeout for the in-pane reachability probes (GET existence
/// check + POST reactivate), matching the 2s daemon-reachability convention
/// used elsewhere in this binary (`pm_guard.rs`, `misc.rs`'s hook relay).
///
/// Why: this path runs on EVERY bare `tm` invocation inside a managed pane —
/// a hung daemon must not add a long stall before falling through to the
/// ordinary guided default.
const PROBE_TIMEOUT: Duration = from_secs;
/// Environment variable exported into a managed pane's shell (#2023 B) that
/// identifies which managed session bare `tm`, run after `claude` exits,
/// belongs to.
const MANAGED_SESSION_ID_ENV: &str = "TM_MANAGED_SESSION_ID";
/// Total time budget for polling the managed-session fetch while the record is
/// transitioning `Active` -> `Stopped` (#2148 race hardening).
///
/// Why: `SessionEnd` marks the record `Stopped` asynchronously (via
/// `mark_runtime_exited_stopped`) at roughly the same moment bare `tm` runs in
/// the just-vacated pane. A single unlucky fetch can observe the record still
/// `"active"`, causing [`plan_inplace`] to reject the in-place path and fall
/// through to the destructive guided-picker `/resume` — exactly the pane loss
/// #2148 is about. A short, bounded poll absorbs that race without adding a
/// human-perceptible delay to every bare-`tm` invocation.
const FETCH_RETRY_BUDGET: Duration = from_millis;
/// Delay between polls within [`FETCH_RETRY_BUDGET`].
///
/// Why: a handful of short polls (400ms / 80ms ≈ up to 5 attempts) is enough
/// to ride out the `SessionEnd` race without noticeably slowing the common
/// case, where the very first fetch already sees `"stopped"`.
const FETCH_RETRY_INTERVAL: Duration = from_millis;
/// Read [`MANAGED_SESSION_ID_ENV`] from the environment, treating a blank
/// value the same as absent.
///
/// Why: an exported-but-empty env var (never expected in practice, but cheap
/// to guard) must not be mistaken for a real session id.
/// What: `std::env::var` filtered to non-blank (after trim).
/// Test: exercised indirectly via [`plan_inplace`]'s tests (which take the
/// already-read `Option<&str>` directly, keeping the env read itself outside
/// the pure/testable seam).
/// Fallback read of [`MANAGED_SESSION_ID_ENV`] from the current tmux SESSION's
/// environment via `tmux show-environment` (#2157 item 2).
///
/// Why: [`read_env_managed_session_id`] only sees the id when the CURRENT
/// process's own environment carries it — true for the exact shell that ran
/// the `export TM_MANAGED_SESSION_ID=…;` prefix, but NOT for a sibling
/// pane/window in the same tmux session, nor for a pane spawned by a
/// pre-#2157 build that never got the durable `tmux set-environment` publish
/// either. Since `tm` running bare here is, by definition, inside a tmux
/// client (`$TMUX` is set) whenever this path is reachable at all, querying
/// the SESSION's own environment table is a reliable second source — durably
/// published at spawn/resume time by `runtime::claude_code::
/// ClaudeCodeAdapter::publish_session_env` and healed for stale panes by
/// `SessionManager::mark_runtime_exited_stopped` (item 3).
/// What: when `$TMUX` is unset (not inside tmux), returns `None` immediately
/// — there is no session to query. Otherwise shells out to
/// `tmux show-environment TM_MANAGED_SESSION_ID` and parses the id via
/// [`parse_show_environment_value`]. Any I/O failure, non-zero exit, or the
/// variable being unset in the session (`tmux` prints `-NAME` for an unset
/// variable) folds into `None` — the caller then falls through exactly as if
/// no env var was found anywhere.
/// Test: the I/O shell-out is not unit-tested (requires a live tmux server);
/// [`parse_show_environment_value`] covers the pure parsing logic exhaustively.
/// Resolve [`MANAGED_SESSION_ID_ENV`] from EITHER the process environment or
/// the tmux SESSION environment — the exact two-source lookup
/// [`try_inplace_relaunch`] itself performs (issue #4061).
///
/// Why (#4061): the guided-default's non-git fallback (`guided::
/// fallback_protected`'s `CwdProject::NotGit` arm) previously printed the
/// "not in a git project" hint unconditionally whenever `derive_project`
/// found no usable git root — including for a managed pane whose bare `tm`
/// happened to run from a non-git cwd while the daemon's Active -> Stopped
/// settle race (the same one [`fetch_managed_session_until_stopped`] guards
/// against) had not yet resolved by the time [`try_inplace_relaunch`]'s own
/// bounded retry gave up. That produced the reported two-invocation UX: a
/// scary "not in a git project" error on the first bare `tm`, then success on
/// an immediate retry once the daemon's record had settled. Exposing the
/// SAME env-var resolution `try_inplace_relaunch` uses lets that fallback ask
/// "does ANY signal say this pane belongs (or very recently belonged) to a
/// managed session?" before ever blaming "not a git project" — without
/// duplicating the process-env-then-tmux-env chain a second time.
/// What: [`read_env_managed_session_id`] first (the exact shell that ran the
/// `export` prefix), falling back to [`read_tmux_env_managed_session_id`] (a
/// sibling pane/window in the same tmux session, or a pane spawned before the
/// durable `tmux set-environment` publish existed). `None` when neither
/// source has it — meaning there is no evidence at all that this pane is a
/// managed one, so the ordinary "not in a git project" hint is exactly right.
/// Test: `resolve_env_managed_session_id_prefers_process_env`,
/// `resolve_env_managed_session_id_none_when_unset` in `guided_inplace/tests.rs`.
pub
/// Parse the id out of `tmux show-environment <name>`'s stdout.
///
/// Why: separating the parse from the process spawn makes the format-handling
/// logic exhaustively unit-testable without a live tmux server.
/// What: `tmux show-environment NAME` prints `NAME=value` when the variable is
/// set in the session, or `-NAME` when it is explicitly unset. Returns
/// `Some(value)` (trimmed, non-empty) only for the `NAME=value` form;
/// everything else (unset `-NAME` form, empty output, an empty value, or
/// unrecognised text) is `None`.
/// Test: `parse_show_environment_value_extracts_id`,
/// `parse_show_environment_value_none_when_unset`,
/// `parse_show_environment_value_none_when_empty`.
/// Decide whether bare `tm`'s in-pane environment signals an in-place
/// relaunch (#2023 component C).
///
/// Why: the actual daemon lookup ("does this id resolve to a known managed
/// session, and is it actually `Stopped`?") is I/O; separating the DECISION
/// from the lookup makes the decision itself exhaustively unit-testable.
/// Folding the Stopped-state check in HERE (rather than trusting the daemon's
/// `mark_reactivated` guard alone) closes the hijack window a code-critic WARN
/// flagged on #2027: a resolved-but-`Active`/`Errored`/`Decommissioned` record
/// (e.g. from a leaked/stale env var pointing at some OTHER session) must fall
/// through to the ordinary picker, not attempt an in-place `exec`.
/// What: `Some(ResumeAction::InPlace)` when `env_session_id` is `Some` AND
/// `record_state` is `Some("stopped")`; `None` otherwise — covering "no env
/// var", "env var present but id unknown to the daemon" (`record_state` is
/// `None`), and "id resolves but is NOT `Stopped`" — every one of which must
/// fall through to the ordinary guided picker rather than error.
/// Test: `plan_inplace_selected_when_env_set_and_stopped`,
/// `plan_inplace_none_when_env_absent`,
/// `plan_inplace_none_when_env_set_but_unresolved`,
/// `plan_inplace_none_when_resolved_but_not_stopped`.
pub
/// GET `/api/v1/sessions/managed/{id}` — resolve the env-supplied id to a record.
///
/// Why: the in-place path must confirm the daemon still knows this session
/// (the env var can go stale — e.g. the record was decommissioned after the
/// pane was left alive) before reactivating/relaunching it.
/// What: `Some(summary)` on HTTP 2xx, `None` on any failure (network error,
/// 404, non-2xx, or an undeserializable body) — every failure mode folds into
/// the same "fall through to the picker" outcome via [`plan_inplace`].
/// Test: I/O path; not unit-tested (requires a live daemon).
async
/// Poll [`fetch_managed_session`] until the record reads `"stopped"` or the
/// [`FETCH_RETRY_BUDGET`] is exhausted (#2148 race hardening).
///
/// Why: [`plan_inplace`] requires the FIRST fetch to already show `"stopped"`;
/// a record that is transitioning `Active` -> `Stopped` (the `SessionEnd` stop
/// racing this exact bare-`tm` invocation) would otherwise be seen as
/// unresolved/non-stopped and fall through to the destructive guided-picker
/// `/resume` path — the very pane loss #2148 fixes. Retrying a few times over
/// a small, bounded budget lets the transition land before giving up.
/// What: fetches once immediately; returns as soon as `state == "stopped"`.
/// Otherwise sleeps [`FETCH_RETRY_INTERVAL`] and retries, stopping the moment
/// the elapsed time reaches [`FETCH_RETRY_BUDGET`] — returning whatever the
/// LAST attempt produced (`Some` non-stopped record, or `None` if the fetch
/// itself kept failing). Never blocks longer than the budget, so a genuinely
/// unresolved/unknown id still falls through promptly.
/// Test: `fetch_until_stopped_returns_immediately_when_already_stopped`,
/// `fetch_until_stopped_gives_up_after_budget_when_never_stopped` (both use a
/// local one-shot/counting mock, mirroring [`spawn_mock`]'s convention).
async
/// POST `/api/v1/sessions/managed/{id}/reactivate` — flip Stopped -> Active
/// in place, with no tmux mutation (#2023 C step 3).
///
/// Why: the daemon's `mark_reactivated` is the second half of the
/// Stopped-only safety guard — [`plan_inplace`] already checked the record
/// was `Stopped` at fetch time, but that is a TOCTOU-prone read; the daemon
/// re-validates atomically against its own current state and can legitimately
/// refuse (404 the id vanished, 409 it is no longer `Stopped`, or the daemon
/// may simply be unreachable). This result MUST be honored, not logged and
/// ignored (code-critic WARN on #2027): exec'ing into `claude` after a
/// refused/failed reactivate would let a hijacked/stale env var drive a
/// relaunch the daemon never actually confirmed.
/// What: returns `true` only on an HTTP 2xx response — the daemon record IS
/// now `Active`. Returns `false` on any other outcome (4xx/5xx or a network
/// error), each logged with the concrete reason; the caller ABORTS the
/// in-place path on `false` and falls through to the ordinary guided picker.
/// When `caller_pane_id` is `Some`, it is forwarded as a `?caller_pane_id=`
/// query param (#2789) so the daemon's stale-`Active` reconcile can treat THIS
/// pane — whose foreground command is the requesting `tm` itself — as idle
/// instead of counting it as a live runtime and returning 409. When
/// `pane_confirmed_dead` is set (#2794), a `?pane_confirmed_dead=true` param is
/// also forwarded: it tells the daemon the caller is asserting — matched via
/// stable tmux `pane_id`, `guided::pane_identity_confirmed`, not independently
/// re-verified by the daemon — that it is this record's OWN pane and the agent
/// has exited, so the reconcile trusts that claim over its tmux-pane liveness
/// probe for the caller's own pane (bounded by an independent sibling-pane
/// check, #2157) — closing the residual zombie-`Active` 409 dead-end where the
/// probe still counted the requesting `tm` (or a not-yet-reaped child) as live.
/// Test: I/O path; not unit-tested (requires a live daemon).
async
/// Replace the CURRENT process image with `cmd` (Unix `exec`), never returning
/// on success.
///
/// Why: the in-place relaunch must put `claude` directly into THIS process's
/// controlling terminal/pane — spawning a child and waiting would leave the
/// `tm` process (and an extra layer of signal/Ctrl-C indirection) sitting
/// between the pane and `claude`, unlike every other managed-session launch
/// path where the daemon's tmux pane runs `claude` as the pane's direct child.
/// What: Unix — `std::os::unix::process::CommandExt::exec` replaces the
/// process image; a return from `exec` is always a failure (it never returns
/// on success), so the error is propagated as `Err`. Non-Unix — no `exec`
/// syscall exists; falls back to spawn+wait and exits this process with the
/// child's status code, which is observably equivalent from the terminal's
/// perspective (just one extra, short-lived process in between).
/// Test: not unit-tested — replacing/exiting the test process is not
/// observable from within the test itself.
/// Non-Unix fallback for [`exec_claude_in_place`] (see its doc for rationale).
/// The result of [`run_inplace_relaunch`] — distinguishes a hard failure
/// (surfaced to the operator, non-zero exit) from a safety-gate abort (must
/// fall through to the ordinary picker exactly like an unresolved id).
///
/// Why: the daemon's reactivate response MUST be honored (#2027 code-critic
/// WARN) — a refused/failed reactivate is NOT a hard error to report and
/// exit on, it is "this in-place attempt is not safe to proceed with,"
/// which is exactly the same outcome as [`plan_inplace`] returning `None`.
/// Separating the two outcomes lets [`try_inplace_relaunch`] route a
/// reactivate failure back into the `None`/fall-through path instead of
/// wrapping it in `Some(Err(..))`. `pub(crate)` (#2453): `super::guided::
/// run_guided_default`'s nested-session-guard branch also drives this enum
/// directly — see [`run_inplace_relaunch`]'s doc for why.
pub
/// Drive the full in-place relaunch once [`plan_inplace`] selected it — OR
/// once `guided::run_guided_default`'s nested-session guard confirms the
/// current tmux pane belongs to a managed record (#2453).
///
/// Why: separated from [`try_inplace_relaunch`] so the "should we take this
/// path at all" decision and the "how do we execute it" mechanics are
/// distinct, readable steps. `pub(crate)` (#2453): the nested-session guard in
/// `guided.rs` matches a record by tmux SESSION name, then — ONLY when it can
/// additionally confirm pane-level identity via tmux's own stable `pane_id`
/// (`super::tmux_attach::current_tmux_pane_id` vs. the record's
/// `SessionRecord::pane_id`; see the `#2456 review finding 1, ROUND 2`
/// correction in this module's top doc comment for why the process-env
/// signal this paragraph used to describe was proven insufficient) — drives
/// this function; a session-name-only match never reaches here) BEFORE the
/// record's `state` is known to be `Stopped` —
/// its `record.state` field can lag reality by up to 60s (the same staleness
/// race #2148 hardens [`fetch_managed_session_until_stopped`] against).
/// Rather than duplicate the Stopped-only gate [`plan_inplace`] enforces for
/// the env-var entry point, that call site drives this function directly
/// with whatever record it matched (any state) and trusts the SAME safety
/// boundary every caller of this function already relies on:
/// [`reactivate_managed_session`]'s daemon round-trip (backed, as of #2453,
/// by the daemon's own independent pane-idle reconciliation — see
/// `daemon::managed_routes::reactivate::reconcile_stale_active_then_reactivate`)
/// is the single source of truth, and a refused/failed reactivate here folds
/// into [`InPlaceOutcome::FallThrough`] exactly as it does for the env-var
/// path — never an unconditional exec. Note (#2456 review finding 2): unlike
/// [`try_inplace_relaunch`]'s own contract (a command-build failure there is
/// a deliberate hard error), the nested-guard caller treats EVERY
/// `InPlaceOutcome::Result(Err(_))` from THIS call site — pre-mutation
/// (cwd/binary resolution) or post-reactivate (`exec` itself failing) alike
/// — as a fall-back-to-reconnect condition, matching that call site's
/// pre-#2453 behavior of never hard-failing.
/// What, IN ORDER (#2027 exec-ordering fix, extended by #2790 and #4204): (1)
/// prints a one-line notice; (2) resolves the workdir; (2a) #2790/#4204
/// CRITICAL: verifies the resolved workdir IS STILL LIVE via
/// [`trusty_mpm::core::workspace_liveness::workspace_liveness`] — a
/// Decommissioned record's workspace may have been removed by `decommission()`
/// while the record's `workspace_path`/`cwd` still names it, and (#4204) a
/// worktree may have been GUTTED, keeping its directory node while losing its
/// `.git` and source tree, which the previous bare `is_dir()` test could not
/// see; either verdict returns [`InPlaceOutcome::FallThrough`] here, BEFORE any
/// daemon call, so a dead workspace can never be masked by a durably-committed
/// `Active` record nor exec'd into; (3) builds the resume argv via
/// [`trusty_mpm::runtime::build_inplace_resume_command`] (the SAME
/// `--resume`-existence-check → `--continue`/fresh-spawn fallback logic the
/// tmux-pane resume path uses, #2013) — this is PURE/local (resolving the
/// `claude` binary can fail with `BinaryNotFound`) and runs BEFORE any daemon
/// mutation, so a missing binary never flips the record to a false `Active`;
/// (4) reactivates the record on the daemon (step 3 of #2023 C — see
/// [`reactivate_managed_session`]), immediately before exec — on a
/// refused/failed reactivate this returns [`InPlaceOutcome::FallThrough`]
/// rather than proceeding; (5) execs `claude` in place.
/// Test: `run_inplace_relaunch_never_reactivates_when_command_build_fails`,
/// `run_inplace_relaunch_falls_through_on_gutted_worktree`,
/// `run_inplace_relaunch_serves_live_linked_worktree`. The argv/environment the
/// final step hands to `exec` is pinned by [`build_inplace_exec_command`]'s own
/// tests (#4336). The exec CALL itself is still not
/// unit-tested (it replaces the process image); the gate-2a tests pin the
/// decision by asserting the daemon mock records ZERO hits, which is only true
/// when the fall-through happened before any daemon mutation. The FSM invariant
/// gate 2a protects is separately proven at the daemon layer
/// (defense-in-depth, so the guard holds even for a future caller that skips
/// this CLI-side check) by
/// `mark_reactivated_refuses_when_workspace_removed_by_decommission` in
/// `session_manager::reactivate_tests`.
pub async
/// Assemble the [`std::process::Command`] the in-place relaunch execs — the
/// pure, inspectable half of the exec seam (#4336).
///
/// Why: this construction used to be inlined immediately before
/// [`exec_claude_in_place`], which is unavoidably untestable (it replaces the
/// process image). That made the LAST step before `exec` — the one that decides
/// what argv and environment `claude` actually receives — the only launch step
/// in the codebase with no coverage at all, which is precisely why #4336 could
/// be reported as "the in-place relaunch execs `claude` with zero args" and not
/// be refutable from the test suite. Splitting the construction out leaves
/// `exec` as a one-line untestable tail and puts everything that carries the
/// isolation flags, the PM persona, and the auth environment under assertion.
/// What: `Command` for `resume.claude_bin` with `resume.args` (the
/// `compose_inplace_args` argv — `--append-system-prompt-file`, the isolation
/// flags, and the resume/continue selection), rooted at `cwd`, with
/// `ANTHROPIC_API_KEY` scrubbed and `CLAUDE_CONFIG_DIR` /
/// `CLAUDE_CODE_OAUTH_TOKEN` set when resolved. Issue #2246: the token mirrors
/// the tmux-pane spawn/resume paths so an in-place relaunch does not silently
/// drop back into the `CLAUDE_CONFIG_DIR`-keyed Keychain login loop the token
/// exists to bypass. Pure — builds and returns, never spawns.
///
/// Issue #4467: the inherited Claude Code session markers are scrubbed here too,
/// via [`trusty_mpm::core::claude_env_scrub::scrub_command`]. This path execs
/// `claude` through a `Command` with no shell in between, so the `env -u` prefix
/// the tmux-pane paths use does not apply to it — but a bare `tm` relaunch run
/// from inside a Claude Code session leaks exactly the same
/// `CLAUDE_CODE_CHILD_SESSION` marker and would silently lose its transcript.
/// The scrub runs BEFORE the deliberate assignments below so it can never
/// clobber `CLAUDE_CONFIG_DIR` (#4455) even if the marker list grew wrongly.
/// Test: `inplace_exec_command_forwards_every_arg_in_order`,
/// `inplace_exec_command_scrubs_api_key_and_sets_auth_env`,
/// `inplace_exec_command_scrubs_inherited_session_markers`,
/// `inplace_exec_command_carries_isolation_flags_and_persona_end_to_end`.
pub
/// Top-level entry point: try the in-place relaunch before any other bare-`tm`
/// logic runs (#2023 component C).
///
/// Why: `guided::run_guided_default` must check this FIRST — before project
/// detection, before the picker — because the in-pane case is a completely
/// different situation from "operator ran `tm` from a project directory to
/// pick a session": here the session is already known and already running IN
/// this exact pane.
/// What: `None` — [`MANAGED_SESSION_ID_ENV`] is unset, blank, does not resolve
/// to a known managed session, resolves to a session NOT currently `Stopped`
/// (see [`plan_inplace`]), or the daemon refuses/fails to confirm reactivation
/// (see [`InPlaceOutcome::FallThrough`]) — means "not this path; fall through
/// to the ordinary guided default." `Some(result)` means this function took
/// over: on success it never returns (`claude` replaced this process); on
/// failure it returns `Some(Err(..))` so the caller can surface the error and
/// exit non-zero rather than silently falling through to a picker that would
/// confusingly re-offer this very session.
/// Test: `plan_inplace_*` cover the decision this function delegates to.
pub async