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
use super::*;
use std::future::IntoFuture;

/// Spawn the daemon's real HTTP API on a random loopback port.
///
/// Why: lets the executor be tested against the genuine daemon routes
/// without a live daemon, tmux, or external network.
/// What: builds `api::router(DaemonState::with_root_isolated_managed(...))`,
/// binds an ephemeral port, serves it on a background task, and returns the
/// state plus base URL. The managed-session store is rooted in a throwaway
/// temp directory and backed by a no-op tmux driver so `reconcile_on_boot`
/// never adopts the operator's live `tmpm-*` sessions into the test store
/// (#1734). The framework root (pairing, audit log) is also pointed at the
/// temp dir so tests never read or write the operator's real `~/.trusty-mpm`.
/// Test: used by the `execute_*` tests below.
async fn spawn_test_daemon() -> (std::sync::Arc<crate::daemon::state::DaemonState>, String) {
    use crate::daemon::{api, state::DaemonState};
    // `keep` converts TempDir into a PathBuf that persists beyond this scope
    // so the directory outlives the background server task.
    let root = tempfile::tempdir().unwrap().keep();
    let state = std::sync::Arc::new(DaemonState::with_root_isolated_managed(root).await);
    let router = api::router(std::sync::Arc::clone(&state));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(axum::serve(listener, router).into_future());
    (state, format!("http://{addr}"))
}

#[tokio::test]
async fn execute_help_returns_help() {
    // The `/help` path is pure — no HTTP, no daemon.
    let executor = CommandExecutor::new("http://unused");
    match executor.execute(TrustyCommand::Help).await {
        CommandResult::Help(text) => assert!(text.contains("/sessions")),
        other => panic!("expected Help, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_sessions_against_test_daemon() {
    // With one registered session, `/sessions` returns exactly that summary.
    use crate::core::session::{ControlModel, Session, SessionId, SessionStatus};
    let (state, url) = spawn_test_daemon().await;
    let mut session = Session::new(SessionId::new(), "/tmp/proj", ControlModel::Tmux, None);
    session.status = SessionStatus::Active;
    state.register_session(session);

    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::Sessions).await {
        CommandResult::Sessions(list) => {
            assert_eq!(list.len(), 1);
            assert_eq!(list[0].workdir, "/tmp/proj");
        }
        other => panic!("expected Sessions, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_kill_returns_killed() {
    // Registering a session then killing it yields `Killed`.
    use crate::core::session::{ControlModel, Session, SessionId, SessionStatus};
    let (state, url) = spawn_test_daemon().await;
    let id = SessionId::new();
    let mut session = Session::new(id, "/tmp/proj", ControlModel::Tmux, None);
    session.status = SessionStatus::Active;
    state.register_session(session);

    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Kill {
            session_id: id.0.to_string(),
        })
        .await
    {
        CommandResult::Killed { session_id } => assert_eq!(session_id, id.0.to_string()),
        other => panic!("expected Killed, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_kill_unknown_session_errors() {
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Kill {
            session_id: uuid::Uuid::new_v4().to_string(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("not found")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_approve_unknown_session_errors() {
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Approve {
            session_id: uuid::Uuid::new_v4().to_string(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("not found")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_approve_known_session() {
    use crate::core::session::{ControlModel, Session, SessionId, SessionStatus};
    let (state, url) = spawn_test_daemon().await;
    let id = SessionId::new();
    let mut session = Session::new(id, "/tmp/proj", ControlModel::Tmux, None);
    session.status = SessionStatus::Active;
    state.register_session(session);

    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Approve {
            session_id: id.0.to_string(),
        })
        .await
    {
        CommandResult::Approved { session_id } => assert_eq!(session_id, id.0.to_string()),
        other => panic!("expected Approved, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_projects_against_test_daemon() {
    // `/projects` returns a well-formed (possibly empty) discovered list.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::Projects).await {
        CommandResult::DiscoveredProjects(list) => {
            for p in &list {
                assert!(!p.path.is_empty());
            }
        }
        other => panic!("expected DiscoveredProjects, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_discover_against_test_daemon() {
    // `/discover` returns a well-formed count (zero when tmux is absent on
    // CI), never an error against a live daemon.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::Discover).await {
        CommandResult::Discovered { count } => {
            // Count is a usize; the call simply must succeed.
            let _ = count;
        }
        other => panic!("expected Discovered, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_adopt_unknown_session_errors() {
    // Adopting a session that does not exist (or with tmux unavailable on
    // CI) reports an error rather than a success.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Adopt {
            session: "no-such-session-xyz".into(),
        })
        .await
    {
        CommandResult::Error(_) => {}
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn register_project_succeeds() {
    // The `[Set Active]` flow registers a project by path.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.register_project("/work/discovered-demo").await {
        CommandResult::ProjectRegistered { path } => {
            assert_eq!(path, "/work/discovered-demo");
        }
        other => panic!("expected ProjectRegistered, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_doctor_against_test_daemon() {
    // `/doctor` returns a twenty-one-check report against a live daemon.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::Doctor).await {
        CommandResult::Doctor(report) => {
            // #1840 added the worktrees check (6); DOC-28 R4(a) added the
            // output_style check (7); A2 (tm-skills-portfolio epic) added the
            // skill_source check (8); #gh-account-awareness added the gh_account
            // check (9); #2158 added the deployment check (10); #2246 added the
            // oauth_token check (11); #2876 added the skill_staleness and
            // legacy_sources checks (13); DOC-42 / issue #2889 added the
            // agent_skills check (14); issue #2906 review split it into
            // agent_skills + agent_skills_prose_hints, bringing the total to
            // 15; issue #2940 added hooks_contamination + hooks_foreign_conflict,
            // bringing the total to 17; issue #2333 added output_style_staleness,
            // bringing the total to 18; issue #2997 added tcc_taint, bringing the
            // total to 19; issue #3453 part 2 added output_style_legacy_ids,
            // bringing the total to 20; issue #3427 added scaffold_tracking,
            // bringing the total to 21. #1905's stale-skill cleanup is a
            // one-time migration, not a probe here.
            assert_eq!(report.checks.len(), 21);
        }
        other => panic!("expected Doctor, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_overseer_returns_status() {
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::Overseer).await {
        CommandResult::OverseerStatus { handler, .. } => assert!(!handler.is_empty()),
        other => panic!("expected OverseerStatus, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_status_no_events() {
    use crate::core::session::{ControlModel, Session, SessionId, SessionStatus};
    let (state, url) = spawn_test_daemon().await;
    let id = SessionId::new();
    let mut session = Session::new(id, "/tmp/proj", ControlModel::Tmux, None);
    session.status = SessionStatus::Active;
    state.register_session(session);

    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Status {
            session_id: id.0.to_string(),
        })
        .await
    {
        CommandResult::SessionDetail { events, .. } => assert!(events.is_empty()),
        other => panic!("expected SessionDetail, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_health_against_test_daemon() {
    // Against a live daemon the `health` verb reports reachable=true, a status
    // word, and a fleet summary (empty fleet → zero counts) — never an error.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url.clone());
    match executor.execute(TrustyCommand::Health).await {
        CommandResult::Health(report) => {
            assert!(report.reachable, "daemon should be reachable");
            assert!(!report.status.is_empty());
            assert_eq!(report.url, url);
            assert_eq!(report.managed_total, 0);
            assert_eq!(report.managed_pending_decisions, 0);
        }
        other => panic!("expected Health, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_health_excludes_deleted_tombstones_from_managed_total() {
    // #3034 fix-round HIGH-2: a slot tombstone (`deleted: true`) is intentionally
    // shown in `tm ls`, but it is not a session an operator can act on — `health`
    // must count only live sessions, never inflate `managed_total` with
    // tombstones the daemon reports for stable-slot numbering.
    use std::path::PathBuf;
    let (state, url) = spawn_test_daemon().await;
    let mgr = state.session_manager().await;

    let live = mgr
        .create(
            "keep me".into(),
            Some(PathBuf::from("/tmp/wt-live")),
            None,
            None,
            None,
            None,
        )
        .await
        .expect("create live session");
    let gone = mgr
        .create(
            "delete me".into(),
            Some(PathBuf::from("/tmp/wt-gone")),
            None,
            None,
            None,
            None,
        )
        .await
        .expect("create session to delete");
    // Observe both into the slot registry, then delete AND compact `gone` so
    // the next list renders it as a `deleted: true` tombstone at its
    // reserved slot. `delete_record` alone (#2012/#3302) is a SOFT delete —
    // the record stays in the store, marked `Deleted` — so a genuine #3034
    // slot tombstone (`record: None`) additionally requires the permanent-
    // removal primitive `compact_record`, mirroring the real two-step CLI
    // path (`tm sessions delete` then `tm sessions prune --state deleted`,
    // which calls the same primitive internally).
    mgr.numbered_snapshot(&mgr.list().await).await;
    mgr.delete_record(&gone.id, true)
        .await
        .expect("delete gone session");
    mgr.compact_record(&gone.id)
        .await
        .expect("compact the soft-deleted session out of the store");

    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::Health).await {
        CommandResult::Health(report) => {
            assert!(report.reachable, "daemon should be reachable");
            assert_eq!(
                report.managed_total, 1,
                "the deleted slot's tombstone must not be counted alongside the live session {}",
                live.id
            );
            assert_eq!(report.managed_pending_decisions, 0);
        }
        other => panic!("expected Health, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_health_dead_daemon_renders() {
    // A dead daemon must render as a Health result with reachable=false — never a
    // panic and never a transport Error.
    let executor = CommandExecutor::new("http://127.0.0.1:0");
    match executor.execute(TrustyCommand::Health).await {
        CommandResult::Health(report) => {
            assert!(!report.reachable, "dead daemon must be reachable=false");
            assert_eq!(report.status, "unreachable");
            assert_eq!(report.managed_total, 0);
        }
        other => panic!("expected Health, got {other:?}"),
    }
}

#[test]
fn resolve_session_exact_and_prefix() {
    use crate::client::http_client::SessionRow;
    use crate::core::session::{SessionId, SessionStatus};
    let rows = vec![
        SessionRow {
            id: SessionId(uuid::Uuid::nil()),
            workdir: "/tmp/a".into(),
            status: SessionStatus::Active,
            active_delegations: 0,
            tmux_name: "tmpm-blue-fox".into(),
            last_seen: Default::default(),
        },
        SessionRow {
            id: SessionId(uuid::Uuid::from_u128(1)),
            workdir: "/tmp/b".into(),
            status: SessionStatus::Active,
            active_delegations: 0,
            tmux_name: "frontend".into(),
            last_seen: Default::default(),
        },
    ];
    // Exact friendly-name match.
    assert_eq!(
        resolve_session(&rows, "frontend").as_deref(),
        Some("frontend")
    );
    // Prefix match.
    assert_eq!(
        resolve_session(&rows, "tmpm-blue").as_deref(),
        Some("tmpm-blue-fox")
    );
    // Exact id match resolves to the friendly name.
    assert_eq!(
        resolve_session(&rows, &uuid::Uuid::nil().to_string()).as_deref(),
        Some("tmpm-blue-fox")
    );
    assert!(resolve_session(&rows, "no-such").is_none());
}

#[test]
fn truncate_output_caps_long_text() {
    let short = "hello";
    assert_eq!(truncate_output(short), short);
    let long = "x".repeat(MAX_OUTPUT_CHARS + 100);
    let truncated = truncate_output(&long);
    assert!(truncated.contains("output truncated"));
    assert!(truncated.chars().count() <= MAX_OUTPUT_CHARS + 32);
}

#[test]
fn decide_answer_prefers_proposed_default() {
    // Approve adopts the harness's proposed default when present, else "yes";
    // deny is always "no" regardless of any proposed default.
    assert_eq!(decide_answer(true, Some("option B")), "option B");
    assert_eq!(decide_answer(true, None), "yes");
    assert_eq!(decide_answer(false, Some("option B")), "no");
    assert_eq!(decide_answer(false, None), "no");
}

#[tokio::test]
async fn execute_approve_managed_miss_then_project_not_found() {
    // The 1A round-trip follow-up: with no managed session matching, `decide`
    // falls through to the project `GET /sessions` path exactly once and reports
    // not-found for an unknown id (it does NOT masquerade as a managed error).
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Approve {
            session_id: uuid::Uuid::new_v4().to_string(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("not found")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_send_unknown_session_errors() {
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::Send {
            session: "no-such-session".into(),
            prompt: "hello".into(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("not found")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_connect_errors_when_daemon_unreachable() {
    // `/connect` registers via `POST /api/v1/sessions/connect`; with no
    // daemon the failure surfaces as a renderable `Error`, never a panic.
    let executor = CommandExecutor::new("http://127.0.0.1:0");
    match executor
        .execute(TrustyCommand::Connect {
            project: "/tmp/no-such-project".into(),
            session_name: None,
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("connect failed")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_launch_errors_when_daemon_unreachable() {
    // `/launch` registers via `POST /sessions`; with no daemon the failure
    // surfaces as a renderable `Error`.
    let executor = CommandExecutor::new("http://127.0.0.1:0");
    match executor
        .execute(TrustyCommand::Launch {
            project: "/tmp/no-such-project".into(),
            session_name: None,
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("launch failed")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_send_empty_prompt_errors() {
    let executor = CommandExecutor::new("http://unused");
    match executor
        .execute(TrustyCommand::Send {
            session: "frontend".into(),
            prompt: "   ".into(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("prompt")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_adopt_requires_tmux_name() {
    // Validation is pure — no daemon needed. An empty tmux_name is rejected with a
    // renderable error before any HTTP call (#1433).
    let executor = CommandExecutor::new("http://unused");
    match executor
        .execute(TrustyCommand::ManagedAdopt {
            tmux_name: "  ".into(),
            cwd: "/x".into(),
            task: None,
            runtime: None,
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("tmux_name")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_adopt_requires_cwd() {
    // The cwd is required because the pane's provenance is unknown to the daemon;
    // an empty cwd is rejected before any HTTP call (#1433).
    let executor = CommandExecutor::new("http://unused");
    match executor
        .execute(TrustyCommand::ManagedAdopt {
            tmux_name: "tmpm-x".into(),
            cwd: "".into(),
            task: None,
            runtime: None,
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("cwd")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn pair_request_returns_code() {
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.pair_request().await {
        CommandResult::PairCode { code, .. } => assert_eq!(code.len(), 6),
        other => panic!("expected PairCode, got {other:?}"),
    }
}

#[tokio::test]
async fn pair_confirm_unknown_code_errors() {
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.pair_confirm("ZZZZZZ", 999).await {
        CommandResult::Error(msg) => assert!(msg.contains("invalid")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_list_against_test_daemon() {
    // With no managed sessions provisioned, `managed-list` returns an empty
    // (but well-formed) list against the live managed route — never an error.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor.execute(TrustyCommand::ManagedList).await {
        CommandResult::ManagedSessions(list) => assert!(list.is_empty()),
        other => panic!("expected ManagedSessions, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_get_unknown_errors() {
    // A target that resolves against no managed session is a renderable error,
    // not a panic.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::ManagedGet {
            target: "no-such-managed".into(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("not found")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_answer_unknown_errors() {
    // The corrected decision-answer path: answering an unknown managed session
    // resolves to a not-found error (it never falls through to a synthetic hook).
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    match executor
        .execute(TrustyCommand::ManagedAnswer {
            target: "no-such-managed".into(),
            answer: "yes".into(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("not found")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_answer_empty_errors() {
    // An empty answer is rejected before any HTTP call.
    let executor = CommandExecutor::new("http://unused");
    match executor
        .execute(TrustyCommand::ManagedAnswer {
            target: "x".into(),
            answer: "   ".into(),
        })
        .await
    {
        CommandResult::Error(msg) => assert!(msg.contains("answer")),
        other => panic!("expected Error, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_managed_lifecycle_unknown_errors() {
    // stop / resume / decommission of an unknown managed target all error.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    for cmd in [
        TrustyCommand::ManagedRuntimeStop {
            target: "no-such".into(),
        },
        TrustyCommand::ManagedResume {
            target: "no-such".into(),
        },
        TrustyCommand::ManagedDecommission {
            target: "no-such".into(),
        },
    ] {
        match executor.execute(cmd).await {
            CommandResult::Error(msg) => assert!(msg.contains("not found")),
            other => panic!("expected Error, got {other:?}"),
        }
    }
}

#[tokio::test]
async fn execute_managed_verbs_error_when_daemon_unreachable() {
    // Every target-taking managed verb surfaces an unreachable daemon as a
    // renderable Error rather than panicking.
    let executor = CommandExecutor::new("http://127.0.0.1:0");
    let cmds = [
        TrustyCommand::ManagedGet { target: "x".into() },
        TrustyCommand::ManagedActivity { target: "x".into() },
        TrustyCommand::ManagedAttachCmd { target: "x".into() },
        TrustyCommand::ManagedSend {
            target: "x".into(),
            text: "hi".into(),
        },
    ];
    for cmd in cmds {
        match executor.execute(cmd).await {
            CommandResult::Error(_) => {}
            other => panic!("expected Error, got {other:?}"),
        }
    }
}

#[tokio::test]
async fn pair_request_then_confirm_succeeds() {
    // The full handshake: request a code, confirm it, then status is paired.
    let (_state, url) = spawn_test_daemon().await;
    let executor = CommandExecutor::new(url);
    let code = match executor.pair_request().await {
        CommandResult::PairCode { code, .. } => code,
        other => panic!("expected PairCode, got {other:?}"),
    };
    match executor.pair_confirm(&code, 424242).await {
        CommandResult::PairSuccess { chat_info } => assert!(chat_info.contains("424242")),
        other => panic!("expected PairSuccess, got {other:?}"),
    }
    match executor.execute(TrustyCommand::Start).await {
        CommandResult::PairState { paired } => assert!(paired),
        other => panic!("expected PairState, got {other:?}"),
    }
}

#[tokio::test]
async fn execute_approve_errors_when_managed_list_unreachable() {
    // Regression for the swallowed-daemon-error fix: `decide()` fetches the
    // managed list first. When that fetch fails (daemon down), the operator
    // must see a transport error, NOT a misleading "session not found" from a
    // silent fall-through to the project-session path.
    let executor = CommandExecutor::new("http://127.0.0.1:0");
    match executor
        .execute(TrustyCommand::Approve {
            session_id: uuid::Uuid::new_v4().to_string(),
        })
        .await
    {
        CommandResult::Error(msg) => {
            assert!(
                msg.contains("daemon unreachable"),
                "expected a daemon-unreachable error, got: {msg}"
            );
            assert!(
                !msg.contains("not found"),
                "must not masquerade a transport failure as not-found: {msg}"
            );
        }
        other => panic!("expected Error, got {other:?}"),
    }
}

#[test]
fn is_session_id_detects_uuid_vs_name() {
    // A canonical id (UUID) is treated as an id so `managed_get` can skip the
    // list round-trip; a friendly name or prefix is not.
    assert!(super::managed::is_session_id(
        &uuid::Uuid::new_v4().to_string()
    ));
    assert!(super::managed::is_session_id(
        "367c6c51-1025-419c-b6d6-be9a753e8914"
    ));
    assert!(!super::managed::is_session_id("brave-otter"));
    assert!(!super::managed::is_session_id("brave"));
    assert!(!super::managed::is_session_id(""));
}