trusty-mpm 1.3.5

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
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 anyhow::Context as _;
use trusty_mpm::core::workspace_liveness::workspace_liveness;

use super::guided_resume::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: std::time::Duration = std::time::Duration::from_secs(2);

/// 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: std::time::Duration = std::time::Duration::from_millis(400);

/// 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: std::time::Duration = std::time::Duration::from_millis(80);

/// 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).
fn read_env_managed_session_id() -> Option<String> {
    std::env::var(MANAGED_SESSION_ID_ENV)
        .ok()
        .filter(|v| !v.trim().is_empty())
}

/// 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.
fn read_tmux_env_managed_session_id() -> Option<String> {
    let inside_tmux = std::env::var("TMUX")
        .map(|v| !v.is_empty())
        .unwrap_or(false);
    if !inside_tmux {
        return None;
    }
    let output = std::process::Command::new("tmux")
        .args(["show-environment", MANAGED_SESSION_ID_ENV])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    parse_show_environment_value(&String::from_utf8_lossy(&output.stdout))
}

/// 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(crate) fn resolve_env_managed_session_id() -> Option<String> {
    read_env_managed_session_id().or_else(read_tmux_env_managed_session_id)
}

/// 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`.
fn parse_show_environment_value(stdout: &str) -> Option<String> {
    let line = stdout.lines().next()?;
    let value = line.strip_prefix(&format!("{MANAGED_SESSION_ID_ENV}="))?;
    let trimmed = value.trim();
    (!trimmed.is_empty()).then(|| trimmed.to_string())
}

/// 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(crate) fn plan_inplace(
    env_session_id: Option<&str>,
    record_state: Option<&str>,
) -> Option<ResumeAction> {
    (env_session_id.is_some() && record_state == Some("stopped")).then_some(ResumeAction::InPlace)
}

/// 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 fn fetch_managed_session(
    client: &reqwest::Client,
    url: &str,
    id: &str,
) -> Option<trusty_mpm::client::ManagedSessionSummary> {
    let resp = client
        .get(format!("{url}/api/v1/sessions/managed/{id}"))
        .timeout(PROBE_TIMEOUT)
        .send()
        .await
        .ok()?;
    if !resp.status().is_success() {
        return None;
    }
    resp.json().await.ok()
}

/// 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 fn fetch_managed_session_until_stopped(
    client: &reqwest::Client,
    url: &str,
    id: &str,
) -> Option<trusty_mpm::client::ManagedSessionSummary> {
    let start = std::time::Instant::now();
    loop {
        let record = fetch_managed_session(client, url, id).await;
        if record.as_ref().map(|r| r.state.as_str()) == Some("stopped") {
            return record;
        }
        if start.elapsed() >= FETCH_RETRY_BUDGET {
            return record;
        }
        tokio::time::sleep(FETCH_RETRY_INTERVAL).await;
    }
}

/// 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 fn reactivate_managed_session(
    client: &reqwest::Client,
    url: &str,
    id: &str,
    caller_pane_id: Option<&str>,
    pane_confirmed_dead: bool,
) -> bool {
    let mut req = client
        .post(format!("{url}/api/v1/sessions/managed/{id}/reactivate"))
        .timeout(PROBE_TIMEOUT);
    if let Some(pane_id) = caller_pane_id.filter(|s| !s.is_empty()) {
        req = req.query(&[("caller_pane_id", pane_id)]);
    }
    if pane_confirmed_dead {
        req = req.query(&[("pane_confirmed_dead", "true")]);
    }
    let result = req.send().await;
    match result {
        Ok(resp) if resp.status().is_success() => true,
        Ok(resp) => {
            let status = resp.status();
            eprintln!(
                "tm: daemon refused to reactivate session {id} ({status}) — \
                 aborting in-place relaunch, falling back to the guided picker"
            );
            false
        }
        Err(e) => {
            eprintln!(
                "tm: could not reach daemon to reactivate session {id}: {e} — \
                 aborting in-place relaunch, falling back to the guided picker"
            );
            false
        }
    }
}

/// 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.
#[cfg(unix)]
fn exec_claude_in_place(mut cmd: std::process::Command) -> anyhow::Result<()> {
    use std::os::unix::process::CommandExt as _;
    let err = cmd.exec();
    Err(anyhow::anyhow!("failed to exec claude in place: {err}"))
}

/// Non-Unix fallback for [`exec_claude_in_place`] (see its doc for rationale).
#[cfg(not(unix))]
fn exec_claude_in_place(mut cmd: std::process::Command) -> anyhow::Result<()> {
    let status = cmd.status().context("failed to run claude")?;
    std::process::exit(status.code().unwrap_or(1));
}

/// 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(crate) enum InPlaceOutcome {
    /// The exec attempt concluded (never returns on success; carries the
    /// error when `exec` itself failed, or when command resolution failed
    /// before any daemon mutation occurred).
    Result(anyhow::Result<()>),
    /// The daemon refused/failed to confirm reactivation — abort, fall
    /// through to the ordinary guided picker (no exec attempted).
    FallThrough,
}

/// 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(crate) async fn run_inplace_relaunch(
    client: &reqwest::Client,
    url: &str,
    id: &str,
    record: trusty_mpm::client::ManagedSessionSummary,
    caller_pane_id: Option<&str>,
    pane_confirmed_dead: bool,
) -> InPlaceOutcome {
    eprintln!("tm: this pane belongs to managed session {id} — relaunching in place…");

    let cwd = match record
        .workspace_path
        .or(record.cwd)
        .map(std::path::PathBuf::from)
        .or_else(|| std::env::current_dir().ok())
        .context("cannot resolve a working directory for the in-place relaunch")
    {
        Ok(cwd) => cwd,
        Err(e) => return InPlaceOutcome::Result(Err(e)),
    };

    // #2790 code-critic CRITICAL: a Decommissioned record's workspace may have
    // been deleted from disk by `decommission()` (the FSM invariant in
    // `session_manager::record` — only Decommissioned means the workspace is
    // gone) while `workspace_path`/`cwd` on the record still names the
    // now-removed path. Confirm the resolved directory ACTUALLY EXISTS before
    // any daemon mutation: reactivating (which durably flips the record to
    // `Active`) then discovering the `cd`/exec target is gone would commit a
    // ghost `Active` record that can never be attached to again. Folding a
    // missing workspace into `FallThrough` here — zero daemon calls made —
    // keeps the invariant intact and routes the operator to the same honest
    // self-relaunch hint a refused reactivate would.
    // #4204 EXTENSION of the #2790 gate above: `is_dir()` is not a liveness
    // check. A worktree whose `.git` and source tree have been stripped keeps
    // its directory node, so the bare `is_dir()` test passed and this function
    // exec'd `claude` into the husk — observed 2026-07-27 with PID 63302 (plus
    // four MCP children) still parked on the dead cwd of
    // `.base/.worktrees/f443c12d-…`.
    //
    // `ManagedSessionSummary` carries no `workspace_owned` flag, so `false` is
    // passed for it and the helper falls back to its NARROW path-shape rule
    // (`.worktrees/<id>`). That is deliberate, not a shortcut: such a directory
    // is only ever produced by `git worktree add`, so a missing `.git` there is
    // unambiguous evidence of destruction — while an operator's plain,
    // non-git working directory (reachable here via `record.cwd` or
    // `current_dir()`) is owed no `.git` and is never refused.
    let workspace_owned_unknown = false;
    let liveness = workspace_liveness(&cwd, workspace_owned_unknown);
    if liveness.is_dead() {
        eprintln!(
            "tm: workspace for session {id} is {liveness} ({}) — cannot relaunch in place",
            cwd.display()
        );
        return InPlaceOutcome::FallThrough;
    }

    // #4752: refresh the project's compiled prompt BEFORE building the resume
    // command, and treat a failure as FATAL — the same policy `prepare_session`
    // and `resume_managed` apply.
    //
    // This path is the THIRD entry point that hands a runtime a prompt, and it
    // calls neither of those two: its only daemon call is `reactivate` below,
    // which does no prompt work. Until this call existed, the sole compiled write
    // here was `build_prompt_file`'s best-effort refresh, so a bare-`tm` relaunch
    // in a managed pane was the one way to start a session on a stale or missing
    // compiled prompt where a fresh launch would have refused.
    //
    // #4873: the PROMPT is the only thing this path had to refresh by hand.
    // Agents and skills are already covered — `build_inplace_resume_command`
    // below calls `runtime::claude_code::prepare_managed_config`, which runs
    // `core::managed_config::ensure_managed_config_dir` and redeploys both
    // rosters. Read the "only daemon call is `reactivate`" line above as being
    // about DAEMON calls specifically; it is not a claim that this path skips
    // asset deployment.
    //
    // Ordered BEFORE `build_inplace_resume_command` so a refusal costs nothing
    // and, like the other two sites, cannot half-provision the pane.
    //
    // #4832: scoped to THIS session's id, so the refreshed file is the one
    // `build_inplace_resume_command` is about to hand the runtime.
    if let Err(msg) = trusty_mpm::core::instruction_pipeline::refresh_compiled_prompt(
        &cwd,
        &record.id.to_string(),
    ) {
        return InPlaceOutcome::Result(Err(anyhow::anyhow!("{msg}")));
    }

    let resume = match trusty_mpm::runtime::build_inplace_resume_command(
        &cwd,
        record.claude_session_id.as_deref(),
    ) {
        Ok(resume) => resume,
        Err(e) => {
            return InPlaceOutcome::Result(Err(anyhow::anyhow!(
                "cannot build in-place relaunch command: {e}"
            )));
        }
    };

    // Reactivate immediately before exec — and HONOR the result (#2027):
    // a refused/failed reactivate aborts rather than proceeding to exec.
    // #2789: forward this pane's own id so the daemon's stale-`Active`
    // reconcile does not count the requesting `tm` process as a live runtime.
    // #2794: `pane_confirmed_dead` additionally carries the caller's
    // proof-of-death for a zombie-`Active` record whose pane the probe would
    // otherwise still read as busy.
    if !reactivate_managed_session(client, url, id, caller_pane_id, pane_confirmed_dead).await {
        return InPlaceOutcome::FallThrough;
    }

    InPlaceOutcome::Result(exec_claude_in_place(build_inplace_exec_command(
        &resume, &cwd,
    )))
}

/// 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(crate) fn build_inplace_exec_command(
    resume: &trusty_mpm::runtime::InPlaceResumeCommand,
    cwd: &std::path::Path,
) -> std::process::Command {
    let mut cmd = std::process::Command::new(&resume.claude_bin);
    cmd.args(&resume.args)
        .current_dir(cwd)
        .env_remove("ANTHROPIC_API_KEY");
    // #4467: strip Claude Code's inherited process-local session markers so the
    // relaunched session keeps native --resume/--continue/rewind recovery.
    trusty_mpm::core::claude_env_scrub::scrub_command(&mut cmd);
    if let Some(dir) = &resume.config_dir {
        cmd.env("CLAUDE_CONFIG_DIR", dir);
    }
    if let Some(token) = &resume.oauth_token {
        cmd.env(trusty_mpm::core::oauth_token::OAUTH_TOKEN_ENV_VAR, token);
    }
    cmd
}

/// 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(crate) async fn try_inplace_relaunch(
    client: &reqwest::Client,
    url: &str,
) -> Option<anyhow::Result<()>> {
    // #2157 item 2: process env is the primary source (it is set for the exact
    // shell that ran the export prefix); the tmux SESSION environment is the
    // fallback for every pane/shell that never ran it (a sibling pane/window,
    // or a pre-#2157-build pane) — see `read_tmux_env_managed_session_id`.
    let env_id = match read_env_managed_session_id() {
        Some(id) => id,
        None => match read_tmux_env_managed_session_id() {
            Some(id) => id,
            None => {
                tracing::debug!(
                    "tm: in-place relaunch gate: TM_MANAGED_SESSION_ID absent from both \
                     process env and tmux session env — falling through to guided default"
                );
                return None;
            }
        },
    };
    // #2148: bounded retry absorbs the Active->Stopped transition race instead
    // of giving up on a single unlucky fetch — see `fetch_managed_session_until_stopped`.
    let record = fetch_managed_session_until_stopped(client, url, &env_id).await;
    let record_state = record.as_ref().map(|r| r.state.as_str());
    match plan_inplace(Some(&env_id), record_state) {
        Some(ResumeAction::InPlace) => {
            let record = record.expect("plan_inplace only selects InPlace when record is Some");
            // #2453 review finding 1 (round 2), extended to this PRE-EXISTING
            // env-var entry point: `env_id` alone only proves SOME shell in
            // this tmux session/process tree carries `TM_MANAGED_SESSION_ID`
            // — including a sibling pane that merely INHERITED it via tmux's
            // session-scoped healing `set-environment` (see `guided::
            // pane_identity_confirmed`'s doc for the full empirical proof).
            // That is not proof THIS pane is the one bound to `record`.
            // Require the SAME pane_id confirmation the nested-session guard
            // uses before driving the destructive exec. In the common case
            // (bare `tm` typed in the exact pane whose runtime just exited)
            // `record.pane_id` was just refreshed by the SessionEnd-hook-
            // triggered `mark_runtime_exited_stopped` moments before this
            // fetch resolved "stopped", so this adds no friction there.
            let current_pane_id = super::tmux_attach::current_tmux_pane_id();
            if !super::guided::pane_identity_confirmed(
                current_pane_id.as_deref(),
                record.pane_id.as_deref(),
            ) {
                tracing::debug!(
                    id = %env_id,
                    "tm: in-place relaunch gate: pane_id could not be confirmed for \
                     this pane (env var may be inherited from a healed sibling \
                     session/window) — falling through to guided default"
                );
                return None;
            }
            // #2794: this env-var path only selects `InPlace` for a record
            // already CONFIRMED `Stopped` (see `plan_inplace`), so `mark_
            // reactivated` succeeds directly and the proof-of-death reconcile is
            // never reached — pass `false`.
            match run_inplace_relaunch(
                client,
                url,
                &env_id,
                record,
                current_pane_id.as_deref(),
                false,
            )
            .await
            {
                InPlaceOutcome::Result(r) => Some(r),
                InPlaceOutcome::FallThrough => {
                    tracing::debug!(
                        id = %env_id,
                        "tm: in-place relaunch gate: daemon reactivate refused/failed — \
                         falling through to guided default"
                    );
                    None
                }
            }
        }
        _ => {
            tracing::debug!(
                id = %env_id,
                state = ?record_state,
                "tm: in-place relaunch gate: session id did not resolve to a known, \
                 Stopped managed session — falling through to guided default"
            );
            None
        }
    }
}

#[cfg(test)]
mod tests;