travelagent 1.11.1

Agent-first TUI code review tool
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
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::io::Write as IoWrite;

use arboard::Clipboard;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};

use crate::app::{CommentTypeDefinition, DiffSource};
use travelagent_core::error::{Result, TrvError};
use travelagent_core::model::{
    AuthorKind, CommentTriage, CommentType, LineRange, LineSide, ReviewSession, TourCommentMeta,
    TourState,
};

/// (file_path, line_range, side, comment_type, author_kind, content)
type CommentEntry<'a> = (
    String,
    Option<LineRange>,
    Option<LineSide>,
    String,
    AuthorKind,
    &'a str,
);

/// Generate markdown content from the review session.
/// Returns the markdown string or an error if there are no comments.
pub fn generate_export_content(
    session: &ReviewSession,
    diff_source: &DiffSource,
    comment_types: &[CommentTypeDefinition],
    show_legend: bool,
) -> Result<String> {
    if !session.has_comments() {
        return Err(TrvError::NoComments);
    }
    Ok(generate_markdown(
        session,
        diff_source,
        comment_types,
        show_legend,
    ))
}

/// Copy an already-generated markdown string to the clipboard. Used after the
/// caller has applied any post-processing (e.g. appending tour triage).
pub fn copy_text_to_clipboard(content: &str) -> Result<String> {
    // Prefer OSC 52 in tmux/SSH where arboard may silently fail
    if should_prefer_osc52() {
        copy_osc52(content)?;
        return Ok("Review copied to clipboard (via terminal)".to_string());
    }

    // Try arboard (system clipboard) first, fall back to OSC 52 for SSH/remote sessions
    if let Ok(()) = Clipboard::new().and_then(|mut cb| cb.set_text(content)) {
        Ok("Review copied to clipboard".to_string())
    } else {
        // Fall back to OSC 52 escape sequence (works over SSH)
        copy_osc52(content)?;
        Ok("Review copied to clipboard (via terminal)".to_string())
    }
}

/// Returns true if we should prefer OSC 52 over the system clipboard.
///
/// In tmux or SSH sessions, arboard may "succeed" but copy to an inaccessible
/// X11 clipboard, so we use OSC 52 which works reliably in these environments.
fn should_prefer_osc52() -> bool {
    std::env::var("TMUX").is_ok()
        || std::env::var("SSH_TTY").is_ok()
        || std::env::var("ZELLIJ").is_ok()
}

/// Copy text to clipboard using OSC 52 escape sequence.
/// In tmux, raw OSC 52 is intercepted and may not reach the outer terminal.
/// We use `tmux load-buffer -w` which tells tmux to handle the clipboard copy itself.
fn copy_osc52(text: &str) -> Result<()> {
    if std::env::var("TMUX").is_ok() {
        copy_via_tmux(text)
    } else {
        let mut stdout = std::io::stdout().lock();
        write_osc52(&mut stdout, text)
    }
}

/// Copy text to the system clipboard via `tmux load-buffer -w -`.
/// The `-w` flag tells tmux to also forward to the outer terminal's clipboard via OSC 52.
fn copy_via_tmux(text: &str) -> Result<()> {
    use std::process::{Command, Stdio};

    let mut child = Command::new("tmux")
        .args(["load-buffer", "-w", "-"])
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|e| TrvError::Clipboard(format!("Failed to run tmux: {e}")))?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(text.as_bytes())
            .map_err(|e| TrvError::Clipboard(format!("Failed to write to tmux: {e}")))?;
    }

    let status = child
        .wait()
        .map_err(|e| TrvError::Clipboard(format!("tmux load-buffer failed: {e}")))?;

    if !status.success() {
        return Err(TrvError::Clipboard(
            "tmux load-buffer exited with error".to_string(),
        ));
    }

    Ok(())
}

/// Write OSC 52 escape sequence to the given writer.
/// Separated for testability.
fn write_osc52<W: IoWrite>(writer: &mut W, text: &str) -> Result<()> {
    let encoded = BASE64.encode(text);
    write!(writer, "\x1b]52;c;{encoded}\x07")
        .map_err(|e| TrvError::Clipboard(format!("Failed to write OSC 52: {e}")))?;
    writer
        .flush()
        .map_err(|e| TrvError::Clipboard(format!("Failed to flush: {e}")))?;
    Ok(())
}

fn review_scope_label(diff_source: &DiffSource) -> String {
    let scope = match diff_source {
        DiffSource::WorkingTree => "working tree changes".to_string(),
        DiffSource::StagedAndUnstaged => "staged + unstaged changes".to_string(),
        DiffSource::Staged => "staged changes".to_string(),
        DiffSource::Unstaged => "unstaged changes".to_string(),
        DiffSource::CommitRange(_) => "selected commit range".to_string(),
        DiffSource::StagedUnstagedAndCommits(_) => {
            "selected commit range + staged/unstaged changes".to_string()
        }
        DiffSource::Remote {
            pr_title,
            pr_number,
        } => {
            format!("PR #{pr_number}: {pr_title}")
        }
    };

    format!("Review Comment (scope: {scope})")
}

fn generate_markdown(
    session: &ReviewSession,
    diff_source: &DiffSource,
    comment_types: &[CommentTypeDefinition],
    show_legend: bool,
) -> String {
    let mut md = String::new();

    // Intro for agents
    let _ = writeln!(
        md,
        "I reviewed your code and have the following comments. Please address them."
    );
    let _ = writeln!(md);

    // Include commit range info if reviewing commits
    match diff_source {
        DiffSource::WorkingTree => {}
        DiffSource::Staged => {
            let _ = writeln!(md, "Reviewing staged changes");
            let _ = writeln!(md);
        }
        DiffSource::Unstaged => {
            let _ = writeln!(md, "Reviewing unstaged changes");
            let _ = writeln!(md);
        }
        DiffSource::StagedAndUnstaged => {
            let _ = writeln!(md, "Reviewing staged + unstaged changes");
            let _ = writeln!(md);
        }
        DiffSource::CommitRange(commits) => {
            if commits.len() == 1 {
                let _ = writeln!(
                    md,
                    "Reviewing commit: {}",
                    &commits[0][..7.min(commits[0].len())]
                );
            } else {
                let short_ids: Vec<&str> = commits.iter().map(|c| &c[..7.min(c.len())]).collect();
                let _ = writeln!(md, "Reviewing commits: {}", short_ids.join(", "));
            }
            let _ = writeln!(md);
        }
        DiffSource::StagedUnstagedAndCommits(commits) => {
            let short_ids: Vec<&str> = commits.iter().map(|c| &c[..7.min(c.len())]).collect();
            let _ = writeln!(
                md,
                "Reviewing staged + unstaged + commits: {}",
                short_ids.join(", ")
            );
            let _ = writeln!(md);
        }
        DiffSource::Remote {
            pr_title,
            pr_number,
        } => {
            let _ = writeln!(md, "Reviewing PR #{pr_number}: {pr_title}");
            let _ = writeln!(md);
        }
    }

    if show_legend {
        let used_ids = collect_used_comment_type_ids(session);
        let legend = if comment_types.is_empty() {
            let all: &[(&str, &str)] = &[
                ("ISSUE", "problems to fix"),
                ("SUGGESTION", "improvements"),
                ("NOTE", "observations"),
                ("QUESTION", "requires answer"),
                ("PRAISE", "positive feedback"),
            ];
            let filtered: Vec<String> = if used_ids.is_empty() {
                all.iter()
                    .map(|(name, def)| format!("{name} ({def})"))
                    .collect()
            } else {
                all.iter()
                    .filter(|(name, _)| used_ids.contains(&name.to_ascii_lowercase()))
                    .map(|(name, def)| format!("{name} ({def})"))
                    .collect()
            };
            filtered.join(", ")
        } else {
            let filtered: Vec<_> = comment_types
                .iter()
                .filter(|ct| used_ids.is_empty() || used_ids.contains(&ct.id))
                .collect();
            filtered
                .iter()
                .map(|comment_type| {
                    let definition = comment_type
                        .definition
                        .as_deref()
                        .unwrap_or(comment_type.id.as_str());
                    format!(
                        "{} ({})",
                        comment_type.label.to_ascii_uppercase(),
                        definition
                    )
                })
                .collect::<Vec<_>>()
                .join(", ")
        };
        let _ = writeln!(md, "Comment types: {legend}");
        let _ = writeln!(md);
    }

    // Session notes/summary
    if let Some(notes) = &session.session_notes {
        let _ = writeln!(md, "Summary: {notes}");
        let _ = writeln!(md);
    }

    // Collect all comments into a flat list
    let mut all_comments: Vec<CommentEntry> = Vec::new();
    let review_comment_location = review_scope_label(diff_source);

    for comment in &session.review_comments {
        all_comments.push((
            review_comment_location.clone(),
            None,
            None,
            export_comment_type_label(&comment.comment_type, comment_types),
            comment.author_kind,
            &comment.content,
        ));
    }

    // Sort files by path for consistent output
    let mut files: Vec<_> = session.files.iter().collect();
    files.sort_by_key(|(path, _)| path.to_string_lossy().to_string());

    for (path, review) in files {
        let path_str = path.display().to_string();

        // File comments (no line number)
        for comment in &review.file_comments {
            all_comments.push((
                path_str.clone(),
                None,
                None,
                export_comment_type_label(&comment.comment_type, comment_types),
                comment.author_kind,
                &comment.content,
            ));
        }

        // Line comments (with line number, sorted)
        let mut line_comments: Vec<_> = review.line_comments.iter().collect();
        line_comments.sort_by_key(|(line, _)| *line);

        for (line, comments) in line_comments {
            for comment in comments {
                // Use comment's line_range if available, otherwise use the key line
                let line_range = comment
                    .line_range
                    .or_else(|| Some(LineRange::single(*line)));
                all_comments.push((
                    path_str.clone(),
                    line_range,
                    comment.side,
                    export_comment_type_label(&comment.comment_type, comment_types),
                    comment.author_kind,
                    &comment.content,
                ));
            }
        }
    }

    // Output numbered list
    for (i, (file, line_range, side, comment_type, author_kind, content)) in
        all_comments.iter().enumerate()
    {
        let location = match (line_range, side) {
            // Range on deleted side (old lines)
            (Some(range), Some(LineSide::Old)) if range.is_single() => {
                format!("`{}:~{}`", file, range.start)
            }
            (Some(range), Some(LineSide::Old)) => {
                format!("`{}:~{}-~{}`", file, range.start, range.end)
            }
            // Range on new/context side
            (Some(range), _) if range.is_single() => {
                format!("`{}:{}`", file, range.start)
            }
            (Some(range), _) => {
                format!("`{}:{}-{}`", file, range.start, range.end)
            }
            // File comment
            (None, _) => format!("`{file}`"),
        };
        // Agent-authored comments carry an explicit `[agent]` tag so the
        // attribution that used to live as a body suffix (`_(via MCP agent)_`)
        // still reaches the exported markdown. Human comments render without
        // an author tag to keep the common case clean.
        let author_tag = match author_kind {
            AuthorKind::McpAgent => " _[agent]_",
            AuthorKind::Human => "",
        };
        let _ = writeln!(
            md,
            "{}. **[{}]**{} {} - {}",
            i + 1,
            comment_type,
            author_tag,
            location,
            content
        );
    }

    md
}

/// Append a "Tour triage" section to an existing exported markdown document.
/// Skipped if there are no triaged tour comments. Live comments are listed
/// first, then likely-obsolete, then moved — so the human sees the must-do
/// items at the top.
pub fn append_tour_triage(
    markdown: &mut String,
    comments: &HashMap<String, TourCommentMeta>,
    triage: &HashMap<String, CommentTriage>,
) {
    use travelagent_core::model::TourTriageVerdict;
    if triage.is_empty() {
        return;
    }
    let _ = writeln!(markdown);
    let _ = writeln!(markdown, "## Tour triage");
    let _ = writeln!(markdown);
    // Group by verdict in the order we want to render.
    let verdict_order = [
        TourTriageVerdict::Live,
        TourTriageVerdict::LikelyObsolete,
        TourTriageVerdict::Moved,
    ];
    for verdict in verdict_order {
        let mut rows: Vec<(&String, &CommentTriage, Option<&TourCommentMeta>)> = triage
            .iter()
            .filter(|(_, t)| t.verdict == verdict)
            .map(|(id, t)| (id, t, comments.get(id)))
            .collect();
        if rows.is_empty() {
            continue;
        }
        rows.sort_by_key(|(_, _, meta)| meta.map_or(usize::MAX, |m| m.stop_index));
        let header = match verdict {
            TourTriageVerdict::Live => "Live (still applies)",
            TourTriageVerdict::LikelyObsolete => "Likely obsolete (auto-resolved by later commits)",
            TourTriageVerdict::Moved => "Moved (applies at a new location)",
        };
        let _ = writeln!(markdown, "### {header}");
        let _ = writeln!(markdown);
        for (_, t, meta) in rows {
            let location = match meta {
                Some(m) => format!("{}:{} (stop {})", m.file, m.line, m.stop_index + 1),
                None => "(unknown)".to_string(),
            };
            let loc_suffix = match (&t.new_location, &verdict) {
                (Some(nl), TourTriageVerdict::Moved) => format!("{}:{}", nl.file, nl.line),
                _ => String::new(),
            };
            let _ = writeln!(markdown, "- `{location}`{loc_suffix}: {}", t.reasoning);
        }
        let _ = writeln!(markdown);
    }
}

/// Append a "Tour stops" section grouping triaged comments under `## Stop N: summary`
/// sub-headings — one per stop that has at least one triaged comment. Skipped
/// entirely when no tour metadata is present. This gives humans a commit-by-commit
/// view of what the agent found, in the same order the tour was walked.
pub fn append_tour_stops(
    markdown: &mut String,
    tour: &TourState,
    comments: &HashMap<String, TourCommentMeta>,
    triage: &HashMap<String, CommentTriage>,
) {
    use travelagent_core::model::TourTriageVerdict;
    if comments.is_empty() {
        return;
    }

    // Bucket triaged comments by stop_index.
    type StopRow<'a> = (&'a String, &'a TourCommentMeta, Option<&'a CommentTriage>);
    let mut by_stop: HashMap<usize, Vec<StopRow>> = HashMap::new();
    for (id, meta) in comments {
        by_stop
            .entry(meta.stop_index)
            .or_default()
            .push((id, meta, triage.get(id)));
    }
    if by_stop.is_empty() {
        return;
    }

    let _ = writeln!(markdown);
    let _ = writeln!(markdown, "## Tour stops");
    let _ = writeln!(markdown);

    for (index, stop) in tour.stops.iter().enumerate() {
        let Some(mut rows) = by_stop.remove(&index) else {
            continue;
        };
        rows.sort_by_key(|(_, m, _)| (m.file.clone(), m.line));
        let summary = stop.summary.trim();
        let heading = if summary.is_empty() {
            format!("Stop {}", index + 1)
        } else {
            format!("Stop {}: {}", index + 1, summary)
        };
        let _ = writeln!(markdown, "### {heading}");
        let _ = writeln!(markdown);
        for (_, meta, t) in rows {
            let verdict = t.map(|t| match t.verdict {
                TourTriageVerdict::Live => "live",
                TourTriageVerdict::LikelyObsolete => "likely obsolete",
                TourTriageVerdict::Moved => "moved",
            });
            let reasoning = t.map_or("(not triaged)", |t| t.reasoning.as_str());
            let verdict_tag = match verdict {
                Some(v) => format!("[{v}] "),
                None => String::new(),
            };
            let _ = writeln!(
                markdown,
                "- `{}:{}` {verdict_tag}{reasoning}",
                meta.file, meta.line
            );
        }
        let _ = writeln!(markdown);
    }
}

/// Phase I6: append a "Sparring summary" section listing the spec
/// comments captured during the review. Emitted only when the caller
/// decides the review is sparring-scope (e.g. `spar_mode` at export
/// time); no-op when the session has no spec comments. Keeps the
/// export surface stable for non-sparring reviews.
pub fn append_sparring_summary(markdown: &mut String, session: &ReviewSession) {
    use travelagent_core::model::{AnchorState, CommentType};
    let is_spec =
        |c: &travelagent_core::model::Comment| matches!(c.comment_type, CommentType::Spec);
    let n = session.spec_count();
    if n == 0 {
        return;
    }
    let _ = writeln!(markdown);
    let _ = writeln!(markdown, "## Sparring summary");
    let _ = writeln!(markdown);
    let _ = writeln!(
        markdown,
        "{n} spec{} captured during this review.",
        if n == 1 { "" } else { "s" }
    );
    let _ = writeln!(markdown);

    // Review-scope specs first (no file anchor).
    let review_specs: Vec<_> = session
        .review_comments
        .iter()
        .filter(|c| is_spec(c))
        .collect();
    if !review_specs.is_empty() {
        let _ = writeln!(markdown, "### Review-scope specs");
        let _ = writeln!(markdown);
        for c in review_specs {
            let _ = writeln!(markdown, "- {}", c.content);
        }
        let _ = writeln!(markdown);
    }

    // File-/line-/orphaned-scope specs grouped by path for readability.
    let mut paths: Vec<_> = session.files.keys().collect();
    paths.sort();
    for path in paths {
        let Some(fr) = session.files.get(path) else {
            continue;
        };
        // Buffer the file's spec rows so we can decide whether to
        // render the `### path` heading at all (skip files that have
        // no specs without leaving an empty header behind).
        let mut rows: Vec<String> = Vec::new();
        for c in fr.file_comments.iter().filter(|c| is_spec(c)) {
            rows.push(format!("- (file): {}", c.content));
        }
        let mut line_rows: Vec<(u32, &travelagent_core::model::Comment)> = fr
            .line_comments
            .iter()
            .flat_map(|(line, cs)| cs.iter().filter(|c| is_spec(c)).map(move |c| (*line, c)))
            .collect();
        line_rows.sort_by_key(|(line, _)| *line);
        for (line, c) in line_rows {
            let side = match c.side {
                Some(LineSide::Old) => "old",
                _ => "new",
            };
            rows.push(format!("- line {line} ({side}): {}", c.content));
        }
        for c in fr.orphaned_comments.iter().filter(|c| is_spec(c)) {
            let was_line = match c.anchor.as_ref() {
                Some(AnchorState::Orphaned { was_line, .. }) => Some(*was_line),
                _ => None,
            };
            let loc = match was_line {
                Some(l) => format!("orphaned (was line {l})"),
                None => "orphaned".to_string(),
            };
            rows.push(format!("- {loc}: {}", c.content));
        }
        if rows.is_empty() {
            continue;
        }
        let _ = writeln!(markdown, "### `{}`", path.display());
        let _ = writeln!(markdown);
        for row in rows {
            let _ = writeln!(markdown, "{row}");
        }
        let _ = writeln!(markdown);
    }
}

fn collect_used_comment_type_ids(session: &ReviewSession) -> HashSet<String> {
    let mut ids = HashSet::new();
    for c in &session.review_comments {
        ids.insert(c.comment_type.id().to_string());
    }
    for review in session.files.values() {
        for c in &review.file_comments {
            ids.insert(c.comment_type.id().to_string());
        }
        for comments in review.line_comments.values() {
            for c in comments {
                ids.insert(c.comment_type.id().to_string());
            }
        }
    }
    ids
}

fn export_comment_type_label(
    comment_type: &CommentType,
    comment_types: &[CommentTypeDefinition],
) -> String {
    if let Some(definition) = comment_types
        .iter()
        .find(|definition| definition.id == comment_type.id())
    {
        return definition.label.to_ascii_uppercase();
    }

    comment_type.to_label()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::CommentTypeDefinition;
    use std::path::PathBuf;
    use travelagent_core::model::{
        Comment, CommentType, FileStatus, LineRange, LineSide, SessionDiffSource,
    };

    fn comment_types() -> Vec<CommentTypeDefinition> {
        vec![
            CommentTypeDefinition {
                id: "note".to_string(),
                label: "note".to_string(),
                definition: Some("observations".to_string()),
                color: None,
            },
            CommentTypeDefinition {
                id: "suggestion".to_string(),
                label: "suggestion".to_string(),
                definition: Some("improvements".to_string()),
                color: None,
            },
            CommentTypeDefinition {
                id: "issue".to_string(),
                label: "issue".to_string(),
                definition: Some("problems to fix".to_string()),
                color: None,
            },
            CommentTypeDefinition {
                id: "praise".to_string(),
                label: "praise".to_string(),
                definition: Some("positive feedback".to_string()),
                color: None,
            },
            CommentTypeDefinition {
                id: "question".to_string(),
                label: "question".to_string(),
                definition: Some("requires answer".to_string()),
                color: None,
            },
        ]
    }

    fn create_test_session() -> ReviewSession {
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);

        // Add a file comment
        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            review.reviewed = true;
            review.add_file_comment(Comment::new(
                "Consider adding documentation".to_string(),
                CommentType::Suggestion,
                None,
            ));
            review.add_line_comment(
                42,
                Comment::new(
                    "Magic number should be a constant".to_string(),
                    CommentType::Issue,
                    Some(LineSide::New),
                ),
            );
        }

        session
    }

    #[test]
    fn should_generate_valid_markdown() {
        // given
        let session = create_test_session();
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("I reviewed your code and have the following comments"));
        assert!(
            markdown.contains("Comment types: SUGGESTION (improvements), ISSUE (problems to fix)")
        );
        assert!(!markdown.contains("NOTE"));
        assert!(!markdown.contains("PRAISE"));
        assert!(markdown.contains("[SUGGESTION]"));
        assert!(markdown.contains("`src/main.rs`"));
        assert!(markdown.contains("Consider adding documentation"));
        assert!(markdown.contains("[ISSUE]"));
        assert!(markdown.contains("`src/main.rs:42`"));
        assert!(markdown.contains("Magic number"));
    }

    #[test]
    fn should_use_configured_label_and_definition_in_export() {
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);
        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            review.add_file_comment(Comment::new(
                "Needs clarification".to_string(),
                CommentType::Note,
                None,
            ));
        }

        let custom_types = vec![CommentTypeDefinition {
            id: "note".to_string(),
            label: "question".to_string(),
            definition: Some("ask for clarification".to_string()),
            color: None,
        }];

        let markdown = generate_markdown(&session, &DiffSource::WorkingTree, &custom_types, true);

        assert!(markdown.contains("Comment types: QUESTION (ask for clarification)"));
        assert!(markdown.contains("**[QUESTION]**"));
    }

    #[test]
    fn should_number_comments_sequentially() {
        // given
        let session = create_test_session();
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        // Should have 2 numbered comments
        assert!(markdown.contains("1. **[SUGGESTION]**"));
        assert!(markdown.contains("2. **[ISSUE]**"));
    }

    #[test]
    fn should_include_review_comments_in_export() {
        let mut session = create_test_session();
        session.review_comments.push(Comment::new(
            "Please split this into smaller commits".to_string(),
            CommentType::Note,
            None,
        ));

        let markdown =
            generate_markdown(&session, &DiffSource::WorkingTree, &comment_types(), true);

        assert!(markdown
            .contains("`Review Comment (scope: working tree changes)` - Please split this into smaller commits"));
    }

    #[test]
    fn should_include_commit_range_scope_for_review_comments() {
        let mut session = create_test_session();
        session.review_comments.push(Comment::new(
            "High-level concern across commits".to_string(),
            CommentType::Issue,
            None,
        ));

        let markdown = generate_markdown(
            &session,
            &DiffSource::CommitRange(vec!["abc1234567890".to_string()]),
            &comment_types(),
            true,
        );

        assert!(markdown.contains(
            "`Review Comment (scope: selected commit range)` - High-level concern across commits"
        ));
    }

    #[test]
    fn should_fail_export_when_no_comments() {
        // given
        let session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        let diff_source = DiffSource::WorkingTree;

        // when
        let result = generate_export_content(&session, &diff_source, &comment_types(), true);

        // then
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), TrvError::NoComments));
    }

    #[test]
    fn should_generate_export_content_with_comments() {
        // given
        let session = create_test_session();
        let diff_source = DiffSource::WorkingTree;

        // when
        let result = generate_export_content(&session, &diff_source, &comment_types(), true);

        // then
        assert!(result.is_ok());
        let content = result.unwrap();
        assert!(content.contains("I reviewed your code"));
        assert!(content.contains("[SUGGESTION]"));
        assert!(content.contains("[ISSUE]"));
    }

    #[test]
    fn should_fail_generate_export_content_when_no_comments() {
        // given
        let session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        let diff_source = DiffSource::WorkingTree;

        // when
        let result = generate_export_content(&session, &diff_source, &comment_types(), true);

        // then
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), TrvError::NoComments));
    }

    #[test]
    fn should_include_commit_range_in_markdown() {
        // given
        let session = create_test_session();
        let diff_source = DiffSource::CommitRange(vec![
            "abc1234567890".to_string(),
            "def4567890123".to_string(),
        ]);

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("Reviewing commits: abc1234, def4567"));
    }

    #[test]
    fn should_include_single_commit_in_markdown() {
        // given
        let session = create_test_session();
        let diff_source = DiffSource::CommitRange(vec!["abc1234567890".to_string()]);

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("Reviewing commit: abc1234"));
    }

    #[test]
    fn should_write_osc52_escape_sequence() {
        // given
        let text = "Hello, World!";
        let mut buffer: Vec<u8> = Vec::new();

        // when
        write_osc52(&mut buffer, text).unwrap();

        // then
        let output = String::from_utf8(buffer).unwrap();
        // OSC 52 format: ESC ] 52 ; c ; <base64> BEL
        assert!(output.starts_with("\x1b]52;c;"));
        assert!(output.ends_with('\x07'));
        // Verify the base64 content
        let base64_content = &output[7..output.len() - 1];
        assert_eq!(BASE64.encode(text), base64_content);
    }

    #[test]
    fn should_encode_empty_string_in_osc52() {
        // given
        let text = "";
        let mut buffer: Vec<u8> = Vec::new();

        // when
        write_osc52(&mut buffer, text).unwrap();

        // then
        let output = String::from_utf8(buffer).unwrap();
        assert_eq!(output, "\x1b]52;c;\x07");
    }

    #[test]
    fn should_encode_unicode_in_osc52() {
        // given
        let text = "こんにちは 🦀";
        let mut buffer: Vec<u8> = Vec::new();

        // when
        write_osc52(&mut buffer, text).unwrap();

        // then
        let output = String::from_utf8(buffer).unwrap();
        let base64_content = &output[7..output.len() - 1];
        // Decode and verify it matches original
        let decoded = String::from_utf8(BASE64.decode(base64_content).unwrap()).unwrap();
        assert_eq!(decoded, text);
    }

    #[test]
    fn should_encode_markdown_content_in_osc52() {
        // given - simulate what would be copied during export
        let session = create_test_session();
        let diff_source = DiffSource::WorkingTree;
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);
        let mut buffer: Vec<u8> = Vec::new();

        // when
        write_osc52(&mut buffer, &markdown).unwrap();

        // then
        let output = String::from_utf8(buffer).unwrap();
        assert!(output.starts_with("\x1b]52;c;"));
        assert!(output.ends_with('\x07'));
        // Verify we can decode the base64 back to the original markdown
        let base64_content = &output[7..output.len() - 1];
        let decoded = String::from_utf8(BASE64.decode(base64_content).unwrap()).unwrap();
        assert_eq!(decoded, markdown);
    }

    #[test]
    fn should_export_single_line_range_as_single_line() {
        // given - a comment with a single-line range should display as L42, not L42-L42
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);

        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            let range = LineRange::single(42);
            review.add_line_comment(
                42,
                Comment::new_with_range(
                    "Single line comment".to_string(),
                    CommentType::Note,
                    Some(LineSide::New),
                    range,
                ),
            );
        }
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("`src/main.rs:42`"));
        assert!(!markdown.contains("`src/main.rs:42-42`"));
    }

    #[test]
    fn should_export_line_range_with_start_and_end() {
        // given - a comment spanning multiple lines
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);

        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            let range = LineRange::new(10, 15);
            review.add_line_comment(
                15, // keyed by end line
                Comment::new_with_range(
                    "Multi-line comment".to_string(),
                    CommentType::Issue,
                    Some(LineSide::New),
                    range,
                ),
            );
        }
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("`src/main.rs:10-15`"));
        assert!(markdown.contains("Multi-line comment"));
    }

    #[test]
    fn should_export_old_side_line_range_with_tilde() {
        // given - a range comment on deleted lines (old side)
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);

        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            let range = LineRange::new(20, 25);
            review.add_line_comment(
                25, // keyed by end line
                Comment::new_with_range(
                    "Deleted lines comment".to_string(),
                    CommentType::Suggestion,
                    Some(LineSide::Old),
                    range,
                ),
            );
        }
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("`src/main.rs:~20-~25`"));
    }

    #[test]
    fn should_export_single_old_side_line_with_tilde() {
        // given - a single line comment on a deleted line
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);

        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            let range = LineRange::single(30);
            review.add_line_comment(
                30,
                Comment::new_with_range(
                    "Single deleted line".to_string(),
                    CommentType::Note,
                    Some(LineSide::Old),
                    range,
                ),
            );
        }
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("`src/main.rs:~30`"));
        assert!(!markdown.contains("`src/main.rs:~30-~30`"));
    }

    #[test]
    fn should_handle_comment_without_line_range_field() {
        // given - backward compatibility: comment without line_range uses line number
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);

        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            // Use Comment::new which sets line_range to None
            review.add_line_comment(
                50,
                Comment::new(
                    "Old style comment".to_string(),
                    CommentType::Note,
                    Some(LineSide::New),
                ),
            );
        }
        let diff_source = DiffSource::WorkingTree;

        // when
        let markdown = generate_markdown(&session, &diff_source, &comment_types(), true);

        // then
        assert!(markdown.contains("`src/main.rs:50`"));
    }

    #[test]
    fn should_omit_legend_when_show_legend_is_false() {
        let session = create_test_session();
        let diff_source = DiffSource::WorkingTree;

        let markdown = generate_markdown(&session, &diff_source, &comment_types(), false);

        assert!(!markdown.contains("Comment types:"));
        assert!(markdown.contains("[SUGGESTION]"));
        assert!(markdown.contains("[ISSUE]"));
    }

    #[test]
    fn should_only_list_used_comment_types_in_legend() {
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);
        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            review.add_file_comment(Comment::new(
                "Great work!".to_string(),
                CommentType::Praise,
                None,
            ));
        }

        let markdown =
            generate_markdown(&session, &DiffSource::WorkingTree, &comment_types(), true);

        assert!(markdown.contains("Comment types: PRAISE (positive feedback)"));
        assert!(!markdown.contains("NOTE"));
        assert!(!markdown.contains("SUGGESTION"));
        assert!(!markdown.contains("ISSUE"));
    }

    #[test]
    fn append_tour_triage_is_no_op_when_empty() {
        let mut md = String::from("prior content\n");
        let comments: HashMap<String, TourCommentMeta> = HashMap::new();
        let triage: HashMap<String, CommentTriage> = HashMap::new();
        append_tour_triage(&mut md, &comments, &triage);
        assert_eq!(md, "prior content\n");
    }

    #[test]
    fn append_tour_triage_groups_by_verdict_and_preserves_reasoning() {
        use travelagent_core::model::{NewCommentLocation, TourTriageVerdict};
        let mut md = String::from("base\n");
        let mut comments = HashMap::new();
        comments.insert(
            "c1".to_string(),
            TourCommentMeta {
                stop_index: 0,
                stop_commit_shas: vec!["aaa".into()],
                file: "src/a.rs".into(),
                line: 10,
            },
        );
        comments.insert(
            "c2".to_string(),
            TourCommentMeta {
                stop_index: 2,
                stop_commit_shas: vec!["ccc".into()],
                file: "src/b.rs".into(),
                line: 20,
            },
        );
        let mut triage = HashMap::new();
        triage.insert(
            "c1".to_string(),
            CommentTriage {
                verdict: TourTriageVerdict::Live,
                reasoning: "still broken".into(),
                new_location: None,
            },
        );
        triage.insert(
            "c2".to_string(),
            CommentTriage {
                verdict: TourTriageVerdict::Moved,
                reasoning: "renamed".into(),
                new_location: Some(NewCommentLocation {
                    file: "src/b2.rs".into(),
                    line: 25,
                }),
            },
        );
        append_tour_triage(&mut md, &comments, &triage);

        assert!(md.contains("## Tour triage"));
        assert!(md.contains("### Live (still applies)"));
        assert!(md.contains("src/a.rs:10 (stop 1)"));
        assert!(md.contains("still broken"));
        assert!(md.contains("### Moved (applies at a new location)"));
        assert!(md.contains("→ src/b2.rs:25"));
        assert!(md.contains("renamed"));
    }

    #[test]
    fn append_tour_stops_groups_by_stop_index_with_summary() {
        use travelagent_core::model::{TourState, TourStop, TourTriageVerdict};
        let tour = TourState::new(vec![
            TourStop {
                commit_ids: vec!["aaa".into()],
                summary: "Add cli parser".into(),
                risk: travelagent_core::risk::RiskScore::MIN,
            },
            TourStop {
                commit_ids: vec!["bbb".into()],
                summary: String::new(),
                risk: travelagent_core::risk::RiskScore::MIN,
            },
        ]);
        let mut comments = HashMap::new();
        comments.insert(
            "c1".to_string(),
            TourCommentMeta {
                stop_index: 0,
                stop_commit_shas: vec!["aaa".into()],
                file: "src/cli.rs".into(),
                line: 12,
            },
        );
        comments.insert(
            "c2".to_string(),
            TourCommentMeta {
                stop_index: 1,
                stop_commit_shas: vec!["bbb".into()],
                file: "src/main.rs".into(),
                line: 99,
            },
        );
        let mut triage = HashMap::new();
        triage.insert(
            "c1".to_string(),
            CommentTriage {
                verdict: TourTriageVerdict::Live,
                reasoning: "still applies".into(),
                new_location: None,
            },
        );
        let mut md = String::from("base\n");
        append_tour_stops(&mut md, &tour, &comments, &triage);

        assert!(md.contains("## Tour stops"));
        assert!(md.contains("### Stop 1: Add cli parser"));
        assert!(md.contains("### Stop 2"));
        assert!(!md.contains("### Stop 2:"));
        assert!(md.contains("`src/cli.rs:12` [live] still applies"));
        assert!(md.contains("`src/main.rs:99` (not triaged)"));
    }

    #[test]
    fn append_tour_stops_is_no_op_when_no_tour_comments() {
        use travelagent_core::model::{TourState, TourStop};
        let tour = TourState::new(vec![TourStop {
            commit_ids: vec!["aaa".into()],
            summary: "only stop".into(),
            risk: travelagent_core::risk::RiskScore::MIN,
        }]);
        let mut md = String::from("prior\n");
        append_tour_stops(&mut md, &tour, &HashMap::new(), &HashMap::new());
        assert_eq!(md, "prior\n");
    }

    #[test]
    fn should_only_list_used_custom_types_in_legend() {
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc1234def".to_string(),
            Some("main".to_string()),
            SessionDiffSource::WorkingTree,
        );
        session.add_file(PathBuf::from("src/main.rs"), FileStatus::Modified);
        if let Some(review) = session.get_file_mut(&PathBuf::from("src/main.rs")) {
            review.add_file_comment(Comment::new(
                "Needs clarification".to_string(),
                CommentType::Note,
                None,
            ));
        }

        let custom_types = vec![
            CommentTypeDefinition {
                id: "note".to_string(),
                label: "question".to_string(),
                definition: Some("ask for clarification".to_string()),
                color: None,
            },
            CommentTypeDefinition {
                id: "issue".to_string(),
                label: "issue".to_string(),
                definition: Some("problems to fix".to_string()),
                color: None,
            },
        ];

        let markdown = generate_markdown(&session, &DiffSource::WorkingTree, &custom_types, true);

        assert!(markdown.contains("Comment types: QUESTION (ask for clarification)"));
        assert!(!markdown.contains("ISSUE"));
    }

    // ── append_sparring_summary (Phase I6) ──

    #[test]
    fn append_sparring_summary_is_no_op_without_specs() {
        let session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc".to_string(),
            None,
            SessionDiffSource::WorkingTree,
        );
        let mut md = String::from("prior\n");
        append_sparring_summary(&mut md, &session);
        assert_eq!(md, "prior\n");
    }

    #[test]
    fn append_sparring_summary_groups_specs_by_scope() {
        use travelagent_core::model::review::FileReview;
        use travelagent_core::model::{Comment, CommentType, FileStatus};

        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc".to_string(),
            None,
            SessionDiffSource::WorkingTree,
        );
        session.review_comments.push(Comment::new(
            "top-level spec".into(),
            CommentType::Spec,
            None,
        ));
        let path = PathBuf::from("src/a.rs");
        let mut fr = FileReview::new(path.clone(), FileStatus::Modified);
        fr.add_file_comment(Comment::new(
            "whole-file spec".into(),
            CommentType::Spec,
            None,
        ));
        fr.add_line_comment(
            42,
            Comment::new("line spec".into(), CommentType::Spec, Some(LineSide::New)),
        );
        // Non-spec comment must be ignored.
        fr.add_file_comment(Comment::new("not a spec".into(), CommentType::Note, None));
        session.files.insert(path, fr);

        let mut md = String::new();
        append_sparring_summary(&mut md, &session);

        assert!(md.contains("## Sparring summary"));
        assert!(md.contains("3 specs captured"));
        assert!(md.contains("### Review-scope specs"));
        assert!(md.contains("top-level spec"));
        assert!(md.contains("### `src/a.rs`"));
        assert!(md.contains("(file): whole-file spec"));
        assert!(md.contains("line 42 (new): line spec"));
        assert!(!md.contains("not a spec"));
    }

    #[test]
    fn append_sparring_summary_singular_when_exactly_one() {
        use travelagent_core::model::{Comment, CommentType};
        let mut session = ReviewSession::new(
            PathBuf::from("/tmp/test-repo"),
            "abc".to_string(),
            None,
            SessionDiffSource::WorkingTree,
        );
        session
            .review_comments
            .push(Comment::new("just one".into(), CommentType::Spec, None));
        let mut md = String::new();
        append_sparring_summary(&mut md, &session);
        assert!(md.contains("1 spec captured"));
        // No plural.
        assert!(!md.contains("1 specs"));
    }
}