trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
use super::*;

#[tokio::test]
async fn top_level_default_client_is_bounded_against_a_stalled_daemon() {
    // Why: issue #2517 — the top-level `tm` CLI (`bin/tm/main.rs`) used to
    // mint its own bare, unbounded `reqwest::Client::new()` instead of
    // reusing `DaemonClient`'s bounded client, so `tm status` against a
    // daemon that accepts the TCP connection but never answers hung for the
    // OS-level socket timeout (observed 55.63s live-verify) instead of the
    // intended ~10s request bound. `main.rs` now calls
    // `client::http_client::default_client()` directly — the SAME function
    // `DaemonClient::new` calls — so this test exercises the real
    // production bounds (not `config`'s scaled-down test bounds) end-to-end
    // against a stalled listener, pinning that the public wrapper is not
    // accidentally an unbounded client in disguise.
    // What: builds a client via `default_client()`, issues a GET against a
    // `TcpListener` that accepts but never answers, and asserts the call
    // errors comfortably within the 10s production request bound.
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind stalling listener");
    let addr = listener.local_addr().expect("read local_addr");

    let client = default_client();
    let url = format!("http://{addr}/");

    let start = std::time::Instant::now();
    let result = client.get(&url).send().await;
    let elapsed = start.elapsed();

    // `listener` stays alive (dropped at function end) for the whole
    // request so the connection stalls rather than being refused outright.
    assert!(result.is_err(), "expected the stalled request to time out");
    assert!(
        elapsed < std::time::Duration::from_secs(15),
        "request took {elapsed:?}, expected it to be bounded by the ~10s production \
         timeout, not the OS-level socket timeout (issue #2517 regression)"
    );
}

#[test]
fn base_url_is_stored() {
    let client = DaemonClient::new("http://127.0.0.1:7880");
    assert_eq!(client.base_url(), "http://127.0.0.1:7880");
}

#[test]
fn with_client_reuses_passed_client() {
    // Why: callers that configured a `reqwest::Client` (TLS/timeout/proxy/pool)
    // must keep that configuration; `with_client` adopts the passed client
    // verbatim instead of minting a fresh default one.
    let configured = reqwest::Client::new();
    let client = DaemonClient::with_client(configured, "http://127.0.0.1:7880");
    assert_eq!(client.base_url(), "http://127.0.0.1:7880");
}

#[test]
fn set_base_url_repoints_client() {
    // Why: a long-lived UI must follow the daemon to a new ephemeral port
    // after a restart; `set_base_url` is what makes that re-pointing possible.
    let mut client = DaemonClient::new("http://127.0.0.1:7880");
    client.set_base_url("http://127.0.0.1:54321");
    assert_eq!(client.base_url(), "http://127.0.0.1:54321");
}

#[tokio::test]
async fn launch_session_errors_when_daemon_unreachable() {
    // Why: `/connect <dir>` launches via `launch_session`; when the daemon is
    // unreachable (port 0 never connects) the error must surface rather than
    // proceeding to spawn tmux against an unregistered session.
    // #8545: pinned to a temp home so any prep that did run could never reach
    // the operator's.
    let home = crate::test_support::hermetic_temp_dir();
    let client = DaemonClient::new("http://127.0.0.1:0").with_home(home.path());
    let result = client.launch_session("/tmp/no-such-project").await;
    assert!(result.is_err(), "expected launch to fail with no daemon");
}

/// #8719: an unreachable daemon fails the launch BEFORE session prep, so
/// neither the project nor the home gains a file.
#[tokio::test]
async fn launch_session_writes_nothing_when_daemon_unreachable() {
    let home = crate::test_support::hermetic_temp_dir();
    let project = crate::test_support::hermetic_temp_dir();
    let client = DaemonClient::new("http://127.0.0.1:0").with_home(home.path());
    let workdir = project.path().to_string_lossy().into_owned();
    let result = client.launch_session(&workdir).await;
    assert!(result.is_err(), "expected launch to fail with no daemon");
    for (what, dir) in [("project", project.path()), ("home", home.path())] {
        let written: Vec<_> = std::fs::read_dir(dir)
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        assert!(
            written.is_empty(),
            "{what} gained {written:?} on a failed launch"
        );
    }
}

/// #8719: with a reachable daemon, prep runs — under the pinned home — before
/// the tmux step; a failed tmux create is reported as such.
///
/// Why: restores the coverage the pre-#8719 unreachable-daemon test gave (prep
/// lands under `with_home`, never the operator's home), now that an unreachable
/// daemon stops the launch before prep.
/// What: a fake listener answers `GET /health` and `POST /sessions` with 200;
/// a fake `tmux` exits 1 inside a `with_tmux_binary` scope, so no real tmux
/// server is touched.
#[tokio::test]
async fn launch_session_prepares_under_the_pinned_home_before_tmux() {
    use std::future::IntoFuture as _;
    use std::os::unix::fs::PermissionsExt as _;

    let router = axum::Router::new()
        .route("/health", axum::routing::get(|| async { "ok" }))
        .route(
            "/sessions",
            axum::routing::post(|| async {
                axum::Json(serde_json::json!({"name": "tm-8719-fake"}))
            }),
        );
    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());

    let bin_dir = tempfile::tempdir().unwrap();
    let tmux = bin_dir.path().join("fake-tmux");
    std::fs::write(&tmux, "#!/bin/sh\necho 'fake tmux refuses' >&2\nexit 1\n").unwrap();
    std::fs::set_permissions(&tmux, std::fs::Permissions::from_mode(0o755)).unwrap();

    let home = crate::test_support::hermetic_temp_dir();
    let project = crate::test_support::hermetic_temp_dir();
    let workdir = project.path().to_string_lossy().into_owned();
    let client = DaemonClient::new(format!("http://{addr}")).with_home(home.path());
    let result = crate::core::tmux::with_tmux_binary(tmux, client.launch_session(&workdir)).await;

    let err = result.expect_err("a failed tmux create must fail the launch");
    assert!(
        err.to_string()
            .contains("failed to create tmux session tm-8719-fake"),
        "{err}"
    );
    // Prep's trust seed and agent deploy land under the pinned home.
    for written in [".claude.json", ".claude"] {
        assert!(
            home.path().join(written).exists(),
            "prep did not write {written} under the pinned home"
        );
    }
}

#[tokio::test]
async fn connect_session_errors_when_daemon_unreachable() {
    // Why: `tm connect` registers via `POST /api/v1/sessions/connect`
    // before touching tmux; when the daemon POST fails the error must
    // surface rather than proceeding to spawn tmux against an
    // unregistered session.
    let client = DaemonClient::new("http://127.0.0.1:0");
    let result = client.connect_session("/tmp/no-such-project").await;
    assert!(result.is_err(), "expected connect to fail with no daemon");
}

/// Spawn the daemon's real HTTP API on a random loopback port, rooted in a
/// throwaway temp directory with an isolated (empty) managed-session store.
///
/// Why: mirrors `client::executor::tests::spawn_test_daemon` — a real bind is
/// needed to prove `spawn_managed_session` reads the response BODY (via
/// [`super::error::response_or_body_error`]), not just the status line.
async fn spawn_test_daemon() -> String {
    spawn_test_daemon_with_state().await.0
}

/// [`spawn_test_daemon`], also handing back the `DaemonState` it serves (#7877).
///
/// Why: a refusal that depends on the store's CONTENTS cannot be provoked
/// through the API alone — the collision needs two records seeded first.
async fn spawn_test_daemon_with_state()
-> (String, std::sync::Arc<crate::daemon::state::DaemonState>) {
    use std::future::IntoFuture as _;

    use crate::daemon::{api, state::DaemonState};
    let root = tempfile::tempdir().unwrap().keep();
    let state = std::sync::Arc::new(DaemonState::with_root_isolated_managed(root).await);
    let router = api::router(state.clone());
    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());
    (format!("http://{addr}"), state)
}

/// A #3764 guard refusal reaches the CLI as its REASON, over a non-500 status.
///
/// Why (#7877): the refusal used to be a 500 whose body `error_for_status`
/// discarded, so `tm sessions decommission` printed "HTTP status server error
/// (500 …)" and the operator learned neither that this was a legitimate refusal
/// nor which sibling session caused it. Both halves of the fix are exercised
/// here over a real socket: the daemon answers 409, and this client turns that
/// body into the error message.
/// Test: this function IS the test.
#[tokio::test]
async fn decommission_conflict_surfaces_the_guard_reason() {
    use crate::session_manager::{ManagedSessionId, ManagedSessionState, SessionRecord};

    let (url, state) = spawn_test_daemon_with_state().await;
    let mgr = state.session_manager().await;
    let shared = std::path::PathBuf::from("/tmp/trusty-mpm-7877-shared-workspace");
    let sibling = ManagedSessionId::new();
    let target = ManagedSessionId::new();
    for id in [sibling, target] {
        let record = SessionRecord {
            id,
            tmux_name: format!("tm-7877-client-{id}"),
            cwd: shared.clone(),
            task: "task".into(),
            state: ManagedSessionState::Active,
            created_at: chrono::Utc::now(),
            last_activity_at: None,
            workspace_path: Some(shared.clone()),
            repo_url: None,
            branch: None,
            pending_decision: None,
            proposed_default: None,
            correlation: Default::default(),
            runtime: Default::default(),
            ephemeral: false,
            workspace_owned: false,
            source_id: None,
            claude_session_id: None,
            scrollback_path: None,
            last_cwd: None,
            deliverable_id: None,
            pane_id: None,
            tmux_server: None,
            injection_status: Default::default(),
            worktree_owner: None,
            terminal_at: None,
            stop_cause: None,
            kind: Default::default(),
        };
        mgr.store
            .write()
            .await
            .upsert(record)
            .await
            .expect("seed record");
    }

    let client = DaemonClient::new(url);
    let err = client
        .decommission_managed_session(&target.to_string())
        .await
        .expect_err("a sibling Active session claiming the same workspace must refuse");
    let msg = err.to_string();
    assert!(
        msg.contains(&sibling.to_string()),
        "the guard's reason must reach the CLI naming the blocking session, got: {msg}"
    );
    // #7660: `(500` / `server error` is how `error_for_status` renders a 500;
    // a bare "500" also matched the random UUIDs in the reason.
    assert!(
        !msg.contains("(500") && !msg.contains("server error"),
        "a guard refusal must never look like a server fault, got: {msg}"
    );
}

/// #2457 follow-up to #2496: a rejected spawn must surface the daemon's body
/// message, not collapse to a bare "404 Not Found" the way `error_for_status`
/// alone would. No project is registered for `repo_url` here, so the daemon's
/// deliverable pre-check (`validate_deliverable_scope`, run BEFORE any
/// provisioning) rejects with `DaemonError::ProjectNotFoundForRepoUrl` — a 404
/// whose body names the offending repo_url.
#[tokio::test]
async fn spawn_managed_session_surfaces_daemon_error_body() {
    let url = spawn_test_daemon().await;
    let client = DaemonClient::new(url);
    let req = ManagedSpawnRequest {
        repo_url: "https://github.com/acme/unregistered".to_string(),
        git_ref: "main".to_string(),
        task: "do it".to_string(),
        name_hint: None,
        runtime: None,
        inject_task: None,
        deliverable_id: Some("11111111-1111-1111-1111-111111111111".to_string()),
        force_new: false,
    };
    let err = client
        .spawn_managed_session(&req)
        .await
        .expect_err("no project is registered for this repo_url");
    let msg = err.to_string();
    assert!(
        msg.contains("acme/unregistered") || msg.contains("unregistered"),
        "error should carry the daemon's body message, not just the bare status: {msg}"
    );
    assert!(msg.contains("404"), "{msg}");
}

#[test]
fn session_row_deserializes_tmux_name() {
    let json = serde_json::json!({
        "id": "abcd1234-5678-90ab-cdef-1234567890ab",
        "workdir": "/tmp/proj",
        "status": "Active",
        "active_delegations": 1,
        "tmux_name": "tmpm-quiet-falcon"
    });
    let row: SessionRow = serde_json::from_value(json).unwrap();
    assert_eq!(row.tmux_name, "tmpm-quiet-falcon");
}

#[test]
fn session_row_defaults_tmux_name_when_absent() {
    let json = serde_json::json!({
        "id": "abcd1234-5678-90ab-cdef-1234567890ab",
        "workdir": "/tmp/proj",
        "status": "Active"
    });
    let row: SessionRow = serde_json::from_value(json).unwrap();
    assert_eq!(row.tmux_name, "");
    assert_eq!(row.last_seen.secs_since_epoch, 0);
}

#[test]
fn events_deserialize_from_record_shape() {
    let json = serde_json::json!({
        "session": "abcd1234-5678-90ab-cdef-1234567890ab",
        "event": "PreToolUse",
        "at": "2024-01-01T00:00:00Z",
        "payload": {}
    });
    let row: EventRow = serde_json::from_value(json).unwrap();
    assert_eq!(row.event, crate::core::hook::HookEvent::PreToolUse);
    assert_eq!(row.at, "2024-01-01T00:00:00Z");
}

#[test]
fn events_default_payload_when_absent() {
    let json = serde_json::json!({
        "session": "abcd1234-5678-90ab-cdef-1234567890ab",
        "event": "Stop",
        "at": "2024-01-01T00:00:00Z"
    });
    let row: EventRow = serde_json::from_value(json).unwrap();
    assert!(row.payload.is_null());
}

#[test]
fn breakers_deserialize_from_api_shape() {
    let json = serde_json::json!({
        "agent": "research",
        "breaker": { "state": "closed", "consecutive_failures": 0 }
    });
    #[derive(serde::Deserialize)]
    struct WireBreaker {
        state: String,
        consecutive_failures: u32,
    }
    #[derive(serde::Deserialize)]
    struct WireRow {
        agent: String,
        breaker: WireBreaker,
    }
    let row: WireRow = serde_json::from_value(json).unwrap();
    assert_eq!(row.agent, "research");
    assert_eq!(row.breaker.state, "closed");
    assert_eq!(row.breaker.consecutive_failures, 0);
}

#[test]
fn tmux_session_row_accepts_name() {
    // The snapshot helper joins a `lines` array; the name parse is exercised
    // here directly on both wire shapes.
    let obj = serde_json::json!({"name": "tmpm-quiet-falcon"});
    assert_eq!(
        obj.get("name").and_then(|v| v.as_str()),
        Some("tmpm-quiet-falcon")
    );
    let plain = serde_json::json!("external-shell");
    assert_eq!(plain.as_str(), Some("external-shell"));
}

#[test]
fn snapshot_text_handles_each_shape() {
    assert_eq!(snapshot_text(&serde_json::json!("plain")), "plain");
    assert_eq!(
        snapshot_text(&serde_json::json!({"content": "from content"})),
        "from content"
    );
    assert_eq!(
        snapshot_text(&serde_json::json!({"lines": ["a", "b"]})),
        "a\nb"
    );
}

#[test]
fn pair_request_deserializes() {
    let json = serde_json::json!({"code": "A4X9KZ", "expires_in_seconds": 300});
    let req: PairRequest = serde_json::from_value(json).unwrap();
    assert_eq!(req.code, "A4X9KZ");
    assert_eq!(req.expires_in_seconds, 300);
}

#[test]
fn pair_confirm_deserializes_failure() {
    let json = serde_json::json!({"success": false, "error": "invalid or expired code"});
    let confirm: PairConfirm = serde_json::from_value(json).unwrap();
    assert!(!confirm.success);
    assert_eq!(confirm.error.as_deref(), Some("invalid or expired code"));
    assert_eq!(confirm.chat_id, None);
}

#[test]
fn llm_chat_message_round_trips() {
    // A ChatMessage serializes to the `{role, content}` wire shape the
    // daemon expects and deserializes back unchanged.
    let msg = ChatMessage {
        role: "user".into(),
        content: "hello".into(),
    };
    let json = serde_json::to_value(&msg).unwrap();
    assert_eq!(json["role"], "user");
    assert_eq!(json["content"], "hello");
    let back: ChatMessage = serde_json::from_value(json).unwrap();
    assert_eq!(back, msg);
}

#[test]
fn chat_message_constructors_set_role() {
    assert_eq!(ChatMessage::user("x").role, "user");
    assert_eq!(ChatMessage::assistant("y").role, "assistant");
    assert_eq!(ChatMessage::user("x").content, "x");
}

#[test]
fn llm_chat_response_deserializes() {
    // The `POST /llm/chat` response carries the reply and updated history.
    let json = serde_json::json!({
        "reply": "hi there",
        "history": [
            { "role": "user", "content": "hello" },
            { "role": "assistant", "content": "hi there" },
        ],
    });
    let outcome: LlmChatOutcome = serde_json::from_value(json).unwrap();
    assert_eq!(outcome.reply, "hi there");
    assert_eq!(outcome.history.len(), 2);
    assert_eq!(outcome.history[1].role, "assistant");
}

#[test]
fn coordinator_context_deserializes() {
    // The `GET /api/v1/sessions/context` snapshot carries the session
    // summaries; the daemon's `recent_events` field is ignored.
    let json = serde_json::json!({
        "sessions": [{
            "id": "00000000-0000-0000-0000-000000000000",
            "name": "tmpm-aipowerranking",
            "prefix": "aipowerranking",
            "workdir": "/tmp/proj",
            "status": "Active",
            "active_delegations": 3,
            "recent_output": ["building…"],
        }],
        "recent_events": [],
        "generated_at": "2026-05-19T00:00:00Z",
    });
    let context: CoordinatorContext = serde_json::from_value(json).unwrap();
    assert_eq!(context.sessions.len(), 1);
    assert_eq!(context.sessions[0].prefix, "aipowerranking");
    assert_eq!(context.sessions[0].active_delegations, 3);
    // This payload is what an OLDER daemon (pre-#1275) emits — no summary
    // fields. `#[serde(default)]` makes the client tolerant: absent → None/false.
    assert_eq!(context.sessions[0].last_summary, None);
    assert!(!context.sessions[0].summarizing);
}

#[test]
fn coordinator_session_carries_summary_fields() {
    // A current daemon (#1275) emits `last_summary` + `summarizing`; the client
    // deserializes both so the TUI can render the bullet and blink (DOC-16 §6.2).
    let json = serde_json::json!({
        "sessions": [{
            "id": "00000000-0000-0000-0000-000000000000",
            "name": "tmpm-aipowerranking",
            "prefix": "aipowerranking",
            "workdir": "/tmp/proj",
            "status": "Active",
            "active_delegations": 0,
            "recent_output": [],
            "last_summary": "Writing the parser tests",
            "summarizing": true,
        }],
    });
    let context: CoordinatorContext = serde_json::from_value(json).unwrap();
    assert_eq!(
        context.sessions[0].last_summary.as_deref(),
        Some("Writing the parser tests")
    );
    assert!(context.sessions[0].summarizing);
}

#[test]
fn coordinator_chat_outcome_deserializes() {
    // A routed-command outcome carries the session name and pane output.
    let json = serde_json::json!({
        "reply": "Sent to tmpm-foo: run tests",
        "routed_to_session": "tmpm-foo",
        "command_output": "tests passed",
    });
    let outcome: CoordinatorChatOutcome = serde_json::from_value(json).unwrap();
    assert_eq!(outcome.routed_to_session.as_deref(), Some("tmpm-foo"));
    assert_eq!(outcome.command_output.as_deref(), Some("tests passed"));

    // A plain LLM reply omits the routing fields.
    let json = serde_json::json!({ "reply": "two sessions are active" });
    let outcome: CoordinatorChatOutcome = serde_json::from_value(json).unwrap();
    assert_eq!(outcome.reply, "two sessions are active");
    assert!(outcome.routed_to_session.is_none());
    // Additive action-path fields default to None when absent.
    assert!(outcome.actions_taken.is_none());
    assert!(outcome.conv_id.is_none());
}

#[test]
fn coordinator_chat_outcome_deserializes_actions() {
    // The action-capable path returns the audit trail and the conversation id.
    let json = serde_json::json!({
        "reply": "ran a health check and listed the fleet",
        "actions_taken": ["sessions.health", "sessions.list"],
        "conv_id": "conv-42",
    });
    let outcome: CoordinatorChatOutcome = serde_json::from_value(json).unwrap();
    assert_eq!(
        outcome.actions_taken.as_deref(),
        Some(["sessions.health".to_string(), "sessions.list".to_string()].as_slice())
    );
    assert_eq!(outcome.conv_id.as_deref(), Some("conv-42"));
}

#[test]
fn coordinator_chat_serializes_actions_flag() {
    // The request body must carry the `actions` boolean so the daemon can route
    // the action-capable SM branch; history is threaded through verbatim.
    let history = [ChatMessage::user("hi"), ChatMessage::assistant("hello")];
    let body = coordinator_chat_body("spin up a session", &history, true);
    assert_eq!(body["message"], "spin up a session");
    assert_eq!(body["actions"], true);
    assert_eq!(body["history"][0]["role"], "user");
    assert_eq!(body["history"][1]["content"], "hello");

    // The passive path serializes `actions: false`.
    let passive = coordinator_chat_body("just chatting", &[], false);
    assert_eq!(passive["actions"], false);
}

#[test]
fn pair_status_deserializes() {
    let json = serde_json::json!({"paired": true, "chat_id": 12345678});
    let status: PairStatus = serde_json::from_value(json).unwrap();
    assert!(status.paired);
    assert_eq!(status.chat_id, Some(12345678));
}

#[test]
fn catalog_stale_health_body_wire_shape() {
    // The HR-3 `catalog_stale` flag must round-trip from the `/health` body, and
    // a body MISSING the field (an older daemon) must default to `false` so
    // `DaemonClient::catalog_stale` degrades to "no updates" instead of erroring.
    // This mirrors the private `HealthBody` the client parses.
    #[derive(serde::Deserialize)]
    struct HealthBody {
        #[serde(default)]
        catalog_stale: bool,
    }

    let stale: HealthBody =
        serde_json::from_value(serde_json::json!({"status":"ok","catalog_stale":true})).unwrap();
    assert!(stale.catalog_stale);

    let fresh: HealthBody =
        serde_json::from_value(serde_json::json!({"status":"ok","catalog_stale":false})).unwrap();
    assert!(!fresh.catalog_stale);

    // Legacy daemon: no `catalog_stale` field present → defaults to false.
    let legacy: HealthBody = serde_json::from_value(serde_json::json!({"status":"ok"})).unwrap();
    assert!(!legacy.catalog_stale, "missing field defaults to false");
}

// ── Managed session-manager wire-shape round-trips ─────────────────────────────

#[test]
fn managed_session_summary_deserializes() {
    // A full summary round-trips; the optional fields are also tolerant of being
    // absent (an older/leaner daemon) via `#[serde(default)]`.
    let json = serde_json::json!({
        "id": "00000000-0000-0000-0000-000000000001",
        "name": "tmpm-brave-otter",
        "state": "running",
        "workspace_path": "/tmp/ws",
        "repo_url": "https://example.com/r.git",
        "branch": "main",
        "created_at": "2026-06-19T00:00:00Z",
        "last_activity_at": "2026-06-19T01:00:00Z",
        "pending_decision": "overwrite?",
        "proposed_default": "yes",
        "source_id": "owner/repo",
    });
    let s: ManagedSessionSummary = serde_json::from_value(json).unwrap();
    assert_eq!(s.id, "00000000-0000-0000-0000-000000000001");
    assert_eq!(s.name, "tmpm-brave-otter");
    assert_eq!(s.state, "running");
    assert_eq!(s.created_at.as_deref(), Some("2026-06-19T00:00:00Z"));
    assert_eq!(s.pending_decision.as_deref(), Some("overwrite?"));
    // source_id round-trips (#1730).
    assert_eq!(s.source_id.as_deref(), Some("owner/repo"));

    // Minimal body: only the always-present fields.
    let lean = serde_json::json!({"id": "x", "name": "n", "state": "stopped"});
    let s: ManagedSessionSummary = serde_json::from_value(lean).unwrap();
    assert_eq!(s.id, "x");
    assert!(s.workspace_path.is_none());
    // An absent `created_at` deserializes to `None`, not an empty string.
    assert!(s.created_at.is_none());
    assert!(s.pending_decision.is_none());
    // An absent `source_id` defaults to None (legacy sessions without it).
    assert!(s.source_id.is_none());
}

/// #5899: the decommission response's workspace verdict must survive the client
/// round-trip, and an absent verdict must stay distinguishable from `false`.
///
/// The keys asserted here are `daemon::managed_routes::DecommissionResponse`'s own
/// serde output — the flattened summary plus `workspace_removed` /
/// `workspace_path_was`. Before this type existed the body was decoded into
/// [`ManagedSessionSummary`], which has nowhere for either field to land, so serde
/// dropped both and the CLI had nothing left to report.
#[test]
fn decommission_outcome_round_trips_daemon_response() {
    let removed = serde_json::json!({
        "id": "00000000-0000-0000-0000-000000000001",
        "name": "tmpm-brave-otter",
        "state": "decommissioned",
        "workspace_path": serde_json::Value::Null,
        "workspace_removed": true,
        "workspace_path_was": "/tmp/base/.worktrees/abc",
    });
    let o: ManagedDecommissionOutcome = serde_json::from_value(removed).unwrap();
    assert_eq!(o.summary.id, "00000000-0000-0000-0000-000000000001");
    assert_eq!(o.summary.state, "decommissioned");
    assert_eq!(o.workspace_removed, Some(true));
    assert_eq!(
        o.workspace_path_was.as_deref(),
        Some("/tmp/base/.worktrees/abc")
    );

    // The error arm: the daemon says it removed nothing.
    let kept = serde_json::json!({
        "id": "x", "name": "n", "state": "decommissioned", "workspace_removed": false
    });
    let o: ManagedDecommissionOutcome = serde_json::from_value(kept).unwrap();
    assert_eq!(o.workspace_removed, Some(false));
    assert!(o.workspace_path_was.is_none());

    // An older daemon that reports no verdict must NOT read as `false`, which
    // would assert "still on disk" the client cannot know.
    let silent = serde_json::json!({"id": "x", "name": "n", "state": "decommissioned"});
    let o: ManagedDecommissionOutcome = serde_json::from_value(silent).unwrap();
    assert_eq!(o.workspace_removed, None);
}

/// #5899: a field the daemon adds later must be retained, not silently dropped.
///
/// This is the class of bug, not just the instance: the client discarded
/// `workspace_removed` because its target type had no field for it, and serde says
/// nothing when that happens. Unmodelled keys now land in `unrecognized`, where the
/// executor logs them and this test can see them.
#[test]
fn decommission_outcome_keeps_unmodelled_daemon_fields() {
    let body = serde_json::json!({
        "id": "x",
        "name": "n",
        "state": "decommissioned",
        "workspace_removed": false,
        "workspace_removal_error": "worktree holds uncommitted work",
    });
    let o: ManagedDecommissionOutcome = serde_json::from_value(body).unwrap();
    assert_eq!(o.workspace_removed, Some(false));
    assert_eq!(
        o.unrecognized
            .get("workspace_removal_error")
            .and_then(|v| v.as_str()),
        Some("worktree holds uncommitted work"),
        "an unmodelled daemon field must be retained, not dropped: {:?}",
        o.unrecognized
    );
    // Fields the client DOES model are consumed by their own fields, so they must
    // not also show up as unrecognized.
    for modelled in ["id", "name", "state", "workspace_removed"] {
        assert!(
            !o.unrecognized.contains_key(modelled),
            "{modelled} is modelled and must not be collected as unrecognized"
        );
    }
}

#[test]
fn managed_session_summary_carries_the_kind() {
    use crate::session_manager::SessionKind;
    // #8942: the daemon's summary serializes the record kind, and the client
    // reads it back; a pre-#8942 daemon omits it.
    let record: crate::session_manager::SessionRecord = serde_json::from_value(serde_json::json!({
        "id": "00000000-0000-0000-0000-000000000001", "task": "t", "tmux_name": "tm-arch",
        "cwd": "/tmp", "state": "active", "created_at": "2026-09-30T00:00:00Z",
        "kind": "supervisor",
    }))
    .unwrap();
    let summary = crate::daemon::managed_routes::summary::record_to_summary(&record);
    let wire = serde_json::to_value(summary).unwrap();
    let s: ManagedSessionSummary = serde_json::from_value(wire).unwrap();
    assert_eq!(s.kind, Some(SessionKind::Supervisor));

    let omitted = serde_json::json!({"id": "x", "name": "n", "state": "stopped"});
    let s: ManagedSessionSummary = serde_json::from_value(omitted).unwrap();
    assert_eq!(s.kind, None);
}

/// #2595: `unresumable` must round-trip when present, and default `false`
/// (never spuriously flag a session dead) when an older daemon omits it.
#[test]
fn managed_session_summary_deserializes_unresumable_flag() {
    let with_flag = serde_json::json!({
        "id": "x", "name": "n", "state": "stopped", "unresumable": true
    });
    let s: ManagedSessionSummary = serde_json::from_value(with_flag).unwrap();
    assert!(s.unresumable, "unresumable: true must deserialize to true");

    let omitted = serde_json::json!({"id": "x", "name": "n", "state": "stopped"});
    let s: ManagedSessionSummary = serde_json::from_value(omitted).unwrap();
    assert!(
        !s.unresumable,
        "an older daemon omitting `unresumable` must default to false"
    );
}

/// #3034: `slot`/`deleted` must round-trip when present, and default to
/// `0`/`false` (never a spurious tombstone) when an older daemon omits them.
#[test]
fn managed_session_summary_deserializes_slot_and_deleted() {
    let with_fields = serde_json::json!({
        "id": "x", "name": "n", "state": "deleted", "slot": 3, "deleted": true
    });
    let s: ManagedSessionSummary = serde_json::from_value(with_fields).unwrap();
    assert_eq!(s.slot, 3);
    assert!(s.deleted);

    let omitted = serde_json::json!({"id": "x", "name": "n", "state": "stopped"});
    let s: ManagedSessionSummary = serde_json::from_value(omitted).unwrap();
    assert_eq!(
        s.slot, 0,
        "an older daemon omitting `slot` must default to 0"
    );
    assert!(
        !s.deleted,
        "an older daemon omitting `deleted` must default to false"
    );
}

/// #2444: `stale_assets` must round-trip when present, and default `false`
/// (never spuriously flag a session stale) when an older daemon omits it.
#[test]
fn managed_session_summary_deserializes_stale_assets_flag() {
    let with_flag = serde_json::json!({
        "id": "x", "name": "n", "state": "active", "stale_assets": true
    });
    let s: ManagedSessionSummary = serde_json::from_value(with_flag).unwrap();
    assert!(
        s.stale_assets,
        "stale_assets: true must deserialize to true"
    );

    let omitted = serde_json::json!({"id": "x", "name": "n", "state": "active"});
    let s: ManagedSessionSummary = serde_json::from_value(omitted).unwrap();
    assert!(
        !s.stale_assets,
        "an older daemon omitting `stale_assets` must default to false"
    );
}

/// #4322: `stale_assets_unchecked` must round-trip when present, and default
/// `false` when omitted — the polarity that matters for wire compatibility.
/// An OLDER daemon probed every meaningful state, so its (field-less)
/// responses ARE authoritative verdicts; defaulting to `false` is what keeps a
/// new client from painting `[assets ?]` across every row it serves.
#[test]
fn managed_session_summary_defaults_stale_assets_unchecked_false() {
    let with_flag = serde_json::json!({
        "id": "x", "name": "n", "state": "stopped", "stale_assets_unchecked": true
    });
    let s: ManagedSessionSummary = serde_json::from_value(with_flag).unwrap();
    assert!(
        s.stale_assets_unchecked,
        "stale_assets_unchecked: true must deserialize to true"
    );

    let omitted = serde_json::json!({"id": "x", "name": "n", "state": "stopped"});
    let s: ManagedSessionSummary = serde_json::from_value(omitted).unwrap();
    assert!(
        !s.stale_assets_unchecked,
        "an older daemon omitting `stale_assets_unchecked` probed everything — \
         its verdicts must stay authoritative, not be repainted as unknown"
    );
}

#[test]
fn managed_list_response_deserializes() {
    let json = serde_json::json!({
        "sessions": [
            {"id": "a", "name": "tmpm-a", "state": "running"},
            {"id": "b", "name": "tmpm-b", "state": "stopped"},
        ],
    });
    let body: ManagedListResponse = serde_json::from_value(json).unwrap();
    assert_eq!(body.sessions.len(), 2);
    assert_eq!(body.sessions[1].name, "tmpm-b");

    // An empty / absent `sessions` array defaults to empty.
    let empty: ManagedListResponse = serde_json::from_value(serde_json::json!({})).unwrap();
    assert!(empty.sessions.is_empty());
}

#[test]
fn managed_spawn_request_serializes() {
    // The `git_ref` field must serialize under the wire key `ref`, and absent
    // optionals must be omitted so the daemon sees them as null/defaulted.
    let req = ManagedSpawnRequest {
        repo_url: "https://example.com/r.git".to_string(),
        git_ref: "main".to_string(),
        task: "do the thing".to_string(),
        name_hint: Some("tmpm-custom".to_string()),
        runtime: Some("tcode".to_string()),
        inject_task: None,
        deliverable_id: Some("11111111-1111-1111-1111-111111111111".to_string()),
        force_new: false,
    };
    let v = serde_json::to_value(&req).unwrap();
    assert_eq!(v["ref"], "main");
    assert_eq!(v["repo_url"], "https://example.com/r.git");
    assert_eq!(v["name_hint"], "tmpm-custom");
    assert_eq!(v["runtime"], "tcode");
    assert_eq!(
        v["deliverable_id"], "11111111-1111-1111-1111-111111111111",
        "Some(deliverable_id) must serialize as its string value"
    );
    assert!(v.get("git_ref").is_none(), "must use wire key `ref`");

    let bare = ManagedSpawnRequest {
        repo_url: "r".to_string(),
        git_ref: "r".to_string(),
        task: "t".to_string(),
        name_hint: None,
        runtime: None,
        inject_task: None,
        deliverable_id: None,
        force_new: false,
    };
    let v = serde_json::to_value(&bare).unwrap();
    assert!(v.get("name_hint").is_none(), "None name_hint is omitted");
    assert!(v.get("runtime").is_none(), "None runtime is omitted");
    assert!(
        v.get("inject_task").is_none(),
        "None inject_task is omitted"
    );
    assert!(
        v.get("deliverable_id").is_none(),
        "None deliverable_id is omitted (#2379, same additive pattern as inject_task)"
    );
    assert!(
        v.get("force_new").is_none(),
        "false force_new is omitted (#2450) so the wire matches the pre-existing shape"
    );
}

#[test]
fn managed_spawn_response_deserializes() {
    let json = serde_json::json!({
        "id": "id-1",
        "name": "tmpm-x",
        "state": "running",
        "created_at": "2026-06-19T00:00:00Z",
        "attach_cmd": "tmux attach-session -t '=tmpm-x'",
        "runtime": "claude-code",
    });
    let r: ManagedSpawnResponse = serde_json::from_value(json).unwrap();
    assert_eq!(r.id, "id-1");
    assert_eq!(r.created_at.as_deref(), Some("2026-06-19T00:00:00Z"));
    assert_eq!(r.attach_cmd, "tmux attach-session -t '=tmpm-x'");
    assert_eq!(r.runtime, "claude-code");

    // An absent `created_at` deserializes to `None`, while `attach_cmd` and
    // `runtime` remain plain strings defaulting to empty.
    let lean = serde_json::json!({"id": "id-2", "name": "tmpm-y", "state": "running"});
    let r: ManagedSpawnResponse = serde_json::from_value(lean).unwrap();
    assert!(r.created_at.is_none());
    assert_eq!(r.attach_cmd, "");
    assert_eq!(r.runtime, "");
}

#[test]
fn managed_adopt_request_serializes() {
    // Required fields are always present; absent optionals are omitted so the
    // daemon defaults them (#1433).
    let req = ManagedAdoptRequest {
        tmux_name: "tmpm-hand-started".to_string(),
        cwd: "/Users/op/work/proj".to_string(),
        task: Some("drive it".to_string()),
        runtime: Some("claude-code".to_string()),
    };
    let v = serde_json::to_value(&req).unwrap();
    assert_eq!(v["tmux_name"], "tmpm-hand-started");
    assert_eq!(v["cwd"], "/Users/op/work/proj");
    assert_eq!(v["task"], "drive it");
    assert_eq!(v["runtime"], "claude-code");

    let bare = ManagedAdoptRequest {
        tmux_name: "my-cli-session".to_string(),
        cwd: "/x".to_string(),
        task: None,
        runtime: None,
    };
    let v = serde_json::to_value(&bare).unwrap();
    assert_eq!(v["tmux_name"], "my-cli-session");
    assert!(v.get("task").is_none(), "None task is omitted");
    assert!(v.get("runtime").is_none(), "None runtime is omitted");
}

#[test]
fn managed_adopt_response_deserializes() {
    let json = serde_json::json!({
        "id": "id-9",
        "name": "tmpm-hand-started",
        "state": "active",
        "cwd": "/Users/op/work/proj",
        "runtime": "claude-code",
        "attach_cmd": "tmux attach-session -t '=tmpm-hand-started'",
    });
    let r: ManagedAdoptResponse = serde_json::from_value(json).unwrap();
    assert_eq!(r.id, "id-9");
    assert_eq!(r.name, "tmpm-hand-started");
    assert_eq!(r.state, "active");
    assert_eq!(r.cwd, "/Users/op/work/proj");
    assert_eq!(r.runtime, "claude-code");
    assert_eq!(r.attach_cmd, "tmux attach-session -t '=tmpm-hand-started'");

    // A lean response (only id/name/state) still deserializes; the defaulted
    // string fields fall back to empty.
    let lean = serde_json::json!({"id": "id-10", "name": "x", "state": "active"});
    let r: ManagedAdoptResponse = serde_json::from_value(lean).unwrap();
    assert_eq!(r.cwd, "");
    assert_eq!(r.runtime, "");
    assert_eq!(r.attach_cmd, "");
}

#[test]
fn managed_send_and_answer_round_trip() {
    let v = serde_json::to_value(ManagedSendInputRequest {
        text: "hello".to_string(),
    })
    .unwrap();
    assert_eq!(v["text"], "hello");
    let sent: ManagedSendInputResponse =
        serde_json::from_value(serde_json::json!({"sent": true, "tmux_name": "tmpm-x"})).unwrap();
    assert!(sent.sent);
    assert_eq!(sent.tmux_name, "tmpm-x");

    let v = serde_json::to_value(ManagedAnswerRequest {
        answer: "yes".to_string(),
    })
    .unwrap();
    assert_eq!(v["answer"], "yes");
    let answered: ManagedAnswerResponse =
        serde_json::from_value(serde_json::json!({"injected": true, "tmux_name": "tmpm-x"}))
            .unwrap();
    assert!(answered.injected);
}

#[test]
fn managed_attach_cmd_response_deserializes() {
    let r: ManagedAttachCmdResponse = serde_json::from_value(
        serde_json::json!({"attach_cmd": "tmux attach-session -t '=tmpm-x'"}),
    )
    .unwrap();
    assert_eq!(r.attach_cmd, "tmux attach-session -t '=tmpm-x'");
}

#[test]
fn managed_activity_response_deserializes() {
    // Both with and without the optional classifier overlay.
    let json = serde_json::json!({
        "raw_pane": "line1\nline2",
        "runtime_active": true,
        "state": "working",
        "summary": "running tests",
        "confidence": 0.8_f32,
        "cache_hit": false,
        "input_tokens": 10,
        "output_tokens": 5,
        "latency_ms": 42,
        "total_input_tokens": 100,
        "total_output_tokens": 50,
        "classification": "working",
        "pending_decision": "overwrite?",
        "proposed_default": "yes",
    });
    let a: ManagedActivityResponse = serde_json::from_value(json).unwrap();
    assert_eq!(a.state, "working");
    assert!(a.runtime_active);
    assert_eq!(a.classification.as_deref(), Some("working"));
    assert_eq!(a.pending_decision.as_deref(), Some("overwrite?"));

    // No classifier ran: `classification` null, raw pane still present.
    let json = serde_json::json!({
        "raw_pane": "pane",
        "runtime_active": false,
        "state": "unknown",
        "summary": "",
        "confidence": 0.0_f32,
        "cache_hit": false,
        "input_tokens": 0,
        "output_tokens": 0,
        "latency_ms": 0,
        "total_input_tokens": 0,
        "total_output_tokens": 0,
        "classification": null,
    });
    let a: ManagedActivityResponse = serde_json::from_value(json).unwrap();
    assert_eq!(a.raw_pane, "pane");
    assert!(a.classification.is_none());
    assert!(a.pending_decision.is_none());
}

#[test]
fn managed_session_urls_use_managed_route_family() {
    // The managed methods build URLs off the `/api/v1/sessions/managed` base and
    // must NOT collide with the legacy `resume_session` route (`/sessions/{id}/
    // resume`). This guards the route family contract that STUI/TELUI converge on.
    let client = DaemonClient::new("http://127.0.0.1:7880");
    assert_eq!(client.base_url(), "http://127.0.0.1:7880");
    // Construct the same format strings the methods use, to lock the shape.
    let base = client.base_url();
    assert_eq!(
        format!("{base}/api/v1/sessions/managed/{id}/resume", id = "abc"),
        "http://127.0.0.1:7880/api/v1/sessions/managed/abc/resume"
    );
    // The legacy method targets a different path; the two never overlap.
    assert_eq!(
        format!("{base}/sessions/{id}/resume", id = "abc"),
        "http://127.0.0.1:7880/sessions/abc/resume"
    );
}

#[test]
fn health_snapshot_deserializes() {
    // The `/health` body deserializes into HealthSnapshot; the catalog flags
    // and `version` (issue #2332) default when absent so an older daemon
    // returning only `status` still parses.
    let full: HealthSnapshot = serde_json::from_value(serde_json::json!({
        "status": "ok",
        "catalog_stale": true,
        "catalog_unknown": false,
        "catalog_changes": ["agents/foo"],
        "version": "0.42.0",
        "supervised": false,
        "pid": 98606,
        "unsupervised_forced": true,
    }))
    .expect("full health body parses");
    assert_eq!(full.status, "ok");
    assert!(full.catalog_stale);
    assert!(!full.catalog_unknown);
    assert_eq!(full.version, "0.42.0");
    // #4230: the orphan-daemon signals must survive the client round-trip — the
    // `supervised` flag was already on the wire (#2486) and simply never parsed
    // on this side; `pid` and `unsupervised_forced` are new.
    assert_eq!(
        full.supervised,
        Some(false),
        "supervised:false must deserialize as Some(false)"
    );
    assert_eq!(full.pid, Some(98606));
    assert!(full.unsupervised_forced);

    let minimal: HealthSnapshot =
        serde_json::from_value(serde_json::json!({ "status": "ok" })).expect("minimal body parses");
    assert_eq!(minimal.status, "ok");
    assert!(!minimal.catalog_stale);
    assert!(!minimal.catalog_unknown);
    assert_eq!(minimal.version, "", "older daemon omitting version → empty");
    assert!(
        !minimal.unsupervised_forced,
        "absent force flag reads as not-forced"
    );
}

/// #4230 review: a daemon whose `/health` predates `supervised` must be
/// DISTINGUISHABLE from one that reports `true`. A `bool` with a `true` default
/// collapsed "cannot tell" into "fine" — a two-state answer to a three-state
/// question — and let the verdict return `Ok` on a daemon it knew nothing about.
#[test]
fn health_snapshot_supervised_is_none_when_absent() {
    let minimal: HealthSnapshot =
        serde_json::from_value(serde_json::json!({ "status": "ok" })).expect("minimal body parses");
    assert_eq!(
        minimal.supervised, None,
        "absent supervised field must be None, not a defaulted bool"
    );
}

/// #7822: a daemon predating `build_id` must parse, yielding `""` — the value
/// the staleness check reads as "cannot tell whether this build is current"
/// rather than as a match on the version string alone.
#[test]
fn health_snapshot_build_id_is_empty_when_absent() {
    let minimal: HealthSnapshot =
        serde_json::from_value(serde_json::json!({ "status": "ok" })).expect("minimal body parses");
    assert_eq!(minimal.build_id, "");

    let full: HealthSnapshot = serde_json::from_value(serde_json::json!({
        "status": "ok",
        "build_id": "1757731440:74125312",
    }))
    .expect("body with the field parses");
    assert_eq!(full.build_id, "1757731440:74125312");
}

/// #4230: an older daemon omits `pid`, so the authoritative PID comparison is
/// unavailable and the verdict must fall back rather than compare against a
/// fabricated zero.
#[test]
fn health_snapshot_pid_is_none_when_absent() {
    let minimal: HealthSnapshot =
        serde_json::from_value(serde_json::json!({ "status": "ok" })).expect("minimal body parses");
    assert_eq!(minimal.pid, None);
}

/// #8058: `degraded` is how a daemon says it has parked a subsystem, and a
/// daemon predating the field must still parse — as "nothing suspended", which
/// is also what a healthy daemon sends.
#[test]
fn health_snapshot_degraded_defaults_to_empty() {
    let minimal: HealthSnapshot =
        serde_json::from_value(serde_json::json!({ "status": "ok" })).expect("minimal body parses");
    assert!(minimal.degraded.is_empty());

    let suspended: HealthSnapshot = serde_json::from_value(serde_json::json!({
        "status": "ok",
        "degraded": ["pr-cleanup sweep suspended: run `gh auth login`"],
    }))
    .expect("body with the field parses");
    assert_eq!(suspended.degraded.len(), 1);
    assert!(suspended.degraded[0].contains("gh auth login"));
}

/// #4469: an older daemon that does not publish `launchd_supervision` must
/// parse, yielding the empty string rather than a hard error.
///
/// Why: the field is new; a newer client talking to an older daemon must fall
/// back to the `supervised` bool rather than failing to parse `/health` at all.
/// Test: this test.
#[test]
fn health_snapshot_launchd_supervision_defaults_to_empty() {
    let minimal: HealthSnapshot =
        serde_json::from_value(serde_json::json!({ "status": "ok" })).expect("minimal body parses");
    assert_eq!(minimal.launchd_supervision, "");

    let full: HealthSnapshot = serde_json::from_value(serde_json::json!({
        "status": "ok",
        "launchd_supervision": "unknown",
    }))
    .expect("body with the field parses");
    assert_eq!(full.launchd_supervision, "unknown");
}

/// Why (#5007): the daemon discloses a degraded store on the list response, and
/// every client that renders a listing reads it from this shared type. It must
/// deserialize when present and default to `None` against an older daemon that
/// never sends it — otherwise upgrading the CLI ahead of the daemon breaks
/// `tm ls` outright.
/// What: asserts both directions.
/// Test: this test.
#[test]
fn managed_list_response_carries_store_health_when_degraded() {
    let json = serde_json::json!({
        "sessions": [],
        "store_health": {
            "message": "/x/sessions.json is corrupt",
            "corrupt": true,
            "observed_at": "2026-08-06T09:01:17Z",
        },
    });
    let body: ManagedListResponse = serde_json::from_value(json).unwrap();
    let health = body.store_health.expect("store_health must deserialize");
    assert!(health.corrupt);
    assert_eq!(health.message, "/x/sessions.json is corrupt");

    let older: ManagedListResponse =
        serde_json::from_value(serde_json::json!({"sessions": []})).unwrap();
    assert!(
        older.store_health.is_none(),
        "a daemon that omits the field must still deserialize"
    );
}