prview 0.4.0

PR Review & Artifact Generator - cross-language PR analysis tool
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
use super::super::CheckGateEntry;
use super::super::signal::BreakingFinding;
use super::*;
use crate::checks::{CheckResult, CheckStatus, SkippedCheck};
use crate::config::{Config, test_config, test_rust_profile};
use crate::git::{CommitInfo, Diff, DiffStats, FileChange, FileStatus};
use crate::policy::PolicyConfig;
use regex::Regex;
use serde_json::json;
use std::fs;
use std::time::Duration;

macro_rules! build_html_test {
    ($config:expr, $diffs:expr, $checks:expr, $heuristics:expr, $ctx:expr, $report_json:expr, $dir:expr, $pr_review:expr, $regression:expr $(,)?) => {
        build_html(BuildHtmlInput {
            config: $config,
            diffs: $diffs,
            checks: $checks,
            heuristics: $heuristics,
            ctx: $ctx,
            report_json: $report_json,
            dir: $dir,
            pr_review: $pr_review,
            regression: $regression,
        })
    };
}

fn mock_config() -> Config {
    let mut config = test_config();
    config.target = Some("feature/test".to_string());
    config.bases = vec!["main".to_string()];
    config.profile = test_rust_profile(true);
    config.do_fetch = false;
    config.use_cache = false;
    config.create_zip = false;
    config.policy = PolicyConfig::default();
    config
}

fn mock_diff() -> Diff {
    Diff {
        base: "main".into(),
        target: "feature/test".into(),
        base_commit_id: "aaa".into(),
        target_commit_id: "bbb".into(),
        stats: DiffStats {
            files_changed: 3,
            additions: 150,
            deletions: 30,
            copied: 0,
        },
        files: vec![
            FileChange {
                path: "src/main.rs".into(),
                status: FileStatus::Modified,
                additions: 100,
                deletions: 20,
            },
            FileChange {
                path: "src/lib.rs".into(),
                status: FileStatus::Modified,
                additions: 40,
                deletions: 5,
            },
            FileChange {
                path: "src/old.rs".into(),
                status: FileStatus::Deleted,
                additions: 0,
                deletions: 5,
            },
        ],
        commits: vec![CommitInfo {
            id: "aabbcc".into(),
            short_id: "aabbc".into(),
            message: "test commit".into(),
            author: "dev".into(),
            email: "dev@test.com".into(),
            date: "2026-01-01".into(),
        }],
    }
}

fn mock_checks() -> Vec<CheckResult> {
    vec![
        CheckResult {
            name: "cargo check".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(2),
            output: "ok".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "cargo clippy".into(),
            status: CheckStatus::Warnings,
            duration: Duration::from_secs(3),
            output: "2 warnings".into(),
            cached: false,
            provenance: None,
        },
    ]
}

fn mock_ctx() -> DashboardContext {
    DashboardContext {
        verdict: "PASS",
        analysis_status: crate::policy::engine::AnalysisStatus::Complete,
        merge_recommendation: crate::policy::engine::MergeRecommendation::Approve,
        allow_merge: true,
        quality_pass: true,
        policy_allow_merge: true,
        recommended_merge: true,
        review_caveats: vec![],
        quality_failures: vec![],
        introduced_quality_failures: vec![],
        preexisting_quality_failures: vec![],
        mixed_quality_failures: vec![],
        unclassified_quality_failures: vec![],
        quality_failure_details: vec![],
        policy_mode: "standard",
        blocking_issues: vec![],
        check_gates: vec![],
        breaking: vec![],
        coverage: super::super::CoverageDelta {
            pct: 100,
            total_source: 1,
            covered_count: 1,
            uncovered: vec![],
            covered: vec![],
            non_code_count: 0,
            ghost_tests: vec![],
        },
        findings: vec![],
        per_file_diff_files: vec!["abc12345__src~2Fmain.rs.patch".into()],
        skipped_checks: vec![SkippedCheck {
            id: "cargo_geiger".into(),
            name: "Cargo Geiger".into(),
            reason: "not installed".into(),
        }],
        previous_run: None,
        run_history: vec![],
        flaky_scores: vec![],
        lint_metrics: vec![],
        ownership_map: vec![
            ("src/main.rs".into(), "core".into()),
            ("src/lib.rs".into(), "core".into()),
            ("src/old.rs".into(), "core".into()),
        ],
        risk_scores: vec![],
        i18n_delta: None,
    }
}

#[test]
fn test_safe_id_deterministic() {
    // Slashes become _x2f_, dots become _x2e_
    assert_eq!(safe_id("src/main.rs"), "src_x2f_main_x2e_rs");
    assert_eq!(
        safe_id("src/artifacts/dashboard.rs"),
        "src_x2f_artifacts_x2f_dashboard_x2e_rs"
    );
    assert_eq!(safe_id("a/b/c.test.tsx"), "a_x2f_b_x2f_c_x2e_test_x2e_tsx");
    // Same input always produces same output
    assert_eq!(safe_id("src/main.rs"), safe_id("src/main.rs"));
}

#[test]
fn test_safe_id_no_special_chars() {
    let id = safe_id("src/[foo]/{bar}.rs");
    assert!(id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'));
}

#[test]
fn test_safe_id_no_collisions() {
    // Paths differing only in separator characters must produce different IDs
    assert_ne!(safe_id("src/foo-bar.rs"), safe_id("src/foo_bar.rs"));
    assert_ne!(safe_id("src/foo.bar"), safe_id("src/foo_bar"));
    assert_ne!(safe_id("a-b"), safe_id("a_b"));
    assert_ne!(safe_id("a/b"), safe_id("a_b"));
    assert_ne!(safe_id("a.b"), safe_id("a_b"));
}

#[test]
fn test_deep_links_consistency() {
    // Every href="#file-..." in the HTML must have a corresponding id="file-..."
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);

    // Extract all href="#file-..." targets
    let href_re = Regex::new(r##"href="#file-([^"]+)""##).unwrap();
    let id_re = Regex::new(r##"id="file-([^"]+)""##).unwrap();

    let hrefs: std::collections::HashSet<String> = href_re
        .captures_iter(&html)
        .map(|c| c[1].to_string())
        .collect();
    let ids: std::collections::HashSet<String> = id_re
        .captures_iter(&html)
        .map(|c| c[1].to_string())
        .collect();

    for href in &hrefs {
        assert!(
            ids.contains(href),
            "href='#file-{}' has no matching id='file-{}'",
            href,
            href
        );
    }
}

#[test]
fn test_collapsible_wrappers_use_data_section_ids() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);

    assert!(html.contains(r#"data-section-id="section-checks""#));
    assert!(html.contains(r#"data-section-id="section-files""#));
    assert!(html.contains(r#"data-section-id="section-artifacts""#));
    assert!(html.contains(r#"id="section-checks__body""#));
    assert!(html.contains(r#"id="section-files__body""#));
}

#[test]
fn test_build_html_stays_self_contained_without_external_font_cdns() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);

    assert!(html.contains("system stack only, no external CDN dependency"));
    assert!(!html.contains("fonts.googleapis.com"));
    assert!(!html.contains("fonts.gstatic.com"));
}

#[test]
fn test_checks_summary_shows_warn() {
    let checks = mock_checks(); // 1 passed, 1 warnings
    let ctx = mock_ctx();
    let html = build_checks_section(&checks, &ctx);

    assert!(html.contains("1 passed"), "Should show passed count");
    assert!(html.contains("1 warn"), "Should show warn count");
    assert!(
        !html.contains("2/2 passed"),
        "Should NOT show old 'X/Y passed' format"
    );
}

#[test]
fn test_skipped_checks_rendered() {
    let checks = mock_checks();
    let ctx = mock_ctx(); // has 1 skipped check
    let html = build_checks_section(&checks, &ctx);

    assert!(
        html.contains(r#"data-i18n="label.skipped""#),
        "Should localize skipped label"
    );
    assert!(html.contains("(1)"), "Should show skipped count");
    assert!(
        html.contains("Cargo Geiger"),
        "Should show skipped check name"
    );
    assert!(html.contains("not installed"), "Should show skip reason");
}

#[test]
fn test_file_rows_have_ids() {
    let diff = mock_diff();
    let ctx = mock_ctx();
    let html = build_files_section(Some(&diff), &ctx);

    assert!(
        html.contains(&format!(r#"id="file-{}""#, safe_id("src/main.rs"))),
        "src/main.rs should have safe id"
    );
    assert!(
        html.contains(&format!(r#"id="file-{}""#, safe_id("src/lib.rs"))),
        "src/lib.rs should have safe id"
    );
    assert!(
        html.contains(&format!(r#"id="file-{}""#, safe_id("src/old.rs"))),
        "src/old.rs should have safe id"
    );
}

#[test]
fn test_files_section_defaults_to_code_hotspots() {
    let diff = mock_diff();
    let ctx = mock_ctx();
    let html = build_files_section(Some(&diff), &ctx);

    assert!(
        html.contains(r#"class="toggle-btn active" data-show="code""#),
        "Files section should default to Code view"
    );
    assert!(
        html.contains("non-code"),
        "Files summary should expose non-code count"
    );
}

#[test]
fn test_file_with_patch_has_data_attr() {
    let diff = mock_diff();
    let ctx = mock_ctx(); // has abc12345__src~2Fmain.rs.patch
    let html = build_files_section(Some(&diff), &ctx);

    assert!(
        html.contains("data-patch-path"),
        "File with patch should have data-patch-path"
    );
    assert!(
        html.contains("abc12345__src~2Fmain.rs.patch"),
        "Patch path should reference correct file with sanitized encoding"
    );
}

#[test]
fn test_artifacts_explorer_has_per_file_patches() {
    let ctx = mock_ctx();
    let html = build_artifacts_section(&ctx);

    assert!(
        html.contains("Artifacts Explorer"),
        "Should have Explorer title"
    );
    assert!(
        html.contains("abc12345__src~2Fmain.rs.patch"),
        "Should include per-file patch with sanitized encoding"
    );
    assert!(html.contains("artifact-search"), "Should have search input");
    assert!(
        html.contains("artifact-kind-chip"),
        "Should have kind filter chips"
    );
}

#[test]
fn test_header_merge_chip_shows_review_caveat() {
    let config = mock_config();
    let diff = mock_diff();
    let mut ctx = mock_ctx();
    ctx.check_gates = vec![CheckGateEntry {
        name: "cargo check".into(),
        id: "cargo".into(),
        blocking: false,
        class: "pass",
        severity: "warn",
    }];
    ctx.breaking = vec![BreakingFinding {
        file: "src/lib.rs".into(),
        kind: BreakingKind::RemovedSymbol {
            symbol_type: "function".into(),
        },
        line: "pub fn old_api()".into(),
        risk_level: BreakingRisk::High,
    }];
    ctx.coverage = super::super::CoverageDelta {
        pct: 11,
        total_source: 43,
        covered_count: 5,
        uncovered: vec![],
        covered: vec![],
        non_code_count: 18,
        ghost_tests: vec![],
    };
    let html = build_header(&config, Some(&diff), &ctx, Path::new("20260308-031035"), "");

    assert!(html.contains("ALLOW WITH REVIEW"));
    assert!(html.contains(r#"data-i18n-template="hero.mergeAllowWithReview""#));
    // De-choinka v2: the header carries only a compact amber-dot marker plus a
    // muted count. The full caveat prose lives in the Merge Decision card below,
    // so it is intentionally NOT duplicated in the above-the-fold header.
    assert!(html.contains("review-signal-dot"));
    assert!(html.contains(r#"data-i18n-template="summary.reviewSignalCount""#));
    assert!(html.contains(r#"data-count="2""#));
    assert!(html.contains("2 review signals"));
    assert!(!html.contains("1 removed public symbol"));
}

#[test]
fn test_header_merge_chip_shows_hold_when_not_recommended() {
    let config = mock_config();
    let diff = mock_diff();
    let mut ctx = mock_ctx();
    ctx.check_gates = vec![CheckGateEntry {
        name: "cargo check".into(),
        id: "cargo".into(),
        blocking: false,
        class: "pass",
        severity: "warn",
    }];
    ctx.quality_pass = false;
    ctx.recommended_merge = false;
    ctx.allow_merge = true;
    ctx.policy_allow_merge = true;
    ctx.quality_failures = vec!["cargo clippy".into()];

    let html = build_header(&config, Some(&diff), &ctx, Path::new("20260308-031035"), "");

    assert!(html.contains("HOLD MERGE"));
    assert!(!html.contains("BLOCK MERGE"));
}

#[test]
fn test_header_contains_dashboard_context_bar() {
    let mut config = mock_config();
    config.gh_repo = Some("vetcoders/prview".into());
    config.pr_number = Some(42);
    config.pr_url = Some("https://github.com/vetcoders/prview/pull/42".into());
    let diff = mock_diff();
    let ctx = mock_ctx();

    let report_json = r#"{"meta":{"generated_at":"2026-03-08T03:10:35+01:00"}}"#;
    let html = build_header(
        &config,
        Some(&diff),
        &ctx,
        Path::new("dashboard-context-header-p0"),
        report_json,
    );

    assert!(html.contains("vetcoders/prview"));
    assert!(html.contains(r#"<span class="wordmark">prview<span class="dot""#));
    assert!(html.contains("feature/test"));
    assert!(html.contains("main"));
    assert!(html.contains("bbb"));
    assert!(html.contains("20260308-031035"));
    assert!(html.contains("2026-03-08 03:10:35"));
    assert!(html.contains("#42"));
}

#[test]
fn test_header_prefers_run_json_context_for_custom_output_dir() {
    let config = mock_config();
    let diff = mock_diff();
    let ctx = mock_ctx();
    let temp = tempfile::tempdir().unwrap();
    let summary_dir = temp.path().join("00_summary");
    fs::create_dir_all(&summary_dir).unwrap();
    fs::write(
        summary_dir.join("RUN.json"),
        serde_json::to_string_pretty(&json!({
            "repo": { "gh_repo": "vetcoders/rmcp-memex" },
            "refs": {
                "target": "agent/context-pass",
                "target_sha": "02aabca1234567890",
                "bases": [{ "name": "develop", "sha": "abc1234567890" }]
            },
            "run_finished_at": "2026-03-05T19:17:49+01:00"
        }))
        .unwrap(),
    )
    .unwrap();

    let html = build_header(&config, Some(&diff), &ctx, temp.path(), "{}");

    assert!(html.contains("vetcoders/rmcp-memex"));
    assert!(html.contains("agent/context-pass"));
    assert!(html.contains("develop"));
    assert!(html.contains("02aabca"));
    assert!(html.contains("20260305-191749"));
    assert!(html.contains("2026-03-05 19:17:49"));
}

// ---- PRV-101: Merge Decision Card ----

#[test]
fn test_merge_decision_card_all_pass() {
    let ctx = mock_ctx(); // recommended_merge=true, quality_pass=true, policy_allow_merge=true
    let html = build_merge_decision_card(&ctx);

    assert!(html.contains("Merge Decision"), "Should have title");
    assert!(html.contains("Policy: ALLOW"), "Policy should be ALLOW");
    assert!(html.contains("Quality: PASS"), "Quality should be PASS");
    assert!(html.contains("Merge: GO"), "Merge should be GO");
    assert!(html.contains("alert-success"), "Should be success class");
    assert!(
        html.contains("All quality gates passed"),
        "Should show success reason"
    );
}

#[test]
fn test_merge_decision_card_review_caveats() {
    let mut ctx = mock_ctx();
    ctx.breaking = vec![BreakingFinding {
        file: "src/lib.rs".into(),
        kind: BreakingKind::RemovedSymbol {
            symbol_type: "function".into(),
        },
        line: "pub fn old_api()".into(),
        risk_level: BreakingRisk::High,
    }];
    ctx.coverage = super::super::CoverageDelta {
        pct: 11,
        total_source: 43,
        covered_count: 5,
        uncovered: vec![],
        covered: vec![],
        non_code_count: 18,
        ghost_tests: vec![],
    };
    ctx.findings = vec![super::super::DashboardFinding {
        level: "warning",
        check_name: "heuristics_loctree".into(),
        check_id: "heuristics_loctree".into(),
        message: "review me".into(),
        in_diff: Some(true),
    }];
    let html = build_merge_decision_card(&ctx);

    assert!(html.contains("Merge: GO WITH REVIEW"));
    assert!(html.contains("alert-warning"));
    assert!(html.contains("Quality gates passed, but 3 review signals need attention"));
    assert!(html.contains(
        r#"data-decision-reason="Quality gates passed, but 3 review signals need attention""#
    ));
    assert!(html.contains(r#"data-i18n="message.reviewSignalsPrefix""#));
    assert!(html.contains(
            r#"data-review-signals="1 removed public symbol · 11% coverage heuristic · 1 inline finding""#
        ));
    assert!(html.contains("11% coverage heuristic"));
    assert!(html.contains("1 inline finding"));
}

#[test]
fn test_merge_decision_card_quality_fail() {
    let mut ctx = mock_ctx();
    ctx.quality_pass = false;
    ctx.recommended_merge = false;
    ctx.allow_merge = true; // policy allows but quality fails
    ctx.quality_failures = vec!["cargo_clippy".into(), "cargo_test".into()];
    let html = build_merge_decision_card(&ctx);

    assert!(html.contains("Quality: FAIL"), "Quality should be FAIL");
    assert!(
        html.contains("Merge: HOLD"),
        "Merge should be HOLD when policy allows but quality fails"
    );
    assert!(html.contains("alert-warning"), "Should be warning class");
    assert!(
        html.contains("2 quality checks failed"),
        "Should show failure count"
    );
}

#[test]
fn test_merge_decision_card_policy_block() {
    let mut ctx = mock_ctx();
    ctx.policy_allow_merge = false;
    ctx.recommended_merge = false;
    ctx.allow_merge = false;
    ctx.blocking_issues = vec!["cargo_clippy (fail)".into()];
    let html = build_merge_decision_card(&ctx);

    assert!(html.contains("Policy: BLOCK"), "Policy should be BLOCK");
    assert!(html.contains("Merge: BLOCK"), "Merge should be BLOCK");
    assert!(html.contains("alert-error"), "Should be error class");
    assert!(
        html.contains("1 blocking issue found"),
        "Should show blocking count"
    );
}

#[test]
fn test_action_center_traffic_light_chips() {
    let ctx = mock_ctx();
    let checks = mock_checks();
    let html = build_action_center(&ctx, &checks, None);

    assert!(
        html.contains("action-row"),
        "Action center should use action-row layout"
    );
    assert!(
        html.contains("action-chip"),
        "Action center should contain action chips"
    );
    // Should have Checks chip (all passed in mock)
    assert!(
        html.contains("Checks"),
        "Action center should contain Checks chip"
    );
    assert!(
        html.contains(r#"data-i18n-template="count.warnings""#),
        "Checks warning card should be localizable"
    );
    // Should have Breaking chip
    assert!(
        html.contains("Breaking"),
        "Action center should contain Breaking chip"
    );
    // Should have Findings chip
    assert!(
        html.contains("Findings"),
        "Action center should contain Findings chip"
    );
}

// ---- PRV-102: Top 3 Blockers ----

#[test]
fn test_blockers_section_no_blockers() {
    let ctx = mock_ctx();
    let checks = mock_checks(); // all passed/warnings, no failures
    let html = build_blockers_section(&ctx, &checks);

    assert!(
        html.is_empty(),
        "Clean runs should not emit a green blockers section"
    );
}

#[test]
fn test_blockers_section_with_failures() {
    let ctx = mock_ctx();
    let checks = vec![
        CheckResult {
            name: "cargo clippy".into(),
            status: CheckStatus::Failed,
            duration: Duration::from_secs(3),
            output: "error: unused variable\nhelp: remove it".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "cargo test".into(),
            status: CheckStatus::Error,
            duration: Duration::from_secs(5),
            output: "thread panicked\ntest result: FAILED".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "cargo check".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(2),
            output: "ok".into(),
            cached: false,
            provenance: None,
        },
    ];
    let html = build_blockers_section(&ctx, &checks);

    assert!(html.contains("Blockers"), "Should have Blockers title");
    assert!(html.contains("cargo test"), "Should show errored check");
    assert!(html.contains("cargo clippy"), "Should show failed check");
    assert!(
        !html.contains("cargo check"),
        "Should not show passed check"
    );
    // Error should appear before Fail
    let error_pos = html.find("cargo test").unwrap();
    let fail_pos = html.find("cargo clippy").unwrap();
    assert!(
        error_pos < fail_pos,
        "Error checks should appear before Failed checks"
    );
}

#[test]
fn test_blockers_section_max_three() {
    let ctx = mock_ctx();
    let checks = vec![
        CheckResult {
            name: "check_a".into(),
            status: CheckStatus::Failed,
            duration: Duration::from_secs(1),
            output: "fail a".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "check_b".into(),
            status: CheckStatus::Failed,
            duration: Duration::from_secs(1),
            output: "fail b".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "check_c".into(),
            status: CheckStatus::Failed,
            duration: Duration::from_secs(1),
            output: "fail c".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "check_d".into(),
            status: CheckStatus::Failed,
            duration: Duration::from_secs(1),
            output: "fail d".into(),
            cached: false,
            provenance: None,
        },
    ];
    let html = build_blockers_section(&ctx, &checks);

    assert!(html.contains("check_a"), "Should show check_a");
    assert!(html.contains("check_b"), "Should show check_b");
    assert!(html.contains("check_c"), "Should show check_c");
    assert!(!html.contains("check_d"), "Should NOT show check_d (max 3)");
    assert!(html.contains("section-count\">3"), "Count should be 3");
}

#[test]
fn test_blockers_debug_hints() {
    assert_eq!(debug_hint_for_check("cargo_clippy"), "cargo clippy --fix");
    assert_eq!(
        debug_hint_for_check("cargo_test"),
        "cargo test -- --nocapture"
    );
    assert_eq!(debug_hint_for_check("cargo_fmt"), "cargo fmt");
    assert_eq!(debug_hint_for_check("eslint"), "npx eslint --fix .");
    assert_eq!(debug_hint_for_check("ruff_check"), "ruff check --fix .");
    assert_eq!(
        debug_hint_for_check("unknown_check"),
        "Re-run locally with verbose output"
    );
}

// ---- PRV-103: Time Budget ----

#[test]
fn test_time_budget_basic() {
    let checks = mock_checks();
    let html = build_time_budget(&checks);

    assert!(
        html.contains("Time Budget"),
        "Should have Time Budget title"
    );
    assert!(
        html.contains("section-time-budget"),
        "Should have section id"
    );
    assert!(html.contains("cargo check"), "Should show check name");
    assert!(html.contains("cargo clippy"), "Should show check name");
    assert!(
        html.contains(r#"data-i18n="label.total""#),
        "Should localize total label"
    );
    assert!(html.contains("2 checks"), "Should show count");
}

#[test]
fn test_time_budget_slowest_badge() {
    let checks = vec![
        CheckResult {
            name: "fast_check".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(1),
            output: "ok".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "slow_check".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(10),
            output: "ok".into(),
            cached: false,
            provenance: None,
        },
    ];
    let html = build_time_budget(&checks);

    assert!(html.contains("tb-slowest"), "Should have slowest bar class");
    assert!(html.contains("slowest"), "Should have slowest badge");
    // Slowest should be on slow_check's row
    let slowest_pos = html.find("tb-slowest").unwrap();
    let slow_check_pos = html.find("slow_check").unwrap();
    assert!(
        slowest_pos > slow_check_pos,
        "Slowest bar should be on slow_check's row"
    );
}

#[test]
fn test_time_budget_cached_label() {
    let checks = vec![
        CheckResult {
            name: "cached_check".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(0),
            output: "ok".into(),
            cached: true,
            provenance: None,
        },
        CheckResult {
            name: "normal_check".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(5),
            output: "ok".into(),
            cached: false,
            provenance: None,
        },
    ];
    let html = build_time_budget(&checks);

    assert!(html.contains("tb-cached"), "Should have cached bar class");
    assert!(html.contains("(cached)"), "Should show cached label");
}

#[test]
fn test_time_budget_empty() {
    let checks: Vec<CheckResult> = vec![];
    let html = build_time_budget(&checks);
    assert!(html.is_empty(), "Empty checks should produce empty string");
}

#[test]
fn test_time_budget_single_check_no_slowest() {
    let checks = vec![CheckResult {
        name: "only_check".into(),
        status: CheckStatus::Passed,
        duration: Duration::from_secs(5),
        output: "ok".into(),
        cached: false,
        provenance: None,
    }];
    let html = build_time_budget(&checks);

    assert!(html.contains("only_check"), "Should show the check");
    assert!(
        !html.contains("slowest"),
        "Single check should not have slowest badge"
    );
    assert!(html.contains("1 check"), "Should show singular count");
}

// ---- Integration: sidebar nav ----

#[test]
fn test_sidebar_has_blockers_when_failures() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = vec![CheckResult {
        name: "failing_check".into(),
        status: CheckStatus::Failed,
        duration: Duration::from_secs(2),
        output: "fail".into(),
        cached: false,
        provenance: None,
    }];
    let mut ctx = mock_ctx();
    ctx.quality_pass = false;
    ctx.recommended_merge = false;
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);

    assert!(
        !html.contains(r##"href="#section-blockers""##),
        "Sidebar should stay compact and avoid a dedicated Blockers link"
    );
    assert!(
        html.contains(r##"href="#section-time-budget""##),
        "Sidebar should have Time Budget link"
    );
    assert!(
        html.contains(r##"href="#section-checks""##),
        "Checks should remain the main quality entry point"
    );
}

#[test]
fn test_sidebar_no_blockers_when_all_pass() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks(); // no failures
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);

    assert!(
        !html.contains(r##"href="#section-blockers""##),
        "Sidebar should NOT have Blockers link when no failures"
    );
    assert!(
        html.contains(r##"href="#section-time-budget""##),
        "Sidebar should have Time Budget link"
    );
}

// ---- PRV-104: Delta vs Previous Run ----

#[test]
fn test_delta_section_empty_when_no_previous() {
    let ctx = mock_ctx(); // previous_run = None
    let checks = mock_checks();
    let html = build_delta_section(&ctx, &checks);
    assert!(
        html.is_empty(),
        "Delta section should be empty when no previous run"
    );
}

#[test]
fn test_delta_section_shows_improvement() {
    use super::super::PreviousRunDelta;
    let mut ctx = mock_ctx();
    ctx.previous_run = Some(PreviousRunDelta {
        checks_passed_before: 1,
        checks_failed_before: 2,
        findings_before: 3,
        breaking_before: 0,
        quality_pass_before: false,
    });
    let checks = mock_checks(); // 1 passed, 0 failed
    let html = build_delta_section(&ctx, &checks);

    assert!(html.contains("vs Previous Run"), "Should show delta header");
    assert!(
        html.contains("delta-better"),
        "Should show improvement badge"
    );
    assert!(html.contains("Passed"), "Should show Passed delta");
    assert!(html.contains("Quality"), "Should show Quality delta");
}

#[test]
fn test_delta_section_shows_regression() {
    use super::super::PreviousRunDelta;
    let mut ctx = mock_ctx();
    ctx.quality_pass = false;
    ctx.previous_run = Some(PreviousRunDelta {
        checks_passed_before: 5,
        checks_failed_before: 0,
        findings_before: 0,
        breaking_before: 0,
        quality_pass_before: true,
    });
    let checks = vec![CheckResult {
        name: "cargo check".into(),
        status: CheckStatus::Failed,
        duration: Duration::from_secs(2),
        output: "error".into(),
        cached: false,
        provenance: None,
    }];
    let html = build_delta_section(&ctx, &checks);

    assert!(html.contains("delta-worse"), "Should show regression badge");
}

#[test]
fn test_delta_nav_conditional() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx(); // no previous_run
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);
    assert!(
        !html.contains(r##"href="#section-delta""##),
        "Nav should NOT have Delta link when no previous run"
    );
}

// ---- PRV-105: View Mode Toggle ----

#[test]
fn test_view_mode_toggle_present() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);
    assert!(
        html.contains("view-mode-review"),
        "Should have review view toggle button"
    );
    assert!(
        html.contains("view-mode-author"),
        "Should have author view toggle button"
    );
    assert!(
        html.contains("Review View"),
        "Toggle should expose review mode label"
    );
    assert!(
        html.contains("Author View"),
        "Toggle should expose author mode label"
    );
}

#[test]
fn test_language_toggle_present() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);
    assert!(
        html.contains("lang-toggle-en"),
        "Should have English language toggle"
    );
    assert!(
        html.contains("lang-toggle-pl"),
        "Should have Polish language toggle"
    );
    assert!(
        html.contains("data-i18n=\"button.copyPrComment\""),
        "Copy button should participate in i18n"
    );
    assert!(
        html.contains("dashboardLang"),
        "Dashboard should persist selected language"
    );
}

#[test]
fn test_author_mode_css_classes_on_sections() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);
    assert!(
        html.contains("section-system"),
        "Should have section-system class"
    );
    assert!(
        html.contains("section-noise"),
        "Should have section-noise class"
    );
    assert!(
        html.contains("body.author-mode .section-system { display: none; }"),
        "CSS should hide system sections"
    );
    assert!(
        html.contains("body.author-mode .section-noise"),
        "CSS should hide noise sections"
    );
}

#[test]
fn test_collapsible_sections_keep_single_visible_title_row() {
    let config = mock_config();
    let diffs = vec![mock_diff()];
    let checks = mock_checks();
    let ctx = mock_ctx();
    let dir = std::env::temp_dir();

    let html = build_html_test!(&config, &diffs, &checks, None, &ctx, "", &dir, "", None);

    assert!(
        html.contains(".section-collapsible > .section-header"),
        "Collapsible styles should target only the outer header"
    );
    assert!(
        html.contains(
            ".section-collapsible .section-body > .section > .section-header .section-title"
        ),
        "Nested section titles should be compacted inside collapsibles"
    );
    assert!(
        html.contains("overflow-wrap: anywhere"),
        "Section summaries should wrap instead of pushing layout wide"
    );
}

// ---- PRV-202: Security Lens ----

#[test]
fn test_security_section_no_security_checks() {
    let checks = mock_checks(); // cargo check, cargo clippy — not security
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);
    assert!(
        html.is_empty(),
        "No security checks should produce empty string"
    );
}

#[test]
fn test_security_section_audit_pass() {
    let checks = vec![CheckResult {
        name: "Cargo audit".into(),
        status: CheckStatus::Passed,
        duration: Duration::from_secs(1),
        output: r#"{"vulnerabilities":{"count":0,"list":[]}}"#.into(),
        cached: false,
        provenance: None,
    }];
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);

    assert!(html.contains("section-security"), "Should have section id");
    assert!(html.contains("Security"), "Should have Security title");
    assert!(html.contains("PASS"), "Overall should be PASS");
    assert!(html.contains("badge-success"), "Should have success badge");
    assert!(
        html.contains("0 vulnerabilities"),
        "Should show 0 vulnerabilities metric"
    );
    assert!(html.contains("Cargo audit"), "Should show check name");
}

#[test]
fn test_security_section_audit_fail() {
    let checks = vec![CheckResult {
        name: "Cargo audit".into(),
        status: CheckStatus::Failed,
        duration: Duration::from_secs(1),
        output: r#"{"vulnerabilities":{"count":3,"list":[{},{},{}]}}"#.into(),
        cached: false,
        provenance: None,
    }];
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);

    assert!(html.contains("FAIL"), "Overall should be FAIL");
    assert!(html.contains("badge-error"), "Should have error badge");
    assert!(
        html.contains("3 vulnerabilities"),
        "Should show 3 vulnerabilities"
    );
    assert!(html.contains("sec-fail"), "Card should have sec-fail class");
}

#[test]
fn test_security_section_mixed() {
    let checks = vec![
        CheckResult {
            name: "Cargo audit".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(1),
            output: r#"{"vulnerabilities":{"count":0,"list":[]}}"#.into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "Cargo geiger".into(),
            status: CheckStatus::Warnings,
            duration: Duration::from_secs(5),
            output: "3/15 unsafe expressions in 2 crates".into(),
            cached: false,
            provenance: None,
        },
    ];
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);

    assert!(
        html.contains("WARN"),
        "Overall should be WARN (worst of pass+warn)"
    );
    assert!(html.contains("Cargo audit"), "Should show audit");
    assert!(html.contains("Cargo geiger"), "Should show geiger");
    assert!(html.contains("0 vulnerabilities"), "Audit metric");
    assert!(
        html.contains("unsafe"),
        "Geiger metric should mention unsafe"
    );
    assert!(html.contains("sec-pass"), "Audit card should be pass");
    assert!(html.contains("sec-warn"), "Geiger card should be warn");
}

#[test]
fn test_security_section_skipped_excluded_from_fold() {
    let checks = vec![
        CheckResult {
            name: "Cargo audit".into(),
            status: CheckStatus::Passed,
            duration: Duration::from_secs(1),
            output: r#"{"vulnerabilities":{"count":0,"list":[]}}"#.into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "Cargo geiger".into(),
            status: CheckStatus::Skipped,
            duration: Duration::from_secs(0),
            output: "skipped: not enabled".into(),
            cached: false,
            provenance: None,
        },
    ];
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);

    // Overall should be PASS (skipped excluded from fold), not SKIP
    assert!(
        html.contains("PASS"),
        "Overall should be PASS when only non-skipped check passed"
    );
    assert!(
        html.contains("1 skipped"),
        "Should show skipped count badge"
    );
    assert!(
        html.contains("badge-muted"),
        "Skipped badge should use muted style"
    );
}

#[test]
fn test_security_section_all_skipped() {
    let checks = vec![
        CheckResult {
            name: "Cargo audit".into(),
            status: CheckStatus::Skipped,
            duration: Duration::from_secs(0),
            output: "skipped".into(),
            cached: false,
            provenance: None,
        },
        CheckResult {
            name: "Cargo geiger".into(),
            status: CheckStatus::Skipped,
            duration: Duration::from_secs(0),
            output: "skipped".into(),
            cached: false,
            provenance: None,
        },
    ];
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);

    assert!(
        html.contains("SKIP"),
        "Overall should be SKIP when all checks are skipped"
    );
    assert!(html.contains("2 skipped"), "Should show 2 skipped");
}

#[test]
fn test_security_section_localizes_fallback_metric() {
    let checks = vec![CheckResult {
        name: "Security scan".into(),
        status: CheckStatus::Warnings,
        duration: Duration::from_secs(1),
        output: "details unavailable".into(),
        cached: false,
        provenance: None,
    }];
    let ctx = mock_ctx();
    let html = build_security_section(&checks, &ctx);

    assert!(
        html.contains(r#"data-i18n-template="message.seeLogForDetails""#),
        "Fallback helper copy should be localizable"
    );
}

#[test]
fn test_is_security_check() {
    assert!(is_security_check("Cargo audit"));
    assert!(is_security_check("Cargo geiger"));
    assert!(is_security_check("semgrep scan"));
    assert!(is_security_check("snyk test"));
    assert!(is_security_check("Security scan"));
    assert!(!is_security_check("Cargo check"));
    assert!(!is_security_check("Clippy"));
    assert!(!is_security_check("Cargo test"));
}

#[test]
fn test_extract_security_metric_audit_json() {
    let output = r#"{"vulnerabilities":{"count":2,"list":[{},{}]}}"#;
    let metric = extract_security_metric("Cargo audit", output);
    assert_eq!(metric, "2 vulnerabilities");
}

#[test]
fn test_extract_security_metric_audit_zero() {
    let output = r#"{"vulnerabilities":{"count":0,"list":[]}}"#;
    let metric = extract_security_metric("Cargo audit", output);
    assert_eq!(metric, "0 vulnerabilities");
}

#[test]
fn test_extract_security_metric_geiger() {
    let output = "3/15 unsafe expressions in 2 crates";
    let metric = extract_security_metric("Cargo geiger", output);
    assert!(metric.contains("unsafe"), "Should extract unsafe ratio");
}

// ---- PRV-206: Confidence Badges ----

#[test]
fn test_confidence_badge_high() {
    assert_eq!(heuristic_confidence("dead_exports", 3), "high");
    assert_eq!(heuristic_confidence("cycles", 5), "high");
}

#[test]
fn test_confidence_badge_medium_from_count() {
    assert_eq!(heuristic_confidence("dead_exports", 15), "medium");
    assert_eq!(heuristic_confidence("cycles", 20), "medium");
}

#[test]
fn test_confidence_badge_medium_twins() {
    assert_eq!(heuristic_confidence("twins", 3), "medium");
    assert_eq!(heuristic_confidence("dead_parrots", 5), "medium");
    assert_eq!(heuristic_confidence("unused_symbols", 5), "medium");
}

#[test]
fn test_confidence_badge_low() {
    assert_eq!(heuristic_confidence("twins", 15), "low");
    assert_eq!(heuristic_confidence("dead_parrots", 20), "low");
    assert_eq!(heuristic_confidence("unused_symbols", 20), "low");
    assert_eq!(heuristic_confidence("unknown", 1), "low");
}

#[test]
fn narrative_section_renders_markdown_through_mdrender() {
    let md = "## Findings\n\n> [!NOTE]\n> Look here.\n\n```rust\nfn a() {}\n```\n";
    let html = build_narrative_section(md);

    // Rendered through mdrender (scoped wrapper + GFM callout + code highlight).
    assert!(html.contains("<div class=\"mdr\">"), "mdr wrapper missing");
    assert!(
        html.contains("markdown-alert markdown-alert-note"),
        "note callout missing: {html}"
    );
    assert!(
        html.contains("<span style=\"color:#"),
        "syntect highlight spans missing"
    );
    // Raw markdown is still preserved for the copy-as-markdown control.
    assert!(html.contains("narrative-content"));
}

#[test]
fn test_pl_locale_merge_gate_caveat_translations() {
    // The MERGE_GATE runtime caveats are formulaic. They are emitted into the
    // dashboard as EN source strings (in data-review-signals) and localized
    // client-side by the JS locale toggle. This test locks both halves: the EN
    // source lands in the markup, and the PL transforms are wired in js().
    let mut ctx = mock_ctx();
    ctx.review_caveats = vec![
        "Semgrep scan returned warnings".to_string(),
        "cargo-geiger skipped: security disabled".to_string(),
        "heuristics_loctree needs manual review".to_string(),
        "2 inline findings".to_string(),
    ];
    let html = build_merge_decision_card(&ctx);

    // EN source is preserved verbatim in the translation attribute so the
    // client toggle can localize (or, for unknown shapes, leave EN as-is).
    assert!(html.contains(
        r#"data-review-signals="Semgrep scan returned warnings · cargo-geiger skipped: security disabled · heuristics_loctree needs manual review · 2 inline findings""#
    ));

    // PL transforms are wired in the locale toggle (JS runs client-side, so we
    // assert on the emitted script). Known shapes localize the wrapper while
    // keeping tool names original.
    let js = js();
    assert!(
        js.contains("returned warnings$"),
        "returned-warnings shape missing"
    );
    assert!(
        js.contains("': ostrzeżenia'"),
        "returned-warnings PL missing"
    );
    assert!(js.contains("skipped: "), "skipped shape missing");
    assert!(js.contains("' pominięty: '"), "skipped PL wrapper missing");
    assert!(
        js.contains("'lint disabled': 'lint wyłączony'"),
        "lint reason map missing"
    );
    assert!(
        js.contains("'tests disabled': 'testy wyłączone'"),
        "tests reason map missing"
    );
    assert!(
        js.contains("'security disabled': 'security wyłączone'"),
        "security reason map missing"
    );
    assert!(
        js.contains("needs manual review$"),
        "manual-review shape missing"
    );
    assert!(
        js.contains("' wymaga ręcznego przeglądu'"),
        "manual-review PL missing"
    );
    assert!(
        js.contains("blocking issue(?:s)? found: "),
        "blocking-with-detail shape missing"
    );
    assert!(
        js.contains("'znaleziono '"),
        "blocking-with-detail PL missing"
    );

    // Fallback discipline: unrecognized shapes return the original EN string
    // (never a guessed translation) in both caveat and reason transforms.
    assert!(
        js.contains("return trimmed;"),
        "review-signal EN fallback missing"
    );
    assert!(
        js.contains("return text;"),
        "decision-reason EN fallback missing"
    );
}