trusty-mpm 1.0.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
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
//! HTTP route handlers for the managed session-manager API.
//!
//! Why: the managed session API (POST/GET /api/v1/sessions/managed/…) is a new
//! cohesive cluster of routes that extends the existing axum router; keeping it
//! in a separate file mirrors the existing coordinator_routes pattern and keeps
//! api.rs focused on the core session/hook surface.
//! What: defines request/response shapes and axum handlers for the managed
//! session endpoints listed in the spec. All handlers receive Arc<DaemonState>
//! via the axum State extractor and delegate to the lazily-initialized
//! [`crate::session_manager::SessionManager`].
//! Test: handler behavior is exercised via the in-process router in
//! `tests/session_manager_mvp.rs`.

use std::sync::Arc;

use axum::{
    Json,
    extract::{Path as AxumPath, State},
    http::StatusCode,
    response::IntoResponse,
};
use serde::{Deserialize, Serialize};
use tracing::warn;

use crate::daemon::state::DaemonState;
use crate::runtime::RuntimeKind;
use crate::session_manager::ManagedSessionId;

pub mod activity;
mod deliverable_link;
mod deployment_check;
mod fleet;
pub mod front_gate;
pub mod inproject;
pub mod inproject_hygiene;
mod launch_on_main;
mod lifecycle;
mod mcp_spawn_gate;
mod project_registry_routes;
mod project_status;
pub mod provision_status;
pub mod proxy;
pub mod prune;
mod reactivate;
pub mod rename;
mod resume_error;
mod session_summary;
mod summary;
pub mod sync_assets;
pub use activity::{ActivityResponse, get_session_activity};
pub use fleet::{FleetByProjectResponse, FleetProjectGroup, fleet_by_project_route};
pub use front_gate::{
    ConformanceGate, FrontGateOutcome, HeadlessApproval, IsrConformanceGate, run_front_gate,
};
pub use lifecycle::{
    SpawnParams, is_local_workdir, resume_managed, spawn_managed, spawn_runtime_for, write_task_md,
};
pub use project_registry_routes::{
    PatchProjectBody, ProjectsListResponse, RegisterProjectBody, get_project_registry_route,
    list_projects_registry_route, patch_project_registry_route, register_project_registry_route,
};
pub use project_status::{
    DeliverableStatusCounts, MilestoneStatusCounts, ProjectConfigFlags, ProjectStatusResponse,
    SessionStateCounts, aggregate_project_status, project_status_route,
};
pub use proxy::{
    DirectManagedBackend, ProxyFocusRequest, ProxyFocusResponse, ProxyMessageRequest,
    ProxyMessageResponse, ProxySummaryResponse, ProxyTargetWire, ProxyUnfocusRequest,
    ProxyUnfocusResponse, proxy_focus, proxy_get_focus, proxy_message, proxy_router, proxy_summary,
    proxy_unfocus,
};
pub use prune::{
    PruneRequest, decommission_ephemeral_route, prune_managed_route, prune_worktrees_route,
};
pub use reactivate::reactivate_managed_session;
pub use rename::{RenameRequest, rename_managed_session};
pub use resume_error::ResumeManagedError;
pub use session_summary::SessionSummary;
pub use summary::record_to_json;
use summary::{
    attach_cmd_for, checked_summaries, numbered_summaries, parse_id, reconcile_against_tmux,
    record_to_summary, record_to_summary_checked,
};

// ── Request / Response shapes ─────────────────────────────────────────────────

/// Request body for POST /api/v1/sessions/managed (spawn).
///
/// Why: the calling agentic process must supply the repo, ref, and task;
/// an optional name hint overrides the auto-generated tmux session name, and an
/// optional runtime selector picks the backend (Claude Code vs trusty-code).
/// What: deserializable JSON body with repo_url, ref, task, optional name_hint,
/// and optional `runtime` (`"claude-code"` | `"tcode"`; defaults to claude-code).
/// Test: spawn handler test in session_manager_mvp.rs; `spawn_request_runtime_*`.
#[derive(Debug, Deserialize)]
pub struct SpawnRequest {
    /// Repository URL to provision the session workspace from.
    pub repo_url: String,
    /// Git branch or ref to check out.
    #[serde(rename = "ref")]
    pub git_ref: String,
    /// Human-readable task description for the session.
    pub task: String,
    /// Optional name hint overriding the auto-generated tmux session name.
    pub name_hint: Option<String>,
    /// Optional runtime selector (`"claude-code"` | `"tcode"`).
    ///
    /// Absent or null → the default Claude Code path, so existing callers are
    /// unaffected. Parsed via [`crate::runtime::RuntimeKind::from_str`]; an
    /// unrecognized value yields a `400 Bad Request`.
    pub runtime: Option<String>,
    /// Optional ephemeral marker (#1508): `true` tags this as a test/throwaway
    /// session eligible for bulk teardown + age-based auto-reap. Absent/null/false
    /// → a normal durable session the automatic paths never touch.
    #[serde(default)]
    pub ephemeral: Option<bool>,
    /// Optional turnkey-injection control (#1903/#1299): absent/null/`true` →
    /// auto-inject `task` into the pane once the runtime is ready (the default,
    /// so `tm session new`/`tm ticket` are turnkey); `false` → metadata-only
    /// (the caller delivers the task via `POST .../{id}/send`).
    #[serde(default)]
    pub inject_task: Option<bool>,
    /// Optional Deliverable id to bind this session to (DOC-35 §10.6, #2379).
    ///
    /// Why: `tm sessions new --deliverable <id>` links a fresh session to an
    /// existing Deliverable so its ledger accumulates the sessions that
    /// worked on it. Validated at spawn time (must exist AND belong to this
    /// project) BEFORE any provisioning side effect; an invalid id is a 404,
    /// never a silently-dropped link. Absent/null → no link (the common case).
    #[serde(default)]
    pub deliverable_id: Option<String>,
    /// Optional force-new control (#2450): `true` SKIPS the in-project reconnect
    /// pre-flight so an explicit "launch new session" surface (the `tm` picker's
    /// "launch new session" choice, `tm session new`) always spawns a FRESH
    /// session + worktree instead of adopting an existing live one for the same
    /// project. Absent or `false` → the reconnect default (#1707), so
    /// programmatic/idempotent callers are unaffected. Unlike `inject_task`
    /// above, this is a plain `bool` (not `Option<bool>`): `#[serde(default)]`
    /// on a bool only supplies the default when the KEY IS ABSENT — an
    /// explicit `"force_new": null` in the request body is a type mismatch and
    /// fails the whole request with a 400, it is not tolerated as `false`.
    #[serde(default)]
    pub force_new: bool,
    /// Optional asynchronous-spawn control (#2605): `true` provisions on a
    /// detached background task and returns `202 Accepted` with
    /// `{ id, state: "provisioning" }` IMMEDIATELY, instead of holding the
    /// connection open for the whole clone/deploy. The caller then polls
    /// `GET /api/v1/sessions/managed/{id}/provision-status` for live progress
    /// and the terminal outcome. Absent/`false` → the legacy synchronous `201`
    /// behaviour (unchanged for every existing programmatic/MCP caller), so
    /// this is a purely additive, opt-in flag. Like `force_new`, it is a plain
    /// `#[serde(default)]` bool: an explicit `"background": null` is a type
    /// mismatch (400), not tolerated as `false`.
    #[serde(default)]
    pub background: bool,
}

/// Response body for POST /api/v1/sessions/managed (spawn, 201 Created).
///
/// Why: the calling agentic process needs the session id, tmux name, workspace path,
/// state, and attach command immediately after spawn.
/// What: serializable JSON with all fields from the spec response shape.
/// Test: spawn handler test.
#[derive(Debug, Serialize)]
pub struct SpawnResponse {
    /// Managed session id (UUID string).
    pub id: String,
    /// tmux session name.
    pub name: String,
    /// Provisioned workspace path, if any.
    pub workspace_path: Option<String>,
    /// Repository URL the session was provisioned from.
    pub repo_url: Option<String>,
    /// Git branch or ref checked out.
    pub branch: Option<String>,
    /// Current lifecycle state.
    pub state: String,
    /// Creation timestamp (RFC 3339).
    pub created_at: String,
    /// tmux attach command string.
    pub attach_cmd: String,
    /// Runtime backend that hosts the session (`"claude-code"` | `"tcode"`).
    pub runtime: String,
    /// The Deliverable this session is bound to, if `--deliverable` was passed
    /// (DOC-35 §10.6, #2379). `None` for the common ad-hoc-session case.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deliverable_id: Option<String>,
}

/// Request body for POST /api/v1/sessions/managed/adopt (#1433).
///
/// Why: adopting an EXISTING unmanaged tmux session connects the managed surface
/// to a pane the operator already has. Unlike the stateless snapshot adopt at
/// `POST /tmux/adopt` (which registers nothing), this REGISTERS a durable record.
/// Because the pane's provenance is unknown to the daemon, the operator must
/// supply the `cwd`; `task` is optional (empty → a generic description) and
/// `runtime` is optional (absent → the default managed runtime).
/// What: `tmux_name` (the live pane to adopt), the required `cwd`, an optional
/// `task`, and an optional `runtime` selector (`"claude-code"` | `"tcode"`).
/// Test: `adopt_existing_*` handler tests in tests/session_manager_mvp.rs.
#[derive(Debug, Deserialize)]
pub struct AdoptExistingRequest {
    /// The live tmux session name to adopt (any name; need not be `tm-`/`tmpm-`).
    pub tmux_name: String,
    /// Working directory the adopted session runs in (REQUIRED — provenance is
    /// unknown to the daemon, so the operator supplies it).
    pub cwd: String,
    /// Optional human-readable task description (empty/absent allowed).
    #[serde(default)]
    pub task: Option<String>,
    /// Optional runtime selector (`"claude-code"` | `"tcode"`); absent → default.
    #[serde(default)]
    pub runtime: Option<String>,
    /// Optional ephemeral marker (#1508): `true` tags this adoption as a
    /// test/throwaway session eligible for bulk teardown + age-based auto-reap.
    /// Absent/null/false → a durable operator adoption the automatic paths never
    /// touch.
    #[serde(default)]
    pub ephemeral: Option<bool>,
}

/// Response body for POST /api/v1/sessions/managed/adopt (201 Created).
///
/// Why: the caller needs the new managed record's identity + the attach command
/// to immediately drive or attach to the now-managed session.
/// What: the same flat summary fields as [`SessionSummary`] plus the derived
/// `attach_cmd`, mirroring [`SpawnResponse`].
/// Test: `adopt_existing_registers_record` in tests/session_manager_mvp.rs.
#[derive(Debug, Serialize)]
pub struct AdoptExistingResponse {
    /// Managed session id (UUID string).
    pub id: String,
    /// tmux session name that was adopted.
    pub name: String,
    /// Current lifecycle state (`active` immediately after adoption).
    pub state: String,
    /// Working directory the adopted session runs in.
    pub cwd: String,
    /// Runtime backend hosting the session (`"claude-code"` | `"tcode"`).
    pub runtime: String,
    /// tmux attach command string.
    pub attach_cmd: String,
}

/// List response for GET /api/v1/sessions/managed.
///
/// Why: the calling agentic process needs the full session list in a consistent
/// JSON shape.
/// What: wraps a vec of SessionSummary.
/// Test: list handler test.
#[derive(Debug, Serialize)]
pub struct ListSessionsResponse {
    /// All managed sessions as summaries.
    pub sessions: Vec<SessionSummary>,
}

// `SessionSummary` lives in its own file (issue #2444) — see
// `session_summary.rs`'s module doc for why, and `stale_assets`'s field doc
// for the new drift marker.

/// Response body for POST /api/v1/sessions/managed/{id}/decommission.
///
/// Why: the decommission operation may or may not physically remove the workspace
/// directory (it is skipped for un-owned workspaces such as local-path or adopted
/// sessions). The CLI must surface an honest message, so the daemon reports what
/// actually happened via `workspace_removed`. `workspace_path_was` lets the CLI
/// locate the base git repo for `git worktree prune` without requiring a second
/// lookup — the path is gone from disk but the parent dir still exists.
/// What: extends the flat session summary with a `workspace_removed` bool that is
/// `true` only when `remove_dir_all` succeeded (the workspace was owned and got
/// deleted from disk), and `workspace_path_was` (the pre-tombstone path) when the
/// session had an owned workspace.
/// Test: `decommission_workspace_removed_reflects_ownership` in managed_routes tests.
#[derive(Debug, Serialize)]
pub struct DecommissionResponse {
    /// Flat session summary (post-tombstone: state=decommissioned, workspace_path=None).
    #[serde(flatten)]
    pub summary: SessionSummary,
    /// Whether the workspace directory was actually removed from disk.
    ///
    /// `true`  → SM-owned workspace was deleted by this call.
    /// `false` → workspace was not owned (adopt/local-path) or was already absent.
    pub workspace_removed: bool,
    /// Pre-decommission workspace path string, when the session was owned (`None`
    /// for adopted/local-path sessions where the workspace was never SM-owned).
    /// Used by the CLI to locate the base git repo and run `git worktree prune`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_path_was: Option<String>,
}

/// Query parameters for POST /api/v1/sessions/managed/{id}/delete (#2012).
///
/// Why: hard-delete needs exactly one caller-controlled knob — whether to
/// bypass the running-session safety guard. A query flag (mirroring
/// `?source_id=` on the list route) keeps the call a plain, bodyless POST for
/// the common (non-running) case, while still letting `--force` opt in.
/// What: `force` (default `false`, the fail-closed default) — when absent or
/// `false`, [`crate::session_manager::SessionManager::delete_record`] refuses
/// to delete a RUNNING (`Active`/`Provisioning`) session.
/// Test: `delete_route_*` in managed_routes tests.
#[derive(Debug, Deserialize)]
pub struct DeleteQuery {
    /// Bypass the running-session guard and hard-delete the record anyway.
    #[serde(default)]
    pub force: bool,
}

/// Response body for POST /api/v1/sessions/managed/{id}/delete (#2012).
///
/// Why: delete SOFT-deletes — it marks the record `Deleted` (rendered
/// `--deleted--`) and keeps it in the store. The response carries the
/// PRE-deletion snapshot (id, name, the state it was in BEFORE deletion, …) so
/// the caller/CLI can render an honest `[was <state>]` confirmation.
/// What: the pre-deletion [`SessionSummary`] plus `deleted: true`. Distinct
/// from [`DecommissionResponse`] — delete never mutates the workspace, so
/// there is no `workspace_removed` field here.
/// Test: `delete_route_*` in managed_routes tests.
#[derive(Debug, Serialize)]
pub struct DeleteResponse {
    /// Snapshot of the record as it was immediately BEFORE deletion.
    #[serde(flatten)]
    pub summary: SessionSummary,
    /// Always `true` on success — the record was marked `--deleted--`.
    pub deleted: bool,
}

/// Request body for POST /api/v1/sessions/managed/{id}/send.
///
/// Why: the calling agentic process or operator injects text into the pane.
/// What: a single `text` field.
/// Test: send handler test.
#[derive(Debug, Deserialize)]
pub struct SendInputRequest {
    /// Text to inject into the session's tmux pane.
    pub text: String,
}

/// Response body for POST /api/v1/sessions/managed/{id}/send.
///
/// Why: confirms the inject succeeded without echoing the full session record.
/// What: sent flag and tmux_name for logging.
/// Test: send handler test.
#[derive(Debug, Serialize)]
pub struct SendInputResponse {
    /// True when the text was injected.
    pub sent: bool,
    /// tmux session name the text was sent to.
    pub tmux_name: String,
}

/// Request body for POST /api/v1/sessions/managed/{id}/answer.
///
/// Why: the calling agentic process injects an answer to a pending decision.
/// What: a single `answer` field.
/// Test: answer handler test.
#[derive(Debug, Deserialize)]
pub struct AnswerRequest {
    /// The answer text to inject for the pending decision.
    pub answer: String,
}

/// Response body for POST /api/v1/sessions/managed/{id}/answer.
///
/// Why: confirms the answer was injected.
/// What: injected flag and tmux_name.
/// Test: answer handler test.
#[derive(Debug, Serialize)]
pub struct AnswerResponse {
    /// True when the answer was injected.
    pub injected: bool,
    /// tmux session name the answer was sent to.
    pub tmux_name: String,
}

/// Response body for GET /api/v1/sessions/managed/{id}/attach-cmd.
///
/// Why: the calling agentic process or operator needs the exact tmux command
/// string to attach to the session.
/// What: a single `attach_cmd` field.
/// Test: attach-cmd handler test.
#[derive(Debug, Serialize)]
pub struct AttachCmdResponse {
    /// tmux attach command string.
    pub attach_cmd: String,
}

// ── Handlers ──────────────────────────────────────────────────────────────────

/// POST /api/v1/sessions/managed — spawn a new managed session.
///
/// Why: the primary entry point for the calling agentic process to create a new
/// isolated agent workspace and start a harness in it.
/// What: in order —
///   (a) pre-generates a `ManagedSessionId` so the workspace path can embed it;
///   (b) provisions an isolated workspace via `WorkspaceProvisioner::provision`
///       (clone + prepare_session deploy of agents/skills);
///   (c) creates the tmux session via `SessionManager::create_with_id` with
///       `cwd = workspace_path` so `tmux new-session -c <workspace>` is issued
///       and claude opens IN the provisioned directory, not $HOME;
///   (d) launches Claude Code in the pane via `ClaudeCodeAdapter::spawn`
///       (`env -u ANTHROPIC_API_KEY claude`).
/// On any step failing the record is marked `errored` (or the error is returned
/// before the record is created). No panics, no `unwrap` on the critical path.
/// Test: `handler_spawn_creates_tmux_at_workspace_cwd` in
/// tests/session_manager_mvp.rs asserts the tmux session was created with
/// `cwd == workspace_path`, never `$HOME`; `handler_spawn_wires_provision_and_spawn`
/// asserts provision was called (workspace_path is non-null under workspaces root)
/// and the spawn command was sent to tmux.
pub async fn spawn_session(
    State(state): State<Arc<DaemonState>>,
    Json(req): Json<SpawnRequest>,
) -> impl IntoResponse {
    // Reject an invalid runtime selector up front with a 400 (the shared
    // `spawn_managed` helper also rejects it, but doing it here lets us keep the
    // HTTP-specific 400-vs-500 status distinction that existing clients rely on).
    if let Some(raw) = req.runtime.as_deref()
        && let Err(e) = raw.parse::<RuntimeKind>()
    {
        warn!("spawn_session: invalid runtime selector: {e}");
        return (StatusCode::BAD_REQUEST, e.to_string()).into_response();
    }

    // Deliverable linkage (DOC-35 §10.6, #2379): validate BEFORE any
    // provisioning side effect, mirroring the runtime-selector pre-check
    // above — an invalid `--deliverable` must never mint infrastructure for a
    // link that was never going to be recorded.
    if let Some(deliverable_id) = req.deliverable_id.as_deref()
        && let Err(resp) =
            deliverable_link::validate_deliverable_scope(&state, &req.repo_url, deliverable_id)
                .await
    {
        return resp;
    }

    let params = SpawnParams {
        repo_url: req.repo_url,
        git_ref: req.git_ref,
        task: req.task,
        name_hint: req.name_hint,
        runtime: req.runtime,
        ephemeral: req.ephemeral,
        // HTTP route == CLI-origin (`tm launch`/`tm ticket` client calls) —
        // never subject to the MCP spawn gate (#1836/#1837).
        mcp_initiated: false,
        // Turnkey by default (#1903/#1299); a client sets `inject_task: false`
        // to opt into the legacy metadata-only behavior (`--no-inject`).
        inject_task: req.inject_task,
        deliverable_id: req.deliverable_id,
        // Force-new opt-out (#2450): a client (the picker's "launch new
        // session", `tm session new`) sets `force_new: true` to skip the
        // in-project reconnect pre-flight and always spawn fresh.
        force_new: req.force_new,
    };

    // Async path (#2605): provision on a detached task and return the job id
    // immediately, so a large-repo clone never outlasts the client's HTTP
    // timeout and the blocking provision runs OFF the request path. The runtime
    // and deliverable validations above already ran synchronously, so an
    // invalid request is still a fast 400/404 (never a deferred failure).
    if req.background {
        return provision_status::accept_async_spawn(state.clone(), params);
    }

    match spawn_managed(&state, ManagedSessionId::new(), params).await {
        Ok(final_record) => {
            let resp = SpawnResponse {
                id: final_record.id.to_string(),
                name: final_record.tmux_name.clone(),
                workspace_path: final_record
                    .workspace_path
                    .as_ref()
                    .map(|p| p.to_string_lossy().to_string()),
                repo_url: final_record.repo_url.clone(),
                branch: final_record.branch.clone(),
                state: final_record.state.to_string(),
                created_at: final_record.created_at.to_rfc3339(),
                attach_cmd: attach_cmd_for(&final_record.tmux_name),
                runtime: final_record.runtime.as_str().to_owned(),
                deliverable_id: final_record.deliverable_id.map(|id| id.to_string()),
            };
            (StatusCode::CREATED, Json(resp)).into_response()
        }
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
    }
}

/// POST /api/v1/sessions/managed/adopt — adopt an EXISTING tmux session (#1433).
///
/// Why: the operator already has a live, unmanaged tmux pane (a hand-started
/// Claude Code, an externally-created session, or one whose record was lost) and
/// wants to drive it through the full managed surface. This REGISTERS a durable
/// `Active` record for that pane. It is deliberately distinct from the stateless
/// `POST /tmux/adopt` snapshot endpoint, which captures a session's shape but
/// registers NOTHING — that endpoint's semantics are unchanged.
/// What: validates an optional runtime selector up front (400 on a bad value),
/// then delegates to [`crate::session_manager::SessionManager::adopt_existing`].
/// Maps its typed errors: `TmuxSessionMissing` → 404 (no such pane),
/// `AlreadyAdopted` → 409 (already tracked), any other → 500. On success returns
/// 201 Created with the new record + attach command.
/// Test: `adopt_existing_registers_record`, `adopt_existing_missing_is_404`,
/// `adopt_existing_double_is_409` in tests/session_manager_mvp.rs.
pub async fn adopt_existing_session(
    State(state): State<Arc<DaemonState>>,
    Json(req): Json<AdoptExistingRequest>,
) -> impl IntoResponse {
    // Resolve the runtime selector up front so a typo is a 400, not a 500.
    let runtime = match req.runtime.as_deref() {
        None => RuntimeKind::default(),
        Some(raw) => match raw.parse::<RuntimeKind>() {
            Ok(rk) => rk,
            Err(e) => {
                warn!("adopt_existing: invalid runtime selector: {e}");
                return (StatusCode::BAD_REQUEST, e.to_string()).into_response();
            }
        },
    };

    let task = req.task.unwrap_or_default();
    let cwd = std::path::PathBuf::from(&req.cwd);

    let mgr = state.session_manager().await;
    match mgr
        .adopt_existing(
            &req.tmux_name,
            cwd,
            task,
            runtime,
            req.ephemeral.unwrap_or(false),
        )
        .await
    {
        Ok(record) => {
            let resp = AdoptExistingResponse {
                id: record.id.to_string(),
                name: record.tmux_name.clone(),
                state: record.state.to_string(),
                cwd: record.cwd.to_string_lossy().to_string(),
                runtime: record.runtime.as_str().to_owned(),
                attach_cmd: attach_cmd_for(&record.tmux_name),
            };
            (StatusCode::CREATED, Json(resp)).into_response()
        }
        Err(crate::session_manager::ManagedError::TmuxSessionMissing(msg)) => {
            (StatusCode::NOT_FOUND, msg).into_response()
        }
        Err(crate::session_manager::ManagedError::AlreadyAdopted(msg)) => {
            (StatusCode::CONFLICT, msg).into_response()
        }
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    }
}

/// GET /api/v1/sessions/managed — list all managed sessions.
///
/// Why: the calling agentic process polls this to see all running sessions,
/// their state, and pending decisions. Since issue #3034, this is also the
/// SOLE source of the stable `tm ls` slot numbers every by-number CLI surface
/// (the picker, `d<N>` delete) resolves against — see
/// `SessionManager::numbered_snapshot`'s doc for why the assignment must live
/// here rather than being recomputed client-side per fetch.
/// What: returns one summary per stable slot (1..=highest ever assigned),
/// live or tombstoned. When the optional `?source_id=<id>` query parameter is
/// present, only rows whose LAST-KNOWN `source_id` matches exactly are
/// returned (a tombstoned slot still carries its last-known `source_id`, so
/// deleting a project's session does not make its slot vanish from that
/// project's filtered view). Each summary's `unresumable` flag (#2595) is
/// computed here — via `session_manager::resume_workdir::is_unresumable`,
/// which short-circuits to `false` without any I/O for every state other than
/// `Stopped`/`Errored` — so every picker/list surface reading this endpoint
/// sees dead sessions flagged up front rather than discovering them via a
/// failed resume. The per-session probes run CONCURRENTLY via
/// [`summary::checked_summaries`] (#2595 review, MEDIUM finding 4) rather than
/// one-at-a-time, so a large fleet's response latency does not scale with its
/// count of stopped/errored sessions. Numbering is observed against the FULL,
/// unfiltered record set BEFORE the `source_id` filter is applied — otherwise
/// a session outside the current filter would go unobserved and receive a
/// fresh number the next time it IS listed.
/// Test: list handler test; list-with-source-id-filter test;
/// `list_marks_dead_stopped_session_unresumable`,
/// `list_leaves_live_and_healthy_stopped_sessions_unmarked`,
/// `list_assigns_stable_slot_numbers_and_tombstones_deleted_one` (integration
/// test, `tests/session_manager_slots.rs`).
pub async fn list_managed_sessions(
    State(state): State<Arc<DaemonState>>,
    axum::extract::Query(q): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> impl IntoResponse {
    let mgr = state.session_manager().await;
    let sid_filter = q.get("source_id").map(String::as_str);
    // #3034: numbering is observed against the FULL, unfiltered record set
    // BEFORE the `source_id` filter is applied — otherwise a session outside
    // the current filter would go unobserved and receive a fresh number the
    // next time it IS listed. `numbered_summaries` applies the `source_id`
    // filter, the async unresumable/stale-assets probes, AND the live-tmux
    // `state`/`attached` reconciliation (#3302/#3531 — a running/attached
    // session must never read `(stopped)`) to the surviving rows, fail-closed
    // on a tmux probe error (see `reconcile_against_tmux`).
    let all_records = mgr.list().await;
    let numbered = mgr.numbered_snapshot(&all_records).await;
    let sessions = numbered_summaries(numbered, mgr.tmux.as_ref(), sid_filter).await;
    Json(ListSessionsResponse { sessions })
}

/// GET /api/v1/sessions/managed/{id} — get one session record.
///
/// Why: the calling agentic process needs the full record for a specific session
/// including workspace_path, repo_url, branch, and pending decision fields.
/// What: looks up the session by id and returns its summary, with `unresumable`
/// (#2595) computed the same way [`list_managed_sessions`] does — kept
/// consistent so `tm session info <id>` never disagrees with the list/picker
/// about whether a session is a dead pick.
/// Test: get handler test.
pub async fn get_managed_session(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    match mgr.get(&id).await {
        Ok(record) => {
            // Reconcile against live tmux like the list handler — this is the
            // record `tm session resume <id>` reads, and its resume decision keys
            // off `state`; serving a stale `stopped` for a live session would let
            // resume destructively recreate the pane (code-critic HIGH).
            let mut summary = record_to_summary_checked(&record).await;
            reconcile_against_tmux(
                mgr.tmux.as_ref(),
                std::slice::from_mut(&mut summary),
                std::slice::from_ref(&record),
            );
            Json(summary).into_response()
        }
        Err(_) => (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response(),
    }
}

/// POST /api/v1/sessions/managed/{id}/send — inject text into pane.
///
/// Why: the calling agentic process or human operator sends messages to the
/// harness without needing to attach to the tmux pane.
/// What: delegates to SessionManager::send_input.
/// Test: send handler test.
pub async fn send_to_session(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
    Json(req): Json<SendInputRequest>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    let tmux_name = match mgr.get(&id).await {
        Ok(r) => r.tmux_name,
        Err(_) => {
            return (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response();
        }
    };
    match mgr.send_input(&id, &req.text).await {
        Ok(()) => Json(SendInputResponse {
            sent: true,
            tmux_name,
        })
        .into_response(),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    }
}

/// POST /api/v1/sessions/managed/{id}/answer — inject answer to pending decision.
///
/// Why: the calling agentic process resolves a pending decision by posting the
/// accepted or overridden answer; the substrate clears pending_decision.
/// What: delegates to SessionManager::answer_decision.
/// Test: answer handler test.
pub async fn answer_session_decision(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
    Json(req): Json<AnswerRequest>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    let record = match mgr.get(&id).await {
        Ok(r) => r,
        Err(_) => {
            return (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response();
        }
    };
    let tmux_name = record.tmux_name.clone();

    // FRONT-gate (#1360) path: a session escalated *before* spawn sits in
    // `Provisioning` with a `pending_decision` and NO running harness. Answering
    // it must clear the decision AND launch the withheld runtime (AC-15) — not
    // inject the answer into a bare pane. Any other state is the ordinary
    // harness-question path (`answer_decision`, which injects into the live pane).
    let is_front_gate_escalation = record.state
        == crate::session_manager::ManagedSessionState::Provisioning
        && record.pending_decision.is_some();

    if is_front_gate_escalation {
        if let Err(e) = mgr.clear_pending_decision(&id).await {
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
        // Re-fetch AFTER clearing: `clear_pending_decision` upserts a new record
        // version, so the `record` captured above is now stale (it still carries
        // the pending decision). Spawn the runtime from the fresh snapshot so the
        // withheld harness launches against the post-clear state (#1360 review).
        let fresh = match mgr.get(&id).await {
            Ok(r) => r,
            Err(_) => {
                return (StatusCode::NOT_FOUND, format!("session {id_str} not found"))
                    .into_response();
            }
        };
        match spawn_runtime_for(&state, &fresh).await {
            Ok(()) => Json(AnswerResponse {
                injected: true,
                tmux_name,
            })
            .into_response(),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e).into_response(),
        }
    } else {
        match mgr.answer_decision(&id, &req.answer).await {
            Ok(()) => Json(AnswerResponse {
                injected: true,
                tmux_name,
            })
            .into_response(),
            Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
        }
    }
}

/// GET /api/v1/sessions/managed/{id}/attach-cmd — return tmux attach command.
///
/// Why: the calling agentic process or operator needs the exact string to attach
/// without hardcoding the naming convention.
/// What: returns "tmux attach-session -t <tmux_name>".
/// Test: attach-cmd handler test.
pub async fn get_attach_cmd(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    match mgr.get(&id).await {
        Ok(record) => {
            let attach_cmd = attach_cmd_for(&record.tmux_name);
            Json(AttachCmdResponse { attach_cmd }).into_response()
        }
        Err(_) => (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response(),
    }
}

/// POST /api/v1/sessions/managed/{id}/runtime-stop — stop the runtime only (keep workspace).
///
/// Why: a session ENDURES beyond its running runtime; `runtime-stop` kills the
/// tmux session and claude process but preserves the workspace directory and
/// record so the session can be resumed later.
/// What: delegates to SessionManager::stop; returns the updated record summary.
/// Test: stop handler test; `manager_stop_keeps_workspace`.
pub async fn stop_managed_session_runtime(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    match mgr.stop(&id).await {
        Ok(record) => Json(record_to_summary(&record)).into_response(),
        Err(_) => (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response(),
    }
}

/// POST /api/v1/sessions/managed/{id}/resume — re-spawn the runtime in the existing workspace.
///
/// Why: after `stop`, the workspace is still on disk; `resume` brings back the
/// runtime without re-cloning by creating a fresh tmux session with
/// cwd = workspace_path and spawning claude inside it.
/// What: delegates to SessionManager::resume, then re-spawns the SAME runtime
/// backend the session was created with (via `build_adapter(record.runtime, …)`)
/// on the fresh tmux session — a tcode session resumes on tcode, not claude-code.
/// Test: `manager_resume_respawns_in_existing_workspace`.
pub async fn resume_managed_session(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };

    // Single round-trip: the shared `resume_managed` helper performs the
    // existence + state check inside `SessionManager::resume` and re-spawns the
    // runtime. The TYPED error picks its own HTTP status/headers via its
    // `IntoResponse` impl (`resume_error.rs`) — no pre-flight `get` (which
    // introduced a TOCTOU race where the session could be decommissioned
    // between the probe and the resume, yielding 500 instead of 404) and no
    // `Display`-substring matching (which silently fell through to 500 whenever
    // the error wording changed).
    match resume_managed(&state, &id).await {
        Ok(final_record) => Json(record_to_summary(&final_record)).into_response(),
        Err(e) => e.into_response(),
    }
}

/// POST /api/v1/sessions/managed/{id}/decommission — full teardown.
///
/// Why: the ONLY operation that removes the workspace from disk. Unlike `stop`,
/// decommission is terminal — no further `resume` is possible.
/// What: delegates to SessionManager::decommission (kills runtime, removes
/// workspace dir when owned, marks record Decommissioned). Returns a
/// [`DecommissionResponse`] that includes `workspace_removed` so callers can
/// display an honest message reflecting whether the filesystem was actually
/// mutated (e.g. adopted/local-path workspaces are NEVER deleted).
/// Test: `manager_decommission_removes_workspace`;
/// `decommission_workspace_removed_reflects_ownership`.
pub async fn decommission_managed_session(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    // Pre-fetch the record to obtain the workspace_path BEFORE the tombstone clears
    // it. `decommission` now returns `workspace_removed` directly (no TOCTOU
    // filesystem re-check); `workspace_path_was` for the CLI's `git worktree prune`
    // hint must still be captured here since the tombstone nulls it out.
    let pre = mgr.get(&id).await.ok();
    let pre_owned = pre.as_ref().map(|r| r.workspace_owned).unwrap_or(false);
    let pre_ws = pre.and_then(|r| r.workspace_path);
    match mgr.decommission(&id, None).await {
        Ok((record, workspace_removed)) => {
            // workspace_path_was: only meaningful for owned sessions (those where
            // `decommission_with_root` might have removed the directory).
            let workspace_path_was = if pre_owned {
                pre_ws.map(|p| p.to_string_lossy().into_owned())
            } else {
                None
            };
            Json(DecommissionResponse {
                summary: record_to_summary(&record),
                workspace_removed,
                workspace_path_was,
            })
            .into_response()
        }
        Err(crate::session_manager::ManagedError::SessionNotFound(_)) => {
            (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response()
        }
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    }
}

/// POST /api/v1/sessions/managed/{id}/delete — soft-delete the RECORD, mark `--deleted--` (#2012).
///
/// Why: distinct from `decommission` (stop runtime + maybe remove workspace +
/// `Decommissioned` tombstone) — this marks the record `Deleted` (rendered
/// `--deleted--`) so the operator's master list REFLECTS the deletion instead
/// of the row vanishing, honouring the "fully-tracked lifecycle" standard.
/// Fail-closed: a RUNNING session (`Active`/`Provisioning`) is refused unless
/// `?force=true`.
/// What: parses the id and the `force` query flag, delegates to
/// [`crate::session_manager::SessionManager::delete_record`], and maps its
/// result — `Ok` → 200 with the pre-deletion [`DeleteResponse`] snapshot;
/// `SessionNotFound` → 404; `InvalidState` (the running-guard refusal) → 409
/// with the manager's actionable message; any other error → 500. NEVER
/// touches the workspace directory on disk (see `delete_record`'s doc).
/// Test: `delete_route_marks_deleted`, `delete_route_refuses_running_without_force`,
/// `delete_route_force_bypasses_guard` in managed_routes tests.
pub async fn delete_managed_session(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
    axum::extract::Query(q): axum::extract::Query<DeleteQuery>,
) -> impl IntoResponse {
    let id = match parse_id(&id_str) {
        Ok(id) => id,
        Err((code, msg)) => return (code, msg).into_response(),
    };
    let mgr = state.session_manager().await;
    match mgr.delete_record(&id, q.force).await {
        Ok(record) => Json(DeleteResponse {
            summary: record_to_summary(&record),
            deleted: true,
        })
        .into_response(),
        Err(crate::session_manager::ManagedError::SessionNotFound(_)) => {
            (StatusCode::NOT_FOUND, format!("session {id_str} not found")).into_response()
        }
        Err(crate::session_manager::ManagedError::InvalidState(_, reason)) => {
            (StatusCode::CONFLICT, reason).into_response()
        }
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
    }
}

/// DELETE /api/v1/sessions/managed/{id} — stop and deregister (legacy alias).
///
/// Why: the original MVP wired DELETE to a "stop" that marked the record Dead.
/// The new semantic is `POST /{id}/runtime-stop` (keep workspace) and
/// `POST /{id}/decommission` (full teardown). This handler now delegates to
/// `runtime-stop` (marks Stopped, keeps workspace) so existing scripts that use
/// DELETE do not experience data loss.
/// What: delegates to SessionManager::stop.
/// Test: covered by `stop_managed_session_runtime` tests.
pub async fn stop_managed_session(
    State(state): State<Arc<DaemonState>>,
    AxumPath(id_str): AxumPath<String>,
) -> impl IntoResponse {
    stop_managed_session_runtime(State(state), AxumPath(id_str)).await
}

#[cfg(test)]
mod tests;