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
//! 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 Arc;
use ;
use ;
use crateDaemonState;
use crateRuntimeKind;
use crateManagedSessionId;
use crateProvisioningDirt;
pub
pub
// #94: the per-session file-change view over the hook-event ring buffer.
// #7965: the hygiene sweep's own env gate, host-state refusal and maintenance
// lane — split out of the daemon boot sequence so the bound cannot be lost there.
pub
/// Post-send "did the relaunch actually take?" status check (#6766).
// #8934: spawn in a repository with no `origin` remote (local-only worktrees).
// #6288: `pub` so `rpc::registry::projects` can call the shared `*_op` bodies.
// #6288: `pub` so `rpc::registry::projects` can call `project_status_op`.
// #9313: `tm sessions rebind`.
// #7087: the `mpm.residency.active` producer route.
pub
// #6497: the explicit ownership transfer for a dead owner's worktree.
// #8942: `tm fleet init` registers the Architect's sessions.
// #8233 item 1: the resume claim's span across `resume_managed`.
// #8983: the resume grant across both daemon resume paths.
pub
pub
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ResumeManagedError;
pub use SessionSummary;
pub use record_to_json;
use ;
// ── 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_*`.
/// 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.
/// 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.
/// 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.
/// 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.
/// A store read failure disclosed alongside a degraded list response (#5007).
///
/// Why: see [`ListSessionsResponse::store_health`].
/// What: the rendered error, whether the file is corrupt (permanent) rather
/// than merely unreadable (possibly transient), and when it was observed.
/// Test: `list_response_omits_store_health_when_healthy`.
// `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.
// #7660 owner ruling 2026-09-24: a later field is not a semver break.
/// 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.
/// 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.
/// Response body for POST /api/v1/sessions/managed/{id}/runtime-stop.
///
/// Why (#8935): a stop whose record's tmux name now belongs to another
/// session moves the record only. The caller must be told the live session
/// was left running, not that the runtime stopped.
/// What: the post-stop [`SessionSummary`], flattened so the body keeps its
/// pre-#8935 shape, plus `runtime_left_running` when nothing was signalled.
/// Test: `the_stop_report_says_the_runtime_was_left_running` (the report it carries).
/// 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.
/// 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.
/// 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.
/// 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.
/// 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.
// ── 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) resolves the session's workspace (ADR-0055: an existing local one)
/// (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
/// 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
/// 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. The optional `?slim=true` (or
/// `slim=1`) query parameter (#4335, folds into #4322) skips the expensive
/// per-session `stale_assets` probe for callers that never read that flag —
/// every `stale_assets` then reports its `false` default, meaning "not
/// computed", so only such a caller may pass it. Anything else (absent,
/// `slim=false`, malformed) keeps the full probe.
/// Test: list handler test; list-with-source-id-filter test;
/// `checked_summaries_slim_skips_stale_assets_probe`;
/// `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
/// 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
/// 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
/// 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
/// 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
/// 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
/// 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
/// Query parameters for POST /api/v1/sessions/managed/{id}/decommission
/// (owner request 2026-07-29, critic HIGH finding #1).
///
/// Why: the `tm ls`/bare `tm` auto-prune sweep must be structurally incapable
/// of removing filesystem content — a remount between its listing-time probe
/// and this call could otherwise reach a real `remove_dir_all`. Rather than
/// trust every future caller to re-check, the route itself routes to a
/// removal-free teardown when asked.
/// What: `record_only` (default `false`, `#[serde(default)]` keeps every
/// existing caller's plain POST unaffected) selects
/// [`SessionManager::decommission_record_only`](crate::session_manager::SessionManager::decommission_record_only) instead of
/// [`SessionManager::decommission`](crate::session_manager::decommission).
/// Test: `decommission_record_only_never_removes_existing_workspace`
/// (`session_manager::tests`).
/// 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) — or, when
/// `?record_only=true`, to [`SessionManager::decommission_record_only`](crate::session_manager::SessionManager::decommission_record_only)
/// (never touches disk). 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`;
/// `decommission_record_only_never_removes_existing_workspace`.
pub async
/// Map the wire's `force` flag onto the decommission dirt policy (#7660).
pub