trusty-mpm 1.0.2

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
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
//! tmux process driver.
//!
//! Why: `trusty-mpm-core::tmux` builds tmux argv vectors but never spawns a
//! process — that keeps it pure and testable. The daemon needs the other half:
//! actually running `tmux` and interpreting its exit status. This module is
//! distilled from `ai-commander`'s `commander-tmux` orchestrator and
//! `open-mpm`'s `tm` manager — find the binary once, run argv, classify the
//! "no server running" empty-list case.
//! What: [`TmuxDriver`] wraps the resolved `tmux` path; it can create/kill/list
//! sessions, send keystrokes, and capture pane output. [`SessionInfo`] is one
//! parsed `list-sessions` row.
//! Test: `cargo test -p trusty-mpm-daemon` covers binary discovery degradation
//! and `list-sessions` row parsing without requiring tmux to be installed.

// The session-start command path (which spawns Claude Code into a tmux
// session) lands in a follow-up issue; until then this driver is exercised
// only by its own tests, so its public surface is intentionally unused.
#![allow(dead_code)]

use std::process::Command;

use tracing::warn;

use crate::core::external_session::ExternalSession;
use crate::core::oauth_token::OAUTH_TOKEN_ENV_VAR;
use crate::core::tmux::{TmuxCommand, TmuxTarget, tmux_argv};
use crate::core::{Error, Result};

/// Find the end (one PAST the true closing `'`, byte offset into `s`) of a
/// POSIX shell single-quoted value, given `s` is the text immediately AFTER
/// the opening quote.
///
/// Why: [`shell_single_quote`](crate::runtime::claude_code) escapes an
/// embedded literal `'` as the 4-byte close-escape-reopen sequence `'\''`
/// (close the current quote, backslash-escape a literal `'`, reopen a new
/// quote) — POSIX shells have no in-quote escape, so this is the standard
/// way to embed a quote inside a single-quoted string. A naive scan for the
/// FIRST `'` after the opener mistakes that sequence's first byte for the
/// closer, truncating the redaction and leaking every byte of the value AFTER
/// the embedded quote in cleartext (a real reviewer-caught edge case: a token
/// containing `'` would leak its tail). This walks the value treating `'\''`
/// as one escaped-quote unit to skip over, so only a BARE `'` — one not
/// followed by `\''` — is treated as the true closer.
/// What: scans byte-by-byte (safe: the only bytes it compares against are `'`
/// and `\`, both single-byte ASCII, so it can never land mid-codepoint of a
/// multi-byte UTF-8 sequence in an untouched run of bytes). At each `'`, if
/// the next three bytes spell `\''` the whole 4-byte run is an escaped
/// literal quote — skipped, continue scanning; otherwise this `'` is the true
/// closer and its index + 1 is returned. Falls back to `s.len()` if no closer
/// is found (malformed input — treat the rest of the string as the value
/// rather than panic or leak).
/// Test: `find_quoted_value_end_stops_at_bare_closer`,
/// `find_quoted_value_end_skips_escaped_embedded_quote`,
/// `redact_oauth_token_masks_value_with_embedded_single_quote`.
fn find_quoted_value_end(s: &str) -> usize {
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\'' {
            if bytes[i..].starts_with(b"'\\''") {
                i += 4; // escaped embedded quote unit — not the closer
                continue;
            }
            return i + 1; // bare closer — include it in the consumed span
        }
        i += 1;
    }
    bytes.len()
}

/// Mask any `CLAUDE_CODE_OAUTH_TOKEN=<value>` secret in `s` before it reaches a
/// log or a persisted record.
///
/// Why: managed-session pane commands interpolate a cleartext
/// `CLAUDE_CODE_OAUTH_TOKEN='<token>'` (#2246). When [`TmuxDriver::run`] maps a
/// failed `send-keys` to an error it formats the full argv — which would
/// otherwise carry that OAuth secret into every downstream `warn!` log in
/// `daemon::managed_routes::lifecycle` AND into the persisted session `task`
/// field via `session_manager::manager::mark_errored`, where `tm session ls`
/// surfaces it. Redacting at this single source closes every one of those
/// paths at once, so no caller has to remember to scrub.
/// What: replaces the value of each `CLAUDE_CODE_OAUTH_TOKEN=` assignment with
/// `<redacted>`, handling both the single-quoted form
/// (`CLAUDE_CODE_OAUTH_TOKEN='…'` → `CLAUDE_CODE_OAUTH_TOKEN='<redacted>'`,
/// via [`find_quoted_value_end`] so a value containing an escaped embedded
/// quote is masked in full, not just up to its first byte) and a bare
/// unquoted form (value ends at the next ASCII whitespace). All other bytes
/// are copied through unchanged, so a string with no token is returned
/// verbatim.
/// Test: `redact_oauth_token_masks_quoted_value`,
/// `redact_oauth_token_masks_unquoted_value`,
/// `redact_oauth_token_masks_value_with_embedded_single_quote`,
/// `redact_oauth_token_leaves_unrelated_text_untouched`,
/// `run_style_error_message_does_not_leak_oauth_token`.
fn redact_oauth_token(s: &str) -> String {
    let needle = format!("{OAUTH_TOKEN_ENV_VAR}=");
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(pos) = rest.find(&needle) {
        out.push_str(&rest[..pos + needle.len()]);
        let after = &rest[pos + needle.len()..];
        if let Some(stripped) = after.strip_prefix('\'') {
            // Single-quoted value: mask up to and including the TRUE closing
            // quote, correctly skipping any escaped embedded quotes.
            let end = find_quoted_value_end(stripped);
            out.push_str("'<redacted>'");
            rest = &stripped[end..];
        } else {
            // Bare value: mask up to the next whitespace (or end of string).
            let end = after.find(char::is_whitespace).unwrap_or(after.len());
            out.push_str("<redacted>");
            rest = &after[end..];
        }
    }
    out.push_str(rest);
    out
}

/// A parsed `tmux list-sessions` row.
///
/// Why: the dashboard wants structured session data, not raw tmux text.
/// What: the fields from `SESSION_LIST_FORMAT` — name, creation epoch, attached.
/// Test: `parses_session_row`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionInfo {
    /// tmux session name.
    pub name: String,
    /// Unix epoch seconds the session was created.
    pub created: i64,
    /// Whether a client is currently attached.
    pub attached: bool,
}

impl SessionInfo {
    /// Parse one `name:created:attached` row from `list-sessions`.
    ///
    /// Why: a single parser keeps the format in sync with
    /// `core::tmux::SESSION_LIST_FORMAT`.
    /// What: splits on `:`; tolerates a malformed `attached` flag by defaulting
    /// it to `false`.
    /// Test: `parses_session_row`.
    pub fn parse(line: &str) -> Result<Self> {
        let mut parts = line.splitn(3, ':');
        let name = parts
            .next()
            .filter(|s| !s.is_empty())
            .ok_or_else(|| Error::Protocol(format!("empty tmux session row: {line:?}")))?
            .to_string();
        let created = parts
            .next()
            .and_then(|s| s.parse::<i64>().ok())
            .ok_or_else(|| Error::Protocol(format!("bad tmux created field: {line:?}")))?;
        let attached = parts.next().map(|s| s == "1").unwrap_or(false);
        Ok(Self {
            name,
            created,
            attached,
        })
    }
}

/// Drives the `tmux` binary on behalf of the daemon's session manager.
///
/// Why: hosting Claude Code inside tmux is the primary control model; the
/// daemon needs a thin, fallible wrapper rather than scattering `Command`
/// calls. Holding the resolved path means PATH is consulted only once.
/// What: stores the `tmux` executable path; methods execute typed
/// [`TmuxCommand`]s built by `core::tmux`.
/// Test: `driver_reports_availability`.
#[derive(Debug, Clone)]
pub struct TmuxDriver {
    /// Absolute path to the `tmux` binary.
    tmux_path: String,
}

impl TmuxDriver {
    /// Resolve the `tmux` binary, or fail if it cannot be found.
    ///
    /// Why: the daemon should refuse the tmux control model up front rather
    /// than fail on the first session start. Under launchd the daemon inherits
    /// a minimal `PATH` (`/usr/bin:/bin:/usr/sbin:/sbin`) that omits Homebrew,
    /// so a bare `PATH` lookup of `tmux` (which lives at `/opt/homebrew/bin`)
    /// returns nothing and every managed-session spawn 500s after a restart
    /// (#1298). Resolving via the well-known dirs makes discovery survive the
    /// minimal inherited `PATH`.
    /// What: delegates to [`trusty_common::bin_resolve::resolve_binary`], which
    /// consults the live `PATH` first and then falls back to the well-known
    /// daemon dirs (Homebrew + user bins). Errors with a clear message if no
    /// `tmux` is found anywhere.
    /// Test: `driver_reports_availability` (skips assertion when tmux missing).
    pub fn discover() -> Result<Self> {
        let path = trusty_common::bin_resolve::resolve_binary("tmux").ok_or_else(|| {
            Error::Protocol(
                "tmux not found on PATH or in well-known dirs (e.g. /opt/homebrew/bin); \
                 use the PTY or SDK control model"
                    .into(),
            )
        })?;
        let path = path
            .to_str()
            .ok_or_else(|| Error::Protocol("resolved tmux path is not valid UTF-8".into()))?
            .to_string();
        Ok(Self { tmux_path: path })
    }

    /// True if a `tmux` binary is available on this host.
    pub fn is_available() -> bool {
        Self::discover().is_ok()
    }

    /// Confirm the tmux SERVER exists, starting it if necessary (#3823).
    ///
    /// Why: on a machine where tmux has never run, the socket directory
    /// itself does not exist yet — `list-sessions` fails with a raw "No such
    /// file or directory"/"error connecting to" message that
    /// [`Self::list_sessions`]'s "no server running"/"no sessions" empty-list
    /// classification does not recognize, so it propagates as an `Err`. The
    /// session-creation flow's FIRST tmux call is exactly this
    /// `list-sessions` (`SessionManager::resolve_session_name` →
    /// `names_for_serial_allocation` and `SessionManager::dedupe_session_name`,
    /// both called before the #3386/#3722 `create_managed_session` choke
    /// point is ever reached), so that choke point's own `ensure_server_up`
    /// call comes too late to help — the caller already 500'd. This method
    /// lets `SessionManager::create_with_id`/`create_with_reserved_name`/
    /// `resume` (`session_manager/create.rs`, `session_manager/manager.rs`)
    /// guarantee the server is up BEFORE issuing that first `list-sessions`.
    /// What: delegates to [`crate::core::tmux::ensure_server_up`] (the same
    /// retried-with-backoff `tmux start-server` primitive #3722 added),
    /// mapping its `Err(String)` to `Error::Protocol`.
    /// Test: `ensure_server_up_issues_start_server_on_a_fresh_socket`,
    /// `ensure_server_up_fails_loudly_when_the_server_never_comes_up`
    /// (`tmux_tests.rs`, both drive a scripted fake `tmux` binary).
    pub fn ensure_server_up(&self) -> Result<()> {
        crate::core::tmux::ensure_server_up(&self.tmux_path).map_err(Error::Protocol)
    }

    /// Run a typed tmux command, returning captured stdout on success.
    ///
    /// Why: every other method routes through here so exit-status handling
    /// lives in one place. The actual process spawn is delegated to
    /// [`crate::core::tmux::run_tmux_with_bin`] (#2398 architecture
    /// consolidation) — `TmuxDriver` WRAPS that single crate-wide entry point
    /// rather than spawning independently, using its own already-resolved
    /// `self.tmux_path` (cached at [`Self::discover`] time for the
    /// fail-fast-if-absent contract) instead of re-resolving on every call.
    /// What: renders argv via `core::tmux::tmux_argv` (for the error message
    /// only — the actual spawn happens inside `run_tmux_with_bin`), runs
    /// `tmux`, and maps a non-zero exit to `Error::Protocol` carrying stderr.
    /// Test: exercised indirectly by the `#[ignore]` integration tests.
    fn run(&self, cmd: &TmuxCommand) -> Result<String> {
        let output = crate::core::tmux::run_tmux_with_bin(&self.tmux_path, cmd)?;
        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).into_owned())
        } else {
            let argv = tmux_argv(cmd);
            let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
            // #2246: the argv can embed a cleartext CLAUDE_CODE_OAUTH_TOKEN
            // (managed-spawn pane command). Redact at this single source so the
            // secret can never reach the ~5 warn! sites in
            // daemon::managed_routes::lifecycle nor the persisted session `task`
            // field (mark_errored → `tm session ls`). stderr is redacted too in
            // case tmux echoes the offending keys back.
            Err(Error::Protocol(redact_oauth_token(&format!(
                "tmux {argv:?} failed: {stderr}"
            ))))
        }
    }

    /// Create a detached tmux session named `name`, optionally in `workdir`.
    ///
    /// Idempotent: if a session with the same name already exists, the
    /// underlying `tmux new-session -A` attaches to it instead of failing
    /// with a "duplicate session" error.
    ///
    /// Why (#2398): the scrollback/mouse server options MUST be applied
    /// before this method's `new-session` call — `history-limit` is captured
    /// into a pane's ring buffer at creation time. Delegates to
    /// [`crate::core::tmux::create_managed_session`], the crate-wide session-
    /// creation choke point EVERY session-creating call site (daemon, CLI,
    /// TUI client, control-plane backend) now routes through, so the
    /// ordering can never be bypassed by a future call site again.
    ///
    /// #3386 review: [`crate::core::tmux::warn_if_options_unverified`] logs
    /// an `error!` naming the session when the ergonomics could not be
    /// verified — the "at minimum" operator-visible surface the review
    /// requires (a `warn!`-only log is the exact silent-degrade #3386 was
    /// filed against).
    pub fn create_session(&self, name: &str, workdir: Option<&str>) -> Result<()> {
        let outcome =
            crate::core::tmux::create_managed_session(Some(&self.tmux_path), name, workdir)
                .inspect(|o| crate::core::tmux::warn_if_options_unverified(o, name))?;
        if outcome.output.status.success() {
            Ok(())
        } else {
            let stderr = String::from_utf8_lossy(&outcome.output.stderr).into_owned();
            Err(Error::Protocol(redact_oauth_token(&format!(
                "tmux new-session for {name} failed: {stderr}"
            ))))
        }
    }

    /// Apply the configured scrollback + mouse ergonomics to the tmux
    /// SERVER, before any pane is created (#2398).
    ///
    /// Why: tmux's own default `history-limit` is 2000 lines — a long-running
    /// PM session scrolls off the top almost immediately. `history-limit` is
    /// captured into a pane's ring buffer AT CREATION TIME; a per-session
    /// `set-option` issued after a pane already exists does not retroactively
    /// grow it (a tmux limitation — existing panes are unaffected by this
    /// call; only NEW panes/sessions created after it benefit). Because
    /// trusty-mpm runs every managed session on the ONE default tmux server
    /// (no dedicated `-S` socket — confirmed: no call site in this crate
    /// passes `-S`/`-L`), setting these as GLOBAL (`-g`) options once, right
    /// before [`Self::create_session`]'s `new-session`, benefits every
    /// session subsequently created without per-session bookkeeping. `mouse
    /// on` additionally maps the wheel to pane-scroll/copy-mode entry, the
    /// actual "scroll" gesture operators expect.
    /// What: loads [`crate::core::trusty_tools_config::TrustyToolsConfig`],
    /// resolves the `tmux:` section via
    /// [`crate::core::trusty_tools_config::resolve_tmux_options`] (defaults:
    /// 100,000-line history-limit, mouse on), and runs each
    /// [`crate::core::tmux::scrollback_option_commands`] entry via
    /// [`Self::run`]. Best-effort: `set-option -g` is idempotent (safe to
    /// call before every session creation) and virtually never fails on a
    /// tmux new enough to run trusty-mpm at all, but a failure here must
    /// never block session creation/restart — each failure is logged and the
    /// next option (or the caller's subsequent tmux call) still runs.
    /// Test: argv construction is covered by `core::tmux`'s
    /// `scrollback_option_commands_*` tests and config resolution by
    /// `core::trusty_tools_config`'s `tmux_options_*` tests; this method's
    /// live-server call site is exercised transitively by every
    /// `create_session` caller with a real `tmux` binary (`#[ignore]` tests).
    pub fn apply_scrollback_options(&self) {
        let config = crate::core::trusty_tools_config::TrustyToolsConfig::load();
        let opts = crate::core::trusty_tools_config::resolve_tmux_options(&config);
        for cmd in crate::core::tmux::scrollback_option_commands(opts.history_limit, opts.mouse) {
            if let Err(e) = self.run(&cmd) {
                warn!("tmux scrollback/mouse option {cmd:?} failed (non-fatal): {e}");
            }
        }
    }

    /// Kill the tmux session named `name`.
    pub fn kill_session(&self, name: &str) -> Result<()> {
        self.run(&TmuxCommand::KillSession {
            name: name.to_string(),
        })?;
        Ok(())
    }

    /// List all tmux sessions on this host.
    ///
    /// Why: the multi-session dashboard enumerates every running session.
    /// What: runs `list-sessions`; tmux exits non-zero with "no server running"
    /// when there are zero sessions — that is mapped to an empty `Vec`.
    /// Test: row parsing covered by `parses_session_row`.
    pub fn list_sessions(&self) -> Result<Vec<SessionInfo>> {
        let argv = tmux_argv(&TmuxCommand::ListSessions);
        let output = Command::new(&self.tmux_path).args(&argv).output()?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("no server running") || stderr.contains("no sessions") {
                return Ok(Vec::new());
            }
            return Err(Error::Protocol(format!("tmux list-sessions: {stderr}")));
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut sessions = Vec::new();
        for line in stdout.lines().filter(|l| !l.is_empty()) {
            sessions.push(SessionInfo::parse(line)?);
        }
        Ok(sessions)
    }

    /// Send literal text to a session/pane, then press Enter to execute it.
    ///
    /// Why: launching Claude Code or feeding it a prompt means typing a line
    /// and submitting it; tmux needs the text sent with `-l` (literal) and the
    /// `Enter` keypress sent separately.
    /// What: two `send-keys` invocations — literal text, then the `Enter` key.
    /// Test: argv shapes covered in `core::tmux` tests.
    pub fn send_line(&self, target: &TmuxTarget, text: &str) -> Result<()> {
        self.run(&TmuxCommand::SendKeys {
            target: target.clone(),
            keys: text.to_string(),
            literal: true,
        })?;
        self.run(&TmuxCommand::SendKeys {
            target: target.clone(),
            keys: "Enter".to_string(),
            literal: false,
        })?;
        Ok(())
    }

    /// Send literal text to a session/pane WITHOUT a trailing Enter.
    ///
    /// Why: the harness-agnostic no-submit inject intent (#1461) types into the
    /// pane but leaves the line uncommitted (vs. [`send_line`](Self::send_line),
    /// which appends Enter). Keeping it a separate one-shot avoids the second
    /// `Enter` send-keys call.
    /// What: a single `send-keys -l` invocation (literal, no key-name follow-up).
    /// Test: argv shape covered by `trusty_common::tmux`'s `send_keys_literal_argv`.
    pub fn send_keys_literal(&self, target: &TmuxTarget, text: &str) -> Result<()> {
        self.run(&TmuxCommand::SendKeys {
            target: target.clone(),
            keys: text.to_string(),
            literal: true,
        })?;
        Ok(())
    }

    /// Send a Ctrl-C interrupt to a session/pane.
    ///
    /// Why: restarting Claude Code in place means interrupting the running
    /// process before relaunching it; `C-c` is the clean stop.
    /// What: one `send-keys` invocation with the `C-c` key name (non-literal).
    /// Test: argv shape covered by `trusty_common::tmux`'s `send_keys_keyname_argv`.
    pub fn send_interrupt(&self, target: &TmuxTarget) -> Result<()> {
        self.run(&TmuxCommand::SendKeys {
            target: target.clone(),
            keys: "C-c".to_string(),
            literal: false,
        })?;
        Ok(())
    }

    /// Capture the last `lines` of a pane's output (whole scrollback if `None`).
    pub fn capture(&self, target: &TmuxTarget, lines: Option<u32>) -> Result<String> {
        self.run(&TmuxCommand::CapturePane {
            target: target.clone(),
            lines,
        })
    }

    /// Durably publish `key=value` into the tmux SESSION environment (#2157 item 1).
    ///
    /// Why: `runtime::claude_code::session_id_export_prefix` exports
    /// `TM_MANAGED_SESSION_ID` into the ONE pane shell that ran the spawn/resume
    /// command line — a sibling pane/window in the same session, or a pane
    /// spawned before this fix landed, never sees it, which is why the
    /// in-place-relaunch gate (`bin/tm/commands/guided_inplace.rs`) could fail
    /// silently and bare `tm` fell through to spawning a nested session
    /// (issue #2157). `set-environment` writes into the session's own
    /// environment table, queryable via `tmux show-environment` from ANY
    /// pane/shell in that session regardless of vintage.
    /// What: runs `tmux set-environment -t <session> <key> <value>`; maps a
    /// non-zero exit to `Error::Protocol`. Callers treat this as best-effort —
    /// the shell-export prefix remains the primary mechanism.
    /// Test: argv shape covered by `core::tmux::set_environment_argv`.
    pub fn set_environment(&self, session: &str, key: &str, value: &str) -> Result<()> {
        self.run(&TmuxCommand::SetEnvironment {
            session: session.to_string(),
            key: key.to_string(),
            value: value.to_string(),
        })?;
        Ok(())
    }

    /// List every pane on the host as `session_name pane_current_command`.
    ///
    /// Why: session auto-discovery scans all panes to find ones running Claude
    /// Code; `list-panes -a` reports every pane across every session in one
    /// call, so the daemon need not iterate sessions itself.
    /// What: runs `tmux list-panes -a -F "#{session_name} #{pane_current_command}"`
    /// directly (this cross-session form has no `core::tmux::TmuxCommand`
    /// variant) and returns its raw stdout. An empty tmux server (`no server
    /// running`) yields an empty string rather than an error.
    /// Test: parsing of the output is covered by `discovery::parse_pane_line`;
    /// this listing path is exercised by the `discovery` tmux-absent test.
    pub fn list_claude_panes(&self) -> Result<String> {
        let output = Command::new(&self.tmux_path)
            .args([
                "list-panes",
                "-a",
                "-F",
                "#{session_name} #{pane_current_command}",
            ])
            .output()?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("no server running") || stderr.contains("no sessions") {
                return Ok(String::new());
            }
            return Err(Error::Protocol(format!("tmux list-panes -a: {stderr}")));
        }
        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    }

    /// Enumerate every pane as a structured [`orphan_gc::PaneInfo`] row.
    ///
    /// Why: the orphan-GC must reconcile live tmux against the registries, and
    /// to decide whether a session is idle it needs each pane's
    /// `pane_current_command` (and, for the belt-and-braces liveness check, the
    /// pane's shell PID). The reactivate-reconcile path (#2789) additionally
    /// needs each pane's stable `pane_id` to identify the caller's OWN pane and
    /// treat it as idle. `list-panes -a` reports all of that across every
    /// session in a single tmux call.
    /// What: runs
    /// `tmux list-panes -a -F "#{session_name}\t#{pane_current_command}\t#{pane_pid}\t#{pane_id}"`
    /// and parses each row into a [`orphan_gc::PaneInfo`]. A tab delimiter avoids
    /// colliding with the colons in session names. An empty tmux server (`no
    /// server running`) yields an empty `Vec` rather than an error, so a quiet
    /// host reaps nothing rather than failing the sweep.
    /// Test: row parsing covered by `parses_managed_pane_row`; the live listing
    /// path is exercised by the `#[ignore]` integration test.
    pub fn list_managed_panes(&self) -> Result<Vec<crate::daemon::orphan_gc::PaneInfo>> {
        let output = Command::new(&self.tmux_path)
            .args([
                "list-panes",
                "-a",
                "-F",
                "#{session_name}\t#{pane_current_command}\t#{pane_pid}\t#{pane_id}",
            ])
            .output()?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            if stderr.contains("no server running") || stderr.contains("no sessions") {
                return Ok(Vec::new());
            }
            return Err(Error::Protocol(format!("tmux list-panes -a: {stderr}")));
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        Ok(stdout
            .lines()
            .filter(|l| !l.is_empty())
            .filter_map(Self::parse_managed_pane_row)
            .collect())
    }

    /// Parse one `session_name\tpane_current_command\tpane_pid\tpane_id` row.
    ///
    /// Why: keeping the parse separate from the subprocess call makes it
    /// unit-testable without spawning tmux.
    /// What: splits on the tab delimiter; a row missing the session name is
    /// dropped (`None`); a missing or unparsable PID degrades to `None` PID
    /// rather than dropping the whole row (the command is the primary signal);
    /// a missing/blank `pane_id` degrades to `None` (an older tmux or a
    /// truncated row still yields a usable pane for the idleness sweep).
    /// Test: `parses_managed_pane_row`.
    fn parse_managed_pane_row(line: &str) -> Option<crate::daemon::orphan_gc::PaneInfo> {
        let mut parts = line.splitn(4, '\t');
        let session_name = parts.next().filter(|s| !s.is_empty())?.to_string();
        let pane_current_command = parts.next().unwrap_or("").trim().to_string();
        let pane_pid = parts.next().and_then(|s| s.trim().parse::<u32>().ok());
        let pane_id = parts
            .next()
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        Some(crate::daemon::orphan_gc::PaneInfo {
            session_name,
            pane_current_command,
            pane_pid,
            pane_id,
        })
    }

    /// List every tmux session, tagged with its [`SessionOrigin`].
    ///
    /// Why: the universal-session dashboard manages *all* tmux sessions, not
    /// just the ones trusty-mpm created; each row must carry its origin so the
    /// UI can offer to adopt external sessions.
    /// What: runs `list-sessions` (same as [`list_sessions`](Self::list_sessions))
    /// and maps each row into an origin-classified [`ExternalSession`]. An empty
    /// tmux server yields an empty `Vec`.
    /// Test: classification covered by `core::external_session` tests; the
    /// listing path is exercised by the `#[ignore]` integration test.
    pub fn list_all_sessions(&self) -> Result<Vec<ExternalSession>> {
        Ok(self
            .list_sessions()?
            .into_iter()
            .map(|s| ExternalSession::new(s.name, s.attached, s.created))
            .collect())
    }

    /// Capture the current state of any session for monitoring.
    ///
    /// Why: trusty-mpm oversees external sessions read-only; the daemon must be
    /// able to snapshot a session's windows, panes, and recent output without
    /// modifying it.
    /// What: runs `list-windows` / `list-panes` / `capture-pane` against `name`
    /// and bundles the results into a [`SessionSnapshot`]. tmux being absent or
    /// the session not existing surfaces as an `Err`.
    /// Test: `#[ignore]` integration test `monitor_session_snapshots_state`.
    pub fn monitor_session(&self, name: &str, lines: u32) -> Result<SessionSnapshot> {
        let windows = self.list_windows(name)?;
        let panes = self.list_panes(name)?;
        let output = self.capture(&TmuxTarget::session(name), Some(lines))?;
        Ok(SessionSnapshot {
            name: name.to_string(),
            windows,
            panes,
            output,
            captured_at: chrono::Utc::now().timestamp(),
        })
    }

    /// Return the pane's current working directory via `display-message`.
    ///
    /// Why: the snapshot-before-stop path (#1816) needs the pane's cwd to
    /// restore it on resume; `tmux display-message -p '#{pane_current_path}'`
    /// is the standard mechanism. The call is best-effort — callers must handle
    /// `None` gracefully (resume falls back to workspace_path/cwd).
    /// What: runs `tmux display-message -t <name> -p '#{pane_current_path}'`,
    /// trims the output, and returns `Some(path)` on success or `None` if the
    /// session does not exist, tmux is unavailable, or the path is empty.
    /// Test: exercised indirectly via `snapshot::capture_into` with a live tmux;
    /// `RealTmuxDriver::get_pane_cwd` wraps this method.
    pub fn pane_current_path(&self, session_name: &str) -> Option<std::path::PathBuf> {
        let output = Command::new(&self.tmux_path)
            .args([
                "display-message",
                "-t",
                session_name,
                "-p",
                "#{pane_current_path}",
            ])
            .output()
            .ok()?;
        if !output.status.success() {
            return None;
        }
        let raw = String::from_utf8_lossy(&output.stdout);
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(std::path::PathBuf::from(trimmed))
        }
    }

    /// Return the pane's stable tmux `pane_id` (e.g. `"%5"`) via `display-message`.
    ///
    /// Why: `#2453` review finding 1 (round 2) — pane-identity confirmation for
    /// the bare-`tm` in-pane relaunch's nested-session guard needs a signal
    /// that is NEVER inherited across panes, unlike a tmux session-scoped env
    /// var (`set-environment` is applied to every new pane/window created in
    /// that session afterward, defeating an env-var-only gate — see
    /// [`crate::session_manager::record::SessionRecord::pane_id`]'s doc for
    /// the full empirical proof). tmux's own `pane_id` (distinct from
    /// `pane_pid`, which the OS can reuse across a pane's lifetime) is that
    /// signal.
    /// What: runs `tmux display-message -t <name> -p '#{pane_id}'`, trims the
    /// output, and returns `Some(id)` on success or `None` if the session does
    /// not exist, tmux is unavailable, or the id is empty. Mirrors
    /// [`Self::pane_current_path`]'s exact shape.
    /// Test: exercised indirectly via `SessionManager::create`/
    /// `mark_runtime_exited_stopped` with a live tmux;
    /// `RealTmuxDriver::get_pane_id` wraps this method.
    pub fn pane_id(&self, session_name: &str) -> Option<String> {
        let output = Command::new(&self.tmux_path)
            .args(["display-message", "-t", session_name, "-p", "#{pane_id}"])
            .output()
            .ok()?;
        if !output.status.success() {
            return None;
        }
        let raw = String::from_utf8_lossy(&output.stdout);
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    }

    /// Register an external session for oversight without modifying it.
    ///
    /// Why: before trusty-mpm watches an externally-created session it records
    /// the session's current shape; adoption is explicitly *non-destructive* —
    /// it never kills, renames, or sends keys to the session.
    /// What: probes the session exists, captures its window/pane lists, and
    /// returns an [`AdoptedSession`] describing it. An unknown session is an
    /// `Err`.
    /// Test: `#[ignore]` integration test `adopt_session_captures_state`.
    pub fn adopt_session(&self, name: &str) -> Result<AdoptedSession> {
        let windows = self.list_windows(name)?;
        let panes = self.list_panes(name)?;
        let origin = crate::core::external_session::SessionOrigin::classify(name);
        Ok(AdoptedSession {
            name: name.to_string(),
            origin,
            windows,
            panes,
            adopted_at: chrono::Utc::now().timestamp(),
        })
    }

    /// List the window `index:name` rows for a session.
    ///
    /// Why: snapshot and adoption both need a session's window list.
    /// What: runs `list-windows -F` and returns each row verbatim.
    /// Test: argv shape covered by `core::tmux::list_windows_argv`.
    fn list_windows(&self, name: &str) -> Result<Vec<String>> {
        let raw = self.run(&TmuxCommand::ListWindows {
            name: name.to_string(),
        })?;
        Ok(raw
            .lines()
            .filter(|l| !l.is_empty())
            .map(String::from)
            .collect())
    }

    /// List the pane `id:active` rows for a session, across ALL of its
    /// windows.
    ///
    /// Why: snapshot and adoption both need a session's FULL pane list, not
    /// just the currently active window's — a plain `list-panes -t <session>`
    /// (no `-s`) resolves the session target down to its active window only,
    /// which silently drops any pane living in a non-active window (exactly
    /// the sibling-window-hijack shape this feature guards against). This bug
    /// was caught by the live-tmux test written for the #2467 follow-up, not
    /// by the mock-only unit tests.
    /// What: runs `list-panes -s -t <name> -F` and returns each row verbatim.
    /// Test: argv shape covered by `core::tmux::list_panes_argv`.
    fn list_panes(&self, name: &str) -> Result<Vec<String>> {
        let raw = self.run(&TmuxCommand::ListPanes {
            name: name.to_string(),
        })?;
        Ok(raw
            .lines()
            .filter(|l| !l.is_empty())
            .map(String::from)
            .collect())
    }

    /// Return whether `pane_id` still exists as a live pane within
    /// `session_name`'s tmux session (sibling-window hijack, follow-up to
    /// #2456).
    ///
    /// Why: `session_exists` alone cannot distinguish "the recorded pane
    /// survived" from "the tmux SESSION merely has some OTHER pane alive"
    /// (e.g. a sibling window opened after the recorded pane was closed) —
    /// `SessionManager::resume`'s reuse branch needs the stronger,
    /// pane-specific answer before it trusts a session-scoped respawn target.
    /// What: runs `list-panes -t <session_name> -F` (via [`Self::list_panes`],
    /// format `#{pane_id}:#{pane_active}`) and checks whether `pane_id`
    /// matches the id portion of any row. Returns `false` on any query
    /// failure (session gone, tmux unavailable) — the safe direction for a
    /// presence check feeding a refusal path is to treat "cannot confirm" as
    /// "not present" (fail toward refusing the unsafe respawn, never toward
    /// silently trusting a pane that might not be there).
    /// Test: argv shape covered by `core::tmux::list_panes_argv`; behavior
    /// (true for a real pane, false for a fabricated pane id in a live,
    /// still-alive session) is exercised by the `#[ignore]` live integration
    /// test `live_pane_scoped_send_targets_original_pane_not_sibling` in
    /// `tests/session_manager_mvp.rs` — that test also covers
    /// `RealTmuxDriver::pane_exists`'s call-through and
    /// `send_line`/`send_line_to_pane`'s pane-scoped `-t` targeting.
    pub fn pane_exists(&self, session_name: &str, pane_id: &str) -> bool {
        match self.list_panes(session_name) {
            Ok(rows) => rows
                .iter()
                .any(|row| row.split(':').next() == Some(pane_id)),
            Err(_) => false,
        }
    }

    /// Tri-state variant of [`Self::pane_exists`] distinguishing "confirmed
    /// present" (`Some(true)`), "confirmed absent" (`Some(false)`), and
    /// "could not determine" (`None`) — #3714 review finding 2.
    ///
    /// Why: [`Self::pane_exists`]'s bare `bool` deliberately collapses
    /// "confirmed absent" and "query failed" into the same `false` — correct
    /// fail-closed behavior for a MUTATION guard (a rename must never trust
    /// an unverifiable pane as safe to physically retarget). A DISPLAY-only
    /// consumer has the opposite risk: collapsing "could not determine" into
    /// "not live" flips a genuinely live record's SHOWN `state` to
    /// `"stopped"` on a transient `tmux list-panes` hiccup — reproducing the
    /// exact `state`/`persisted_state` disagreement #3714 exists to fix,
    /// just from a different trigger (a query error rather than a
    /// duplicate-name collision). This lets a display-only caller fall back
    /// to a weaker signal (e.g. name-only) on `None` instead of asserting
    /// absence it cannot actually prove.
    /// What: identical query to `pane_exists`, but `Err` maps to `None`
    /// instead of `false`.
    /// Test: `daemon::managed_routes::summary`'s
    /// `reconcile_live_state_pane_query_error_does_not_flip_live_record_to_stopped`
    /// exercises the consumer; this method's own argv shape is covered by
    /// the same `core::tmux::list_panes_argv` coverage `pane_exists` uses.
    pub fn pane_exists_checked(&self, session_name: &str, pane_id: &str) -> Option<bool> {
        match self.list_panes(session_name) {
            Ok(rows) => Some(
                rows.iter()
                    .any(|row| row.split(':').next() == Some(pane_id)),
            ),
            Err(_) => None,
        }
    }
}

/// A non-destructive registration of an external tmux session.
///
/// Why: `POST /tmux/adopt` brings a pre-existing session under trusty-mpm
/// oversight; the response documents what was adopted without implying any
/// modification was made.
/// What: the session name, its classified origin, the window/pane lists at
/// adoption time, and the adoption epoch.
/// Test: `adopt_session_captures_state` (integration, `#[ignore]`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AdoptedSession {
    /// tmux session name.
    pub name: String,
    /// Whether the session is a trusty-mpm session or external.
    pub origin: crate::core::external_session::SessionOrigin,
    /// Window `index:name` rows captured at adoption time.
    pub windows: Vec<String>,
    /// Pane `id:active` rows captured at adoption time.
    pub panes: Vec<String>,
    /// Unix epoch seconds the session was adopted.
    pub adopted_at: i64,
}

/// A point-in-time snapshot of any tmux session's state.
///
/// Why: `GET /tmux/sessions/{name}/snapshot` lets the dashboard inspect any
/// session (internal or external) without attaching to it.
/// What: the session name, its window/pane lists, the captured pane output,
/// and the capture epoch.
/// Test: `monitor_session_snapshots_state` (integration, `#[ignore]`).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionSnapshot {
    /// tmux session name.
    pub name: String,
    /// Window `index:name` rows.
    pub windows: Vec<String>,
    /// Pane `id:active` rows.
    pub panes: Vec<String>,
    /// Captured pane output (last `lines` requested).
    pub output: String,
    /// Unix epoch seconds the snapshot was taken.
    pub captured_at: i64,
}

#[cfg(test)]
#[path = "tmux_tests.rs"]
mod tests;