bugwarden 0.6.0

MCP server for Bugzilla with operator-controlled security guards
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
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
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
//! End-to-end tests of the audit stream against a mock Bugzilla.
//!
//! Each test builds a real [`BugWarden`] with auditing enabled, serves it
//! over an in-memory duplex transport, and calls the tools through an rmcp
//! MCP client — the same dispatch path a production client takes, so the
//! record-per-call guarantee is proven where it is enforced (the handler
//! wrapper), not in a helper. The sink writes a real JSONL file in a
//! tempdir; every assertion about "the record exists" reads that file
//! immediately after the call future resolves, which is the
//! persisted-before-response guarantee exercised end to end.

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

use bugwarden::audit::{
    AuditConfig, AuditEvent, AuditEventKind, AuditSink, AuditState, FailMode, OutcomeClass,
    TransportKind, Verdict,
};
use bugwarden::config::Cli;
use bugwarden::server::{BugWarden, USER_AGENT};
use bugwarden_core::client::BugzillaClient;
use bugwarden_core::guard::Guard;
use bugwarden_core::policy::Policy;
use rmcp::model::{CallToolRequestParams, CallToolResult};
use rmcp::service::{RoleClient, RunningService};
use rmcp::ServiceExt as _;
use serde_json::{json, Value};
use wiremock::matchers::{method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[path = "common/deadline.rs"]
mod deadline;
#[path = "common/pinned_cli.rs"]
mod pinned_cli;

use deadline::bounded;
use pinned_cli::pinned;

/// The pin's own self-check, run in each binary that relies on it so a
/// single-binary `cargo test --test ...` still proves what its harness
/// claims. Both halves assert with their own message, so folding them into
/// one test costs no diagnosis.
#[test]
fn the_environment_pin_holds() {
    pinned_cli::assert_the_pin_drops_every_fallback::<Cli>();
    pinned_cli::assert_the_pin_neutralises_a_flag_added_later::<Cli>();
}

/// A served, audited server plus the handles the assertions need.
struct Audited {
    client: RunningService<RoleClient, ()>,
    audit_path: PathBuf,
    /// Owns the audit directory for the test's lifetime.
    _dir: tempfile::TempDir,
}

/// Serve a [`BugWarden`] built from `policy` with auditing on
/// (fail_mode = open, so nothing in here depends on refusal behavior),
/// and connect an MCP client over an in-memory duplex transport.
async fn audited_client_for(policy: &str, mock: &MockServer, api_key: &str) -> Audited {
    audited_client_with(policy, mock, api_key, true).await
}

/// As [`audited_client_for`], with the `suppressed_ids` record knob under
/// the test's control.
async fn audited_client_with(
    policy: &str,
    mock: &MockServer,
    api_key: &str,
    suppressed_ids: bool,
) -> Audited {
    let dir = tempfile::tempdir().expect("tempdir");
    let audit_path = dir.path().join("audit.jsonl");
    let sink = AuditSink::open(AuditConfig {
        path: Some(audit_path.clone()),
        fsync: false,
        fail_mode: None,
        rotate_max_bytes: 0,
        rotate_keep: 8,
        suppressed_ids,
    })
    .expect("audit sink must open");
    let audit = Arc::new(AuditState::new(
        sink,
        FailMode::Open,
        Some("sha256:policy-under-test".to_string()),
    ));

    let cfg: Arc<Cli> = Arc::new(pinned(&[
        "bugwarden",
        "--bugzilla-server",
        &mock.uri(),
        "--transport",
        "stdio",
        "--api-key",
        api_key,
    ]));
    let guard = Arc::new(Guard {
        policy: Policy::from_toml_str(policy).expect("test policy must parse"),
    });
    let bz =
        Arc::new(BugzillaClient::new(&mock.uri(), false, USER_AGENT).expect("client must build"));
    let server = BugWarden::new(cfg, guard, bz)
        .expect("server must build")
        .with_audit(audit);

    let (client_io, server_io) = tokio::io::duplex(1 << 16);
    tokio::spawn(async move {
        if let Ok(running) = server.serve(server_io).await {
            let _ = running.waiting().await;
        }
    });
    let client = bounded("the MCP handshake", ().serve(client_io))
        .await
        .expect("MCP handshake must succeed");
    Audited {
        client,
        audit_path,
        _dir: dir,
    }
}

/// An un-audited server over the same transport, for comparisons.
async fn plain_client_for(policy: &str, mock: &MockServer) -> RunningService<RoleClient, ()> {
    let cfg: Arc<Cli> = Arc::new(pinned(&[
        "bugwarden",
        "--bugzilla-server",
        &mock.uri(),
        "--transport",
        "stdio",
        "--api-key",
        "test-key",
    ]));
    let guard = Arc::new(Guard {
        policy: Policy::from_toml_str(policy).expect("test policy must parse"),
    });
    let bz =
        Arc::new(BugzillaClient::new(&mock.uri(), false, USER_AGENT).expect("client must build"));
    let server = BugWarden::new(cfg, guard, bz).expect("server must build");
    let (client_io, server_io) = tokio::io::duplex(1 << 16);
    tokio::spawn(async move {
        if let Ok(running) = server.serve(server_io).await {
            let _ = running.waiting().await;
        }
    });
    bounded("the MCP handshake", ().serve(client_io))
        .await
        .expect("MCP handshake must succeed")
}

async fn call(client: &RunningService<RoleClient, ()>, tool: &str, args: Value) -> CallToolResult {
    let Value::Object(args) = args else {
        panic!("tool arguments must be a JSON object");
    };
    bounded(
        &format!("the {tool} call"),
        client.call_tool(CallToolRequestParams::new(tool.to_string()).with_arguments(args)),
    )
    .await
    .expect("tool call must not be a protocol error")
}

/// Parse every line of the audit file (empty lines skipped, as the sink's
/// self-healing documents).
fn read_events(path: &Path) -> Vec<AuditEvent> {
    let s = std::fs::read_to_string(path).expect("audit file must be readable");
    s.lines()
        .filter(|l| !l.is_empty())
        .map(|l| serde_json::from_str(l).expect("every audit line must parse as AuditEvent"))
        .collect()
}

fn last_tool_call(events: &[AuditEvent]) -> &bugwarden::audit::ToolCallEvent {
    match &events.last().expect("at least one event").kind {
        AuditEventKind::ToolCall(tc) => tc,
        other => panic!("expected a tool_call record, got {other:?}"),
    }
}

fn world_bug(id: u64) -> Value {
    json!({
        "id": id,
        "summary": "a plain bug",
        "product": "openSUSE",
        "component": "Kernel",
        "status": "NEW",
        "severity": "normal",
        "priority": "P3",
        "keywords": [],
        "groups": [],
        "whiteboard": "",
        "creation_time": "2020-01-01T00:00:00Z",
    })
}

/// Mount a full fixture upstream: bug 7 (classify + bodies), the id=0
/// padding fetch, history/comments/attachments for 7, attachment 55,
/// write endpoints, server-info endpoints, and the quicksearch doc page.
/// Mounted so that every routed tool has a workable happy path.
async fn mount_fixture(mock: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(mock)
        .await;
    // Catch-all for /rest/bug: classification and body fetches for id=7
    // and the quicksearch scan all serve bug 7. The quicksearch scan must
    // see an empty page past offset 0, or a short page no longer being
    // end-of-results makes it replay this single row up to the request
    // bound.
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .respond_with(|req: &wiremock::Request| {
            let q: std::collections::HashMap<_, _> = req.url.query_pairs().collect();
            if q.get("offset").is_some_and(|v| v != "0") {
                return ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] }));
            }
            ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] }))
        })
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/history"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(json!({ "bugs": [{ "history": [] }] })),
        )
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": { "7": { "comments": [
                { "id": 1, "bug_id": 7, "is_private": false, "text": "public comment" },
            ] } }
        })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/attachment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": { "7": [] } })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/attachment/55"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "attachments": { "55": {
                "id": 55,
                "bug_id": 7,
                "is_private": false,
                "size": 3,
                "file_name": "log.txt",
                "content_type": "text/plain",
                "data": "QUFB",
            } }
        })))
        .mount(mock)
        .await;
    Mock::given(method("PUT"))
        .and(path("/rest/bug/7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(mock)
        .await;
    Mock::given(method("POST"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 11 })))
        .mount(mock)
        .await;
    Mock::given(method("POST"))
        .and(path("/rest/bug/7/attachment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "ids": [31] })))
        .mount(mock)
        .await;
    Mock::given(method("POST"))
        .and(path("/rest/bug"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 4242 })))
        .mount(mock)
        .await;
    for (endpoint, body) in [
        ("/rest/version", json!({ "version": "5.0" })),
        ("/rest/extensions", json!({ "extensions": {} })),
        (
            "/rest/time",
            json!({ "web_time": "2026-01-01T00:00:00Z", "tz_name": "UTC" }),
        ),
        ("/rest/parameters", json!({ "parameters": {} })),
    ] {
        Mock::given(method("GET"))
            .and(path(endpoint))
            .respond_with(ResponseTemplate::new(200).set_body_json(body))
            .mount(mock)
            .await;
    }
    Mock::given(method("GET"))
        .and(path("/page.cgi"))
        .respond_with(ResponseTemplate::new(200).set_body_string("<html>quicksearch</html>"))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/product_enterable"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "ids": [] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/field/bug"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "fields": [] })))
        .mount(mock)
        .await;
}

/// Minimal valid arguments for each routed tool against [`mount_fixture`].
/// A new tool must be added here before the one-record-per-call test can
/// pass.
fn minimal_args(tool: &str) -> Value {
    match tool {
        "bug_info" => json!({ "bug_ids": [7] }),
        "bug_history" => json!({ "id": 7 }),
        "bug_comments" => json!({ "id": 7 }),
        "bugs_quicksearch" => json!({ "query": "kernel" }),
        "create_bug" => json!({
            "product": "openSUSE",
            "component": "core",
            "summary": "crash on start",
            "version": "1.0",
        }),
        "add_attachment" => json!({
            "bug_id": 7,
            "data": "QUFB",
            "file_name": "log.txt",
            "summary": "boot log",
            "content_type": "text/plain",
        }),
        "add_comment" => json!({ "bug_id": 7, "comment": "hello" }),
        "update_bug_status" => json!({ "bug_id": 7, "status": "NEW" }),
        "assign_bug" => json!({ "bug_id": 7, "assignee": "dev@example.org" }),
        "update_bug_fields" => json!({ "bug_id": 7, "priority": "P1" }),
        "update_bug_dependencies" => json!({ "bug_id": 7, "blocks_add": [7] }),
        "add_cc_to_bug" => json!({ "bug_id": 7, "cc_email": "cc@example.org" }),
        "mark_as_duplicate" => json!({ "bug_id": 7, "duplicate_of": 7 }),
        "list_attachments" => json!({ "bug_id": 7 }),
        "download_attachment" => json!({ "attachment_id": 55 }),
        "bug_url" => json!({ "bug_id": 7 }),
        "bugzilla_server_info" => json!({}),
        "bugzilla_products" => json!({}),
        "bug_fields" => json!({}),
        "quicksearch_syntax" => json!({}),
        "mcp_server_info" => json!({}),
        "summarize_bug" => json!({ "id": 7 }),
        other => panic!("no minimal args for tool {other} — extend the map"),
    }
}

/// Requests wiremock has actually served, the independent ground truth the
/// record's `upstream.requests` is measured against.
async fn upstream_hits(mock: &MockServer) -> usize {
    mock.received_requests()
        .await
        .expect("wiremock records requests by default")
        .len()
}

#[tokio::test]
async fn every_routed_tool_writes_exactly_one_record_per_call() {
    let mock = MockServer::start().await;
    mount_fixture(&mock).await;
    // allow_discovery = true so the full router — discovery tools included
    // (I16) — is exercised by this one-record-per-call guarantee (I15).
    let audited = audited_client_for("[global]\nallow_discovery = true\n", &mock, "test-key").await;

    let tools = bounded("tools/list", audited.client.list_all_tools())
        .await
        .expect("list_tools must succeed");
    assert!(!tools.is_empty(), "the router lists the tool surface");

    // The handshake wrote the initialize record.
    let mut expected = 1;
    assert_eq!(read_events(&audited.audit_path).len(), expected);
    for tool in &tools {
        let before = upstream_hits(&mock).await;
        let _ = call(&audited.client, &tool.name, minimal_args(&tool.name)).await;
        let hits = upstream_hits(&mock).await - before;
        expected += 1;
        // Read IMMEDIATELY after the response future resolves: the
        // record must already be on disk (persisted before response).
        let events = read_events(&audited.audit_path);
        assert_eq!(
            events.len(),
            expected,
            "calling {} must grow the file by exactly one record",
            tool.name
        );
        // Issue #94's fourth criterion, at the two record fields the same
        // blind spot covered: `request.id` and the handshake identity on a
        // TOOL-CALL record were read only off a hand-built `RequestInfo` /
        // `ClientInfo` in the schema fixtures, so both could be dropped to
        // `None` on every real call with the suite green. Checked here
        // because this is the one test that walks the whole router.
        let tc = last_tool_call(&events);
        // Byte-identical for every SERVED name, which is what keeps the
        // record cap on that same string invisible here (#243).
        assert_eq!(tc.request.tool, tool.name);
        assert!(
            tc.request.id.as_deref().is_some_and(|id| !id.is_empty()),
            "calling {} must record the JSON-RPC id the transport exposed: {:?}",
            tool.name,
            tc.request
        );
        assert!(
            tc.client.name.as_deref().is_some_and(|n| !n.is_empty()),
            "and the client that introduced itself in the handshake: {:?}",
            tc.client
        );
        assert!(
            tc.client.version.as_deref().is_some_and(|v| !v.is_empty()),
            "version too: {:?}",
            tc.client
        );
        assert_eq!(
            (
                tc.client.principal.as_deref(),
                tc.client.work_context.as_deref()
            ),
            (None, None),
            "and NEITHER server-verified slot on any routed tool: no verifier \
             exists, and nothing self-declared may be promoted into one \
             (#32, #34): {:?}",
            tc.client
        );
        // Issue #118, the same blind spot at the `upstream` block: it was
        // read only off the hand-built goldens. Measured against what
        // wiremock independently served, so a hardcoded count cannot pass
        // the whole walk — bug_info fans out to a classify plus a body
        // fetch, quicksearch_syntax makes its one non-REST page.cgi call,
        // and bug_url makes none.
        assert_eq!(
            tc.upstream.map_or(0, |u| u.requests) as usize,
            hits,
            "calling {} must record every upstream request it made: {:?}",
            tool.name,
            tc.upstream
        );
        assert_eq!(
            tc.upstream.is_some(),
            hits > 0,
            "and carry the block exactly when Bugzilla was contacted: {}",
            tool.name
        );
        if let Some(upstream) = tc.upstream {
            // The fixture answers 200 everywhere, so the recorded status is
            // the observed one and not a default. latency_ms is asserted
            // present only: against a localhost mock its magnitude rounds
            // to 0 ms and no threshold on it could fail.
            assert_eq!(
                upstream.status,
                Some(200),
                "and the status the fixture returned: {}",
                tool.name
            );
        }
    }
}

#[tokio::test]
async fn refusal_paths_write_exactly_one_record_each() {
    // hide-secret first (it decides bug 99); the group_restricted rule
    // makes may_create refuse ALL creation — the documented behaviour of
    // such a policy.
    let policy = concat!(
        "[[rule]]\nname = \"hide-secret\"\naction = \"deny\"\n",
        "[rule.match]\nproducts = [\"Secret*\"]\n",
        "[[rule]]\nname = \"group-restricted\"\naction = \"deny\"\n",
        "[rule.match]\ngroup_restricted = true\n",
    );
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(&mock)
        .await;
    let mut secret = world_bug(99);
    secret["product"] = json!("SecretSauce");
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "99"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [secret] })))
        .mount(&mock)
        .await;
    let audited = audited_client_for(policy, &mock, "test-key").await;

    let mut expected = 1; // initialize

    // `requests` is the upstream count the record must carry (issue #118):
    // a refusal decided from the request alone contacts Bugzilla not at all
    // and must leave the block absent, while a DENIAL still paid for the
    // classify that produced the verdict.
    let mut check = |events: Vec<AuditEvent>, verdict: Verdict, rule: Option<&str>, reqs: u32| {
        expected += 1;
        assert_eq!(events.len(), expected, "exactly one new record");
        let tc = last_tool_call(&events);
        let guard = tc.guard.as_ref().expect("the guard was consulted");
        assert_eq!(guard.verdict, verdict);
        assert_eq!(guard.rule.as_deref(), rule);
        assert_eq!(
            tc.upstream.map_or(0, |u| u.requests),
            reqs,
            "upstream requests: {:?}",
            tc.upstream
        );
        assert_eq!(tc.upstream.is_some(), reqs > 0);
    };

    // too_many_ids: 26 distinct ids.
    let ids: Vec<u64> = (1..=26).collect();
    let refused = call(&audited.client, "bug_info", json!({ "bug_ids": ids })).await;
    assert_eq!(refused.is_error, Some(true));
    check(read_events(&audited.audit_path), Verdict::Refused, None, 0);

    // Empty id list.
    let refused = call(&audited.client, "bug_info", json!({ "bug_ids": [] })).await;
    assert_eq!(refused.is_error, Some(true));
    check(read_events(&audited.audit_path), Verdict::Refused, None, 0);

    // A guard denial names its rule in the record — and nowhere else.
    let denied = call(&audited.client, "bug_history", json!({ "id": 99 })).await;
    assert_eq!(denied.is_error, Some(true));
    check(
        read_events(&audited.audit_path),
        Verdict::Denied,
        Some("hide-secret"),
        1,
    );
    // The denial is a well-formed response: outcome class stays ok.
    let events = read_events(&audited.audit_path);
    assert_eq!(last_tool_call(&events).outcome.class, OutcomeClass::Ok);

    // create_bug under a group_restricted policy: refused as requested.
    let refused = call(
        &audited.client,
        "create_bug",
        json!({
            "product": "openSUSE",
            "component": "core",
            "summary": "crash on start",
            "version": "1.0",
        }),
    )
    .await;
    assert_eq!(refused.is_error, Some(true));
    // The padded create refusal: no POST, but one classify against bug 0.
    check(read_events(&audited.audit_path), Verdict::Refused, None, 1);

    // A DENIED bug_info: the classify that produced the verdict ran and the
    // link-disclosure padding after it did, but no body fetch — the exact
    // two-request shape, measured at the client's send choke point, which
    // no handler could have reported (the padding is inside the guard).
    let denied = call(&audited.client, "bug_info", json!({ "bug_ids": [99] })).await;
    // bug_info answers a denial inside its envelope's `restricted` list, so
    // this is a well-formed response — the denial lives in the record.
    assert_eq!(denied.is_error, Some(false));
    check(
        read_events(&audited.audit_path),
        Verdict::Denied,
        Some("hide-secret"),
        2,
    );
}

#[tokio::test]
async fn a_default_decided_call_records_the_literal_default_rule() {
    // Issue #67: the policy default is a NAMED decision. Both arms of it
    // write the literal "default" into the record — an absent rule means
    // no single rule decided, which is a different statement. Asserted on
    // the audit record rather than on Access, because the record is what
    // a consumer reads.
    let mock = MockServer::start().await;
    mount_fixture(&mock).await;

    // Denying default, no rules at all: bug 7 is denied by the default.
    let audited = audited_client_for("default_action = \"deny\"\n", &mock, "test-key").await;
    let denied = call(&audited.client, "bug_history", json!({ "id": 7 })).await;
    assert_eq!(denied.is_error, Some(true));
    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events)
        .guard
        .as_ref()
        .expect("the guard was consulted");
    assert_eq!(guard.verdict, Verdict::Denied);
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "a default-decided denial is named, not rule-less"
    );

    // Allowing default, no rules at all: the same name on the serve side.
    let audited = audited_client_for("default_action = \"allow\"\n", &mock, "test-key").await;
    let served = call(&audited.client, "bug_history", json!({ "id": 7 })).await;
    assert_ne!(served.is_error, Some(true), "the history is served");
    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events)
        .guard
        .as_ref()
        .expect("the guard was consulted");
    assert_eq!(guard.verdict, Verdict::Served);
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "a default-decided serve is named too"
    );
}

/// `server::PARAM_VALUE_MAX_CHARS`, which is private. Mirrored rather
/// than inferred so the end-to-end record pins the cap's VALUE (#191) and
/// not merely the fact that something shortened the name.
const RECORDED_MAX_CHARS: usize = 1024;

#[tokio::test]
async fn unknown_and_stripped_tools_error_identically_and_still_record() {
    let mock = MockServer::start().await;
    let read_only = "[global]\nread_only = true\n";
    let audited = audited_client_for(read_only, &mock, "test-key").await;
    let plain = plain_client_for(read_only, &mock).await;

    // Unknown tool: the same protocol error with auditing on or off,
    // plus exactly one record with outcome error.
    let with_audit = bounded(
        "the audited no_such_tool call",
        audited
            .client
            .call_tool(CallToolRequestParams::new("no_such_tool".to_string())),
    )
    .await
    .expect_err("unknown tool is a protocol error");
    let without = bounded(
        "the unaudited no_such_tool call",
        plain.call_tool(CallToolRequestParams::new("no_such_tool".to_string())),
    )
    .await
    .expect_err("unknown tool is a protocol error");
    assert_eq!(
        format!("{with_audit:?}"),
        format!("{without:?}"),
        "auditing must not change the protocol error"
    );
    // Held against the oversized name below: the refusal names no tool,
    // so it cannot vary with one.
    let unknown_refusal = format!("{with_audit:?}");
    let events = read_events(&audited.audit_path);
    assert_eq!(events.len(), 2, "initialize + the failed call");
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "no_such_tool");
    assert_eq!(tc.outcome.class, OutcomeClass::Error);
    assert!(tc.guard.is_none(), "no guard ran for an unknown tool");

    // A write tool stripped by read-only mode (I13) is an unknown tool.
    let with_audit = bounded(
        "the audited add_comment call",
        audited.client.call_tool(
            CallToolRequestParams::new("add_comment".to_string()).with_arguments(
                serde_json::Map::from_iter([
                    ("bug_id".to_string(), json!(7)),
                    ("comment".to_string(), json!("hi")),
                ]),
            ),
        ),
    )
    .await
    .expect_err("a stripped tool is a protocol error");
    let without = bounded(
        "the unaudited add_comment call",
        plain.call_tool(
            CallToolRequestParams::new("add_comment".to_string()).with_arguments(
                serde_json::Map::from_iter([
                    ("bug_id".to_string(), json!(7)),
                    ("comment".to_string(), json!("hi")),
                ]),
            ),
        ),
    )
    .await
    .expect_err("a stripped tool is a protocol error");
    assert_eq!(format!("{with_audit:?}"), format!("{without:?}"));
    let events = read_events(&audited.audit_path);
    assert_eq!(events.len(), 3, "one more record for the stripped call");
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "add_comment");
    assert_eq!(tc.outcome.class, OutcomeClass::Error);
    // The comment body is not allowlisted even on this path.
    assert_eq!(tc.request.params["comment"], json!({ "_len": 4 }));

    // #243: an unknown name is unbounded client text on its way into the
    // file and the OTLP export, and it is recorded whatever it is. Four
    // times the cap, through the real transport.
    let huge = "z".repeat(RECORDED_MAX_CHARS * 4);
    let with_audit = bounded(
        "the audited oversized-name call",
        audited
            .client
            .call_tool(CallToolRequestParams::new(huge.clone())),
    )
    .await
    .expect_err("an unknown tool is a protocol error whatever its length");
    let without = bounded(
        "the unaudited oversized-name call",
        plain.call_tool(CallToolRequestParams::new(huge.clone())),
    )
    .await
    .expect_err("an unknown tool is a protocol error whatever its length");
    assert_eq!(
        format!("{with_audit:?}"),
        format!("{without:?}"),
        "auditing must not change the protocol error"
    );
    assert_eq!(
        format!("{with_audit:?}"),
        unknown_refusal,
        "and the same refusal a short unknown name gets: no echo of the name"
    );
    let events = read_events(&audited.audit_path);
    assert_eq!(events.len(), 4, "one record for the oversized name too");
    let tc = last_tool_call(&events);
    assert_eq!(tc.outcome.class, OutcomeClass::Error);
    assert_eq!(
        tc.request.tool.chars().count(),
        RECORDED_MAX_CHARS,
        "the recorded name is cut to the cap, not merely shortened"
    );
    assert_eq!(
        tc.request.tool,
        huge.chars().take(RECORDED_MAX_CHARS).collect::<String>(),
        "and it is that prefix verbatim — capped() appends no marker"
    );
}

/// Policy hiding every bug in a `Secret*` product.
const HIDE_SECRET_POLICY: &str = concat!(
    "[[rule]]\nname = \"hide-secret\"\naction = \"deny\"\n",
    "[rule.match]\nproducts = [\"Secret*\"]\n",
);

/// Bug 7 names the [`HIDE_SECRET_POLICY`]-hidden bug 666 twice: its
/// `depends_on` links it, and its history records the link being added.
/// Both are I14 scrub sites, so both must enrich the record.
async fn mount_hidden_link(mock: &MockServer) {
    let mut linked = world_bug(7);
    linked["depends_on"] = json!([666]);
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [linked] })))
        .mount(mock)
        .await;
    let mut secret = world_bug(666);
    secret["product"] = json!("SecretSauce");
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "666"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [secret] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/history"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": [{ "history": [{
                "when": "2020-01-02T00:00:00Z",
                "who": "dev@example.org",
                "changes": [
                    { "field_name": "depends_on", "added": "666", "removed": "" },
                ],
            }] }]
        })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn suppressed_ids_reach_the_log_never_the_envelope() {
    // Bug 7 depends on the policy-hidden bug 666: I14 scrubs the link
    // from the served envelope; the audit record carries the id.
    let mock = MockServer::start().await;
    mount_hidden_link(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bug_info", json!({ "bug_ids": [7] })).await;
    assert_ne!(result.is_error, Some(true), "bug 7 itself is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        !envelope.contains("666"),
        "the hidden id must be scrubbed from the client envelope (I14): {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert!(
        guard.suppressed_ids.contains(&666),
        "the audit record must carry the suppressed id: {:?}",
        guard.suppressed_ids
    );
    assert!(guard.suppressed_ids_count >= 1);
    assert_eq!(
        guard.suppressed_other_count, 0,
        "a scrubbed link is an ID suppression and lands in no other tally: {guard:?}"
    );
    assert_eq!(
        guard.policy_hash.as_deref(),
        Some("sha256:policy-under-test"),
        "records tie to the policy in force"
    );

    // The history of bug 7 names 666 too: the scrub site is a different
    // one, and its record must carry the id all the same.
    let result = call(&audited.client, "bug_history", json!({ "id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "the history itself is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        !envelope.contains("666"),
        "the hidden id must be scrubbed from the served history (I14): {envelope}"
    );
    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_history");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert!(
        guard.suppressed_ids.contains(&666),
        "the bug_history record must carry the scrubbed id: {:?}",
        guard.suppressed_ids
    );
}

#[tokio::test]
async fn suppressed_ids_off_records_the_count_never_the_ids() {
    // The same scenario with `suppressed_ids = false` in the audit config:
    // the record still counts the suppression but names no id — and the
    // served envelope is exactly as clean as with the knob on.
    let mock = MockServer::start().await;
    mount_hidden_link(&mock).await;
    let audited = audited_client_with(HIDE_SECRET_POLICY, &mock, "test-key", false).await;

    let result = call(&audited.client, "bug_info", json!({ "bug_ids": [7] })).await;
    assert_ne!(result.is_error, Some(true), "bug 7 itself is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        !envelope.contains("666"),
        "the hidden id must be scrubbed from the client envelope (I14): {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert!(
        guard.suppressed_ids_count >= 1,
        "the id count survives the elision: {guard:?}"
    );
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(
        guard.suppressed_ids.is_empty(),
        "ids are elided when the knob is off: {:?}",
        guard.suppressed_ids
    );
}

/// Bug 7's comments mix BOTH suppression populations in one call (issue
/// #68): three private comments the I5 gate drops, which carry no bug id
/// of their own, and two duplicate markers naming the
/// [`HIDE_SECRET_POLICY`]-hidden bugs 666 and 667, which do.
///
/// One of the three private comments is ITSELF a duplicate marker, naming
/// a third hidden bug 668. That comment is what makes the fixture defend
/// the disjointness the sum rests on rather than merely assume it: the
/// marker ids are harvested from the comments that SURVIVED the private
/// filter, so 668 is counted once as id-less content and never named —
/// total 5. Harvest the ids from the pre-filter list instead and the same
/// dropped comment is counted twice, once in each tally: 6, over a
/// three-id list. Both classify fetches are mounted so that mutation
/// fails on the NUMBER rather than on an unmatched mock.
async fn mount_mixed_suppression(mock: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] })))
        .mount(mock)
        .await;
    let secret = |id: u64| {
        let mut bug = world_bug(id);
        bug["product"] = json!("SecretSauce");
        bug
    };
    // The link-disclosure fetch asks for the whole candidate set at once.
    // Expected exactly once: without the expectation an id list the guard
    // never asks for still 404s into disclosable's fail-closed arm, which
    // withholds 666/667 anyway and leaves the fixture decorative.
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "666,667"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(json!({ "bugs": [secret(666), secret(667)] })),
        )
        .expect(1)
        .mount(mock)
        .await;
    // Never requested while the harvest stays post-filter — mounted so a
    // pre-filter harvest gets a truthful answer and is caught by the
    // count, not by a 404.
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "666,667,668"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(json!({ "bugs": [secret(666), secret(667), secret(668)] })),
        )
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": { "7": { "comments": [
                { "id": 1, "bug_id": 7, "is_private": false, "text": "public comment" },
                { "id": 2, "bug_id": 7, "is_private": true, "text": "canary-private-8a1c one" },
                { "id": 3, "bug_id": 7, "is_private": true, "text": "canary-private-8a1c two" },
                // Private AND a duplicate marker: id-less content by the
                // only reading that keeps the two tallies disjoint.
                { "id": 4, "bug_id": 7, "is_private": true,
                  "text": "canary-private-8a1c *** Bug 668 has been marked as a duplicate of this bug ***" },
                { "id": 5, "bug_id": 7, "is_private": false,
                  "text": "*** Bug 666 has been marked as a duplicate of this bug ***" },
                { "id": 6, "bug_id": 7, "is_private": false,
                  "text": "*** Bug 667 has been marked as a duplicate of this bug ***" },
            ] } }
        })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn split_counters_report_both_populations_in_one_call() {
    // Issue #68 at schema v2: one call suppresses three id-less private
    // comments AND two duplicate-marker bug ids, and each population is
    // reported as itself. THE SEPARATING FIXTURE — 3 and 2 are different
    // numbers on purpose, so swapping the two fields fails here; a single
    // summed field structurally could not catch that.
    let mock = MockServer::start().await;
    mount_mixed_suppression(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bug_comments", json!({ "id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "bug 7's comments are served");
    let envelope = serde_json::to_string(&result).unwrap();
    for id in ["666", "667"] {
        assert!(
            !envelope.contains(id),
            "the hidden id must be scrubbed from the served comments (I14): {envelope}"
        );
    }
    assert!(
        !envelope.contains("canary-private-8a1c"),
        "the private comments must not reach the client (I5): {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_comments");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.suppressed_ids,
        vec![666, 667],
        "the surviving comments' marker ids are named, and 668's — noted \
         only inside a DROPPED private comment — is not: naming it would \
         count that one comment in both tallies"
    );
    assert_eq!(
        guard.suppressed_ids_count, 2,
        "the two withheld ids, counted as themselves: {guard:?}"
    );
    assert_eq!(
        guard.suppressed_other_count, 3,
        "the three id-less private comments, counted as themselves: {guard:?}"
    );
    assert_eq!(
        guard.suppressed_ids.len() as u64,
        guard.suppressed_ids_count,
        "the id list accounts for its own tally exactly, and for the other \
         one not at all: {guard:?}"
    );
}

#[tokio::test]
async fn summarize_bug_records_the_same_split_as_bug_comments() {
    // summarize_bug filters and scrubs the same comments as bug_comments
    // and notes both tallies from its own call site (server.rs), so this
    // diff changes the numbers it records too — it needs its own record,
    // not bug_comments' by analogy.
    let mock = MockServer::start().await;
    mount_mixed_suppression(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "summarize_bug", json!({ "id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "the summary prompt is served");
    let envelope = serde_json::to_string(&result).unwrap();
    for id in ["666", "667", "668"] {
        assert!(
            !envelope.contains(id),
            "no hidden id may reach the summarization prompt (I14): {envelope}"
        );
    }
    assert!(
        !envelope.contains("canary-private-8a1c"),
        "no private comment may reach the summarization prompt (I5): {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "summarize_bug");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.suppressed_ids,
        vec![666, 667],
        "the same two ids bug_comments names, and 668 no more than it does"
    );
    assert_eq!(
        guard.suppressed_ids_count, 2,
        "the same two ids, in the same field: {guard:?}"
    );
    assert_eq!(
        guard.suppressed_other_count, 3,
        "and the same three id-less comments: {guard:?}"
    );
}

#[tokio::test]
async fn split_counters_survive_the_ids_config() {
    // The same call under `suppressed_ids = false`, which is the case the
    // issue calls out: with no id list at all the two counts are the
    // operator's ONLY signal that anything was withheld (I3 keeps it from
    // the client). `suppressed_ids_count` must therefore come from the id
    // SET and not from the vector this switch empties.
    let mock = MockServer::start().await;
    mount_mixed_suppression(&mock).await;
    let audited = audited_client_with(HIDE_SECRET_POLICY, &mock, "test-key", false).await;

    let result = call(&audited.client, "bug_comments", json!({ "id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "bug 7's comments are served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert!(
        guard.suppressed_ids.is_empty(),
        "ids are elided when the knob is off: {:?}",
        guard.suppressed_ids
    );
    assert_eq!(
        guard.suppressed_ids_count, 2,
        "the elided ids still COUNT — this is the operator's only remaining \
         statement that two bugs were withheld: {guard:?}"
    );
    assert_eq!(
        guard.suppressed_other_count, 3,
        "and the id-less tally is untouched by that switch: {guard:?}"
    );
}

#[tokio::test]
async fn bug_comments_with_nothing_filtered_stays_served_and_counts_zero() {
    // Issue #87: the id-less counter is fed on EVERY call of these tools,
    // with `0` on the common path where the private filter dropped
    // nothing. `note_suppressed_count` returns early on zero for exactly
    // that reason — without it this record would claim `served_filtered`
    // over an empty suppression, and the one field an operator filters on
    // to find the calls the guard acted upon would say the same thing
    // about every call.
    let mock = MockServer::start().await;
    mount_fixture(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bug_comments", json!({ "id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "bug 7's comments are served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_comments");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.verdict,
        Verdict::Served,
        "the fixture's only comment is public and names no bug, so nothing \
         was withheld: {guard:?}"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(guard.suppressed_ids.is_empty());
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "and the rule that decided the call survives — a filtered merge \
         outranks a clean serve and would clear it"
    );
}

/// The counterpart to [`mount_hidden_link`]: bug 7 names bug 808 twice —
/// its `depends_on` links it, and its one comment is a duplicate marker
/// naming it — and 808 is a plain bug [`HIDE_SECRET_POLICY`] lets through.
/// That comment is public, so the I5 gate drops nothing either.
///
/// The point is that each id-set call site HAS a candidate to weigh: a
/// clean record over this fixture means "the guard withheld nothing", not
/// "there was nothing to withhold". A guard that never classified 808 —
/// or classified it and said no — fails closed and scrubs the link, which
/// shows up here as a suppression rather than as a pass.
///
/// Every row is load-bearing, which is the property a fixture built
/// against vacuity had better have: deleting 808's classification mock,
/// making 808 a hidden `Secret*` bug, dropping the `depends_on` link,
/// emptying the comment list, making the comment private, and replacing
/// the marker with plain text each turn one of the two tests below red.
async fn mount_disclosable_link(mock: &MockServer) {
    let mut linked = world_bug(7);
    linked["depends_on"] = json!([808]);
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [linked] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "808"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(808)] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": { "7": { "comments": [
                { "id": 1, "bug_id": 7, "is_private": false,
                  "text": "*** Bug 808 has been marked as a duplicate of this bug ***" },
            ] } }
        })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn summarize_bug_with_nothing_filtered_stays_served_and_counts_zero() {
    // Issue #88, the sibling of the bug_comments case above: summarize_bug
    // feeds BOTH tallies on every call — the id-less counter
    // unconditionally, the id set under `if !hidden.is_empty()`. Drop that
    // guard and `note_suppressed` fires with an empty iterator and merges
    // `served_filtered` into every summarize_bug record, over an empty
    // `suppressed_ids`; the one field an operator filters on to find the
    // calls the guard acted upon would then say the same thing about all
    // of them. The other tally leans on the `n == 0` early return inside
    // `note_suppressed_count`, which the issue #87 tests pin for
    // bug_comments and list_attachments but not at this third call site.
    let mock = MockServer::start().await;
    mount_disclosable_link(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "summarize_bug", json!({ "id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "the summary prompt is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        envelope.contains("Bug 808 has been marked as a duplicate"),
        "the marker names a bug the policy allows, so the scrub keeps it \
         and the recorded zero means nothing was withheld: {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "summarize_bug");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.verdict,
        Verdict::Served,
        "every comment is public and the only bug they name is disclosable, \
         so nothing was withheld: {guard:?}"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(guard.suppressed_ids.is_empty());
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "and the rule that decided the call survives — a filtered merge \
         outranks a clean serve and would clear it"
    );
}

#[tokio::test]
async fn bug_info_with_every_link_disclosable_stays_served_and_redacts_nothing() {
    // The same defect class at bug_info's two notes, neither of which
    // anything was pinning: the I14-scrubbed link ids under
    // `if !hidden_links.is_empty()`, and the summary-view marker under
    // `if redacted`. Both notes fire unconditionally once their guard is
    // gone, and either one merges `served_filtered` into every bug_info
    // record — the redaction note additionally naming a view the client
    // was never put into.
    let mock = MockServer::start().await;
    mount_disclosable_link(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bug_info", json!({ "bug_ids": [7] })).await;
    assert_ne!(result.is_error, Some(true), "bug 7 is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        envelope.contains("808"),
        "the link names a bug the policy allows, so I14 keeps it and the \
         empty suppression means nothing was withheld: {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_info");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.verdict,
        Verdict::Served,
        "bug 7 is served whole and its only link was disclosable: {guard:?}"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(guard.suppressed_ids.is_empty());
    assert!(
        guard.redacted_fields.is_empty(),
        "and the bug was served whole, not as a summary view: {:?}",
        guard.redacted_fields
    );
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "and the rule that decided the call survives — a filtered merge \
         outranks a clean serve and would clear it"
    );
}

/// Bug 7's history as three plain status-change entries, with the
/// classify fetch and the id=0 link-disclosure padding — the minimal
/// mock a windowed `bug_history` call needs (issue #142).
async fn mount_windowed_history(mock: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/history"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": [{ "id": 7, "history": [
                { "when": "2020-01-01T00:00:00Z", "who": "dev@example.org", "changes": [
                    { "field_name": "status", "added": "CONFIRMED", "removed": "NEW" },
                ] },
                { "when": "2020-01-02T00:00:00Z", "who": "dev@example.org", "changes": [
                    { "field_name": "status", "added": "IN_PROGRESS", "removed": "CONFIRMED" },
                ] },
                { "when": "2020-01-03T00:00:00Z", "who": "dev@example.org", "changes": [
                    { "field_name": "status", "added": "RESOLVED", "removed": "IN_PROGRESS" },
                ] },
            ] }]
        })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn bug_history_windowing_records_the_omission_it_applied() {
    // Issue #142: head=1 over three entries omits two. The omission is
    // something the guard withheld from the served envelope, so the
    // record names it — redacted_fields carries "history_window" and the
    // verdict upgrades to served_filtered.
    let mock = MockServer::start().await;
    mount_windowed_history(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(
        &audited.client,
        "bug_history",
        json!({ "id": 7, "head": 1 }),
    )
    .await;
    assert_ne!(
        result.is_error,
        Some(true),
        "the windowed history is served"
    );
    let text = result.content[0]
        .as_text()
        .expect("bug_history answers with text");
    let envelope: Value = serde_json::from_str(&text.text).expect("bug_history returns JSON");
    assert_eq!(envelope["history"].as_array().unwrap().len(), 1);
    assert_eq!(
        envelope["truncation"],
        json!({ "omitted_entries": 2, "shown_entries": 1 }),
        "the window omitted two of three: {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_history");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.redacted_fields,
        vec!["history_window".to_string()],
        "the record names the window as the redaction it applied: {guard:?}"
    );
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "and the granting rule survives: the CLIENT asked for one entry, so \
         no rule decided the omission: {guard:?}"
    );
    assert_eq!(
        (guard.suppressed_ids_count, guard.suppressed_other_count),
        (0, 0),
        "nothing else was withheld, so the window is the ONLY thing the \
         filtered verdict can have come from: {guard:?}"
    );
    assert!(guard.suppressed_ids.is_empty());
}

#[tokio::test]
async fn bug_history_window_that_omits_nothing_stays_silent() {
    // The other half of issue #142's audit contract: params present but
    // nothing omitted (head covers every entry) is a CLEAN serve — the
    // envelope carries its zeros and the record gains no redacted field
    // and no filtered verdict. An unconditional note would mark every
    // windowed call served_filtered (#87/#88).
    let mock = MockServer::start().await;
    mount_windowed_history(&mock).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(
        &audited.client,
        "bug_history",
        json!({ "id": 7, "head": 3, "tail": 3 }),
    )
    .await;
    assert_ne!(
        result.is_error,
        Some(true),
        "the windowed history is served"
    );
    let text = result.content[0]
        .as_text()
        .expect("bug_history answers with text");
    let envelope: Value = serde_json::from_str(&text.text).expect("bug_history returns JSON");
    assert_eq!(envelope["history"].as_array().unwrap().len(), 3);
    assert_eq!(
        envelope["truncation"],
        json!({ "omitted_entries": 0, "shown_entries": 3 }),
        "the overlapping windows omitted nothing: {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_history");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.verdict,
        Verdict::Served,
        "a window that withheld nothing is a clean serve: {guard:?}"
    );
    assert!(
        guard.redacted_fields.is_empty(),
        "and the window note stays silent when nothing was omitted: {:?}",
        guard.redacted_fields
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(guard.suppressed_ids.is_empty());
}

/// Policy granting `summary` and nothing else over the world product, so
/// every bug it matches is served as the [`Guard::summary_view`]
/// projection rather than whole — the one way a tool call reaches
/// `note_redacted`.
const SUMMARY_ONLY_POLICY: &str = concat!(
    "[[rule]]\nname = \"summaries-only\"\naction = \"restrict\"\n",
    "capabilities = [\"summary\"]\n",
    "[rule.match]\nproducts = [\"openSUSE\"]\n",
);

/// Bug 7 as [`SUMMARY_ONLY_POLICY`] sees it. The classification fetch is
/// the ONLY body bug_info gets — a summary grant earns no second fetch —
/// and the id=0 row answers the constant-cost link-disclosure padding a
/// projection with no link fields still pays (I2).
///
/// The whiteboard canary is what makes the fixture non-vacuous: it is not
/// a `SUMMARY_FIELDS` member, so a bug served whole and a bug served as a
/// projection are told apart by the envelope alone, and a policy that
/// stopped restricting would fail here before any record was read.
async fn mount_summary_only_bug(mock: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(mock)
        .await;
    let mut bug = world_bug(7);
    bug["whiteboard"] = json!("canary-whole-body-4d21");
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [bug] })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn bug_info_over_a_summary_view_records_the_redaction_it_applied() {
    // Issue #94, the opposite direction from #88 at the same note: the
    // `if redacted` guard is CORRECT, and the hazard is the note never
    // running at all. Nothing observed a non-empty `redacted_fields`
    // produced by a tool call — the assertions reached from one are
    // `is_empty()` checks a dead note satisfies trivially, and the
    // non-empty ones drive the cell directly or serialise a hand-built
    // `GuardInfo`. The verdict beside the note is computed independently,
    // so a dead note still leaves the record reading `served_filtered`;
    // it just no longer says WHICH projection filtered the serve.
    let mock = MockServer::start().await;
    mount_summary_only_bug(&mock).await;
    let audited = audited_client_for(SUMMARY_ONLY_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bug_info", json!({ "bug_ids": [7] })).await;
    assert_ne!(result.is_error, Some(true), "the summary view is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        envelope.contains("_redacted"),
        "the policy serves bug 7 as a summary view, not whole: {envelope}"
    );
    assert!(
        !envelope.contains("canary-whole-body-4d21"),
        "and the projection keeps no field outside SUMMARY_FIELDS: {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_info");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.redacted_fields,
        vec!["summary_view".to_string()],
        "the record names the projection that produced the verdict: {guard:?}"
    );
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.rule.as_deref(),
        Some("summaries-only"),
        "and the restrict rule that granted the summary decided the call"
    );
    assert_eq!(
        (guard.suppressed_ids_count, guard.suppressed_other_count),
        (0, 0),
        "nothing else was withheld, so the summary view is the ONLY thing \
         the filtered verdict can have come from: {guard:?}"
    );
    assert!(guard.suppressed_ids.is_empty());
}

/// One row of bug 7's attachment metadata, as Bugzilla serves it with the
/// content excluded.
fn attachment(id: u64, is_private: bool, file_name: &str) -> Value {
    json!({
        "id": id,
        "bug_id": 7,
        "is_private": is_private,
        "file_name": file_name,
        "summary": "attached",
        "content_type": "text/plain",
        "size": 3,
    })
}

/// Serve `rows` as bug 7's attachment metadata — the `list_attachments`
/// counter site. The private rows are what the I5 gate drops, and what it
/// drops carries no bug id of its own: this tool names no ids at all, so
/// the call feeds the id-less tally and nothing else.
async fn mount_attachments(mock: &MockServer, rows: Vec<Value>) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/attachment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": { "7": rows } })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn list_attachments_counts_the_private_metadata_it_dropped() {
    // Issue #87: the third id-less site. Two private attachments the I5
    // gate withheld are counted and never named, so this record carries a
    // non-zero count over an EMPTY id list — the shape only this tool
    // produces, and the reason nothing else was pinning its counter.
    let mock = MockServer::start().await;
    mount_attachments(
        &mock,
        vec![
            attachment(51, false, "log.txt"),
            attachment(52, true, "canary-private-3f7b-one.txt"),
            attachment(53, true, "canary-private-3f7b-two.txt"),
        ],
    )
    .await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "list_attachments", json!({ "bug_id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "the public metadata is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        !envelope.contains("canary-private-3f7b"),
        "private attachment metadata must not reach the client (I5): {envelope}"
    );
    // Nor into the operator's own stream: the record counts the drop, it
    // does not describe what was dropped.
    let raw = std::fs::read_to_string(&audited.audit_path).expect("audit file readable");
    assert!(
        !raw.contains("canary-private-3f7b"),
        "the withheld metadata must not reach the audit file either"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "list_attachments");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.suppressed_other_count, 2,
        "both dropped attachments are counted, id-lessly: {guard:?}"
    );
    assert_eq!(
        guard.suppressed_ids_count, 0,
        "attachment metadata names no bug, so the id tally stays empty: {guard:?}"
    );
    assert!(
        guard.suppressed_ids.is_empty(),
        "and neither is named — list_attachments names no ids at all: {:?}",
        guard.suppressed_ids
    );
}

#[tokio::test]
async fn list_attachments_with_nothing_private_stays_served_and_counts_zero() {
    // Issue #87 at the CALL SITE, which the zero guard alone does not
    // cover: an unconditional note added beside the counter — a
    // `note_redacted`, a rule-less `note_verdict` — leaves the `n == 0`
    // early return intact and still marks every clean listing
    // `served_filtered`.
    //
    // Two PUBLIC attachments rather than an empty list: the filter keeps
    // both, so the recorded zero means "nothing was withheld" and not
    // "there was nothing to withhold", and a counter fed the list length
    // instead of the drop fails here as well.
    let mock = MockServer::start().await;
    mount_attachments(
        &mock,
        vec![
            attachment(51, false, "log.txt"),
            attachment(52, false, "trace.txt"),
        ],
    )
    .await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "list_attachments", json!({ "bug_id": 7 })).await;
    assert_ne!(result.is_error, Some(true), "both attachments are served");
    let envelope = serde_json::to_string(&result).unwrap();
    for file_name in ["log.txt", "trace.txt"] {
        assert!(
            envelope.contains(file_name),
            "the gate kept {file_name}, so nothing was withheld: {envelope}"
        );
    }

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "list_attachments");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.verdict,
        Verdict::Served,
        "a listing that withheld nothing is a clean serve: {guard:?}"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(guard.suppressed_ids.is_empty());
    assert!(
        guard.redacted_fields.is_empty(),
        "and nothing was redacted from it either: {:?}",
        guard.redacted_fields
    );
}

/// Attachment 55 of bug 7 as a text payload of `data_b64`: the owning bug's
/// classification plus both attachment GETs (metadata and blob share the
/// path) — the `download_attachment` windowing fixture.
async fn mount_windowed_attachment(mock: &MockServer, data_b64: &str) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/attachment/55"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "attachments": { "55": {
                "id": 55,
                "bug_id": 7,
                "is_private": false,
                "size": 128,
                "file_name": "log.txt",
                "content_type": "text/plain",
                "data": data_b64,
            } }
        })))
        .mount(mock)
        .await;
}

#[tokio::test]
async fn download_attachment_windowing_that_cuts_records_the_redaction() {
    // Twenty lines windowed to three: content was removed, so the record
    // must name the projection that did it — the same bar the summary_view
    // note is held to.
    use base64::{engine::general_purpose, Engine as _};
    let mock = MockServer::start().await;
    let text: String = (1..=20).map(|i| format!("log line {i}\n")).collect();
    mount_windowed_attachment(&mock, &general_purpose::STANDARD.encode(&text)).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let result = call(
        &audited.client,
        "download_attachment",
        json!({ "attachment_id": 55, "head_lines": 3 }),
    )
    .await;
    assert_ne!(result.is_error, Some(true), "the window is served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "download_attachment");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.redacted_fields,
        vec!["attachment_window".to_string()],
        "the record names the window that cut the payload: {guard:?}"
    );
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "and the granting rule survives: the CLIENT asked for three lines, \
         so no rule decided the cut: {guard:?}"
    );
}

#[tokio::test]
async fn download_attachment_windowing_that_cuts_nothing_records_no_redaction() {
    // Params present but the window covers the whole text: the note must
    // stay silent, or every windowed-but-intact download would read as a
    // filtered serve.
    use base64::{engine::general_purpose, Engine as _};
    let mock = MockServer::start().await;
    mount_windowed_attachment(&mock, &general_purpose::STANDARD.encode("alpha\nbeta\n")).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let result = call(
        &audited.client,
        "download_attachment",
        json!({ "attachment_id": 55, "head_lines": 10, "max_chars": 1000 }),
    )
    .await;
    assert_ne!(result.is_error, Some(true), "the whole text is served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "download_attachment");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.verdict,
        Verdict::Served,
        "nothing was cut, so the serve stays clean: {guard:?}"
    );
    assert!(
        guard.redacted_fields.is_empty(),
        "and no redaction is noted: {:?}",
        guard.redacted_fields
    );
}

/// Serve a quicksearch corpus (issue #29 tests): search requests are paged
/// by limit/offset the way Bugzilla pages them, and the I14 link-disclosure
/// classify fetch — which addresses bugs by id, not by query — gets an
/// empty answer (the corpus rows carry no link fields to disclose).
async fn mount_search_corpus(mock: &MockServer, rows: Vec<Value>) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .respond_with(move |req: &wiremock::Request| {
            let q: std::collections::HashMap<_, _> = req.url.query_pairs().collect();
            if !q.contains_key("quicksearch") {
                return ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] }));
            }
            let get = |k: &str| q.get(k).and_then(|v| v.parse::<usize>().ok());
            let offset = get("offset").unwrap_or(0);
            let limit = get("limit").unwrap_or(rows.len());
            let page: Vec<_> = rows.iter().skip(offset).take(limit).cloned().collect();
            ResponseTemplate::new(200).set_body_json(json!({ "bugs": page }))
        })
        .mount(mock)
        .await;
}

/// A [`world_bug`] in the `Secret*` product the [`HIDE_SECRET_POLICY`]
/// denies.
fn secret_bug(id: u64) -> Value {
    let mut bug = world_bug(id);
    bug["product"] = json!("SecretSauce");
    bug
}

#[tokio::test]
async fn quicksearch_scan_accounting_reaches_the_record_never_the_envelope() {
    // Five upstream rows, two of them hidden: the record must say the scan
    // examined 5 and dropped 2 — and which two, through the existing
    // suppressed-ids machinery — while the envelope shows three bugs and
    // not a hint of accounting (I3).
    let mock = MockServer::start().await;
    mount_search_corpus(
        &mock,
        vec![
            world_bug(1),
            secret_bug(2),
            world_bug(3),
            secret_bug(4),
            world_bug(5),
        ],
    )
    .await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bugs_quicksearch", json!({ "query": "q" })).await;
    assert_ne!(result.is_error, Some(true), "the search is served");
    let envelope = serde_json::to_string(&result).unwrap();
    for leak in ["scanned", "dropped", "\"scan\""] {
        assert!(
            !envelope.contains(leak),
            "scan accounting leaked into the envelope: {envelope}"
        );
    }

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    let guard = tc.guard.as_ref().expect("guard info recorded");
    let scan = guard.scan.expect("a search records its scan");
    assert_eq!(scan.scanned, 5, "every upstream row was examined");
    assert_eq!(scan.dropped, 2, "the two hidden rows were dropped");
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.suppressed_ids,
        vec![2, 4],
        "the dropped ids ride the suppressed-ids machinery"
    );
    assert_eq!(guard.suppressed_ids_count, 2);
    assert_eq!(
        guard.suppressed_other_count, 0,
        "a dropped search row carries its own id, so nothing lands id-less"
    );
}

#[tokio::test]
async fn quicksearch_response_is_byte_identical_whether_or_not_rows_were_dropped() {
    // Acceptance (b) of issue #29, at the tool level with auditing ON: a
    // window that dropped hidden rows serializes byte-identically to the
    // same window over an upstream where those rows simply do not exist.
    let visible: Vec<u64> = vec![1, 3, 5, 6, 8, 9, 10, 11, 12];
    let mock_mixed = MockServer::start().await;
    mount_search_corpus(
        &mock_mixed,
        (1..=12)
            .map(|id| {
                if [2, 4, 7].contains(&id) {
                    secret_bug(id)
                } else {
                    world_bug(id)
                }
            })
            .collect(),
    )
    .await;
    let mock_clean = MockServer::start().await;
    mount_search_corpus(
        &mock_clean,
        visible.iter().map(|&id| world_bug(id)).collect(),
    )
    .await;

    let mixed = audited_client_for(HIDE_SECRET_POLICY, &mock_mixed, "test-key").await;
    let clean = audited_client_for(HIDE_SECRET_POLICY, &mock_clean, "test-key").await;
    let args = json!({ "query": "q", "limit": 4, "offset": 2 });
    let from_mixed = call(&mixed.client, "bugs_quicksearch", args.clone()).await;
    let from_clean = call(&clean.client, "bugs_quicksearch", args).await;
    assert_eq!(
        serde_json::to_string(&from_mixed).unwrap(),
        serde_json::to_string(&from_clean).unwrap(),
        "dropped rows must not change a single response byte (I3)"
    );

    // The difference lives in the records alone: the mixed scan dropped,
    // the clean scan did not.
    let mixed_events = read_events(&mixed.audit_path);
    let mixed_guard = last_tool_call(&mixed_events).guard.as_ref().unwrap();
    assert!(mixed_guard.scan.expect("scan recorded").dropped > 0);
    let clean_events = read_events(&clean.audit_path);
    let clean_guard = last_tool_call(&clean_events).guard.as_ref().unwrap();
    assert_eq!(clean_guard.scan.expect("scan recorded").dropped, 0);
}

#[tokio::test]
async fn quicksearch_group_by_reshapes_the_envelope_and_nothing_in_the_record() {
    // Issue #143: grouping runs after the audit block, so a grouped call and
    // a flat call over the same window must record the same guard info —
    // same scan, same verdict, same suppressed ids, no new redaction. Only
    // `params` differs, and it carries `group_by` by value (allowlisted: a
    // vocabulary field, not free text) rather than as `{"_len": n}`.
    let mock = MockServer::start().await;
    mount_search_corpus(&mock, vec![world_bug(1), secret_bug(2), world_bug(3)]).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let flat = call(&audited.client, "bugs_quicksearch", json!({ "query": "q" })).await;
    assert_ne!(flat.is_error, Some(true), "the flat search is served");
    let flat_guard = last_tool_call(&read_events(&audited.audit_path))
        .guard
        .clone()
        .expect("guard info recorded");

    let grouped = call(
        &audited.client,
        "bugs_quicksearch",
        json!({ "query": "q", "group_by": "product,status" }),
    )
    .await;
    assert_ne!(grouped.is_error, Some(true), "the grouped search is served");
    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    let grouped_guard = tc.guard.as_ref().expect("guard info recorded");

    assert_eq!(
        *grouped_guard, flat_guard,
        "grouping must not move a single field of the guard record"
    );
    assert!(
        grouped_guard.redacted_fields.is_empty(),
        "hoisting a field into a group header is not a redaction: {:?}",
        grouped_guard.redacted_fields
    );
    assert_eq!(
        tc.request.params["group_by"],
        json!("product,status"),
        "an allowlisted vocabulary param is recorded verbatim"
    );
    assert!(
        serde_json::to_string(&grouped).unwrap().contains("groups"),
        "the envelope really was grouped"
    );
}

#[tokio::test]
async fn quicksearch_drop_count_survives_the_suppressed_ids_knob() {
    // Acceptance (c) of issue #29: with `suppressed_ids = false` the
    // record still counts what the scan dropped — it just names no id.
    let mock = MockServer::start().await;
    mount_search_corpus(&mock, vec![world_bug(1), secret_bug(2), world_bug(3)]).await;
    let audited = audited_client_with(HIDE_SECRET_POLICY, &mock, "test-key", false).await;

    let result = call(&audited.client, "bugs_quicksearch", json!({ "query": "q" })).await;
    assert_ne!(result.is_error, Some(true), "the search is served");

    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events).guard.as_ref().unwrap();
    let scan = guard.scan.expect("a search records its scan");
    assert_eq!(scan.dropped, 1, "the count survives the elision");
    assert_eq!(scan.scanned, 3);
    assert!(guard.suppressed_ids_count >= 1, "so does the id count");
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(
        guard.suppressed_ids.is_empty(),
        "ids are elided when the knob is off: {:?}",
        guard.suppressed_ids
    );
}

#[tokio::test]
async fn quicksearch_clean_scan_records_zero_drops_and_stays_served() {
    // A search that hid nothing still accounts for its scan — dropped = 0
    // is a statement, not an omission — and keeps the clean verdict.
    let mock = MockServer::start().await;
    mount_search_corpus(&mock, vec![world_bug(1), world_bug(2), world_bug(3)]).await;
    let audited = audited_client_for(HIDE_SECRET_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bugs_quicksearch", json!({ "query": "q" })).await;
    assert_ne!(result.is_error, Some(true), "the search is served");

    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events).guard.as_ref().unwrap();
    assert_eq!(
        guard.scan,
        Some(bugwarden::audit::ScanInfo {
            scanned: 3,
            dropped: 0
        })
    );
    assert_eq!(guard.verdict, Verdict::Served, "a clean scan stays served");
    assert!(guard.suppressed_ids.is_empty());
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
}

#[tokio::test]
async fn quicksearch_over_summary_views_records_the_redaction_it_applied() {
    // Issue #94 at the second `note_redacted` site. Every row the scan
    // kept was projected down to a summary view, and NOTHING was dropped:
    // `scan.dropped == 0` and an empty suppression leave the redaction
    // note as the sole reason this window is a filtered serve, so a note
    // that never fires fails on the verdict as well as on the field.
    //
    // `assigned_to` is in the tool's default projection and is not a
    // `SUMMARY_FIELDS` member, so it reaches the envelope only from a row
    // served whole — the fixture cannot pass by serving full bugs.
    let mock = MockServer::start().await;
    mount_search_corpus(
        &mock,
        (1..=3)
            .map(|id| {
                let mut bug = world_bug(id);
                bug["assigned_to"] = json!("canary-assignee-9e73@example.org");
                bug
            })
            .collect(),
    )
    .await;
    let audited = audited_client_for(SUMMARY_ONLY_POLICY, &mock, "test-key").await;

    let result = call(&audited.client, "bugs_quicksearch", json!({ "query": "q" })).await;
    assert_ne!(result.is_error, Some(true), "the search is served");
    let envelope = serde_json::to_string(&result).unwrap();
    assert!(
        envelope.contains("_redacted"),
        "every row the policy kept is a summary view: {envelope}"
    );
    assert!(
        !envelope.contains("canary-assignee-9e73"),
        "and a projected row carries no field outside SUMMARY_FIELDS, \
         whatever the client asked for: {envelope}"
    );

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bugs_quicksearch");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.redacted_fields,
        vec!["summary_view".to_string()],
        "the record names the projection every served row went through, \
         once for the window however many rows it covers: {guard:?}"
    );
    assert_eq!(
        guard.verdict,
        Verdict::ServedFiltered,
        "a window of projections is a filtered serve: {guard:?}"
    );
    assert_eq!(
        guard.scan,
        Some(bugwarden::audit::ScanInfo {
            scanned: 3,
            dropped: 0
        }),
        "and it is not the scan that filtered it — every row was kept"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
    assert!(guard.suppressed_ids.is_empty());
}

#[tokio::test]
async fn quicksearch_records_no_rule_even_when_a_named_rule_judged_every_row() {
    // The other half of issue #67: a search verdict belongs to the WINDOW,
    // not to any one bug, so the record names no rule — here even though
    // `allow-openSUSE` is what granted every row it served. Asserted on a
    // CLEAN scan deliberately: once a scan drops rows it merges
    // served_filtered rule-lessly, which would clear any rule the search
    // had noted and make this assertion pass for the wrong reason.
    let policy = concat!(
        "default_action = \"deny\"\n",
        "[[rule]]\nname = \"allow-openSUSE\"\naction = \"allow\"\n",
        "[rule.match]\nproducts = [\"openSUSE\"]\n",
    );
    let mock = MockServer::start().await;
    mount_search_corpus(&mock, vec![world_bug(1), world_bug(2), world_bug(3)]).await;
    let audited = audited_client_for(policy, &mock, "test-key").await;

    let result = call(&audited.client, "bugs_quicksearch", json!({ "query": "q" })).await;
    assert_ne!(result.is_error, Some(true), "the search is served");

    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events)
        .guard
        .as_ref()
        .expect("guard info recorded");
    assert_eq!(guard.verdict, Verdict::Served, "a clean scan stays served");
    assert_eq!(guard.scan.expect("a search records its scan").dropped, 0);
    assert_eq!(
        guard.rule.as_deref(),
        None,
        "no single rule decided the window"
    );
}

#[tokio::test]
async fn canary_content_never_reaches_the_audit_file() {
    const KEY_CANARY: &str = "canary-api-key-5c9e02";
    const SUMMARY_CANARY: &str = "canary-summary-77aa01";
    const COMMENT_CANARY: &str = "canary-comment-b3f604";
    const OUTGOING_CANARY: &str = "canary-outgoing-19dd08";

    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(&mock)
        .await;
    let mut bug = world_bug(7);
    bug["summary"] = json!(SUMMARY_CANARY);
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [bug] })))
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": { "7": { "comments": [
                { "id": 1, "bug_id": 7, "is_private": false, "text": COMMENT_CANARY },
            ] } }
        })))
        .mount(&mock)
        .await;
    Mock::given(method("POST"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "id": 11 })))
        .mount(&mock)
        .await;
    let audited = audited_client_for("", &mock, KEY_CANARY).await;

    let _ = call(&audited.client, "bug_info", json!({ "bug_ids": [7] })).await;
    let _ = call(&audited.client, "bug_comments", json!({ "id": 7 })).await;
    let _ = call(
        &audited.client,
        "add_comment",
        json!({ "bug_id": 7, "comment": OUTGOING_CANARY }),
    )
    .await;

    let raw = std::fs::read_to_string(&audited.audit_path).expect("audit file readable");
    for canary in [KEY_CANARY, SUMMARY_CANARY, COMMENT_CANARY, OUTGOING_CANARY] {
        assert!(
            !raw.contains(canary),
            "canary {canary} leaked into the audit file"
        );
    }
    // The outgoing comment appears as presence + size only.
    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "add_comment");
    let expected_len = serde_json::to_vec(&json!(OUTGOING_CANARY)).unwrap().len();
    assert_eq!(
        tc.request.params["comment"],
        json!({ "_len": expected_len })
    );
}

#[tokio::test]
async fn a_client_sent_len_marker_is_distinguishable_on_the_served_path() {
    // #241, end to end: one call carries `{"_len": 5}` under an
    // allowlisted key (copied verbatim, so forgeable without the
    // reservation) and under a non-allowlisted one (reduced by the
    // server). The allowlisted side must not carry a `_len` the server
    // did not write: it is told apart by shape, never by the number.
    // Off-schema keys on bug_url are ignored by serde, so this is the
    // served path.
    let mock = MockServer::start().await;
    mount_fixture(&mock).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let _ = call(
        &audited.client,
        "bug_url",
        json!({
            "bug_id": 7,
            "groups": { "_len": 5 },
            "custom_fields": { "_len": 5 },
        }),
    )
    .await;

    let events = read_events(&audited.audit_path);
    let calls: Vec<&bugwarden::audit::ToolCallEvent> = events
        .iter()
        .filter_map(|e| match &e.kind {
            AuditEventKind::ToolCall(tc) => Some(&**tc),
            _ => None,
        })
        .collect();
    let [tc] = calls.as_slice() else {
        panic!("exactly one tool-call record, got {}", calls.len());
    };
    assert_eq!(tc.request.tool, "bug_url");
    assert_eq!(tc.outcome.class, OutcomeClass::Ok, "the served path");

    let allowlisted = &tc.request.params["groups"];
    assert!(
        allowlisted.get("_len").is_none(),
        "a client-sent marker would be indistinguishable from the reduction"
    );
    let Some([entry]) = allowlisted
        .get("_overlong_keys")
        .and_then(|v| v.as_array())
        .map(Vec::as_slice)
    else {
        panic!("the client's own _len key belongs under _overlong_keys, alone");
    };
    assert_eq!(
        entry,
        &json!({ "prefix": "_len", "key_chars": 4, "value": 5 }),
        "it is routed like any reserved name, keeping its true length"
    );
    let reduced = serde_json::to_vec(&json!({ "_len": 5 })).unwrap().len();
    assert_eq!(
        tc.request.params["custom_fields"],
        json!({ "_len": reduced }),
        "the server's own reduction, the only way _len reaches a record"
    );
}

#[tokio::test]
async fn initialize_writes_exactly_one_record_with_the_client_identity() {
    // Recorded unconditionally: auditing on means session starts are in
    // the stream — there is no configuration knob that turns this off.
    let mock = MockServer::start().await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let events = read_events(&audited.audit_path);
    assert_eq!(events.len(), 1, "the handshake writes exactly one record");
    let init = match &events[0].kind {
        AuditEventKind::Initialize(init) => init,
        other => panic!("expected an initialize record, got {other:?}"),
    };
    assert!(
        init.client.name.as_deref().is_some_and(|n| !n.is_empty()),
        "client name recorded: {init:?}"
    );
    assert!(
        init.client.version.is_some(),
        "client version recorded: {init:?}"
    );
    assert!(
        init.protocol_version.is_some(),
        "protocol version recorded: {init:?}"
    );
    // Session info anchors the stdio session to the process.
    assert_eq!(events[0].session.transport, TransportKind::Stdio);
    let id = events[0].session.id.as_deref().expect("stdio session id");
    let (pid, _) = id.split_once('-').expect("session id is <pid>-<epoch>");
    assert_eq!(pid, std::process::id().to_string());
    assert_eq!(events[0].session.remote, None);
}

/// Mount classify + padding for bug 7 and serve `comments` from its
/// comment endpoint. Deliberately minimal: a windowing call reaching for
/// an unmounted endpoint must fail, not fall through a catch-all.
async fn mount_bug7_with_comments(mock: &MockServer, comments: Vec<Value>) {
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug/7/comment"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "bugs": { "7": { "comments": comments } }
        })))
        .mount(mock)
        .await;
}

fn six_public_comments() -> Vec<Value> {
    (1..=6)
        .map(|i| {
            json!({ "id": i, "bug_id": 7, "is_private": false, "text": format!("comment {i}") })
        })
        .collect()
}

/// Named grant over the world product. The windowing tests otherwise run
/// rule-less, where the surviving rule is the literal `default` — the same
/// value a misattribution would most plausibly produce.
const ALLOW_WORLD_POLICY: &str = concat!(
    "default_action = \"deny\"\n",
    "[[rule]]\nname = \"allow-openSUSE\"\naction = \"allow\"\n",
    "[rule.match]\nproducts = [\"openSUSE\"]\n",
);

#[tokio::test]
async fn bug_comments_window_keeps_the_named_rule_that_granted_the_call() {
    // Issue #67, the strong form: the record must name the rule that
    // GRANTED the call, not merely carry some rule. `default` cannot tell
    // those apart, so this one is granted by name.
    let mock = MockServer::start().await;
    mount_bug7_with_comments(&mock, six_public_comments()).await;
    let audited = audited_client_for(ALLOW_WORLD_POLICY, &mock, "test-key").await;

    let result = call(
        &audited.client,
        "bug_comments",
        json!({ "id": 7, "head": 1, "tail": 2 }),
    )
    .await;
    assert_ne!(result.is_error, Some(true), "the window is served");

    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events)
        .guard
        .clone()
        .expect("guard info recorded");
    assert_eq!(guard.redacted_fields, vec!["comments_window".to_string()]);
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.rule.as_deref(),
        Some("allow-openSUSE"),
        "the granting rule by name, so a fallback to `default` fails here: {guard:?}"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(guard.suppressed_other_count, 0);
}

#[tokio::test]
async fn bug_comments_window_beside_an_i5_suppression_records_no_rule() {
    // The one production combination where keeping the rule would be
    // WRONG, and the one that pins the note ordering in the handler: the
    // I5 drop upgrades the verdict rule-lessly BEFORE the window notes, so
    // the guard's own decision clears the rule and the client's window
    // cannot put it back. Reverse the two notes and this goes green on a
    // record that credits `default` for a suppression it did not make.
    let mock = MockServer::start().await;
    let mut comments = six_public_comments();
    comments[5]["is_private"] = json!(true);
    mount_bug7_with_comments(&mock, comments).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let result = call(
        &audited.client,
        "bug_comments",
        json!({ "id": 7, "head": 1, "tail": 2 }),
    )
    .await;
    assert_ne!(result.is_error, Some(true), "the window is served");

    let events = read_events(&audited.audit_path);
    let guard = last_tool_call(&events)
        .guard
        .clone()
        .expect("guard info recorded");
    assert_eq!(guard.redacted_fields, vec!["comments_window".to_string()]);
    assert_eq!(guard.verdict, Verdict::ServedFiltered);
    assert_eq!(
        guard.suppressed_other_count, 1,
        "the private comment is counted, id-lessly: {guard:?}"
    );
    assert_eq!(guard.suppressed_ids_count, 0);
    assert_eq!(
        guard.rule, None,
        "a GUARD suppression upgraded the verdict, so the rule goes with \
         it — the client window beside it changes nothing: {guard:?}"
    );
}

#[tokio::test]
async fn bug_comments_window_records_the_redaction_it_applied() {
    // The #94 pin at the comments_window note site: windowing that actually
    // omits must leave its mark in the record — a note that can never fire
    // would leave the operator unable to tell a complete answer from a
    // windowed one.
    let mock = MockServer::start().await;
    mount_bug7_with_comments(&mock, six_public_comments()).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let result = call(
        &audited.client,
        "bug_comments",
        json!({ "id": 7, "head": 1, "tail": 2 }),
    )
    .await;
    assert_ne!(result.is_error, Some(true), "the window is served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_comments");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert_eq!(
        guard.redacted_fields,
        vec!["comments_window".to_string()],
        "the record names the windowing that shaped the response: {guard:?}"
    );
    assert_eq!(
        guard.rule.as_deref(),
        Some("default"),
        "and the granting rule survives: the CLIENT asked for a window, so \
         no rule decided the omission: {guard:?}"
    );
}

#[tokio::test]
async fn bug_comments_window_with_nothing_omitted_records_no_redaction() {
    // The #87/#88 sibling at the same site: windowing params present but
    // the window covers everything and nothing is capped — the note must
    // stay silent, or every call reads served-with-redaction.
    let mock = MockServer::start().await;
    mount_bug7_with_comments(&mock, six_public_comments()).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let result = call(
        &audited.client,
        "bug_comments",
        json!({ "id": 7, "head": 4, "tail": 4 }),
    )
    .await;
    assert_ne!(result.is_error, Some(true), "the window is served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.request.tool, "bug_comments");
    let guard = tc.guard.as_ref().expect("guard info recorded");
    assert!(
        guard.redacted_fields.is_empty(),
        "nothing omitted, nothing capped: no redaction is recorded: {guard:?}"
    );
}

// ---------- outcome.response_bytes (issue #145) ----------

/// Serialized length of the content the client actually received.
///
/// Computed from the client's own view of the result, so the assertion is
/// end to end: if `response_bytes` were measured off anything but the
/// payload that reached the client, this would not match. Deliberately
/// sizes `content` alone — the enclosing `CallToolResult` carries
/// `resultType`, which the SDK clears per negotiated revision.
fn content_len(result: &CallToolResult) -> u64 {
    serde_json::to_vec(&result.content)
        .expect("served content must serialize")
        .len() as u64
}

#[tokio::test]
async fn response_bytes_is_the_served_payload_length() {
    let mock = MockServer::start().await;
    mount_fixture(&mock).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let result = call(&audited.client, "bug_info", json!({ "bug_ids": [7] })).await;
    assert_ne!(result.is_error, Some(true), "bug 7 is served");

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(
        tc.outcome.response_bytes,
        Some(content_len(&result)),
        "the record sizes the content the client received"
    );
    // Block framing is real: the array is strictly larger than the text
    // it wraps, so this is not silently measuring the text alone.
    let text = match result.content.first() {
        Some(block) => block.as_text().expect("one text block").text.clone(),
        None => panic!("a served bug_info carries content"),
    };
    let bytes = tc.outcome.response_bytes.expect("measured");
    assert!(
        bytes > text.len() as u64,
        "{bytes} must exceed the {} bytes of text it wraps",
        text.len()
    );
}

#[tokio::test]
async fn a_wholly_denied_call_is_sized_by_its_id_width_and_nothing_else() {
    // WHOLLY denied — the qualifier is the point. `denied` is the WORST
    // verdict of a call, not a claim that nothing was served, so this
    // property holds only where the entire payload is the uniform denial
    // (contrast `a_partial_denial_is_sized_by_what_was_served`).
    //
    // Where it does hold: the denial text (I2) interpolates the id the
    // CALLER asked for — `Bug {id} is not accessible through this server`
    // — so its length is fixed by that id's decimal width and by nothing
    // about the bug. Both halves are pinned: two same-width ids over
    // wildly different upstream bugs must size identically (nothing about
    // the bug leaks into the size), and a wider id must cost exactly the
    // extra digits (nothing else varies). The id itself is not a
    // disclosure — the caller supplied it and `request.params` already
    // records it verbatim — and the stream reaches no MCP surface (I15).
    let policy = concat!(
        "[[rule]]\nname = \"hide-secret\"\naction = \"deny\"\n",
        "[rule.match]\nproducts = [\"Secret*\"]\n",
    );
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(&mock)
        .await;
    // 7 and 8 are the same width; 4242424 is six digits wider. Bug 8 is
    // deliberately bulky where bug 7 is minimal.
    for id in [7_u64, 8, 4_242_424] {
        let mut secret = world_bug(id);
        secret["product"] = json!("SecretSauce");
        if id == 8 {
            secret["summary"] = json!("x".repeat(4096));
            secret["whiteboard"] = json!("y".repeat(512));
            secret["keywords"] = json!(["alpha", "beta", "gamma"]);
        }
        Mock::given(method("GET"))
            .and(path("/rest/bug"))
            .and(query_param("id", id.to_string()))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [secret] })))
            .mount(&mock)
            .await;
    }
    let audited = audited_client_for(policy, &mock, "test-key").await;

    let mut sizes = Vec::new();
    for id in [7_u64, 8, 4_242_424] {
        let denied = call(&audited.client, "bug_history", json!({ "id": id })).await;
        assert_eq!(denied.is_error, Some(true), "bug {id} is denied");
        let events = read_events(&audited.audit_path);
        let tc = last_tool_call(&events);
        assert_eq!(
            tc.guard.as_ref().expect("the guard ran").verdict,
            Verdict::Denied
        );
        let bytes = tc
            .outcome
            .response_bytes
            .expect("a denial is still content");
        assert_eq!(
            bytes,
            content_len(&denied),
            "a denial is sized like any other served content"
        );
        sizes.push(bytes);
    }
    assert_eq!(
        sizes[0], sizes[1],
        "a 4KiB bug and a minimal one deny at the same size: the bug does not \
         reach the denial"
    );
    assert_eq!(
        sizes[2] - sizes[0],
        6,
        "4242424 is six digits wider than 7, and that is the whole difference"
    );
}

#[tokio::test]
async fn a_partial_denial_is_sized_by_what_was_served() {
    // The counterexample to reading `response_bytes` as "how big was the
    // refusal". `bug_info` puts served bugs and denied ones in ONE
    // envelope, and the record takes the WORST verdict of the call, so a
    // record can read `denied` over a payload carrying a full bug body.
    // Pinned because the field is easy to misread the other way: the size
    // tracks the payload, and no verdict bounds it.
    let policy = concat!(
        "[[rule]]\nname = \"hide-secret\"\naction = \"deny\"\n",
        "[rule.match]\nproducts = [\"Secret*\"]\n",
    );
    let mock = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "0"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [] })))
        .mount(&mock)
        .await;
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "7"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [world_bug(7)] })))
        .mount(&mock)
        .await;
    let mut secret = world_bug(8);
    secret["product"] = json!("SecretSauce");
    Mock::given(method("GET"))
        .and(path("/rest/bug"))
        .and(query_param("id", "8"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "bugs": [secret] })))
        .mount(&mock)
        .await;
    let audited = audited_client_for(policy, &mock, "test-key").await;

    let whole = call(&audited.client, "bug_info", json!({ "bug_ids": [8] })).await;
    let events = read_events(&audited.audit_path);
    let denied_only = last_tool_call(&events)
        .outcome
        .response_bytes
        .expect("measured");
    drop(whole);

    let partial = call(&audited.client, "bug_info", json!({ "bug_ids": [7, 8] })).await;
    assert_ne!(
        partial.is_error,
        Some(true),
        "bug 7 is still served alongside the denial"
    );
    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(
        tc.guard.as_ref().expect("the guard ran").verdict,
        Verdict::Denied,
        "worst-wins: one denied id stamps the whole record"
    );
    let bytes = tc.outcome.response_bytes.expect("measured");
    assert_eq!(
        bytes,
        content_len(&partial),
        "the record sizes the envelope"
    );
    assert!(
        bytes > denied_only,
        "{bytes} carries bug 7's body on top of the same denial ({denied_only}): a \
         `denied` record is not bounded by the refusal's width"
    );
}

#[tokio::test]
async fn a_protocol_error_records_no_response_size() {
    // No result exists, so the field is absent rather than zero: an
    // operator averaging payload size must not see errors pulled in.
    let mock = MockServer::start().await;
    mount_fixture(&mock).await;
    let audited = audited_client_for("", &mock, "test-key").await;

    let err = bounded(
        "the no_such_tool call",
        audited
            .client
            .call_tool(CallToolRequestParams::new("no_such_tool".to_string())),
    )
    .await
    .expect_err("an unknown tool is a protocol error");
    drop(err);

    let events = read_events(&audited.audit_path);
    let tc = last_tool_call(&events);
    assert_eq!(tc.outcome.class, OutcomeClass::Error);
    assert_eq!(tc.outcome.response_bytes, None, "absent, not zero");
}