cruise 0.1.35

YAML-driven coding agent workflow orchestrator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
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
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
use std::io::Write;

use console::style;
use inquire::InquireError;
use serde::Serialize;

use crate::cli::{DEFAULT_MAX_RETRIES, DEFAULT_RATE_LIMIT_RETRIES, ListArgs};
use crate::error::{CruiseError, Result};
use crate::multiline_input::{InputResult, prompt_multiline};
use crate::session::{SessionManager, SessionPhase, SessionState, WorkspaceMode, get_cruise_home};

/// CLI-only DTO for JSON output. Stable machine-readable form of `SessionState`.
/// `phase` is always a plain string; `phase_error` carries the failure message for Failed sessions.
#[derive(Debug, Serialize)]
struct ListSessionJson {
    id: String,
    base_dir: String,
    phase: &'static str,
    phase_error: Option<String>,
    plan_error: Option<String>,
    config_source: String,
    input: String,
    title: Option<String>,
    current_step: Option<String>,
    created_at: String,
    completed_at: Option<String>,
    worktree_path: Option<String>,
    worktree_branch: Option<String>,
    workspace_mode: WorkspaceMode,
    target_branch: Option<String>,
    pr_url: Option<String>,
    config_path: Option<String>,
    updated_at: Option<String>,
    awaiting_input: bool,
    plan_available: bool,
}

/// `Failed(msg)` is normalized to `phase = "Failed"` + `phase_error = Some(msg)`.
#[cfg(test)]
fn session_to_json(session: SessionState) -> ListSessionJson {
    session_to_json_with_plan_availability(session, false)
}

fn session_to_json_with_plan_availability(
    session: SessionState,
    plan_available: bool,
) -> ListSessionJson {
    let (phase, phase_error): (&'static str, Option<String>) = match session.phase {
        SessionPhase::AwaitingApproval => ("AwaitingApproval", None),
        SessionPhase::Planned => ("Planned", None),
        SessionPhase::Running => ("Running", None),
        SessionPhase::Completed => ("Completed", None),
        SessionPhase::Failed(msg) => ("Failed", Some(msg)),
        SessionPhase::Suspended => ("Suspended", None),
    };
    ListSessionJson {
        id: session.id,
        base_dir: session.base_dir.to_string_lossy().into_owned(),
        phase,
        phase_error,
        plan_error: session.plan_error,
        config_source: session.config_source,
        input: session.input,
        title: session.title,
        current_step: session.current_step,
        created_at: session.created_at,
        completed_at: session.completed_at,
        worktree_path: session
            .worktree_path
            .map(|p| p.to_string_lossy().into_owned()),
        worktree_branch: session.worktree_branch,
        workspace_mode: session.workspace_mode,
        target_branch: session.target_branch,
        pr_url: session.pr_url,
        config_path: session
            .config_path
            .map(|p| p.to_string_lossy().into_owned()),
        updated_at: session.updated_at,
        awaiting_input: session.awaiting_input,
        plan_available,
    }
}

/// Serialize a list of sessions to a JSON array (pretty-printed) followed by a newline.
#[cfg(test)]
fn write_sessions_json<W: Write>(mut writer: W, sessions: Vec<SessionState>) -> Result<()> {
    let dtos: Vec<ListSessionJson> = sessions.into_iter().map(session_to_json).collect();
    serde_json::to_writer_pretty(&mut writer, &dtos)
        .map_err(|e| CruiseError::Other(format!("JSON serialization error: {e}")))?;
    writer
        .write_all(b"\n")
        .map_err(|e| CruiseError::Other(format!("write error: {e}")))?;
    Ok(())
}

fn write_sessions_json_with_manager<W: Write>(
    mut writer: W,
    sessions: Vec<SessionState>,
    manager: &SessionManager,
) -> Result<()> {
    let dtos: Vec<ListSessionJson> = sessions
        .into_iter()
        .map(|session| {
            let plan_available = plan_available_for_session(&session, manager);
            session_to_json_with_plan_availability(session, plan_available)
        })
        .collect();
    serde_json::to_writer_pretty(&mut writer, &dtos)
        .map_err(|e| CruiseError::Other(format!("JSON serialization error: {e}")))?;
    writer
        .write_all(b"\n")
        .map_err(|e| CruiseError::Other(format!("write error: {e}")))?;
    Ok(())
}

#[expect(
    clippy::too_many_lines,
    reason = "interactive session picker with multiple action branches"
)]
pub async fn run(args: ListArgs) -> Result<()> {
    let manager = SessionManager::new(get_cruise_home()?);

    if args.json {
        let sessions = manager.list()?;
        write_sessions_json_with_manager(
            std::io::BufWriter::new(std::io::stdout()),
            sessions,
            &manager,
        )?;
        return Ok(());
    }

    loop {
        let Some(mut session) = pick_session(&manager)? else {
            return Ok(());
        };

        loop {
            let plan_available = plan_available_for_session(&session, &manager);

            // Show plan.md content.
            let plan_path = session.plan_path(&manager.sessions_dir());
            if let Ok(content) = std::fs::read_to_string(&plan_path) {
                crate::display::print_bordered(&content, Some("plan.md"));
            }

            // Action menu.
            let actions = session_actions_with_plan_availability(&session, plan_available);

            let action = match inquire::Select::new("Action:", actions).prompt() {
                Ok(a) => a,
                Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => "Back",
                Err(e) => return Err(CruiseError::Other(format!("selection error: {e}"))),
            };

            match action {
                "Approve" => {
                    if !plan_available || session.plan_error.is_some() {
                        eprintln!("{} plan is not ready for approval yet", style("!").yellow());
                        continue;
                    }
                    if let Err(err) =
                        crate::metadata::refresh_session_title_from_session(&manager, &mut session)
                    {
                        eprintln!("warning: failed to refresh session title: {err}");
                    }
                    session.approve();
                    manager.save(&session)?;
                    eprintln!(
                        "{} Session {} approved. Run with: {}",
                        style("v").green(),
                        session.id,
                        style(format!("cruise run {}", session.id)).cyan()
                    );
                }
                "Run" | "Resume" => {
                    let run_args = crate::cli::RunArgs {
                        session: Some(session.id.clone()),
                        all: false,
                        max_retries: DEFAULT_MAX_RETRIES,
                        rate_limit_retries: DEFAULT_RATE_LIMIT_RETRIES,
                        dry_run: false,
                    };
                    return crate::run_cmd::run(run_args).await;
                }
                "Replan" => {
                    let text = match prompt_multiline("Describe the changes needed:")? {
                        InputResult::Submitted(t) => t,
                        InputResult::Cancelled => continue,
                    };
                    crate::plan_cmd::replan_session(
                        &manager,
                        &mut session,
                        text,
                        DEFAULT_RATE_LIMIT_RETRIES,
                    )
                    .await?;
                    // Re-load so subsequent session_actions(&session) uses fresh state.
                    session = manager.load(&session.id)?;
                }
                "Open PR" => {
                    let url = session.pr_url.as_deref().ok_or_else(|| {
                        CruiseError::Other("Open PR action requires pr_url".into())
                    })?;
                    match open_pr_in_browser(url) {
                        Ok(()) => {
                            eprintln!("{} Opening PR in browser...", style("v").green());
                        }
                        Err(e) => {
                            eprintln!("{} {e}", style("x").red());
                        }
                    }
                }
                "Reset to Planned" => {
                    session.reset_to_planned();
                    manager.save(&session)?;
                    eprintln!(
                        "{} Session {} reset to Planned.",
                        style("v").green(),
                        session.id
                    );
                }
                "Delete" => {
                    manager.delete(&session.id)?;
                    eprintln!("{} Session {} deleted.", style("v").green(), session.id);
                    break;
                }
                _ => {
                    // "Back" -- return to the session list.
                    break;
                }
            }
        }
    }
}

/// Prompts the user to select a session from the list.
/// Returns `Ok(None)` if the list is empty or the user cancels.
fn pick_session(manager: &crate::session::SessionManager) -> Result<Option<SessionState>> {
    let sessions = manager.list()?;
    if sessions.is_empty() {
        eprintln!("No sessions found.");
        return Ok(None);
    }
    let labels: Vec<String> = sessions
        .iter()
        .map(|session| {
            format_session_label_with_plan_availability(
                session,
                plan_available_for_session(session, manager),
            )
        })
        .collect();
    let label_refs: Vec<&str> = labels.iter().map(std::string::String::as_str).collect();
    let selected = match inquire::Select::new("Select a session:", label_refs).prompt() {
        Ok(s) => s,
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => {
            return Ok(None);
        }
        Err(e) => return Err(CruiseError::Other(format!("selection error: {e}"))),
    };
    let Some(idx) = labels.iter().position(|l| l.as_str() == selected) else {
        return Err(CruiseError::Other(format!(
            "selected label not found: {selected}"
        )));
    };
    Ok(Some(sessions[idx].clone()))
}

/// Returns the action menu items available for the given session.
/// "Run"/"Resume" appears for runnable phases; "Replan" only for Planned.
/// "Open PR" appears for Completed sessions that have a PR URL.
/// "Reset to Planned" appears for Running, Failed, Completed, and Suspended.
/// "Delete" and "Back" are always present (in that order) at the end.
#[cfg(test)]
fn session_actions(session: &SessionState) -> Vec<&'static str> {
    let plan_available =
        !matches!(session.phase, SessionPhase::AwaitingApproval) || session.plan_error.is_none();
    session_actions_with_plan_availability(session, plan_available)
}

fn session_actions_with_plan_availability(
    session: &SessionState,
    plan_available: bool,
) -> Vec<&'static str> {
    let mut actions = vec![];
    match &session.phase {
        SessionPhase::AwaitingApproval => {
            if plan_available && session.plan_error.is_none() {
                actions.push("Approve");
            }
        }
        SessionPhase::Planned => {
            actions.push("Run");
            actions.push("Replan");
        }
        SessionPhase::Running | SessionPhase::Suspended => {
            actions.push("Resume");
            actions.push("Reset to Planned");
        }
        SessionPhase::Failed(_) => {
            actions.push("Run");
            actions.push("Reset to Planned");
        }
        SessionPhase::Completed => {
            if session.pr_url.is_some() {
                actions.push("Open PR");
            }
            actions.push("Reset to Planned");
        }
    }
    actions.push("Delete");
    actions.push("Back");
    actions
}

fn plan_available_for_session(session: &SessionState, manager: &SessionManager) -> bool {
    let plan_path = session.plan_path(&manager.sessions_dir());
    crate::metadata::plan_markdown_available(&plan_path)
}

fn open_pr_in_browser(pr_url: &str) -> crate::error::Result<()> {
    let status = std::process::Command::new("gh")
        .args(["pr", "view", pr_url, "--web"])
        .status()
        .map_err(|e| CruiseError::Other(format!("failed to run gh: {e}")))?;
    if !status.success() {
        return Err(CruiseError::Other(format!(
            "gh pr view --web exited with {status}"
        )));
    }
    Ok(())
}

#[cfg(test)]
fn format_session_label(s: &SessionState) -> String {
    let plan_available =
        !matches!(s.phase, SessionPhase::AwaitingApproval) || s.plan_error.is_none();
    format_session_label_with_plan_availability(s, plan_available)
}

fn format_session_label_with_plan_availability(s: &SessionState, plan_available: bool) -> String {
    let (icon, phase_str) = match &s.phase {
        SessionPhase::AwaitingApproval if s.plan_error.is_some() => {
            (style("✗").red(), style("Plan Failed").red())
        }
        SessionPhase::AwaitingApproval if !plan_available => {
            (style("◌").yellow(), style("Planning").yellow())
        }
        SessionPhase::AwaitingApproval => {
            (style("o").magenta(), style("Awaiting Approval").magenta())
        }
        SessionPhase::Planned => (style("o").cyan(), style("Planned").cyan()),
        SessionPhase::Running => (style(">").yellow(), style("Running").yellow()),
        SessionPhase::Completed => (style("v").green(), style("Completed").green()),
        SessionPhase::Failed(_) => (style("x").red(), style("Failed").red()),
        SessionPhase::Suspended => (style("||").yellow(), style("Suspended").yellow()),
    };
    let date = format_session_date(&s.id);
    let suffix = format_suffix(s);
    let input_preview = crate::display::truncate(s.title_or_input(), 60);
    format!("{icon} {date} {phase_str} {input_preview}{suffix}")
}

/// "`YYYYMMDDHHmmss`" -> "MM/DD HH:MM"
fn format_session_date(id: &str) -> String {
    let (Some(month), Some(day), Some(hour), Some(min)) =
        (id.get(4..6), id.get(6..8), id.get(8..10), id.get(10..12))
    else {
        return id.to_string();
    };
    format!("{month}/{day} {hour}:{min}")
}

/// Returns " \[`step_name`\]" for Running/Suspended, or " PR#N" for Completed with PR URL.
fn format_suffix(s: &SessionState) -> String {
    match &s.phase {
        SessionPhase::Running | SessionPhase::Suspended => s
            .current_step
            .as_ref()
            .map(|step| format!(" [{step}]"))
            .unwrap_or_default(),
        SessionPhase::Completed => s
            .pr_url
            .as_ref()
            .map(|url| {
                let num = url.trim_end_matches('/').rsplit('/').next().unwrap_or("");
                format!(" PR#{num}")
            })
            .unwrap_or_default(),
        _ => String::new(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    // -----------------------------------------------------------------------
    // session_actions
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_planned_has_run_and_replan() {
        // Given: Planned phase
        let session = make_session("20260306143000", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: contains "Run" and "Replan"; also contains "Delete" and "Back"
        assert!(
            actions.contains(&"Run"),
            "Planned should have Run: {actions:?}"
        );
        assert!(
            actions.contains(&"Replan"),
            "Planned should have Replan: {actions:?}"
        );
        assert!(
            actions.contains(&"Delete"),
            "should always have Delete: {actions:?}"
        );
        assert!(
            actions.contains(&"Back"),
            "should always have Back: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_planned_has_no_resume() {
        // Given: Planned phase
        let session = make_session("20260306143000", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: "Resume" is absent (Run is used for a fresh start, not Resume)
        assert!(
            !actions.contains(&"Resume"),
            "Planned should NOT have Resume: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_running_has_resume_not_replan() {
        // Given: Running phase
        let session = make_session("20260306143000", "task", SessionPhase::Running);

        // When
        let actions = session_actions(&session);

        // Then: "Resume" is present but "Replan" is absent
        assert!(
            actions.contains(&"Resume"),
            "Running should have Resume: {actions:?}"
        );
        assert!(
            !actions.contains(&"Replan"),
            "Running should NOT have Replan: {actions:?}"
        );
        assert!(
            !actions.contains(&"Run"),
            "Running should NOT have Run (use Resume): {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_failed_has_run_not_replan() {
        // Given: Failed phase
        let session = make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("some error".to_string()),
        );

        // When
        let actions = session_actions(&session);

        // Then: "Run" is present but "Replan" is absent
        assert!(
            actions.contains(&"Run"),
            "Failed should have Run: {actions:?}"
        );
        assert!(
            !actions.contains(&"Replan"),
            "Failed should NOT have Replan: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_completed_has_no_run_no_replan_has_reset() {
        // Given: Completed phase, no pr_url
        let session = make_session("20260306143000", "task", SessionPhase::Completed);

        // When
        let actions = session_actions(&session);

        // Then: "Run", "Resume", and "Replan" are absent; "Reset to Planned" is present
        assert!(
            !actions.contains(&"Run"),
            "Completed should NOT have Run: {actions:?}"
        );
        assert!(
            !actions.contains(&"Resume"),
            "Completed should NOT have Resume: {actions:?}"
        );
        assert!(
            !actions.contains(&"Replan"),
            "Completed should NOT have Replan: {actions:?}"
        );
        assert!(
            actions.contains(&"Reset to Planned"),
            "Completed should have Reset to Planned: {actions:?}"
        );
        assert!(
            actions.contains(&"Delete"),
            "should always have Delete: {actions:?}"
        );
        assert!(
            actions.contains(&"Back"),
            "should always have Back: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_planned_run_before_replan() {
        // Given: Planned phase
        let session = make_session("20260306143000", "task", SessionPhase::Planned);

        // When
        let actions = session_actions(&session);

        // Then: "Run" appears before "Replan" (primary action first)
        let run_pos = actions
            .iter()
            .position(|&a| a == "Run")
            .unwrap_or_else(|| panic!("unexpected None"));
        let replan_pos = actions
            .iter()
            .position(|&a| a == "Replan")
            .unwrap_or_else(|| panic!("unexpected None"));
        assert!(
            run_pos < replan_pos,
            "Run should come before Replan in actions list"
        );
    }

    #[test]
    fn test_session_actions_delete_and_back_always_at_end() {
        // Given: Delete and Back are the last two entries across all phases
        let sessions = [
            make_session("20260306143000", "task", SessionPhase::AwaitingApproval),
            make_session("20260306143000", "task", SessionPhase::Planned),
            make_session("20260306143000", "task", SessionPhase::Running),
            make_session("20260306143000", "task", SessionPhase::Completed),
            make_session(
                "20260306143000",
                "task",
                SessionPhase::Failed("err".to_string()),
            ),
        ];

        for session in &sessions {
            let phase = &session.phase;
            // When
            let actions = session_actions(session);
            let len = actions.len();

            // Then: Back is last, Delete is second-to-last
            assert!(
                len >= 2,
                "actions must have at least 2 items for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 1],
                "Back",
                "Back should be last for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 2],
                "Delete",
                "Delete should be second-to-last for {phase:?}: {actions:?}"
            );
        }
    }

    fn make_session(id: &str, input: &str, phase: SessionPhase) -> SessionState {
        let mut s = SessionState::new(
            id.to_string(),
            PathBuf::from("/tmp"),
            "cruise.yaml".to_string(),
            input.to_string(),
        );
        s.phase = phase;
        s
    }

    // -----------------------------------------------------------------------
    // format_session_date
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_session_date_standard_id_returns_mm_dd_hh_mm() {
        // Given: standard 14-digit session ID
        let id = "20260306143000";

        // When
        let result = format_session_date(id);

        // Then: converted to "MM/DD HH:MM" format
        assert_eq!(result, "03/06 14:30");
    }

    #[test]
    fn test_format_session_date_twelve_digit_id_is_accepted() {
        // Given: 12-digit (no seconds) ID
        let id = "202603061430";

        // When
        let result = format_session_date(id);

        // Then: converted to "03/06 14:30"
        assert_eq!(result, "03/06 14:30");
    }

    #[test]
    fn test_format_session_date_midnight() {
        // Given: session at midnight (00:00)
        let id = "20260101000000";

        // When
        let result = format_session_date(id);

        // Then
        assert_eq!(result, "01/01 00:00");
    }

    // -----------------------------------------------------------------------
    // format_suffix
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_suffix_running_with_step_returns_step_bracket() {
        // Given: Running phase, current_step present
        let mut s = make_session("20260306143000", "add feature", SessionPhase::Running);
        s.current_step = Some("implement".to_string());

        // When
        let result = format_suffix(&s);

        // Then: "[implement]" format
        assert_eq!(result, " [implement]");
    }

    #[test]
    fn test_format_suffix_running_without_step_returns_empty() {
        // Given: Running phase, no current_step
        let s = make_session("20260306143000", "add feature", SessionPhase::Running);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_suffix_completed_with_pr_url_returns_pr_number() {
        // Given: Completed phase, PR URL present
        let mut s = make_session("20260306143000", "add feature", SessionPhase::Completed);
        s.pr_url = Some("https://github.com/owner/repo/pull/42".to_string());

        // When
        let result = format_suffix(&s);

        // Then: "PR#42" format
        assert_eq!(result, " PR#42");
    }

    #[test]
    fn test_format_suffix_completed_without_pr_url_returns_empty() {
        // Given: Completed phase, no PR URL
        let s = make_session("20260306143000", "add feature", SessionPhase::Completed);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_suffix_planned_returns_empty() {
        // Given: Planned phase
        let s = make_session("20260306143000", "add feature", SessionPhase::Planned);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    #[test]
    fn test_format_suffix_failed_returns_empty() {
        // Given: Failed phase
        let s = make_session(
            "20260306143000",
            "add feature",
            SessionPhase::Failed("timeout".to_string()),
        );

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    // -----------------------------------------------------------------------
    // format_session_label (expected values for new format)
    // -----------------------------------------------------------------------

    /// Helper to strip ANSI escapes and verify label content.
    fn strip(s: &str) -> String {
        console::strip_ansi_codes(s).to_string()
    }

    #[test]
    fn test_format_session_label_planned_contains_icon_date_phase_input() {
        // Given: Planned session
        let s = make_session(
            "20260306143000",
            "add hello world feature",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains icon, date, phase, and input
        assert!(label.contains('o'), "should contain o icon: {label}");
        assert!(
            label.contains("03/06 14:30"),
            "should contain date: {label}"
        );
        assert!(label.contains("Planned"), "should contain phase: {label}");
        assert!(
            label.contains("add hello world feature"),
            "should contain input: {label}"
        );
    }

    #[test]
    fn test_format_session_label_running_contains_running_icon_and_step() {
        // Given: Running phase, current_step present
        let mut s = make_session("20260307150000", "implement auth", SessionPhase::Running);
        s.current_step = Some("test".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains > icon and step info
        assert!(label.contains('>'), "should contain > icon: {label}");
        assert!(label.contains("Running"), "should contain Running: {label}");
        assert!(label.contains("[test]"), "should contain step: {label}");
    }

    #[test]
    fn test_format_session_label_completed_with_pr_contains_checkmark_and_pr() {
        // Given: Completed phase, PR URL present
        let mut s = make_session("20260307090000", "refactor db", SessionPhase::Completed);
        s.pr_url = Some("https://github.com/owner/repo/pull/42".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains v icon and PR number
        assert!(label.contains('v'), "should contain v icon: {label}");
        assert!(
            label.contains("Completed"),
            "should contain Completed: {label}"
        );
        assert!(label.contains("PR#42"), "should contain PR#42: {label}");
    }

    #[test]
    fn test_format_session_label_failed_contains_cross_icon() {
        // Given: Failed phase
        let s = make_session(
            "20260307103000",
            "fix login bug",
            SessionPhase::Failed("exit 1".to_string()),
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains x icon
        assert!(label.contains('x'), "should contain x icon: {label}");
        assert!(label.contains("Failed"), "should contain Failed: {label}");
    }

    #[test]
    fn test_format_session_label_long_input_is_truncated() {
        // Given: very long input
        let long_input = "a".repeat(200);
        let s = make_session("20260306143000", &long_input, SessionPhase::Planned);

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains ellipsis "..." and total label length is 200 chars or less
        assert!(
            label.contains("..."),
            "long input should be truncated: {label}"
        );
    }

    #[test]
    fn test_format_session_label_prefers_title_over_input() {
        // Given: a session with both raw input and a generated title
        let mut s = make_session(
            "20260306143000",
            "raw task input that should not be the primary label",
            SessionPhase::Planned,
        );
        s.title = Some("Generated session title".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: the generated title is shown instead of the raw input
        assert!(
            label.contains("Generated session title"),
            "should contain generated title: {label}"
        );
        assert!(
            !label.contains("raw task input that should not be the primary label"),
            "should not contain raw input when title is present: {label}"
        );
    }

    #[test]
    fn test_format_session_label_falls_back_to_input_when_title_missing() {
        // Given: a session without a generated title
        let s = make_session(
            "20260306143000",
            "raw task input remains visible",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: the raw input remains the visible fallback
        assert!(
            label.contains("raw task input remains visible"),
            "should contain raw input fallback: {label}"
        );
    }

    // -----------------------------------------------------------------------
    // session_actions -- Reset to Planned coverage
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // session_actions -- Suspended
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_suspended_exact() {
        // Given / When / Then: Suspended action list matches expectations
        assert_eq!(
            session_actions(&make_session("test", "test", SessionPhase::Suspended)),
            vec!["Resume", "Reset to Planned", "Delete", "Back"]
        );
    }

    // -----------------------------------------------------------------------
    // format_suffix -- Suspended
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_suffix_suspended_with_step_returns_step_bracket() {
        // Given: Suspended phase, current_step present
        let mut s = make_session("20260310143000", "add feature", SessionPhase::Suspended);
        s.current_step = Some("implement".to_string());

        // When
        let result = format_suffix(&s);

        // Then: "[implement]" format
        assert_eq!(result, " [implement]");
    }

    #[test]
    fn test_format_suffix_suspended_without_step_returns_empty() {
        // Given: Suspended phase, no current_step
        let s = make_session("20260310143000", "add feature", SessionPhase::Suspended);

        // When
        let result = format_suffix(&s);

        // Then: empty string
        assert_eq!(result, "");
    }

    // -----------------------------------------------------------------------
    // format_session_label -- Suspended
    // -----------------------------------------------------------------------

    #[test]
    fn test_format_session_label_suspended_contains_phase_and_step() {
        // Given: Suspended phase, current_step present
        let mut s = make_session("20260310150000", "fix auth", SessionPhase::Suspended);
        s.current_step = Some("test".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains "Suspended" phase and the suspended step name
        assert!(
            label.contains("Suspended"),
            "should contain Suspended: {label}"
        );
        assert!(label.contains("[test]"), "should contain step: {label}");
    }

    // -----------------------------------------------------------------------
    // session_actions -- Delete/Back tail check (all phases including Suspended)
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_delete_and_back_always_at_end_including_suspended() {
        // Given: all phases including Suspended
        let phases = [
            SessionPhase::Planned,
            SessionPhase::Running,
            SessionPhase::Completed,
            SessionPhase::Failed("err".to_string()),
            SessionPhase::Suspended,
        ];

        for phase in &phases {
            // When
            let actions = session_actions(&make_session("test", "test", phase.clone()));
            let len = actions.len();

            // Then: Back is last, Delete is second-to-last
            assert!(
                len >= 2,
                "actions must have at least 2 items for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 1],
                "Back",
                "Back should be last for {phase:?}: {actions:?}"
            );
            assert_eq!(
                actions[len - 2],
                "Delete",
                "Delete should be second-to-last for {phase:?}: {actions:?}"
            );
        }
    }

    #[test]
    fn test_session_actions_planned_exact() {
        let session = make_session("20260306143000", "task", SessionPhase::Planned);
        assert_eq!(
            session_actions(&session),
            vec!["Run", "Replan", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_running_has_reset_to_planned() {
        let session = make_session("20260306143000", "task", SessionPhase::Running);
        assert_eq!(
            session_actions(&session),
            vec!["Resume", "Reset to Planned", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_completed_has_reset_to_planned() {
        // Given: Completed + no pr_url
        let session = make_session("20260306143000", "task", SessionPhase::Completed);
        assert_eq!(
            session_actions(&session),
            vec!["Reset to Planned", "Delete", "Back"]
        );
    }

    #[test]
    fn test_session_actions_failed_has_run_and_reset_to_planned() {
        let session = make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("exit 1".to_string()),
        );
        assert_eq!(
            session_actions(&session),
            vec!["Run", "Reset to Planned", "Delete", "Back"]
        );
    }

    // -----------------------------------------------------------------------
    // session_actions -- Open PR coverage
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_completed_with_pr_url_exact_order() {
        // Given: Completed + pr_url present
        let mut session = make_session("20260306143000", "task", SessionPhase::Completed);
        session.pr_url = Some("https://github.com/owner/repo/pull/10".to_string());

        // When
        let actions = session_actions(&session);

        // Then: order is ["Open PR", "Reset to Planned", "Delete", "Back"]
        assert_eq!(
            actions,
            vec!["Open PR", "Reset to Planned", "Delete", "Back"]
        );
    }

    // -----------------------------------------------------------------------
    // open_pr_in_browser
    // -----------------------------------------------------------------------

    #[cfg(unix)]
    #[test]
    fn test_open_pr_in_browser_calls_gh_view_web() {
        use std::os::unix::fs::PermissionsExt;
        use std::{fs, io::Read};

        let tmp = tempfile::tempdir().unwrap_or_else(|e| panic!("{e:?}"));
        let bin_dir = tmp.path().join("bin");
        fs::create_dir_all(&bin_dir).unwrap_or_else(|e| panic!("{e:?}"));
        let log_path = tmp.path().join("gh.log");

        // fake gh: records args to log file then exits 0
        let script_path = bin_dir.join("gh");
        fs::write(
            &script_path,
            format!(
                "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"{}\"\n",
                log_path.display()
            ),
        )
        .unwrap_or_else(|e| panic!("{e:?}"));
        let mut perms = fs::metadata(&script_path)
            .unwrap_or_else(|e| panic!("{e:?}"))
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap_or_else(|e| panic!("{e:?}"));

        let _guard = crate::test_binary_support::PathEnvGuard::prepend(&bin_dir);

        let url = "https://github.com/owner/repo/pull/42";
        let result = open_pr_in_browser(url);

        assert!(result.is_ok(), "should succeed: {result:?}");

        // Verify log: "pr view <url> --web" was passed
        let mut log_content = String::new();
        fs::File::open(&log_path)
            .unwrap_or_else(|e| panic!("{e:?}"))
            .read_to_string(&mut log_content)
            .unwrap_or_else(|e| panic!("{e:?}"));
        assert!(
            log_content.contains("pr view"),
            "gh should receive 'pr view': {log_content}"
        );
        assert!(
            log_content.contains(url),
            "gh should receive the PR url: {log_content}"
        );
        assert!(
            log_content.contains("--web"),
            "gh should receive '--web': {log_content}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_open_pr_in_browser_gh_failure_returns_error() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap_or_else(|e| panic!("{e:?}"));
        let bin_dir = tmp.path().join("bin");
        fs::create_dir_all(&bin_dir).unwrap_or_else(|e| panic!("{e:?}"));

        // fake gh: always exits 1
        let script_path = bin_dir.join("gh");
        fs::write(&script_path, "#!/bin/sh\nexit 1\n").unwrap_or_else(|e| panic!("{e:?}"));
        let mut perms = fs::metadata(&script_path)
            .unwrap_or_else(|e| panic!("{e:?}"))
            .permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap_or_else(|e| panic!("{e:?}"));

        let _guard = crate::test_binary_support::PathEnvGuard::prepend(&bin_dir);

        let result = open_pr_in_browser("https://github.com/owner/repo/pull/1");

        assert!(result.is_err(), "should fail when gh exits non-zero");
    }

    // -----------------------------------------------------------------------
    // AwaitingApproval phase -- actions and labels
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_actions_awaiting_approval_has_approve() {
        // Given: AwaitingApproval phase
        let session = make_session("20260311100000", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions(&session);

        // Then: contains "Approve" action
        assert!(
            actions.contains(&"Approve"),
            "AwaitingApproval should have Approve: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_awaiting_approval_has_no_run_no_resume() {
        // Given: AwaitingApproval phase
        let session = make_session("20260311100000", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions(&session);

        // Then: neither "Run" nor "Resume" since it is not yet approved
        assert!(
            !actions.contains(&"Run"),
            "AwaitingApproval should NOT have Run: {actions:?}"
        );
        assert!(
            !actions.contains(&"Resume"),
            "AwaitingApproval should NOT have Resume: {actions:?}"
        );
    }

    #[test]
    fn test_session_actions_awaiting_approval_exact_order() {
        // Given: AwaitingApproval phase
        let session = make_session("20260311100000", "task", SessionPhase::AwaitingApproval);

        // When / Then: order is Approve -> Delete -> Back
        assert_eq!(session_actions(&session), vec!["Approve", "Delete", "Back"]);
    }

    #[test]
    fn test_session_actions_awaiting_approval_with_plan_error_hides_approve() {
        // Given: background planning failed before approval
        let mut session = make_session("20260311100002", "task", SessionPhase::AwaitingApproval);
        session.plan_error = Some("model error".to_string());

        // When
        let actions = session_actions(&session);

        // Then: approval stays gated until planning succeeds again
        assert_eq!(actions, vec!["Delete", "Back"]);
    }

    #[test]
    fn test_session_actions_awaiting_approval_without_plan_hides_approve() {
        // Given: background planning is still in progress
        let session = make_session("20260311100004", "task", SessionPhase::AwaitingApproval);

        // When
        let actions = session_actions_with_plan_availability(&session, false);

        // Then: approval stays hidden until a real plan exists
        assert_eq!(actions, vec!["Delete", "Back"]);
    }

    #[test]
    fn test_format_session_label_awaiting_approval_contains_phase_text() {
        // Given: AwaitingApproval phase session
        let s = make_session(
            "20260311100000",
            "pending task",
            SessionPhase::AwaitingApproval,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: contains "Awaiting Approval" text and icon
        assert!(
            label.contains("Awaiting Approval"),
            "label should contain 'Awaiting Approval': {label}"
        );
        assert!(label.contains('o'), "label should contain o icon: {label}");
        assert!(
            label.contains("pending task"),
            "label should contain input: {label}"
        );
    }

    #[test]
    fn test_format_session_label_awaiting_approval_not_planned_text() {
        // Given: AwaitingApproval phase session
        let s = make_session(
            "20260311100001",
            "some task",
            SessionPhase::AwaitingApproval,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: "Planned" text is absent (to avoid phase confusion)
        assert!(
            !label.contains("Planned"),
            "AwaitingApproval label should NOT contain 'Planned': {label}"
        );
    }

    #[test]
    fn test_format_session_label_awaiting_approval_with_plan_error_shows_plan_failed() {
        // Given: background planning failed before approval
        let mut s = make_session(
            "20260311100003",
            "some task",
            SessionPhase::AwaitingApproval,
        );
        s.plan_error = Some("model error".to_string());

        // When
        let label = strip(&format_session_label(&s));

        // Then: the list surfaces the failure instead of looking approval-ready
        assert!(
            label.contains("Plan Failed"),
            "label should show Plan Failed: {label}"
        );
        assert!(
            !label.contains("Awaiting Approval"),
            "label should not look approval-ready: {label}"
        );
    }

    #[test]
    fn test_format_session_label_awaiting_approval_without_plan_shows_planning() {
        // Given: background planning has started but plan.md is not ready yet
        let s = make_session(
            "20260311100005",
            "some task",
            SessionPhase::AwaitingApproval,
        );

        // When
        let label = strip(&format_session_label_with_plan_availability(&s, false));

        // Then: the list shows an in-progress label instead of approval-ready text
        assert!(
            label.contains("Planning"),
            "label should show Planning: {label}"
        );
        assert!(
            !label.contains("Awaiting Approval"),
            "label should not show Awaiting Approval: {label}"
        );
    }

    // -- format_session_label: multiline input ---------------------------------

    #[test]
    fn test_format_session_label_multiline_input_shows_first_line_only() {
        // Given: session.input contains multiple lines (e.g. input with embedded newlines)
        let s = make_session(
            "20260306143000",
            "line1\nline2\nline3",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: only the first line appears in the label; remaining lines are absent
        assert!(
            label.contains("line1"),
            "label must contain first line: {label}"
        );
        assert!(
            !label.contains("line2"),
            "label must NOT contain second line: {label}"
        );
        assert!(
            !label.contains("line3"),
            "label must NOT contain third line: {label}"
        );
    }

    #[test]
    fn test_format_session_label_multiline_input_does_not_contain_newline_char() {
        // Given: multi-line input
        let s = make_session(
            "20260306143000",
            "implement feature\nwith extra detail",
            SessionPhase::Planned,
        );

        // When
        let label = strip(&format_session_label(&s));

        // Then: label contains no newline characters (displayable as a single list row)
        assert!(
            !label.contains('\n'),
            "label must not contain newline character: {label:?}"
        );
    }

    // -----------------------------------------------------------------------
    // session_to_json
    // -----------------------------------------------------------------------

    #[test]
    fn test_session_to_json_failed_phase_has_phase_string_and_error() {
        // Given: a session in Failed phase with an error message
        let session = make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("db error".to_string()),
        );

        // When
        let dto = session_to_json(session);

        // Then: phase is "Failed" and phase_error contains the message
        assert_eq!(dto.phase, "Failed");
        assert_eq!(dto.phase_error, Some("db error".to_string()));
    }

    #[test]
    fn test_session_to_json_all_non_failed_phases_have_null_phase_error() {
        // Given: all non-Failed phases
        let cases = [
            (SessionPhase::AwaitingApproval, "AwaitingApproval"),
            (SessionPhase::Planned, "Planned"),
            (SessionPhase::Running, "Running"),
            (SessionPhase::Completed, "Completed"),
            (SessionPhase::Suspended, "Suspended"),
        ];

        for (phase, expected_str) in cases {
            // When
            let session = make_session("20260306143000", "task", phase);
            let dto = session_to_json(session);

            // Then: phase string matches and phase_error is None
            assert_eq!(
                dto.phase, expected_str,
                "phase string mismatch for {expected_str}"
            );
            assert_eq!(
                dto.phase_error, None,
                "phase_error should be None for {expected_str}"
            );
        }
    }

    #[test]
    fn test_session_to_json_awaiting_approval_plan_error_is_preserved() {
        // Given: a session whose background planning failed before approval
        let mut session = make_session("20260306143000", "task", SessionPhase::AwaitingApproval);
        session.plan_error = Some("planner exited 1".to_string());

        // When
        let dto = session_to_json(session);
        let value =
            serde_json::to_value(&dto).unwrap_or_else(|e| panic!("serialization failed: {e}"));

        // Then: the durable planning error is exposed separately from run-phase failures
        assert_eq!(value["phase"], "AwaitingApproval");
        assert_eq!(value["phase_error"], serde_json::Value::Null);
        assert_eq!(value["plan_error"], "planner exited 1");
        assert_eq!(value["plan_available"], false);
    }

    #[test]
    fn test_session_to_json_with_plan_availability_sets_flag() {
        // Given: an AwaitingApproval session whose plan.md is ready
        let session = make_session("20260306143001", "task", SessionPhase::AwaitingApproval);

        // When
        let dto = session_to_json_with_plan_availability(session, true);
        let value =
            serde_json::to_value(&dto).unwrap_or_else(|e| panic!("serialization failed: {e}"));

        // Then
        assert_eq!(value["plan_available"], true);
    }

    #[test]
    fn test_session_to_json_path_fields_are_strings() {
        // Given: session with base_dir and optional path fields set
        let mut session = make_session("20260306143000", "task", SessionPhase::Planned);
        session.worktree_path = Some(PathBuf::from("/tmp/worktree"));
        session.config_path = Some(PathBuf::from("/home/user/config.yaml"));

        // When
        let dto = session_to_json(session);

        // Then: path fields are serialized as strings
        assert_eq!(dto.base_dir, "/tmp");
        assert_eq!(dto.worktree_path, Some("/tmp/worktree".to_string()));
        assert_eq!(dto.config_path, Some("/home/user/config.yaml".to_string()));
    }

    #[test]
    fn test_session_to_json_null_optional_paths_are_none() {
        let session = make_session("20260306143000", "task", SessionPhase::Planned);
        let dto = session_to_json(session);
        assert_eq!(dto.worktree_path, None);
        assert_eq!(dto.config_path, None);
    }

    #[test]
    fn test_session_to_json_id_and_input_are_preserved() {
        let session = make_session(
            "20260306143000",
            "my task description",
            SessionPhase::Planned,
        );
        let dto = session_to_json(session);
        assert_eq!(dto.id, "20260306143000");
        assert_eq!(dto.input, "my task description");
    }

    // -----------------------------------------------------------------------
    // write_sessions_json
    // -----------------------------------------------------------------------

    #[test]
    fn test_write_sessions_json_empty_list_produces_empty_json_array() {
        // Given: an empty session list
        let sessions: Vec<SessionState> = vec![];
        let mut buf = Vec::new();

        // When
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));

        // Then: output parses as a JSON array with 0 entries
        let output = String::from_utf8(buf).unwrap_or_else(|e| panic!("{e:?}"));
        let value: serde_json::Value =
            serde_json::from_str(&output).unwrap_or_else(|e| panic!("{e:?}"));
        assert!(value.is_array(), "output should be a JSON array");
        assert_eq!(
            value
                .as_array()
                .unwrap_or_else(|| panic!("expected JSON array"))
                .len(),
            0,
            "empty input should produce an empty array"
        );
    }

    #[test]
    fn test_write_sessions_json_multiple_sessions_produces_array_with_correct_ids() {
        // Given: two sessions with distinct IDs
        let sessions = vec![
            make_session("20260306143000", "task A", SessionPhase::Planned),
            make_session("20260306144500", "task B", SessionPhase::Completed),
        ];
        let mut buf = Vec::new();

        // When
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));

        // Then: JSON array contains 2 entries with the expected IDs
        let output = String::from_utf8(buf).unwrap_or_else(|e| panic!("{e:?}"));
        let value: serde_json::Value =
            serde_json::from_str(&output).unwrap_or_else(|e| panic!("{e:?}"));
        let arr = value
            .as_array()
            .unwrap_or_else(|| panic!("expected JSON array"));
        assert_eq!(arr.len(), 2, "should have 2 sessions");
        assert_eq!(arr[0]["id"], "20260306143000");
        assert_eq!(arr[1]["id"], "20260306144500");
    }

    #[test]
    fn test_write_sessions_json_failed_phase_is_normalized() {
        // Given: a session in Failed phase
        let sessions = vec![make_session(
            "20260306143000",
            "task",
            SessionPhase::Failed("some error".to_string()),
        )];
        let mut buf = Vec::new();

        // When
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));

        // Then: JSON entry has phase="Failed" and phase_error="some error"
        let output = String::from_utf8(buf).unwrap_or_else(|e| panic!("{e:?}"));
        let value: serde_json::Value =
            serde_json::from_str(&output).unwrap_or_else(|e| panic!("{e:?}"));
        let entry = &value
            .as_array()
            .unwrap_or_else(|| panic!("expected JSON array"))[0];
        assert_eq!(entry["phase"], "Failed");
        assert_eq!(entry["phase_error"], "some error");
    }

    #[test]
    fn test_write_sessions_json_output_ends_with_newline() {
        let sessions: Vec<SessionState> = vec![];
        let mut buf = Vec::new();
        write_sessions_json(&mut buf, sessions).unwrap_or_else(|e| panic!("{e:?}"));
        assert!(
            buf.ends_with(b"\n"),
            "JSON output should end with a newline"
        );
    }
}