eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
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
//! SRR6.46.17 — Pre-grant lane visibility audit (pure decision module).
//!
//! Before a user runs `ee mesh grant <peer> --lane <lane>` to widen the
//! conservative auto-enrollment defaults (body / embedding / graph_link
//! deny by default), they need to see EXACTLY which memories would
//! become visible. Without that surface, working out exposure requires
//! reasoning across SRR6.5 trust, SRR6.30 scope, redaction classes, and
//! memory tags — practically impossible.
//!
//! This module owns the **pure visibility computation** and its schema
//! constants. It does not touch the database, does not consult the
//! Tailscale CLI, does not emit audit rows: the caller hands in a
//! resolved slice of [`MemoryView`] (already redaction-aware), the
//! current and proposed [`IntendedLanePolicy`], the target [`Lane`]
//! being granted, and a small set of caller-side facts (peer-in-group,
//! sample strategy). The output is a fully populated
//! [`LaneGrantPreview`] envelope shaped to the documented
//! `ee.mesh.lane_grant_preview.v2` schema, ready for any renderer.
//!
//! Why a separate module rather than folding this into the auto-enroll
//! flow: (1) the preview is a pure read with a strict "no DB writes,
//! no audit rows" invariant, while auto-enroll is mutating; (2) the
//! visibility math is non-trivial and earns its own focused test
//! surface; (3) keeping the schema constants here lets the CLI and a future
//! MCP renderer consume one shape without re-deriving it.
//!
//! The `ee mesh preview-grant` CLI surface is wired to real DB inputs. An
//! `ee_mesh_preview_grant` MCP tool remains deferred; it must reuse this pure
//! computation and schema rather than introduce a second preview contract.

use std::cmp::Reverse;
#[cfg(test)]
use std::collections::BTreeSet;
use std::sync::OnceLock;

use serde::{Deserialize, Serialize};

use crate::mesh::auto_enrollment_safety::{IntendedLanePolicy, LaneDecision};
use crate::models::TrustClass;

/// JSON schema identifier for the lane-grant preview output. Held as the
/// source-of-truth constant so the renderer and the schema-lifecycle
/// drift gate agree.
pub const LANE_GRANT_PREVIEW_SCHEMA_V2: &str = "ee.mesh.lane_grant_preview.v2";

/// Copy contract bound into every authenticated approval snapshot. Copy
/// changes are consent changes: a token issued for older operator wording may
/// not authorize a mutation rendered with newer wording.
pub const LANE_GRANT_PREVIEW_COPY_VERSION: &str = "ee.mesh.lane_grant_preview.copy.v2";

/// Closed candidate-kind vocabulary for the approval-bound complete set.
pub const LANE_GRANT_MEMORY_CANDIDATE_KIND: &str = "memory";
pub const LANE_GRANT_MESH_LEDGER_EVENT_CANDIDATE_KIND: &str = "mesh_ledger_event";

/// Deterministic generation of the scanner implementation that prepares
/// redacted preview rows. The source-derived value makes a binary upgrade that
/// changes scanner behavior invalidate approvals even when the observed
/// samples and redaction-reason union happen to remain identical.
#[must_use]
pub fn lane_grant_redaction_scanner_generation() -> &'static str {
    static GENERATION: OnceLock<String> = OnceLock::new();
    GENERATION
        .get_or_init(|| {
            let mut hasher = blake3::Hasher::new();
            hasher.update(b"ee.mesh.lane_grant.redaction_scanner_generation.v1");
            hasher.update(include_bytes!("../policy/mod.rs"));
            format!("redscan1_{}", hasher.finalize().to_hex())
        })
        .as_str()
}

/// Versioned opaque-handle adapter persisted with the grant. T2.2/T3.1 can
/// migrate its private representation when stable node identities land; the
/// public preview intentionally exposes only this version and the peer ID.
pub const LANE_GRANT_TARGET_ADAPTER_VERSION: &str = "ee.mesh.grant_target.v1";

/// Degraded code emitted (informational) when the lane-grant preview
/// runs against a peer that is not in the workspace's auto-enrolled
/// peer-group. The preview still produces a valid envelope — the
/// caution surfaces the operator misunderstanding without aborting.
pub const LANE_GRANT_PREVIEW_PEER_NOT_IN_GROUP_CODE: &str = "lane_grant_preview_peer_not_in_group";

/// Degraded code emitted (info) when the proposed lane is already
/// granted in the current policy. Preview is still useful (it shows
/// what's currently exposed) but the user almost certainly didn't mean
/// to "grant" something already allowed.
pub const LANE_GRANT_PREVIEW_LANE_ALREADY_GRANTED_CODE: &str =
    "lane_grant_preview_lane_already_granted";

/// Default number of preview rows when the caller omits `--limit`.
pub const LANE_GRANT_PREVIEW_DEFAULT_LIMIT: usize = 25;

/// Hard ceiling on preview rows even when the caller passes `--limit`.
/// Prevents huge workspaces from producing 500MB+ preview envelopes.
pub const LANE_GRANT_PREVIEW_MAX_LIMIT: usize = 500;

/// Number of characters of memory body to include per preview row.
/// The body content is assumed pre-redacted by the caller; this module
/// neutralizes terminal/control formatting hazards before truncating it.
pub const LANE_GRANT_PREVIEW_CONTENT_PREVIEW_CHARS: usize = 100;

/// Threshold above which `large_volume_exposure` caution fires.
pub const LANE_GRANT_PREVIEW_LARGE_VOLUME_THRESHOLD: u64 = 1000;

/// Canonical sensitive-tag vocabulary that triggers
/// `sensitive_tags_in_exposure`. Kept here so the rule is self-evident
/// from the module surface; callers cannot extend the list (extending
/// it must land here so the schema documentation stays accurate).
pub const SENSITIVE_TAGS: &[&str] = &["secret", "private", "personal", "internal"];

// ============================================================================
// Lane and SampleStrategy enums
// ============================================================================

/// The six trust-lane channels a peer-group binding can grant or deny.
/// Matches the field names on [`IntendedLanePolicy`] one-for-one so
/// schema serialization and decision lookup share the same canonical
/// string set.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Lane {
    Metadata,
    Body,
    Embedding,
    GraphLink,
    CurationSignal,
    RevisionNotice,
}

impl Lane {
    /// Canonical wire string used in `ee.mesh.lane_grant_preview.v2`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Metadata => "metadata",
            Self::Body => "body",
            Self::Embedding => "embedding",
            Self::GraphLink => "graph_link",
            Self::CurationSignal => "curation_signal",
            Self::RevisionNotice => "revision_notice",
        }
    }

    /// Extract this lane's [`LaneDecision`] from an [`IntendedLanePolicy`].
    /// The two structs are kept in lock-step so this is a total function.
    #[must_use]
    pub fn decision_in(self, policy: &IntendedLanePolicy) -> LaneDecision {
        match self {
            Self::Metadata => policy.metadata,
            Self::Body => policy.body,
            Self::Embedding => policy.embedding,
            Self::GraphLink => policy.graph_link,
            Self::CurationSignal => policy.curation_signal,
            Self::RevisionNotice => policy.revision_notice,
        }
    }
}

/// Strategy for choosing which memories appear in the preview sample
/// when the total exposed count exceeds the requested limit.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SampleStrategy {
    /// Representative sample: deterministic shuffle by hashing
    /// `(memory_id, random_seed)` so identical inputs reproduce identical
    /// previews. "Random" is a misnomer — it is `deterministic-random`
    /// for the same seed. Pinned for test reproducibility.
    Random,
    /// Sort by trust class with [`TrustClass::HumanExplicit`] first.
    /// Useful for "what high-authority memories would leak?" audits.
    HighestTrust,
    /// Sort by `created_at_secs` descending (newest first). Useful for
    /// "what would the peer see if I granted this right now?" audits.
    MostRecent,
}

impl SampleStrategy {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Random => "random",
            Self::HighestTrust => "highest-trust",
            Self::MostRecent => "most-recent",
        }
    }
}

fn trust_score(trust_class: TrustClass) -> u8 {
    match trust_class {
        TrustClass::HumanExplicit => 6,
        TrustClass::PeerHumanAttested => 5,
        TrustClass::AgentValidated => 4,
        TrustClass::AgentAssertion => 3,
        TrustClass::CassEvidence => 2,
        TrustClass::LegacyImport => 1,
    }
}

fn is_high_trust(trust_class: TrustClass) -> bool {
    matches!(trust_class, TrustClass::HumanExplicit)
}

// ============================================================================
// Inputs
// ============================================================================

/// Per-memory facts the caller hands in. Borrowed to keep the preview
/// path allocation-light over very large memory slices.
#[derive(Clone, Copy, Debug)]
pub struct MemoryView<'a> {
    pub memory_id: &'a str,
    pub level: &'a str,
    pub kind: &'a str,
    /// Caller is responsible for any content redaction (secret-detector
    /// pass, tailscale_metadata strip, etc) before passing the body in.
    /// This module neutralizes terminal/control formatting hazards and then
    /// truncates to [`LANE_GRANT_PREVIEW_CONTENT_PREVIEW_CHARS`].
    pub content: &'a str,
    pub tags: &'a [String],
    pub trust_class: TrustClass,
    /// Names of fields the redaction pipeline already stripped from
    /// this memory before it reached us. Reported into the preview row
    /// so the operator sees exactly which fields are hidden.
    pub redacted_fields: &'a [String],
    pub created_at_secs: i64,
    pub is_tombstoned: bool,
    /// Whether the memory would still be hidden via a redaction-class
    /// rule even after the lane is granted (e.g. an `api_key`-tagged
    /// memory body never crosses the body lane). When `true`, the
    /// memory is counted in `redactedFromExposureCount` and its
    /// preview row's `wouldExposeUnderProposedPolicy` is `false`.
    pub blocked_by_redaction_class: bool,
}

/// All inputs to [`compute_lane_grant_preview`]. Pure-data; no DB
/// handle, no `&Cx`, no I/O.
#[derive(Clone, Copy, Debug)]
pub struct LaneGrantPreviewInput<'a> {
    pub peer_node_key: &'a str,
    pub peer_in_group: bool,
    pub lane: Lane,
    pub workspace_id: &'a str,
    pub current_policy: IntendedLanePolicy,
    pub proposed_policy: IntendedLanePolicy,
    pub memories: &'a [MemoryView<'a>],
    pub sample_strategy: SampleStrategy,
    /// Caller-requested cap on preview-row count. Internally clamped
    /// to [`LANE_GRANT_PREVIEW_MAX_LIMIT`].
    pub limit: usize,
    /// Names of redaction classes that the upstream pipeline already
    /// applied (e.g. `["api_key", "jwt", "tailscale_metadata"]`).
    /// Reported into the output after terminal/control hazards are
    /// deterministically neutralized.
    pub redaction_rules: &'a [String],
    /// Seed for [`SampleStrategy::Random`]. Pinned by the test layer and by
    /// the CLI's `--seed` option for reproducibility.
    pub sample_random_seed: u64,
}

// ============================================================================
// Output shapes (camelCase serde for direct envelope emission)
// ============================================================================

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PolicySnapshot {
    pub generation: String,
    pub lane: String,
    pub decision: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GrantTargetSnapshot {
    pub adapter_version: String,
    pub peer_id: String,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct MeshLedgerEventCandidateView<'a> {
    /// Immutable public event identity. No event body, body reference, URI,
    /// policy JSON, or content/event digest crosses this pure-module boundary.
    pub event_id: &'a str,
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CandidateRevisionPin {
    pub candidate_kind: String,
    pub candidate_id: String,
    pub revision_id: String,
}

/// Additional state that turns the pure visibility calculation into the
/// canonical approval snapshot. The legacy wrapper uses deterministic
/// placeholder generations; DB-backed callers must provide real values.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LaneGrantApprovalContext<'a> {
    pub target_peer_id: &'a str,
    pub grant_generation: u64,
    /// Monotonic workspace mutation generation used as the candidate-set
    /// revision fence. Memory rows are not universally immutable yet: content,
    /// trust, tombstones, and tags can change in place. The workspace generation
    /// advances for each of those source mutations, so incorporating it into
    /// every revision pin makes even an unsampled change stale without exposing
    /// a body/content hash in the public preview.
    pub candidate_revision_generation: u64,
    pub current_policy_generation: &'a str,
    pub proposed_policy_generation: &'a str,
}

#[derive(Clone, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApprovalTokenProjection {
    pub schema: String,
    pub value: String,
    pub expires_at: String,
    pub handling: String,
}

impl std::fmt::Debug for ApprovalTokenProjection {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ApprovalTokenProjection")
            .field("schema", &self.schema)
            .field("value", &"<redacted>")
            .field("expires_at", &self.expires_at)
            .field("handling", &self.handling)
            .finish()
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PreviewRow {
    #[serde(rename = "memoryId")]
    pub memory_id: String,
    #[serde(rename = "revisionId")]
    pub revision_id: String,
    pub level: String,
    pub kind: String,
    #[serde(rename = "contentPreview")]
    pub content_preview: String,
    pub tags: Vec<String>,
    #[serde(rename = "trustClass")]
    pub trust_class: String,
    #[serde(rename = "hasSensitiveTags")]
    pub has_sensitive_tags: bool,
    #[serde(rename = "redactedFields")]
    pub redacted_fields: Vec<String>,
    #[serde(rename = "wouldExposeUnderProposedPolicy")]
    pub would_expose_under_proposed_policy: bool,
}

/// Caution kind vocabulary. Held as `&'static str` constants so a
/// downstream code-taxonomy gate can statically index them.
pub mod caution_kinds {
    pub const HIGH_TRUST_CLASS_EXPOSURE: &str = "high_trust_class_exposure";
    pub const LARGE_VOLUME_EXPOSURE: &str = "large_volume_exposure";
    pub const SENSITIVE_TAGS_IN_EXPOSURE: &str = "sensitive_tags_in_exposure";
    pub const TOMBSTONED_IN_EXPOSURE: &str = "tombstoned_in_exposure";
    pub const REDACTION_ACTIVE: &str = "redaction_active";
    pub const PEER_NOT_IN_GROUP: &str = "peer_not_in_group";
    pub const LANE_ALREADY_GRANTED: &str = "lane_already_granted";
}

/// One UX hazard surfaced by the preview. Severity is one of
/// `"info" | "warning"`; an `"error"` severity would imply the preview
/// itself failed, which is not a path this pure-decision module takes.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Caution {
    pub kind: String,
    pub message: String,
    pub severity: String,
}

/// Schema-shaped envelope ready for emission via the renderer or MCP.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct LaneGrantPreview {
    pub schema: &'static str,
    #[serde(rename = "copyVersion")]
    pub copy_version: &'static str,
    #[serde(rename = "workspaceId")]
    pub workspace_id: String,
    pub target: GrantTargetSnapshot,
    pub lane: String,
    #[serde(rename = "grantGeneration")]
    pub grant_generation: u64,
    #[serde(rename = "currentPolicy")]
    pub current_policy: PolicySnapshot,
    #[serde(rename = "proposedPolicy")]
    pub proposed_policy: PolicySnapshot,
    #[serde(rename = "candidateSet")]
    pub candidate_set: Vec<CandidateRevisionPin>,
    #[serde(rename = "affectedMemoryCount")]
    pub affected_memory_count: u64,
    #[serde(rename = "affectedLedgerEventCount")]
    pub affected_ledger_event_count: u64,
    #[serde(rename = "redactedFromExposureCount")]
    pub redacted_from_exposure_count: u64,
    #[serde(rename = "previewSampleStrategy")]
    pub preview_sample_strategy: String,
    #[serde(rename = "previewSampleLimit")]
    pub preview_sample_limit: usize,
    #[serde(rename = "previewSample")]
    pub preview_sample: Vec<PreviewRow>,
    #[serde(rename = "redactionRulesApplied")]
    pub redaction_rules_applied: Vec<String>,
    #[serde(rename = "redactionScannerGeneration")]
    pub redaction_scanner_generation: String,
    #[serde(rename = "cautionCodes")]
    pub caution_codes: Vec<String>,
    pub cautions: Vec<Caution>,
    #[serde(rename = "approvalToken", skip_serializing_if = "Option::is_none")]
    pub approval_token: Option<ApprovalTokenProjection>,
}

impl LaneGrantPreview {
    /// Stable bytes authenticated by the approval token. The bearer projection
    /// is deliberately excluded so equal snapshots can receive unlinkable
    /// nonces without recursively authenticating their own token text.
    pub fn canonical_approval_snapshot_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        let mut snapshot = self.clone();
        snapshot.approval_token = None;
        serde_json::to_vec(&snapshot)
    }
}

// ============================================================================
// Core decision function
// ============================================================================

/// Compute the lane-grant preview envelope. Pure function — caller
/// supplies all facts; no DB queries, no audit emission, no I/O.
///
/// Algorithm (read-only invariant — load-bearing):
/// 1. Effective limit = `min(input.limit, MAX_LIMIT)`, or DEFAULT_LIMIT
///    when caller passed 0.
/// 2. Partition memories into "would expose" (proposed policy is
///    [`LaneDecision::Allow`] and not blocked by redaction class AND
///    not tombstoned) and "would-not-expose" (the residual).
/// 3. `affectedMemoryCount = |would_expose|`.
/// 4. `redactedFromExposureCount = #memories where
///    blocked_by_redaction_class && proposed_policy_allows_lane`.
/// 5. Apply [`SampleStrategy`] to `would_expose`, clip to the
///    effective limit, project to [`PreviewRow`]s.
/// 6. Run the caution detection rules across the entire memory set
///    (not just the sample) so volume / tag / trust signals don't
///    depend on sampling.
/// 7. Add every caller-authorized immutable mesh-ledger event identity to the
///    complete candidate set and report `affectedLedgerEventCount` exactly.
#[must_use]
pub fn compute_lane_grant_preview(input: &LaneGrantPreviewInput<'_>) -> LaneGrantPreview {
    compute_lane_grant_preview_with_context(
        input,
        &LaneGrantApprovalContext {
            target_peer_id: input.peer_node_key,
            grant_generation: 0,
            candidate_revision_generation: 0,
            current_policy_generation: "policy:unspecified",
            proposed_policy_generation: "policy:unspecified",
        },
    )
}

/// Compute the canonical v2 preview using DB/config-derived generation state.
#[must_use]
pub fn compute_lane_grant_preview_with_context(
    input: &LaneGrantPreviewInput<'_>,
    context: &LaneGrantApprovalContext<'_>,
) -> LaneGrantPreview {
    compute_lane_grant_preview_with_context_and_ledger_candidates(input, context, &[])
}

/// Compute the canonical v2 approval snapshot while binding every mesh-ledger
/// event whose lane material, or whose retained body reference for a body
/// grant, the caller's proposed outbound policy authorizes. The caller must
/// derive this slice through the production outbound policy engine; this module
/// only pins opaque identities.
#[must_use]
pub fn compute_lane_grant_preview_with_context_and_ledger_candidates(
    input: &LaneGrantPreviewInput<'_>,
    context: &LaneGrantApprovalContext<'_>,
    ledger_candidates: &[MeshLedgerEventCandidateView<'_>],
) -> LaneGrantPreview {
    let effective_limit = effective_limit(input.limit);
    let current_decision = input.lane.decision_in(&input.current_policy);
    let proposed_decision = input.lane.decision_in(&input.proposed_policy);
    let proposed_allows = proposed_decision == LaneDecision::Allow;

    let mut would_expose: Vec<&MemoryView<'_>> = Vec::with_capacity(input.memories.len());
    let mut tombstoned_blocked = 0_u64;
    let mut redacted_blocked = 0_u64;

    for memory in input.memories {
        let exposable =
            proposed_allows && !memory.is_tombstoned && !memory.blocked_by_redaction_class;
        if exposable {
            would_expose.push(memory);
            continue;
        }
        if proposed_allows && memory.is_tombstoned {
            tombstoned_blocked += 1;
        }
        if proposed_allows && memory.blocked_by_redaction_class {
            redacted_blocked += 1;
        }
    }

    let affected_memory_count = would_expose.len() as u64;

    sort_sample(
        &mut would_expose,
        input.sample_strategy,
        input.sample_random_seed,
    );
    let sample_rows: Vec<PreviewRow> = would_expose
        .iter()
        .take(effective_limit)
        .map(|memory| build_preview_row(memory, true, context.candidate_revision_generation))
        .collect();

    let cautions = collect_cautions(
        input,
        current_decision,
        proposed_decision,
        affected_memory_count,
        tombstoned_blocked,
        redacted_blocked,
    )
    .into_iter()
    .map(sanitize_preview_caution)
    .collect::<Vec<_>>();

    let mut candidate_set = input
        .memories
        .iter()
        .map(|memory| CandidateRevisionPin {
            candidate_kind: LANE_GRANT_MEMORY_CANDIDATE_KIND.to_owned(),
            candidate_id: sanitize_preview_text(memory.memory_id),
            revision_id: memory_candidate_revision_id(
                memory.memory_id,
                context.candidate_revision_generation,
            ),
        })
        .collect::<Vec<_>>();
    candidate_set.extend(
        ledger_candidates
            .iter()
            .map(|candidate| CandidateRevisionPin {
                candidate_kind: LANE_GRANT_MESH_LEDGER_EVENT_CANDIDATE_KIND.to_owned(),
                candidate_id: sanitize_preview_text(candidate.event_id),
                revision_id: mesh_ledger_event_revision_id(candidate.event_id),
            }),
    );
    candidate_set.sort();
    let caution_codes = cautions.iter().map(|item| item.kind.clone()).collect();

    LaneGrantPreview {
        schema: LANE_GRANT_PREVIEW_SCHEMA_V2,
        copy_version: LANE_GRANT_PREVIEW_COPY_VERSION,
        workspace_id: sanitize_preview_text(input.workspace_id),
        target: GrantTargetSnapshot {
            adapter_version: LANE_GRANT_TARGET_ADAPTER_VERSION.to_owned(),
            peer_id: sanitize_preview_text(context.target_peer_id),
        },
        lane: input.lane.as_str().to_owned(),
        grant_generation: context.grant_generation,
        current_policy: PolicySnapshot {
            generation: sanitize_preview_text(context.current_policy_generation),
            lane: input.lane.as_str().to_owned(),
            decision: current_decision.as_str().to_owned(),
        },
        proposed_policy: PolicySnapshot {
            generation: sanitize_preview_text(context.proposed_policy_generation),
            lane: input.lane.as_str().to_owned(),
            decision: proposed_decision.as_str().to_owned(),
        },
        candidate_set,
        affected_memory_count,
        affected_ledger_event_count: ledger_candidates.len() as u64,
        redacted_from_exposure_count: redacted_blocked,
        preview_sample_strategy: input.sample_strategy.as_str().to_owned(),
        preview_sample_limit: effective_limit,
        preview_sample: sample_rows,
        redaction_rules_applied: input
            .redaction_rules
            .iter()
            .map(|rule| sanitize_preview_text(rule))
            .collect(),
        redaction_scanner_generation: lane_grant_redaction_scanner_generation().to_owned(),
        caution_codes,
        cautions,
        approval_token: None,
    }
}

// ============================================================================
// Internal helpers
// ============================================================================

fn effective_limit(requested: usize) -> usize {
    let baseline = if requested == 0 {
        LANE_GRANT_PREVIEW_DEFAULT_LIMIT
    } else {
        requested
    };
    baseline.min(LANE_GRANT_PREVIEW_MAX_LIMIT)
}

fn build_preview_row(
    memory: &MemoryView<'_>,
    would_expose: bool,
    candidate_revision_generation: u64,
) -> PreviewRow {
    PreviewRow {
        memory_id: sanitize_preview_text(memory.memory_id),
        revision_id: memory_candidate_revision_id(memory.memory_id, candidate_revision_generation),
        level: sanitize_preview_text(memory.level),
        kind: sanitize_preview_text(memory.kind),
        content_preview: sanitize_preview_content(
            memory.content,
            LANE_GRANT_PREVIEW_CONTENT_PREVIEW_CHARS,
        ),
        tags: memory
            .tags
            .iter()
            .map(|tag| sanitize_preview_text(tag))
            .collect(),
        trust_class: memory.trust_class.as_str().to_owned(),
        has_sensitive_tags: memory_has_sensitive_tag(memory),
        redacted_fields: memory
            .redacted_fields
            .iter()
            .map(|field| sanitize_preview_text(field))
            .collect(),
        would_expose_under_proposed_policy: would_expose,
    }
}

fn memory_candidate_revision_id(memory_id: &str, candidate_revision_generation: u64) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"ee.mesh.lane_grant.candidate_revision.v1");
    hasher.update(&(memory_id.len() as u64).to_le_bytes());
    hasher.update(memory_id.as_bytes());
    hasher.update(&candidate_revision_generation.to_le_bytes());
    format!("revwg1_{}", hasher.finalize().to_hex())
}

/// Pin an immutable ledger event without turning its content/event digest into
/// an equality oracle. A newly inserted event adds a new pin and therefore
/// changes the canonical snapshot even though ledger inserts do not advance the
/// workspace memory generation.
fn mesh_ledger_event_revision_id(event_id: &str) -> String {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"ee.mesh.lane_grant.mesh_ledger_event_revision.v1");
    hasher.update(&(event_id.len() as u64).to_le_bytes());
    hasher.update(event_id.as_bytes());
    format!("revme1_{}", hasher.finalize().to_hex())
}

fn truncate_chars(value: &str, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value.to_owned();
    }
    value.chars().take(max_chars).collect()
}

/// Build terminal-safe preview text without changing ordinary Unicode.
///
/// JSON escaping alone is insufficient here: the same value is also rendered
/// for humans and authenticated as part of the approval snapshot. Replacing
/// unsafe scalar values before snapshot structs are constructed keeps those
/// three surfaces byte-for-byte aligned. A visible replacement character is
/// used instead of silently joining text that was separated by a control.
fn sanitize_preview_text(value: &str) -> String {
    value.chars().map(sanitize_preview_character).collect()
}

fn sanitize_preview_content(value: &str, max_chars: usize) -> String {
    truncate_chars(value, max_chars)
        .chars()
        .map(sanitize_preview_character)
        .collect()
}

fn sanitize_preview_character(character: char) -> char {
    if is_preview_format_hazard(character) {
        '\u{FFFD}'
    } else {
        character
    }
}

fn is_preview_format_hazard(character: char) -> bool {
    character.is_control()
        || matches!(
            character,
            // Soft/invisible separators and byte-order marks.
            '\u{00AD}'
                | '\u{180E}'
                | '\u{200B}'
                | '\u{2060}'
                | '\u{FEFF}'
                // Bidirectional marks, embeddings, overrides, isolates, and
                // deprecated directional formatting controls. Ordinary RTL
                // script characters remain unchanged.
                | '\u{061C}'
                | '\u{200E}'
                | '\u{200F}'
                | '\u{202A}'..='\u{202E}'
                | '\u{2066}'..='\u{206F}'
                // Unicode line/paragraph injection and annotation controls.
                | '\u{2028}'
                | '\u{2029}'
                | '\u{FFF9}'..='\u{FFFB}'
                // Invisible tag characters can carry misleading terminal
                // labels without contributing visible glyphs.
                | '\u{E0000}'..='\u{E007F}'
        )
}

fn sanitize_preview_caution(mut caution: Caution) -> Caution {
    caution.message = sanitize_preview_text(&caution.message);
    caution
}

fn memory_has_sensitive_tag(memory: &MemoryView<'_>) -> bool {
    memory.tags.iter().any(|tag| tag_has_sensitive_token(tag))
}

fn tag_has_sensitive_token(tag: &str) -> bool {
    tag.split(|ch: char| !ch.is_ascii_alphanumeric())
        .filter(|token| !token.is_empty())
        .any(|token| {
            SENSITIVE_TAGS
                .iter()
                .any(|sensitive| token.eq_ignore_ascii_case(sensitive))
        })
}

fn sort_sample(items: &mut [&MemoryView<'_>], strategy: SampleStrategy, seed: u64) {
    match strategy {
        SampleStrategy::HighestTrust => {
            items
                .sort_by_key(|memory| (Reverse(trust_score(memory.trust_class)), memory.memory_id));
        }
        SampleStrategy::MostRecent => {
            items.sort_by_key(|memory| (Reverse(memory.created_at_secs), memory.memory_id));
        }
        SampleStrategy::Random => {
            items.sort_by_key(|memory| deterministic_random_key(memory.memory_id, seed));
        }
    }
}

/// Deterministic per-row sort key for [`SampleStrategy::Random`]. Uses
/// blake3 of `(seed, memory_id)` so the same seed reproduces the same
/// ordering across runs (and across machines). Not cryptographic
/// strength is required — only deterministic and well-mixed.
fn deterministic_random_key(memory_id: &str, seed: u64) -> [u8; 16] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(&seed.to_le_bytes());
    hasher.update(memory_id.as_bytes());
    let mut out = [0_u8; 16];
    out.copy_from_slice(&hasher.finalize().as_bytes()[..16]);
    out
}

fn collect_cautions(
    input: &LaneGrantPreviewInput<'_>,
    current_decision: LaneDecision,
    _proposed_decision: LaneDecision,
    affected_memory_count: u64,
    tombstoned_blocked: u64,
    redacted_blocked: u64,
) -> Vec<Caution> {
    let mut cautions = Vec::new();

    if !input.peer_in_group {
        cautions.push(Caution {
            kind: caution_kinds::PEER_NOT_IN_GROUP.to_owned(),
            message: format!(
                "peer {} is enrolled but is not included in this workspace's peer-group bindings; if that membership is intended, add it, then review and freshly approve the lane because membership alone does not grant a denied lane",
                input.peer_node_key
            ),
            severity: "info".to_owned(),
        });
    }

    if current_decision == LaneDecision::Allow {
        cautions.push(Caution {
            kind: caution_kinds::LANE_ALREADY_GRANTED.to_owned(),
            message: format!(
                "lane '{}' is already granted in the current policy; this preview shows what is currently exposed",
                input.lane.as_str()
            ),
            severity: "info".to_owned(),
        });
    }

    let mut high_trust_exposure_count: u64 = 0;
    let mut sensitive_tag_exposure_count: u64 = 0;
    let proposed_allows = input.lane.decision_in(&input.proposed_policy) == LaneDecision::Allow;
    for memory in input.memories {
        let would_expose =
            proposed_allows && !memory.is_tombstoned && !memory.blocked_by_redaction_class;
        if !would_expose {
            continue;
        }
        if is_high_trust(memory.trust_class) {
            high_trust_exposure_count += 1;
        }
        if memory_has_sensitive_tag(memory) {
            sensitive_tag_exposure_count += 1;
        }
    }

    if high_trust_exposure_count > 0 {
        cautions.push(Caution {
            kind: caution_kinds::HIGH_TRUST_CLASS_EXPOSURE.to_owned(),
            message: format!(
                "{high_trust_exposure_count} memor{plural} with trust_class=human_explicit would be exposed; these are the user's directly-authored rules",
                plural = if high_trust_exposure_count == 1 { "y" } else { "ies" }
            ),
            severity: "warning".to_owned(),
        });
    }

    if affected_memory_count > LANE_GRANT_PREVIEW_LARGE_VOLUME_THRESHOLD {
        cautions.push(Caution {
            kind: caution_kinds::LARGE_VOLUME_EXPOSURE.to_owned(),
            message: format!(
                "{affected_memory_count} memories would be exposed (>{LANE_GRANT_PREVIEW_LARGE_VOLUME_THRESHOLD}); the workspace may be larger than expected"
            ),
            severity: "warning".to_owned(),
        });
    }

    if sensitive_tag_exposure_count > 0 {
        cautions.push(Caution {
            kind: caution_kinds::SENSITIVE_TAGS_IN_EXPOSURE.to_owned(),
            message: format!(
                "{sensitive_tag_exposure_count} memor{plural} tagged secret/private/personal/internal would be exposed; tag-driven scope filtering is the user's main lever to hide things",
                plural = if sensitive_tag_exposure_count == 1 { "y" } else { "ies" }
            ),
            severity: "warning".to_owned(),
        });
    }

    if tombstoned_blocked > 0 {
        cautions.push(Caution {
            kind: caution_kinds::TOMBSTONED_IN_EXPOSURE.to_owned(),
            message: format!(
                "{tombstoned_blocked} tombstoned memor{plural} would not be exposed; tombstoned status is honored",
                plural = if tombstoned_blocked == 1 { "y" } else { "ies" }
            ),
            severity: "info".to_owned(),
        });
    }

    let field_redacted_memory_count = input
        .memories
        .iter()
        .filter(|memory| !memory.redacted_fields.is_empty())
        .count() as u64;
    if redacted_blocked > 0 || field_redacted_memory_count > 0 {
        let message = match (redacted_blocked, field_redacted_memory_count) {
            (blocked, 0) => format!(
                "{blocked} memor{plural} would not be exposed because existing redaction-class rules block that lane",
                plural = if blocked == 1 { "y" } else { "ies" }
            ),
            (0, field_redacted) => format!(
                "{field_redacted} memor{plural} had sensitive fields redacted before preview or exposure; the listed redaction rules remain active",
                plural = if field_redacted == 1 { "y" } else { "ies" }
            ),
            (blocked, field_redacted) => format!(
                "{blocked} memor{blocked_plural} would not be exposed because redaction-class rules block the lane, and {field_redacted} memor{field_plural} had sensitive fields redacted before preview or exposure",
                blocked_plural = if blocked == 1 { "y" } else { "ies" },
                field_plural = if field_redacted == 1 { "y" } else { "ies" },
            ),
        };
        cautions.push(Caution {
            kind: caution_kinds::REDACTION_ACTIVE.to_owned(),
            message,
            severity: "info".to_owned(),
        });
    }

    cautions
}

// ============================================================================
// Inline tests (AGENTS.md L300-302 / bd-3usjw.62 Rule 7)
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mesh::auto_enrollment_safety::IntendedLanePolicy;

    fn tags(values: &[&str]) -> Vec<String> {
        values.iter().map(|s| (*s).to_owned()).collect()
    }

    fn empty_strings() -> Vec<String> {
        Vec::new()
    }

    fn assert_json_strings_are_terminal_safe(value: &serde_json::Value) {
        match value {
            serde_json::Value::String(text) => assert!(
                !text.chars().any(is_preview_format_hazard),
                "snapshot string retained a terminal/control hazard: {text:?}",
            ),
            serde_json::Value::Array(items) => {
                for item in items {
                    assert_json_strings_are_terminal_safe(item);
                }
            }
            serde_json::Value::Object(fields) => {
                for field in fields.values() {
                    assert_json_strings_are_terminal_safe(field);
                }
            }
            serde_json::Value::Null | serde_json::Value::Bool(_) | serde_json::Value::Number(_) => {
            }
        }
    }

    fn body_grant_proposed() -> IntendedLanePolicy {
        let mut policy = IntendedLanePolicy::conservative_default();
        policy.body = LaneDecision::Allow;
        policy
    }

    fn build_memory<'a>(
        memory_id: &'a str,
        trust_class: TrustClass,
        tag_storage: &'a [String],
        created_at_secs: i64,
        is_tombstoned: bool,
        blocked_by_redaction_class: bool,
        redacted_field_storage: &'a [String],
    ) -> MemoryView<'a> {
        MemoryView {
            memory_id,
            level: "memory",
            kind: "fact",
            content: "example content body that the peer would see if body lane is granted",
            tags: tag_storage,
            trust_class,
            redacted_fields: redacted_field_storage,
            created_at_secs,
            is_tombstoned,
            blocked_by_redaction_class,
        }
    }

    #[test]
    fn approval_token_debug_redacts_secret_value() {
        let token = ApprovalTokenProjection {
            schema: "ee.mesh.approval_token.v1".to_owned(),
            value: "eeap1_secret-bearer-material".to_owned(),
            expires_at: "2026-08-04T08:15:00Z".to_owned(),
            handling: "secret".to_owned(),
        };

        let rendered = format!("{token:?}");
        assert!(rendered.contains("<redacted>"));
        assert!(!rendered.contains("secret-bearer-material"));
    }

    #[test]
    fn redaction_scanner_generation_is_stable_and_source_derived() {
        let first = lane_grant_redaction_scanner_generation();
        let second = lane_grant_redaction_scanner_generation();
        assert_eq!(first, second);
        assert!(first.starts_with("redscan1_"));
        assert_eq!(first.len(), "redscan1_".len() + 64);
        assert!(first.strip_prefix("redscan1_").is_some_and(|suffix| {
            suffix
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
        }));
    }

    // ---- Lane <-> IntendedLanePolicy decision lookup -----------------------

    #[test]
    fn lane_decision_lookup_matches_policy_fields() {
        let policy = IntendedLanePolicy {
            metadata: LaneDecision::Allow,
            body: LaneDecision::Quarantine,
            embedding: LaneDecision::Deny,
            graph_link: LaneDecision::Deny,
            curation_signal: LaneDecision::Allow,
            revision_notice: LaneDecision::Allow,
        };
        assert_eq!(Lane::Metadata.decision_in(&policy), LaneDecision::Allow);
        assert_eq!(Lane::Body.decision_in(&policy), LaneDecision::Quarantine);
        assert_eq!(Lane::Embedding.decision_in(&policy), LaneDecision::Deny);
        assert_eq!(Lane::GraphLink.decision_in(&policy), LaneDecision::Deny);
        assert_eq!(
            Lane::CurationSignal.decision_in(&policy),
            LaneDecision::Allow
        );
        assert_eq!(
            Lane::RevisionNotice.decision_in(&policy),
            LaneDecision::Allow
        );
    }

    // ---- effective_limit clamping ------------------------------------------

    #[test]
    fn effective_limit_falls_back_to_default_when_zero() {
        assert_eq!(effective_limit(0), LANE_GRANT_PREVIEW_DEFAULT_LIMIT);
    }

    #[test]
    fn effective_limit_honors_requested_below_max() {
        assert_eq!(effective_limit(50), 50);
    }

    #[test]
    fn effective_limit_clamps_to_max() {
        assert_eq!(effective_limit(usize::MAX), LANE_GRANT_PREVIEW_MAX_LIMIT);
    }

    // ---- truncate_chars (multibyte-safe) -----------------------------------

    #[test]
    fn truncate_chars_short_returns_input_unchanged() {
        assert_eq!(truncate_chars("hello", 100), "hello");
    }

    #[test]
    fn truncate_chars_long_truncates_to_char_count_not_byte_count() {
        // 4-byte UTF-8 chars (rocket); each is one char, so 5 chars max
        let s = "🚀🚀🚀🚀🚀🚀";
        assert_eq!(truncate_chars(s, 5).chars().count(), 5);
    }

    #[test]
    fn preview_content_neutralizes_terminal_controls_before_snapshot_construction() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let hostile =
            "safe\u{1b}[31mRED\u{1b}[0m|\n|\0|\u{202E}rtl\u{202C}|\u{2066}iso\u{2069}|\u{200B}end";
        let base = build_memory(
            "hostile",
            TrustClass::AgentAssertion,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        );
        let memories = [MemoryView {
            content: hostile,
            ..base
        }];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::MostRecent,
            limit: 1,
            redaction_rules: &redaction_rules,
            sample_random_seed: 0,
        });

        let expected = "safe\u{FFFD}[31mRED\u{FFFD}[0m|\u{FFFD}|\u{FFFD}|\u{FFFD}rtl\u{FFFD}|\u{FFFD}iso\u{FFFD}|\u{FFFD}end";
        assert_eq!(preview.preview_sample[0].content_preview, expected);
        assert!(
            !preview.preview_sample[0]
                .content_preview
                .chars()
                .any(is_preview_format_hazard),
            "the constructed row must contain no terminal or Unicode formatting hazards",
        );

        let canonical = preview.canonical_approval_snapshot_bytes().unwrap();
        let canonical_text = std::str::from_utf8(&canonical).unwrap();
        for encoded_hazard in [
            r"\u001b", r"\n", r"\u0000", r"\u202e", r"\u202c", r"\u2066", r"\u2069", r"\u200b",
        ] {
            assert!(
                !canonical_text.contains(encoded_hazard),
                "canonical approval snapshot retained {encoded_hazard:?}",
            );
        }
        assert!(!canonical_text.chars().any(is_preview_format_hazard));

        let decoded: serde_json::Value = serde_json::from_slice(&canonical).unwrap();
        assert_eq!(
            decoded
                .pointer("/previewSample/0/contentPreview")
                .and_then(serde_json::Value::as_str),
            Some(expected),
        );
    }

    #[test]
    fn preview_content_preserves_ordinary_unicode_exactly() {
        let ordinary = "Café; cafe\u{0301}; עברית; العربية; 👨\u{200D}👩\u{200D}👧\u{200D}👦; 中文";
        assert_eq!(
            sanitize_preview_content(ordinary, LANE_GRANT_PREVIEW_CONTENT_PREVIEW_CHARS),
            ordinary,
        );

        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let base = build_memory(
            "ordinary-unicode",
            TrustClass::AgentAssertion,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        );
        let memories = [MemoryView {
            content: ordinary,
            ..base
        }];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::MostRecent,
            limit: 1,
            redaction_rules: &redaction_rules,
            sample_random_seed: 0,
        });

        assert_eq!(preview.preview_sample[0].content_preview, ordinary);
        let canonical = preview.canonical_approval_snapshot_bytes().unwrap();
        let decoded: serde_json::Value = serde_json::from_slice(&canonical).unwrap();
        assert_eq!(
            decoded
                .pointer("/previewSample/0/contentPreview")
                .and_then(serde_json::Value::as_str),
            Some(ordinary),
        );
    }

    #[test]
    fn every_caller_derived_snapshot_string_is_terminal_safe() {
        let hostile_tags = tags(&[
            "private\u{202E}tag",
            "family-👨\u{200D}👩\u{200D}👧\u{200D}👦",
        ]);
        let hostile_redacted_fields = tags(&["body\nsecret", "nom-Café"]);
        let memories = [MemoryView {
            memory_id: "memory\u{1B}[31m-red-👨\u{200D}👩",
            level: "episodic\r-Café",
            kind: "fact\u{200B}-中文",
            content: "body\t-Café",
            tags: &hostile_tags,
            trust_class: TrustClass::HumanExplicit,
            redacted_fields: &hostile_redacted_fields,
            created_at_secs: 1,
            is_tombstoned: false,
            blocked_by_redaction_class: false,
        }];
        let hostile_redaction_rules = tags(&["api\u{009D}key", "règle"]);
        let input = LaneGrantPreviewInput {
            peer_node_key: "node\nkey-עברית",
            peer_in_group: false,
            lane: Lane::Body,
            workspace_id: "workspace\u{1B}[2J-Café",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::MostRecent,
            limit: 1,
            redaction_rules: &hostile_redaction_rules,
            sample_random_seed: 0,
        };
        let context = LaneGrantApprovalContext {
            target_peer_id: "peer\u{202E}spoof\u{202C}-עברית",
            grant_generation: 4,
            candidate_revision_generation: 9,
            current_policy_generation: "current\n-Café",
            proposed_policy_generation: "proposed\u{2066}iso\u{2069}-中文",
        };
        let ledger_candidates = [MeshLedgerEventCandidateView {
            event_id: "event\u{202E}rtl\u{202C}-العربية",
        }];

        let preview = compute_lane_grant_preview_with_context_and_ledger_candidates(
            &input,
            &context,
            &ledger_candidates,
        );

        assert_eq!(preview.workspace_id, "workspace\u{FFFD}[2J-Café");
        assert_eq!(preview.target.peer_id, "peer\u{FFFD}spoof\u{FFFD}-עברית");
        assert_eq!(preview.current_policy.generation, "current\u{FFFD}-Café");
        assert_eq!(
            preview.proposed_policy.generation,
            "proposed\u{FFFD}iso\u{FFFD}-中文",
        );

        let memory_pin = preview
            .candidate_set
            .iter()
            .find(|candidate| candidate.candidate_kind == LANE_GRANT_MEMORY_CANDIDATE_KIND)
            .expect("memory pin");
        assert_eq!(
            memory_pin.candidate_id,
            "memory\u{FFFD}[31m-red-👨\u{200D}👩"
        );
        let ledger_pin = preview
            .candidate_set
            .iter()
            .find(|candidate| {
                candidate.candidate_kind == LANE_GRANT_MESH_LEDGER_EVENT_CANDIDATE_KIND
            })
            .expect("ledger-event pin");
        assert_eq!(ledger_pin.candidate_id, "event\u{FFFD}rtl\u{FFFD}-العربية",);

        let row = &preview.preview_sample[0];
        assert_eq!(row.memory_id, "memory\u{FFFD}[31m-red-👨\u{200D}👩");
        assert_eq!(row.level, "episodic\u{FFFD}-Café");
        assert_eq!(row.kind, "fact\u{FFFD}-中文");
        assert_eq!(row.content_preview, "body\u{FFFD}-Café");
        assert_eq!(
            row.tags,
            [
                "private\u{FFFD}tag".to_owned(),
                "family-👨\u{200D}👩\u{200D}👧\u{200D}👦".to_owned(),
            ],
        );
        assert_eq!(
            row.redacted_fields,
            ["body\u{FFFD}secret".to_owned(), "nom-Café".to_owned()],
        );
        assert_eq!(
            preview.redaction_rules_applied,
            ["api\u{FFFD}key".to_owned(), "règle".to_owned()],
        );
        let peer_caution = preview
            .cautions
            .iter()
            .find(|caution| caution.kind == caution_kinds::PEER_NOT_IN_GROUP)
            .expect("peer-not-in-group caution");
        assert!(peer_caution.message.contains("node\u{FFFD}key-עברית"));

        let rendered = serde_json::to_value(&preview).unwrap();
        assert_json_strings_are_terminal_safe(&rendered);
        let canonical = preview.canonical_approval_snapshot_bytes().unwrap();
        let decoded: serde_json::Value = serde_json::from_slice(&canonical).unwrap();
        assert_json_strings_are_terminal_safe(&decoded);
    }

    // ---- Pure compute: deny → allow lane shows everything ------------------

    #[test]
    fn body_deny_to_allow_with_non_tombstoned_non_blocked_memories_exposes_all() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [
            build_memory(
                "m1",
                TrustClass::AgentAssertion,
                &no_tags,
                1_000_000,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "m2",
                TrustClass::AgentAssertion,
                &no_tags,
                2_000_000,
                false,
                false,
                &no_redacted,
            ),
        ];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        assert_eq!(preview.affected_memory_count, 2);
        assert_eq!(preview.redacted_from_exposure_count, 0);
        assert_eq!(preview.preview_sample.len(), 2);
        assert_eq!(preview.lane, "body");
        assert_eq!(preview.current_policy.decision, "deny");
        assert_eq!(preview.proposed_policy.decision, "allow");
        assert!(
            preview
                .preview_sample
                .iter()
                .all(|row| row.would_expose_under_proposed_policy)
        );
    }

    #[test]
    fn workspace_generation_revision_pin_fences_unsampled_candidate_mutation() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [
            build_memory(
                "sampled",
                TrustClass::AgentAssertion,
                &no_tags,
                2,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "unsampled",
                TrustClass::AgentAssertion,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
        ];
        let redaction_rules = empty_strings();
        let input = LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::MostRecent,
            limit: 1,
            redaction_rules: &redaction_rules,
            sample_random_seed: 0,
        };
        let before = compute_lane_grant_preview_with_context(
            &input,
            &LaneGrantApprovalContext {
                target_peer_id: "peer-1",
                grant_generation: 3,
                candidate_revision_generation: 41,
                current_policy_generation: "policy-current",
                proposed_policy_generation: "policy-proposed",
            },
        );
        let after_unsampled_mutation = compute_lane_grant_preview_with_context(
            &input,
            &LaneGrantApprovalContext {
                target_peer_id: "peer-1",
                grant_generation: 3,
                candidate_revision_generation: 42,
                current_policy_generation: "policy-current",
                proposed_policy_generation: "policy-proposed",
            },
        );

        assert_eq!(before.preview_sample.len(), 1);
        assert_eq!(before.preview_sample[0].memory_id, "sampled");
        let before_unsampled = before
            .candidate_set
            .iter()
            .find(|candidate| {
                candidate.candidate_kind == LANE_GRANT_MEMORY_CANDIDATE_KIND
                    && candidate.candidate_id == "unsampled"
            })
            .expect("complete candidate set includes unsampled memory");
        let after_unsampled = after_unsampled_mutation
            .candidate_set
            .iter()
            .find(|candidate| {
                candidate.candidate_kind == LANE_GRANT_MEMORY_CANDIDATE_KIND
                    && candidate.candidate_id == "unsampled"
            })
            .expect("complete candidate set still includes unsampled memory");
        assert_ne!(before_unsampled.revision_id, after_unsampled.revision_id);
        assert!(before_unsampled.revision_id.starts_with("revwg1_"));
        assert!(!before_unsampled.revision_id.contains("unsampled"));
        assert_ne!(
            before.canonical_approval_snapshot_bytes().unwrap(),
            after_unsampled_mutation
                .canonical_approval_snapshot_bytes()
                .unwrap(),
            "an unsampled source mutation must stale the authenticated snapshot",
        );
    }

    #[test]
    fn immutable_ledger_event_pins_are_generic_deterministic_and_snapshot_bound() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "memory-candidate",
            TrustClass::AgentAssertion,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        )];
        let redaction_rules = empty_strings();
        let input = LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::GraphLink,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: IntendedLanePolicy {
                graph_link: LaneDecision::Allow,
                ..IntendedLanePolicy::conservative_default()
            },
            memories: &memories,
            sample_strategy: SampleStrategy::MostRecent,
            limit: 1,
            redaction_rules: &redaction_rules,
            sample_random_seed: 0,
        };
        let context = LaneGrantApprovalContext {
            target_peer_id: "peer-1",
            grant_generation: 3,
            candidate_revision_generation: 41,
            current_policy_generation: "policy-current",
            proposed_policy_generation: "policy-proposed",
        };
        let first_event = [MeshLedgerEventCandidateView {
            event_id: "mesh_evt_immutable_1",
        }];
        let first = compute_lane_grant_preview_with_context_and_ledger_candidates(
            &input,
            &context,
            &first_event,
        );
        let repeated = compute_lane_grant_preview_with_context_and_ledger_candidates(
            &input,
            &context,
            &first_event,
        );
        let second_event = [
            MeshLedgerEventCandidateView {
                event_id: "mesh_evt_immutable_1",
            },
            MeshLedgerEventCandidateView {
                event_id: "mesh_evt_immutable_2",
            },
        ];
        let after_insert = compute_lane_grant_preview_with_context_and_ledger_candidates(
            &input,
            &context,
            &second_event,
        );

        assert_eq!(first, repeated);
        assert_eq!(first.affected_ledger_event_count, 1);
        assert_eq!(after_insert.affected_ledger_event_count, 2);
        let event_pin = first
            .candidate_set
            .iter()
            .find(|candidate| {
                candidate.candidate_kind == LANE_GRANT_MESH_LEDGER_EVENT_CANDIDATE_KIND
            })
            .expect("ledger event is in the complete candidate set");
        assert_eq!(event_pin.candidate_id, "mesh_evt_immutable_1");
        assert!(event_pin.revision_id.starts_with("revme1_"));
        assert!(!event_pin.revision_id.contains("mesh_evt_immutable_1"));
        assert_ne!(
            first.canonical_approval_snapshot_bytes().unwrap(),
            after_insert.canonical_approval_snapshot_bytes().unwrap(),
            "a ledger insert must stale the snapshot without a workspace-generation change",
        );
    }

    #[test]
    fn every_public_canonical_field_is_bound_but_bearer_projection_is_not() {
        let sensitive_tags = tags(&["private"]);
        let redacted_fields = tags(&["content:api_key"]);
        let memories = [build_memory(
            "m1",
            TrustClass::HumanExplicit,
            &sensitive_tags,
            1,
            false,
            false,
            &redacted_fields,
        )];
        let redaction_rules = tags(&["api_key"]);
        let already_allowed = body_grant_proposed();
        let base = compute_lane_grant_preview_with_context(
            &LaneGrantPreviewInput {
                peer_node_key: "nodekey:test",
                peer_in_group: false,
                lane: Lane::Body,
                workspace_id: "ws-1",
                current_policy: already_allowed,
                proposed_policy: already_allowed,
                memories: &memories,
                sample_strategy: SampleStrategy::Random,
                limit: 1,
                redaction_rules: &redaction_rules,
                sample_random_seed: 7,
            },
            &LaneGrantApprovalContext {
                target_peer_id: "peer-1",
                grant_generation: 3,
                candidate_revision_generation: 41,
                current_policy_generation: "policy-current",
                proposed_policy_generation: "policy-proposed",
            },
        );
        let canonical = base.canonical_approval_snapshot_bytes().unwrap();

        macro_rules! assert_field_drift {
            ($label:literal, $mutation:expr) => {{
                let mut changed = base.clone();
                $mutation(&mut changed);
                assert_ne!(
                    changed.canonical_approval_snapshot_bytes().unwrap(),
                    canonical,
                    "{} must be authenticated by the canonical snapshot",
                    $label,
                );
            }};
        }

        assert_field_drift!("schema", |value: &mut LaneGrantPreview| value.schema =
            "ee.mesh.lane_grant_preview.test");
        assert_field_drift!("copyVersion", |value: &mut LaneGrantPreview| value
            .copy_version =
            "ee.mesh.lane_grant_preview.copy.test");
        assert_field_drift!("workspaceId", |value: &mut LaneGrantPreview| value
            .workspace_id
            .push('x'));
        assert_field_drift!("target.adapterVersion", |value: &mut LaneGrantPreview| {
            value.target.adapter_version.push('x')
        });
        assert_field_drift!("target.peerId", |value: &mut LaneGrantPreview| value
            .target
            .peer_id
            .push('x'));
        assert_field_drift!("lane", |value: &mut LaneGrantPreview| value.lane.push('x'));
        assert_field_drift!("grantGeneration", |value: &mut LaneGrantPreview| value
            .grant_generation +=
            1);
        assert_field_drift!(
            "currentPolicy.generation",
            |value: &mut LaneGrantPreview| value.current_policy.generation.push('x')
        );
        assert_field_drift!("currentPolicy.lane", |value: &mut LaneGrantPreview| value
            .current_policy
            .lane
            .push('x'));
        assert_field_drift!("currentPolicy.decision", |value: &mut LaneGrantPreview| {
            value.current_policy.decision.push('x')
        });
        assert_field_drift!(
            "proposedPolicy.generation",
            |value: &mut LaneGrantPreview| value.proposed_policy.generation.push('x')
        );
        assert_field_drift!("proposedPolicy.lane", |value: &mut LaneGrantPreview| value
            .proposed_policy
            .lane
            .push('x'));
        assert_field_drift!("proposedPolicy.decision", |value: &mut LaneGrantPreview| {
            value.proposed_policy.decision.push('x')
        });
        assert_field_drift!(
            "candidateSet.candidateKind",
            |value: &mut LaneGrantPreview| { value.candidate_set[0].candidate_kind.push('x') }
        );
        assert_field_drift!(
            "candidateSet.candidateId",
            |value: &mut LaneGrantPreview| { value.candidate_set[0].candidate_id.push('x') }
        );
        assert_field_drift!("candidateSet.revisionId", |value: &mut LaneGrantPreview| {
            value.candidate_set[0].revision_id.push('x')
        });
        assert_field_drift!("affectedMemoryCount", |value: &mut LaneGrantPreview| {
            value.affected_memory_count += 1
        });
        assert_field_drift!(
            "affectedLedgerEventCount",
            |value: &mut LaneGrantPreview| { value.affected_ledger_event_count += 1 }
        );
        assert_field_drift!(
            "redactedFromExposureCount",
            |value: &mut LaneGrantPreview| value.redacted_from_exposure_count += 1
        );
        assert_field_drift!("previewSampleStrategy", |value: &mut LaneGrantPreview| {
            value.preview_sample_strategy.push('x')
        });
        assert_field_drift!("previewSampleLimit", |value: &mut LaneGrantPreview| {
            value.preview_sample_limit += 1
        });
        assert_field_drift!("previewSample.memoryId", |value: &mut LaneGrantPreview| {
            value.preview_sample[0].memory_id.push('x')
        });
        assert_field_drift!(
            "previewSample.revisionId",
            |value: &mut LaneGrantPreview| value.preview_sample[0].revision_id.push('x')
        );
        assert_field_drift!("previewSample.level", |value: &mut LaneGrantPreview| value
            .preview_sample[0]
            .level
            .push('x'));
        assert_field_drift!("previewSample.kind", |value: &mut LaneGrantPreview| value
            .preview_sample[0]
            .kind
            .push('x'));
        assert_field_drift!(
            "previewSample.contentPreview",
            |value: &mut LaneGrantPreview| value.preview_sample[0].content_preview.push('x')
        );
        assert_field_drift!("previewSample.tags", |value: &mut LaneGrantPreview| value
            .preview_sample[0]
            .tags
            .push("extra".to_owned()));
        assert_field_drift!(
            "previewSample.trustClass",
            |value: &mut LaneGrantPreview| value.preview_sample[0].trust_class.push('x')
        );
        assert_field_drift!(
            "previewSample.hasSensitiveTags",
            |value: &mut LaneGrantPreview| {
                let row = &mut value.preview_sample[0];
                row.has_sensitive_tags = !row.has_sensitive_tags;
            }
        );
        assert_field_drift!(
            "previewSample.redactedFields",
            |value: &mut LaneGrantPreview| value.preview_sample[0]
                .redacted_fields
                .push("tag:jwt".to_owned())
        );
        assert_field_drift!(
            "previewSample.wouldExposeUnderProposedPolicy",
            |value: &mut LaneGrantPreview| value.preview_sample[0]
                .would_expose_under_proposed_policy = false
        );
        assert_field_drift!("redactionRulesApplied", |value: &mut LaneGrantPreview| {
            value.redaction_rules_applied.push("jwt".to_owned())
        });
        assert_field_drift!(
            "redactionScannerGeneration",
            |value: &mut LaneGrantPreview| value.redaction_scanner_generation.push('x')
        );
        assert_field_drift!("cautionCodes", |value: &mut LaneGrantPreview| value
            .caution_codes
            .push("extra".to_owned()));
        assert_field_drift!("cautions.kind", |value: &mut LaneGrantPreview| value
            .cautions[0]
            .kind
            .push('x'));
        assert_field_drift!("cautions.message", |value: &mut LaneGrantPreview| value
            .cautions[0]
            .message
            .push('x'));
        assert_field_drift!("cautions.severity", |value: &mut LaneGrantPreview| value
            .cautions[0]
            .severity
            .push('x'));

        let mut projected = base.clone();
        projected.approval_token = Some(ApprovalTokenProjection {
            schema: "ee.mesh.approval_token.v1".to_owned(),
            value: "eeap1_redacted-test-bearer".to_owned(),
            expires_at: "2026-08-04T08:15:00Z".to_owned(),
            handling: "secret".to_owned(),
        });
        assert_eq!(
            projected.canonical_approval_snapshot_bytes().unwrap(),
            canonical,
            "the bearer projection must not recursively authenticate itself",
        );
    }

    // ---- Read-only invariant: tombstoned + blocked are excluded ------------

    #[test]
    fn tombstoned_and_redaction_blocked_memories_are_excluded_from_exposure() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [
            build_memory(
                "live",
                TrustClass::AgentAssertion,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "tomb",
                TrustClass::AgentAssertion,
                &no_tags,
                1,
                true,
                false,
                &no_redacted,
            ),
            build_memory(
                "blocked",
                TrustClass::AgentAssertion,
                &no_tags,
                1,
                false,
                true,
                &no_redacted,
            ),
        ];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        assert_eq!(preview.affected_memory_count, 1);
        assert_eq!(preview.redacted_from_exposure_count, 1);
        assert!(
            preview
                .preview_sample
                .iter()
                .all(|row| row.memory_id == "live")
        );

        let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
        assert!(kinds.contains(caution_kinds::TOMBSTONED_IN_EXPOSURE));
        assert!(kinds.contains(caution_kinds::REDACTION_ACTIVE));
        let redaction_caution = preview
            .cautions
            .iter()
            .find(|caution| caution.kind == caution_kinds::REDACTION_ACTIVE)
            .expect("redaction_active caution present");
        assert!(redaction_caution.message.contains("would not be exposed"));
        assert!(
            redaction_caution
                .message
                .contains("redaction-class rules block that lane")
        );
    }

    #[test]
    fn field_level_redaction_emits_redaction_active_without_blocking_exposure() {
        let no_tags = empty_strings();
        let redacted_fields = tags(&["content:api_key"]);
        let memories = [build_memory(
            "redacted",
            TrustClass::AgentAssertion,
            &no_tags,
            1,
            false,
            false,
            &redacted_fields,
        )];
        let redaction_rules = tags(&["api_key"]);
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        assert_eq!(preview.affected_memory_count, 1);
        assert_eq!(preview.redacted_from_exposure_count, 0);
        assert_eq!(preview.preview_sample[0].redacted_fields, redacted_fields);
        let caution = preview
            .cautions
            .iter()
            .find(|caution| caution.kind == caution_kinds::REDACTION_ACTIVE)
            .expect("field redaction must emit redaction_active");
        assert!(caution.message.contains("had sensitive fields redacted"));
    }

    // ---- Caution: high trust exposure --------------------------------------

    #[test]
    fn high_trust_exposure_caution_fires_for_human_explicit() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "explicit-1",
            TrustClass::HumanExplicit,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        )];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::HighestTrust,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
        assert!(kinds.contains(caution_kinds::HIGH_TRUST_CLASS_EXPOSURE));
    }

    #[test]
    fn human_explicit_exposure_caution_excludes_peer_human_attested() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "peer-attested-1",
            TrustClass::PeerHumanAttested,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        )];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::HighestTrust,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        assert!(
            preview
                .cautions
                .iter()
                .all(|caution| caution.kind != caution_kinds::HIGH_TRUST_CLASS_EXPOSURE)
        );
    }

    // ---- Caution: sensitive tag exposure -----------------------------------

    #[test]
    fn sensitive_tag_exposure_caution_fires_for_canonical_tags() {
        for sensitive_tag in SENSITIVE_TAGS {
            let tag_storage = tags(&[sensitive_tag]);
            let no_redacted = empty_strings();
            let memories = [build_memory(
                "m1",
                TrustClass::AgentAssertion,
                &tag_storage,
                1,
                false,
                false,
                &no_redacted,
            )];
            let redaction_rules = empty_strings();
            let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
                peer_node_key: "nodekey:test",
                peer_in_group: true,
                lane: Lane::Body,
                workspace_id: "ws-1",
                current_policy: IntendedLanePolicy::conservative_default(),
                proposed_policy: body_grant_proposed(),
                memories: &memories,
                sample_strategy: SampleStrategy::Random,
                limit: 25,
                redaction_rules: &redaction_rules,
                sample_random_seed: 42,
            });

            let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
            assert!(
                kinds.contains(caution_kinds::SENSITIVE_TAGS_IN_EXPOSURE),
                "tag {sensitive_tag} should fire sensitive caution",
            );
            assert!(preview.preview_sample[0].has_sensitive_tags);
        }
    }

    #[test]
    fn sensitive_tag_exposure_caution_fires_for_case_and_scoped_tags() {
        let variants = [
            "Secret",
            "security:secret",
            "private-data",
            "personal_data",
            "INTERNAL",
        ];

        for variant in variants {
            let tag_storage = tags(&[variant]);
            let no_redacted = empty_strings();
            let memories = [build_memory(
                "m1",
                TrustClass::AgentAssertion,
                &tag_storage,
                1,
                false,
                false,
                &no_redacted,
            )];
            let redaction_rules = empty_strings();
            let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
                peer_node_key: "nodekey:test",
                peer_in_group: true,
                lane: Lane::Body,
                workspace_id: "ws-1",
                current_policy: IntendedLanePolicy::conservative_default(),
                proposed_policy: body_grant_proposed(),
                memories: &memories,
                sample_strategy: SampleStrategy::Random,
                limit: 25,
                redaction_rules: &redaction_rules,
                sample_random_seed: 42,
            });

            let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
            assert!(
                kinds.contains(caution_kinds::SENSITIVE_TAGS_IN_EXPOSURE),
                "tag {variant} should fire sensitive caution",
            );
            assert!(
                preview.preview_sample[0].has_sensitive_tags,
                "tag {variant} should mark the preview row sensitive",
            );
        }
    }

    #[test]
    fn sensitive_tag_exposure_caution_does_not_match_embedded_words() {
        let tag_storage = tags(&["nonsecret", "privately", "personality", "internalized"]);
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "m1",
            TrustClass::AgentAssertion,
            &tag_storage,
            1,
            false,
            false,
            &no_redacted,
        )];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
        assert!(!kinds.contains(caution_kinds::SENSITIVE_TAGS_IN_EXPOSURE));
        assert!(!preview.preview_sample[0].has_sensitive_tags);
    }

    // ---- Caution: peer not in group, lane already granted ------------------

    #[test]
    fn peer_not_in_group_caution_fires_with_explicit_severity() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "m1",
            TrustClass::AgentAssertion,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        )];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:stranger",
            peer_in_group: false,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let caution = preview
            .cautions
            .iter()
            .find(|c| c.kind == caution_kinds::PEER_NOT_IN_GROUP)
            .expect("peer_not_in_group caution present");
        assert_eq!(caution.severity, "info");
        assert!(caution.message.contains("nodekey:stranger"));
        assert!(caution.message.contains("peer-group bindings"));
    }

    #[test]
    fn lane_already_granted_caution_fires_when_current_is_allow() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "m1",
            TrustClass::AgentAssertion,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        )];
        // Current and proposed both grant body — informational case.
        let already_allow = body_grant_proposed();
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: already_allow,
            proposed_policy: already_allow,
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let caution = preview
            .cautions
            .iter()
            .find(|c| c.kind == caution_kinds::LANE_ALREADY_GRANTED)
            .expect("lane_already_granted caution present");
        assert_eq!(caution.severity, "info");
    }

    // ---- Sample strategy: HighestTrust orders human_explicit first ---------

    #[test]
    fn highest_trust_strategy_orders_peer_attestation_between_human_and_agent_validation() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [
            build_memory(
                "agent",
                TrustClass::AgentAssertion,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "explicit",
                TrustClass::HumanExplicit,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "peer-attested",
                TrustClass::PeerHumanAttested,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "validated",
                TrustClass::AgentValidated,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "external",
                TrustClass::CassEvidence,
                &no_tags,
                1,
                false,
                false,
                &no_redacted,
            ),
        ];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::HighestTrust,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let order: Vec<&str> = preview
            .preview_sample
            .iter()
            .map(|row| row.memory_id.as_str())
            .collect();
        assert_eq!(
            order,
            vec![
                "explicit",
                "peer-attested",
                "validated",
                "agent",
                "external"
            ]
        );
    }

    // ---- Sample strategy: MostRecent orders by created_at desc -------------

    #[test]
    fn most_recent_strategy_orders_newest_first() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [
            build_memory(
                "old",
                TrustClass::AgentAssertion,
                &no_tags,
                100,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "new",
                TrustClass::AgentAssertion,
                &no_tags,
                999_999,
                false,
                false,
                &no_redacted,
            ),
            build_memory(
                "middle",
                TrustClass::AgentAssertion,
                &no_tags,
                5_000,
                false,
                false,
                &no_redacted,
            ),
        ];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::MostRecent,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let order: Vec<&str> = preview
            .preview_sample
            .iter()
            .map(|row| row.memory_id.as_str())
            .collect();
        assert_eq!(order, vec!["new", "middle", "old"]);
    }

    // ---- Sample strategy: Random is deterministic for fixed seed ----------

    #[test]
    fn random_strategy_is_deterministic_for_fixed_seed() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories: Vec<MemoryView<'_>> = (0..20)
            .map(|i| {
                let id: &'static str = match i {
                    0 => "m00",
                    1 => "m01",
                    2 => "m02",
                    3 => "m03",
                    4 => "m04",
                    5 => "m05",
                    6 => "m06",
                    7 => "m07",
                    8 => "m08",
                    9 => "m09",
                    10 => "m10",
                    11 => "m11",
                    12 => "m12",
                    13 => "m13",
                    14 => "m14",
                    15 => "m15",
                    16 => "m16",
                    17 => "m17",
                    18 => "m18",
                    _ => "m19",
                };
                build_memory(
                    id,
                    TrustClass::AgentAssertion,
                    &no_tags,
                    i,
                    false,
                    false,
                    &no_redacted,
                )
            })
            .collect();
        let redaction_rules = empty_strings();

        let preview_a = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 5,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });
        let preview_b = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 5,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        let ids_a: Vec<&str> = preview_a
            .preview_sample
            .iter()
            .map(|row| row.memory_id.as_str())
            .collect();
        let ids_b: Vec<&str> = preview_b
            .preview_sample
            .iter()
            .map(|row| row.memory_id.as_str())
            .collect();
        assert_eq!(ids_a, ids_b, "same seed must produce same ordering");
    }

    #[test]
    fn random_strategy_different_seed_produces_different_ordering() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories: Vec<MemoryView<'_>> = (0..20)
            .map(|i| {
                let id: &'static str = match i {
                    0 => "m00",
                    1 => "m01",
                    2 => "m02",
                    3 => "m03",
                    4 => "m04",
                    5 => "m05",
                    6 => "m06",
                    7 => "m07",
                    8 => "m08",
                    9 => "m09",
                    10 => "m10",
                    11 => "m11",
                    12 => "m12",
                    13 => "m13",
                    14 => "m14",
                    15 => "m15",
                    16 => "m16",
                    17 => "m17",
                    18 => "m18",
                    _ => "m19",
                };
                build_memory(
                    id,
                    TrustClass::AgentAssertion,
                    &no_tags,
                    i,
                    false,
                    false,
                    &no_redacted,
                )
            })
            .collect();
        let redaction_rules = empty_strings();

        let preview_a = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 20,
            redaction_rules: &redaction_rules,
            sample_random_seed: 1,
        });
        let preview_b = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 20,
            redaction_rules: &redaction_rules,
            sample_random_seed: 2,
        });

        let ids_a: Vec<&str> = preview_a
            .preview_sample
            .iter()
            .map(|row| row.memory_id.as_str())
            .collect();
        let ids_b: Vec<&str> = preview_b
            .preview_sample
            .iter()
            .map(|row| row.memory_id.as_str())
            .collect();
        assert_ne!(ids_a, ids_b, "different seeds should rarely match");
    }

    // ---- Large volume caution fires above threshold ------------------------

    #[test]
    fn large_volume_exposure_caution_fires_above_threshold() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories: Vec<MemoryView<'_>> = (0..1500)
            .map(|i| {
                // Leak a deterministic but unique id; for >1000 elements we
                // need to allocate string storage outside the loop to keep
                // the borrow checker happy in a Vec<MemoryView<'a>>.
                let id_ref: &'static str = Box::leak(format!("m{i:04}").into_boxed_str());
                build_memory(
                    id_ref,
                    TrustClass::AgentAssertion,
                    &no_tags,
                    i,
                    false,
                    false,
                    &no_redacted,
                )
            })
            .collect();
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            proposed_policy: body_grant_proposed(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 7,
        });

        assert_eq!(preview.affected_memory_count, 1500);
        assert_eq!(preview.preview_sample.len(), 25);

        let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
        assert!(kinds.contains(caution_kinds::LARGE_VOLUME_EXPOSURE));
    }

    // ---- Proposed policy still Deny → zero exposure, zero cautions ---------

    #[test]
    fn proposed_deny_yields_zero_exposure_and_minimal_cautions() {
        let no_tags = empty_strings();
        let no_redacted = empty_strings();
        let memories = [build_memory(
            "m1",
            TrustClass::HumanExplicit,
            &no_tags,
            1,
            false,
            false,
            &no_redacted,
        )];
        let redaction_rules = empty_strings();
        let preview = compute_lane_grant_preview(&LaneGrantPreviewInput {
            peer_node_key: "nodekey:test",
            peer_in_group: true,
            lane: Lane::Body,
            workspace_id: "ws-1",
            current_policy: IntendedLanePolicy::conservative_default(),
            // Proposed leaves body=Deny (same as current); preview is a no-op.
            proposed_policy: IntendedLanePolicy::conservative_default(),
            memories: &memories,
            sample_strategy: SampleStrategy::Random,
            limit: 25,
            redaction_rules: &redaction_rules,
            sample_random_seed: 42,
        });

        assert_eq!(preview.affected_memory_count, 0);
        assert_eq!(preview.preview_sample.len(), 0);
        // No high_trust_class_exposure caution because nothing is exposed.
        let kinds: BTreeSet<&str> = preview.cautions.iter().map(|c| c.kind.as_str()).collect();
        assert!(!kinds.contains(caution_kinds::HIGH_TRUST_CLASS_EXPOSURE));
        assert!(!kinds.contains(caution_kinds::LARGE_VOLUME_EXPOSURE));
    }

    // ---- Schema constant is the documented version -------------------------

    #[test]
    fn schema_constant_is_documented_version() {
        assert_eq!(
            LANE_GRANT_PREVIEW_SCHEMA_V2,
            "ee.mesh.lane_grant_preview.v2"
        );
    }
}