ripr 0.9.0

Find static mutation-exposure gaps before expensive mutation testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
//! Fact-layer cache for repo seam analysis (`cache/repo-seam-facts-v1`).
//!
//! Caches `Vec<ClassifiedSeam>` keyed on the aggregate workspace state
//! (per-file content hashes, cfg/features, config, test intent,
//! suppressions, analyzer version, schema version). The cold path
//! computes the inventory from scratch and writes the entry; the warm
//! path returns the cached entry when the key matches; corrupt entries
//! degrade to `Miss` so analysis never fails because of cache state.
//!
//! Per Campaign 5A acceptance:
//!
//! - cache fact layers only — `FileFacts`, owner index, `RepoSeam` facts,
//!   `TestGripEvidence`, `ClassifiedSeam` summaries. v1 caches the
//!   workspace-level `Vec<ClassifiedSeam>` (which transitively covers
//!   the listed layers) and per-file `FileFacts` so timed-out cold paths can
//!   still make the next run cheaper.
//! - never cache rendered JSON, Markdown, diagnostics, hover, or packet
//!   strings. The renderers re-render from the cached facts.
//! - codec stays behind a module boundary
//!   ([`codec::encode`] / [`codec::decode`]).
//! - never `bincode`. v1 uses `serde_json` (inspectable, easy to debug).
//!   `postcard` is the binary path if profiling later proves it
//!   necessary; the codec module is the only place that needs to change.
//!
//! The cache directory lives at:
//!
//! ```text
//! {workspace_root}/target/ripr/cache/repo-seam-facts/{schema_version}/{key_hash}.json
//! ```
//!
//! `{key_hash}` is the FNV-1a 64-bit hash of the canonical key fields,
//! so different keys land in different files and a v1 cache hit on a
//! v0.5 entry is impossible.

use super::facts::FileFacts;
use super::seam_classification::ClassifiedSeam;
#[cfg(test)]
use super::seam_classification::SeamGripClassCounts;
use std::path::{Path, PathBuf};

/// Cache schema version. Bump when the on-disk file shape changes; old
/// directories can be deleted on `cargo clean` or manually.
///
/// `0.1` → `0.2`: `RelatedTestGrip` gained `relation_reason` and
/// `relation_confidence` fields in `analysis/related-test-precision-v1`.
/// Old envelopes lack those fields and would fail serde deserialization
/// of the new shape; the version bump routes new entries to a fresh
/// directory and lets old entries go orphaned (gc'd on `cargo clean`).
pub(crate) const CACHE_SCHEMA_VERSION: &str = "0.2";
const SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.1";

/// Compact-classified seam cache schema. This cache stores the same
/// `ClassifiedSeam` envelope shape as the full repo exposure cache, but
/// under a separate directory because the evidence payload is intentionally
/// compact and must never satisfy full repo-exposure consumers.
pub(crate) const COMPACT_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION: &str = "0.1";

/// Compact class-count cache used by repo badge rendering. It keys off
/// the same workspace state as the full fact cache, but stores only
/// per-class counts so badge endpoints never need to deserialize the
/// multi-hundred-megabyte evidence cache.
#[cfg(test)]
const COUNT_CACHE_SCHEMA_VERSION: &str = "0.1";

/// Per-file fact cache schema. This is intentionally separate from the
/// workspace-level classified seam cache so warm compute can reuse parser facts
/// even when a full classified seam entry has not been written yet.
const FILE_FACT_CACHE_SCHEMA_VERSION: &str = "0.1";

/// Keep the best-effort classified-seam cache from turning a successful live
/// analysis into an unbounded post-analysis stall on large repos. Larger live
/// audits should surface a named cache-store limitation instead of spending the
/// remaining audit budget on full-evidence JSON serialization.
pub(crate) const CLASSIFIED_SEAM_CACHE_STORE_LIMIT: usize = 20_000;
pub(crate) const CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV: &str = "RIPR_REPO_SEAM_CACHE_LIMIT";
pub(crate) const COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT: usize = 100_000;
pub(crate) const COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV: &str =
    "RIPR_COMPACT_REPO_SEAM_CACHE_MAX_SEAMS";

pub(crate) fn classified_seam_cache_store_limit() -> Result<usize, String> {
    classified_seam_cache_store_limit_from_env(std::env::var(CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV))
}

fn classified_seam_cache_store_limit_from_env(
    value: Result<String, std::env::VarError>,
) -> Result<usize, String> {
    seam_cache_store_limit_from_env(
        value,
        CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV,
        CLASSIFIED_SEAM_CACHE_STORE_LIMIT,
    )
}

pub(crate) fn compact_classified_seam_cache_store_limit() -> Result<usize, String> {
    compact_classified_seam_cache_store_limit_from_env(std::env::var(
        COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV,
    ))
}

fn compact_classified_seam_cache_store_limit_from_env(
    value: Result<String, std::env::VarError>,
) -> Result<usize, String> {
    seam_cache_store_limit_from_env(
        value,
        COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV,
        COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT,
    )
}

fn seam_cache_store_limit_from_env(
    value: Result<String, std::env::VarError>,
    env_name: &str,
    default_limit: usize,
) -> Result<usize, String> {
    match value {
        Ok(value) => parse_positive_seam_cache_store_limit(&value, env_name),
        Err(std::env::VarError::NotPresent) => Ok(default_limit),
        Err(std::env::VarError::NotUnicode(_)) => Err(format!("{env_name} must be valid UTF-8")),
    }
}

fn parse_positive_seam_cache_store_limit(value: &str, env_name: &str) -> Result<usize, String> {
    let trimmed = value.trim();
    let parsed = trimmed
        .parse::<usize>()
        .map_err(|err| format!("{env_name} must be a positive integer: {err}"))?;
    if parsed == 0 {
        return Err(format!("{env_name} must be a positive integer"));
    }
    Ok(parsed)
}

/// Aggregate cache key — every field that, when changed, must invalidate
/// the workspace-level classified seam cache.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct RepoSeamCacheKey {
    pub(crate) schema_version: String,
    pub(crate) analyzer_version: String,
    pub(crate) workspace_root_hash: String,
    pub(crate) files_content_hash: String,
    pub(crate) cfg_features_hash: String,
    pub(crate) config_hash: String,
    pub(crate) test_intent_hash: String,
    pub(crate) suppressions_hash: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct RepoFileFactCacheKey {
    schema_version: String,
    analyzer_version: String,
    file_path: PathBuf,
    content_hash: String,
}

impl RepoFileFactCacheKey {
    pub(crate) fn new(file_path: &Path, content: &[u8]) -> Self {
        Self {
            schema_version: FILE_FACT_CACHE_SCHEMA_VERSION.to_string(),
            analyzer_version: env!("CARGO_PKG_VERSION").to_string(),
            file_path: file_path.to_path_buf(),
            content_hash: hash_bytes(content),
        }
    }

    fn filename(&self) -> String {
        let file_path = self.file_path.to_string_lossy();
        let parts = [
            self.schema_version.as_str(),
            self.analyzer_version.as_str(),
            file_path.as_ref(),
            self.content_hash.as_str(),
        ];
        let mut buf = String::new();
        for (idx, part) in parts.iter().enumerate() {
            if idx > 0 {
                buf.push('\0');
            }
            buf.push_str(part);
        }
        format!("{:016x}.json", fnv1a_64(buf.as_bytes()))
    }
}

impl RepoSeamCacheKey {
    /// Filename component derived from the canonical key fields. The
    /// FNV-1a 64-bit hash is stable across releases (unlike
    /// `DefaultHasher`) and produces a 16-char lowercase hex string.
    pub(crate) fn filename(&self) -> String {
        let parts: [&str; 8] = [
            &self.schema_version,
            &self.analyzer_version,
            &self.workspace_root_hash,
            &self.files_content_hash,
            &self.cfg_features_hash,
            &self.config_hash,
            &self.test_intent_hash,
            &self.suppressions_hash,
        ];
        let mut buf = String::new();
        for (i, p) in parts.iter().enumerate() {
            if i > 0 {
                buf.push('\0');
            }
            buf.push_str(p);
        }
        format!("{:016x}.json", fnv1a_64(buf.as_bytes()))
    }
}

/// Outcome of a cache load. `CorruptIgnored` exists so analysis can
/// continue when an entry is unreadable, malformed, or references a
/// schema we no longer accept.
#[derive(Debug)]
pub(crate) enum CacheLoad<T> {
    Hit(T),
    Miss,
    CorruptIgnored { reason: String },
}

/// Inputs the analysis pipeline collects to derive the cache key. Held
/// separately so the test pyramid can construct a known state without
/// touching the filesystem.
pub(crate) struct WorkspaceState<'a> {
    pub(crate) workspace_root: &'a Path,
    /// `(canonical relative path, content bytes)` for every Rust file
    /// the inventory will index — production **seam sources** plus test
    /// **evidence sources**. `ClassifiedSeam` carries `TestGripEvidence`
    /// derived from test files, so a test-only edit must invalidate the
    /// cache; restricting this to production files would let stale grip
    /// evidence survive a test rewrite. Order does not matter — the
    /// hash sorts before mixing.
    pub(crate) files: &'a [(PathBuf, Vec<u8>)],
    pub(crate) cfg_features: Option<&'a str>,
    pub(crate) config_text: Option<&'a str>,
    pub(crate) test_intent_text: Option<&'a str>,
    pub(crate) suppressions_text: Option<&'a str>,
}

impl<'a> WorkspaceState<'a> {
    pub(crate) fn cache_key(&self) -> RepoSeamCacheKey {
        let workspace_root_hash = hash_str(&self.workspace_root.to_string_lossy());

        // Sort by path so file walk order does not change the hash.
        let mut sorted_files: Vec<(&PathBuf, &Vec<u8>)> =
            self.files.iter().map(|(p, b)| (p, b)).collect();
        sorted_files.sort_by(|a, b| a.0.cmp(b.0));
        let mut files_buf = String::new();
        for (path, content) in sorted_files {
            files_buf.push_str(&path.to_string_lossy().replace('\\', "/"));
            files_buf.push('\0');
            files_buf.push_str(&hash_bytes(content));
            files_buf.push('\n');
        }
        let files_content_hash = hash_str(&files_buf);

        RepoSeamCacheKey {
            schema_version: CACHE_SCHEMA_VERSION.to_string(),
            analyzer_version: env!("CARGO_PKG_VERSION").to_string(),
            workspace_root_hash,
            files_content_hash,
            cfg_features_hash: hash_str(self.cfg_features.unwrap_or("")),
            config_hash: hash_str(self.config_text.unwrap_or("")),
            test_intent_hash: hash_str(self.test_intent_text.unwrap_or("")),
            suppressions_hash: hash_str(self.suppressions_text.unwrap_or("")),
        }
    }
}

/// Crate-private cache I/O surface. Holds the directory the cache lives
/// in but not in-memory state; safe to construct cheaply per call.
pub(crate) struct RepoSeamFactCache {
    dir: PathBuf,
    sharded_dir: PathBuf,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct CacheStoreStatus {
    pub(crate) label: String,
}

impl RepoSeamFactCache {
    /// Construct a cache rooted at the workspace's `target/ripr/cache/...`.
    pub(crate) fn at(workspace_root: &Path) -> Self {
        Self::at_named(workspace_root, "repo-seam-facts", CACHE_SCHEMA_VERSION)
    }

    /// Construct the separate compact-classified cache used by repo badge
    /// projection. It deliberately does not share entries with full repo
    /// exposure because compact evidence omits the large related-test payload.
    pub(crate) fn at_compact_classified(workspace_root: &Path) -> Self {
        Self::at_named(
            workspace_root,
            "repo-compact-classified-seams",
            COMPACT_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION,
        )
    }

    fn at_named(workspace_root: &Path, cache_name: &str, schema_version: &str) -> Self {
        let cache_root = workspace_root.join("target").join("ripr").join("cache");
        Self {
            dir: cache_root.join(cache_name).join(schema_version),
            sharded_dir: cache_root
                .join(format!("{cache_name}-sharded"))
                .join(schema_version)
                .join(SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION),
        }
    }

    /// Construct a cache at an explicit directory (tests use this to
    /// avoid touching the real workspace).
    #[cfg(test)]
    pub(crate) fn at_dir(dir: PathBuf) -> Self {
        Self {
            sharded_dir: dir.join("sharded"),
            dir,
        }
    }

    /// Look up classified seams by key. `Miss` is returned for both
    /// "no file" and "different key", so callers do not have to
    /// distinguish in v1. `CorruptIgnored` carries a reason for logs.
    pub(crate) fn load_classified_seams(
        &self,
        key: &RepoSeamCacheKey,
    ) -> CacheLoad<Vec<ClassifiedSeam>> {
        match self.load_single_classified_seams(key) {
            CacheLoad::Miss => self.load_sharded_classified_seams(key),
            other => other,
        }
    }

    fn load_single_classified_seams(
        &self,
        key: &RepoSeamCacheKey,
    ) -> CacheLoad<Vec<ClassifiedSeam>> {
        let path = self.entry_path(key);
        let bytes = match std::fs::read(&path) {
            Ok(b) => b,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return CacheLoad::Miss,
            Err(err) => {
                return CacheLoad::CorruptIgnored {
                    reason: format!("read failed: {err}"),
                };
            }
        };
        match codec::decode(&bytes) {
            Ok(envelope) => {
                if envelope.matches_key(key) {
                    CacheLoad::Hit(envelope.classified_seams)
                } else {
                    // Key collision is unlikely (16-char FNV file
                    // names + 8 fields hashed in), but possible. Treat
                    // as miss without failing analysis.
                    CacheLoad::Miss
                }
            }
            Err(reason) => CacheLoad::CorruptIgnored { reason },
        }
    }

    pub(crate) fn store_compact_classified_seams_with_limit(
        &self,
        key: &RepoSeamCacheKey,
        seams: &[ClassifiedSeam],
        store_limit: usize,
    ) -> Result<CacheStoreStatus, String> {
        self.store_classified_seams_with_limit(key, seams, store_limit)
    }

    pub(crate) fn store_classified_seams_with_limit(
        &self,
        key: &RepoSeamCacheKey,
        seams: &[ClassifiedSeam],
        store_limit: usize,
    ) -> Result<CacheStoreStatus, String> {
        if store_limit == 0 {
            return Err("classified seam cache store limit must be positive".to_string());
        }
        if seams.len() > store_limit {
            return self.store_sharded_classified_seams_with_limit(key, seams, store_limit);
        }
        std::fs::create_dir_all(&self.dir)
            .map_err(|err| format!("create cache dir failed: {err}"))?;
        let envelope = CacheEnvelope::new(key.clone(), seams.to_vec());
        let bytes = codec::encode(&envelope)?;
        let path = self.entry_path(key);
        std::fs::write(&path, &bytes).map_err(|err| format!("write cache failed: {err}"))?;
        Ok(CacheStoreStatus {
            label: "ok".to_string(),
        })
    }

    fn entry_path(&self, key: &RepoSeamCacheKey) -> PathBuf {
        self.dir.join(key.filename())
    }

    fn load_sharded_classified_seams(
        &self,
        key: &RepoSeamCacheKey,
    ) -> CacheLoad<Vec<ClassifiedSeam>> {
        let manifest_path = self.sharded_manifest_path(key);
        let bytes = match std::fs::read(&manifest_path) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return CacheLoad::Miss,
            Err(err) => {
                return CacheLoad::CorruptIgnored {
                    reason: format!("read sharded manifest failed: {err}"),
                };
            }
        };
        let manifest = match codec::decode_sharded_manifest(&bytes) {
            Ok(manifest) => manifest,
            Err(reason) => return CacheLoad::CorruptIgnored { reason },
        };
        if !manifest.matches_key(key) {
            return CacheLoad::Miss;
        }
        if manifest.shards.is_empty() && manifest.total_seams != 0 {
            return CacheLoad::CorruptIgnored {
                reason: "sharded manifest has no shards for non-empty seam payload".to_string(),
            };
        }
        if manifest.shard_count != manifest.shards.len() {
            return CacheLoad::CorruptIgnored {
                reason: format!(
                    "sharded manifest expected {} shards but listed {}",
                    manifest.shard_count,
                    manifest.shards.len()
                ),
            };
        }

        let mut seams = Vec::with_capacity(manifest.total_seams);
        for (index, shard) in manifest.shards.iter().enumerate() {
            if shard.index != index {
                return CacheLoad::CorruptIgnored {
                    reason: format!(
                        "sharded manifest index mismatch at position {index}: {}",
                        shard.index
                    ),
                };
            }
            let shard_path = self.sharded_entry_dir(key).join(&shard.file);
            let bytes = match std::fs::read(&shard_path) {
                Ok(bytes) => bytes,
                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                    return CacheLoad::CorruptIgnored {
                        reason: format!("missing sharded cache file {}", shard_path.display()),
                    };
                }
                Err(err) => {
                    return CacheLoad::CorruptIgnored {
                        reason: format!("read sharded cache file failed: {err}"),
                    };
                }
            };
            let envelope = match codec::decode_shard(&bytes) {
                Ok(envelope) => envelope,
                Err(reason) => return CacheLoad::CorruptIgnored { reason },
            };
            if !envelope.matches_key(key) {
                return CacheLoad::CorruptIgnored {
                    reason: format!("sharded cache key mismatch in {}", shard.file),
                };
            }
            if envelope.sharded_cache_schema_version != manifest.sharded_cache_schema_version
                || envelope.shard_index != shard.index
                || envelope.shard_count != manifest.shard_count
            {
                return CacheLoad::CorruptIgnored {
                    reason: format!("sharded cache metadata mismatch in {}", shard.file),
                };
            }
            if envelope.classified_seams.len() != shard.seams {
                return CacheLoad::CorruptIgnored {
                    reason: format!(
                        "sharded cache file {} carried {} seams but manifest expected {}",
                        shard.file,
                        envelope.classified_seams.len(),
                        shard.seams
                    ),
                };
            }
            seams.extend(envelope.classified_seams);
        }
        if seams.len() != manifest.total_seams {
            return CacheLoad::CorruptIgnored {
                reason: format!(
                    "sharded cache loaded {} seams but manifest expected {}",
                    seams.len(),
                    manifest.total_seams
                ),
            };
        }
        CacheLoad::Hit(seams)
    }

    fn store_sharded_classified_seams_with_limit(
        &self,
        key: &RepoSeamCacheKey,
        seams: &[ClassifiedSeam],
        store_limit: usize,
    ) -> Result<CacheStoreStatus, String> {
        std::fs::create_dir_all(self.sharded_entry_dir(key))
            .map_err(|err| format!("create sharded cache dir failed: {err}"))?;
        let shard_count = seams.len().div_ceil(store_limit);
        let mut shard_refs = Vec::with_capacity(shard_count);
        for (index, chunk) in seams.chunks(store_limit).enumerate() {
            let file = format!("shard-{index:05}.json");
            let envelope =
                ShardedCacheEnvelope::new(key.clone(), index, shard_count, chunk.to_vec());
            let bytes = codec::encode_shard(&envelope)?;
            let path = self.sharded_entry_dir(key).join(&file);
            std::fs::write(&path, &bytes)
                .map_err(|err| format!("write sharded cache file failed: {err}"))?;
            shard_refs.push(ShardedCacheShardRef {
                index,
                file,
                seams: chunk.len(),
            });
        }
        let manifest = ShardedCacheManifest::new(key.clone(), seams.len(), shard_count, shard_refs);
        let bytes = codec::encode_sharded_manifest(&manifest)?;
        let manifest_path = self.sharded_manifest_path(key);
        std::fs::write(&manifest_path, bytes)
            .map_err(|err| format!("write sharded cache manifest failed: {err}"))?;
        Ok(CacheStoreStatus {
            label: format!(
                "sharded_ok_seams_{}_shards_{}_limit_{}",
                seams.len(),
                shard_count,
                store_limit
            ),
        })
    }

    fn sharded_entry_dir(&self, key: &RepoSeamCacheKey) -> PathBuf {
        self.sharded_dir
            .join(key.filename().trim_end_matches(".json"))
    }

    fn sharded_manifest_path(&self, key: &RepoSeamCacheKey) -> PathBuf {
        self.sharded_entry_dir(key).join("manifest.json")
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct FileFactCacheStats {
    pub(crate) hits: usize,
    pub(crate) misses: usize,
    pub(crate) corrupt_ignored: usize,
    pub(crate) stores: usize,
    pub(crate) store_errors: usize,
}

impl FileFactCacheStats {
    pub(crate) fn status_label(&self) -> String {
        format!(
            "hits_{}_misses_{}_corrupt_{}_store_errors_{}",
            self.hits, self.misses, self.corrupt_ignored, self.store_errors
        )
    }
}

pub(crate) struct RepoFileFactCache {
    dir: PathBuf,
}

impl RepoFileFactCache {
    pub(crate) fn at(workspace_root: &Path) -> Self {
        Self {
            dir: workspace_root
                .join("target")
                .join("ripr")
                .join("cache")
                .join("repo-file-facts")
                .join(FILE_FACT_CACHE_SCHEMA_VERSION),
        }
    }

    #[cfg(test)]
    pub(crate) fn at_dir(dir: PathBuf) -> Self {
        Self { dir }
    }

    pub(crate) fn load_file_facts(&self, key: &RepoFileFactCacheKey) -> CacheLoad<FileFacts> {
        let path = self.entry_path(key);
        let bytes = match std::fs::read(&path) {
            Ok(bytes) => bytes,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return CacheLoad::Miss,
            Err(err) => {
                return CacheLoad::CorruptIgnored {
                    reason: format!("read failed: {err}"),
                };
            }
        };
        match codec::decode_file_facts(&bytes) {
            Ok(envelope) => {
                if envelope.matches_key(key) {
                    CacheLoad::Hit(envelope.file_facts)
                } else {
                    CacheLoad::Miss
                }
            }
            Err(reason) => CacheLoad::CorruptIgnored { reason },
        }
    }

    pub(crate) fn store_file_facts(
        &self,
        key: &RepoFileFactCacheKey,
        facts: &FileFacts,
    ) -> Result<(), String> {
        std::fs::create_dir_all(&self.dir)
            .map_err(|err| format!("create file fact cache dir failed: {err}"))?;
        let envelope = FileFactCacheEnvelope::new(key.clone(), facts.clone());
        let bytes = codec::encode_file_facts(&envelope)?;
        std::fs::write(self.entry_path(key), bytes)
            .map_err(|err| format!("write file fact cache failed: {err}"))?;
        Ok(())
    }

    fn entry_path(&self, key: &RepoFileFactCacheKey) -> PathBuf {
        self.dir.join(key.filename())
    }
}

/// Compact cache for [`SeamGripClassCounts`].
#[cfg(test)]
pub(crate) struct RepoSeamCountCache {
    dir: PathBuf,
}

#[cfg(test)]
impl RepoSeamCountCache {
    /// Construct a count cache rooted at the workspace's
    /// `target/ripr/cache/...`.
    pub(crate) fn at(workspace_root: &Path) -> Self {
        Self {
            dir: workspace_root
                .join("target")
                .join("ripr")
                .join("cache")
                .join("repo-seam-counts")
                .join(COUNT_CACHE_SCHEMA_VERSION),
        }
    }

    pub(crate) fn load_counts(&self, key: &RepoSeamCacheKey) -> CacheLoad<SeamGripClassCounts> {
        let path = self.entry_path(key);
        let bytes = match std::fs::read(&path) {
            Ok(b) => b,
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return CacheLoad::Miss,
            Err(err) => {
                return CacheLoad::CorruptIgnored {
                    reason: format!("read failed: {err}"),
                };
            }
        };
        match codec::decode_counts(&bytes) {
            Ok(envelope) => {
                if envelope.matches_key(key) {
                    CacheLoad::Hit(envelope.counts)
                } else {
                    CacheLoad::Miss
                }
            }
            Err(reason) => CacheLoad::CorruptIgnored { reason },
        }
    }

    pub(crate) fn store_counts(
        &self,
        key: &RepoSeamCacheKey,
        counts: &SeamGripClassCounts,
    ) -> Result<(), String> {
        std::fs::create_dir_all(&self.dir)
            .map_err(|err| format!("create count cache dir failed: {err}"))?;
        let envelope = CountCacheEnvelope::new(key.clone(), counts.clone());
        let bytes = codec::encode_counts(&envelope)?;
        let path = self.entry_path(key);
        std::fs::write(&path, &bytes).map_err(|err| format!("write count cache failed: {err}"))?;
        Ok(())
    }

    fn entry_path(&self, key: &RepoSeamCacheKey) -> PathBuf {
        self.dir.join(key.filename())
    }
}

/// On-disk shape. The key is embedded so callers can verify on read
/// even though the filename already encodes a hash of the same fields.
#[derive(serde::Serialize, serde::Deserialize)]
struct CacheEnvelope {
    schema_version: String,
    analyzer_version: String,
    workspace_root_hash: String,
    files_content_hash: String,
    cfg_features_hash: String,
    config_hash: String,
    test_intent_hash: String,
    suppressions_hash: String,
    classified_seams: Vec<ClassifiedSeam>,
}

#[cfg(test)]
#[derive(serde::Serialize, serde::Deserialize)]
struct CountCacheEnvelope {
    count_cache_schema_version: String,
    schema_version: String,
    analyzer_version: String,
    workspace_root_hash: String,
    files_content_hash: String,
    cfg_features_hash: String,
    config_hash: String,
    test_intent_hash: String,
    suppressions_hash: String,
    counts: SeamGripClassCounts,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct FileFactCacheEnvelope {
    file_fact_cache_schema_version: String,
    analyzer_version: String,
    file_path: PathBuf,
    content_hash: String,
    file_facts: FileFacts,
}

impl FileFactCacheEnvelope {
    fn new(key: RepoFileFactCacheKey, file_facts: FileFacts) -> Self {
        Self {
            file_fact_cache_schema_version: key.schema_version,
            analyzer_version: key.analyzer_version,
            file_path: key.file_path,
            content_hash: key.content_hash,
            file_facts,
        }
    }

    fn matches_key(&self, key: &RepoFileFactCacheKey) -> bool {
        self.file_fact_cache_schema_version == key.schema_version
            && self.analyzer_version == key.analyzer_version
            && self.file_path == key.file_path
            && self.content_hash == key.content_hash
    }
}

#[cfg(test)]
impl CountCacheEnvelope {
    fn new(key: RepoSeamCacheKey, counts: SeamGripClassCounts) -> Self {
        Self {
            count_cache_schema_version: COUNT_CACHE_SCHEMA_VERSION.to_string(),
            schema_version: key.schema_version,
            analyzer_version: key.analyzer_version,
            workspace_root_hash: key.workspace_root_hash,
            files_content_hash: key.files_content_hash,
            cfg_features_hash: key.cfg_features_hash,
            config_hash: key.config_hash,
            test_intent_hash: key.test_intent_hash,
            suppressions_hash: key.suppressions_hash,
            counts,
        }
    }

    fn matches_key(&self, key: &RepoSeamCacheKey) -> bool {
        self.count_cache_schema_version == COUNT_CACHE_SCHEMA_VERSION
            && self.schema_version == key.schema_version
            && self.analyzer_version == key.analyzer_version
            && self.workspace_root_hash == key.workspace_root_hash
            && self.files_content_hash == key.files_content_hash
            && self.cfg_features_hash == key.cfg_features_hash
            && self.config_hash == key.config_hash
            && self.test_intent_hash == key.test_intent_hash
            && self.suppressions_hash == key.suppressions_hash
    }
}

impl CacheEnvelope {
    fn new(key: RepoSeamCacheKey, classified_seams: Vec<ClassifiedSeam>) -> Self {
        Self {
            schema_version: key.schema_version,
            analyzer_version: key.analyzer_version,
            workspace_root_hash: key.workspace_root_hash,
            files_content_hash: key.files_content_hash,
            cfg_features_hash: key.cfg_features_hash,
            config_hash: key.config_hash,
            test_intent_hash: key.test_intent_hash,
            suppressions_hash: key.suppressions_hash,
            classified_seams,
        }
    }

    fn matches_key(&self, key: &RepoSeamCacheKey) -> bool {
        self.schema_version == key.schema_version
            && self.analyzer_version == key.analyzer_version
            && self.workspace_root_hash == key.workspace_root_hash
            && self.files_content_hash == key.files_content_hash
            && self.cfg_features_hash == key.cfg_features_hash
            && self.config_hash == key.config_hash
            && self.test_intent_hash == key.test_intent_hash
            && self.suppressions_hash == key.suppressions_hash
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
struct ShardedCacheManifest {
    sharded_cache_schema_version: String,
    schema_version: String,
    analyzer_version: String,
    workspace_root_hash: String,
    files_content_hash: String,
    cfg_features_hash: String,
    config_hash: String,
    test_intent_hash: String,
    suppressions_hash: String,
    total_seams: usize,
    shard_count: usize,
    shards: Vec<ShardedCacheShardRef>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct ShardedCacheShardRef {
    index: usize,
    file: String,
    seams: usize,
}

#[derive(serde::Serialize, serde::Deserialize)]
struct ShardedCacheEnvelope {
    sharded_cache_schema_version: String,
    schema_version: String,
    analyzer_version: String,
    workspace_root_hash: String,
    files_content_hash: String,
    cfg_features_hash: String,
    config_hash: String,
    test_intent_hash: String,
    suppressions_hash: String,
    shard_index: usize,
    shard_count: usize,
    classified_seams: Vec<ClassifiedSeam>,
}

impl ShardedCacheManifest {
    fn new(
        key: RepoSeamCacheKey,
        total_seams: usize,
        shard_count: usize,
        shards: Vec<ShardedCacheShardRef>,
    ) -> Self {
        Self {
            sharded_cache_schema_version: SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION.to_string(),
            schema_version: key.schema_version,
            analyzer_version: key.analyzer_version,
            workspace_root_hash: key.workspace_root_hash,
            files_content_hash: key.files_content_hash,
            cfg_features_hash: key.cfg_features_hash,
            config_hash: key.config_hash,
            test_intent_hash: key.test_intent_hash,
            suppressions_hash: key.suppressions_hash,
            total_seams,
            shard_count,
            shards,
        }
    }

    fn matches_key(&self, key: &RepoSeamCacheKey) -> bool {
        self.sharded_cache_schema_version == SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION
            && self.schema_version == key.schema_version
            && self.analyzer_version == key.analyzer_version
            && self.workspace_root_hash == key.workspace_root_hash
            && self.files_content_hash == key.files_content_hash
            && self.cfg_features_hash == key.cfg_features_hash
            && self.config_hash == key.config_hash
            && self.test_intent_hash == key.test_intent_hash
            && self.suppressions_hash == key.suppressions_hash
    }
}

impl ShardedCacheEnvelope {
    fn new(
        key: RepoSeamCacheKey,
        shard_index: usize,
        shard_count: usize,
        classified_seams: Vec<ClassifiedSeam>,
    ) -> Self {
        Self {
            sharded_cache_schema_version: SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION.to_string(),
            schema_version: key.schema_version,
            analyzer_version: key.analyzer_version,
            workspace_root_hash: key.workspace_root_hash,
            files_content_hash: key.files_content_hash,
            cfg_features_hash: key.cfg_features_hash,
            config_hash: key.config_hash,
            test_intent_hash: key.test_intent_hash,
            suppressions_hash: key.suppressions_hash,
            shard_index,
            shard_count,
            classified_seams,
        }
    }

    fn matches_key(&self, key: &RepoSeamCacheKey) -> bool {
        self.sharded_cache_schema_version == SHARDED_CLASSIFIED_SEAM_CACHE_SCHEMA_VERSION
            && self.schema_version == key.schema_version
            && self.analyzer_version == key.analyzer_version
            && self.workspace_root_hash == key.workspace_root_hash
            && self.files_content_hash == key.files_content_hash
            && self.cfg_features_hash == key.cfg_features_hash
            && self.config_hash == key.config_hash
            && self.test_intent_hash == key.test_intent_hash
            && self.suppressions_hash == key.suppressions_hash
    }
}

/// Codec module — the only place serialization format is decided.
/// Switching to `postcard` for binary v2 is a localized change here.
mod codec {
    #[cfg(test)]
    use super::CountCacheEnvelope;
    use super::{CacheEnvelope, FileFactCacheEnvelope, ShardedCacheEnvelope, ShardedCacheManifest};

    pub(super) fn encode(envelope: &CacheEnvelope) -> Result<Vec<u8>, String> {
        serde_json::to_vec_pretty(envelope).map_err(|err| format!("encode failed: {err}"))
    }

    pub(super) fn decode(bytes: &[u8]) -> Result<CacheEnvelope, String> {
        serde_json::from_slice(bytes).map_err(|err| format!("decode failed: {err}"))
    }

    pub(super) fn encode_sharded_manifest(
        manifest: &ShardedCacheManifest,
    ) -> Result<Vec<u8>, String> {
        serde_json::to_vec_pretty(manifest)
            .map_err(|err| format!("encode sharded manifest failed: {err}"))
    }

    pub(super) fn decode_sharded_manifest(bytes: &[u8]) -> Result<ShardedCacheManifest, String> {
        serde_json::from_slice(bytes)
            .map_err(|err| format!("decode sharded manifest failed: {err}"))
    }

    pub(super) fn encode_shard(envelope: &ShardedCacheEnvelope) -> Result<Vec<u8>, String> {
        serde_json::to_vec_pretty(envelope)
            .map_err(|err| format!("encode sharded cache file failed: {err}"))
    }

    pub(super) fn decode_shard(bytes: &[u8]) -> Result<ShardedCacheEnvelope, String> {
        serde_json::from_slice(bytes)
            .map_err(|err| format!("decode sharded cache file failed: {err}"))
    }

    #[cfg(test)]
    pub(super) fn encode_counts(envelope: &CountCacheEnvelope) -> Result<Vec<u8>, String> {
        serde_json::to_vec_pretty(envelope).map_err(|err| format!("encode counts failed: {err}"))
    }

    #[cfg(test)]
    pub(super) fn decode_counts(bytes: &[u8]) -> Result<CountCacheEnvelope, String> {
        serde_json::from_slice(bytes).map_err(|err| format!("decode counts failed: {err}"))
    }

    pub(super) fn encode_file_facts(envelope: &FileFactCacheEnvelope) -> Result<Vec<u8>, String> {
        serde_json::to_vec_pretty(envelope)
            .map_err(|err| format!("encode file facts failed: {err}"))
    }

    pub(super) fn decode_file_facts(bytes: &[u8]) -> Result<FileFactCacheEnvelope, String> {
        serde_json::from_slice(bytes).map_err(|err| format!("decode file facts failed: {err}"))
    }
}

fn hash_str(s: &str) -> String {
    hash_bytes(s.as_bytes())
}

fn hash_bytes(bytes: &[u8]) -> String {
    format!("{:016x}", fnv1a_64(bytes))
}

/// FNV-1a 64-bit. Same algorithm `seams::compute_seam_id` uses; chosen
/// for its dependency-free determinism across Rust releases.
fn fnv1a_64(bytes: &[u8]) -> u64 {
    const FNV_OFFSET: u64 = 0xcbf29ce484222325;
    const FNV_PRIME: u64 = 0x100000001b3;
    let mut hash: u64 = FNV_OFFSET;
    for byte in bytes {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::seam_classification::ClassifiedSeam;
    use crate::analysis::seams::{
        ExpectedSink, RepoSeam, RequiredDiscriminator, SeamGripClass, SeamKind,
    };
    use crate::analysis::test_grip_evidence::TestGripEvidence;
    use crate::domain::{Confidence, StageEvidence, StageState};
    use std::path::PathBuf;

    fn sample_classified() -> ClassifiedSeam {
        let seam = RepoSeam::new(
            PathBuf::from("src/foo.rs"),
            "src/foo.rs::foo",
            SeamKind::PredicateBoundary,
            42,
            10,
            "x > 5".to_string(),
            RequiredDiscriminator::BoundaryValue {
                description: "x > 5".to_string(),
            },
            ExpectedSink::ReturnValue,
        );
        let evidence = TestGripEvidence {
            seam_id: seam.id().clone(),
            related_tests: Vec::new(),
            reach: StageEvidence::new(StageState::Yes, Confidence::High, "reach"),
            activate: StageEvidence::new(StageState::Unknown, Confidence::Medium, "activate"),
            propagate: StageEvidence::new(StageState::Unknown, Confidence::Medium, "propagate"),
            observe: StageEvidence::new(StageState::Weak, Confidence::Low, "observe"),
            discriminate: StageEvidence::new(StageState::No, Confidence::Low, "discriminate"),
            observed_values: Vec::new(),
            missing_discriminators: Vec::new(),
        };
        ClassifiedSeam {
            seam,
            evidence,
            class: SeamGripClass::Ungripped,
        }
    }

    fn empty_state() -> WorkspaceState<'static> {
        WorkspaceState {
            workspace_root: Path::new("/repo"),
            files: &[],
            cfg_features: None,
            config_text: None,
            test_intent_text: None,
            suppressions_text: None,
        }
    }

    fn isolated_dir(label: &str) -> PathBuf {
        std::env::temp_dir().join(format!("ripr-cache-{label}-{}", uuid_like()))
    }

    #[test]
    fn given_no_cache_when_load_runs_then_miss_is_returned() -> Result<(), String> {
        let dir = isolated_dir("cold");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir);
        let key = empty_state().cache_key();
        match cache.load_classified_seams(&key) {
            CacheLoad::Miss => Ok(()),
            other => Err(format!("expected Miss on missing cache dir, got {other:?}")),
        }
    }

    #[test]
    fn given_unchanged_inputs_when_cache_is_warm_then_classified_seams_are_reused()
    -> Result<(), String> {
        let dir = isolated_dir("warm");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let seams = vec![sample_classified()];
        cache
            .store_classified_seams_with_limit(&key, &seams, CLASSIFIED_SEAM_CACHE_STORE_LIMIT)
            .map_err(|err| format!("store should succeed: {err}"))?;
        let result = match cache.load_classified_seams(&key) {
            CacheLoad::Hit(loaded) => {
                if loaded.len() != seams.len() {
                    Err(format!(
                        "warm path should return stored seams, got {} vs {}",
                        loaded.len(),
                        seams.len()
                    ))
                } else if loaded[0].seam.id().as_str() != seams[0].seam.id().as_str() {
                    Err(format!(
                        "round-trip should preserve seam id, got {} vs {}",
                        loaded[0].seam.id().as_str(),
                        seams[0].seam.id().as_str()
                    ))
                } else if loaded[0].class != seams[0].class {
                    Err(format!(
                        "round-trip should preserve class, got {:?} vs {:?}",
                        loaded[0].class, seams[0].class
                    ))
                } else {
                    Ok(())
                }
            }
            other => Err(format!("expected Hit on warm cache, got {other:?}")),
        };
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[test]
    fn given_large_classified_entry_when_cache_store_runs_then_shards_are_written()
    -> Result<(), String> {
        let dir = isolated_dir("large-shard");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let seams = vec![sample_classified(); 2];
        let status = cache
            .store_classified_seams_with_limit(&key, &seams, 1)
            .map_err(|err| format!("large classified seam cache should shard: {err}"))?;

        assert_eq!(status.label, "sharded_ok_seams_2_shards_2_limit_1");
        assert!(
            !cache.entry_path(&key).exists(),
            "sharded cache store should not write a monolithic classified seam entry"
        );
        assert!(
            cache.sharded_manifest_path(&key).exists(),
            "sharded cache store should write a manifest"
        );
        assert!(
            cache
                .sharded_entry_dir(&key)
                .join("shard-00000.json")
                .exists(),
            "sharded cache store should write the first shard"
        );
        assert!(
            cache
                .sharded_entry_dir(&key)
                .join("shard-00001.json")
                .exists(),
            "sharded cache store should write the second shard"
        );

        match cache.load_classified_seams(&key) {
            CacheLoad::Hit(loaded) if loaded.len() == 2 => {}
            other => return Err(format!("expected sharded cache hit, got {other:?}")),
        }

        let _ = std::fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn classified_cache_store_limit_rejects_zero_direct_limit() -> Result<(), String> {
        let dir = isolated_dir("zero-limit");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let err = match cache.store_classified_seams_with_limit(&key, &[sample_classified()], 0) {
            Ok(status) => {
                return Err(format!(
                    "zero direct cache limit should fail, got {}",
                    status.label
                ));
            }
            Err(err) => err,
        };

        assert!(
            err.contains("positive"),
            "zero direct cache limit should produce positive-limit diagnostic: {err}"
        );

        let _ = std::fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn classified_cache_store_limit_defaults_to_20k_when_env_missing() -> Result<(), String> {
        let limit =
            classified_seam_cache_store_limit_from_env(Err(std::env::VarError::NotPresent))?;

        assert_eq!(limit, CLASSIFIED_SEAM_CACHE_STORE_LIMIT);
        Ok(())
    }

    #[test]
    fn classified_cache_store_limit_accepts_positive_env_override() -> Result<(), String> {
        let limit = classified_seam_cache_store_limit_from_env(Ok("25000".to_string()))?;

        assert_eq!(limit, 25_000);
        Ok(())
    }

    #[test]
    fn classified_cache_store_limit_rejects_invalid_env_override() -> Result<(), String> {
        for value in ["", "0", "not-a-number"] {
            let err = match classified_seam_cache_store_limit_from_env(Ok(value.to_string())) {
                Ok(limit) => {
                    return Err(format!(
                        "invalid classified cache env value {value:?} should fail, got limit {limit}"
                    ));
                }
                Err(err) => err,
            };
            assert!(
                err.contains(CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV),
                "diagnostic should name env var for {value:?}: {err}"
            );
            assert!(
                err.contains("positive integer"),
                "diagnostic should describe expected value for {value:?}: {err}"
            );
        }
        Ok(())
    }

    #[test]
    fn classified_cache_store_limit_can_be_raised_for_large_entries() -> Result<(), String> {
        let dir = isolated_dir("classified-raised-limit");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let seams = vec![sample_classified(); 2];

        cache
            .store_classified_seams_with_limit(&key, &seams, 2)
            .map_err(|err| format!("raised classified cache limit should allow store: {err}"))?;

        match cache.load_classified_seams(&key) {
            CacheLoad::Hit(loaded) if loaded.len() == 2 => {}
            other => {
                return Err(format!(
                    "expected classified cache hit after raised limit: {other:?}"
                ));
            }
        }

        let _ = std::fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn compact_cache_store_limit_defaults_to_100k_when_env_missing() -> Result<(), String> {
        let limit = compact_classified_seam_cache_store_limit_from_env(Err(
            std::env::VarError::NotPresent,
        ))?;

        assert_eq!(limit, COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT);
        Ok(())
    }

    #[test]
    fn compact_cache_store_limit_accepts_positive_env_override() -> Result<(), String> {
        let limit = compact_classified_seam_cache_store_limit_from_env(Ok("200000".to_string()))?;

        assert_eq!(limit, 200_000);
        Ok(())
    }

    #[test]
    fn compact_cache_store_limit_rejects_invalid_env_override() -> Result<(), String> {
        for value in ["", "0", "not-a-number"] {
            let err = match compact_classified_seam_cache_store_limit_from_env(
                Ok(value.to_string()),
            ) {
                Ok(limit) => {
                    return Err(format!(
                        "invalid compact cache env value {value:?} should fail, got limit {limit}"
                    ));
                }
                Err(err) => err,
            };
            assert!(
                err.contains(COMPACT_CLASSIFIED_SEAM_CACHE_STORE_LIMIT_ENV),
                "diagnostic should name env var for {value:?}: {err}"
            );
            assert!(
                err.contains("positive integer"),
                "diagnostic should describe expected value for {value:?}: {err}"
            );
        }
        Ok(())
    }

    #[test]
    fn compact_cache_store_limit_controls_shard_size() -> Result<(), String> {
        let dir = isolated_dir("compact-large-shard");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let seams = vec![sample_classified(); 2];

        let status = cache
            .store_compact_classified_seams_with_limit(&key, &seams, 1)
            .map_err(|err| format!("configured compact cache limit should shard: {err}"))?;

        assert_eq!(status.label, "sharded_ok_seams_2_shards_2_limit_1");
        assert!(
            !cache.entry_path(&key).exists(),
            "sharded compact cache store should not write a monolithic entry"
        );
        match cache.load_classified_seams(&key) {
            CacheLoad::Hit(loaded) if loaded.len() == 2 => {}
            other => return Err(format!("expected compact sharded cache hit: {other:?}")),
        }

        let _ = std::fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn given_missing_sharded_cache_file_when_loading_then_corrupt_ignored_is_reported()
    -> Result<(), String> {
        let dir = isolated_dir("missing-shard");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let seams = vec![sample_classified(); 2];

        cache
            .store_classified_seams_with_limit(&key, &seams, 1)
            .map_err(|err| format!("large classified seam cache should shard: {err}"))?;
        std::fs::remove_file(cache.sharded_entry_dir(&key).join("shard-00001.json"))
            .map_err(|err| format!("remove shard fixture: {err}"))?;

        match cache.load_classified_seams(&key) {
            CacheLoad::CorruptIgnored { reason } => {
                assert!(
                    reason.contains("missing sharded cache file"),
                    "missing shard should be named in corrupt reason: {reason}"
                );
            }
            other => {
                return Err(format!(
                    "expected CorruptIgnored for missing sharded cache file, got {other:?}"
                ));
            }
        }

        let _ = std::fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn compact_cache_store_limit_can_be_raised_for_large_entries() -> Result<(), String> {
        let dir = isolated_dir("compact-raised-limit");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let seams = vec![sample_classified(); 2];

        cache
            .store_compact_classified_seams_with_limit(&key, &seams, 2)
            .map_err(|err| format!("raised compact cache limit should allow store: {err}"))?;

        match cache.load_classified_seams(&key) {
            CacheLoad::Hit(loaded) if loaded.len() == 2 => {}
            other => {
                return Err(format!(
                    "expected compact cache hit after raised limit: {other:?}"
                ));
            }
        }

        let _ = std::fs::remove_dir_all(&dir);
        Ok(())
    }

    #[test]
    fn given_changed_file_content_hash_when_cache_is_loaded_then_old_entry_is_treated_as_miss()
    -> Result<(), String> {
        let dir = isolated_dir("changed");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let path = PathBuf::from("src/foo.rs");
        let original_files = [(path.clone(), b"fn foo() {}\n".to_vec())];
        let original_key = WorkspaceState {
            workspace_root: Path::new("/repo"),
            files: &original_files,
            cfg_features: None,
            config_text: None,
            test_intent_text: None,
            suppressions_text: None,
        }
        .cache_key();
        cache
            .store_classified_seams_with_limit(
                &original_key,
                &[sample_classified()],
                CLASSIFIED_SEAM_CACHE_STORE_LIMIT,
            )
            .map_err(|err| format!("store original: {err}"))?;
        let new_files = [(path, b"fn foo() { let x = 1; }\n".to_vec())];
        let new_key = WorkspaceState {
            workspace_root: Path::new("/repo"),
            files: &new_files,
            cfg_features: None,
            config_text: None,
            test_intent_text: None,
            suppressions_text: None,
        }
        .cache_key();
        if original_key.files_content_hash == new_key.files_content_hash {
            return Err("different file content must produce different files_content_hash".into());
        }
        let result = match cache.load_classified_seams(&new_key) {
            CacheLoad::Miss => Ok(()),
            other => Err(format!(
                "expected Miss after file content change, got {other:?}"
            )),
        };
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[test]
    fn given_test_file_content_changes_when_cache_key_is_built_then_classified_seam_cache_is_invalidated()
    -> Result<(), String> {
        // The cache hashes the same Rust file set fed to `build_index`
        // — production *and* test files. `ClassifiedSeam` carries
        // `TestGripEvidence` derived from test files, so a test-only
        // edit must change the key. This test pins that contract by
        // varying only a test file's content (no test_intent.toml,
        // no suppressions.toml, no production change).
        let prod = PathBuf::from("src/foo.rs");
        let prod_bytes = b"pub fn foo() -> i32 { 1 }\n".to_vec();
        let test_path = PathBuf::from("tests/foo_test.rs");

        let baseline_files = [
            (prod.clone(), prod_bytes.clone()),
            (
                test_path.clone(),
                b"#[test] fn smoke() { assert_eq!(1, 1); }\n".to_vec(),
            ),
        ];
        let baseline = WorkspaceState {
            workspace_root: Path::new("/repo"),
            files: &baseline_files,
            cfg_features: None,
            config_text: None,
            test_intent_text: None,
            suppressions_text: None,
        }
        .cache_key();

        let updated_files = [
            (prod, prod_bytes),
            (
                test_path,
                b"#[test] fn smoke() { assert_eq!(super::foo(), 1); }\n".to_vec(),
            ),
        ];
        let updated = WorkspaceState {
            workspace_root: Path::new("/repo"),
            files: &updated_files,
            cfg_features: None,
            config_text: None,
            test_intent_text: None,
            suppressions_text: None,
        }
        .cache_key();

        if baseline.files_content_hash == updated.files_content_hash {
            return Err(
                "test-only file content change must change files_content_hash so stale \
                 TestGripEvidence cannot survive in the cache"
                    .into(),
            );
        }
        if baseline.filename() == updated.filename() {
            return Err(
                "test-only file content change must produce a different cache filename".into(),
            );
        }
        Ok(())
    }

    #[test]
    fn given_test_intent_hash_change_when_cache_is_loaded_then_classified_seam_cache_is_invalidated()
    -> Result<(), String> {
        let baseline = WorkspaceState {
            test_intent_text: Some(""),
            ..empty_state()
        }
        .cache_key();
        let updated = WorkspaceState {
            test_intent_text: Some("[[test]] name = \"smoke\""),
            ..empty_state()
        }
        .cache_key();
        if baseline.test_intent_hash == updated.test_intent_hash {
            return Err("different test intent must produce different test_intent_hash".into());
        }
        if baseline.filename() == updated.filename() {
            return Err(
                "different test_intent_hash must produce a different cache filename".into(),
            );
        }
        Ok(())
    }

    #[test]
    fn given_suppression_hash_change_when_cache_is_loaded_then_classified_seam_cache_is_invalidated()
    -> Result<(), String> {
        let baseline = WorkspaceState {
            suppressions_text: Some(""),
            ..empty_state()
        }
        .cache_key();
        let updated = WorkspaceState {
            suppressions_text: Some("[[suppression]] kind = \"exposure_gap\""),
            ..empty_state()
        }
        .cache_key();
        if baseline.suppressions_hash == updated.suppressions_hash {
            return Err(
                "different suppressions text must produce different suppressions_hash".into(),
            );
        }
        if baseline.filename() == updated.filename() {
            return Err(
                "different suppressions_hash must produce a different cache filename".into(),
            );
        }
        Ok(())
    }

    #[test]
    fn given_corrupt_cache_entry_when_loading_then_corrupt_ignored_is_reported_without_failing()
    -> Result<(), String> {
        let dir = isolated_dir("corrupt");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).map_err(|err| format!("mkdir: {err}"))?;
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key = empty_state().cache_key();
        let path = cache.entry_path(&key);
        std::fs::write(&path, b"{not valid json")
            .map_err(|err| format!("write corrupt entry: {err}"))?;
        let result = match cache.load_classified_seams(&key) {
            CacheLoad::CorruptIgnored { reason } => {
                if !reason.contains("decode failed") {
                    Err(format!(
                        "corrupt reason should explain decode failure, got {reason}"
                    ))
                } else {
                    Ok(())
                }
            }
            other => Err(format!(
                "expected CorruptIgnored on bad json, got {other:?}"
            )),
        };
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[test]
    fn given_envelope_key_mismatch_when_loading_then_miss_is_returned_without_failing()
    -> Result<(), String> {
        let dir = isolated_dir("keymismatch");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoSeamFactCache::at_dir(dir.clone());
        let key_a = WorkspaceState {
            cfg_features: Some("a"),
            ..empty_state()
        }
        .cache_key();
        let key_b = WorkspaceState {
            cfg_features: Some("b"),
            ..empty_state()
        }
        .cache_key();
        cache
            .store_classified_seams_with_limit(
                &key_a,
                &[sample_classified()],
                CLASSIFIED_SEAM_CACHE_STORE_LIMIT,
            )
            .map_err(|err| format!("store under key_a: {err}"))?;
        // Write key_a's envelope under key_b's filename — simulates a
        // hash collision or stale entry.
        let envelope = CacheEnvelope::new(key_a.clone(), vec![sample_classified()]);
        std::fs::create_dir_all(&dir).map_err(|err| format!("mkdir: {err}"))?;
        let bytes = codec::encode(&envelope)?;
        std::fs::write(cache.entry_path(&key_b), bytes)
            .map_err(|err| format!("write under wrong filename: {err}"))?;
        let result = match cache.load_classified_seams(&key_b) {
            CacheLoad::Miss => Ok(()),
            other => Err(format!(
                "expected Miss when envelope key mismatches request, got {other:?}"
            )),
        };
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[test]
    fn given_file_facts_cached_when_loading_same_file_bytes_then_hit_is_returned()
    -> Result<(), String> {
        let dir = isolated_dir("file-facts-warm");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoFileFactCache::at_dir(dir.clone());
        let path = PathBuf::from("src/lib.rs");
        let key = RepoFileFactCacheKey::new(&path, b"pub fn cached() {}\n");
        let facts = FileFacts {
            path: path.clone(),
            source: "pub fn cached() {}\n".to_string(),
            ..FileFacts::default()
        };

        cache
            .store_file_facts(&key, &facts)
            .map_err(|err| format!("store file facts should succeed: {err}"))?;

        let result = match cache.load_file_facts(&key) {
            CacheLoad::Hit(loaded) => {
                if loaded != facts {
                    Err("loaded file facts should match stored facts".to_string())
                } else {
                    Ok(())
                }
            }
            other => Err(format!("expected file fact cache hit, got {other:?}")),
        };
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[test]
    fn given_file_content_changes_when_file_facts_load_then_miss_is_returned() -> Result<(), String>
    {
        let dir = isolated_dir("file-facts-invalidates");
        let _ = std::fs::remove_dir_all(&dir);
        let cache = RepoFileFactCache::at_dir(dir.clone());
        let path = PathBuf::from("src/lib.rs");
        let original_key = RepoFileFactCacheKey::new(&path, b"pub fn cached() -> i32 { 1 }\n");
        let changed_key = RepoFileFactCacheKey::new(&path, b"pub fn cached() -> i32 { 2 }\n");
        let facts = FileFacts {
            path: path.clone(),
            source: "pub fn cached() -> i32 { 1 }\n".to_string(),
            ..FileFacts::default()
        };

        cache
            .store_file_facts(&original_key, &facts)
            .map_err(|err| format!("store original file facts: {err}"))?;

        let result = match cache.load_file_facts(&changed_key) {
            CacheLoad::Miss => Ok(()),
            other => Err(format!(
                "expected Miss after file content change, got {other:?}"
            )),
        };
        let _ = std::fs::remove_dir_all(&dir);
        result
    }

    #[test]
    fn file_fact_cache_stats_status_label_is_trace_safe() {
        let stats = FileFactCacheStats {
            hits: 2,
            misses: 3,
            corrupt_ignored: 1,
            stores: 3,
            store_errors: 0,
        };
        assert_eq!(
            stats.status_label(),
            "hits_2_misses_3_corrupt_1_store_errors_0"
        );
    }

    /// Tiny non-crypto unique-ish suffix for tempdir naming. Avoids
    /// depending on `tempfile` and avoids tests racing each other when
    /// run with `--test-threads`.
    fn uuid_like() -> String {
        use std::time::{SystemTime, UNIX_EPOCH};
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        format!("{}-{:x}", std::process::id(), nanos)
    }
}