repotoire 0.9.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
//! Diff command — compare findings between two analysis states
//!
//! Shows new findings, fixed findings, and score delta.

use anyhow::{Context, Result};
use std::path::Path;
use std::time::Instant;

use crate::models::{Finding, FindingsSummary, Grade, HealthReport, Severity};
use console::style;
use serde_json::json;

use super::diff_hunks::{Attribution, DiffHunks};

/// Check if two findings refer to the same logical issue.
///
/// Uses fuzzy matching: same detector, same file, line within ±3.
/// File-level findings (no line) match if detector and file match.
fn findings_match(a: &Finding, b: &Finding) -> bool {
    a.detector == b.detector
        && a.affected_files.first() == b.affected_files.first()
        && match (a.line_start, b.line_start) {
            (Some(la), Some(lb)) => la.abs_diff(lb) <= 3,
            (None, None) => true,
            _ => false,
        }
}

/// Result of diffing two sets of findings (raw, before attribution).
#[derive(Debug)]
struct DiffResult {
    base_ref: String,
    head_ref: String,
    new_findings: Vec<Finding>,
    fixed_findings: Vec<Finding>,
    score_before: Option<f64>,
    score_after: Option<f64>,
}

/// A finding with its attribution (how it relates to the diff).
#[derive(Debug, Clone)]
pub struct AttributedFinding {
    pub finding: Finding,
    pub attribution: Attribution,
}

/// Result of a smart diff with attribution.
#[derive(Debug)]
pub struct SmartDiffResult {
    pub base_ref: String,
    pub head_ref: String,
    pub files_changed: usize,
    pub new_findings: Vec<AttributedFinding>,
    pub all_new_count: usize,
    pub fixed_findings: Vec<Finding>,
    pub score_before: Option<f64>,
    pub score_after: Option<f64>,
    /// Accounted suppressions (`// repotoire:ignore[detector] — <reason>`) that matched a finding
    /// in the head analysis. Empty when nothing was suppressed with a recognised reason. Surfaced
    /// in `--format json` so the (later) harvest pipeline has signal; `accepted-risk` events are
    /// flagged `harvestable: false`.
    pub suppression_events: Vec<crate::models::SuppressionEvent>,
    /// Count of `Tier::Blocking` findings suppressed with a bare `// repotoire:ignore` (no
    /// accounted reason). Non-zero means the gate still fails ("suppressed without an accounted
    /// reason") even though the finding is absent from `new_findings`.
    pub suppressed_unaccounted_blocking_count: usize,
}

impl SmartDiffResult {
    pub fn score_delta(&self) -> Option<f64> {
        match (self.score_before, self.score_after) {
            (Some(before), Some(after)) => Some(after - before),
            _ => None,
        }
    }

    /// Extract just the Finding structs (for APIs that need &[Finding]).
    pub fn findings_only(&self) -> Vec<Finding> {
        self.new_findings
            .iter()
            .map(|af| af.finding.clone())
            .collect()
    }

    /// Extract hunk-level findings only.
    pub fn hunk_findings(&self) -> Vec<Finding> {
        self.new_findings
            .iter()
            .filter(|af| af.attribution == Attribution::InChangedHunk)
            .map(|af| af.finding.clone())
            .collect()
    }
}

/// Compute the diff between baseline and head findings.
fn diff_findings(
    baseline: &[Finding],
    head: &[Finding],
    base_ref: &str,
    head_ref: &str,
    score_before: Option<f64>,
    score_after: Option<f64>,
) -> DiffResult {
    let new_findings: Vec<Finding> = head
        .iter()
        .filter(|h| !baseline.iter().any(|b| findings_match(b, h)))
        .cloned()
        .collect();

    let fixed_findings: Vec<Finding> = baseline
        .iter()
        .filter(|b| !head.iter().any(|h| findings_match(b, h)))
        .cloned()
        .collect();

    DiffResult {
        base_ref: base_ref.to_string(),
        head_ref: head_ref.to_string(),
        new_findings,
        fixed_findings,
        score_before,
        score_after,
    }
}

// ---------------------------------------------------------------------------
// Output formatters
// ---------------------------------------------------------------------------

fn severity_icon(severity: &Severity) -> &'static str {
    match severity {
        Severity::Critical => "[C]",
        Severity::High => "[H]",
        Severity::Medium => "[M]",
        Severity::Low => "[L]",
        Severity::Info => "[I]",
    }
}

/// A finding's tier as it should be presented in the diff: `Blocking` findings lead the report;
/// everything else (Advisory, Deep) is shown under "Advisory".
fn is_blocking(finding: &Finding) -> bool {
    finding.tier >= crate::models::Tier::Blocking
}

/// Render a `SourceSpan` as `path:line` (just the start line — that's what reads in a terminal).
fn span_loc(span: &crate::models::SourceSpan) -> String {
    format!("{}:{}", span.file.display(), span.line_start)
}

/// Mask a secret value, keeping only its last 4 characters visible.
/// Used for the inline `Evidence::Secret` rendering — the format name already says *what* it is;
/// the masked tail is enough to find it in the file without leaking it into a CI log.
fn mask_secret(raw: &str) -> String {
    let trimmed = raw
        .trim()
        .trim_matches(|c| c == '"' || c == '\'' || c == '`');
    let n = trimmed.chars().count();
    if n <= 4 {
        "****".to_string()
    } else {
        let tail: String = trimmed.chars().skip(n.saturating_sub(4)).collect();
        format!("****…{tail}")
    }
}

/// Render a finding's evidence inline as a single human-readable line (or `None` if it has none).
fn render_evidence_inline(finding: &Finding) -> Option<String> {
    use crate::models::Evidence;
    match finding.evidence.as_ref()? {
        Evidence::TaintPath {
            source,
            sink,
            sink_kind,
            ..
        } => Some(format!(
            "tainted flow: {}{} sink at {}",
            span_loc(source),
            sink_kind,
            span_loc(sink)
        )),
        Evidence::Secret { span, format, .. } => {
            let masked = span
                .snippet
                .as_deref()
                .map(mask_secret)
                .unwrap_or_else(|| "(redacted)".to_string());
            Some(format!("{format}: {masked} at {}", span_loc(span)))
        }
        Evidence::ConfigFact { span, rule } => Some(format!("{rule} at {}", span_loc(span))),
    }
}

/// Format a single finding line for text output.
fn format_finding_line(out: &mut String, finding: &Finding, _no_emoji: bool) {
    let file = finding
        .affected_files
        .first()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    let line = finding
        .line_start
        .map(|l| format!(":{l}"))
        .unwrap_or_default();
    out.push_str(&format!(
        "  {} {:<40} {}{}\n",
        severity_icon(&finding.severity),
        &finding.title.chars().take(40).collect::<String>(),
        file,
        line
    ));
}

/// Format a blocking finding: the headline line, then its evidence indented underneath, then the
/// suppress-with-a-reason instruction (the only legitimate way to make the gate pass without a fix).
fn format_blocking_finding(out: &mut String, finding: &Finding, no_emoji: bool) {
    format_finding_line(out, finding, no_emoji);
    if let Some(ev) = render_evidence_inline(finding) {
        out.push_str(&format!("      {}\n", style(ev).dim()));
    }
    out.push_str(&format!(
        "      {}\n",
        style(format!(
            "fix it, or — if it's an accepted risk — // repotoire:ignore[{}] — <reason>",
            finding.detector
        ))
        .dim()
    ));
}

/// Severity × confidence weight, for ordering findings within a section (most-worth-a-glance first).
fn severity_confidence_rank(finding: &Finding) -> f64 {
    let sev = match finding.severity {
        Severity::Critical => 5.0,
        Severity::High => 4.0,
        Severity::Medium => 3.0,
        Severity::Low => 2.0,
        Severity::Info => 1.0,
    };
    sev * finding.confidence.unwrap_or(0.5)
}

/// Sort attributed findings by [`severity_confidence_rank`], highest first.
fn sort_by_rank_desc(findings: &mut [&AttributedFinding]) {
    findings.sort_by(|a, b| {
        severity_confidence_rank(&b.finding)
            .partial_cmp(&severity_confidence_rank(&a.finding))
            .unwrap_or(std::cmp::Ordering::Equal)
    });
}

/// Render the diff result as colored terminal text.
///
/// Leads with `Blocking` findings (each with its evidence inline) under the "🛑 Blocking" header,
/// then the `Advisory` findings, then — only when `show_score` is set — the score delta.
/// When `no_emoji` is true, plain ASCII markers are used instead of emoji.
pub fn format_text(result: &SmartDiffResult, no_emoji: bool, show_score: bool) -> String {
    let mut out = String::new();

    // Header
    out.push_str(&format!(
        "Repotoire Diff: {}..{} ({} files changed)\n\n",
        result.base_ref, result.head_ref, result.files_changed,
    ));

    // ── Blocking — leads the report ─────────────────────────────────────
    let mut blocking: Vec<_> = result
        .new_findings
        .iter()
        .filter(|af| is_blocking(&af.finding))
        .collect();
    sort_by_rank_desc(&mut blocking);

    if blocking.is_empty() {
        let check = if no_emoji { "[ok]" } else { "\u{2705}" };
        out.push_str(&format!(
            "{} {}\n\n",
            check,
            style("Nothing in this change trips the gate.").green()
        ));
        if result.suppressed_unaccounted_blocking_count > 0 {
            out.push_str(&format!(
                "{}\n\n",
                style(format!(
                    "(but {} blocking finding{} suppressed with a bare `// repotoire:ignore` — \
                     the gate still fails; use `// repotoire:ignore[detector] — <reason>`)",
                    result.suppressed_unaccounted_blocking_count,
                    if result.suppressed_unaccounted_blocking_count == 1 {
                        " is"
                    } else {
                        "s are"
                    }
                ))
                .red()
            ));
        }
    } else {
        let stop = if no_emoji { "" } else { "\u{1f6d1} " };
        out.push_str(&format!(
            "{}{}\n",
            stop,
            style(format!(
                "Blocking — fix before this merges ({} finding{})",
                blocking.len(),
                if blocking.len() == 1 { "" } else { "s" }
            ))
            .red()
            .bold()
        ));
        for af in &blocking {
            format_blocking_finding(&mut out, &af.finding, no_emoji);
        }
        out.push('\n');
    }

    // ── Advisory ────────────────────────────────────────────────────────
    let mut advisory: Vec<_> = result
        .new_findings
        .iter()
        .filter(|af| !is_blocking(&af.finding))
        .collect();
    sort_by_rank_desc(&mut advisory);

    if !advisory.is_empty() {
        out.push_str(&format!(
            "{}\n",
            style(format!(
                "Advisory ({} finding{})",
                advisory.len(),
                if advisory.len() == 1 { "" } else { "s" }
            ))
            .bold()
        ));
        // A per-line attribution marker only when the set is mixed (hunk + non-hunk) — keeps the
        // common "all in your changes" case uncluttered.
        let mixed = advisory
            .iter()
            .any(|af| af.attribution != Attribution::InChangedHunk)
            && advisory
                .iter()
                .any(|af| af.attribution == Attribution::InChangedHunk);
        for af in &advisory {
            format_finding_line(&mut out, &af.finding, no_emoji);
            if mixed && af.attribution != Attribution::InChangedHunk {
                out.push_str(&format!(
                    "      {}\n",
                    style("(pre-existing — not introduced by this change)").dim()
                ));
            }
        }
        out.push('\n');
    }

    // Findings filtered out of the report by the attribution scope (`--all` shows them).
    let hidden = result
        .all_new_count
        .saturating_sub(result.new_findings.len());
    if hidden > 0 {
        let info_icon = if no_emoji { "i" } else { "\u{2139}\u{fe0f}" };
        out.push_str(&format!(
            "{} {} finding{} in other files (use --all to see)\n\n",
            style(info_icon).dim(),
            hidden,
            if hidden == 1 { "" } else { "s" }
        ));
    }

    // Fixed findings
    if !result.fixed_findings.is_empty() {
        let prefix = if no_emoji { "" } else { "\u{2728} " };
        out.push_str(&format!(
            "{}{} finding{} fixed\n",
            prefix,
            result.fixed_findings.len(),
            if result.fixed_findings.len() == 1 {
                ""
            } else {
                "s"
            }
        ));
    }

    // ── Score (de-emphasised — only on request) ─────────────────────────
    if show_score {
        if let (Some(before), Some(after)) = (result.score_before, result.score_after) {
            let delta = after - before;
            let delta_str = if delta >= 0.0 {
                style(format!("+{:.1}", delta)).green().to_string()
            } else {
                style(format!("{:.1}", delta)).red().to_string()
            };
            out.push_str(&format!(
                "\nScore: {:.1} \u{2192} {:.1} ({})\n",
                before, after, delta_str,
            ));
        }
    }

    out
}

/// Render the diff result as clean Markdown (no ANSI escapes).
pub fn format_markdown(result: &SmartDiffResult) -> String {
    let mut out = String::new();

    out.push_str(&format!(
        "# Repotoire Diff: {}..{} ({} files changed)\n\n",
        result.base_ref, result.head_ref, result.files_changed,
    ));

    let hunk_findings: Vec<_> = result
        .new_findings
        .iter()
        .filter(|af| af.attribution == Attribution::InChangedHunk)
        .collect();
    let file_findings: Vec<_> = result
        .new_findings
        .iter()
        .filter(|af| af.attribution == Attribution::InChangedFile)
        .collect();
    let unrelated_findings: Vec<_> = result
        .new_findings
        .iter()
        .filter(|af| af.attribution == Attribution::InUnchangedFile)
        .collect();

    if result.new_findings.is_empty() && result.all_new_count > 0 {
        out.push_str("**No new findings in your changes.**\n\n");
        out.push_str(&format!(
            "> {} finding{} in other files (use `--all` to see)\n\n",
            result.all_new_count,
            if result.all_new_count == 1 { "" } else { "s" }
        ));
    } else if result.new_findings.is_empty() {
        out.push_str("**No new findings.**\n\n");
    } else {
        if !hunk_findings.is_empty() {
            out.push_str(&format!(
                "## Your Changes ({} finding{})\n\n",
                hunk_findings.len(),
                if hunk_findings.len() == 1 { "" } else { "s" }
            ));
            out.push_str("| Severity | Finding | Location |\n");
            out.push_str("|----------|---------|----------|\n");
            for af in &hunk_findings {
                format_markdown_row(&mut out, &af.finding);
            }
            out.push('\n');
        }

        if !file_findings.is_empty() {
            out.push_str(&format!(
                "## Pre-existing ({} in changed files)\n\n",
                file_findings.len()
            ));
            out.push_str("| Severity | Finding | Location |\n");
            out.push_str("|----------|---------|----------|\n");
            for af in &file_findings {
                format_markdown_row(&mut out, &af.finding);
            }
            out.push('\n');
        }

        if !unrelated_findings.is_empty() {
            out.push_str(&format!(
                "## Unrelated ({} in unchanged files)\n\n",
                unrelated_findings.len()
            ));
            out.push_str("| Severity | Finding | Location |\n");
            out.push_str("|----------|---------|----------|\n");
            for af in &unrelated_findings {
                format_markdown_row(&mut out, &af.finding);
            }
            out.push('\n');
        }
    }

    // Score delta
    if let (Some(before), Some(after)) = (result.score_before, result.score_after) {
        let delta = after - before;
        let sign = if delta >= 0.0 { "+" } else { "" };
        out.push_str(&format!(
            "**Score:** {:.1} \u{2192} {:.1} ({}{:.1})\n\n",
            before, after, sign, delta,
        ));
    }

    if !result.fixed_findings.is_empty() {
        out.push_str(&format!(
            "{} finding{} fixed\n",
            result.fixed_findings.len(),
            if result.fixed_findings.len() == 1 {
                ""
            } else {
                "s"
            }
        ));
    }

    out
}

/// Format a single finding as a Markdown table row.
fn format_markdown_row(out: &mut String, finding: &Finding) {
    let file = finding
        .affected_files
        .first()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    let line = finding
        .line_start
        .map(|l| format!(":{l}"))
        .unwrap_or_default();
    let title: String = finding
        .title
        .chars()
        .take(60)
        .collect::<String>()
        .replace('|', "\\|");
    out.push_str(&format!(
        "| {} | {} | `{}{}` |\n",
        finding.severity, title, file, line
    ));
}

/// Render the diff result as pretty-printed JSON.
pub fn format_json(result: &SmartDiffResult) -> String {
    let all_findings = result.findings_only();
    let new_summary = FindingsSummary::from_findings(&all_findings);
    let fixed_summary = FindingsSummary::from_findings(&result.fixed_findings);

    let score_delta = result.score_delta();

    let new_findings_json: Vec<serde_json::Value> = result
        .new_findings
        .iter()
        .map(|af| {
            json!({
                "detector": af.finding.detector,
                "severity": af.finding.severity.to_string(),
                "tier": af.finding.tier.to_string(),
                "evidence": af.finding.evidence,
                "confidence": af.finding.confidence,
                "suppressed": af.finding.suppressed,
                "suppression_reason": af.finding.suppression_reason,
                "title": af.finding.title,
                "description": af.finding.description,
                "file": af.finding.affected_files.first().map(|p| p.display().to_string()).unwrap_or_default(),
                "line": af.finding.line_start,
                "attribution": match af.attribution {
                    Attribution::InChangedHunk => "in_changed_hunk",
                    Attribution::InChangedFile => "in_changed_file",
                    Attribution::InUnchangedFile => "in_unchanged_file",
                },
            })
        })
        .collect();

    let fixed_findings_json: Vec<serde_json::Value> = result
        .fixed_findings
        .iter()
        .map(|f| {
            json!({
                "detector": f.detector,
                "severity": f.severity.to_string(),
                "title": f.title,
                "file": f.affected_files.first().map(|p| p.display().to_string()).unwrap_or_default(),
                "line": f.line_start,
            })
        })
        .collect();

    let output = json!({
        "base_ref": result.base_ref,
        "head_ref": result.head_ref,
        "files_changed": result.files_changed,
        "total_new_findings": result.all_new_count,
        "new_findings": new_findings_json,
        "fixed_findings": fixed_findings_json,
        "suppression_events": result.suppression_events,
        "suppressed_unaccounted_blocking_count": result.suppressed_unaccounted_blocking_count,
        "score_before": result.score_before,
        "score_after": result.score_after,
        "score_delta": score_delta,
        "summary": {
            "new": {
                "critical": new_summary.critical,
                "high": new_summary.high,
                "medium": new_summary.medium,
                "low": new_summary.low,
            },
            "fixed": {
                "critical": fixed_summary.critical,
                "high": fixed_summary.high,
                "medium": fixed_summary.medium,
                "low": fixed_summary.low,
            },
        },
    });

    serde_json::to_string_pretty(&output).expect("JSON serialization should not fail")
}

/// Render the diff result as SARIF 2.1.0 (only hunk-level findings).
///
/// Builds a temporary `HealthReport` containing only the hunk findings,
/// then delegates to the existing SARIF reporter.
pub fn format_sarif(result: &SmartDiffResult) -> anyhow::Result<String> {
    let hunk_findings = result.hunk_findings();
    let report = HealthReport {
        overall_score: result.score_after.unwrap_or(0.0),
        grade: Grade::default(),
        structure_score: 0.0,
        quality_score: 0.0,
        architecture_score: None,
        findings_summary: FindingsSummary::from_findings(&hunk_findings),
        findings: hunk_findings,
        total_files: 0,
        total_functions: 0,
        total_classes: 0,
        total_loc: 0,
        suppression_events: Vec::new(),
        suppressed_unaccounted_blocking_count: 0,
    };

    crate::reporters::report_with_format(&report, crate::reporters::OutputFormat::Sarif)
}

/// Run analysis inline and cache results so diff can load them.
fn run_inline_analysis(repo_path: &Path, repotoire_dir: &Path) -> Result<()> {
    let session_dir = repotoire_dir.join("session");
    let mut engine = match crate::engine::AnalysisEngine::load(&session_dir, repo_path, false) {
        Ok(e) => e,
        Err(_) => crate::engine::AnalysisEngine::new(repo_path, false)?,
    };

    let config = crate::engine::AnalysisConfig::default();
    let result = engine.analyze(&config)?;

    // Build a HealthReport for cache_results
    let findings_summary = FindingsSummary::from_findings(&result.findings);
    let report = crate::models::HealthReport {
        overall_score: result.score.overall,
        grade: result.score.grade,
        structure_score: result.score.breakdown.structure.final_score,
        quality_score: result.score.breakdown.quality.final_score,
        architecture_score: Some(result.score.breakdown.architecture.final_score),
        findings: result.findings.clone(),
        findings_summary,
        total_files: result.stats.files_analyzed,
        total_functions: result.stats.total_functions,
        total_classes: result.stats.total_classes,
        total_loc: result.stats.total_loc,
        suppression_events: result.suppression_events.clone(),
        suppressed_unaccounted_blocking_count: result.suppressed_unaccounted_blocking.len(),
    };

    super::analyze::output::cache_results(repotoire_dir, &report, &result.findings)?;

    if let Err(e) = engine.save(&session_dir) {
        tracing::debug!("Failed to save session after inline analysis: {e}");
    }

    Ok(())
}

/// Load baseline and head findings from cache, returning them along with scores.
fn load_baseline_and_head(
    repotoire_dir: &Path,
    _repo_path: &Path,
    _base_ref: Option<&str>,
) -> Result<(Vec<Finding>, Vec<Finding>, Option<f64>, Option<f64>)> {
    // Load baseline findings from snapshot (saved by a previous `analyze`)
    let baseline_path = repotoire_dir.join("baseline_findings.json");
    let baseline = if baseline_path.exists() {
        use super::analyze::output::CacheLoadOutcome;
        let outcome = super::analyze::output::load_cached_findings_outcome_from(&baseline_path);
        match outcome {
            CacheLoadOutcome::Findings(v) => v,
            outcome @ CacheLoadOutcome::Corrupt { .. } => {
                // Bug 3 surface: a corrupt baseline cache previously
                // degraded silently to "no baseline" (every finding
                // shown as new). Surface the warning on stdout and
                // continue with an empty baseline, equivalent to
                // first-run UX. Bailing here is wrong because the
                // outer auto-re-analyze fallback can't actually
                // overwrite a stale baseline (`cache_results` only
                // snapshots `last_findings.json` into
                // `baseline_findings.json`, never overwrites it
                // unconditionally), so we'd loop the same error.
                //
                // The outcome is reused (not re-fetched) so the
                // underlying `tracing::warn!` events emit once per
                // invocation, not twice.
                if let Some(msg) = outcome.user_warning() {
                    println!("{}", msg);
                }
                println!(
                    "  Treating as first-run (no baseline); all findings will appear as new. \
                     Delete the corrupt file or run `repotoire analyze` twice to rebuild it."
                );
                Vec::new()
            }
            CacheLoadOutcome::Missing | CacheLoadOutcome::VersionMismatch { .. } => Vec::new(),
        }
    } else {
        // No baseline yet — treat everything as new (first-run scenario)
        Vec::new()
    };

    let score_before = load_score_from(&if baseline_path.exists() {
        repotoire_dir.join("baseline_health.json")
    } else {
        repotoire_dir.join("last_health.json")
    });

    // Load current findings from cache (from the most recent `analyze` run)
    let head = {
        use super::analyze::output::CacheLoadOutcome;
        let last_findings = repotoire_dir.join("last_findings.json");
        let outcome = super::analyze::output::load_cached_findings_outcome_from(&last_findings);
        match outcome {
            CacheLoadOutcome::Findings(v) => v,
            outcome @ CacheLoadOutcome::Corrupt { .. } => {
                // Same single-call discipline as the baseline branch
                // above: reuse `outcome` so we don't double-log.
                if let Some(msg) = outcome.user_warning() {
                    println!("{}", msg);
                }
                anyhow::bail!(
                    "current findings cache is corrupt; re-run `repotoire analyze` to regenerate it"
                );
            }
            CacheLoadOutcome::Missing | CacheLoadOutcome::VersionMismatch { .. } => {
                anyhow::bail!(
                    "No current analysis found. Run 'repotoire analyze' to generate findings."
                );
            }
        }
    };
    let score_after = load_cached_score(repotoire_dir);

    Ok((baseline, head, score_before, score_after))
}

/// Send telemetry event for the diff run.
fn send_diff_telemetry(
    telemetry: &crate::telemetry::Telemetry,
    repo_path: &Path,
    result: &SmartDiffResult,
) {
    if let crate::telemetry::Telemetry::Active(ref state) = *telemetry {
        if let Some(distinct_id) = &state.distinct_id {
            let repo_id = crate::telemetry::config::compute_repo_id(repo_path);
            let event = crate::telemetry::events::DiffRun {
                repo_id,
                score_before: result.score_before.unwrap_or(0.0),
                score_after: result.score_after.unwrap_or(0.0),
                score_delta: result.score_delta().unwrap_or(0.0),
                findings_added: result.all_new_count as u64,
                findings_removed: result.fixed_findings.len() as u64,
                version: env!("CARGO_PKG_VERSION").to_string(),
                ..Default::default()
            };
            let props = serde_json::to_value(&event).unwrap_or_default();
            crate::telemetry::posthog::capture_queued("diff_run", distinct_id, props);
        }
    }
}

/// Format the diff result and write it to the output destination.
fn emit_output(
    result: &SmartDiffResult,
    format: crate::reporters::OutputFormat,
    no_emoji: bool,
    show_score: bool,
    output: Option<&Path>,
    start: Instant,
) -> Result<()> {
    use crate::reporters::OutputFormat;

    let output_str = match format {
        OutputFormat::Json => format_json(result),
        OutputFormat::Sarif => format_sarif(result)?,
        OutputFormat::Markdown => format_markdown(result),
        _ => format_text(result, no_emoji, show_score),
    };

    if let Some(out_path) = output {
        std::fs::write(out_path, &output_str)?;
        eprintln!("Report written to: {}", out_path.display());
    } else {
        println!("{}", output_str);
    }

    // Summary (text mode only)
    if !matches!(
        format,
        OutputFormat::Json | OutputFormat::Sarif | OutputFormat::Markdown
    ) {
        let elapsed = start.elapsed();
        let prefix = if no_emoji { "" } else { "" };
        eprintln!(
            "{}Diff complete in {:.2}s ({} new, {} fixed)",
            prefix,
            elapsed.as_secs_f64(),
            result.new_findings.len(),
            result.fixed_findings.len()
        );
    }

    Ok(())
}

/// Check whether new findings in changed hunks should fail the gate.
///
/// `--fail-on-tier <tier>` (the 0.9.0 gate) fails iff a new finding in the changed hunks is at
/// that tier or higher. A `Blocking` finding suppressed with a *bare* `// repotoire:ignore`
/// (no accounted reason) is hidden from the reported set but still fails the gate — see
/// `suppressed_unaccounted_blocking_count` and design §3 ("a `Blocking` finding suppressed only
/// by `DisplayOnly` is *not* gate-suppressed"). `--fail-on <severity>` is the deprecated
/// severity-based predecessor; passing both is an error.
fn check_fail_threshold(
    fail_on: Option<Severity>,
    fail_on_tier: Option<crate::models::Tier>,
    result: &SmartDiffResult,
) -> Result<()> {
    if fail_on.is_some() && fail_on_tier.is_some() {
        anyhow::bail!("--fail-on and --fail-on-tier are mutually exclusive; use --fail-on-tier");
    }

    if let Some(tier) = fail_on_tier {
        let tripped = result
            .hunk_findings()
            .iter()
            .filter(|f| f.tier >= tier)
            .count();
        if tripped > 0 {
            anyhow::bail!(
                "Failing due to --fail-on-tier={}: {} new {}+ finding(s) in changed hunks",
                tier,
                tripped,
                tier
            );
        }
        // A `Blocking` finding suppressed without an accounted reason still fails the gate at
        // any `--fail-on-tier` (Blocking >= every tier). The finding is absent from
        // `new_findings` (hidden from the report), so it can only be caught here.
        if result.suppressed_unaccounted_blocking_count > 0 {
            anyhow::bail!(
                "Failing due to --fail-on-tier={}: {} blocking finding(s) suppressed without an \
                 accounted reason — name a reason: `// repotoire:ignore[<detector>] — <reason>`",
                tier,
                result.suppressed_unaccounted_blocking_count
            );
        }
        return Ok(());
    }

    if let Some(threshold) = fail_on {
        eprintln!("warning: --fail-on is deprecated; use --fail-on-tier blocking");
        let hunk_findings = result.hunk_findings();
        let new_summary = FindingsSummary::from_findings(&hunk_findings);
        let should_fail = match threshold {
            Severity::Critical => new_summary.critical > 0,
            Severity::High => new_summary.critical > 0 || new_summary.high > 0,
            Severity::Medium => {
                new_summary.critical > 0 || new_summary.high > 0 || new_summary.medium > 0
            }
            Severity::Low | Severity::Info => {
                new_summary.critical > 0
                    || new_summary.high > 0
                    || new_summary.medium > 0
                    || new_summary.low > 0
            }
        };
        if should_fail {
            anyhow::bail!(
                "Failing due to --fail-on={}: {} new finding(s) in changed hunks",
                threshold,
                hunk_findings.len()
            );
        }
    }
    Ok(())
}

/// Options controlling side effects of `compute_smart_diff`.
///
/// The `repotoire diff` command sets both true; the Claude Code hook sets both false.
#[derive(Debug, Clone, Copy)]
pub(crate) struct SmartDiffOptions {
    /// If true, run a full inline analysis when no cache is found (slow path used by `repotoire diff`).
    /// If false, return `Ok(None)` instead — the hook context where we never block on a 14s analyze.
    pub allow_inline_analysis: bool,
    /// If true, emit a PostHog `diff_run` telemetry event on success.
    pub emit_telemetry: bool,
}

impl Default for SmartDiffOptions {
    fn default() -> Self {
        Self {
            allow_inline_analysis: true,
            emit_telemetry: true,
        }
    }
}

/// Compute a smart diff against a cached baseline.
///
/// Returns:
/// - `Ok(Some(result))` — baseline was loaded (or auto-analysis ran when allowed) and diff produced.
/// - `Ok(None)` — no baseline cached AND `options.allow_inline_analysis == false` (hook path: skip silently).
/// - `Err(_)` — git not present, repo path bad, or analysis failed.
pub(crate) fn compute_smart_diff(
    repo_path: &Path,
    base_ref: Option<&str>,
    all: bool,
    changed: bool,
    working_tree: bool,
    options: SmartDiffOptions,
    telemetry: &crate::telemetry::Telemetry,
) -> Result<Option<SmartDiffResult>> {
    let repo_path = repo_path
        .canonicalize()
        .context("Cannot resolve repository path")?;

    if !repo_path.join(".git").exists() {
        anyhow::bail!(
            "diff requires a git repository (no .git found in {})",
            repo_path.display()
        );
    }

    // Resolve cache dir without creating it (creating is the caller's choice).
    let repotoire_dir = crate::cache::paths::cache_dir(&repo_path);

    let load_result = load_baseline_and_head(&repotoire_dir, &repo_path, base_ref);
    let (baseline, head, score_before, score_after) = match load_result {
        Ok(t) => t,
        // A *corrupt* findings cache is a loud failure (Audit pass 2): `load_baseline_and_head`
        // has already printed the user-facing warning — propagate the error so `repotoire diff`
        // exits non-zero. Do NOT fall through to the auto-analyze path: re-running `analyze`
        // would silently overwrite the corrupt file and mask the problem. A *missing* cache
        // (the arm below) is a different, benign case where auto-analyzing is the right call.
        Err(e) if e.to_string().contains("findings cache is corrupt") => return Err(e),
        Err(e) => {
            tracing::debug!("load_baseline_and_head failed: {e}");
            if !options.allow_inline_analysis {
                // Hook path: never trigger an inline analyze. Skip silently.
                return Ok(None);
            }
            // `repotoire diff` path: ensure cache dir exists, run inline analysis, retry load.
            let repotoire_dir = crate::cache::ensure_cache_dir(&repo_path)
                .context("Failed to create cache directory")?;
            eprintln!("No cached analysis found, running analysis...");
            run_inline_analysis(&repo_path, &repotoire_dir)?;
            load_baseline_and_head(&repotoire_dir, &repo_path, base_ref)
                .context("Analysis completed but could not load findings")?
        }
    };

    let base_label = base_ref.unwrap_or(if working_tree { "HEAD" } else { "cached" });
    let head_label = if working_tree { "working-tree" } else { "HEAD" };
    let raw_diff = diff_findings(
        &baseline,
        &head,
        base_label,
        head_label,
        score_before,
        score_after,
    );

    let effective_base = base_ref.unwrap_or(if working_tree { "HEAD" } else { "HEAD~1" });
    let hunks = if working_tree {
        DiffHunks::from_git_diff_worktree(&repo_path, effective_base)
    } else {
        DiffHunks::from_git_diff(&repo_path, effective_base)
    }
    .unwrap_or_else(|e| {
        tracing::debug!("git diff -U0 failed: {e}, attributing all as InUnchangedFile");
        DiffHunks::parse_diff("")
    });

    let all_attributed: Vec<AttributedFinding> = raw_diff
        .new_findings
        .into_iter()
        .map(|f| {
            let attr = f
                .affected_files
                .first()
                .map(|path| hunks.attribute(path, f.line_start))
                .unwrap_or(Attribution::InUnchangedFile);
            AttributedFinding {
                finding: f,
                attribution: attr,
            }
        })
        .collect();

    let all_new_count = all_attributed.len();

    let filtered: Vec<AttributedFinding> = if all {
        all_attributed
    } else if changed {
        all_attributed
            .into_iter()
            .filter(|af| af.attribution != Attribution::InUnchangedFile)
            .collect()
    } else {
        all_attributed
            .into_iter()
            .filter(|af| af.attribution == Attribution::InChangedHunk)
            .collect()
    };

    // The suppression audit trail is "this run" = the head analysis, persisted alongside
    // `last_findings.json` by `cache_results`.
    let (suppression_events, suppressed_unaccounted_blocking_count) =
        super::analyze::output::load_suppression_audit_from(
            &repotoire_dir.join("last_findings.json"),
        );

    let result = SmartDiffResult {
        base_ref: raw_diff.base_ref,
        head_ref: raw_diff.head_ref,
        files_changed: hunks.changed_file_count(),
        new_findings: filtered,
        all_new_count,
        fixed_findings: raw_diff.fixed_findings,
        score_before: raw_diff.score_before,
        score_after: raw_diff.score_after,
        suppression_events,
        suppressed_unaccounted_blocking_count,
    };

    if options.emit_telemetry {
        send_diff_telemetry(telemetry, &repo_path, &result);
    }

    Ok(Some(result))
}

pub struct RunArgs<'a> {
    pub repo_path: &'a Path,
    pub base_ref: Option<String>,
    pub format: crate::reporters::OutputFormat,
    pub fail_on: Option<crate::models::Severity>,
    pub fail_on_tier: Option<crate::models::Tier>,
    pub no_emoji: bool,
    /// Show the health-score delta block (it is de-emphasised — hidden by default in text output).
    pub show_score: bool,
    pub output: Option<&'a Path>,
    pub all: bool,
    pub changed: bool,
    /// Attribute findings to changes vs the working tree (incl. uncommitted + untracked),
    /// not just `<ref>..HEAD`. When set and `base_ref` is `None`, the baseline is `HEAD`.
    pub working_tree: bool,
    pub telemetry: &'a crate::telemetry::Telemetry,
}

/// Run the diff command (presentation wrapper around `compute_smart_diff`).
pub fn run(args: RunArgs<'_>) -> Result<()> {
    let RunArgs {
        repo_path,
        base_ref,
        format,
        fail_on,
        fail_on_tier,
        no_emoji,
        show_score,
        output,
        all,
        changed,
        working_tree,
        telemetry,
    } = args;
    let start = Instant::now();
    let result = compute_smart_diff(
        repo_path,
        base_ref.as_deref(),
        all,
        changed,
        working_tree,
        SmartDiffOptions::default(),
        telemetry,
    )?;
    let result =
        result.expect("compute_smart_diff returns Some when allow_inline_analysis is true");

    emit_output(&result, format, no_emoji, show_score, output, start)?;
    check_fail_threshold(fail_on, fail_on_tier, &result)?;
    Ok(())
}

/// Load cached health score from last_health.json.
fn load_cached_score(repotoire_dir: &Path) -> Option<f64> {
    load_score_from(&repotoire_dir.join("last_health.json"))
}

/// Load health score from a specific JSON file.
fn load_score_from(path: &Path) -> Option<f64> {
    let data = std::fs::read_to_string(path).ok()?;
    let json_val: serde_json::Value = serde_json::from_str(&data).ok()?;
    json_val.get("health_score").and_then(|v| v.as_f64())
}

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

    fn make_finding(detector: &str, file: &str, line: Option<u32>) -> Finding {
        Finding {
            detector: detector.to_string(),
            affected_files: vec![PathBuf::from(file)],
            line_start: line,
            severity: Severity::Medium,
            title: "test".to_string(),
            ..Default::default()
        }
    }

    #[test]
    fn test_exact_match() {
        let a = make_finding("dead_code", "src/foo.rs", Some(10));
        let b = make_finding("dead_code", "src/foo.rs", Some(10));
        assert!(findings_match(&a, &b));
    }

    #[test]
    fn fail_on_tier_blocking_trips_only_on_new_blocking() {
        use crate::models::Tier;

        let make_attr = |detector: &str, tier: Tier| AttributedFinding {
            finding: Finding {
                tier,
                ..make_finding(detector, "src/web.rs", Some(5))
            },
            attribution: Attribution::InChangedHunk,
        };

        let mut result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![
                make_attr("xss", Tier::Advisory),
                make_attr("command_injection", Tier::Blocking),
            ],
            all_new_count: 2,
            fixed_findings: vec![],
            score_before: Some(96.0),
            score_after: Some(95.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        // A new Blocking finding in the changed hunks trips --fail-on-tier blocking.
        assert!(check_fail_threshold(None, Some(Tier::Blocking), &result).is_err());

        // Drop the Blocking finding — only Advisory left — and it passes.
        result
            .new_findings
            .retain(|af| af.finding.tier != Tier::Blocking);
        assert!(check_fail_threshold(None, Some(Tier::Blocking), &result).is_ok());
        // ...but --fail-on-tier advisory still trips on the remaining Advisory finding.
        assert!(check_fail_threshold(None, Some(Tier::Advisory), &result).is_err());

        // Passing both --fail-on and --fail-on-tier is an error.
        let err = check_fail_threshold(Some(Severity::High), Some(Tier::Blocking), &result)
            .expect_err("both flags should be rejected");
        assert!(err.to_string().contains("mutually exclusive"));
    }

    #[test]
    fn fail_on_tier_trips_on_unaccounted_blocking_suppression() {
        use crate::models::Tier;

        // No findings in `new_findings`, but a Blocking finding was suppressed with a bare
        // `// repotoire:ignore` (no accounted reason): the gate must still fail — at every
        // `--fail-on-tier`, since Blocking >= every tier. See design §3.
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![],
            all_new_count: 0,
            fixed_findings: vec![],
            score_before: Some(96.0),
            score_after: Some(96.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 1,
        };

        let err = check_fail_threshold(None, Some(Tier::Blocking), &result)
            .expect_err("an unaccounted blocking suppression must fail --fail-on-tier blocking");
        assert!(err
            .to_string()
            .contains("suppressed without an accounted reason"));
        // Also fails under a wider tier.
        assert!(check_fail_threshold(None, Some(Tier::Advisory), &result).is_err());
        // ...but with no `--fail-on-tier` set, this alone does not fail.
        assert!(check_fail_threshold(None, None, &result).is_ok());
    }

    #[test]
    fn test_fuzzy_line_match_within_tolerance() {
        let a = make_finding("dead_code", "src/foo.rs", Some(10));
        let b = make_finding("dead_code", "src/foo.rs", Some(13)); // +3
        assert!(findings_match(&a, &b));

        let c = make_finding("dead_code", "src/foo.rs", Some(7)); // -3
        assert!(findings_match(&a, &c));
    }

    #[test]
    fn test_fuzzy_line_beyond_tolerance() {
        let a = make_finding("dead_code", "src/foo.rs", Some(10));
        let b = make_finding("dead_code", "src/foo.rs", Some(14)); // +4
        assert!(!findings_match(&a, &b));
    }

    #[test]
    fn test_different_detector_no_match() {
        let a = make_finding("dead_code", "src/foo.rs", Some(10));
        let b = make_finding("magic_number", "src/foo.rs", Some(10));
        assert!(!findings_match(&a, &b));
    }

    #[test]
    fn test_different_file_no_match() {
        let a = make_finding("dead_code", "src/foo.rs", Some(10));
        let b = make_finding("dead_code", "src/bar.rs", Some(10));
        assert!(!findings_match(&a, &b));
    }

    #[test]
    fn test_file_level_findings_match() {
        let a = make_finding("circular_dependency", "src/foo.rs", None);
        let b = make_finding("circular_dependency", "src/foo.rs", None);
        assert!(findings_match(&a, &b));
    }

    #[test]
    fn test_line_vs_no_line_no_match() {
        let a = make_finding("dead_code", "src/foo.rs", Some(10));
        let b = make_finding("dead_code", "src/foo.rs", None);
        assert!(!findings_match(&a, &b));
    }

    #[test]
    fn test_diff_new_and_fixed() {
        let baseline = vec![
            make_finding("dead_code", "src/foo.rs", Some(10)),
            make_finding("magic_number", "src/bar.rs", Some(20)),
        ];
        let head = vec![
            make_finding("dead_code", "src/foo.rs", Some(11)), // shifted by 1, same issue
            make_finding("xss", "src/web.rs", Some(5)),        // new
        ];

        let result = diff_findings(&baseline, &head, "main", "HEAD", Some(96.0), Some(95.5));

        assert_eq!(result.new_findings.len(), 1);
        assert_eq!(result.new_findings[0].detector, "xss");

        assert_eq!(result.fixed_findings.len(), 1);
        assert_eq!(result.fixed_findings[0].detector, "magic_number");

        let delta = result.score_after.unwrap() - result.score_before.unwrap();
        assert!((delta - (-0.5)).abs() < f64::EPSILON);
    }

    #[test]
    fn test_diff_no_changes() {
        let findings = vec![make_finding("dead_code", "src/foo.rs", Some(10))];
        let result = diff_findings(&findings, &findings, "main", "HEAD", None, None);
        assert!(result.new_findings.is_empty());
        assert!(result.fixed_findings.is_empty());
        assert!(result.score_before.is_none());
        assert!(result.score_after.is_none());
    }

    #[test]
    fn test_format_json_structure() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 2,
            new_findings: vec![AttributedFinding {
                finding: make_finding("xss", "src/web.rs", Some(5)),
                attribution: Attribution::InChangedHunk,
            }],
            all_new_count: 1,
            fixed_findings: vec![make_finding("dead_code", "src/old.rs", Some(10))],
            score_before: Some(96.0),
            score_after: Some(95.5),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let json_str = format_json(&result);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

        assert_eq!(parsed["base_ref"], "main");
        assert_eq!(parsed["head_ref"], "HEAD");
        assert_eq!(parsed["files_changed"], 2);
        assert_eq!(parsed["new_findings"].as_array().unwrap().len(), 1);
        assert_eq!(parsed["new_findings"][0]["attribution"], "in_changed_hunk");
        assert_eq!(parsed["fixed_findings"].as_array().unwrap().len(), 1);
        assert_eq!(parsed["score_delta"], -0.5);
    }

    #[test]
    fn test_format_json_carries_tier_evidence_and_suppression_events() {
        use crate::models::{Evidence, SourceSpan, SuppressionEvent, Tier};

        let mut blocking = make_finding("command_injection", "src/app.js", Some(10));
        blocking.tier = Tier::Blocking;
        blocking.confidence = Some(0.97);
        blocking.evidence = Some(Evidence::ConfigFact {
            span: SourceSpan {
                file: PathBuf::from("src/app.js"),
                line_start: 10,
                line_end: 10,
                snippet: None,
            },
            rule: "gha_untrusted_input_to_run".to_string(),
        });

        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![AttributedFinding {
                finding: blocking,
                attribution: Attribution::InChangedHunk,
            }],
            all_new_count: 1,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(80.0),
            suppression_events: vec![SuppressionEvent {
                detector: "command-injection".into(),
                reason: "accepted-risk".into(),
                file: PathBuf::from("src/legacy.js"),
                line: Some(3),
                fingerprint: "abc123".into(),
                harvestable: false,
            }],
            suppressed_unaccounted_blocking_count: 1,
        };

        let json_str = format_json(&result);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).expect("valid JSON");

        let f = &parsed["new_findings"][0];
        assert_eq!(f["tier"], "blocking");
        assert_eq!(f["confidence"].as_f64(), Some(0.97));
        assert_eq!(
            f["evidence"]["config_fact"]["rule"],
            "gha_untrusted_input_to_run"
        );
        assert_eq!(f["suppressed"], false);

        let events = parsed["suppression_events"]
            .as_array()
            .expect("suppression_events array");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0]["reason"], "accepted-risk");
        assert_eq!(events[0]["harvestable"], false);
        assert_eq!(parsed["suppressed_unaccounted_blocking_count"], 1);
    }

    #[test]
    fn test_format_text_no_new_findings() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![],
            all_new_count: 0,
            fixed_findings: vec![],
            score_before: Some(97.0),
            score_after: Some(97.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let text = format_text(&result, true, false);
        assert!(text.contains("Nothing in this change trips the gate."));
        assert!(!text.contains("--all"));
        assert!(!text.contains("Score:"), "score is hidden unless --score");
    }

    #[test]
    fn test_format_text_filtered_hint() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![],
            all_new_count: 5,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(88.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let text = format_text(&result, true, false);
        assert!(text.contains("Nothing in this change trips the gate."));
        assert!(text.contains("5 findings in other files"));
        assert!(text.contains("--all"));
    }

    #[test]
    fn test_format_json_total_new_findings() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![],
            all_new_count: 3,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(90.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let json_str = format_json(&result);
        let parsed: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(parsed["total_new_findings"], 3);
    }

    #[test]
    fn test_format_markdown_structure() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![AttributedFinding {
                finding: make_finding("xss", "src/web.rs", Some(5)),
                attribution: Attribution::InChangedHunk,
            }],
            all_new_count: 1,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(88.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let md = format_markdown(&result);
        assert!(md.starts_with("# Repotoire Diff:"));
        assert!(md.contains("## Your Changes"));
        assert!(md.contains("| Severity |"));
        assert!(md.contains("`src/web.rs:5`"));
        assert!(!md.contains("\x1b[")); // no ANSI escapes
    }

    #[test]
    fn test_format_markdown_no_findings() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![],
            all_new_count: 0,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(90.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let md = format_markdown(&result);
        assert!(md.contains("**No new findings.**"));
    }

    #[test]
    fn test_format_markdown_filtered_hint() {
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 2,
            new_findings: vec![],
            all_new_count: 4,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(88.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let md = format_markdown(&result);
        assert!(md.contains("**No new findings in your changes.**"));
        assert!(md.contains("4 finding"));
        assert!(md.contains("`--all`"));
    }

    #[test]
    fn diff_text_leads_with_blocking_when_present() {
        use crate::models::{Evidence, SourceSpan, Tier};

        let mut blocking = make_finding("command_injection", "src/app.js", Some(30));
        blocking.tier = Tier::Blocking;
        blocking.severity = Severity::Critical;
        blocking.title = "Tainted input flows to exec()".to_string();
        blocking.evidence = Some(Evidence::TaintPath {
            source: SourceSpan {
                file: PathBuf::from("src/app.js"),
                line_start: 12,
                line_end: 12,
                snippet: None,
            },
            sink: SourceSpan {
                file: PathBuf::from("src/app.js"),
                line_start: 30,
                line_end: 30,
                snippet: None,
            },
            sink_kind: "exec".to_string(),
            flow: vec![],
            sanitizers_seen: vec![],
        });

        let advisory = make_finding("magic_number", "src/util.js", Some(7));

        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 2,
            new_findings: vec![
                AttributedFinding {
                    finding: blocking,
                    attribution: Attribution::InChangedHunk,
                },
                AttributedFinding {
                    finding: advisory,
                    attribution: Attribution::InChangedHunk,
                },
            ],
            all_new_count: 2,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(80.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let text = console::strip_ansi_codes(&format_text(&result, true, true)).to_string();
        let blocking_pos = text.find("Blocking").expect("blocking header present");
        let advisory_pos = text.find("Advisory").expect("advisory header present");
        let score_pos = text.find("Score:").expect("score block present");
        assert!(
            blocking_pos < advisory_pos,
            "blocking section should come before advisory section"
        );
        assert!(
            advisory_pos < score_pos,
            "advisory section should come before the score block"
        );
        // Evidence rendered inline.
        assert!(
            text.contains("src/app.js:12") && text.contains("src/app.js:30"),
            "taint-path evidence should show source → sink spans, got:\n{text}"
        );
        assert!(text.contains("exec"), "sink kind should be shown");
    }

    #[test]
    fn diff_text_says_clean_when_no_blocking() {
        let advisory = make_finding("magic_number", "src/util.js", Some(7));
        let result = SmartDiffResult {
            base_ref: "main".to_string(),
            head_ref: "HEAD".to_string(),
            files_changed: 1,
            new_findings: vec![AttributedFinding {
                finding: advisory,
                attribution: Attribution::InChangedHunk,
            }],
            all_new_count: 1,
            fixed_findings: vec![],
            score_before: Some(90.0),
            score_after: Some(89.0),
            suppression_events: Vec::new(),
            suppressed_unaccounted_blocking_count: 0,
        };

        let text = format_text(&result, true, false);
        assert!(
            text.contains("Nothing in this change trips the gate."),
            "no-blocking output should say the gate is clear, got:\n{text}"
        );
    }
}