vela-protocol 0.108.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
//! Git-native VelaRepo abstraction — load/save projects from either monolithic JSON
//! or a `.vela/` directory of individual finding files.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::bundle::{ConfidenceUpdate, FindingBundle, Link, ReviewEvent};
use crate::events::StateEvent;
use crate::project::{self, Project};
use crate::proposals::{ProofState, StateProposal};

// ── Source detection ──────────────────────────────────────────────────

/// Where a project lives on disk.
#[derive(Debug, Clone, PartialEq)]
pub enum VelaSource {
    /// A single monolithic JSON file.
    ProjectFile(PathBuf),
    /// A directory with a `.vela/` subdirectory containing individual finding files.
    VelaRepo(PathBuf),
    /// A publishable frontier packet directory with `manifest.json` and payload files.
    PacketDir(PathBuf),
}

#[derive(Debug, Deserialize)]
struct PacketManifestHeader {
    packet_format: String,
    #[serde(default)]
    source: Option<PacketSourceHeader>,
}

#[derive(Debug, Default, Deserialize)]
struct PacketSourceHeader {
    #[serde(default)]
    project_name: String,
    #[serde(default)]
    description: String,
    #[serde(default)]
    compiled_at: String,
    #[serde(default)]
    compiler: String,
    #[serde(default)]
    vela_version: String,
    #[serde(default)]
    schema: String,
}

#[derive(Debug, Default, Deserialize)]
struct PacketOverviewHeader {
    #[serde(default)]
    project_name: String,
    #[serde(default)]
    description: String,
    #[serde(default)]
    compiled_at: String,
    #[serde(default)]
    papers_processed: usize,
}

/// Detect the source type from a path.
///
/// - If `path` points to a file with `.json` extension -> ProjectFile
/// - If `path` is a directory with a `.vela/` subdirectory -> VelaRepo
/// - Otherwise -> error
pub fn detect(path: &Path) -> Result<VelaSource, String> {
    if path.is_file() {
        return Ok(VelaSource::ProjectFile(path.to_path_buf()));
    }
    if path.is_dir() {
        if is_packet_dir(path) {
            return Ok(VelaSource::PacketDir(path.to_path_buf()));
        }
        let vela_dir = path.join(".vela");
        if vela_dir.is_dir() {
            return Ok(VelaSource::VelaRepo(path.to_path_buf()));
        }
        // A path that looks like it should be a JSON file but doesn't exist yet
        if path.extension().is_some_and(|ext| ext == "json") {
            return Ok(VelaSource::ProjectFile(path.to_path_buf()));
        }
        return Err(format!(
            "Directory '{}' is not a Vela repository or frontier packet. Run `vela init`, `vela import`, or `vela migrate` first.",
            path.display()
        ));
    }
    // Path doesn't exist yet — check extension
    if path.extension().is_some_and(|ext| ext == "json") {
        return Ok(VelaSource::ProjectFile(path.to_path_buf()));
    }
    Err(format!(
        "Path '{}' does not exist. Provide a .json file, frontier packet, or a directory with .vela/",
        path.display()
    ))
}

// ── Config TOML ──────────────────────────────────────────────────────

#[derive(Debug, Serialize, Deserialize)]
struct RepoConfig {
    project: RepoProjectMeta,
}

#[derive(Debug, Serialize, Deserialize)]
struct RepoProjectMeta {
    name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    frontier_id: Option<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    compiled_at: String,
    #[serde(default)]
    description: String,
    #[serde(default = "default_compiler")]
    compiler: String,
    #[serde(default)]
    papers_processed: usize,
}

fn default_compiler() -> String {
    crate::project::VELA_COMPILER_VERSION.into()
}

// ── Link manifest ────────────────────────────────────────────────────

/// A link record in the centralized manifest. Contains a `source` field
/// (the finding ID that owns this link) so we can redistribute on load.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct ManifestLink {
    source: String,
    target: String,
    #[serde(rename = "type")]
    link_type: String,
    #[serde(default)]
    note: String,
    #[serde(default = "default_inferred_by")]
    inferred_by: String,
    #[serde(default)]
    created_at: String,
}

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

// ── Load ─────────────────────────────────────────────────────────────

/// Load a project from a detected source.
pub fn load(source: &VelaSource) -> Result<Project, String> {
    match source {
        VelaSource::ProjectFile(path) => load_project_file(path),
        VelaSource::VelaRepo(dir) => load_vela_repo(dir),
        VelaSource::PacketDir(dir) => load_packet_dir(dir),
    }
}

pub(crate) fn load_project_file(path: &Path) -> Result<Project, String> {
    let data = std::fs::read_to_string(path)
        .map_err(|e| format!("Failed to read project file '{}': {e}", path.display()))?;
    serde_json::from_str(&data)
        .map_err(|e| format!("Failed to parse project JSON '{}': {e}", path.display()))
}

fn load_packet_dir(dir: &Path) -> Result<Project, String> {
    let manifest_path = dir.join("manifest.json");
    let manifest_data = std::fs::read_to_string(&manifest_path).map_err(|e| {
        format!(
            "Failed to read packet manifest '{}': {e}",
            manifest_path.display()
        )
    })?;
    let manifest: PacketManifestHeader = serde_json::from_str(&manifest_data).map_err(|e| {
        format!(
            "Failed to parse packet manifest '{}': {e}",
            manifest_path.display()
        )
    })?;

    if manifest.packet_format != "vela.frontier-packet" {
        return Err(format!(
            "Unsupported packet format '{}' in {}",
            manifest.packet_format,
            manifest_path.display()
        ));
    }

    let findings_path = dir.join("findings/full.json");
    let findings_data = std::fs::read_to_string(&findings_path).map_err(|e| {
        format!(
            "Failed to read packet findings '{}': {e}",
            findings_path.display()
        )
    })?;
    let findings: Vec<FindingBundle> = serde_json::from_str(&findings_data).map_err(|e| {
        format!(
            "Failed to parse packet findings '{}': {e}",
            findings_path.display()
        )
    })?;

    let reviews_path = dir.join("reviews/review-events.json");
    let review_events: Vec<ReviewEvent> = if reviews_path.is_file() {
        let reviews_data = std::fs::read_to_string(&reviews_path).map_err(|e| {
            format!(
                "Failed to read packet reviews '{}': {e}",
                reviews_path.display()
            )
        })?;
        serde_json::from_str(&reviews_data).map_err(|e| {
            format!(
                "Failed to parse packet reviews '{}': {e}",
                reviews_path.display()
            )
        })?
    } else {
        Vec::new()
    };
    let confidence_updates_path = dir.join("reviews/confidence-updates.json");
    let confidence_updates: Vec<ConfidenceUpdate> = if confidence_updates_path.is_file() {
        let updates_data = std::fs::read_to_string(&confidence_updates_path).map_err(|e| {
            format!(
                "Failed to read packet confidence updates '{}': {e}",
                confidence_updates_path.display()
            )
        })?;
        serde_json::from_str(&updates_data).map_err(|e| {
            format!(
                "Failed to parse packet confidence updates '{}': {e}",
                confidence_updates_path.display()
            )
        })?
    } else {
        Vec::new()
    };
    let events_path = dir.join("events/events.json");
    let events: Vec<StateEvent> = if events_path.is_file() {
        let events_data = std::fs::read_to_string(&events_path).map_err(|e| {
            format!(
                "Failed to read packet events '{}': {e}",
                events_path.display()
            )
        })?;
        serde_json::from_str(&events_data).map_err(|e| {
            format!(
                "Failed to parse packet events '{}': {e}",
                events_path.display()
            )
        })?
    } else {
        Vec::new()
    };
    let proposals_path = dir.join("proposals/proposals.json");
    let proposals: Vec<StateProposal> = if proposals_path.is_file() {
        let proposals_data = std::fs::read_to_string(&proposals_path).map_err(|e| {
            format!(
                "Failed to read packet proposals '{}': {e}",
                proposals_path.display()
            )
        })?;
        serde_json::from_str(&proposals_data).map_err(|e| {
            format!(
                "Failed to parse packet proposals '{}': {e}",
                proposals_path.display()
            )
        })?
    } else {
        Vec::new()
    };

    let overview_path = dir.join("overview.json");
    let overview: PacketOverviewHeader = if overview_path.is_file() {
        let overview_data = std::fs::read_to_string(&overview_path).map_err(|e| {
            format!(
                "Failed to read packet overview '{}': {e}",
                overview_path.display()
            )
        })?;
        serde_json::from_str(&overview_data).map_err(|e| {
            format!(
                "Failed to parse packet overview '{}': {e}",
                overview_path.display()
            )
        })?
    } else {
        PacketOverviewHeader::default()
    };

    let source = manifest.source.unwrap_or_default();
    let name = first_non_empty([
        source.project_name.as_str(),
        overview.project_name.as_str(),
        dir.file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("packet"),
    ]);
    let description = first_non_empty([
        source.description.as_str(),
        overview.description.as_str(),
        "",
    ]);
    let compiled_at = first_non_empty([
        source.compiled_at.as_str(),
        overview.compiled_at.as_str(),
        "",
    ]);

    let mut project = project::assemble(name, findings, overview.papers_processed, 0, description);
    if !compiled_at.is_empty() {
        project.project.compiled_at = compiled_at.to_string();
    }
    if !source.compiler.is_empty() {
        project.project.compiler = source.compiler;
    }
    if !source.vela_version.is_empty() {
        project.vela_version = source.vela_version;
    }
    if !source.schema.is_empty() {
        project.schema = source.schema;
    }
    project.review_events = review_events;
    project.confidence_updates = confidence_updates;
    project.events = events;
    project.proposals = proposals;
    project::recompute_stats(&mut project);
    Ok(project)
}

fn load_vela_repo(dir: &Path) -> Result<Project, String> {
    let vela_dir = dir.join(".vela");
    let config_path = vela_dir.join("config.toml");

    // Read config
    let config: RepoConfig = if config_path.exists() {
        let toml_str = std::fs::read_to_string(&config_path)
            .map_err(|e| format!("Failed to read config.toml: {e}"))?;
        toml::from_str(&toml_str).map_err(|e| format!("Failed to parse config.toml: {e}"))?
    } else {
        RepoConfig {
            project: RepoProjectMeta {
                name: dir
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
                frontier_id: None,
                compiled_at: String::new(),
                description: String::new(),
                compiler: default_compiler(),
                papers_processed: 0,
            },
        }
    };

    // Read findings
    let findings_dir = dir.join(".vela/findings");
    let mut findings: Vec<FindingBundle> = Vec::new();

    if findings_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&findings_dir)
            .map_err(|e| format!("Failed to read findings/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();

        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let finding: FindingBundle = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            findings.push(finding);
        }
    }

    // Read link manifest and redistribute
    let links_dir = dir.join(".vela/links");
    let manifest_path = links_dir.join("manifest.json");
    if manifest_path.exists() {
        let data = std::fs::read_to_string(&manifest_path)
            .map_err(|e| format!("Failed to read links/manifest.json: {e}"))?;
        let manifest_links: Vec<ManifestLink> = serde_json::from_str(&data)
            .map_err(|e| format!("Failed to parse links/manifest.json: {e}"))?;

        // Build a map of source_id -> links
        let mut links_by_source: HashMap<String, Vec<Link>> = HashMap::new();
        for ml in manifest_links {
            links_by_source
                .entry(ml.source.clone())
                .or_default()
                .push(Link {
                    target: ml.target,
                    link_type: ml.link_type,
                    note: ml.note,
                    inferred_by: ml.inferred_by,
                    created_at: ml.created_at,
                    mechanism: None,
                });
        }

        // Distribute links into findings
        for finding in &mut findings {
            if let Some(links) = links_by_source.remove(&finding.id) {
                finding.links = links;
            }
        }
    }

    // Read reviews
    let reviews_dir = dir.join(".vela/reviews");
    let mut review_events: Vec<ReviewEvent> = Vec::new();
    if reviews_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&reviews_dir)
            .map_err(|e| format!("Failed to read reviews/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();

        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let event: ReviewEvent = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            review_events.push(event);
        }
    }

    let confidence_updates_dir = dir.join(".vela/confidence-updates");
    let mut confidence_updates: Vec<ConfidenceUpdate> = Vec::new();
    if confidence_updates_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&confidence_updates_dir)
            .map_err(|e| format!("Failed to read confidence-updates/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();

        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let update: ConfidenceUpdate = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            confidence_updates.push(update);
        }
    }
    let events_dir = dir.join(".vela/events");
    let proposals_dir = dir.join(".vela/proposals");
    let proof_state_path = vela_dir.join("proof-state.json");
    let mut events: Vec<StateEvent> = Vec::new();
    if events_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&events_dir)
            .map_err(|e| format!("Failed to read events/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();

        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let event: StateEvent = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            events.push(event);
        }
    }
    let mut proposals: Vec<StateProposal> = Vec::new();
    if proposals_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&proposals_dir)
            .map_err(|e| format!("Failed to read proposals/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();

        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let proposal: StateProposal = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            proposals.push(proposal);
        }
    }
    let proof_state = if proof_state_path.is_file() {
        let data = std::fs::read_to_string(&proof_state_path)
            .map_err(|e| format!("Failed to read {}: {e}", proof_state_path.display()))?;
        serde_json::from_str::<ProofState>(&data)
            .map_err(|e| format!("Failed to parse {}: {e}", proof_state_path.display()))?
    } else {
        ProofState::default()
    };

    // v0.32: Read replications from `.vela/replications/`. Each file
    // is a single Replication serialized as JSON, content-addressed
    // by `vrep_<id>.json`. Same pattern as findings.
    let replications_dir = dir.join(".vela/replications");
    let mut replications: Vec<crate::bundle::Replication> = Vec::new();
    if replications_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&replications_dir)
            .map_err(|e| format!("Failed to read replications/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();

        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let replication: crate::bundle::Replication = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            replications.push(replication);
        }
    }

    // v0.33: Read datasets from `.vela/datasets/` and code artifacts
    // from `.vela/code-artifacts/`. Same one-file-per-record pattern
    // as findings and replications. Both directories are optional,
    // so pre-v0.33 frontiers without them load unchanged.
    let datasets_dir = dir.join(".vela/datasets");
    let mut datasets: Vec<crate::bundle::Dataset> = Vec::new();
    if datasets_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&datasets_dir)
            .map_err(|e| format!("Failed to read datasets/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();
        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let dataset: crate::bundle::Dataset = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            datasets.push(dataset);
        }
    }

    let code_artifacts_dir = dir.join(".vela/code-artifacts");
    let mut code_artifacts: Vec<crate::bundle::CodeArtifact> = Vec::new();
    if code_artifacts_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&code_artifacts_dir)
            .map_err(|e| format!("Failed to read code-artifacts/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();
        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let artifact: crate::bundle::CodeArtifact = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            code_artifacts.push(artifact);
        }
    }

    let artifacts_dir = dir.join(".vela/artifacts");
    let mut artifacts: Vec<crate::bundle::Artifact> = Vec::new();
    if artifacts_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&artifacts_dir)
            .map_err(|e| format!("Failed to read artifacts/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();
        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let artifact: crate::bundle::Artifact = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            artifacts.push(artifact);
        }
    }

    // v0.34: predictions and resolutions. One file per record at
    // `.vela/predictions/<vpred_id>.json` and
    // `.vela/resolutions/<vres_id>.json`. Same pattern as findings,
    // replications, datasets, code-artifacts.
    let predictions_dir = dir.join(".vela/predictions");
    let mut predictions: Vec<crate::bundle::Prediction> = Vec::new();
    if predictions_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&predictions_dir)
            .map_err(|e| format!("Failed to read predictions/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();
        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let prediction: crate::bundle::Prediction = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            predictions.push(prediction);
        }
    }

    let resolutions_dir = dir.join(".vela/resolutions");
    let mut resolutions: Vec<crate::bundle::Resolution> = Vec::new();
    if resolutions_dir.is_dir() {
        let mut entries: Vec<PathBuf> = std::fs::read_dir(&resolutions_dir)
            .map_err(|e| format!("Failed to read resolutions/: {e}"))?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().is_some_and(|ext| ext == "json"))
            .collect();
        entries.sort();
        for path in entries {
            let data = std::fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let resolution: crate::bundle::Resolution = serde_json::from_str(&data)
                .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;
            resolutions.push(resolution);
        }
    }

    // v0.39: federation peer registry. Stored as a single JSON file
    // (peers are a small flat list, not content-addressed) at
    // `.vela/peers.json`. Pre-v0.39 frontiers without the file load
    // unchanged with an empty peer registry.
    let peers_path = dir.join(".vela/peers.json");
    let peers: Vec<crate::federation::PeerHub> = if peers_path.is_file() {
        let data = std::fs::read_to_string(&peers_path)
            .map_err(|e| format!("Failed to read {}: {e}", peers_path.display()))?;
        serde_json::from_str(&data)
            .map_err(|e| format!("Failed to parse {}: {e}", peers_path.display()))?
    } else {
        Vec::new()
    };

    // Actor registry. Stored as one flat JSON file because actors are a
    // small authority list, not content-addressed frontier objects.
    let actors_path = dir.join(".vela/actors.json");
    let actors: Vec<crate::sign::ActorRecord> = if actors_path.is_file() {
        let data = std::fs::read_to_string(&actors_path)
            .map_err(|e| format!("Failed to read {}: {e}", actors_path.display()))?;
        serde_json::from_str(&data)
            .map_err(|e| format!("Failed to parse {}: {e}", actors_path.display()))?
    } else {
        Vec::new()
    };

    let signatures_path = dir.join(".vela/signatures.json");
    let signatures: Vec<crate::sign::SignedEnvelope> = if signatures_path.is_file() {
        let data = std::fs::read_to_string(&signatures_path)
            .map_err(|e| format!("Failed to read {}: {e}", signatures_path.display()))?;
        serde_json::from_str(&data)
            .map_err(|e| format!("Failed to parse {}: {e}", signatures_path.display()))?
    } else {
        Vec::new()
    };

    let manifest = crate::frontier_repo::manifest_overrides(dir)?;

    // Assemble into Project using the project::assemble function for stats,
    // then patch metadata from config and optional frontier.yaml.
    let manifest_name = manifest
        .as_ref()
        .map(|m| m.name.as_str())
        .unwrap_or(config.project.name.as_str());
    let manifest_description = manifest
        .as_ref()
        .map(|m| m.description.as_str())
        .unwrap_or(config.project.description.as_str());
    // v0.59: rehydrate cross-frontier dependencies from the yaml
    // manifest. Pre-v0.59 these were written into the rendered
    // `frontier.json` but `vela frontier materialize` regenerated
    // that file without them, so any cross-frontier link from a
    // split-repo failed with "no matching dep is declared". The
    // structured field `manifest.dependencies.frontiers_v2` is the
    // durable source of truth.
    let manifest_deps: Vec<project::ProjectDependency> = manifest
        .as_ref()
        .map(|m| m.dependencies.frontiers_v2.clone())
        .unwrap_or_default();
    let mut c = project::assemble(
        manifest_name,
        findings,
        config.project.papers_processed,
        0,
        manifest_description,
    );
    if !config.project.compiled_at.is_empty() {
        c.project.compiled_at = config.project.compiled_at;
    }
    c.project.compiler = config.project.compiler;
    if !manifest_deps.is_empty() {
        c.project.dependencies = manifest_deps;
    }
    let configured_frontier_id = manifest
        .and_then(|m| m.frontier_id)
        .or(config.project.frontier_id);
    c.review_events = review_events;
    c.confidence_updates = confidence_updates;
    c.events = events;
    c.frontier_id = configured_frontier_id.or_else(|| project::frontier_id_from_genesis(&c.events));
    c.proposals = proposals;
    c.proof_state = proof_state;
    c.actors = actors;
    c.signatures = signatures;
    c.replications = replications;
    c.datasets = datasets;
    c.code_artifacts = code_artifacts;
    c.artifacts = artifacts;
    c.predictions = predictions;
    c.resolutions = resolutions;
    c.peers = peers;

    // v0.55: materialize trajectories and negative_results from the
    // event log. Pre-v0.55 these primitives existed in the canonical
    // event stream but never populated `Project.trajectories` or
    // `Project.negative_results` on load, which meant every downstream
    // consumer (CLI listing commands like `vela negative-results .`,
    // `vela trajectory-step`, the export reducer, the Workbench
    // /trajectories and /negative-results pages, and the marketing
    // site's render_findings_constellation SVG) saw empty arrays even
    // though the events were intact in `.vela/events/`.
    materialize_trajectories_and_nulls_from_events(&mut c);

    // v0.56: replay evidence_atom.locator_repaired events into the
    // loaded evidence_atoms array. `project::assemble` derives atoms
    // from findings, which produces atoms with `locator: None` for
    // findings whose evidence_spans are empty. The repair events in
    // `.vela/events/` carry the resolved locator and the parent
    // source id. Without this step, every load erases the curation
    // work the canonical events recorded.
    materialize_evidence_atom_locators_from_events(&mut c);

    project::recompute_stats(&mut c);

    Ok(c)
}

/// v0.56: Walk the event log and apply
/// `evidence_atom.locator_repaired` events into the materialized
/// `evidence_atoms` array. Each event names a single atom by id and
/// sets its `locator`. Idempotent: applying twice with the same
/// payload is a no-op. Divergent locator overwrites are silently
/// dropped here because the reducer-side validator already rejected
/// them at event-emit time; if a stale chain ever made it past the
/// emit boundary the integrity report flags the divergence.
fn materialize_evidence_atom_locators_from_events(p: &mut Project) {
    for ev in &p.events {
        if ev.kind != "evidence_atom.locator_repaired" {
            continue;
        }
        if ev.target.r#type != "evidence_atom" {
            continue;
        }
        let atom_id = ev.target.id.as_str();
        let locator = match ev.payload.get("locator").and_then(|v| v.as_str()) {
            Some(value) if !value.is_empty() => value.to_string(),
            _ => continue,
        };
        if let Some(atom) = p.evidence_atoms.iter_mut().find(|a| a.id == atom_id)
            && atom.locator.is_none()
        {
            atom.locator = Some(locator);
            atom.caveats.retain(|c| c != "missing evidence locator");
        }
    }
}

/// Walk the event log to populate `Project.trajectories` and
/// `Project.negative_results` from the canonical
/// `trajectory.created` / `trajectory.step_appended` /
/// `trajectory.retracted` / `negative_result.asserted` /
/// `negative_result.retracted` events. Mirrors what the reducer
/// would do on a fresh replay; this is the missing materialization
/// step in `load_vela_repo`.
fn materialize_trajectories_and_nulls_from_events(p: &mut Project) {
    use crate::bundle::{NegativeResult, Trajectory, TrajectoryStep};

    let mut trajectories: std::collections::HashMap<String, Trajectory> =
        std::collections::HashMap::new();
    let mut nulls: std::collections::HashMap<String, NegativeResult> =
        std::collections::HashMap::new();

    for ev in &p.events {
        match ev.kind.as_str() {
            "trajectory.created" => {
                if let Some(traj_value) = ev.payload.get("trajectory")
                    && let Ok(traj) = serde_json::from_value::<Trajectory>(traj_value.clone())
                {
                    trajectories.insert(traj.id.clone(), traj);
                }
            }
            "trajectory.step_appended" => {
                let traj_id = ev.target.id.clone();
                if let Some(step_value) = ev.payload.get("step")
                    && let Ok(step) = serde_json::from_value::<TrajectoryStep>(step_value.clone())
                    && let Some(traj) = trajectories.get_mut(&traj_id)
                {
                    traj.steps.push(step);
                }
            }
            "trajectory.retracted" => {
                if let Some(traj) = trajectories.get_mut(&ev.target.id) {
                    traj.retracted = true;
                }
            }
            "negative_result.asserted" => {
                if let Some(nr_value) = ev.payload.get("negative_result")
                    && let Ok(nr) = serde_json::from_value::<NegativeResult>(nr_value.clone())
                {
                    nulls.insert(nr.id.clone(), nr);
                }
            }
            "negative_result.retracted" => {
                if let Some(nr) = nulls.get_mut(&ev.target.id) {
                    nr.retracted = true;
                }
            }
            _ => {}
        }
    }

    if !trajectories.is_empty() {
        let mut traj_vec: Vec<Trajectory> = trajectories.into_values().collect();
        traj_vec.sort_by(|a, b| a.id.cmp(&b.id));
        p.trajectories = traj_vec;
    }
    if !nulls.is_empty() {
        let mut nr_vec: Vec<NegativeResult> = nulls.into_values().collect();
        nr_vec.sort_by(|a, b| a.id.cmp(&b.id));
        p.negative_results = nr_vec;
    }
}

// ── Save ─────────────────────────────────────────────────────────────

/// Save a project to a detected source.
pub fn save(source: &VelaSource, project: &Project) -> Result<(), String> {
    match source {
        VelaSource::ProjectFile(path) => save_project_file(path, project),
        VelaSource::VelaRepo(dir) => save_vela_repo(dir, project),
        VelaSource::PacketDir(dir) => Err(format!(
            "Cannot save directly into packet directory '{}'. Export a new packet instead.",
            dir.display()
        )),
    }
}

fn save_project_file(path: &Path, project: &Project) -> Result<(), String> {
    let json = serde_json::to_string_pretty(project)
        .map_err(|e| format!("Failed to serialize project: {e}"))?;
    std::fs::write(path, json)
        .map_err(|e| format!("Failed to write project file '{}': {e}", path.display()))
}

fn save_vela_repo(dir: &Path, project: &Project) -> Result<(), String> {
    let vela_dir = dir.join(".vela");
    let findings_dir = vela_dir.join("findings");
    let events_dir = vela_dir.join("events");
    let proposals_dir = vela_dir.join("proposals");
    // v0.32: structured replications live in their own directory;
    // each `vrep_<id>.json` is a single Replication record.
    let replications_dir = vela_dir.join("replications");
    // v0.33: datasets and code artifacts each get their own directory.
    let datasets_dir = vela_dir.join("datasets");
    let code_artifacts_dir = vela_dir.join("code-artifacts");
    let artifacts_dir = vela_dir.join("artifacts");
    // v0.34: predictions + resolutions form the epistemic ledger.
    let predictions_dir = vela_dir.join("predictions");
    let resolutions_dir = vela_dir.join("resolutions");

    // Create directories
    for d in [
        &vela_dir,
        &findings_dir,
        &events_dir,
        &proposals_dir,
        &replications_dir,
        &datasets_dir,
        &code_artifacts_dir,
        &artifacts_dir,
        &predictions_dir,
        &resolutions_dir,
    ] {
        std::fs::create_dir_all(d)
            .map_err(|e| format!("Failed to create directory {}: {e}", d.display()))?;
    }

    // Write config.toml
    let config = RepoConfig {
        project: RepoProjectMeta {
            name: project.project.name.clone(),
            frontier_id: Some(project.frontier_id()),
            compiled_at: project.project.compiled_at.clone(),
            description: project.project.description.clone(),
            compiler: project.project.compiler.clone(),
            papers_processed: project.project.papers_processed,
        },
    };
    let toml_str = toml::to_string_pretty(&config)
        .map_err(|e| format!("Failed to serialize config.toml: {e}"))?;
    std::fs::write(vela_dir.join("config.toml"), toml_str)
        .map_err(|e| format!("Failed to write config.toml: {e}"))?;

    // Write each finding as findings/{id}.json. Links remain embedded in the
    // finding bundle; legacy link manifests are still accepted on load.
    for finding in &project.findings {
        let json = serde_json::to_string_pretty(finding)
            .map_err(|e| format!("Failed to serialize finding {}: {e}", finding.id))?;
        let filename = format!("{}.json", finding.id);
        std::fs::write(findings_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write {}: {e}", filename))?;
    }

    for event in &project.events {
        let json = serde_json::to_string_pretty(event)
            .map_err(|e| format!("Failed to serialize state event {}: {e}", event.id))?;
        let filename = format!("{}.json", event.id);
        std::fs::write(events_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write event {}: {e}", filename))?;
    }

    for proposal in &project.proposals {
        let json = serde_json::to_string_pretty(proposal)
            .map_err(|e| format!("Failed to serialize proposal {}: {e}", proposal.id))?;
        let filename = format!("{}.json", proposal.id);
        std::fs::write(proposals_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write proposal {}: {e}", filename))?;
    }

    let proof_state_json = serde_json::to_string_pretty(&project.proof_state)
        .map_err(|e| format!("Failed to serialize proof state: {e}"))?;
    std::fs::write(vela_dir.join("proof-state.json"), proof_state_json)
        .map_err(|e| format!("Failed to write proof-state.json: {e}"))?;

    // v0.32: write replications as one file per `vrep_<id>.json`.
    for replication in &project.replications {
        let json = serde_json::to_string_pretty(replication)
            .map_err(|e| format!("Failed to serialize replication {}: {e}", replication.id))?;
        let filename = format!("{}.json", replication.id);
        std::fs::write(replications_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write replication {}: {e}", filename))?;
    }

    // v0.33: datasets and code artifacts as individual `vd_<id>.json`
    // and `vc_<id>.json` files. Same persistence shape as findings.
    for dataset in &project.datasets {
        let json = serde_json::to_string_pretty(dataset)
            .map_err(|e| format!("Failed to serialize dataset {}: {e}", dataset.id))?;
        let filename = format!("{}.json", dataset.id);
        std::fs::write(datasets_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write dataset {}: {e}", filename))?;
    }
    for artifact in &project.code_artifacts {
        let json = serde_json::to_string_pretty(artifact)
            .map_err(|e| format!("Failed to serialize code artifact {}: {e}", artifact.id))?;
        let filename = format!("{}.json", artifact.id);
        std::fs::write(code_artifacts_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write code artifact {}: {e}", filename))?;
    }

    for artifact in &project.artifacts {
        let json = serde_json::to_string_pretty(artifact)
            .map_err(|e| format!("Failed to serialize artifact {}: {e}", artifact.id))?;
        let filename = format!("{}.json", artifact.id);
        std::fs::write(artifacts_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write artifact {}: {e}", filename))?;
    }

    // v0.34: predictions and resolutions, one file per record.
    for prediction in &project.predictions {
        let json = serde_json::to_string_pretty(prediction)
            .map_err(|e| format!("Failed to serialize prediction {}: {e}", prediction.id))?;
        let filename = format!("{}.json", prediction.id);
        std::fs::write(predictions_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write prediction {}: {e}", filename))?;
    }
    for resolution in &project.resolutions {
        let json = serde_json::to_string_pretty(resolution)
            .map_err(|e| format!("Failed to serialize resolution {}: {e}", resolution.id))?;
        let filename = format!("{}.json", resolution.id);
        std::fs::write(resolutions_dir.join(&filename), json)
            .map_err(|e| format!("Failed to write resolution {}: {e}", filename))?;
    }

    // v0.39: federation peer registry. One JSON file holding the full
    // list (peers are flat, not content-addressed). Skip writing the
    // file when the registry is empty so pre-v0.39 frontiers stay
    // byte-identical on disk.
    let peers_path = vela_dir.join("peers.json");
    if project.peers.is_empty() {
        // Tidy up a stale file if the last peer was removed.
        if peers_path.is_file() {
            std::fs::remove_file(&peers_path)
                .map_err(|e| format!("Failed to remove stale peers.json: {e}"))?;
        }
    } else {
        let json = serde_json::to_string_pretty(&project.peers)
            .map_err(|e| format!("Failed to serialize peers: {e}"))?;
        std::fs::write(&peers_path, json)
            .map_err(|e| format!("Failed to write peers.json: {e}"))?;
    }

    let actors_path = vela_dir.join("actors.json");
    let json = serde_json::to_string_pretty(&project.actors)
        .map_err(|e| format!("Failed to serialize actors: {e}"))?;
    std::fs::write(&actors_path, json).map_err(|e| format!("Failed to write actors.json: {e}"))?;

    let signatures_path = vela_dir.join("signatures.json");
    if project.signatures.is_empty() {
        if signatures_path.is_file() {
            std::fs::remove_file(&signatures_path)
                .map_err(|e| format!("Failed to remove stale signatures.json: {e}"))?;
        }
    } else {
        let json = serde_json::to_string_pretty(&project.signatures)
            .map_err(|e| format!("Failed to serialize signatures: {e}"))?;
        std::fs::write(&signatures_path, json)
            .map_err(|e| format!("Failed to write signatures.json: {e}"))?;
    }

    crate::frontier_repo::write_visible_repo_files(dir, project)?;

    Ok(())
}

// ── Convenience ──────────────────────────────────────────────────────

/// Detect source type from path, then load.
pub fn load_from_path(path: &Path) -> Result<Project, String> {
    let source = detect(path)?;
    load(&source)
}

fn is_packet_dir(path: &Path) -> bool {
    let manifest_path = path.join("manifest.json");
    if !manifest_path.is_file() {
        return false;
    }
    let Ok(data) = std::fs::read_to_string(&manifest_path) else {
        return false;
    };
    let Ok(manifest) = serde_json::from_str::<PacketManifestHeader>(&data) else {
        return false;
    };
    manifest.packet_format == "vela.frontier-packet"
}

fn first_non_empty<'a>(values: impl IntoIterator<Item = &'a str>) -> &'a str {
    values
        .into_iter()
        .find(|value| !value.is_empty())
        .unwrap_or("")
}

/// Detect source type from path, then save.
pub fn save_to_path(path: &Path, project: &Project) -> Result<(), String> {
    let source = detect(path)?;
    save(&source, project)
}

/// Initialize a VelaRepo from a Project at the given directory.
/// Creates the minimum public `.vela/` layout and writes frontier state.
pub fn init_repo(dir: &Path, project: &Project) -> Result<(), String> {
    let vela_dir = dir.join(".vela");
    std::fs::create_dir_all(&vela_dir).map_err(|e| format!("Failed to create .vela/: {e}"))?;
    save_vela_repo(dir, project)
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bundle::*;
    use crate::project;
    use tempfile::TempDir;

    fn make_finding(id: &str, score: f64, assertion_type: &str) -> FindingBundle {
        FindingBundle {
            id: id.into(),
            version: 1,
            previous_version: None,
            assertion: Assertion {
                text: format!("Finding {id}"),
                assertion_type: assertion_type.into(),
                entities: vec![Entity {
                    name: "TestEntity".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: None,
                direction: None,
                causal_claim: None,
                causal_evidence_grade: None,
            },
            evidence: Evidence {
                evidence_type: "experimental".into(),
                model_system: String::new(),
                species: None,
                method: String::new(),
                sample_size: None,
                effect_size: None,
                p_value: None,
                replicated: false,
                replication_count: None,
                evidence_spans: vec![],
            },
            conditions: Conditions {
                text: String::new(),
                species_verified: vec![],
                species_unverified: vec![],
                in_vitro: false,
                in_vivo: false,
                human_data: false,
                clinical_trial: false,
                concentration_range: None,
                duration: None,
                age_group: None,
                cell_type: None,
            },
            confidence: Confidence::raw(score, "seeded prior", 0.85),
            provenance: Provenance {
                source_type: "published_paper".into(),
                doi: None,
                pmid: None,
                pmc: None,
                openalex_id: None,
                url: None,
                title: "Test".into(),
                authors: vec![],
                year: Some(2024),
                journal: None,
                license: None,
                publisher: None,
                funders: vec![],
                extraction: Extraction::default(),
                review: None,
                citation_count: None,
            },
            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,
            },
            links: vec![],
            annotations: vec![],
            attachments: vec![],
            created: String::new(),
            updated: None,

            access_tier: crate::access_tier::AccessTier::Public,
        }
    }

    fn make_project(name: &str, findings: Vec<FindingBundle>) -> Project {
        project::assemble(name, findings, 10, 0, "Test project")
    }

    // ── detect tests ────────────────────────────────────────────────

    #[test]
    fn detect_json_file() {
        let tmp = TempDir::new().unwrap();
        let json_path = tmp.path().join("test.json");
        std::fs::write(&json_path, "{}").unwrap();
        let source = detect(&json_path).unwrap();
        assert_eq!(source, VelaSource::ProjectFile(json_path));
    }

    #[test]
    fn detect_vela_repo() {
        let tmp = TempDir::new().unwrap();
        let repo_dir = tmp.path().join("my-repo");
        std::fs::create_dir_all(repo_dir.join(".vela")).unwrap();
        let source = detect(&repo_dir).unwrap();
        assert_eq!(source, VelaSource::VelaRepo(repo_dir));
    }

    #[test]
    fn detect_dir_without_vela_errors() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("plain-dir");
        std::fs::create_dir_all(&dir).unwrap();
        let result = detect(&dir);
        assert!(result.is_err());
        let error = result.unwrap_err();
        assert!(error.contains("frontier packet"));
        assert!(error.contains("vela init"));
    }

    #[test]
    fn detect_nonexistent_json_path() {
        let path = Path::new("/tmp/nonexistent_test_vela.json");
        let source = detect(path).unwrap();
        assert_eq!(source, VelaSource::ProjectFile(path.to_path_buf()));
    }

    #[test]
    fn detect_nonexistent_non_json_errors() {
        let path = Path::new("/tmp/nonexistent_test_vela_dir");
        let result = detect(path);
        assert!(result.is_err());
    }

    // ── roundtrip: project file ────────────────────────────────────

    #[test]
    fn roundtrip_project_file() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("test.json");

        let mut f1 = make_finding("vf_001", 0.8, "mechanism");
        f1.add_link("vf_002", "extends", "shared entity");
        let f2 = make_finding("vf_002", 0.6, "therapeutic");
        let original = make_project("roundtrip-test", vec![f1, f2]);

        let source = VelaSource::ProjectFile(path.clone());
        save(&source, &original).unwrap();
        let loaded = load(&source).unwrap();

        assert_eq!(loaded.findings.len(), 2);
        assert_eq!(loaded.project.name, "roundtrip-test");
        assert_eq!(loaded.findings[0].links.len(), 1);
        assert_eq!(loaded.findings[0].links[0].target, "vf_002");
    }

    // ── roundtrip: vela repo ────────────────────────────────────────

    #[test]
    fn roundtrip_vela_repo() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("test-repo");

        let mut f1 = make_finding("vf_aaa", 0.9, "mechanism");
        f1.add_link("vf_bbb", "contradicts", "opposite direction");
        f1.add_link("vf_ccc", "supports", "same pathway");
        let f2 = make_finding("vf_bbb", 0.7, "therapeutic");
        let f3 = make_finding("vf_ccc", 0.5, "biomarker");
        let original = make_project("repo-test", vec![f1, f2, f3]);

        init_repo(&dir, &original).unwrap();

        // Verify directory structure
        assert!(dir.join(".vela").is_dir());
        assert!(dir.join(".vela/config.toml").exists());
        assert!(dir.join(".vela/findings").is_dir());
        assert!(dir.join(".vela/findings/vf_aaa.json").exists());
        assert!(dir.join(".vela/findings/vf_bbb.json").exists());
        assert!(dir.join(".vela/findings/vf_ccc.json").exists());
        assert!(dir.join(".vela/events").is_dir());
        assert!(dir.join(".vela/proposals").is_dir());
        assert!(dir.join(".vela/proof-state.json").exists());
        assert!(!dir.join(".vela/links/manifest.json").exists());
        assert!(!dir.join(".vela/reviews").exists());

        // Load back
        let source = VelaSource::VelaRepo(dir);
        let loaded = load(&source).unwrap();

        assert_eq!(loaded.findings.len(), 3);
        assert_eq!(loaded.project.name, "repo-test");
        assert_eq!(loaded.project.description, "Test project");

        // Check links redistributed correctly
        let f1_loaded = loaded.findings.iter().find(|f| f.id == "vf_aaa").unwrap();
        assert_eq!(f1_loaded.links.len(), 2);
        let f2_loaded = loaded.findings.iter().find(|f| f.id == "vf_bbb").unwrap();
        assert!(f2_loaded.links.is_empty());
    }

    // ── links remain embedded in finding bundles ─────────────────────

    #[test]
    fn embedded_links_roundtrip() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("link-test");

        let mut f1 = make_finding("vf_x1", 0.8, "mechanism");
        f1.add_link("vf_x2", "extends", "entity overlap");
        f1.add_link_with_source("vf_x3", "supports", "pathway link", "llm");
        let mut f2 = make_finding("vf_x2", 0.7, "mechanism");
        f2.add_link("vf_x1", "contradicts", "opposite");
        let f3 = make_finding("vf_x3", 0.6, "therapeutic");

        let original = make_project("link-test", vec![f1, f2, f3]);
        init_repo(&dir, &original).unwrap();

        assert!(!dir.join(".vela/links/manifest.json").exists());

        // Load back and verify redistribution
        let loaded = load(&VelaSource::VelaRepo(dir)).unwrap();
        let lf1 = loaded.findings.iter().find(|f| f.id == "vf_x1").unwrap();
        assert_eq!(lf1.links.len(), 2);
        let lf2 = loaded.findings.iter().find(|f| f.id == "vf_x2").unwrap();
        assert_eq!(lf2.links.len(), 1);
        assert_eq!(lf2.links[0].link_type, "contradicts");
    }

    // ── config.toml parsing ─────────────────────────────────────────

    #[test]
    fn config_toml_parsing() {
        let toml_str = r#"
[project]
name = "alzheimers-tau"
description = "Tau pathology in Alzheimer's disease"
compiler = "vela/0.2.0"
papers_processed = 700
"#;
        let config: RepoConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.project.name, "alzheimers-tau");
        assert_eq!(
            config.project.description,
            "Tau pathology in Alzheimer's disease"
        );
        assert_eq!(config.project.papers_processed, 700);
        assert_eq!(config.project.compiler, "vela/0.2.0");
        assert_eq!(config.project.frontier_id, None);
        assert_eq!(config.project.compiled_at, "");
    }

    #[test]
    fn config_toml_minimal() {
        let toml_str = r#"
[project]
name = "minimal"
"#;
        let config: RepoConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.project.name, "minimal");
        assert_eq!(config.project.description, "");
        assert_eq!(config.project.papers_processed, 0);
    }

    #[test]
    fn vela_repo_persists_frontier_id_and_actors() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("actor-repo");

        let mut original = make_project(
            "actor-test",
            vec![make_finding("vf_actor", 0.8, "mechanism")],
        );
        let expected_frontier_id = original.frontier_id();
        original.actors.push(crate::sign::ActorRecord {
            id: "reviewer:test".into(),
            public_key: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(),
            algorithm: "ed25519".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            tier: None,
            orcid: None,
            access_clearance: None,
        });
        original.signatures.push(crate::sign::SignedEnvelope {
            finding_id: "vf_actor".into(),
            signature: "00".repeat(64),
            public_key: "aa".repeat(32),
            signed_at: "2026-01-01T00:00:00Z".into(),
            algorithm: "ed25519".into(),
        });

        init_repo(&dir, &original).unwrap();
        assert!(dir.join(".vela/actors.json").exists());
        assert!(dir.join(".vela/signatures.json").exists());

        let first_load = load(&VelaSource::VelaRepo(dir.clone())).unwrap();
        let second_load = load(&VelaSource::VelaRepo(dir)).unwrap();

        assert_eq!(first_load.frontier_id(), expected_frontier_id);
        assert_eq!(second_load.frontier_id(), expected_frontier_id);
        assert_eq!(first_load.actors, original.actors);
        assert_eq!(first_load.signatures.len(), 1);
        assert_eq!(second_load.signatures.len(), 1);
        assert_eq!(second_load.signatures[0].finding_id, "vf_actor");
    }

    // ── empty project ──────────────────────────────────────────────

    #[test]
    fn empty_project_roundtrip() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("empty-repo");

        let original = make_project("empty", vec![]);
        init_repo(&dir, &original).unwrap();

        let loaded = load(&VelaSource::VelaRepo(dir)).unwrap();
        assert_eq!(loaded.findings.len(), 0);
        assert_eq!(loaded.stats.findings, 0);
        assert_eq!(loaded.stats.links, 0);
        assert_eq!(loaded.project.name, "empty");
    }

    #[test]
    fn artifacts_roundtrip_from_vela_repo() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("artifact-repo");

        let mut original = make_project("artifact-test", vec![]);
        let artifact = Artifact::new(
            "protocol",
            "trial protocol",
            "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
            Some(17),
            Some("application/json".into()),
            "local_blob",
            Some(".vela/artifact-blobs/sha256/bbbb".into()),
            Some("https://example.test/protocol".into()),
            Some("CC0-1.0".into()),
            vec!["vf_target".into()],
            Provenance {
                source_type: "clinical_trial".into(),
                doi: None,
                pmid: None,
                pmc: None,
                openalex_id: None,
                url: Some("https://example.test/protocol".into()),
                title: "trial protocol".into(),
                authors: vec![],
                year: Some(2026),
                journal: None,
                license: Some("CC0-1.0".into()),
                publisher: None,
                funders: vec![],
                extraction: Extraction::default(),
                review: None,
                citation_count: None,
            },
            std::collections::BTreeMap::new(),
            crate::access_tier::AccessTier::Public,
        )
        .unwrap();
        let id = artifact.id.clone();
        original.artifacts.push(artifact);
        init_repo(&dir, &original).unwrap();

        let loaded = load(&VelaSource::VelaRepo(dir.clone())).unwrap();
        assert_eq!(loaded.artifacts.len(), 1);
        assert_eq!(loaded.artifacts[0].id, id);
        assert!(dir.join(".vela/artifacts").is_dir());
    }

    // ── large finding count ─────────────────────────────────────────

    #[test]
    fn large_finding_count() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("large-repo");

        let findings: Vec<FindingBundle> = (0..100)
            .map(|i| make_finding(&format!("vf_{i:04}"), 0.5 + (i as f64) * 0.004, "mechanism"))
            .collect();
        let original = make_project("large", findings);
        assert_eq!(original.findings.len(), 100);

        init_repo(&dir, &original).unwrap();

        let loaded = load(&VelaSource::VelaRepo(dir)).unwrap();
        assert_eq!(loaded.findings.len(), 100);
        assert_eq!(loaded.stats.findings, 100);
    }

    // ── legacy review events remain readable ─────────────────────────

    #[test]
    fn legacy_review_events_load() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("review-repo");

        let mut original =
            make_project("review-test", vec![make_finding("vf_r1", 0.8, "mechanism")]);
        original.review_events.push(ReviewEvent {
            id: "rev_001".into(),
            workspace: None,
            finding_id: "vf_r1".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,
        });

        init_repo(&dir, &original).unwrap();
        assert!(!dir.join(".vela/reviews").exists());
        std::fs::create_dir_all(dir.join(".vela/reviews")).unwrap();
        std::fs::write(
            dir.join(".vela/reviews/rev_001.json"),
            serde_json::to_string_pretty(&original.review_events[0]).unwrap(),
        )
        .unwrap();

        let loaded = load(&VelaSource::VelaRepo(dir)).unwrap();
        assert_eq!(loaded.review_events.len(), 1);
        assert_eq!(loaded.review_events[0].id, "rev_001");
        assert_eq!(loaded.review_events[0].finding_id, "vf_r1");
    }

    #[test]
    fn load_vela_repo_accepts_bbb_review_artifact() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("bbb-review-repo");
        std::fs::create_dir_all(dir.join(".vela/reviews")).unwrap();
        std::fs::write(
            dir.join(".vela/config.toml"),
            "[project]\nname = \"bbb-review-repo\"\ndescription = \"\"\ncompiler = \"vela/test\"\npapers_processed = 0\n",
        )
        .unwrap();
        std::fs::write(
            dir.join(".vela/reviews/rev_001_bbb_correction.json"),
            include_str!("../embedded/tests/fixtures/legacy/rev_001_bbb_correction.json"),
        )
        .unwrap();

        let loaded = load(&VelaSource::VelaRepo(dir)).unwrap();
        assert_eq!(loaded.review_events.len(), 1);
        assert!(matches!(
            loaded.review_events[0].action,
            ReviewAction::Qualified { .. }
        ));
        assert_eq!(loaded.review_events[0].status.as_deref(), Some("accepted"));
    }

    // ── load_from_path convenience ──────────────────────────────────

    #[test]
    fn load_from_path_json() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("convenience.json");

        let original = make_project("convenience", vec![make_finding("vf_c1", 0.8, "mechanism")]);
        let json = serde_json::to_string_pretty(&original).unwrap();
        std::fs::write(&path, json).unwrap();

        let loaded = load_from_path(&path).unwrap();
        assert_eq!(loaded.project.name, "convenience");
        assert_eq!(loaded.findings.len(), 1);
    }

    #[test]
    fn load_from_path_repo() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("conv-repo");

        let original = make_project("conv-repo", vec![make_finding("vf_cr1", 0.8, "mechanism")]);
        init_repo(&dir, &original).unwrap();

        let loaded = load_from_path(&dir).unwrap();
        assert_eq!(loaded.project.name, "conv-repo");
        assert_eq!(loaded.findings.len(), 1);
    }

    #[test]
    fn load_from_path_packet_dir() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("packet-frontier");

        let mut original = make_project(
            "packet-frontier",
            vec![make_finding("vf_pkt1", 0.81, "mechanism")],
        );
        original.review_events.push(ReviewEvent {
            id: "rev_pkt1".into(),
            workspace: Some("bbb".into()),
            finding_id: "vf_pkt1".into(),
            reviewer: "reviewer:test".into(),
            reviewed_at: "2026-01-01T00:00:00Z".into(),
            scope: Some("external".into()),
            status: Some("accepted".into()),
            action: ReviewAction::Approved,
            reason: "Imported from another lab".into(),
            evidence_considered: vec![],
            state_change: None,
        });
        original.stats.review_event_count = original.review_events.len();
        crate::export::export_packet(&original, &dir).unwrap();

        let loaded = load_from_path(&dir).unwrap();
        assert_eq!(loaded.project.name, "packet-frontier");
        assert_eq!(loaded.findings.len(), 1);
        assert_eq!(loaded.review_events.len(), 1);
        assert_eq!(loaded.stats.review_event_count, 1);
    }

    // ── project file -> repo -> project file roundtrip ────────────

    #[test]
    fn full_format_roundtrip() {
        let tmp = TempDir::new().unwrap();

        // Create a project with findings and links
        let mut f1 = make_finding("vf_rt1", 0.85, "mechanism");
        f1.add_link("vf_rt2", "extends", "shared protein");
        let f2 = make_finding("vf_rt2", 0.72, "therapeutic");

        let original = make_project("full-roundtrip", vec![f1, f2]);

        // Save as JSON
        let json_path = tmp.path().join("original.json");
        save(&VelaSource::ProjectFile(json_path.clone()), &original).unwrap();

        // Load from JSON
        let from_json = load(&VelaSource::ProjectFile(json_path)).unwrap();

        // Save as repo
        let repo_dir = tmp.path().join("repo");
        init_repo(&repo_dir, &from_json).unwrap();

        // Load from repo
        let from_repo = load(&VelaSource::VelaRepo(repo_dir)).unwrap();

        // Verify structural equivalence
        assert_eq!(from_repo.findings.len(), from_json.findings.len());
        assert_eq!(from_repo.project.name, from_json.project.name);

        let rt1 = from_repo
            .findings
            .iter()
            .find(|f| f.id == "vf_rt1")
            .unwrap();
        assert_eq!(rt1.links.len(), 1);
        assert_eq!(rt1.links[0].target, "vf_rt2");
        assert_eq!(rt1.links[0].link_type, "extends");
    }
}