cartomancer 0.6.0

PR review tool with blast radius awareness — opengrep + cartog + LLM
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
//! Pipeline orchestration — the core review state machine.
//!
//! Stages:
//! 1. Prepare working directory (clone or reuse)
//! 2. Fetch PR metadata and diff (GitHub API)
//! 3. Run opengrep scan (subprocess with --baseline-commit)
//! 4. Enrich with cartog graph context
//! 5. Escalate severity based on blast radius
//! 6. LLM deepen high-severity findings (conditional)
//! 7. Build ReviewResult

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use anyhow::{Context, Result};
use tokio::sync::Semaphore;
use tracing::{info, warn};

use cartomancer_core::config::AppConfig;
use cartomancer_core::diff::PullRequestDiff;
use cartomancer_core::finding::Finding;
use cartomancer_core::review::{ReviewResult, ReviewStatus};
use cartomancer_github::client::GitHubClient;
use cartomancer_github::diff::{is_line_in_diff, parse_diff};
use cartomancer_github::types::{PrMetadata, ReviewComment};
use cartomancer_graph::enricher::CartogEnricher;
use cartomancer_graph::escalator::SeverityEscalator;

use cartomancer_store::store::Store;
use cartomancer_store::types::ScanRecord;

use crate::comment;
use crate::llm;
use crate::opengrep;

/// Outcome of the pipeline, including the parsed diff and work directory for cleanup.
pub struct PipelineResult {
    pub review: ReviewResult,
    /// Parsed diff — reused for inline comment placement without refetching.
    pub diff: PullRequestDiff,
    /// PR branch name (head_ref) — used for scan persistence.
    pub branch: String,
    /// Base branch name (base_ref) — used for regression comparison.
    pub base_branch: String,
    /// Pipeline wall-clock duration — used for summary regeneration after off-diff splitting.
    pub scan_duration: std::time::Duration,
    /// Number of opengrep rules used — used for summary regeneration after off-diff splitting.
    pub rule_count: usize,
    /// Scan ID from the store (if stage tracking is active). Used by `finalize_and_post`
    /// to update the existing scan record instead of inserting a duplicate.
    pub scan_id: Option<i64>,
    /// Temp dir handle — kept alive until review is posted, then dropped for cleanup.
    /// None if --work-dir was used.
    #[allow(dead_code)]
    pub temp_dir: Option<tempfile::TempDir>,
}

/// Run the full review pipeline for a single PR.
///
/// When `resume_scan_id` is Some, resumes a previously failed scan from its
/// last completed stage (requires the work directory to still exist or a new clone).
pub async fn run_pipeline(
    config: &AppConfig,
    github: &GitHubClient,
    token: &str,
    repo: &str,
    pr_number: u64,
    work_dir: Option<&str>,
    resume_scan_id: Option<i64>,
) -> Result<PipelineResult> {
    use cartomancer_core::review::PipelineStage;

    let pipeline_start = Instant::now();

    // Determine which stage to start from (resume support)
    let (start_stage, mut findings, scan_id) = match resume_scan_id {
        Some(sid) => {
            let store = Store::open(&config.storage.db_path)
                .map_err(|e| anyhow::anyhow!("failed to open store for resume: {e}"))?;
            let scan = store
                .get_scan(sid)?
                .ok_or_else(|| anyhow::anyhow!("scan {sid} not found — cannot resume"))?;

            let stage = PipelineStage::from_db(&scan.stage)
                .ok_or_else(|| anyhow::anyhow!("unknown stage '{}' for scan {sid}", scan.stage))?;

            if stage == PipelineStage::Completed {
                anyhow::bail!("scan {sid} already completed — nothing to resume");
            }

            // Verify the stored scan matches the current request
            if scan.repo != repo {
                anyhow::bail!(
                    "scan {sid} belongs to repo '{}', not '{repo}' — cannot resume",
                    scan.repo
                );
            }
            if scan.pr_number != Some(pr_number) {
                anyhow::bail!(
                    "scan {sid} belongs to PR #{}, not #{pr_number} — cannot resume",
                    scan.pr_number.map_or("none".into(), |n| n.to_string())
                );
            }

            // Load persisted findings to resume from
            let stored = store.get_findings(sid)?;
            let resumed_findings = stored_to_findings(&stored);

            info!(scan_id = sid, stage = %stage, findings = resumed_findings.len(), "resuming pipeline");
            (stage, resumed_findings, Some(sid))
        }
        None => (PipelineStage::Pending, vec![], None),
    };

    // 0. LLM health check — warn early if provider is unreachable
    match llm::create_provider(&config.llm, config.knowledge.system_prompt.as_deref()) {
        Ok(provider) => match provider.health_check().await {
            Ok(()) => info!(provider = provider.name(), "LLM provider ready"),
            Err(e) => {
                warn!(err = %e, "LLM provider health check failed — deepening will be skipped")
            }
        },
        Err(e) => warn!(err = %e, "could not create LLM provider — deepening will be skipped"),
    }

    // 1. Fetch PR metadata
    info!(repo, pr_number, "fetching PR metadata");
    let pr_meta = github.fetch_pr_metadata(repo, pr_number).await?;

    // 2. Prepare working directory
    let (work_path, temp_dir) = prepare_work_dir(repo, token, work_dir)?;
    let work_str = work_path.to_string_lossy();

    // Fetch and checkout PR head, fetch base for opengrep --baseline-commit
    prepare_pr_commits(&work_path, &pr_meta)?;

    // 3. Fetch and parse diff
    info!("fetching PR diff");
    let raw_diff = github.fetch_diff(repo, pr_number).await?;
    let diff = parse_diff(&raw_diff)?;
    info!(
        files_changed = diff.files_changed.len(),
        chunks = diff.chunks.len(),
        "diff parsed"
    );

    // Open store for stage persistence (best-effort — stage tracking is optional)
    let store = Store::open(&config.storage.db_path).ok();
    let rule_count = config.opengrep.rules.len();

    // Create or reuse scan record
    let scan_id: Option<i64> = match scan_id {
        Some(id) => Some(id),
        None => {
            if let Some(ref s) = store {
                let record = ScanRecord {
                    id: None,
                    repo: repo.to_string(),
                    branch: pr_meta.head_ref.clone(),
                    commit_sha: pr_meta.head_sha.clone(),
                    command: "review".into(),
                    pr_number: Some(pr_number),
                    finding_count: 0,
                    summary: String::new(),
                    created_at: None,
                    stage: "pending".into(),
                    error_message: None,
                    failed_at_stage: None,
                };
                match s.insert_scan(&record) {
                    Ok(id) => Some(id),
                    Err(e) => {
                        warn!(err = %e, "failed to create scan record — stage tracking disabled");
                        None
                    }
                }
            } else {
                None
            }
        }
    };

    // Helper to persist stage (best-effort)
    let advance_stage =
        |store: &Option<Store>, scan_id: Option<i64>, stage: &str, findings: &[Finding]| {
            let id = match scan_id {
                Some(id) => id,
                None => return,
            };
            if let Some(ref s) = store {
                if let Err(e) = s.update_scan_findings(id, findings) {
                    warn!(err = %e, stage, "failed to persist findings at stage");
                }
                if let Err(e) = s.update_scan_stage(id, stage) {
                    warn!(err = %e, stage, "failed to update scan stage");
                }
            }
        };

    // Helper to record failure metadata (best-effort)
    let record_failure =
        |store: &Option<Store>, scan_id: Option<i64>, stage: &str, err: &anyhow::Error| {
            if let (Some(id), Some(ref s)) = (scan_id, store) {
                if let Err(e) = s.mark_scan_failed(id, stage, &err.to_string()) {
                    warn!(err = %e, "failed to record scan failure");
                }
            }
        };

    // --- Stage: Scan ---
    if start_stage < PipelineStage::Scanned {
        let opengrep_start = Instant::now();
        findings = match opengrep::run_opengrep(
            &work_str,
            &config.opengrep,
            Some(&pr_meta.base_sha),
        )
        .await
        {
            Ok(f) => f,
            Err(e) => {
                record_failure(&store, scan_id, "scanned", &e);
                return Err(e);
            }
        };
        let opengrep_elapsed = opengrep_start.elapsed();
        info!(
            findings = findings.len(),
            elapsed_ms = opengrep_elapsed.as_millis() as u64,
            "opengrep scan complete"
        );
        advance_stage(&store, scan_id, "scanned", &findings);
    } else {
        info!(stage = "scanned", "skipping (already completed)");
    }

    if findings.is_empty() {
        let branch = pr_meta.head_ref.clone();
        let base_branch = pr_meta.base_ref.clone();
        let scan_duration = pipeline_start.elapsed();
        advance_stage(&store, scan_id, "completed", &findings);
        let review = ReviewResult {
            pr_number,
            repo_full_name: repo.to_string(),
            head_sha: pr_meta.head_sha,
            findings: vec![],
            summary: comment::format_clean_summary(scan_duration, rule_count),
            status: ReviewStatus::Completed,
        };
        return Ok(PipelineResult {
            review,
            diff,
            branch,
            base_branch,
            scan_duration,
            rule_count,
            scan_id,
            temp_dir,
        });
    }

    // --- Stage: Enrich ---
    if start_stage < PipelineStage::Enriched {
        enrich_findings(&work_path, config, &mut findings);
        advance_stage(&store, scan_id, "enriched", &findings);
    } else {
        info!(stage = "enriched", "skipping (already completed)");
    }

    // --- Stage: Escalate ---
    if start_stage < PipelineStage::Escalated {
        let escalator = SeverityEscalator::new(config.severity.blast_radius_threshold);
        escalator.escalate_batch(&mut findings, &config.knowledge.rules);
        advance_stage(&store, scan_id, "escalated", &findings);
    } else {
        info!(stage = "escalated", "skipping (already completed)");
    }

    // --- Stage: Deepen ---
    if start_stage < PipelineStage::Deepened {
        deepen_findings(config, &work_path, &mut findings).await;
        advance_stage(&store, scan_id, "deepened", &findings);
    } else {
        info!(stage = "deepened", "skipping (already completed)");
    }

    // Sort by severity (critical first)
    findings.sort_by(|a, b| b.severity.cmp(&a.severity));

    // Build ReviewResult and mark completed
    let scan_duration = pipeline_start.elapsed();
    let summary = comment::format_summary(&findings, &[], scan_duration, rule_count);
    let branch = pr_meta.head_ref;
    let base_branch = pr_meta.base_ref;

    advance_stage(&store, scan_id, "completed", &findings);

    let review = ReviewResult {
        pr_number,
        repo_full_name: repo.to_string(),
        head_sha: pr_meta.head_sha,
        findings,
        summary,
        status: ReviewStatus::Completed,
    };

    Ok(PipelineResult {
        review,
        diff,
        branch,
        base_branch,
        scan_duration,
        rule_count,
        scan_id,
        temp_dir,
    })
}

/// Convert stored findings back to domain `Finding` structs for pipeline resumption.
fn stored_to_findings(stored: &[cartomancer_store::types::StoredFinding]) -> Vec<Finding> {
    use cartomancer_core::finding::GraphContext;
    use cartomancer_core::severity::Severity;

    stored
        .iter()
        .map(|sf| {
            let severity = sf.severity.parse::<Severity>().unwrap_or(Severity::Warning);

            let graph_context = sf
                .graph_context_json
                .as_deref()
                .and_then(|json| serde_json::from_str::<GraphContext>(json).ok());

            let escalation_reasons: Vec<String> = sf
                .escalation_reasons_json
                .as_deref()
                .and_then(|json| serde_json::from_str(json).ok())
                .unwrap_or_default();

            Finding {
                rule_id: sf.rule_id.clone(),
                message: sf.message.clone(),
                severity,
                file_path: sf.file_path.clone(),
                start_line: sf.start_line,
                end_line: sf.end_line,
                snippet: sf.snippet.clone(),
                cwe: sf.cwe.clone(),
                graph_context,
                llm_analysis: sf.llm_analysis.clone(),
                escalation_reasons,
                is_new: None,
                enclosing_context: sf.enclosing_context.clone(),
                suggested_fix: sf.suggested_fix.clone(),
                agent_prompt: sf.agent_prompt.clone(),
            }
        })
        .collect()
}

/// Prepare the working directory: clone to temp dir or reuse existing.
fn prepare_work_dir(
    repo: &str,
    token: &str,
    work_dir: Option<&str>,
) -> Result<(PathBuf, Option<tempfile::TempDir>)> {
    match work_dir {
        Some(dir) => {
            let path = PathBuf::from(dir);
            if path.join(".git").exists() {
                info!(path = %path.display(), "reusing existing git checkout");
                Ok((path, None))
            } else {
                info!(path = %path.display(), "cloning repo into work-dir");
                std::fs::create_dir_all(&path)
                    .with_context(|| format!("creating work-dir: {}", path.display()))?;
                clone_repo(repo, token, &path)?;
                Ok((path, None))
            }
        }
        None => {
            let temp_dir = tempfile::tempdir().context("creating temp directory")?;
            let path = temp_dir.path().to_path_buf();
            info!(path = %path.display(), "cloning repo into temp directory");
            clone_repo(repo, token, &path)?;
            Ok((path, Some(temp_dir)))
        }
    }
}

/// Clone a GitHub repo into the given directory.
/// Token is passed via `GIT_ASKPASS` env var pointing to a script that echoes
/// the token, avoiding exposure in process arguments visible via `/proc` or `ps`.
fn clone_repo(repo: &str, token: &str, target: &Path) -> Result<()> {
    let url = format!("https://x-access-token@github.com/{repo}.git");

    // Create a temporary askpass script that echoes the token.
    // git calls this script with a prompt; the script ignores it and prints the token.
    let askpass_dir = tempfile::tempdir().context("creating askpass temp dir")?;
    let askpass_path = askpass_dir.path().join("askpass.sh");
    // Write token to a separate file, script reads from it to avoid shell injection
    let token_path = askpass_dir.path().join("token");
    std::fs::write(&token_path, token).context("writing token file")?;
    std::fs::write(
        &askpass_path,
        format!("#!/bin/sh\ncat '{}'", token_path.display()),
    )
    .context("writing askpass script")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&askpass_path, std::fs::Permissions::from_mode(0o700))
            .context("setting askpass permissions")?;
    }

    let status = std::process::Command::new("git")
        .args(["clone", "--depth", "50", &url, "."])
        .env("GIT_ASKPASS", &askpass_path)
        .env("GIT_TERMINAL_PROMPT", "0")
        .current_dir(target)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .context("failed to execute git clone — is git installed?")?;

    // askpass_dir is dropped here, cleaning up the script

    if !status.success() {
        anyhow::bail!(
            "git clone failed for {repo} (exit {})",
            status.code().unwrap_or(-1)
        );
    }
    Ok(())
}

/// Fetch and checkout the PR head commit, and fetch the base commit
/// so opengrep `--baseline-commit` can find it.
fn prepare_pr_commits(work_path: &Path, pr_meta: &PrMetadata) -> Result<()> {
    // Fetch head SHA
    let status = std::process::Command::new("git")
        .args(["fetch", "origin", &pr_meta.head_sha, "--depth", "50"])
        .current_dir(work_path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .context("failed to fetch PR head")?;

    if !status.success() {
        anyhow::bail!(
            "git fetch of PR head {} failed (exit {})",
            &pr_meta.head_sha[..8.min(pr_meta.head_sha.len())],
            status.code().unwrap_or(-1)
        );
    }

    // Checkout head SHA
    let status = std::process::Command::new("git")
        .args(["checkout", &pr_meta.head_sha])
        .current_dir(work_path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .context("failed to checkout PR head")?;

    if !status.success() {
        anyhow::bail!(
            "git checkout of PR head {} failed (exit {})",
            &pr_meta.head_sha[..8.min(pr_meta.head_sha.len())],
            status.code().unwrap_or(-1)
        );
    }

    // Fetch base SHA so opengrep --baseline-commit can find it
    let status = std::process::Command::new("git")
        .args(["fetch", "origin", &pr_meta.base_sha, "--depth", "50"])
        .current_dir(work_path)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .status()
        .context("failed to fetch PR base")?;

    if !status.success() {
        warn!(
            base_sha = %&pr_meta.base_sha[..8.min(pr_meta.base_sha.len())],
            "git fetch of PR base failed — opengrep --baseline-commit may not work"
        );
    }

    Ok(())
}

/// Enrich findings with cartog graph context (if .cartog.db exists).
fn enrich_findings(work_path: &Path, config: &AppConfig, findings: &mut [Finding]) {
    let db_path = work_path.join(".cartog.db");
    if !db_path.exists() {
        info!("no .cartog.db found, skipping graph enrichment");
        return;
    }

    match CartogEnricher::open(&db_path.to_string_lossy(), config.severity.impact_depth) {
        Ok(enricher) => {
            let mut enriched = 0u32;
            let mut failed = 0u32;
            for finding in findings.iter_mut() {
                match enricher.enrich(finding) {
                    Ok(()) => {
                        if finding.graph_context.is_some() {
                            enriched += 1;
                        }
                    }
                    Err(e) => {
                        warn!(
                            rule = %finding.rule_id,
                            file = %finding.file_path,
                            line = finding.start_line,
                            err = %e,
                            "failed to enrich finding, skipping"
                        );
                        failed += 1;
                    }
                }
            }
            info!(enriched, failed, "graph enrichment complete");
        }
        Err(e) => {
            warn!(
                path = %db_path.display(),
                err = %e,
                "could not open cartog database, skipping enrichment"
            );
        }
    }
}

/// LLM-deepen qualifying findings with bounded concurrency.
async fn deepen_findings(config: &AppConfig, work_path: &Path, findings: &mut [Finding]) {
    let threshold = config.severity.llm_deepening_threshold;
    let rule_overrides = &config.knowledge.rules;
    let candidates: Vec<usize> = findings
        .iter()
        .enumerate()
        .filter(|(_, f)| {
            // Check if this rule has always_deepen override
            let always = rule_overrides
                .get(&f.rule_id)
                .map(|r| r.always_deepen)
                .unwrap_or(false);
            always
                || (f.severity >= threshold
                    && f.graph_context
                        .as_ref()
                        .map(|ctx| ctx.blast_radius > 3)
                        .unwrap_or(false))
        })
        .map(|(i, _)| i)
        .collect();

    if candidates.is_empty() {
        info!(threshold = %threshold, "no findings qualify for LLM deepening");
        return;
    }

    let provider: Arc<dyn llm::LlmProvider> =
        match llm::create_provider(&config.llm, config.knowledge.system_prompt.as_deref()) {
            Ok(p) => Arc::from(p),
            Err(e) => {
                warn!(err = %e, "could not create LLM provider, skipping deepening");
                return;
            }
        };

    let concurrency = config.llm.max_concurrent_deepening;
    info!(
        provider = provider.name(),
        candidates = candidates.len(),
        concurrency,
        "starting LLM deepening"
    );

    // Load company knowledge once (used in every prompt)
    let company_context = llm::load_knowledge(work_path, &config.knowledge);
    if !company_context.is_empty() {
        info!(
            chars = company_context.len(),
            "loaded company knowledge for LLM deepening"
        );
    }

    // Build prompts upfront (cheap, no async needed)
    let tasks: Vec<(usize, String)> = candidates
        .iter()
        .map(|&idx| {
            (
                idx,
                llm::build_deepening_prompt(&findings[idx], &company_context),
            )
        })
        .collect();

    // Fire concurrent LLM requests with bounded concurrency
    let semaphore = Arc::new(Semaphore::new(concurrency));
    let mut handles = Vec::with_capacity(tasks.len());

    for (idx, prompt) in tasks {
        let provider = Arc::clone(&provider);
        let sem = Arc::clone(&semaphore);
        handles.push(tokio::spawn(async move {
            let _permit = sem.acquire().await.expect("semaphore closed unexpectedly");
            let result = provider.complete(&prompt).await;
            (idx, result)
        }));
    }

    // Collect results and apply back to findings
    let mut deepened = 0u32;
    let mut failed = 0u32;
    for handle in handles {
        match handle.await {
            Ok((idx, Ok(raw))) => {
                let (analysis, fix) = llm::parse_llm_response(&raw);
                findings[idx].llm_analysis = Some(analysis);
                if let Some(ref fix) = fix {
                    findings[idx].agent_prompt = Some(llm::build_agent_prompt(&findings[idx], fix));
                }
                findings[idx].suggested_fix = fix;
                deepened += 1;
            }
            Ok((idx, Err(e))) => {
                warn!(
                    rule = %findings[idx].rule_id,
                    file = %findings[idx].file_path,
                    err = %e,
                    "LLM deepening failed, skipping"
                );
                failed += 1;
            }
            Err(e) => {
                warn!(err = %e, "LLM deepening task panicked");
                failed += 1;
            }
        }
    }

    info!(deepened, failed, "LLM deepening complete");
}

/// Findings partitioned by diff placement, with comments ready for posting.
pub struct ReviewPayload {
    pub summary: String,
    pub inline_comments: Vec<ReviewComment>,
    pub off_diff_bodies: Vec<String>,
}

/// Partition findings into inline review comments and off-diff comments,
/// regenerating the summary when off-diff findings exist.
pub fn prepare_review_payload(result: &PipelineResult) -> ReviewPayload {
    let review = &result.review;
    let mut inline_comments = Vec::new();
    let mut off_diff_findings: Vec<&Finding> = Vec::new();

    for finding in &review.findings {
        if is_line_in_diff(&result.diff, &finding.file_path, finding.start_line) {
            inline_comments.push(ReviewComment {
                path: finding.file_path.clone(),
                line: finding.start_line,
                body: comment::format_inline_comment(finding),
            });
        } else {
            off_diff_findings.push(finding);
        }
    }

    let summary = if off_diff_findings.is_empty() {
        review.summary.clone()
    } else {
        comment::format_summary(
            &review.findings,
            &off_diff_findings,
            result.scan_duration,
            result.rule_count,
        )
    };

    let off_diff_bodies = off_diff_findings
        .iter()
        .map(|f| comment::format_off_diff_comment(f))
        .collect();

    ReviewPayload {
        summary,
        inline_comments,
        off_diff_bodies,
    }
}

/// Post-pipeline finalization: annotate regression, filter dismissed, persist, post to GitHub.
///
/// Shared between `cmd_review()` (CLI) and webhook handler.
pub async fn finalize_and_post(
    config: &AppConfig,
    github: &GitHubClient,
    repo: &str,
    pr: u64,
    result: &mut PipelineResult,
) -> Result<()> {
    // Annotate findings as new/existing (US-5) and filter dismissed (US-6)
    annotate_regression(
        &config.storage.db_path,
        repo,
        &result.base_branch,
        &mut result.review.findings,
    );
    filter_dismissed(&config.storage.db_path, &mut result.review.findings);

    // Recompute summary to reflect filtered findings
    let payload = prepare_review_payload(result);
    result.review.summary = payload.summary.clone();

    // Persist findings (BR-3: best-effort) but defer "completed" until after posting
    if let Some(sid) = result.scan_id {
        if let Ok(store) = Store::open(&config.storage.db_path) {
            if let Err(e) = store.update_scan_findings(sid, &result.review.findings) {
                warn!(err = %e, "failed to update findings for finalization");
            }
        }
    } else {
        persist_scan(
            &config.storage.db_path,
            repo,
            &result.branch,
            &result.review.head_sha,
            "review",
            Some(pr),
            &result.review,
        );
    }

    // Post to GitHub
    if result.review.findings.is_empty() {
        github
            .post_comment(repo, pr, &result.review.summary)
            .await?;
        info!("clean summary posted for {repo}#{pr}");
    } else {
        github
            .post_review(
                repo,
                pr,
                &result.review.head_sha,
                &payload.summary,
                payload.inline_comments,
            )
            .await?;

        for body in &payload.off_diff_bodies {
            github.post_comment(repo, pr, body).await?;
        }

        info!(
            total = result.review.findings.len(),
            "review posted for {repo}#{pr}"
        );
    }

    // Mark completed only after posting succeeds
    if let Some(sid) = result.scan_id {
        if let Ok(store) = Store::open(&config.storage.db_path) {
            if let Err(e) = store.update_scan_stage(sid, "completed") {
                warn!(err = %e, "failed to mark scan as completed");
            }
        }
    }

    Ok(())
}

/// Persist a scan/review result to the store (BR-3: best-effort, never blocks pipeline).
pub fn persist_scan(
    db_path: &str,
    repo: &str,
    branch: &str,
    commit_sha: &str,
    command: &str,
    pr_number: Option<u64>,
    review: &cartomancer_core::review::ReviewResult,
) {
    let store = match Store::open(db_path) {
        Ok(s) => s,
        Err(e) => {
            warn!(path = db_path, err = %e, "failed to open store — scan not persisted");
            return;
        }
    };

    let record = ScanRecord {
        id: None,
        repo: repo.to_string(),
        branch: branch.to_string(),
        commit_sha: commit_sha.to_string(),
        command: command.to_string(),
        pr_number,
        finding_count: review.findings.len() as u32,
        summary: review.summary.clone(),
        created_at: None,
        stage: "completed".into(),
        error_message: None,
        failed_at_stage: None,
    };

    let scan_id = match store.insert_scan(&record) {
        Ok(id) => id,
        Err(e) => {
            warn!(err = %e, "failed to insert scan record — scan not persisted");
            return;
        }
    };

    if !review.findings.is_empty() {
        if let Err(e) = store.insert_findings(scan_id, &review.findings) {
            warn!(err = %e, "failed to insert findings — findings not persisted");
        }
    }

    info!(
        scan_id,
        findings = review.findings.len(),
        "scan persisted to store"
    );
}

/// Annotate findings as "new" or "existing" by comparing fingerprints against
/// the base branch baseline (US-5, BR-4). Best-effort: if the store is unavailable,
/// all findings are treated as new.
pub fn annotate_regression(
    db_path: &str,
    repo: &str,
    base_branch: &str,
    findings: &mut [Finding],
) -> (usize, usize) {
    let baseline = match Store::open(db_path) {
        Ok(store) => match store.baseline_fingerprints(repo, base_branch) {
            Ok(fps) => fps,
            Err(e) => {
                warn!(err = %e, "failed to load baseline — all findings treated as new");
                std::collections::HashSet::new()
            }
        },
        Err(e) => {
            warn!(err = %e, "failed to open store for regression check — all findings treated as new");
            std::collections::HashSet::new()
        }
    };

    let mut new_count = 0;
    let mut existing_count = 0;

    for finding in findings.iter_mut() {
        let fp = cartomancer_store::fingerprint::compute(
            &finding.rule_id,
            &finding.file_path,
            &finding.snippet,
        );
        if baseline.contains(&fp) {
            finding.is_new = Some(false);
            existing_count += 1;
        } else {
            finding.is_new = Some(true);
            new_count += 1;
        }
    }

    info!(
        new = new_count,
        existing = existing_count,
        "regression annotation complete"
    );
    (new_count, existing_count)
}

/// Filter out dismissed findings (BR-1: same fingerprint in dismissals table).
/// Best-effort: if the store is unavailable, no filtering is applied.
pub fn filter_dismissed(db_path: &str, findings: &mut Vec<Finding>) -> usize {
    let dismissed = match Store::open(db_path) {
        Ok(store) => match store.dismissed_fingerprints() {
            Ok(fps) => fps,
            Err(e) => {
                warn!(err = %e, "failed to load dismissed fingerprints — no filtering applied");
                return 0;
            }
        },
        Err(e) => {
            warn!(err = %e, "failed to open store for dismissal check — no filtering applied");
            return 0;
        }
    };

    if dismissed.is_empty() {
        return 0;
    }

    let before = findings.len();
    findings.retain(|f| {
        let fp = cartomancer_store::fingerprint::compute(&f.rule_id, &f.file_path, &f.snippet);
        !dismissed.contains(&fp)
    });
    let filtered = before - findings.len();

    if filtered > 0 {
        info!(filtered, "dismissed findings removed");
    }
    filtered
}

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

    #[test]
    fn prepare_work_dir_with_existing_git_repo() {
        let temp = tempfile::tempdir().unwrap();
        // Create a .git directory to simulate an existing checkout
        std::fs::create_dir(temp.path().join(".git")).unwrap();
        let (path, temp_handle) = prepare_work_dir(
            "owner/repo",
            "fake-token",
            Some(temp.path().to_str().unwrap()),
        )
        .unwrap();
        assert_eq!(path, temp.path());
        assert!(
            temp_handle.is_none(),
            "should not create temp dir for existing checkout"
        );
    }

    #[test]
    fn prepare_work_dir_without_arg_creates_temp() {
        // We can't actually clone here, but we test that temp dir is created
        let result = prepare_work_dir("owner/repo", "fake-token", None);
        // This will fail because git clone won't work, but we're testing the temp dir path
        // The error is expected — it means we got past temp dir creation
        assert!(result.is_err()); // git clone fails without network
    }

    #[test]
    fn pipeline_persist_scan_writes_to_store() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let db_str = db_path.to_str().unwrap();

        let review = ReviewResult {
            pr_number: 42,
            repo_full_name: "owner/repo".into(),
            head_sha: "abc123".into(),
            findings: vec![cartomancer_core::finding::Finding {
                rule_id: "test-rule".into(),
                message: "test finding".into(),
                severity: cartomancer_core::severity::Severity::Warning,
                file_path: "src/lib.rs".into(),
                start_line: 10,
                end_line: 12,
                snippet: "let x = 1;".into(),
                cwe: None,
                graph_context: None,
                llm_analysis: None,
                escalation_reasons: vec![],
                is_new: None,
                enclosing_context: None,
                suggested_fix: None,
                agent_prompt: None,
            }],
            summary: "1 finding".into(),
            status: ReviewStatus::Completed,
        };

        persist_scan(
            db_str,
            "owner/repo",
            "main",
            "abc123",
            "review",
            Some(42),
            &review,
        );

        // Verify it was written
        let store = Store::open(db_str).unwrap();
        let scans = store
            .list_scans(&cartomancer_store::types::ScanFilter::default())
            .unwrap();
        assert_eq!(scans.len(), 1);
        assert_eq!(scans[0].repo, "owner/repo");
        assert_eq!(scans[0].branch, "main");
        assert_eq!(scans[0].commit_sha, "abc123");
        assert_eq!(scans[0].command, "review");
        assert_eq!(scans[0].pr_number, Some(42));
        assert_eq!(scans[0].finding_count, 1);

        let findings = store.get_findings(scans[0].id.unwrap()).unwrap();
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "test-rule");
    }

    #[test]
    fn pipeline_persist_scan_empty_findings() {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let db_str = db_path.to_str().unwrap();

        let review = ReviewResult {
            pr_number: 1,
            repo_full_name: "owner/repo".into(),
            head_sha: "def456".into(),
            findings: vec![],
            summary: "clean".into(),
            status: ReviewStatus::Completed,
        };

        persist_scan(
            db_str,
            "owner/repo",
            "main",
            "def456",
            "scan",
            None,
            &review,
        );

        let store = Store::open(db_str).unwrap();
        let scans = store
            .list_scans(&cartomancer_store::types::ScanFilter::default())
            .unwrap();
        assert_eq!(scans.len(), 1);
        assert_eq!(scans[0].finding_count, 0);
        assert!(scans[0].pr_number.is_none());
    }

    #[test]
    fn pipeline_persist_scan_bad_path_does_not_panic() {
        let review = ReviewResult {
            pr_number: 1,
            repo_full_name: "owner/repo".into(),
            head_sha: "abc".into(),
            findings: vec![],
            summary: "clean".into(),
            status: ReviewStatus::Completed,
        };

        // Write to an invalid path — should log warning, not panic (BR-3)
        persist_scan(
            "/nonexistent/deep/path/that/cannot/be/created\0invalid",
            "owner/repo",
            "main",
            "abc",
            "scan",
            None,
            &review,
        );
        // If we get here without panic, BR-3 is satisfied
    }

    mod regression {
        use super::*;

        fn make_finding(rule_id: &str, file_path: &str, snippet: &str) -> Finding {
            Finding {
                rule_id: rule_id.into(),
                message: "test".into(),
                severity: cartomancer_core::severity::Severity::Warning,
                file_path: file_path.into(),
                start_line: 1,
                end_line: 1,
                snippet: snippet.into(),
                cwe: None,
                graph_context: None,
                llm_analysis: None,
                escalation_reasons: vec![],
                is_new: None,
                enclosing_context: None,
                suggested_fix: None,
                agent_prompt: None,
            }
        }

        #[test]
        fn regression_all_new_when_no_baseline() {
            let dir = tempfile::tempdir().unwrap();
            let db_path = dir.path().join("test.db");
            let db_str = db_path.to_str().unwrap();

            let mut findings = vec![make_finding("rule-a", "a.rs", "code")];
            let (new, existing) = annotate_regression(db_str, "owner/repo", "main", &mut findings);

            assert_eq!(new, 1);
            assert_eq!(existing, 0);
            assert_eq!(findings[0].is_new, Some(true));
        }

        #[test]
        fn regression_existing_findings_detected() {
            let dir = tempfile::tempdir().unwrap();
            let db_path = dir.path().join("test.db");
            let db_str = db_path.to_str().unwrap();

            // First: persist a scan with a finding on "main"
            let baseline_finding = make_finding("rule-a", "a.rs", "code");
            let review = ReviewResult {
                pr_number: 0,
                repo_full_name: "owner/repo".into(),
                head_sha: "base-sha".into(),
                findings: vec![baseline_finding],
                summary: "1 finding".into(),
                status: ReviewStatus::Completed,
            };
            persist_scan(
                db_str,
                "owner/repo",
                "main",
                "base-sha",
                "scan",
                None,
                &review,
            );

            // Now: annotate the same finding in a PR
            let mut findings = vec![
                make_finding("rule-a", "a.rs", "code"),     // same → existing
                make_finding("rule-b", "b.rs", "new code"), // new
            ];
            let (new, existing) = annotate_regression(db_str, "owner/repo", "main", &mut findings);

            assert_eq!(existing, 1);
            assert_eq!(new, 1);
            assert_eq!(findings[0].is_new, Some(false));
            assert_eq!(findings[1].is_new, Some(true));
        }

        #[test]
        fn regression_changed_snippet_is_new() {
            let dir = tempfile::tempdir().unwrap();
            let db_path = dir.path().join("test.db");
            let db_str = db_path.to_str().unwrap();

            // Baseline with original snippet
            let review = ReviewResult {
                pr_number: 0,
                repo_full_name: "owner/repo".into(),
                head_sha: "base-sha".into(),
                findings: vec![make_finding("rule-a", "a.rs", "old code")],
                summary: "1 finding".into(),
                status: ReviewStatus::Completed,
            };
            persist_scan(
                db_str,
                "owner/repo",
                "main",
                "base-sha",
                "scan",
                None,
                &review,
            );

            // Same rule + file but different snippet → new finding
            let mut findings = vec![make_finding("rule-a", "a.rs", "modified code")];
            let (new, existing) = annotate_regression(db_str, "owner/repo", "main", &mut findings);

            assert_eq!(new, 1);
            assert_eq!(existing, 0);
            assert_eq!(findings[0].is_new, Some(true));
        }

        #[test]
        fn regression_bad_store_treats_all_as_new() {
            let mut findings = vec![make_finding("rule-a", "a.rs", "code")];
            let (new, existing) =
                annotate_regression("/nonexistent\0invalid", "owner/repo", "main", &mut findings);

            assert_eq!(new, 1);
            assert_eq!(existing, 0);
            assert_eq!(findings[0].is_new, Some(true));
        }
    }

    mod dismiss {
        use super::*;
        use cartomancer_store::types::Dismissal;

        fn make_finding(rule_id: &str, file_path: &str, snippet: &str) -> Finding {
            Finding {
                rule_id: rule_id.into(),
                message: "test".into(),
                severity: cartomancer_core::severity::Severity::Warning,
                file_path: file_path.into(),
                start_line: 1,
                end_line: 1,
                snippet: snippet.into(),
                cwe: None,
                graph_context: None,
                llm_analysis: None,
                escalation_reasons: vec![],
                is_new: None,
                enclosing_context: None,
                suggested_fix: None,
                agent_prompt: None,
            }
        }

        #[test]
        fn dismiss_filters_matching_findings() {
            let dir = tempfile::tempdir().unwrap();
            let db_path = dir.path().join("test.db");
            let db_str = db_path.to_str().unwrap();

            // Create a dismissal
            let store = Store::open(db_str).unwrap();
            let fp = cartomancer_store::fingerprint::compute("rule-a", "a.rs", "code");
            store
                .dismiss(&Dismissal {
                    id: None,
                    fingerprint: fp,
                    rule_id: "rule-a".into(),
                    file_path: "a.rs".into(),
                    start_line: 1,
                    end_line: 1,
                    snippet_hash: cartomancer_store::fingerprint::snippet_hash("code"),
                    reason: Some("false positive".into()),
                    created_at: None,
                })
                .unwrap();
            drop(store);

            let mut findings = vec![
                make_finding("rule-a", "a.rs", "code"),  // dismissed
                make_finding("rule-b", "b.rs", "other"), // not dismissed
            ];

            let filtered = filter_dismissed(db_str, &mut findings);
            assert_eq!(filtered, 1);
            assert_eq!(findings.len(), 1);
            assert_eq!(findings[0].rule_id, "rule-b");
        }

        #[test]
        fn dismiss_no_dismissals_keeps_all() {
            let dir = tempfile::tempdir().unwrap();
            let db_path = dir.path().join("test.db");
            let db_str = db_path.to_str().unwrap();

            let mut findings = vec![make_finding("rule-a", "a.rs", "code")];
            let filtered = filter_dismissed(db_str, &mut findings);
            assert_eq!(filtered, 0);
            assert_eq!(findings.len(), 1);
        }

        #[test]
        fn dismiss_changed_snippet_not_filtered() {
            let dir = tempfile::tempdir().unwrap();
            let db_path = dir.path().join("test.db");
            let db_str = db_path.to_str().unwrap();

            // Dismiss with original snippet
            let store = Store::open(db_str).unwrap();
            let fp = cartomancer_store::fingerprint::compute("rule-a", "a.rs", "old code");
            store
                .dismiss(&Dismissal {
                    id: None,
                    fingerprint: fp,
                    rule_id: "rule-a".into(),
                    file_path: "a.rs".into(),
                    start_line: 1,
                    end_line: 1,
                    snippet_hash: cartomancer_store::fingerprint::snippet_hash("old code"),
                    reason: None,
                    created_at: None,
                })
                .unwrap();
            drop(store);

            // Finding with changed snippet → different fingerprint → not filtered
            let mut findings = vec![make_finding("rule-a", "a.rs", "new code")];
            let filtered = filter_dismissed(db_str, &mut findings);
            assert_eq!(filtered, 0);
            assert_eq!(findings.len(), 1);
        }

        #[test]
        fn dismiss_bad_store_keeps_all() {
            let mut findings = vec![make_finding("rule-a", "a.rs", "code")];
            let filtered = filter_dismissed("/nonexistent\0invalid", &mut findings);
            assert_eq!(filtered, 0);
            assert_eq!(findings.len(), 1);
        }
    }

    mod stored_to_findings_tests {
        use super::*;
        use cartomancer_store::types::StoredFinding;

        fn sample_stored_finding() -> StoredFinding {
            StoredFinding {
                id: Some(1),
                scan_id: 1,
                fingerprint: "fp123".into(),
                rule_id: "test-rule".into(),
                severity: "error".into(),
                file_path: "src/lib.rs".into(),
                start_line: 10,
                end_line: 12,
                message: "test finding".into(),
                snippet: "let x = 1;".into(),
                cwe: Some("CWE-798".into()),
                graph_context_json: None,
                llm_analysis: Some("analysis text".into()),
                escalation_reasons_json: None,
                enclosing_context: Some("fn main() { ... }".into()),
                suggested_fix: Some("-old\n+new".into()),
                agent_prompt: Some("fix it".into()),
            }
        }

        #[test]
        fn converts_basic_fields() {
            let stored = vec![sample_stored_finding()];
            let findings = stored_to_findings(&stored);

            assert_eq!(findings.len(), 1);
            let f = &findings[0];
            assert_eq!(f.rule_id, "test-rule");
            assert_eq!(f.severity, cartomancer_core::severity::Severity::Error);
            assert_eq!(f.file_path, "src/lib.rs");
            assert_eq!(f.start_line, 10);
            assert_eq!(f.end_line, 12);
            assert_eq!(f.message, "test finding");
            assert_eq!(f.snippet, "let x = 1;");
            assert_eq!(f.cwe.as_deref(), Some("CWE-798"));
            assert_eq!(f.llm_analysis.as_deref(), Some("analysis text"));
            assert_eq!(f.enclosing_context.as_deref(), Some("fn main() { ... }"));
            assert_eq!(f.suggested_fix.as_deref(), Some("-old\n+new"));
            assert_eq!(f.agent_prompt.as_deref(), Some("fix it"));
            assert!(f.graph_context.is_none());
            assert!(f.escalation_reasons.is_empty());
            assert!(f.is_new.is_none());
        }

        #[test]
        fn invalid_severity_falls_back_to_warning() {
            let mut sf = sample_stored_finding();
            sf.severity = "unknown_level".into();
            let findings = stored_to_findings(&[sf]);
            assert_eq!(
                findings[0].severity,
                cartomancer_core::severity::Severity::Warning
            );
        }

        #[test]
        fn parses_graph_context_json() {
            let mut sf = sample_stored_finding();
            sf.graph_context_json = Some(
                r#"{"symbol_name":"check","callers":["main"],"blast_radius":5,"is_public_api":true,"domain_tags":["auth"]}"#.into(),
            );
            let findings = stored_to_findings(&[sf]);
            let ctx = findings[0].graph_context.as_ref().unwrap();
            assert_eq!(ctx.blast_radius, 5);
            assert_eq!(ctx.callers, vec!["main"]);
            assert!(ctx.is_public_api);
        }

        #[test]
        fn parses_escalation_reasons_json() {
            let mut sf = sample_stored_finding();
            sf.escalation_reasons_json = Some(r#"["high blast radius","auth domain"]"#.into());
            let findings = stored_to_findings(&[sf]);
            assert_eq!(
                findings[0].escalation_reasons,
                vec!["high blast radius", "auth domain"]
            );
        }

        #[test]
        fn invalid_json_fields_are_none() {
            let mut sf = sample_stored_finding();
            sf.graph_context_json = Some("not json".into());
            sf.escalation_reasons_json = Some("{bad".into());
            let findings = stored_to_findings(&[sf]);
            assert!(findings[0].graph_context.is_none());
            assert!(findings[0].escalation_reasons.is_empty());
        }

        #[test]
        fn empty_input_returns_empty() {
            let findings = stored_to_findings(&[]);
            assert!(findings.is_empty());
        }
    }

    mod prepare_review_payload_tests {
        use super::*;
        use cartomancer_core::diff::{DiffChunk, PullRequestDiff};

        fn make_finding(file: &str, line: u32) -> Finding {
            Finding {
                rule_id: "test-rule".into(),
                message: "test finding".into(),
                severity: cartomancer_core::severity::Severity::Warning,
                file_path: file.into(),
                start_line: line,
                end_line: line + 1,
                snippet: "code".into(),
                cwe: None,
                graph_context: None,
                llm_analysis: None,
                escalation_reasons: vec![],
                is_new: None,
                enclosing_context: None,
                suggested_fix: None,
                agent_prompt: None,
            }
        }

        fn make_diff(file: &str, start: u32, lines: u32) -> PullRequestDiff {
            PullRequestDiff {
                chunks: vec![DiffChunk {
                    file_path: file.into(),
                    old_start: 1,
                    new_start: start,
                    old_lines: lines,
                    new_lines: lines,
                    content: String::new(),
                }],
                files_changed: vec![file.into()],
            }
        }

        fn make_result(findings: Vec<Finding>, diff: PullRequestDiff) -> PipelineResult {
            PipelineResult {
                review: ReviewResult {
                    pr_number: 1,
                    repo_full_name: "o/r".into(),
                    head_sha: "abc".into(),
                    findings,
                    summary: "original summary".into(),
                    status: ReviewStatus::Completed,
                },
                diff,
                branch: "feat".into(),
                base_branch: "main".into(),
                scan_duration: std::time::Duration::from_secs(1),
                rule_count: 5,
                scan_id: None,
                temp_dir: None,
            }
        }

        #[test]
        fn empty_findings_returns_original_summary() {
            let result = make_result(vec![], make_diff("a.rs", 1, 10));
            let payload = prepare_review_payload(&result);
            assert!(payload.inline_comments.is_empty());
            assert!(payload.off_diff_bodies.is_empty());
            assert_eq!(payload.summary, "original summary");
        }

        #[test]
        fn inline_finding_becomes_review_comment() {
            let diff = make_diff("src/lib.rs", 10, 5);
            let findings = vec![make_finding("src/lib.rs", 12)];
            let result = make_result(findings, diff);
            let payload = prepare_review_payload(&result);

            assert_eq!(payload.inline_comments.len(), 1);
            assert_eq!(payload.inline_comments[0].path, "src/lib.rs");
            assert_eq!(payload.inline_comments[0].line, 12);
            assert!(payload.off_diff_bodies.is_empty());
        }

        #[test]
        fn off_diff_finding_becomes_comment_body() {
            let diff = make_diff("src/lib.rs", 10, 5);
            // Finding at line 50, outside diff range 10..15
            let findings = vec![make_finding("src/lib.rs", 50)];
            let result = make_result(findings, diff);
            let payload = prepare_review_payload(&result);

            assert!(payload.inline_comments.is_empty());
            assert_eq!(payload.off_diff_bodies.len(), 1);
            // Summary is regenerated when off-diff findings exist
            assert_ne!(payload.summary, "original summary");
        }

        #[test]
        fn mixed_inline_and_off_diff() {
            let diff = make_diff("src/lib.rs", 10, 5);
            let findings = vec![
                make_finding("src/lib.rs", 12), // inline (in diff 10..15)
                make_finding("src/lib.rs", 50), // off-diff
                make_finding("other.rs", 1),    // off-diff (different file)
            ];
            let result = make_result(findings, diff);
            let payload = prepare_review_payload(&result);

            assert_eq!(payload.inline_comments.len(), 1);
            assert_eq!(payload.off_diff_bodies.len(), 2);
        }

        #[test]
        fn all_inline_keeps_original_summary() {
            let diff = make_diff("src/lib.rs", 1, 100);
            let findings = vec![
                make_finding("src/lib.rs", 10),
                make_finding("src/lib.rs", 20),
            ];
            let result = make_result(findings, diff);
            let payload = prepare_review_payload(&result);

            assert_eq!(payload.inline_comments.len(), 2);
            assert!(payload.off_diff_bodies.is_empty());
            assert_eq!(payload.summary, "original summary");
        }
    }

    #[test]
    fn pipeline_result_has_correct_fields() {
        let review = ReviewResult {
            pr_number: 42,
            repo_full_name: "owner/repo".into(),
            head_sha: "abc123".into(),
            findings: vec![],
            summary: "clean".into(),
            status: ReviewStatus::Completed,
        };
        let result = PipelineResult {
            review,
            diff: PullRequestDiff {
                chunks: vec![],
                files_changed: vec![],
            },
            branch: "main".into(),
            base_branch: "main".into(),
            scan_duration: std::time::Duration::from_secs(1),
            rule_count: 10,
            scan_id: None,
            temp_dir: None,
        };
        assert_eq!(result.review.pr_number, 42);
        assert_eq!(result.review.summary, "clean");
        assert!(result.diff.chunks.is_empty());
    }
}