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
//! Claude Code configuration analyzer HTTP routes.
//!
//! Why: the daemon's Claude Code config endpoints — analyze, apply a
//! recommendation, checkpoint / restore / delete, list and deploy profiles,
//! restart — form a cohesive cluster that, kept inline in `api.rs`, dominated
//! the file. Splitting them into their own route module keeps `api.rs` focused
//! on the core session / hook / tmux surface.
//! What: the `#[utoipa::path]`-annotated handlers for the `/claude-config/*`
//! endpoints, plus their request/query structs. They are wired into the router
//! by `api::router` and registered in the OpenAPI document by `openapi.rs`.
//! Test: `cargo test -p trusty-mpm-daemon` drives these via the `api_tests`
//! module, which references them through `crate::daemon::api::claude_config_routes::*`.

use std::path::PathBuf;
use std::sync::Arc;

use axum::{
    Json,
    extract::{Path, Query, State},
    http::StatusCode,
};

use crate::daemon::api::types::{
    ApplyConfigResponse, CheckpointsResponse, ClaudeConfigResponse, CreateCheckpointResponse,
    DeleteCheckpointResponse, DeployProfileResponse, ProfilesResponse, RestartResponse,
    RestoreResponse,
};
use crate::daemon::error::DaemonError;
use crate::daemon::state::DaemonState;
use crate::session_manager::record::{ManagedSessionState, SessionRecord};

// ---- Claude Code configuration analyzer ---------------------------------

/// Query parameters for `GET /claude-config`.
///
/// Why: the analyzer inspects the config for a specific project directory.
/// What: the absolute project path to analyze.
/// Test: `get_claude_config_returns_recommendations`.
#[derive(serde::Deserialize)]
pub struct ClaudeConfigQuery {
    /// Project directory whose Claude Code config to analyze.
    pub project: PathBuf,
}

/// `GET /claude-config?project=<path>` — analyze Claude Code config.
///
/// Why: trusty-mpm can recommend config changes (hooks, permission scoping,
/// agent deployment) for a project's Claude Code setup.
/// What: resolves the user- and project-level config paths, reads and merges
/// them, and returns `{ config, recommendations }`.
/// Test: `get_claude_config_returns_recommendations`.
#[utoipa::path(
    get,
    path = "/claude-config",
    tag = "claude-config",
    params(("project" = String, Query, description = "Project directory")),
    responses((status = 200, description = "Analyzed config plus recommendations"))
)]
pub async fn get_claude_config(
    State(state): State<Arc<DaemonState>>,
    Query(query): Query<ClaudeConfigQuery>,
) -> Json<ClaudeConfigResponse> {
    Json(get_claude_config_op(&state, query))
}

/// Transport-neutral body of `GET /claude-config` and `mpm.claude_config.get`
/// (#6288).
///
/// Test: `get_claude_config_returns_recommendations`,
/// `parity_claude_config_get_agrees_across_transports`.
pub fn get_claude_config_op(
    _state: &Arc<DaemonState>,
    query: ClaudeConfigQuery,
) -> ClaudeConfigResponse {
    use crate::core::claude_config::ClaudeConfigReader;
    let paths = ClaudeConfigReader::paths_for_project(&query.project);
    let config = crate::daemon::claude_config::ClaudeConfigAnalyzer::read_config(&paths);
    let recommendations = crate::daemon::claude_config::ClaudeConfigAnalyzer::analyze(&config);
    ClaudeConfigResponse {
        config,
        recommendations,
    }
}

/// JSON body for `POST /claude-config/apply`.
///
/// Why: applying a recommendation needs the project path and the rec id.
/// What: the project directory and the recommendation id to apply.
/// Test: `apply_claude_config_unknown_rec_is_404`.
#[derive(serde::Deserialize, utoipa::ToSchema)]
pub struct ApplyConfigRequest {
    /// Project directory the recommendation applies to.
    #[schema(value_type = String)]
    pub project: PathBuf,
    /// Id of the recommendation to apply.
    pub recommendation_id: String,
}

/// `POST /claude-config/apply` — apply a Claude Code config recommendation.
///
/// Why: lets an operator act on a recommendation without hand-editing JSON.
/// What: re-analyzes the project, finds the recommendation by id, and applies
/// it via `ClaudeConfigAnalyzer::apply_recommendation`, which checkpoints the
/// config first. Returns `{ applied: true, checkpoint_id }` so the caller can
/// undo. An unknown id is `404`.
/// Test: `apply_claude_config_unknown_rec_is_404`.
#[utoipa::path(
    post,
    path = "/claude-config/apply",
    tag = "claude-config",
    request_body = ApplyConfigRequest,
    responses(
        (status = 200, description = "Recommendation applied; returns checkpoint id"),
        (status = 404, description = "No recommendation with that id"),
        (status = 500, description = "Applying the recommendation failed"),
    )
)]
pub async fn apply_claude_config(
    State(state): State<Arc<DaemonState>>,
    Json(body): Json<ApplyConfigRequest>,
) -> Result<Json<ApplyConfigResponse>, StatusCode> {
    apply_claude_config_op(&state, body)
        .map(Json)
        .map_err(|e| e.status())
}

/// Transport-neutral body of `POST /claude-config/apply` and
/// `mpm.claude_config.apply` (#6288).
///
/// # Errors
///
/// [`DaemonError::NotFound`] when no recommendation carries that id (HTTP 404),
/// [`DaemonError::Internal`] when applying it fails (HTTP 500).
///
/// Test: `apply_claude_config_unknown_rec_is_404`,
/// `rpc_claude_config_apply_unknown_recommendation_reports_not_found`.
pub fn apply_claude_config_op(
    _state: &Arc<DaemonState>,
    body: ApplyConfigRequest,
) -> Result<ApplyConfigResponse, DaemonError> {
    use crate::core::claude_config::ClaudeConfigReader;
    let paths = ClaudeConfigReader::paths_for_project(&body.project);
    let config = crate::daemon::claude_config::ClaudeConfigAnalyzer::read_config(&paths);
    let recommendations = crate::daemon::claude_config::ClaudeConfigAnalyzer::analyze(&config);
    let rec = recommendations
        .iter()
        .find(|r| r.id == body.recommendation_id)
        .ok_or_else(|| {
            DaemonError::NotFound(format!("recommendation `{}`", body.recommendation_id))
        })?;
    let checkpoint_id = crate::daemon::claude_config::ClaudeConfigAnalyzer::apply_recommendation(
        rec,
        &paths,
        &body.project,
    )
    .map_err(|e| {
        tracing::warn!("applying recommendation {} failed: {e}", rec.id);
        DaemonError::Internal(format!("applying recommendation {} failed: {e}", rec.id))
    })?;
    Ok(ApplyConfigResponse {
        applied: true,
        recommendation_id: body.recommendation_id,
        checkpoint_id,
    })
}

// ---- checkpoints & deployment profiles ----------------------------------

/// Query parameters for the checkpoint list / delete endpoints.
///
/// Why: checkpoints are project-scoped; the project path identifies which
/// `.trusty-mpm/checkpoints` directory to operate on.
/// What: the project directory.
/// Test: `list_checkpoints_returns_array`.
#[derive(serde::Deserialize)]
pub struct CheckpointQuery {
    /// Project directory whose checkpoints to operate on.
    pub project: PathBuf,
}

/// `GET /claude-config/checkpoints?project=<path>` — list config checkpoints.
///
/// Why: the dashboard offers a restore picker; this feeds it.
/// What: returns `{ checkpoints: [ConfigCheckpoint, ...] }`, newest first.
/// Test: `list_checkpoints_returns_array`.
#[utoipa::path(
    get,
    path = "/claude-config/checkpoints",
    tag = "claude-config",
    params(("project" = String, Query, description = "Project directory")),
    responses((status = 200, description = "Config checkpoints, newest first"))
)]
pub async fn list_checkpoints(
    State(state): State<Arc<DaemonState>>,
    Query(query): Query<CheckpointQuery>,
) -> Json<CheckpointsResponse> {
    Json(list_checkpoints_op(&state, query))
}

/// Transport-neutral body of `GET /claude-config/checkpoints` and
/// `mpm.claude_config.checkpoints.list` (#6288).
///
/// Test: `list_checkpoints_returns_array`,
/// `parity_claude_config_checkpoints_agrees_across_transports`.
pub fn list_checkpoints_op(
    _state: &Arc<DaemonState>,
    query: CheckpointQuery,
) -> CheckpointsResponse {
    let checkpoints = crate::daemon::claude_config::ConfigCheckpointer::list(&query.project)
        .unwrap_or_else(|e| {
            tracing::warn!("listing checkpoints failed: {e}");
            Vec::new()
        });
    CheckpointsResponse { checkpoints }
}

/// JSON body for `POST /claude-config/checkpoints`.
///
/// Why: creating a checkpoint needs the project and an optional human label.
/// What: the project directory and an optional label.
/// Test: `create_checkpoint_returns_id`.
#[derive(serde::Deserialize, utoipa::ToSchema)]
pub struct CreateCheckpointRequest {
    /// Project directory to checkpoint.
    #[schema(value_type = String)]
    pub project: PathBuf,
    /// Optional human-readable label for the checkpoint.
    #[serde(default)]
    pub label: Option<String>,
}

/// `POST /claude-config/checkpoints` — create a config checkpoint.
///
/// Why: lets the operator take a manual backup before a risky change.
/// What: snapshots the project's config and returns `{ id }`.
/// Test: `create_checkpoint_returns_id`.
#[utoipa::path(
    post,
    path = "/claude-config/checkpoints",
    tag = "claude-config",
    request_body = CreateCheckpointRequest,
    responses(
        (status = 200, description = "Checkpoint created; returns its id"),
        (status = 500, description = "Creating the checkpoint failed"),
    )
)]
pub async fn create_checkpoint(
    State(state): State<Arc<DaemonState>>,
    Json(body): Json<CreateCheckpointRequest>,
) -> Result<Json<CreateCheckpointResponse>, StatusCode> {
    create_checkpoint_op(&state, body)
        .map(Json)
        .map_err(|e| e.status())
}

/// Transport-neutral body of `POST /claude-config/checkpoints` and
/// `mpm.claude_config.checkpoints.create` (#6288).
///
/// # Errors
///
/// [`DaemonError::Internal`] when the snapshot cannot be written (HTTP 500).
///
/// Test: `create_checkpoint_returns_id`.
pub fn create_checkpoint_op(
    _state: &Arc<DaemonState>,
    body: CreateCheckpointRequest,
) -> Result<CreateCheckpointResponse, DaemonError> {
    use crate::core::claude_config::ClaudeConfigReader;
    let paths = ClaudeConfigReader::paths_for_project(&body.project);
    let id = crate::daemon::claude_config::ConfigCheckpointer::create(
        &paths,
        &body.project,
        body.label.as_deref(),
    )
    .map_err(|e| {
        tracing::warn!("creating checkpoint failed: {e}");
        DaemonError::Internal(format!("creating checkpoint failed: {e}"))
    })?;
    Ok(CreateCheckpointResponse { id })
}

/// JSON body for `POST /claude-config/restore`.
///
/// Why: restoring needs the project and the checkpoint id to revert to.
/// What: the project directory and the checkpoint id.
/// Test: `restore_unknown_checkpoint_is_500`.
#[derive(serde::Deserialize, utoipa::ToSchema)]
pub struct RestoreRequest {
    /// Project directory whose config to restore.
    #[schema(value_type = String)]
    pub project: PathBuf,
    /// Id of the checkpoint to restore.
    pub checkpoint_id: String,
}

/// `POST /claude-config/restore` — restore config from a checkpoint.
///
/// Why: the undo half of the safety model.
/// What: rewrites the project's config files to the checkpoint's state. A
/// missing or malformed checkpoint surfaces as `500`.
/// Test: `restore_unknown_checkpoint_is_500`.
#[utoipa::path(
    post,
    path = "/claude-config/restore",
    tag = "claude-config",
    request_body = RestoreRequest,
    responses(
        (status = 200, description = "Config restored from the checkpoint"),
        (status = 500, description = "Checkpoint missing or restore failed"),
    )
)]
pub async fn restore_checkpoint(
    State(state): State<Arc<DaemonState>>,
    Json(body): Json<RestoreRequest>,
) -> Result<Json<RestoreResponse>, StatusCode> {
    restore_checkpoint_op(&state, body)
        .map(Json)
        .map_err(|e| e.status())
}

/// Transport-neutral body of `POST /claude-config/restore` and
/// `mpm.claude_config.restore` (#6288).
///
/// # Errors
///
/// [`DaemonError::Internal`] when the checkpoint is missing or the rewrite
/// fails — HTTP 500, the status this route has always answered for both.
///
/// Test: `restore_unknown_checkpoint_is_500`.
pub fn restore_checkpoint_op(
    _state: &Arc<DaemonState>,
    body: RestoreRequest,
) -> Result<RestoreResponse, DaemonError> {
    crate::daemon::claude_config::ConfigCheckpointer::restore(&body.project, &body.checkpoint_id)
        .map_err(|e| {
        tracing::warn!("restoring checkpoint {} failed: {e}", body.checkpoint_id);
        DaemonError::Internal(format!(
            "restoring checkpoint {} failed: {e}",
            body.checkpoint_id
        ))
    })?;
    Ok(RestoreResponse {
        restored: true,
        checkpoint_id: body.checkpoint_id,
    })
}

/// `DELETE /claude-config/checkpoints/{id}?project=<path>` — delete a checkpoint.
///
/// Why: checkpoints accumulate; the operator prunes them here.
/// What: removes the checkpoint file. A missing checkpoint surfaces as `404`.
/// Test: `delete_unknown_checkpoint_is_404`.
#[utoipa::path(
    delete,
    path = "/claude-config/checkpoints/{id}",
    tag = "claude-config",
    params(
        ("id" = String, Path, description = "Checkpoint id"),
        ("project" = String, Query, description = "Project directory"),
    ),
    responses(
        (status = 200, description = "Checkpoint deleted"),
        (status = 404, description = "No checkpoint with that id"),
    )
)]
pub async fn delete_checkpoint(
    State(state): State<Arc<DaemonState>>,
    Path(id): Path<String>,
    Query(query): Query<CheckpointQuery>,
) -> Result<Json<DeleteCheckpointResponse>, StatusCode> {
    delete_checkpoint_op(
        &state,
        DeleteCheckpointParams {
            project: query.project,
            id,
        },
    )
    .map(Json)
    .map_err(|e| e.status())
}

/// The two arguments `DELETE /claude-config/checkpoints/{id}` splits across a
/// path segment and a query string, carried as one decoded value (#6288).
///
/// Why a struct rather than two parameters: the socket carries one `params`
/// object per call, so the RPC method needs a single type to decode into, and
/// giving the shared body that shape keeps one signature for both transports.
#[derive(serde::Deserialize)]
pub struct DeleteCheckpointParams {
    /// Project directory whose checkpoint is being deleted.
    pub project: PathBuf,
    /// Id of the checkpoint to delete.
    pub id: String,
}

/// Transport-neutral body of `DELETE /claude-config/checkpoints/{id}` and
/// `mpm.claude_config.checkpoints.delete` (#6288).
///
/// # Errors
///
/// [`DaemonError::CheckpointNotFound`] when the checkpoint cannot be removed —
/// HTTP 404, the status this route has always answered for every failure here.
///
/// Test: `delete_unknown_checkpoint_is_404`.
pub fn delete_checkpoint_op(
    _state: &Arc<DaemonState>,
    params: DeleteCheckpointParams,
) -> Result<DeleteCheckpointResponse, DaemonError> {
    crate::daemon::claude_config::ConfigCheckpointer::delete(&params.project, &params.id).map_err(
        |e| {
            tracing::warn!("deleting checkpoint {} failed: {e}", params.id);
            DaemonError::CheckpointNotFound {
                id: params.id.clone(),
            }
        },
    )?;
    Ok(DeleteCheckpointResponse { deleted: params.id })
}

/// `GET /claude-config/profiles` — list the built-in deployment profiles.
///
/// Why: the dashboard shows the available configuration presets.
/// What: returns `{ profiles: [DeploymentProfile, ...] }`.
/// Test: `list_profiles_returns_builtins`.
#[utoipa::path(
    get,
    path = "/claude-config/profiles",
    tag = "claude-config",
    responses((status = 200, description = "Built-in deployment profiles"))
)]
pub async fn list_profiles(State(state): State<Arc<DaemonState>>) -> Json<ProfilesResponse> {
    Json(list_profiles_op(&state))
}

/// Transport-neutral body of `GET /claude-config/profiles` and
/// `mpm.claude_config.profiles` (#6288).
///
/// Test: `list_profiles_returns_builtins`,
/// `parity_claude_config_profiles_agrees_across_transports`.
pub fn list_profiles_op(_state: &Arc<DaemonState>) -> ProfilesResponse {
    let profiles = crate::daemon::claude_config::ProfileDeployer::builtin_profiles();
    ProfilesResponse { profiles }
}

/// JSON body for `POST /claude-config/deploy`.
///
/// Why: deploying a profile needs the project, the profile name, and an
/// optional target override.
/// What: the project directory, the profile name, and an optional deploy
/// target (`user`, `project`, `both`) overriding the profile's default.
/// Test: `deploy_profile_returns_checkpoint_id`.
#[derive(serde::Deserialize, utoipa::ToSchema)]
pub struct DeployProfileRequest {
    /// Project directory to deploy the profile onto.
    #[schema(value_type = String)]
    pub project: PathBuf,
    /// Name of the built-in profile to deploy.
    pub profile_name: String,
    /// Optional deploy-target override (`user`, `project`, `both`).
    #[serde(default)]
    pub target: Option<crate::core::claude_config::DeployTarget>,
}

/// `POST /claude-config/deploy` — deploy a built-in profile onto a project.
///
/// Why: lets the operator apply a configuration preset in one click; the deploy
/// checkpoints the config first so it is reversible.
/// What: looks up the named built-in profile (applying an optional `target`
/// override), deploys it, and returns `{ checkpoint_id }`. An unknown profile
/// name is `404`.
/// Test: `deploy_profile_returns_checkpoint_id`, `deploy_unknown_profile_is_404`.
#[utoipa::path(
    post,
    path = "/claude-config/deploy",
    tag = "claude-config",
    request_body = DeployProfileRequest,
    responses(
        (status = 200, description = "Profile deployed; returns checkpoint id"),
        (status = 404, description = "No built-in profile with that name"),
        (status = 500, description = "Deploying the profile failed"),
    )
)]
pub async fn deploy_profile(
    State(state): State<Arc<DaemonState>>,
    Json(body): Json<DeployProfileRequest>,
) -> Result<Json<DeployProfileResponse>, StatusCode> {
    deploy_profile_op(&state, body)
        .map(Json)
        .map_err(|e| e.status())
}

/// Transport-neutral body of `POST /claude-config/deploy` and
/// `mpm.claude_config.deploy` (#6288).
///
/// # Errors
///
/// [`DaemonError::NotFound`] when no built-in profile carries that name (HTTP
/// 404), [`DaemonError::Internal`] when the deploy fails (HTTP 500).
///
/// Test: `deploy_profile_returns_checkpoint_id`, `deploy_unknown_profile_is_404`,
/// `rpc_claude_config_deploy_unknown_profile_reports_not_found`.
pub fn deploy_profile_op(
    _state: &Arc<DaemonState>,
    body: DeployProfileRequest,
) -> Result<DeployProfileResponse, DaemonError> {
    use crate::core::claude_config::ClaudeConfigReader;
    let mut profile = crate::daemon::claude_config::ProfileDeployer::builtin_profiles()
        .into_iter()
        .find(|p| p.name == body.profile_name)
        .ok_or_else(|| DaemonError::NotFound(format!("profile `{}`", body.profile_name)))?;
    if let Some(target) = body.target {
        profile.target = target;
    }
    let paths = ClaudeConfigReader::paths_for_project(&body.project);
    let checkpoint_id =
        crate::daemon::claude_config::ProfileDeployer::deploy(&profile, &paths, &body.project)
            .map_err(|e| {
                tracing::warn!("deploying profile {} failed: {e}", body.profile_name);
                DaemonError::Internal(format!(
                    "deploying profile {} failed: {e}",
                    body.profile_name
                ))
            })?;
    Ok(DeployProfileResponse {
        deployed: body.profile_name,
        checkpoint_id,
    })
}

/// JSON body for `POST /claude-config/restart`.
///
/// Why: restarting Claude Code happens inside a named tmux session.
/// What: the tmux session in which to restart `claude`.
/// Test: `restart_claude_code_handles_missing_tmux`.
#[derive(serde::Deserialize, utoipa::ToSchema)]
pub struct RestartRequest {
    /// tmux session in which to restart Claude Code.
    pub tmux_session: String,
}

/// Select the `pane_id` to restart into from the full managed-session record
/// set, given the target tmux session name (#2514 review, minor finding 4).
///
/// Why: `tmux_name` is recycled once a session is decommissioned — a fresh
/// session provisioned later can be assigned the SAME tmux name a
/// decommissioned record used. A naive `.find(|r| r.tmux_name == name)` over
/// the full record list can therefore match the stale, decommissioned
/// tombstone instead of the live record, silently threading a dead/garbage
/// `pane_id` (or a `None` that masks a real one) into the restart call.
/// What: filters to records matching `tmux_session` whose state is NOT
/// `Decommissioned` (the terminal, unresumable state — see
/// [`ManagedSessionState`]'s doc), then — since more than one non-terminal
/// record can theoretically share a recycled name during a narrow
/// provisioning race — prefers the most recently created match. Returns
/// `None` when no live record matches (unmanaged/legacy session name) or the
/// surviving record never captured a `pane_id`; the session-scoped restart
/// fallback then applies exactly as before #2468.
/// #9101: returns the record, not its pane id, so the caller can prove the
/// pane is the record's on the live server before typing into it.
/// Test: `select_restart_pane_id_skips_decommissioned_record`,
/// `select_restart_pane_id_prefers_most_recent_when_multiple_live_match`,
/// `select_restart_pane_id_none_when_no_match`.
fn select_restart_record<'a>(
    records: &'a [SessionRecord],
    tmux_session: &str,
) -> Option<&'a SessionRecord> {
    records
        .iter()
        .filter(|r| r.tmux_name == tmux_session)
        .filter(|r| !matches!(r.state, ManagedSessionState::Decommissioned))
        .max_by_key(|r| r.created_at)
}

/// The pane the restart types into for `tmux_session` (#9101).
///
/// What: `Ok(None)` when no live managed record carries the name (an
/// unmanaged session, restarted session-scoped as before #2468). For a
/// managed record, `SessionManager::owned_pane`'s pane, or its refusal as
/// [`DaemonError::SessionNotActive`] (409): a record with no pane id, a pane
/// on another tmux server, or an identity that cannot be read never gets a
/// restart.
/// Test: `a_stale_record_after_a_server_restart_never_gets_a_claude_restart`,
/// `an_unreadable_pane_identity_refuses_the_claude_restart`.
async fn restart_pane_for(
    state: &Arc<DaemonState>,
    tmux_session: &str,
) -> Result<Option<String>, DaemonError> {
    let mgr = state.session_manager().await;
    let records = mgr.list().await;
    let Some(record) = select_restart_record(&records, tmux_session) else {
        return Ok(None);
    };
    mgr.owned_pane(&record.id, record).map(Some).map_err(|e| {
        tracing::warn!("restart in {tmux_session} refused: {e}");
        // #9101: a 409, as the reactivate route answers an unproven pane.
        DaemonError::SessionNotActive {
            id: tmux_session.to_owned(),
            status: format!("restart refused: {e}"),
        }
    })
}

/// `POST /claude-config/restart` — restart Claude Code in a tmux session.
///
/// Why: after applying config changes the operator wants a clean Claude Code
/// process; this sends Ctrl-C then `claude` into the session's pane. The
/// managed-session record's `pane_id`, when one is tracked for this tmux
/// session, is threaded through so the restart lands in the record's OWN
/// pane rather than tmux's session-scoped "active pane" resolution — the
/// same sibling-window hijack risk #2467 fixed for resume/restart respawn
/// (issue #2468).
/// What: looks up `body.tmux_session` against the managed-session store via
/// [`select_restart_record`], which excludes decommissioned (tombstone)
/// records and prefers the most recently created live match — a recycled
/// `tmux_name` can otherwise resolve to a stale decommissioned record (#2514
/// review). `None` (unmanaged/legacy session, or no matching live record)
/// falls back to the session-scoped restart exactly as before #2468. #9101:
/// a matched record's pane must pass [`restart_pane_for`]'s ownership gate.
/// Then calls `ClaudeCodeRestarter::restart_in_session`. tmux being absent
/// or a confirmed-gone recorded pane surface as `500`; an unproven pane is
/// `409`.
/// Test: `restart_claude_code_handles_missing_tmux`;
/// `ClaudeCodeRestarter::restart_target`'s pane/session decision is
/// unit-tested directly in `daemon::claude_config::restarter`;
/// [`select_restart_record`]'s own unit tests cover the stale-record fix.
#[utoipa::path(
    post,
    path = "/claude-config/restart",
    tag = "claude-config",
    request_body = RestartRequest,
    responses(
        (status = 200, description = "Restart command sent"),
        (status = 409, description = "the recorded pane is not proven the record's own"),
        (status = 500, description = "tmux unavailable or restart failed"),
    )
)]
pub async fn restart_claude_code(
    State(state): State<Arc<DaemonState>>,
    Json(body): Json<RestartRequest>,
) -> Result<Json<RestartResponse>, StatusCode> {
    restart_claude_code_op(&state, body)
        .await
        .map(Json)
        .map_err(|e| e.status())
}

/// Transport-neutral body of `POST /claude-config/restart` and
/// `mpm.claude_config.restart` (#6288).
///
/// # Errors
///
/// [`DaemonError::InvalidRequest`] (HTTP 400) for an empty `tmux_session`
/// (#8443: it used to render `=:`, which tmux resolves to the current
/// session). [`DaemonError::Internal`] when tmux is absent, or the recorded
/// pane is confirmed gone or not proven the record's (#9101) (HTTP 500).
///
/// Test: `restart_claude_code_handles_missing_tmux`,
/// `restart_route_rejects_an_empty_tmux_session`.
pub async fn restart_claude_code_op(
    state: &Arc<DaemonState>,
    body: RestartRequest,
) -> Result<RestartResponse, DaemonError> {
    crate::core::tmux::check_session_name(&body.tmux_session)
        .map_err(|e| DaemonError::InvalidRequest(e.to_string()))?;
    let pane_id = restart_pane_for(state, &body.tmux_session).await?;
    crate::daemon::claude_config::ClaudeCodeRestarter::restart_in_session(
        &body.tmux_session,
        pane_id.as_deref(),
    )
    .map_err(|e| {
        tracing::warn!("restart in {} failed: {e}", body.tmux_session);
        DaemonError::Internal(format!("restart in {} failed: {e}", body.tmux_session))
    })?;
    Ok(RestartResponse {
        restarted: body.tmux_session,
    })
}

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

    /// #8443 critic HIGH: an empty `tmux_session` is a 400, never a restart
    /// typed into whichever session `=:` resolves to.
    #[tokio::test]
    async fn restart_route_rejects_an_empty_tmux_session() {
        let dir = tempfile::tempdir().expect("temp dir");
        let paths = crate::core::paths::FrameworkPaths::under(dir.path());
        let state = Arc::new(DaemonState::with_paths(&paths));
        for name in ["", "=", "  "] {
            let status = restart_claude_code(
                State(state.clone()),
                Json(RestartRequest {
                    tmux_session: name.to_string(),
                }),
            )
            .await
            .err();
            assert_eq!(status, Some(StatusCode::BAD_REQUEST), "{name:?}");
        }
    }
    use crate::session_manager::record::ManagedSessionId;

    /// Builds a minimal, otherwise-default [`SessionRecord`] for the pure
    /// selection-fn tests below — only `tmux_name`, `state`, `pane_id`, and
    /// `created_at` matter to [`select_restart_record`].
    fn make_record(
        tmux_name: &str,
        state: ManagedSessionState,
        pane_id: Option<&str>,
        created_at: chrono::DateTime<chrono::Utc>,
    ) -> SessionRecord {
        SessionRecord {
            id: ManagedSessionId::new(),
            tmux_name: tmux_name.to_string(),
            cwd: PathBuf::from("/tmp"),
            task: "task".to_string(),
            state,
            created_at,
            last_activity_at: None,
            workspace_path: None,
            repo_url: None,
            branch: None,
            pending_decision: None,
            proposed_default: None,
            correlation: crate::driver::SessionCorrelation::new(),
            runtime: crate::runtime::RuntimeKind::default(),
            ephemeral: true,
            workspace_owned: false,
            source_id: None,
            claude_session_id: None,
            scrollback_path: None,
            last_cwd: None,
            deliverable_id: None,
            pane_id: pane_id.map(str::to_owned),
            tmux_server: None,
            injection_status: Default::default(),
            worktree_owner: None,
            terminal_at: None,
            stop_cause: None,
            kind: Default::default(),
        }
    }

    #[test]
    fn select_restart_pane_id_skips_decommissioned_record() {
        // A decommissioned record's tmux_name has been recycled by a live
        // record; the stale tombstone must never win.
        let now = chrono::Utc::now();
        let stale = make_record(
            "tmpm-proj-1",
            ManagedSessionState::Decommissioned,
            Some("%old"),
            now - chrono::Duration::hours(1),
        );
        let live = make_record(
            "tmpm-proj-1",
            ManagedSessionState::Active,
            Some("%new"),
            now,
        );
        let records = vec![stale, live];

        assert_eq!(
            select_restart_record(&records, "tmpm-proj-1").and_then(|r| r.pane_id.clone()),
            Some("%new".to_string())
        );
    }

    #[test]
    fn select_restart_pane_id_prefers_most_recent_when_multiple_live_match() {
        let now = chrono::Utc::now();
        let older = make_record(
            "tmpm-proj-1",
            ManagedSessionState::Stopped,
            Some("%older"),
            now - chrono::Duration::minutes(5),
        );
        let newer = make_record(
            "tmpm-proj-1",
            ManagedSessionState::Active,
            Some("%newer"),
            now,
        );
        let records = vec![older, newer];

        assert_eq!(
            select_restart_record(&records, "tmpm-proj-1").and_then(|r| r.pane_id.clone()),
            Some("%newer".to_string())
        );
    }

    #[test]
    fn select_restart_pane_id_none_when_no_match() {
        let now = chrono::Utc::now();
        let records = vec![make_record(
            "tmpm-other",
            ManagedSessionState::Active,
            Some("%x"),
            now,
        )];

        assert!(select_restart_record(&records, "tmpm-proj-1").is_none());
    }
}