vela-protocol 0.912.0

Core library for the Vela scientific knowledge protocol: replayable frontier state, signed canonical events, and proof packets.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
//! Content-addressed finding bundles: the atomic object of the Vela protocol.

use std::collections::BTreeMap;

use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};

/// Valid assertion types per schema.
///
/// v0.10 added `measurement` and `exclusion` for measurement-heavy domains
/// (physics, chemistry, climate, materials) where the substance of a
/// finding is a numerical value or an exclusion limit at a confidence level.
pub const VALID_ASSERTION_TYPES: &[&str] = &[
    "mechanism",
    "observational",
    "computational",
    "theoretical",
    "negative",
    // v0.10
    "measurement",
    "exclusion",
    // v0.30: Notes Compiler emits these for proposals derived from
    // researcher zettelkasten / Obsidian vaults. They become canonical
    // findings on accept; rejecting them at the validator would force a
    // post-hoc rewrite that breaks content-addressed ids. The semantic
    // intent: `tension` = a theoretical claim about a field-level
    // contradiction (paired claims that don't reconcile); `open_question`
    // = an unresolved framing the agent surfaced; `hypothesis` = a
    // provisional candidate claim awaiting evidence. The notes-compiler
    // proposals doc covers how these are produced.
    "tension",
    "open_question",
    "hypothesis",
    "candidate_finding",
];

/// Valid artifact kinds for the generic `Artifact` kernel object.
///
/// `Dataset` and `CodeArtifact` remain as stronger, typed legacy objects.
/// `Artifact` is the shared substrate path for files and records that need
/// durable byte or pointer provenance before a domain-specific object exists.
pub const VALID_ARTIFACT_KINDS: &[&str] = &[
    "dataset",
    "clinical_trial_record",
    "protocol",
    "supplement",
    "notebook",
    "code",
    "model_output",
    "table",
    "figure",
    "registry_record",
    "lab_file",
    "source_file",
    "other",
];

pub fn valid_artifact_kind(kind: &str) -> bool {
    VALID_ARTIFACT_KINDS.contains(&kind)
}

/// Valid evidence types per schema.
pub const VALID_EVIDENCE_TYPES: &[&str] = &[
    "experimental",
    "observational",
    "computational",
    "theoretical",
    // v0.30: Notes Compiler — the evidence span lives in the researcher's
    // zettelkasten note rather than a primary literature passage.
    // Treated as an `expert_assertion`-shaped evidence kind.
    "extracted_from_notes",
];

/// Valid provenance source types per schema.
///
/// v0.10 added `data_release` for instrument runs, observation campaigns,
/// and dataset versions that are themselves the substantive object — distinct
/// from the paper that reports them (XENONnT SR0, Planck data releases,
/// JWST observation runs, LHC analysis releases).
pub const VALID_PROVENANCE_SOURCE_TYPES: &[&str] = &[
    "published_paper",
    "preprint",
    "model_output",
    "expert_assertion",
    "database_record",
    // v0.10
    "data_release",
    // v0.30: notes-compiler proposals cite the source markdown note
    // by filename. Distinct from `lab_notebook` (which implies a
    // dated lab workbook entry with primary observations) and
    // `expert_assertion` (which implies a named expert's claim).
    "researcher_notes",
];

/// Valid link types per protocol §5.
///
/// T7 (FrontierGraph substrate) extends the vocabulary with the
/// relation kinds the typed-edge layer reasons over. The conceptual
/// T7 set is SUPPORTS / CONTRADICTS / DEPENDS_ON / DERIVED_FROM /
/// IMPROVES / GENERALIZES / SPECIALIZES / SUPERSEDES; the existing
/// lowercase strings already cover DEPENDS_ON (`depends`) and
/// DERIVED_FROM (`synthesized_from`), so only the three genuinely new
/// concepts are added here. `extends` and `replicates` predate T7 and
/// stay. No redundant aliases — the FrontierGraph EdgeKind layer maps
/// strings to the canonical T7 vocabulary.
pub const VALID_LINK_TYPES: &[&str] = &[
    "supports",
    "contradicts",
    "extends",
    "depends",
    "replicates",
    "supersedes",
    "synthesized_from",
    // T7 additions:
    "improves",
    "generalizes",
    "specializes",
    // cross-domain transfer (vtr_):
    "discharges",
];

/// The local finding id of a link target, stripping any cross-frontier
/// `@vfr_…` suffix. A `vf_X@vfr_Y` target resolves to `vf_X`; a plain
/// `vf_X` is returned unchanged. Single source of truth for the
/// resolution the graph builders and read tools all rely on.
#[must_use]
pub fn bare_finding_id(target: &str) -> &str {
    target.split('@').next().unwrap_or(target)
}

/// A resolved identifier from a scientific database.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedId {
    /// The database source (mesh, uniprot, pubchem, chebi, go, ncbi_gene).
    pub source: String,
    /// The identifier value (e.g., "D000544", "Q6ZSS7", "24752728").
    pub id: String,
    /// Confidence in this resolution (0.0-1.0).
    pub confidence: f64,
    /// The matched name in the source database.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub matched_name: Option<String>,
}

/// How an entity was resolved to its canonical form (v0.2.0 schema).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResolutionMethod {
    ExactMatch,
    FuzzyMatch,
    LlmInference,
    Manual,
}

impl std::fmt::Display for ResolutionMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResolutionMethod::ExactMatch => write!(f, "exact_match"),
            ResolutionMethod::FuzzyMatch => write!(f, "fuzzy_match"),
            ResolutionMethod::LlmInference => write!(f, "llm_inference"),
            ResolutionMethod::Manual => write!(f, "manual"),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entity {
    pub name: String,
    #[serde(rename = "type")]
    pub entity_type: String,
    /// Deprecated: flat identifiers map. Retained for backward compatibility with
    /// older frontier JSON files. New code should use `canonical_id` and `candidates`.
    #[serde(default)]
    pub identifiers: serde_json::Map<String, serde_json::Value>,
    /// The primary resolved identifier (if resolved).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_id: Option<ResolvedId>,
    /// Alternative resolution candidates with scores.
    #[serde(default)]
    pub candidates: Vec<ResolvedId>,
    /// Known aliases for this entity (e.g., NLRP3 = cryopyrin = NALP3).
    #[serde(default)]
    pub aliases: Vec<String>,
    /// How this resolution was performed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution_provenance: Option<String>,
    #[serde(default = "default_one")]
    pub resolution_confidence: f64,
    /// How the entity was resolved: exact_match, fuzzy_match, llm_inference, manual.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution_method: Option<ResolutionMethod>,
    /// Species context for orthologs (e.g., "Homo sapiens" vs "Mus musculus" for APP).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub species_context: Option<String>,
    /// True when resolution_confidence < 0.8 and the match needs human review.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub needs_review: bool,
}

fn default_one() -> f64 {
    1.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Evidence {
    #[serde(rename = "type")]
    pub evidence_type: String,
    #[serde(default)]
    pub model_system: String,
    #[serde(default)]
    pub method: String,
    // v0.700: the empirical-measurement slots (species/sample_size/effect_size/
    // p_value) were removed — unused in the math wedge, stripped from every live
    // finding by the re-genesis, byte-identical to their skip-guarded form.
    #[serde(default)]
    pub replicated: bool,
    pub replication_count: Option<u32>,
    #[serde(default)]
    pub evidence_spans: Vec<serde_json::Value>,
}

/// v0.33: Dataset as a first-class kernel object.
///
/// A `Dataset` is a versioned, content-addressed reference to data
/// that anchors empirical claims. Before v0.33, datasets were strings
/// in `Provenance.title` or entity-typed mentions in assertions —
/// a claim could say "we used ADNI" without anchoring which release
/// of ADNI the analysis ran against, and re-running the same code on
/// a refreshed cohort silently produced a "different" claim.
///
/// `vd_<id>` is content-addressed over `name + version + content_hash
/// + url`. Two dataset records with the same name but different
/// versions get distinct ids; two records pointing at the same
/// snapshot collapse to the same id. Claims can reference the exact
/// bytes they rest on, not only a dataset name in prose.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dataset {
    /// `vd_<16hex>`, content-addressed; see `Dataset::content_address`.
    pub id: String,
    /// Human-readable name (e.g. "ADNI", "TRAILBLAZER-ALZ", "MIMIC-IV").
    pub name: String,
    /// Semantic version or release tag (e.g. "ADNI-3", "v2.2", "SR0").
    /// Two entries differing only in version are distinct kernel objects.
    pub version: Option<String>,
    /// Optional column-level schema as `(name, type)` pairs. For
    /// non-tabular datasets, leave empty.
    #[serde(default)]
    pub schema: Vec<(String, String)>,
    /// Number of rows / observations / records, when known.
    pub row_count: Option<u64>,
    /// SHA-256 of the canonical contents, when computable. For
    /// large datasets stored remotely, this is the publisher's
    /// declared content hash; integrity verification is the puller's
    /// job (same pattern as `vfr_*` snapshots).
    pub content_hash: String,
    /// Where the dataset is reachable (https URL, file://, s3://, etc.).
    pub url: Option<String>,
    /// License identifier or URL (e.g. "CC-BY-4.0", a Crossref license).
    pub license: Option<String>,
    /// Provenance of the dataset itself — typically the paper or release
    /// that publishes it. Reuses `Provenance` for shape parity with
    /// findings.
    pub provenance: Provenance,
    /// RFC 3339 creation timestamp.
    pub created: String,
}

impl Dataset {
    /// Compute the content-addressed ID per v0.33 spec:
    /// `SHA-256(name | version | content_hash | url)`.
    /// Returns first 16 hex chars prefixed with "vd_".
    pub fn content_address(
        name: &str,
        version: Option<&str>,
        content_hash: &str,
        url: Option<&str>,
    ) -> String {
        let preimage = format!(
            "{}|{}|{}|{}",
            name,
            version.unwrap_or(""),
            content_hash,
            url.unwrap_or("")
        );
        let hash = Sha256::digest(preimage.as_bytes());
        format!("vd_{}", &hex::encode(hash)[..16])
    }

    /// Construct a new Dataset with a freshly-derived id and `created`
    /// timestamp set to now.
    pub fn new(
        name: impl Into<String>,
        version: Option<String>,
        content_hash: impl Into<String>,
        url: Option<String>,
        license: Option<String>,
        provenance: Provenance,
    ) -> Self {
        let n = name.into();
        let h = content_hash.into();
        let id = Self::content_address(&n, version.as_deref(), &h, url.as_deref());
        Self {
            id,
            name: n,
            version,
            schema: Vec::new(),
            row_count: None,
            content_hash: h,
            url,
            license,
            provenance,
            created: Utc::now().to_rfc3339(),
        }
    }
}

/// v0.33: CodeArtifact as a first-class kernel object.
///
/// A `CodeArtifact` is a content-addressed pointer at a specific
/// region of source code (a function, a notebook cell, a script, a
/// pipeline step) at a specific git commit. Before v0.33, code was
/// captured as a string in `Evidence.method` — "we ran a logistic
/// regression" — with no way for a reader to verify which code
/// produced the result, or to re-run it.
///
/// `vc_<id>` is content-addressed over `repo_url + git_commit + path
/// + line_range + content_hash`. The same code at two commits gets
/// two records (the relevant historical fact); the same code in two
/// paths in the same repo also gets two records (location matters
/// for re-execution).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeArtifact {
    /// `vc_<16hex>`, content-addressed; see `CodeArtifact::content_address`.
    pub id: String,
    /// Source language: `python` / `r` / `julia` / `rust` / `bash`,
    /// etc. Not validated against a closed allow-list — code provenance
    /// should accept whatever language the analysis was actually in.
    pub language: String,
    /// Repository URL (e.g. `https://github.com/vela-science/vela`).
    pub repo_url: Option<String>,
    /// Specific git commit (40-char SHA preferred). Required for
    /// reproducibility; `None` means "unpinned" and weakens the
    /// substrate claim.
    pub git_commit: Option<String>,
    /// Path within the repository (e.g. `crates/producer/src/notes.rs`).
    pub path: String,
    /// Optional line range as `(start, end)`, both inclusive.
    pub line_range: Option<(u32, u32)>,
    /// SHA-256 of the snippet body. Decouples the artifact from the
    /// repository's external state — even if a repo is deleted, the
    /// content_hash remains anchored.
    pub content_hash: String,
    /// Optional entry point: function name, notebook cell id, or
    /// `__main__`. Used by re-execution tooling.
    pub entry_point: Option<String>,
    /// RFC 3339 creation timestamp.
    pub created: String,
}

impl CodeArtifact {
    /// Compute the content-addressed ID per v0.33 spec:
    /// `SHA-256(repo_url | git_commit | path | line_range | content_hash)`.
    /// Returns first 16 hex chars prefixed with "vc_".
    pub fn content_address(
        repo_url: Option<&str>,
        git_commit: Option<&str>,
        path: &str,
        line_range: Option<(u32, u32)>,
        content_hash: &str,
    ) -> String {
        let lr = line_range
            .map(|(a, b)| format!("{a}-{b}"))
            .unwrap_or_default();
        let preimage = format!(
            "{}|{}|{}|{}|{}",
            repo_url.unwrap_or(""),
            git_commit.unwrap_or(""),
            path,
            lr,
            content_hash
        );
        let hash = Sha256::digest(preimage.as_bytes());
        format!("vc_{}", &hex::encode(hash)[..16])
    }

    /// Construct a new CodeArtifact with a freshly-derived id and
    /// `created` timestamp.
    pub fn new(
        language: impl Into<String>,
        repo_url: Option<String>,
        git_commit: Option<String>,
        path: impl Into<String>,
        line_range: Option<(u32, u32)>,
        content_hash: impl Into<String>,
        entry_point: Option<String>,
    ) -> Self {
        let p = path.into();
        let h = content_hash.into();
        let id = Self::content_address(
            repo_url.as_deref(),
            git_commit.as_deref(),
            &p,
            line_range,
            &h,
        );
        Self {
            id,
            language: language.into(),
            repo_url,
            git_commit,
            path: p,
            line_range,
            content_hash: h,
            entry_point,
            created: Utc::now().to_rfc3339(),
        }
    }
}

/// Generic content-addressed artifact.
///
/// This is the common substrate object for records and files that are not
/// only papers: trial registry snapshots, protocols, supplements, notebooks,
/// tables, figures, model outputs, lab files, and dataset manifests. Typed
/// objects such as `Dataset` and `CodeArtifact` still exist because they
/// carry stronger domain-specific fields. `Artifact` gives every byte or
/// pointer the same minimum durability contract.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactDisclosure {
    Public,
    Restricted,
    #[default]
    Unknown,
}

impl ArtifactDisclosure {
    pub(crate) fn is_unknown(value: &Self) -> bool {
        *value == Self::Unknown
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LocatorIntegrity {
    Immutable,
    Mutable,
    #[default]
    Unknown,
}

impl LocatorIntegrity {
    pub(crate) fn is_unknown(value: &Self) -> bool {
        *value == Self::Unknown
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactAvailability {
    Available,
    Unavailable,
    #[default]
    Unknown,
}

impl ArtifactAvailability {
    pub(crate) fn is_unknown(value: &Self) -> bool {
        *value == Self::Unknown
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Artifact {
    /// `va_<16hex>`, content-addressed over kind, name, hash, source, and
    /// locator.
    pub id: String,
    /// One of `VALID_ARTIFACT_KINDS`.
    pub kind: String,
    /// Human-readable label.
    pub name: String,
    /// SHA-256 commitment. Convention: `sha256:<64hex>`.
    pub content_hash: String,
    /// Byte count when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub size_bytes: Option<u64>,
    /// MIME type or close equivalent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,
    /// `local_blob`, `local_file`, `remote`, or `pointer`.
    pub storage_mode: String,
    /// Independent disclosure axis. Missing on legacy artifacts means
    /// `unknown`, never silently `public`.
    #[serde(default, skip_serializing_if = "ArtifactDisclosure::is_unknown")]
    pub disclosure: ArtifactDisclosure,
    /// Locator mutability is independent from storage and disclosure.
    #[serde(default, skip_serializing_if = "LocatorIntegrity::is_unknown")]
    pub locator_integrity: LocatorIntegrity,
    /// Observed availability is independent from locator integrity.
    #[serde(default, skip_serializing_if = "ArtifactAvailability::is_unknown")]
    pub availability: ArtifactAvailability,
    /// Local relative path, file path, HTTPS URL, S3 URL, or registry locator.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub locator: Option<String>,
    /// Original upstream URL or accession, distinct from a mirrored blob path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_url: Option<String>,
    /// License identifier, URL, or access terms note.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
    /// Findings this artifact directly bears on.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_findings: Vec<String>,
    /// Pointer to the source record that described this artifact, if one
    /// already exists in `sources`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source_id: Option<String>,
    /// Artifact-level provenance. The source record may be a registry,
    /// repository, dataset portal, protocol page, or paper.
    pub provenance: Provenance,
    /// Structured adapter metadata such as NCT id, outcomes, accession ids,
    /// version tags, or retrieval timestamps.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub metadata: BTreeMap<String, Value>,
    /// Review lifecycle for the artifact itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub review_state: Option<ReviewState>,
    #[serde(default)]
    pub retracted: bool,
    #[serde(default)]
    pub access_tier: crate::access_tier::AccessTier,
    /// RFC 3339 creation timestamp.
    pub created: String,
}

impl Artifact {
    pub fn content_address(
        kind: &str,
        name: &str,
        content_hash: &str,
        source_url: Option<&str>,
        locator: Option<&str>,
    ) -> String {
        let preimage = format!(
            "{}|{}|{}|{}|{}",
            kind,
            name,
            content_hash,
            source_url.unwrap_or(""),
            locator.unwrap_or("")
        );
        let hash = Sha256::digest(preimage.as_bytes());
        format!("va_{}", &hex::encode(hash)[..16])
    }

    /// Content-address a descriptor that opts into the independent reference
    /// axes. The all-unknown shape deliberately delegates to the legacy
    /// preimage so existing artifact IDs remain stable.
    #[allow(clippy::too_many_arguments)]
    pub fn content_address_with_axes(
        kind: &str,
        name: &str,
        content_hash: &str,
        source_url: Option<&str>,
        locator: Option<&str>,
        disclosure: ArtifactDisclosure,
        locator_integrity: LocatorIntegrity,
        availability: ArtifactAvailability,
    ) -> String {
        if disclosure == ArtifactDisclosure::Unknown
            && locator_integrity == LocatorIntegrity::Unknown
            && availability == ArtifactAvailability::Unknown
        {
            return Self::content_address(kind, name, content_hash, source_url, locator);
        }
        let preimage = crate::canonical::to_canonical_bytes(&serde_json::json!({
            "schema": "vela.artifact-reference-axes.v1",
            "kind": kind,
            "name": name,
            "content_hash": content_hash,
            "source_url": source_url,
            "locator": locator,
            "disclosure": disclosure,
            "locator_integrity": locator_integrity,
            "availability": availability,
        }))
        .unwrap_or_default();
        let hash = Sha256::digest(preimage);
        format!("va_{}", &hex::encode(hash)[..16])
    }

    /// Fail-closed validation for descriptors crossing the receipt write edge.
    /// Restricted bytes use an opaque custodian locator in the first safe
    /// implementation; no public equality digest is emitted until a separately
    /// reviewed sealed-commitment scheme exists.
    pub fn validate_reference_axes(&self) -> Result<(), String> {
        match self.disclosure {
            ArtifactDisclosure::Public => {
                let digest = self.content_hash.strip_prefix("sha256:").ok_or_else(|| {
                    "public artifact content_hash must be sha256:<64 lowercase hex>".to_string()
                })?;
                if digest.len() != 64
                    || !digest
                        .bytes()
                        .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
                {
                    return Err(
                        "public artifact content_hash must be sha256:<64 lowercase hex>"
                            .to_string(),
                    );
                }
            }
            ArtifactDisclosure::Restricted => {
                if !self.content_hash.is_empty() {
                    return Err(
                        "restricted artifact must use an opaque custodian reference; public digest disclosure requires a separately reviewed commitment scheme"
                            .to_string(),
                    );
                }
                let locator = self.locator.as_deref().unwrap_or_default();
                if locator.trim().is_empty()
                    || !(locator.starts_with("custodian:") || locator.starts_with("opaque:"))
                {
                    return Err(
                        "restricted artifact requires an opaque custodian: or opaque: locator"
                            .to_string(),
                    );
                }
            }
            ArtifactDisclosure::Unknown => {}
        }
        if self.storage_mode == "local_blob"
            && self.availability == ArtifactAvailability::Unavailable
        {
            return Err("local_blob artifact cannot be declared unavailable".to_string());
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn new(
        kind: impl Into<String>,
        name: impl Into<String>,
        content_hash: impl Into<String>,
        size_bytes: Option<u64>,
        media_type: Option<String>,
        storage_mode: impl Into<String>,
        locator: Option<String>,
        source_url: Option<String>,
        license: Option<String>,
        target_findings: Vec<String>,
        provenance: Provenance,
        metadata: BTreeMap<String, Value>,
        access_tier: crate::access_tier::AccessTier,
    ) -> Result<Self, String> {
        let kind = kind.into();
        if !valid_artifact_kind(&kind) {
            return Err(format!(
                "artifact kind '{kind}' is not supported; valid: {}",
                VALID_ARTIFACT_KINDS.join(", ")
            ));
        }
        let name = name.into();
        if name.trim().is_empty() {
            return Err("artifact name must be non-empty".to_string());
        }
        let content_hash = normalize_sha256(content_hash.into())?;
        let storage_mode = storage_mode.into();
        if !matches!(
            storage_mode.as_str(),
            "local_blob" | "local_file" | "remote" | "pointer"
        ) {
            return Err(format!(
                "artifact storage_mode '{storage_mode}' is not supported; valid: local_blob, local_file, remote, pointer"
            ));
        }
        let id = Self::content_address(
            &kind,
            &name,
            &content_hash,
            source_url.as_deref(),
            locator.as_deref(),
        );
        Ok(Self {
            id,
            kind,
            name,
            content_hash,
            size_bytes,
            media_type,
            storage_mode,
            disclosure: ArtifactDisclosure::Unknown,
            locator_integrity: LocatorIntegrity::Unknown,
            availability: ArtifactAvailability::Unknown,
            locator,
            source_url,
            license,
            target_findings,
            source_id: None,
            provenance,
            metadata,
            review_state: None,
            retracted: false,
            access_tier,
            created: Utc::now().to_rfc3339(),
        })
    }
}

fn normalize_sha256(value: String) -> Result<String, String> {
    let trimmed = value.trim();
    let hex = trimmed.strip_prefix("sha256:").unwrap_or(trimmed);
    if hex.len() != 64 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(format!(
            "content_hash must be sha256:<64hex> or 64 hex chars, got {trimmed:?}"
        ));
    }
    Ok(format!("sha256:{}", hex.to_ascii_lowercase()))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Conditions {
    #[serde(default)]
    pub text: String,
    // v0.700: the empirical-context slots (species_verified/species_unverified/
    // in_vitro/in_vivo/human_data/clinical_trial/concentration_range/age_group/
    // cell_type) were removed. The cheap-verifier math wedge never populated them,
    // the re-genesis stripped them from every live finding, and dropping the struct
    // fields is byte-identical to their skip-guarded (always-omitted) form.
    pub duration: Option<String>,
}

/// Confidence method: how the score was determined.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum ConfidenceMethod {
    /// Computed from structured frontier support components (v0.2.0).
    Computed,
    /// A human expert assigned it.
    ExpertJudgment,
    /// Legacy import path for confidence seeded before component breakdown existed.
    #[default]
    LlmInitial,
}

/// Semantic category of the confidence score stored on the frontier.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum ConfidenceKind {
    /// Bounded epistemic support for the finding as currently represented in frontier state.
    #[default]
    FrontierEpistemic,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Confidence {
    /// Semantic meaning of `score`. v0 emits `frontier_epistemic`.
    #[serde(default)]
    pub kind: ConfidenceKind,
    pub score: f64,
    pub basis: String,
    /// How this score was determined.
    #[serde(default)]
    pub method: ConfidenceMethod,
    /// Confidence in the extraction itself (separate from scientific confidence).
    #[serde(default = "default_extraction_conf")]
    pub extraction_confidence: f64,
}

fn default_extraction_conf() -> f64 {
    0.85
}

impl Confidence {
    /// Construct a `Confidence` with a raw score and basis string. The
    /// agent and verifier layers use this directly: a frozen verifier
    /// assigns `score = 1.0`, while an LLM extraction supplies a single
    /// confidence value.
    ///
    /// Renamed from `legacy()` in v0.36; the previous name was a
    /// historical accident (the constructor was never actually
    /// deprecated, just misnamed).
    pub fn raw(score: f64, basis: impl Into<String>, extraction_confidence: f64) -> Self {
        Self {
            kind: ConfidenceKind::FrontierEpistemic,
            score,
            basis: basis.into(),
            method: ConfidenceMethod::LlmInitial,
            extraction_confidence,
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Extraction {
    #[serde(default = "default_extraction_method")]
    pub method: String,
    pub model: Option<String>,
    pub model_version: Option<String>,
    #[serde(default)]
    pub extracted_at: String,
    #[serde(default = "default_extractor_version")]
    pub extractor_version: String,
}

fn default_extraction_method() -> String {
    "llm_extraction".into()
}
fn default_extractor_version() -> String {
    "vela/0.2.0".into()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Review {
    #[serde(default)]
    pub reviewed: bool,
    pub reviewer: Option<String>,
    pub reviewed_at: Option<String>,
    #[serde(default)]
    pub corrections: Vec<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Author {
    pub name: String,
    pub orcid: Option<String>,
}

/// What sub-part of a finding a contribution applies to.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContributionUnitType {
    /// An evidence span within a paper finding.
    EvidenceSpan,
    /// A Lean declaration name (FC / formal findings).
    LeanDecl,
    /// A single step of an argument.
    Step,
    /// The whole bundle (the finding-level default).
    Whole,
}

/// The kind of actor behind a contribution. A `model` holds no key and can never
/// be accountable; only a `human` can carry a signature.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentKind {
    Human,
    Agent,
    Model,
}

/// The kind of contribution. Only `vouched` carries trust weight, and it maps to
/// a human signature — a `model` or `agent` can never be `vouched`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContributionRole {
    Originated,
    Derived,
    Formalized,
    Extracted,
    Reviewed,
    Vouched,
}

/// One attribution record at claim granularity: which actor contributed which
/// unit of a finding, and in what role. Descriptive provenance only — the
/// reducer never reads it as state, the gate never reads it as evidence, and it
/// is outside the `vf_` id preimage (adding it does not change the finding id).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contribution {
    /// The sub-claim reference: an evidence-span ref, a Lean decl name, or the
    /// literal `whole` (the current finding-level behaviour).
    pub unit: String,
    pub unit_type: ContributionUnitType,
    pub agent_kind: AgentKind,
    /// ORCID, agent handle, or model id.
    pub agent_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model_version: Option<String>,
    pub role: ContributionRole,
    /// Free text or an evidence-span reference backing the claim.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub basis: String,
}

impl AgentKind {
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Human => "human",
            Self::Agent => "agent",
            Self::Model => "model",
        }
    }
}

impl ContributionRole {
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Originated => "originated",
            Self::Derived => "derived",
            Self::Formalized => "formalized",
            Self::Extracted => "extracted",
            Self::Reviewed => "reviewed",
            Self::Vouched => "vouched",
        }
    }
}

impl Contribution {
    /// The one trust invariant: `vouched` is a human-signature role, so a
    /// `model` or `agent` can never carry it. Structural, not a verdict.
    pub fn validate(&self) -> Result<(), String> {
        if self.role == ContributionRole::Vouched && self.agent_kind != AgentKind::Human {
            return Err(
                "a contribution with role `vouched` must be a human (agents and models hold no key)"
                    .to_string(),
            );
        }
        if self.unit.trim().is_empty() {
            return Err("contribution `unit` must be non-empty".to_string());
        }
        if self.agent_id.trim().is_empty() {
            return Err("contribution `agent_id` must be non-empty".to_string());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Provenance {
    #[serde(default = "default_source_type")]
    pub source_type: String,
    pub doi: Option<String>,
    // v0.700: the bibliometric slots (pmid/pmc/openalex_id/journal/citation_count)
    // were removed. The math wedge cites by DOI/title, never PubMed/OpenAlex; the
    // re-genesis stripped them from every live finding (0 were pmid-addressed, so
    // content_address now uses doi||title with no id change). Byte-identical to the
    // skip-guarded form.
    /// v0.11: generic source URL when none of the structured identifiers
    /// fit (preprint server URL, dataset landing page, talk recording, etc.).
    /// Skipped when None so pre-v0.11 frontiers serialise byte-identically.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    #[serde(default)]
    pub title: String,
    #[serde(default)]
    pub authors: Vec<Author>,
    pub year: Option<i32>,
    /// License URL (e.g., Creative Commons), typically from Crossref.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
    /// Publisher name, typically from Crossref.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher: Option<String>,
    /// Funding sources, typically from Crossref.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub funders: Vec<String>,
    #[serde(default)]
    pub extraction: Extraction,
    pub review: Option<Review>,
    /// Claim-granularity attribution: which actor originated / derived /
    /// formalized which unit of this finding. Descriptive provenance, distinct
    /// from `extraction` (who extracted the whole bundle) and `authors` (the
    /// source paper's humans). Skipped when empty so pre-existing bundles
    /// serialise byte-identically, and outside the `vf_` id preimage.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contributions: Vec<Contribution>,
}

fn default_source_type() -> String {
    "published_paper".into()
}

/// Typed review state. Replaces the v0.2 `flags.contested: bool` collapse
/// of three semantically distinct review judgments. Doctrine line 6:
/// "scientific disagreement should remain live state."
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewState {
    /// Review verdict was "accepted" or "approved" — finding stands.
    Accepted,
    /// Review verdict was "contested" — disagreement preserved as live state.
    Contested,
    /// Review verdict was "needs_revision" — finding stays but flagged for
    /// confidence revision or condition refinement.
    NeedsRevision,
    /// Review verdict was "rejected" — finding kept for replay history but
    /// not treated as active state.
    Rejected,
}

impl ReviewState {
    /// Whether `flags.contested` should be true given this review_state.
    /// Backwards-compat shim: contested is the v0.2 derived bit.
    #[must_use]
    pub fn implies_contested(&self) -> bool {
        matches!(
            self,
            ReviewState::Contested | ReviewState::NeedsRevision | ReviewState::Rejected
        )
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Flags {
    #[serde(default)]
    pub gap: bool,
    #[serde(default)]
    pub negative_space: bool,
    /// Derived from `review_state` for backward compatibility. Code that
    /// reads `flags.contested` still works; new code should read
    /// `review_state` for the typed verdict.
    #[serde(default)]
    pub contested: bool,
    #[serde(default)]
    pub retracted: bool,
    #[serde(default)]
    pub declining: bool,
    #[serde(default)]
    pub gravity_well: bool,
    /// Typed review verdict (v0.3+). When set, drives `flags.contested`
    /// for backward compatibility. `None` means no review verdict has
    /// been recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub review_state: Option<ReviewState>,
    /// v0.14: true once a newer content-addressed finding supersedes
    /// this one via the `finding.supersede` proposal kind. The newer
    /// finding carries a `supersedes` link back to this finding's id.
    /// Skipped when false so pre-v0.14 frontiers serialize byte-identically.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub superseded: bool,
    /// v0.37: minimum number of unique valid signatures required for
    /// this finding to qualify as `jointly_accepted`. `None` (the
    /// default) preserves single-sig semantics — any one valid
    /// signature is accepted. When `Some(k)`, the finding only counts
    /// as joint-accepted once `k` distinct registered actors have
    /// each contributed a valid Ed25519 signature over the canonical
    /// finding bytes. Pre-v0.37 frontiers omit the field; loading is
    /// backward-compatible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature_threshold: Option<u32>,
    /// v0.37: true once at least `signature_threshold` unique actors
    /// have signed this finding. Set by the verify pass; not written
    /// directly by any other code path. Skipped when false so pre-v0.37
    /// frontiers serialize byte-identically.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub jointly_accepted: bool,
}

/// v0.38: Pearlian causal typing for an assertion. The kernel's
/// pre-v0.38 record carried only `direction: Some("positive" |
/// "negative")` — enough to know that "X covaries with Y" but not
/// whether the speaker meant correlation, mediation, or intervention.
/// In real review work those are different epistemic claims with
/// different evidence requirements; conflating them produced silent
/// over-claiming.
///
/// This release lands the schema layer. The reasoning surface
/// (do-calculus, identifiability, derived bridges that propagate
/// causal vs correlational claims separately) ships in a follow-up.
/// The same staging used v0.32 (Replication as object) → v0.36.1
/// (Project.replications becomes the source of truth for confidence).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CausalClaim {
    /// "X covaries with Y" — no claim about generative direction.
    Correlation,
    /// "X mediates Y → Z" — pathway claim, weaker than intervention.
    Mediation,
    /// "Setting X=x changes Y" — Pearl's `do(X=x)`.
    Intervention,
}

/// v0.38: study-design grade backing a causal claim.
/// The grade is what makes the difference between "the data is
/// consistent with X causing Y" (Observational) and "X causes Y"
/// (Rct). The kernel carries the design label so reviewers can
/// re-grade without re-extracting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CausalEvidenceGrade {
    /// Randomized controlled trial. Strongest grade for intervention claims.
    Rct,
    /// Mendelian randomization, instrumental variables, regression
    /// discontinuity, natural experiments, etc.
    QuasiExperimental,
    /// Cohort, case-control, cross-sectional. Identifies association
    /// only without further design assumptions.
    Observational,
    /// Computational simulation, theoretical model, mathematical proof.
    Theoretical,
}

/// Valid string forms for serialized `CausalClaim`. The kernel
/// validates against this on load.
pub const VALID_CAUSAL_CLAIMS: &[&str] = &["correlation", "mediation", "intervention"];

/// Valid string forms for serialized `CausalEvidenceGrade`.
pub const VALID_CAUSAL_EVIDENCE_GRADES: &[&str] =
    &["rct", "quasi_experimental", "observational", "theoretical"];

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Assertion {
    pub text: String,
    #[serde(rename = "type")]
    pub assertion_type: String,
    // v0.700: typed entities are an empirical-domain affordance (gene/protein/
    // dataset mentions). The math wedge encodes its objects in the assertion
    // text and OEIS/Lean anchors, never here, so the array stays empty and is
    // skip-guarded out of the serialised finding (see Conditions).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entities: Vec<Entity>,
    pub relation: Option<String>,
    pub direction: Option<String>,
    /// v0.38: the kind of causal claim this assertion makes. `None`
    /// means the kernel hasn't been told yet — the legacy default for
    /// pre-v0.38 findings. `Some(Correlation)` is the safe minimum
    /// claim; `Some(Intervention)` is the strongest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub causal_claim: Option<CausalClaim>,
    /// v0.38: study-design grade backing the causal claim. Drives the
    /// reasoning layer's identifiability checks (deferred). Pre-v0.38
    /// findings omit the field; loading is backward-compatible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub causal_evidence_grade: Option<CausalEvidenceGrade>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Link {
    pub target: String,
    #[serde(rename = "type")]
    pub link_type: String,
    #[serde(default)]
    pub note: String,
    #[serde(default = "default_compiler")]
    pub inferred_by: String,
    /// When this link was created (immutable timestamp). Uses serde default for backward compat.
    #[serde(default)]
    pub created_at: String,
    /// v0.45: optional structural causal mechanism on a `depends` /
    /// `supports` edge. When present, the edge participates in
    /// counterfactual (Pearl level 3) queries via twin-network
    /// construction. Edges without a mechanism still participate in
    /// level 2 (back-door / front-door identification); they simply
    /// can't answer twin-network counterfactuals.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mechanism: Option<Mechanism>,
}

fn default_compiler() -> String {
    "compiler".into()
}

/// v0.45: structural causal mechanism on a directed edge.
///
/// A `Mechanism` captures *how* a parent finding determines a child's
/// value, not just that a dependency exists. With mechanisms in place,
/// the kernel can answer counterfactual (Pearl level 3) queries: "given
/// that we observed X under parent=p, what would X have been under
/// parent=p'?" via twin-network construction.
///
/// Doctrine: mechanisms are deliberately coarse. Science rarely warrants
/// precise functional forms; what we need is enough algebraic structure
/// to propagate counterfactual perturbations sign-and-magnitude. Five
/// shapes cover the empirical distribution of biology / clinical claims:
///
/// - `Linear { sign, slope }`: dY = slope * dX (with sign packing the
///   direction; slope is a unitless effect-size on the [0,1] confidence
///   scale).
/// - `Monotonic { sign }`: dY agrees with sign(dX) but magnitude is
///   ungraded (used when direction is known but effect-size isn't).
/// - `Threshold { sign, threshold }`: parent must cross `threshold` for
///   any child response (binary above/below).
/// - `Saturating { sign, half_max }`: hyperbolic / Hill-style; large dX
///   above `half_max` produces vanishing dY.
/// - `Unknown`: explicitly annotated as causally connected but
///   mechanism unspecified. Twin-network treats this as opaque (the
///   counterfactual is reported as `MechanismUnspecified`).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Mechanism {
    Linear {
        sign: MechanismSign,
        /// Effect-size on [0, 1] confidence scale.
        slope: f64,
    },
    Monotonic {
        sign: MechanismSign,
    },
    Threshold {
        sign: MechanismSign,
        threshold: f64,
    },
    Saturating {
        sign: MechanismSign,
        half_max: f64,
    },
    Unknown,
}

/// v0.45: causal direction on a `Mechanism`.
///
/// `Positive`: parent confidence ↑ ⇒ child confidence ↑.
/// `Negative`: parent confidence ↑ ⇒ child confidence ↓.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum MechanismSign {
    Positive,
    Negative,
}

impl MechanismSign {
    #[must_use]
    pub fn as_f64(self) -> f64 {
        match self {
            Self::Positive => 1.0,
            Self::Negative => -1.0,
        }
    }
}

impl Mechanism {
    /// Apply this mechanism to a parent perturbation `delta_x`,
    /// returning the implied child perturbation `delta_y` on the
    /// confidence scale. Returns `None` for `Unknown`.
    #[must_use]
    pub fn apply(&self, delta_x: f64) -> Option<f64> {
        match *self {
            Self::Linear { sign, slope } => Some(sign.as_f64() * slope * delta_x),
            Self::Monotonic { sign } => {
                Some(sign.as_f64() * delta_x.signum() * delta_x.abs().min(1.0))
            }
            Self::Threshold { sign, threshold } => {
                if delta_x.abs() >= threshold {
                    Some(sign.as_f64() * delta_x.signum())
                } else {
                    Some(0.0)
                }
            }
            Self::Saturating { sign, half_max } => {
                // Hill-style: delta_y = sign * dx / (|dx| + half_max), bounded to [-1,1]
                let denom = delta_x.abs() + half_max.max(1e-9);
                Some(sign.as_f64() * delta_x / denom)
            }
            Self::Unknown => None,
        }
    }
}

/// v0.8: typed reference resolved from `Link.target`.
///
/// Targets stay opaque `String` on the wire (canonical-JSON stable). At
/// validation/render time callers parse via `LinkRef::parse`. The
/// `Local` variant is the v0–v0.7 shape; `Cross` is new in v0.8 and
/// requires the dependent frontier to declare a matching `vfr_id` in
/// `frontier.dependencies`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkRef {
    /// `vf_<16hex>` — the target finding lives in this same frontier.
    Local { vf_id: String },
    /// `vf_<16hex>@vfr_<16hex>` — the target finding lives in a
    /// different frontier. Strict validation requires the `vfr_id` to
    /// appear in `Project.frontier.dependencies`.
    Cross { vf_id: String, vfr_id: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkParseError {
    Empty,
    BadVfPrefix,
    BadVfrPrefix,
    EmptyVfId,
    EmptyVfrId,
    TooManyAtSigns,
}

impl std::fmt::Display for LinkParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LinkParseError::Empty => write!(f, "empty link target"),
            LinkParseError::BadVfPrefix => write!(f, "link target must start with 'vf_'"),
            LinkParseError::BadVfrPrefix => {
                write!(f, "cross-frontier suffix must start with 'vfr_'")
            }
            LinkParseError::EmptyVfId => write!(f, "link target's vf_ id is empty"),
            LinkParseError::EmptyVfrId => write!(f, "cross-frontier vfr_ id is empty"),
            LinkParseError::TooManyAtSigns => {
                write!(f, "link target has more than one '@' separator")
            }
        }
    }
}

impl std::error::Error for LinkParseError {}

impl LinkRef {
    /// Parse `vf_<id>` or `vf_<id>@vfr_<id>` into a typed reference.
    /// Treats inputs as opaque hex-ish blobs — does not validate hex
    /// length or character set, since the substrate's content-address
    /// derivation already handles that.
    pub fn parse(s: &str) -> Result<Self, LinkParseError> {
        if s.is_empty() {
            return Err(LinkParseError::Empty);
        }
        let mut parts = s.split('@');
        let local = parts.next().ok_or(LinkParseError::Empty)?;
        let remote = parts.next();
        if parts.next().is_some() {
            return Err(LinkParseError::TooManyAtSigns);
        }
        let vf_id = local
            .strip_prefix("vf_")
            .ok_or(LinkParseError::BadVfPrefix)?;
        if vf_id.is_empty() {
            return Err(LinkParseError::EmptyVfId);
        }
        match remote {
            None => Ok(LinkRef::Local {
                vf_id: local.to_string(),
            }),
            Some(r) => {
                let vfr_id = r.strip_prefix("vfr_").ok_or(LinkParseError::BadVfrPrefix)?;
                if vfr_id.is_empty() {
                    return Err(LinkParseError::EmptyVfrId);
                }
                Ok(LinkRef::Cross {
                    vf_id: local.to_string(),
                    vfr_id: r.to_string(),
                })
            }
        }
    }

    /// Round-trip: format back to the canonical wire string.
    pub fn format(&self) -> String {
        match self {
            LinkRef::Local { vf_id } => vf_id.clone(),
            LinkRef::Cross { vf_id, vfr_id } => format!("{vf_id}@{vfr_id}"),
        }
    }

    /// True if this reference points outside the current frontier.
    pub fn is_cross_frontier(&self) -> bool {
        matches!(self, LinkRef::Cross { .. })
    }
}

#[cfg(test)]
mod link_ref_tests {
    use super::*;

    #[test]
    fn parses_local_vf_id() {
        let r = LinkRef::parse("vf_abc123").unwrap();
        assert_eq!(
            r,
            LinkRef::Local {
                vf_id: "vf_abc123".into()
            }
        );
        assert_eq!(r.format(), "vf_abc123");
        assert!(!r.is_cross_frontier());
    }

    #[test]
    fn parses_cross_frontier_target() {
        let r = LinkRef::parse("vf_abc@vfr_def").unwrap();
        assert_eq!(
            r,
            LinkRef::Cross {
                vf_id: "vf_abc".into(),
                vfr_id: "vfr_def".into(),
            }
        );
        assert_eq!(r.format(), "vf_abc@vfr_def");
        assert!(r.is_cross_frontier());
    }

    #[test]
    fn rejects_empty() {
        assert_eq!(LinkRef::parse(""), Err(LinkParseError::Empty));
    }

    #[test]
    fn rejects_missing_vf_prefix() {
        assert_eq!(LinkRef::parse("xx_abc"), Err(LinkParseError::BadVfPrefix));
    }

    #[test]
    fn rejects_empty_vf_id() {
        assert_eq!(LinkRef::parse("vf_"), Err(LinkParseError::EmptyVfId));
    }

    #[test]
    fn rejects_missing_vfr_prefix_after_at() {
        assert_eq!(
            LinkRef::parse("vf_abc@xxx_def"),
            Err(LinkParseError::BadVfrPrefix)
        );
    }

    #[test]
    fn rejects_empty_vfr_id() {
        assert_eq!(
            LinkRef::parse("vf_abc@vfr_"),
            Err(LinkParseError::EmptyVfrId)
        );
    }

    #[test]
    fn rejects_double_at() {
        assert_eq!(
            LinkRef::parse("vf_abc@vfr_def@x"),
            Err(LinkParseError::TooManyAtSigns)
        );
    }

    #[test]
    fn round_trips_real_ids() {
        for s in [
            "vf_d0a962d3251133dd",
            "vf_d0a962d3251133dd@vfr_7344e96c0f2669d5",
        ] {
            assert_eq!(LinkRef::parse(s).unwrap().format(), s);
        }
    }
}

/// A lightweight annotation on a finding — like a comment on a line of code.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Annotation {
    /// Content-addressed ID (ann_{hash}).
    pub id: String,
    /// The annotation text.
    pub text: String,
    /// Who wrote it (ORCID preferred).
    pub author: String,
    /// When it was created (RFC 3339).
    pub timestamp: String,
    /// Phase β (v0.6): structured provenance for the annotation.
    /// Optional. When present, encodes which paper / preprint / extract
    /// span produced this note. Reviewers query by these fields:
    /// "show every annotation from PMID 25378646" works because the
    /// identifier is structure, not prose.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceRef>,
}

/// Phase β (v0.6): structured provenance reference attached to an
/// annotation (or any future note-shaped object). At least one
/// identifying field (`doi`, `pmid`, `title`) must be set when the
/// provenance is present; an all-empty `ProvenanceRef` is rejected by
/// `validate_event_payload`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProvenanceRef {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pmid: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Verbatim quote / extraction span from the source.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub span: Option<String>,
}

impl ProvenanceRef {
    /// True iff at least one identifying field is set. Used by
    /// `validate_event_payload` to reject all-empty `provenance: {}` objects.
    #[must_use]
    pub fn has_identifier(&self) -> bool {
        self.doi.is_some() || self.pmid.is_some() || self.title.is_some()
    }
}

/// A file attached to a finding (dataset, figure, supplementary material).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Attachment {
    pub filename: String,
    pub label: Option<String>,
    pub path: String,
    pub size_bytes: u64,
    pub mime_type: Option<String>,
    pub attached_at: String,
    pub attached_by: Option<String>,
}

// ── REVIEW layer: content-addressed review events ──────────────────────────

/// A review event is a content-addressed record of human judgment on a finding.
/// Like a Git commit, it records who, when, what changed, and why.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReviewEvent {
    /// Content-addressed ID of this review event.
    pub id: String,
    /// Optional workspace-relative origin for repo-scoped reviews.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace: Option<String>,
    /// ID of the finding being reviewed.
    pub finding_id: String,
    /// The reviewer (ORCID preferred).
    pub reviewer: String,
    /// When the review happened (RFC 3339).
    pub reviewed_at: String,
    /// Optional review scope for richer curation workflows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    /// Optional status for the review event (for example: accepted).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// What action was taken.
    pub action: ReviewAction,
    /// Human-readable reason.
    #[serde(default)]
    pub reason: String,
    /// Supporting findings or artifacts considered during review.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence_considered: Vec<ReviewEvidence>,
    /// Optional structured interpretation update payload.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state_change: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReviewEvidence {
    pub finding_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// The action taken in a review event.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ReviewAction {
    /// Finding approved as correct.
    Approved,
    /// Finding interpretation was qualified to narrow or constrain the claim.
    Qualified { target: String },
    /// Finding corrected — a specific field was changed.
    Corrected {
        field: String,
        original: String,
        corrected: String,
    },
    /// Finding flagged with a specific flag type.
    Flagged { flag_type: String },
    /// Finding disputed — reviewer disagrees with the claim.
    Disputed {
        counter_evidence: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        counter_doi: Option<String>,
    },
}

// ── Interpretation layer: mutable confidence updates ───────────────────────

/// A confidence update is a mutable interpretation layer event.
/// The finding's evidence is immutable; the confidence assessment can evolve.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceUpdate {
    pub finding_id: String,
    pub previous_score: f64,
    pub new_score: f64,
    pub basis: String,
    /// Who or what produced this update (e.g., "grounding_pass", "reviewer:0000-0001-2345-6789").
    pub updated_by: String,
    /// When this update was produced (RFC 3339).
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FindingBundle {
    pub id: String,
    #[serde(default = "default_version")]
    pub version: u32,
    pub previous_version: Option<String>,
    pub assertion: Assertion,
    pub evidence: Evidence,
    pub conditions: Conditions,
    pub confidence: Confidence,
    pub provenance: Provenance,
    pub flags: Flags,
    #[serde(default)]
    pub links: Vec<Link>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub annotations: Vec<Annotation>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attachments: Vec<Attachment>,
    pub created: String,
    pub updated: Option<String>,
    /// v0.51: Read-side access tier. Default `Public` — pre-v0.51
    /// findings load with `Public` and serialize byte-identically
    /// (skip-if-public). Mutated through `tier.set` events; gated in
    /// MCP/HTTP read paths via `access_tier::redact_for_actor`. NOT
    /// part of the content-address preimage — re-classifying a
    /// finding does not mint a new id.
    #[serde(default, skip_serializing_if = "is_public_tier")]
    pub access_tier: crate::access_tier::AccessTier,
}

fn is_public_tier(tier: &crate::access_tier::AccessTier) -> bool {
    matches!(tier, crate::access_tier::AccessTier::Public)
}

fn default_version() -> u32 {
    1
}

impl FindingBundle {
    /// Create a new finding bundle with a content-addressed ID.
    /// Normalize text for content-addressing: lowercase, collapse whitespace,
    /// strip trailing punctuation. Matches the v0.2.0 schema specification.
    /// Public since v0.32 so `Replication::content_address` can reuse the
    /// same canonicalization rule for its conditions preimage.
    pub fn normalize_text(s: &str) -> String {
        let lower = s.to_lowercase();
        // Collapse all runs of whitespace into a single space
        let collapsed: String = lower.split_whitespace().collect::<Vec<_>>().join(" ");
        // Strip trailing punctuation (., ;, :, !, ?)
        collapsed
            .trim_end_matches(['.', ';', ':', '!', '?'])
            .to_string()
    }

    /// Compute the content-addressed ID per v0.2.0 spec:
    /// SHA-256(normalize(assertion.text) + "|" + assertion.type + "|" + (provenance.doi || provenance.pmid || provenance.title))
    /// Returns first 16 hex chars prefixed with "vf_".
    pub fn content_address(assertion: &Assertion, provenance: &Provenance) -> String {
        let norm_text = Self::normalize_text(&assertion.text);
        // v0.700: pmid removed. doi || title (no live finding was pmid-addressed,
        // so every existing vf_ id is unchanged).
        let prov_id = provenance.doi.as_deref().unwrap_or(&provenance.title);
        let preimage = format!("{}|{}|{}", norm_text, assertion.assertion_type, prov_id);
        let hash = Sha256::digest(preimage.as_bytes());
        format!("vf_{}", &hex::encode(hash)[..16])
    }

    pub fn new(
        assertion: Assertion,
        evidence: Evidence,
        conditions: Conditions,
        confidence: Confidence,
        provenance: Provenance,
        flags: Flags,
    ) -> Self {
        let now = Utc::now().to_rfc3339();
        let id = Self::content_address(&assertion, &provenance);

        Self {
            id,
            version: 1,
            previous_version: None,
            assertion,
            evidence,
            conditions,
            confidence,
            provenance,
            flags,
            links: Vec::new(),
            annotations: Vec::new(),
            attachments: Vec::new(),
            created: now,
            updated: None,
            access_tier: crate::access_tier::AccessTier::Public,
        }
    }

    pub fn add_link(&mut self, target_id: &str, link_type: &str, note: &str) {
        self.links.push(Link {
            target: target_id.to_string(),
            link_type: link_type.to_string(),
            note: note.to_string(),
            inferred_by: "compiler".to_string(),
            created_at: Utc::now().to_rfc3339(),
            mechanism: None,
        });
    }

    pub fn add_link_with_source(
        &mut self,
        target_id: &str,
        link_type: &str,
        note: &str,
        inferred_by: &str,
    ) {
        self.links.push(Link {
            target: target_id.to_string(),
            link_type: link_type.to_string(),
            note: note.to_string(),
            inferred_by: inferred_by.to_string(),
            created_at: Utc::now().to_rfc3339(),
            mechanism: None,
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_assertion() -> Assertion {
        Assertion {
            text: "NLRP3 activates IL-1B".into(),
            assertion_type: "mechanism".into(),
            entities: vec![Entity {
                name: "NLRP3".into(),
                entity_type: "protein".into(),
                identifiers: serde_json::Map::new(),
                canonical_id: None,
                candidates: vec![],
                aliases: vec![],
                resolution_provenance: None,
                resolution_confidence: 1.0,
                resolution_method: None,
                species_context: None,
                needs_review: false,
            }],
            relation: Some("activates".into()),
            direction: Some("positive".into()),
            causal_claim: None,
            causal_evidence_grade: None,
        }
    }

    fn sample_evidence() -> Evidence {
        Evidence {
            evidence_type: "experimental".into(),
            model_system: "mouse".into(),
            method: "Western blot".into(),
            replicated: true,
            replication_count: Some(3),
            evidence_spans: vec![],
        }
    }

    fn sample_conditions() -> Conditions {
        Conditions {
            text: "In vitro, mouse microglia".into(),
            duration: None,
        }
    }

    fn sample_confidence() -> Confidence {
        Confidence {
            kind: ConfidenceKind::FrontierEpistemic,
            score: 0.85,
            basis: "Experimental with replication".into(),
            method: ConfidenceMethod::LlmInitial,
            extraction_confidence: 0.9,
        }
    }

    fn sample_provenance() -> Provenance {
        Provenance {
            source_type: "published_paper".into(),
            doi: Some("10.1234/test".into()),
            url: None,
            title: "Test Paper".into(),
            authors: vec![Author {
                name: "Smith J".into(),
                orcid: None,
            }],
            year: Some(2024),
            license: None,
            publisher: None,
            funders: vec![],
            extraction: Extraction::default(),
            review: None,
            contributions: Vec::new(),
        }
    }

    fn sample_flags() -> Flags {
        Flags {
            gap: false,
            negative_space: false,
            contested: false,
            retracted: false,
            declining: false,
            gravity_well: false,
            review_state: None,
            superseded: false,
            signature_threshold: None,
            jointly_accepted: false,
        }
    }

    // ── Content-addressed ID tests ───────────────────────────────────

    #[test]
    fn same_content_same_id() {
        let b1 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let b2 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert_eq!(b1.id, b2.id);
    }

    #[test]
    fn different_content_different_id() {
        let b1 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let mut different_assertion = sample_assertion();
        different_assertion.text = "Completely different claim".into();
        let b2 = FindingBundle::new(
            different_assertion,
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert_ne!(b1.id, b2.id);
    }

    #[test]
    fn id_starts_with_vf_prefix() {
        let b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert!(b.id.starts_with("vf_"));
        assert_eq!(b.id.len(), 3 + 16); // "vf_" + 16 hex chars
    }

    #[test]
    fn new_bundle_version_is_one() {
        let b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert_eq!(b.version, 1);
        assert!(b.previous_version.is_none());
    }

    #[test]
    fn new_bundle_has_no_links() {
        let b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert!(b.links.is_empty());
    }

    #[test]
    fn new_bundle_has_created_timestamp() {
        let b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert!(!b.created.is_empty());
        assert!(b.updated.is_none());
    }

    // ── add_link tests ───────────────────────────────────────────────

    #[test]
    fn add_link_works() {
        let mut b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        b.add_link("target_id", "extends", "shared entity");
        assert_eq!(b.links.len(), 1);
        assert_eq!(b.links[0].target, "target_id");
        assert_eq!(b.links[0].link_type, "extends");
        assert_eq!(b.links[0].note, "shared entity");
        assert_eq!(b.links[0].inferred_by, "compiler");
    }

    #[test]
    fn add_link_with_source_works() {
        let mut b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        b.add_link_with_source(
            "target_id",
            "contradicts",
            "opposite direction",
            "entity_overlap",
        );
        assert_eq!(b.links.len(), 1);
        assert_eq!(b.links[0].inferred_by, "entity_overlap");
    }

    #[test]
    fn multiple_links_accumulate() {
        let mut b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        b.add_link("t1", "extends", "note1");
        b.add_link("t2", "contradicts", "note2");
        b.add_link("t3", "supports", "note3");
        assert_eq!(b.links.len(), 3);
    }

    // ── ReviewEvent creation test ────────────────────────────────────

    #[test]
    fn review_event_creation() {
        let event = ReviewEvent {
            id: "rev_abc123".into(),
            workspace: None,
            finding_id: "vf_abc".into(),
            reviewer: "0000-0001-2345-6789".into(),
            reviewed_at: "2024-01-01T00:00:00Z".into(),
            scope: None,
            status: None,
            action: ReviewAction::Approved,
            reason: "Looks correct".into(),
            evidence_considered: vec![],
            state_change: None,
        };
        assert_eq!(event.finding_id, "vf_abc");
        assert_eq!(event.reviewer, "0000-0001-2345-6789");
    }

    #[test]
    fn review_action_corrected() {
        let action = ReviewAction::Corrected {
            field: "direction".into(),
            original: "positive".into(),
            corrected: "negative".into(),
        };
        if let ReviewAction::Corrected {
            field,
            original,
            corrected,
        } = action
        {
            assert_eq!(field, "direction");
            assert_eq!(original, "positive");
            assert_eq!(corrected, "negative");
        } else {
            panic!("Expected Corrected variant");
        }
    }

    #[test]
    fn review_action_disputed() {
        let action = ReviewAction::Disputed {
            counter_evidence: "Later study contradicts".into(),
            counter_doi: Some("10.1234/counter".into()),
        };
        if let ReviewAction::Disputed {
            counter_evidence,
            counter_doi,
        } = action
        {
            assert_eq!(counter_evidence, "Later study contradicts");
            assert_eq!(counter_doi, Some("10.1234/counter".into()));
        } else {
            panic!("Expected Disputed variant");
        }
    }

    // ── ConfidenceUpdate creation test ───────────────────────────────

    #[test]
    fn confidence_update_creation() {
        let update = ConfidenceUpdate {
            finding_id: "vf_abc".into(),
            previous_score: 0.7,
            new_score: 0.85,
            basis: "grounded".into(),
            updated_by: "grounding_pass".into(),
            updated_at: "2024-01-01T00:00:00Z".into(),
        };
        assert_eq!(update.previous_score, 0.7);
        assert_eq!(update.new_score, 0.85);
        assert_eq!(update.updated_by, "grounding_pass");
    }

    // ── Serialization round-trip test ────────────────────────────────

    #[test]
    fn finding_serializes_and_deserializes() {
        let b = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let json = serde_json::to_string(&b).unwrap();
        let b2: FindingBundle = serde_json::from_str(&json).unwrap();
        assert_eq!(b.id, b2.id);
        assert_eq!(b.assertion.text, b2.assertion.text);
        assert_eq!(b.confidence.score, b2.confidence.score);
    }

    #[test]
    fn v0_10_assertion_and_source_extensions() {
        assert!(VALID_ASSERTION_TYPES.contains(&"measurement"));
        assert!(VALID_ASSERTION_TYPES.contains(&"exclusion"));
        assert!(VALID_PROVENANCE_SOURCE_TYPES.contains(&"data_release"));
    }

    // ── Different fields change the ID ───────────────────────────────

    #[test]
    fn confidence_does_not_affect_id() {
        // v0.2.0: confidence is the mutable interpretation layer, not part of content address
        let b1 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let mut conf2 = sample_confidence();
        conf2.score = 0.5;
        let b2 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            conf2,
            sample_provenance(),
            sample_flags(),
        );
        assert_eq!(b1.id, b2.id);
    }

    #[test]
    fn flags_do_not_affect_id() {
        let b1 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let mut flags2 = sample_flags();
        flags2.gap = true;
        flags2.contested = true;
        let b2 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            flags2,
        );
        // Flags are NOT in the content hash, so IDs should be the same
        assert_eq!(b1.id, b2.id);
    }

    #[test]
    fn different_assertion_text_different_id() {
        let b1 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let mut assertion2 = sample_assertion();
        assertion2.assertion_type = "therapeutic".into();
        let b2 = FindingBundle::new(
            assertion2,
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        assert_ne!(b1.id, b2.id);
    }

    #[test]
    fn different_doi_different_id() {
        let b1 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            sample_provenance(),
            sample_flags(),
        );
        let mut prov2 = sample_provenance();
        prov2.doi = Some("10.5678/other".into());
        let b2 = FindingBundle::new(
            sample_assertion(),
            sample_evidence(),
            sample_conditions(),
            sample_confidence(),
            prov2,
            sample_flags(),
        );
        assert_ne!(b1.id, b2.id);
    }

    // ── v0.2.0 content-addressing determinism ───────────────────────

    #[test]
    fn content_address_is_deterministic_across_runs() {
        // Two independent extraction runs with the same assertion text,
        // assertion type, and DOI must produce the same finding ID.
        let assertion1 = Assertion {
            text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
            assertion_type: "mechanism".into(),
            entities: vec![],
            relation: None,
            direction: None,
            causal_claim: None,
            causal_evidence_grade: None,
        };
        let prov1 = Provenance {
            source_type: "published_paper".into(),
            doi: Some("10.1038/s41586-023-06789-1".into()),
            url: None,
            title: "Mitochondria in AD".into(),
            authors: vec![],
            year: Some(2023),
            license: None,
            publisher: None,
            funders: vec![],
            extraction: Extraction::default(),
            review: None,
            contributions: Vec::new(),
        };

        // Different entities, evidence, conditions, confidence -- should NOT matter
        let assertion2 = Assertion {
            text: "Mitochondrial dysfunction precedes amyloid plaque formation.".into(),
            assertion_type: "mechanism".into(),
            entities: vec![Entity {
                name: "mitochondria".into(),
                entity_type: "anatomical_structure".into(),
                identifiers: serde_json::Map::new(),
                canonical_id: None,
                candidates: vec![],
                aliases: vec![],
                resolution_provenance: None,
                resolution_confidence: 1.0,
                resolution_method: None,
                species_context: None,
                needs_review: false,
            }],
            relation: Some("precedes".into()),
            direction: Some("positive".into()),
            causal_claim: None,
            causal_evidence_grade: None,
        };
        let prov2 = Provenance {
            source_type: "published_paper".into(),
            doi: Some("10.1038/s41586-023-06789-1".into()),
            url: None,
            title: "Different title".into(),
            authors: vec![Author {
                name: "Jones A".into(),
                orcid: None,
            }],
            year: Some(2023),
            license: None,
            publisher: None,
            funders: vec![],
            extraction: Extraction::default(),
            review: None,
            contributions: Vec::new(),
        };

        let id1 = FindingBundle::content_address(&assertion1, &prov1);
        let id2 = FindingBundle::content_address(&assertion2, &prov2);
        assert_eq!(
            id1, id2,
            "Same assertion text + type + DOI must produce same ID"
        );
    }

    #[test]
    fn content_address_normalizes_whitespace_and_punctuation() {
        let assertion1 = Assertion {
            text: "  NLRP3  activates   IL-1B.  ".into(),
            assertion_type: "mechanism".into(),
            entities: vec![],
            relation: None,
            direction: None,
            causal_claim: None,
            causal_evidence_grade: None,
        };
        let assertion2 = Assertion {
            text: "NLRP3 activates IL-1B".into(),
            assertion_type: "mechanism".into(),
            entities: vec![],
            relation: None,
            direction: None,
            causal_claim: None,
            causal_evidence_grade: None,
        };
        let prov = sample_provenance();
        let id1 = FindingBundle::content_address(&assertion1, &prov);
        let id2 = FindingBundle::content_address(&assertion2, &prov);
        assert_eq!(
            id1, id2,
            "Whitespace and trailing punctuation should be normalized away"
        );
    }

    #[test]
    fn content_address_falls_back_to_title_when_no_doi() {
        let assertion = sample_assertion();
        let mut prov = sample_provenance();
        prov.doi = None;
        prov.title = "Fallback Title".into();
        let id = FindingBundle::content_address(&assertion, &prov);
        assert!(id.starts_with("vf_"));
        assert_eq!(id.len(), 19); // "vf_" + 16 hex chars

        // Same title -> same ID
        let mut prov2 = sample_provenance();
        prov2.doi = None;
        prov2.title = "Fallback Title".into();
        let id2 = FindingBundle::content_address(&assertion, &prov2);
        assert_eq!(id, id2);
    }

    #[test]
    fn content_address_prefers_doi_over_title() {
        let assertion = sample_assertion();

        let mut prov_doi = sample_provenance();
        prov_doi.doi = Some("10.1234/test".into());
        prov_doi.title = "Title".into();

        let mut prov_title = sample_provenance();
        prov_title.doi = None;
        prov_title.title = "Title".into();

        let id_doi = FindingBundle::content_address(&assertion, &prov_doi);
        let id_title = FindingBundle::content_address(&assertion, &prov_title);

        assert_ne!(id_doi, id_title, "DOI vs title should differ");
    }

    #[test]
    fn parses_bbb_review_event_with_richer_schema() {
        let raw = include_str!("../../embedded/tests/fixtures/legacy/rev_001_bbb_correction.json");
        let review: ReviewEvent = serde_json::from_str(raw).unwrap();

        assert_eq!(review.id, "rev_001_bbb_correction");
        assert_eq!(review.workspace.as_deref(), Some("projects/bbb-flagship"));
        assert_eq!(review.scope.as_deref(), Some("bbb_opening_trusted_subset"));
        assert_eq!(review.status.as_deref(), Some("accepted"));
        assert!(matches!(
            review.action,
            ReviewAction::Qualified { ref target } if target == "trusted_interpretation"
        ));
        assert_eq!(review.evidence_considered.len(), 3);
        assert_eq!(
            review.evidence_considered[0].role.as_deref(),
            Some("qualifier")
        );
        assert_eq!(
            review
                .state_change
                .as_ref()
                .and_then(|value| value.get("assumption_retired"))
                .and_then(|value| value.as_str()),
            Some("safe opening implies therapeutic efficacy")
        );
    }

    #[test]
    fn artifact_requires_sha256_and_stable_kind() {
        let artifact = Artifact::new(
            "clinical_trial_record",
            "AHEAD 3-45",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            Some(42),
            Some("application/json".into()),
            "local_blob",
            Some(".vela/artifact-blobs/sha256/aaaaaaaa".into()),
            Some("https://clinicaltrials.gov/study/NCT04468659".into()),
            Some("ClinicalTrials.gov public record".into()),
            vec!["vf_demo".into()],
            sample_provenance(),
            BTreeMap::new(),
            crate::access_tier::AccessTier::Public,
        )
        .unwrap();

        assert!(artifact.id.starts_with("va_"));
        assert_eq!(
            artifact.content_hash,
            "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
        );
        assert_eq!(artifact.kind, "clinical_trial_record");
    }

    #[test]
    fn artifact_reference_axes_are_independent_and_content_bound() {
        let hash = format!("sha256:{}", "a".repeat(64));
        let legacy = Artifact::content_address(
            "dataset",
            "public data",
            &hash,
            None,
            Some("https://example.test/data"),
        );
        let all_unknown = Artifact::content_address_with_axes(
            "dataset",
            "public data",
            &hash,
            None,
            Some("https://example.test/data"),
            ArtifactDisclosure::Unknown,
            LocatorIntegrity::Unknown,
            ArtifactAvailability::Unknown,
        );
        assert_eq!(legacy, all_unknown);

        let immutable = Artifact::content_address_with_axes(
            "dataset",
            "public data",
            &hash,
            None,
            Some("https://example.test/data"),
            ArtifactDisclosure::Public,
            LocatorIntegrity::Immutable,
            ArtifactAvailability::Available,
        );
        let mutable = Artifact::content_address_with_axes(
            "dataset",
            "public data",
            &hash,
            None,
            Some("https://example.test/data"),
            ArtifactDisclosure::Public,
            LocatorIntegrity::Mutable,
            ArtifactAvailability::Available,
        );
        assert_ne!(immutable, mutable);
    }

    #[test]
    fn restricted_reference_refuses_public_equality_digest() {
        let mut artifact = Artifact::new(
            "dataset",
            "restricted data",
            "a".repeat(64),
            None,
            None,
            "pointer",
            Some("custodian:lab-vault/item-7".to_string()),
            None,
            None,
            vec![],
            sample_provenance(),
            BTreeMap::new(),
            crate::access_tier::AccessTier::Restricted,
        )
        .unwrap();
        artifact.disclosure = ArtifactDisclosure::Restricted;
        artifact.locator_integrity = LocatorIntegrity::Immutable;
        artifact.availability = ArtifactAvailability::Unknown;
        assert!(artifact.validate_reference_axes().is_err());

        artifact.content_hash.clear();
        assert!(artifact.validate_reference_axes().is_ok());
    }
}