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
//! The [`ManagedTmuxDriver`] trait seam used by the session manager.
//!
//! Why: split out of `manager.rs` (issue #1955) purely to keep that file under
//! the 500-SLOC production cap after the serial-numbered naming rework added a
//! new error variant and helper method. The trait itself has no behavior
//! change — it is a mechanical move.
//! What: [`ManagedTmuxDriver`], the minimal tmux operation surface the manager
//! depends on, with default implementations for the operations most drivers
//! do not need to override (`send_keys_literal`, `send_interrupt`,
//! `get_pane_cwd`, `session_exists`, `graceful_stop`).
//! Test: exercised via [`crate::session_manager::real_tmux::RealTmuxDriver`]
//! and the `FakeTmuxDriver` test double in `tests.rs`.

use super::manager::ManagedError;

/// Trait seam over tmux operations used by the session manager.
///
/// Why: the manager must be fully unit-testable without a live tmux binary;
/// a trait lets tests inject a `FakeTmuxDriver` instead of the real
/// [`crate::daemon::tmux::TmuxDriver`].
/// What: minimal surface — create session, kill session, send a line, capture
/// pane output, list session names, and probe existence.
/// Test: `FakeTmuxDriver` in `manager.rs`'s test section (`tests.rs`).
pub trait ManagedTmuxDriver: Send + Sync {
    /// Confirm the tmux SERVER exists (starting it if necessary) before any
    /// OTHER tmux call in this driver relies on it (#3823).
    ///
    /// Why: on a machine where tmux has never run, the very FIRST tmux call a
    /// session-creation/resume flow issues is a `list-sessions` probe
    /// (`SessionManager::resolve_session_name`/`dedupe_session_name`'s
    /// name-collision checks, `SessionManager::resume`'s
    /// `session_exists`/`ensure_pane_alive` checks) — well before the
    /// #3386/#3722 `create_managed_session` choke point (which already
    /// guarantees server-up, but only for the `set-option -g`/`new-session`
    /// sequence it directly issues) is ever reached. Without an explicit
    /// guard here, that first `list-sessions` fails on the missing socket and
    /// the whole flow 500s instead of transparently starting tmux.
    /// What: the default is `Ok(())` — a safe no-op for every test double
    /// (`FakeTmuxDriver`, `FakeNoopTmuxDriver`) and the `NoopTmuxDriver`
    /// tmux-absent fallback, none of which spawn a real tmux process.
    /// [`super::real_tmux::RealTmuxDriver`] overrides this to call
    /// [`crate::daemon::tmux::TmuxDriver::ensure_server_up`], which retries
    /// `tmux start-server` with backoff via
    /// [`crate::core::tmux::ensure_server_up`] (the same #3722 primitive
    /// `create_managed_session` uses).
    /// Test: `session_manager::server_up_tests` (`create_ensures_server_up_
    /// before_creating_session`, `create_fails_loudly_when_server_cannot_
    /// start`, `create_with_reserved_name_ensures_server_up_before_creating_
    /// session`, `resume_fails_loudly_when_server_cannot_start`) exercises
    /// `RealTmuxDriver`'s override via a call-counting/failure-injecting
    /// `FakeTmuxDriver`; `daemon::tmux::tests::ensure_server_up_issues_
    /// start_server_on_a_fresh_socket`/`_fails_loudly_when_the_server_
    /// never_comes_up` cover the underlying `TmuxDriver::ensure_server_up`
    /// this override delegates to. The trait default is exercised
    /// transitively by every `FakeTmuxDriver`-backed manager test (never
    /// errors).
    fn ensure_server_up(&self) -> Result<(), ManagedError> {
        Ok(())
    }

    /// Create a detached tmux session named `name`, rooted at `workdir`.
    fn create_session(&self, name: &str, workdir: &str) -> Result<(), ManagedError>;

    /// Kill the tmux session named `name`.
    fn kill_session(&self, name: &str) -> Result<(), ManagedError>;

    /// Rename the live tmux session `old` → `new`.
    ///
    /// Why: `tm sessions rename` keeps the tmux entity's name in sync with the
    /// record's `tmux_name` so `tmux attach`/`list-sessions` show the new name.
    /// What: the default FAILS CLOSED — a driver that cannot rename must not
    /// silently succeed and let the stored name drift from the live session;
    /// [`super::real_tmux::RealTmuxDriver`] runs `tmux rename-session`.
    /// Test: `RealTmuxDriver` override via the `#[ignore]` live test;
    /// `FakeTmuxDriver` overrides to rename in its in-memory session map.
    fn rename_session(&self, old: &str, new: &str) -> Result<(), ManagedError> {
        Err(ManagedError::TmuxUnavailable(format!(
            "rename-session not implemented for this driver ({old} -> {new})"
        )))
    }

    /// Names of tmux sessions with a client currently ATTACHED.
    ///
    /// Why: the `tm ls` list reconciliation distinguishes an ATTACHED session
    /// from a merely-live detached one so the picker renders `attached` and
    /// offers connect rather than a destructive restart.
    /// What: the default is EMPTY (best-effort — a driver that cannot report
    /// attachment simply never marks a session attached);
    /// [`super::real_tmux::RealTmuxDriver`] overrides it via tmux
    /// `#{session_attached}`.
    /// Test: `RealTmuxDriver` override is exercised by the `#[ignore]` live
    /// test; `FakeTmuxDriver` seeds attachment for `list_reconciles_*` coverage.
    fn attached_session_names(&self) -> Vec<String> {
        Vec::new()
    }

    /// Send literal text followed by Enter to the session named `name`.
    fn send_line(&self, name: &str, text: &str) -> Result<(), ManagedError>;

    /// Send literal text to `name` WITHOUT a trailing Enter (#1461).
    ///
    /// Why: the harness-agnostic [`Submit::NoSubmit`](crate::core::sm::control::Submit::NoSubmit)
    /// intent must type into the pane without committing the line (e.g. staging a
    /// partial command a human will edit). Splitting this out keeps `send_line`
    /// (literal + Enter) and this (literal only) as distinct, testable primitives.
    /// What: sends `text` literally. The default returns an explicit
    /// `TmuxUnavailable` error rather than silently falling back to `send_line`:
    /// delegating to `send_line` would append an Enter and SUBMIT a line the
    /// caller asked NOT to submit (`Submit::NoSubmit`) — a silent-wrong-behavior
    /// trap. Any driver actually used with `inject(.., NoSubmit)` MUST override
    /// this (the real `RealTmuxDriver` does); an un-overriding driver fails loudly.
    /// Test: `RealTmuxDriver` override is asserted via `core::tmux` argv tests;
    /// the no-submit dispatch is asserted by `inject_dispatch_nosubmit_sends_literal_only`.
    fn send_keys_literal(&self, _name: &str, _text: &str) -> Result<(), ManagedError> {
        Err(ManagedError::TmuxUnavailable(
            "send_keys_literal not implemented for this driver".into(),
        ))
    }

    /// Send literal text followed by Enter to a SPECIFIC pane within `name`'s
    /// tmux session, rather than whichever pane happens to be active.
    ///
    /// Why (sibling-window hijack, follow-up to #2456): `send_line` addresses
    /// the tmux SESSION only. tmux resolves a session-scoped target to
    /// whichever pane/window is currently ACTIVE — not necessarily the pane
    /// this call is actually about. `SessionManager::resume`'s reuse branch
    /// discovered this the hard way: a sibling window opened after the
    /// original pane, left active, silently received the respawned `claude`
    /// process while the original pane sat at a bare shell. This method is
    /// the pane-scoped alternative: it must land in the exact pane addressed
    /// by `pane_id`, regardless of tmux's notion of "active".
    /// What: sends `text` + Enter to the pane addressed by `name:pane_id`
    /// (tmux's `-t <session>:<pane_id>` form). The default falls back to
    /// [`Self::send_line`] (session-scoped) — correct for any driver that
    /// predates pane-level addressing or has no pane to target yet (e.g. a
    /// freshly created session, where the session-scoped target IS the only
    /// pane). [`super::real_tmux::RealTmuxDriver`] overrides this to build an
    /// actual pane-scoped `TmuxTarget`.
    /// Test: `RealTmuxDriver`'s override is exercised by `core::tmux`'s
    /// pane-target argv coverage (`TmuxTarget::pane`); call-site assertions
    /// live in `runtime::test_helpers::FakeTmux` (`pane_sends`) and
    /// `claude_code`'s `spawn_resume_targets_stored_pane_id_when_known` test.
    fn send_line_to_pane(&self, name: &str, pane_id: &str, text: &str) -> Result<(), ManagedError> {
        let _ = pane_id;
        self.send_line(name, text)
    }

    /// Send literal text WITHOUT a trailing Enter to a SPECIFIC pane (#2468,
    /// same rationale as [`Self::send_line_to_pane`]).
    ///
    /// What: the pane-scoped counterpart to [`Self::send_keys_literal`],
    /// used by `SessionManager::inject`'s `Submit::NoSubmit` dispatch when
    /// `record.pane_id` is known. The default returns an explicit
    /// `TmuxUnavailable` error rather than silently falling back to
    /// `send_keys_literal(name, text)` (#2514 review, minor finding 5): a
    /// silent session-scoped fallback here is exactly the sibling-window
    /// hijack #2468 exists to close, and a future driver that forgets to
    /// override this method would silently REGAIN the vulnerability with no
    /// compiler signal. Mirrors the fail-closed pattern already used by
    /// [`Self::send_keys_literal`]'s own default. Any driver actually used
    /// with a known `pane_id` MUST override this — both
    /// [`super::real_tmux::RealTmuxDriver`] and the test-only
    /// `FakeTmuxDriver` do.
    /// Test: `inject_nosubmit_targets_pane_when_pane_id_known` in
    /// `pane_scoped_tests.rs`; `send_keys_literal_to_pane_default_fails_closed`
    /// in this module's tests.
    fn send_keys_literal_to_pane(
        &self,
        name: &str,
        pane_id: &str,
        text: &str,
    ) -> Result<(), ManagedError> {
        let _ = (name, pane_id, text);
        Err(ManagedError::TmuxUnavailable(
            "send_keys_literal_to_pane not implemented for this driver".into(),
        ))
    }

    /// Report whether `pane_id` still exists as a live pane within `name`'s
    /// tmux session.
    ///
    /// Why (sibling-window hijack, follow-up to #2456): `resume`'s reuse
    /// branch must distinguish "the recorded pane is still there" from "the
    /// tmux SESSION merely has some OTHER pane alive" (e.g. a sibling window
    /// opened after the original pane was closed) — `session_exists` alone
    /// conflates the two, which is exactly how the hijack happens: the
    /// session look-alive check passes, so the code reuses it, then respawns
    /// via a session-scoped target that resolves to the sibling.
    /// What: returns `true` when the pane is confirmed present, `false` when
    /// confirmed absent. The default is `true` — "cannot verify" is treated
    /// as "assume present," so a driver that does not implement pane-level
    /// listing keeps today's session-scoped reuse behavior; this is a
    /// STRICTER check layered on top for drivers that opt in, not a new
    /// failure mode for ones that do not.
    /// [`super::real_tmux::RealTmuxDriver`] overrides this to actually query
    /// `tmux list-panes`.
    /// Test: `RealTmuxDriver`'s override is covered by `core::tmux`'s
    /// `list_panes_argv`; the manager-level refusal path is covered by
    /// `resume_refuses_when_stored_pane_gone_but_session_alive` in
    /// `resume_reattach_tests.rs`.
    fn pane_exists(&self, _name: &str, _pane_id: &str) -> bool {
        true
    }

    /// Tri-state variant of [`Self::pane_exists`] distinguishing "confirmed
    /// present", "confirmed absent", and "could not determine" (#3714 review
    /// finding 2).
    ///
    /// Why: [`Self::pane_exists`]'s bare `bool` deliberately collapses
    /// "confirmed absent" and "query failed" into `false` — correct,
    /// fail-closed behavior for a MUTATION guard (e.g.
    /// `SessionManager::rename` must never trust an unverifiable pane as
    /// safe to physically retarget — that call site keeps using
    /// [`Self::pane_exists`] unchanged). A DISPLAY-only reconciler
    /// (`daemon::managed_routes::summary::reconcile_live_state`) has the
    /// opposite risk: collapsing "could not determine" into "not live"
    /// would flip a genuinely live record's SHOWN `state` to `"stopped"` on
    /// a transient tmux query hiccup — reproducing the exact
    /// `state`/`persisted_state` disagreement #3714 exists to fix, just
    /// from a different trigger. This lets that caller fall back to a
    /// weaker signal (name-only) on `None` instead of asserting an absence
    /// it cannot actually prove.
    /// What: the default derives from [`Self::pane_exists`] — `true` maps to
    /// `Some(true)`, `false` maps to `Some(false)`; a driver that never
    /// overrides `pane_exists` therefore never produces `None`, matching its
    /// existing "cannot verify → assume present" semantics exactly.
    /// [`super::real_tmux::RealTmuxDriver`] overrides this to call
    /// `TmuxDriver::pane_exists_checked` directly, so a genuine
    /// `list-panes` query failure reports `None` rather than `Some(false)`.
    /// Test: `RealTmuxDriver`'s override is covered by the same
    /// `core::tmux::list_panes_argv` coverage `pane_exists` uses; the
    /// display-reconciliation consumer is covered by
    /// `reconcile_live_state_pane_query_error_does_not_flip_live_record_to_stopped`
    /// in `daemon::managed_routes::tests`.
    fn pane_exists_checked(&self, name: &str, pane_id: &str) -> Option<bool> {
        Some(self.pane_exists(name, pane_id))
    }

    /// Send an interrupt (Ctrl-C) to the session named `name` (#1461).
    ///
    /// Why: the [`Submit::Interrupt`](crate::core::sm::control::Submit::Interrupt)
    /// intent stops a running task in place (the clean precursor to relaunching a
    /// runtime). Exposing it on the trait keeps the interrupt path runtime-neutral.
    /// What: sends the runtime's interrupt. The default returns an explicit
    /// `TmuxUnavailable` error rather than a silent no-op `Ok(())`: Interrupt is
    /// the verb used to STOP a running task, so a silent no-op would leave the
    /// task running while the caller believes it was interrupted — a dangerous
    /// silent-wrong-behavior trap. Any driver actually used with
    /// `inject(.., Interrupt)` MUST override this (the real `RealTmuxDriver` sends
    /// `C-c`); an un-overriding driver fails loudly.
    /// Test: `RealTmuxDriver` override via `core::tmux::send_keys_keyname_argv`;
    /// dispatch asserted by `inject_dispatch_interrupt_sends_ctrl_c`.
    fn send_interrupt(&self, _name: &str) -> Result<(), ManagedError> {
        Err(ManagedError::TmuxUnavailable(
            "send_interrupt not implemented for this driver".into(),
        ))
    }

    /// Send Ctrl-C to a SPECIFIC pane rather than the session (#2468, same
    /// rationale as [`Self::send_line_to_pane`]).
    ///
    /// What: the pane-scoped counterpart to [`Self::send_interrupt`], used by
    /// `SessionManager::inject`'s `Submit::Interrupt` dispatch when
    /// `record.pane_id` is known. The default returns an explicit
    /// `TmuxUnavailable` error rather than silently falling back to
    /// `send_interrupt(name)` (#2514 review, minor finding 5) — the same
    /// fail-closed rationale as [`Self::send_keys_literal_to_pane`]'s default:
    /// a silent session-scoped fallback would regain the sibling-window
    /// hijack #2468 fixed, with no compiler signal warning a future driver
    /// that it forgot to override this. Any driver actually used with a known
    /// `pane_id` MUST override this — both
    /// [`super::real_tmux::RealTmuxDriver`] and the test-only
    /// `FakeTmuxDriver` do.
    /// Test: `inject_interrupt_targets_pane_when_pane_id_known` in
    /// `pane_scoped_tests.rs`; `send_interrupt_to_pane_default_fails_closed`
    /// in this module's tests.
    fn send_interrupt_to_pane(&self, name: &str, pane_id: &str) -> Result<(), ManagedError> {
        let _ = (name, pane_id);
        Err(ManagedError::TmuxUnavailable(
            "send_interrupt_to_pane not implemented for this driver".into(),
        ))
    }

    /// Capture the last `lines` of pane output for the session named `name`.
    ///
    /// `lines` is `usize` to match the harness-agnostic
    /// [`SessionControl::observe`](crate::core::sm::control::SessionControl::observe)
    /// contract end-to-end; the single `usize → u32` narrowing the underlying
    /// tmux `-S` argv requires is confined to the real-tmux driver edge, so no
    /// caller in the observe path needs a `try_from`.
    fn capture(&self, name: &str, lines: usize) -> Result<String, ManagedError>;

    /// Capture the last `lines` of output from a SPECIFIC pane rather than
    /// whichever pane the session name currently resolves to (#2468).
    ///
    /// Why: `SessionManager::observe`'s LLM-free pane read had the same
    /// sibling-window-hijack hole #2467 fixed for resume/restart — a
    /// session-scoped capture reads whatever pane tmux considers active,
    /// which need not be the pane this record is actually about.
    /// What: the pane-scoped counterpart to [`Self::capture`]. The default
    /// returns an explicit `TmuxUnavailable` error rather than silently
    /// falling back to `capture(name, lines)` (session-scoped) (#2514 review,
    /// minor finding 5) — the same fail-closed rationale as
    /// [`Self::send_keys_literal_to_pane`]'s default: a silent session-scoped
    /// fallback would regain the sibling-window hijack #2468 fixed for reads
    /// too, with no compiler signal warning a future driver that it forgot to
    /// override this. Any driver actually used with a known `pane_id` MUST
    /// override this — both [`super::real_tmux::RealTmuxDriver`] and the
    /// test-only `FakeTmuxDriver` do.
    /// Test: `observe_captures_pane_scoped_when_pane_id_known` in
    /// `pane_scoped_tests.rs`; `capture_pane_default_fails_closed` in this
    /// module's tests.
    fn capture_pane(
        &self,
        name: &str,
        pane_id: &str,
        lines: usize,
    ) -> Result<String, ManagedError> {
        let _ = (name, pane_id, lines);
        Err(ManagedError::TmuxUnavailable(
            "capture_pane not implemented for this driver".into(),
        ))
    }

    /// Return the pane's current working directory for snapshot-before-stop (#1816).
    ///
    /// Why: the idle auto-stop path captures cwd just before killing tmux so
    /// `resume()` can restore the operator's working directory instead of always
    /// starting at the workspace root. Returning `None` (the default) is safe —
    /// resume falls back to `workspace_path`/`cwd` as before.
    /// What: returns the `pane_current_path` tmux format string value, or `None`
    /// if the driver does not support it or the call fails.
    /// Test: `RealTmuxDriver` runs `tmux display-message`; fake drivers return `None`.
    fn get_pane_cwd(&self, _name: &str) -> Option<std::path::PathBuf> {
        None
    }

    /// Return the session's pane's stable tmux `pane_id` (e.g. `"%5"`),
    /// captured at spawn/reconcile time for pane-identity confirmation
    /// (#2453 review finding 1, round 2).
    ///
    /// Why: a session-name or process-env-var match is not proof the
    /// operator's CURRENT pane is the one bound to a record — see
    /// [`super::record::SessionRecord::pane_id`]'s doc for the full
    /// rationale (session-scoped `tmux set-environment` is inherited by
    /// sibling panes created afterward, which defeats an env-var-only gate).
    /// `pane_id` is tmux's own identifier and is never inherited across
    /// panes.
    /// What: returns the `pane_id` tmux format string value, or `None` if
    /// the driver does not support it or the call fails — the safe default,
    /// mirroring [`Self::get_pane_cwd`]. Callers MUST treat `None` as
    /// "identity unconfirmed," never as an implicit match.
    /// Test: `RealTmuxDriver` runs `tmux display-message`; fake drivers
    /// return `None` unless a test explicitly seeds one.
    fn get_pane_id(&self, _name: &str) -> Option<String> {
        None
    }

    /// Return all live tmux session names on the host.
    fn list_sessions(&self) -> Result<Vec<String>, ManagedError>;

    /// True if a tmux session with this name currently exists.
    fn session_exists(&self, name: &str) -> bool {
        self.list_sessions()
            .map(|names| names.iter().any(|n| n == name))
            .unwrap_or(false)
    }

    /// Probe whether the runtime inside `name`'s pane is READY to accept typed
    /// input (issue #1903 / #1299).
    ///
    /// Why: turnkey task injection (`SessionManager::inject_task_when_ready`)
    /// must not type the task into the pane before the runtime (`claude`) has
    /// actually launched — keystrokes sent to a pane whose shell is still
    /// exec-ing the runtime are lost or mangled. This is the readiness signal
    /// the injection loop polls (with bounded backoff) before delivering the
    /// task, replacing the blind fixed sleep the meta-launch prototype used.
    /// What: the default is `session_exists(name)` — sufficient for the test
    /// doubles (a fake reports its created session as existing) and a safe
    /// lower bound for any driver that cannot inspect the pane's process tree.
    /// [`super::real_tmux::RealTmuxDriver`] overrides this to the stronger
    /// signal: the `claude` child PID has appeared under the pane shell (the
    /// same probe `daemon::services::session_service::spawn_pid_capture` uses).
    /// Test: `RealTmuxDriver`'s override is exercised by the `#[ignore]` live
    /// integration test; the default is exercised via `FakeTmuxDriver` in
    /// `session_manager::task_inject`'s tests.
    fn runtime_ready(&self, name: &str) -> bool {
        self.session_exists(name)
    }

    /// Durably publish `key=value` into the named session's tmux environment
    /// (#2157 item 1) — belt-and-suspenders alongside the pane-shell `export …;`
    /// prefix `runtime::claude_code`/`runtime::tcode` already send.
    ///
    /// Why: the pane-shell export only lands in the ONE shell process that ran
    /// the spawn/resume command line; a sibling pane/window in the same tmux
    /// session (or a pane spawned before this method existed) never sees it.
    /// `tmux set-environment` writes into the SESSION's own environment table,
    /// which `tmux show-environment` can read from ANY pane in that session
    /// regardless of vintage — this is what lets the in-place-relaunch gate
    /// (`bin/tm/commands/guided_inplace.rs`) fall back to a tmux-side read when
    /// the process environment does not carry `TM_MANAGED_SESSION_ID`.
    /// What: the default is a silent `Ok(())` no-op — this is best-effort
    /// durability plumbing, not a caller-visible control action like
    /// `send_keys_literal`/`send_interrupt`, so a driver that cannot support it
    /// (e.g. tmux absent) must never fail the spawn/resume it is attached to.
    /// [`super::real_tmux::RealTmuxDriver`] overrides this to actually call
    /// tmux; test doubles record the call for assertions.
    /// Test: `RealTmuxDriver` override is asserted via `core::tmux::
    /// set_environment_argv`; call-site assertions live in
    /// `runtime::test_helpers::FakeTmux` and `session_manager::tests::
    /// FakeTmuxDriver`.
    fn set_environment(&self, _name: &str, _key: &str, _value: &str) -> Result<(), ManagedError> {
        Ok(())
    }

    /// Signal a session's process to stop, then kill the tmux session.
    ///
    /// Why: abruptly killing a session (`kill_session`) discards any in-flight
    /// work the claude process was persisting. Sending a termination signal first
    /// gives the process a chance to flush state — the async caller is responsible
    /// for inserting the ~2 s grace window before calling this (see
    /// `SessionManager::shutdown` in `restart_ops.rs`). This method is
    /// intentionally synchronous so it can live on the non-async trait; the delay
    /// is owned by the async shutdown path to avoid blocking a Tokio worker thread.
    /// What: if `claude_pid` is known, sends SIGTERM via `nix::signal::kill`;
    /// then unconditionally calls `kill_session`. If `claude_pid` is `None`,
    /// falls back to `send_interrupt` (Ctrl-C) before the kill. Signal errors are
    /// logged as warnings (the process may have already exited); only
    /// `kill_session` failure is returned as `Err`. Does NOT sleep — callers
    /// must insert an async delay (`tokio::time::sleep`) between the signal phase
    /// and calling this if a grace window is desired.
    /// Test: `fake_driver_graceful_stop_with_pid` (pid known, records kill),
    /// `fake_driver_graceful_stop_without_pid` (no pid, falls back to C-c).
    fn graceful_stop(&self, name: &str, claude_pid: Option<u32>) -> Result<(), ManagedError> {
        self.signal_terminate(name, claude_pid);
        self.kill_session(name)
    }

    /// Signal a session's `claude` process to stop WITHOUT killing the pane.
    ///
    /// Why: a truly graceful teardown sends the termination signal, waits a grace
    /// window so `claude` can flush state, and only THEN reclaims the pane. That
    /// ordering requires the signal and the kill to be separate steps — so this is
    /// the signal-only half, letting an async caller insert a `tokio::time::sleep`
    /// grace window between it and `kill_session` (see
    /// [`SessionManager::graceful_terminate_runtime`] for the CLI stop/decommission
    /// path). `graceful_stop` composes this with an immediate kill for the
    /// batched, one-grace-window-for-all shutdown path.
    /// What: SIGTERMs the known `claude_pid` via `nix::signal::kill` (unix only);
    /// when the pid is unknown, falls back to a single `send_interrupt` (Ctrl-C).
    /// Signal errors are logged and swallowed — the process may already be gone —
    /// so this method is infallible (the fallible reclaim lives in `kill_session`).
    /// Test: `fake_driver_graceful_stop_with_pid` / `_without_pid` cover the
    /// composed `graceful_stop`; the CLI drain is covered by
    /// `graceful_terminate_runtime_signals_then_kills` in `restart_ops`.
    fn signal_terminate(&self, name: &str, claude_pid: Option<u32>) {
        if let Some(pid) = claude_pid {
            #[cfg(unix)]
            {
                use nix::sys::signal::{Signal, kill};
                use nix::unistd::Pid;
                if let Err(e) = kill(Pid::from_raw(pid as i32), Signal::SIGTERM) {
                    tracing::warn!(pid, name, "signal_terminate: SIGTERM failed: {e}");
                }
            }
            #[cfg(not(unix))]
            {
                let _ = pid; // SIGTERM not applicable on non-unix
            }
        } else {
            // No pid — best effort interrupt via tmux send-keys.
            let _ = self.send_interrupt(name);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A minimal driver that overrides only the REQUIRED (non-defaulted)
    /// trait methods, so `send_keys_literal_to_pane`, `send_interrupt_to_pane`,
    /// and `capture_pane` all run the trait's own default bodies — exactly
    /// the "a driver forgot to override this" scenario minor finding 5
    /// (#2514 review) is guarding against.
    struct MinimalDriver;

    impl ManagedTmuxDriver for MinimalDriver {
        fn create_session(&self, _name: &str, _workdir: &str) -> Result<(), ManagedError> {
            Ok(())
        }
        fn kill_session(&self, _name: &str) -> Result<(), ManagedError> {
            Ok(())
        }
        fn send_line(&self, _name: &str, _text: &str) -> Result<(), ManagedError> {
            Ok(())
        }
        fn capture(&self, _name: &str, _lines: usize) -> Result<String, ManagedError> {
            Ok(String::new())
        }
        fn list_sessions(&self) -> Result<Vec<String>, ManagedError> {
            Ok(Vec::new())
        }
    }

    #[test]
    fn send_keys_literal_to_pane_default_fails_closed() {
        let err = MinimalDriver
            .send_keys_literal_to_pane("sess", "%1", "text")
            .expect_err(
                "a driver that does not override this must fail loudly, never \
                 silently fall back to the session-scoped send",
            );
        assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
    }

    #[test]
    fn send_interrupt_to_pane_default_fails_closed() {
        let err = MinimalDriver
            .send_interrupt_to_pane("sess", "%1")
            .expect_err(
                "a driver that does not override this must fail loudly, never \
                 silently fall back to the session-scoped interrupt",
            );
        assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
    }

    #[test]
    fn capture_pane_default_fails_closed() {
        let err = MinimalDriver.capture_pane("sess", "%1", 50).expect_err(
            "a driver that does not override this must fail loudly, never \
                 silently fall back to the session-scoped capture",
        );
        assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
    }
}