trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Workdir resolution + pane-cwd verification for `SessionManager::resume` (#2250).
//!
//! Why: `manager.rs` sits at the 500-SLOC production cap (same constraint that
//! forced `reactivate.rs`/`hook_sync.rs`/`create.rs` out into sibling files),
//! so the two new guards `resume()` needs land here instead of growing that
//! file further. Prior to #2250, `resume()`'s recreate branch picked
//! `workspace_path` as a fallback WITHOUT an existence check (unlike
//! `last_cwd`, which already had one), and a `create_session` success was
//! trusted blindly. `tmux new-session -c <missing-dir>` exits 0 but silently
//! roots the pane at `$HOME` — the project-tier `.claude/` skills/persona/MCP
//! config that only exists under the real workspace is silently lost the
//! instant that happens, because `claude --setting-sources project,local`
//! only reads `<cwd>/.claude`.
//! What: [`resolve_existing_workdir`] applies the #8551 rule — a recorded
//! `workspace_path` decides alone (gone or unprobable refuses the resume), and
//! `cwd` is a candidate only when no workspace is recorded. Otherwise it picks
//! the first existing of `last_cwd`, then `workspace_path` or `cwd`, returning a
//! typed [`ManagedError::WorkspaceMissing`] when none exist (never a silent
//! `$HOME` fallback). [`verify_pane_cwd`] compares the driver-reported pane cwd against
//! the expected workdir right after a fresh `create_session` — waiting a
//! bounded time for tmux's stale first report to settle (#9524) — failing
//! loudly on a mismatch (tmux silently fell back) rather than proceeding to type the
//! resume command into a mis-rooted pane. A driver that cannot report the pane
//! cwd (`get_pane_cwd` returns `None` — the trait default, and every test
//! double unless it opts in) is treated as "cannot verify", not a mismatch.
//! Test: `resolve_existing_workdir_prefers_first_existing`,
//! `resolve_existing_workdir_falls_back_through_candidates`,
//! `resolve_existing_workdir_errors_when_all_missing`,
//! `verify_pane_cwd_ok_on_match`, `verify_pane_cwd_ok_when_unknown`,
//! `verify_pane_cwd_errors_on_mismatch`, `verify_pane_cwd_waits_for_a_stale_cwd_to_settle`,
//! `verify_pane_cwd_errors_once_the_deadline_passes`,
//! `verify_pane_cwd_keeps_the_mismatch_when_a_later_read_fails`, `is_unresumable_*` (this file's
//! `#[cfg(test)]` module); end-to-end coverage of the recreate branch lives in
//! `resume_reattach_tests.rs`.

use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use super::ManagedTmuxDriver;
use super::manager::ManagedError;
use super::record::{ManagedSessionId, ManagedSessionState, SessionRecord};

/// The three resume-workdir candidates for `record`, in priority order.
///
/// Why: [`resolve_existing_workdir`] and [`is_unresumable`] (#2595) must probe
/// the EXACT same candidates in the EXACT same order — a divergence here would
/// mean a session `resolve_existing_workdir` can still resume gets flagged
/// dead (or vice versa). Factoring the candidate list out of both callers
/// makes that impossible.
/// What: `[last_cwd, workspace_path, cwd]`, `None`-filtered by the caller via
/// `.into_iter().flatten()`. `cwd` is `None` whenever a workspace is recorded.
/// Test: exercised transitively by every `resolve_existing_workdir_*` and
/// `is_unresumable_*` test.
fn workdir_candidates(record: &SessionRecord) -> [Option<&Path>; 3] {
    [
        record.last_cwd.as_deref(),
        record.workspace_path.as_deref(),
        // #8551: `cwd` can be the main checkout; a session with a recorded
        // workspace never falls back to it.
        record
            .workspace_path
            .is_none()
            .then_some(record.cwd.as_path()),
    ]
}

/// Probe a session's recorded workspace (#8551).
///
/// Why: a recorded workspace is the session's own tree. When it is gone, or
/// cannot be probed, resuming anywhere else — `cwd` can be the main checkout —
/// runs the session outside its tree.
/// What: `None` when no workspace is recorded or it exists; otherwise the
/// refusal — `WorkspaceMissing` when it is definitively absent, `Io` (naming
/// the path) when the probe fails with anything but NotFound.
/// Test: `resolve_existing_workdir_refuses_when_recorded_workspace_is_gone`,
/// `resolve_existing_workdir_refuses_on_workspace_probe_error`.
async fn recorded_workspace_refusal(
    id: &ManagedSessionId,
    record: &SessionRecord,
) -> Option<ManagedError> {
    let ws = record.workspace_path.as_deref()?;
    match tokio::fs::try_exists(ws).await {
        Ok(true) => None,
        Ok(false) => Some(ManagedError::WorkspaceMissing(
            id.to_string(),
            ws.display().to_string(),
        )),
        Err(e) => Some(ManagedError::Io(std::io::Error::new(
            e.kind(),
            format!(
                "cannot check workspace {} of session {id}: {e}; refusing to resume it in \
                 any other directory — restore access to that path and retry",
                ws.display()
            ),
        ))),
    }
}

/// Pick the first candidate workdir that exists on disk, in priority order.
///
/// Why: see module doc — `resume()` must never hand a stale/removed path to
/// tmux; all three fallback candidates need the same existence guard
/// `last_cwd` already had before #2250 (`workspace_path` and `cwd` did not).
/// Takes `&SessionRecord` (rather than three separate `Option<&Path>`
/// parameters) purely to keep the call site in `manager.rs` — already at its
/// 500-SLOC cap — a single short line.
/// What: a recorded workspace decides alone — gone or unprobable refuses the
/// resume ([`recorded_workspace_refusal`], #8551). Otherwise checks
/// [`workdir_candidates`] in order — `last_cwd`, then `workspace_path`, or
/// `cwd` only when no workspace is recorded — with `tokio::fs::try_exists`
/// (non-blocking) and returns the first that exists. When none do, returns
/// [`ManagedError::WorkspaceMissing`] carrying `id` and the most-informative
/// candidate (`workspace_path` if set, else `cwd`).
/// Test: `resolve_existing_workdir_prefers_first_existing`,
/// `resolve_existing_workdir_falls_back_through_candidates`,
/// `resolve_existing_workdir_errors_when_all_missing`,
/// `resolve_existing_workdir_refuses_when_recorded_workspace_is_gone`,
/// `resolve_existing_workdir_refuses_on_workspace_probe_error`.
pub(super) async fn resolve_existing_workdir(
    id: &ManagedSessionId,
    record: &SessionRecord,
) -> Result<PathBuf, ManagedError> {
    // #8551: a gone or unprobable recorded workspace refuses the resume.
    if let Some(refusal) = recorded_workspace_refusal(id, record).await {
        return Err(refusal);
    }
    for candidate in workdir_candidates(record).into_iter().flatten() {
        if tokio::fs::try_exists(candidate).await.unwrap_or(false) {
            return Ok(candidate.to_path_buf());
        }
    }
    let missing = record.workspace_path.as_deref().unwrap_or(&record.cwd);
    Err(ManagedError::WorkspaceMissing(
        id.to_string(),
        missing.display().to_string(),
    ))
}

/// The shared "unresumable" predicate (#2595): true when a stopped/errored
/// session's resume is guaranteed to fail with
/// [`ManagedError::WorkspaceMissing`] — its recorded workspace is gone, or,
/// with no workspace recorded, neither `last_cwd` nor `cwd` exists (#8551).
///
/// Why (#2595, builds on #2594's `ResumeManagedError::Unresumable` semantics):
/// before this, an operator-facing session picker offered "restart" for a
/// session whose workspace had been GC-pruned — the restart could only ever
/// 422. #2594 fixed the ERROR response; this predicate lets every LISTING
/// surface (the bare-`tm` guided default, `tm ls`, `tm sessions ls` — all of
/// which read `GET /api/v1/sessions/managed`) exclude/flag the session
/// BEFORE the operator ever selects it, instead of only failing loudly after
/// the fact. Gated to `Stopped`/`Errored` (mirrors the CLI's own
/// `guided_resume::needs_restart`) because a live/provisioning session has (or
/// is about to have) a real tmux pane — whether its ORIGINAL workdir still
/// exists is irrelevant to whether it can be resumed (reattached).
/// What: returns `false` immediately for any state other than
/// `Stopped`/`Errored` (no I/O). For `Stopped`/`Errored` with a recorded
/// workspace, returns `true` only when that workspace probes `Ok(false)`;
/// `last_cwd` and `cwd` are not consulted. With no workspace recorded, probes
/// the same candidates [`resolve_existing_workdir`] does (via
/// [`workdir_candidates`]) and returns `true` only when every probe comes back
/// `Ok(false)` (definitively absent).
///
/// **Deliberately diverges from [`resolve_existing_workdir`] on a probe
/// `Err`** (PR #2652 review, MEDIUM finding 3): this predicate is FAIL-OPEN —
/// a transient I/O/permission/network-volume error on any candidate is
/// treated as "possibly present" and short-circuits to `false` (never
/// flagged dead), the same as `Ok(true)`. `resolve_existing_workdir` keeps
/// its existing `Err → treat as absent` behavior (`.unwrap_or(false)`)
/// UNCHANGED — the two callers have opposite failure trade-offs by design:
/// `resolve_existing_workdir` guards an ACTUAL resume attempt, where refusing
/// to hand tmux a possibly-bad path on an unprobable candidate is the SAFE
/// failure mode (#2250's original "never silently fall back" intent), and the
/// #2594 422 the operator sees is retryable. This predicate instead gates
/// whether a session is even OFFERED in a picker — wrongly flagging it dead
/// on a transient probe error leaves the operator with only a destructive
/// delete as the way out, which is the wrong trade-off for a condition that
/// may clear on the next poll. `workdir_candidates` (the candidate LIST) is
/// still shared so the two can never disagree about WHICH paths to check —
/// only how an inconclusive probe on one of them is interpreted.
/// Test: `is_unresumable_true_when_all_candidates_missing_and_stopped`,
/// `is_unresumable_false_when_any_candidate_exists`,
/// `is_unresumable_true_when_recorded_workspace_is_gone_even_if_cwd_exists`,
/// `is_unresumable_false_for_non_stopped_states_even_when_all_missing`,
/// `is_unresumable_fails_open_on_probe_error`.
pub(crate) async fn is_unresumable(record: &SessionRecord) -> bool {
    if !matches!(
        record.state,
        ManagedSessionState::Stopped | ManagedSessionState::Errored
    ) {
        return false;
    }
    // #8551: mirror `resolve_existing_workdir` — the recorded workspace
    // decides alone; a probe error still fails open.
    if let Some(ws) = record.workspace_path.as_deref() {
        return matches!(tokio::fs::try_exists(ws).await, Ok(false));
    }
    for candidate in workdir_candidates(record).into_iter().flatten() {
        match tokio::fs::try_exists(candidate).await {
            // Definitively present, or the probe itself couldn't tell
            // (permission denied, transient I/O, an unmounted network
            // volume, …) — either way, do NOT flag this session dead.
            Ok(true) | Err(_) => return false,
            Ok(false) => continue,
        }
    }
    true
}

/// How long a fresh pane's reported cwd may lag `new-session -c` (#9524).
///
/// tmux 3.6a reports the server's own cwd for about 12 ms after the session
/// is created; this bound leaves a wide margin over that on a loaded host.
const PANE_CWD_DEADLINE: Duration = Duration::from_millis(300);

/// Pause between two pane-cwd reads while waiting out [`PANE_CWD_DEADLINE`].
const PANE_CWD_POLL: Duration = Duration::from_millis(10);

/// Verify a freshly created tmux pane actually landed at `expected`.
///
/// Why: `tmux new-session -c <missing-dir>` exits 0 but silently roots the
/// pane at `$HOME` — exit status alone can never detect this (#2250); this is
/// the only point where the ACTUAL pane cwd can be cross-checked before the
/// resume command is typed into it. #9524: tmux 3.6a reports a stale cwd for
/// ~12 ms after the create, so one read refused a good pane.
/// What: [`verify_pane_cwd_within`] with [`PANE_CWD_DEADLINE`]. A blocking
/// wait — at most the deadline, and only on a mismatch — like every other
/// tmux call on this driver, which spawns a process synchronously.
/// Test: `verify_pane_cwd_ok_on_match`, `verify_pane_cwd_ok_when_unknown`,
/// `verify_pane_cwd_errors_on_mismatch`,
/// `verify_pane_cwd_waits_for_a_stale_cwd_to_settle`,
/// `verify_pane_cwd_errors_once_the_deadline_passes`,
/// `verify_pane_cwd_keeps_the_mismatch_when_a_later_read_fails`.
pub(super) fn verify_pane_cwd(
    driver: &dyn ManagedTmuxDriver,
    name: &str,
    expected: &Path,
) -> Result<(), ManagedError> {
    verify_pane_cwd_within(driver, name, expected, PANE_CWD_DEADLINE)
}

/// [`verify_pane_cwd`] with the wait bound passed in.
///
/// What: the first `driver.get_pane_cwd(name)` read decides "cannot verify":
/// `None` (the trait default, and every test double unless it opts in) is
/// `Ok`, so drivers that never implement the probe don't spuriously break.
/// Otherwise the pane cwd is re-read every [`PANE_CWD_POLL`] until it equals
/// `expected` or `deadline` passes. Both sides are canonicalized when possible
/// (the raw path otherwise) so a symlinked tmp dir does not mismatch. Fails
/// closed: a read that fails mid-wait keeps the last mismatch, and a mismatch
/// still standing at the deadline is [`ManagedError::TmuxUnavailable`] with an
/// actionable message — the timeout never becomes success.
/// Test: see [`verify_pane_cwd`].
fn verify_pane_cwd_within(
    driver: &dyn ManagedTmuxDriver,
    name: &str,
    expected: &Path,
    deadline: Duration,
) -> Result<(), ManagedError> {
    let Some(mut actual) = driver.get_pane_cwd(name) else {
        return Ok(());
    };
    let canonical = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
    let expected_c = canonical(expected);
    // #9524: wait out tmux's stale pane_current_path, bounded by `deadline`.
    let give_up = Instant::now() + deadline;
    while canonical(&actual) != expected_c {
        if Instant::now() >= give_up {
            return Err(ManagedError::TmuxUnavailable(format!(
                "tmux session '{name}' pane landed at '{}' instead of the requested workspace \
                 '{}' — tmux silently fell back (likely $HOME) because the target directory was \
                 unusable; refusing to type the resume command into a mis-rooted pane",
                actual.display(),
                expected.display()
            )));
        }
        std::thread::sleep(PANE_CWD_POLL);
        // #9524: a failed re-read is not "cannot verify"; the mismatch stands.
        if let Some(next) = driver.get_pane_cwd(name) {
            actual = next;
        }
    }
    Ok(())
}

/// Create a fresh tmux session at `workdir`, then verify it actually landed
/// there (#2250).
///
/// Why: `manager.rs::resume`'s recreate branch needs both steps back-to-back
/// every time it creates a session — folding them into one call keeps that
/// call site a single line instead of growing `manager.rs` (already at its
/// 500-SLOC cap) by the width of both.
/// What: `driver.create_session_exclusive(name, workdir)`, then
/// [`verify_pane_cwd`] against the same `workdir`. #9101: exclusive, because
/// `create_session` renders `new-session -A`, which attaches to a session
/// that already holds the name; a taken name is
/// [`ManagedError::NameCollision`] and no pane is adopted.
/// Test: covered end-to-end via `SessionManager::resume` in
/// `resume_reattach_tests.rs` (`manager_resume_respawns_in_existing_workspace`,
/// `manager_resume_errors_when_recreated_pane_cwd_mismatches`);
/// `the_resume_create_never_attaches_to_a_session_holding_the_name`.
pub(super) fn create_and_verify_pane(
    driver: &dyn ManagedTmuxDriver,
    name: &str,
    workdir: &str,
) -> Result<(), ManagedError> {
    driver.create_session_exclusive(name, workdir)?;
    verify_pane_cwd(driver, name, Path::new(workdir))
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::Mutex;

    use chrono::Utc;
    use tempfile::TempDir;

    use super::super::record::ManagedSessionState;
    use super::*;

    /// Minimal `SessionRecord` builder for `resolve_existing_workdir` tests —
    /// only `cwd`/`workspace_path`/`last_cwd` vary between cases.
    fn make_record(
        cwd: PathBuf,
        workspace_path: Option<PathBuf>,
        last_cwd: Option<PathBuf>,
    ) -> SessionRecord {
        SessionRecord {
            id: ManagedSessionId::new(),
            tmux_name: "tmpm-resume-workdir-test".into(),
            cwd,
            task: "test".into(),
            state: ManagedSessionState::Stopped,
            created_at: Utc::now(),
            last_activity_at: None,
            workspace_path,
            repo_url: None,
            branch: None,
            pending_decision: None,
            proposed_default: None,
            correlation: Default::default(),
            runtime: Default::default(),
            ephemeral: false,
            workspace_owned: false,
            source_id: None,
            claude_session_id: None,
            scrollback_path: None,
            last_cwd,
            deliverable_id: None,
            pane_id: None,
            tmux_server: None,
            injection_status: Default::default(),
            worktree_owner: None,
            terminal_at: None,
            stop_cause: None,
            kind: Default::default(),
        }
    }

    #[tokio::test]
    async fn resolve_existing_workdir_prefers_first_existing() {
        let last = TempDir::new().unwrap();
        let workspace = TempDir::new().unwrap();
        let id = ManagedSessionId::new();
        let record = make_record(
            last.path().to_owned(),
            Some(workspace.path().to_owned()),
            Some(last.path().to_owned()),
        );
        let resolved = resolve_existing_workdir(&id, &record)
            .await
            .expect("last_cwd exists, must be chosen first");
        assert_eq!(resolved, last.path());
    }

    #[tokio::test]
    async fn resolve_existing_workdir_falls_back_through_candidates() {
        let workspace = TempDir::new().unwrap();
        let cwd = TempDir::new().unwrap();
        let id = ManagedSessionId::new();
        let missing_last = PathBuf::from("/nonexistent/last-cwd-2250");

        // last_cwd missing -> falls back to workspace_path.
        let record = make_record(
            cwd.path().to_owned(),
            Some(workspace.path().to_owned()),
            Some(missing_last.clone()),
        );
        let resolved = resolve_existing_workdir(&id, &record)
            .await
            .expect("workspace_path exists, must be chosen over missing last_cwd");
        assert_eq!(resolved, workspace.path());

        // #8551: no workspace recorded (a session launched in place, e.g. the
        // main checkout by design) and last_cwd missing -> cwd, unchanged.
        let record = make_record(cwd.path().to_owned(), None, Some(missing_last));
        let resolved = resolve_existing_workdir(&id, &record)
            .await
            .expect("no workspace recorded, cwd exists: must resume in cwd");
        assert_eq!(resolved, cwd.path());
    }

    /// #8551: a recorded workspace that is gone must refuse the resume and
    /// name that path — never fall back to `cwd` (it can be the main
    /// checkout) or to a surviving `last_cwd`.
    #[tokio::test]
    async fn resolve_existing_workdir_refuses_when_recorded_workspace_is_gone() {
        let main_checkout = TempDir::new().unwrap();
        let id = ManagedSessionId::new();
        let gone = PathBuf::from("/nonexistent/worktrees/tm-demo-01");
        for last_cwd in [None, Some(main_checkout.path().to_owned())] {
            let record = make_record(
                main_checkout.path().to_owned(),
                Some(gone.clone()),
                last_cwd.clone(),
            );
            match resolve_existing_workdir(&id, &record).await {
                Err(ManagedError::WorkspaceMissing(err_id, path)) => {
                    assert_eq!(err_id, id.to_string());
                    assert_eq!(path, gone.display().to_string());
                }
                other => panic!(
                    "last_cwd {last_cwd:?}: a gone worktree must be refused with \
                     WorkspaceMissing, got {other:?}"
                ),
            }
        }
    }

    /// #8551 Fail-Open Check: a workspace probe that errors with something
    /// other than NotFound (ENOTDIR here) is neither "present" nor a licence
    /// to fall back to `cwd` — the resume is refused and the path named.
    #[tokio::test]
    async fn resolve_existing_workdir_refuses_on_workspace_probe_error() {
        let dir = TempDir::new().unwrap();
        let not_a_dir = dir.path().join("tm-demo-01-file");
        std::fs::write(&not_a_dir, b"x").expect("write stand-in file");
        let unprobable = not_a_dir.join("worktree");
        let main_checkout = TempDir::new().unwrap();
        let id = ManagedSessionId::new();
        let record = make_record(
            main_checkout.path().to_owned(),
            Some(unprobable.clone()),
            None,
        );

        match resolve_existing_workdir(&id, &record).await {
            Err(ManagedError::Io(e)) => {
                let msg = e.to_string();
                assert!(msg.contains(&unprobable.display().to_string()), "{msg}");
            }
            other => panic!("a workspace probe error must refuse the resume, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn resolve_existing_workdir_errors_when_all_missing() {
        let id = ManagedSessionId::new();
        let missing_workspace = PathBuf::from("/nonexistent/workspace-2250");
        let record = make_record(
            PathBuf::from("/nonexistent/cwd-2250"),
            Some(missing_workspace.clone()),
            Some(PathBuf::from("/nonexistent/last-cwd-2250")),
        );

        let err = resolve_existing_workdir(&id, &record).await.expect_err(
            "no candidate exists on disk — must error, not silently fall back to $HOME",
        );

        match err {
            ManagedError::WorkspaceMissing(err_id, path) => {
                assert_eq!(err_id, id.to_string());
                assert_eq!(path, missing_workspace.display().to_string());
            }
            other => panic!("expected WorkspaceMissing, got {other:?}"),
        }
    }

    // ── is_unresumable (#2595) ───────────────────────────────────────────

    #[tokio::test]
    async fn is_unresumable_true_when_all_candidates_missing_and_stopped() {
        let mut record = make_record(
            PathBuf::from("/nonexistent/cwd-2595"),
            Some(PathBuf::from("/nonexistent/workspace-2595")),
            Some(PathBuf::from("/nonexistent/last-cwd-2595")),
        );
        record.state = ManagedSessionState::Stopped;
        assert!(
            is_unresumable(&record).await,
            "stopped session with no existing candidate must be unresumable"
        );

        // Errored is the sibling resumable-from state and must behave identically.
        record.state = ManagedSessionState::Errored;
        assert!(
            is_unresumable(&record).await,
            "errored session with no existing candidate must be unresumable"
        );
    }

    #[tokio::test]
    async fn is_unresumable_false_when_any_candidate_exists() {
        let cwd = TempDir::new().unwrap();
        // No workspace recorded; only `cwd` exists on disk — resumable,
        // mirroring `resolve_existing_workdir`'s fallback-to-cwd behavior.
        let mut record = make_record(
            cwd.path().to_owned(),
            None,
            Some(PathBuf::from("/nonexistent/last-cwd-2595")),
        );
        record.state = ManagedSessionState::Stopped;
        assert!(
            !is_unresumable(&record).await,
            "a session with ANY existing candidate must not be flagged unresumable"
        );
    }

    /// #8551: a recorded workspace that is gone decides alone — the surviving
    /// cwd no longer makes the session resumable.
    #[tokio::test]
    async fn is_unresumable_true_when_recorded_workspace_is_gone_even_if_cwd_exists() {
        let cwd = TempDir::new().unwrap();
        let mut record = make_record(
            cwd.path().to_owned(),
            Some(PathBuf::from("/nonexistent/worktrees/tm-demo-01")),
            None,
        );
        record.state = ManagedSessionState::Stopped;
        assert!(
            is_unresumable(&record).await,
            "a gone recorded workspace must be unresumable even when cwd exists"
        );
    }

    #[tokio::test]
    async fn is_unresumable_false_for_non_stopped_states_even_when_all_missing() {
        // Why: a live/provisioning session already has (or is about to have) a
        // real tmux pane; whether its original workdir still exists on disk is
        // irrelevant to whether it can be resumed (reattached). The predicate
        // must short-circuit to `false` WITHOUT probing the filesystem.
        let mut record = make_record(
            PathBuf::from("/nonexistent/cwd-2595"),
            Some(PathBuf::from("/nonexistent/workspace-2595")),
            Some(PathBuf::from("/nonexistent/last-cwd-2595")),
        );
        for state in [
            ManagedSessionState::Active,
            ManagedSessionState::Provisioning,
        ] {
            record.state = state;
            assert!(
                !is_unresumable(&record).await,
                "state {:?} must never be flagged unresumable regardless of workdir",
                record.state
            );
        }
    }

    /// #2595 (PR #2652 review, MEDIUM finding 3): a probe `Err` on a
    /// candidate — NOT "not found", a genuine I/O failure — must fail OPEN
    /// (never flag the session dead), the opposite of `resolve_existing_workdir`'s
    /// `Err → treat as absent` behavior (see [`is_unresumable`]'s doc for why
    /// the two callers deliberately diverge here).
    #[tokio::test]
    async fn is_unresumable_fails_open_on_probe_error() {
        // A regular FILE used as a directory component makes any stat of a
        // path beneath it fail with ENOTDIR — a genuine I/O error, not
        // "not found" — which is a reliable, cross-platform way to force
        // `tokio::fs::try_exists` into its `Err` branch rather than `Ok(false)`.
        let dir = TempDir::new().unwrap();
        let not_a_dir = dir.path().join("this-is-a-file-not-a-dir");
        std::fs::write(&not_a_dir, b"x").expect("write stand-in file");
        let unprobable = not_a_dir.join("child-cannot-be-stat-ed");

        // Placed as `last_cwd` — the FIRST candidate checked — so the
        // fail-open short-circuit fires before `cwd` (definitely missing) is
        // ever reached.
        let mut record = make_record(
            PathBuf::from("/nonexistent/cwd-2595-failopen"),
            None,
            Some(unprobable.clone()),
        );
        record.state = ManagedSessionState::Stopped;

        assert!(
            !is_unresumable(&record).await,
            "a probe error on any candidate must fail OPEN (never flag dead) — a \
             transient I/O/permission/network-volume error is not proof the \
             workspace is gone, and the picker's only override would otherwise \
             be a destructive delete"
        );

        // #8551: the same holds when the unprobable path is the recorded
        // workspace, which now decides alone.
        record.workspace_path = Some(unprobable);
        record.last_cwd = None;
        assert!(
            !is_unresumable(&record).await,
            "a probe error on the recorded workspace must fail OPEN too"
        );
    }

    /// Minimal `ManagedTmuxDriver` test double whose `get_pane_cwd` is
    /// controllable, so `verify_pane_cwd` can be exercised without pulling in
    /// the full `FakeTmuxDriver` from `tests.rs`.
    ///
    /// #9524: answers `reads` in order and repeats the last one, so a test can
    /// script a pane cwd that changes between reads. `served` counts reads.
    struct StubDriver {
        reads: Mutex<Vec<Option<PathBuf>>>,
        served: Mutex<usize>,
    }

    impl StubDriver {
        fn answering(reads: Vec<Option<PathBuf>>) -> Self {
            Self {
                reads: Mutex::new(reads),
                served: Mutex::new(0),
            }
        }

        fn served(&self) -> usize {
            *self.served.lock().unwrap()
        }
    }

    impl ManagedTmuxDriver for StubDriver {
        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())
        }
        fn get_pane_cwd(&self, _name: &str) -> Option<PathBuf> {
            *self.served.lock().unwrap() += 1;
            let mut reads = self.reads.lock().unwrap();
            if reads.len() > 1 {
                reads.remove(0)
            } else {
                reads.first().cloned().flatten()
            }
        }
    }

    #[test]
    fn verify_pane_cwd_ok_on_match() {
        let dir = TempDir::new().unwrap();
        let driver = StubDriver::answering(vec![Some(dir.path().to_path_buf())]);
        assert!(verify_pane_cwd(&driver, "s", dir.path()).is_ok());
    }

    #[test]
    fn verify_pane_cwd_ok_when_unknown() {
        // Driver reports no pane cwd (the trait default) — "cannot verify" is
        // NOT the same as a mismatch, so this must succeed.
        let dir = TempDir::new().unwrap();
        let driver = StubDriver::answering(vec![None]);
        assert!(verify_pane_cwd(&driver, "s", dir.path()).is_ok());
    }

    #[test]
    fn verify_pane_cwd_errors_on_mismatch() {
        let expected = TempDir::new().unwrap();
        let actual = TempDir::new().unwrap();
        let driver = StubDriver::answering(vec![Some(actual.path().to_path_buf())]);
        let err = verify_pane_cwd(&driver, "s", expected.path())
            .expect_err("pane cwd disagrees with the requested workdir — must fail loudly");
        assert!(matches!(err, ManagedError::TmuxUnavailable(_)));
    }

    /// #9524: tmux 3.6a reports the server's cwd for ~12 ms after the create.
    /// A pane whose cwd is correct only from the third read is accepted.
    #[test]
    fn verify_pane_cwd_waits_for_a_stale_cwd_to_settle() {
        let expected = TempDir::new().unwrap();
        let stale = TempDir::new().unwrap();
        let driver = StubDriver::answering(vec![
            Some(stale.path().to_path_buf()),
            Some(stale.path().to_path_buf()),
            Some(expected.path().to_path_buf()),
        ]);
        verify_pane_cwd(&driver, "s", expected.path())
            .expect("the pane settled at the requested workdir inside the deadline");
        assert_eq!(driver.served(), 3);
    }

    /// Fail-Open Check, #9524: a mismatch that outlasts the deadline still
    /// errors, after the deadline and not before, having re-read the pane.
    #[test]
    fn verify_pane_cwd_errors_once_the_deadline_passes() {
        let expected = TempDir::new().unwrap();
        let actual = TempDir::new().unwrap();
        let driver = StubDriver::answering(vec![Some(actual.path().to_path_buf())]);
        let started = std::time::Instant::now();
        let err = verify_pane_cwd(&driver, "s", expected.path())
            .expect_err("a persistent mismatch must never time out into success");
        assert!(matches!(err, ManagedError::TmuxUnavailable(_)), "{err:?}");
        assert!(started.elapsed() >= PANE_CWD_DEADLINE);
        assert!(driver.served() > 1, "the pane cwd was read only once");
    }

    /// Fail-Open Check, #9524: once a mismatch is seen, a read that fails is
    /// not "cannot verify" — the mismatch stands and errors at the deadline.
    #[test]
    fn verify_pane_cwd_keeps_the_mismatch_when_a_later_read_fails() {
        let expected = TempDir::new().unwrap();
        let actual = TempDir::new().unwrap();
        let driver = StubDriver::answering(vec![Some(actual.path().to_path_buf()), None]);
        let err = verify_pane_cwd_within(&driver, "s", expected.path(), Duration::from_millis(30))
            .expect_err("a failed re-read after a mismatch must not pass");
        assert!(matches!(err, ManagedError::TmuxUnavailable(_)), "{err:?}");
    }
}