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
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! Daemon-side implementation of the nine session-lifecycle MCP tools
//! (#1221 + the two fleet-wide #1508 teardown verbs + #2012's `session_delete`).
//!
//! Why: the MCP `StateBackend` (in `mcp_backend.rs`) must service the new
//! session-lifecycle tools, but inlining their bodies there would push that file
//! over the 500-SLOC production cap. More importantly, these tools must be THIN
//! WRAPPERS over the existing [`crate::session_manager::SessionManager`]
//! lifecycle ops that the HTTP `…/managed/*` routes already use — not a parallel
//! reimplementation — so MCP and HTTP behave identically. This module holds the
//! wrapping logic; `session_new` delegates to the shared
//! [`crate::daemon::managed_routes::spawn_managed`] used by the HTTP handler too.
//! What: nine free async functions — the seven per-session ops (`session_new`,
//! `session_stop`, `session_resume`, `session_decommission`, `session_delete`,
//! `session_activity`, `session_send`) plus the two fleet-wide #1508 verbs
//! (`session_decommission_ephemeral`, `session_prune`) — each taking
//! `&Arc<DaemonState>` plus parsed arguments and returning the same JSON shapes
//! the HTTP routes return, or a human-readable error string.
//! Test: `cargo test -p trusty-mpm daemon::mcp_session` plus the dispatch-level
//! tests in `crate::mcp`.

use std::sync::Arc;

use serde_json::{Value, json};

use crate::daemon::managed_routes::{SpawnParams, record_to_json, spawn_managed};
use crate::daemon::state::DaemonState;
use crate::session_manager::{ManagedError, ManagedSessionId, PruneFilter};

/// Parse a managed-session id string into a [`ManagedSessionId`].
///
/// Why: every single-id tool must reject a non-UUID with a clear message rather
/// than a confusing downstream "not found".
/// What: parses `raw` as a UUID, mapping failure to a descriptive error string.
/// Test: `parse_managed_id_rejects_garbage` in the `tests` module.
fn parse_managed_id(raw: &str) -> Result<ManagedSessionId, String> {
    raw.parse::<uuid::Uuid>()
        .map(ManagedSessionId::from)
        .map_err(|_| format!("`{raw}` is not a valid managed session id (expected a UUID)"))
}

/// Map a [`ManagedError`] to a human-readable tool error string.
///
/// Why: the MCP tool result carries a flat string; mapping here keeps every
/// wrapper's error path uniform and avoids leaking `Debug` formatting.
/// What: renders the error via its `Display` impl (which already carries
/// actionable context for each variant).
/// Test: exercised by the not-found paths in the `tests` module.
fn managed_err(e: ManagedError) -> String {
    e.to_string()
}

/// Spawn a new managed session (`session_new` tool).
///
/// Why: gives the driver a typed spawn path; delegates to the shared
/// [`spawn_managed`] helper so the MCP and HTTP spawn flows are identical.
/// What: validates the optional `runtime` selector, provisions the workspace,
/// creates the tmux host, launches the harness, and returns the new record as
/// JSON (id, tmux name, workspace path, state, attach command, runtime). The
/// optional `ephemeral` flag (#1508) tags a test/throwaway session for the
/// bulk-teardown + auto-reap paths.
/// Test: `session_new_invalid_runtime_errors` (unit, no tmux needed).
pub async fn session_new(
    state: &Arc<DaemonState>,
    repo_url: &str,
    git_ref: &str,
    task: &str,
    name_hint: Option<&str>,
    runtime: Option<&str>,
    ephemeral: Option<bool>,
) -> Result<Value, String> {
    let params = SpawnParams {
        repo_url: repo_url.to_string(),
        git_ref: git_ref.to_string(),
        task: task.to_string(),
        name_hint: name_hint.map(str::to_string),
        runtime: runtime.map(str::to_string),
        ephemeral,
        // This IS the MCP tool surface (#1836/#1837): every call here is
        // subject to the off-by-default gate + registry allowlist.
        mcp_initiated: true,
        // Turnkey by default (#1903/#1299): an MCP `session_new` spawns to work.
        inject_task: None,
        // The MCP `session_new` tool does not expose Deliverable linkage
        // (#2379's CLI surface is `tm sessions new --deliverable`, HTTP-only).
        deliverable_id: None,
        // Keep the #1707 reconnect (#2450): an MCP `session_new` re-issued for a
        // project that already has a live session should ADOPT it, not spawn a
        // duplicate — idempotent reconnect is the safe default for automated
        // callers (prevents LLM-driven session proliferation).
        force_new: false,
        // #5274: the MCP tool surface does not expose the worktree request, the
        // same boundary `deliverable_id` above draws — an explicit request for
        // isolation is a person's decision, and this is the surface an LLM
        // caller drives. An MCP-spawned session runs in the main checkout;
        // `tm launch --worktree` is how a human asks for the other placement.
        worktree: false,
    };
    let record = spawn_managed(
        state,
        crate::session_manager::ManagedSessionId::new(),
        params,
    )
    .await?;
    Ok(record_to_json(&record))
}

/// Stop a session's runtime, keeping its workspace (`session_stop` tool).
///
/// Why: thin wrapper over [`crate::session_manager::SessionManager::stop`].
/// What: parses the id, calls `stop_reporting`, returns the updated record as
/// JSON plus `runtime_left_running` — the reason a live tmux session with the
/// record's name was left running, or `null` (#8935; additive, as the HTTP
/// route).
/// Test: `unknown_id_errors_for_all_single_id_tools`,
/// `session_stop_says_an_unproven_runtime_was_left_running`.
pub async fn session_stop(state: &Arc<DaemonState>, session_id: &str) -> Result<Value, String> {
    let id = parse_managed_id(session_id)?;
    let mgr = state.session_manager().await;
    let report = mgr
        .stop_reporting(&id, crate::session_manager::StopCause::Deliberate)
        .await
        .map_err(managed_err)?;
    let mut json = record_to_json(&report.record);
    // #8935: a record-only stop must not read as a stopped runtime.
    if let Some(obj) = json.as_object_mut() {
        obj.insert(
            "runtime_left_running".into(),
            report.runtime.left_running().into(),
        );
    }
    Ok(json)
}

/// Resume a stopped session in its existing workspace (`session_resume` tool).
///
/// Why: thin wrapper that mirrors the HTTP resume handler — it both resumes the
/// record AND re-spawns the runtime so the session is actually live again.
/// What: parses the id, delegates to
/// [`crate::daemon::managed_routes::resume_managed`], and renders its typed
/// [`crate::daemon::managed_routes::ResumeManagedError`] to a flat string via
/// `Display` for the MCP tool result (the not-found variant's string still
/// contains the literal "not found" the dispatch tests assert on). On success
/// returns the record as JSON.
/// Test: `session_resume_unknown_id_errors` in the `tests` module.
pub async fn session_resume(state: &Arc<DaemonState>, session_id: &str) -> Result<Value, String> {
    let id = parse_managed_id(session_id)?;
    let record = crate::daemon::managed_routes::resume_managed(state, &id)
        .await
        .map_err(|e| e.to_string())?;
    Ok(record_to_json(&record))
}

/// Permanently tear down a session (`session_decommission` tool).
///
/// Why: thin wrapper over
/// [`crate::session_manager::SessionManager::decommission`].
/// What: parses the id, calls `decommission_reporting` (the same teardown
/// as `decommission`, without `--force`), returns the tombstone record plus
/// `workspace_removed` (bool), `workspace_kept_reason` and
/// `workspace_kept_by_design` (string or null each, as the HTTP route) — a
/// workspace kept for the work it holds is reported, not hidden (#8663).
///
/// `caller` (#3649, Option B): the trait-level MCP `Backend::session_decommission`
/// method currently carries no per-connection caller identity — the wire
/// protocol has no notion of "which managed session is the JSON-RPC client".
/// Until that identity is threaded through (tracked as a follow-up against
/// #3649; a candidate source is the `TM_MANAGED_SESSION_ID` a pane-scoped
/// session already carries), this always passes `None`, which preserves
/// full pre-#3649 authority — i.e. an MCP-driven decommission behaves
/// exactly as it did before this issue, never gated by the new owner check.
/// Test: `session_decommission_unknown_id_errors`,
/// `session_decommission_prunes_stale_worktree_bookkeeping`,
/// `session_decommission_reports_a_workspace_kept_by_design` in the `tests`
/// module.
pub async fn session_decommission(
    state: &Arc<DaemonState>,
    session_id: &str,
) -> Result<Value, String> {
    let id = parse_managed_id(session_id)?;
    let mgr = state.session_manager().await;
    // TODO(#3649): populate `caller` from the calling session's identity once
    // the MCP transport threads it through; `None` preserves current authority.
    let report = mgr
        .decommission_reporting(
            &id,
            None,
            crate::session_manager::decommission_force::ProvisioningDirt::Refuse,
        )
        .await
        .map_err(managed_err)?;
    let mut value = record_to_json(&report.record);
    if let Some(obj) = value.as_object_mut() {
        obj.insert(
            "workspace_removed".to_string(),
            Value::Bool(report.workspace_removed),
        );
        obj.insert(
            "workspace_kept_reason".to_string(),
            report
                .workspace_kept_reason
                .map_or(Value::Null, Value::String),
        );
        // #8663 critic round 2: the same verdict fields the HTTP route returns.
        obj.insert(
            "workspace_kept_by_design".to_string(),
            report
                .workspace_kept_by_design
                .map_or(Value::Null, Value::String),
        );
    }
    Ok(value)
}

/// Hard-delete a session's RECORD from the store (`session_delete` tool, #2012).
///
/// Why: thin wrapper over
/// [`crate::session_manager::SessionManager::delete_record`] — distinct from
/// `session_decommission` (stops the runtime and may remove the workspace, but
/// always leaves a `Decommissioned` tombstone). This permanently drops the
/// record itself for an operator who wants a mis-provisioned or stale record
/// gone outright. Fail-closed: refuses a RUNNING (`Active`/`Provisioning`)
/// session unless `force` is `true`.
/// What: parses the id, calls `delete_record(&id, force)`, and returns the
/// pre-deletion record as JSON with `deleted: true` appended. NEVER touches the
/// workspace directory on disk (store-only operation).
/// Test: `session_delete_unknown_id_errors`, `session_delete_refuses_running`,
/// `session_delete_force_bypasses_guard` in the `tests` module.
pub async fn session_delete(
    state: &Arc<DaemonState>,
    session_id: &str,
    force: bool,
) -> Result<Value, String> {
    let id = parse_managed_id(session_id)?;
    let mgr = state.session_manager().await;
    let record = mgr.delete_record(&id, force).await.map_err(managed_err)?;
    let mut value = record_to_json(&record);
    if let Some(obj) = value.as_object_mut() {
        obj.insert("deleted".to_string(), Value::Bool(true));
    }
    Ok(value)
}

/// Inspect a session's recent activity (`session_activity` tool).
///
/// Why: the driver needs raw pane content (always) plus lifecycle fields so it
/// can reason about session state without an LLM key — matching the HTTP
/// `…/activity` route's no-key contract.
/// What: parses the id, captures the last `lines` pane lines, reports
/// `runtime_active` and the pending-decision fields. The LLM classification
/// overlay is intentionally NOT invoked here (it requires the activity monitor
/// and a key); the raw pane is sufficient for the driver's own inference. A
/// missing tmux pane degrades to an empty `raw_pane`, never an error.
/// Test: `session_activity_unknown_id_errors` in the `tests` module.
pub async fn session_activity(
    state: &Arc<DaemonState>,
    session_id: &str,
    lines: u32,
) -> Result<Value, String> {
    let id = parse_managed_id(session_id)?;
    let mgr = state.session_manager().await;
    let record = mgr.get(&id).await.map_err(managed_err)?;
    // `lines` arrives as u32 from the MCP `session_activity` contract; the
    // `capture_pane` param is `usize` (aligned with the observe path). u32→usize
    // never narrows on supported platforms; saturate defensively just in case.
    let raw_pane = mgr
        .capture_pane(&id, usize::try_from(lines).unwrap_or(usize::MAX))
        .await
        .unwrap_or_default();
    let runtime_active = mgr.tmux_driver().session_exists(&record.tmux_name);
    Ok(json!({
        "id": record.id.to_string(),
        "name": record.tmux_name,
        "state": record.state.to_string(),
        "raw_pane": raw_pane,
        "lines": lines,
        "runtime_active": runtime_active,
        "pending_decision": record.pending_decision,
        "proposed_default": record.proposed_default,
    }))
}

/// Send a line of text into a session's pane (`session_send` tool).
///
/// Why: thin wrapper over
/// [`crate::session_manager::SessionManager::send_input_observed`]. #5699: the
/// pre-fix wrapper called `send_input` and hardcoded `"sent": true`, which
/// meant only "the two tmux subprocesses exited 0" — a long single-line
/// message the harness collapsed into a bracketed paste and never submitted
/// reported success just the same, and the PM on the other end proceeded
/// believing it had been delivered. The boolean could not fail.
/// What: parses the id, resolves the tmux name (for the confirmation), injects
/// `text`, and returns `{ id, sent, submit_state, tmux_name }`. `submit_state`
/// is the three-valued verdict a post-send pane read established
/// ([`crate::session_manager::SubmitState`]); `sent` is `false` for the one
/// state that positively proves non-delivery and keeps its pre-#5699 `true`
/// when the pane could not be read — an unobservable pane is not evidence of
/// failure.
/// Test: `session_send_unknown_id_errors`,
/// `session_send_reports_an_unsubmitted_paste` in the `tests` module.
pub async fn session_send(
    state: &Arc<DaemonState>,
    session_id: &str,
    text: &str,
) -> Result<Value, String> {
    let id = parse_managed_id(session_id)?;
    let mgr = state.session_manager().await;
    let record = mgr.get(&id).await.map_err(managed_err)?;
    let submit = mgr
        .send_input_observed(&id, text)
        .await
        .map_err(managed_err)?;
    Ok(json!({
        "id": record.id.to_string(),
        "sent": submit.delivered(),
        "submit_state": submit.as_str(),
        "tmux_name": record.tmux_name,
    }))
}

/// Bulk-tear-down every ephemeral session (`session_decommission_ephemeral` tool, #1508).
///
/// Why: gives the driver a typed "clean up all my throwaway test sessions" path
/// over MCP, delegating to the SAME
/// [`SessionManager::decommission_all_ephemeral`](crate::session_manager::SessionManager::decommission_all_ephemeral)
/// engine the HTTP route and CLI use, so behaviour is identical across transports.
/// REAL sessions default `ephemeral=false` and are unreachable — durable work is safe.
/// What: decommissions every ephemeral session and returns `{ decommissioned: <count> }`.
/// Test: `dispatch_session_decommission_ephemeral_tool` (mock) in `crate::mcp`.
pub async fn session_decommission_ephemeral(state: &Arc<DaemonState>) -> Result<Value, String> {
    let mgr = state.session_manager().await;
    let count = mgr
        .decommission_all_ephemeral()
        .await
        .map_err(managed_err)?;
    Ok(json!({ "decommissioned": count }))
}

/// By-state prune + tombstone compaction (`session_prune` tool, #1508).
///
/// Why: the fleet-wide teardown tool exposed over MCP so the legacy stale records
/// can be purged with the SAME
/// [`SessionManager::prune_managed`](crate::session_manager::SessionManager::prune_managed)
/// engine the HTTP route and CLI use.
/// What: parses `state` (an unknown spelling is a `400`-style error string), then
/// prunes with `dry_run`/`include_active` and returns the serialized
/// [`crate::session_manager::PruneOutcome`]. A RUNNING session is NEVER torn down
/// unless `include_active`; with `dry_run` nothing is mutated.
/// Test: `dispatch_session_prune_tool`, `dispatch_session_prune_rejects_bad_state`
/// (mock) in `crate::mcp`.
///
/// `caller` (#3649, Option B): same wire-layer gap as
/// [`session_decommission`] — the MCP transport carries no per-connection
/// caller identity today, so this always passes `None` to `prune_managed`,
/// preserving full pre-#3649 authority for the fleet-wide prune tool.
pub async fn session_prune(
    state: &Arc<DaemonState>,
    filter: &str,
    dry_run: bool,
    include_active: bool,
) -> Result<Value, String> {
    let filter = PruneFilter::parse(filter)?;
    let mgr = state.session_manager().await;
    // TODO(#3649): populate `caller` once the MCP transport threads it through.
    // #6118: `invoker` stays `None` here — an MCP call occupies no pane, so
    // there is no invoking session to exclude.
    let outcome = mgr
        .prune_managed(filter, dry_run, include_active, None, None)
        .await
        .map_err(managed_err)?;
    serde_json::to_value(&outcome).map_err(|e| format!("failed to serialize prune outcome: {e}"))
}

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

    /// An ISOLATED daemon state rooted in a tempdir.
    ///
    /// Why (#5544): this used to be `DaemonState::shared()`, whose
    /// `FrameworkPaths` are rooted at the process's working directory. The
    /// lifecycle tools these tests drive run real `prepare_session` side
    /// effects, so the fixture seeded a workspace-trust record for the crate
    /// directory — into the operator's real `~/.claude.json` before the home
    /// tier was confined to the framework base, and into an untracked
    /// `crates/trusty-mpm/.claude.json` afterwards. A test asserting "unknown id
    /// errors" has no business writing either.
    /// What: returns a state over a fresh tempdir, with the `TempDir` handed
    /// back so the caller keeps it alive for the test's duration.
    /// Test: used by every test in this module.
    async fn state() -> (tempfile::TempDir, Arc<DaemonState>) {
        let tmp = tempfile::tempdir().expect("isolated daemon root");
        let state = DaemonState::with_root_isolated_managed(tmp.path().to_path_buf()).await;
        (tmp, Arc::new(state))
    }

    /// A tmux driver that actually TRACKS created/killed session names (#2022).
    ///
    /// Why: `DaemonState::with_root_isolated_managed`'s `FakeNoopTmuxDriver` is
    /// deliberately stateless — every session always reports "not live" — which
    /// is exactly right for the many tests proving "no real tmux session ever
    /// escapes the test", but wrong for a test that wants to exercise the #2022
    /// fix (the delete guard is now a REAL tmux liveness probe): such a test
    /// needs a driver whose `session_exists` reflects reality. `create_session`
    /// records the name as live; `kill_session` removes it — mirroring exactly
    /// what `create_with_id`/`stop`/`decommission` already call in production.
    /// What: a `Mutex<HashSet<String>>` of live session names, driving
    /// `create_session`/`kill_session`/`list_sessions` (and therefore the
    /// trait's default `session_exists`).
    /// Test: `session_delete_refuses_running_then_force_bypasses`.
    struct LiveTrackingTmux {
        live: std::sync::Mutex<std::collections::HashSet<String>>,
    }

    impl LiveTrackingTmux {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                live: std::sync::Mutex::new(std::collections::HashSet::new()),
            })
        }
    }

    impl crate::session_manager::ManagedTmuxDriver for LiveTrackingTmux {
        fn create_session(&self, name: &str, _workdir: &str) -> Result<(), ManagedError> {
            self.live.lock().unwrap().insert(name.to_owned());
            Ok(())
        }

        fn kill_session(&self, name: &str) -> Result<(), ManagedError> {
            self.live.lock().unwrap().remove(name);
            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(self.live.lock().unwrap().iter().cloned().collect())
        }
    }

    /// Why: a non-UUID id must be rejected before any store lookup.
    /// Test: this test.
    #[test]
    fn parse_managed_id_rejects_garbage() {
        let err = parse_managed_id("not-a-uuid").unwrap_err();
        assert!(err.contains("not a valid managed session id"), "{err}");
    }

    /// Why: an unknown (well-formed) id must produce a "not found" error, not a
    /// panic, for each single-id lifecycle tool.
    /// What: drives stop/resume/decommission/activity/send against a fresh state
    /// with a random UUID and asserts each returns Err containing "not found".
    /// Test: this test.
    #[tokio::test]
    async fn unknown_id_errors_for_all_single_id_tools() {
        let (_root, s) = state().await;
        let id = uuid::Uuid::new_v4().to_string();

        assert!(
            session_stop(&s, &id)
                .await
                .unwrap_err()
                .contains("not found")
        );
        assert!(
            session_resume(&s, &id)
                .await
                .unwrap_err()
                .contains("not found")
        );
        assert!(
            session_decommission(&s, &id)
                .await
                .unwrap_err()
                .contains("not found")
        );
        assert!(
            session_delete(&s, &id, false)
                .await
                .unwrap_err()
                .contains("not found")
        );
        assert!(
            session_activity(&s, &id, 60)
                .await
                .unwrap_err()
                .contains("not found")
        );
        assert!(
            session_send(&s, &id, "hi")
                .await
                .unwrap_err()
                .contains("not found")
        );
    }

    /// Why: garbage ids must be rejected with the parse message (before lookup)
    /// for every single-id tool.
    /// Test: this test.
    #[tokio::test]
    async fn garbage_id_rejected_for_all_single_id_tools() {
        let (_root, s) = state().await;
        for r in [
            session_stop(&s, "xx").await,
            session_resume(&s, "xx").await,
            session_decommission(&s, "xx").await,
            session_delete(&s, "xx", false).await,
            session_activity(&s, "xx", 60).await,
            session_send(&s, "xx", "t").await,
        ] {
            assert!(r.unwrap_err().contains("valid managed session id"));
        }
    }

    /// #8935 critic round: `session_stop` says when it moved the record only.
    /// The live session carries the record's name and the record has no pane
    /// id, so ownership is unproven and nothing is killed. Red on a73e5ac7f3,
    /// whose response had no `runtime_left_running` key.
    #[tokio::test]
    async fn session_stop_says_an_unproven_runtime_was_left_running() {
        let root = tempfile::TempDir::new().expect("tempdir");
        let tmux = LiveTrackingTmux::new();
        let s = Arc::new(
            DaemonState::with_root_isolated_managed_and_driver(
                root.path().to_path_buf(),
                tmux.clone(),
            )
            .await,
        );
        let id = ManagedSessionId::new();
        let ws = root.path().join(format!("{id}-mcp-stop"));
        s.session_manager()
            .await
            .create_with_id(
                id,
                "mcp session_stop test".to_string(),
                Some(ws.clone()),
                None,
                Some(ws),
                None,
                None,
                crate::runtime::RuntimeKind::default(),
                false,
                false,
            )
            .await
            .expect("seed session");

        let json = session_stop(&s, &id.to_string()).await.expect("stop");

        let why = json["runtime_left_running"]
            .as_str()
            .unwrap_or_else(|| panic!("the stop names the live session: {json}"));
        assert!(why.contains("no pane id"), "{why}");
        assert_eq!(json["state"], "stopped", "{json}");
        assert!(
            !tmux.live.lock().unwrap().is_empty(),
            "the session was killed"
        );
    }

    /// `session_delete` fail-closed guard + `force` bypass, driven end-to-end
    /// against a real (isolated) [`SessionManager`] record (#2012).
    ///
    /// Why: `unknown_id_errors_for_all_single_id_tools` only proves the
    /// not-found path; the actual running-guard/force behaviour needs a seeded
    /// record, which requires an isolated store (never the shared production
    /// one `state()` above points at). Uses [`LiveTrackingTmux`] (#2022) rather
    /// than the default `FakeNoopTmuxDriver` so the guard — now a real tmux
    /// liveness probe — has a genuinely live session to observe.
    /// What: seeds an Active (running) record via `create_with_id` (which
    /// registers the session as live on `LiveTrackingTmux`), asserts a
    /// non-forced `session_delete` call is refused (error mentions the
    /// session), then asserts `force=true` succeeds, returns `deleted: true`,
    /// and the record is gone from the store.
    /// Test: this function IS the test.
    #[tokio::test]
    async fn session_delete_refuses_running_then_force_bypasses() {
        use crate::runtime::RuntimeKind;

        let root = tempfile::TempDir::new().expect("tempdir");
        let s = Arc::new(
            DaemonState::with_root_isolated_managed_and_driver(
                root.path().to_path_buf(),
                LiveTrackingTmux::new(),
            )
            .await,
        );
        let mgr = s.session_manager().await;

        let id = ManagedSessionId::new();
        let ws = root.path().join(format!("{id}-mcp-delete"));
        mgr.create_with_id(
            id,
            "mcp session_delete test".to_string(),
            Some(ws.clone()),
            None,
            Some(ws),
            Some("https://example.com/r.git".to_string()),
            Some("main".to_string()),
            RuntimeKind::default(),
            false,
            false,
        )
        .await
        .expect("seed session");

        // Non-forced delete of a running (Provisioning) session must be refused.
        let err = session_delete(&s, &id.to_string(), false)
            .await
            .expect_err("must refuse to delete a running session without force");
        assert!(err.contains(&id.to_string()), "{err}");

        // The record must still be present after the refusal.
        assert!(mgr.get(&id).await.is_ok(), "record must survive refusal");

        // `force: true` bypasses the guard and soft-deletes the record.
        let value = session_delete(&s, &id.to_string(), true)
            .await
            .expect("force must bypass the running guard");
        assert_eq!(value["deleted"], serde_json::json!(true));
        // Soft-delete (#2012): the record is marked `--deleted--`, kept in store.
        assert_eq!(
            mgr.get(&id).await.expect("record still tracked").state,
            crate::session_manager::ManagedSessionState::Deleted,
            "record must be marked --deleted-- after forced delete"
        );
    }

    /// A tmux driver whose pane always shows a collapsed bracketed paste
    /// (#5699).
    ///
    /// Why: `LiveTrackingTmux` captures an empty pane, which the submit probe
    /// correctly reads as "could not tell". Proving the `sent: false` path
    /// needs a pane that positively shows the unsubmitted buffer.
    /// What: `LiveTrackingTmux` with `capture` answering the exact prompt line
    /// issue #5699 recorded.
    /// Test: `session_send_reports_an_unsubmitted_paste`.
    struct PastedPaneTmux {
        live: std::sync::Mutex<std::collections::HashSet<String>>,
    }

    impl crate::session_manager::ManagedTmuxDriver for PastedPaneTmux {
        fn create_session(&self, name: &str, _workdir: &str) -> Result<(), ManagedError> {
            self.live.lock().unwrap().insert(name.to_owned());
            Ok(())
        }

        fn kill_session(&self, name: &str) -> Result<(), ManagedError> {
            self.live.lock().unwrap().remove(name);
            Ok(())
        }

        fn send_line(&self, _name: &str, _text: &str) -> Result<(), ManagedError> {
            Ok(())
        }

        fn capture(&self, _name: &str, _lines: usize) -> Result<String, ManagedError> {
            Ok("❯ [Pasted text #1][Pasted text #2]".to_string())
        }

        fn list_sessions(&self) -> Result<Vec<String>, ManagedError> {
            Ok(self.live.lock().unwrap().iter().cloned().collect())
        }

        /// #9101: a pane id naming its session, so the record owns its pane.
        fn get_pane_id(&self, name: &str) -> Option<String> {
            Some(crate::test_support::self_describing_pane(name))
        }

        fn pane_identity(
            &self,
            pane_id: &str,
        ) -> Result<crate::session_manager::pane_identity::PaneIdentity, ManagedError> {
            Ok(crate::test_support::self_describing_identity(pane_id))
        }

        fn capture_pane(&self, name: &str, _p: &str, lines: usize) -> Result<String, ManagedError> {
            self.capture(name, lines)
        }
    }

    /// `session_send` must report `sent: false` when the pane proves the
    /// message was never submitted (#5699).
    ///
    /// Why: this is the wire-level half of the defect — the tool's caller is a
    /// PM coordinating another live session and acts on `sent`. Against PRE-FIX
    /// code `sent` is the literal `true` and there is no `submit_state` key at
    /// all, so BOTH assertions below fail. Asserting the tool still returns
    /// `Ok` (not an error) is deliberate: the characters did reach the pane, so
    /// this is a delivery verdict, not a dispatch failure.
    /// Test: this function IS the test.
    #[tokio::test]
    async fn session_send_reports_an_unsubmitted_paste() {
        use crate::runtime::RuntimeKind;

        let root = tempfile::TempDir::new().expect("tempdir");
        let s = Arc::new(
            DaemonState::with_root_isolated_managed_and_driver(
                root.path().to_path_buf(),
                Arc::new(PastedPaneTmux {
                    live: std::sync::Mutex::new(std::collections::HashSet::new()),
                }),
            )
            .await,
        );
        let mgr = s.session_manager().await;

        let id = ManagedSessionId::new();
        let ws = root.path().join(format!("{id}-mcp-send"));
        mgr.create_with_id(
            id,
            "mcp session_send test".to_string(),
            Some(ws.clone()),
            None,
            Some(ws),
            Some("https://example.com/r.git".to_string()),
            Some("main".to_string()),
            RuntimeKind::Tcode,
            false,
            false,
        )
        .await
        .expect("seed session");
        {
            let mut store = mgr.store.write().await;
            let mut r = store.get(&id).await.expect("seeded record");
            r.state = crate::session_manager::ManagedSessionState::Active;
            store.upsert(r).await.expect("mark active");
        }

        let value = session_send(&s, &id.to_string(), "a long coordination message")
            .await
            .expect("the characters reached the pane — this is a delivery verdict");
        assert_eq!(
            value["sent"],
            serde_json::json!(false),
            "pre-fix this is a hardcoded `true`: {value}"
        );
        assert_eq!(
            value["submit_state"],
            serde_json::json!("unsubmitted_paste"),
            "pre-fix the key does not exist: {value}"
        );
    }

    /// Why: an unknown `runtime` selector must be rejected up front (before any
    /// provisioning/tmux work), with a message naming the supported values.
    /// Test: this test.
    #[tokio::test]
    async fn session_new_invalid_runtime_errors() {
        let (_root, s) = state().await;
        let err = session_new(
            &s,
            "https://example.com/r.git",
            "main",
            "t",
            None,
            Some("bogus"),
            None,
        )
        .await
        .unwrap_err();
        assert!(err.contains("unknown runtime"), "{err}");
    }

    /// Point `$HOME` at a temp directory and restore it on drop, panic or not.
    ///
    /// Why: `SessionManager::decommission` resolves its containment root from
    /// the ambient environment, so a test that wants a real removal to happen
    /// must seed its workspace under a redirected root. The redirect is
    /// process-wide, hence `#[serial_test::serial]` on the only user.
    /// What: swaps `$HOME` and puts the prior value back on drop.
    /// Test: `session_decommission_prunes_stale_worktree_bookkeeping`.
    struct HomeGuard(Option<String>);

    impl HomeGuard {
        fn redirect(to: &std::path::Path) -> Self {
            let prior = std::env::var("HOME").ok();
            // SAFETY: the only caller is `#[serial_test::serial]`.
            unsafe { std::env::set_var("HOME", to) };
            Self(prior)
        }
    }

    impl Drop for HomeGuard {
        fn drop(&mut self) {
            // SAFETY: the only caller is `#[serial_test::serial]`.
            match self.0 {
                Some(ref prior) => unsafe { std::env::set_var("HOME", prior) },
                None => unsafe { std::env::remove_var("HOME") },
            }
        }
    }

    /// #5949: the MCP `session_decommission` tool leaves the base checkout's
    /// worktree bookkeeping clean.
    ///
    /// Why: this tool calls `SessionManager::decommission` in-process, below the
    /// client layer that carried the repair for the routed HTTP paths, so it
    /// removed an owned workspace and left git still listing it. The idle reaper
    /// reaches the same function the same way and runs unattended.
    /// What: a real checkout with a real registered worktree under a redirected
    /// `$HOME`, an owned record pointing at that worktree, then the MCP tool.
    /// Asserts the tombstone came back and that git no longer lists the leaf.
    /// Against the pre-fix code the last assertion fails.
    /// Test: this function IS the test.
    #[tokio::test]
    #[serial_test::serial]
    async fn session_decommission_prunes_stale_worktree_bookkeeping() {
        fn git(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
            std::process::Command::new("git")
                .arg("-C")
                .arg(dir)
                .args(args)
                .output()
                .unwrap_or_else(|e| panic!("git {args:?} could not run: {e}"))
        }

        let home = tempfile::tempdir().expect("home tempdir");
        let _home_guard = HomeGuard::redirect(home.path());
        let workspace_root = trusty_common::workspace_layout::resolve_workspace_root(None);

        let base = workspace_root.join("tm-5949-base");
        std::fs::create_dir_all(&base).expect("create base repo dir");
        if !git(&base, &["init", "--quiet"]).status.success() {
            eprintln!("session_decommission_prunes_stale_worktree_bookkeeping: no git, skipping");
            return;
        }
        assert!(
            git(&base, &["config", "user.email", "ci@test.invalid"])
                .status
                .success()
        );
        assert!(git(&base, &["config", "user.name", "CI"]).status.success());
        assert!(
            git(&base, &["config", "commit.gpgsign", "false"])
                .status
                .success()
        );
        std::fs::write(base.join("README.md"), "seed\n").expect("write README");
        assert!(git(&base, &["add", "README.md"]).status.success());
        assert!(
            git(&base, &["commit", "--quiet", "-m", "seed"])
                .status
                .success()
        );
        // #8663: pushed, so the owned workspace holds no unpushed commit.
        let remote = workspace_root.join("tm-5949-remote.git");
        assert!(
            git(
                &workspace_root,
                &["init", "--quiet", "--bare", "tm-5949-remote.git"]
            )
            .status
            .success()
        );
        let remote = remote.to_string_lossy();
        for args in [
            &["remote", "add", "origin", &remote][..],
            &["push", "--quiet", "origin", "HEAD"],
            &["fetch", "--quiet", "origin"],
        ] {
            assert!(git(&base, args).status.success(), "git {args:?}");
        }

        let id = crate::session_manager::ManagedSessionId::new();
        let leaf = format!("tm-5949-{id}");
        let ws = base.join(".worktrees").join(&leaf);
        assert!(
            git(
                &base,
                &[
                    "worktree",
                    "add",
                    "--quiet",
                    "-b",
                    &format!("session/{leaf}"),
                    &ws.to_string_lossy(),
                ],
            )
            .status
            .success(),
            "fixture: the worktree must be registered"
        );
        let listed = |dir: &std::path::Path| {
            String::from_utf8_lossy(&git(dir, &["worktree", "list", "--porcelain"]).stdout)
                .into_owned()
        };
        assert!(
            listed(&base).contains(&leaf),
            "fixture invariant: git must list the worktree before decommission"
        );

        let (_root, s) = state().await;
        s.session_manager()
            .await
            .create_with_id(
                id,
                "regression: #5949 MCP decommission".to_string(),
                Some(ws.clone()),
                None,
                Some(ws.clone()),
                None,
                None,
                crate::runtime::RuntimeKind::default(),
                false,
                // Owned: the branch that removes with `remove_dir_all`.
                true,
            )
            .await
            .expect("seed session");

        let json = session_decommission(&s, &id.to_string())
            .await
            .expect("decommission");
        assert_eq!(json["state"], "decommissioned", "{json}");
        // #8663 critic round 1: the verdict is reported, not discarded.
        assert_eq!(json["workspace_removed"], Value::Bool(true), "{json}");
        assert_eq!(
            json.get("workspace_kept_reason"),
            Some(&Value::Null),
            "{json}"
        );
        assert!(!ws.exists(), "the workspace must be gone: {}", ws.display());
        assert!(
            !listed(&base).contains(&leaf),
            "the MCP decommission left a stale worktree entry for {leaf} — the \
             bookkeeping repair did not run (#5949)"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    /// #8663 critic round 1: a kept owned workspace comes back from the MCP
    /// tool as `workspace_removed: false` with the reason, not as a bare
    /// tombstone.
    #[tokio::test]
    #[serial_test::serial]
    async fn session_decommission_reports_a_kept_workspace() {
        let home = tempfile::tempdir().expect("home tempdir");
        let _home_guard = HomeGuard::redirect(home.path());
        let workspace_root = trusty_common::workspace_layout::resolve_workspace_root(None);
        let ws = workspace_root
            .join("owner")
            .join("repo")
            .join("tm-8663-kept");
        std::fs::create_dir_all(&ws).expect("create workspace");
        std::fs::write(ws.join("notes.md"), "agent work\n").expect("write notes");

        let (_root, s) = state().await;
        let id = crate::session_manager::ManagedSessionId::new();
        s.session_manager()
            .await
            .create_with_id(
                id,
                "regression: #8663 MCP kept workspace".to_string(),
                Some(ws.clone()),
                None,
                Some(ws.clone()),
                None,
                None,
                crate::runtime::RuntimeKind::default(),
                false,
                true,
            )
            .await
            .expect("seed session");

        let json = session_decommission(&s, &id.to_string())
            .await
            .expect("a refusal is not an error");
        assert_eq!(json["state"], "decommissioned", "{json}");
        assert_eq!(json["workspace_removed"], Value::Bool(false), "{json}");
        let reason = json["workspace_kept_reason"]
            .as_str()
            .unwrap_or_else(|| panic!("the kept reason is a string: {json}"));
        assert!(reason.contains("notes.md"), "{reason}");
        assert!(ws.join("notes.md").exists(), "the work must survive");
        assert_eq!(
            json.get("workspace_kept_by_design"),
            Some(&Value::Null),
            "{json}"
        );
    }

    /// #8663 critic round 2: a workspace tm never removes comes back as
    /// `workspace_kept_by_design`, as the HTTP route reports it.
    #[tokio::test]
    async fn session_decommission_reports_a_workspace_kept_by_design() {
        let ws = tempfile::tempdir().expect("user directory");
        let (_root, s) = state().await;
        let id = crate::session_manager::ManagedSessionId::new();
        s.session_manager()
            .await
            .create_with_id(
                id,
                "regression: #8663 MCP kept by design".to_string(),
                Some(ws.path().to_path_buf()),
                None,
                Some(ws.path().to_path_buf()),
                None,
                None,
                crate::runtime::RuntimeKind::default(),
                false,
                // Unowned: a local-path directory decommission never deletes.
                false,
            )
            .await
            .expect("seed session");

        let json = session_decommission(&s, &id.to_string())
            .await
            .expect("decommission");
        let by_design = json["workspace_kept_by_design"]
            .as_str()
            .unwrap_or_else(|| panic!("the by-design reason is a string: {json}"));
        assert!(by_design.contains("kept by design"), "{by_design}");
        assert_eq!(json["workspace_removed"], Value::Bool(false), "{json}");
        assert!(ws.path().exists(), "the user's directory must survive");
    }
}