supercov-engine 0.0.51

Rust instrumentation, evidence, attribution, and query engine for Supercov
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
//! Agent-authored assertion maps. Edges are explanations, never inferred proofs.
//! This module owns format validation, text relocation and input acknowledgement bookkeeping.

use crate::source_units::{Code, Diff, named};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};

pub type Files = BTreeMap<String, String>;
pub fn digest(value: &impl Serialize) -> String {
    format!(
        "{:x}",
        Sha256::digest(serde_json::to_vec(value).expect("serializable map"))
    )
}
fn version() -> u32 {
    1
}

/// One-based lines and UTF-8 byte columns, for every language. Text is exact.
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Anchor {
    pub file: String,
    pub line: usize,
    pub column: usize,
    pub text: String,
}

pub fn local_path(file: &str) -> bool {
    !file.is_empty()
        && !file.contains(['\\', ':'])
        && file.split('/').all(|p| !matches!(p, "" | "." | ".."))
}
impl Anchor {
    pub fn new(file: &str, source: &str, start: usize, end: usize) -> Self {
        Self {
            file: file.into(),
            line: source[..start].bytes().filter(|b| *b == b'\n').count() + 1,
            column: start - source[..start].rfind('\n').map_or(0, |n| n + 1) + 1,
            text: source[start..end].into(),
        }
    }
    pub fn offset(&self, files: &Files) -> Option<usize> {
        if !local_path(&self.file) || self.text.is_empty() || self.line == 0 || self.column == 0 {
            return None;
        }
        let source = files.get(&self.file)?;
        let start = source
            .split_inclusive('\n')
            .take(self.line - 1)
            .map(str::len)
            .sum::<usize>();
        if source[..start].bytes().filter(|b| *b == b'\n').count() != self.line - 1 {
            return None;
        }
        let line = source.get(start..)?.split('\n').next()?;
        if self.column - 1 > line.len() {
            return None;
        }
        let pos = start.checked_add(self.column - 1)?;
        source.get(pos..)?.starts_with(&self.text).then_some(pos)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct InventorySite {
    pub at: Anchor,
    pub operation: String,
}

/// Source text held in memory for capture or a verified current-checkout query.
/// The serialized form is retained only for reading legacy source archives.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Inputs {
    #[serde(default = "version")]
    pub schema_version: u32,
    pub language: String,
    pub context_digest: String,
    pub files: Files,
    pub assertions: Vec<InventorySite>,
    pub limitations: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FileFingerprint {
    pub sha256: String,
    pub bytes: usize,
    /// The parser's view of the file: what it declares, each declaration
    /// digested with comments blanked. Absent for a file no parser reads and
    /// in manifests written before this existed; such a file is compared by
    /// its bytes, as every file once was.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<Code>,
}
impl FileFingerprint {
    pub fn of(source: &str) -> Self {
        Self {
            sha256: format!("{:x}", Sha256::digest(source.as_bytes())),
            bytes: source.len(),
            code: None,
        }
    }
    /// Bytes and, where Supercov has a parser for the file, its declarations.
    pub fn read(path: &str, source: &str) -> Self {
        let mut fingerprint = Self::of(source);
        fingerprint.code = crate::source_units::code(path, source);
        fingerprint
    }
    pub fn same_bytes(&self, other: &Self) -> bool {
        self.sha256 == other.sha256
    }
}
pub type FileManifest = BTreeMap<String, FileFingerprint>;

/// The run stores identities and hashes, never complete source files.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct InputManifest {
    pub schema_version: u32,
    pub language: String,
    pub context_digest: String,
    pub files: FileManifest,
    pub assertions: Vec<InventorySite>,
    pub limitations: Vec<String>,
}
impl Inputs {
    pub fn manifest(&self) -> InputManifest {
        InputManifest {
            schema_version: 2,
            language: self.language.clone(),
            context_digest: self.context_digest.clone(),
            files: self
                .files
                .iter()
                .map(|(p, s)| (p.clone(), FileFingerprint::read(p, s)))
                .collect(),
            assertions: self.assertions.clone(),
            limitations: self.limitations.clone(),
        }
    }
    pub fn identity(&self) -> String {
        digest(&self.manifest())
    }
}
impl InputManifest {
    pub fn with_sources(&self, files: Files) -> Inputs {
        Inputs {
            schema_version: 1,
            language: self.language.clone(),
            context_digest: self.context_digest.clone(),
            files,
            assertions: self.assertions.clone(),
            limitations: self.limitations.clone(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Node {
    pub id: String,
    pub at: Anchor,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub role: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub meaning: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Edge {
    pub from: String,
    pub to: String,
    pub kind: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub basis: String,
}
#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TestSelector {
    pub file: String,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Flow {
    pub id: String,
    #[serde(deserialize_with = "required_basis")]
    #[schemars(required, schema_with = "basis_schema")]
    pub basis: Option<String>,
    pub explanation: String,
    pub applies_to: Vec<TestSelector>,
    pub nodes: Vec<Node>,
    #[serde(default)]
    pub edges: Vec<Edge>,
    pub counts_as_asserted: Vec<String>,
    pub watch: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub questions: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Assertion {
    pub id: String,
    pub at: Anchor,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub questions: Vec<String>,
    #[serde(default)]
    pub observes: Vec<String>,
    #[serde(default)]
    pub flows: Vec<Flow>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Retired {
    pub assertion: Assertion,
    pub reason: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct AssertionMap {
    #[schemars(range(min = 2, max = 2))]
    pub schema_version: u32,
    pub assertions: Vec<Assertion>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub change_assessments: Vec<ChangeAssessment>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub retired_assertions: Vec<Retired>,
}

// Missing basis is a syntax error; null explicitly means unfinished work.
fn required_basis<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
    let value = Option::<String>::deserialize(d)?;
    if value.as_deref().is_some_and(|s| !valid_basis(s)) {
        return Err(serde::de::Error::custom(
            "expected null or scov3:<64 lowercase hex digits>",
        ));
    }
    Ok(value)
}
fn basis_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
    schemars::json_schema!({"type":["string","null"],"pattern":"^scov[23]:[0-9a-f]{64}$"})
}
fn valid_basis(s: &str) -> bool {
    s.strip_prefix("scov3:")
        .or_else(|| s.strip_prefix("scov2:"))
        .is_some_and(|h| {
            h.len() == 64
                && h.bytes()
                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        })
}
/// A token from a release whose basis pinned files rather than the code a
/// claim rests on. It still parses, so the map stays valid; it can no longer
/// match, so the claim reads as needing acknowledgement, with this as its
/// reason rather than a change that never happened.
pub fn superseded_basis(s: &str) -> bool {
    s.starts_with("scov2:")
}
pub const SUPERSEDED_BASIS: &str = "acknowledged under an earlier Supercov basis format; reread the claim and copy the current expectedBasis";
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ChangeAssessment {
    pub id: String,
    #[serde(deserialize_with = "required_basis")]
    #[schemars(required, schema_with = "basis_schema")]
    pub basis: Option<String>,
    pub affected_flows: Vec<String>,
    pub explanation: String,
}

/// Editor schema generated from the same Rust types used by every map command.
/// Source existence, links, freshness and semantic meaning are outside JSON Schema.
pub fn schema() -> serde_json::Value {
    serde_json::to_value(schemars::schema_for!(AssertionMap)).expect("schema")
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ParseError {
    pub pointer: String,
    pub line: usize,
    pub column: usize,
    pub message: String,
}
impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} at {} (JSON line {}, column {})",
            self.message, self.pointer, self.line, self.column
        )
    }
}
pub fn parse(bytes: &[u8]) -> Result<AssertionMap, ParseError> {
    let mut deserializer = serde_json::Deserializer::from_slice(bytes);
    let map: AssertionMap = serde_path_to_error::deserialize(&mut deserializer).map_err(|e| {
        let pointer = e
            .path()
            .iter()
            .map(|segment| {
                use serde_path_to_error::Segment;
                let part = match segment {
                    Segment::Seq { index } => index.to_string(),
                    Segment::Map { key } => key.clone(),
                    Segment::Enum { variant } => variant.clone(),
                    Segment::Unknown => "?".into(),
                };
                format!("/{}", part.replace('~', "~0").replace('/', "~1"))
            })
            .collect();
        ParseError {
            pointer,
            line: e.inner().line(),
            column: e.inner().column(),
            message: e.inner().to_string(),
        }
    })?;
    deserializer.end().map_err(|e| ParseError {
        pointer: String::new(),
        line: e.line(),
        column: e.column(),
        message: e.to_string(),
    })?;
    if map.schema_version != 2 {
        return Err(ParseError {
            pointer: "/schemaVersion".into(),
            line: 0,
            column: 0,
            message: "unsupported map schema version; expected 2".into(),
        });
    }
    Ok(map)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct FlowState {
    pub generation: String,
    pub reasons: BTreeSet<String>,
    /// Changes near this flow that could not have reached it: a file it
    /// depends on changed only in code its test never ran. Told, not asked.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub notices: BTreeSet<String>,
}
/// What each test of a run executed, in the units of that run's manifest.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Executions {
    pub tests: Vec<Execution>,
    /// Per file, the units that hold a probe of their own. A change confined
    /// to these can reach a test only by being run.
    pub probed: BTreeMap<String, Vec<usize>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Execution {
    pub test: TestSelector,
    pub passed: bool,
    /// Per file, the innermost unit of every probe this test fired.
    pub files: BTreeMap<String, Vec<usize>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Change {
    pub id: String,
    pub file: Option<String>,
    pub before: Option<String>,
    pub after: Option<String>,
    pub reason: String,
    /// Flows this change has already made stale. An assessment has to name
    /// them; it may name more.
    pub known_flows: BTreeSet<String>,
    /// Flows whose selected tests ran the changed code, or have no execution
    /// record to say. Not stale for it -- the claim they make does not pass
    /// through that code -- but these are the ones the assessment is about.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub exposed: BTreeSet<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct State {
    pub schema_version: u32,
    pub inputs_digest: String,
    pub evidence_digest: String,
    pub flows: BTreeMap<String, FlowState>,
    pub changes: Vec<Change>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inheritance: Option<Inheritance>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub executions: Option<Executions>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Inheritance {
    pub from: Option<String>,
    pub skipped: Vec<SkippedMap>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SkippedMap {
    pub run: String,
    pub reason: String,
}
pub fn flow_key(a: &Assertion, f: &Flow) -> String {
    format!("{}/{}", a.id, f.id)
}
fn valid_id(id: &str) -> bool {
    !id.is_empty()
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.'))
}

pub fn seed(inputs: &Inputs, evidence_digest: &str) -> (AssertionMap, State) {
    seed_manifest(&inputs.manifest(), evidence_digest)
}
pub fn seed_manifest(inputs: &InputManifest, evidence_digest: &str) -> (AssertionMap, State) {
    (
        AssertionMap {
            schema_version: 2,
            assertions: inputs
                .assertions
                .iter()
                .map(|site| Assertion {
                    id: format!("a_{}", &digest(&site.at)[..20]),
                    at: site.at.clone(),
                    questions: vec![],
                    observes: vec![],
                    flows: vec![],
                })
                .collect(),
            change_assessments: vec![],
            retired_assertions: vec![],
        },
        State {
            schema_version: 3,
            inputs_digest: digest(inputs),
            evidence_digest: evidence_digest.into(),
            flows: BTreeMap::new(),
            changes: vec![],
            inheritance: None,
            executions: None,
        },
    )
}

/// Structural checks only; malformed entries cannot silently earn credit.
pub fn validate(map: &AssertionMap, inputs: &Inputs) -> Vec<String> {
    let mut errors = Vec::new();
    if map.schema_version != 2 || inputs.schema_version != 1 {
        errors.push("unsupported schema version".into());
    }
    let mut ids = BTreeSet::new();
    let mut sites = BTreeSet::new();
    for a in &map.assertions {
        if !valid_id(&a.id) || !ids.insert(&a.id) {
            errors.push(format!("{}: invalid/duplicate assertion ID", a.id));
        }
        if !sites.insert(&a.at) {
            errors.push(format!("{}: duplicate assertion location", a.id));
        }
        if a.at.offset(&inputs.files).is_none() {
            errors.push(format!("{}: invalid assertion anchor", a.id));
        }
        // Agents can register custom assertions absent from the syntax inventory.
        // They still require exact run evidence to earn execution-backed credit.
        let mut flows = BTreeSet::new();
        for f in &a.flows {
            let key = flow_key(a, f);
            if !valid_id(&f.id) || !flows.insert(&f.id) {
                errors.push(format!("{key}: invalid/duplicate flow ID"));
            }
            errors.extend(
                validate_flow(f, &inputs.files)
                    .into_iter()
                    .map(|e| format!("{key}: {e}")),
            );
        }
    }
    let mut changes = BTreeSet::new();
    for change in &map.change_assessments {
        if !valid_id(&change.id) || !changes.insert(&change.id) {
            errors.push("invalid/duplicate change assessment ID".into());
        }
    }
    errors
}
/// Things worth telling the author that do not make the map wrong.
///
/// A redundant `watch` is the one that matters today. Supercov already marks
/// every flow dirty when a dependency manifest or the execution configuration
/// changes, so naming one of those files per flow catches nothing extra. It
/// does teach a false model -- that per-flow watching is how dependency drift
/// is caught -- and an author who believes it spends the effort on entries that
/// change nothing instead of on the helper their claim actually rests on.
pub fn advisories(map: &AssertionMap) -> Vec<String> {
    let mut out = Vec::new();
    for a in &map.assertions {
        for f in &a.flows {
            for file in &f.watch {
                if crate::integrity::globally_tracked(file) {
                    out.push(format!(
                        "{}: watch \"{file}\" is redundant; Supercov invalidates every flow when that file changes",
                        flow_key(a, f)
                    ));
                }
            }
        }
    }
    out
}
pub fn validate_flow(flow: &Flow, files: &Files) -> Vec<String> {
    let mut errors = Vec::new();
    let mut nodes = BTreeSet::new();
    for node in &flow.nodes {
        if !valid_id(&node.id) || !nodes.insert(&node.id) {
            errors.push("invalid/duplicate node ID".into());
        }
        if node.at.offset(files).is_none() {
            errors.push(format!("node {}: invalid anchor", node.id));
        }
    }
    for edge in &flow.edges {
        if !nodes.contains(&edge.from) || (!nodes.contains(&edge.to) && edge.to != "$assertion") {
            errors.push("dangling edge".into());
        }
    }
    if flow.counts_as_asserted.iter().any(|id| !nodes.contains(id)) {
        errors.push("unknown counted node".into());
    }
    // Traverse only the author's graph. Never infer a dependency from source.
    let mut reaches = BTreeSet::from(["$assertion".to_owned()]);
    loop {
        let size = reaches.len();
        for edge in &flow.edges {
            if reaches.contains(&edge.to) {
                reaches.insert(edge.from.clone());
            }
        }
        if reaches.len() == size {
            break;
        }
    }
    for id in &flow.counts_as_asserted {
        if !reaches.contains(id) {
            errors.push(format!(
                "counted node {id} has no authored path to $assertion"
            ));
        }
    }
    if flow.edges.iter().any(|e| e.kind.trim().is_empty()) {
        errors.push("missing edge kind".into());
    }
    if flow
        .applies_to
        .iter()
        .any(|t| !local_path(&t.file) || !files.contains_key(&t.file) || t.name.trim().is_empty())
    {
        errors.push("invalid test selector file or name".into());
    }
    if flow.applies_to.iter().collect::<BTreeSet<_>>().len() != flow.applies_to.len() {
        errors.push("duplicate test selector".into());
    }
    if flow
        .counts_as_asserted
        .iter()
        .collect::<BTreeSet<_>>()
        .len()
        != flow.counts_as_asserted.len()
    {
        errors.push("duplicate counted node".into());
    }
    if flow.explanation.trim().is_empty() {
        errors.push("missing explanation".into());
    }
    for file in &flow.watch {
        if !local_path(file) || !files.contains_key(file) {
            errors.push(format!("watched file missing: {file}"));
        }
    }
    errors
}

/// Whole-file input dependencies, not a mechanically inferred semantic slice.
pub fn dependencies<'a>(a: &'a Assertion, f: &'a Flow) -> BTreeSet<&'a str> {
    std::iter::once(a.at.file.as_str())
        .chain(f.applies_to.iter().map(|t| t.file.as_str()))
        .chain(f.nodes.iter().map(|n| n.at.file.as_str()))
        // A watch on a file Supercov already answers for run-wide contributes
        // nothing here, and hashing its bytes would quietly undo the manifest
        // rule: a version bump would still make every flow that names
        // `package.json` stale, which is most of them in a real map. The
        // run-level signal still fires, as a change to assess.
        //
        // Only the watch list is filtered. An anchor or a node in one of those
        // files is the flow's actual subject -- `setup.py` is a dependency
        // manifest and measured source at once -- and editing it must still
        // cost a review.
        .chain(
            f.watch
                .iter()
                .map(String::as_str)
                .filter(|path| !crate::integrity::globally_tracked(path)),
        )
        .collect()
}
fn token(value: &impl Serialize) -> String {
    format!("scov3:{}", digest(value))
}
fn flow_keys(map: &AssertionMap) -> BTreeSet<String> {
    map.assertions
        .iter()
        .flat_map(|a| a.flows.iter().map(move |f| flow_key(a, f)))
        .collect()
}
pub fn change_errors(
    map: &AssertionMap,
    change: &Change,
    response: &ChangeAssessment,
) -> Vec<String> {
    change_errors_with(&flow_keys(map), change, response)
}
fn change_errors_with(
    keys: &BTreeSet<String>,
    change: &Change,
    response: &ChangeAssessment,
) -> Vec<String> {
    let affected = response
        .affected_flows
        .iter()
        .cloned()
        .collect::<BTreeSet<_>>();
    let mut errors = Vec::new();
    if response.explanation.trim().is_empty() {
        errors.push("missing impact explanation".into());
    }
    if affected.len() != response.affected_flows.len() {
        errors.push("duplicate affected flow".into());
    }
    if !affected.is_subset(keys) {
        errors.push("unknown affected flow".into());
    }
    if !change
        .known_flows
        .intersection(keys)
        .all(|k| affected.contains(k))
    {
        errors.push("known dependent flows must be included unless removed from the map".into());
    }
    errors
}
pub fn expected_change_basis(
    change: &Change,
    response: &ChangeAssessment,
    inputs: &InputManifest,
) -> String {
    expected_change_basis_with(change, response, &digest(inputs))
}
fn expected_change_basis_with(
    change: &Change,
    response: &ChangeAssessment,
    inputs_digest: &str,
) -> String {
    token(&(
        "supercov-change-v2",
        change,
        inputs_digest,
        &response.id,
        &response.affected_flows,
        &response.explanation,
    ))
}
pub fn change_current(map: &AssertionMap, change: &Change, inputs: &InputManifest) -> bool {
    Ledger::with_changes(map, std::slice::from_ref(change), inputs).current(&change.id)
}
/// What every token of one run shares, computed once: the manifest's digest,
/// and each change whose assessment is current with the flows it names.
///
/// Computed per flow instead, this serialised the whole manifest once per
/// flow per pending change -- minutes on a real map with a backlog of
/// changes, on every carry and every report.
pub struct Ledger<'a> {
    pub inputs_digest: String,
    keys: BTreeSet<String>,
    /// Current assessments by change id: the basis the author recorded and
    /// the flows it names.
    current: BTreeMap<&'a str, (&'a Option<String>, &'a [String])>,
}
impl<'a> Ledger<'a> {
    pub fn new(map: &'a AssertionMap, state: &'a State, inputs: &InputManifest) -> Self {
        Self::with_changes(map, &state.changes, inputs)
    }
    fn with_changes(map: &'a AssertionMap, changes: &'a [Change], inputs: &InputManifest) -> Self {
        let inputs_digest = digest(inputs);
        let keys = flow_keys(map);
        let current = changes
            .iter()
            .filter_map(|change| {
                let responses = map
                    .change_assessments
                    .iter()
                    .filter(|r| r.id == change.id)
                    .collect::<Vec<_>>();
                match responses.as_slice() {
                    [r] if change_errors_with(&keys, change, r).is_empty()
                        && r.basis.as_deref()
                            == Some(
                                expected_change_basis_with(change, r, &inputs_digest).as_str(),
                            ) =>
                    {
                        Some((change.id.as_str(), (&r.basis, r.affected_flows.as_slice())))
                    }
                    _ => None,
                }
            })
            .collect();
        Self {
            inputs_digest,
            keys,
            current,
        }
    }
    /// Whether the change has a valid, current assessment.
    pub fn current(&self, change: &str) -> bool {
        self.current.contains_key(change)
    }
    pub fn expected_change_basis(&self, change: &Change, response: &ChangeAssessment) -> String {
        expected_change_basis_with(change, response, &self.inputs_digest)
    }
    pub fn change_errors(&self, change: &Change, response: &ChangeAssessment) -> Vec<String> {
        change_errors_with(&self.keys, change, response)
    }
}
/// Why a file is one of a flow's dependencies, and where the flow sits in it.
///
/// "dependency file changed" names a file and leaves the author to work out
/// what it has to do with this claim. A flow depends on a file for one of four
/// reasons, and they call for different judgements: a node there is the claim's
/// subject, a watch is something the author asked to be told about, the test
/// file is where the claim is exercised, and the assertion's own file is where
/// it is written. Saying which -- and where the nodes are -- is the difference
/// between rereading a claim and glancing at a line number.
fn roles(a: &Assertion, f: &Flow, file: &str) -> Vec<String> {
    let mut roles: Vec<String> = Vec::new();
    let lines = f
        .nodes
        .iter()
        .filter(|n| n.at.file == file)
        .map(|n| format!("{}:{}", n.id, n.at.line))
        .collect::<Vec<_>>();
    if !lines.is_empty() {
        roles.push(format!("holds this flow's {}", lines.join(", ")));
    }
    if a.at.file == file {
        roles.push(format!("holds the assertion, line {}", a.at.line));
    }
    if f.applies_to.iter().any(|t| t.file == file) {
        roles.push("is the test this claim applies to".to_owned());
    }
    if f.watch.iter().any(|w| w == file) {
        roles.push("is watched by this flow".to_owned());
    }
    roles
}
fn in_role(roles: &[String]) -> String {
    if roles.is_empty() {
        // Every path into dependencies() is covered above; say nothing rather
        // than guess if that ever stops being true.
        String::new()
    } else {
        format!(" ({})", roles.join("; "))
    }
}
/// A file the flow rests on as a whole: the test it applies to, a file it
/// watches, the file its assertion is written in. Any change there is the
/// author's to judge; only its comments are not.
fn whole_file(a: &Assertion, f: &Flow, file: &str) -> bool {
    a.at.file == file
        || f.applies_to.iter().any(|t| t.file == file)
        || f.watch.iter().any(|w| w == file)
}
/// A claim's identity is where it points and what it says, not the line it
/// happens to be on: a file edited above a node moves the node without
/// touching the claim. Where the file has a parser's view, a node is placed by
/// the declaration holding it and how many lines of code lie between it and
/// the nearest boundary in that declaration -- the declaration's start, or the
/// end of the last nested declaration before it. Growth anywhere else, and
/// comments or blank lines anywhere, leave it in place; pointing it at another
/// statement of the same text on another line does not.
#[derive(Serialize)]
struct Site<'a> {
    file: &'a str,
    text: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    unit: Option<&'a str>,
    line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    column: Option<usize>,
}
fn site<'a>(at: &'a Anchor, inputs: &'a InputManifest) -> Site<'a> {
    let code = inputs.files.get(&at.file).and_then(|f| f.code.as_ref());
    let Some(code) = code else {
        return Site {
            file: &at.file,
            text: &at.text,
            unit: None,
            line: at.line,
            column: Some(at.column),
        };
    };
    let holder = code.unit_at(at.line, at.column);
    let mut boundary = code.units[holder].line;
    for child in code.units.iter().filter(|u| u.parent == Some(holder)) {
        if (child.end_line, child.end_column) <= (at.line, at.column) && child.end_line > boundary {
            boundary = child.end_line;
        }
    }
    Site {
        file: &at.file,
        text: &at.text,
        unit: Some(&code.units[holder].path),
        line: code
            .code_line(at.line)
            .saturating_sub(code.code_line(boundary)),
        column: None,
    }
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct NodeClaim<'a> {
    id: &'a str,
    at: Site<'a>,
    role: &'a str,
    meaning: &'a str,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct Claim<'a> {
    id: &'a str,
    explanation: &'a str,
    applies_to: &'a [TestSelector],
    nodes: Vec<NodeClaim<'a>>,
    edges: &'a [Edge],
    counts_as_asserted: &'a [String],
    watch: &'a [String],
    questions: &'a [String],
}
fn claim<'a>(f: &'a Flow, inputs: &'a InputManifest) -> Claim<'a> {
    Claim {
        id: &f.id,
        explanation: &f.explanation,
        applies_to: &f.applies_to,
        nodes: f
            .nodes
            .iter()
            .map(|n| NodeClaim {
                id: &n.id,
                at: site(&n.at, inputs),
                role: &n.role,
                meaning: &n.meaning,
            })
            .collect(),
        edges: &f.edges,
        counts_as_asserted: &f.counts_as_asserted,
        watch: &f.watch,
        questions: &f.questions,
    }
}
/// What an acknowledgement rests on in one dependency file.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
enum Footing<'a> {
    /// Named by the flow but not among the run's inputs.
    Absent,
    /// No parser reads this file; its bytes are the claim's ground.
    Bytes(&'a str),
    /// Everything the file does, comments aside.
    Semantic(&'a str),
    /// The declarations holding this flow's nodes, and the file's set of
    /// declarations. Code elsewhere in the file is answered for by what the
    /// flow's test executed, which `carry` judges.
    Units {
        structure: &'a str,
        units: BTreeMap<&'a str, &'a str>,
    },
}
fn footing<'a>(
    a: &'a Assertion,
    f: &'a Flow,
    inputs: &'a InputManifest,
) -> BTreeMap<&'a str, Footing<'a>> {
    dependencies(a, f)
        .into_iter()
        .map(|file| {
            let Some(fingerprint) = inputs.files.get(file) else {
                return (file, Footing::Absent);
            };
            let Some(code) = &fingerprint.code else {
                return (file, Footing::Bytes(&fingerprint.sha256));
            };
            if whole_file(a, f, file) {
                return (file, Footing::Semantic(&code.semantic));
            }
            let units = f
                .nodes
                .iter()
                .filter(|n| n.at.file == file)
                .flat_map(|n| code.ancestors(code.unit_at(n.at.line, n.at.column)))
                .map(|i| (code.units[i].path.as_str(), code.units[i].digest.as_str()))
                .collect();
            (
                file,
                Footing::Units {
                    structure: &code.structure,
                    units,
                },
            )
        })
        .collect()
}

fn generation(a: &Assertion, f: &Flow, state: &State, ledger: &Ledger<'_>) -> String {
    let key = flow_key(a, f);
    let base = state.flows.get(&key).map_or("0", |s| s.generation.as_str());
    let impacts = ledger
        .current
        .iter()
        .filter(|(_, (_, affected))| affected.contains(&key))
        .map(|(id, (basis, _))| (*id, *basis))
        .collect::<BTreeMap<_, _>>();
    if impacts.is_empty() {
        base.into()
    } else {
        digest(&("supercov-generation-v2", base, impacts))
    }
}
pub fn expected_basis(
    a: &Assertion,
    f: &Flow,
    map: &AssertionMap,
    state: &State,
    inputs: &InputManifest,
) -> String {
    expected_basis_with(a, f, state, inputs, &Ledger::new(map, state, inputs))
}
/// The token with the run-wide facts already in hand; what every caller with
/// more than one flow to judge should use.
pub fn expected_basis_with(
    a: &Assertion,
    f: &Flow,
    state: &State,
    inputs: &InputManifest,
    ledger: &Ledger<'_>,
) -> String {
    token(&(
        "supercov-flow-v3",
        &inputs.context_digest,
        &a.id,
        site(&a.at, inputs),
        &a.observes,
        claim(f, inputs),
        footing(a, f, inputs),
        generation(a, f, state, ledger),
    ))
}
pub fn reasons(
    a: &Assertion,
    f: &Flow,
    map: &AssertionMap,
    state: &State,
    inputs: &Inputs,
) -> BTreeSet<String> {
    reasons_for_manifest(a, f, map, state, inputs, &inputs.manifest())
}
pub fn reasons_for_manifest(
    a: &Assertion,
    f: &Flow,
    map: &AssertionMap,
    state: &State,
    inputs: &Inputs,
    manifest: &InputManifest,
) -> BTreeSet<String> {
    reasons_with(
        a,
        f,
        state,
        inputs,
        manifest,
        &Ledger::new(map, state, manifest),
    )
}
pub fn reasons_with(
    a: &Assertion,
    f: &Flow,
    state: &State,
    inputs: &Inputs,
    manifest: &InputManifest,
    ledger: &Ledger<'_>,
) -> BTreeSet<String> {
    let mut reasons = BTreeSet::new();
    if state.schema_version != 3 || state.inputs_digest != ledger.inputs_digest {
        reasons.insert("state does not match run inputs".into());
    }
    if f.basis.as_deref() != Some(expected_basis_with(a, f, state, manifest, ledger).as_str()) {
        reasons.insert(
            match f.basis.as_deref() {
                None => "draft: input acknowledgement not recorded",
                Some(basis) if superseded_basis(basis) => SUPERSEDED_BASIS,
                Some(_) => "claim or inputs changed; needs rechecking",
            }
            .into(),
        );
        if let Some(s) = state.flows.get(&flow_key(a, f)) {
            reasons.extend(s.reasons.iter().cloned());
        }
    }
    reasons.extend(validate_flow(f, &inputs.files));
    if a.at.offset(&inputs.files).is_none() {
        reasons.insert("invalid assertion anchor".into());
    }
    if !f.questions.is_empty() {
        reasons.insert("flow has unresolved questions".into());
    }
    reasons
}
/// Read-only validation. Tokens acknowledge authored claims, never prove them.
pub fn validation(map: &AssertionMap, state: &State, inputs: &Inputs) -> serde_json::Value {
    use serde_json::json;
    let manifest = inputs.manifest();
    let ledger = Ledger::new(map, state, &manifest);
    let mut errors = validate(map, inputs);
    for r in &map.change_assessments {
        if !state.changes.iter().any(|c| c.id == r.id) {
            errors.push(format!("{}: unknown change assessment", r.id));
        }
    }
    // Exposure is kept per flow but read per test: hundreds of flow keys say
    // less than the dozen tests they apply to, and cost more to page.
    let selectors = map
        .assertions
        .iter()
        .flat_map(|a| a.flows.iter().map(move |f| (flow_key(a, f), &f.applies_to)))
        .collect::<BTreeMap<_, _>>();
    let changes = state.changes.iter().map(|c| {
        let response = map.change_assessments.iter().find(|r| r.id == c.id);
        let faults = response.map(|r| ledger.change_errors(c, r)).unwrap_or_default();
        errors.extend(faults.iter().map(|e| format!("{}: {e}", c.id)));
        let tests = c.exposed.iter().filter_map(|k| selectors.get(k)).flat_map(|t| t.iter()).collect::<BTreeSet<_>>();
        json!({"id":c.id,"file":c.file,"before":c.before,"after":c.after,"reason":c.reason,"knownFlows":c.known_flows,
            "exposed":{"flows":c.exposed.len(),"tests":tests,"sample":c.exposed.iter().take(8).collect::<Vec<_>>()},
            "current":ledger.current(&c.id),"assessment":response,"errors":faults,
            "expectedBasis":response.map(|r| ledger.expected_change_basis(c,r))})
    }).collect::<Vec<_>>();
    let flows = map.assertions.iter().flat_map(|a| a.flows.iter().map(move |f| (a,f))).map(|(a,f)| {
        json!({"id":flow_key(a,f),"expectedBasis":expected_basis_with(a,f,state,&manifest,&ledger),"reasons":reasons_with(a,f,state,inputs,&manifest,&ledger)})
    }).collect::<Vec<_>>();
    json!({"valid":errors.is_empty(),"stage":"references","errors":errors,"flows":flows,"changes":changes,
        "meaning":"Authored graph references and input acknowledgements only; no semantic proof or completeness claim"})
}
pub fn invalidate(state: &mut State, map: &AssertionMap, reason: &str) {
    for a in &map.assertions {
        for f in &a.flows {
            let key = flow_key(a, f);
            let base = state.flows.get(&key).map_or("0", |s| s.generation.as_str());
            state.flows.insert(
                key,
                FlowState {
                    generation: digest(&(base, reason, &state.inputs_digest)),
                    reasons: BTreeSet::from([reason.into()]),
                    notices: BTreeSet::new(),
                },
            );
        }
    }
}
pub fn add_change(
    state: &mut State,
    file: Option<String>,
    before: Option<String>,
    after: Option<String>,
    reason: String,
    known_flows: BTreeSet<String>,
    exposed: BTreeSet<String>,
) {
    // Include pending history so edit/revert/edit cannot alias a still-pending event.
    let id = format!(
        "c_{}",
        &digest(&(
            "supercov-change-id-v2",
            &state.changes,
            &file,
            &before,
            &after,
            &reason
        ))[..24]
    );
    state.changes.push(Change {
        id,
        file,
        before,
        after,
        reason,
        known_flows,
        exposed,
    });
}

fn unique_occurrence(text: &str, snippet: &str) -> Option<usize> {
    if snippet.is_empty() {
        return None;
    }
    let first = text.find(snippet)?;
    // Include overlapping occurrences; match_indices skips them.
    let next = first + text[first..].chars().next()?.len_utf8();
    text[next..]
        .contains(snippet)
        .then_some(())
        .map_or(Some(first), |_| None)
}
fn target_file(file: &str, old: &FileManifest, new: &Files) -> Option<String> {
    if new.contains_key(file) {
        return Some(file.into());
    }
    let hash = old.get(file)?;
    let mut matches = new
        .iter()
        .filter(|(_, s)| FileFingerprint::of(s).same_bytes(hash));
    let first = matches.next()?.0;
    matches.next().is_none().then(|| first.clone())
}
pub fn relocate(at: &Anchor, old: &FileManifest, new: &Files) -> Option<Anchor> {
    let before = old.get(&at.file)?;
    let target = target_file(&at.file, old, new)?;
    let after = &new[&target];
    let mut candidate = at.clone();
    candidate.file.clone_from(&target);
    if FileFingerprint::of(after).same_bytes(before) && candidate.offset(new).is_some() {
        return Some(candidate);
    }
    // The file changed somewhere. That says nothing about this anchor: read the
    // recorded position in the new file and see whether it still holds the same
    // text. If it does, the anchor did not move and there is nothing to find.
    //
    // Without this, every anchor in a changed file is re-found by searching the
    // whole file, and that search insists the text be unique -- so a statement
    // that appears twice is reported "changed or ambiguous" while sitting
    // untouched at the line it was recorded at. That is a false statement about
    // a specific node, and it is most of the staleness in a real map.
    if let Some(start) = candidate.offset(new)
        && after.get(start..start + at.text.len()) == Some(at.text.as_str())
    {
        return Some(candidate);
    }
    let position = unique_occurrence(after, &at.text)?;
    Some(Anchor::new(
        &target,
        after,
        position,
        position + at.text.len(),
    ))
}

/// How one captured file moved between two runs, judged once and read for
/// every flow.
pub enum FileChange<'a> {
    Same,
    /// Only comments changed: no program can tell.
    CommentsOnly,
    /// Not among the previous run's inputs.
    Added,
    Removed,
    /// No parser reads the file on one side or the other; its bytes moved.
    Bytes,
    Code {
        before: &'a Code,
        after: &'a Code,
        diff: Diff,
        /// The change is confined to declaration bodies that only run: it
        /// reaches a test only if the test ran one of them.
        narrow: bool,
    },
}
pub fn file_change<'a>(
    before: Option<&'a FileFingerprint>,
    after: Option<&'a FileFingerprint>,
    probed: Option<&[usize]>,
) -> Option<FileChange<'a>> {
    let Some(before) = before else {
        return after.map(|_| FileChange::Added);
    };
    let Some(after) = after else {
        return Some(FileChange::Removed);
    };
    if before.same_bytes(after) {
        return Some(FileChange::Same);
    }
    let (Some(old), Some(new)) = (&before.code, &after.code) else {
        return Some(FileChange::Bytes);
    };
    if old.semantic == new.semantic {
        return Some(FileChange::CommentsOnly);
    }
    let diff = old.diff(new);
    let narrow = probed.is_some_and(|probed| diff.narrow(old, probed));
    Some(FileChange::Code {
        before: old,
        after: new,
        diff,
        narrow,
    })
}
/// Every unit that moved, by name: what changed, what arrived, what went.
pub fn describe(before: &Code, after: &Code, diff: &Diff) -> String {
    let mut parts = Vec::new();
    if !diff.changed.is_empty() {
        parts.push(named(diff.changed.iter().map(|i| &before.units[*i])));
    }
    if !diff.added.is_empty() {
        parts.push(format!(
            "added {}",
            named(diff.added.iter().map(|i| &after.units[*i]))
        ));
    }
    if !diff.removed.is_empty() {
        parts.push(format!(
            "removed {}",
            named(diff.removed.iter().map(|i| &before.units[*i]))
        ));
    }
    if parts.is_empty() {
        "declarations".to_owned()
    } else {
        parts.join("; ")
    }
}
/// The units a flow's tests executed, per file, each with what it sits
/// inside; `None` when a selected test has no execution record in this state,
/// in which case nothing about execution can be assumed.
fn executed<'s>(
    records: &BTreeMap<&TestSelector, &'s Execution>,
    f: &Flow,
    manifest: &InputManifest,
) -> Option<BTreeMap<&'s str, BTreeSet<usize>>> {
    let mut out: BTreeMap<&str, BTreeSet<usize>> = BTreeMap::new();
    for selector in &f.applies_to {
        let record = records.get(selector)?;
        for (file, units) in &record.files {
            let code = manifest.files.get(file).and_then(|fp| fp.code.as_ref());
            let set = out.entry(file.as_str()).or_default();
            for &unit in units {
                match code {
                    Some(code) if unit < code.units.len() => set.extend(code.ancestors(unit)),
                    _ => {
                        set.insert(unit);
                    }
                }
            }
        }
    }
    Some(out)
}

/// Carries explanations, never execution events. Uncertain matches are retained
/// as retired suggestions; no nearest-line heuristic assigns semantic meaning.
///
/// A flow goes stale for a change to what its claim rests on and for nothing
/// else: the declarations holding its nodes and the top level of their files,
/// the test it applies to, a file it watches, its assertion, the run's
/// context. A change elsewhere in a node's file is a notice. A change to
/// comments or blank lines is nothing.
///
/// What each flow's test executed does not make the flow stale -- a claim
/// does not pass through every function its test happened to run, and an
/// acknowledgement demanded for all of them at once stops being read. It goes
/// on the change record instead: a changed file names the flows whose tests
/// ran the changed code, so the one assessment the change asks for is asked
/// of the right people, and a change nobody ran asks for none.
pub fn carry(
    map: &AssertionMap,
    state: &State,
    old: &InputManifest,
    new: &Inputs,
    evidence_digest: &str,
    context_changed: bool,
) -> Result<(AssertionMap, State), String> {
    if map.schema_version != 2 || old.schema_version != 2 || new.schema_version != 1 {
        return Err("unsupported map/input schema version".into());
    }
    if state.inputs_digest != digest(old) || state.schema_version != 3 {
        return Err("old map state does not match its run inputs".into());
    }
    let ledger = Ledger::new(map, state, old);
    let new_manifest = new.manifest();
    let (mut next, mut next_state) = seed_manifest(&new_manifest, evidence_digest);
    next.assertions.clear();
    next.retired_assertions = map.retired_assertions.clone();
    next_state.changes = state
        .changes
        .iter()
        .filter(|c| !ledger.current(&c.id))
        .cloned()
        .collect();
    next.change_assessments = map
        .change_assessments
        .iter()
        .filter(|r| next_state.changes.iter().any(|c| c.id == r.id))
        .cloned()
        .collect();
    let records = state
        .executions
        .iter()
        .flat_map(|e| e.tests.iter().map(|t| (&t.test, t)))
        .collect::<BTreeMap<_, _>>();
    let probed = |file: &str| {
        state
            .executions
            .as_ref()
            .and_then(|e| e.probed.get(file))
            .map(Vec::as_slice)
    };
    let changes = old
        .files
        .keys()
        .chain(new_manifest.files.keys())
        .collect::<BTreeSet<_>>()
        .into_iter()
        .filter_map(|file| {
            file_change(
                old.files.get(file),
                new_manifest.files.get(file),
                probed(file),
            )
            .map(|change| (file.as_str(), change))
        })
        .collect::<BTreeMap<_, _>>();
    // Per changed file: the flows it made stale, and the flows whose tests ran
    // the changed code or have no record to say -- what the change record
    // names as known and as exposed.
    let mut marked: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
    let mut exposed: BTreeMap<&str, BTreeSet<String>> = BTreeMap::new();
    let mut consumed = BTreeSet::new();
    let exact = map
        .assertions
        .iter()
        .map(|a| {
            relocate(&a.at, &old.files, &new.files).filter(|at| {
                new.assertions.iter().any(|s| &s.at == at)
                    || !old.assertions.iter().any(|s| s.at == a.at)
            })
        })
        .collect::<Vec<_>>();
    let reserved = exact.iter().flatten().collect::<BTreeSet<_>>();
    for (index, a) in map.assertions.iter().enumerate() {
        // A sole old/new unmatched site in the same file is a review
        // suggestion. Preserve its explanation but never its reviewed status.
        let candidates = new
            .assertions
            .iter()
            .filter(|s| s.at.file == a.at.file && !reserved.contains(&s.at))
            .collect::<Vec<_>>();
        let unmatched = map
            .assertions
            .iter()
            .zip(&exact)
            .filter(|(other, at)| other.at.file == a.at.file && at.is_none())
            .count();
        let replacement = if exact[index].is_none() && unmatched == 1 && candidates.len() == 1 {
            Some(&candidates[0].at)
        } else {
            None
        };
        let matched = exact[index]
            .as_ref()
            .or(replacement)
            .filter(|at| !consumed.contains(*at));
        let Some(at) = matched else {
            next.retired_assertions.push(Retired {
                assertion: a.clone(),
                reason:
                    "assertion removed, changed or ambiguous; reuse its explanation after review"
                        .into(),
            });
            continue;
        };
        consumed.insert(at.clone());
        let mut updated = a.clone();
        updated.at = at.clone();
        for (prior, f) in a.flows.iter().zip(&mut updated.flows) {
            let key = flow_key(a, f);
            let base = generation(a, prior, state, &ledger);
            let mut dirty = BTreeSet::new();
            let mut notices = BTreeSet::new();
            match prior.basis.as_deref() {
                Some(basis) if superseded_basis(basis) => {
                    dirty.insert(SUPERSEDED_BASIS.into());
                }
                Some(basis) if basis != expected_basis_with(a, prior, state, old, &ledger) => {
                    dirty.insert("inherited claim still needs rechecking".into());
                }
                _ => {}
            }
            // What the flow's test ran, for the change record: a changed file
            // is assessed by whoever ran the change, and a change nobody ran
            // is not assessed at all.
            match executed(&records, prior, old) {
                Some(ran) => {
                    for (file, units) in &ran {
                        let reached = match changes.get(file) {
                            None
                            | Some(
                                FileChange::Same | FileChange::CommentsOnly | FileChange::Added,
                            ) => false,
                            Some(FileChange::Removed | FileChange::Bytes) => true,
                            Some(FileChange::Code { diff, narrow, .. }) => {
                                !*narrow || diff.changed.iter().any(|i| units.contains(i))
                            }
                        };
                        if reached {
                            exposed.entry(file).or_default().insert(key.clone());
                        }
                    }
                }
                None => {
                    for (file, change) in &changes {
                        if !matches!(
                            change,
                            FileChange::Same | FileChange::CommentsOnly | FileChange::Added
                        ) {
                            exposed.entry(file).or_default().insert(key.clone());
                        }
                    }
                }
            }
            // What the flow names: its test, its watch list and its assertion's
            // file as a whole; the file of a node for the declarations that
            // hold the node, its top level and its set of declarations.
            for file in dependencies(a, prior) {
                let roles = roles(a, prior, file);
                let verdict = match changes.get(file) {
                    None => Some(format!(
                        "{file} is not among the run's inputs{}",
                        in_role(&roles)
                    )),
                    Some(FileChange::Added) => Some(format!(
                        "{file} is new since the previous run{}",
                        in_role(&roles)
                    )),
                    Some(FileChange::Same | FileChange::CommentsOnly) => None,
                    Some(FileChange::Removed) => Some(format!("{file} removed{}", in_role(&roles))),
                    Some(FileChange::Bytes) => Some(format!("{file} changed{}", in_role(&roles))),
                    Some(FileChange::Code {
                        before,
                        after,
                        diff,
                        ..
                    }) => {
                        if whole_file(a, prior, file) {
                            Some(format!(
                                "{file}: {} changed{}",
                                describe(before, after, diff),
                                in_role(&roles)
                            ))
                        } else {
                            let holders = prior
                                .nodes
                                .iter()
                                .filter(|n| n.at.file == file)
                                .flat_map(|n| {
                                    before.ancestors(before.unit_at(n.at.line, n.at.column))
                                })
                                .collect::<BTreeSet<_>>();
                            let moved = holders
                                .iter()
                                .filter(|i| diff.changed.contains(i) || diff.removed.contains(i))
                                .map(|i| &before.units[*i])
                                .collect::<Vec<_>>();
                            if !moved.is_empty() {
                                Some(format!(
                                    "{file}: {} changed{}",
                                    named(moved),
                                    in_role(&roles)
                                ))
                            } else if diff.structural {
                                Some(format!(
                                    "{file}: declarations changed, {}{}",
                                    describe(before, after, diff),
                                    in_role(&roles)
                                ))
                            } else {
                                notices.insert(format!(
                                    "{file} changed outside this flow's nodes: {}",
                                    describe(before, after, diff)
                                ));
                                None
                            }
                        }
                    }
                };
                if let Some(reason) = verdict {
                    dirty.insert(reason);
                    marked.entry(file).or_default().insert(key.clone());
                }
            }
            if replacement.is_some() {
                dirty.insert("assertion changed or replaced; confirm identity and meaning".into());
            }
            for node in &mut f.nodes {
                if let Some(at) = relocate(&node.at, &old.files, &new.files) {
                    node.at = at;
                } else {
                    dirty.insert(format!("node {} changed or ambiguous", node.id));
                }
            }
            for file in f
                .watch
                .iter_mut()
                .chain(f.applies_to.iter_mut().map(|t| &mut t.file))
            {
                if let Some(target) = target_file(file, &old.files, &new.files) {
                    *file = target;
                } else {
                    dirty.insert(format!("dependency file removed: {file}"));
                }
            }
            if context_changed {
                dirty.insert("run configuration, dependencies or execution context changed".into());
            }
            next_state.flows.insert(
                key,
                FlowState {
                    generation: if dirty.is_empty() {
                        base
                    } else {
                        digest(&("supercov-carry-v3", base, &new_manifest, &dirty))
                    },
                    reasons: dirty,
                    notices,
                },
            );
        }
        next.assertions.push(updated);
    }
    let mut ids = map
        .assertions
        .iter()
        .map(|a| a.id.clone())
        .chain(
            map.retired_assertions
                .iter()
                .map(|r| r.assertion.id.clone()),
        )
        .collect::<BTreeSet<_>>();
    for a in seed(new, evidence_digest).0.assertions {
        if !consumed.contains(&a.at) {
            let mut a = a;
            while !ids.insert(a.id.clone()) {
                a.id.push('_');
            }
            next.assertions.push(a);
        }
    }
    for file in old
        .files
        .keys()
        .chain(new_manifest.files.keys())
        .collect::<BTreeSet<_>>()
    {
        // A manifest is answered for by the run's dependency fingerprint, which
        // reads what it declares. Reporting its bytes here as well would make
        // cutting a release look like a change to assess when nothing about the
        // project moved.
        if crate::integrity::tracked_manifest(file) {
            continue;
        }
        let exposed_to = exposed.get(file.as_str()).cloned().unwrap_or_default();
        match changes.get(file.as_str()) {
            // A comment is not a change to assess.
            Some(FileChange::Same | FileChange::CommentsOnly) => continue,
            // A change confined to code that only runs, which no selected test
            // ran, cannot have reached any claim; the flow claiming that code
            // is already stale for it. Nothing to ask.
            Some(FileChange::Code { narrow: true, .. }) if exposed_to.is_empty() => continue,
            _ => {}
        }
        add_change(
            &mut next_state,
            Some(file.clone()),
            old.files.get(file).map(|f| f.sha256.clone()),
            new_manifest.files.get(file).map(|f| f.sha256.clone()),
            "captured source file changed".into(),
            marked.get(file.as_str()).cloned().unwrap_or_default(),
            exposed_to,
        );
    }
    next.assertions.sort_by(|a, b| a.at.cmp(&b.at));
    Ok((next, next_state))
}

#[path = "assertion_legacy.rs"]
mod legacy;
pub fn parse_stored(bytes: &[u8]) -> Result<AssertionMap, String> {
    let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
    match value
        .get("schemaVersion")
        .and_then(serde_json::Value::as_u64)
    {
        None | Some(1) => legacy::import(bytes),
        _ => parse(bytes).map_err(|e| e.to_string()),
    }
}
pub fn parse_state(
    bytes: &[u8],
    map: &AssertionMap,
    inputs: &InputManifest,
    evidence: &str,
    legacy_digest: Option<&str>,
) -> Result<State, String> {
    let value: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
    if value["schemaVersion"] == 3 {
        let state: State = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
        if state.inputs_digest != digest(inputs) || state.evidence_digest != evidence {
            return Err("Assertion state belongs to different run evidence; rerun tests".into());
        }
        Ok(state)
    } else {
        legacy::state(bytes, map, inputs, evidence, legacy_digest)
    }
}