quorum-cli 0.4.0

Quorum CLI: the quorum binary.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
//! Bundle assembly: assemble a synthesized StagedDiff and assert deny-list
//! exclusion, per-section budgets, truncation markers, and 200KB cap.

use quorum_core::bundle::{
    assemble, BundleError, BundleInputs, FileExclusionReason, BEGIN, BUDGET_DIFF, BUDGET_MEMORY,
    BUDGET_TOTAL, END,
};
use quorum_core::conventions::ConventionsState;
use quorum_core::discovery::Discovery;
use quorum_core::git::{FileStatus, StagedDiff, StagedFile};
use quorum_core::memory::{
    Dismissal, DismissalId, DismissalReason, FindingIdentityHash, PromotionState,
};

fn empty_discovery() -> Discovery {
    Discovery {
        chosen: None,
        ignored: vec![],
        chosen_path: None,
    }
}

fn file(path: &str, body: &[u8], binary: bool) -> StagedFile {
    StagedFile {
        path: path.into(),
        status: FileStatus::Modified,
        index_blob: if binary { None } else { Some(body.to_vec()) },
        is_binary: binary,
        size_bytes: body.len() as u64,
        hunk_count: 1,
    }
}

/// Same as [`file`] but with an explicit hunk count (AC 176 scoring).
fn file_hunks(path: &str, body: &[u8], hunk_count: u32) -> StagedFile {
    StagedFile {
        hunk_count,
        ..file(path, body, false)
    }
}

#[test]
fn quorum_state_dir_excluded_from_bundle() {
    // .quorum/ holds Quorum's own state — config, sqlite db, archives.
    // Even if `git add .` sweeps these into the index, they must not
    // appear in the Lippa-bound bundle.
    let files = vec![
        file(".quorum/config.toml", b"project_id=\"p_x\"\n", false),
        file(
            ".quorum/dismissals.sqlite",
            b"SQLite format 3\0fake-db-bytes\n",
            false,
        ),
        file(
            ".quorum/reviews/2026-05-15T10-00-00Z.json",
            b"{\"sid\":\"abc\"}\n",
            false,
        ),
        file("src/lib.rs", b"pub fn ok() {}\n", false),
    ];
    let staged = StagedDiff {
        unified: String::new(),
        files,
        is_empty: false,
    };
    let conv = ConventionsState::Absent;
    let disc = empty_discovery();
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: None,
        conventions: &conv,
        discovery: &disc,
        branch: "main",
        head_sha: "abc",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    })
    .expect("assemble");
    let excluded: Vec<&String> = res
        .exclusions
        .iter()
        .filter_map(|(p, r)| match r {
            FileExclusionReason::DenyList(_) => Some(p),
            _ => None,
        })
        .collect();
    assert!(
        excluded.iter().any(|p| p.as_str() == ".quorum/config.toml"),
        "config.toml must be excluded; got {excluded:?}"
    );
    assert!(excluded
        .iter()
        .any(|p| p.as_str() == ".quorum/dismissals.sqlite"));
    assert!(excluded
        .iter()
        .any(|p| p.as_str() == ".quorum/reviews/2026-05-15T10-00-00Z.json"));
    // Body content of state files must not leak into the bundle.
    assert!(!res.prompt.contains("SQLite format 3"));
    assert!(!res.prompt.contains("project_id=\"p_x\""));
    // The non-state file is still bundled.
    assert!(res.prompt.contains("src/lib.rs"));
}

#[test]
fn deny_listed_files_excluded_with_marker() {
    let files = vec![
        file(".env", b"SECRET=hunter2\n", false),
        file("src/main.rs", b"fn main() {}\n", false),
        file("infra/staging/.env", b"NESTED=true\n", false),
        file(".aws/credentials", b"[default]\n", false),
        file("services/api/secrets.yml", b"k: v\n", false),
    ];
    let staged = StagedDiff {
        unified: String::new(),
        files,
        is_empty: false,
    };
    let conv = ConventionsState::Absent;
    let disc = empty_discovery();
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: None,
        conventions: &conv,
        discovery: &disc,
        branch: "main",
        head_sha: "abc",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    })
    .expect("assemble");
    let excluded: Vec<&String> = res
        .exclusions
        .iter()
        .filter_map(|(p, r)| match r {
            FileExclusionReason::DenyList(_) => Some(p),
            _ => None,
        })
        .collect();
    assert!(excluded.iter().any(|p| p.as_str() == ".env"));
    assert!(excluded.iter().any(|p| p.as_str() == "infra/staging/.env"));
    assert!(excluded.iter().any(|p| p.as_str() == ".aws/credentials"));
    assert!(excluded
        .iter()
        .any(|p| p.as_str() == "services/api/secrets.yml"));
    // src/main.rs included.
    assert!(res.prompt.contains("src/main.rs"));
    // Secret values absent.
    assert!(!res.prompt.contains("SECRET=hunter2"));
    assert!(!res.prompt.contains("NESTED=true"));
}

#[test]
fn binary_files_excluded() {
    let files = vec![file("logo.png", &[0u8; 10], true)];
    let staged = StagedDiff {
        unified: String::new(),
        files,
        is_empty: false,
    };
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: None,
        conventions: &ConventionsState::Absent,
        discovery: &empty_discovery(),
        branch: "m",
        head_sha: "a",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    })
    .unwrap();
    assert!(res
        .exclusions
        .iter()
        .any(|(p, r)| p == "logo.png" && matches!(r, FileExclusionReason::Binary)));
}

#[test]
fn oversized_diff_triggers_truncation_marker() {
    let huge = "x".repeat(BUDGET_DIFF + 5_000);
    let staged = StagedDiff {
        unified: huge,
        files: vec![],
        is_empty: false,
    };
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: None,
        conventions: &ConventionsState::Absent,
        discovery: &empty_discovery(),
        branch: "m",
        head_sha: "a",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    })
    .unwrap();
    assert!(res.diff_truncated);
    assert!(res.prompt.contains("[diff truncated"));
}

#[test]
fn bundle_over_total_cap_errors() {
    // Build a diff that fits the 100KB diff cap but stack files to overflow
    // the 200KB total. Files are budgeted at 80KB so this requires forcing
    // multiple oversize files past per-section. Simpler: stuff the diff and
    // verify the cap kicks in for diff overflow alone (already covered by
    // truncation), so synth a separate path: huge memory + huge conventions.
    let huge_mem = "m".repeat(50_000);
    let huge_conv = "c".repeat(50_000);
    let staged = StagedDiff {
        unified: "x".repeat(BUDGET_DIFF),
        files: vec![file("a.rs", &vec![b'a'; 70_000], false)],
        is_empty: false,
    };
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: Some(quorum_core::bundle::MemoryInput {
            source_basename: "CLAUDE.md".into(),
            content: huge_mem,
        }),
        conventions: &ConventionsState::Trusted(huge_conv),
        discovery: &empty_discovery(),
        branch: "m",
        head_sha: "a",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    });
    // Per-section budgets may keep total under cap; verify either succeeds
    // (with each section truncated) or returns BundleTooLarge.
    match res {
        Ok(r) => assert!(r.bytes_used <= BUDGET_TOTAL, "stays under cap"),
        Err(BundleError::BundleTooLarge(n, _)) => assert!(n > BUDGET_TOTAL, "reports excess"),
    }
}

// =====================================================================
// Phase 1C Stage 2 — §6.1 memory subsection + §6.2 bridge.
// =====================================================================

fn empty_staged() -> StagedDiff {
    StagedDiff {
        unified: String::new(),
        files: vec![],
        is_empty: true,
    }
}

/// Build a `Dismissal` fixture suitable for the bundle's local-conv path.
/// `seed` controls the hash (every byte = seed) so the short-hash render
/// is predictable. `at_ymd` controls the dismissed_at date for the
/// `since=` HTML comment.
fn dismissal_fixture(
    seed: u8,
    title: &str,
    body: Option<&str>,
    recurrence: u32,
    state: PromotionState,
    at_ymd: (i32, u8, u8),
    last_seen_ymd: (i32, u8, u8),
) -> Dismissal {
    let h = FindingIdentityHash([seed; 32]);
    let mk = |(y, m, d): (i32, u8, u8)| {
        let date = time::Date::from_calendar_date(y, time::Month::try_from(m).unwrap(), d).unwrap();
        time::PrimitiveDateTime::new(date, time::Time::MIDNIGHT).assume_utc()
    };
    Dismissal {
        id: DismissalId(seed as i64),
        finding_identity_hash: h,
        title_snapshot: title.into(),
        body_snapshot: body.map(|s| s.to_string()),
        source_type_snapshot: "agreement".into(),
        models_snapshot: vec!["m1".into()],
        branch_snapshot: "main".into(),
        reason: DismissalReason::FalsePositive,
        note: None,
        dismissed_at: mk(at_ymd),
        last_seen_at: mk(last_seen_ymd),
        last_seen_session_id: None,
        recurrence_count: recurrence,
        expires_at: None,
        repo_head_sha_first: "sha".into(),
        promotion_state: state,
    }
}

/// Build BundleInputs around just the memory subsection. Diff/files are
/// empty so we can read the rendered memory section in isolation.
fn assemble_memory_only<'a>(
    local: &'a [Dismissal],
    cap: usize,
    conventions: &'a ConventionsState,
    memory: Option<quorum_core::bundle::MemoryInput>,
) -> String {
    let staged = empty_staged();
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory,
        conventions,
        discovery: &empty_discovery(),
        branch: "m",
        head_sha: "a",
        remote_url: None,
        local_conventions: local,
        local_convention_bundle_cap: cap,
        context: Default::default(),
    })
    .expect("assemble");
    res.prompt
}

#[test]
fn ac152_local_only_entries_render_under_header_in_sorted_order() {
    // Two `local_only` rows. Input is already pre-sorted by the storage
    // query (recurrence DESC, then last_seen DESC); the bundle layer
    // preserves order without re-sorting.
    let high = dismissal_fixture(
        0xAA,
        "use ? operator instead of unwrap",
        Some("Prefer `?` over `.unwrap()` in production paths."),
        7,
        PromotionState::LocalOnly,
        (2026, 1, 15),
        (2026, 5, 10),
    );
    let low = dismissal_fixture(
        0xBB,
        "snake_case for module names",
        Some("Rust module names should be snake_case."),
        3,
        PromotionState::LocalOnly,
        (2026, 2, 1),
        (2026, 5, 9),
    );
    let prompt = assemble_memory_only(&[high, low], 500, &ConventionsState::Absent, None);
    // Header present.
    assert!(prompt.contains("## Local conventions (auto-derived)"));
    // Both entries present.
    assert!(prompt.contains("Local convention: use ? operator instead of unwrap"));
    assert!(prompt.contains("Local convention: snake_case for module names"));
    // First (recurrence=7) precedes second (recurrence=3) in the rendered
    // output — storage-layer sort preserved.
    let pos_high = prompt.find("recurrence=7").unwrap();
    let pos_low = prompt.find("recurrence=3").unwrap();
    assert!(pos_high < pos_low, "high-recurrence row must precede low");
}

#[test]
fn ac153_per_entry_format_matches_spec() {
    let d = dismissal_fixture(
        0xAB,
        "title body",
        Some("body content"),
        4,
        PromotionState::LocalOnly,
        (2026, 1, 7),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(&[d], 500, &ConventionsState::Absent, None);
    // Title header (codepoint-truncated to 80 chars — short title here).
    assert!(prompt.contains("### Local convention: title body\n"));
    // Body content present.
    assert!(prompt.contains("body content"));
    // Trailing HTML comment with recurrence + since (ISO) + 12-char hash.
    // Hash bytes are all 0xAB → hex "ab" repeated, first 12 = "ababababab" + "ab" = "ababababab" + "ab"…
    // The full hex starts with "abababab..." so the short prefix is "ababababab" + "ab" = "ababababab" + "ab"
    assert!(
        prompt.contains("<!-- recurrence=4, since=2026-01-07, hash=ababababab"),
        "metadata line missing or wrong shape; prompt was:\n{prompt}"
    );
}

#[test]
fn ac154_per_entry_truncation_marker_when_body_overflows_cap() {
    // body > cap → keeps prefix at codepoint boundary, appends the
    // [local convention truncated: …] marker before the closing comment.
    let body = "x".repeat(600);
    let d = dismissal_fixture(
        0xC1,
        "long body convention",
        Some(&body),
        5,
        PromotionState::LocalOnly,
        (2026, 3, 3),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(&[d], 100, &ConventionsState::Absent, None);
    assert!(
        prompt.contains("[local convention truncated: "),
        "per-entry truncation marker missing"
    );
    // 600 - 100 = 500 bytes elided.
    assert!(prompt.contains("500 bytes elided"));
    assert!(prompt.contains("raise [memory] local_convention_bundle_cap to see full text"));
    // Hash-short (first 12 hex chars of bytes 0xC1×32 = "c1" × 6).
    assert!(prompt.contains("[local convention truncated: c1c1c1c1c1c1"));
}

#[test]
fn ac154_total_section_truncation_marker_when_entries_exceed_budget() {
    // Build many large entries so the cumulative subsection size exceeds
    // BUDGET_MEMORY (20KB) and forces drop-at-entry-boundary plus the
    // SERVICES.md §2 marker.
    let big_body = "z".repeat(2000);
    let mut rows = Vec::new();
    for i in 0u8..15 {
        rows.push(dismissal_fixture(
            i,
            &format!("convention number {i}"),
            Some(&big_body),
            (15 - i) as u32, // descending recurrence so first is top
            PromotionState::LocalOnly,
            (2026, 1, 1),
            (2026, 5, 10),
        ));
    }
    let prompt = assemble_memory_only(&rows, 2048, &ConventionsState::Absent, None);
    assert!(
        prompt.contains("[memory truncated:"),
        "total-section truncation marker missing"
    );
    assert!(prompt.contains("bytes exceeded 20KB; review only top portion"));
}

#[test]
fn ac155_bridge_dirty_renders_promoted_in_memory_section() {
    // promoted_convention + conventions.md NOT trusted → renders in
    // memory section as if it were local_only.
    let d = dismissal_fixture(
        0xD0,
        "promoted but dirty",
        Some("rule body"),
        4,
        PromotionState::PromotedConvention,
        (2026, 1, 10),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(&[d], 500, &ConventionsState::PresentButIgnored, None);
    assert!(prompt.contains("## Local conventions (auto-derived)"));
    assert!(prompt.contains("Local convention: promoted but dirty"));
}

#[test]
fn ac155_bridge_trusted_suppresses_promoted_in_memory_section() {
    // promoted_convention + conventions.md committed-and-clean (Trusted)
    // → memory-section render suppressed; conventions section carries
    // the rule via the file contents (Phase 1A path, not asserted here).
    let d = dismissal_fixture(
        0xD1,
        "promoted and clean",
        Some("rule body"),
        4,
        PromotionState::PromotedConvention,
        (2026, 1, 10),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(
        &[d],
        500,
        &ConventionsState::Trusted("# committed conventions\n".into()),
        None,
    );
    assert!(!prompt.contains("Local convention: promoted and clean"));
    assert!(!prompt.contains("## Local conventions (auto-derived)"));
}

#[test]
fn ac155_mixed_local_and_bridged_render_under_one_header() {
    let local = dismissal_fixture(
        0xE0,
        "a real local rule",
        Some("text"),
        5,
        PromotionState::LocalOnly,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    let bridged = dismissal_fixture(
        0xE1,
        "bridged from promoted",
        Some("text"),
        3,
        PromotionState::PromotedConvention,
        (2026, 1, 1),
        (2026, 5, 9),
    );
    let prompt = assemble_memory_only(
        &[local, bridged],
        500,
        &ConventionsState::PresentButIgnored, // dirty triggers bridge
        None,
    );
    // Exactly one header for both rows.
    assert_eq!(
        prompt
            .matches("## Local conventions (auto-derived)")
            .count(),
        1
    );
    assert!(prompt.contains("a real local rule"));
    assert!(prompt.contains("bridged from promoted"));
}

#[test]
fn empty_subsection_omits_header() {
    // No local_only and no bridge-eligible rows → header MUST NOT render
    // (an empty `## Local conventions (auto-derived)` header reads as a
    // bug; spec §6.1 wording is presence-conditional).
    let promoted_clean = dismissal_fixture(
        0x10,
        "lives in conventions.md",
        Some("text"),
        2,
        PromotionState::PromotedConvention,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(
        &[promoted_clean],
        500,
        &ConventionsState::Trusted("committed\n".into()),
        None,
    );
    assert!(!prompt.contains("## Local conventions (auto-derived)"));
}

#[test]
fn ac170_delimiters_wrap_entire_memory_section() {
    let d = dismissal_fixture(
        0xF0,
        "wrapped under delimiters",
        Some("body"),
        2,
        PromotionState::LocalOnly,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(&[d], 500, &ConventionsState::Absent, None);
    let begin_pos = prompt.find(BEGIN).unwrap();
    let end_pos = prompt.find(END).unwrap();
    let subsection_pos = prompt.find("## Local conventions (auto-derived)").unwrap();
    assert!(begin_pos < subsection_pos);
    assert!(subsection_pos < end_pos);
    // No second pair of delimiters around the subsection itself.
    assert_eq!(prompt.matches(BEGIN).count(), 1);
    assert_eq!(prompt.matches(END).count(), 1);
}

#[test]
fn ac173_partial_render_side_toggle() {
    // Render-side toggle correctness (partial AC 173 — full T2/T3
    // round-trip closes at Stage 4). Same SQLite row rendered twice,
    // once with conventions.md dirty, once with it trusted: the first
    // appears in the memory section; the second does not.
    let d = dismissal_fixture(
        0x77,
        "toggle me",
        Some("toggle body"),
        4,
        PromotionState::PromotedConvention,
        (2026, 4, 1),
        (2026, 5, 10),
    );
    let dirty = assemble_memory_only(
        std::slice::from_ref(&d),
        500,
        &ConventionsState::PresentButIgnored,
        None,
    );
    assert!(dirty.contains("toggle me"));

    let clean = assemble_memory_only(
        std::slice::from_ref(&d),
        500,
        &ConventionsState::Trusted("committed\n".into()),
        None,
    );
    assert!(!clean.contains("toggle me"));

    // Toggling back to dirty re-enables the bridge render.
    let dirty_again = assemble_memory_only(
        std::slice::from_ref(&d),
        500,
        &ConventionsState::PresentButIgnored,
        None,
    );
    assert!(dirty_again.contains("toggle me"));
}

#[test]
fn body_without_snapshot_renders_only_header_and_comment() {
    // body_snapshot = None → no body line, just the header and the
    // trailing HTML comment.
    let d = dismissal_fixture(
        0x33,
        "title only",
        None,
        2,
        PromotionState::LocalOnly,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(&[d], 500, &ConventionsState::Absent, None);
    assert!(prompt.contains("### Local convention: title only\n"));
    assert!(prompt.contains("<!-- recurrence=2, since=2026-01-01, hash=3333333333"));
    // No truncation marker (body is None, nothing to truncate).
    assert!(!prompt.contains("[local convention truncated:"));
}

#[test]
fn body_multibyte_utf8_truncation_lands_on_codepoint_boundary() {
    // "é" is two bytes (0xC3 0xA9). Cap=4 must back off to 2 ("ca") not
    // slice through the codepoint. Build a body whose first 4 bytes hit
    // the middle of an é.
    let body = "café".repeat(10); // 50 bytes
    let d = dismissal_fixture(
        0x44,
        "utf8 title",
        Some(&body),
        2,
        PromotionState::LocalOnly,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    // cap=4 forces truncation; the kept prefix is "caf" (3 bytes) — the
    // walk-back from 4 hits the é's leading byte at index 3.
    let prompt = assemble_memory_only(&[d], 4, &ConventionsState::Absent, None);
    assert!(prompt.contains("[local convention truncated:"));
    // No invalid UTF-8 in the output (assemble would have panicked).
    assert!(prompt.is_ascii() || std::str::from_utf8(prompt.as_bytes()).is_ok());
}

#[test]
fn title_truncation_is_codepoint_aware_at_80() {
    // 100-codepoint title with multibyte characters — truncation should
    // keep 80 codepoints, not 80 bytes. Use "é" repeated so byte vs
    // codepoint counts diverge.
    let title: String = "é".repeat(100);
    let d = dismissal_fixture(
        0x55,
        &title,
        None,
        1,
        PromotionState::LocalOnly,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(&[d], 500, &ConventionsState::Absent, None);
    // Expected rendered title: exactly 80 "é" characters.
    let expected_title: String = "é".repeat(80);
    assert!(prompt.contains(&format!("### Local convention: {expected_title}\n")));
    // 81st é should NOT appear in the title line — confirm 81 chars is absent.
    let too_many: String = "é".repeat(81);
    assert!(!prompt.contains(&format!("### Local convention: {too_many}")));
}

#[test]
fn ac156_total_bundle_stays_under_cap_with_local_conventions() {
    // Even with a fully-loaded subsection, BUDGET_TOTAL holds.
    let big = "z".repeat(2048);
    let mut rows = Vec::new();
    for i in 0u8..30 {
        rows.push(dismissal_fixture(
            i,
            &format!("rule {i}"),
            Some(&big),
            (30 - i) as u32,
            PromotionState::LocalOnly,
            (2026, 1, 1),
            (2026, 5, 10),
        ));
    }
    let staged = StagedDiff {
        unified: "x".repeat(BUDGET_DIFF),
        files: vec![file("a.rs", &vec![b'a'; 70_000], false)],
        is_empty: false,
    };
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: Some(quorum_core::bundle::MemoryInput {
            source_basename: "CLAUDE.md".into(),
            content: "c".repeat(10_000),
        }),
        conventions: &ConventionsState::Trusted("c".repeat(5_000)),
        discovery: &empty_discovery(),
        branch: "m",
        head_sha: "a",
        remote_url: None,
        local_conventions: &rows,
        local_convention_bundle_cap: 2048,
        context: Default::default(),
    });
    match res {
        Ok(r) => assert!(r.bytes_used <= BUDGET_TOTAL),
        Err(BundleError::BundleTooLarge(n, _)) => assert!(n > BUDGET_TOTAL),
    }
}

#[test]
fn claude_md_content_precedes_local_conventions_subsection() {
    // §6.1 step ordering: CLAUDE.md (step 1) precedes the auto-derived
    // subsection (step 2).
    let d = dismissal_fixture(
        0x66,
        "ordering check",
        Some("body"),
        2,
        PromotionState::LocalOnly,
        (2026, 1, 1),
        (2026, 5, 10),
    );
    let prompt = assemble_memory_only(
        &[d],
        500,
        &ConventionsState::Absent,
        Some(quorum_core::bundle::MemoryInput {
            source_basename: "CLAUDE.md".into(),
            content: "CLAUDE_MD_MARKER body".into(),
        }),
    );
    let claude_pos = prompt.find("CLAUDE_MD_MARKER").unwrap();
    let subsection_pos = prompt.find("## Local conventions (auto-derived)").unwrap();
    assert!(claude_pos < subsection_pos);
}

// Hush an unused-import warning when only some test fns reference
// BUDGET_MEMORY (kept available for future fixtures).
#[allow(dead_code)]
const _: usize = BUDGET_MEMORY;

// ===== v0.4 Stage 1 — WI-1 priority scoring =====

/// Build a body of `kb` kilobytes as 80-byte lines (79 chars + newline),
/// so the AC 182a line-number gutter arithmetic is exercised realistically.
fn body_kb(kb: usize, fill: char) -> Vec<u8> {
    let line: String = std::iter::repeat(fill).take(79).collect::<String>() + "\n";
    line.repeat(kb * 1024 / 80).into_bytes()
}

/// AC 178 — the exact dogfood shape from the external review. Two large
/// markdown files must not evict the code under review.
#[test]
fn ac178_large_markdown_does_not_evict_code_under_review() {
    let a_md = body_kb(60, 'a');
    let b_md = body_kb(30, 'b');
    let x_ts = body_kb(4, 'x');
    let x_test_ts = body_kb(2, 't');
    let types_ts = body_kb(1, 'y');

    let files = vec![
        file("a.md", &a_md, false),
        file("b.md", &b_md, false),
        file("src/x.ts", &x_ts, false),
        file("src/x.test.ts", &x_test_ts, false),
        file("types.ts", &types_ts, false),
    ];
    let staged = StagedDiff {
        unified: String::new(),
        files,
        is_empty: false,
    };
    let conv = ConventionsState::Absent;
    let disc = empty_discovery();
    let res = assemble(&BundleInputs {
        staged: &staged,
        memory: None,
        conventions: &conv,
        discovery: &disc,
        branch: "main",
        head_sha: "abc",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    })
    .expect("assemble");

    // The three code files are present in full.
    for (path, body) in [
        ("src/x.ts", &x_ts),
        ("src/x.test.ts", &x_test_ts),
        ("types.ts", &types_ts),
    ] {
        assert!(
            !res.files_omitted.contains(&path.to_string()),
            "{path} must not be omitted; omitted = {:?}",
            res.files_omitted
        );
        let last_line = String::from_utf8(body.clone())
            .unwrap()
            .lines()
            .last()
            .unwrap()
            .to_string();
        assert!(
            res.prompt.contains(&last_line),
            "{path} must be included in full (last line missing)"
        );
    }

    // The largest markdown file is evicted, not the code.
    assert!(
        res.files_omitted.contains(&"a.md".to_string()),
        "a.md (60KB docs) must be omitted; omitted = {:?}",
        res.files_omitted
    );
}

// ===================== v0.4 Stage 1 — WI-2 related files =====================

use quorum_core::bundle::{class_rank, FileClass, RelatedContext};
use quorum_core::config::BundleConfig;
use std::collections::HashSet;

/// A working tree on disk plus the set of paths "tracked at HEAD".
struct Tree {
    dir: tempfile::TempDir,
    tracked: HashSet<String>,
}

impl Tree {
    fn new(files: &[(&str, &str)]) -> Tree {
        let dir = tempfile::tempdir().unwrap();
        let mut tracked = HashSet::new();
        for (path, body) in files {
            let abs = dir.path().join(path);
            std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
            std::fs::write(&abs, body).unwrap();
            tracked.insert((*path).to_string());
        }
        Tree { dir, tracked }
    }

    /// Write a file that exists on disk but is NOT tracked at HEAD.
    fn untracked(&self, path: &str, body: &str) {
        let abs = self.dir.path().join(path);
        std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
        std::fs::write(&abs, body).unwrap();
    }

    fn ctx(&self, cfg: BundleConfig) -> RelatedContext<'_> {
        RelatedContext {
            repo_root: Some(self.dir.path()),
            tracked: Some(&self.tracked),
            cfg,
        }
    }
}

fn assemble_with(
    files: Vec<StagedFile>,
    ctx: RelatedContext<'_>,
) -> quorum_core::bundle::BundleResult {
    let staged = StagedDiff {
        unified: String::new(),
        files,
        is_empty: false,
    };
    let conv = ConventionsState::Absent;
    let disc = empty_discovery();
    assemble(&BundleInputs {
        staged: &staged,
        memory: None,
        conventions: &conv,
        discovery: &disc,
        branch: "main",
        head_sha: "abc",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: ctx,
    })
    .expect("assemble")
}

fn included_paths(res: &quorum_core::bundle::BundleResult) -> Vec<String> {
    res.inclusion_order
        .iter()
        .filter(|r| r.included)
        .map(|r| r.path.clone())
        .collect()
}

/// AC 183 — config-allowlist files are read from the working tree, and
/// are labelled `(unchanged, context)` so a model cannot mistake them for
/// part of the diff.
#[test]
fn ac183_config_allowlist_pulled_in_and_labelled() {
    let tree = Tree::new(&[
        ("package.json", "{\"name\":\"demo\"}\n"),
        ("tsconfig.json", "{\"compilerOptions\":{}}\n"),
        ("src/app.ts", "export const a = 1;\n"),
    ]);
    let res = assemble_with(
        vec![file("src/app.ts", b"export const a = 2;\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    let inc = included_paths(&res);
    assert!(inc.contains(&"package.json".to_string()), "got {inc:?}");
    assert!(inc.contains(&"tsconfig.json".to_string()), "got {inc:?}");
    assert!(res.prompt.contains("### package.json (unchanged, context)"));
    assert!(res
        .prompt
        .contains("### tsconfig.json (unchanged, context)"));
    // The changed file carries no such label.
    assert!(res.prompt.contains("### src/app.ts\n"));
    // Working-tree bytes, not the staged blob.
    assert!(res.prompt.contains("\"name\":\"demo\""));
}

/// AC 183 — a Rust change pulls Cargo.toml, not the JS/TS config set.
#[test]
fn ac183_allowlist_is_keyed_on_the_changed_language() {
    let tree = Tree::new(&[
        ("Cargo.toml", "[package]\nname = \"x\"\n"),
        ("package.json", "{}\n"),
        ("src/lib.rs", "pub fn a() {}\n"),
    ]);
    let res = assemble_with(
        vec![file("src/lib.rs", b"pub fn a() {}\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    let inc = included_paths(&res);
    assert!(inc.contains(&"Cargo.toml".to_string()), "got {inc:?}");
    assert!(
        !inc.contains(&"package.json".to_string()),
        "a Rust change must not drag in the JS config set; got {inc:?}"
    );
}

/// AC 184 — one hop only. `a.ts` imports `b.ts`, which imports `c.ts`.
/// `b.ts` is context; `c.ts` must never appear.
#[test]
fn ac184_resolution_is_one_hop_only() {
    let tree = Tree::new(&[
        ("src/a.ts", "import { b } from './b';\n"),
        (
            "src/b.ts",
            "import { c } from './c';\nexport const b = 1;\n",
        ),
        ("src/c.ts", "export const c = 2;\n"),
    ]);
    let res = assemble_with(
        vec![file("src/a.ts", b"import { b } from './b';\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    let inc = included_paths(&res);
    assert!(inc.contains(&"src/b.ts".to_string()), "got {inc:?}");
    assert!(
        !inc.contains(&"src/c.ts".to_string()),
        "neighbours of neighbours must never be added; got {inc:?}"
    );
}

/// AC 184 — the same guarantee for Rust `mod` / `crate::` references.
#[test]
fn ac184_one_hop_for_rust_module_references() {
    let tree = Tree::new(&[
        ("src/main.rs", "mod helper;\nuse crate::deep::thing;\n"),
        ("src/helper.rs", "mod nested;\npub fn h() {}\n"),
        ("src/helper/nested.rs", "pub fn n() {}\n"),
        ("src/deep.rs", "pub struct thing;\n"),
    ]);
    let res = assemble_with(
        vec![file(
            "src/main.rs",
            b"mod helper;\nuse crate::deep::thing;\n",
            false,
        )],
        tree.ctx(BundleConfig::default()),
    );
    let inc = included_paths(&res);
    assert!(inc.contains(&"src/helper.rs".to_string()), "got {inc:?}");
    assert!(inc.contains(&"src/deep.rs".to_string()), "got {inc:?}");
    assert!(
        !inc.contains(&"src/helper/nested.rs".to_string()),
        "second hop must not be followed; got {inc:?}"
    );
}

/// AC 185 — related files never displace a changed file. The budget is
/// set so that only some candidates fit; every changed file must survive.
#[test]
fn ac185_related_files_never_displace_changed_files() {
    let big = "x".repeat(40 * 1024);
    let tree = Tree::new(&[
        ("src/a.ts", "import './ctx1';\nimport './ctx2';\n"),
        ("src/ctx1.ts", &big),
        ("src/ctx2.ts", &big),
    ]);
    let cfg = BundleConfig {
        total_budget_kb: 100,
        ..BundleConfig::default()
    };
    let changed_body = b"import './ctx1';\nimport './ctx2';\n";
    let res = assemble_with(vec![file("src/a.ts", changed_body, false)], tree.ctx(cfg));
    assert!(
        !res.files_omitted.contains(&"src/a.ts".to_string()),
        "the changed file must never be evicted by context; omitted = {:?}",
        res.files_omitted
    );
    // The changed file is first in the ordering, ahead of both context files.
    assert_eq!(res.inclusion_order[0].path, "src/a.ts");
}

/// AC 186 — at most `related_file_max` related files; the overflow is
/// reported in the inclusion-order block.
#[test]
fn ac186_related_file_cap_binds_and_is_reported() {
    let mut files: Vec<(&str, &str)> = vec![("src/a.ts", "")];
    let owned: Vec<(String, String)> = (0..10)
        .map(|i| {
            (
                format!("src/m{i}.ts"),
                format!("export const m{i} = {i};\n"),
            )
        })
        .collect();
    for (p, b) in &owned {
        files.push((p.as_str(), b.as_str()));
    }
    let tree = Tree::new(&files);

    let body: String = (0..10).map(|i| format!("import './m{i}';\n")).collect();
    let cfg = BundleConfig {
        related_file_max: 3,
        ..BundleConfig::default()
    };
    let res = assemble_with(
        vec![file("src/a.ts", body.as_bytes(), false)],
        tree.ctx(cfg),
    );
    let related: Vec<_> = res
        .inclusion_order
        .iter()
        .filter(|r| r.path != "src/a.ts")
        .collect();
    assert_eq!(related.len(), 3, "cap must bind at 3");
    assert_eq!(res.related_capped_out, 7);
    assert!(
        res.prompt
            .contains("[related-file cap reached: related_file_max=3;"),
        "the cap must be visible in the inclusion-order block"
    );
}

/// AC 186 — `related_file_max = 0` admits no related files at all.
#[test]
fn ac186_related_file_max_zero_admits_nothing() {
    let tree = Tree::new(&[
        ("Cargo.toml", "[package]\n"),
        ("src/lib.rs", "pub fn a() {}\n"),
    ]);
    let cfg = BundleConfig {
        related_file_max: 0,
        ..BundleConfig::default()
    };
    let res = assemble_with(
        vec![file("src/lib.rs", b"pub fn a() {}\n", false)],
        tree.ctx(cfg),
    );
    assert_eq!(included_paths(&res), vec!["src/lib.rs".to_string()]);
}

/// AC 187 — deny-list rules apply identically to related files.
#[test]
fn ac187_denylist_applies_to_related_files() {
    let tree = Tree::new(&[
        ("src/a.ts", "import './secret.env';\n"),
        (".env", "API_KEY=sk-live-should-never-ship\n"),
        ("src/keys.ts", "export const k = 1;\n"),
    ]);
    let cfg = BundleConfig {
        include: vec![".env".into(), "src/*.ts".into()],
        ..BundleConfig::default()
    };
    let res = assemble_with(
        vec![file("src/a.ts", b"import './keys';\n", false)],
        tree.ctx(cfg),
    );
    let inc = included_paths(&res);
    assert!(
        !inc.contains(&".env".to_string()),
        "a deny-listed related file must never be included; got {inc:?}"
    );
    assert!(!res.prompt.contains("sk-live-should-never-ship"));
    assert!(res
        .exclusions
        .iter()
        .any(|(p, r)| p == ".env" && matches!(r, FileExclusionReason::DenyList(_))));
}

/// AC 188 — related files respect MAX_FILE_BYTES and the binary check.
#[test]
fn ac188_related_files_respect_size_and_binary_checks() {
    let tree = Tree::new(&[("src/a.ts", "")]);
    // A tracked "related" file containing a null byte.
    tree.untracked("src/bin.ts", "");
    std::fs::write(tree.dir.path().join("src/bin.ts"), [0xffu8, 0x00, b'h']).unwrap();
    let mut tracked = tree.tracked.clone();
    tracked.insert("src/bin.ts".to_string());
    let ctx = RelatedContext {
        repo_root: Some(tree.dir.path()),
        tracked: Some(&tracked),
        cfg: BundleConfig {
            include: vec!["src/bin.ts".into()],
            ..BundleConfig::default()
        },
    };
    let res = assemble_with(vec![file("src/a.ts", b"const a = 1;\n", false)], ctx);
    assert!(
        !included_paths(&res).contains(&"src/bin.ts".to_string()),
        "a binary related file must be excluded"
    );
    assert!(res
        .exclusions
        .iter()
        .any(|(p, r)| p == "src/bin.ts" && matches!(r, FileExclusionReason::Binary)));
}

/// AC 188 — related files respect `MAX_FILE_BYTES` (2 MB), the same
/// ceiling changed files get. Covers the size half of AC 188; the binary
/// half is covered above.
#[test]
fn ac188_related_files_respect_max_file_bytes() {
    let tree = Tree::new(&[("src/a.ts", "")]);
    // Just over the 2 MB ceiling.
    let huge = "x".repeat(2 * 1024 * 1024 + 1);
    tree.untracked("src/huge.ts", &huge);
    let mut tracked = tree.tracked.clone();
    tracked.insert("src/huge.ts".to_string());
    let ctx = RelatedContext {
        repo_root: Some(tree.dir.path()),
        tracked: Some(&tracked),
        cfg: BundleConfig {
            include: vec!["src/huge.ts".into()],
            ..BundleConfig::default()
        },
    };
    let res = assemble_with(vec![file("src/a.ts", b"const a = 1;\n", false)], ctx);
    assert!(
        !included_paths(&res).contains(&"src/huge.ts".to_string()),
        "a related file over MAX_FILE_BYTES must be excluded"
    );
    assert!(res
        .exclusions
        .iter()
        .any(|(p, r)| p == "src/huge.ts" && matches!(r, FileExclusionReason::TooLarge)));
}

/// AC 189 — a specifier resolving outside the repository root is skipped.
#[test]
fn ac189_related_discovery_never_leaves_the_repo() {
    let tree = Tree::new(&[("src/a.ts", "")]);
    // A file that exists just outside the repo root.
    let outside = tree.dir.path().parent().unwrap().join("outside_secret.ts");
    std::fs::write(&outside, "export const leaked = 1;\n").ok();
    let res = assemble_with(
        vec![file(
            "src/a.ts",
            b"import '../../outside_secret';\nimport '../outside_secret';\n",
            false,
        )],
        tree.ctx(BundleConfig::default()),
    );
    assert!(!res.prompt.contains("leaked"));
    assert_eq!(included_paths(&res), vec!["src/a.ts".to_string()]);
    std::fs::remove_file(&outside).ok();
}

// ============ SEC-1 — related-file reads never follow a link out of the repo ============
//
// git stores a symlink as a blob whose content is the target string, so a
// committed `tsconfig.json -> ~/.aws/credentials` is a *tracked* path. The
// changed-file section is safe by construction (it reads index blobs, and
// a link's blob is just that string); only the working-tree read path for
// related files can follow it. In the tests below the link is added to
// `tracked` by hand for exactly that reason.

/// Create file symlink `link` -> `target`. Windows needs Developer Mode or
/// admin for this; without the privilege it returns `false` and the caller
/// skips, loudly. These tests are authoritative on Unix.
fn symlink_file(target: &std::path::Path, link: &std::path::Path) -> bool {
    #[cfg(unix)]
    {
        std::os::unix::fs::symlink(target, link).expect("symlink");
        true
    }
    #[cfg(windows)]
    {
        match std::os::windows::fs::symlink_file(target, link) {
            Ok(()) => true,
            Err(e) => {
                eprintln!(
                    "SKIPPED: cannot create a symlink here ({e}); this test is authoritative on Unix"
                );
                false
            }
        }
    }
}

/// Link directory `link` -> `target`: a symlink on Unix, a junction on
/// Windows (which needs no privilege and which both the OS and
/// `std::fs::canonicalize` resolve like a directory symlink).
fn link_dir(target: &std::path::Path, link: &std::path::Path) {
    #[cfg(unix)]
    std::os::unix::fs::symlink(target, link).expect("dir symlink");
    #[cfg(windows)]
    {
        let status = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(link)
            .arg(target)
            .stdout(std::process::Stdio::null())
            .status()
            .expect("run mklink /J");
        assert!(status.success(), "mklink /J failed");
    }
}

/// The `UnsafePath` reason recorded for `path`, if any.
fn unsafe_reason(res: &quorum_core::bundle::BundleResult, path: &str) -> Option<&'static str> {
    res.exclusions.iter().find_map(|(p, r)| match r {
        FileExclusionReason::UnsafePath(why) if p == path => Some(*why),
        _ => None,
    })
}

/// SEC-1 — `tsconfig.json -> <outside>/credentials`, reached through the
/// config allowlist by staging any `.ts` change, is excluded and reported.
#[test]
fn sec1_allowlist_symlink_out_of_repo_is_excluded_and_reported() {
    let outside = tempfile::tempdir().unwrap();
    let creds = outside.path().join("credentials");
    std::fs::write(
        &creds,
        "[default]\naws_secret_access_key = OUTSIDE-CANARY-1\n",
    )
    .unwrap();
    let mut tree = Tree::new(&[("src/app.ts", "export const a = 1;\n")]);
    if !symlink_file(&creds, &tree.dir.path().join("tsconfig.json")) {
        return;
    }
    tree.tracked.insert("tsconfig.json".into());
    let res = assemble_with(
        vec![file("src/app.ts", b"export const a = 2;\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    assert!(
        !res.prompt.contains("OUTSIDE-CANARY-1"),
        "credentials behind a symlink were sent:\n{}",
        res.prompt
    );
    assert!(!included_paths(&res).contains(&"tsconfig.json".to_string()));
    assert_eq!(
        unsafe_reason(&res, "tsconfig.json"),
        Some("resolves outside the repository"),
        "the skip must be reported; exclusions = {:?}",
        res.exclusions
    );
}

/// SEC-1 — `src/foo.rs -> <outside>/id_rsa` behind a `mod foo;` is the same
/// hole reached through one-hop import resolution.
#[test]
fn sec1_one_hop_symlink_out_of_repo_is_excluded_and_reported() {
    let outside = tempfile::tempdir().unwrap();
    let key = outside.path().join("id_rsa");
    std::fs::write(
        &key,
        "-----BEGIN OPENSSH PRIVATE KEY-----\nOUTSIDE-CANARY-2\n",
    )
    .unwrap();
    let mut tree = Tree::new(&[("src/lib.rs", "mod foo;\n")]);
    if !symlink_file(&key, &tree.dir.path().join("src/foo.rs")) {
        return;
    }
    tree.tracked.insert("src/foo.rs".into());
    let res = assemble_with(
        vec![file("src/lib.rs", b"mod foo;\npub fn a() {}\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    assert!(!res.prompt.contains("OUTSIDE-CANARY-2"), "{}", res.prompt);
    assert_eq!(
        unsafe_reason(&res, "src/foo.rs"),
        Some("resolves outside the repository"),
        "exclusions = {:?}",
        res.exclusions
    );
}

/// SEC-1 — do not over-block: a symlink to a tracked file *inside* the
/// repository is normal and is still read and sent.
#[test]
fn sec1_in_repo_symlink_is_still_allowed() {
    let mut tree = Tree::new(&[
        (
            "configs/tsconfig.base.json",
            "{\"compilerOptions\":{\"strict\":true}}\n",
        ),
        ("src/app.ts", "export const a = 1;\n"),
    ]);
    let link = tree.dir.path().join("tsconfig.json");
    if !symlink_file(std::path::Path::new("configs/tsconfig.base.json"), &link) {
        return;
    }
    tree.tracked.insert("tsconfig.json".into());
    let res = assemble_with(
        vec![file("src/app.ts", b"export const a = 2;\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    assert!(
        included_paths(&res).contains(&"tsconfig.json".to_string()),
        "an in-repo symlink must still be followed; exclusions = {:?}",
        res.exclusions
    );
    assert!(res
        .prompt
        .contains("### tsconfig.json (unchanged, context)"));
    assert!(res.prompt.contains("\"strict\":true"));
    assert_eq!(unsafe_reason(&res, "tsconfig.json"), None);
}

/// SEC-1 — the deny-list and the tracked check were applied to the *name*,
/// which the link chooses. An in-repo link onto `.env`, or onto an
/// untracked file, must be judged by where it lands.
#[test]
fn sec1_in_repo_symlink_to_denied_or_untracked_target_is_excluded() {
    let mut tree = Tree::new(&[("src/app.ts", "export const a = 1;\n")]);
    tree.untracked(".env", "API_KEY=IN-REPO-CANARY-3\n");
    tree.untracked("local.json", "{\"token\":\"UNTRACKED-CANARY-4\"}\n");
    let root = tree.dir.path().to_path_buf();
    if !symlink_file(std::path::Path::new(".env"), &root.join("tsconfig.json"))
        || !symlink_file(
            std::path::Path::new("local.json"),
            &root.join("package.json"),
        )
    {
        return;
    }
    tree.tracked.insert("tsconfig.json".into());
    tree.tracked.insert("package.json".into());
    let res = assemble_with(
        vec![file("src/app.ts", b"export const a = 2;\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    assert!(!res.prompt.contains("IN-REPO-CANARY-3"), "{}", res.prompt);
    assert!(!res.prompt.contains("UNTRACKED-CANARY-4"), "{}", res.prompt);
    assert_eq!(
        unsafe_reason(&res, "tsconfig.json"),
        Some("symlink target is deny-listed")
    );
    assert_eq!(
        unsafe_reason(&res, "package.json"),
        Some("symlink target is not tracked")
    );
}

/// SEC-1 — README.md: "untracked files are NEVER sent". The config
/// allowlist used to probe only `is_file()`, so an untracked or gitignored
/// `package.json` / `.eslintrc.js` at the repo root was read and sent.
#[test]
fn sec1_untracked_allowlist_config_is_not_sent() {
    let tree = Tree::new(&[
        ("src/app.ts", "export const a = 1;\n"),
        ("tsconfig.json", "{\"compilerOptions\":{}}\n"),
    ]);
    tree.untracked("package.json", "{\"name\":\"UNTRACKED-CANARY-5\"}\n");
    tree.untracked(
        ".eslintrc.js",
        "module.exports = { c: 'UNTRACKED-CANARY-6' };\n",
    );
    let res = assemble_with(
        vec![file("src/app.ts", b"export const a = 2;\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    let inc = included_paths(&res);
    assert!(!res.prompt.contains("UNTRACKED-CANARY-5"), "got {inc:?}");
    assert!(!res.prompt.contains("UNTRACKED-CANARY-6"), "got {inc:?}");
    // Positive control: the tracked allowlist config is still offered.
    assert!(inc.contains(&"tsconfig.json".to_string()), "got {inc:?}");
}

/// SEC-1 — a link in a *directory* component, not just the leaf. A path
/// that `tracked` lists under `vendor/` must not be read when `vendor` is a
/// link out of the repository. Runs on Windows too, via a junction.
#[test]
fn sec1_directory_link_out_of_repo_is_excluded_and_reported() {
    let outside = tempfile::tempdir().unwrap();
    std::fs::write(
        outside.path().join("creds.ts"),
        "export const leaked = 'OUTSIDE-CANARY-7';\n",
    )
    .unwrap();
    let mut tree = Tree::new(&[("src/app.ts", "export const a = 1;\n")]);
    link_dir(outside.path(), &tree.dir.path().join("vendor"));
    tree.tracked.insert("vendor/creds.ts".into());
    let cfg = BundleConfig {
        include: vec!["vendor/*.ts".into()],
        ..BundleConfig::default()
    };
    let res = assemble_with(
        vec![file("src/app.ts", b"export const a = 2;\n", false)],
        tree.ctx(cfg),
    );
    assert!(!res.prompt.contains("OUTSIDE-CANARY-7"), "{}", res.prompt);
    assert_eq!(
        unsafe_reason(&res, "vendor/creds.ts"),
        Some("resolves outside the repository"),
        "exclusions = {:?}",
        res.exclusions
    );
}

/// AC 190 — `related_files = false` restores exactly the v0.3.3 candidate
/// set: the changed files and nothing else.
#[test]
fn ac190_related_files_false_restores_v033_candidate_set() {
    let tree = Tree::new(&[
        ("Cargo.toml", "[package]\nname = \"x\"\n"),
        ("src/lib.rs", "mod helper;\n"),
        ("src/helper.rs", "pub fn h() {}\n"),
    ]);
    let changed = || {
        vec![
            file("src/lib.rs", b"mod helper;\n", false),
            file("README.md", b"# docs\n", false),
        ]
    };

    let on = assemble_with(changed(), tree.ctx(BundleConfig::default()));
    let off = assemble_with(
        changed(),
        tree.ctx(BundleConfig {
            related_files: false,
            ..BundleConfig::default()
        }),
    );

    let mut off_paths = included_paths(&off);
    off_paths.sort();
    assert_eq!(
        off_paths,
        vec!["README.md".to_string(), "src/lib.rs".to_string()],
        "with related_files = false the candidate set is the changed set"
    );
    // And discovery really was doing something with the flag on.
    assert!(included_paths(&on).contains(&"src/helper.rs".to_string()));
    assert_eq!(off.related_capped_out, 0);
}

/// AC 182 — no file is included twice, including when a path is both in
/// the changed set and matched by the config allowlist.
#[test]
fn ac182_no_file_included_twice() {
    let tree = Tree::new(&[
        ("Cargo.toml", "[package]\nname = \"x\"\n"),
        ("src/lib.rs", "pub fn a() {}\n"),
    ]);
    // Cargo.toml is BOTH changed and on the allowlist for the changed .rs.
    let cfg = BundleConfig {
        // ...and matched by an include glob as well, for good measure.
        include: vec!["Cargo.toml".into(), "src/*.rs".into()],
        ..BundleConfig::default()
    };
    let res = assemble_with(
        vec![
            file("Cargo.toml", b"[package]\nname = \"x\"\n", false),
            file("src/lib.rs", b"pub fn a() {}\n", false),
        ],
        tree.ctx(cfg),
    );
    let inc = included_paths(&res);
    let mut uniq = inc.clone();
    uniq.sort();
    uniq.dedup();
    assert_eq!(inc.len(), uniq.len(), "duplicate paths in {inc:?}");
    assert_eq!(
        res.prompt.matches("### Cargo.toml").count(),
        1,
        "Cargo.toml emitted more than once"
    );
    // The changed copy wins: no "(unchanged, context)" label on it.
    assert!(!res.prompt.contains("### Cargo.toml (unchanged, context)"));
}

/// AC 193 — `include` globs match repo-relative paths and enter at the
/// class their path implies, not at a privileged rank.
#[test]
fn ac193_include_globs_enter_at_their_implied_class() {
    let tree = Tree::new(&[
        ("src/a.rs", "pub fn a() {}\n"),
        ("docs/notes.md", "# notes\n"),
        ("schema/001.sql", "CREATE TABLE t();\n"),
    ]);
    let cfg = BundleConfig {
        include: vec!["docs/*.md".into(), "schema/*.sql".into()],
        ..BundleConfig::default()
    };
    let res = assemble_with(
        vec![file("src/a.rs", b"pub fn a() {}\n", false)],
        tree.ctx(cfg),
    );
    let by_path = |p: &str| {
        res.inclusion_order
            .iter()
            .find(|r| r.path == p)
            .unwrap_or_else(|| panic!("{p} missing from {:?}", included_paths(&res)))
    };
    assert_eq!(by_path("docs/notes.md").class, FileClass::Docs);
    assert_eq!(by_path("schema/001.sql").class, FileClass::Source);
    assert_eq!(class_rank("schema/001.sql"), FileClass::Source);
    // Not privileged: the changed source file still comes first.
    assert_eq!(res.inclusion_order[0].path, "src/a.rs");
}

/// AC 180 — the `## File inclusion order` block records path, class and
/// hunk count for each file, so the ordering is auditable from the
/// archived prompt without re-running the review.
#[test]
fn ac180_inclusion_order_block_is_emitted() {
    let tree = Tree::new(&[
        ("Cargo.toml", "[package]\n"),
        ("src/lib.rs", "pub fn a() {}\n"),
    ]);
    let res = assemble_with(
        vec![
            file_hunks("src/lib.rs", b"pub fn a() {}\n", 4),
            file_hunks("README.md", b"# hi\n", 1),
        ],
        tree.ctx(BundleConfig::default()),
    );
    assert!(res.prompt.contains("## File inclusion order"));
    assert!(res
        .prompt
        .contains("src/lib.rs class=source hunks=4 bytes=14 origin=changed included"));
    assert!(res
        .prompt
        .contains("README.md class=docs hunks=1 bytes=5 origin=changed included"));
    // The related Cargo.toml is attributed to the allowlist.
    assert!(res.prompt.contains("Cargo.toml class=config hunks=0"));
    assert!(res.prompt.contains("origin=config-allowlist"));
    // Block order matches emission order.
    let pos_src = res.prompt.find("src/lib.rs class=").unwrap();
    let pos_doc = res.prompt.find("README.md class=").unwrap();
    assert!(pos_src < pos_doc, "block must follow the real ordering");
}

/// AC 181 — `files_omitted` still lists every omitted path, and the
/// `[file omitted: …; budget exhausted]` marker keeps its v0.3.3 shape.
#[test]
fn ac181_omission_marker_shape_is_unchanged() {
    let big = body_kb(90, 'z');
    let res = assemble_with(
        vec![
            file("src/small.rs", b"pub fn a() {}\n", false),
            file("huge.md", &big, false),
        ],
        Default::default(),
    );
    assert_eq!(res.files_omitted, vec!["huge.md".to_string()]);
    assert!(
        res.prompt.contains(&format!(
            "[file omitted: huge.md, {} bytes; budget exhausted]",
            big.len()
        )),
        "marker shape changed"
    );
}

/// AC 182a — every file body in the changed-file section carries a
/// 1-based `%6d | ` gutter.
#[test]
fn ac182a_changed_file_bodies_are_line_numbered() {
    let res = assemble_with(
        vec![file("src/a.rs", b"fn one() {}\nfn two() {}\n", false)],
        Default::default(),
    );
    assert!(res.prompt.contains("     1 | fn one() {}"));
    assert!(res.prompt.contains("     2 | fn two() {}"));
}

/// AC 182b — context files are numbered too, and the section says the
/// numbers refer to the working tree at HEAD rather than to the diff.
#[test]
fn ac182b_context_files_are_line_numbered_and_explained() {
    let tree = Tree::new(&[
        ("Cargo.toml", "[package]\nname = \"x\"\n"),
        ("src/lib.rs", "pub fn a() {}\n"),
    ]);
    let res = assemble_with(
        vec![file("src/lib.rs", b"pub fn a() {}\n", false)],
        tree.ctx(BundleConfig::default()),
    );
    assert!(res.prompt.contains("### Cargo.toml (unchanged, context)"));
    assert!(res.prompt.contains("     1 | [package]"));
    assert!(res.prompt.contains("     2 | name = \"x\""));
    assert!(
        res.prompt.contains("working tree") && res.prompt.contains("HEAD"),
        "the section must explain what the context line numbers refer to"
    );
}

/// AC 194 — raising `total_budget_kb` admits more content; the section
/// budgets are derived, not hard-coded.
#[test]
fn ac194_raising_total_budget_admits_more_files() {
    let changed = || {
        vec![
            file("src/a.rs", &body_kb(40, 'a'), false),
            file("src/b.rs", &body_kb(40, 'b'), false),
            file("src/c.rs", &body_kb(40, 'c'), false),
        ]
    };
    let small = assemble_with(changed(), Default::default());
    let large = assemble_with(
        changed(),
        RelatedContext {
            cfg: BundleConfig {
                total_budget_kb: 400,
                ..BundleConfig::default()
            },
            ..Default::default()
        },
    );
    assert!(
        !small.files_omitted.is_empty(),
        "120KB of source must not fit the 200KB default file budget"
    );
    assert!(
        large.files_omitted.len() < small.files_omitted.len(),
        "raising total_budget_kb must admit more: {:?} vs {:?}",
        large.files_omitted,
        small.files_omitted
    );
}

/// `tracked_paths` really reports what git has at HEAD — the input the
/// one-hop resolver trusts (AC 184 / AC 190).
#[test]
fn tracked_paths_reflects_head() {
    let dir = tempfile::tempdir().unwrap();
    let repo = git2::Repository::init(dir.path()).unwrap();
    std::fs::create_dir_all(dir.path().join("src")).unwrap();
    std::fs::write(dir.path().join("src/a.rs"), "pub fn a() {}\n").unwrap();
    std::fs::write(dir.path().join("Cargo.toml"), "[package]\n").unwrap();
    let mut idx = repo.index().unwrap();
    idx.add_path(std::path::Path::new("src/a.rs")).unwrap();
    idx.add_path(std::path::Path::new("Cargo.toml")).unwrap();
    idx.write().unwrap();
    let tree_id = idx.write_tree().unwrap();
    let tree = repo.find_tree(tree_id).unwrap();
    let sig = git2::Signature::now("t", "t@e").unwrap();
    repo.commit(Some("HEAD"), &sig, &sig, "c", &tree, &[])
        .unwrap();

    // An untracked file on disk must not appear.
    std::fs::write(dir.path().join("src/scratch.rs"), "// scratch\n").unwrap();

    let tracked = quorum_core::git::tracked_paths(&repo);
    assert!(tracked.contains("src/a.rs"));
    assert!(tracked.contains("Cargo.toml"));
    assert!(
        !tracked.contains("src/scratch.rs"),
        "untracked files must not be offered as context"
    );
}

// ===================== SEC-1 — deny-list filters the diff BODY =====================
//
// Every test below builds a real repository and stages real changes, so the
// unified diff under test is libgit2's own output rather than a synthetic
// string. The pre-SEC-1 deny-list tests all passed `unified: String::new()`,
// which is how a filter that only ever removed the `diff --git` / `---` /
// `+++` lines shipped while README.md promised denied files appear "never as
// content".

/// Commit `base` at HEAD, then write and `git add` each of `staged`
/// (`None` = delete from index and working tree). Returns the tempdir (keep
/// it alive) and the staged diff exactly as `quorum review` computes it.
fn staged_repo(
    base: &[(&str, &str)],
    staged: &[(&str, Option<&str>)],
) -> (tempfile::TempDir, StagedDiff) {
    let dir = tempfile::tempdir().unwrap();
    let repo = git2::Repository::init(dir.path()).unwrap();
    let write = |path: &str, body: &str| {
        let abs = dir.path().join(path);
        std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
        std::fs::write(abs, body).unwrap();
    };
    let mut idx = repo.index().unwrap();
    for (p, b) in base {
        write(p, b);
        idx.add_path(std::path::Path::new(p)).unwrap();
    }
    idx.write().unwrap();
    let tree_id = idx.write_tree().unwrap();
    {
        let tree = repo.find_tree(tree_id).unwrap();
        let sig = git2::Signature::now("t", "t@e").unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "base", &tree, &[])
            .unwrap();
    }
    for (p, b) in staged {
        match b {
            Some(body) => {
                write(p, body);
                idx.add_path(std::path::Path::new(p)).unwrap();
            }
            None => {
                std::fs::remove_file(dir.path().join(p)).unwrap();
                idx.remove_path(std::path::Path::new(p)).unwrap();
            }
        }
    }
    idx.write().unwrap();
    drop(repo);
    let (_repo, diff) = quorum_core::git::staged_diff(dir.path()).unwrap();
    (dir, diff)
}

fn assemble_staged(staged: &StagedDiff) -> quorum_core::bundle::BundleResult {
    let conv = ConventionsState::Absent;
    let disc = empty_discovery();
    assemble(&BundleInputs {
        staged,
        memory: None,
        conventions: &conv,
        discovery: &disc,
        branch: "main",
        head_sha: "0000000000000000000000000000000000000000",
        remote_url: None,
        local_conventions: &[],
        local_convention_bundle_cap: 500,
        context: Default::default(),
    })
    .expect("assemble")
}

/// The diff section of `unified` for an unrenamed `path`, verbatim.
fn section_of<'a>(unified: &'a str, path: &str) -> &'a str {
    let head = format!("diff --git a/{path} b/{path}\n");
    let start = unified
        .find(&head)
        .unwrap_or_else(|| panic!("no section for {path} in:\n{unified}"));
    let body_start = start + head.len();
    let end = unified[body_start..]
        .find("\ndiff --git ")
        .map(|i| body_start + i + 1)
        .unwrap_or(unified.len());
    &unified[start..end]
}

/// The short (7-hex) blob id git prints on a section's `index` line.
fn short_blob_id(body: &str) -> String {
    git2::Oid::hash_object(git2::ObjectType::Blob, body.as_bytes())
        .unwrap()
        .to_string()[..7]
        .to_string()
}

/// Everything before the changed-file section: the envelope plus the diff.
fn diff_part(prompt: &str) -> &str {
    prompt.split("## Changed-file contents").next().unwrap()
}

const ENV_OLD: &str = "DB_HOST=prod.internal\nAWS_SECRET_ACCESS_KEY=old\n";
const ENV_NEW: &str = "DB_HOST=prod.internal\n\
                       AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI_EXAMPLE\n\
                       STRIPE_SECRET_KEY=sk_live_51H8xQ2\n";

/// Assert that nothing a denied blob contributes to a diff reaches `text`:
/// no line of any listed blob, and not the blob id on its `index` line.
fn assert_no_trace(text: &str, label: &str, blobs: &[&str]) {
    for blob in blobs {
        for line in blob.lines().filter(|l| !l.is_empty()) {
            assert!(
                !text.contains(line),
                "{label}: denied-file line {line:?} leaked into the bundle:\n{text}"
            );
        }
        let id = short_blob_id(blob);
        assert!(
            !text.contains(&id),
            "{label}: denied blob id {id} (its `index` line) leaked into the bundle:\n{text}"
        );
    }
}

/// SEC-1 negative control. A staged `.env` must contribute no byte of its
/// content to the bundle. Before the fix only the three header lines that
/// contain `a/.env` / `b/.env` were dropped; the `index` line, the `@@`
/// header and every `+` / `-` / context line survived.
#[test]
fn sec1_staged_env_contributes_nothing_to_the_diff_body() {
    let (_dir, staged) = staged_repo(&[(".env", ENV_OLD)], &[(".env", Some(ENV_NEW))]);
    // Precondition: the raw diff really carries the secret, so the
    // assertions below cannot pass vacuously.
    assert!(staged
        .unified
        .contains("+STRIPE_SECRET_KEY=sk_live_51H8xQ2"));
    assert!(staged.unified.contains(&short_blob_id(ENV_NEW)));

    let res = assemble_staged(&staged);
    assert_no_trace(&res.prompt, "modified .env", &[ENV_OLD, ENV_NEW]);
    // `.env` is the only change, so no hunk header may survive either.
    assert!(
        !res.prompt.contains("@@"),
        "a hunk header from the denied section survived:\n{}",
        res.prompt
    );
}

/// SEC-1 — the same guarantee for a staged deletion, where every line of
/// the old blob appears as a `-` line, and for a rename *away from* a
/// denied name, where only the old path is one the deny-list knows.
#[test]
fn sec1_deleted_or_renamed_away_env_contributes_nothing_to_the_diff() {
    let (_d1, deleted) = staged_repo(&[(".env", ENV_NEW)], &[(".env", None)]);
    assert!(deleted
        .unified
        .contains("-STRIPE_SECRET_KEY=sk_live_51H8xQ2"));
    let res = assemble_staged(&deleted);
    assert_no_trace(&res.prompt, "deleted .env", &[ENV_NEW]);
    assert!(res
        .prompt
        .contains("[excluded by deny-list: .env, pattern=.env]"));

    // Rename plus an edit, so the section carries hunks, not just headers.
    let renamed_body = format!("{ENV_NEW}EXTRA=1\n");
    let (_d2, renamed) = staged_repo(
        &[(".env", ENV_NEW)],
        &[(".env", None), ("config/env.txt", Some(&renamed_body))],
    );
    assert!(
        renamed.unified.contains("rename from .env"),
        "precondition: libgit2 must detect the rename:\n{}",
        renamed.unified
    );
    let res = assemble_staged(&renamed);
    let diff = diff_part(&res.prompt);
    assert_no_trace(diff, "renamed-away .env", &[ENV_NEW]);
    assert!(diff.contains("[excluded by deny-list: .env, pattern=.env]"));
    assert!(res
        .exclusions
        .iter()
        .any(|(p, r)| p == ".env" && matches!(r, FileExclusionReason::DenyList(_))));
}

/// SEC-1 — the old predicate was an unanchored substring test over every
/// line, so a content line in an innocent file that merely *mentions*
/// `a/.env` was silently deleted from the diff the models reviewed.
#[test]
fn sec1_content_mentioning_a_denied_path_is_not_mutilated() {
    let readme_old = "# Setup\n";
    let readme_new = "# Setup\n\
                      Copy a/.env.example to b/.env before running.\n\
                      diff --git a/.env b/.env is what git prints for it.\n";
    let (_dir, staged) = staged_repo(
        &[(".env", ENV_OLD), ("README.md", readme_old)],
        &[(".env", Some(ENV_NEW)), ("README.md", Some(readme_new))],
    );
    let readme = section_of(&staged.unified, "README.md");
    assert!(readme.contains("+Copy a/.env.example to b/.env before running."));
    let res = assemble_staged(&staged);
    assert!(
        res.prompt.contains(readme),
        "README.md's diff section must reach the bundle byte-for-byte.\n\
         expected section:\n{readme}\nbundle:\n{}",
        res.prompt
    );
    assert_no_trace(&res.prompt, ".env beside README", &[ENV_OLD, ENV_NEW]);
}

/// SEC-1 — the exclusion marker sits where the denied file's section was,
/// in addition to the header summary, and `exclusions` still records it.
#[test]
fn sec1_marker_replaces_the_denied_section_in_place() {
    let (_dir, staged) = staged_repo(
        &[(".env", ENV_OLD), ("src/main.rs", "fn main() {}\n")],
        &[
            (".env", Some(ENV_NEW)),
            ("src/main.rs", Some("fn main() { println!(\"hi\"); }\n")),
        ],
    );
    let res = assemble_staged(&staged);
    let marker = "[excluded by deny-list: .env, pattern=.env]";
    let diff = diff_part(&res.prompt);
    assert_eq!(
        diff.matches(marker).count(),
        2,
        "expected the header-summary marker plus one in place:\n{diff}"
    );
    // libgit2 orders deltas by path, so `.env` precedes `src/main.rs`: the
    // in-place marker must sit immediately before main.rs's section.
    let in_place = format!("{marker}\ndiff --git a/src/main.rs b/src/main.rs\n");
    assert!(diff.contains(&in_place), "marker not in place:\n{diff}");
    assert!(res
        .exclusions
        .iter()
        .any(|(p, r)| p == ".env" && matches!(r, FileExclusionReason::DenyList(".env"))));
}

/// SEC-1 — a denied file alongside a normal one: the normal file's diff
/// section survives byte-for-byte (index line, hunk header, every line).
#[test]
fn sec1_normal_file_beside_denied_file_is_intact() {
    let pem_old = "-----OLD PEM BODY-----\n";
    let pem_new = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\n";
    let (_dir, staged) = staged_repo(
        &[
            ("src/main.rs", "fn main() {}\n"),
            ("deploy/server.pem", pem_old),
        ],
        &[
            (
                "src/main.rs",
                Some("fn main() {\n    let token = std::env::var(\"API\");\n}\n"),
            ),
            ("deploy/server.pem", Some(pem_new)),
        ],
    );
    let main = section_of(&staged.unified, "src/main.rs");
    assert!(main.contains("@@"), "precondition: main.rs has a hunk");
    let res = assemble_staged(&staged);
    assert!(
        res.prompt.contains(main),
        "src/main.rs's section must survive intact.\nexpected:\n{main}\nbundle:\n{}",
        res.prompt
    );
    assert_no_trace(&res.prompt, "server.pem", &[pem_old, pem_new]);
}

/// SEC-1 — git C-quotes a path containing non-ASCII bytes in its
/// `diff --git` header (`"a/caf\303\251/.env"`). The section's path must be
/// decoded from that form, or the deny-list sees `.env"` and lets it pass.
#[test]
fn sec1_quoted_header_path_is_still_filtered() {
    let (_dir, staged) = staged_repo(
        &[("café/.env", ENV_OLD), ("src/lib.rs", "pub fn a() {}\n")],
        &[
            ("café/.env", Some(ENV_NEW)),
            ("src/lib.rs", Some("pub fn a() -> u8 { 1 }\n")),
        ],
    );
    assert!(staged.unified.contains("STRIPE_SECRET_KEY=sk_live_51H8xQ2"));
    let res = assemble_staged(&staged);
    assert_no_trace(&res.prompt, "quoted café/.env", &[ENV_OLD, ENV_NEW]);
    assert!(res
        .prompt
        .contains("[excluded by deny-list: café/.env, pattern=.env]"));
    assert!(res
        .prompt
        .contains(section_of(&staged.unified, "src/lib.rs")));
}