1use crate::{
2 benchmark, bridge, bundle, carina_validate, conformance, decision, diff, events, export,
3 frontier_repo, impact, lint, normalize, packet, project, propagate, proposals, repo, review,
4 search, serve, sign, signals, sources, state, state_integrity, tensions, validate,
5};
6
7use std::collections::BTreeMap;
8use std::future::Future;
9use std::path::{Path, PathBuf};
10use std::pin::Pin;
11use std::sync::OnceLock;
12
13use clap::{Parser, Subcommand};
14use colored::Colorize;
15
16use crate::cli_style as style;
17use reqwest::Client;
18use serde::Serialize;
19use serde_json::{Value, json};
20use sha2::{Digest, Sha256};
21
22#[derive(Parser)]
23#[command(name = "vela", version)]
24#[command(about = "Portable frontier state for science")]
25struct Cli {
26 #[command(subcommand)]
27 command: Commands,
28}
29
30#[derive(Subcommand)]
31enum Commands {
32 Scout {
39 folder: PathBuf,
41 #[arg(long)]
43 frontier: PathBuf,
44 #[arg(short, long)]
46 backend: Option<String>,
47 #[arg(long)]
49 dry_run: bool,
50 #[arg(long)]
52 json: bool,
53 },
54 CompileNotes {
61 vault: PathBuf,
63 #[arg(long)]
65 frontier: PathBuf,
66 #[arg(short, long)]
68 backend: Option<String>,
69 #[arg(long)]
71 max_files: Option<usize>,
72 #[arg(long)]
77 max_items_per_category: Option<usize>,
78 #[arg(long)]
80 dry_run: bool,
81 #[arg(long)]
83 json: bool,
84 },
85 CompileCode {
91 root: PathBuf,
93 #[arg(long)]
95 frontier: PathBuf,
96 #[arg(short, long)]
98 backend: Option<String>,
99 #[arg(long)]
101 max_files: Option<usize>,
102 #[arg(long)]
104 dry_run: bool,
105 #[arg(long)]
107 json: bool,
108 },
109 ReviewPending {
115 #[arg(long)]
116 frontier: PathBuf,
117 #[arg(short, long)]
118 backend: Option<String>,
119 #[arg(long)]
120 max_proposals: Option<usize>,
121 #[arg(long, default_value = "1")]
126 batch_size: usize,
127 #[arg(long)]
128 dry_run: bool,
129 #[arg(long)]
130 json: bool,
131 },
132 FindTensions {
136 #[arg(long)]
137 frontier: PathBuf,
138 #[arg(short, long)]
139 backend: Option<String>,
140 #[arg(long)]
141 max_findings: Option<usize>,
142 #[arg(long)]
143 dry_run: bool,
144 #[arg(long)]
145 json: bool,
146 },
147 PlanExperiments {
151 #[arg(long)]
152 frontier: PathBuf,
153 #[arg(short, long)]
154 backend: Option<String>,
155 #[arg(long)]
156 max_findings: Option<usize>,
157 #[arg(long)]
158 dry_run: bool,
159 #[arg(long)]
160 json: bool,
161 },
162 CompileData {
167 root: PathBuf,
169 #[arg(long)]
171 frontier: PathBuf,
172 #[arg(short, long)]
174 backend: Option<String>,
175 #[arg(long)]
177 sample_rows: Option<usize>,
178 #[arg(long)]
180 dry_run: bool,
181 #[arg(long)]
183 json: bool,
184 },
185 Check {
187 source: Option<PathBuf>,
189 #[arg(long)]
191 schema: bool,
192 #[arg(long)]
194 stats: bool,
195 #[arg(long)]
197 conformance: bool,
198 #[arg(long, default_value = "tests/conformance")]
200 conformance_dir: PathBuf,
201 #[arg(long)]
203 all: bool,
204 #[arg(long)]
206 schema_only: bool,
207 #[arg(long)]
209 strict: bool,
210 #[arg(long)]
212 fix: bool,
213 #[arg(long)]
215 json: bool,
216 },
217 Integrity {
219 frontier: PathBuf,
221 #[arg(long)]
223 json: bool,
224 },
225 Impact {
227 frontier: PathBuf,
229 finding_id: String,
231 #[arg(long)]
233 depth: Option<usize>,
234 #[arg(long)]
236 json: bool,
237 },
238 Discord {
245 frontier: PathBuf,
247 #[arg(long)]
249 json: bool,
250 #[arg(long)]
254 kind: Option<String>,
255 },
256 Normalize {
258 source: PathBuf,
260 #[arg(short, long)]
262 out: Option<PathBuf>,
263 #[arg(long)]
265 write: bool,
266 #[arg(long)]
268 dry_run: bool,
269 #[arg(long)]
271 rewrite_ids: bool,
272 #[arg(long)]
274 id_map: Option<PathBuf>,
275 #[arg(long)]
279 resync_provenance: bool,
280 #[arg(long)]
282 json: bool,
283 },
284 Proof {
286 frontier: PathBuf,
288 #[arg(long, short = 'o', default_value = "proof-packet")]
290 out: PathBuf,
291 #[arg(long, default_value = "bbb-alzheimer")]
293 template: String,
294 #[arg(long)]
296 gold: Option<PathBuf>,
297 #[arg(long)]
299 record_proof_state: bool,
300 #[arg(long)]
302 json: bool,
303 },
304 Repo {
306 #[command(subcommand)]
307 action: RepoAction,
308 },
309 Serve {
311 #[arg(required_unless_present_any = ["frontiers", "setup"])]
313 frontier: Option<PathBuf>,
314 #[arg(long)]
316 frontiers: Option<PathBuf>,
317 #[arg(short, long)]
319 backend: Option<String>,
320 #[arg(long)]
322 http: Option<u16>,
323 #[arg(long)]
325 setup: bool,
326 #[arg(long)]
328 check_tools: bool,
329 #[arg(long)]
331 json: bool,
332 #[arg(long)]
336 workbench: bool,
337 },
338 Status {
342 frontier: PathBuf,
343 #[arg(long)]
345 json: bool,
346 },
347 Log {
350 frontier: PathBuf,
351 #[arg(long, default_value = "20")]
353 limit: usize,
354 #[arg(long)]
356 kind: Option<String>,
357 #[arg(long)]
359 json: bool,
360 },
361 Inbox {
365 frontier: PathBuf,
366 #[arg(long)]
368 kind: Option<String>,
369 #[arg(long, default_value = "30")]
371 limit: usize,
372 #[arg(long)]
374 json: bool,
375 },
376 Ask {
381 frontier: PathBuf,
382 #[arg(trailing_var_arg = true)]
384 question: Vec<String>,
385 #[arg(long)]
387 json: bool,
388 },
389 Stats {
391 frontier: PathBuf,
393 #[arg(long)]
395 json: bool,
396 },
397 Search {
399 query: String,
401 #[arg(long)]
403 source: Option<PathBuf>,
404 #[arg(long)]
406 entity: Option<String>,
407 #[arg(long)]
409 r#type: Option<String>,
410 #[arg(long)]
412 all: Option<PathBuf>,
413 #[arg(long, default_value = "20")]
415 limit: usize,
416 #[arg(long)]
418 json: bool,
419 },
420 Tensions {
422 source: PathBuf,
423 #[arg(long)]
424 both_high: bool,
425 #[arg(long)]
426 cross_domain: bool,
427 #[arg(long, default_value = "20")]
428 top: usize,
429 #[arg(long)]
430 json: bool,
431 },
432 Gaps {
434 #[command(subcommand)]
435 action: GapsAction,
436 },
437 Bridge {
439 #[arg(required = true)]
441 inputs: Vec<PathBuf>,
442 #[arg(long, default_value = "true", action = clap::ArgAction::Set)]
444 novelty: bool,
445 #[arg(long, default_value = "30")]
447 top: usize,
448 },
449 Export {
451 frontier: PathBuf,
452 #[arg(short, long, default_value = "csv")]
453 format: String,
454 #[arg(short, long)]
455 output: Option<PathBuf>,
456 },
457 Packet {
459 #[command(subcommand)]
460 action: PacketAction,
461 },
462 Verify {
469 path: PathBuf,
471 #[arg(long)]
472 json: bool,
473 },
474 Bench {
486 frontier: Option<PathBuf>,
488 #[arg(long)]
490 gold: Option<PathBuf>,
491 #[arg(long)]
495 candidate: Option<PathBuf>,
496 #[arg(long)]
500 sources: Option<PathBuf>,
501 #[arg(long)]
504 threshold: Option<f64>,
505 #[arg(long)]
508 report: Option<PathBuf>,
509 #[arg(long)]
510 entity_gold: Option<PathBuf>,
511 #[arg(long)]
512 link_gold: Option<PathBuf>,
513 #[arg(long)]
514 suite: Option<PathBuf>,
515 #[arg(long)]
516 suite_ready: bool,
517 #[arg(long)]
518 min_f1: Option<f64>,
519 #[arg(long)]
520 min_precision: Option<f64>,
521 #[arg(long)]
522 min_recall: Option<f64>,
523 #[arg(long)]
524 no_thresholds: bool,
525 #[arg(long)]
526 json: bool,
527 },
528 Conformance {
530 #[arg(default_value = "tests/conformance")]
531 dir: PathBuf,
532 },
533 Version,
535 Sign {
537 #[command(subcommand)]
538 action: SignAction,
539 },
540 Actor {
542 #[command(subcommand)]
543 action: ActorAction,
544 },
545 Federation {
550 #[command(subcommand)]
551 action: FederationAction,
552 },
553 Causal {
560 #[command(subcommand)]
561 action: CausalAction,
562 },
563 Frontier {
567 #[command(subcommand)]
568 action: FrontierAction,
569 },
570 Queue {
573 #[command(subcommand)]
574 action: QueueAction,
575 },
576 Registry {
579 #[command(subcommand)]
580 action: RegistryAction,
581 },
582 Init {
584 #[arg(default_value = ".")]
585 path: PathBuf,
586 #[arg(long, default_value = "unnamed")]
587 name: String,
588 #[arg(long, default_value = "default")]
589 template: String,
590 #[arg(long)]
591 no_git: bool,
592 #[arg(long)]
593 json: bool,
594 },
595 Agent {
612 #[command(subcommand)]
613 action: AgentAction,
614 },
615 Quickstart {
616 #[arg(default_value = "demo")]
618 path: PathBuf,
619 #[arg(long, default_value = "Quickstart frontier")]
621 name: String,
622 #[arg(long, default_value = "reviewer:you")]
626 reviewer: String,
627 #[arg(long)]
630 assertion: Option<String>,
631 #[arg(long)]
634 keys_out: Option<PathBuf>,
635 #[arg(long)]
637 json: bool,
638 },
639 Lock {
646 path: PathBuf,
648 #[arg(long)]
651 check: bool,
652 #[arg(long)]
654 json: bool,
655 },
656 Doc {
663 path: PathBuf,
665 #[arg(long)]
667 out: Option<PathBuf>,
668 #[arg(long)]
671 json: bool,
672 },
673 Import {
675 frontier: PathBuf,
676 #[arg(long)]
677 into: Option<PathBuf>,
678 },
679 Diff {
689 target: String,
693 frontier_b: Option<String>,
697 #[arg(long)]
701 frontier: Option<PathBuf>,
702 #[arg(long, default_value = "reviewer:preview")]
704 reviewer: String,
705 #[arg(long)]
711 from: Option<String>,
712 #[arg(long)]
713 json: bool,
714 #[arg(long)]
715 quiet: bool,
716 },
717 Proposals {
719 #[command(subcommand)]
720 action: ProposalAction,
721 },
722 SearchIndex {
727 #[command(subcommand)]
728 action: SearchAction,
729 },
730 Credit {
735 frontier: PathBuf,
736 #[arg(long)]
737 out: Option<PathBuf>,
738 #[arg(long)]
739 json: bool,
740 },
741 Citation {
746 target: String,
750 #[arg(long)]
752 frontier: Option<PathBuf>,
753 #[arg(long, default_value = "bibtex")]
756 format: String,
757 #[arg(long)]
761 locator: Option<String>,
762 #[arg(long)]
764 out: Option<PathBuf>,
765 #[arg(long)]
766 json: bool,
767 },
768 Lean {
774 #[command(subcommand)]
775 action: LeanAction,
776 },
777 DiffPack {
782 #[command(subcommand)]
783 action: DiffPackAction,
784 },
785 Tool {
791 #[command(subcommand)]
792 action: ToolCliAction,
793 },
794 Eval {
799 #[command(subcommand)]
800 action: EvalCliAction,
801 },
802 Conflict {
807 #[command(subcommand)]
808 action: ConflictCliAction,
809 },
810 Hub {
815 #[command(subcommand)]
816 action: HubSpecCli,
817 },
818 ReviewThread {
825 #[command(subcommand)]
826 action: ReviewThreadCli,
827 },
828 Preprint {
833 frontier: PathBuf,
835 #[arg(long)]
838 released_at: Option<String>,
839 #[arg(long)]
841 out: Option<PathBuf>,
842 #[arg(long)]
843 json: bool,
844 },
845 Handle {
850 handle: String,
853 #[arg(long, default_value = "https://vela-site.fly.dev")]
856 site: String,
857 #[arg(long)]
858 json: bool,
859 },
860 Crossref {
865 frontier: PathBuf,
867 #[arg(long)]
870 release: Option<String>,
871 #[arg(long)]
873 member: String,
874 #[arg(long)]
877 prefix: String,
878 #[arg(long)]
880 depositor_name: String,
881 #[arg(long)]
883 depositor_email: String,
884 #[arg(long)]
886 resource_url: String,
887 #[arg(long)]
889 title: Option<String>,
890 #[arg(long)]
892 description: Option<String>,
893 #[arg(long)]
895 license: Option<String>,
896 #[arg(long)]
899 xml: bool,
900 #[arg(long)]
902 out: Option<PathBuf>,
903 #[arg(long)]
904 json: bool,
905 },
906 ArtifactToState {
908 frontier: PathBuf,
910 packet: PathBuf,
912 #[arg(long)]
914 actor: String,
915 #[arg(long)]
917 apply_artifacts: bool,
918 #[arg(long)]
919 json: bool,
920 },
921 BridgeKit {
923 #[command(subcommand)]
924 action: BridgeKitAction,
925 },
926 SourceAdapter {
928 #[command(subcommand)]
929 action: SourceAdapterAction,
930 },
931 RuntimeAdapter {
933 #[command(subcommand)]
934 action: RuntimeAdapterAction,
935 },
936 Finding {
938 #[command(subcommand)]
939 command: FindingCommands,
940 },
941 Link {
945 #[command(subcommand)]
946 action: LinkAction,
947 },
948 Workbench {
953 #[arg(default_value = ".")]
955 path: PathBuf,
956 #[arg(long, default_value_t = 3850)]
958 port: u16,
959 #[arg(long)]
961 no_open: bool,
962 },
963 Bridges {
969 #[command(subcommand)]
970 action: BridgesAction,
971 },
972 Entity {
977 #[command(subcommand)]
978 action: EntityAction,
979 },
980 Review {
982 frontier: PathBuf,
984 finding_id: String,
986 #[arg(long)]
988 status: Option<String>,
989 #[arg(long)]
991 reason: Option<String>,
992 #[arg(long)]
994 reviewer: String,
995 #[arg(long)]
997 apply: bool,
998 #[arg(long)]
1000 json: bool,
1001 },
1002 Note {
1004 frontier: PathBuf,
1005 finding_id: String,
1006 #[arg(long)]
1007 text: String,
1008 #[arg(long)]
1009 author: String,
1010 #[arg(long)]
1012 apply: bool,
1013 #[arg(long)]
1014 json: bool,
1015 },
1016 Caveat {
1018 frontier: PathBuf,
1019 finding_id: String,
1020 #[arg(long)]
1021 text: String,
1022 #[arg(long)]
1023 author: String,
1024 #[arg(long)]
1025 apply: bool,
1026 #[arg(long)]
1027 json: bool,
1028 },
1029 Revise {
1031 frontier: PathBuf,
1032 finding_id: String,
1033 #[arg(long)]
1035 confidence: f64,
1036 #[arg(long)]
1038 reason: String,
1039 #[arg(long)]
1041 reviewer: String,
1042 #[arg(long)]
1043 apply: bool,
1044 #[arg(long)]
1045 json: bool,
1046 },
1047 Reject {
1049 frontier: PathBuf,
1050 finding_id: String,
1051 #[arg(long)]
1052 reason: String,
1053 #[arg(long)]
1054 reviewer: String,
1055 #[arg(long)]
1056 apply: bool,
1057 #[arg(long)]
1058 json: bool,
1059 },
1060 History {
1062 frontier: PathBuf,
1063 finding_id: String,
1064 #[arg(long)]
1065 json: bool,
1066 #[arg(long, value_name = "RFC3339_TIMESTAMP")]
1070 as_of: Option<String>,
1071 },
1072 ImportEvents {
1074 source: PathBuf,
1075 #[arg(long)]
1076 into: PathBuf,
1077 #[arg(long)]
1078 json: bool,
1079 },
1080 Retract {
1082 source: PathBuf,
1083 finding_id: String,
1084 #[arg(long)]
1085 reason: String,
1086 #[arg(long)]
1087 reviewer: String,
1088 #[arg(long)]
1089 apply: bool,
1090 #[arg(long)]
1091 json: bool,
1092 },
1093 ProofAdd {
1105 frontier: PathBuf,
1106 #[arg(long = "target-finding")]
1108 target_finding: String,
1109 #[arg(long, default_value = "lean4")]
1112 tool: String,
1113 #[arg(long = "tool-version", default_value = "4.29.1")]
1115 tool_version: String,
1116 #[arg(long = "script-path")]
1118 script_path: PathBuf,
1119 #[arg(long, default_value = "Proof script")]
1121 name: String,
1122 #[arg(long)]
1124 reviewer: String,
1125 #[arg(long)]
1127 reason: String,
1128 #[arg(long)]
1129 json: bool,
1130 },
1131 ProofAttestVerification {
1139 #[arg(long)]
1141 proof_id: String,
1142 #[arg(long, default_value = "lean4")]
1144 tool: String,
1145 #[arg(long = "tool-version", default_value = "4.29.1")]
1146 tool_version: String,
1147 #[arg(long)]
1150 script_locator: String,
1151 #[arg(long = "lake-manifest-hash")]
1153 lake_manifest_hash: Option<String>,
1154 #[arg(long = "verifier-output-hash")]
1156 verifier_output_hash: String,
1157 #[arg(long, default_value = "verified")]
1159 status: String,
1160 #[arg(long = "verifier-actor")]
1163 verifier_actor: String,
1164 #[arg(long)]
1166 key: PathBuf,
1167 #[arg(long)]
1169 out: PathBuf,
1170 #[arg(long)]
1171 json: bool,
1172 },
1173 ProofVerifyAttestation {
1177 record: PathBuf,
1179 #[arg(long)]
1180 json: bool,
1181 },
1182 EntityAdd {
1187 frontier: PathBuf,
1188 finding_id: String,
1189 #[arg(long)]
1190 entity: String,
1191 #[arg(long)]
1195 entity_type: String,
1196 #[arg(long)]
1197 reviewer: String,
1198 #[arg(long)]
1199 reason: String,
1200 #[arg(long)]
1201 apply: bool,
1202 #[arg(long)]
1203 json: bool,
1204 },
1205 EntityResolve {
1209 frontier: PathBuf,
1210 finding_id: String,
1211 #[arg(long)]
1212 entity: String,
1213 #[arg(long)]
1214 source: String,
1215 #[arg(long)]
1216 id: String,
1217 #[arg(long)]
1218 confidence: f64,
1219 #[arg(long)]
1220 matched_name: Option<String>,
1221 #[arg(long, default_value = "manual")]
1222 resolution_method: String,
1223 #[arg(long)]
1224 reviewer: String,
1225 #[arg(long)]
1226 reason: String,
1227 #[arg(long)]
1228 apply: bool,
1229 #[arg(long)]
1230 json: bool,
1231 },
1232 SourceFetch {
1240 identifier: String,
1243 #[arg(long)]
1247 cache: Option<PathBuf>,
1248 #[arg(long)]
1250 out: Option<PathBuf>,
1251 #[arg(long)]
1253 refresh: bool,
1254 #[arg(long)]
1255 json: bool,
1256 },
1257 SpanRepair {
1260 frontier: PathBuf,
1261 finding_id: String,
1262 #[arg(long)]
1263 section: String,
1264 #[arg(long)]
1265 text: String,
1266 #[arg(long)]
1267 reviewer: String,
1268 #[arg(long)]
1269 reason: String,
1270 #[arg(long)]
1271 apply: bool,
1272 #[arg(long)]
1273 json: bool,
1274 },
1275 LocatorRepair {
1280 frontier: PathBuf,
1281 atom_id: String,
1282 #[arg(long)]
1285 locator: Option<String>,
1286 #[arg(long)]
1289 reviewer: String,
1290 #[arg(long)]
1292 reason: String,
1293 #[arg(long)]
1295 apply: bool,
1296 #[arg(long)]
1297 json: bool,
1298 },
1299 Propagate {
1301 frontier: PathBuf,
1302 #[arg(long)]
1303 retract: Option<String>,
1304 #[arg(long)]
1305 reduce_confidence: Option<String>,
1306 #[arg(long)]
1307 to: Option<f64>,
1308 #[arg(short, long)]
1309 output: Option<PathBuf>,
1310 },
1311 Replicate {
1320 frontier: PathBuf,
1322 target: String,
1324 #[arg(long)]
1326 outcome: String,
1327 #[arg(long)]
1329 by: String,
1330 #[arg(long)]
1334 conditions: String,
1335 #[arg(long)]
1337 source_title: String,
1338 #[arg(long)]
1340 doi: Option<String>,
1341 #[arg(long)]
1343 pmid: Option<String>,
1344 #[arg(long)]
1346 sample_size: Option<String>,
1347 #[arg(long, default_value = "")]
1350 note: String,
1351 #[arg(long)]
1353 previous_attempt: Option<String>,
1354 #[arg(long, default_value_t = false)]
1361 no_cascade: bool,
1362 #[arg(long)]
1364 json: bool,
1365 },
1366 Replications {
1369 frontier: PathBuf,
1371 #[arg(long)]
1373 target: Option<String>,
1374 #[arg(long)]
1376 json: bool,
1377 },
1378 DatasetAdd {
1385 frontier: PathBuf,
1387 #[arg(long)]
1389 name: String,
1390 #[arg(long)]
1392 version: Option<String>,
1393 #[arg(long)]
1397 content_hash: String,
1398 #[arg(long)]
1400 url: Option<String>,
1401 #[arg(long)]
1403 license: Option<String>,
1404 #[arg(long)]
1406 source_title: String,
1407 #[arg(long)]
1409 doi: Option<String>,
1410 #[arg(long)]
1412 row_count: Option<u64>,
1413 #[arg(long)]
1415 json: bool,
1416 },
1417 Datasets {
1419 frontier: PathBuf,
1420 #[arg(long)]
1421 json: bool,
1422 },
1423 CodeAdd {
1427 frontier: PathBuf,
1429 #[arg(long)]
1431 language: String,
1432 #[arg(long)]
1434 repo_url: Option<String>,
1435 #[arg(long)]
1438 commit: Option<String>,
1439 #[arg(long)]
1441 path: String,
1442 #[arg(long)]
1444 content_hash: String,
1445 #[arg(long)]
1447 line_start: Option<u32>,
1448 #[arg(long)]
1450 line_end: Option<u32>,
1451 #[arg(long)]
1453 entry_point: Option<String>,
1454 #[arg(long)]
1456 json: bool,
1457 },
1458 CodeArtifacts {
1460 frontier: PathBuf,
1461 #[arg(long)]
1462 json: bool,
1463 },
1464 ArtifactAdd {
1469 frontier: PathBuf,
1471 #[arg(long)]
1474 kind: String,
1475 #[arg(long)]
1477 name: String,
1478 #[arg(long)]
1481 file: Option<PathBuf>,
1482 #[arg(long)]
1484 url: Option<String>,
1485 #[arg(long)]
1487 content_hash: Option<String>,
1488 #[arg(long)]
1490 media_type: Option<String>,
1491 #[arg(long)]
1493 license: Option<String>,
1494 #[arg(long)]
1496 source_title: Option<String>,
1497 #[arg(long)]
1499 source_url: Option<String>,
1500 #[arg(long)]
1502 doi: Option<String>,
1503 #[arg(long)]
1505 target: Vec<String>,
1506 #[arg(long)]
1508 metadata: Vec<String>,
1509 #[arg(long, default_value = "public")]
1511 access_tier: String,
1512 #[arg(long, default_value = "reviewer:manual")]
1514 deposited_by: String,
1515 #[arg(long, default_value = "artifact deposit")]
1517 reason: String,
1518 #[arg(long)]
1520 json: bool,
1521 },
1522 Artifacts {
1524 frontier: PathBuf,
1525 #[arg(long)]
1527 target: Option<String>,
1528 #[arg(long)]
1529 json: bool,
1530 },
1531 ArtifactAudit {
1533 frontier: PathBuf,
1534 #[arg(long)]
1536 json: bool,
1537 },
1538 DecisionBrief {
1540 frontier: PathBuf,
1541 #[arg(long)]
1543 json: bool,
1544 },
1545 TrialSummary {
1547 frontier: PathBuf,
1548 #[arg(long)]
1550 json: bool,
1551 },
1552 SourceVerification {
1554 frontier: PathBuf,
1555 #[arg(long)]
1557 json: bool,
1558 },
1559 SourceIngestPlan {
1561 frontier: PathBuf,
1562 #[arg(long)]
1564 json: bool,
1565 },
1566 ClinicalTrialImport {
1569 frontier: PathBuf,
1571 nct_id: String,
1573 #[arg(long)]
1576 input_json: Option<PathBuf>,
1577 #[arg(long)]
1579 target: Vec<String>,
1580 #[arg(long, default_value = "reviewer:manual")]
1582 deposited_by: String,
1583 #[arg(long, default_value = "clinical trial record import")]
1585 reason: String,
1586 #[arg(long, default_value = "ClinicalTrials.gov public record")]
1588 license: String,
1589 #[arg(long)]
1591 json: bool,
1592 },
1593 NegativeResultAdd {
1601 frontier: PathBuf,
1603 #[arg(long)]
1605 kind: String,
1606 #[arg(long)]
1608 deposited_by: String,
1609 #[arg(long)]
1611 reason: String,
1612 #[arg(long)]
1615 conditions_text: String,
1616 #[arg(long, default_value = "")]
1618 notes: String,
1619 #[arg(long)]
1622 target: Vec<String>,
1623 #[arg(long)]
1627 endpoint: Option<String>,
1628 #[arg(long)]
1630 intervention: Option<String>,
1631 #[arg(long)]
1633 comparator: Option<String>,
1634 #[arg(long)]
1636 population: Option<String>,
1637 #[arg(long)]
1639 n_enrolled: Option<u32>,
1640 #[arg(long)]
1642 power: Option<f64>,
1643 #[arg(long)]
1645 ci_lower: Option<f64>,
1646 #[arg(long)]
1648 ci_upper: Option<f64>,
1649 #[arg(long)]
1651 effect_size_threshold: Option<f64>,
1652 #[arg(long)]
1654 registry_id: Option<String>,
1655 #[arg(long)]
1658 reagent: Option<String>,
1659 #[arg(long)]
1661 observation: Option<String>,
1662 #[arg(long)]
1664 attempts: Option<u32>,
1665 #[arg(long)]
1668 source_title: String,
1669 #[arg(long)]
1671 doi: Option<String>,
1672 #[arg(long)]
1674 url: Option<String>,
1675 #[arg(long)]
1677 year: Option<i32>,
1678 #[arg(long)]
1680 json: bool,
1681 },
1682 NegativeResults {
1684 frontier: PathBuf,
1685 #[arg(long)]
1687 target: Option<String>,
1688 #[arg(long)]
1689 json: bool,
1690 },
1691 TrajectoryCreate {
1696 frontier: PathBuf,
1698 #[arg(long)]
1700 deposited_by: String,
1701 #[arg(long)]
1703 reason: String,
1704 #[arg(long)]
1709 target: Vec<String>,
1710 #[arg(long, default_value = "")]
1712 notes: String,
1713 #[arg(long)]
1714 json: bool,
1715 },
1716 TrajectoryStep {
1719 frontier: PathBuf,
1721 trajectory_id: String,
1723 #[arg(long)]
1725 kind: String,
1726 #[arg(long)]
1730 description: String,
1731 #[arg(long)]
1733 actor: String,
1734 #[arg(long)]
1736 reason: String,
1737 #[arg(long)]
1740 reference: Vec<String>,
1741 #[arg(long)]
1742 json: bool,
1743 },
1744 Trajectories {
1746 frontier: PathBuf,
1747 #[arg(long)]
1749 target: Option<String>,
1750 #[arg(long)]
1751 json: bool,
1752 },
1753 TierSet {
1759 frontier: PathBuf,
1761 #[arg(long)]
1763 object_type: String,
1764 #[arg(long)]
1766 object_id: String,
1767 #[arg(long)]
1769 tier: String,
1770 #[arg(long)]
1773 actor: String,
1774 #[arg(long)]
1777 reason: String,
1778 #[arg(long)]
1779 json: bool,
1780 },
1781 Predict {
1788 frontier: PathBuf,
1790 #[arg(long)]
1792 by: String,
1793 #[arg(long)]
1796 claim: String,
1797 #[arg(long)]
1799 criterion: String,
1800 #[arg(long)]
1802 resolves_by: Option<String>,
1803 #[arg(long)]
1805 confidence: f64,
1806 #[arg(long, default_value = "")]
1808 target: String,
1809 #[arg(long, default_value = "affirmed")]
1811 outcome: String,
1812 #[arg(long, default_value = "")]
1814 conditions: String,
1815 #[arg(long)]
1817 json: bool,
1818 },
1819 Resolve {
1824 frontier: PathBuf,
1826 prediction: String,
1828 #[arg(long)]
1830 outcome: String,
1831 #[arg(long)]
1833 matched: bool,
1834 #[arg(long)]
1837 by: String,
1838 #[arg(long, default_value = "1.0")]
1840 confidence: f64,
1841 #[arg(long, default_value = "")]
1843 source_title: String,
1844 #[arg(long)]
1846 doi: Option<String>,
1847 #[arg(long)]
1849 json: bool,
1850 },
1851 Predictions {
1853 frontier: PathBuf,
1854 #[arg(long)]
1856 by: Option<String>,
1857 #[arg(long)]
1859 open: bool,
1860 #[arg(long)]
1862 json: bool,
1863 },
1864 Calibration {
1867 frontier: PathBuf,
1868 #[arg(long)]
1870 actor: Option<String>,
1871 #[arg(long)]
1873 json: bool,
1874 },
1875 PredictionsExpire {
1883 frontier: PathBuf,
1884 #[arg(long)]
1887 now: Option<String>,
1888 #[arg(long)]
1891 dry_run: bool,
1892 #[arg(long)]
1893 json: bool,
1894 },
1895 Consensus {
1904 frontier: PathBuf,
1906 target: String,
1908 #[arg(long, default_value = "composite")]
1911 weighting: String,
1912 #[arg(long)]
1917 causal_claim: Option<String>,
1918 #[arg(long)]
1923 causal_grade_min: Option<String>,
1924 #[arg(long)]
1926 json: bool,
1927 },
1928
1929 Ingest {
1945 path: String,
1948 #[arg(long)]
1951 frontier: PathBuf,
1952 #[arg(short, long)]
1956 backend: Option<String>,
1957 #[arg(long)]
1961 actor: Option<String>,
1962 #[arg(long)]
1964 dry_run: bool,
1965 #[arg(long)]
1966 json: bool,
1967 },
1968
1969 Propose {
1975 frontier: PathBuf,
1976 finding_id: String,
1977 #[arg(long)]
1979 status: String,
1980 #[arg(long)]
1981 reason: String,
1982 #[arg(long)]
1983 reviewer: String,
1984 #[arg(long)]
1987 apply: bool,
1988 #[arg(long)]
1989 json: bool,
1990 },
1991
1992 Accept {
1996 frontier: PathBuf,
1997 proposal_id: String,
1998 #[arg(long)]
1999 reviewer: String,
2000 #[arg(long)]
2001 reason: String,
2002 #[arg(long)]
2003 json: bool,
2004 },
2005
2006 Attest {
2018 frontier: PathBuf,
2020 #[arg(long)]
2024 event: Option<String>,
2025 #[arg(long)]
2028 attester: Option<String>,
2029 #[arg(long)]
2032 scope_note: Option<String>,
2033 #[arg(long)]
2036 proof_id: Option<String>,
2037 #[arg(long)]
2042 signature: Option<String>,
2043 #[arg(long)]
2046 key: Option<PathBuf>,
2047 #[arg(long)]
2048 json: bool,
2049 },
2050
2051 Lineage {
2054 frontier: PathBuf,
2055 finding_id: String,
2056 #[arg(long, value_name = "RFC3339_TIMESTAMP")]
2057 as_of: Option<String>,
2058 #[arg(long)]
2059 json: bool,
2060 },
2061
2062 Carina {
2065 #[command(subcommand)]
2066 action: CarinaAction,
2067 },
2068
2069 Atlas {
2074 #[command(subcommand)]
2075 action: AtlasAction,
2076 },
2077
2078 Constellation {
2084 #[command(subcommand)]
2085 action: ConstellationAction,
2086 },
2087}
2088
2089#[derive(Subcommand)]
2094enum AtlasAction {
2095 Init {
2100 name: String,
2103 #[arg(long, value_delimiter = ',', num_args = 1..)]
2105 frontiers: Vec<PathBuf>,
2106 #[arg(long, default_value = "general")]
2109 domain: String,
2110 #[arg(long)]
2112 scope_note: Option<String>,
2113 #[arg(long, default_value = "atlases")]
2115 atlases_root: PathBuf,
2116 #[arg(long)]
2117 json: bool,
2118 },
2119 Materialize {
2123 name: String,
2125 #[arg(long, default_value = "atlases")]
2126 atlases_root: PathBuf,
2127 #[arg(long)]
2128 json: bool,
2129 },
2130 Serve {
2135 name: String,
2136 #[arg(long, default_value = "atlases")]
2137 atlases_root: PathBuf,
2138 #[arg(long, default_value_t = 3848)]
2139 port: u16,
2140 #[arg(long)]
2141 no_open: bool,
2142 },
2143 Update {
2150 name: String,
2151 #[arg(long, value_delimiter = ',')]
2154 add_frontier: Vec<PathBuf>,
2155 #[arg(long, value_delimiter = ',')]
2158 remove_vfr_id: Vec<String>,
2159 #[arg(long, default_value = "atlases")]
2160 atlases_root: PathBuf,
2161 #[arg(long)]
2162 json: bool,
2163 },
2164}
2165
2166#[derive(Subcommand)]
2170enum ConstellationAction {
2171 Init {
2175 name: String,
2176 #[arg(long, value_delimiter = ',', num_args = 1..)]
2178 atlases: Vec<PathBuf>,
2179 #[arg(long)]
2180 scope_note: Option<String>,
2181 #[arg(long, default_value = "constellations")]
2182 constellations_root: PathBuf,
2183 #[arg(long)]
2184 json: bool,
2185 },
2186 Materialize {
2191 name: String,
2192 #[arg(long, default_value = "constellations")]
2193 constellations_root: PathBuf,
2194 #[arg(long)]
2195 json: bool,
2196 },
2197 Serve {
2201 name: String,
2202 #[arg(long, default_value = "constellations")]
2203 constellations_root: PathBuf,
2204 #[arg(long, default_value_t = 3849)]
2205 port: u16,
2206 #[arg(long)]
2207 no_open: bool,
2208 },
2209}
2210
2211#[derive(Subcommand)]
2215enum CarinaAction {
2216 Validate {
2221 path: PathBuf,
2225 #[arg(long)]
2228 primitive: Option<String>,
2229 #[arg(long)]
2230 json: bool,
2231 },
2232 List {
2234 #[arg(long)]
2235 json: bool,
2236 },
2237 Schema { primitive: String },
2239}
2240
2241#[derive(Subcommand)]
2242enum PacketAction {
2243 Inspect {
2245 path: PathBuf,
2246 #[arg(long)]
2247 json: bool,
2248 },
2249 Validate {
2251 path: PathBuf,
2252 #[arg(long)]
2253 json: bool,
2254 },
2255}
2256
2257#[derive(Subcommand)]
2258enum SignAction {
2259 GenerateKeypair {
2261 #[arg(long, default_value = ".vela/keys")]
2262 out: PathBuf,
2263 #[arg(long)]
2264 json: bool,
2265 },
2266 Apply {
2268 frontier: PathBuf,
2269 #[arg(long)]
2270 private_key: PathBuf,
2271 #[arg(long)]
2272 json: bool,
2273 },
2274 Verify {
2276 frontier: PathBuf,
2277 #[arg(long)]
2278 public_key: Option<PathBuf>,
2279 #[arg(long)]
2280 json: bool,
2281 },
2282 ThresholdSet {
2287 frontier: PathBuf,
2288 finding_id: String,
2290 #[arg(long)]
2292 to: u32,
2293 #[arg(long)]
2294 json: bool,
2295 },
2296}
2297
2298#[derive(Subcommand)]
2299enum ActorAction {
2300 Add {
2302 frontier: PathBuf,
2303 id: String,
2305 #[arg(long)]
2307 pubkey: String,
2308 #[arg(long)]
2312 tier: Option<String>,
2313 #[arg(long)]
2317 orcid: Option<String>,
2318 #[arg(long)]
2323 clearance: Option<String>,
2324 #[arg(long)]
2325 json: bool,
2326 },
2327 List {
2329 frontier: PathBuf,
2330 #[arg(long)]
2331 json: bool,
2332 },
2333 Rotate {
2344 frontier: PathBuf,
2345 #[arg(long)]
2348 id: String,
2349 #[arg(long = "new-id")]
2354 new_id: String,
2355 #[arg(long = "new-pubkey")]
2357 new_pubkey: String,
2358 #[arg(long)]
2361 reason: String,
2362 #[arg(long)]
2363 json: bool,
2364 },
2365 LookupOrcid {
2370 orcid: String,
2373 #[arg(long)]
2378 register_on: Option<PathBuf>,
2379 #[arg(long)]
2382 id: Option<String>,
2383 #[arg(long)]
2386 pubkey: Option<String>,
2387 #[arg(long)]
2388 json: bool,
2389 },
2390}
2391
2392#[derive(Subcommand)]
2399enum AgentAction {
2400 Init {
2404 name: String,
2407 #[arg(long, default_value = "custom")]
2411 framework: String,
2412 #[arg(long)]
2414 out: Option<PathBuf>,
2415 #[arg(long)]
2416 json: bool,
2417 },
2418 List {
2420 #[arg(long, default_value = "agents")]
2422 root: PathBuf,
2423 #[arg(long)]
2424 json: bool,
2425 },
2426}
2427
2428#[derive(Subcommand)]
2429enum CausalAction {
2430 Audit {
2434 frontier: PathBuf,
2435 #[arg(long)]
2438 problems_only: bool,
2439 #[arg(long)]
2440 json: bool,
2441 },
2442 Effect {
2455 frontier: PathBuf,
2456 source: String,
2458 #[arg(long)]
2460 on: String,
2461 #[arg(long)]
2462 json: bool,
2463 },
2464 Graph {
2467 frontier: PathBuf,
2468 #[arg(long)]
2470 node: Option<String>,
2471 #[arg(long)]
2472 json: bool,
2473 },
2474 Counterfactual {
2481 frontier: PathBuf,
2482 intervene_on: String,
2484 #[arg(long)]
2486 set_to: f64,
2487 #[arg(long)]
2489 target: String,
2490 #[arg(long)]
2491 json: bool,
2492 },
2493}
2494
2495#[derive(Subcommand)]
2496enum BridgesAction {
2497 Derive {
2501 frontier_a: PathBuf,
2504 #[arg(long, default_value = "a")]
2506 label_a: String,
2507 frontier_b: PathBuf,
2509 #[arg(long, default_value = "b")]
2511 label_b: String,
2512 #[arg(long)]
2513 json: bool,
2514 },
2515 List {
2517 frontier: PathBuf,
2519 #[arg(long)]
2521 status: Option<String>,
2522 #[arg(long)]
2523 json: bool,
2524 },
2525 Show {
2527 frontier: PathBuf,
2528 bridge_id: String,
2529 #[arg(long)]
2530 json: bool,
2531 },
2532 Confirm {
2537 frontier: PathBuf,
2538 bridge_id: String,
2539 #[arg(long)]
2542 reviewer: Option<String>,
2543 #[arg(long)]
2545 note: Option<String>,
2546 #[arg(long)]
2547 json: bool,
2548 },
2549 Refute {
2552 frontier: PathBuf,
2553 bridge_id: String,
2554 #[arg(long)]
2555 reviewer: Option<String>,
2556 #[arg(long)]
2557 note: Option<String>,
2558 #[arg(long)]
2559 json: bool,
2560 },
2561}
2562
2563#[derive(Subcommand)]
2564enum FederationAction {
2565 PeerAdd {
2569 frontier: PathBuf,
2570 id: String,
2572 #[arg(long)]
2574 url: String,
2575 #[arg(long)]
2577 pubkey: String,
2578 #[arg(long, default_value = "")]
2580 note: String,
2581 #[arg(long)]
2582 json: bool,
2583 },
2584 PeerList {
2586 frontier: PathBuf,
2587 #[arg(long)]
2588 json: bool,
2589 },
2590 PeerRemove {
2594 frontier: PathBuf,
2595 id: String,
2596 #[arg(long)]
2597 json: bool,
2598 },
2599 Sync {
2616 frontier: PathBuf,
2617 peer_id: String,
2619 #[arg(long)]
2621 url: Option<String>,
2622 #[arg(long)]
2626 via_hub: bool,
2627 #[arg(long)]
2630 vfr_id: Option<String>,
2631 #[arg(long)]
2638 allow_cross_vfr: bool,
2639 #[arg(long)]
2641 dry_run: bool,
2642 #[arg(long)]
2643 json: bool,
2644 },
2645 PushResolution {
2658 frontier: PathBuf,
2659 conflict_event_id: String,
2663 #[arg(long = "to")]
2665 to: String,
2666 #[arg(long)]
2670 key: Option<PathBuf>,
2671 #[arg(long)]
2674 vfr_id: Option<String>,
2675 #[arg(long)]
2676 json: bool,
2677 },
2678}
2679
2680#[derive(Subcommand)]
2681enum ReviewThreadCli {
2682 Create {
2686 target: String,
2688 #[arg(long)]
2689 frontier_id: String,
2690 #[arg(long)]
2691 out: PathBuf,
2692 #[arg(long)]
2693 json: bool,
2694 },
2695 Post {
2698 thread: PathBuf,
2701 #[arg(long)]
2702 author_actor_id: String,
2703 #[arg(long)]
2705 key: PathBuf,
2706 #[arg(long)]
2708 message: String,
2709 #[arg(long)]
2711 parent: Option<String>,
2712 #[arg(long)]
2713 json: bool,
2714 },
2715 Verify {
2718 thread: PathBuf,
2719 #[arg(long)]
2720 json: bool,
2721 },
2722}
2723
2724#[derive(Subcommand)]
2725enum HubSpecCli {
2726 Declare {
2728 #[arg(long)]
2729 hub_id: String,
2730 #[arg(long)]
2731 display_name: String,
2732 #[arg(long)]
2733 base_url: String,
2734 #[arg(long)]
2735 operator_pubkey_hex: String,
2736 #[arg(long)]
2737 substrate_version: String,
2738 #[arg(long)]
2739 contact: Option<String>,
2740 #[arg(long)]
2741 latest_checkpoint: Option<String>,
2742 #[arg(long)]
2743 out: Option<PathBuf>,
2744 #[arg(long)]
2745 json: bool,
2746 },
2747 Validate {
2750 spec: PathBuf,
2751 #[arg(long)]
2752 json: bool,
2753 },
2754}
2755
2756#[derive(Subcommand)]
2757enum LeanAction {
2758 AnchorAll {
2761 #[arg(long)]
2763 lean_dir: Option<PathBuf>,
2764 #[arg(long, default_value = "./theorems")]
2767 out: PathBuf,
2768 #[arg(long)]
2769 json: bool,
2770 },
2771 Anchor {
2773 id: u32,
2775 #[arg(long)]
2776 lean_dir: Option<PathBuf>,
2777 #[arg(long)]
2779 out: Option<PathBuf>,
2780 #[arg(long)]
2781 json: bool,
2782 },
2783 List {
2785 #[arg(long)]
2786 json: bool,
2787 },
2788 Keygen {
2792 #[arg(long)]
2793 key_out: PathBuf,
2794 #[arg(long)]
2795 pub_out: PathBuf,
2796 #[arg(long)]
2799 actor: String,
2800 },
2801 VerifyAll {
2806 #[arg(long, default_value = "./theorems")]
2809 anchors_dir: PathBuf,
2810 #[arg(long)]
2813 out_dir: Option<PathBuf>,
2814 #[arg(long)]
2818 build_log: PathBuf,
2819 #[arg(long)]
2821 key: PathBuf,
2822 #[arg(long)]
2824 actor: String,
2825 #[arg(long)]
2829 lean_toolchain: Option<String>,
2830 #[arg(long)]
2833 mathlib_revision: Option<String>,
2834 #[arg(long)]
2835 json: bool,
2836 },
2837 VerifyCheck {
2840 record: PathBuf,
2841 #[arg(long)]
2844 anchor: Option<PathBuf>,
2845 #[arg(long)]
2846 json: bool,
2847 },
2848}
2849
2850#[derive(Subcommand)]
2851enum DiffPackAction {
2852 Create {
2857 frontier: PathBuf,
2859 #[arg(long, value_delimiter = ',', required = true)]
2862 proposals: Vec<String>,
2863 #[arg(long)]
2865 summary: String,
2866 #[arg(long)]
2869 aggregate_kind: String,
2870 #[arg(long)]
2872 agent_run: Option<String>,
2873 #[arg(long)]
2875 parent_pack: Option<String>,
2876 #[arg(long)]
2879 key: Option<PathBuf>,
2880 #[arg(long)]
2882 out: PathBuf,
2883 #[arg(long)]
2884 json: bool,
2885 },
2886 Show {
2888 pack: PathBuf,
2889 #[arg(long)]
2890 json: bool,
2891 },
2892 Verify {
2895 pack: PathBuf,
2896 #[arg(long)]
2897 json: bool,
2898 },
2899 PromoteVerdicts {
2904 frontier: PathBuf,
2906 #[arg(long)]
2907 json: bool,
2908 },
2909 BackfillRelease {
2916 frontier: PathBuf,
2918 #[arg(long)]
2919 json: bool,
2920 },
2921 WitnessCheck {
2927 pack_id: String,
2929 #[arg(long, value_delimiter = ',', required = true)]
2931 hubs: Vec<String>,
2932 #[arg(long)]
2933 json: bool,
2934 },
2935}
2936
2937#[derive(Subcommand)]
2938enum ToolCliAction {
2939 Register {
2944 #[arg(long)]
2945 tool_name: String,
2946 #[arg(long)]
2947 tool_version: String,
2948 #[arg(long)]
2951 provider: String,
2952 #[arg(long)]
2955 calling_convention: String,
2956 #[arg(long)]
2958 input_schema: PathBuf,
2959 #[arg(long)]
2961 output_schema: PathBuf,
2962 #[arg(long)]
2964 evidence_url: Option<String>,
2965 #[arg(long, value_delimiter = ',')]
2968 cited_in_findings: Vec<String>,
2969 #[arg(long)]
2971 out: PathBuf,
2972 #[arg(long)]
2973 json: bool,
2974 },
2975 Show {
2977 descriptor: PathBuf,
2978 #[arg(long)]
2979 json: bool,
2980 },
2981 Verify {
2983 descriptor: PathBuf,
2984 #[arg(long)]
2985 json: bool,
2986 },
2987}
2988
2989#[derive(Subcommand)]
2990enum EvalCliAction {
2991 Record {
2995 #[arg(long)]
2997 target_kind: String,
2998 #[arg(long)]
3000 target_id: String,
3001 #[arg(long)]
3003 evaluation_kind: String,
3004 #[arg(long)]
3006 outcome: String,
3007 #[arg(long)]
3009 evaluator: String,
3010 #[arg(long, value_delimiter = ',')]
3012 evidence_refs: Vec<String>,
3013 #[arg(long)]
3015 benchmark_id: Option<String>,
3016 #[arg(long)]
3018 score: Option<f64>,
3019 #[arg(long)]
3021 notes: Option<String>,
3022 #[arg(long)]
3024 key: Option<PathBuf>,
3025 #[arg(long)]
3027 out: PathBuf,
3028 #[arg(long)]
3029 json: bool,
3030 },
3031 Show {
3033 record: PathBuf,
3034 #[arg(long)]
3035 json: bool,
3036 },
3037 Verify {
3040 record: PathBuf,
3041 #[arg(long)]
3042 json: bool,
3043 },
3044}
3045
3046#[derive(Subcommand)]
3047enum ConflictCliAction {
3048 Detect {
3053 frontier: PathBuf,
3055 #[arg(long)]
3056 json: bool,
3057 },
3058 Resolve {
3063 frontier: PathBuf,
3065 #[arg(long, value_delimiter = ',', required = true)]
3067 verdicts: Vec<String>,
3068 #[arg(long, value_delimiter = ',', required = true)]
3070 shared_members: Vec<String>,
3071 #[arg(long)]
3073 mode: String,
3074 #[arg(long)]
3076 resolver: String,
3077 #[arg(long)]
3079 winning: Option<String>,
3080 #[arg(long)]
3082 rationale: Option<String>,
3083 #[arg(long)]
3085 key: Option<PathBuf>,
3086 #[arg(long)]
3087 json: bool,
3088 },
3089 List {
3091 frontier: PathBuf,
3092 #[arg(long)]
3093 json: bool,
3094 },
3095}
3096
3097#[derive(Subcommand)]
3098enum FrontierAction {
3099 New {
3106 path: PathBuf,
3108 #[arg(long)]
3110 name: String,
3111 #[arg(long, default_value = "")]
3113 description: String,
3114 #[arg(long)]
3116 force: bool,
3117 #[arg(long)]
3118 json: bool,
3119 },
3120 Materialize {
3122 frontier: PathBuf,
3124 #[arg(long)]
3125 json: bool,
3126 },
3127 AddDep {
3131 frontier: PathBuf,
3133 vfr_id: String,
3135 #[arg(long)]
3138 locator: String,
3139 #[arg(long)]
3142 snapshot: String,
3143 #[arg(long)]
3145 name: Option<String>,
3146 #[arg(long)]
3147 json: bool,
3148 },
3149 ListDeps {
3151 frontier: PathBuf,
3152 #[arg(long)]
3153 json: bool,
3154 },
3155 RemoveDep {
3158 frontier: PathBuf,
3159 vfr_id: String,
3160 #[arg(long)]
3161 json: bool,
3162 },
3163 RefreshDeps {
3170 frontier: PathBuf,
3171 #[arg(long, default_value = "https://vela-hub.fly.dev")]
3173 from: String,
3174 #[arg(long)]
3176 dry_run: bool,
3177 #[arg(long)]
3178 json: bool,
3179 },
3180 Diff {
3192 frontier: PathBuf,
3194 #[arg(long)]
3197 since: Option<String>,
3198 #[arg(long)]
3201 week: Option<String>,
3202 #[arg(long)]
3204 json: bool,
3205 },
3206 Release {
3212 frontier: PathBuf,
3214 #[arg(long)]
3217 name: String,
3218 #[arg(long)]
3220 notes: Option<String>,
3221 #[arg(long)]
3225 previous: Option<String>,
3226 #[arg(long)]
3227 json: bool,
3228 },
3229 Releases {
3231 frontier: PathBuf,
3233 #[arg(long)]
3234 json: bool,
3235 },
3236}
3237
3238#[derive(Subcommand)]
3239enum RepoAction {
3240 Status {
3242 frontier: PathBuf,
3244 #[arg(long)]
3246 json: bool,
3247 },
3248 Doctor {
3250 frontier: PathBuf,
3252 #[arg(long)]
3254 json: bool,
3255 },
3256}
3257
3258#[derive(Subcommand)]
3259enum QueueAction {
3260 List {
3262 #[arg(long)]
3263 queue_file: Option<PathBuf>,
3264 #[arg(long)]
3265 json: bool,
3266 },
3267 Sign {
3270 #[arg(long)]
3272 actor: String,
3273 #[arg(long)]
3275 key: PathBuf,
3276 #[arg(long)]
3278 queue_file: Option<PathBuf>,
3279 #[arg(long, alias = "all")]
3285 yes_to_all: bool,
3286 #[arg(long)]
3287 json: bool,
3288 },
3289 Clear {
3291 #[arg(long)]
3292 queue_file: Option<PathBuf>,
3293 #[arg(long)]
3294 json: bool,
3295 },
3296}
3297
3298#[derive(Subcommand)]
3299enum RegistryAction {
3300 List {
3302 #[arg(long)]
3304 from: Option<String>,
3305 #[arg(long)]
3306 json: bool,
3307 },
3308 Publish {
3310 frontier: PathBuf,
3312 #[arg(long)]
3314 owner: String,
3315 #[arg(long)]
3317 key: PathBuf,
3318 #[arg(long)]
3325 locator: Option<String>,
3326 #[arg(long)]
3328 to: Option<String>,
3329 #[arg(long)]
3334 license: Option<String>,
3335 #[arg(long)]
3336 json: bool,
3337 },
3338 DependsOn {
3345 vfr_id: String,
3347 #[arg(long, default_value = "https://vela-hub.fly.dev")]
3349 from: String,
3350 #[arg(long)]
3351 json: bool,
3352 },
3353 Mirror {
3361 vfr_id: String,
3363 #[arg(long)]
3365 from: String,
3366 #[arg(long)]
3368 to: String,
3369 #[arg(long)]
3370 json: bool,
3371 },
3372 WitnessCheck {
3380 vfr_id: String,
3382 #[arg(long, value_delimiter = ',')]
3387 hubs: Vec<String>,
3388 #[arg(long)]
3389 json: bool,
3390 },
3391 Governance {
3398 #[command(subcommand)]
3399 action: GovernanceAction,
3400 },
3401 HubFederation {
3410 #[command(subcommand)]
3411 action: HubFederationAction,
3412 },
3413 Checkpoint {
3423 #[command(subcommand)]
3424 action: CheckpointAction,
3425 },
3426 VerifyAll {
3432 #[arg(long)]
3435 from: Option<PathBuf>,
3436 #[arg(long)]
3437 json: bool,
3438 },
3439 VerifyChain {
3447 frontier: PathBuf,
3450 #[arg(long)]
3454 artifacts: PathBuf,
3455 #[arg(long)]
3456 json: bool,
3457 },
3458 OwnerRotateGoverned {
3472 #[command(subcommand)]
3473 action: OwnerRotateGovernedAction,
3474 },
3475 OwnerRotate {
3485 frontier: PathBuf,
3487 #[arg(long)]
3489 current_owner: String,
3490 #[arg(long)]
3492 new_owner: String,
3493 #[arg(long)]
3495 new_key: PathBuf,
3496 #[arg(long)]
3499 reason: String,
3500 #[arg(long)]
3505 locator: Option<String>,
3506 #[arg(long)]
3509 to: Option<String>,
3510 #[arg(long)]
3511 json: bool,
3512 },
3513 Pull {
3515 vfr_id: String,
3517 #[arg(long)]
3519 from: Option<String>,
3520 #[arg(long)]
3524 out: PathBuf,
3525 #[arg(long)]
3528 transitive: bool,
3529 #[arg(long, default_value = "4")]
3532 depth: usize,
3533 #[arg(long)]
3534 json: bool,
3535 },
3536}
3537
3538#[derive(Subcommand)]
3539enum GovernanceAction {
3540 Init {
3544 frontier: PathBuf,
3546 #[arg(long)]
3548 threshold: u32,
3549 #[arg(long, value_delimiter = ',')]
3551 eligible: Vec<String>,
3552 #[arg(long)]
3558 bootstrap: bool,
3559 #[arg(long)]
3562 owner_epoch: Option<u64>,
3563 #[arg(long)]
3567 current_owner_counts: bool,
3568 #[arg(long, default_value = "168")]
3570 attestation_ttl_hours: u32,
3571 #[arg(long)]
3574 out: Option<PathBuf>,
3575 #[arg(long)]
3576 json: bool,
3577 },
3578 Show {
3580 policy: PathBuf,
3582 #[arg(long)]
3583 json: bool,
3584 },
3585 Validate {
3588 policy: PathBuf,
3590 #[arg(long)]
3591 json: bool,
3592 },
3593}
3594
3595#[derive(Subcommand)]
3596enum SearchAction {
3597 Build {
3599 #[arg(required = true)]
3601 frontiers: Vec<PathBuf>,
3602 #[arg(long)]
3604 out: PathBuf,
3605 #[arg(long)]
3609 include_bootstrap: bool,
3610 #[arg(long)]
3613 include_broken: bool,
3614 #[arg(long)]
3615 json: bool,
3616 },
3617 Query {
3619 #[arg(default_value = "")]
3622 query: String,
3623 #[arg(long)]
3626 index: Option<PathBuf>,
3627 #[arg(long)]
3629 kind: Option<String>,
3630 #[arg(long)]
3632 entity: Option<String>,
3633 #[arg(long)]
3636 status: Option<String>,
3637 #[arg(long)]
3639 frontier_id: Option<String>,
3640 #[arg(long)]
3642 source_id: Option<String>,
3643 #[arg(long)]
3647 chain_status: Option<String>,
3648 #[arg(long)]
3650 limit: Option<usize>,
3651 #[arg(long)]
3652 json: bool,
3653 },
3654}
3655
3656#[derive(Subcommand)]
3657enum HubFederationAction {
3658 Status {
3668 #[arg(long = "source", value_delimiter = ',')]
3669 sources: Vec<String>,
3670 #[arg(long)]
3671 json: bool,
3672 },
3673}
3674
3675#[derive(Subcommand)]
3676enum CheckpointAction {
3677 Create {
3679 #[arg(long)]
3681 from: PathBuf,
3682 #[arg(long)]
3684 hub_id: String,
3685 #[arg(long)]
3687 sequence: u64,
3688 #[arg(long)]
3690 previous: Option<String>,
3691 #[arg(long)]
3693 key: PathBuf,
3694 #[arg(long)]
3696 out: PathBuf,
3697 #[arg(long)]
3698 json: bool,
3699 },
3700 Verify {
3703 checkpoint: PathBuf,
3705 #[arg(long)]
3707 registry: PathBuf,
3708 #[arg(long)]
3709 json: bool,
3710 },
3711}
3712
3713#[derive(Subcommand)]
3714enum OwnerRotateGovernedAction {
3715 Propose {
3722 frontier: PathBuf,
3723 #[arg(long)]
3724 old_owner: String,
3725 #[arg(long)]
3726 new_owner: String,
3727 #[arg(long)]
3731 new_pubkey_hex: String,
3732 #[arg(long)]
3733 target_epoch: u64,
3734 #[arg(long)]
3735 previous_entry_hash: String,
3736 #[arg(long)]
3737 policy: PathBuf,
3738 #[arg(long)]
3739 reason: String,
3740 #[arg(long, default_value = "168")]
3741 ttl_hours: u32,
3742 #[arg(long)]
3743 out: PathBuf,
3744 #[arg(long)]
3745 json: bool,
3746 },
3747 Attest {
3752 #[arg(long)]
3753 proposal: PathBuf,
3754 #[arg(long)]
3755 attester_id: String,
3756 #[arg(long)]
3757 key: PathBuf,
3758 #[arg(long)]
3759 bundle: PathBuf,
3760 #[arg(long)]
3761 json: bool,
3762 },
3763 Apply {
3768 frontier: PathBuf,
3769 #[arg(long)]
3770 proposal: PathBuf,
3771 #[arg(long)]
3772 bundle: PathBuf,
3773 #[arg(long)]
3774 policy: PathBuf,
3775 #[arg(long)]
3778 new_key: PathBuf,
3779 #[arg(long)]
3780 locator: Option<String>,
3781 #[arg(long)]
3782 to: Option<String>,
3783 #[arg(long)]
3784 json: bool,
3785 },
3786}
3787
3788#[derive(Subcommand)]
3789enum GapsAction {
3790 Rank {
3792 frontier: PathBuf,
3793 #[arg(long, default_value = "10")]
3794 top: usize,
3795 #[arg(long)]
3796 domain: Option<String>,
3797 #[arg(long)]
3798 json: bool,
3799 },
3800}
3801
3802#[derive(Subcommand)]
3803enum LinkAction {
3804 Add {
3809 frontier: PathBuf,
3811 #[arg(long)]
3813 from: String,
3814 #[arg(long)]
3816 to: String,
3817 #[arg(long, default_value = "supports")]
3819 r#type: String,
3820 #[arg(long, default_value = "")]
3822 note: String,
3823 #[arg(long, default_value = "reviewer")]
3825 inferred_by: String,
3826 #[arg(long)]
3835 no_check_target: bool,
3836 #[arg(long)]
3837 json: bool,
3838 },
3839}
3840
3841#[derive(Subcommand)]
3842enum EntityAction {
3843 Resolve {
3850 frontier: PathBuf,
3851 #[arg(long)]
3853 force: bool,
3854 #[arg(long)]
3855 json: bool,
3856 },
3857 List {
3859 #[arg(long)]
3860 json: bool,
3861 },
3862}
3863
3864#[derive(Subcommand)]
3865enum FindingCommands {
3866 Add {
3868 frontier: PathBuf,
3870 #[arg(long)]
3872 assertion: String,
3873 #[arg(long, default_value = "mechanism")]
3875 r#type: String,
3876 #[arg(long, default_value = "manual finding")]
3878 source: String,
3879 #[arg(long, default_value = "expert_assertion")]
3881 source_type: String,
3882 #[arg(long)]
3884 author: String,
3885 #[arg(long, default_value = "0.3")]
3887 confidence: f64,
3888 #[arg(long, default_value = "theoretical")]
3890 evidence_type: String,
3891 #[arg(long, default_value = "")]
3893 entities: String,
3894 #[arg(long)]
3896 entities_reviewed: bool,
3897 #[arg(long)]
3899 evidence_span: Vec<String>,
3900 #[arg(long)]
3902 gap: bool,
3903 #[arg(long)]
3905 negative_space: bool,
3906 #[arg(long)]
3908 doi: Option<String>,
3909 #[arg(long)]
3911 pmid: Option<String>,
3912 #[arg(long)]
3914 year: Option<i32>,
3915 #[arg(long)]
3917 journal: Option<String>,
3918 #[arg(long)]
3920 url: Option<String>,
3921 #[arg(long)]
3923 source_authors: Option<String>,
3924 #[arg(long)]
3926 conditions_text: Option<String>,
3927 #[arg(long)]
3929 species: Option<String>,
3930 #[arg(long)]
3932 in_vivo: bool,
3933 #[arg(long)]
3935 in_vitro: bool,
3936 #[arg(long)]
3938 human_data: bool,
3939 #[arg(long)]
3941 clinical_trial: bool,
3942 #[arg(long)]
3944 json: bool,
3945 #[arg(long)]
3947 apply: bool,
3948 },
3949 Supersede {
3956 frontier: PathBuf,
3958 old_id: String,
3960 #[arg(long)]
3962 assertion: String,
3963 #[arg(long, default_value = "mechanism")]
3965 r#type: String,
3966 #[arg(long, default_value = "manual finding")]
3968 source: String,
3969 #[arg(long, default_value = "expert_assertion")]
3971 source_type: String,
3972 #[arg(long)]
3974 author: String,
3975 #[arg(long)]
3977 reason: String,
3978 #[arg(long, default_value = "0.5")]
3980 confidence: f64,
3981 #[arg(long, default_value = "experimental")]
3983 evidence_type: String,
3984 #[arg(long, default_value = "")]
3986 entities: String,
3987 #[arg(long)]
3989 doi: Option<String>,
3990 #[arg(long)]
3992 pmid: Option<String>,
3993 #[arg(long)]
3995 year: Option<i32>,
3996 #[arg(long)]
3998 journal: Option<String>,
3999 #[arg(long)]
4001 url: Option<String>,
4002 #[arg(long)]
4004 source_authors: Option<String>,
4005 #[arg(long)]
4007 conditions_text: Option<String>,
4008 #[arg(long)]
4010 species: Option<String>,
4011 #[arg(long)]
4012 in_vivo: bool,
4013 #[arg(long)]
4014 in_vitro: bool,
4015 #[arg(long)]
4016 human_data: bool,
4017 #[arg(long)]
4018 clinical_trial: bool,
4019 #[arg(long)]
4020 json: bool,
4021 #[arg(long)]
4023 apply: bool,
4024 },
4025 CausalSet {
4031 frontier: PathBuf,
4033 finding_id: String,
4035 #[arg(long)]
4037 claim: String,
4038 #[arg(long)]
4041 grade: Option<String>,
4042 #[arg(long)]
4045 actor: String,
4046 #[arg(long)]
4049 reason: String,
4050 #[arg(long)]
4051 json: bool,
4052 },
4053}
4054
4055#[derive(Subcommand)]
4056enum ProposalAction {
4057 List {
4059 frontier: PathBuf,
4060 #[arg(long)]
4061 status: Option<String>,
4062 #[arg(long)]
4063 json: bool,
4064 },
4065 Show {
4067 frontier: PathBuf,
4068 proposal_id: String,
4069 #[arg(long)]
4070 json: bool,
4071 },
4072 Preview {
4074 frontier: PathBuf,
4075 proposal_id: String,
4076 #[arg(long, default_value = "reviewer:preview")]
4077 reviewer: String,
4078 #[arg(long)]
4079 json: bool,
4080 },
4081 Import {
4083 frontier: PathBuf,
4084 source: PathBuf,
4085 #[arg(long)]
4086 json: bool,
4087 },
4088 Validate {
4090 source: PathBuf,
4091 #[arg(long)]
4092 json: bool,
4093 },
4094 Export {
4096 frontier: PathBuf,
4097 output: PathBuf,
4098 #[arg(long)]
4099 status: Option<String>,
4100 #[arg(long)]
4101 json: bool,
4102 },
4103 Accept {
4105 frontier: PathBuf,
4106 proposal_id: String,
4107 #[arg(long)]
4108 reviewer: String,
4109 #[arg(long)]
4110 reason: String,
4111 #[arg(long)]
4112 json: bool,
4113 },
4114 Reject {
4116 frontier: PathBuf,
4117 proposal_id: String,
4118 #[arg(long)]
4119 reviewer: String,
4120 #[arg(long)]
4121 reason: String,
4122 #[arg(long)]
4123 json: bool,
4124 },
4125}
4126
4127#[derive(Subcommand)]
4128enum SourceAdapterAction {
4129 Run {
4131 frontier: PathBuf,
4133 adapter: String,
4135 #[arg(long)]
4137 actor: String,
4138 #[arg(long = "entry")]
4140 entries: Vec<String>,
4141 #[arg(long)]
4143 priority: Option<String>,
4144 #[arg(long)]
4146 include_excluded: bool,
4147 #[arg(long)]
4149 allow_partial: bool,
4150 #[arg(long)]
4152 dry_run: bool,
4153 #[arg(long)]
4155 input_dir: Option<PathBuf>,
4156 #[arg(long)]
4158 apply_artifacts: bool,
4159 #[arg(long)]
4161 json: bool,
4162 },
4163}
4164
4165#[derive(Subcommand)]
4166enum RuntimeAdapterAction {
4167 Run {
4169 frontier: PathBuf,
4171 adapter: String,
4173 #[arg(long)]
4175 input: PathBuf,
4176 #[arg(long)]
4178 actor: String,
4179 #[arg(long)]
4181 dry_run: bool,
4182 #[arg(long)]
4184 apply_artifacts: bool,
4185 #[arg(long)]
4187 json: bool,
4188 },
4189}
4190
4191#[derive(Subcommand)]
4192enum BridgeKitAction {
4193 Validate {
4195 source: PathBuf,
4197 #[arg(long)]
4199 json: bool,
4200 },
4201 VerifyProvenance {
4208 packet: PathBuf,
4210 #[arg(long)]
4212 json: bool,
4213 #[arg(long = "cross-check")]
4220 cross_check: bool,
4221 },
4222}
4223
4224pub async fn run_command() {
4225 dotenvy::dotenv().ok();
4226
4227 match Cli::parse().command {
4228 Commands::Scout {
4229 folder,
4230 frontier,
4231 backend,
4232 dry_run,
4233 json,
4234 } => {
4235 cmd_scout(&folder, &frontier, backend.as_deref(), dry_run, json).await;
4236 }
4237 Commands::CompileNotes {
4238 vault,
4239 frontier,
4240 backend,
4241 max_files,
4242 max_items_per_category,
4243 dry_run,
4244 json,
4245 } => {
4246 cmd_compile_notes(
4247 &vault,
4248 &frontier,
4249 backend.as_deref(),
4250 max_files,
4251 max_items_per_category,
4252 dry_run,
4253 json,
4254 )
4255 .await;
4256 }
4257 Commands::CompileCode {
4258 root,
4259 frontier,
4260 backend,
4261 max_files,
4262 dry_run,
4263 json,
4264 } => {
4265 cmd_compile_code(
4266 &root,
4267 &frontier,
4268 backend.as_deref(),
4269 max_files,
4270 dry_run,
4271 json,
4272 )
4273 .await;
4274 }
4275 Commands::CompileData {
4276 root,
4277 frontier,
4278 backend,
4279 sample_rows,
4280 dry_run,
4281 json,
4282 } => {
4283 cmd_compile_data(
4284 &root,
4285 &frontier,
4286 backend.as_deref(),
4287 sample_rows,
4288 dry_run,
4289 json,
4290 )
4291 .await;
4292 }
4293 Commands::ReviewPending {
4294 frontier,
4295 backend,
4296 max_proposals,
4297 batch_size,
4298 dry_run,
4299 json,
4300 } => {
4301 cmd_review_pending(
4302 &frontier,
4303 backend.as_deref(),
4304 max_proposals,
4305 batch_size,
4306 dry_run,
4307 json,
4308 )
4309 .await;
4310 }
4311 Commands::FindTensions {
4312 frontier,
4313 backend,
4314 max_findings,
4315 dry_run,
4316 json,
4317 } => {
4318 cmd_find_tensions(&frontier, backend.as_deref(), max_findings, dry_run, json).await;
4319 }
4320 Commands::PlanExperiments {
4321 frontier,
4322 backend,
4323 max_findings,
4324 dry_run,
4325 json,
4326 } => {
4327 cmd_plan_experiments(&frontier, backend.as_deref(), max_findings, dry_run, json).await;
4328 }
4329 Commands::Check {
4330 source,
4331 schema,
4332 stats,
4333 conformance,
4334 conformance_dir,
4335 all,
4336 schema_only,
4337 strict,
4338 fix,
4339 json,
4340 } => cmd_check(
4341 source.as_deref(),
4342 schema,
4343 stats,
4344 conformance,
4345 &conformance_dir,
4346 all,
4347 schema_only,
4348 strict,
4349 fix,
4350 json,
4351 ),
4352 Commands::Integrity { frontier, json } => cmd_integrity(&frontier, json),
4353 Commands::Impact {
4354 frontier,
4355 finding_id,
4356 depth,
4357 json,
4358 } => cmd_impact(&frontier, &finding_id, depth, json),
4359 Commands::Discord {
4360 frontier,
4361 json,
4362 kind,
4363 } => cmd_discord(&frontier, json, kind.as_deref()),
4364 Commands::Normalize {
4365 source,
4366 out,
4367 write,
4368 dry_run,
4369 rewrite_ids,
4370 id_map,
4371 resync_provenance,
4372 json,
4373 } => cmd_normalize(
4374 &source,
4375 out.as_deref(),
4376 write,
4377 dry_run,
4378 rewrite_ids,
4379 id_map.as_deref(),
4380 resync_provenance,
4381 json,
4382 ),
4383 Commands::Proof {
4384 frontier,
4385 out,
4386 template,
4387 gold,
4388 record_proof_state,
4389 json,
4390 } => cmd_proof(
4391 &frontier,
4392 &out,
4393 &template,
4394 gold.as_deref(),
4395 record_proof_state,
4396 json,
4397 ),
4398 Commands::Repo { action } => cmd_repo(action),
4399 Commands::Serve {
4400 frontier,
4401 frontiers,
4402 backend,
4403 http,
4404 setup,
4405 check_tools,
4406 json,
4407 workbench,
4408 } => {
4409 if setup {
4410 cmd_mcp_setup(frontier.as_deref(), frontiers.as_deref());
4411 } else if check_tools {
4412 let source =
4413 serve::ProjectSource::from_args(frontier.as_deref(), frontiers.as_deref());
4414 match serve::check_tools(source) {
4415 Ok(report) => {
4416 if json {
4417 println!(
4418 "{}",
4419 serde_json::to_string_pretty(&report)
4420 .expect("failed to serialize tool check report")
4421 );
4422 } else {
4423 print_tool_check_report(&report);
4424 }
4425 }
4426 Err(e) => fail(&format!("Tool check failed: {e}")),
4427 }
4428 } else {
4429 let source =
4430 serve::ProjectSource::from_args(frontier.as_deref(), frontiers.as_deref());
4431 let resolved_port = if workbench {
4433 Some(http.unwrap_or(3848))
4434 } else {
4435 http
4436 };
4437 if let Some(port) = resolved_port {
4438 serve::run_http(source, backend.as_deref(), port, workbench).await;
4439 } else {
4440 serve::run(source, backend.as_deref()).await;
4441 }
4442 }
4443 }
4444 Commands::Status { frontier, json } => cmd_status(&frontier, json),
4445 Commands::Log {
4446 frontier,
4447 limit,
4448 kind,
4449 json,
4450 } => cmd_log(&frontier, limit, kind.as_deref(), json),
4451 Commands::Inbox {
4452 frontier,
4453 kind,
4454 limit,
4455 json,
4456 } => cmd_inbox(&frontier, kind.as_deref(), limit, json),
4457 Commands::Ask {
4458 frontier,
4459 question,
4460 json,
4461 } => cmd_ask(&frontier, &question.join(" "), json),
4462 Commands::Stats { frontier, json } => {
4463 if json {
4464 print_stats_json(&frontier);
4465 } else {
4466 cmd_stats(&frontier);
4467 }
4468 }
4469 Commands::Search {
4470 source,
4471 query,
4472 entity,
4473 r#type,
4474 all,
4475 limit,
4476 json,
4477 } => cmd_search(
4478 source.as_deref(),
4479 &query,
4480 entity.as_deref(),
4481 r#type.as_deref(),
4482 all.as_deref(),
4483 limit,
4484 json,
4485 ),
4486 Commands::Tensions {
4487 source,
4488 both_high,
4489 cross_domain,
4490 top,
4491 json,
4492 } => cmd_tensions(&source, both_high, cross_domain, top, json),
4493 Commands::Gaps { action } => cmd_gaps(action),
4494 Commands::Bridge {
4495 inputs,
4496 novelty,
4497 top,
4498 } => cmd_bridge(&inputs, novelty, top).await,
4499 Commands::Export {
4500 frontier,
4501 format,
4502 output,
4503 } => export::run(&frontier, &format, output.as_deref()),
4504 Commands::Packet { action } => cmd_packet(action),
4505 Commands::Verify { path, json } => cmd_verify(&path, json),
4506 Commands::Bench {
4507 frontier,
4508 gold,
4509 candidate,
4510 sources,
4511 threshold,
4512 report,
4513 entity_gold,
4514 link_gold,
4515 suite,
4516 suite_ready,
4517 min_f1,
4518 min_precision,
4519 min_recall,
4520 no_thresholds,
4521 json,
4522 } => {
4523 if let Some(cand) = candidate.clone() {
4528 let Some(g) = gold.clone() else {
4529 eprintln!(
4530 "{} `vela bench --candidate <…>` requires `--gold <…>`",
4531 style::err_prefix()
4532 );
4533 std::process::exit(2);
4534 };
4535 cmd_agent_bench(
4536 &g,
4537 &cand,
4538 sources.as_deref(),
4539 threshold,
4540 report.as_deref(),
4541 json,
4542 );
4543 } else {
4544 cmd_bench(BenchArgs {
4545 frontier,
4546 gold,
4547 entity_gold,
4548 link_gold,
4549 suite,
4550 suite_ready,
4551 min_f1,
4552 min_precision,
4553 min_recall,
4554 no_thresholds,
4555 json,
4556 });
4557 }
4558 }
4559 Commands::Conformance { dir } => {
4560 let _ = conformance::run(&dir);
4561 }
4562 Commands::Version => println!("vela 0.36.0"),
4563 Commands::Sign { action } => cmd_sign(action),
4564 Commands::Actor { action } => cmd_actor(action),
4565 Commands::Federation { action } => cmd_federation(action),
4566 Commands::Causal { action } => cmd_causal(action),
4567 Commands::Frontier { action } => cmd_frontier(action),
4568 Commands::Queue { action } => cmd_queue(action),
4569 Commands::Registry { action } => cmd_registry(action),
4570 Commands::Init {
4571 path,
4572 name,
4573 template,
4574 no_git,
4575 json,
4576 } => cmd_init(&path, &name, &template, !no_git, json),
4577 Commands::Quickstart {
4578 path,
4579 name,
4580 reviewer,
4581 assertion,
4582 keys_out,
4583 json,
4584 } => cmd_quickstart(
4585 &path,
4586 &name,
4587 &reviewer,
4588 assertion.as_deref(),
4589 keys_out.as_deref(),
4590 json,
4591 ),
4592 Commands::Agent { action } => cmd_agent(action),
4593 Commands::Lock { path, check, json } => cmd_lock(&path, check, json),
4594 Commands::Doc { path, out, json } => cmd_doc(&path, out.as_deref(), json),
4595 Commands::Import { frontier, into } => cmd_import(&frontier, into.as_deref()),
4596 Commands::Diff {
4597 target,
4598 frontier_b,
4599 frontier,
4600 reviewer,
4601 from,
4602 json,
4603 quiet,
4604 } => {
4605 if target.starts_with("vpr_") {
4610 let frontier_root = frontier
4611 .clone()
4612 .or_else(|| frontier_b.clone().map(std::path::PathBuf::from))
4613 .unwrap_or_else(|| std::path::PathBuf::from("."));
4614 let preview = proposals::preview_at_path(&frontier_root, &target, &reviewer)
4615 .unwrap_or_else(|e| fail_return(&e));
4616 let payload = json!({
4617 "ok": true,
4618 "command": "diff.proposal",
4619 "frontier": frontier_root.display().to_string(),
4620 "proposal_id": target,
4621 "preview": preview,
4622 });
4623 if json {
4624 println!(
4625 "{}",
4626 serde_json::to_string_pretty(&payload)
4627 .expect("failed to serialize diff preview")
4628 );
4629 } else {
4630 println!("vela diff · proposal preview");
4631 println!(" proposal: {}", target);
4632 println!(" kind: {}", preview.kind);
4633 println!(
4634 " findings: {} -> {}",
4635 preview.findings_before, preview.findings_after
4636 );
4637 println!(
4638 " artifacts: {} -> {}",
4639 preview.artifacts_before, preview.artifacts_after
4640 );
4641 println!(
4642 " events: {} -> {}",
4643 preview.events_before, preview.events_after
4644 );
4645 if !preview.changed_findings.is_empty() {
4646 println!(
4647 " findings changed: {}",
4648 preview.changed_findings.join(", ")
4649 );
4650 }
4651 }
4652 } else {
4653 let b_str = frontier_b.unwrap_or_else(|| {
4654 fail_return(
4655 "diff: two-frontier mode needs a second positional (filesystem path or `vfr_*` id); for proposal preview pass a `vpr_*` id",
4656 )
4657 });
4658 let _tmp = if target.starts_with("vfr_") || b_str.starts_with("vfr_") {
4664 Some(
4665 tempfile::Builder::new()
4666 .prefix("vela-diff-")
4667 .tempdir()
4668 .unwrap_or_else(|e| {
4669 fail_return(&format!("tempdir for vfr resolve: {e}"))
4670 }),
4671 )
4672 } else {
4673 None
4674 };
4675 let resolve_side = |side: &str, slot: &str| -> std::path::PathBuf {
4676 if side.starts_with("vfr_") {
4677 let tmp = _tmp.as_ref().expect("tempdir initialized above");
4678 let dest = tmp.path().join(format!("{slot}-{side}.json"));
4679 resolve_vfr_to_path(side, from.as_deref(), &dest)
4680 .unwrap_or_else(|e| fail_return(&e));
4681 dest
4682 } else {
4683 std::path::PathBuf::from(side)
4684 }
4685 };
4686 let frontier_a = resolve_side(&target, "a");
4687 let frontier_b_path = resolve_side(&b_str, "b");
4688 diff::run(&frontier_a, &frontier_b_path, json, quiet);
4689 }
4690 }
4691 Commands::Proposals { action } => cmd_proposals(action),
4692 Commands::SearchIndex { action } => cmd_search_index(action).await,
4693 Commands::Citation {
4694 target,
4695 frontier,
4696 format,
4697 locator,
4698 out,
4699 json,
4700 } => cmd_citation(target, frontier, format, locator, out, json),
4701 Commands::Credit {
4702 frontier,
4703 out,
4704 json,
4705 } => cmd_credit(frontier, out, json),
4706 Commands::Handle { handle, site, json } => cmd_handle_resolve(handle, site, json),
4707 Commands::Lean { action } => cmd_lean(action),
4708 Commands::DiffPack { action } => cmd_diff_pack(action),
4709 Commands::Tool { action } => cmd_tool(action),
4710 Commands::Eval { action } => cmd_eval(action),
4711 Commands::Conflict { action } => cmd_conflict(action),
4712 Commands::Hub { action } => cmd_hub_spec(action),
4713 Commands::ReviewThread { action } => cmd_review_thread(action),
4714 Commands::Preprint {
4715 frontier,
4716 released_at,
4717 out,
4718 json,
4719 } => cmd_preprint(frontier, released_at, out, json),
4720 Commands::Crossref {
4721 frontier,
4722 release,
4723 member,
4724 prefix,
4725 depositor_name,
4726 depositor_email,
4727 resource_url,
4728 title,
4729 description,
4730 license,
4731 xml,
4732 out,
4733 json,
4734 } => cmd_crossref(
4735 frontier,
4736 release,
4737 member,
4738 prefix,
4739 depositor_name,
4740 depositor_email,
4741 resource_url,
4742 title,
4743 description,
4744 license,
4745 xml,
4746 out,
4747 json,
4748 ),
4749 Commands::ArtifactToState {
4750 frontier,
4751 packet,
4752 actor,
4753 apply_artifacts,
4754 json,
4755 } => cmd_artifact_to_state(&frontier, &packet, &actor, apply_artifacts, json),
4756 Commands::BridgeKit { action } => cmd_bridge_kit(action).await,
4757 Commands::SourceAdapter { action } => cmd_source_adapter(action).await,
4758 Commands::RuntimeAdapter { action } => cmd_runtime_adapter(action),
4759 Commands::Link { action } => cmd_link(action),
4760 Commands::Workbench {
4761 path,
4762 port,
4763 no_open,
4764 } => {
4765 if let Err(e) = crate::workbench::run(path, port, !no_open).await {
4766 fail(&e);
4767 }
4768 }
4769 Commands::Bridges { action } => cmd_bridges(action),
4770 Commands::Entity { action } => cmd_entity(action),
4771 Commands::Finding { command } => match command {
4772 FindingCommands::Add {
4773 frontier,
4774 assertion,
4775 r#type,
4776 source,
4777 source_type,
4778 author,
4779 confidence,
4780 evidence_type,
4781 entities,
4782 entities_reviewed,
4783 evidence_span,
4784 gap,
4785 negative_space,
4786 doi,
4787 pmid,
4788 year,
4789 journal,
4790 url,
4791 source_authors,
4792 conditions_text,
4793 species,
4794 in_vivo,
4795 in_vitro,
4796 human_data,
4797 clinical_trial,
4798 json,
4799 apply,
4800 } => {
4801 validate_enum_arg("--type", &r#type, bundle::VALID_ASSERTION_TYPES);
4802 validate_enum_arg(
4803 "--evidence-type",
4804 &evidence_type,
4805 bundle::VALID_EVIDENCE_TYPES,
4806 );
4807 validate_enum_arg(
4808 "--source-type",
4809 &source_type,
4810 bundle::VALID_PROVENANCE_SOURCE_TYPES,
4811 );
4812 let parsed_entities = parse_entities(&entities);
4813 let parsed_evidence_spans = parse_evidence_spans(&evidence_span);
4814 for (name, etype) in &parsed_entities {
4815 if !bundle::VALID_ENTITY_TYPES.contains(&etype.as_str()) {
4816 fail(&format!(
4817 "invalid entity type '{}' for '{}'. Valid: {}",
4818 etype,
4819 name,
4820 bundle::VALID_ENTITY_TYPES.join(", "),
4821 ));
4822 }
4823 }
4824 let parsed_source_authors = source_authors
4825 .map(|s| {
4826 s.split(';')
4827 .map(|a| a.trim().to_string())
4828 .filter(|a| !a.is_empty())
4829 .collect()
4830 })
4831 .unwrap_or_default();
4832 let parsed_species = species
4833 .map(|s| {
4834 s.split(';')
4835 .map(|a| a.trim().to_string())
4836 .filter(|a| !a.is_empty())
4837 .collect()
4838 })
4839 .unwrap_or_default();
4840 let report = state::add_finding(
4841 &frontier,
4842 state::FindingDraftOptions {
4843 text: assertion,
4844 assertion_type: r#type,
4845 source,
4846 source_type,
4847 author,
4848 confidence,
4849 evidence_type,
4850 entities: parsed_entities,
4851 doi,
4852 pmid,
4853 year,
4854 journal,
4855 url,
4856 source_authors: parsed_source_authors,
4857 conditions_text,
4858 species: parsed_species,
4859 in_vivo,
4860 in_vitro,
4861 human_data,
4862 clinical_trial,
4863 entities_reviewed,
4864 evidence_spans: parsed_evidence_spans,
4865 gap,
4866 negative_space,
4867 },
4868 apply,
4869 )
4870 .unwrap_or_else(|e| fail_return(&e));
4871 print_state_report(&report, json);
4872 }
4873 FindingCommands::Supersede {
4874 frontier,
4875 old_id,
4876 assertion,
4877 r#type,
4878 source,
4879 source_type,
4880 author,
4881 reason,
4882 confidence,
4883 evidence_type,
4884 entities,
4885 doi,
4886 pmid,
4887 year,
4888 journal,
4889 url,
4890 source_authors,
4891 conditions_text,
4892 species,
4893 in_vivo,
4894 in_vitro,
4895 human_data,
4896 clinical_trial,
4897 json,
4898 apply,
4899 } => {
4900 validate_enum_arg("--type", &r#type, bundle::VALID_ASSERTION_TYPES);
4901 validate_enum_arg(
4902 "--evidence-type",
4903 &evidence_type,
4904 bundle::VALID_EVIDENCE_TYPES,
4905 );
4906 validate_enum_arg(
4907 "--source-type",
4908 &source_type,
4909 bundle::VALID_PROVENANCE_SOURCE_TYPES,
4910 );
4911 let parsed_entities = parse_entities(&entities);
4912 for (name, etype) in &parsed_entities {
4913 if !bundle::VALID_ENTITY_TYPES.contains(&etype.as_str()) {
4914 fail(&format!(
4915 "invalid entity type '{}' for '{}'. Valid: {}",
4916 etype,
4917 name,
4918 bundle::VALID_ENTITY_TYPES.join(", "),
4919 ));
4920 }
4921 }
4922 let parsed_source_authors = source_authors
4923 .map(|s| {
4924 s.split(';')
4925 .map(|a| a.trim().to_string())
4926 .filter(|a| !a.is_empty())
4927 .collect()
4928 })
4929 .unwrap_or_default();
4930 let parsed_species = species
4931 .map(|s| {
4932 s.split(';')
4933 .map(|a| a.trim().to_string())
4934 .filter(|a| !a.is_empty())
4935 .collect()
4936 })
4937 .unwrap_or_default();
4938 let report = state::supersede_finding(
4939 &frontier,
4940 &old_id,
4941 &reason,
4942 state::FindingDraftOptions {
4943 text: assertion,
4944 assertion_type: r#type,
4945 source,
4946 source_type,
4947 author,
4948 confidence,
4949 evidence_type,
4950 entities: parsed_entities,
4951 doi,
4952 pmid,
4953 year,
4954 journal,
4955 url,
4956 source_authors: parsed_source_authors,
4957 conditions_text,
4958 species: parsed_species,
4959 in_vivo,
4960 in_vitro,
4961 human_data,
4962 clinical_trial,
4963 entities_reviewed: false,
4964 evidence_spans: Vec::new(),
4965 gap: false,
4966 negative_space: false,
4967 },
4968 apply,
4969 )
4970 .unwrap_or_else(|e| fail_return(&e));
4971 print_state_report(&report, json);
4972 }
4973 FindingCommands::CausalSet {
4974 frontier,
4975 finding_id,
4976 claim,
4977 grade,
4978 actor,
4979 reason,
4980 json,
4981 } => {
4982 if !bundle::VALID_CAUSAL_CLAIMS.contains(&claim.as_str()) {
4983 fail(&format!(
4984 "invalid --claim '{claim}'; valid: {:?}",
4985 bundle::VALID_CAUSAL_CLAIMS
4986 ));
4987 }
4988 if let Some(g) = grade.as_deref()
4989 && !bundle::VALID_CAUSAL_EVIDENCE_GRADES.contains(&g)
4990 {
4991 fail(&format!(
4992 "invalid --grade '{g}'; valid: {:?}",
4993 bundle::VALID_CAUSAL_EVIDENCE_GRADES
4994 ));
4995 }
4996 let report = state::set_causal(
4997 &frontier,
4998 &finding_id,
4999 &claim,
5000 grade.as_deref(),
5001 &actor,
5002 &reason,
5003 )
5004 .unwrap_or_else(|e| fail_return(&e));
5005 print_state_report(&report, json);
5006 }
5007 },
5008 Commands::Review {
5009 frontier,
5010 finding_id,
5011 status,
5012 reason,
5013 reviewer,
5014 apply,
5015 json,
5016 } => {
5017 let status = status.unwrap_or_else(|| fail_return("--status is required for review"));
5018 let reason = reason.unwrap_or_else(|| fail_return("--reason is required for review"));
5019 let report = state::review_finding(
5020 &frontier,
5021 &finding_id,
5022 state::ReviewOptions {
5023 status,
5024 reason,
5025 reviewer,
5026 },
5027 apply,
5028 )
5029 .unwrap_or_else(|e| fail_return(&e));
5030 print_state_report(&report, json);
5031 }
5032 Commands::Note {
5033 frontier,
5034 finding_id,
5035 text,
5036 author,
5037 apply,
5038 json,
5039 } => {
5040 let report = state::add_note(&frontier, &finding_id, &text, &author, apply)
5041 .unwrap_or_else(|e| fail_return(&e));
5042 print_state_report(&report, json);
5043 }
5044 Commands::Caveat {
5045 frontier,
5046 finding_id,
5047 text,
5048 author,
5049 apply,
5050 json,
5051 } => {
5052 let report = state::caveat_finding(&frontier, &finding_id, &text, &author, apply)
5053 .unwrap_or_else(|e| fail_return(&e));
5054 print_state_report(&report, json);
5055 }
5056 Commands::Revise {
5057 frontier,
5058 finding_id,
5059 confidence,
5060 reason,
5061 reviewer,
5062 apply,
5063 json,
5064 } => {
5065 let report = state::revise_confidence(
5066 &frontier,
5067 &finding_id,
5068 state::ReviseOptions {
5069 confidence,
5070 reason,
5071 reviewer,
5072 },
5073 apply,
5074 )
5075 .unwrap_or_else(|e| fail_return(&e));
5076 print_state_report(&report, json);
5077 }
5078 Commands::Reject {
5079 frontier,
5080 finding_id,
5081 reason,
5082 reviewer,
5083 apply,
5084 json,
5085 } => {
5086 let report = state::reject_finding(&frontier, &finding_id, &reviewer, &reason, apply)
5087 .unwrap_or_else(|e| fail_return(&e));
5088 print_state_report(&report, json);
5089 }
5090 Commands::History {
5091 frontier,
5092 finding_id,
5093 json,
5094 as_of,
5095 } => {
5096 let payload = state::history_as_of(&frontier, &finding_id, as_of.as_deref())
5097 .unwrap_or_else(|e| fail_return(&e));
5098 if json {
5099 println!(
5100 "{}",
5101 serde_json::to_string_pretty(&payload)
5102 .expect("failed to serialize history response")
5103 );
5104 } else {
5105 print_history(&payload);
5106 }
5107 }
5108 Commands::ImportEvents { source, into, json } => {
5109 let report =
5110 review::import_review_events(&source, &into).unwrap_or_else(|e| fail_return(&e));
5111 if json {
5112 println!(
5113 "{}",
5114 serde_json::to_string_pretty(&json!({
5115 "ok": true,
5116 "command": "import-events",
5117 "source": report.source,
5118 "target": into.display().to_string(),
5119 "summary": {
5120 "imported": report.imported,
5121 "new": report.new,
5122 "duplicate": report.duplicate,
5123 "canonical_events_imported": report.events_imported,
5124 "canonical_events_new": report.events_new,
5125 "canonical_events_duplicate": report.events_duplicate,
5126 }
5127 }))
5128 .expect("failed to serialize import-events response")
5129 );
5130 } else {
5131 println!("{report}");
5132 }
5133 }
5134 Commands::Retract {
5135 source,
5136 finding_id,
5137 reason,
5138 reviewer,
5139 apply,
5140 json,
5141 } => {
5142 let report = state::retract_finding(&source, &finding_id, &reviewer, &reason, apply)
5143 .unwrap_or_else(|e| fail_return(&e));
5144 print_state_report(&report, json);
5145 }
5146 Commands::LocatorRepair {
5147 frontier,
5148 atom_id,
5149 locator,
5150 reviewer,
5151 reason,
5152 apply,
5153 json,
5154 } => {
5155 cmd_locator_repair(
5156 &frontier,
5157 &atom_id,
5158 locator.as_deref(),
5159 &reviewer,
5160 &reason,
5161 apply,
5162 json,
5163 );
5164 }
5165 Commands::SourceFetch {
5166 identifier,
5167 cache,
5168 out,
5169 refresh,
5170 json,
5171 } => {
5172 cmd_source_fetch(&identifier, cache.as_deref(), out.as_deref(), refresh, json).await;
5173 }
5174 Commands::SpanRepair {
5175 frontier,
5176 finding_id,
5177 section,
5178 text,
5179 reviewer,
5180 reason,
5181 apply,
5182 json,
5183 } => {
5184 cmd_span_repair(
5185 &frontier,
5186 &finding_id,
5187 §ion,
5188 &text,
5189 &reviewer,
5190 &reason,
5191 apply,
5192 json,
5193 );
5194 }
5195 Commands::ProofAdd {
5196 frontier,
5197 target_finding,
5198 tool,
5199 tool_version,
5200 script_path,
5201 name,
5202 reviewer,
5203 reason,
5204 json,
5205 } => {
5206 cmd_proof_add(
5207 &frontier,
5208 &target_finding,
5209 &tool,
5210 &tool_version,
5211 &script_path,
5212 &name,
5213 &reviewer,
5214 &reason,
5215 json,
5216 );
5217 }
5218 Commands::ProofAttestVerification {
5219 proof_id,
5220 tool,
5221 tool_version,
5222 script_locator,
5223 lake_manifest_hash,
5224 verifier_output_hash,
5225 status,
5226 verifier_actor,
5227 key,
5228 out,
5229 json,
5230 } => cmd_proof_attest_verification(
5231 proof_id,
5232 tool,
5233 tool_version,
5234 script_locator,
5235 lake_manifest_hash,
5236 verifier_output_hash,
5237 status,
5238 verifier_actor,
5239 key,
5240 out,
5241 json,
5242 ),
5243 Commands::ProofVerifyAttestation { record, json } => {
5244 cmd_proof_verify_attestation(record, json)
5245 }
5246 Commands::EntityAdd {
5247 frontier,
5248 finding_id,
5249 entity,
5250 entity_type,
5251 reviewer,
5252 reason,
5253 apply,
5254 json,
5255 } => {
5256 let report = state::add_finding_entity(
5257 &frontier,
5258 &finding_id,
5259 &entity,
5260 &entity_type,
5261 &reviewer,
5262 &reason,
5263 apply,
5264 )
5265 .unwrap_or_else(|e| fail_return(&e));
5266 print_state_report(&report, json);
5267 }
5268 Commands::EntityResolve {
5269 frontier,
5270 finding_id,
5271 entity,
5272 source,
5273 id,
5274 confidence,
5275 matched_name,
5276 resolution_method,
5277 reviewer,
5278 reason,
5279 apply,
5280 json,
5281 } => {
5282 cmd_entity_resolve(
5283 &frontier,
5284 &finding_id,
5285 &entity,
5286 &source,
5287 &id,
5288 confidence,
5289 matched_name.as_deref(),
5290 &resolution_method,
5291 &reviewer,
5292 &reason,
5293 apply,
5294 json,
5295 );
5296 }
5297 Commands::Propagate {
5298 frontier,
5299 retract,
5300 reduce_confidence,
5301 to,
5302 output,
5303 } => cmd_propagate(&frontier, retract, reduce_confidence, to, output.as_deref()),
5304 Commands::Replicate {
5305 frontier,
5306 target,
5307 outcome,
5308 by,
5309 conditions,
5310 source_title,
5311 doi,
5312 pmid,
5313 sample_size,
5314 note,
5315 previous_attempt,
5316 no_cascade,
5317 json,
5318 } => cmd_replicate(
5319 &frontier,
5320 &target,
5321 &outcome,
5322 &by,
5323 &conditions,
5324 &source_title,
5325 doi.as_deref(),
5326 pmid.as_deref(),
5327 sample_size.as_deref(),
5328 ¬e,
5329 previous_attempt.as_deref(),
5330 no_cascade,
5331 json,
5332 ),
5333 Commands::Replications {
5334 frontier,
5335 target,
5336 json,
5337 } => cmd_replications(&frontier, target.as_deref(), json),
5338 Commands::DatasetAdd {
5339 frontier,
5340 name,
5341 version,
5342 content_hash,
5343 url,
5344 license,
5345 source_title,
5346 doi,
5347 row_count,
5348 json,
5349 } => cmd_dataset_add(
5350 &frontier,
5351 &name,
5352 version.as_deref(),
5353 &content_hash,
5354 url.as_deref(),
5355 license.as_deref(),
5356 &source_title,
5357 doi.as_deref(),
5358 row_count,
5359 json,
5360 ),
5361 Commands::Datasets { frontier, json } => cmd_datasets(&frontier, json),
5362 Commands::CodeAdd {
5363 frontier,
5364 language,
5365 repo_url,
5366 commit,
5367 path,
5368 content_hash,
5369 line_start,
5370 line_end,
5371 entry_point,
5372 json,
5373 } => cmd_code_add(
5374 &frontier,
5375 &language,
5376 repo_url.as_deref(),
5377 commit.as_deref(),
5378 &path,
5379 &content_hash,
5380 line_start,
5381 line_end,
5382 entry_point.as_deref(),
5383 json,
5384 ),
5385 Commands::CodeArtifacts { frontier, json } => cmd_code_artifacts(&frontier, json),
5386 Commands::ArtifactAdd {
5387 frontier,
5388 kind,
5389 name,
5390 file,
5391 url,
5392 content_hash,
5393 media_type,
5394 license,
5395 source_title,
5396 source_url,
5397 doi,
5398 target,
5399 metadata,
5400 access_tier,
5401 deposited_by,
5402 reason,
5403 json,
5404 } => cmd_artifact_add(
5405 &frontier,
5406 &kind,
5407 &name,
5408 file.as_deref(),
5409 url.as_deref(),
5410 content_hash.as_deref(),
5411 media_type.as_deref(),
5412 license.as_deref(),
5413 source_title.as_deref(),
5414 source_url.as_deref(),
5415 doi.as_deref(),
5416 target,
5417 metadata,
5418 &access_tier,
5419 &deposited_by,
5420 &reason,
5421 json,
5422 ),
5423 Commands::Artifacts {
5424 frontier,
5425 target,
5426 json,
5427 } => cmd_artifacts(&frontier, target.as_deref(), json),
5428 Commands::ArtifactAudit { frontier, json } => cmd_artifact_audit(&frontier, json),
5429 Commands::DecisionBrief { frontier, json } => cmd_decision_brief(&frontier, json),
5430 Commands::TrialSummary { frontier, json } => cmd_trial_summary(&frontier, json),
5431 Commands::SourceVerification { frontier, json } => cmd_source_verification(&frontier, json),
5432 Commands::SourceIngestPlan { frontier, json } => cmd_source_ingest_plan(&frontier, json),
5433 Commands::ClinicalTrialImport {
5434 frontier,
5435 nct_id,
5436 input_json,
5437 target,
5438 deposited_by,
5439 reason,
5440 license,
5441 json,
5442 } => {
5443 cmd_clinical_trial_import(
5444 &frontier,
5445 &nct_id,
5446 input_json.as_deref(),
5447 target,
5448 &deposited_by,
5449 &reason,
5450 &license,
5451 json,
5452 )
5453 .await
5454 }
5455 Commands::NegativeResultAdd {
5456 frontier,
5457 kind,
5458 deposited_by,
5459 reason,
5460 conditions_text,
5461 notes,
5462 target,
5463 endpoint,
5464 intervention,
5465 comparator,
5466 population,
5467 n_enrolled,
5468 power,
5469 ci_lower,
5470 ci_upper,
5471 effect_size_threshold,
5472 registry_id,
5473 reagent,
5474 observation,
5475 attempts,
5476 source_title,
5477 doi,
5478 url,
5479 year,
5480 json,
5481 } => cmd_negative_result_add(
5482 &frontier,
5483 &kind,
5484 &deposited_by,
5485 &reason,
5486 &conditions_text,
5487 ¬es,
5488 target,
5489 endpoint.as_deref(),
5490 intervention.as_deref(),
5491 comparator.as_deref(),
5492 population.as_deref(),
5493 n_enrolled,
5494 power,
5495 ci_lower,
5496 ci_upper,
5497 effect_size_threshold,
5498 registry_id.as_deref(),
5499 reagent.as_deref(),
5500 observation.as_deref(),
5501 attempts,
5502 &source_title,
5503 doi.as_deref(),
5504 url.as_deref(),
5505 year,
5506 json,
5507 ),
5508 Commands::NegativeResults {
5509 frontier,
5510 target,
5511 json,
5512 } => cmd_negative_results(&frontier, target.as_deref(), json),
5513 Commands::TrajectoryCreate {
5514 frontier,
5515 deposited_by,
5516 reason,
5517 target,
5518 notes,
5519 json,
5520 } => cmd_trajectory_create(&frontier, &deposited_by, &reason, target, ¬es, json),
5521 Commands::TrajectoryStep {
5522 frontier,
5523 trajectory_id,
5524 kind,
5525 description,
5526 actor,
5527 reason,
5528 reference,
5529 json,
5530 } => cmd_trajectory_step(
5531 &frontier,
5532 &trajectory_id,
5533 &kind,
5534 &description,
5535 &actor,
5536 &reason,
5537 reference,
5538 json,
5539 ),
5540 Commands::Trajectories {
5541 frontier,
5542 target,
5543 json,
5544 } => cmd_trajectories(&frontier, target.as_deref(), json),
5545 Commands::TierSet {
5546 frontier,
5547 object_type,
5548 object_id,
5549 tier,
5550 actor,
5551 reason,
5552 json,
5553 } => cmd_tier_set(
5554 &frontier,
5555 &object_type,
5556 &object_id,
5557 &tier,
5558 &actor,
5559 &reason,
5560 json,
5561 ),
5562 Commands::Predict {
5563 frontier,
5564 by,
5565 claim,
5566 criterion,
5567 resolves_by,
5568 confidence,
5569 target,
5570 outcome,
5571 conditions,
5572 json,
5573 } => cmd_predict(
5574 &frontier,
5575 &by,
5576 &claim,
5577 &criterion,
5578 resolves_by.as_deref(),
5579 confidence,
5580 &target,
5581 &outcome,
5582 &conditions,
5583 json,
5584 ),
5585 Commands::Resolve {
5586 frontier,
5587 prediction,
5588 outcome,
5589 matched,
5590 by,
5591 confidence,
5592 source_title,
5593 doi,
5594 json,
5595 } => cmd_resolve(
5596 &frontier,
5597 &prediction,
5598 &outcome,
5599 matched,
5600 &by,
5601 confidence,
5602 &source_title,
5603 doi.as_deref(),
5604 json,
5605 ),
5606 Commands::Predictions {
5607 frontier,
5608 by,
5609 open,
5610 json,
5611 } => cmd_predictions(&frontier, by.as_deref(), open, json),
5612 Commands::Calibration {
5613 frontier,
5614 actor,
5615 json,
5616 } => cmd_calibration(&frontier, actor.as_deref(), json),
5617 Commands::PredictionsExpire {
5618 frontier,
5619 now,
5620 dry_run,
5621 json,
5622 } => cmd_predictions_expire(&frontier, now.as_deref(), dry_run, json),
5623 Commands::Consensus {
5624 frontier,
5625 target,
5626 weighting,
5627 causal_claim,
5628 causal_grade_min,
5629 json,
5630 } => cmd_consensus(
5631 &frontier,
5632 &target,
5633 &weighting,
5634 causal_claim.as_deref(),
5635 causal_grade_min.as_deref(),
5636 json,
5637 ),
5638
5639 Commands::Ingest {
5642 path,
5643 frontier,
5644 backend,
5645 actor,
5646 dry_run,
5647 json,
5648 } => {
5649 cmd_ingest(
5650 &path,
5651 &frontier,
5652 backend.as_deref(),
5653 actor.as_deref(),
5654 dry_run,
5655 json,
5656 )
5657 .await
5658 }
5659
5660 Commands::Propose {
5661 frontier,
5662 finding_id,
5663 status,
5664 reason,
5665 reviewer,
5666 apply,
5667 json,
5668 } => {
5669 let options = state::ReviewOptions {
5672 status: status.clone(),
5673 reason: reason.clone(),
5674 reviewer: reviewer.clone(),
5675 };
5676 let report = state::review_finding(&frontier, &finding_id, options, apply)
5677 .unwrap_or_else(|e| fail_return(&e));
5678 print_state_report(&report, json);
5679 }
5680
5681 Commands::Accept {
5682 frontier,
5683 proposal_id,
5684 reviewer,
5685 reason,
5686 json,
5687 } => {
5688 let event_id = proposals::accept_at_path(&frontier, &proposal_id, &reviewer, &reason)
5690 .unwrap_or_else(|e| fail_return(&e));
5691 let payload = json!({
5692 "ok": true,
5693 "command": "accept",
5694 "frontier": frontier.display().to_string(),
5695 "proposal_id": proposal_id,
5696 "reviewer": reviewer,
5697 "applied_event_id": event_id,
5698 });
5699 if json {
5700 println!(
5701 "{}",
5702 serde_json::to_string_pretty(&payload)
5703 .expect("failed to serialize accept response")
5704 );
5705 } else {
5706 println!(
5707 "{} accepted and applied proposal {}",
5708 style::ok("ok"),
5709 proposal_id
5710 );
5711 println!(" event: {}", event_id);
5712 }
5713 }
5714
5715 Commands::Attest {
5716 frontier,
5717 event,
5718 attester,
5719 scope_note,
5720 proof_id,
5721 signature,
5722 key,
5723 json,
5724 } => {
5725 if let Some(target_event_id) = event {
5729 let attester_id = attester.unwrap_or_else(|| {
5730 fail_return("attest: --attester is required in per-event mode")
5731 });
5732 let scope = scope_note.unwrap_or_else(|| {
5733 fail_return("attest: --scope-note is required in per-event mode")
5734 });
5735 let attestation_event_id = state::record_attestation(
5736 &frontier,
5737 &target_event_id,
5738 &attester_id,
5739 &scope,
5740 proof_id.as_deref(),
5741 signature.as_deref(),
5742 )
5743 .unwrap_or_else(|e| fail_return(&e));
5744 if json {
5745 let payload = json!({
5746 "ok": true,
5747 "command": "attest.event",
5748 "frontier": frontier.display().to_string(),
5749 "target_event_id": target_event_id,
5750 "attestation_event_id": attestation_event_id,
5751 "attester_id": attester_id,
5752 });
5753 println!(
5754 "{}",
5755 serde_json::to_string_pretty(&payload)
5756 .expect("failed to serialize attest.event response")
5757 );
5758 } else {
5759 println!(
5760 "{} attested {} by {} ({})",
5761 style::ok("ok"),
5762 target_event_id,
5763 attester_id,
5764 attestation_event_id
5765 );
5766 }
5767 return;
5768 }
5769 let key_path = key.unwrap_or_else(|| {
5771 fail_return(
5772 "attest: --key is required in frontier-wide mode (or pass --event for per-event mode)",
5773 )
5774 });
5775 let count =
5776 sign::sign_frontier(&frontier, &key_path).unwrap_or_else(|e| fail_return(&e));
5777 let payload = json!({
5778 "ok": true,
5779 "command": "attest",
5780 "frontier": frontier.display().to_string(),
5781 "private_key": key_path.display().to_string(),
5782 "signed": count,
5783 });
5784 if json {
5785 println!(
5786 "{}",
5787 serde_json::to_string_pretty(&payload)
5788 .expect("failed to serialize attest response")
5789 );
5790 } else {
5791 println!(
5792 "{} {count} findings in {}",
5793 style::ok("attested"),
5794 frontier.display()
5795 );
5796 }
5797 }
5798
5799 Commands::Lineage {
5800 frontier,
5801 finding_id,
5802 as_of,
5803 json,
5804 } => {
5805 let payload = state::history_as_of(&frontier, &finding_id, as_of.as_deref())
5807 .unwrap_or_else(|e| fail_return(&e));
5808 if json {
5809 println!(
5810 "{}",
5811 serde_json::to_string_pretty(&payload)
5812 .expect("failed to serialize lineage response")
5813 );
5814 } else {
5815 print_history(&payload);
5816 }
5817 }
5818
5819 Commands::Carina { action } => cmd_carina(action),
5820
5821 Commands::Atlas { action } => cmd_atlas(action).await,
5822
5823 Commands::Constellation { action } => cmd_constellation(action).await,
5824 }
5825}
5826
5827async fn cmd_atlas(action: AtlasAction) {
5832 match action {
5833 AtlasAction::Init {
5834 name,
5835 frontiers,
5836 domain,
5837 scope_note,
5838 atlases_root,
5839 json,
5840 } => match ATLAS_INIT_HANDLER.get() {
5841 Some(handler) => {
5842 handler(atlases_root, name, domain, scope_note, frontiers, json).await;
5843 }
5844 None => fail("vela atlas init: handler not registered (built without vela-atlas)"),
5845 },
5846 AtlasAction::Materialize {
5847 name,
5848 atlases_root,
5849 json,
5850 } => match ATLAS_MATERIALIZE_HANDLER.get() {
5851 Some(handler) => handler(atlases_root, name, json).await,
5852 None => fail("vela atlas materialize: handler not registered"),
5853 },
5854 AtlasAction::Serve {
5855 name,
5856 atlases_root,
5857 port,
5858 no_open,
5859 } => {
5860 match ATLAS_SERVE_HANDLER.get() {
5864 Some(handler) => handler(atlases_root, name, port, !no_open).await,
5865 None => fail("vela atlas serve: handler not registered"),
5866 }
5867 }
5868 AtlasAction::Update {
5869 name,
5870 add_frontier,
5871 remove_vfr_id,
5872 atlases_root,
5873 json,
5874 } => match ATLAS_UPDATE_HANDLER.get() {
5875 Some(handler) => {
5876 handler(atlases_root, name, add_frontier, remove_vfr_id, json).await;
5877 }
5878 None => fail("vela atlas update: handler not registered"),
5879 },
5880 }
5881}
5882
5883async fn cmd_constellation(action: ConstellationAction) {
5887 match action {
5888 ConstellationAction::Init {
5889 name,
5890 atlases,
5891 scope_note,
5892 constellations_root,
5893 json,
5894 } => match CONSTELLATION_INIT_HANDLER.get() {
5895 Some(handler) => {
5896 handler(constellations_root, name, scope_note, atlases, json).await;
5897 }
5898 None => fail(
5899 "vela constellation init: handler not registered (built without vela-constellation)",
5900 ),
5901 },
5902 ConstellationAction::Materialize {
5903 name,
5904 constellations_root,
5905 json,
5906 } => match CONSTELLATION_MATERIALIZE_HANDLER.get() {
5907 Some(handler) => handler(constellations_root, name, json).await,
5908 None => fail("vela constellation materialize: handler not registered"),
5909 },
5910 ConstellationAction::Serve {
5911 name,
5912 constellations_root,
5913 port,
5914 no_open,
5915 } => match CONSTELLATION_SERVE_HANDLER.get() {
5916 Some(handler) => handler(constellations_root, name, port, !no_open).await,
5917 None => fail("vela constellation serve: handler not registered"),
5918 },
5919 }
5920}
5921
5922fn cmd_carina(action: CarinaAction) {
5925 match action {
5926 CarinaAction::List { json } => {
5927 if json {
5928 println!(
5929 "{}",
5930 serde_json::to_string_pretty(&json!({
5931 "ok": true,
5932 "command": "carina.list",
5933 "primitives": carina_validate::PRIMITIVE_NAMES,
5934 }))
5935 .expect("failed to serialize carina.list")
5936 );
5937 } else {
5938 println!("Carina primitives bundled with this build:");
5939 for name in carina_validate::PRIMITIVE_NAMES {
5940 println!(" · {name}");
5941 }
5942 }
5943 }
5944 CarinaAction::Schema { primitive } => match carina_validate::schema_text(&primitive) {
5945 Some(text) => print!("{text}"),
5946 None => fail(&format!("carina: unknown primitive '{primitive}'")),
5947 },
5948 CarinaAction::Validate {
5949 path,
5950 primitive,
5951 json,
5952 } => {
5953 let text = std::fs::read_to_string(&path)
5954 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", path.display())));
5955 let value: Value = serde_json::from_str(&text)
5956 .unwrap_or_else(|e| fail_return(&format!("parse {}: {e}", path.display())));
5957 type CarinaValidateOutcome = Result<Option<&'static str>, Vec<String>>;
5963 let mut report: Vec<(String, CarinaValidateOutcome)> = Vec::new();
5964 if value.get("primitives").and_then(Value::as_object).is_some() && primitive.is_none() {
5965 let primitives = value.get("primitives").and_then(Value::as_object).unwrap();
5966 for (key, child) in primitives {
5967 let outcome = carina_validate::validate(key, child)
5968 .map(|()| carina_validate::detect_primitive(child));
5969 report.push((key.clone(), outcome));
5970 }
5971 } else {
5972 let outcome = match primitive.as_deref() {
5973 Some(name) => carina_validate::validate(name, &value).map(|()| {
5974 carina_validate::PRIMITIVE_NAMES
5975 .iter()
5976 .copied()
5977 .find(|p| *p == name)
5978 }),
5979 None => carina_validate::validate_auto(&value).map(Some),
5980 };
5981 let label = primitive.clone().unwrap_or_else(|| "<auto>".to_string());
5982 report.push((label, outcome));
5983 }
5984
5985 let total = report.len();
5986 let pass = report.iter().filter(|(_, r)| r.is_ok()).count();
5987 let fail = total - pass;
5988
5989 if json {
5990 let entries: Vec<Value> = report
5991 .iter()
5992 .map(|(label, r)| match r {
5993 Ok(name) => json!({
5994 "key": label,
5995 "primitive": name,
5996 "ok": true,
5997 }),
5998 Err(errs) => json!({
5999 "key": label,
6000 "ok": false,
6001 "errors": errs,
6002 }),
6003 })
6004 .collect();
6005 println!(
6006 "{}",
6007 serde_json::to_string_pretty(&json!({
6008 "ok": fail == 0,
6009 "command": "carina.validate",
6010 "file": path.display().to_string(),
6011 "total": total,
6012 "passed": pass,
6013 "failed": fail,
6014 "entries": entries,
6015 }))
6016 .expect("failed to serialize carina.validate")
6017 );
6018 } else {
6019 for (label, r) in &report {
6020 match r {
6021 Ok(Some(name)) => println!(" {} {label} (as {name})", style::ok("ok")),
6022 Ok(None) => println!(" {} {label}", style::ok("ok")),
6023 Err(errs) => {
6024 println!(" {} {label}", style::lost("fail"));
6025 for e in errs {
6026 println!(" {e}");
6027 }
6028 }
6029 }
6030 }
6031 println!();
6032 if fail == 0 {
6033 println!("{} {pass}/{total} valid", style::ok("carina.validate"));
6034 } else {
6035 println!(
6036 "{} {pass}/{total} valid · {fail} failed",
6037 style::lost("carina.validate")
6038 );
6039 }
6040 }
6041
6042 if fail > 0 {
6043 std::process::exit(1);
6044 }
6045 }
6046 }
6047}
6048
6049#[allow(clippy::too_many_arguments)]
6060fn cmd_proof_add(
6061 frontier: &Path,
6062 target_finding: &str,
6063 tool: &str,
6064 tool_version: &str,
6065 script_path: &Path,
6066 name: &str,
6067 reviewer: &str,
6068 reason: &str,
6069 json_output: bool,
6070) {
6071 use std::collections::BTreeMap;
6072
6073 if !target_finding.starts_with("vf_") {
6075 fail(&format!(
6076 "--target-finding must be a vf_* finding id; got `{target_finding}`"
6077 ));
6078 }
6079 let valid_tools = [
6081 "lean4", "coq", "isabelle", "agda", "metamath", "rocq", "other",
6082 ];
6083 if !valid_tools.contains(&tool) {
6084 fail(&format!(
6085 "--tool `{tool}` not in {valid_tools:?}; see embedded/carina-schemas/proof.schema.json"
6086 ));
6087 }
6088
6089 let script_bytes = std::fs::read(script_path)
6091 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", script_path.display())));
6092 let script_hash_hex = hex::encode(Sha256::digest(&script_bytes));
6093 let script_locator = format!("sha256:{script_hash_hex}");
6094
6095 let vpf_preimage = format!("{script_locator}|{tool}|{tool_version}|{target_finding}");
6099 let vpf_id = format!(
6100 "vpf_{}",
6101 &hex::encode(Sha256::digest(vpf_preimage.as_bytes()))[..16]
6102 );
6103
6104 let verified_at = chrono::Utc::now().to_rfc3339();
6107 let proof_primitive = json!({
6108 "schema": "carina.proof.v0.3",
6109 "id": vpf_id,
6110 "tool": tool,
6111 "tool_version": tool_version,
6112 "script_locator": script_locator,
6113 "verifier_output_hash": format!("sha256:{}", "0".repeat(64)),
6117 "verified_at": verified_at,
6118 "target_finding_id": target_finding,
6119 });
6120 if let Err(errs) = carina_validate::validate("proof", &proof_primitive) {
6121 fail(&format!(
6122 "constructed Proof primitive does not validate against proof.schema.json:\n - {}",
6123 errs.join("\n - ")
6124 ));
6125 }
6126
6127 let mut metadata: BTreeMap<String, Value> = BTreeMap::new();
6129 metadata.insert(
6130 "carina_kind".to_string(),
6131 Value::String("proof_script".to_string()),
6132 );
6133 metadata.insert(
6134 "carina_proof_tool".to_string(),
6135 Value::String(tool.to_string()),
6136 );
6137 metadata.insert(
6138 "carina_proof_tool_version".to_string(),
6139 Value::String(tool_version.to_string()),
6140 );
6141 metadata.insert("carina_proof_id".to_string(), Value::String(vpf_id.clone()));
6142 metadata.insert(
6143 "carina_proof_target_finding".to_string(),
6144 Value::String(target_finding.to_string()),
6145 );
6146
6147 let media_type = match tool {
6148 "lean4" | "rocq" => Some("text/x-lean".to_string()),
6149 "coq" => Some("text/x-coq".to_string()),
6150 "isabelle" => Some("text/x-isabelle".to_string()),
6151 "agda" => Some("text/x-agda".to_string()),
6152 "metamath" => Some("text/x-metamath".to_string()),
6153 _ => None,
6154 };
6155
6156 let provenance = crate::bundle::Provenance {
6157 source_type: "code_repository".to_string(),
6158 doi: None,
6159 pmid: None,
6160 pmc: None,
6161 openalex_id: None,
6162 url: None,
6163 title: format!("Proof script for {target_finding} ({tool} {tool_version})"),
6164 authors: Vec::new(),
6165 year: None,
6166 journal: None,
6167 license: Some("Apache-2.0 OR MIT".to_string()),
6168 publisher: None,
6169 funders: Vec::new(),
6170 extraction: crate::bundle::Extraction::default(),
6171 review: None,
6172 citation_count: None,
6173 };
6174
6175 let artifact_id = crate::bundle::Artifact::content_address(
6176 "source_file",
6177 name,
6178 &format!("sha256:{script_hash_hex}"),
6179 None,
6180 Some(&script_path.display().to_string()),
6181 );
6182
6183 let artifact = crate::bundle::Artifact {
6184 id: artifact_id.clone(),
6185 kind: "source_file".to_string(),
6186 name: name.to_string(),
6187 content_hash: format!("sha256:{script_hash_hex}"),
6188 size_bytes: Some(script_bytes.len() as u64),
6189 media_type,
6190 storage_mode: "pointer".to_string(),
6191 locator: Some(script_path.display().to_string()),
6192 source_url: None,
6193 license: Some("Apache-2.0 OR MIT".to_string()),
6194 target_findings: vec![target_finding.to_string()],
6195 source_id: None,
6196 provenance,
6197 metadata,
6198 review_state: None,
6199 retracted: false,
6200 access_tier: crate::access_tier::AccessTier::default(),
6201 created: verified_at.clone(),
6202 };
6203
6204 let report = state::add_artifact(frontier, artifact, reviewer, reason)
6208 .unwrap_or_else(|e| fail_return(&e));
6209
6210 let payload = json!({
6212 "ok": true,
6213 "command": "proof-add",
6214 "frontier": frontier.display().to_string(),
6215 "target_finding": target_finding,
6216 "tool": tool,
6217 "tool_version": tool_version,
6218 "script_path": script_path.display().to_string(),
6219 "script_locator": script_locator,
6220 "size_bytes": script_bytes.len(),
6221 "vpf_id": vpf_id,
6222 "va_id": artifact_id,
6223 "applied_event_id": report.applied_event_id,
6224 "verified_at": verified_at,
6225 "reviewer": reviewer,
6226 });
6227
6228 if json_output {
6229 println!(
6230 "{}",
6231 serde_json::to_string_pretty(&payload).expect("failed to serialize proof-add response")
6232 );
6233 } else {
6234 println!(
6235 "{} proof artifact deposited for {target_finding}",
6236 style::ok("ok")
6237 );
6238 println!(" vpf_id: {vpf_id}");
6239 println!(" va_id: {artifact_id}");
6240 println!(" locator: {script_locator}");
6241 println!(" tool: {tool} {tool_version}");
6242 if let Some(eid) = &report.applied_event_id {
6243 println!(" event: {eid}");
6244 }
6245 }
6246}
6247
6248fn cmd_consensus(
6251 frontier: &Path,
6252 target: &str,
6253 weighting_str: &str,
6254 causal_claim: Option<&str>,
6255 causal_grade_min: Option<&str>,
6256 json: bool,
6257) {
6258 use crate::bundle::{CausalClaim, CausalEvidenceGrade};
6259
6260 if !target.starts_with("vf_") {
6261 fail(&format!("target `{target}` is not a vf_ finding id"));
6262 }
6263 let scheme =
6264 crate::aggregate::WeightingScheme::parse(weighting_str).unwrap_or_else(|e| fail_return(&e));
6265
6266 let parsed_claim = match causal_claim {
6267 None => None,
6268 Some("correlation") => Some(CausalClaim::Correlation),
6269 Some("mediation") => Some(CausalClaim::Mediation),
6270 Some("intervention") => Some(CausalClaim::Intervention),
6271 Some(other) => fail_return(&format!(
6272 "invalid --causal-claim '{other}'; valid: correlation | mediation | intervention"
6273 )),
6274 };
6275 let parsed_grade = match causal_grade_min {
6276 None => None,
6277 Some("theoretical") => Some(CausalEvidenceGrade::Theoretical),
6278 Some("observational") => Some(CausalEvidenceGrade::Observational),
6279 Some("quasi_experimental") => Some(CausalEvidenceGrade::QuasiExperimental),
6280 Some("rct") => Some(CausalEvidenceGrade::Rct),
6281 Some(other) => fail_return(&format!(
6282 "invalid --causal-grade-min '{other}'; valid: theoretical | observational | quasi_experimental | rct"
6283 )),
6284 };
6285 let filter = crate::aggregate::AggregateFilter {
6286 causal_claim: parsed_claim,
6287 causal_grade_min: parsed_grade,
6288 };
6289 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6290
6291 let result = crate::aggregate::consensus_for_with_filter(&project, target, scheme, &filter)
6292 .unwrap_or_else(|| fail_return(&format!("target `{target}` not in frontier")));
6293
6294 if json {
6295 println!(
6296 "{}",
6297 serde_json::to_string_pretty(&result).expect("serialize consensus")
6298 );
6299 return;
6300 }
6301
6302 println!();
6303 println!(
6304 " {}",
6305 format!(
6306 "VELA · CONSENSUS · {} ({})",
6307 result.target, result.weighting
6308 )
6309 .to_uppercase()
6310 .dimmed()
6311 );
6312 println!(" {}", style::tick_row(60));
6313 println!(
6314 " target: {}",
6315 truncate(&result.target_assertion, 80)
6316 );
6317 println!(" similar findings: {}", result.n_findings);
6318 println!(
6319 " consensus: {:.3} ({:.3} – {:.3} 95% credible)",
6320 result.consensus_confidence, result.credible_interval_lo, result.credible_interval_hi
6321 );
6322 println!();
6323 println!(" constituents (sorted by weight):");
6324 let mut sorted = result.constituents.clone();
6325 sorted.sort_by(|a, b| {
6326 b.weight
6327 .partial_cmp(&a.weight)
6328 .unwrap_or(std::cmp::Ordering::Equal)
6329 });
6330 for c in sorted.iter().take(10) {
6331 let repls = if c.n_replications > 0 {
6332 format!(" ({}r {}f)", c.n_replicated, c.n_failed_replications)
6333 } else {
6334 String::new()
6335 };
6336 println!(
6337 " · w={:.2} raw={:.2} adj={:.2}{}",
6338 c.weight, c.raw_score, c.adjusted_score, repls
6339 );
6340 println!(" {}", truncate(&c.assertion_text, 88));
6341 }
6342 if result.constituents.len() > 10 {
6343 println!(" ... ({} more)", result.constituents.len() - 10);
6344 }
6345}
6346
6347fn parse_expected_outcome(s: &str) -> Result<crate::bundle::ExpectedOutcome, String> {
6353 let trimmed = s.trim();
6354 if trimmed.eq_ignore_ascii_case("affirmed") {
6355 return Ok(crate::bundle::ExpectedOutcome::Affirmed);
6356 }
6357 if trimmed.eq_ignore_ascii_case("falsified") {
6358 return Ok(crate::bundle::ExpectedOutcome::Falsified);
6359 }
6360 if let Some(rest) = trimmed.strip_prefix("cat:") {
6361 return Ok(crate::bundle::ExpectedOutcome::Categorical {
6362 value: rest.to_string(),
6363 });
6364 }
6365 if let Some(rest) = trimmed.strip_prefix("quant:") {
6366 let (vt, units) = rest.split_once(' ').unwrap_or((rest, ""));
6367 let (val_s, tol_s) = vt
6368 .split_once('±')
6369 .or_else(|| vt.split_once("+/-"))
6370 .ok_or_else(|| format!("expected `quant:VALUE±TOL UNITS`, got `quant:{rest}`"))?;
6371 let value: f64 = val_s
6372 .parse()
6373 .map_err(|e| format!("bad quant value `{val_s}`: {e}"))?;
6374 let tolerance: f64 = tol_s
6375 .parse()
6376 .map_err(|e| format!("bad quant tolerance `{tol_s}`: {e}"))?;
6377 return Ok(crate::bundle::ExpectedOutcome::Quantitative {
6378 value,
6379 tolerance,
6380 units: units.to_string(),
6381 });
6382 }
6383 Err(format!(
6384 "unknown outcome `{s}`; expected one of: affirmed | falsified | quant:V±T units | cat:label"
6385 ))
6386}
6387
6388#[allow(clippy::too_many_arguments)]
6390fn cmd_predict(
6391 frontier: &Path,
6392 by: &str,
6393 claim: &str,
6394 criterion: &str,
6395 resolves_by: Option<&str>,
6396 confidence: f64,
6397 target_csv: &str,
6398 outcome: &str,
6399 conditions_text: &str,
6400 json: bool,
6401) {
6402 if !(0.0..=1.0).contains(&confidence) {
6403 fail(&format!("confidence must be in [0, 1]; got {confidence}"));
6404 }
6405 let expected = parse_expected_outcome(outcome).unwrap_or_else(|e| fail_return(&e));
6406
6407 let mut project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6408
6409 let targets: Vec<String> = target_csv
6410 .split(',')
6411 .map(|s| s.trim().to_string())
6412 .filter(|s| !s.is_empty())
6413 .collect();
6414 for t in &targets {
6415 if !t.starts_with("vf_") {
6416 fail(&format!("target `{t}` is not a vf_ id"));
6417 }
6418 if !project.findings.iter().any(|f| f.id == *t) {
6419 fail(&format!("target `{t}` not present in frontier"));
6420 }
6421 }
6422
6423 let lower = conditions_text.to_lowercase();
6424 let conditions = crate::bundle::Conditions {
6425 text: conditions_text.to_string(),
6426 species_verified: Vec::new(),
6427 species_unverified: Vec::new(),
6428 in_vitro: lower.contains("in vitro"),
6429 in_vivo: lower.contains("in vivo"),
6430 human_data: lower.contains("human") || lower.contains("clinical"),
6431 clinical_trial: lower.contains("clinical trial") || lower.contains("phase "),
6432 concentration_range: None,
6433 duration: None,
6434 age_group: None,
6435 cell_type: None,
6436 };
6437
6438 let prediction = crate::bundle::Prediction::new(
6439 claim.to_string(),
6440 targets,
6441 None,
6442 resolves_by.map(|s| s.to_string()),
6443 criterion.to_string(),
6444 expected,
6445 by.to_string(),
6446 confidence,
6447 conditions,
6448 );
6449
6450 if project.predictions.iter().any(|p| p.id == prediction.id) {
6451 if json {
6452 println!(
6453 "{}",
6454 serde_json::to_string_pretty(&json!({
6455 "ok": false,
6456 "command": "predict",
6457 "reason": "prediction_already_exists",
6458 "id": prediction.id,
6459 }))
6460 .expect("serialize")
6461 );
6462 } else {
6463 println!(
6464 "{} prediction {} already exists in {}; skipping.",
6465 style::warn("predict"),
6466 prediction.id,
6467 frontier.display()
6468 );
6469 }
6470 return;
6471 }
6472
6473 let new_id = prediction.id.clone();
6474 project.predictions.push(prediction);
6475 repo::save_to_path(frontier, &project).unwrap_or_else(|e| fail_return(&e));
6476
6477 if json {
6478 println!(
6479 "{}",
6480 serde_json::to_string_pretty(&json!({
6481 "ok": true,
6482 "command": "predict",
6483 "id": new_id,
6484 "made_by": by,
6485 "confidence": confidence,
6486 "frontier": frontier.display().to_string(),
6487 }))
6488 .expect("serialize predict result")
6489 );
6490 } else {
6491 println!();
6492 println!(
6493 " {}",
6494 format!("VELA · PREDICT · {}", new_id)
6495 .to_uppercase()
6496 .dimmed()
6497 );
6498 println!(" {}", style::tick_row(60));
6499 println!(" by: {by}");
6500 println!(" confidence: {confidence:.3}");
6501 if let Some(d) = resolves_by {
6502 println!(" resolves by: {d}");
6503 }
6504 println!(" outcome: {outcome}");
6505 println!(" claim: {}", truncate(claim, 88));
6506 println!();
6507 println!(
6508 " {} prediction recorded in {}",
6509 style::ok("ok"),
6510 frontier.display()
6511 );
6512 }
6513}
6514
6515#[allow(clippy::too_many_arguments)]
6517fn cmd_resolve(
6518 frontier: &Path,
6519 prediction_id: &str,
6520 actual_outcome: &str,
6521 matched: bool,
6522 by: &str,
6523 confidence: f64,
6524 source_title: &str,
6525 doi: Option<&str>,
6526 json: bool,
6527) {
6528 if !prediction_id.starts_with("vpred_") {
6529 fail(&format!("prediction `{prediction_id}` is not a vpred_ id"));
6530 }
6531 if !(0.0..=1.0).contains(&confidence) {
6532 fail(&format!("confidence must be in [0, 1]; got {confidence}"));
6533 }
6534 let mut project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6535 if !project.predictions.iter().any(|p| p.id == prediction_id) {
6536 fail(&format!(
6537 "prediction `{prediction_id}` not present in frontier"
6538 ));
6539 }
6540
6541 let evidence = crate::bundle::Evidence {
6542 evidence_type: "experimental".to_string(),
6543 model_system: String::new(),
6544 species: None,
6545 method: "prediction_resolution".to_string(),
6546 sample_size: None,
6547 effect_size: None,
6548 p_value: None,
6549 replicated: false,
6550 replication_count: None,
6551 evidence_spans: if source_title.is_empty() {
6552 Vec::new()
6553 } else {
6554 vec![serde_json::json!({"text": source_title})]
6555 },
6556 };
6557
6558 let _ = doi; let resolution = crate::bundle::Resolution::new(
6565 prediction_id.to_string(),
6566 actual_outcome.to_string(),
6567 matched,
6568 by.to_string(),
6569 evidence,
6570 confidence,
6571 );
6572
6573 if project.resolutions.iter().any(|r| r.id == resolution.id) {
6574 if json {
6575 println!(
6576 "{}",
6577 serde_json::to_string_pretty(&json!({
6578 "ok": false,
6579 "command": "resolve",
6580 "reason": "resolution_already_exists",
6581 "id": resolution.id,
6582 }))
6583 .expect("serialize")
6584 );
6585 } else {
6586 println!(
6587 "{} resolution {} already exists in {}; skipping.",
6588 style::warn("resolve"),
6589 resolution.id,
6590 frontier.display()
6591 );
6592 }
6593 return;
6594 }
6595
6596 let new_id = resolution.id.clone();
6597 project.resolutions.push(resolution);
6598 repo::save_to_path(frontier, &project).unwrap_or_else(|e| fail_return(&e));
6599
6600 if json {
6601 println!(
6602 "{}",
6603 serde_json::to_string_pretty(&json!({
6604 "ok": true,
6605 "command": "resolve",
6606 "id": new_id,
6607 "prediction": prediction_id,
6608 "matched": matched,
6609 "frontier": frontier.display().to_string(),
6610 }))
6611 .expect("serialize resolve result")
6612 );
6613 } else {
6614 println!();
6615 println!(
6616 " {}",
6617 format!("VELA · RESOLVE · {}", new_id)
6618 .to_uppercase()
6619 .dimmed()
6620 );
6621 println!(" {}", style::tick_row(60));
6622 println!(" prediction: {prediction_id}");
6623 println!(
6624 " matched: {}",
6625 if matched {
6626 style::ok("yes")
6627 } else {
6628 style::lost("no")
6629 }
6630 );
6631 println!(" by: {by}");
6632 println!(" outcome: {}", truncate(actual_outcome, 80));
6633 println!();
6634 println!(
6635 " {} resolution recorded in {}",
6636 style::ok("ok"),
6637 frontier.display()
6638 );
6639 }
6640}
6641
6642fn cmd_predictions(frontier: &Path, by: Option<&str>, open: bool, json: bool) {
6644 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6645
6646 let resolved_ids: std::collections::HashSet<&str> = project
6647 .resolutions
6648 .iter()
6649 .map(|r| r.prediction_id.as_str())
6650 .collect();
6651
6652 let mut filtered: Vec<&crate::bundle::Prediction> = project
6653 .predictions
6654 .iter()
6655 .filter(|p| by.is_none_or(|b| p.made_by == b))
6656 .filter(|p| !open || !resolved_ids.contains(p.id.as_str()))
6657 .collect();
6658 filtered.sort_by(|a, b| {
6659 a.resolves_by
6660 .as_deref()
6661 .unwrap_or("9999")
6662 .cmp(b.resolves_by.as_deref().unwrap_or("9999"))
6663 });
6664
6665 if json {
6666 let payload: Vec<serde_json::Value> = filtered
6667 .iter()
6668 .map(|p| {
6669 json!({
6670 "id": p.id,
6671 "claim_text": p.claim_text,
6672 "made_by": p.made_by,
6673 "confidence": p.confidence,
6674 "predicted_at": p.predicted_at,
6675 "resolves_by": p.resolves_by,
6676 "expected_outcome": p.expected_outcome,
6677 "resolved": resolved_ids.contains(p.id.as_str()),
6678 })
6679 })
6680 .collect();
6681 println!(
6682 "{}",
6683 serde_json::to_string_pretty(&json!({
6684 "ok": true,
6685 "command": "predictions",
6686 "frontier": frontier.display().to_string(),
6687 "count": payload.len(),
6688 "predictions": payload,
6689 }))
6690 .expect("serialize predictions")
6691 );
6692 return;
6693 }
6694
6695 println!();
6696 println!(
6697 " {}",
6698 format!("VELA · PREDICTIONS · {}", frontier.display())
6699 .to_uppercase()
6700 .dimmed()
6701 );
6702 println!(" {}", style::tick_row(60));
6703 if filtered.is_empty() {
6704 println!(" (no predictions matching filters)");
6705 return;
6706 }
6707 for p in &filtered {
6708 let resolved = resolved_ids.contains(p.id.as_str());
6709 let chip = if resolved {
6710 style::ok("resolved")
6711 } else {
6712 style::warn("open")
6713 };
6714 let deadline = p.resolves_by.as_deref().unwrap_or("(no deadline)");
6715 println!(
6716 " · {} {} by {} → {}",
6717 p.id.dimmed(),
6718 chip,
6719 p.made_by,
6720 deadline,
6721 );
6722 println!(" claim: {}", truncate(&p.claim_text, 90));
6723 println!(" confidence: {:.2}", p.confidence);
6724 }
6725}
6726
6727fn cmd_predictions_expire(frontier: &Path, now_override: Option<&str>, dry_run: bool, json: bool) {
6732 use chrono::DateTime;
6733
6734 let now_dt = match now_override {
6735 Some(s) => DateTime::parse_from_rfc3339(s)
6736 .map(|dt| dt.with_timezone(&chrono::Utc))
6737 .unwrap_or_else(|e| fail_return(&format!("invalid --now '{s}': {e}"))),
6738 None => chrono::Utc::now(),
6739 };
6740
6741 let mut project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6742 if dry_run {
6743 let mut probe = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6745 let report = crate::calibration::expire_overdue_predictions(&mut probe, now_dt);
6746 if json {
6747 println!(
6748 "{}",
6749 serde_json::to_string_pretty(&json!({
6750 "ok": true,
6751 "command": "predictions.expire",
6752 "dry_run": true,
6753 "report": report,
6754 }))
6755 .expect("serialize predictions.expire (dry-run)")
6756 );
6757 } else {
6758 println!(
6759 "{} dry-run @ {}: {} would expire, {} already expired, {} resolved, {} still open",
6760 style::ok("ok"),
6761 report.now,
6762 report.newly_expired.len(),
6763 report.already_expired.len(),
6764 report.already_resolved.len(),
6765 report.still_open.len(),
6766 );
6767 for id in &report.newly_expired {
6768 println!(" · {id}");
6769 }
6770 }
6771 return;
6772 }
6773
6774 let report = crate::calibration::expire_overdue_predictions(&mut project, now_dt);
6775 repo::save_to_path(frontier, &project).unwrap_or_else(|e| fail_return(&e));
6776
6777 if json {
6778 println!(
6779 "{}",
6780 serde_json::to_string_pretty(&json!({
6781 "ok": true,
6782 "command": "predictions.expire",
6783 "report": report,
6784 }))
6785 .expect("serialize predictions.expire")
6786 );
6787 } else {
6788 println!(
6789 "{} @ {}: {} newly expired, {} already expired, {} resolved, {} still open",
6790 style::ok("expired"),
6791 report.now,
6792 report.newly_expired.len(),
6793 report.already_expired.len(),
6794 report.already_resolved.len(),
6795 report.still_open.len(),
6796 );
6797 for id in &report.newly_expired {
6798 println!(" · {id}");
6799 }
6800 }
6801}
6802
6803fn cmd_calibration(frontier: &Path, actor: Option<&str>, json: bool) {
6804 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6805 let records = match actor {
6806 Some(a) => {
6807 crate::calibration::calibration_for_actor(a, &project.predictions, &project.resolutions)
6808 .map(|r| vec![r])
6809 .unwrap_or_default()
6810 }
6811 None => crate::calibration::calibration_records(&project.predictions, &project.resolutions),
6812 };
6813
6814 if json {
6815 println!(
6816 "{}",
6817 serde_json::to_string_pretty(&json!({
6818 "ok": true,
6819 "command": "calibration",
6820 "frontier": frontier.display().to_string(),
6821 "filter_actor": actor,
6822 "records": records,
6823 }))
6824 .expect("serialize calibration")
6825 );
6826 return;
6827 }
6828
6829 println!();
6830 println!(
6831 " {}",
6832 format!("VELA · CALIBRATION · {}", frontier.display())
6833 .to_uppercase()
6834 .dimmed()
6835 );
6836 println!(" {}", style::tick_row(60));
6837 if records.is_empty() {
6838 println!(" (no calibration records)");
6839 return;
6840 }
6841 for r in &records {
6842 println!(" · {}", r.actor);
6843 println!(
6844 " predictions: {} resolved: {} hits: {}",
6845 r.n_predictions, r.n_resolved, r.n_hit
6846 );
6847 match r.hit_rate {
6848 Some(h) => println!(" hit rate: {:.1}%", h * 100.0),
6849 None => println!(" hit rate: n/a"),
6850 }
6851 match r.brier_score {
6852 Some(b) => println!(
6853 " brier: {:.4} (lower is better; 0.25 = chance)",
6854 b
6855 ),
6856 None => println!(" brier: n/a"),
6857 }
6858 match r.log_score {
6859 Some(l) => println!(
6860 " log score: {:.4} (higher is better; 0 = perfect)",
6861 l
6862 ),
6863 None => println!(" log score: n/a"),
6864 }
6865 }
6866}
6867
6868#[allow(clippy::too_many_arguments)]
6870fn cmd_dataset_add(
6871 frontier: &Path,
6872 name: &str,
6873 version: Option<&str>,
6874 content_hash: &str,
6875 url: Option<&str>,
6876 license: Option<&str>,
6877 source_title: &str,
6878 doi: Option<&str>,
6879 row_count: Option<u64>,
6880 json: bool,
6881) {
6882 let mut project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
6883
6884 let provenance = crate::bundle::Provenance {
6885 source_type: "data_release".to_string(),
6886 doi: doi.map(|s| s.to_string()),
6887 pmid: None,
6888 pmc: None,
6889 openalex_id: None,
6890 url: url.map(|s| s.to_string()),
6891 title: source_title.to_string(),
6892 authors: Vec::new(),
6893 year: None,
6894 journal: None,
6895 license: license.map(|s| s.to_string()),
6896 publisher: None,
6897 funders: Vec::new(),
6898 extraction: crate::bundle::Extraction {
6899 method: "manual_curation".to_string(),
6900 model: None,
6901 model_version: None,
6902 extracted_at: chrono::Utc::now().to_rfc3339(),
6903 extractor_version: env!("CARGO_PKG_VERSION").to_string(),
6904 },
6905 review: None,
6906 citation_count: None,
6907 };
6908
6909 let mut dataset = crate::bundle::Dataset::new(
6910 name.to_string(),
6911 version.map(|s| s.to_string()),
6912 content_hash.to_string(),
6913 url.map(|s| s.to_string()),
6914 license.map(|s| s.to_string()),
6915 provenance,
6916 );
6917 dataset.row_count = row_count;
6918
6919 if project.datasets.iter().any(|d| d.id == dataset.id) {
6920 if json {
6921 println!(
6922 "{}",
6923 serde_json::to_string_pretty(&json!({
6924 "ok": false,
6925 "command": "dataset.add",
6926 "reason": "dataset_already_exists",
6927 "id": dataset.id,
6928 }))
6929 .expect("serialize")
6930 );
6931 } else {
6932 println!(
6933 "{} dataset {} already exists in {}; skipping.",
6934 style::warn("dataset"),
6935 dataset.id,
6936 frontier.display()
6937 );
6938 }
6939 return;
6940 }
6941
6942 let new_id = dataset.id.clone();
6943 project.datasets.push(dataset);
6944 repo::save_to_path(frontier, &project).unwrap_or_else(|e| fail_return(&e));
6945
6946 if json {
6947 println!(
6948 "{}",
6949 serde_json::to_string_pretty(&json!({
6950 "ok": true,
6951 "command": "dataset.add",
6952 "id": new_id,
6953 "name": name,
6954 "version": version,
6955 "frontier": frontier.display().to_string(),
6956 }))
6957 .expect("failed to serialize dataset.add result")
6958 );
6959 } else {
6960 println!();
6961 println!(
6962 " {}",
6963 format!("VELA · DATASET · {}", new_id)
6964 .to_uppercase()
6965 .dimmed()
6966 );
6967 println!(" {}", style::tick_row(60));
6968 println!(" name: {name}");
6969 if let Some(v) = version {
6970 println!(" version: {v}");
6971 }
6972 println!(" content_hash: {content_hash}");
6973 if let Some(u) = url {
6974 println!(" url: {u}");
6975 }
6976 println!(" source: {source_title}");
6977 println!();
6978 println!(
6979 " {} dataset recorded in {}",
6980 style::ok("ok"),
6981 frontier.display()
6982 );
6983 }
6984}
6985
6986#[allow(clippy::too_many_arguments)]
6992fn cmd_negative_result_add(
6993 frontier: &Path,
6994 kind: &str,
6995 deposited_by: &str,
6996 reason: &str,
6997 conditions_text: &str,
6998 notes: &str,
6999 targets: Vec<String>,
7000 endpoint: Option<&str>,
7001 intervention: Option<&str>,
7002 comparator: Option<&str>,
7003 population: Option<&str>,
7004 n_enrolled: Option<u32>,
7005 power: Option<f64>,
7006 ci_lower: Option<f64>,
7007 ci_upper: Option<f64>,
7008 effect_size_threshold: Option<f64>,
7009 registry_id: Option<&str>,
7010 reagent: Option<&str>,
7011 observation: Option<&str>,
7012 attempts: Option<u32>,
7013 source_title: &str,
7014 doi: Option<&str>,
7015 url: Option<&str>,
7016 year: Option<i32>,
7017 json: bool,
7018) {
7019 let nr_kind = match kind {
7020 "registered_trial" => {
7021 let endpoint =
7022 endpoint.unwrap_or_else(|| fail_return("--endpoint required for registered_trial"));
7023 let intervention = intervention
7024 .unwrap_or_else(|| fail_return("--intervention required for registered_trial"));
7025 let comparator = comparator
7026 .unwrap_or_else(|| fail_return("--comparator required for registered_trial"));
7027 let population = population
7028 .unwrap_or_else(|| fail_return("--population required for registered_trial"));
7029 let n_enrolled = n_enrolled
7030 .unwrap_or_else(|| fail_return("--n-enrolled required for registered_trial"));
7031 let power =
7032 power.unwrap_or_else(|| fail_return("--power required for registered_trial"));
7033 let ci_lower =
7034 ci_lower.unwrap_or_else(|| fail_return("--ci-lower required for registered_trial"));
7035 let ci_upper =
7036 ci_upper.unwrap_or_else(|| fail_return("--ci-upper required for registered_trial"));
7037 crate::bundle::NegativeResultKind::RegisteredTrial {
7038 endpoint: endpoint.to_string(),
7039 intervention: intervention.to_string(),
7040 comparator: comparator.to_string(),
7041 population: population.to_string(),
7042 n_enrolled,
7043 power,
7044 effect_size_ci: (ci_lower, ci_upper),
7045 effect_size_threshold,
7046 registry_id: registry_id.map(|s| s.to_string()),
7047 }
7048 }
7049 "exploratory" => {
7050 let reagent =
7051 reagent.unwrap_or_else(|| fail_return("--reagent required for exploratory"));
7052 let observation = observation
7053 .unwrap_or_else(|| fail_return("--observation required for exploratory"));
7054 let attempts =
7055 attempts.unwrap_or_else(|| fail_return("--attempts required for exploratory"));
7056 crate::bundle::NegativeResultKind::Exploratory {
7057 reagent: reagent.to_string(),
7058 observation: observation.to_string(),
7059 attempts,
7060 }
7061 }
7062 other => fail_return(&format!(
7063 "--kind must be 'registered_trial' or 'exploratory', got '{other}'"
7064 )),
7065 };
7066
7067 let conditions = crate::bundle::Conditions {
7068 text: conditions_text.to_string(),
7069 species_verified: Vec::new(),
7070 species_unverified: Vec::new(),
7071 in_vitro: false,
7072 in_vivo: false,
7073 human_data: false,
7074 clinical_trial: matches!(kind, "registered_trial"),
7075 concentration_range: None,
7076 duration: None,
7077 age_group: None,
7078 cell_type: None,
7079 };
7080
7081 let provenance = crate::bundle::Provenance {
7082 source_type: if matches!(kind, "registered_trial") {
7083 "clinical_trial".to_string()
7084 } else {
7085 "lab_notebook".to_string()
7086 },
7087 doi: doi.map(|s| s.to_string()),
7088 pmid: None,
7089 pmc: None,
7090 openalex_id: None,
7091 url: url.map(|s| s.to_string()),
7092 title: source_title.to_string(),
7093 authors: Vec::new(),
7094 year,
7095 journal: None,
7096 license: None,
7097 publisher: None,
7098 funders: Vec::new(),
7099 extraction: crate::bundle::Extraction {
7100 method: "manual_curation".to_string(),
7101 model: None,
7102 model_version: None,
7103 extracted_at: chrono::Utc::now().to_rfc3339(),
7104 extractor_version: env!("CARGO_PKG_VERSION").to_string(),
7105 },
7106 review: None,
7107 citation_count: None,
7108 };
7109
7110 let report = state::add_negative_result(
7111 frontier,
7112 nr_kind,
7113 targets,
7114 deposited_by,
7115 conditions,
7116 provenance,
7117 notes,
7118 reason,
7119 )
7120 .unwrap_or_else(|e| fail_return(&e));
7121
7122 if json {
7123 println!(
7124 "{}",
7125 serde_json::to_string_pretty(&report).expect("serialize report")
7126 );
7127 } else {
7128 println!();
7129 println!(
7130 " {}",
7131 format!("VELA · NEGATIVE-RESULT · {}", report.finding_id)
7132 .to_uppercase()
7133 .dimmed()
7134 );
7135 println!(" {}", style::tick_row(60));
7136 println!(" kind: {kind}");
7137 println!(" deposited_by: {deposited_by}");
7138 if let Some(ev) = &report.applied_event_id {
7139 println!(" event: {ev}");
7140 }
7141 println!(
7142 " {} negative_result deposited in {}",
7143 style::ok("ok"),
7144 frontier.display()
7145 );
7146 }
7147}
7148
7149fn cmd_negative_results(frontier: &Path, target: Option<&str>, json: bool) {
7152 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7153 let filtered: Vec<&crate::bundle::NegativeResult> = project
7154 .negative_results
7155 .iter()
7156 .filter(|nr| {
7157 target
7158 .map(|t| nr.target_findings.iter().any(|f| f == t))
7159 .unwrap_or(true)
7160 })
7161 .collect();
7162
7163 if json {
7164 println!(
7165 "{}",
7166 serde_json::to_string_pretty(&json!({
7167 "ok": true,
7168 "command": "negative_results",
7169 "frontier": frontier.display().to_string(),
7170 "count": filtered.len(),
7171 "negative_results": filtered,
7172 }))
7173 .expect("serialize negative_results")
7174 );
7175 return;
7176 }
7177
7178 if filtered.is_empty() {
7179 println!(" no negative_results in {}", frontier.display());
7180 return;
7181 }
7182
7183 println!();
7184 println!(
7185 " {} ({})",
7186 "VELA · NEGATIVE RESULTS".dimmed(),
7187 filtered.len()
7188 );
7189 println!(" {}", style::tick_row(60));
7190 for nr in &filtered {
7191 let kind_label = match &nr.kind {
7192 crate::bundle::NegativeResultKind::RegisteredTrial {
7193 endpoint, power, ..
7194 } => format!("trial · {endpoint} · power {power:.2}"),
7195 crate::bundle::NegativeResultKind::Exploratory {
7196 reagent, attempts, ..
7197 } => format!("exploratory · {reagent} · {attempts} attempts"),
7198 };
7199 let retracted = if nr.retracted { " [retracted]" } else { "" };
7200 let review = nr
7201 .review_state
7202 .as_ref()
7203 .map(|s| format!(" [{s:?}]"))
7204 .unwrap_or_default();
7205 println!(" {}{}{}", nr.id, retracted, review);
7206 println!(" {kind_label}");
7207 if !nr.target_findings.is_empty() {
7208 println!(" targets: {}", nr.target_findings.join(", "));
7209 }
7210 }
7211 println!();
7212}
7213
7214#[allow(clippy::too_many_arguments)]
7216fn cmd_tier_set(
7217 frontier: &Path,
7218 object_type: &str,
7219 object_id: &str,
7220 tier: &str,
7221 actor: &str,
7222 reason: &str,
7223 json: bool,
7224) {
7225 let parsed_tier =
7226 crate::access_tier::AccessTier::parse(tier).unwrap_or_else(|e| fail_return(&e));
7227 let report = state::set_tier(frontier, object_type, object_id, parsed_tier, actor, reason)
7228 .unwrap_or_else(|e| fail_return(&e));
7229
7230 if json {
7231 println!(
7232 "{}",
7233 serde_json::to_string_pretty(&report).expect("serialize tier-set report")
7234 );
7235 } else {
7236 println!();
7237 println!(
7238 " {}",
7239 format!("VELA · TIER · {}", object_id)
7240 .to_uppercase()
7241 .dimmed()
7242 );
7243 println!(" {}", style::tick_row(60));
7244 println!(" object_type: {object_type}");
7245 println!(" new_tier: {}", parsed_tier.canonical());
7246 println!(" actor: {actor}");
7247 if let Some(ev) = &report.applied_event_id {
7248 println!(" event: {ev}");
7249 }
7250 println!(" {} tier set in {}", style::ok("ok"), frontier.display());
7251 }
7252}
7253
7254#[allow(clippy::too_many_arguments)]
7256fn cmd_trajectory_create(
7257 frontier: &Path,
7258 deposited_by: &str,
7259 reason: &str,
7260 targets: Vec<String>,
7261 notes: &str,
7262 json: bool,
7263) {
7264 let report = state::create_trajectory(frontier, targets, deposited_by, notes, reason)
7265 .unwrap_or_else(|e| fail_return(&e));
7266
7267 if json {
7268 println!(
7269 "{}",
7270 serde_json::to_string_pretty(&report).expect("serialize trajectory report")
7271 );
7272 } else {
7273 println!();
7274 println!(
7275 " {}",
7276 format!("VELA · TRAJECTORY · {}", report.finding_id)
7277 .to_uppercase()
7278 .dimmed()
7279 );
7280 println!(" {}", style::tick_row(60));
7281 println!(" deposited_by: {deposited_by}");
7282 if let Some(ev) = &report.applied_event_id {
7283 println!(" event: {ev}");
7284 }
7285 println!(
7286 " {} trajectory opened in {}",
7287 style::ok("ok"),
7288 frontier.display()
7289 );
7290 }
7291}
7292
7293#[allow(clippy::too_many_arguments)]
7295fn cmd_trajectory_step(
7296 frontier: &Path,
7297 trajectory_id: &str,
7298 kind: &str,
7299 description: &str,
7300 actor: &str,
7301 reason: &str,
7302 references: Vec<String>,
7303 json: bool,
7304) {
7305 let parsed_kind = match kind {
7306 "hypothesis" => crate::bundle::TrajectoryStepKind::Hypothesis,
7308 "tried" => crate::bundle::TrajectoryStepKind::Tried,
7309 "ruled_out" => crate::bundle::TrajectoryStepKind::RuledOut,
7310 "observed" => crate::bundle::TrajectoryStepKind::Observed,
7311 "refined" => crate::bundle::TrajectoryStepKind::Refined,
7312 "question" => crate::bundle::TrajectoryStepKind::Question,
7314 "context" => crate::bundle::TrajectoryStepKind::Context,
7315 "data" => crate::bundle::TrajectoryStepKind::Data,
7316 "tool" => crate::bundle::TrajectoryStepKind::Tool,
7317 "model" => crate::bundle::TrajectoryStepKind::Model,
7318 "expert" => crate::bundle::TrajectoryStepKind::Expert,
7319 "decision" => crate::bundle::TrajectoryStepKind::Decision,
7320 "protocol" => crate::bundle::TrajectoryStepKind::Protocol,
7321 "output" => crate::bundle::TrajectoryStepKind::Output,
7322 "review" => crate::bundle::TrajectoryStepKind::Review,
7323 "risk" => crate::bundle::TrajectoryStepKind::Risk,
7324 "outcome" => crate::bundle::TrajectoryStepKind::Outcome,
7325 other => fail_return(&format!(
7326 "--kind must be one of: hypothesis|tried|ruled_out|observed|refined (v0.50 legacy) or question|context|data|tool|model|expert|decision|protocol|output|review|risk|outcome (v0.194 vision-taxonomy), got '{other}'"
7327 )),
7328 };
7329 let report = state::append_trajectory_step(
7330 frontier,
7331 trajectory_id,
7332 parsed_kind,
7333 description,
7334 actor,
7335 references,
7336 reason,
7337 )
7338 .unwrap_or_else(|e| fail_return(&e));
7339
7340 if json {
7341 println!(
7342 "{}",
7343 serde_json::to_string_pretty(&report).expect("serialize step report")
7344 );
7345 } else {
7346 println!();
7347 println!(
7348 " {}",
7349 format!("VELA · STEP · {}", report.finding_id)
7350 .to_uppercase()
7351 .dimmed()
7352 );
7353 println!(" {}", style::tick_row(60));
7354 println!(" trajectory: {trajectory_id}");
7355 println!(" kind: {kind}");
7356 println!(" actor: {actor}");
7357 println!(
7358 " {} step appended in {}",
7359 style::ok("ok"),
7360 frontier.display()
7361 );
7362 }
7363}
7364
7365fn cmd_trajectories(frontier: &Path, target: Option<&str>, json: bool) {
7367 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7368 let filtered: Vec<&crate::bundle::Trajectory> = project
7369 .trajectories
7370 .iter()
7371 .filter(|t| {
7372 target
7373 .map(|tg| t.target_findings.iter().any(|f| f == tg))
7374 .unwrap_or(true)
7375 })
7376 .collect();
7377
7378 if json {
7379 println!(
7380 "{}",
7381 serde_json::to_string_pretty(&json!({
7382 "ok": true,
7383 "command": "trajectories",
7384 "frontier": frontier.display().to_string(),
7385 "count": filtered.len(),
7386 "trajectories": filtered,
7387 }))
7388 .expect("serialize trajectories")
7389 );
7390 return;
7391 }
7392
7393 if filtered.is_empty() {
7394 println!(" no trajectories in {}", frontier.display());
7395 return;
7396 }
7397
7398 println!();
7399 println!(" {} ({})", "VELA · TRAJECTORIES".dimmed(), filtered.len());
7400 println!(" {}", style::tick_row(60));
7401 for t in &filtered {
7402 let retracted = if t.retracted { " [retracted]" } else { "" };
7403 let review = t
7404 .review_state
7405 .as_ref()
7406 .map(|s| format!(" [{s:?}]"))
7407 .unwrap_or_default();
7408 println!(" {}{}{}", t.id, retracted, review);
7409 println!(
7410 " {} step(s){}",
7411 t.steps.len(),
7412 if t.target_findings.is_empty() {
7413 String::new()
7414 } else {
7415 format!(" · targets: {}", t.target_findings.join(", "))
7416 }
7417 );
7418 for step in &t.steps {
7419 let label = step.kind.canonical();
7422 let preview: String = step.description.chars().take(80).collect();
7423 println!(" [{label}] {preview}");
7424 }
7425 }
7426 println!();
7427}
7428
7429fn cmd_datasets(frontier: &Path, json: bool) {
7431 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7432 if json {
7433 println!(
7434 "{}",
7435 serde_json::to_string_pretty(&json!({
7436 "ok": true,
7437 "command": "datasets",
7438 "frontier": frontier.display().to_string(),
7439 "count": project.datasets.len(),
7440 "datasets": project.datasets,
7441 }))
7442 .expect("serialize datasets")
7443 );
7444 return;
7445 }
7446 println!();
7447 println!(
7448 " {}",
7449 format!("VELA · DATASETS · {}", frontier.display())
7450 .to_uppercase()
7451 .dimmed()
7452 );
7453 println!(" {}", style::tick_row(60));
7454 if project.datasets.is_empty() {
7455 println!(" (no datasets registered)");
7456 return;
7457 }
7458 for ds in &project.datasets {
7459 let v = ds
7460 .version
7461 .as_deref()
7462 .map(|s| format!("@{s}"))
7463 .unwrap_or_default();
7464 println!(" · {} {}{}", ds.id.dimmed(), ds.name, v);
7465 if let Some(u) = &ds.url {
7466 println!(" url: {}", truncate(u, 80));
7467 }
7468 println!(" hash: {}", truncate(&ds.content_hash, 80));
7469 }
7470}
7471
7472#[allow(clippy::too_many_arguments)]
7474fn cmd_code_add(
7475 frontier: &Path,
7476 language: &str,
7477 repo_url: Option<&str>,
7478 commit: Option<&str>,
7479 path: &str,
7480 content_hash: &str,
7481 line_start: Option<u32>,
7482 line_end: Option<u32>,
7483 entry_point: Option<&str>,
7484 json: bool,
7485) {
7486 let mut project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7487
7488 let line_range = match (line_start, line_end) {
7489 (Some(a), Some(b)) => Some((a, b)),
7490 (Some(a), None) => Some((a, a)),
7491 _ => None,
7492 };
7493
7494 let artifact = crate::bundle::CodeArtifact::new(
7495 language.to_string(),
7496 repo_url.map(|s| s.to_string()),
7497 commit.map(|s| s.to_string()),
7498 path.to_string(),
7499 line_range,
7500 content_hash.to_string(),
7501 entry_point.map(|s| s.to_string()),
7502 );
7503
7504 if project.code_artifacts.iter().any(|c| c.id == artifact.id) {
7505 if json {
7506 println!(
7507 "{}",
7508 serde_json::to_string_pretty(&json!({
7509 "ok": false,
7510 "command": "code.add",
7511 "reason": "artifact_already_exists",
7512 "id": artifact.id,
7513 }))
7514 .expect("serialize")
7515 );
7516 } else {
7517 println!(
7518 "{} code artifact {} already exists in {}; skipping.",
7519 style::warn("code"),
7520 artifact.id,
7521 frontier.display()
7522 );
7523 }
7524 return;
7525 }
7526
7527 let new_id = artifact.id.clone();
7528 project.code_artifacts.push(artifact);
7529 repo::save_to_path(frontier, &project).unwrap_or_else(|e| fail_return(&e));
7530
7531 if json {
7532 println!(
7533 "{}",
7534 serde_json::to_string_pretty(&json!({
7535 "ok": true,
7536 "command": "code.add",
7537 "id": new_id,
7538 "language": language,
7539 "path": path,
7540 "frontier": frontier.display().to_string(),
7541 }))
7542 .expect("failed to serialize code.add result")
7543 );
7544 } else {
7545 println!();
7546 println!(
7547 " {}",
7548 format!("VELA · CODE · {}", new_id).to_uppercase().dimmed()
7549 );
7550 println!(" {}", style::tick_row(60));
7551 println!(" language: {language}");
7552 if let Some(r) = repo_url {
7553 println!(" repo: {r}");
7554 }
7555 if let Some(c) = commit {
7556 println!(" commit: {c}");
7557 }
7558 println!(" path: {path}");
7559 if let Some((a, b)) = line_range {
7560 println!(" lines: {a}-{b}");
7561 }
7562 println!(" content_hash: {content_hash}");
7563 println!();
7564 println!(
7565 " {} code artifact recorded in {}",
7566 style::ok("ok"),
7567 frontier.display()
7568 );
7569 }
7570}
7571
7572fn cmd_code_artifacts(frontier: &Path, json: bool) {
7574 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7575 if json {
7576 println!(
7577 "{}",
7578 serde_json::to_string_pretty(&json!({
7579 "ok": true,
7580 "command": "code-artifacts",
7581 "frontier": frontier.display().to_string(),
7582 "count": project.code_artifacts.len(),
7583 "code_artifacts": project.code_artifacts,
7584 }))
7585 .expect("serialize code-artifacts")
7586 );
7587 return;
7588 }
7589 println!();
7590 println!(
7591 " {}",
7592 format!("VELA · CODE · {}", frontier.display())
7593 .to_uppercase()
7594 .dimmed()
7595 );
7596 println!(" {}", style::tick_row(60));
7597 if project.code_artifacts.is_empty() {
7598 println!(" (no code artifacts registered)");
7599 return;
7600 }
7601 for c in &project.code_artifacts {
7602 let lr = c
7603 .line_range
7604 .map(|(a, b)| format!(":{a}-{b}"))
7605 .unwrap_or_default();
7606 println!(" · {} {} {}{}", c.id.dimmed(), c.language, c.path, lr);
7607 if let Some(r) = &c.repo_url {
7608 println!(" repo: {}", truncate(r, 80));
7609 }
7610 if let Some(g) = &c.git_commit {
7611 println!(" commit: {g}");
7612 }
7613 }
7614}
7615
7616fn sha256_for_bytes(bytes: &[u8]) -> String {
7617 format!("sha256:{}", hex::encode(Sha256::digest(bytes)))
7618}
7619
7620fn sha256_hex_part(content_hash: &str) -> &str {
7621 content_hash.strip_prefix("sha256:").unwrap_or(content_hash)
7622}
7623
7624fn artifact_blob_locator(frontier: &Path, content_hash: &str, bytes: &[u8]) -> Option<String> {
7625 let Ok(repo::VelaSource::VelaRepo(root)) = repo::detect(frontier) else {
7626 return None;
7627 };
7628 let hex = sha256_hex_part(content_hash);
7629 let rel = format!(".vela/artifact-blobs/sha256/{hex}");
7630 let path = root.join(&rel);
7631 if let Some(parent) = path.parent() {
7632 std::fs::create_dir_all(parent).unwrap_or_else(|e| {
7633 fail(&format!(
7634 "Failed to create artifact blob directory {}: {e}",
7635 parent.display()
7636 ))
7637 });
7638 }
7639 if !path.is_file() {
7640 std::fs::write(&path, bytes)
7641 .unwrap_or_else(|e| fail(&format!("Failed to write artifact blob: {e}")));
7642 }
7643 Some(rel)
7644}
7645
7646fn parse_metadata_pairs(pairs: Vec<String>) -> BTreeMap<String, Value> {
7647 let mut out = BTreeMap::new();
7648 for pair in pairs {
7649 let Some((key, value)) = pair.split_once('=') else {
7650 fail(&format!("--metadata must be key=value, got {pair:?}"));
7651 };
7652 let key = key.trim();
7653 if key.is_empty() {
7654 fail("--metadata key must be non-empty");
7655 }
7656 out.insert(key.to_string(), Value::String(value.trim().to_string()));
7657 }
7658 out
7659}
7660
7661fn artifact_source_type(kind: &str) -> &'static str {
7662 match kind {
7663 "clinical_trial_record" | "protocol" => "clinical_trial",
7664 "dataset" => "data_release",
7665 "model_output" => "model_output",
7666 "registry_record" => "database_record",
7667 "lab_file" => "lab_notebook",
7668 _ => "database_record",
7669 }
7670}
7671
7672fn artifact_provenance(
7673 kind: &str,
7674 title: &str,
7675 url: Option<&str>,
7676 doi: Option<&str>,
7677 license: Option<&str>,
7678) -> crate::bundle::Provenance {
7679 crate::bundle::Provenance {
7680 source_type: artifact_source_type(kind).to_string(),
7681 doi: doi.map(str::to_string),
7682 pmid: None,
7683 pmc: None,
7684 openalex_id: None,
7685 url: url.map(str::to_string),
7686 title: title.to_string(),
7687 authors: Vec::new(),
7688 year: None,
7689 journal: None,
7690 license: license.map(str::to_string),
7691 publisher: None,
7692 funders: Vec::new(),
7693 extraction: crate::bundle::Extraction {
7694 method: "artifact_deposit".to_string(),
7695 model: None,
7696 model_version: None,
7697 extracted_at: chrono::Utc::now().to_rfc3339(),
7698 extractor_version: env!("CARGO_PKG_VERSION").to_string(),
7699 },
7700 review: None,
7701 citation_count: None,
7702 }
7703}
7704
7705#[allow(clippy::too_many_arguments)]
7706fn cmd_artifact_add(
7707 frontier: &Path,
7708 kind: &str,
7709 name: &str,
7710 file: Option<&Path>,
7711 url: Option<&str>,
7712 content_hash: Option<&str>,
7713 media_type: Option<&str>,
7714 license: Option<&str>,
7715 source_title: Option<&str>,
7716 source_url: Option<&str>,
7717 doi: Option<&str>,
7718 target: Vec<String>,
7719 metadata: Vec<String>,
7720 access_tier: &str,
7721 deposited_by: &str,
7722 reason: &str,
7723 json_out: bool,
7724) {
7725 let tier =
7726 crate::access_tier::AccessTier::parse(access_tier).unwrap_or_else(|e| fail_return(&e));
7727 let mut size_bytes = None;
7728 let mut storage_mode = "pointer".to_string();
7729 let mut locator = url.map(str::to_string);
7730 let mut computed_hash = content_hash.map(str::to_string);
7731
7732 if let Some(path) = file {
7733 let bytes = std::fs::read(path)
7734 .unwrap_or_else(|e| fail(&format!("Failed to read artifact file: {e}")));
7735 let actual_hash = sha256_for_bytes(&bytes);
7736 if let Some(expected) = content_hash {
7737 let expected_hex = sha256_hex_part(expected);
7738 let actual_hex = sha256_hex_part(&actual_hash);
7739 if !expected_hex.eq_ignore_ascii_case(actual_hex) {
7740 fail(&format!(
7741 "--content-hash does not match file bytes: expected {expected}, got {actual_hash}"
7742 ));
7743 }
7744 }
7745 size_bytes = Some(bytes.len() as u64);
7746 computed_hash = Some(actual_hash.clone());
7747 if let Some(rel) = artifact_blob_locator(frontier, &actual_hash, &bytes) {
7748 storage_mode = "local_blob".to_string();
7749 locator = Some(rel);
7750 } else {
7751 storage_mode = "local_file".to_string();
7752 locator = Some(path.display().to_string());
7753 }
7754 }
7755
7756 let Some(content_hash) = computed_hash else {
7757 fail("Provide --content-hash unless --file is present.");
7758 };
7759 let content_hash_for_print = content_hash.clone();
7760 if file.is_none() && url.is_some() {
7761 storage_mode = "remote".to_string();
7762 }
7763
7764 let source_url_effective = source_url.or(url);
7765 let source_title = source_title.unwrap_or(name);
7766 let provenance = artifact_provenance(kind, source_title, source_url_effective, doi, license);
7767 let metadata = parse_metadata_pairs(metadata);
7768 let artifact = crate::bundle::Artifact::new(
7769 kind.to_string(),
7770 name.to_string(),
7771 content_hash,
7772 size_bytes,
7773 media_type.map(str::to_string),
7774 storage_mode,
7775 locator,
7776 source_url_effective.map(str::to_string),
7777 license.map(str::to_string),
7778 target,
7779 provenance,
7780 metadata,
7781 tier,
7782 )
7783 .unwrap_or_else(|e| fail_return(&e));
7784
7785 let artifact_id = artifact.id.clone();
7786 let report = state::add_artifact(frontier, artifact, deposited_by, reason)
7787 .unwrap_or_else(|e| fail_return(&e));
7788
7789 if json_out {
7790 println!(
7791 "{}",
7792 serde_json::to_string_pretty(&json!({
7793 "ok": true,
7794 "command": "artifact.add",
7795 "id": artifact_id,
7796 "frontier": frontier.display().to_string(),
7797 "event": report.applied_event_id,
7798 }))
7799 .expect("serialize artifact.add")
7800 );
7801 } else {
7802 println!();
7803 println!(
7804 " {}",
7805 format!("VELA · ARTIFACT · {}", artifact_id)
7806 .to_uppercase()
7807 .dimmed()
7808 );
7809 println!(" {}", style::tick_row(60));
7810 println!(" kind: {kind}");
7811 println!(" name: {name}");
7812 println!(" hash: {content_hash_for_print}");
7813 println!(
7814 " {} artifact recorded in {}",
7815 style::ok("ok"),
7816 frontier.display()
7817 );
7818 }
7819}
7820
7821fn cmd_artifacts(frontier: &Path, target: Option<&str>, json_out: bool) {
7822 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7823 let filtered: Vec<&crate::bundle::Artifact> = project
7824 .artifacts
7825 .iter()
7826 .filter(|artifact| {
7827 target
7828 .map(|t| artifact.target_findings.iter().any(|f| f == t))
7829 .unwrap_or(true)
7830 })
7831 .collect();
7832
7833 if json_out {
7834 println!(
7835 "{}",
7836 serde_json::to_string_pretty(&json!({
7837 "ok": true,
7838 "command": "artifacts",
7839 "frontier": frontier.display().to_string(),
7840 "count": filtered.len(),
7841 "artifacts": filtered,
7842 }))
7843 .expect("serialize artifacts")
7844 );
7845 return;
7846 }
7847
7848 println!();
7849 println!(
7850 " {}",
7851 format!("VELA · ARTIFACTS · {}", frontier.display())
7852 .to_uppercase()
7853 .dimmed()
7854 );
7855 println!(" {}", style::tick_row(60));
7856 if filtered.is_empty() {
7857 println!(" (no artifacts registered)");
7858 return;
7859 }
7860 for artifact in filtered {
7861 println!(
7862 " · {} {} · {}",
7863 artifact.id.dimmed(),
7864 artifact.kind,
7865 artifact.name
7866 );
7867 if let Some(locator) = &artifact.locator {
7868 println!(" locator: {}", truncate(locator, 88));
7869 }
7870 if !artifact.target_findings.is_empty() {
7871 println!(" targets: {}", artifact.target_findings.join(", "));
7872 }
7873 }
7874}
7875
7876fn cmd_artifact_audit(frontier: &Path, json_out: bool) {
7877 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7878 let audit = crate::artifact_audit::audit_artifacts(frontier, &project);
7879 if json_out {
7880 println!(
7881 "{}",
7882 serde_json::to_string_pretty(&audit).expect("serialize artifact audit")
7883 );
7884 if !audit.ok {
7885 std::process::exit(1);
7886 }
7887 return;
7888 }
7889
7890 println!();
7891 println!(
7892 " {}",
7893 format!("VELA · ARTIFACT AUDIT · {}", frontier.display())
7894 .to_uppercase()
7895 .dimmed()
7896 );
7897 println!(" {}", style::tick_row(60));
7898 println!(" artifacts: {}", audit.artifact_count);
7899 println!(" checked local blobs: {}", audit.checked_local_blobs);
7900 println!(" local blob bytes: {}", audit.local_blob_bytes);
7901 if !audit.by_kind.is_empty() {
7902 let kinds = audit
7903 .by_kind
7904 .iter()
7905 .map(|(kind, count)| format!("{kind}:{count}"))
7906 .collect::<Vec<_>>()
7907 .join(", ");
7908 println!(" kinds: {kinds}");
7909 }
7910 if audit.ok {
7911 println!(" {} artifact audit passed.", style::ok("ok"));
7912 return;
7913 }
7914 for issue in &audit.issues {
7915 println!(
7916 " {} {} {}: {}",
7917 style::lost("invalid"),
7918 issue.id,
7919 issue.field,
7920 issue.message
7921 );
7922 }
7923 std::process::exit(1);
7924}
7925
7926fn cmd_decision_brief(frontier: &Path, json_out: bool) {
7927 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7928 let report = decision::load_decision_brief(frontier, &project);
7929 if json_out {
7930 println!(
7931 "{}",
7932 serde_json::to_string_pretty(&report).expect("serialize decision brief report")
7933 );
7934 if !report.ok {
7935 std::process::exit(1);
7936 }
7937 return;
7938 }
7939 println!();
7940 println!(
7941 " {}",
7942 format!("VELA · DECISION BRIEF · {}", project.project.name)
7943 .to_uppercase()
7944 .dimmed()
7945 );
7946 println!(" {}", style::tick_row(60));
7947 if !report.ok {
7948 print_projection_issues(&report.issues, report.error.as_deref());
7949 std::process::exit(1);
7950 }
7951 let brief = report
7952 .projection
7953 .as_ref()
7954 .expect("ok decision report carries projection");
7955 for question in &brief.questions {
7956 println!(" · {} · {}", question.id.dimmed(), question.title);
7957 println!(" answer: {}", wrap_line(&question.short_answer, 82));
7958 println!(" caveat: {}", wrap_line(&question.caveat, 82));
7959 println!(" support: {}", question.supporting_findings.join(", "));
7960 if !question.tension_findings.is_empty() {
7961 println!(" tensions: {}", question.tension_findings.join(", "));
7962 }
7963 if !question.gap_findings.is_empty() {
7964 println!(" gaps: {}", question.gap_findings.join(", "));
7965 }
7966 if !question.artifact_ids.is_empty() {
7967 println!(" artifacts: {}", question.artifact_ids.join(", "));
7968 }
7969 println!(
7970 " would change: {}",
7971 wrap_line(&question.what_would_change_this_answer, 82)
7972 );
7973 }
7974}
7975
7976fn cmd_trial_summary(frontier: &Path, json_out: bool) {
7977 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
7978 let report = decision::load_trial_outcomes(frontier, &project);
7979 if json_out {
7980 println!(
7981 "{}",
7982 serde_json::to_string_pretty(&report).expect("serialize trial summary report")
7983 );
7984 if !report.ok {
7985 std::process::exit(1);
7986 }
7987 return;
7988 }
7989 println!();
7990 println!(
7991 " {}",
7992 format!("VELA · TRIAL SUMMARY · {}", project.project.name)
7993 .to_uppercase()
7994 .dimmed()
7995 );
7996 println!(" {}", style::tick_row(60));
7997 if !report.ok {
7998 print_projection_issues(&report.issues, report.error.as_deref());
7999 std::process::exit(1);
8000 }
8001 let outcomes = report
8002 .projection
8003 .as_ref()
8004 .expect("ok trial report carries projection");
8005 for row in &outcomes.rows {
8006 println!(" · {} · {} ({})", row.id.dimmed(), row.program, row.drug);
8007 println!(" population: {}", wrap_line(&row.population, 82));
8008 println!(" endpoint: {}", wrap_line(&row.primary_endpoint, 82));
8009 println!(" cognition: {}", wrap_line(&row.cognitive_result, 82));
8010 println!(" biomarker: {}", wrap_line(&row.biomarker_result, 82));
8011 println!(" risk: {}", wrap_line(&row.aria_or_safety_result, 82));
8012 println!(" status: {}", wrap_line(&row.regulatory_status, 82));
8013 if !row.finding_ids.is_empty() {
8014 println!(" findings: {}", row.finding_ids.join(", "));
8015 }
8016 if !row.artifact_ids.is_empty() {
8017 println!(" artifacts: {}", row.artifact_ids.join(", "));
8018 }
8019 }
8020}
8021
8022fn cmd_source_verification(frontier: &Path, json_out: bool) {
8023 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
8024 let report = decision::load_source_verification(frontier, &project);
8025 if json_out {
8026 println!(
8027 "{}",
8028 serde_json::to_string_pretty(&report).expect("serialize source verification report")
8029 );
8030 if !report.ok {
8031 std::process::exit(1);
8032 }
8033 return;
8034 }
8035 println!();
8036 println!(
8037 " {}",
8038 format!("VELA · SOURCE VERIFICATION · {}", project.project.name)
8039 .to_uppercase()
8040 .dimmed()
8041 );
8042 println!(" {}", style::tick_row(60));
8043 if !report.ok {
8044 print_projection_issues(&report.issues, report.error.as_deref());
8045 std::process::exit(1);
8046 }
8047 let verification = report
8048 .projection
8049 .as_ref()
8050 .expect("ok source verification report carries projection");
8051 println!(" verified_at: {}", verification.verified_at);
8052 for source in &verification.sources {
8053 println!(" · {} · {}", source.id.dimmed(), source.title);
8054 println!(" agency: {}", source.agency);
8055 println!(" url: {}", truncate(&source.url, 88));
8056 println!(" status: {}", wrap_line(&source.current_status, 82));
8057 }
8058}
8059
8060fn cmd_source_ingest_plan(frontier: &Path, json_out: bool) {
8061 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
8062 let report = decision::load_source_ingest_plan(frontier, &project);
8063 if json_out {
8064 println!(
8065 "{}",
8066 serde_json::to_string_pretty(&report).expect("serialize source ingest plan report")
8067 );
8068 if !report.ok {
8069 std::process::exit(1);
8070 }
8071 return;
8072 }
8073 println!();
8074 println!(
8075 " {}",
8076 format!("VELA · SOURCE INGEST PLAN · {}", project.project.name)
8077 .to_uppercase()
8078 .dimmed()
8079 );
8080 println!(" {}", style::tick_row(60));
8081 if !report.ok {
8082 print_projection_issues(&report.issues, report.error.as_deref());
8083 std::process::exit(1);
8084 }
8085 let plan = report
8086 .projection
8087 .as_ref()
8088 .expect("ok source ingest plan report carries projection");
8089 println!(" verified_at: {}", plan.verified_at);
8090 println!(" entries: {}", plan.entries.len());
8091 for entry in &plan.entries {
8092 println!(
8093 " · {} · {} · {} · {}",
8094 entry.id.dimmed(),
8095 entry.category,
8096 entry.priority,
8097 entry.ingest_status
8098 );
8099 println!(" name: {}", wrap_line(&entry.name, 82));
8100 println!(" locator: {}", truncate(&entry.locator, 88));
8101 println!(" use: {}", wrap_line(&entry.target_use, 82));
8102 if let Some(id) = &entry.current_frontier_artifact_id {
8103 println!(" artifact: {id}");
8104 }
8105 if !entry.target_findings.is_empty() {
8106 println!(" findings: {}", entry.target_findings.join(", "));
8107 }
8108 }
8109}
8110
8111fn print_projection_issues(issues: &[decision::ProjectionIssue], error: Option<&str>) {
8112 if let Some(error) = error {
8113 println!(" {} {error}", style::lost("unavailable"));
8114 }
8115 for issue in issues {
8116 println!(
8117 " {} {}: {}",
8118 style::lost("invalid"),
8119 issue.path,
8120 issue.message
8121 );
8122 }
8123}
8124
8125fn wrap_line(text: &str, max_chars: usize) -> String {
8126 if text.chars().count() <= max_chars {
8127 return text.to_string();
8128 }
8129 let mut out = String::new();
8130 let mut line_len = 0usize;
8131 for word in text.split_whitespace() {
8132 let word_len = word.chars().count();
8133 if line_len > 0 && line_len + 1 + word_len > max_chars {
8134 out.push('\n');
8135 out.push_str(" ");
8136 out.push_str(word);
8137 line_len = word_len;
8138 } else {
8139 if line_len > 0 {
8140 out.push(' ');
8141 line_len += 1;
8142 }
8143 out.push_str(word);
8144 line_len += word_len;
8145 }
8146 }
8147 out
8148}
8149
8150fn clinical_str<'a>(study: &'a Value, pointer: &str) -> Option<&'a str> {
8151 study.pointer(pointer).and_then(Value::as_str)
8152}
8153
8154fn clinical_string_array(study: &Value, pointer: &str) -> Vec<String> {
8155 study
8156 .pointer(pointer)
8157 .and_then(Value::as_array)
8158 .map(|items| {
8159 items
8160 .iter()
8161 .filter_map(Value::as_str)
8162 .map(str::to_string)
8163 .collect()
8164 })
8165 .unwrap_or_default()
8166}
8167
8168fn clinical_named_array(study: &Value, pointer: &str, field: &str) -> Vec<String> {
8169 study
8170 .pointer(pointer)
8171 .and_then(Value::as_array)
8172 .map(|items| {
8173 items
8174 .iter()
8175 .filter_map(|item| item.get(field).and_then(Value::as_str))
8176 .map(str::to_string)
8177 .collect()
8178 })
8179 .unwrap_or_default()
8180}
8181
8182fn insert_string_vec_metadata(
8183 metadata: &mut BTreeMap<String, Value>,
8184 key: &str,
8185 values: Vec<String>,
8186) {
8187 if values.is_empty() {
8188 return;
8189 }
8190 metadata.insert(
8191 key.to_string(),
8192 Value::Array(values.into_iter().map(Value::String).collect()),
8193 );
8194}
8195
8196async fn cmd_clinical_trial_import(
8197 frontier: &Path,
8198 nct_id: &str,
8199 input_json: Option<&Path>,
8200 target: Vec<String>,
8201 deposited_by: &str,
8202 reason: &str,
8203 license: &str,
8204 json_out: bool,
8205) {
8206 let api_url = format!("https://clinicaltrials.gov/api/v2/studies/{nct_id}");
8207 let raw = if let Some(path) = input_json {
8208 std::fs::read_to_string(path)
8209 .unwrap_or_else(|e| fail(&format!("Failed to read ClinicalTrials.gov JSON: {e}")))
8210 } else {
8211 let response = reqwest::get(&api_url).await.unwrap_or_else(|e| {
8212 fail(&format!(
8213 "Failed to fetch ClinicalTrials.gov record {nct_id}: {e}"
8214 ))
8215 });
8216 let response = response.error_for_status().unwrap_or_else(|e| {
8217 fail(&format!(
8218 "Failed to fetch ClinicalTrials.gov record {nct_id}: {e}"
8219 ))
8220 });
8221 response.text().await.unwrap_or_else(|e| {
8222 fail(&format!(
8223 "Failed to read ClinicalTrials.gov record {nct_id}: {e}"
8224 ))
8225 })
8226 };
8227 let study: Value = serde_json::from_str(&raw)
8228 .unwrap_or_else(|e| fail(&format!("Failed to parse ClinicalTrials.gov JSON: {e}")));
8229 let canonical_bytes = crate::canonical::to_canonical_bytes(&study)
8230 .unwrap_or_else(|e| fail(&format!("Failed to canonicalize trial JSON: {e}")));
8231 let content_hash = sha256_for_bytes(&canonical_bytes);
8232 let locator = artifact_blob_locator(frontier, &content_hash, &canonical_bytes)
8233 .unwrap_or_else(|| api_url.clone());
8234 let storage_mode = if locator.starts_with(".vela/") {
8235 "local_blob"
8236 } else {
8237 "remote"
8238 };
8239
8240 let parsed_nct = clinical_str(&study, "/protocolSection/identificationModule/nctId")
8241 .unwrap_or(nct_id)
8242 .to_string();
8243 let title = clinical_str(&study, "/protocolSection/identificationModule/briefTitle")
8244 .or_else(|| {
8245 clinical_str(
8246 &study,
8247 "/protocolSection/identificationModule/officialTitle",
8248 )
8249 })
8250 .unwrap_or(nct_id);
8251 let public_url = format!("https://clinicaltrials.gov/study/{parsed_nct}");
8252 let mut metadata = BTreeMap::new();
8253 metadata.insert("nct_id".to_string(), Value::String(parsed_nct.clone()));
8254 metadata.insert(
8255 "source_api".to_string(),
8256 Value::String("clinicaltrials.gov-v2".to_string()),
8257 );
8258 metadata.insert(
8259 "retrieved_at".to_string(),
8260 Value::String(chrono::Utc::now().to_rfc3339()),
8261 );
8262 for (key, pointer) in [
8263 (
8264 "overall_status",
8265 "/protocolSection/statusModule/overallStatus",
8266 ),
8267 (
8268 "start_date",
8269 "/protocolSection/statusModule/startDateStruct/date",
8270 ),
8271 (
8272 "completion_date",
8273 "/protocolSection/statusModule/completionDateStruct/date",
8274 ),
8275 ] {
8276 if let Some(value) = clinical_str(&study, pointer) {
8277 metadata.insert(key.to_string(), Value::String(value.to_string()));
8278 }
8279 }
8280 insert_string_vec_metadata(
8281 &mut metadata,
8282 "phases",
8283 clinical_string_array(&study, "/protocolSection/designModule/phases"),
8284 );
8285 insert_string_vec_metadata(
8286 &mut metadata,
8287 "conditions",
8288 clinical_string_array(&study, "/protocolSection/conditionsModule/conditions"),
8289 );
8290 insert_string_vec_metadata(
8291 &mut metadata,
8292 "interventions",
8293 clinical_named_array(
8294 &study,
8295 "/protocolSection/armsInterventionsModule/interventions",
8296 "name",
8297 ),
8298 );
8299 insert_string_vec_metadata(
8300 &mut metadata,
8301 "primary_outcomes",
8302 clinical_named_array(
8303 &study,
8304 "/protocolSection/outcomesModule/primaryOutcomes",
8305 "measure",
8306 ),
8307 );
8308 if let Some(has_results) = study.get("hasResults").and_then(Value::as_bool) {
8309 metadata.insert("has_results".to_string(), Value::Bool(has_results));
8310 }
8311
8312 let provenance = artifact_provenance(
8313 "clinical_trial_record",
8314 title,
8315 Some(&public_url),
8316 None,
8317 Some(license),
8318 );
8319 let artifact = crate::bundle::Artifact::new(
8320 "clinical_trial_record",
8321 title.to_string(),
8322 content_hash,
8323 Some(canonical_bytes.len() as u64),
8324 Some("application/json".to_string()),
8325 storage_mode.to_string(),
8326 Some(locator),
8327 Some(public_url.clone()),
8328 Some(license.to_string()),
8329 target,
8330 provenance,
8331 metadata,
8332 crate::access_tier::AccessTier::Public,
8333 )
8334 .unwrap_or_else(|e| fail_return(&e));
8335 let artifact_id = artifact.id.clone();
8336 let report = state::add_artifact(frontier, artifact, deposited_by, reason)
8337 .unwrap_or_else(|e| fail_return(&e));
8338
8339 if json_out {
8340 println!(
8341 "{}",
8342 serde_json::to_string_pretty(&json!({
8343 "ok": true,
8344 "command": "clinical-trial-import",
8345 "nct_id": parsed_nct,
8346 "id": artifact_id,
8347 "frontier": frontier.display().to_string(),
8348 "event": report.applied_event_id,
8349 "source_url": public_url,
8350 }))
8351 .expect("serialize clinical-trial-import")
8352 );
8353 } else {
8354 println!();
8355 println!(
8356 " {}",
8357 format!("VELA · CLINICAL TRIAL · {}", artifact_id)
8358 .to_uppercase()
8359 .dimmed()
8360 );
8361 println!(" {}", style::tick_row(60));
8362 println!(" nct_id: {parsed_nct}");
8363 println!(" title: {}", truncate(title, 96));
8364 println!(" source: {public_url}");
8365 println!(
8366 " {} trial record imported into {}",
8367 style::ok("ok"),
8368 frontier.display()
8369 );
8370 }
8371}
8372
8373#[allow(clippy::too_many_arguments)]
8380fn cmd_replicate(
8381 frontier: &Path,
8382 target: &str,
8383 outcome: &str,
8384 attempted_by: &str,
8385 conditions_text: &str,
8386 source_title: &str,
8387 doi: Option<&str>,
8388 pmid: Option<&str>,
8389 sample_size: Option<&str>,
8390 note: &str,
8391 previous_attempt: Option<&str>,
8392 no_cascade: bool,
8393 json: bool,
8394) {
8395 if !crate::bundle::VALID_REPLICATION_OUTCOMES.contains(&outcome) {
8396 fail(&format!(
8397 "invalid outcome '{outcome}'; valid: {:?}",
8398 crate::bundle::VALID_REPLICATION_OUTCOMES
8399 ));
8400 }
8401 if !target.starts_with("vf_") {
8402 fail(&format!("target '{target}' is not a vf_ finding id"));
8403 }
8404
8405 let mut project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
8406
8407 if !project.findings.iter().any(|f| f.id == target) {
8408 fail(&format!(
8409 "target finding '{target}' not present in frontier '{}'",
8410 frontier.display()
8411 ));
8412 }
8413
8414 let lower = conditions_text.to_lowercase();
8419 let conditions = crate::bundle::Conditions {
8420 text: conditions_text.to_string(),
8421 species_verified: Vec::new(),
8422 species_unverified: Vec::new(),
8423 in_vitro: lower.contains("in vitro") || lower.contains("ipsc"),
8424 in_vivo: lower.contains("in vivo") || lower.contains("mouse") || lower.contains("rat"),
8425 human_data: lower.contains("human")
8426 || lower.contains("clinical")
8427 || lower.contains("patient"),
8428 clinical_trial: lower.contains("clinical trial") || lower.contains("phase "),
8429 concentration_range: None,
8430 duration: None,
8431 age_group: None,
8432 cell_type: None,
8433 };
8434
8435 let evidence = crate::bundle::Evidence {
8436 evidence_type: "experimental".to_string(),
8437 model_system: String::new(),
8438 species: None,
8439 method: "replication_attempt".to_string(),
8440 sample_size: sample_size.map(|s| s.to_string()),
8441 effect_size: None,
8442 p_value: None,
8443 replicated: outcome == "replicated",
8444 replication_count: None,
8445 evidence_spans: Vec::new(),
8446 };
8447
8448 let provenance = crate::bundle::Provenance {
8449 source_type: "published_paper".to_string(),
8450 doi: doi.map(|s| s.to_string()),
8451 pmid: pmid.map(|s| s.to_string()),
8452 pmc: None,
8453 openalex_id: None,
8454 url: None,
8455 title: source_title.to_string(),
8456 authors: Vec::new(),
8457 year: None,
8458 journal: None,
8459 license: None,
8460 publisher: None,
8461 funders: Vec::new(),
8462 extraction: crate::bundle::Extraction {
8463 method: "manual_curation".to_string(),
8464 model: None,
8465 model_version: None,
8466 extracted_at: chrono::Utc::now().to_rfc3339(),
8467 extractor_version: env!("CARGO_PKG_VERSION").to_string(),
8468 },
8469 review: None,
8470 citation_count: None,
8471 };
8472
8473 let mut rep = crate::bundle::Replication::new(
8474 target.to_string(),
8475 attempted_by.to_string(),
8476 outcome.to_string(),
8477 evidence,
8478 conditions,
8479 provenance,
8480 note.to_string(),
8481 );
8482 rep.previous_attempt = previous_attempt.map(|s| s.to_string());
8483
8484 if project.replications.iter().any(|r| r.id == rep.id) {
8487 if json {
8488 println!(
8489 "{}",
8490 serde_json::to_string_pretty(&json!({
8491 "ok": false,
8492 "command": "replicate",
8493 "reason": "replication_already_exists",
8494 "id": rep.id,
8495 }))
8496 .expect("serialize")
8497 );
8498 } else {
8499 println!(
8500 "{} replication {} already exists in {}; skipping.",
8501 style::warn("replicate"),
8502 rep.id,
8503 frontier.display()
8504 );
8505 }
8506 return;
8507 }
8508
8509 let new_id = rep.id.clone();
8510 project.replications.push(rep);
8511
8512 let cascade_result = if no_cascade {
8519 None
8520 } else {
8521 let result = propagate::propagate_correction(
8522 &mut project,
8523 target,
8524 propagate::PropagationAction::ReplicationOutcome {
8525 outcome: outcome.to_string(),
8526 vrep_id: new_id.clone(),
8527 },
8528 );
8529 project.review_events.extend(result.events.clone());
8532 project::recompute_stats(&mut project);
8533 Some(result)
8534 };
8535
8536 repo::save_to_path(frontier, &project).unwrap_or_else(|e| fail_return(&e));
8537
8538 if json {
8539 let cascade_json = cascade_result.as_ref().map(|r| {
8540 json!({
8541 "affected": r.affected,
8542 "events": r.events.len(),
8543 })
8544 });
8545 println!(
8546 "{}",
8547 serde_json::to_string_pretty(&json!({
8548 "ok": true,
8549 "command": "replicate",
8550 "id": new_id,
8551 "target": target,
8552 "outcome": outcome,
8553 "attempted_by": attempted_by,
8554 "cascade": cascade_json,
8555 "frontier": frontier.display().to_string(),
8556 }))
8557 .expect("failed to serialize replicate result")
8558 );
8559 } else {
8560 println!();
8561 println!(
8562 " {}",
8563 format!("VELA · REPLICATE · {}", new_id)
8564 .to_uppercase()
8565 .dimmed()
8566 );
8567 println!(" {}", style::tick_row(60));
8568 println!(" target: {target}");
8569 println!(" outcome: {outcome}");
8570 println!(" attempted by: {attempted_by}");
8571 println!(" conditions: {conditions_text}");
8572 println!(" source: {source_title}");
8573 if let Some(d) = doi {
8574 println!(" doi: {d}");
8575 }
8576 println!();
8577 println!(
8578 " {} replication recorded in {}",
8579 style::ok("ok"),
8580 frontier.display()
8581 );
8582 if let Some(result) = cascade_result {
8583 println!(
8584 " {} cascade: {} dependent(s) flagged, {} review event(s) recorded",
8585 style::ok("ok"),
8586 result.affected,
8587 result.events.len()
8588 );
8589 } else {
8590 println!(" {} cascade skipped (--no-cascade)", style::warn("info"));
8591 }
8592 }
8593}
8594
8595fn cmd_replications(frontier: &Path, target: Option<&str>, json: bool) {
8597 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
8598 let filtered: Vec<&crate::bundle::Replication> = project
8599 .replications
8600 .iter()
8601 .filter(|r| target.is_none_or(|t| r.target_finding == t))
8602 .collect();
8603
8604 if json {
8605 let payload = json!({
8606 "ok": true,
8607 "command": "replications",
8608 "frontier": frontier.display().to_string(),
8609 "filter_target": target,
8610 "count": filtered.len(),
8611 "replications": filtered,
8612 });
8613 println!(
8614 "{}",
8615 serde_json::to_string_pretty(&payload).expect("failed to serialize replications list")
8616 );
8617 return;
8618 }
8619
8620 println!();
8621 let header = match target {
8622 Some(t) => format!("VELA · REPLICATIONS · {t}"),
8623 None => format!("VELA · REPLICATIONS · {}", frontier.display()),
8624 };
8625 println!(" {}", header.to_uppercase().dimmed());
8626 println!(" {}", style::tick_row(60));
8627 if filtered.is_empty() {
8628 println!(" (no replications recorded)");
8629 return;
8630 }
8631 for rep in &filtered {
8632 let outcome_chip = match rep.outcome.as_str() {
8633 "replicated" => style::ok(&rep.outcome),
8634 "failed" => style::lost(&rep.outcome),
8635 "partial" => style::warn(&rep.outcome),
8636 _ => rep.outcome.clone().normal().to_string(),
8637 };
8638 println!(
8639 " · {} {} by {}",
8640 rep.id.dimmed(),
8641 outcome_chip,
8642 rep.attempted_by
8643 );
8644 println!(" target: {}", rep.target_finding);
8645 if !rep.conditions.text.is_empty() {
8646 println!(" conditions: {}", truncate(&rep.conditions.text, 80));
8647 }
8648 if !rep.provenance.title.is_empty() {
8649 println!(" source: {}", truncate(&rep.provenance.title, 80));
8650 }
8651 }
8652}
8653
8654async fn cmd_ingest(
8667 path: &str,
8668 frontier: &Path,
8669 backend: Option<&str>,
8670 actor: Option<&str>,
8671 dry_run: bool,
8672 json: bool,
8673) {
8674 let lowered = path.trim().to_lowercase();
8676 if lowered.starts_with("doi:") || lowered.starts_with("pmid:") || lowered.starts_with("nct:") {
8677 cmd_source_fetch(path.trim(), None, None, false, json).await;
8678 if !json {
8684 eprintln!();
8685 eprintln!(
8686 " vela ingest · note: doi:/pmid:/nct: URIs only fetch metadata; no frontier state was written."
8687 );
8688 eprintln!(
8689 " next: turn this paper into a proposal with `vela finding add {} --assertion '...' --author 'reviewer:you' --apply`",
8690 frontier.display()
8691 );
8692 }
8693 return;
8694 }
8695
8696 let p = std::path::PathBuf::from(path);
8697 if !p.exists() {
8698 fail(&format!(
8699 "ingest: path '{path}' does not exist (and is not a doi:/pmid:/nct: URI)"
8700 ));
8701 }
8702
8703 let ext = p
8705 .extension()
8706 .and_then(|s| s.to_str())
8707 .map(|s| s.to_ascii_lowercase());
8708
8709 if p.is_file() {
8710 match ext.as_deref() {
8711 Some("pdf") => {
8712 cmd_scout(&p, frontier, backend, dry_run, json).await;
8716 }
8717 Some("md") | Some("markdown") => {
8718 cmd_compile_notes(&p, frontier, backend, None, None, dry_run, json).await;
8721 }
8722 Some("csv") | Some("tsv") => {
8723 cmd_compile_data(&p, frontier, backend, None, dry_run, json).await;
8726 }
8727 Some("json") => {
8728 let actor_id = actor.unwrap_or("agent:vela-ingest-bot");
8730 cmd_artifact_to_state(frontier, &p, actor_id, false, json);
8731 }
8732 other => {
8733 fail(&format!(
8734 "ingest: unsupported file type '{}' (expected .pdf, .md, .csv, .tsv, .json, or a doi:/pmid:/nct: URI)",
8735 other.unwrap_or("(none)")
8736 ));
8737 }
8738 }
8739 return;
8740 }
8741
8742 if p.is_dir() {
8743 let mut pdf_count = 0usize;
8750 let mut md_count = 0usize;
8751 let mut data_count = 0usize;
8752 let mut json_count = 0usize;
8753 let mut unhandled_exts: std::collections::BTreeSet<String> =
8754 std::collections::BTreeSet::new();
8755 if let Ok(entries) = std::fs::read_dir(&p) {
8756 for entry in entries.flatten() {
8757 let path = entry.path();
8758 if !path.is_file() {
8759 continue;
8760 }
8761 if let Some(name) = entry.file_name().to_str()
8762 && let Some(dot) = name.rfind('.')
8763 {
8764 let ext = name[dot + 1..].to_ascii_lowercase();
8765 match ext.as_str() {
8766 "pdf" => pdf_count += 1,
8767 "md" | "markdown" => md_count += 1,
8768 "csv" | "tsv" => data_count += 1,
8769 "json" => json_count += 1,
8770 other => {
8771 if !name.starts_with('.') {
8774 unhandled_exts.insert(other.to_string());
8775 }
8776 }
8777 }
8778 }
8779 }
8780 }
8781
8782 let dispatched_types = (pdf_count > 0) as usize
8783 + (md_count > 0) as usize
8784 + (data_count > 0) as usize
8785 + (json_count > 0) as usize;
8786
8787 if dispatched_types == 0 {
8788 cmd_compile_code(&p, frontier, backend, None, dry_run, json).await;
8791 return;
8792 }
8793
8794 if dispatched_types > 1 {
8795 eprintln!(
8796 " vela ingest · folder has multiple handlable types; running each in sequence"
8797 );
8798 eprintln!(
8799 " pdf:{pdf_count} md:{md_count} csv/tsv:{data_count} json:{json_count}"
8800 );
8801 }
8802
8803 if pdf_count > 0 {
8810 cmd_scout(&p, frontier, backend, dry_run, json).await;
8811 }
8812 if md_count > 0 {
8813 cmd_compile_notes(&p, frontier, backend, None, None, dry_run, json).await;
8814 }
8815 if data_count > 0 {
8816 cmd_compile_data(&p, frontier, backend, None, dry_run, json).await;
8817 }
8818 if json_count > 0 {
8819 let actor_id = actor.unwrap_or("agent:vela-ingest-bot");
8822 if let Ok(entries) = std::fs::read_dir(&p) {
8823 for entry in entries.flatten() {
8824 let path = entry.path();
8825 if path.is_file()
8826 && path
8827 .extension()
8828 .and_then(|s| s.to_str())
8829 .map(|s| s.eq_ignore_ascii_case("json"))
8830 .unwrap_or(false)
8831 {
8832 cmd_artifact_to_state(frontier, &path, actor_id, false, json);
8833 }
8834 }
8835 }
8836 }
8837
8838 if !unhandled_exts.is_empty() {
8839 let kinds: Vec<String> = unhandled_exts.into_iter().collect();
8840 eprintln!(
8841 " vela ingest · skipped {} file extension(s) with no handler: {}",
8842 kinds.len(),
8843 kinds.join(", ")
8844 );
8845 }
8846 return;
8847 }
8848
8849 fail(&format!(
8850 "ingest: path '{path}' is neither a file nor a directory"
8851 ));
8852}
8853
8854#[allow(clippy::too_many_arguments)]
8855async fn cmd_compile_data(
8857 root: &Path,
8858 frontier: &Path,
8859 backend: Option<&str>,
8860 sample_rows: Option<usize>,
8861 dry_run: bool,
8862 json_out: bool,
8863) {
8864 match DATASETS_HANDLER.get() {
8865 Some(handler) => {
8866 handler(
8867 root.to_path_buf(),
8868 frontier.to_path_buf(),
8869 backend.map(String::from),
8870 sample_rows,
8871 dry_run,
8872 json_out,
8873 )
8874 .await;
8875 }
8876 None => {
8877 eprintln!(
8878 "{} `vela compile-data` requires the vela CLI binary; the library is unwired without a registered datasets handler.",
8879 style::err_prefix()
8880 );
8881 std::process::exit(1);
8882 }
8883 }
8884}
8885
8886async fn cmd_review_pending(
8889 frontier: &Path,
8890 backend: Option<&str>,
8891 max_proposals: Option<usize>,
8892 batch_size: usize,
8893 dry_run: bool,
8894 json_out: bool,
8895) {
8896 match REVIEWER_HANDLER.get() {
8897 Some(handler) => {
8898 handler(
8899 frontier.to_path_buf(),
8900 backend.map(String::from),
8901 max_proposals,
8902 batch_size,
8903 dry_run,
8904 json_out,
8905 )
8906 .await;
8907 }
8908 None => {
8909 eprintln!(
8910 "{} `vela review-pending` requires the vela CLI binary; the library is unwired without a registered reviewer handler.",
8911 style::err_prefix()
8912 );
8913 std::process::exit(1);
8914 }
8915 }
8916}
8917
8918async fn cmd_find_tensions(
8921 frontier: &Path,
8922 backend: Option<&str>,
8923 max_findings: Option<usize>,
8924 dry_run: bool,
8925 json_out: bool,
8926) {
8927 match TENSIONS_HANDLER.get() {
8928 Some(handler) => {
8929 handler(
8930 frontier.to_path_buf(),
8931 backend.map(String::from),
8932 max_findings,
8933 dry_run,
8934 json_out,
8935 )
8936 .await;
8937 }
8938 None => {
8939 eprintln!(
8940 "{} `vela find-tensions` requires the vela CLI binary; the library is unwired without a registered tensions handler.",
8941 style::err_prefix()
8942 );
8943 std::process::exit(1);
8944 }
8945 }
8946}
8947
8948async fn cmd_plan_experiments(
8951 frontier: &Path,
8952 backend: Option<&str>,
8953 max_findings: Option<usize>,
8954 dry_run: bool,
8955 json_out: bool,
8956) {
8957 match EXPERIMENTS_HANDLER.get() {
8958 Some(handler) => {
8959 handler(
8960 frontier.to_path_buf(),
8961 backend.map(String::from),
8962 max_findings,
8963 dry_run,
8964 json_out,
8965 )
8966 .await;
8967 }
8968 None => {
8969 eprintln!(
8970 "{} `vela plan-experiments` requires the vela CLI binary; the library is unwired without a registered experiments handler.",
8971 style::err_prefix()
8972 );
8973 std::process::exit(1);
8974 }
8975 }
8976}
8977
8978async fn cmd_compile_code(
8981 root: &Path,
8982 frontier: &Path,
8983 backend: Option<&str>,
8984 max_files: Option<usize>,
8985 dry_run: bool,
8986 json_out: bool,
8987) {
8988 match CODE_HANDLER.get() {
8989 Some(handler) => {
8990 handler(
8991 root.to_path_buf(),
8992 frontier.to_path_buf(),
8993 backend.map(String::from),
8994 max_files,
8995 dry_run,
8996 json_out,
8997 )
8998 .await;
8999 }
9000 None => {
9001 eprintln!(
9002 "{} `vela compile-code` requires the vela CLI binary; the library is unwired without a registered code handler.",
9003 style::err_prefix()
9004 );
9005 std::process::exit(1);
9006 }
9007 }
9008}
9009
9010async fn cmd_compile_notes(
9015 vault: &Path,
9016 frontier: &Path,
9017 backend: Option<&str>,
9018 max_files: Option<usize>,
9019 max_items_per_category: Option<usize>,
9020 dry_run: bool,
9021 json_out: bool,
9022) {
9023 match NOTES_HANDLER.get() {
9024 Some(handler) => {
9025 handler(
9026 vault.to_path_buf(),
9027 frontier.to_path_buf(),
9028 backend.map(String::from),
9029 max_files,
9030 max_items_per_category,
9031 dry_run,
9032 json_out,
9033 )
9034 .await;
9035 }
9036 None => {
9037 eprintln!(
9038 "{} `vela compile-notes` requires the vela CLI binary; the library is unwired without a registered notes handler.",
9039 style::err_prefix()
9040 );
9041 std::process::exit(1);
9042 }
9043 }
9044}
9045
9046async fn cmd_scout(
9053 folder: &Path,
9054 frontier: &Path,
9055 backend: Option<&str>,
9056 dry_run: bool,
9057 json_out: bool,
9058) {
9059 match SCOUT_HANDLER.get() {
9060 Some(handler) => {
9061 handler(
9062 folder.to_path_buf(),
9063 frontier.to_path_buf(),
9064 backend.map(String::from),
9065 dry_run,
9066 json_out,
9067 )
9068 .await;
9069 }
9070 None => {
9071 eprintln!(
9072 "{} `vela scout` requires the vela CLI binary; the library is unwired without a registered scout handler.",
9073 style::err_prefix()
9074 );
9075 std::process::exit(1);
9076 }
9077 }
9078}
9079
9080#[allow(clippy::too_many_arguments)]
9081pub fn scan_for_sensitive_paths(root: &Path) -> Vec<PathBuf> {
9090 let mut hits: Vec<PathBuf> = Vec::new();
9091 let skip_dirs: &[&str] = &[".git", "target", "node_modules", "dist", "build"];
9092 let bad_exts: &[&str] = &["key", "pem", "p12", "pfx"];
9093 let bad_substrings: &[&str] = &["private", "secret", "credential"];
9094 let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
9095 while let Some(dir) = stack.pop() {
9096 let Ok(entries) = std::fs::read_dir(&dir) else {
9097 continue;
9098 };
9099 for entry in entries.flatten() {
9100 let path = entry.path();
9101 let name_os = path.file_name();
9102 let Some(name) = name_os.and_then(|n| n.to_str()) else {
9103 continue;
9104 };
9105 let lower = name.to_lowercase();
9106 if path.is_dir() {
9107 if skip_dirs.contains(&name) {
9108 continue;
9109 }
9110 stack.push(path);
9111 continue;
9112 }
9113 if lower.ends_with(".pub") || lower.ends_with(".pubkey") {
9115 continue;
9116 }
9117 if lower == "public.key" {
9119 continue;
9120 }
9121 let ext = path
9122 .extension()
9123 .and_then(|e| e.to_str())
9124 .map(str::to_lowercase)
9125 .unwrap_or_default();
9126 let mut hit = false;
9127 if bad_exts.iter().any(|x| ext == *x) {
9128 hit = true;
9129 }
9130 if bad_substrings.iter().any(|s| lower.contains(s)) {
9131 hit = true;
9132 }
9133 if hit {
9134 hits.push(path);
9135 }
9136 }
9137 }
9138 hits.sort();
9139 hits
9140}
9141
9142fn cmd_check(
9143 source: Option<&Path>,
9144 schema: bool,
9145 stats: bool,
9146 conformance_flag: bool,
9147 conformance_dir: &Path,
9148 all: bool,
9149 schema_only: bool,
9150 strict: bool,
9151 fix: bool,
9152 json_output: bool,
9153) {
9154 if json_output {
9155 let Some(src) = source else {
9156 fail("--json requires a frontier source");
9157 };
9158 let payload = check_json_payload(src, schema_only, strict);
9159 println!(
9160 "{}",
9161 serde_json::to_string_pretty(&payload).expect("failed to serialize check report")
9162 );
9163 if payload.get("ok").and_then(Value::as_bool) != Some(true) {
9164 std::process::exit(1);
9165 }
9166 return;
9167 }
9168
9169 if strict && let Some(src) = source {
9180 let hits = scan_for_sensitive_paths(src);
9181 if !hits.is_empty() {
9182 eprintln!(
9183 "{} secret-audit: {} sensitive path(s) found under {}",
9184 style::err_prefix(),
9185 hits.len(),
9186 src.display()
9187 );
9188 for hit in &hits {
9189 eprintln!(" - {}", hit.display());
9190 }
9191 eprintln!(
9192 " hint: add `keys/` and `*.key` to .gitignore so these never reach a public repo (see THREAT_MODEL.md A17)"
9193 );
9194 std::process::exit(1);
9195 }
9196 }
9197
9198 let run_all = all || (!schema && !stats && !conformance_flag && !schema_only);
9199 if run_all || schema || schema_only {
9200 let Some(src) = source else {
9201 fail("check requires a frontier source");
9202 };
9203 validate::run(src);
9204 }
9205 if !schema_only && (run_all || stats) {
9206 let Some(src) = source else {
9207 fail("--stats requires a frontier source");
9208 };
9209 let frontier = load_frontier_or_fail(src);
9210 let report = lint::lint(&frontier, None, None);
9211 lint::print_report(&report);
9212 let replay_report = events::replay_report(&frontier);
9213 println!("event replay: {}", replay_report.status);
9214 if !replay_report.conflicts.is_empty() {
9215 for conflict in &replay_report.conflicts {
9216 println!(" - {conflict}");
9217 }
9218 }
9219 if let Ok(signature_report) = sign::verify_frontier_data(&frontier, None)
9220 && signature_report.signed > 0
9221 {
9222 println!(
9223 "Signatures: {} valid / {} invalid / {} unsigned",
9224 signature_report.valid, signature_report.invalid, signature_report.unsigned
9225 );
9226 }
9227 let signal_report = signals::analyze(&frontier, &[]);
9228 print_signal_summary(&signal_report, strict);
9229 if !replay_report.ok
9230 || (strict
9231 && (!signal_report.review_queue.is_empty()
9232 || signal_report.proof_readiness.status != "ready"))
9233 {
9234 std::process::exit(1);
9235 }
9236 }
9237 if run_all || conformance_flag {
9238 if conformance_flag || conformance_dir.is_dir() {
9248 conformance::run(conformance_dir);
9249 } else {
9250 eprintln!(
9251 " conformance: skipped ({} not present; pass --conformance-dir <path> to point at the source repo's tests/conformance)",
9252 conformance_dir.display()
9253 );
9254 }
9255 }
9256 let _ = fix;
9257}
9258
9259fn check_json_payload(src: &Path, schema_only: bool, strict: bool) -> Value {
9260 let report = validate::validate(src);
9261 let loaded = repo::load_from_path(src).ok();
9262 let (method_report, graph_report) = if schema_only {
9263 (None, None)
9264 } else if let Some(frontier) = loaded.as_ref() {
9265 (
9266 Some(lint::lint(frontier, None, None)),
9267 Some(lint::lint_frontier(frontier)),
9268 )
9269 } else {
9270 (None, None)
9271 };
9272 let source_hash = hash_path(src).unwrap_or_else(|_| "unavailable".to_string());
9273 let mut diagnostics = Vec::new();
9274 diagnostics.extend(report.errors.iter().map(|e| {
9275 json!({
9276 "severity": "error",
9277 "rule_id": "schema",
9278 "finding_id": null,
9279 "file": &e.file,
9280 "field_path": null,
9281 "message": &e.error,
9282 "suggestion": schema_error_suggestion(&e.error),
9283 "fixable": schema_error_fix(&e.error),
9284 "normalize_action": schema_error_action(&e.error),
9285 })
9286 }));
9287 for (check_id, lint_report) in [
9288 ("methodology", method_report.as_ref()),
9289 ("frontier_graph", graph_report.as_ref()),
9290 ] {
9291 if let Some(lint_report) = lint_report {
9292 diagnostics.extend(lint_report.diagnostics.iter().map(|d| {
9293 json!({
9294 "severity": d.severity.to_string(),
9295 "rule_id": &d.rule_id,
9296 "check": check_id,
9297 "finding_id": &d.finding_id,
9298 "field_path": null,
9299 "message": &d.message,
9300 "suggestion": &d.suggestion,
9301 "fixable": false,
9302 "normalize_action": null,
9303 })
9304 }));
9305 }
9306 }
9307 let method_errors = method_report.as_ref().map_or(0, |r| r.errors);
9308 let method_warnings = method_report.as_ref().map_or(0, |r| r.warnings);
9309 let method_infos = method_report.as_ref().map_or(0, |r| r.infos);
9310 let graph_errors = graph_report.as_ref().map_or(0, |r| r.errors);
9311 let graph_warnings = graph_report.as_ref().map_or(0, |r| r.warnings);
9312 let graph_infos = graph_report.as_ref().map_or(0, |r| r.infos);
9313 let replay_report = loaded.as_ref().map(events::replay_report);
9314 let state_integrity_report = if schema_only {
9315 loaded.as_ref().map(state_integrity::analyze)
9316 } else {
9317 state_integrity::analyze_path(src).ok()
9318 };
9319 if let Some(replay) = replay_report.as_ref()
9320 && !replay.ok
9321 {
9322 diagnostics.extend(replay.conflicts.iter().map(|conflict| {
9323 json!({
9324 "severity": "error",
9325 "rule_id": "event_replay",
9326 "check": "events",
9327 "finding_id": null,
9328 "field_path": null,
9329 "message": conflict,
9330 "suggestion": "Inspect canonical state events and repair the frontier event log before proof export.",
9331 "fixable": false,
9332 "normalize_action": null,
9333 })
9334 }));
9335 }
9336 let event_errors = replay_report
9337 .as_ref()
9338 .map_or(0, |replay| usize::from(!replay.ok));
9339 let state_integrity_errors = state_integrity_report
9340 .as_ref()
9341 .map_or(0, |report| report.structural_errors.len());
9342 let (source_registry, evidence_atoms, conditions, proposal_summary, proof_state) = loaded
9343 .as_ref()
9344 .map(|frontier| {
9345 (
9346 sources::source_summary(frontier),
9347 sources::evidence_summary(frontier),
9348 sources::condition_summary(frontier),
9349 proposals::summary(frontier),
9350 proposals::proof_state_json(&frontier.proof_state),
9351 )
9352 })
9353 .unwrap_or_else(|| {
9354 (
9355 sources::SourceRegistrySummary::default(),
9356 sources::EvidenceAtomSummary::default(),
9357 sources::ConditionSummary::default(),
9358 proposals::ProposalSummary::default(),
9359 Value::Null,
9360 )
9361 });
9362 let signature_report = loaded
9363 .as_ref()
9364 .and_then(|frontier| sign::verify_frontier_data(frontier, None).ok());
9365 if let Some(frontier) = loaded.as_ref()
9366 && !schema_only
9367 {
9368 let projection = sources::derive_projection(frontier);
9369 let existing_sources = frontier
9370 .sources
9371 .iter()
9372 .map(|source| source.id.as_str())
9373 .collect::<std::collections::BTreeSet<_>>();
9374 let existing_atoms = frontier
9375 .evidence_atoms
9376 .iter()
9377 .map(|atom| atom.id.as_str())
9378 .collect::<std::collections::BTreeSet<_>>();
9379 let existing_conditions = frontier
9380 .condition_records
9381 .iter()
9382 .map(|record| record.id.as_str())
9383 .collect::<std::collections::BTreeSet<_>>();
9384 for source in projection
9385 .sources
9386 .iter()
9387 .filter(|source| !existing_sources.contains(source.id.as_str()))
9388 {
9389 diagnostics.push(json!({
9390 "severity": "warning",
9391 "rule_id": "missing_source_record",
9392 "check": "source_registry",
9393 "finding_id": source.finding_ids.first(),
9394 "field_path": "sources",
9395 "message": format!("Source record {} is derivable but not materialized in frontier state.", source.id),
9396 "suggestion": "Run `vela normalize` to materialize source records before proof export.",
9397 "fixable": true,
9398 "normalize_action": "materialize_source_record",
9399 }));
9400 }
9401 for atom in projection
9402 .evidence_atoms
9403 .iter()
9404 .filter(|atom| !existing_atoms.contains(atom.id.as_str()))
9405 {
9406 diagnostics.push(json!({
9407 "severity": "warning",
9408 "rule_id": "missing_evidence_atom",
9409 "check": "evidence_atoms",
9410 "finding_id": atom.finding_id,
9411 "field_path": "evidence_atoms",
9412 "message": format!("Evidence atom {} is derivable but not materialized in frontier state.", atom.id),
9413 "suggestion": "Run `vela normalize` to materialize evidence atoms before proof export.",
9414 "fixable": true,
9415 "normalize_action": "materialize_evidence_atom",
9416 }));
9417 }
9418 for atom in projection
9419 .evidence_atoms
9420 .iter()
9421 .filter(|atom| atom.locator.is_none())
9422 {
9423 diagnostics.push(json!({
9424 "severity": "warning",
9425 "rule_id": "missing_evidence_locator",
9426 "check": "evidence_atoms",
9427 "finding_id": atom.finding_id,
9428 "field_path": "evidence_atoms[].locator",
9429 "message": format!("Evidence atom {} has no source locator.", atom.id),
9430 "suggestion": "Add or verify evidence spans, table rows, pages, sections, or run locators.",
9431 "fixable": false,
9432 "normalize_action": null,
9433 }));
9434 }
9435 for condition in projection
9436 .condition_records
9437 .iter()
9438 .filter(|condition| !existing_conditions.contains(condition.id.as_str()))
9439 {
9440 diagnostics.push(json!({
9441 "severity": "warning",
9442 "rule_id": "condition_record_missing",
9443 "check": "conditions",
9444 "finding_id": condition.finding_id,
9445 "field_path": "condition_records",
9446 "message": format!("Condition record {} is derivable but not materialized in frontier state.", condition.id),
9447 "suggestion": "Run `vela normalize` to materialize condition boundaries before proof export.",
9448 "fixable": true,
9449 "normalize_action": "materialize_condition_record",
9450 }));
9451 }
9452 for proposal in frontier.proposals.iter().filter(|proposal| {
9453 matches!(proposal.status.as_str(), "accepted" | "applied")
9454 && proposal
9455 .reviewed_by
9456 .as_deref()
9457 .is_none_or(proposals::is_placeholder_reviewer)
9458 }) {
9459 diagnostics.push(json!({
9460 "severity": "error",
9461 "rule_id": "reviewer_identity_missing",
9462 "check": "proposals",
9463 "finding_id": proposal.target.id,
9464 "field_path": "proposals[].reviewed_by",
9465 "message": format!("Accepted or applied proposal {} uses a missing or placeholder reviewer identity.", proposal.id),
9466 "suggestion": "Accept the proposal with a stable named reviewer id before strict proof use.",
9467 "fixable": false,
9468 "normalize_action": null,
9469 }));
9470 }
9471 }
9472 let signal_report = loaded
9473 .as_ref()
9474 .map(|frontier| signals::analyze(frontier, &diagnostics))
9475 .unwrap_or_else(empty_signal_report);
9476 let errors =
9477 report.errors.len() + method_errors + graph_errors + event_errors + state_integrity_errors;
9478 let warnings = method_warnings + graph_warnings + signal_report.proof_readiness.warnings;
9479 let infos = method_infos + graph_infos;
9480 let strict_blockers = signal_report
9481 .signals
9482 .iter()
9483 .filter(|signal| signal.blocks.iter().any(|block| block == "strict_check"))
9484 .count();
9485 let fixable = diagnostics
9486 .iter()
9487 .filter(|d| d.get("fixable").and_then(Value::as_bool).unwrap_or(false))
9488 .count();
9489 let ok = errors == 0 && (!strict || (warnings == 0 && strict_blockers == 0));
9490
9491 json!({
9492 "ok": ok,
9493 "command": "check",
9494 "schema_version": project::VELA_SCHEMA_VERSION,
9495 "source": {
9496 "path": src.display().to_string(),
9497 "hash": format!("sha256:{source_hash}"),
9498 },
9499 "summary": {
9500 "status": if ok { "pass" } else { "fail" },
9501 "checked_findings": report.total_files,
9502 "valid_findings": report.valid,
9503 "invalid_findings": report.invalid,
9504 "errors": errors,
9505 "warnings": warnings,
9506 "info": infos,
9507 "fixable": fixable,
9508 "strict": strict,
9509 "schema_only": schema_only,
9510 },
9511 "checks": [
9512 {
9513 "id": "schema",
9514 "status": if report.invalid == 0 { "pass" } else { "fail" },
9515 "checked": report.total_files,
9516 "failed": report.invalid,
9517 "errors": report.errors.iter().map(|e| json!({
9518 "file": e.file,
9519 "message": e.error,
9520 })).collect::<Vec<_>>(),
9521 },
9522 {
9523 "id": "methodology",
9524 "status": if method_errors == 0 { "pass" } else { "fail" },
9525 "checked": method_report.as_ref().map_or(0, |r| r.findings_checked),
9526 "failed": method_errors,
9527 "warnings": method_warnings,
9528 "info": method_infos,
9529 "skipped": schema_only,
9530 },
9531 {
9532 "id": "frontier_graph",
9533 "status": if graph_errors == 0 { "pass" } else { "fail" },
9534 "checked": graph_report.as_ref().map_or(0, |r| r.findings_checked),
9535 "failed": graph_errors,
9536 "warnings": graph_warnings,
9537 "info": graph_infos,
9538 "skipped": schema_only,
9539 },
9540 {
9541 "id": "signals",
9542 "status": if strict_blockers == 0 { "pass" } else { "fail" },
9543 "checked": signal_report.signals.len(),
9544 "failed": strict_blockers,
9545 "warnings": signal_report.proof_readiness.warnings,
9546 "skipped": loaded.is_none(),
9547 "blockers": signal_report.signals.iter()
9548 .filter(|s| s.blocks.iter().any(|b| b == "strict_check"))
9549 .map(|s| json!({
9550 "id": s.id,
9551 "kind": s.kind,
9552 "severity": s.severity,
9553 "reason": s.reason,
9554 }))
9555 .collect::<Vec<_>>(),
9556 },
9557 {
9558 "id": "events",
9559 "status": if replay_report.as_ref().is_none_or(|replay| replay.ok) { "pass" } else { "fail" },
9560 "checked": replay_report.as_ref().map_or(0, |replay| replay.event_log.count),
9561 "failed": event_errors,
9562 "skipped": schema_only || loaded.is_none(),
9563 },
9564 {
9565 "id": "state_integrity",
9566 "status": if state_integrity_report.as_ref().is_none_or(|report| report.status != "fail") { "pass" } else { "fail" },
9567 "checked": state_integrity_report.as_ref().map_or(0, |report| report.summary.get("events").copied().unwrap_or_default()),
9568 "failed": state_integrity_errors,
9569 "skipped": schema_only || loaded.is_none(),
9570 }
9571 ],
9572 "event_log": replay_report.as_ref().map(|replay| &replay.event_log),
9573 "replay": replay_report,
9574 "state_integrity": state_integrity_report,
9575 "source_registry": source_registry,
9576 "evidence_atoms": evidence_atoms,
9577 "conditions": conditions,
9578 "proposals": proposal_summary,
9579 "proof_state": proof_state,
9580 "signatures": signature_report,
9581 "diagnostics": diagnostics,
9582 "signals": signal_report.signals,
9583 "review_queue": signal_report.review_queue,
9584 "proof_readiness": signal_report.proof_readiness,
9585 "repair_plan": build_repair_plan(&diagnostics),
9586 })
9587}
9588
9589#[allow(clippy::too_many_arguments)]
9590fn cmd_normalize(
9591 source: &Path,
9592 out: Option<&Path>,
9593 write: bool,
9594 dry_run: bool,
9595 rewrite_ids: bool,
9596 id_map: Option<&Path>,
9597 resync_provenance: bool,
9598 json_output: bool,
9599) {
9600 if write && out.is_some() {
9601 fail("Use either --write or --out, not both.");
9602 }
9603 if dry_run && (write || out.is_some()) {
9604 fail("--dry-run cannot be combined with --write or --out.");
9605 }
9606 if id_map.is_some() && !rewrite_ids {
9607 fail("--id-map requires --rewrite-ids.");
9608 }
9609
9610 let detected = repo::detect(source).unwrap_or_else(|e| {
9611 eprintln!("{e}");
9612 std::process::exit(1);
9613 });
9614 if matches!(detected, repo::VelaSource::PacketDir(_)) {
9615 fail(
9616 "Cannot normalize a proof packet directory. Export a new packet from frontier state instead.",
9617 );
9618 }
9619 let mut frontier = repo::load(&detected).unwrap_or_else(|e| fail_return(&e));
9620 let has_substantive_events = frontier
9625 .events
9626 .iter()
9627 .any(|event| event.kind != "frontier.created");
9628 if has_substantive_events && (write || out.is_some()) {
9629 fail(
9630 "Refusing to normalize a frontier with canonical events. Normalize before proposal-backed writes, or create a new reviewed transition for the intended change.",
9631 );
9632 }
9633 let source_hash = hash_path(source).unwrap_or_else(|_| "unavailable".to_string());
9634 let before_stats = serde_json::to_value(&frontier.stats).unwrap_or(Value::Null);
9635 let (entity_type_fixes, entity_name_fixes) =
9636 normalize::normalize_findings(&mut frontier.findings);
9637 let confidence_updates =
9638 bundle::recompute_all_confidence(&mut frontier.findings, &frontier.replications);
9639 let provenance_resync_count = if resync_provenance {
9643 sources::resync_provenance_from_sources(&mut frontier)
9644 } else {
9645 0
9646 };
9647 let before_source_count = frontier.sources.len();
9648 let before_evidence_atom_count = frontier.evidence_atoms.len();
9649 let before_condition_record_count = frontier.condition_records.len();
9650
9651 let mut id_rewrites = Vec::new();
9652 if rewrite_ids {
9653 let mut id_map_values = std::collections::BTreeMap::<String, String>::new();
9654 for finding in &frontier.findings {
9655 let expected =
9656 bundle::FindingBundle::content_address(&finding.assertion, &finding.provenance);
9657 if expected != finding.id {
9658 id_map_values.insert(finding.id.clone(), expected);
9659 }
9660 }
9661 let new_ids = id_map_values
9662 .values()
9663 .map(String::as_str)
9664 .collect::<std::collections::HashSet<_>>();
9665 if new_ids.len() != id_map_values.len() {
9666 fail("Refusing to rewrite IDs because two findings map to the same content address.");
9667 }
9668 for finding in &mut frontier.findings {
9669 if let Some(new_id) = id_map_values.get(&finding.id) {
9670 id_rewrites.push(json!({"old": finding.id, "new": new_id}));
9671 finding.previous_version = Some(finding.id.clone());
9672 finding.id = new_id.clone();
9673 }
9674 }
9675 for finding in &mut frontier.findings {
9676 for link in &mut finding.links {
9677 if let Some(new_target) = id_map_values.get(&link.target) {
9678 link.target = new_target.clone();
9679 }
9680 }
9681 }
9682 if let Some(path) = id_map {
9683 std::fs::write(
9684 path,
9685 serde_json::to_string_pretty(&id_map_values)
9686 .expect("failed to serialize normalize id map"),
9687 )
9688 .unwrap_or_else(|e| fail(&format!("Failed to write {}: {e}", path.display())));
9689 }
9690 }
9691
9692 sources::materialize_project(&mut frontier);
9693 let source_records_materialized = frontier.sources.len().saturating_sub(before_source_count);
9694 let evidence_atoms_materialized = frontier
9695 .evidence_atoms
9696 .len()
9697 .saturating_sub(before_evidence_atom_count);
9698 let condition_records_materialized = frontier
9699 .condition_records
9700 .len()
9701 .saturating_sub(before_condition_record_count);
9702 let after_stats = serde_json::to_value(&frontier.stats).unwrap_or(Value::Null);
9703 let id_rewrite_count = id_rewrites.len();
9704 let wrote_to = if write {
9705 repo::save(&detected, &frontier).unwrap_or_else(|e| fail(&e));
9706 Some(source.display().to_string())
9707 } else if let Some(out_path) = out {
9708 repo::save_to_path(out_path, &frontier).unwrap_or_else(|e| fail(&e));
9709 Some(out_path.display().to_string())
9710 } else {
9711 None
9712 };
9713 let wrote = wrote_to.is_some();
9714 let planned_changes = entity_type_fixes
9715 + entity_name_fixes
9716 + confidence_updates
9717 + id_rewrite_count
9718 + source_records_materialized
9719 + evidence_atoms_materialized
9720 + condition_records_materialized
9721 + provenance_resync_count;
9722 let payload = json!({
9723 "ok": true,
9724 "command": "normalize",
9725 "schema_version": project::VELA_SCHEMA_VERSION,
9726 "source": {
9727 "path": source.display().to_string(),
9728 "hash": format!("sha256:{source_hash}"),
9729 },
9730 "dry_run": wrote_to.is_none(),
9731 "wrote_to": wrote_to,
9732 "summary": {
9733 "planned": planned_changes,
9734 "safe": planned_changes,
9735 "unsafe": 0,
9736 "applied": if wrote { planned_changes } else { 0 },
9737 },
9738 "changes": {
9739 "entity_type_fixes": entity_type_fixes,
9740 "entity_name_fixes": entity_name_fixes,
9741 "confidence_updates": confidence_updates,
9742 "id_rewrites": id_rewrite_count,
9743 "source_records_materialized": source_records_materialized,
9744 "evidence_atoms_materialized": evidence_atoms_materialized,
9745 "condition_records_materialized": condition_records_materialized,
9746 "provenance_resyncs": provenance_resync_count,
9747 "stats_changed": before_stats != after_stats,
9748 },
9749 "id_rewrites": id_rewrites,
9750 "repair_plan": if wrote { Vec::<Value>::new() } else {
9751 vec![json!({
9752 "action": "apply_normalization",
9753 "command": "vela normalize <frontier> --out frontier.normalized.json"
9754 })]
9755 },
9756 });
9757 if json_output {
9758 println!(
9759 "{}",
9760 serde_json::to_string_pretty(&payload).expect("failed to serialize normalize report")
9761 );
9762 } else if let Some(path) = payload.get("wrote_to").and_then(Value::as_str) {
9763 println!("{} normalized frontier written to {path}", style::ok("ok"));
9764 println!(
9765 " entity type fixes: {}, entity name fixes: {}, confidence updates: {}, id rewrites: {}",
9766 entity_type_fixes, entity_name_fixes, confidence_updates, id_rewrite_count
9767 );
9768 } else {
9769 println!("normalize dry run for {}", source.display());
9770 println!(
9771 " would apply entity type fixes: {}, entity name fixes: {}, confidence updates: {}, id rewrites: {}",
9772 entity_type_fixes, entity_name_fixes, confidence_updates, id_rewrite_count
9773 );
9774 }
9775}
9776
9777fn cmd_proof(
9778 frontier: &Path,
9779 out: &Path,
9780 template: &str,
9781 gold: Option<&Path>,
9782 record_proof_state: bool,
9783 json_output: bool,
9784) {
9785 if template != "bbb-alzheimer" {
9786 fail(&format!(
9787 "Unsupported proof template '{template}'. Supported: bbb-alzheimer"
9788 ));
9789 }
9790 let mut loaded = load_frontier_or_fail(frontier);
9791 let source_hash = hash_path_or_fail(frontier);
9792 let export_record = export::export_packet_with_source(&loaded, Some(frontier), out)
9793 .unwrap_or_else(|e| fail(&e));
9794 let benchmark_summary = gold.map(|gold_path| {
9795 let summary = benchmark::run_suite(gold_path).unwrap_or_else(|e| {
9796 fail(&format!(
9797 "Failed to run proof benchmark '{}': {e}",
9798 gold_path.display()
9799 ))
9800 });
9801 append_packet_json_file(out, "benchmark-summary.json", &summary).unwrap_or_else(|e| {
9802 fail(&format!("Failed to write benchmark summary: {e}"));
9803 });
9804 if summary.get("ok").and_then(Value::as_bool) != Some(true) {
9805 fail(&format!(
9806 "Proof benchmark failed for {}",
9807 gold_path.display()
9808 ));
9809 }
9810 summary
9811 });
9812 let validation_summary = packet::validate(out).unwrap_or_else(|e| {
9813 fail(&format!("Proof packet validation failed: {e}"));
9814 });
9815 proposals::record_proof_export(
9816 &mut loaded,
9817 proposals::ProofPacketRecord {
9818 generated_at: export_record.generated_at.clone(),
9819 snapshot_hash: export_record.snapshot_hash.clone(),
9820 event_log_hash: export_record.event_log_hash.clone(),
9821 packet_manifest_hash: export_record.packet_manifest_hash.clone(),
9822 },
9823 );
9824 project::recompute_stats(&mut loaded);
9825 if record_proof_state {
9826 repo::save_to_path(frontier, &loaded).unwrap_or_else(|e| fail(&e));
9827 }
9828 let signal_report = signals::analyze(&loaded, &[]);
9829 if json_output {
9830 let payload = json!({
9831 "ok": true,
9832 "command": "proof",
9833 "schema_version": project::VELA_SCHEMA_VERSION,
9834 "recorded_proof_state": record_proof_state,
9835 "frontier": {
9836 "name": &loaded.project.name,
9837 "source": frontier.display().to_string(),
9838 "hash": format!("sha256:{source_hash}"),
9839 },
9840 "template": template,
9841 "gold": gold.map(|p| p.display().to_string()),
9842 "benchmark": benchmark_summary,
9843 "output": out.display().to_string(),
9844 "packet": {
9845 "manifest_path": out.join("manifest.json").display().to_string(),
9846 },
9847 "validation": {
9848 "status": "ok",
9849 "summary": validation_summary,
9850 },
9851 "proposals": proposals::summary(&loaded),
9852 "proof_state": loaded.proof_state,
9853 "signals": signal_report.signals,
9854 "review_queue": signal_report.review_queue,
9855 "proof_readiness": signal_report.proof_readiness,
9856 "trace_path": out.join("proof-trace.json").display().to_string(),
9857 });
9858 println!(
9859 "{}",
9860 serde_json::to_string_pretty(&payload).expect("failed to serialize proof response")
9861 );
9862 } else {
9863 println!("vela proof");
9864 println!(" source: {}", frontier.display());
9865 println!(" template: {template}");
9866 println!(" output: {}", out.display());
9867 println!(" trace: {}", out.join("proof-trace.json").display());
9868 println!(
9869 " proof state: {}",
9870 if record_proof_state {
9871 "recorded"
9872 } else {
9873 "not recorded"
9874 }
9875 );
9876 println!();
9877 println!("{validation_summary}");
9878 }
9879}
9880
9881fn cmd_status(path: &Path, json: bool) {
9885 let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
9886
9887 let mut pending_total = 0usize;
9889 let mut pending_by_kind: std::collections::BTreeMap<String, usize> =
9890 std::collections::BTreeMap::new();
9891 for p in &project.proposals {
9892 if p.status == "pending_review" {
9893 pending_total += 1;
9894 *pending_by_kind.entry(p.kind.clone()).or_insert(0) += 1;
9895 }
9896 }
9897
9898 let audit = crate::causal_reasoning::audit_frontier(&project);
9900 let audit_summary = crate::causal_reasoning::summarize_audit(&audit);
9901
9902 let mut last_sync: Option<&crate::events::StateEvent> = None;
9904 let mut last_conflict: Option<&crate::events::StateEvent> = None;
9905 let mut total_conflicts = 0usize;
9906 for e in &project.events {
9907 match e.kind.as_str() {
9908 "frontier.synced_with_peer" => {
9909 if last_sync
9910 .map(|prev| e.timestamp > prev.timestamp)
9911 .unwrap_or(true)
9912 {
9913 last_sync = Some(e);
9914 }
9915 }
9916 "frontier.conflict_detected" => {
9917 total_conflicts += 1;
9918 if last_conflict
9919 .map(|prev| e.timestamp > prev.timestamp)
9920 .unwrap_or(true)
9921 {
9922 last_conflict = Some(e);
9923 }
9924 }
9925 _ => {}
9926 }
9927 }
9928
9929 let mut targets_with_success = std::collections::HashSet::new();
9931 let mut failed_replications = 0usize;
9932 for r in &project.replications {
9933 if r.outcome == "replicated" {
9934 targets_with_success.insert(r.target_finding.clone());
9935 } else if r.outcome == "failed" {
9936 failed_replications += 1;
9937 }
9938 }
9939
9940 if json {
9941 println!(
9942 "{}",
9943 serde_json::to_string_pretty(&json!({
9944 "ok": true,
9945 "command": "status",
9946 "frontier": frontier_label(&project),
9947 "vfr_id": project.frontier_id(),
9948 "findings": project.findings.len(),
9949 "events": project.events.len(),
9950 "actors": project.actors.len(),
9951 "peers": project.peers.len(),
9952 "inbox": {
9953 "pending_total": pending_total,
9954 "pending_by_kind": pending_by_kind,
9955 },
9956 "causal_audit": {
9957 "identified": audit_summary.identified,
9958 "conditional": audit_summary.conditional,
9959 "underidentified": audit_summary.underidentified,
9960 "underdetermined": audit_summary.underdetermined,
9961 },
9962 "replications": {
9963 "total": project.replications.len(),
9964 "findings_with_success": targets_with_success.len(),
9965 "failed": failed_replications,
9966 },
9967 "federation": {
9968 "peers": project.peers.len(),
9969 "last_sync": last_sync.map(|e| e.timestamp.clone()),
9970 "last_conflict": last_conflict.map(|e| e.timestamp.clone()),
9971 "total_conflicts": total_conflicts,
9972 },
9973 }))
9974 .expect("serialize status")
9975 );
9976 return;
9977 }
9978
9979 println!();
9980 println!(
9981 " {}",
9982 format!("VELA · STATUS · {}", path.display())
9983 .to_uppercase()
9984 .dimmed()
9985 );
9986 println!(" {}", style::tick_row(60));
9987 println!();
9988 println!(" frontier: {}", frontier_label(&project));
9989 println!(" vfr_id: {}", project.frontier_id());
9990 println!(
9991 " findings: {} events: {} peers: {} actors: {}",
9992 project.findings.len(),
9993 project.events.len(),
9994 project.peers.len(),
9995 project.actors.len(),
9996 );
9997 println!();
9998 if pending_total > 0 {
9999 println!(
10000 " {} {pending_total} pending proposals",
10001 style::warn("inbox")
10002 );
10003 for (k, n) in &pending_by_kind {
10004 println!(" · {n:>3} {k}");
10005 }
10006 } else {
10007 println!(" {} inbox clean", style::ok("ok"));
10008 }
10009 println!();
10010 if audit_summary.underidentified > 0 || audit_summary.conditional > 0 {
10011 let chip = if audit_summary.underidentified > 0 {
10012 style::lost("audit")
10013 } else {
10014 style::warn("audit")
10015 };
10016 println!(
10017 " {} identified {} · conditional {} · underidentified {} · underdetermined {}",
10018 chip,
10019 audit_summary.identified,
10020 audit_summary.conditional,
10021 audit_summary.underidentified,
10022 audit_summary.underdetermined,
10023 );
10024 if audit_summary.underidentified > 0 {
10025 println!(
10026 " next: vela causal audit {} --problems-only",
10027 path.display()
10028 );
10029 }
10030 } else if audit_summary.underdetermined == 0 {
10031 println!(
10032 " {} causal audit: all {} identified",
10033 style::ok("ok"),
10034 audit_summary.identified
10035 );
10036 } else {
10037 println!(
10038 " {} causal audit: {} identified, {} ungraded",
10039 style::warn("audit"),
10040 audit_summary.identified,
10041 audit_summary.underdetermined,
10042 );
10043 }
10044 println!();
10045 if !project.replications.is_empty() {
10046 println!(
10047 " {} {} records · {} findings replicated · {} failed",
10048 style::ok("replications"),
10049 project.replications.len(),
10050 targets_with_success.len(),
10051 failed_replications,
10052 );
10053 }
10054 if project.peers.is_empty() {
10055 println!(
10056 " {} no federation peers registered",
10057 style::warn("federation")
10058 );
10059 } else {
10060 let last = last_sync
10061 .map(|e| fmt_timestamp(&e.timestamp))
10062 .unwrap_or_else(|| "never".to_string());
10063 let chip = if total_conflicts > 0 {
10064 style::warn("federation")
10065 } else {
10066 style::ok("federation")
10067 };
10068 println!(
10069 " {} {} peer(s) · last sync {} · {} conflict events",
10070 chip,
10071 project.peers.len(),
10072 last,
10073 total_conflicts,
10074 );
10075 }
10076 println!();
10077}
10078
10079fn cmd_log(path: &Path, limit: usize, kind_filter: Option<&str>, json: bool) {
10081 let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
10082 let mut events: Vec<&crate::events::StateEvent> = project
10083 .events
10084 .iter()
10085 .filter(|e| match kind_filter {
10086 Some(k) => e.kind.contains(k),
10087 None => true,
10088 })
10089 .collect();
10090 events.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
10091 events.truncate(limit);
10092
10093 if json {
10094 let payload: Vec<_> = events
10095 .iter()
10096 .map(|e| {
10097 json!({
10098 "id": e.id,
10099 "kind": e.kind,
10100 "actor": e.actor.id,
10101 "target": &e.target.id,
10102 "target_type": &e.target.r#type,
10103 "timestamp": e.timestamp,
10104 "reason": e.reason,
10105 })
10106 })
10107 .collect();
10108 println!(
10109 "{}",
10110 serde_json::to_string_pretty(&json!({
10111 "ok": true,
10112 "command": "log",
10113 "events": payload,
10114 }))
10115 .expect("serialize log")
10116 );
10117 return;
10118 }
10119
10120 println!();
10121 println!(
10122 " {}",
10123 format!("VELA · LOG · {} (latest {})", path.display(), events.len())
10124 .to_uppercase()
10125 .dimmed()
10126 );
10127 println!(" {}", style::tick_row(60));
10128 if events.is_empty() {
10129 println!(" (no events)");
10130 return;
10131 }
10132 for e in &events {
10133 let when = fmt_timestamp(&e.timestamp);
10134 let target_short = if e.target.id.len() > 22 {
10135 format!("{}…", &e.target.id[..21])
10136 } else {
10137 e.target.id.clone()
10138 };
10139 let reason: String = e.reason.chars().take(70).collect();
10140 println!(
10141 " {:<19} {:<32} {:<24} {}",
10142 when, e.kind, target_short, reason
10143 );
10144 }
10145 println!();
10146}
10147
10148fn cmd_inbox(path: &Path, kind_filter: Option<&str>, limit: usize, json: bool) {
10150 let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
10151
10152 let mut score_map: std::collections::HashMap<String, (f64, f64, f64, f64)> =
10155 std::collections::HashMap::new();
10156 for p in &project.proposals {
10157 if p.kind != "finding.note" {
10158 continue;
10159 }
10160 if p.actor.id != "agent:reviewer-agent" {
10161 continue;
10162 }
10163 let reason = &p.reason;
10164 let Some(target) = reason.split_whitespace().find(|s| s.starts_with("vpr_")) else {
10165 continue;
10166 };
10167 let text = p.payload.get("text").and_then(|v| v.as_str()).unwrap_or("");
10168 let extract = |k: &str| -> f64 {
10169 let pat = format!("{k} ");
10170 text.find(&pat)
10171 .and_then(|idx| text[idx + pat.len()..].split_whitespace().next())
10172 .and_then(|t| t.parse::<f64>().ok())
10173 .unwrap_or(0.0)
10174 };
10175 score_map.insert(
10176 target.to_string(),
10177 (
10178 extract("plausibility"),
10179 extract("evidence"),
10180 extract("scope"),
10181 extract("duplicate-risk"),
10182 ),
10183 );
10184 }
10185
10186 let mut pending: Vec<&crate::proposals::StateProposal> = project
10187 .proposals
10188 .iter()
10189 .filter(|p| {
10190 p.status == "pending_review"
10191 && match kind_filter {
10192 Some(k) => p.kind.contains(k),
10193 None => true,
10194 }
10195 })
10196 .collect();
10197 pending.sort_by(|a, b| {
10199 let sa = score_map
10200 .get(&a.id)
10201 .map(|(p, e, s, d)| 0.4 * p + 0.3 * e + 0.2 * s - 0.3 * d);
10202 let sb = score_map
10203 .get(&b.id)
10204 .map(|(p, e, s, d)| 0.4 * p + 0.3 * e + 0.2 * s - 0.3 * d);
10205 sb.partial_cmp(&sa).unwrap_or(std::cmp::Ordering::Equal)
10206 });
10207 pending.truncate(limit);
10208
10209 if json {
10210 let payload: Vec<_> = pending
10211 .iter()
10212 .map(|p| {
10213 let assertion_text = p
10214 .payload
10215 .get("finding")
10216 .and_then(|f| f.get("assertion"))
10217 .and_then(|a| a.get("text"))
10218 .and_then(|t| t.as_str());
10219 let assertion_type = p
10220 .payload
10221 .get("finding")
10222 .and_then(|f| f.get("assertion"))
10223 .and_then(|a| a.get("type"))
10224 .and_then(|t| t.as_str());
10225 let composite = score_map
10226 .get(&p.id)
10227 .map(|(pl, e, s, d)| 0.4 * pl + 0.3 * e + 0.2 * s - 0.3 * d);
10228 json!({
10229 "proposal_id": p.id,
10230 "kind": p.kind,
10231 "actor": p.actor,
10232 "reason": p.reason,
10233 "assertion_text": assertion_text,
10234 "assertion_type": assertion_type,
10235 "reviewer_composite": composite,
10236 })
10237 })
10238 .collect();
10239 println!(
10240 "{}",
10241 serde_json::to_string_pretty(&json!({
10242 "ok": true,
10243 "command": "inbox",
10244 "shown": pending.len(),
10245 "proposals": payload,
10246 }))
10247 .expect("serialize inbox")
10248 );
10249 return;
10250 }
10251
10252 println!();
10253 println!(
10254 " {}",
10255 format!(
10256 "VELA · INBOX · {} ({} pending shown)",
10257 path.display(),
10258 pending.len()
10259 )
10260 .to_uppercase()
10261 .dimmed()
10262 );
10263 println!(" {}", style::tick_row(60));
10264 if pending.is_empty() {
10265 println!(" (inbox clean)");
10266 return;
10267 }
10268 for p in &pending {
10269 let assertion_text = p
10270 .payload
10271 .get("finding")
10272 .and_then(|f| f.get("assertion"))
10273 .and_then(|a| a.get("text"))
10274 .and_then(|t| t.as_str())
10275 .unwrap_or("");
10276 let assertion_type = p
10277 .payload
10278 .get("finding")
10279 .and_then(|f| f.get("assertion"))
10280 .and_then(|a| a.get("type"))
10281 .and_then(|t| t.as_str())
10282 .unwrap_or("");
10283 let composite = score_map
10284 .get(&p.id)
10285 .map(|(pl, e, s, d)| 0.4 * pl + 0.3 * e + 0.2 * s - 0.3 * d);
10286 let score_str = composite
10287 .map(|c| format!("[{:.2}]", c))
10288 .unwrap_or_else(|| "[—] ".to_string());
10289 let kind_short = if p.kind.len() > 12 {
10290 format!("{}…", &p.kind[..11])
10291 } else {
10292 p.kind.clone()
10293 };
10294 let summary: String = if !assertion_text.is_empty() {
10295 assertion_text.chars().take(80).collect()
10296 } else {
10297 p.reason.chars().take(80).collect()
10298 };
10299 println!(
10300 " {} {} {:<13} {:<18} {}",
10301 score_str, p.id, kind_short, assertion_type, summary
10302 );
10303 }
10304 println!();
10305}
10306
10307fn cmd_ask(path: &Path, question: &str, json: bool) {
10312 let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
10313
10314 if question.trim().is_empty() {
10315 use std::io::{BufRead, Write};
10317 println!();
10318 println!(
10319 " {}",
10320 format!("VELA · ASK · {}", path.display())
10321 .to_uppercase()
10322 .dimmed()
10323 );
10324 println!(" {}", style::tick_row(60));
10325 println!(" Ask a question. Type `exit` to quit.");
10326 println!(" Examples:");
10327 println!(" · what's pending?");
10328 println!(" · what's underidentified?");
10329 println!(" · how many findings?");
10330 println!(" · what changed recently?");
10331 println!(" · who has what calibration?");
10332 println!();
10333 let stdin = std::io::stdin();
10334 let mut stdout = std::io::stdout();
10335 loop {
10336 print!(" ask> ");
10337 stdout.flush().ok();
10338 let mut line = String::new();
10339 if stdin.lock().read_line(&mut line).is_err() {
10340 break;
10341 }
10342 let q = line.trim();
10343 if q.is_empty() {
10344 continue;
10345 }
10346 if matches!(q, "exit" | "quit" | "q") {
10347 break;
10348 }
10349 answer(&project, q, false);
10350 }
10351 return;
10352 }
10353
10354 answer(&project, question, json);
10355}
10356
10357fn answer(project: &crate::project::Project, q: &str, json: bool) {
10358 let lower = q.to_lowercase();
10359
10360 if lower.contains("pending")
10362 || lower.contains("inbox")
10363 || lower.contains("queue")
10364 || lower.contains("to review")
10365 {
10366 let pending: Vec<&crate::proposals::StateProposal> = project
10367 .proposals
10368 .iter()
10369 .filter(|p| p.status == "pending_review")
10370 .collect();
10371 let mut by_kind: std::collections::BTreeMap<String, usize> = Default::default();
10372 for p in &pending {
10373 *by_kind.entry(p.kind.clone()).or_insert(0) += 1;
10374 }
10375 if json {
10376 println!(
10377 "{}",
10378 serde_json::to_string_pretty(&json!({
10379 "answer": "pending",
10380 "total": pending.len(),
10381 "by_kind": by_kind,
10382 }))
10383 .unwrap()
10384 );
10385 } else {
10386 println!(" {} pending proposals.", pending.len());
10387 for (k, n) in &by_kind {
10388 println!(" · {n:>3} {k}");
10389 }
10390 if pending.is_empty() {
10391 println!(" Inbox is clean.");
10392 } else {
10393 println!(" Run `vela inbox <frontier>` to triage.");
10394 }
10395 }
10396 return;
10397 }
10398
10399 if lower.contains("underident")
10401 || lower.contains("audit")
10402 || lower.contains("identif")
10403 || lower.contains("causal")
10404 {
10405 let entries = crate::causal_reasoning::audit_frontier(project);
10406 let summary = crate::causal_reasoning::summarize_audit(&entries);
10407 if json {
10408 println!(
10409 "{}",
10410 serde_json::to_string_pretty(&json!({
10411 "answer": "audit",
10412 "summary": {
10413 "identified": summary.identified,
10414 "conditional": summary.conditional,
10415 "underidentified": summary.underidentified,
10416 "underdetermined": summary.underdetermined,
10417 },
10418 }))
10419 .unwrap()
10420 );
10421 } else {
10422 println!(
10423 " Causal audit: {} identified · {} conditional · {} underidentified · {} underdetermined.",
10424 summary.identified,
10425 summary.conditional,
10426 summary.underidentified,
10427 summary.underdetermined,
10428 );
10429 if summary.underidentified > 0 {
10430 println!(
10431 " The {} underidentified findings are concrete review items:",
10432 summary.underidentified
10433 );
10434 for e in entries
10435 .iter()
10436 .filter(|e| {
10437 matches!(
10438 e.verdict,
10439 crate::causal_reasoning::Identifiability::Underidentified
10440 )
10441 })
10442 .take(8)
10443 {
10444 let txt: String = e.assertion_text.chars().take(70).collect();
10445 println!(" · {} {}", e.finding_id, txt);
10446 }
10447 }
10448 }
10449 return;
10450 }
10451
10452 if lower.contains("recent")
10454 || lower.contains("changed")
10455 || lower.contains("latest")
10456 || lower.contains("happen")
10457 {
10458 let mut events: Vec<&crate::events::StateEvent> = project.events.iter().collect();
10459 events.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
10460 events.truncate(8);
10461 if json {
10462 println!(
10463 "{}",
10464 serde_json::to_string_pretty(&json!({
10465 "answer": "recent_events",
10466 "events": events.iter().map(|e| json!({
10467 "id": e.id, "kind": e.kind, "timestamp": e.timestamp,
10468 "actor": e.actor.id, "target": e.target.id,
10469 })).collect::<Vec<_>>(),
10470 }))
10471 .unwrap()
10472 );
10473 } else {
10474 println!(" Most recent {} events:", events.len());
10475 for e in &events {
10476 let when = fmt_timestamp(&e.timestamp);
10477 println!(" · {when} {:<28} {}", e.kind, e.target.id);
10478 }
10479 }
10480 return;
10481 }
10482
10483 if lower.starts_with("how many") || lower.contains("count") || lower.contains("total") {
10485 let n = project.findings.len();
10486 let evs = project.events.len();
10487 let peers = project.peers.len();
10488 let actors = project.actors.len();
10489 if json {
10490 println!(
10491 "{}",
10492 serde_json::to_string_pretty(&json!({
10493 "answer": "counts",
10494 "findings": n,
10495 "events": evs,
10496 "peers": peers,
10497 "actors": actors,
10498 "replications": project.replications.len(),
10499 "predictions": project.predictions.len(),
10500 }))
10501 .unwrap()
10502 );
10503 } else {
10504 println!(" {n} findings · {evs} events · {actors} actors · {peers} peers.");
10505 println!(
10506 " {} replications · {} predictions · {} datasets · {} code artifacts.",
10507 project.replications.len(),
10508 project.predictions.len(),
10509 project.datasets.len(),
10510 project.code_artifacts.len(),
10511 );
10512 }
10513 return;
10514 }
10515
10516 if lower.contains("calibration") || lower.contains("brier") || lower.contains("predict") {
10518 let records =
10519 crate::calibration::calibration_records(&project.predictions, &project.resolutions);
10520 if json {
10521 println!("{}", serde_json::to_string_pretty(&records).unwrap());
10522 } else if records.is_empty() {
10523 println!(" No predictions yet. The calibration ledger is empty.");
10524 } else {
10525 println!(" Calibration over {} actor(s):", records.len());
10526 for r in &records {
10527 let brier = r
10528 .brier_score
10529 .map(|b| format!("{:.3}", b))
10530 .unwrap_or_else(|| "—".into());
10531 println!(
10532 " · {:<28} predictions {} · resolved {} · expired {} · Brier {}",
10533 r.actor, r.n_predictions, r.n_resolved, r.n_expired, brier
10534 );
10535 }
10536 }
10537 return;
10538 }
10539
10540 if lower.contains("peer")
10542 || lower.contains("federat")
10543 || lower.contains("sync")
10544 || lower.contains("conflict")
10545 {
10546 let mut total_conflicts = 0usize;
10547 for e in &project.events {
10548 if e.kind == "frontier.conflict_detected" {
10549 total_conflicts += 1;
10550 }
10551 }
10552 if json {
10553 println!(
10554 "{}",
10555 serde_json::to_string_pretty(&json!({
10556 "answer": "federation",
10557 "peers": project.peers.iter().map(|p| &p.id).collect::<Vec<_>>(),
10558 "total_conflicts": total_conflicts,
10559 }))
10560 .unwrap()
10561 );
10562 } else {
10563 println!(" {} peer(s) registered:", project.peers.len());
10564 for p in &project.peers {
10565 println!(" · {:<24} {}", p.id, p.url);
10566 }
10567 println!(" {total_conflicts} conflict events on the canonical log.");
10568 }
10569 return;
10570 }
10571
10572 if json {
10574 println!(
10575 "{}",
10576 serde_json::to_string_pretty(&json!({
10577 "answer": "unknown_question",
10578 "question": q,
10579 "hint": "Try: pending, audit, recent, how many, calibration, peers."
10580 }))
10581 .unwrap()
10582 );
10583 } else {
10584 println!(" Don't know how to route that question yet.");
10585 println!(" Try: pending · audit · recent · how many · calibration · peers");
10586 }
10587}
10588
10589fn frontier_label(p: &crate::project::Project) -> String {
10590 if p.project.name.trim().is_empty() {
10591 "(unnamed)".to_string()
10592 } else {
10593 p.project.name.clone()
10594 }
10595}
10596
10597fn fmt_timestamp(ts: &str) -> String {
10598 chrono::DateTime::parse_from_rfc3339(ts)
10601 .map(|dt| dt.format("%m-%d %H:%M").to_string())
10602 .unwrap_or_else(|_| ts.chars().take(16).collect())
10603}
10604
10605fn cmd_stats(path: &Path) {
10606 let frontier = load_frontier_or_fail(path);
10607 let s = &frontier.stats;
10608 println!();
10609 println!(" {}", "FRONTIER · V0.36.0".dimmed());
10610 println!(" {}", frontier.project.name.bold());
10611 println!(" {}", style::tick_row(60));
10612 println!(" id: {}", frontier.frontier_id());
10613 println!(" compiled: {}", frontier.project.compiled_at);
10614 println!(" papers: {}", frontier.project.papers_processed);
10615 println!(" findings: {}", s.findings);
10616 println!(" links: {}", s.links);
10617 println!(" replicated: {}", s.replicated);
10618 println!(" avg confidence: {}", s.avg_confidence);
10619 println!(" gaps: {}", s.gaps);
10620 println!(" contested: {}", s.contested);
10621 println!(" reviewed: {}", s.human_reviewed);
10622 println!(" proposals: {}", s.proposal_count);
10623 println!(
10624 " recorded proof: {}",
10625 frontier.proof_state.latest_packet.status
10626 );
10627 if frontier.proof_state.latest_packet.status != "never_exported" {
10628 println!(
10629 " proof note: recorded frontier metadata; packet files are checked by `vela packet validate`"
10630 );
10631 }
10632 if !s.categories.is_empty() {
10633 println!();
10634 println!(" {}", "categories".dimmed());
10635 let mut categories = s.categories.iter().collect::<Vec<_>>();
10636 categories.sort_by(|a, b| b.1.cmp(a.1));
10637 for (category, count) in categories {
10638 println!(" {category}: {}", count);
10639 }
10640 }
10641 println!();
10642 println!(" {}", style::tick_row(60));
10643 println!();
10644}
10645
10646fn cmd_proposals(action: ProposalAction) {
10647 match action {
10648 ProposalAction::List {
10649 frontier,
10650 status,
10651 json,
10652 } => {
10653 let frontier_state =
10654 repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
10655 let proposals_list = proposals::list(&frontier_state, status.as_deref());
10656 let payload = json!({
10657 "ok": true,
10658 "command": "proposals.list",
10659 "frontier": frontier_state.project.name,
10660 "status_filter": status,
10661 "summary": proposals::summary(&frontier_state),
10662 "proposals": proposals_list,
10663 });
10664 if json {
10665 println!(
10666 "{}",
10667 serde_json::to_string_pretty(&payload)
10668 .expect("failed to serialize proposals list")
10669 );
10670 } else {
10671 println!("vela proposals list");
10672 println!(" frontier: {}", frontier_state.project.name);
10673 println!(
10674 " proposals: {}",
10675 payload["proposals"].as_array().map_or(0, Vec::len)
10676 );
10677 }
10678 }
10679 ProposalAction::Show {
10680 frontier,
10681 proposal_id,
10682 json,
10683 } => {
10684 let frontier_state =
10685 repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
10686 let proposal =
10687 proposals::show(&frontier_state, &proposal_id).unwrap_or_else(|e| fail_return(&e));
10688 let payload = json!({
10689 "ok": true,
10690 "command": "proposals.show",
10691 "frontier": frontier_state.project.name,
10692 "proposal": proposal,
10693 });
10694 if json {
10695 println!(
10696 "{}",
10697 serde_json::to_string_pretty(&payload)
10698 .expect("failed to serialize proposal show")
10699 );
10700 } else {
10701 println!("vela proposals show");
10702 println!(" frontier: {}", frontier_state.project.name);
10703 println!(" proposal: {}", proposal_id);
10704 println!(" kind: {}", proposal.kind);
10705 println!(" status: {}", proposal.status);
10706 }
10707 }
10708 ProposalAction::Preview {
10709 frontier,
10710 proposal_id,
10711 reviewer,
10712 json,
10713 } => {
10714 let preview = proposals::preview_at_path(&frontier, &proposal_id, &reviewer)
10715 .unwrap_or_else(|e| fail_return(&e));
10716 let payload = json!({
10717 "ok": true,
10718 "command": "proposals.preview",
10719 "frontier": frontier.display().to_string(),
10720 "preview": preview,
10721 });
10722 if json {
10723 println!(
10724 "{}",
10725 serde_json::to_string_pretty(&payload)
10726 .expect("failed to serialize proposal preview")
10727 );
10728 } else {
10729 println!("vela proposals preview");
10730 println!(" proposal: {}", proposal_id);
10731 println!(" kind: {}", preview.kind);
10732 println!(
10733 " findings: {} -> {}",
10734 preview.findings_before, preview.findings_after
10735 );
10736 println!(
10737 " artifacts: {} -> {}",
10738 preview.artifacts_before, preview.artifacts_after
10739 );
10740 println!(
10741 " events: {} -> {}",
10742 preview.events_before, preview.events_after
10743 );
10744 if !preview.changed_findings.is_empty() {
10745 println!(
10746 " findings changed: {}",
10747 preview.changed_findings.join(", ")
10748 );
10749 }
10750 if !preview.changed_artifacts.is_empty() {
10751 println!(
10752 " artifacts changed: {}",
10753 preview.changed_artifacts.join(", ")
10754 );
10755 }
10756 if !preview.event_kinds.is_empty() {
10757 println!(" event kinds: {}", preview.event_kinds.join(", "));
10758 }
10759 println!(" event: {}", preview.applied_event_id);
10760 }
10761 }
10762 ProposalAction::Import {
10763 frontier,
10764 source,
10765 json,
10766 } => {
10767 let report =
10768 proposals::import_from_path(&frontier, &source).unwrap_or_else(|e| fail_return(&e));
10769 let payload = json!({
10770 "ok": true,
10771 "command": "proposals.import",
10772 "frontier": frontier.display().to_string(),
10773 "source": source.display().to_string(),
10774 "summary": {
10775 "imported": report.imported,
10776 "applied": report.applied,
10777 "rejected": report.rejected,
10778 "duplicates": report.duplicates,
10779 },
10780 });
10781 if json {
10782 println!(
10783 "{}",
10784 serde_json::to_string_pretty(&payload)
10785 .expect("failed to serialize proposal import")
10786 );
10787 } else {
10788 println!(
10789 "Imported {} proposals into {}",
10790 report.imported, report.wrote_to
10791 );
10792 }
10793 }
10794 ProposalAction::Validate { source, json } => {
10795 let report = proposals::validate_source(&source).unwrap_or_else(|e| fail_return(&e));
10796 let payload = json!({
10797 "ok": report.ok,
10798 "command": "proposals.validate",
10799 "source": source.display().to_string(),
10800 "summary": {
10801 "checked": report.checked,
10802 "valid": report.valid,
10803 "invalid": report.invalid,
10804 },
10805 "proposal_ids": report.proposal_ids,
10806 "errors": report.errors,
10807 });
10808 if json {
10809 println!(
10810 "{}",
10811 serde_json::to_string_pretty(&payload)
10812 .expect("failed to serialize proposal validation")
10813 );
10814 } else if report.ok {
10815 println!("{} validated {} proposals", style::ok("ok"), report.valid);
10816 } else {
10817 println!(
10818 "{} validated {} proposals, {} invalid",
10819 style::lost("lost"),
10820 report.valid,
10821 report.invalid
10822 );
10823 for error in &report.errors {
10824 println!(" · {error}");
10825 }
10826 std::process::exit(1);
10827 }
10828 }
10829 ProposalAction::Export {
10830 frontier,
10831 output,
10832 status,
10833 json,
10834 } => {
10835 let count = proposals::export_to_path(&frontier, &output, status.as_deref())
10836 .unwrap_or_else(|e| fail_return(&e));
10837 let payload = json!({
10838 "ok": true,
10839 "command": "proposals.export",
10840 "frontier": frontier.display().to_string(),
10841 "output": output.display().to_string(),
10842 "status": status,
10843 "exported": count,
10844 });
10845 if json {
10846 println!(
10847 "{}",
10848 serde_json::to_string_pretty(&payload)
10849 .expect("failed to serialize proposal export")
10850 );
10851 } else {
10852 println!("sealed · {count} proposals · {}", output.display());
10853 }
10854 }
10855 ProposalAction::Accept {
10856 frontier,
10857 proposal_id,
10858 reviewer,
10859 reason,
10860 json,
10861 } => {
10862 let event_id = proposals::accept_at_path(&frontier, &proposal_id, &reviewer, &reason)
10863 .unwrap_or_else(|e| fail_return(&e));
10864 let payload = json!({
10865 "ok": true,
10866 "command": "proposals.accept",
10867 "frontier": frontier.display().to_string(),
10868 "proposal_id": proposal_id,
10869 "reviewer": reviewer,
10870 "applied_event_id": event_id,
10871 });
10872 if json {
10873 println!(
10874 "{}",
10875 serde_json::to_string_pretty(&payload)
10876 .expect("failed to serialize proposal accept")
10877 );
10878 } else {
10879 println!(
10880 "{} accepted and applied proposal {}",
10881 style::ok("ok"),
10882 proposal_id
10883 );
10884 println!(" event: {}", event_id);
10885 }
10886 }
10887 ProposalAction::Reject {
10888 frontier,
10889 proposal_id,
10890 reviewer,
10891 reason,
10892 json,
10893 } => {
10894 proposals::reject_at_path(&frontier, &proposal_id, &reviewer, &reason)
10895 .unwrap_or_else(|e| fail_return(&e));
10896 let payload = json!({
10897 "ok": true,
10898 "command": "proposals.reject",
10899 "frontier": frontier.display().to_string(),
10900 "proposal_id": proposal_id,
10901 "reviewer": reviewer,
10902 "status": "rejected",
10903 });
10904 if json {
10905 println!(
10906 "{}",
10907 serde_json::to_string_pretty(&payload)
10908 .expect("failed to serialize proposal reject")
10909 );
10910 } else {
10911 println!(
10912 "{} rejected proposal {}",
10913 style::warn("rejected"),
10914 proposal_id
10915 );
10916 }
10917 }
10918 }
10919}
10920
10921fn cmd_artifact_to_state(
10922 frontier: &Path,
10923 packet: &Path,
10924 actor: &str,
10925 apply_artifacts: bool,
10926 json: bool,
10927) {
10928 let report =
10929 crate::artifact_to_state::import_packet_at_path(frontier, packet, actor, apply_artifacts)
10930 .unwrap_or_else(|e| fail_return(&e));
10931 if json {
10932 println!(
10933 "{}",
10934 serde_json::to_string_pretty(&report)
10935 .expect("failed to serialize artifact-to-state report")
10936 );
10937 } else {
10938 println!("vela artifact-to-state");
10939 println!(" packet: {}", report.packet_id);
10940 println!(" frontier: {}", report.frontier);
10941 println!(" artifact proposals: {}", report.artifact_proposals);
10942 println!(" finding proposals: {}", report.finding_proposals);
10943 println!(" gap proposals: {}", report.gap_proposals);
10944 println!(
10945 " applied artifact events: {}",
10946 report.applied_artifact_events
10947 );
10948 println!(
10949 " pending truth proposals: {}",
10950 report.pending_truth_proposals
10951 );
10952 }
10953}
10954
10955async fn cmd_bridge_kit(action: BridgeKitAction) {
10956 match action {
10957 BridgeKitAction::Validate { source, json } => {
10958 let report = crate::artifact_to_state::validate_bridge_kit_path(&source);
10959 if json {
10960 println!(
10961 "{}",
10962 serde_json::to_string_pretty(&report)
10963 .expect("failed to serialize bridge-kit validation report")
10964 );
10965 } else {
10966 println!("vela bridge-kit validate");
10967 println!(" source: {}", report.source);
10968 println!(" packets: {}", report.packet_count);
10969 println!(" valid: {}", report.valid_packet_count);
10970 println!(" invalid: {}", report.invalid_packet_count);
10971 for packet in &report.packets {
10972 if packet.ok {
10973 println!(
10974 " ok: {} · {} artifacts · {} claims · {} needs",
10975 packet
10976 .packet_id
10977 .as_deref()
10978 .unwrap_or("packet id unavailable"),
10979 packet.artifact_count,
10980 packet.candidate_claim_count,
10981 packet.open_need_count
10982 );
10983 } else {
10984 println!(" invalid: {} · {}", packet.path, packet.errors.join("; "));
10985 }
10986 }
10987 for error in &report.errors {
10988 println!(" error: {error}");
10989 }
10990 }
10991 if !report.ok {
10992 std::process::exit(1);
10993 }
10994 }
10995 BridgeKitAction::VerifyProvenance {
10996 packet,
10997 json,
10998 cross_check,
10999 } => {
11000 let mut report = verify_packet_provenance(&packet).await;
11001 if cross_check {
11002 cross_check_packet_provenance(&packet, &mut report).await;
11003 }
11004 if json {
11005 println!(
11006 "{}",
11007 serde_json::to_string_pretty(&report)
11008 .expect("failed to serialize provenance verification report")
11009 );
11010 } else {
11011 println!("vela bridge-kit verify-provenance");
11012 println!(" packet: {}", report.packet);
11013 println!(" identifiers: {}", report.identifiers.len());
11014 println!(" resolved: {}", report.resolved_count);
11015 println!(" unresolved: {}", report.unresolved_count);
11016 println!(" skipped: {}", report.skipped_count);
11017 for entry in &report.identifiers {
11018 let status = match entry.status.as_str() {
11019 "resolved" => "ok ",
11020 "unresolved" => "FAIL",
11021 "skipped" => "skip",
11022 _ => "? ",
11023 };
11024 println!(
11025 " {} {} ({})",
11026 status,
11027 entry.identifier,
11028 entry.note.as_deref().unwrap_or(entry.kind.as_str())
11029 );
11030 }
11031 }
11032 if report.unresolved_count > 0 {
11033 std::process::exit(1);
11034 }
11035 }
11036 }
11037}
11038
11039#[derive(Debug, Clone, Serialize)]
11040struct ProvenanceVerificationReport {
11041 command: String,
11042 packet: String,
11043 identifiers: Vec<ProvenanceVerificationEntry>,
11044 resolved_count: usize,
11045 unresolved_count: usize,
11046 skipped_count: usize,
11047 #[serde(skip_serializing_if = "Option::is_none")]
11052 cross_check: Option<Vec<CrossCheckEntry>>,
11053}
11054
11055#[derive(Debug, Clone, Serialize)]
11056struct ProvenanceVerificationEntry {
11057 identifier: String,
11058 kind: String,
11059 status: String,
11060 #[serde(skip_serializing_if = "Option::is_none")]
11061 note: Option<String>,
11062 #[serde(skip_serializing_if = "Option::is_none")]
11065 title: Option<String>,
11066 #[serde(skip_serializing_if = "Option::is_none")]
11069 first_author: Option<String>,
11070}
11071
11072#[derive(Debug, Clone, Serialize)]
11076struct CrossCheckEntry {
11077 identifiers: Vec<String>,
11079 sources: Vec<CrossCheckSource>,
11081 consensus: String,
11085 #[serde(skip_serializing_if = "Option::is_none")]
11086 note: Option<String>,
11087}
11088
11089#[derive(Debug, Clone, Serialize)]
11090struct CrossCheckSource {
11091 source: String,
11092 identifier: String,
11093 #[serde(skip_serializing_if = "Option::is_none")]
11094 title: Option<String>,
11095 #[serde(skip_serializing_if = "Option::is_none")]
11096 first_author: Option<String>,
11097}
11098
11099async fn verify_packet_provenance(packet_path: &Path) -> ProvenanceVerificationReport {
11104 use crate::artifact_to_state::ArtifactPacket;
11105 let raw = std::fs::read_to_string(packet_path)
11106 .unwrap_or_else(|e| fail_return(&format!("read packet: {e}")));
11107 let parsed: ArtifactPacket =
11108 serde_json::from_str(&raw).unwrap_or_else(|e| fail_return(&format!("parse packet: {e}")));
11109 let packet = parsed
11110 .validate()
11111 .unwrap_or_else(|e| fail_return(&format!("validate packet: {e}")));
11112
11113 let mut candidates: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
11115 for artifact in &packet.artifacts {
11116 if let Some(ident) = extract_identifier(&artifact.locator) {
11117 candidates.insert(ident);
11118 }
11119 }
11120 for claim in &packet.candidate_claims {
11121 for source_ref in &claim.source_refs {
11122 if let Some(ident) = extract_identifier(source_ref) {
11123 candidates.insert(ident);
11124 }
11125 }
11126 }
11127
11128 let client = reqwest::Client::builder()
11129 .user_agent("vela/0.108 (+https://github.com/vela-science/vela)")
11130 .timeout(std::time::Duration::from_secs(15))
11131 .build()
11132 .unwrap_or_else(|e| fail_return(&format!("build http client: {e}")));
11133
11134 let mut entries: Vec<ProvenanceVerificationEntry> = Vec::new();
11135 let mut resolved = 0usize;
11136 let mut unresolved = 0usize;
11137 let mut skipped = 0usize;
11138 for candidate in &candidates {
11139 let entry = if let Some(doi) = candidate.strip_prefix("doi:") {
11140 verify_doi(&client, doi).await
11141 } else if let Some(pmid) = candidate.strip_prefix("pmid:") {
11142 verify_pmid(&client, pmid).await
11143 } else if let Some(s2_id) = candidate.strip_prefix("s2:") {
11144 verify_s2(&client, s2_id).await
11145 } else if let Some(arxiv_id) = candidate.strip_prefix("arxiv:") {
11146 verify_arxiv(&client, arxiv_id).await
11147 } else {
11148 ProvenanceVerificationEntry {
11149 identifier: candidate.clone(),
11150 kind: "unknown".to_string(),
11151 status: "skipped".to_string(),
11152 note: Some("no recognized identifier prefix".to_string()),
11153 title: None,
11154 first_author: None,
11155 }
11156 };
11157 match entry.status.as_str() {
11158 "resolved" => resolved += 1,
11159 "unresolved" => unresolved += 1,
11160 _ => skipped += 1,
11161 }
11162 entries.push(entry);
11163 }
11164
11165 ProvenanceVerificationReport {
11166 command: "bridge-kit.verify-provenance".to_string(),
11167 packet: packet_path.display().to_string(),
11168 identifiers: entries,
11169 resolved_count: resolved,
11170 unresolved_count: unresolved,
11171 skipped_count: skipped,
11172 cross_check: None,
11173 }
11174}
11175
11176async fn cross_check_packet_provenance(
11186 packet_path: &Path,
11187 report: &mut ProvenanceVerificationReport,
11188) {
11189 use crate::artifact_to_state::ArtifactPacket;
11190 let raw = std::fs::read_to_string(packet_path)
11194 .unwrap_or_else(|e| fail_return(&format!("read packet: {e}")));
11195 let parsed: ArtifactPacket =
11196 serde_json::from_str(&raw).unwrap_or_else(|e| fail_return(&format!("parse packet: {e}")));
11197 let packet = parsed
11198 .validate()
11199 .unwrap_or_else(|e| fail_return(&format!("validate packet: {e}")));
11200
11201 let by_ident: std::collections::HashMap<String, &ProvenanceVerificationEntry> = report
11203 .identifiers
11204 .iter()
11205 .filter(|e| e.status == "resolved")
11206 .map(|e| (e.identifier.clone(), e))
11207 .collect();
11208
11209 let mut cross_entries: Vec<CrossCheckEntry> = Vec::new();
11210 for artifact in &packet.artifacts {
11211 let Some(ident) = extract_identifier(&artifact.locator) else {
11219 continue;
11220 };
11221 let Some(entry) = by_ident.get(&ident) else {
11222 continue;
11223 };
11224 let source = CrossCheckSource {
11225 source: entry.kind.clone(),
11226 identifier: entry.identifier.clone(),
11227 title: entry.title.clone(),
11228 first_author: entry.first_author.clone(),
11229 };
11230 cross_entries.push(CrossCheckEntry {
11231 identifiers: vec![entry.identifier.clone()],
11232 sources: vec![source],
11233 consensus: "insufficient".to_string(),
11234 note: Some("only one source resolved for this artifact".to_string()),
11235 });
11236 }
11237
11238 for claim in &packet.candidate_claims {
11243 let mut cluster_idents: Vec<String> = Vec::new();
11244 let mut cluster_sources: Vec<CrossCheckSource> = Vec::new();
11245 for source_ref in &claim.source_refs {
11246 let Some(ident) = extract_identifier(source_ref) else {
11247 continue;
11248 };
11249 let Some(entry) = by_ident.get(&ident) else {
11250 continue;
11251 };
11252 cluster_idents.push(entry.identifier.clone());
11253 cluster_sources.push(CrossCheckSource {
11254 source: entry.kind.clone(),
11255 identifier: entry.identifier.clone(),
11256 title: entry.title.clone(),
11257 first_author: entry.first_author.clone(),
11258 });
11259 }
11260 if cluster_sources.len() >= 2 {
11261 let mut title_mismatch = false;
11266 let mut author_mismatch = false;
11267 for i in 0..cluster_sources.len() {
11268 for j in (i + 1)..cluster_sources.len() {
11269 let a = &cluster_sources[i];
11270 let b = &cluster_sources[j];
11271 if let (Some(ta), Some(tb)) = (&a.title, &b.title)
11272 && ta != tb
11273 {
11274 title_mismatch = true;
11275 }
11276 if let (Some(la), Some(lb)) = (&a.first_author, &b.first_author) {
11277 if !la.is_empty()
11287 && !lb.is_empty()
11288 && !la.starts_with(lb.as_str())
11289 && !lb.starts_with(la.as_str())
11290 {
11291 author_mismatch = true;
11292 }
11293 }
11294 }
11295 }
11296 let consensus = match (title_mismatch, author_mismatch) {
11297 (false, false) => "agree".to_string(),
11298 (true, false) => "title_mismatch".to_string(),
11299 (false, true) => "author_mismatch".to_string(),
11300 (true, true) => "both_mismatch".to_string(),
11301 };
11302 cross_entries.push(CrossCheckEntry {
11303 identifiers: cluster_idents,
11304 sources: cluster_sources,
11305 consensus,
11306 note: None,
11307 });
11308 }
11309 }
11310
11311 report.cross_check = Some(cross_entries);
11312}
11313
11314fn extract_identifier(s: &str) -> Option<String> {
11319 let trimmed = s.trim();
11320 if trimmed.is_empty() {
11321 return None;
11322 }
11323 if trimmed.starts_with("doi:")
11325 || trimmed.starts_with("pmid:")
11326 || trimmed.starts_with("s2:")
11327 || trimmed.starts_with("arxiv:")
11328 {
11329 return Some(trimmed.to_string());
11330 }
11331 for prefix in ["https://doi.org/", "http://doi.org/", "https://dx.doi.org/"] {
11333 if let Some(rest) = trimmed.strip_prefix(prefix) {
11334 return Some(format!("doi:{rest}"));
11335 }
11336 }
11337 for prefix in [
11339 "https://pubmed.ncbi.nlm.nih.gov/",
11340 "http://pubmed.ncbi.nlm.nih.gov/",
11341 ] {
11342 if let Some(rest) = trimmed.strip_prefix(prefix) {
11343 let pmid = rest.trim_end_matches('/');
11344 return Some(format!("pmid:{pmid}"));
11345 }
11346 }
11347 for prefix in [
11352 "https://www.semanticscholar.org/paper/",
11353 "http://www.semanticscholar.org/paper/",
11354 "https://api.semanticscholar.org/graph/v1/paper/",
11355 "https://api.semanticscholar.org/v1/paper/",
11356 ] {
11357 if let Some(rest) = trimmed.strip_prefix(prefix) {
11358 let s2_id = rest
11359 .split('/')
11360 .next_back()
11361 .unwrap_or(rest)
11362 .split('?')
11363 .next()
11364 .unwrap_or(rest);
11365 if !s2_id.is_empty() {
11366 return Some(format!("s2:{s2_id}"));
11367 }
11368 }
11369 }
11370 for prefix in [
11375 "https://arxiv.org/abs/",
11376 "http://arxiv.org/abs/",
11377 "https://arxiv.org/pdf/",
11378 "http://arxiv.org/pdf/",
11379 "https://www.arxiv.org/abs/",
11380 ] {
11381 if let Some(rest) = trimmed.strip_prefix(prefix) {
11382 let arxiv_id = rest
11383 .trim_end_matches('/')
11384 .trim_end_matches(".pdf")
11385 .split('?')
11386 .next()
11387 .unwrap_or(rest);
11388 if !arxiv_id.is_empty() {
11389 return Some(format!("arxiv:{arxiv_id}"));
11390 }
11391 }
11392 }
11393 if trimmed.starts_with("10.") && trimmed.contains('/') && !trimmed.contains(' ') {
11395 return Some(format!("doi:{trimmed}"));
11396 }
11397 None
11398}
11399
11400async fn verify_doi(client: &reqwest::Client, doi: &str) -> ProvenanceVerificationEntry {
11401 let url = format!("https://api.crossref.org/works/{doi}");
11402 match client.get(&url).send().await {
11403 Ok(resp) if resp.status().is_success() => {
11404 let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
11408 let title = body
11409 .pointer("/message/title/0")
11410 .and_then(serde_json::Value::as_str)
11411 .map(normalize_title);
11412 let first_author = body
11413 .pointer("/message/author/0/family")
11414 .and_then(serde_json::Value::as_str)
11415 .map(normalize_last_name);
11416 ProvenanceVerificationEntry {
11417 identifier: format!("doi:{doi}"),
11418 kind: "doi".to_string(),
11419 status: "resolved".to_string(),
11420 note: None,
11421 title,
11422 first_author,
11423 }
11424 }
11425 Ok(resp) => ProvenanceVerificationEntry {
11426 identifier: format!("doi:{doi}"),
11427 kind: "doi".to_string(),
11428 status: "unresolved".to_string(),
11429 note: Some(format!("crossref returned {}", resp.status())),
11430 title: None,
11431 first_author: None,
11432 },
11433 Err(e) => ProvenanceVerificationEntry {
11434 identifier: format!("doi:{doi}"),
11435 kind: "doi".to_string(),
11436 status: "skipped".to_string(),
11437 note: Some(format!("crossref unreachable: {e}")),
11438 title: None,
11439 first_author: None,
11440 },
11441 }
11442}
11443
11444fn normalize_title(s: &str) -> String {
11450 let lower = s.to_lowercase();
11451 let stripped: String = lower
11452 .chars()
11453 .filter(|c| c.is_alphanumeric() || c.is_whitespace())
11454 .collect();
11455 stripped.split_whitespace().collect::<Vec<_>>().join(" ")
11456}
11457
11458fn normalize_last_name(s: &str) -> String {
11464 let trimmed = s.trim();
11465 let candidate = if let Some(comma_idx) = trimmed.find(',') {
11466 &trimmed[..comma_idx]
11467 } else if let Some(last_space) = trimmed.rsplit_once(' ') {
11468 last_space.1
11469 } else {
11470 trimmed
11471 };
11472 candidate
11473 .to_lowercase()
11474 .chars()
11475 .filter(|c| c.is_alphanumeric() || *c == '-')
11476 .collect()
11477}
11478
11479async fn verify_pmid(client: &reqwest::Client, pmid: &str) -> ProvenanceVerificationEntry {
11480 let url = format!(
11481 "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id={pmid}&retmode=json"
11482 );
11483 match client.get(&url).send().await {
11484 Ok(resp) if resp.status().is_success() => {
11485 let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
11488 let result = body.get("result");
11489 let uids = result
11490 .and_then(|r| r.get("uids"))
11491 .and_then(|u| u.as_array());
11492 let resolved = uids.is_some_and(|a| !a.is_empty());
11493 if resolved {
11494 let record = result.and_then(|r| r.get(pmid));
11498 let title = record
11499 .and_then(|r| r.get("title"))
11500 .and_then(serde_json::Value::as_str)
11501 .map(normalize_title);
11502 let first_author = record
11503 .and_then(|r| r.get("authors"))
11504 .and_then(serde_json::Value::as_array)
11505 .and_then(|a| a.first())
11506 .and_then(|a| a.get("name"))
11507 .and_then(serde_json::Value::as_str)
11508 .map(normalize_last_name);
11509 ProvenanceVerificationEntry {
11510 identifier: format!("pmid:{pmid}"),
11511 kind: "pmid".to_string(),
11512 status: "resolved".to_string(),
11513 note: None,
11514 title,
11515 first_author,
11516 }
11517 } else {
11518 ProvenanceVerificationEntry {
11519 identifier: format!("pmid:{pmid}"),
11520 kind: "pmid".to_string(),
11521 status: "unresolved".to_string(),
11522 note: Some("eutils returned empty uids".to_string()),
11523 title: None,
11524 first_author: None,
11525 }
11526 }
11527 }
11528 Ok(resp) => ProvenanceVerificationEntry {
11529 identifier: format!("pmid:{pmid}"),
11530 kind: "pmid".to_string(),
11531 status: "unresolved".to_string(),
11532 note: Some(format!("eutils returned {}", resp.status())),
11533 title: None,
11534 first_author: None,
11535 },
11536 Err(e) => ProvenanceVerificationEntry {
11537 identifier: format!("pmid:{pmid}"),
11538 kind: "pmid".to_string(),
11539 status: "skipped".to_string(),
11540 note: Some(format!("eutils unreachable: {e}")),
11541 title: None,
11542 first_author: None,
11543 },
11544 }
11545}
11546
11547async fn verify_s2(client: &reqwest::Client, s2_id: &str) -> ProvenanceVerificationEntry {
11554 let url = format!("https://api.semanticscholar.org/graph/v1/paper/{s2_id}");
11555 match client.get(&url).send().await {
11556 Ok(resp) if resp.status().is_success() => {
11557 let body: serde_json::Value = resp.json().await.unwrap_or(serde_json::Value::Null);
11558 let has_paper_id = body
11559 .get("paperId")
11560 .and_then(serde_json::Value::as_str)
11561 .is_some_and(|v| !v.is_empty());
11562 if has_paper_id {
11563 let title = body
11568 .get("title")
11569 .and_then(serde_json::Value::as_str)
11570 .map(normalize_title);
11571 let first_author = body
11572 .get("authors")
11573 .and_then(serde_json::Value::as_array)
11574 .and_then(|a| a.first())
11575 .and_then(|a| a.get("name"))
11576 .and_then(serde_json::Value::as_str)
11577 .map(normalize_last_name);
11578 ProvenanceVerificationEntry {
11579 identifier: format!("s2:{s2_id}"),
11580 kind: "s2".to_string(),
11581 status: "resolved".to_string(),
11582 note: None,
11583 title,
11584 first_author,
11585 }
11586 } else {
11587 ProvenanceVerificationEntry {
11588 identifier: format!("s2:{s2_id}"),
11589 kind: "s2".to_string(),
11590 status: "unresolved".to_string(),
11591 note: Some("semantic scholar returned 200 with no paperId".to_string()),
11592 title: None,
11593 first_author: None,
11594 }
11595 }
11596 }
11597 Ok(resp) => ProvenanceVerificationEntry {
11598 identifier: format!("s2:{s2_id}"),
11599 kind: "s2".to_string(),
11600 status: "unresolved".to_string(),
11601 note: Some(format!("semantic scholar returned {}", resp.status())),
11602 title: None,
11603 first_author: None,
11604 },
11605 Err(e) => ProvenanceVerificationEntry {
11606 identifier: format!("s2:{s2_id}"),
11607 kind: "s2".to_string(),
11608 status: "skipped".to_string(),
11609 note: Some(format!("semantic scholar unreachable: {e}")),
11610 title: None,
11611 first_author: None,
11612 },
11613 }
11614}
11615
11616async fn verify_arxiv(client: &reqwest::Client, arxiv_id: &str) -> ProvenanceVerificationEntry {
11625 let url = format!("https://export.arxiv.org/api/query?id_list={arxiv_id}&max_results=1");
11626 match client.get(&url).send().await {
11627 Ok(resp) if resp.status().is_success() => {
11628 let body = resp.text().await.unwrap_or_default();
11629 let has_entry = body.contains("<entry>") || body.contains("<entry ");
11633 let has_id_url = body.contains("http://arxiv.org/abs/");
11637 if has_entry && has_id_url {
11638 let title = atom_inner_text(&body, "<entry>", "<title>", "</title>")
11648 .as_deref()
11649 .map(normalize_title);
11650 let first_author = atom_inner_text(&body, "<author>", "<name>", "</name>")
11651 .as_deref()
11652 .map(normalize_last_name);
11653 ProvenanceVerificationEntry {
11654 identifier: format!("arxiv:{arxiv_id}"),
11655 kind: "arxiv".to_string(),
11656 status: "resolved".to_string(),
11657 note: None,
11658 title,
11659 first_author,
11660 }
11661 } else {
11662 ProvenanceVerificationEntry {
11663 identifier: format!("arxiv:{arxiv_id}"),
11664 kind: "arxiv".to_string(),
11665 status: "unresolved".to_string(),
11666 note: Some("arxiv returned 200 with no matching entry".to_string()),
11667 title: None,
11668 first_author: None,
11669 }
11670 }
11671 }
11672 Ok(resp) => ProvenanceVerificationEntry {
11673 identifier: format!("arxiv:{arxiv_id}"),
11674 kind: "arxiv".to_string(),
11675 status: "unresolved".to_string(),
11676 note: Some(format!("arxiv returned {}", resp.status())),
11677 title: None,
11678 first_author: None,
11679 },
11680 Err(e) => ProvenanceVerificationEntry {
11681 identifier: format!("arxiv:{arxiv_id}"),
11682 kind: "arxiv".to_string(),
11683 status: "skipped".to_string(),
11684 note: Some(format!("arxiv unreachable: {e}")),
11685 title: None,
11686 first_author: None,
11687 },
11688 }
11689}
11690
11691fn atom_inner_text(body: &str, scope_open: &str, open: &str, close: &str) -> Option<String> {
11698 let scope_start = body.find(scope_open)?;
11699 let after_scope = &body[scope_start..];
11700 let open_idx = after_scope.find(open)?;
11701 let after_open = &after_scope[open_idx + open.len()..];
11702 let close_idx = after_open.find(close)?;
11703 Some(after_open[..close_idx].trim().to_string())
11704}
11705
11706async fn cmd_source_adapter(action: SourceAdapterAction) {
11707 match action {
11708 SourceAdapterAction::Run {
11709 frontier,
11710 adapter,
11711 actor,
11712 entries,
11713 priority,
11714 include_excluded,
11715 allow_partial,
11716 dry_run,
11717 input_dir,
11718 apply_artifacts,
11719 json,
11720 } => {
11721 let report = crate::source_adapters::run(
11722 &frontier,
11723 crate::source_adapters::SourceAdapterRunOptions {
11724 adapter,
11725 actor,
11726 entries,
11727 priority,
11728 include_excluded,
11729 allow_partial,
11730 dry_run,
11731 input_dir,
11732 apply_artifacts,
11733 },
11734 )
11735 .await
11736 .unwrap_or_else(|e| fail_return(&e));
11737 if json {
11738 println!(
11739 "{}",
11740 serde_json::to_string_pretty(&report)
11741 .expect("failed to serialize source adapter report")
11742 );
11743 } else {
11744 println!("vela source-adapter run");
11745 println!(" adapter: {}", report.adapter);
11746 println!(" run: {}", report.run_id);
11747 println!(" frontier: {}", report.frontier);
11748 println!(" selected entries: {}", report.selected_entries);
11749 println!(" fetched records: {}", report.fetched_records);
11750 println!(" changed records: {}", report.changed_records);
11751 println!(" unchanged records: {}", report.unchanged_records);
11752 println!(" failed records: {}", report.failed_records.len());
11753 if let Some(packet_id) = report.packet_id {
11754 println!(" packet: {packet_id}");
11755 }
11756 println!(" artifact proposals: {}", report.artifact_proposals);
11757 println!(" review note proposals: {}", report.review_note_proposals);
11758 println!(" applied events: {}", report.applied_event_ids.len());
11759 }
11760 }
11761 }
11762}
11763
11764fn cmd_runtime_adapter(action: RuntimeAdapterAction) {
11765 match action {
11766 RuntimeAdapterAction::Run {
11767 frontier,
11768 adapter,
11769 input,
11770 actor,
11771 dry_run,
11772 apply_artifacts,
11773 json,
11774 } => {
11775 let report = crate::runtime_adapters::run(
11776 &frontier,
11777 crate::runtime_adapters::RuntimeAdapterRunOptions {
11778 adapter,
11779 input,
11780 actor,
11781 dry_run,
11782 apply_artifacts,
11783 },
11784 )
11785 .unwrap_or_else(|e| fail_return(&e));
11786 if json {
11787 println!(
11788 "{}",
11789 serde_json::to_string_pretty(&report)
11790 .expect("failed to serialize runtime adapter report")
11791 );
11792 } else {
11793 println!("vela runtime-adapter run");
11794 println!(" adapter: {}", report.adapter);
11795 println!(" run: {}", report.run_id);
11796 println!(" frontier: {}", report.frontier);
11797 if let Some(packet_id) = report.packet_id {
11798 println!(" packet: {packet_id}");
11799 }
11800 println!(" artifact proposals: {}", report.artifact_proposals);
11801 println!(" finding proposals: {}", report.finding_proposals);
11802 println!(" gap proposals: {}", report.gap_proposals);
11803 println!(" review note proposals: {}", report.review_note_proposals);
11804 println!(
11805 " applied artifact events: {}",
11806 report.applied_artifact_events
11807 );
11808 println!(
11809 " pending truth proposals: {}",
11810 report.pending_truth_proposals
11811 );
11812 }
11813 }
11814 }
11815}
11816
11817fn cmd_sign(action: SignAction) {
11818 match action {
11819 SignAction::GenerateKeypair { out, json } => {
11820 let public_key = sign::generate_keypair(&out).unwrap_or_else(|e| fail_return(&e));
11821 let payload = json!({
11822 "ok": true,
11823 "command": "sign.generate-keypair",
11824 "output_dir": out.display().to_string(),
11825 "public_key": public_key,
11826 });
11827 if json {
11828 println!(
11829 "{}",
11830 serde_json::to_string_pretty(&payload)
11831 .expect("failed to serialize sign.generate-keypair")
11832 );
11833 } else {
11834 println!("{} keypair · {}", style::ok("generated"), out.display());
11835 println!(" public key: {public_key}");
11836 }
11837 }
11838 SignAction::Apply {
11839 frontier,
11840 private_key,
11841 json,
11842 } => {
11843 let count =
11844 sign::sign_frontier(&frontier, &private_key).unwrap_or_else(|e| fail_return(&e));
11845 let payload = json!({
11846 "ok": true,
11847 "command": "sign.apply",
11848 "frontier": frontier.display().to_string(),
11849 "private_key": private_key.display().to_string(),
11850 "signed": count,
11851 });
11852 if json {
11853 println!(
11854 "{}",
11855 serde_json::to_string_pretty(&payload).expect("failed to serialize sign.apply")
11856 );
11857 } else {
11858 println!(
11859 "{} {count} findings in {}",
11860 style::ok("signed"),
11861 frontier.display()
11862 );
11863 }
11864 }
11865 SignAction::Verify {
11866 frontier,
11867 public_key,
11868 json,
11869 } => {
11870 let report = sign::verify_frontier(&frontier, public_key.as_deref())
11871 .unwrap_or_else(|e| fail_return(&e));
11872 if json {
11873 println!(
11874 "{}",
11875 serde_json::to_string_pretty(&report).expect("failed to serialize sign.verify")
11876 );
11877 } else {
11878 println!();
11879 println!(
11880 " {}",
11881 format!("VELA · SIGN · VERIFY · {}", frontier.display())
11882 .to_uppercase()
11883 .dimmed()
11884 );
11885 println!(" {}", style::tick_row(60));
11886 println!(" total findings: {}", report.total_findings);
11887 println!(" signed: {}", report.signed);
11888 println!(" unsigned: {}", report.unsigned);
11889 println!(" valid: {}", report.valid);
11890 println!(" invalid: {}", report.invalid);
11891 if report.findings_with_threshold > 0 {
11892 println!(" with threshold: {}", report.findings_with_threshold);
11893 println!(" jointly accepted: {}", report.jointly_accepted);
11894 }
11895 }
11896 }
11897 SignAction::ThresholdSet {
11898 frontier,
11899 finding_id,
11900 to,
11901 json,
11902 } => {
11903 if to == 0 {
11904 fail("--to must be >= 1");
11905 }
11906 let mut project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
11907 let Some(idx) = project.findings.iter().position(|f| f.id == finding_id) else {
11908 fail(&format!("finding '{finding_id}' not present in frontier"));
11909 };
11910 project.findings[idx].flags.signature_threshold = Some(to);
11911 sign::refresh_jointly_accepted(&mut project);
11915 let met = project.findings[idx].flags.jointly_accepted;
11916 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
11917
11918 if json {
11919 println!(
11920 "{}",
11921 serde_json::to_string_pretty(&json!({
11922 "ok": true,
11923 "command": "sign.threshold-set",
11924 "finding_id": finding_id,
11925 "threshold": to,
11926 "jointly_accepted": met,
11927 "frontier": frontier.display().to_string(),
11928 }))
11929 .expect("failed to serialize sign.threshold-set")
11930 );
11931 } else {
11932 println!(
11933 "{} signature_threshold={to} on {finding_id} ({})",
11934 style::ok("set"),
11935 if met {
11936 "jointly accepted"
11937 } else {
11938 "awaiting signatures"
11939 }
11940 );
11941 }
11942 }
11943 }
11944}
11945
11946fn cmd_actor(action: ActorAction) {
11947 match action {
11948 ActorAction::Add {
11949 frontier,
11950 id,
11951 pubkey,
11952 tier,
11953 orcid,
11954 clearance,
11955 json,
11956 } => {
11957 let trimmed = pubkey.trim();
11959 if trimmed.len() != 64 || hex::decode(trimmed).is_err() {
11960 fail("Public key must be 64 hex characters (32-byte Ed25519 pubkey).");
11961 }
11962 let orcid_normalized = orcid
11964 .as_deref()
11965 .map(|s| sign::validate_orcid(s).unwrap_or_else(|e| fail_return(&e)));
11966 let clearance: Option<crate::access_tier::AccessTier> = clearance.as_deref().map(|s| {
11969 crate::access_tier::AccessTier::parse(s).unwrap_or_else(|e| fail_return(&e))
11970 });
11971
11972 let mut project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
11973 if project.actors.iter().any(|actor| actor.id == id) {
11974 fail(&format!(
11975 "Actor '{id}' already registered in this frontier."
11976 ));
11977 }
11978 project.actors.push(sign::ActorRecord {
11979 id: id.clone(),
11980 public_key: trimmed.to_string(),
11981 algorithm: "ed25519".to_string(),
11982 created_at: chrono::Utc::now().to_rfc3339(),
11983 tier: tier.clone(),
11984 orcid: orcid_normalized.clone(),
11985 access_clearance: clearance,
11986 revoked_at: None,
11987 revoked_reason: None,
11988 });
11989 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
11990 let payload = json!({
11991 "ok": true,
11992 "command": "actor.add",
11993 "frontier": frontier.display().to_string(),
11994 "actor_id": id,
11995 "public_key": trimmed,
11996 "tier": tier,
11997 "orcid": orcid_normalized,
11998 "registered_count": project.actors.len(),
11999 });
12000 if json {
12001 println!(
12002 "{}",
12003 serde_json::to_string_pretty(&payload).expect("failed to serialize actor.add")
12004 );
12005 } else {
12006 let tier_suffix = tier
12007 .as_deref()
12008 .map_or_else(String::new, |t| format!(" tier={t}"));
12009 println!(
12010 "{} actor {} (pubkey {}{tier_suffix})",
12011 style::ok("registered"),
12012 id,
12013 &trimmed[..16]
12014 );
12015 }
12016 }
12017 ActorAction::Rotate {
12018 frontier,
12019 id,
12020 new_id,
12021 new_pubkey,
12022 reason,
12023 json,
12024 } => {
12025 let trimmed = new_pubkey.trim();
12027 if trimmed.len() != 64 || hex::decode(trimmed).is_err() {
12028 fail("--new-pubkey must be 64 hex characters (32-byte Ed25519 pubkey).");
12029 }
12030 if reason.trim().is_empty() {
12031 fail("--reason must be non-empty (record why the rotation is happening).");
12032 }
12033 if id == new_id {
12034 fail("--id and --new-id must differ; rotation registers a fresh actor record.");
12035 }
12036
12037 let mut project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
12038
12039 if project.actors.iter().any(|a| a.id == new_id) {
12041 fail(&format!(
12042 "Refusing to rotate: actor '{new_id}' is already registered."
12043 ));
12044 }
12045
12046 let now = chrono::Utc::now().to_rfc3339();
12048 let mut found_old = false;
12049 let mut old_pubkey_prefix: Option<String> = None;
12050 for actor in project.actors.iter_mut() {
12051 if actor.id == id {
12052 if actor.revoked_at.is_some() {
12053 fail(&format!(
12054 "Refusing to rotate: actor '{id}' is already revoked at {}.",
12055 actor.revoked_at.as_deref().unwrap_or("?")
12056 ));
12057 }
12058 actor.revoked_at = Some(now.clone());
12059 actor.revoked_reason = Some(reason.clone());
12060 old_pubkey_prefix = Some(actor.public_key[..16].to_string());
12061 found_old = true;
12062 }
12063 }
12064 if !found_old {
12065 fail(&format!(
12066 "Cannot rotate: actor '{id}' is not registered in this frontier."
12067 ));
12068 }
12069
12070 project.actors.push(sign::ActorRecord {
12072 id: new_id.clone(),
12073 public_key: trimmed.to_string(),
12074 algorithm: "ed25519".to_string(),
12075 created_at: now.clone(),
12076 tier: None,
12077 orcid: None,
12078 access_clearance: None,
12079 revoked_at: None,
12080 revoked_reason: None,
12081 });
12082
12083 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
12084
12085 let payload = json!({
12086 "ok": true,
12087 "command": "actor.rotate",
12088 "frontier": frontier.display().to_string(),
12089 "retired_actor_id": id,
12090 "retired_pubkey_prefix": old_pubkey_prefix,
12091 "new_actor_id": new_id,
12092 "new_pubkey": trimmed,
12093 "revoked_at": now,
12094 "reason": reason,
12095 });
12096 if json {
12097 println!(
12098 "{}",
12099 serde_json::to_string_pretty(&payload)
12100 .expect("failed to serialize actor.rotate")
12101 );
12102 } else {
12103 println!(
12104 "{} actor {} retired (pubkey {}...), {} registered (pubkey {}...)",
12105 style::ok("rotated"),
12106 id,
12107 old_pubkey_prefix.as_deref().unwrap_or("?"),
12108 new_id,
12109 &trimmed[..16]
12110 );
12111 println!(" revoked_at: {now}");
12112 println!(" reason: {reason}");
12113 }
12114 }
12115 ActorAction::List { frontier, json } => {
12116 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
12117 if json {
12118 let payload = json!({
12119 "ok": true,
12120 "command": "actor.list",
12121 "frontier": frontier.display().to_string(),
12122 "actors": project.actors,
12123 });
12124 println!(
12125 "{}",
12126 serde_json::to_string_pretty(&payload).expect("failed to serialize actor.list")
12127 );
12128 } else {
12129 println!();
12130 println!(
12131 " {}",
12132 format!("VELA · ACTOR · LIST · {}", frontier.display())
12133 .to_uppercase()
12134 .dimmed()
12135 );
12136 println!(" {}", style::tick_row(60));
12137 if project.actors.is_empty() {
12138 println!(" (no actors registered)");
12139 } else {
12140 for actor in &project.actors {
12141 println!(
12142 " {:<28} {}… registered {}",
12143 actor.id,
12144 &actor.public_key[..16],
12145 actor.created_at
12146 );
12147 }
12148 }
12149 }
12150 }
12151 ActorAction::LookupOrcid {
12152 orcid,
12153 register_on,
12154 id,
12155 pubkey,
12156 json,
12157 } => cmd_actor_lookup_orcid(orcid, register_on, id, pubkey, json),
12158 }
12159}
12160
12161fn cmd_actor_lookup_orcid(
12164 orcid: String,
12165 register_on: Option<PathBuf>,
12166 id: Option<String>,
12167 pubkey: Option<String>,
12168 json: bool,
12169) {
12170 let normalized = sign::validate_orcid(&orcid).unwrap_or_else(|e| fail_return(&e));
12172
12173 let client = reqwest::blocking::Client::builder()
12175 .user_agent("vela-cli/0.155 (https://github.com/vela-science/vela)")
12176 .timeout(std::time::Duration::from_secs(15))
12177 .build()
12178 .unwrap_or_else(|e| fail_return(&format!("http client init: {e}")));
12179 let url = format!("https://pub.orcid.org/v3.0/{normalized}/person");
12180 let resp_result = client.get(&url).header("Accept", "application/json").send();
12181
12182 let (status_label, name, affiliation, note) = match resp_result {
12183 Ok(resp) if resp.status().is_success() => match resp.json::<serde_json::Value>() {
12184 Ok(body) => {
12185 let given = body
12186 .pointer("/name/given-names/value")
12187 .and_then(|v| v.as_str())
12188 .unwrap_or("")
12189 .to_string();
12190 let family = body
12191 .pointer("/name/family-name/value")
12192 .and_then(|v| v.as_str())
12193 .unwrap_or("")
12194 .to_string();
12195 let display_name = format!("{given} {family}").trim().to_string();
12196 let affil_opt = body
12197 .pointer("/employments/employment-summary/0/organization/name")
12198 .and_then(|v| v.as_str())
12199 .map(str::to_string)
12200 .or_else(|| {
12201 body.pointer("/educations/education-summary/0/organization/name")
12202 .and_then(|v| v.as_str())
12203 .map(str::to_string)
12204 });
12205 (
12206 "resolved",
12207 if display_name.is_empty() {
12208 None
12209 } else {
12210 Some(display_name)
12211 },
12212 affil_opt,
12213 None,
12214 )
12215 }
12216 Err(e) => ("parse_error", None, None, Some(format!("parse: {e}"))),
12217 },
12218 Ok(resp) => (
12219 "http_error",
12220 None,
12221 None,
12222 Some(format!("HTTP {}", resp.status())),
12223 ),
12224 Err(e) => ("unreachable", None, None, Some(format!("{e}"))),
12225 };
12226
12227 let unreachable = status_label == "unreachable";
12228
12229 let mut registered_summary: Option<serde_json::Value> = None;
12231 if let Some(frontier_path) = register_on {
12232 let actor_id = id.unwrap_or_else(|| {
12233 fail_return("--register-on requires --id (stable actor id like `reviewer:will-blair`).")
12234 });
12235 let pubkey_hex = pubkey.unwrap_or_else(|| {
12236 fail_return("--register-on requires --pubkey (64 hex chars Ed25519).")
12237 });
12238 let trimmed = pubkey_hex.trim();
12239 if trimmed.len() != 64 || hex::decode(trimmed).is_err() {
12240 fail("--pubkey must be 64 hex characters (32-byte Ed25519 pubkey).");
12241 }
12242 let mut project = repo::load_from_path(&frontier_path).unwrap_or_else(|e| fail_return(&e));
12243 if project.actors.iter().any(|a| a.id == actor_id) {
12244 fail(&format!(
12245 "Actor '{actor_id}' already registered in this frontier."
12246 ));
12247 }
12248 project.actors.push(sign::ActorRecord {
12249 id: actor_id.clone(),
12250 public_key: trimmed.to_string(),
12251 algorithm: "ed25519".to_string(),
12252 created_at: chrono::Utc::now().to_rfc3339(),
12253 tier: None,
12254 orcid: Some(normalized.clone()),
12255 access_clearance: None,
12256 revoked_at: None,
12257 revoked_reason: None,
12258 });
12259 repo::save_to_path(&frontier_path, &project)
12260 .unwrap_or_else(|e| fail_return(&format!("save: {e}")));
12261 registered_summary = Some(json!({
12262 "frontier": frontier_path.display().to_string(),
12263 "actor_id": actor_id,
12264 "pubkey": trimmed,
12265 "orcid": normalized,
12266 }));
12267 }
12268
12269 let payload = json!({
12270 "ok": !unreachable,
12271 "command": "actor.lookup-orcid",
12272 "orcid": normalized,
12273 "status": status_label,
12274 "name": name,
12275 "affiliation": affiliation,
12276 "note": note,
12277 "registered": registered_summary,
12278 });
12279 if json {
12280 println!(
12281 "{}",
12282 serde_json::to_string_pretty(&payload).expect("serialize lookup-orcid")
12283 );
12284 } else {
12285 match status_label {
12286 "resolved" => {
12287 println!("{} resolved ORCID {normalized}", style::ok("orcid"),);
12288 if let Some(n) = &name {
12289 println!(" name: {n}");
12290 }
12291 if let Some(a) = &affiliation {
12292 println!(" affiliation: {a}");
12293 }
12294 if let Some(reg) = ®istered_summary {
12295 println!(
12296 " registered: actor {} on {}",
12297 reg.get("actor_id").and_then(|v| v.as_str()).unwrap_or("?"),
12298 reg.get("frontier").and_then(|v| v.as_str()).unwrap_or("?")
12299 );
12300 }
12301 }
12302 other => {
12303 eprintln!(
12304 "warn · ORCID lookup {other}: {}",
12305 note.as_deref().unwrap_or("(no detail)")
12306 );
12307 }
12308 }
12309 }
12310 if unreachable {
12311 std::process::exit(0); }
12313}
12314
12315fn cmd_causal(action: CausalAction) {
12317 use crate::causal_reasoning;
12318
12319 match action {
12320 CausalAction::Audit {
12321 frontier,
12322 problems_only,
12323 json,
12324 } => {
12325 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
12326 let mut entries = causal_reasoning::audit_frontier(&project);
12327 if problems_only {
12328 entries.retain(|e| e.verdict.needs_reviewer_attention());
12329 }
12330 let summary = causal_reasoning::summarize_audit(&entries);
12331
12332 if json {
12333 println!(
12334 "{}",
12335 serde_json::to_string_pretty(&json!({
12336 "ok": true,
12337 "command": "causal.audit",
12338 "frontier": frontier.display().to_string(),
12339 "summary": summary,
12340 "entries": entries,
12341 }))
12342 .expect("serialize causal.audit")
12343 );
12344 return;
12345 }
12346
12347 println!();
12348 println!(
12349 " {}",
12350 format!("VELA · CAUSAL · AUDIT · {}", frontier.display())
12351 .to_uppercase()
12352 .dimmed()
12353 );
12354 println!(" {}", style::tick_row(60));
12355 println!(
12356 " total: {} identified: {} conditional: {} underidentified: {} underdetermined: {}",
12357 summary.total,
12358 summary.identified,
12359 summary.conditional,
12360 summary.underidentified,
12361 summary.underdetermined,
12362 );
12363 if entries.is_empty() {
12364 println!(" (no entries to report)");
12365 return;
12366 }
12367 for e in &entries {
12368 let chip = match e.verdict {
12369 crate::causal_reasoning::Identifiability::Identified => style::ok("identified"),
12370 crate::causal_reasoning::Identifiability::Conditional => {
12371 style::warn("conditional")
12372 }
12373 crate::causal_reasoning::Identifiability::Underidentified => {
12374 style::lost("underidentified")
12375 }
12376 crate::causal_reasoning::Identifiability::Underdetermined => {
12377 style::warn("underdetermined")
12378 }
12379 };
12380 let claim = e
12381 .causal_claim
12382 .map_or("none".to_string(), |c| format!("{c:?}").to_lowercase());
12383 let grade = e
12384 .causal_evidence_grade
12385 .map_or("none".to_string(), |g| format!("{g:?}").to_lowercase());
12386 println!();
12387 println!(" {chip} {} ({}/{})", e.finding_id, claim, grade);
12388 let assertion_short: String = e.assertion_text.chars().take(78).collect();
12389 println!(" {assertion_short}");
12390 println!(" {} {}", style::ok("why:"), e.rationale);
12391 if e.verdict.needs_reviewer_attention()
12392 || matches!(
12393 e.verdict,
12394 crate::causal_reasoning::Identifiability::Underdetermined
12395 )
12396 {
12397 println!(" {} {}", style::ok("fix:"), e.remediation);
12398 }
12399 }
12400 }
12401 CausalAction::Effect {
12402 frontier,
12403 source,
12404 on: target,
12405 json,
12406 } => {
12407 use crate::causal_graph::{CausalEffectVerdict, identify_effect};
12408
12409 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
12410 let verdict = identify_effect(&project, &source, &target);
12411
12412 if json {
12413 println!(
12414 "{}",
12415 serde_json::to_string_pretty(&json!({
12416 "ok": true,
12417 "command": "causal.effect",
12418 "frontier": frontier.display().to_string(),
12419 "source": source,
12420 "target": target,
12421 "verdict": verdict,
12422 }))
12423 .expect("serialize causal.effect")
12424 );
12425 return;
12426 }
12427
12428 println!();
12429 println!(
12430 " {}",
12431 format!("VELA · CAUSAL · EFFECT · {} → {}", source, target)
12432 .to_uppercase()
12433 .dimmed()
12434 );
12435 println!(" {}", style::tick_row(60));
12436 match verdict {
12437 CausalEffectVerdict::Identified {
12438 adjustment_set,
12439 back_door_paths_considered,
12440 } => {
12441 if adjustment_set.is_empty() {
12442 println!(
12443 " {} no back-door adjustment needed",
12444 style::ok("identified")
12445 );
12446 } else {
12447 println!(" {} identified by adjusting on:", style::ok("identified"));
12448 for z in &adjustment_set {
12449 println!(" · {z}");
12450 }
12451 }
12452 println!(
12453 " back-door paths considered: {}",
12454 back_door_paths_considered
12455 );
12456 }
12457 CausalEffectVerdict::IdentifiedByFrontDoor { mediator_set } => {
12458 println!(
12459 " {} identified via front-door criterion (Pearl 1995 §3.3)",
12460 style::ok("identified")
12461 );
12462 println!(" mediators that intercept all directed paths:");
12463 for m in &mediator_set {
12464 println!(" · {m}");
12465 }
12466 println!(
12467 " applies when source-target confounders are unobserved but the mediator chain is."
12468 );
12469 }
12470 CausalEffectVerdict::NoCausalPath { reason } => {
12471 println!(" {} no causal path: {reason}", style::warn("no_path"));
12472 }
12473 CausalEffectVerdict::Underidentified {
12474 unblocked_back_door_paths,
12475 candidates_tried,
12476 } => {
12477 println!(
12478 " {} no observational adjustment set found ({} candidates tried)",
12479 style::lost("underidentified"),
12480 candidates_tried
12481 );
12482 println!(" open back-door paths:");
12483 for path in unblocked_back_door_paths.iter().take(5) {
12484 println!(" · {}", path.join(" — "));
12485 }
12486 println!(
12487 " remediation: either intervene experimentally on {source}, or extend the link graph to make a confounder observable."
12488 );
12489 }
12490 CausalEffectVerdict::UnknownNode { which } => {
12491 fail(&which);
12492 }
12493 }
12494 println!();
12495 }
12496 CausalAction::Graph {
12497 frontier,
12498 node,
12499 json,
12500 } => {
12501 use crate::causal_graph::CausalGraph;
12502 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
12503 let graph = CausalGraph::from_project(&project);
12504
12505 let nodes: Vec<&str> = if let Some(n) = node.as_deref() {
12508 if !graph.contains(n) {
12509 fail(&format!("node not in frontier: {n}"));
12510 }
12511 vec![n]
12512 } else {
12513 project.findings.iter().map(|f| f.id.as_str()).collect()
12514 };
12515
12516 if json {
12517 let payload: Vec<_> = nodes
12518 .iter()
12519 .map(|n| {
12520 let parents: Vec<&str> = graph.parents_of(n).collect();
12521 let children: Vec<&str> = graph.children_of(n).collect();
12522 json!({
12523 "node": n,
12524 "parents": parents,
12525 "children": children,
12526 })
12527 })
12528 .collect();
12529 println!(
12530 "{}",
12531 serde_json::to_string_pretty(&json!({
12532 "ok": true,
12533 "command": "causal.graph",
12534 "node_count": graph.node_count(),
12535 "edge_count": graph.edge_count(),
12536 "nodes": payload,
12537 }))
12538 .expect("serialize causal.graph")
12539 );
12540 return;
12541 }
12542
12543 println!();
12544 println!(
12545 " {}",
12546 format!("VELA · CAUSAL · GRAPH · {}", frontier.display())
12547 .to_uppercase()
12548 .dimmed()
12549 );
12550 println!(" {}", style::tick_row(60));
12551 println!(
12552 " {} nodes · {} edges",
12553 graph.node_count(),
12554 graph.edge_count()
12555 );
12556 println!();
12557 for n in &nodes {
12558 let parents: Vec<&str> = graph.parents_of(n).collect();
12559 let children: Vec<&str> = graph.children_of(n).collect();
12560 if parents.is_empty() && children.is_empty() && nodes.len() > 1 {
12561 continue; }
12563 println!(" {n}");
12564 if !parents.is_empty() {
12565 println!(" parents: {}", parents.join(", "));
12566 }
12567 if !children.is_empty() {
12568 println!(" children: {}", children.join(", "));
12569 }
12570 }
12571 }
12572 CausalAction::Counterfactual {
12573 frontier,
12574 intervene_on,
12575 set_to,
12576 target,
12577 json,
12578 } => {
12579 use crate::counterfactual::{
12580 CounterfactualQuery, CounterfactualVerdict, answer_counterfactual,
12581 };
12582
12583 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
12584 let query = CounterfactualQuery {
12585 intervene_on: intervene_on.clone(),
12586 set_to,
12587 target: target.clone(),
12588 };
12589 let verdict = answer_counterfactual(&project, &query);
12590
12591 if json {
12592 println!(
12593 "{}",
12594 serde_json::to_string_pretty(&json!({
12595 "ok": true,
12596 "command": "causal.counterfactual",
12597 "frontier": frontier.display().to_string(),
12598 "query": query,
12599 "verdict": verdict,
12600 }))
12601 .expect("serialize causal.counterfactual")
12602 );
12603 return;
12604 }
12605
12606 println!();
12607 println!(
12608 " {}",
12609 format!(
12610 "VELA · CAUSAL · COUNTERFACTUAL · do({intervene_on} := {set_to:.3}) → {target}"
12611 )
12612 .to_uppercase()
12613 .dimmed()
12614 );
12615 println!(" {}", style::tick_row(72));
12616 match verdict {
12617 CounterfactualVerdict::Resolved {
12618 factual,
12619 counterfactual,
12620 delta,
12621 paths_used,
12622 } => {
12623 println!(
12624 " {} factual: {factual:.3} counterfactual: {counterfactual:.3} delta: {delta:+.3}",
12625 style::ok("resolved")
12626 );
12627 println!(
12628 " twin-network propagation through {} causal path(s):",
12629 paths_used.len()
12630 );
12631 for p in paths_used.iter().take(5) {
12632 println!(" · {}", p.join(" → "));
12633 }
12634 println!(
12635 " reading: \"if {intervene_on}'s confidence had been {set_to:.3} \
12636 instead of factual, {target}'s confidence would shift by {delta:+.3}.\""
12637 );
12638 }
12639 CounterfactualVerdict::MechanismUnspecified { unspecified_edges } => {
12640 println!(
12641 " {} causal path exists but {} edge(s) lack a mechanism annotation",
12642 style::warn("mechanism_unspecified"),
12643 unspecified_edges.len()
12644 );
12645 for (parent, child) in unspecified_edges.iter().take(8) {
12646 println!(" · {parent} → {child}");
12647 }
12648 println!(
12649 " remediation: annotate one of the link mechanisms (linear / monotonic / threshold / saturating)."
12650 );
12651 }
12652 CounterfactualVerdict::NoCausalPath { factual } => {
12653 println!(
12654 " {} no directed path from {intervene_on} to {target}; counterfactual = factual = {factual:.3}",
12655 style::warn("no_path")
12656 );
12657 }
12658 CounterfactualVerdict::UnknownNode { which } => {
12659 fail(&format!("node not in frontier: {which}"));
12660 }
12661 CounterfactualVerdict::InvalidIntervention { reason } => {
12662 fail(&reason);
12663 }
12664 }
12665 println!();
12666 }
12667 }
12668}
12669
12670fn cmd_bridges(action: BridgesAction) {
12673 use crate::bridge::{Bridge, BridgeStatus, derive_bridges};
12674 use std::collections::HashMap;
12675
12676 fn bridges_dir(frontier: &Path) -> PathBuf {
12677 frontier.join(".vela/bridges")
12678 }
12679
12680 fn load_bridge(frontier: &Path, id: &str) -> Result<Bridge, String> {
12681 let path = bridges_dir(frontier).join(format!("{id}.json"));
12682 if !path.is_file() {
12683 return Err(format!("bridge not found: {id}"));
12684 }
12685 let data = std::fs::read_to_string(&path).map_err(|e| format!("read {id}: {e}"))?;
12686 serde_json::from_str(&data).map_err(|e| format!("parse {id}: {e}"))
12687 }
12688
12689 fn save_bridge(frontier: &Path, b: &Bridge) -> Result<(), String> {
12690 let dir = bridges_dir(frontier);
12691 std::fs::create_dir_all(&dir).map_err(|e| format!("mkdir bridges/: {e}"))?;
12692 let path = dir.join(format!("{}.json", b.id));
12693 let data = serde_json::to_string_pretty(b).map_err(|e| format!("serialize bridge: {e}"))?;
12694 std::fs::write(&path, format!("{data}\n")).map_err(|e| format!("write bridge: {e}"))
12695 }
12696
12697 fn default_reviewer_id() -> String {
12700 std::env::var("VELA_REVIEWER_ID").unwrap_or_else(|_| "reviewer:will-blair".to_string())
12701 }
12702
12703 fn emit_bridge_reviewed_event(
12714 frontier: &Path,
12715 bridge_id: &str,
12716 status: &str,
12717 reviewer_id: &str,
12718 note: Option<&str>,
12719 ) -> Result<(), String> {
12720 let mut payload = serde_json::json!({
12721 "bridge_id": bridge_id,
12722 "status": status,
12723 });
12724 if let Some(n) = note
12725 && !n.trim().is_empty()
12726 {
12727 payload["note"] = serde_json::Value::String(n.to_string());
12728 }
12729 let known_ids: Vec<String> = list_bridges(frontier)
12731 .unwrap_or_default()
12732 .into_iter()
12733 .map(|b| b.id)
12734 .collect();
12735 crate::events::validate_bridge_reviewed_against_state(&payload, &known_ids)?;
12736 let event = crate::events::new_bridge_reviewed_event(
12737 bridge_id,
12738 reviewer_id,
12739 "human",
12740 &format!("Bridge {status} by {reviewer_id}"),
12741 payload,
12742 Vec::new(),
12743 );
12744 let events_dir = frontier.join(".vela/events");
12745 std::fs::create_dir_all(&events_dir).map_err(|e| format!("mkdir .vela/events: {e}"))?;
12746 let event_path = events_dir.join(format!("{}.json", event.id));
12747 let data =
12748 serde_json::to_string_pretty(&event).map_err(|e| format!("serialize event: {e}"))?;
12749 std::fs::write(&event_path, format!("{data}\n")).map_err(|e| format!("write event: {e}"))
12750 }
12751
12752 fn list_bridges(frontier: &Path) -> Result<Vec<Bridge>, String> {
12753 let dir = bridges_dir(frontier);
12754 if !dir.is_dir() {
12755 return Ok(Vec::new());
12756 }
12757 let mut out = Vec::new();
12758 for entry in std::fs::read_dir(&dir).map_err(|e| format!("read bridges/: {e}"))? {
12759 let entry = entry.map_err(|e| format!("read entry: {e}"))?;
12760 let path = entry.path();
12761 if path.extension().and_then(|s| s.to_str()) != Some("json") {
12762 continue;
12763 }
12764 let data = std::fs::read_to_string(&path).map_err(|e| format!("read {path:?}: {e}"))?;
12765 let b: Bridge =
12766 serde_json::from_str(&data).map_err(|e| format!("parse {path:?}: {e}"))?;
12767 out.push(b);
12768 }
12769 out.sort_by(|a, b| {
12770 b.finding_refs
12771 .len()
12772 .cmp(&a.finding_refs.len())
12773 .then(a.entity_name.cmp(&b.entity_name))
12774 });
12775 Ok(out)
12776 }
12777
12778 match action {
12779 BridgesAction::Derive {
12780 frontier_a,
12781 label_a,
12782 frontier_b,
12783 label_b,
12784 json,
12785 } => {
12786 let a = repo::load_from_path(&frontier_a).unwrap_or_else(|e| fail_return(&e));
12787 let b = repo::load_from_path(&frontier_b).unwrap_or_else(|e| fail_return(&e));
12788 let now = chrono::Utc::now().to_rfc3339();
12789 let new_bridges =
12790 derive_bridges(&[(label_a.as_str(), &a), (label_b.as_str(), &b)], &now);
12791
12792 let existing = list_bridges(&frontier_a).unwrap_or_default();
12796 let existing_by_id: HashMap<String, Bridge> =
12797 existing.iter().map(|b| (b.id.clone(), b.clone())).collect();
12798 let mut written = 0;
12799 let mut preserved = 0;
12800 let mut new_ids = Vec::new();
12801 for mut bridge in new_bridges {
12802 if let Some(prev) = existing_by_id.get(&bridge.id)
12803 && prev.status != BridgeStatus::Derived
12804 {
12805 bridge.status = prev.status;
12807 bridge.derived_at = prev.derived_at.clone();
12808 preserved += 1;
12809 }
12810 save_bridge(&frontier_a, &bridge).unwrap_or_else(|e| fail_return(&e));
12811 new_ids.push(bridge.id.clone());
12812 written += 1;
12813 }
12814
12815 if json {
12816 println!(
12817 "{}",
12818 serde_json::to_string_pretty(&json!({
12819 "ok": true,
12820 "command": "bridges.derive",
12821 "frontier_a": frontier_a.display().to_string(),
12822 "frontier_b": frontier_b.display().to_string(),
12823 "bridges_written": written,
12824 "reviewer_judgments_preserved": preserved,
12825 "ids": new_ids,
12826 }))
12827 .expect("serialize bridges.derive")
12828 );
12829 return;
12830 }
12831
12832 println!();
12833 println!(
12834 " {}",
12835 format!("VELA · BRIDGES · DERIVE · {} ↔ {}", label_a, label_b)
12836 .to_uppercase()
12837 .dimmed()
12838 );
12839 println!(" {}", style::tick_row(60));
12840 println!(" {} {} bridge(s) materialized", style::ok("ok"), written);
12841 if preserved > 0 {
12842 println!(
12843 " {} {} reviewer judgment(s) preserved",
12844 style::ok("kept"),
12845 preserved
12846 );
12847 }
12848 for id in new_ids.iter().take(10) {
12849 println!(" · {id}");
12850 }
12851 if new_ids.len() > 10 {
12852 println!(" … and {} more", new_ids.len() - 10);
12853 }
12854 println!();
12855 }
12856 BridgesAction::List {
12857 frontier,
12858 status,
12859 json,
12860 } => {
12861 let mut bridges = list_bridges(&frontier).unwrap_or_else(|e| fail_return(&e));
12862 if let Some(s) = status.as_deref() {
12863 let want = match s.to_lowercase().as_str() {
12864 "derived" => BridgeStatus::Derived,
12865 "confirmed" => BridgeStatus::Confirmed,
12866 "refuted" => BridgeStatus::Refuted,
12867 other => fail_return(&format!(
12868 "unknown bridge status '{other}' (try derived|confirmed|refuted)"
12869 )),
12870 };
12871 bridges.retain(|b| b.status == want);
12872 }
12873 if json {
12874 println!(
12875 "{}",
12876 serde_json::to_string_pretty(&json!({
12877 "ok": true,
12878 "command": "bridges.list",
12879 "frontier": frontier.display().to_string(),
12880 "count": bridges.len(),
12881 "bridges": bridges,
12882 }))
12883 .expect("serialize bridges.list")
12884 );
12885 return;
12886 }
12887 println!();
12888 println!(
12889 " {}",
12890 format!("VELA · BRIDGES · LIST · {}", frontier.display())
12891 .to_uppercase()
12892 .dimmed()
12893 );
12894 println!(" {}", style::tick_row(60));
12895 println!(" {} bridge(s)", bridges.len());
12896 for b in &bridges {
12897 let chip = match b.status {
12898 BridgeStatus::Derived => style::warn("derived"),
12899 BridgeStatus::Confirmed => style::ok("confirmed"),
12900 BridgeStatus::Refuted => style::lost("refuted"),
12901 };
12902 println!();
12903 println!(
12904 " {chip} {} {} ↔ findings:{}",
12905 b.id,
12906 b.entity_name,
12907 b.finding_refs.len()
12908 );
12909 println!(" frontiers: {}", b.frontiers.join(", "));
12910 if let Some(t) = &b.tension {
12911 println!(" tension: {t}");
12912 }
12913 }
12914 println!();
12915 }
12916 BridgesAction::Show {
12917 frontier,
12918 bridge_id,
12919 json,
12920 } => {
12921 let b = load_bridge(&frontier, &bridge_id).unwrap_or_else(|e| fail_return(&e));
12922 if json {
12923 println!("{}", serde_json::to_string_pretty(&b).expect("serialize"));
12924 return;
12925 }
12926 println!();
12927 println!(
12928 " {}",
12929 format!("VELA · BRIDGES · SHOW · {}", b.id)
12930 .to_uppercase()
12931 .dimmed()
12932 );
12933 println!(" {}", style::tick_row(60));
12934 println!(" entity: {}", b.entity_name);
12935 println!(" status: {:?}", b.status);
12936 println!(" frontiers: {}", b.frontiers.join(", "));
12937 if !b.frontier_ids.is_empty() {
12938 println!(" frontier_ids: {}", b.frontier_ids.join(", "));
12939 }
12940 if let Some(t) = &b.tension {
12941 println!(" tension: {t}");
12942 }
12943 println!(" derived_at: {}", b.derived_at);
12944 println!(" finding refs ({}):", b.finding_refs.len());
12945 for r in &b.finding_refs {
12946 let dir = r.direction.as_deref().unwrap_or("—");
12947 let truncated: String = r.assertion_text.chars().take(72).collect();
12948 println!(
12949 " · [{}] {} (conf={:.2}, dir={})",
12950 r.frontier, r.finding_id, r.confidence, dir
12951 );
12952 println!(" {truncated}");
12953 }
12954 println!();
12955 }
12956 BridgesAction::Confirm {
12957 frontier,
12958 bridge_id,
12959 reviewer,
12960 note,
12961 json,
12962 } => {
12963 let mut b = load_bridge(&frontier, &bridge_id).unwrap_or_else(|e| fail_return(&e));
12964 let reviewer_id = reviewer.unwrap_or_else(default_reviewer_id);
12965 b.status = BridgeStatus::Confirmed;
12966 save_bridge(&frontier, &b).unwrap_or_else(|e| fail_return(&e));
12967 let _ = emit_bridge_reviewed_event(
12971 &frontier,
12972 &bridge_id,
12973 "confirmed",
12974 &reviewer_id,
12975 note.as_deref(),
12976 );
12977 if json {
12978 println!("{}", serde_json::to_string_pretty(&b).expect("serialize"));
12979 return;
12980 }
12981 println!();
12982 println!(" {} {} now confirmed", style::ok("confirmed"), b.id);
12983 println!();
12984 }
12985 BridgesAction::Refute {
12986 frontier,
12987 bridge_id,
12988 reviewer,
12989 note,
12990 json,
12991 } => {
12992 let mut b = load_bridge(&frontier, &bridge_id).unwrap_or_else(|e| fail_return(&e));
12993 let reviewer_id = reviewer.unwrap_or_else(default_reviewer_id);
12994 b.status = BridgeStatus::Refuted;
12995 save_bridge(&frontier, &b).unwrap_or_else(|e| fail_return(&e));
12996 let _ = emit_bridge_reviewed_event(
12997 &frontier,
12998 &bridge_id,
12999 "refuted",
13000 &reviewer_id,
13001 note.as_deref(),
13002 );
13003 if json {
13004 println!("{}", serde_json::to_string_pretty(&b).expect("serialize"));
13005 return;
13006 }
13007 println!();
13008 println!(" {} {} now refuted", style::lost("refuted"), b.id);
13009 println!();
13010 }
13011 }
13012}
13013
13014fn cmd_federation(action: FederationAction) {
13016 use crate::federation::PeerHub;
13017
13018 match action {
13019 FederationAction::PeerAdd {
13020 frontier,
13021 id,
13022 url,
13023 pubkey,
13024 note,
13025 json,
13026 } => {
13027 let peer = PeerHub {
13028 id: id.clone(),
13029 url: url.clone(),
13030 public_key: pubkey.trim().to_string(),
13031 added_at: chrono::Utc::now().to_rfc3339(),
13032 note: note.clone(),
13033 };
13034 peer.validate().unwrap_or_else(|e| fail_return(&e));
13035
13036 let mut project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
13037 if project.peers.iter().any(|p| p.id == id) {
13038 fail(&format!("peer '{id}' already in registry"));
13039 }
13040 project.peers.push(peer.clone());
13041 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
13042
13043 if json {
13044 println!(
13045 "{}",
13046 serde_json::to_string_pretty(&json!({
13047 "ok": true,
13048 "command": "federation.peer-add",
13049 "frontier": frontier.display().to_string(),
13050 "peer": peer,
13051 "registered_count": project.peers.len(),
13052 }))
13053 .expect("serialize federation.peer-add")
13054 );
13055 } else {
13056 println!(
13057 "{} peer {} (pubkey {}…) at {}",
13058 style::ok("registered"),
13059 id,
13060 &peer.public_key[..16],
13061 peer.url
13062 );
13063 }
13064 }
13065 FederationAction::PeerList { frontier, json } => {
13066 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
13067 if json {
13068 println!(
13069 "{}",
13070 serde_json::to_string_pretty(&json!({
13071 "ok": true,
13072 "command": "federation.peer-list",
13073 "frontier": frontier.display().to_string(),
13074 "peers": project.peers,
13075 }))
13076 .expect("serialize federation.peer-list")
13077 );
13078 } else {
13079 println!();
13080 println!(
13081 " {}",
13082 format!("VELA · FEDERATION · PEERS · {}", frontier.display())
13083 .to_uppercase()
13084 .dimmed()
13085 );
13086 println!(" {}", style::tick_row(60));
13087 if project.peers.is_empty() {
13088 println!(" (no peers registered)");
13089 } else {
13090 for p in &project.peers {
13091 let note_suffix = if p.note.is_empty() {
13092 String::new()
13093 } else {
13094 format!(" · {}", p.note)
13095 };
13096 println!(
13097 " {:<24} {} {}…{note_suffix}",
13098 p.id,
13099 p.url,
13100 &p.public_key[..16]
13101 );
13102 }
13103 }
13104 }
13105 }
13106 FederationAction::Sync {
13107 frontier,
13108 peer_id,
13109 url,
13110 via_hub,
13111 vfr_id,
13112 allow_cross_vfr,
13113 dry_run,
13114 json,
13115 } => {
13116 use crate::federation::{self, DiscoveryResult};
13117
13118 let mut project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
13119 let Some(peer) = project.peers.iter().find(|p| p.id == peer_id).cloned() else {
13120 fail(&format!(
13121 "peer '{peer_id}' not in registry; run `vela federation peer add` first"
13122 ));
13123 };
13124 let local_frontier_id = project.frontier_id();
13125
13126 if via_hub
13133 && let Some(target) = vfr_id.as_deref()
13134 && target != local_frontier_id
13135 && !allow_cross_vfr
13136 {
13137 fail(&format!(
13138 "cross-vfr sync refused: --vfr-id {target} differs from local frontier_id {local_frontier_id}. \
13139 Pass --allow-cross-vfr to opt in (every peer-side finding will be recorded as a \
13140 missing_locally conflict). Or omit --vfr-id to default to the local frontier id."
13141 ));
13142 }
13143
13144 #[derive(Debug)]
13146 enum SyncOutcome {
13147 Resolved(crate::project::Project, String), BrokenLocator(String, String, u16), UnverifiedEntry(String, String), EntryNotFound(String, u16),
13151 }
13152
13153 let outcome = if via_hub {
13154 let target_vfr = vfr_id.clone().unwrap_or_else(|| local_frontier_id.clone());
13155 match federation::discover_peer_frontier(
13156 &peer.url,
13157 &target_vfr,
13158 Some(&peer.public_key),
13159 ) {
13160 DiscoveryResult::Resolved(p) => {
13161 let src =
13162 format!("{}/entries/{}", peer.url.trim_end_matches('/'), target_vfr);
13163 SyncOutcome::Resolved(p, src)
13164 }
13165 DiscoveryResult::BrokenLocator {
13166 vfr_id,
13167 locator,
13168 status,
13169 } => SyncOutcome::BrokenLocator(vfr_id, locator, status),
13170 DiscoveryResult::UnverifiedEntry { vfr_id, reason } => {
13171 SyncOutcome::UnverifiedEntry(vfr_id, reason)
13172 }
13173 DiscoveryResult::EntryNotFound { vfr_id, status } => {
13174 SyncOutcome::EntryNotFound(vfr_id, status)
13175 }
13176 DiscoveryResult::Unreachable { url, error } => {
13177 fail(&format!("peer hub unreachable ({url}): {error}"));
13178 }
13179 }
13180 } else {
13181 let resolved_url = url.unwrap_or_else(|| {
13182 let base = peer.url.trim_end_matches('/');
13183 format!("{base}/manifest/{local_frontier_id}.json")
13184 });
13185 match federation::fetch_peer_frontier(&resolved_url) {
13186 Ok(p) => SyncOutcome::Resolved(p, resolved_url),
13187 Err(e) => fail(&format!("direct fetch failed: {e}")),
13188 }
13189 };
13190
13191 let peer_source: String;
13194 let peer_state = match outcome {
13195 SyncOutcome::Resolved(p, src) => {
13196 if !json {
13197 println!(" · resolved via {src}");
13198 }
13199 peer_source = src;
13200 p
13201 }
13202 SyncOutcome::BrokenLocator(vfr, locator, status) => {
13203 if dry_run {
13204 if json {
13205 println!(
13206 "{}",
13207 serde_json::to_string_pretty(&json!({
13208 "ok": true,
13209 "command": "federation.sync",
13210 "dry_run": true,
13211 "outcome": "broken_locator",
13212 "vfr_id": vfr,
13213 "locator": locator,
13214 "http_status": status,
13215 }))
13216 .expect("serialize")
13217 );
13218 } else {
13219 println!(
13220 "{} dry-run: peer entry resolved but locator dead",
13221 style::warn("broken_locator")
13222 );
13223 println!(" vfr_id: {vfr}");
13224 println!(" locator: {locator} (HTTP {status})");
13225 }
13226 return;
13227 }
13228 let report = federation::record_locator_failure(
13229 &mut project,
13230 &peer_id,
13231 &vfr,
13232 &locator,
13233 status,
13234 );
13235 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
13236 if json {
13237 println!(
13238 "{}",
13239 serde_json::to_string_pretty(&json!({
13240 "ok": true,
13241 "command": "federation.sync",
13242 "outcome": "broken_locator",
13243 "report": report,
13244 }))
13245 .expect("serialize")
13246 );
13247 } else {
13248 println!(
13249 "{} sync recorded broken-locator conflict against {peer_id}",
13250 style::warn("broken_locator")
13251 );
13252 println!(" vfr_id: {vfr}");
13253 println!(" locator: {locator} (HTTP {status})");
13254 println!(" events appended: {}", report.events_appended);
13255 }
13256 return;
13257 }
13258 SyncOutcome::UnverifiedEntry(vfr, reason) => {
13259 if dry_run {
13260 if json {
13261 println!(
13262 "{}",
13263 serde_json::to_string_pretty(&json!({
13264 "ok": true,
13265 "command": "federation.sync",
13266 "dry_run": true,
13267 "outcome": "unverified_peer_entry",
13268 "vfr_id": vfr,
13269 "reason": reason,
13270 }))
13271 .expect("serialize")
13272 );
13273 } else {
13274 println!(
13275 "{} dry-run: peer entry signature did not verify",
13276 style::lost("unverified_peer_entry")
13277 );
13278 println!(" vfr_id: {vfr}");
13279 println!(" reason: {reason}");
13280 }
13281 return;
13282 }
13283 let report =
13284 federation::record_unverified_entry(&mut project, &peer_id, &vfr, &reason);
13285 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
13286 if json {
13287 println!(
13288 "{}",
13289 serde_json::to_string_pretty(&json!({
13290 "ok": true,
13291 "command": "federation.sync",
13292 "outcome": "unverified_peer_entry",
13293 "report": report,
13294 }))
13295 .expect("serialize")
13296 );
13297 } else {
13298 println!(
13299 "{} sync halted; peer's registry entry signature did not verify",
13300 style::lost("unverified_peer_entry")
13301 );
13302 println!(" vfr_id: {vfr}");
13303 println!(" reason: {reason}");
13304 }
13305 return;
13306 }
13307 SyncOutcome::EntryNotFound(vfr, status) => {
13308 if json {
13309 println!(
13310 "{}",
13311 serde_json::to_string_pretty(&json!({
13312 "ok": false,
13313 "command": "federation.sync",
13314 "outcome": "entry_not_found",
13315 "vfr_id": vfr,
13316 "http_status": status,
13317 }))
13318 .expect("serialize")
13319 );
13320 } else {
13321 println!(
13322 "{} peer's hub does not publish vfr_id {vfr} (HTTP {status})",
13323 style::warn("entry_not_found")
13324 );
13325 }
13326 return;
13327 }
13328 };
13329
13330 if dry_run {
13331 let conflicts = federation::diff_frontiers(&project, &peer_state);
13332 if json {
13333 println!(
13334 "{}",
13335 serde_json::to_string_pretty(&json!({
13336 "ok": true,
13337 "command": "federation.sync",
13338 "dry_run": true,
13339 "peer_id": peer_id,
13340 "peer_source": peer_source,
13341 "conflicts": conflicts,
13342 }))
13343 .expect("serialize federation.sync (dry-run)")
13344 );
13345 } else {
13346 println!(
13347 "{} dry-run vs {peer_id} ({}): {} conflict(s)",
13348 style::ok("ok"),
13349 peer_source,
13350 conflicts.len()
13351 );
13352 for c in &conflicts {
13353 println!(" · {} {} {}", c.kind.as_str(), c.finding_id, c.detail);
13354 }
13355 }
13356 return;
13357 }
13358
13359 let report = federation::sync_with_peer(&mut project, &peer_id, &peer_state);
13360 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
13361
13362 if json {
13363 println!(
13364 "{}",
13365 serde_json::to_string_pretty(&json!({
13366 "ok": true,
13367 "command": "federation.sync",
13368 "peer_id": peer_id,
13369 "peer_source": peer_source,
13370 "report": report,
13371 }))
13372 .expect("serialize federation.sync")
13373 );
13374 } else {
13375 println!(
13376 "{} synced with {} ({})",
13377 style::ok("ok"),
13378 peer_id,
13379 peer_source
13380 );
13381 println!(
13382 " our: {}",
13383 &report.our_snapshot_hash[..16.min(report.our_snapshot_hash.len())]
13384 );
13385 println!(
13386 " peer: {}",
13387 &report.peer_snapshot_hash[..16.min(report.peer_snapshot_hash.len())]
13388 );
13389 println!(
13390 " conflicts: {} events appended: {}",
13391 report.conflicts.len(),
13392 report.events_appended
13393 );
13394 for c in &report.conflicts {
13395 println!(" · {} {} {}", c.kind.as_str(), c.finding_id, c.detail);
13396 }
13397 }
13398 }
13399 FederationAction::PushResolution {
13400 frontier,
13401 conflict_event_id,
13402 to,
13403 key,
13404 vfr_id,
13405 json,
13406 } => {
13407 cmd_federation_push_resolution(frontier, conflict_event_id, to, key, vfr_id, json);
13408 }
13409 FederationAction::PeerRemove { frontier, id, json } => {
13410 let mut project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
13411 let before = project.peers.len();
13412 project.peers.retain(|p| p.id != id);
13413 if project.peers.len() == before {
13414 fail(&format!("peer '{id}' not found in registry"));
13415 }
13416 repo::save_to_path(&frontier, &project).unwrap_or_else(|e| fail_return(&e));
13417
13418 if json {
13419 println!(
13420 "{}",
13421 serde_json::to_string_pretty(&json!({
13422 "ok": true,
13423 "command": "federation.peer-remove",
13424 "frontier": frontier.display().to_string(),
13425 "removed": id,
13426 "remaining": project.peers.len(),
13427 }))
13428 .expect("serialize federation.peer-remove")
13429 );
13430 } else {
13431 println!(
13432 "{} peer {} ({} remaining)",
13433 style::ok("removed"),
13434 id,
13435 project.peers.len()
13436 );
13437 }
13438 }
13439 }
13440}
13441
13442fn cmd_federation_push_resolution(
13454 frontier: PathBuf,
13455 conflict_event_id: String,
13456 to: String,
13457 key: Option<PathBuf>,
13458 vfr_id: Option<String>,
13459 json: bool,
13460) {
13461 use crate::canonical;
13462 use crate::sign;
13463
13464 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
13465
13466 let Some(peer) = project.peers.iter().find(|p| p.id == to).cloned() else {
13467 fail(&format!(
13468 "peer '{to}' not in registry; run `vela federation peer-add` first"
13469 ));
13470 };
13471
13472 let Some(resolution) = project
13474 .events
13475 .iter()
13476 .find(|e| {
13477 e.kind == "frontier.conflict_resolved"
13478 && e.payload.get("conflict_event_id").and_then(|v| v.as_str())
13479 == Some(conflict_event_id.as_str())
13480 })
13481 .cloned()
13482 else {
13483 fail(&format!(
13484 "no frontier.conflict_resolved event paired with conflict {conflict_event_id} in {}",
13485 frontier.display()
13486 ));
13487 };
13488
13489 let actor_id = resolution.actor.id.clone();
13492 let Some(actor) = project.actors.iter().find(|a| a.id == actor_id) else {
13493 fail(&format!(
13494 "resolution event's actor.id ({actor_id}) is not in the frontier's actor registry; \
13495 register the reviewer with `vela actor add` before pushing"
13496 ));
13497 };
13498
13499 let key_path = key.unwrap_or_else(|| {
13502 let home = std::env::var("HOME").unwrap_or_default();
13503 let base = PathBuf::from(home)
13504 .join(".config")
13505 .join("vela")
13506 .join("keys");
13507 let safe_id = actor.id.replace([':', '/'], "_");
13508 let by_actor = base.join(format!("{safe_id}.key"));
13509 if by_actor.exists() {
13510 by_actor
13511 } else {
13512 base.join("private.key")
13513 }
13514 });
13515
13516 let signing_key = sign::load_signing_key_from_path(&key_path).unwrap_or_else(|e| {
13517 fail_return(&format!(
13518 "load private key from {}: {e}",
13519 key_path.display()
13520 ))
13521 });
13522 let pubkey_hex = sign::pubkey_hex(&signing_key);
13523 if !pubkey_hex.eq_ignore_ascii_case(&actor.public_key) {
13524 fail(&format!(
13525 "private key at {} does not match actor {}'s registered public key. \
13526 Loaded pubkey {}, expected {}.",
13527 key_path.display(),
13528 actor.id,
13529 &pubkey_hex[..16],
13530 &actor.public_key[..16]
13531 ));
13532 }
13533
13534 let signature_hex = sign::sign_event(&resolution, &signing_key)
13537 .unwrap_or_else(|e| fail_return(&format!("sign event: {e}")));
13538
13539 let mut body = resolution.clone();
13544 body.signature = None;
13545 let body_value =
13546 serde_json::to_value(&body).unwrap_or_else(|e| fail_return(&format!("serialize: {e}")));
13547 let _canonical_check = canonical::to_canonical_bytes(&body_value)
13548 .unwrap_or_else(|e| fail_return(&format!("canonicalize: {e}")));
13549
13550 let target_vfr = vfr_id.unwrap_or_else(|| project.frontier_id());
13551 let url = format!(
13552 "{}/entries/{}/events",
13553 peer.url.trim_end_matches('/'),
13554 target_vfr
13555 );
13556
13557 let url_owned = url.clone();
13559 let pubkey_owned = pubkey_hex.clone();
13560 let signature_owned = signature_hex.clone();
13561 let body_owned = body_value.clone();
13562 let response: Result<(u16, String), String> = std::thread::spawn(move || {
13563 let client = reqwest::blocking::Client::new();
13564 let resp = client
13565 .post(&url_owned)
13566 .header("X-Vela-Signer-Pubkey", &pubkey_owned)
13567 .header("X-Vela-Signature", &signature_owned)
13568 .json(&body_owned)
13569 .send()
13570 .map_err(|e| format!("HTTP POST {url_owned}: {e}"))?;
13571 let status = resp.status().as_u16();
13572 let text = resp.text().unwrap_or_default();
13573 Ok((status, text))
13574 })
13575 .join()
13576 .map_err(|_| "push thread panicked".to_string())
13577 .unwrap_or_else(|e| fail_return(&e));
13578
13579 let (status, text) = response.unwrap_or_else(|e| fail_return(&e));
13580 let parsed: serde_json::Value =
13581 serde_json::from_str(&text).unwrap_or_else(|_| json!({ "raw": text }));
13582
13583 let accepted = matches!(status, 200..=202);
13584 if json {
13585 println!(
13586 "{}",
13587 serde_json::to_string_pretty(&json!({
13588 "ok": accepted,
13589 "command": "federation.push-resolution",
13590 "frontier": frontier.display().to_string(),
13591 "peer_id": to,
13592 "url": url,
13593 "conflict_event_id": conflict_event_id,
13594 "event_id": resolution.id,
13595 "actor_id": actor.id,
13596 "http_status": status,
13597 "response": parsed,
13598 }))
13599 .expect("serialize federation.push-resolution")
13600 );
13601 } else if accepted {
13602 println!(
13603 "{} resolution {} pushed to {} (HTTP {})",
13604 style::ok("ok"),
13605 &resolution.id[..16.min(resolution.id.len())],
13606 to,
13607 status
13608 );
13609 println!(" url: {url}");
13610 println!(" signer: {} (actor {})", &pubkey_hex[..16], actor.id);
13611 } else {
13612 println!("{} push refused (HTTP {})", style::lost("rejected"), status);
13613 println!(" url: {url}");
13614 println!(" response: {text}");
13615 std::process::exit(1);
13616 }
13617}
13618
13619fn cmd_queue(action: QueueAction) {
13624 use crate::queue;
13625 match action {
13626 QueueAction::List { queue_file, json } => {
13627 let path = queue_file.unwrap_or_else(queue::default_queue_path);
13628 let q = queue::load(&path).unwrap_or_else(|e| fail_return(&e));
13629 if json {
13630 let payload = json!({
13631 "ok": true,
13632 "command": "queue.list",
13633 "queue_file": path.display().to_string(),
13634 "schema": q.schema,
13635 "actions": q.actions,
13636 });
13637 println!(
13638 "{}",
13639 serde_json::to_string_pretty(&payload).expect("failed to serialize queue.list")
13640 );
13641 } else {
13642 println!();
13643 println!(
13644 " {}",
13645 format!("VELA · QUEUE · LIST · {}", path.display())
13646 .to_uppercase()
13647 .dimmed()
13648 );
13649 println!(" {}", style::tick_row(60));
13650 if q.actions.is_empty() {
13651 println!(" (queue is empty)");
13652 } else {
13653 for (idx, action) in q.actions.iter().enumerate() {
13654 println!(
13655 " [{idx}] {} → {} queued {}",
13656 action.kind,
13657 action.frontier.display(),
13658 action.queued_at
13659 );
13660 }
13661 }
13662 }
13663 }
13664 QueueAction::Clear { queue_file, json } => {
13665 let path = queue_file.unwrap_or_else(queue::default_queue_path);
13666 let dropped = queue::clear(&path).unwrap_or_else(|e| fail_return(&e));
13667 if json {
13668 let payload = json!({
13669 "ok": true,
13670 "command": "queue.clear",
13671 "queue_file": path.display().to_string(),
13672 "dropped": dropped,
13673 });
13674 println!(
13675 "{}",
13676 serde_json::to_string_pretty(&payload)
13677 .expect("failed to serialize queue.clear")
13678 );
13679 } else {
13680 println!("{} dropped {dropped} queued action(s)", style::ok("ok"));
13681 }
13682 }
13683 QueueAction::Sign {
13684 actor,
13685 key,
13686 queue_file,
13687 yes_to_all,
13688 json,
13689 } => {
13690 let path = queue_file.unwrap_or_else(queue::default_queue_path);
13691 let q = queue::load(&path).unwrap_or_else(|e| fail_return(&e));
13692 if q.actions.is_empty() {
13693 if json {
13694 println!("{}", json!({"ok": true, "signed": 0, "remaining": 0}));
13695 } else {
13696 println!("{} queue is empty", style::ok("ok"));
13697 }
13698 return;
13699 }
13700 let key_hex = std::fs::read_to_string(&key)
13701 .map(|s| s.trim().to_string())
13702 .unwrap_or_else(|e| fail_return(&format!("read key {}: {e}", key.display())));
13703 let signing_key = parse_signing_key(&key_hex);
13704 let mut signed_count = 0usize;
13705 let mut remaining = Vec::new();
13706 for action in q.actions.iter() {
13707 if !yes_to_all && !confirm_action(action) {
13708 remaining.push(action.clone());
13709 continue;
13710 }
13711 match sign_and_apply(&signing_key, &actor, action) {
13712 Ok(report) => {
13713 signed_count += 1;
13714 if !json {
13715 println!(
13716 "{} {} on {} → {}",
13717 style::ok("signed"),
13718 action.kind,
13719 action.frontier.display(),
13720 report
13721 );
13722 }
13723 }
13724 Err(error) => {
13725 remaining.push(action.clone());
13727 if !json {
13728 eprintln!(
13729 "{} {} on {}: {error}",
13730 style::warn("failed"),
13731 action.kind,
13732 action.frontier.display()
13733 );
13734 }
13735 }
13736 }
13737 }
13738 queue::replace_actions(&path, remaining.clone()).unwrap_or_else(|e| fail_return(&e));
13739 if json {
13740 let payload = json!({
13741 "ok": true,
13742 "command": "queue.sign",
13743 "signed": signed_count,
13744 "remaining": remaining.len(),
13745 });
13746 println!(
13747 "{}",
13748 serde_json::to_string_pretty(&payload).expect("failed to serialize queue.sign")
13749 );
13750 } else {
13751 println!(
13752 "{} signed {signed_count} action(s); {} remaining in queue",
13753 style::ok("ok"),
13754 remaining.len()
13755 );
13756 }
13757 }
13758 }
13759}
13760
13761fn governance_chain_path(frontier: &Path) -> PathBuf {
13766 let dir = if frontier.is_dir() {
13767 frontier.to_path_buf()
13768 } else if let Some(parent) = frontier.parent() {
13769 parent.to_path_buf()
13770 } else {
13771 PathBuf::from(".")
13772 };
13773 dir.join(".vela").join("governance").join("chain.json")
13774}
13775
13776fn default_registry_path() -> PathBuf {
13779 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
13780 PathBuf::from(home)
13781 .join(".vela")
13782 .join("registry")
13783 .join("entries.json")
13784}
13785
13786fn resolve_vfr_to_path(vfr_id: &str, from: Option<&str>, dest: &Path) -> Result<(), String> {
13793 use crate::registry;
13794 let registry_data = match from {
13795 Some(loc) if loc.starts_with("http") => registry::load_any(loc)?,
13796 Some(loc) => {
13797 let p = registry::resolve_local(loc)?;
13798 registry::load_local(&p)?
13799 }
13800 None => {
13801 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
13802 let p = PathBuf::from(home)
13803 .join(".vela")
13804 .join("registry")
13805 .join("entries.json");
13806 registry::load_local(&p)?
13807 }
13808 };
13809 let entry = registry::find_latest(®istry_data, vfr_id)
13810 .ok_or_else(|| format!("{vfr_id} not found in registry"))?;
13811 registry::fetch_frontier_to_prefer_event_hub(&entry, from, dest)
13812 .map_err(|e| format!("fetch frontier for {vfr_id}: {e}"))?;
13813 registry::verify_pull(&entry, dest)
13814 .map_err(|e| format!("pull verification failed for {vfr_id}: {e}"))?;
13815 Ok(())
13816}
13817
13818fn parse_signing_key(hex_str: &str) -> ed25519_dalek::SigningKey {
13819 let bytes = hex::decode(hex_str)
13820 .unwrap_or_else(|e| fail_return(&format!("invalid private-key hex: {e}")));
13821 let key_bytes: [u8; 32] = bytes
13822 .try_into()
13823 .unwrap_or_else(|_| fail_return("private key must be 32 bytes"));
13824 ed25519_dalek::SigningKey::from_bytes(&key_bytes)
13825}
13826
13827fn confirm_action(action: &crate::queue::QueuedAction) -> bool {
13828 use std::io::{self, BufRead, Write};
13829 let mut stdout = io::stdout().lock();
13830 let _ = writeln!(
13831 stdout,
13832 " sign {} on {}? [y/N] ",
13833 action.kind,
13834 action.frontier.display()
13835 );
13836 let _ = stdout.flush();
13837 drop(stdout);
13838 let stdin = io::stdin();
13839 let mut line = String::new();
13840 if stdin.lock().read_line(&mut line).is_err() {
13841 return false;
13842 }
13843 matches!(line.trim().to_lowercase().as_str(), "y" | "yes")
13844}
13845
13846fn sign_and_apply(
13851 signing_key: &ed25519_dalek::SigningKey,
13852 actor: &str,
13853 action: &crate::queue::QueuedAction,
13854) -> Result<String, String> {
13855 use crate::events::StateTarget;
13856 use crate::proposals;
13857 let args = &action.args;
13858 match action.kind.as_str() {
13859 "propose_review" | "propose_note" | "propose_revise_confidence" | "propose_retract" => {
13860 let kind = match action.kind.as_str() {
13861 "propose_review" => "finding.review",
13862 "propose_note" => "finding.note",
13863 "propose_revise_confidence" => "finding.confidence_revise",
13864 "propose_retract" => "finding.retract",
13865 _ => unreachable!(),
13866 };
13867 let target_id = args
13868 .get("target_finding_id")
13869 .and_then(Value::as_str)
13870 .ok_or("target_finding_id missing")?;
13871 let reason = args
13872 .get("reason")
13873 .and_then(Value::as_str)
13874 .ok_or("reason missing")?;
13875 let payload = match action.kind.as_str() {
13876 "propose_review" => {
13877 let status = args
13878 .get("status")
13879 .and_then(Value::as_str)
13880 .ok_or("status missing")?;
13881 json!({"status": status})
13882 }
13883 "propose_note" => {
13884 let text = args
13885 .get("text")
13886 .and_then(Value::as_str)
13887 .ok_or("text missing")?;
13888 json!({"text": text})
13889 }
13890 "propose_revise_confidence" => {
13891 let new_score = args
13892 .get("new_score")
13893 .and_then(Value::as_f64)
13894 .ok_or("new_score missing")?;
13895 json!({"new_score": new_score})
13896 }
13897 "propose_retract" => json!({}),
13898 _ => unreachable!(),
13899 };
13900 let created_at = args
13901 .get("created_at")
13902 .and_then(Value::as_str)
13903 .map(String::from)
13904 .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
13905 let mut proposal = proposals::new_proposal(
13906 kind,
13907 StateTarget {
13908 r#type: "finding".to_string(),
13909 id: target_id.to_string(),
13910 },
13911 actor,
13912 "human",
13913 reason,
13914 payload,
13915 Vec::new(),
13916 Vec::new(),
13917 );
13918 proposal.created_at = created_at;
13919 proposal.id = proposals::proposal_id(&proposal);
13920 let _signature = crate::sign::sign_proposal(&proposal, signing_key)?;
13924 let result = proposals::create_or_apply(&action.frontier, proposal, false)
13925 .map_err(|e| format!("create_or_apply: {e}"))?;
13926 Ok(format!("proposal {}", result.proposal_id))
13927 }
13928 "accept_proposal" | "reject_proposal" => {
13929 let proposal_id = args
13930 .get("proposal_id")
13931 .and_then(Value::as_str)
13932 .ok_or("proposal_id missing")?;
13933 let reason = args
13934 .get("reason")
13935 .and_then(Value::as_str)
13936 .ok_or("reason missing")?;
13937 let timestamp = args
13938 .get("timestamp")
13939 .and_then(Value::as_str)
13940 .map(String::from)
13941 .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
13942 let preimage = json!({
13944 "action": if action.kind == "accept_proposal" { "accept" } else { "reject" },
13945 "proposal_id": proposal_id,
13946 "reviewer_id": actor,
13947 "reason": reason,
13948 "timestamp": timestamp,
13949 });
13950 let bytes = crate::canonical::to_canonical_bytes(&preimage)?;
13951 use ed25519_dalek::Signer;
13952 let _signature = hex::encode(signing_key.sign(&bytes).to_bytes());
13953 if action.kind == "accept_proposal" {
13954 let event_id =
13955 crate::proposals::accept_at_path(&action.frontier, proposal_id, actor, reason)
13956 .map_err(|e| format!("accept_at_path: {e}"))?;
13957 Ok(format!("event {event_id}"))
13958 } else {
13959 crate::proposals::reject_at_path(&action.frontier, proposal_id, actor, reason)
13960 .map_err(|e| format!("reject_at_path: {e}"))?;
13961 Ok(format!("rejected {proposal_id}"))
13962 }
13963 }
13964 other => Err(format!("unsupported queued action kind '{other}'")),
13965 }
13966}
13967
13968fn cmd_entity(action: EntityAction) {
13980 use crate::entity_resolve;
13981 match action {
13982 EntityAction::Resolve {
13983 frontier,
13984 force,
13985 json,
13986 } => {
13987 let mut p = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
13988 let report = entity_resolve::resolve_frontier(&mut p, force);
13989 repo::save_to_path(&frontier, &p).unwrap_or_else(|e| fail_return(&e));
13990 if json {
13991 println!(
13992 "{}",
13993 serde_json::to_string_pretty(&serde_json::json!({
13994 "ok": true,
13995 "command": "entity.resolve",
13996 "frontier_path": frontier.display().to_string(),
13997 "report": report,
13998 }))
13999 .expect("serialize")
14000 );
14001 } else {
14002 println!(
14003 "{} resolved {} of {} entities ({} already, {} unresolved) across {} findings",
14004 style::ok("entity"),
14005 report.resolved,
14006 report.total_entities,
14007 report.already_resolved,
14008 report.unresolved_count,
14009 report.findings_touched,
14010 );
14011 let unresolved_summary: std::collections::BTreeSet<&str> = report
14012 .per_finding
14013 .iter()
14014 .flat_map(|f| f.unresolved.iter().map(String::as_str))
14015 .collect();
14016 if !unresolved_summary.is_empty() {
14017 let take = unresolved_summary.iter().take(8).collect::<Vec<_>>();
14018 println!(
14019 " unresolved (first {}): {}",
14020 take.len(),
14021 take.iter().copied().cloned().collect::<Vec<_>>().join(", ")
14022 );
14023 }
14024 }
14025 }
14026 EntityAction::List { json } => {
14027 let entries: Vec<serde_json::Value> = entity_resolve::iter_bundled()
14028 .map(|(name, etype, source, id)| {
14029 serde_json::json!({
14030 "canonical_name": name,
14031 "entity_type": etype,
14032 "source": source,
14033 "id": id,
14034 })
14035 })
14036 .collect();
14037 if json {
14038 println!(
14039 "{}",
14040 serde_json::to_string_pretty(&serde_json::json!({
14041 "ok": true,
14042 "command": "entity.list",
14043 "count": entries.len(),
14044 "entries": entries,
14045 }))
14046 .expect("serialize")
14047 );
14048 } else {
14049 println!("{} {} bundled entries", style::ok("entity"), entries.len());
14050 for e in &entries {
14051 println!(
14052 " {:32} {:18} {} {}",
14053 e["canonical_name"].as_str().unwrap_or("?"),
14054 e["entity_type"].as_str().unwrap_or("?"),
14055 e["source"].as_str().unwrap_or("?"),
14056 e["id"].as_str().unwrap_or("?"),
14057 );
14058 }
14059 }
14060 }
14061 }
14062}
14063
14064fn cmd_link(action: LinkAction) {
14065 use crate::bundle::{Link, LinkRef};
14066 match action {
14067 LinkAction::Add {
14068 frontier,
14069 from,
14070 to,
14071 r#type,
14072 note,
14073 inferred_by,
14074 no_check_target,
14075 json,
14076 } => {
14077 validate_enum_arg("--type", &r#type, bundle::VALID_LINK_TYPES);
14078 if !["compiler", "reviewer", "author"].contains(&inferred_by.as_str()) {
14079 fail(&format!(
14080 "invalid --inferred-by '{inferred_by}'. Valid: compiler, reviewer, author"
14081 ));
14082 }
14083 let parsed = LinkRef::parse(&to).unwrap_or_else(|e| {
14084 fail(&format!(
14085 "invalid --to '{to}': {e}. Expected vf_<hex> or vf_<hex>@vfr_<hex>"
14086 ))
14087 });
14088 let mut p = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
14089 let source_idx = p
14090 .findings
14091 .iter()
14092 .position(|f| f.id == from)
14093 .unwrap_or_else(|| {
14094 fail_return(&format!("--from finding '{from}' not in frontier"))
14095 });
14096 if let LinkRef::Local { vf_id } = &parsed
14097 && !p.findings.iter().any(|f| &f.id == vf_id)
14098 {
14099 fail(&format!(
14100 "local --to target '{vf_id}' not in frontier; add the target finding first"
14101 ));
14102 }
14103 if let LinkRef::Cross { vfr_id, .. } = &parsed
14104 && p.dep_for_vfr(vfr_id).is_none()
14105 {
14106 fail(&format!(
14107 "cross-frontier --to references vfr_id '{vfr_id}' but no matching dep is declared. Run `vela frontier add-dep {vfr_id} --locator <url> --snapshot <hash>` first."
14108 ));
14109 }
14110
14111 let mut target_warning: Option<String> = None;
14117 if let LinkRef::Cross {
14118 vfr_id: target_vfr,
14119 vf_id: target_vf,
14120 } = &parsed
14121 && !no_check_target
14122 && let Some(dep) = p.dep_for_vfr(target_vfr)
14123 && let Some(locator) = dep.locator.as_deref()
14124 && (locator.starts_with("http://") || locator.starts_with("https://"))
14125 {
14126 let client = reqwest::blocking::Client::builder()
14127 .timeout(std::time::Duration::from_secs(15))
14128 .build()
14129 .ok();
14130 if let Some(client) = client
14131 && let Ok(resp) = client.get(locator).send()
14132 && resp.status().is_success()
14133 && let Ok(dep_project) = resp.json::<crate::project::Project>()
14134 {
14135 if let Some(target_finding) =
14136 dep_project.findings.iter().find(|f| &f.id == target_vf)
14137 {
14138 if target_finding.flags.superseded {
14139 target_warning = Some(format!(
14140 "warn · cross-frontier target '{target_vf}' in '{target_vfr}' has flags.superseded = true. \
14141You may be linking to outdated wording. Pull --transitive and inspect the supersedes chain to find the current finding. \
14142Use --no-check-target to skip this check."
14143 ));
14144 }
14145 } else {
14146 target_warning = Some(format!(
14147 "warn · cross-frontier target '{target_vf}' not found in dep '{target_vfr}' (fetched from {locator}). \
14148The target may have been removed or never existed in the pinned snapshot."
14149 ));
14150 }
14151 }
14152 }
14153
14154 let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
14155 let link = Link {
14156 target: to.clone(),
14157 link_type: r#type.clone(),
14158 note: note.clone(),
14159 inferred_by: inferred_by.clone(),
14160 created_at: now,
14161 mechanism: None,
14162 };
14163 p.findings[source_idx].links.push(link);
14164 project::recompute_stats(&mut p);
14165 repo::save_to_path(&frontier, &p).unwrap_or_else(|e| fail_return(&e));
14166 let payload = json!({
14167 "ok": true,
14168 "command": "link.add",
14169 "frontier": frontier.display().to_string(),
14170 "from": from,
14171 "to": to,
14172 "type": r#type,
14173 "cross_frontier": parsed.is_cross_frontier(),
14174 });
14175 if json {
14176 let mut p2 = payload.clone();
14177 if let Some(w) = &target_warning
14178 && let serde_json::Value::Object(m) = &mut p2
14179 {
14180 m.insert(
14181 "target_warning".to_string(),
14182 serde_json::Value::String(w.clone()),
14183 );
14184 }
14185 println!(
14186 "{}",
14187 serde_json::to_string_pretty(&p2).expect("failed to serialize link.add")
14188 );
14189 } else {
14190 println!(
14191 "{} {} --[{}]--> {}{}",
14192 style::ok("link"),
14193 from,
14194 r#type,
14195 to,
14196 if parsed.is_cross_frontier() {
14197 " (cross-frontier)"
14198 } else {
14199 ""
14200 }
14201 );
14202 if let Some(w) = target_warning {
14203 println!(" {w}");
14204 }
14205 }
14206 }
14207 }
14208}
14209
14210fn cmd_frontier(action: FrontierAction) {
14211 use crate::project::ProjectDependency;
14212 use crate::repo;
14213 match action {
14214 FrontierAction::New {
14215 path,
14216 name,
14217 description,
14218 force,
14219 json,
14220 } => {
14221 if path.exists() && !force {
14222 fail(&format!(
14223 "{} already exists; pass --force to overwrite",
14224 path.display()
14225 ));
14226 }
14227 let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
14228 let project = project::Project {
14229 vela_version: project::VELA_SCHEMA_VERSION.to_string(),
14230 schema: project::VELA_SCHEMA_URL.to_string(),
14231 frontier_id: None,
14232 project: project::ProjectMeta {
14233 name: name.clone(),
14234 description: description.clone(),
14235 compiled_at: now,
14236 compiler: project::VELA_COMPILER_VERSION.to_string(),
14237 papers_processed: 0,
14238 errors: 0,
14239 dependencies: Vec::new(),
14240 },
14241 stats: project::ProjectStats::default(),
14242 findings: Vec::new(),
14243 sources: Vec::new(),
14244 evidence_atoms: Vec::new(),
14245 condition_records: Vec::new(),
14246 review_events: Vec::new(),
14247 confidence_updates: Vec::new(),
14248 events: Vec::new(),
14249 proposals: Vec::new(),
14250 proof_state: proposals::ProofState::default(),
14251 signatures: Vec::new(),
14252 actors: Vec::new(),
14253 replications: Vec::new(),
14254 datasets: Vec::new(),
14255 code_artifacts: Vec::new(),
14256 artifacts: Vec::new(),
14257 predictions: Vec::new(),
14258 resolutions: Vec::new(),
14259 peers: Vec::new(),
14260 negative_results: Vec::new(),
14261 trajectories: Vec::new(),
14262 released_diff_packs: Vec::new(),
14263 verdict_conflicts: Vec::new(),
14264 };
14265 repo::save_to_path(&path, &project).unwrap_or_else(|e| fail_return(&e));
14266 let payload = json!({
14267 "ok": true,
14268 "command": "frontier.new",
14269 "path": path.display().to_string(),
14270 "name": name,
14271 "schema": project::VELA_SCHEMA_URL,
14272 "vela_version": env!("CARGO_PKG_VERSION"),
14273 "next_steps": [
14274 "vela finding add <path> --assertion '...' --author 'reviewer:you' --apply",
14275 "vela sign generate-keypair --out keys",
14276 "vela actor add <path> reviewer:you --pubkey \"$(cat keys/public.key)\"",
14277 "vela registry publish <path> --owner reviewer:you --key keys/private.key --locator <url> --to https://vela-hub.fly.dev",
14278 ],
14279 });
14280 if json {
14281 println!(
14282 "{}",
14283 serde_json::to_string_pretty(&payload)
14284 .expect("failed to serialize frontier.new")
14285 );
14286 } else {
14287 println!(
14288 "{} scaffolded frontier '{name}' at {}",
14289 style::ok("frontier"),
14290 path.display()
14291 );
14292 println!(" next steps:");
14293 println!(
14294 " 1. vela finding add {} --assertion '...' --author 'reviewer:you' --apply",
14295 path.display()
14296 );
14297 println!(" 2. vela sign generate-keypair --out keys");
14298 println!(
14299 " 3. vela actor add {} reviewer:you --pubkey \"$(cat keys/public.key)\"",
14300 path.display()
14301 );
14302 println!(
14303 " 4. vela registry publish {} --owner reviewer:you --key keys/private.key --locator <url> --to https://vela-hub.fly.dev",
14304 path.display()
14305 );
14306 }
14307 }
14308 FrontierAction::Materialize { frontier, json } => {
14309 let payload = frontier_repo::materialize(&frontier).unwrap_or_else(|e| fail_return(&e));
14310 if json {
14311 println!(
14312 "{}",
14313 serde_json::to_string_pretty(&payload)
14314 .expect("failed to serialize frontier materialize")
14315 );
14316 } else {
14317 println!(
14318 "{} materialized frontier repo at {}",
14319 style::ok("frontier"),
14320 frontier.display()
14321 );
14322 }
14323 }
14324 FrontierAction::AddDep {
14325 frontier,
14326 vfr_id,
14327 locator,
14328 snapshot,
14329 name,
14330 json,
14331 } => {
14332 let mut p = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
14333 if p.project
14334 .dependencies
14335 .iter()
14336 .any(|d| d.vfr_id.as_deref() == Some(&vfr_id))
14337 {
14338 fail(&format!(
14339 "cross-frontier dependency '{vfr_id}' already declared; remove it first via `vela frontier remove-dep`"
14340 ));
14341 }
14342 let dep = ProjectDependency {
14343 name: name.unwrap_or_else(|| vfr_id.clone()),
14344 source: "vela.hub".into(),
14345 version: None,
14346 pinned_hash: None,
14347 vfr_id: Some(vfr_id.clone()),
14348 locator: Some(locator.clone()),
14349 pinned_snapshot_hash: Some(snapshot.clone()),
14350 };
14351 p.project.dependencies.push(dep);
14352 repo::save_to_path(&frontier, &p).unwrap_or_else(|e| fail_return(&e));
14353 let payload = json!({
14354 "ok": true,
14355 "command": "frontier.add-dep",
14356 "frontier": frontier.display().to_string(),
14357 "vfr_id": vfr_id,
14358 "locator": locator,
14359 "pinned_snapshot_hash": snapshot,
14360 "declared_count": p.project.dependencies.len(),
14361 });
14362 if json {
14363 println!(
14364 "{}",
14365 serde_json::to_string_pretty(&payload)
14366 .expect("failed to serialize frontier.add-dep")
14367 );
14368 } else {
14369 println!(
14370 "{} declared cross-frontier dep {vfr_id}",
14371 style::ok("frontier")
14372 );
14373 println!(" locator: {locator}");
14374 println!(" snapshot: {snapshot}");
14375 }
14376 }
14377 FrontierAction::ListDeps { frontier, json } => {
14378 let p = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
14379 let deps: Vec<&ProjectDependency> = p.project.dependencies.iter().collect();
14380 if json {
14381 let payload = json!({
14382 "ok": true,
14383 "command": "frontier.list-deps",
14384 "frontier": frontier.display().to_string(),
14385 "count": deps.len(),
14386 "dependencies": deps,
14387 });
14388 println!(
14389 "{}",
14390 serde_json::to_string_pretty(&payload)
14391 .expect("failed to serialize frontier.list-deps")
14392 );
14393 } else {
14394 println!();
14395 println!(
14396 " {}",
14397 format!("VELA · FRONTIER · LIST-DEPS · {}", frontier.display())
14398 .to_uppercase()
14399 .dimmed()
14400 );
14401 println!(" {}", style::tick_row(60));
14402 if deps.is_empty() {
14403 println!(" (no dependencies declared)");
14404 } else {
14405 for d in &deps {
14406 let kind = if d.is_cross_frontier() {
14407 "cross-frontier"
14408 } else {
14409 "compile-time"
14410 };
14411 println!(" · {} [{kind}]", d.name);
14412 if let Some(v) = &d.vfr_id {
14413 println!(" vfr_id: {v}");
14414 }
14415 if let Some(l) = &d.locator {
14416 println!(" locator: {l}");
14417 }
14418 if let Some(s) = &d.pinned_snapshot_hash {
14419 println!(" snapshot: {s}");
14420 }
14421 }
14422 }
14423 }
14424 }
14425 FrontierAction::RemoveDep {
14426 frontier,
14427 vfr_id,
14428 json,
14429 } => {
14430 let mut p = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
14431 for f in &p.findings {
14433 for l in &f.links {
14434 if let Ok(crate::bundle::LinkRef::Cross { vfr_id: ref v, .. }) =
14435 crate::bundle::LinkRef::parse(&l.target)
14436 && v == &vfr_id
14437 {
14438 fail(&format!(
14439 "cannot remove dep '{vfr_id}': finding {} still links to it via {}",
14440 f.id, l.target
14441 ));
14442 }
14443 }
14444 }
14445 let before = p.project.dependencies.len();
14446 p.project
14447 .dependencies
14448 .retain(|d| d.vfr_id.as_deref() != Some(&vfr_id));
14449 let removed = before - p.project.dependencies.len();
14450 if removed == 0 {
14451 fail(&format!("no cross-frontier dependency '{vfr_id}' found"));
14452 }
14453 repo::save_to_path(&frontier, &p).unwrap_or_else(|e| fail_return(&e));
14454 let payload = json!({
14455 "ok": true,
14456 "command": "frontier.remove-dep",
14457 "frontier": frontier.display().to_string(),
14458 "vfr_id": vfr_id,
14459 "removed": removed,
14460 });
14461 if json {
14462 println!(
14463 "{}",
14464 serde_json::to_string_pretty(&payload)
14465 .expect("failed to serialize frontier.remove-dep")
14466 );
14467 } else {
14468 println!(
14469 "{} removed cross-frontier dep {vfr_id}",
14470 style::ok("frontier")
14471 );
14472 }
14473 }
14474 FrontierAction::RefreshDeps {
14475 frontier,
14476 from,
14477 dry_run,
14478 json,
14479 } => {
14480 let mut p = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
14481 let cross_deps: Vec<String> = p
14482 .project
14483 .dependencies
14484 .iter()
14485 .filter_map(|d| d.vfr_id.clone())
14486 .collect();
14487 if cross_deps.is_empty() {
14488 if json {
14489 println!(
14490 "{}",
14491 serde_json::to_string_pretty(&json!({
14492 "ok": true,
14493 "command": "frontier.refresh-deps",
14494 "frontier": frontier.display().to_string(),
14495 "from": from,
14496 "dry_run": dry_run,
14497 "deps": [],
14498 "summary": { "total": 0, "refreshed": 0, "unchanged": 0, "missing": 0, "unreachable": 0 },
14499 })).expect("serialize")
14500 );
14501 } else {
14502 println!(
14503 "{} no cross-frontier deps declared in {}",
14504 style::ok("frontier"),
14505 frontier.display()
14506 );
14507 }
14508 return;
14509 }
14510 let client = reqwest::blocking::Client::builder()
14511 .timeout(std::time::Duration::from_secs(20))
14512 .build()
14513 .unwrap_or_else(|e| fail_return(&format!("http client init failed: {e}")));
14514 let base = from.trim_end_matches('/');
14515 #[derive(serde::Deserialize)]
14516 struct HubEntry {
14517 latest_snapshot_hash: String,
14518 }
14519 let mut per_dep: Vec<serde_json::Value> = Vec::new();
14520 let (mut refreshed, mut unchanged, mut missing, mut unreachable) =
14521 (0u32, 0u32, 0u32, 0u32);
14522 for vfr in &cross_deps {
14523 let url = format!("{base}/entries/{vfr}");
14524 let resp = client.get(&url).send();
14525 let outcome = match resp {
14526 Ok(r) if r.status().as_u16() == 404 => {
14527 missing += 1;
14528 json!({ "vfr_id": vfr, "status": "missing", "url": url })
14529 }
14530 Ok(r) if !r.status().is_success() => {
14531 unreachable += 1;
14532 json!({ "vfr_id": vfr, "status": "unreachable", "http_status": r.status().as_u16() })
14533 }
14534 Err(e) => {
14535 unreachable += 1;
14536 json!({ "vfr_id": vfr, "status": "unreachable", "error": e.to_string() })
14537 }
14538 Ok(r) => match r.json::<HubEntry>() {
14539 Err(e) => {
14540 unreachable += 1;
14541 json!({ "vfr_id": vfr, "status": "unreachable", "error": format!("invalid hub response: {e}") })
14542 }
14543 Ok(entry) => {
14544 match p
14546 .project
14547 .dependencies
14548 .iter()
14549 .position(|d| d.vfr_id.as_deref() == Some(vfr.as_str()))
14550 {
14551 None => {
14552 unreachable += 1;
14553 json!({ "vfr_id": vfr, "status": "unreachable", "error": "dep disappeared mid-scan" })
14554 }
14555 Some(idx) => {
14556 let local_pin =
14557 p.project.dependencies[idx].pinned_snapshot_hash.clone();
14558 let new_pin = entry.latest_snapshot_hash;
14559 if local_pin.as_deref() == Some(new_pin.as_str()) {
14560 unchanged += 1;
14561 json!({ "vfr_id": vfr, "status": "unchanged", "snapshot": new_pin })
14562 } else {
14563 if !dry_run {
14564 p.project.dependencies[idx].pinned_snapshot_hash =
14565 Some(new_pin.clone());
14566 }
14567 refreshed += 1;
14568 json!({
14569 "vfr_id": vfr,
14570 "status": "refreshed",
14571 "old_snapshot": local_pin,
14572 "new_snapshot": new_pin,
14573 })
14574 }
14575 }
14576 }
14577 }
14578 },
14579 };
14580 per_dep.push(outcome);
14581 }
14582 if !dry_run && refreshed > 0 {
14583 repo::save_to_path(&frontier, &p).unwrap_or_else(|e| fail_return(&e));
14584 }
14585 let payload = json!({
14586 "ok": true,
14587 "command": "frontier.refresh-deps",
14588 "frontier": frontier.display().to_string(),
14589 "from": from,
14590 "dry_run": dry_run,
14591 "deps": per_dep,
14592 "summary": {
14593 "total": cross_deps.len(),
14594 "refreshed": refreshed,
14595 "unchanged": unchanged,
14596 "missing": missing,
14597 "unreachable": unreachable,
14598 },
14599 });
14600 if json {
14601 println!(
14602 "{}",
14603 serde_json::to_string_pretty(&payload)
14604 .expect("failed to serialize frontier.refresh-deps")
14605 );
14606 } else {
14607 let mode = if dry_run { " (dry-run)" } else { "" };
14608 println!(
14609 "{} refresh-deps{mode} · {} total · {refreshed} refreshed · {unchanged} unchanged · {missing} missing · {unreachable} unreachable",
14610 style::ok("frontier"),
14611 cross_deps.len()
14612 );
14613 for d in &per_dep {
14614 let vfr = d["vfr_id"].as_str().unwrap_or("?");
14615 let status = d["status"].as_str().unwrap_or("?");
14616 match status {
14617 "refreshed" => println!(
14618 " {vfr} refreshed {} → {}",
14619 d["old_snapshot"]
14620 .as_str()
14621 .unwrap_or("(none)")
14622 .chars()
14623 .take(16)
14624 .collect::<String>(),
14625 d["new_snapshot"]
14626 .as_str()
14627 .unwrap_or("?")
14628 .chars()
14629 .take(16)
14630 .collect::<String>(),
14631 ),
14632 "unchanged" => println!(" {vfr} unchanged"),
14633 "missing" => println!(" {vfr} missing on hub"),
14634 _ => println!(" {vfr} unreachable"),
14635 }
14636 }
14637 }
14638 }
14639 FrontierAction::Diff {
14640 frontier,
14641 since,
14642 week,
14643 json,
14644 } => cmd_frontier_diff(&frontier, since.as_deref(), week.as_deref(), json),
14645 FrontierAction::Release {
14646 frontier,
14647 name,
14648 notes,
14649 previous,
14650 json,
14651 } => cmd_frontier_release(frontier, name, notes, previous, json),
14652 FrontierAction::Releases { frontier, json } => cmd_frontier_releases(frontier, json),
14653 }
14654}
14655
14656fn cmd_frontier_release(
14658 frontier: PathBuf,
14659 name: String,
14660 notes: Option<String>,
14661 previous: Option<String>,
14662 json: bool,
14663) {
14664 use crate::frontier_release::{FrontierRelease, ReleaseDraft};
14665
14666 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
14667 let frontier_id = project.frontier_id();
14668 let snapshot_hash = events::snapshot_hash(&project);
14669 let event_log_hash = events::event_log_hash(&project.events);
14670
14671 let releases_dir = releases_dir_for(&frontier);
14674 let chained_previous = if previous.is_some() {
14675 previous
14676 } else {
14677 latest_release_id(&releases_dir)
14678 };
14679
14680 let owner_epoch = derive_owner_epoch(&frontier);
14684
14685 let draft = ReleaseDraft {
14686 frontier_id: frontier_id.clone(),
14687 name,
14688 notes,
14689 owner_epoch,
14690 snapshot_hash,
14691 event_log_hash,
14692 governance_policy_id: None,
14693 previous_release: chained_previous,
14694 released_at: chrono::Utc::now().to_rfc3339(),
14695 };
14696 let release = FrontierRelease::from_draft(draft).unwrap_or_else(|e| fail_return(&e));
14697
14698 if let Err(e) = std::fs::create_dir_all(&releases_dir) {
14699 fail(&format!("create releases dir: {e}"));
14700 }
14701 let path = releases_dir.join(format!("{}.json", release.release_id));
14702 let body = serde_json::to_string_pretty(&release).expect("serialize frontier release");
14703 std::fs::write(&path, format!("{body}\n"))
14704 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", path.display())));
14705
14706 if json {
14707 let payload = json!({
14708 "ok": true,
14709 "command": "frontier.release",
14710 "release_id": release.release_id,
14711 "frontier_id": release.frontier_id,
14712 "name": release.name,
14713 "owner_epoch": release.owner_epoch,
14714 "snapshot_hash": release.snapshot_hash,
14715 "event_log_hash": release.event_log_hash,
14716 "previous_release": release.previous_release,
14717 "released_at": release.released_at,
14718 "out": path.display().to_string(),
14719 });
14720 println!(
14721 "{}",
14722 serde_json::to_string_pretty(&payload).expect("serialize release summary")
14723 );
14724 } else {
14725 println!(
14726 "{} released {} ({}) of {}",
14727 style::ok("release"),
14728 release.release_id,
14729 release.name,
14730 release.frontier_id
14731 );
14732 println!(" owner_epoch: {}", release.owner_epoch);
14733 println!(" snapshot: {}", release.snapshot_hash);
14734 println!(" event_log: {}", release.event_log_hash);
14735 if let Some(prev) = &release.previous_release {
14736 println!(" previous: {}", prev);
14737 }
14738 println!(" out: {}", path.display());
14739 }
14740}
14741
14742fn cmd_frontier_releases(frontier: PathBuf, json: bool) {
14744 use crate::frontier_release::FrontierRelease;
14745
14746 let releases_dir = releases_dir_for(&frontier);
14747 let mut releases: Vec<FrontierRelease> = Vec::new();
14748 if releases_dir.exists() {
14749 for entry in std::fs::read_dir(&releases_dir)
14750 .unwrap_or_else(|e| fail_return(&format!("read releases dir: {e}")))
14751 {
14752 let entry = match entry {
14753 Ok(e) => e,
14754 Err(_) => continue,
14755 };
14756 let path = entry.path();
14757 if path.extension().and_then(|s| s.to_str()) != Some("json") {
14758 continue;
14759 }
14760 let raw = match std::fs::read_to_string(&path) {
14761 Ok(r) => r,
14762 Err(_) => continue,
14763 };
14764 if let Ok(r) = serde_json::from_str::<FrontierRelease>(&raw) {
14765 releases.push(r);
14766 }
14767 }
14768 }
14769 releases.sort_by(|a, b| b.released_at.cmp(&a.released_at));
14770
14771 if json {
14772 let payload = json!({
14773 "ok": true,
14774 "command": "frontier.releases",
14775 "frontier": frontier.display().to_string(),
14776 "release_count": releases.len(),
14777 "releases": releases,
14778 });
14779 println!(
14780 "{}",
14781 serde_json::to_string_pretty(&payload).expect("serialize releases list")
14782 );
14783 } else {
14784 println!(
14785 "{} {} release(s) for {}",
14786 style::ok("releases"),
14787 releases.len(),
14788 frontier.display()
14789 );
14790 for r in &releases {
14791 println!(" {} {} (epoch {})", r.release_id, r.name, r.owner_epoch);
14792 println!(" released_at: {}", r.released_at);
14793 if let Some(prev) = &r.previous_release {
14794 println!(" previous: {}", prev);
14795 }
14796 }
14797 }
14798}
14799
14800fn releases_dir_for(frontier: &Path) -> PathBuf {
14801 let dir = if frontier.is_dir() {
14802 frontier.to_path_buf()
14803 } else if let Some(parent) = frontier.parent() {
14804 parent.to_path_buf()
14805 } else {
14806 PathBuf::from(".")
14807 };
14808 dir.join(".vela").join("releases")
14809}
14810
14811fn latest_release_id(releases_dir: &Path) -> Option<String> {
14812 use crate::frontier_release::FrontierRelease;
14813 if !releases_dir.exists() {
14814 return None;
14815 }
14816 let mut latest: Option<(String, String)> = None;
14817 if let Ok(entries) = std::fs::read_dir(releases_dir) {
14818 for entry in entries.flatten() {
14819 let path = entry.path();
14820 if path.extension().and_then(|s| s.to_str()) != Some("json") {
14821 continue;
14822 }
14823 let raw = match std::fs::read_to_string(&path) {
14824 Ok(r) => r,
14825 Err(_) => continue,
14826 };
14827 if let Ok(r) = serde_json::from_str::<FrontierRelease>(&raw) {
14828 let pick = latest
14829 .as_ref()
14830 .map(|(_, ts)| ts.as_str() < r.released_at.as_str())
14831 .unwrap_or(true);
14832 if pick {
14833 latest = Some((r.release_id, r.released_at));
14834 }
14835 }
14836 }
14837 }
14838 latest.map(|(id, _)| id)
14839}
14840
14841fn derive_owner_epoch(frontier: &Path) -> u64 {
14842 let chain_path = if frontier.is_dir() {
14843 frontier.join(".vela").join("governance").join("chain.json")
14844 } else if let Some(parent) = frontier.parent() {
14845 parent.join(".vela").join("governance").join("chain.json")
14846 } else {
14847 return 0;
14848 };
14849 if !chain_path.exists() {
14850 return 0;
14851 }
14852 let raw = match std::fs::read_to_string(&chain_path) {
14853 Ok(r) => r,
14854 Err(_) => return 0,
14855 };
14856 let v: serde_json::Value = match serde_json::from_str(&raw) {
14857 Ok(v) => v,
14858 Err(_) => return 0,
14859 };
14860 v.get("transitions")
14861 .and_then(|t| t.as_array())
14862 .and_then(|arr| arr.last())
14863 .and_then(|t| t.get("owner_epoch"))
14864 .and_then(|e| e.as_u64())
14865 .unwrap_or(0)
14866}
14867
14868fn cmd_repo(action: RepoAction) {
14869 match action {
14870 RepoAction::Status { frontier, json } => {
14871 let payload = frontier_repo::repo_status(&frontier).unwrap_or_else(|e| fail_return(&e));
14872 if json {
14873 println!(
14874 "{}",
14875 serde_json::to_string_pretty(&payload)
14876 .expect("failed to serialize repo status")
14877 );
14878 } else {
14879 let summary = payload.get("summary").unwrap_or(&Value::Null);
14880 let freshness = payload.get("freshness").unwrap_or(&Value::Null);
14881 println!("vela repo status");
14882 println!(" frontier: {}", frontier.display());
14883 println!(
14884 " events: {}",
14885 summary
14886 .get("accepted_events")
14887 .and_then(Value::as_u64)
14888 .unwrap_or_default()
14889 );
14890 println!(
14891 " open proposals: {}",
14892 summary
14893 .get("open_proposals")
14894 .and_then(Value::as_u64)
14895 .unwrap_or_default()
14896 );
14897 println!(
14898 " state: {}",
14899 freshness
14900 .get("materialized_state")
14901 .and_then(Value::as_str)
14902 .unwrap_or("unknown")
14903 );
14904 println!(
14905 " proof: {}",
14906 freshness
14907 .get("proof")
14908 .and_then(Value::as_str)
14909 .unwrap_or("unknown")
14910 );
14911 }
14912 }
14913 RepoAction::Doctor { frontier, json } => {
14914 let payload = frontier_repo::repo_doctor(&frontier).unwrap_or_else(|e| fail_return(&e));
14915 if json {
14916 println!(
14917 "{}",
14918 serde_json::to_string_pretty(&payload)
14919 .expect("failed to serialize repo doctor")
14920 );
14921 } else {
14922 let ok = payload.get("ok").and_then(Value::as_bool) == Some(true);
14923 let issues = payload
14924 .get("issues")
14925 .and_then(Value::as_array)
14926 .map_or(0, Vec::len);
14927 println!("vela repo doctor");
14928 println!(" frontier: {}", frontier.display());
14929 println!(" status: {}", if ok { "ok" } else { "needs attention" });
14930 println!(" issues: {issues}");
14931 }
14932 }
14933 }
14934}
14935
14936fn cmd_proof_verify(frontier: &Path, json_output: bool) {
14937 let payload = frontier_repo::proof_verify(frontier).unwrap_or_else(|e| fail_return(&e));
14938 if json_output {
14939 println!(
14940 "{}",
14941 serde_json::to_string_pretty(&payload).expect("failed to serialize proof verify")
14942 );
14943 if payload.get("ok").and_then(Value::as_bool) != Some(true) {
14944 std::process::exit(1);
14945 }
14946 } else {
14947 let ok = payload.get("ok").and_then(Value::as_bool) == Some(true);
14948 println!("vela proof verify");
14949 println!(" frontier: {}", frontier.display());
14950 println!(" status: {}", if ok { "ok" } else { "failed" });
14951 if let Some(issues) = payload.get("issues").and_then(Value::as_array) {
14952 for issue in issues {
14953 if let Some(message) = issue.get("message").and_then(Value::as_str) {
14954 println!(" issue: {message}");
14955 }
14956 }
14957 }
14958 if !ok {
14959 std::process::exit(1);
14960 }
14961 }
14962}
14963
14964fn cmd_proof_explain(frontier: &Path) {
14965 let text = frontier_repo::proof_explain(frontier).unwrap_or_else(|e| fail_return(&e));
14966 print!("{text}");
14967}
14968
14969fn cmd_frontier_diff(frontier: &Path, since: Option<&str>, week: Option<&str>, json: bool) {
14978 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
14979
14980 let now = chrono::Utc::now();
14982 let (window_start, window_end, week_label): (
14983 chrono::DateTime<chrono::Utc>,
14984 chrono::DateTime<chrono::Utc>,
14985 Option<String>,
14986 ) = if let Some(s) = since {
14987 let parsed = chrono::DateTime::parse_from_rfc3339(s)
14988 .map(|d| d.with_timezone(&chrono::Utc))
14989 .unwrap_or_else(|e| fail_return(&format!("invalid --since timestamp '{s}': {e}")));
14990 (parsed, now, None)
14991 } else {
14992 let key = week
14993 .map(str::to_owned)
14994 .unwrap_or_else(|| iso_week_key_for(now.date_naive()));
14995 let (start, end) = iso_week_bounds(&key)
14996 .unwrap_or_else(|e| fail_return(&format!("invalid --week '{key}': {e}")));
14997 (start, end, Some(key))
14998 };
14999
15000 let mut added: Vec<&crate::bundle::FindingBundle> = Vec::new();
15002 let mut updated: Vec<&crate::bundle::FindingBundle> = Vec::new();
15003 let mut new_contradictions: Vec<&crate::bundle::FindingBundle> = Vec::new();
15004 let mut cumulative: usize = 0;
15005
15006 for f in &project.findings {
15007 let created = chrono::DateTime::parse_from_rfc3339(&f.created)
15008 .map(|d| d.with_timezone(&chrono::Utc))
15009 .ok();
15010 let updated_ts = f
15011 .updated
15012 .as_deref()
15013 .and_then(|u| chrono::DateTime::parse_from_rfc3339(u).ok())
15014 .map(|d| d.with_timezone(&chrono::Utc));
15015
15016 if let Some(c) = created
15017 && c < window_end
15018 {
15019 cumulative += 1;
15020 }
15021
15022 if let Some(c) = created
15023 && c >= window_start
15024 && c < window_end
15025 {
15026 added.push(f);
15027 let is_tension = f.flags.contested || f.assertion.assertion_type == "tension";
15028 if is_tension {
15029 new_contradictions.push(f);
15030 }
15031 continue;
15032 }
15033 if let Some(u) = updated_ts
15034 && u >= window_start
15035 && u < window_end
15036 {
15037 updated.push(f);
15038 }
15039 }
15040
15041 let summary_for = |list: &[&crate::bundle::FindingBundle]| -> Vec<serde_json::Value> {
15043 list.iter()
15044 .map(|f| {
15045 json!({
15046 "id": f.id,
15047 "assertion": f.assertion.text,
15048 "evidence_type": f.evidence.evidence_type,
15049 "confidence": f.confidence.score,
15050 "doi": f.provenance.doi,
15051 "pmid": f.provenance.pmid,
15052 })
15053 })
15054 .collect()
15055 };
15056
15057 let payload = json!({
15058 "ok": true,
15059 "command": "frontier.diff",
15060 "frontier": frontier.display().to_string(),
15061 "frontier_id": project.frontier_id,
15062 "window": {
15063 "start": window_start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
15064 "end": window_end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
15065 "iso_week": week_label,
15066 },
15067 "totals": {
15068 "added": added.len(),
15069 "updated": updated.len(),
15070 "new_contradictions": new_contradictions.len(),
15071 "cumulative_claims": cumulative,
15072 },
15073 "added": summary_for(&added),
15074 "updated": summary_for(&updated),
15075 "new_contradictions": summary_for(&new_contradictions),
15076 });
15077
15078 if json {
15079 println!(
15080 "{}",
15081 serde_json::to_string_pretty(&payload).expect("failed to serialize frontier.diff")
15082 );
15083 return;
15084 }
15085
15086 let label = week_label
15087 .clone()
15088 .unwrap_or_else(|| format!("since {}", window_start.format("%Y-%m-%d %H:%M UTC")));
15089 println!();
15090 println!(
15091 " {}",
15092 format!("VELA · FRONTIER · DIFF · {label}")
15093 .to_uppercase()
15094 .dimmed()
15095 );
15096 println!(" {}", style::tick_row(60));
15097 println!(
15098 " range: {} → {}",
15099 window_start.format("%Y-%m-%d %H:%M"),
15100 window_end.format("%Y-%m-%d %H:%M")
15101 );
15102 println!(" added: {}", added.len());
15103 println!(" updated: {}", updated.len());
15104 println!(" contradictions: {}", new_contradictions.len());
15105 println!(" cumulative: {cumulative}");
15106 if added.is_empty() && updated.is_empty() {
15107 println!();
15108 println!(" (quiet window — no findings added or updated)");
15109 } else {
15110 println!();
15111 println!(" added:");
15112 for f in &added {
15113 println!(
15114 " · {} {}",
15115 f.id.dimmed(),
15116 truncate(&f.assertion.text, 88)
15117 );
15118 }
15119 if !updated.is_empty() {
15120 println!();
15121 println!(" updated:");
15122 for f in &updated {
15123 println!(
15124 " · {} {}",
15125 f.id.dimmed(),
15126 truncate(&f.assertion.text, 88)
15127 );
15128 }
15129 }
15130 }
15131}
15132
15133fn truncate(s: &str, n: usize) -> String {
15134 if s.chars().count() <= n {
15135 s.to_string()
15136 } else {
15137 let mut out: String = s.chars().take(n.saturating_sub(1)).collect();
15138 out.push('…');
15139 out
15140 }
15141}
15142
15143fn iso_week_key_for(d: chrono::NaiveDate) -> String {
15145 use chrono::Datelike;
15146 let iso = d.iso_week();
15147 format!("{:04}-W{:02}", iso.year(), iso.week())
15148}
15149
15150fn iso_week_bounds(
15153 key: &str,
15154) -> Result<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>), String> {
15155 let (year_str, week_str) = key
15156 .split_once("-W")
15157 .ok_or_else(|| format!("expected YYYY-Www, got '{key}'"))?;
15158 let year: i32 = year_str
15159 .parse()
15160 .map_err(|e| format!("bad year in '{key}': {e}"))?;
15161 let week: u32 = week_str
15162 .parse()
15163 .map_err(|e| format!("bad week in '{key}': {e}"))?;
15164 let monday = chrono::NaiveDate::from_isoywd_opt(year, week, chrono::Weekday::Mon)
15165 .ok_or_else(|| format!("invalid ISO week: {key}"))?;
15166 let next_monday = monday + chrono::Duration::days(7);
15167 let start = monday.and_hms_opt(0, 0, 0).expect("00:00 valid").and_utc();
15168 let end = next_monday
15169 .and_hms_opt(0, 0, 0)
15170 .expect("00:00 valid")
15171 .and_utc();
15172 Ok((start, end))
15173}
15174
15175fn cmd_registry(action: RegistryAction) {
15180 use crate::registry;
15181 let default_registry = || -> PathBuf {
15182 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
15183 PathBuf::from(home)
15184 .join(".vela")
15185 .join("registry")
15186 .join("entries.json")
15187 };
15188 match action {
15189 RegistryAction::Governance { action } => cmd_governance(action),
15190 RegistryAction::OwnerRotateGoverned { action } => cmd_owner_rotate_governed(action),
15191 RegistryAction::Checkpoint { action } => cmd_checkpoint(action),
15192 RegistryAction::VerifyAll { from, json } => cmd_verify_all(from, json),
15193 RegistryAction::HubFederation { action } => cmd_hub_federation(action),
15194 RegistryAction::VerifyChain {
15195 frontier,
15196 artifacts,
15197 json,
15198 } => cmd_verify_chain(frontier, artifacts, json),
15199 RegistryAction::DependsOn { vfr_id, from, json } => {
15200 let base = from.trim_end_matches('/');
15201 let url = format!("{base}/entries/{vfr_id}/depends-on");
15202 let client = reqwest::blocking::Client::builder()
15203 .timeout(std::time::Duration::from_secs(30))
15204 .build()
15205 .unwrap_or_else(|e| fail_return(&format!("http client init: {e}")));
15206 let resp = client
15207 .get(&url)
15208 .send()
15209 .unwrap_or_else(|e| fail_return(&format!("GET {url}: {e}")));
15210 if !resp.status().is_success() {
15211 fail(&format!("GET {url}: HTTP {}", resp.status()));
15212 }
15213 let body: serde_json::Value = resp
15214 .json()
15215 .unwrap_or_else(|e| fail_return(&format!("parse response: {e}")));
15216 if json {
15217 println!(
15218 "{}",
15219 serde_json::to_string_pretty(&body).expect("serialize")
15220 );
15221 } else {
15222 let dependents = body
15223 .get("dependents")
15224 .and_then(|v| v.as_array())
15225 .cloned()
15226 .unwrap_or_default();
15227 let count = dependents.len();
15228 println!(
15229 "{} {count} {} on {vfr_id}",
15230 style::ok("registry"),
15231 if count == 1 {
15232 "frontier depends"
15233 } else {
15234 "frontiers depend"
15235 },
15236 );
15237 for e in &dependents {
15238 let v = e.get("vfr_id").and_then(|v| v.as_str()).unwrap_or("?");
15239 let n = e.get("name").and_then(|v| v.as_str()).unwrap_or("?");
15240 let o = e
15241 .get("owner_actor_id")
15242 .and_then(|v| v.as_str())
15243 .unwrap_or("?");
15244 println!(" {v} {n} ({o})");
15245 }
15246 }
15247 }
15248 RegistryAction::Mirror {
15249 vfr_id,
15250 from,
15251 to,
15252 json,
15253 } => {
15254 let src_base = from.trim_end_matches('/');
15255 let dst_base = to.trim_end_matches('/');
15256 let src_url = format!("{src_base}/entries/{vfr_id}");
15257 let dst_url = format!("{dst_base}/entries");
15258 let client = reqwest::blocking::Client::builder()
15259 .timeout(std::time::Duration::from_secs(30))
15260 .build()
15261 .unwrap_or_else(|e| fail_return(&format!("http client init: {e}")));
15262
15263 let entry: serde_json::Value = client
15264 .get(&src_url)
15265 .send()
15266 .unwrap_or_else(|e| fail_return(&format!("GET {src_url}: {e}")))
15267 .error_for_status()
15268 .unwrap_or_else(|e| fail_return(&format!("GET {src_url}: {e}")))
15269 .json()
15270 .unwrap_or_else(|e| fail_return(&format!("parse {src_url}: {e}")));
15271
15272 let resp = client
15273 .post(&dst_url)
15274 .header("content-type", "application/json")
15275 .body(
15276 serde_json::to_vec(&entry)
15277 .unwrap_or_else(|e| fail_return(&format!("serialize: {e}"))),
15278 )
15279 .send()
15280 .unwrap_or_else(|e| fail_return(&format!("POST {dst_url}: {e}")));
15281 let status = resp.status();
15282 if !status.is_success() {
15283 let body = resp.text().unwrap_or_default();
15284 fail(&format!(
15285 "POST {dst_url}: HTTP {status}: {}",
15286 body.chars().take(300).collect::<String>()
15287 ));
15288 }
15289 let body: serde_json::Value = resp
15290 .json()
15291 .unwrap_or_else(|e| fail_return(&format!("parse POST response: {e}")));
15292 let duplicate = body
15293 .get("duplicate")
15294 .and_then(serde_json::Value::as_bool)
15295 .unwrap_or(false);
15296 let payload = json!({
15297 "ok": true,
15298 "command": "registry.mirror",
15299 "vfr_id": vfr_id,
15300 "from": src_base,
15301 "to": dst_base,
15302 "duplicate_on_destination": duplicate,
15303 "destination_response": body,
15304 });
15305 if json {
15306 println!(
15307 "{}",
15308 serde_json::to_string_pretty(&payload).expect("serialize")
15309 );
15310 } else {
15311 println!(
15312 "{} mirrored {vfr_id} from {src_base} → {dst_base}{}",
15313 style::ok("registry"),
15314 if duplicate {
15315 " (duplicate; signature already known)"
15316 } else {
15317 " (fresh insert)"
15318 }
15319 );
15320 }
15321 }
15322 RegistryAction::WitnessCheck { vfr_id, hubs, json } => {
15323 if hubs.len() < 2 {
15332 fail("--hubs requires at least two hub URLs (comma-separated).");
15333 }
15334 let client = reqwest::blocking::Client::builder()
15335 .timeout(std::time::Duration::from_secs(30))
15336 .build()
15337 .unwrap_or_else(|e| fail_return(&format!("http client init: {e}")));
15338
15339 #[derive(serde::Serialize)]
15340 struct HubResponse {
15341 hub: String,
15342 status: String,
15343 #[serde(skip_serializing_if = "Option::is_none")]
15344 canonical_hash: Option<String>,
15345 #[serde(skip_serializing_if = "Option::is_none")]
15346 note: Option<String>,
15347 }
15348
15349 let mut responses: Vec<HubResponse> = Vec::new();
15350 let mut hash_counts: std::collections::BTreeMap<String, usize> =
15351 std::collections::BTreeMap::new();
15352
15353 for hub_url in &hubs {
15354 let base = hub_url.trim_end_matches('/');
15355 let url = format!("{base}/entries/{vfr_id}");
15356 match client.get(&url).send() {
15357 Ok(resp) if resp.status().is_success() => {
15358 match resp.json::<serde_json::Value>() {
15359 Ok(entry) => {
15360 let canonical = crate::canonical::to_canonical_bytes(&entry)
15365 .unwrap_or_else(|e| fail_return(&format!("canonicalize: {e}")));
15366 let hash =
15367 format!("sha256:{}", hex::encode(Sha256::digest(&canonical)));
15368 *hash_counts.entry(hash.clone()).or_insert(0) += 1;
15369 responses.push(HubResponse {
15370 hub: base.to_string(),
15371 status: "ok".to_string(),
15372 canonical_hash: Some(hash),
15373 note: None,
15374 });
15375 }
15376 Err(e) => responses.push(HubResponse {
15377 hub: base.to_string(),
15378 status: "parse_error".to_string(),
15379 canonical_hash: None,
15380 note: Some(format!("parse: {e}")),
15381 }),
15382 }
15383 }
15384 Ok(resp) => responses.push(HubResponse {
15385 hub: base.to_string(),
15386 status: "http_error".to_string(),
15387 canonical_hash: None,
15388 note: Some(format!("HTTP {}", resp.status())),
15389 }),
15390 Err(e) => responses.push(HubResponse {
15391 hub: base.to_string(),
15392 status: "unreachable".to_string(),
15393 canonical_hash: None,
15394 note: Some(format!("{e}")),
15395 }),
15396 }
15397 }
15398
15399 let resolved_count = responses
15401 .iter()
15402 .filter(|r| r.canonical_hash.is_some())
15403 .count();
15404 let consensus = if resolved_count < 2 {
15405 "insufficient".to_string()
15406 } else if hash_counts.len() == 1 {
15407 "unanimous".to_string()
15408 } else {
15409 let max = hash_counts.values().copied().max().unwrap_or(0);
15410 if max * 2 > resolved_count {
15411 "majority".to_string()
15412 } else {
15413 "split".to_string()
15414 }
15415 };
15416
15417 let payload = json!({
15418 "ok": consensus == "unanimous" || consensus == "majority",
15419 "command": "registry.witness-check",
15420 "vfr_id": vfr_id,
15421 "hubs_queried": hubs.len(),
15422 "hubs_resolved": resolved_count,
15423 "distinct_canonical_hashes": hash_counts.len(),
15424 "consensus": consensus,
15425 "responses": responses,
15426 });
15427
15428 if json {
15429 println!(
15430 "{}",
15431 serde_json::to_string_pretty(&payload)
15432 .expect("failed to serialize witness-check")
15433 );
15434 } else {
15435 println!(
15436 "{} witness-check {} across {} hub(s): {}",
15437 style::ok("registry"),
15438 vfr_id,
15439 hubs.len(),
15440 consensus
15441 );
15442 for r in &responses {
15443 let hash_display = r
15444 .canonical_hash
15445 .as_deref()
15446 .map(|h| h.chars().take(16).collect::<String>())
15447 .unwrap_or_else(|| r.note.clone().unwrap_or_default());
15448 println!(" {} {} {hash_display}", r.status, r.hub);
15449 }
15450 }
15451 if consensus == "split" {
15452 std::process::exit(1);
15453 }
15454 }
15455 RegistryAction::List { from, json } => {
15456 let (label, registry_data) = match &from {
15459 Some(loc) if loc.starts_with("http") => (
15460 loc.clone(),
15461 registry::load_any(loc).unwrap_or_else(|e| fail_return(&e)),
15462 ),
15463 Some(loc) => {
15464 let p = registry::resolve_local(loc).unwrap_or_else(|e| fail_return(&e));
15465 (
15466 p.display().to_string(),
15467 registry::load_local(&p).unwrap_or_else(|e| fail_return(&e)),
15468 )
15469 }
15470 None => {
15471 let p = default_registry();
15472 (
15473 p.display().to_string(),
15474 registry::load_local(&p).unwrap_or_else(|e| fail_return(&e)),
15475 )
15476 }
15477 };
15478 let r = registry_data;
15479 let path_label = label;
15480 if json {
15481 let payload = json!({
15482 "ok": true,
15483 "command": "registry.list",
15484 "registry": path_label,
15485 "entry_count": r.entries.len(),
15486 "entries": r.entries,
15487 });
15488 println!(
15489 "{}",
15490 serde_json::to_string_pretty(&payload)
15491 .expect("failed to serialize registry.list")
15492 );
15493 } else {
15494 println!();
15495 println!(
15496 " {}",
15497 format!("VELA · REGISTRY · LIST · {}", path_label)
15498 .to_uppercase()
15499 .dimmed()
15500 );
15501 println!(" {}", style::tick_row(60));
15502 if r.entries.is_empty() {
15503 println!(" (registry is empty)");
15504 } else {
15505 for entry in &r.entries {
15506 println!(
15507 " {} {} ({}) by {} published {}",
15508 entry.vfr_id,
15509 entry.name,
15510 entry.network_locator,
15511 entry.owner_actor_id,
15512 entry.signed_publish_at
15513 );
15514 }
15515 }
15516 }
15517 }
15518 RegistryAction::Publish {
15519 frontier,
15520 owner,
15521 key,
15522 locator,
15523 to,
15524 license,
15525 json,
15526 } => {
15527 let key_hex = std::fs::read_to_string(&key)
15530 .map(|s| s.trim().to_string())
15531 .unwrap_or_else(|e| fail_return(&format!("read key {}: {e}", key.display())));
15532 let signing_key = parse_signing_key(&key_hex);
15533 let derived = hex::encode(signing_key.verifying_key().to_bytes());
15534
15535 let mut frontier_data =
15537 repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
15538
15539 let pubkey = match frontier_data.actors.iter().find(|actor| actor.id == owner) {
15540 Some(actor) => actor.public_key.clone(),
15541 None => {
15542 eprintln!(
15550 " vela registry publish · auto-registering actor {owner} (derived pubkey {})",
15551 &derived[..16]
15552 );
15553 frontier_data.actors.push(sign::ActorRecord {
15554 id: owner.clone(),
15555 public_key: derived.clone(),
15556 algorithm: "ed25519".to_string(),
15557 created_at: chrono::Utc::now().to_rfc3339(),
15558 tier: None,
15559 orcid: None,
15560 access_clearance: None,
15561 revoked_at: None,
15562 revoked_reason: None,
15563 });
15564 repo::save_to_path(&frontier, &frontier_data)
15565 .unwrap_or_else(|e| fail_return(&format!("save actor: {e}")));
15566 derived.clone()
15567 }
15568 };
15569
15570 let snapshot_hash = events::snapshot_hash(&frontier_data);
15574 let event_log_hash = events::event_log_hash(&frontier_data.events);
15575 let vfr_id = frontier_data.frontier_id();
15576 let name = frontier_data.project.name.clone();
15577
15578 if derived != pubkey {
15580 fail(&format!(
15581 "private key does not match registered pubkey for owner '{owner}'"
15582 ));
15583 }
15584
15585 let to_is_remote = matches!(
15593 to.as_deref(),
15594 Some(loc) if loc.starts_with("http://") || loc.starts_with("https://")
15595 );
15596 let resolved_locator = match locator {
15597 Some(l) => l,
15598 None => {
15599 if to_is_remote {
15600 let hub = to.as_deref().unwrap().trim_end_matches('/');
15601 let hub_root = hub.trim_end_matches("/entries");
15602 format!("{hub_root}/entries/{vfr_id}/snapshot")
15603 } else {
15604 fail_return(
15605 "--locator is required for local publishes; pass e.g. \
15606 --locator file:///path/to/frontier.json or an HTTPS URL.",
15607 )
15608 }
15609 }
15610 };
15611
15612 let mut entry = registry::RegistryEntry {
15613 schema: registry::ENTRY_SCHEMA.to_string(),
15614 vfr_id: vfr_id.clone(),
15615 name: name.clone(),
15616 owner_actor_id: owner.clone(),
15617 owner_pubkey: pubkey,
15618 latest_snapshot_hash: snapshot_hash,
15619 latest_event_log_hash: event_log_hash,
15620 network_locator: resolved_locator,
15621 license: license.clone(),
15622 signed_publish_at: chrono::Utc::now().to_rfc3339(),
15623 signature: String::new(),
15624 };
15625 entry.signature =
15626 registry::sign_entry(&entry, &signing_key).unwrap_or_else(|e| fail_return(&e));
15627
15628 let (registry_label, duplicate) = if to_is_remote {
15629 let hub_url = to.clone().unwrap();
15630 let resp = registry::publish_remote(&entry, &hub_url, Some(&frontier_data))
15634 .unwrap_or_else(|e| fail_return(&e));
15635 (hub_url, resp.duplicate)
15636 } else {
15637 let registry_path = match &to {
15638 Some(loc) => registry::resolve_local(loc).unwrap_or_else(|e| fail_return(&e)),
15639 None => default_registry(),
15640 };
15641 registry::publish_entry(®istry_path, entry.clone())
15642 .unwrap_or_else(|e| fail_return(&e));
15643 (registry_path.display().to_string(), false)
15644 };
15645
15646 let payload = json!({
15647 "ok": true,
15648 "command": "registry.publish",
15649 "registry": registry_label,
15650 "vfr_id": vfr_id,
15651 "name": name,
15652 "owner": owner,
15653 "snapshot_hash": entry.latest_snapshot_hash,
15654 "event_log_hash": entry.latest_event_log_hash,
15655 "signed_publish_at": entry.signed_publish_at,
15656 "signature": entry.signature,
15657 "duplicate": duplicate,
15658 });
15659 if json {
15660 println!(
15661 "{}",
15662 serde_json::to_string_pretty(&payload)
15663 .expect("failed to serialize registry.publish")
15664 );
15665 } else {
15666 let dup_suffix = if duplicate { " (duplicate, no-op)" } else { "" };
15667 println!(
15668 "{} published {vfr_id} → {}{}",
15669 style::ok("registry"),
15670 registry_label,
15671 dup_suffix
15672 );
15673 println!(" snapshot: {}", entry.latest_snapshot_hash);
15674 println!(" event_log: {}", entry.latest_event_log_hash);
15675 println!(" signature: {}…", &entry.signature[..16]);
15676 }
15677 }
15678 RegistryAction::OwnerRotate {
15679 frontier,
15680 current_owner,
15681 new_owner,
15682 new_key,
15683 reason,
15684 locator,
15685 to,
15686 json,
15687 } => {
15688 if reason.trim().is_empty() {
15689 fail("--reason must be non-empty (record why the rotation is happening).");
15690 }
15691 if current_owner == new_owner {
15692 fail(
15693 "--current-owner and --new-owner must differ; rotation registers a fresh owner actor record.",
15694 );
15695 }
15696
15697 let key_hex = std::fs::read_to_string(&new_key)
15701 .map(|s| s.trim().to_string())
15702 .unwrap_or_else(|e| {
15703 fail_return(&format!("read new key {}: {e}", new_key.display()))
15704 });
15705 let signing_key = parse_signing_key(&key_hex);
15706 let derived = hex::encode(signing_key.verifying_key().to_bytes());
15707
15708 let mut frontier_data =
15709 repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
15710
15711 let now = chrono::Utc::now().to_rfc3339();
15713 let mut retired_pubkey_prefix: Option<String> = None;
15714 let mut found_current = false;
15715 for actor in frontier_data.actors.iter_mut() {
15716 if actor.id == current_owner {
15717 if actor.revoked_at.is_some() {
15718 fail(&format!(
15719 "Refusing to rotate: actor '{current_owner}' is already revoked at {}.",
15720 actor.revoked_at.as_deref().unwrap_or("?")
15721 ));
15722 }
15723 actor.revoked_at = Some(now.clone());
15724 actor.revoked_reason = Some(reason.clone());
15725 retired_pubkey_prefix = Some(actor.public_key[..16].to_string());
15726 found_current = true;
15727 }
15728 }
15729 if !found_current {
15730 fail(&format!(
15731 "Cannot rotate: actor '{current_owner}' is not registered in this frontier."
15732 ));
15733 }
15734
15735 let new_pubkey = match frontier_data.actors.iter().find(|a| a.id == new_owner) {
15740 Some(existing) => {
15741 if existing.revoked_at.is_some() {
15742 fail(&format!(
15743 "Refusing to rotate: target actor '{new_owner}' is already revoked at {}.",
15744 existing.revoked_at.as_deref().unwrap_or("?")
15745 ));
15746 }
15747 if existing.public_key != derived {
15748 fail(&format!(
15749 "private key does not match registered pubkey for new owner '{new_owner}'"
15750 ));
15751 }
15752 existing.public_key.clone()
15753 }
15754 None => {
15755 frontier_data.actors.push(sign::ActorRecord {
15756 id: new_owner.clone(),
15757 public_key: derived.clone(),
15758 algorithm: "ed25519".to_string(),
15759 created_at: now.clone(),
15760 tier: None,
15761 orcid: None,
15762 access_clearance: None,
15763 revoked_at: None,
15764 revoked_reason: None,
15765 });
15766 derived.clone()
15767 }
15768 };
15769
15770 repo::save_to_path(&frontier, &frontier_data)
15771 .unwrap_or_else(|e| fail_return(&format!("save rotation: {e}")));
15772
15773 let snapshot_hash = events::snapshot_hash(&frontier_data);
15777 let event_log_hash = events::event_log_hash(&frontier_data.events);
15778 let vfr_id = frontier_data.frontier_id();
15779 let name = frontier_data.project.name.clone();
15780
15781 let to_is_remote = matches!(
15782 to.as_deref(),
15783 Some(loc) if loc.starts_with("http://") || loc.starts_with("https://")
15784 );
15785 let resolved_locator = match locator {
15786 Some(l) => l,
15787 None => {
15788 if to_is_remote {
15789 let hub = to.as_deref().unwrap().trim_end_matches('/');
15790 let hub_root = hub.trim_end_matches("/entries");
15791 format!("{hub_root}/entries/{vfr_id}/snapshot")
15792 } else {
15793 fail_return(
15794 "--locator is required for local publishes; pass e.g. \
15795 --locator file:///path/to/frontier.json or an HTTPS URL.",
15796 )
15797 }
15798 }
15799 };
15800
15801 let mut entry = registry::RegistryEntry {
15802 schema: registry::ENTRY_SCHEMA.to_string(),
15803 vfr_id: vfr_id.clone(),
15804 name: name.clone(),
15805 owner_actor_id: new_owner.clone(),
15806 owner_pubkey: new_pubkey,
15807 latest_snapshot_hash: snapshot_hash,
15808 latest_event_log_hash: event_log_hash,
15809 network_locator: resolved_locator,
15810 license: None,
15811 signed_publish_at: chrono::Utc::now().to_rfc3339(),
15812 signature: String::new(),
15813 };
15814 entry.signature =
15815 registry::sign_entry(&entry, &signing_key).unwrap_or_else(|e| fail_return(&e));
15816
15817 let (registry_label, duplicate) = if to_is_remote {
15818 let hub_url = to.clone().unwrap();
15819 let resp = registry::publish_remote(&entry, &hub_url, Some(&frontier_data))
15820 .unwrap_or_else(|e| fail_return(&e));
15821 (hub_url, resp.duplicate)
15822 } else {
15823 let registry_path = match &to {
15824 Some(loc) => registry::resolve_local(loc).unwrap_or_else(|e| fail_return(&e)),
15825 None => default_registry(),
15826 };
15827 registry::publish_entry(®istry_path, entry.clone())
15828 .unwrap_or_else(|e| fail_return(&e));
15829 (registry_path.display().to_string(), false)
15830 };
15831
15832 let payload = json!({
15833 "ok": true,
15834 "command": "registry.owner_rotate",
15835 "registry": registry_label,
15836 "vfr_id": vfr_id,
15837 "name": name,
15838 "retired_owner": current_owner,
15839 "retired_pubkey_prefix": retired_pubkey_prefix,
15840 "new_owner": new_owner,
15841 "new_pubkey": derived,
15842 "revoked_at": now,
15843 "reason": reason,
15844 "snapshot_hash": entry.latest_snapshot_hash,
15845 "event_log_hash": entry.latest_event_log_hash,
15846 "signed_publish_at": entry.signed_publish_at,
15847 "signature": entry.signature,
15848 "duplicate": duplicate,
15849 });
15850 if json {
15851 println!(
15852 "{}",
15853 serde_json::to_string_pretty(&payload)
15854 .expect("failed to serialize registry.owner_rotate")
15855 );
15856 } else {
15857 println!(
15858 "{} owner rotated: {} (pubkey {}...) retired, {} (pubkey {}...) active",
15859 style::ok("registry"),
15860 current_owner,
15861 retired_pubkey_prefix.as_deref().unwrap_or("?"),
15862 new_owner,
15863 &derived[..16]
15864 );
15865 println!(" revoked_at: {now}");
15866 println!(" reason: {reason}");
15867 let dup_suffix = if duplicate { " (duplicate, no-op)" } else { "" };
15868 println!(" registry: {vfr_id} → {registry_label}{dup_suffix}");
15869 println!(" signature: {}…", &entry.signature[..16]);
15870 }
15871 }
15872 RegistryAction::Pull {
15873 vfr_id,
15874 from,
15875 out,
15876 transitive,
15877 depth,
15878 json,
15879 } => {
15880 let (registry_label, registry_data) = match &from {
15884 Some(loc) if loc.starts_with("http") => (
15885 loc.clone(),
15886 registry::load_any(loc).unwrap_or_else(|e| fail_return(&e)),
15887 ),
15888 Some(loc) => {
15889 let p = registry::resolve_local(loc).unwrap_or_else(|e| fail_return(&e));
15890 (
15891 p.display().to_string(),
15892 registry::load_local(&p).unwrap_or_else(|e| fail_return(&e)),
15893 )
15894 }
15895 None => {
15896 let p = default_registry();
15897 (
15898 p.display().to_string(),
15899 registry::load_local(&p).unwrap_or_else(|e| fail_return(&e)),
15900 )
15901 }
15902 };
15903 let entry = registry::find_latest(®istry_data, &vfr_id)
15904 .unwrap_or_else(|| fail_return(&format!("{vfr_id} not found in registry")));
15905
15906 if transitive {
15907 let result = registry::pull_transitive(®istry_data, &vfr_id, &out, depth)
15911 .unwrap_or_else(|e| fail_return(&format!("transitive pull failed: {e}")));
15912
15913 let dep_paths_json: serde_json::Value = serde_json::Value::Object(
15914 result
15915 .deps
15916 .iter()
15917 .map(|(k, v)| (k.clone(), serde_json::json!(v.display().to_string())))
15918 .collect(),
15919 );
15920 let payload = json!({
15921 "ok": true,
15922 "command": "registry.pull",
15923 "registry": registry_label,
15924 "vfr_id": vfr_id,
15925 "transitive": true,
15926 "depth": depth,
15927 "out_dir": out.display().to_string(),
15928 "primary": result.primary_path.display().to_string(),
15929 "verified": result.verified,
15930 "deps": dep_paths_json,
15931 });
15932 if json {
15933 println!(
15934 "{}",
15935 serde_json::to_string_pretty(&payload)
15936 .expect("failed to serialize registry.pull")
15937 );
15938 } else {
15939 println!(
15940 "{} pulled {vfr_id} (transitive) → {}",
15941 style::ok("registry"),
15942 out.display()
15943 );
15944 println!(" verified {} frontier(s):", result.verified.len());
15945 for v in &result.verified {
15946 println!(" · {v}");
15947 }
15948 println!(" every cross-frontier dependency's pinned snapshot hash matched");
15949 }
15950 return;
15951 }
15952
15953 registry::fetch_frontier_to_prefer_event_hub(&entry, from.as_deref(), &out)
15956 .unwrap_or_else(|e| fail_return(&format!("fetch frontier: {e}")));
15957 registry::verify_pull(&entry, &out).unwrap_or_else(|e| {
15958 let _ = std::fs::remove_file(&out);
15959 fail_return(&format!("pull verification failed: {e}"))
15960 });
15961
15962 let payload = json!({
15963 "ok": true,
15964 "command": "registry.pull",
15965 "registry": registry_label,
15966 "vfr_id": vfr_id,
15967 "out": out.display().to_string(),
15968 "snapshot_hash": entry.latest_snapshot_hash,
15969 "event_log_hash": entry.latest_event_log_hash,
15970 "verified": true,
15971 });
15972 if json {
15973 println!(
15974 "{}",
15975 serde_json::to_string_pretty(&payload)
15976 .expect("failed to serialize registry.pull")
15977 );
15978 } else {
15979 println!(
15980 "{} pulled {vfr_id} → {}",
15981 style::ok("registry"),
15982 out.display()
15983 );
15984 println!(" verified snapshot+event_log hashes match registry; signature ok");
15985 }
15986 }
15987 }
15988}
15989
15990fn cmd_owner_rotate_governed(action: OwnerRotateGovernedAction) {
15992 use crate::governance::{
15993 AttestationEntry, GovernancePolicy, OwnerRotateAttestationBundle, OwnerRotateProposal,
15994 ProposalDraft, verify_quorum,
15995 };
15996 use crate::registry;
15997 use ed25519_dalek::Signer;
15998
15999 match action {
16000 OwnerRotateGovernedAction::Propose {
16001 frontier,
16002 old_owner,
16003 new_owner,
16004 new_pubkey_hex,
16005 target_epoch,
16006 previous_entry_hash,
16007 policy,
16008 reason,
16009 ttl_hours,
16010 out,
16011 json,
16012 } => {
16013 if target_epoch == 0 {
16014 fail("--target-epoch must be >= 1; the first governed rotation produces epoch 1.");
16015 }
16016 if new_pubkey_hex.len() != 64 || hex::decode(&new_pubkey_hex).is_err() {
16017 fail("--new-pubkey-hex must be 64 hex chars (32-byte Ed25519 pubkey).");
16018 }
16019 let frontier_data = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
16020 let frontier_id = frontier_data.frontier_id().to_string();
16021
16022 let policy_raw = std::fs::read_to_string(&policy)
16023 .unwrap_or_else(|e| fail_return(&format!("read policy: {e}")));
16024 let policy_obj: GovernancePolicy = serde_json::from_str(&policy_raw)
16025 .unwrap_or_else(|e| fail_return(&format!("parse policy: {e}")));
16026 policy_obj
16027 .verify_content_address()
16028 .unwrap_or_else(|e| fail_return(&e));
16029
16030 let old_actor = frontier_data
16031 .actors
16032 .iter()
16033 .find(|a| a.id == old_owner)
16034 .unwrap_or_else(|| {
16035 fail_return(&format!(
16036 "old owner `{old_owner}` is not registered in the frontier"
16037 ))
16038 });
16039 let old_pubkey = old_actor.public_key.clone();
16040
16041 let now = chrono::Utc::now();
16042 let expires = now + chrono::Duration::hours(i64::from(ttl_hours));
16043
16044 let draft = ProposalDraft {
16045 frontier_id,
16046 old_owner_actor_id: old_owner,
16047 old_owner_pubkey: old_pubkey,
16048 new_owner_actor_id: new_owner,
16049 new_owner_pubkey: new_pubkey_hex,
16050 owner_epoch: target_epoch,
16051 previous_registry_entry_hash: previous_entry_hash,
16052 governance_policy_id: policy_obj.policy_id.clone(),
16053 reason,
16054 created_at: now.to_rfc3339(),
16055 expires_at: expires.to_rfc3339(),
16056 nonce: hex::encode(rand::random::<[u8; 8]>()),
16057 };
16058 let proposal =
16059 OwnerRotateProposal::from_draft(draft).unwrap_or_else(|e| fail_return(&e));
16060
16061 let body =
16062 serde_json::to_string_pretty(&proposal).expect("serialize owner-rotate proposal");
16063 std::fs::write(&out, format!("{body}\n"))
16064 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
16065
16066 let preimage_hash = proposal.preimage_hash().unwrap_or_else(|e| fail_return(&e));
16067 if json {
16068 let payload = json!({
16069 "ok": true,
16070 "command": "registry.owner-rotate-governed.propose",
16071 "proposal_id": proposal.proposal_id,
16072 "frontier_id": proposal.frontier_id,
16073 "target_epoch": proposal.owner_epoch,
16074 "governance_policy_id": proposal.governance_policy_id,
16075 "proposal_preimage_hash": preimage_hash,
16076 "expires_at": proposal.expires_at,
16077 "out": out.display().to_string(),
16078 });
16079 println!(
16080 "{}",
16081 serde_json::to_string_pretty(&payload).expect("serialize propose summary")
16082 );
16083 } else {
16084 println!(
16085 "{} proposed owner rotation: {} (target epoch {})",
16086 style::ok("registry"),
16087 proposal.proposal_id,
16088 proposal.owner_epoch
16089 );
16090 println!(" preimage hash: {preimage_hash}");
16091 println!(" policy: {}", proposal.governance_policy_id);
16092 println!(" expires_at: {}", proposal.expires_at);
16093 println!(" out: {}", out.display());
16094 }
16095 }
16096 OwnerRotateGovernedAction::Attest {
16097 proposal,
16098 attester_id,
16099 key,
16100 bundle,
16101 json,
16102 } => {
16103 let proposal_raw = std::fs::read_to_string(&proposal)
16104 .unwrap_or_else(|e| fail_return(&format!("read proposal: {e}")));
16105 let proposal_obj: OwnerRotateProposal = serde_json::from_str(&proposal_raw)
16106 .unwrap_or_else(|e| fail_return(&format!("parse proposal: {e}")));
16107 let derived = proposal_obj.derive_id().unwrap_or_else(|e| fail_return(&e));
16109 if derived != proposal_obj.proposal_id {
16110 fail(&format!(
16111 "proposal id mismatch: stored `{}`, derived `{}`",
16112 proposal_obj.proposal_id, derived
16113 ));
16114 }
16115
16116 let key_hex = std::fs::read_to_string(&key)
16117 .map(|s| s.trim().to_string())
16118 .unwrap_or_else(|e| fail_return(&format!("read key: {e}")));
16119 let sk = parse_signing_key(&key_hex);
16120 let pubkey_hex = hex::encode(sk.verifying_key().to_bytes());
16121
16122 let preimage = proposal_obj
16123 .preimage_bytes()
16124 .unwrap_or_else(|e| fail_return(&e));
16125 let sig = sk.sign(&preimage);
16126
16127 let entry = AttestationEntry {
16128 attester_id: attester_id.clone(),
16129 attester_pubkey: pubkey_hex.clone(),
16130 judgment: "approve_owner_rotate".to_string(),
16131 signature: hex::encode(sig.to_bytes()),
16132 signed_at: chrono::Utc::now().to_rfc3339(),
16133 };
16134
16135 let existing: Option<OwnerRotateAttestationBundle> = if bundle.exists() {
16137 let raw = std::fs::read_to_string(&bundle)
16138 .unwrap_or_else(|e| fail_return(&format!("read bundle: {e}")));
16139 Some(
16140 serde_json::from_str(&raw)
16141 .unwrap_or_else(|e| fail_return(&format!("parse bundle: {e}"))),
16142 )
16143 } else {
16144 None
16145 };
16146
16147 let mut attestations: Vec<AttestationEntry> = existing
16148 .as_ref()
16149 .map(|b| b.attestations.clone())
16150 .unwrap_or_default();
16151 attestations.retain(|a| a.attester_id != attester_id);
16154 attestations.push(entry);
16155
16156 let new_bundle = OwnerRotateAttestationBundle::new(&proposal_obj, attestations)
16157 .unwrap_or_else(|e| fail_return(&e));
16158
16159 let body =
16160 serde_json::to_string_pretty(&new_bundle).expect("serialize attestation bundle");
16161 std::fs::write(&bundle, format!("{body}\n"))
16162 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", bundle.display())));
16163
16164 if json {
16165 let payload = json!({
16166 "ok": true,
16167 "command": "registry.owner-rotate-governed.attest",
16168 "bundle_id": new_bundle.bundle_id,
16169 "proposal_id": new_bundle.proposal_id,
16170 "attester_id": attester_id,
16171 "attester_pubkey": pubkey_hex,
16172 "attestation_count": new_bundle.attestations.len(),
16173 "bundle": bundle.display().to_string(),
16174 });
16175 println!(
16176 "{}",
16177 serde_json::to_string_pretty(&payload).expect("serialize attest summary")
16178 );
16179 } else {
16180 println!(
16181 "{} attested {} ({} attestation(s) total)",
16182 style::ok("attest"),
16183 new_bundle.bundle_id,
16184 new_bundle.attestations.len()
16185 );
16186 println!(" attester: {attester_id}");
16187 println!(" pubkey: {}...", &pubkey_hex[..16]);
16188 println!(" bundle: {}", bundle.display());
16189 }
16190 }
16191 OwnerRotateGovernedAction::Apply {
16192 frontier,
16193 proposal,
16194 bundle,
16195 policy,
16196 new_key,
16197 locator,
16198 to,
16199 json,
16200 } => {
16201 let proposal_obj: OwnerRotateProposal = serde_json::from_str(
16203 &std::fs::read_to_string(&proposal)
16204 .unwrap_or_else(|e| fail_return(&format!("read proposal: {e}"))),
16205 )
16206 .unwrap_or_else(|e| fail_return(&format!("parse proposal: {e}")));
16207 let bundle_obj: OwnerRotateAttestationBundle = serde_json::from_str(
16208 &std::fs::read_to_string(&bundle)
16209 .unwrap_or_else(|e| fail_return(&format!("read bundle: {e}"))),
16210 )
16211 .unwrap_or_else(|e| fail_return(&format!("parse bundle: {e}")));
16212 let policy_obj: GovernancePolicy = serde_json::from_str(
16213 &std::fs::read_to_string(&policy)
16214 .unwrap_or_else(|e| fail_return(&format!("read policy: {e}"))),
16215 )
16216 .unwrap_or_else(|e| fail_return(&format!("parse policy: {e}")));
16217 policy_obj
16218 .verify_content_address()
16219 .unwrap_or_else(|e| fail_return(&e));
16220
16221 let mut frontier_data =
16223 repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
16224 let revocation = FrontierRevocation {
16225 map: frontier_data
16226 .actors
16227 .iter()
16228 .filter_map(|a| a.revoked_at.as_ref().map(|r| (a.id.clone(), r.clone())))
16229 .collect(),
16230 };
16231
16232 let now = chrono::Utc::now().to_rfc3339();
16233 let report = verify_quorum(&proposal_obj, &bundle_obj, &policy_obj, &revocation, &now)
16234 .unwrap_or_else(|e| fail_return(&format!("quorum verification failed: {e}")));
16235
16236 let key_hex = std::fs::read_to_string(&new_key)
16240 .map(|s| s.trim().to_string())
16241 .unwrap_or_else(|e| fail_return(&format!("read new key: {e}")));
16242 let sk = parse_signing_key(&key_hex);
16243 let derived_pubkey = hex::encode(sk.verifying_key().to_bytes());
16244 if derived_pubkey != proposal_obj.new_owner_pubkey {
16245 fail(&format!(
16246 "--new-key derives to pubkey `{}`, but proposal declares new_owner_pubkey `{}`",
16247 derived_pubkey, proposal_obj.new_owner_pubkey
16248 ));
16249 }
16250
16251 let mut retired_pubkey_prefix: Option<String> = None;
16255 for actor in frontier_data.actors.iter_mut() {
16256 if actor.id == proposal_obj.old_owner_actor_id {
16257 if actor.revoked_at.is_some() {
16258 fail(&format!(
16259 "refusing to apply: old owner `{}` is already revoked at {}",
16260 actor.id,
16261 actor.revoked_at.as_deref().unwrap_or("?")
16262 ));
16263 }
16264 actor.revoked_at = Some(now.clone());
16265 actor.revoked_reason = Some(proposal_obj.reason.clone());
16266 retired_pubkey_prefix = Some(actor.public_key[..16].to_string());
16267 }
16268 }
16269
16270 if !frontier_data
16271 .actors
16272 .iter()
16273 .any(|a| a.id == proposal_obj.new_owner_actor_id)
16274 {
16275 frontier_data.actors.push(sign::ActorRecord {
16276 id: proposal_obj.new_owner_actor_id.clone(),
16277 public_key: proposal_obj.new_owner_pubkey.clone(),
16278 algorithm: "ed25519".to_string(),
16279 created_at: now.clone(),
16280 tier: None,
16281 orcid: None,
16282 access_clearance: None,
16283 revoked_at: None,
16284 revoked_reason: None,
16285 });
16286 }
16287
16288 repo::save_to_path(&frontier, &frontier_data)
16289 .unwrap_or_else(|e| fail_return(&format!("save rotation: {e}")));
16290
16291 let snapshot_hash = events::snapshot_hash(&frontier_data);
16295 let event_log_hash = events::event_log_hash(&frontier_data.events);
16296 let vfr_id = frontier_data.frontier_id();
16297 let name = frontier_data.project.name.clone();
16298
16299 let to_is_remote = matches!(
16300 to.as_deref(),
16301 Some(loc) if loc.starts_with("http://") || loc.starts_with("https://")
16302 );
16303 let resolved_locator = match locator {
16304 Some(l) => l,
16305 None => {
16306 if to_is_remote {
16307 let hub = to.as_deref().unwrap().trim_end_matches('/');
16308 let hub_root = hub.trim_end_matches("/entries");
16309 format!("{hub_root}/entries/{vfr_id}/snapshot")
16310 } else {
16311 fail_return(
16312 "--locator is required for local publishes; pass e.g. \
16313 --locator file:///path/to/frontier.json or an HTTPS URL.",
16314 )
16315 }
16316 }
16317 };
16318
16319 let mut entry = registry::RegistryEntry {
16320 schema: registry::ENTRY_SCHEMA.to_string(),
16321 vfr_id: vfr_id.clone(),
16322 name: name.clone(),
16323 owner_actor_id: proposal_obj.new_owner_actor_id.clone(),
16324 owner_pubkey: proposal_obj.new_owner_pubkey.clone(),
16325 latest_snapshot_hash: snapshot_hash,
16326 latest_event_log_hash: event_log_hash,
16327 network_locator: resolved_locator,
16328 license: None,
16329 signed_publish_at: chrono::Utc::now().to_rfc3339(),
16330 signature: String::new(),
16331 };
16332 entry.signature = registry::sign_entry(&entry, &sk).unwrap_or_else(|e| fail_return(&e));
16333
16334 let (registry_label, duplicate) = if to_is_remote {
16335 let hub_url = to.clone().unwrap();
16336 let resp = registry::publish_remote(&entry, &hub_url, Some(&frontier_data))
16337 .unwrap_or_else(|e| fail_return(&e));
16338 (hub_url, resp.duplicate)
16339 } else {
16340 let registry_path = match &to {
16341 Some(loc) => registry::resolve_local(loc).unwrap_or_else(|e| fail_return(&e)),
16342 None => default_registry_path(),
16343 };
16344 registry::publish_entry(®istry_path, entry.clone())
16345 .unwrap_or_else(|e| fail_return(&e));
16346 (registry_path.display().to_string(), false)
16347 };
16348
16349 let chain_path = governance_chain_path(&frontier);
16355 let mut chain = if chain_path.exists() {
16356 let raw = std::fs::read_to_string(&chain_path).unwrap_or_else(|e| {
16357 fail_return(&format!("read chain {}: {e}", chain_path.display()))
16358 });
16359 serde_json::from_str::<crate::governance::OwnerEpochChain>(&raw)
16360 .unwrap_or_else(|e| fail_return(&format!("parse chain: {e}")))
16361 } else {
16362 crate::governance::OwnerEpochChain::new(vfr_id.clone())
16363 };
16364 let transition = crate::governance::ChainTransition {
16365 owner_epoch: proposal_obj.owner_epoch,
16366 policy_id: policy_obj.policy_id.clone(),
16367 proposal_id: proposal_obj.proposal_id.clone(),
16368 bundle_id: bundle_obj.bundle_id.clone(),
16369 previous_entry_hash: proposal_obj.previous_registry_entry_hash.clone(),
16370 new_owner_actor_id: proposal_obj.new_owner_actor_id.clone(),
16371 new_owner_pubkey: proposal_obj.new_owner_pubkey.clone(),
16372 signed_at: now.clone(),
16373 };
16374 chain
16375 .append(transition)
16376 .unwrap_or_else(|e| fail_return(&format!("append chain: {e}")));
16377 if let Some(parent) = chain_path.parent() {
16378 std::fs::create_dir_all(parent).unwrap_or_else(|e| {
16379 fail_return(&format!("create chain dir {}: {e}", parent.display()))
16380 });
16381 }
16382 let chain_json =
16383 serde_json::to_string_pretty(&chain).expect("serialize owner-epoch chain");
16384 std::fs::write(&chain_path, format!("{chain_json}\n")).unwrap_or_else(|e| {
16385 fail_return(&format!("write chain {}: {e}", chain_path.display()))
16386 });
16387
16388 let payload = json!({
16389 "ok": true,
16390 "command": "registry.owner-rotate-governed.apply",
16391 "proposal_id": proposal_obj.proposal_id,
16392 "bundle_id": bundle_obj.bundle_id,
16393 "policy_id": policy_obj.policy_id,
16394 "quorum_report": report,
16395 "vfr_id": vfr_id,
16396 "name": name,
16397 "retired_owner": proposal_obj.old_owner_actor_id,
16398 "retired_pubkey_prefix": retired_pubkey_prefix,
16399 "new_owner": proposal_obj.new_owner_actor_id,
16400 "new_pubkey": derived_pubkey,
16401 "registry": registry_label,
16402 "signature": entry.signature,
16403 "duplicate": duplicate,
16404 "chain_file": chain_path.display().to_string(),
16405 "chain_length": chain.transitions.len(),
16406 });
16407 if json {
16408 println!(
16409 "{}",
16410 serde_json::to_string_pretty(&payload).expect("serialize apply summary")
16411 );
16412 } else {
16413 println!(
16414 "{} governed rotation applied: {} -> {} (epoch {})",
16415 style::ok("registry"),
16416 proposal_obj.old_owner_actor_id,
16417 proposal_obj.new_owner_actor_id,
16418 proposal_obj.owner_epoch
16419 );
16420 println!(
16421 " approving signers: {}",
16422 report.approving_signers.join(", ")
16423 );
16424 println!(" threshold: {}", report.threshold);
16425 println!(" bundle: {}", bundle_obj.bundle_id);
16426 println!(" registry: {}", registry_label);
16427 println!(" signature: {}…", &entry.signature[..16]);
16428 }
16429 }
16430 }
16431}
16432
16433#[allow(clippy::too_many_arguments)]
16435fn cmd_proof_attest_verification(
16436 proof_id: String,
16437 tool: String,
16438 tool_version: String,
16439 script_locator: String,
16440 lake_manifest_hash: Option<String>,
16441 verifier_output_hash: String,
16442 status: String,
16443 verifier_actor: String,
16444 key: PathBuf,
16445 out: PathBuf,
16446 json: bool,
16447) {
16448 use crate::proof_verification::{ProofVerification, VerificationDraft};
16449
16450 let key_hex = std::fs::read_to_string(&key)
16451 .map(|s| s.trim().to_string())
16452 .unwrap_or_else(|e| fail_return(&format!("read key: {e}")));
16453 let sk = parse_signing_key(&key_hex);
16454
16455 let draft = VerificationDraft {
16456 proof_id,
16457 tool,
16458 tool_version,
16459 script_locator,
16460 lake_manifest_hash,
16461 verifier_output_hash,
16462 status,
16463 verified_at: chrono::Utc::now().to_rfc3339(),
16464 verifier_actor,
16465 };
16466 let record = ProofVerification::build(draft, &sk).unwrap_or_else(|e| fail_return(&e));
16467
16468 let body = serde_json::to_string_pretty(&record).expect("serialize proof verification record");
16469 std::fs::write(&out, format!("{body}\n"))
16470 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
16471
16472 if json {
16473 let payload = json!({
16474 "ok": true,
16475 "command": "proof-attest-verification",
16476 "verification_id": record.verification_id,
16477 "proof_id": record.proof_id,
16478 "tool": record.tool,
16479 "tool_version": record.tool_version,
16480 "status": record.status,
16481 "verifier_actor": record.verifier_actor,
16482 "out": out.display().to_string(),
16483 });
16484 println!(
16485 "{}",
16486 serde_json::to_string_pretty(&payload).expect("serialize summary")
16487 );
16488 } else {
16489 println!(
16490 "{} attested {} verifying {} ({} {})",
16491 style::ok("proof"),
16492 record.verification_id,
16493 record.proof_id,
16494 record.tool,
16495 record.tool_version
16496 );
16497 println!(" status: {}", record.status);
16498 println!(" verifier_actor: {}", record.verifier_actor);
16499 println!(" verifier_output_hash: {}", record.verifier_output_hash);
16500 println!(" out: {}", out.display());
16501 }
16502}
16503
16504fn cmd_proof_verify_attestation(record: PathBuf, json: bool) {
16506 use crate::proof_verification::ProofVerification;
16507
16508 let raw = std::fs::read_to_string(&record)
16509 .unwrap_or_else(|e| fail_return(&format!("read record: {e}")));
16510 let parsed: ProofVerification =
16511 serde_json::from_str(&raw).unwrap_or_else(|e| fail_return(&format!("parse record: {e}")));
16512
16513 if let Err(e) = parsed.verify() {
16514 if json {
16515 let payload = json!({
16516 "ok": false,
16517 "command": "proof-verify-attestation",
16518 "verification_id": parsed.verification_id,
16519 "error": e,
16520 });
16521 println!(
16522 "{}",
16523 serde_json::to_string_pretty(&payload).expect("serialize verify failure")
16524 );
16525 } else {
16526 eprintln!("err · {e}");
16527 }
16528 std::process::exit(1);
16529 }
16530
16531 if json {
16532 let payload = json!({
16533 "ok": true,
16534 "command": "proof-verify-attestation",
16535 "verification_id": parsed.verification_id,
16536 "proof_id": parsed.proof_id,
16537 "tool": parsed.tool,
16538 "tool_version": parsed.tool_version,
16539 "status": parsed.status,
16540 "verifier_actor": parsed.verifier_actor,
16541 "verifier_pubkey": parsed.verifier_pubkey,
16542 });
16543 println!(
16544 "{}",
16545 serde_json::to_string_pretty(&payload).expect("serialize verify success")
16546 );
16547 } else {
16548 println!(
16549 "{} verification {} ok ({} {} verified {})",
16550 style::ok("verify"),
16551 parsed.verification_id,
16552 parsed.tool,
16553 parsed.tool_version,
16554 parsed.proof_id
16555 );
16556 }
16557}
16558
16559fn cmd_credit(frontier: PathBuf, out: Option<PathBuf>, json: bool) {
16561 use crate::credit::build_ledger;
16562
16563 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
16564 let now = chrono::Utc::now().to_rfc3339();
16565 let ledger = build_ledger(&project, &now);
16566 let body = serde_json::to_string_pretty(&ledger).expect("serialize credit ledger");
16567
16568 if let Some(out_path) = out {
16569 std::fs::write(&out_path, format!("{body}\n"))
16570 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out_path.display())));
16571 if json {
16572 let payload = json!({
16573 "ok": true,
16574 "command": "credit",
16575 "frontier_id": ledger.frontier_id,
16576 "contributor_count": ledger.contributor_count,
16577 "out": out_path.display().to_string(),
16578 });
16579 println!(
16580 "{}",
16581 serde_json::to_string_pretty(&payload).expect("serialize credit summary")
16582 );
16583 } else {
16584 println!(
16585 "{} credit ledger for {}: {} contributor(s) -> {}",
16586 style::ok("credit"),
16587 ledger.frontier_id,
16588 ledger.contributor_count,
16589 out_path.display()
16590 );
16591 }
16592 } else if json {
16593 println!("{body}");
16594 } else {
16595 println!(
16596 " vela credit · {} · {} contributor(s)",
16597 ledger.frontier_id, ledger.contributor_count
16598 );
16599 println!();
16600 for c in &ledger.contributors {
16601 print!(" {}", c.actor_id);
16602 if let Some(orcid) = &c.orcid {
16603 print!(" (ORCID {orcid})");
16604 }
16605 println!(" · {} event(s)", c.event_count);
16606 for role in &c.roles {
16607 let count = c.role_counts.get(role).copied().unwrap_or(0);
16608 println!(" · {role} ({count})");
16609 }
16610 }
16611 }
16612}
16613
16614fn cmd_review_thread(action: ReviewThreadCli) {
16618 use crate::review_thread::{MessageDraft, ReviewMessage, ReviewThread, ThreadTargetKind};
16619
16620 match action {
16621 ReviewThreadCli::Create {
16622 target,
16623 frontier_id,
16624 out,
16625 json,
16626 } => {
16627 let kind: ThreadTargetKind = if target.starts_with("vpr_") {
16628 ThreadTargetKind::Proposal
16629 } else if target.starts_with("vf_") {
16630 ThreadTargetKind::Finding
16631 } else if target.starts_with("vsd_") {
16632 ThreadTargetKind::DiffPack
16633 } else {
16634 fail_return(&format!(
16635 "target must start with `vpr_`, `vf_`, or `vsd_`, got `{target}`"
16636 ))
16637 };
16638 let thread = ReviewThread::new(
16639 kind,
16640 target.clone(),
16641 frontier_id.clone(),
16642 chrono::Utc::now().to_rfc3339(),
16643 )
16644 .unwrap_or_else(|e| fail_return(&e));
16645 let body = serde_json::to_string_pretty(&thread).expect("serialize thread");
16646 std::fs::write(&out, format!("{body}\n"))
16647 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
16648 if json {
16649 let payload = json!({
16650 "ok": true,
16651 "command": "review-thread.create",
16652 "thread_id": thread.thread_id,
16653 "target": target,
16654 "frontier_id": frontier_id,
16655 "out": out.display().to_string(),
16656 });
16657 println!(
16658 "{}",
16659 serde_json::to_string_pretty(&payload).expect("serialize")
16660 );
16661 } else {
16662 println!(
16663 "{} {} on {} -> {}",
16664 style::ok("review-thread.create"),
16665 thread.thread_id,
16666 target,
16667 out.display()
16668 );
16669 }
16670 }
16671 ReviewThreadCli::Post {
16672 thread,
16673 author_actor_id,
16674 key,
16675 message,
16676 parent,
16677 json,
16678 } => {
16679 let body = std::fs::read_to_string(&thread)
16680 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", thread.display())));
16681 let mut t: ReviewThread = serde_json::from_str(&body)
16682 .unwrap_or_else(|e| fail_return(&format!("parse thread: {e}")));
16683 let key_hex = std::fs::read_to_string(&key)
16684 .unwrap_or_else(|e| fail_return(&format!("read key {}: {e}", key.display())));
16685 let key_bytes = hex::decode(key_hex.trim())
16686 .unwrap_or_else(|e| fail_return(&format!("decode key hex: {e}")));
16687 let key_arr: [u8; 32] = key_bytes
16688 .try_into()
16689 .unwrap_or_else(|_| fail_return("signing key must be 32 bytes"));
16690 let signing_key = ed25519_dalek::SigningKey::from_bytes(&key_arr);
16691 let msg = ReviewMessage::build(
16692 MessageDraft {
16693 thread_id: t.thread_id.clone(),
16694 author_actor_id,
16695 body: message,
16696 parent_message_id: parent,
16697 posted_at: chrono::Utc::now().to_rfc3339(),
16698 },
16699 &signing_key,
16700 )
16701 .unwrap_or_else(|e| fail_return(&e));
16702 let message_id = msg.message_id.clone();
16703 t.append_message(msg)
16704 .unwrap_or_else(|e| fail_return(&format!("append: {e}")));
16705 let serialized = serde_json::to_string_pretty(&t).expect("serialize thread");
16706 std::fs::write(&thread, format!("{serialized}\n"))
16707 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", thread.display())));
16708 if json {
16709 let payload = json!({
16710 "ok": true,
16711 "command": "review-thread.post",
16712 "thread_id": t.thread_id,
16713 "message_id": message_id,
16714 "message_count": t.messages.len(),
16715 });
16716 println!(
16717 "{}",
16718 serde_json::to_string_pretty(&payload).expect("serialize")
16719 );
16720 } else {
16721 println!(
16722 "{} {} -> thread {} ({} message(s))",
16723 style::ok("review-thread.post"),
16724 message_id,
16725 t.thread_id,
16726 t.messages.len()
16727 );
16728 }
16729 }
16730 ReviewThreadCli::Verify { thread, json } => {
16731 let body = std::fs::read_to_string(&thread)
16732 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", thread.display())));
16733 let t: ReviewThread = serde_json::from_str(&body)
16734 .unwrap_or_else(|e| fail_return(&format!("parse thread: {e}")));
16735 let mut errors = Vec::new();
16736 for (i, m) in t.messages.iter().enumerate() {
16737 if let Err(e) = m.verify() {
16738 errors.push(format!("message {i} ({}): {e}", m.message_id));
16739 }
16740 }
16741 if !errors.is_empty() {
16742 fail(&format!(
16743 "review-thread.verify failed: {} error(s)\n {}",
16744 errors.len(),
16745 errors.join("\n ")
16746 ));
16747 }
16748 if json {
16749 let payload = json!({
16750 "ok": true,
16751 "command": "review-thread.verify",
16752 "thread_id": t.thread_id,
16753 "message_count": t.messages.len(),
16754 });
16755 println!(
16756 "{}",
16757 serde_json::to_string_pretty(&payload).expect("serialize")
16758 );
16759 } else {
16760 println!(
16761 "{} {} ({} message(s)) verifies",
16762 style::ok("review-thread.verify"),
16763 t.thread_id,
16764 t.messages.len()
16765 );
16766 }
16767 }
16768 }
16769}
16770
16771fn cmd_hub_spec(action: HubSpecCli) {
16774 use crate::hub_spec::{HubSpec, HubSpecDraft};
16775
16776 match action {
16777 HubSpecCli::Declare {
16778 hub_id,
16779 display_name,
16780 base_url,
16781 operator_pubkey_hex,
16782 substrate_version,
16783 contact,
16784 latest_checkpoint,
16785 out,
16786 json,
16787 } => {
16788 let spec = HubSpec::from_draft(HubSpecDraft {
16789 hub_id,
16790 display_name,
16791 base_url,
16792 operator_pubkey_hex,
16793 substrate_version,
16794 contact,
16795 latest_checkpoint,
16796 declared_at: chrono::Utc::now().to_rfc3339(),
16797 })
16798 .unwrap_or_else(|e| fail_return(&e));
16799 let body = serde_json::to_string_pretty(&spec).expect("serialize hub spec");
16800 if let Some(path) = out {
16801 std::fs::write(&path, format!("{body}\n"))
16802 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", path.display())));
16803 if json {
16804 let payload = json!({
16805 "ok": true,
16806 "command": "hub.declare",
16807 "spec_id": spec.spec_id,
16808 "hub_id": spec.hub_id,
16809 "base_url": spec.base_url,
16810 "out": path.display().to_string(),
16811 });
16812 println!(
16813 "{}",
16814 serde_json::to_string_pretty(&payload).expect("serialize summary")
16815 );
16816 } else {
16817 println!(
16818 "{} {} ({}) -> {}",
16819 style::ok("hub.declare"),
16820 spec.spec_id,
16821 spec.hub_id,
16822 path.display()
16823 );
16824 }
16825 } else {
16826 println!("{body}");
16827 }
16828 }
16829 HubSpecCli::Validate { spec, json } => {
16830 let body = std::fs::read_to_string(&spec)
16831 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", spec.display())));
16832 let parsed: HubSpec = serde_json::from_str(&body)
16833 .unwrap_or_else(|e| fail_return(&format!("parse hub spec: {e}")));
16834 let rebuilt = HubSpec::from_draft(crate::hub_spec::HubSpecDraft {
16836 hub_id: parsed.hub_id.clone(),
16837 display_name: parsed.display_name.clone(),
16838 base_url: parsed.base_url.clone(),
16839 operator_pubkey_hex: parsed.operator_pubkey_hex.clone(),
16840 substrate_version: parsed.substrate_version.clone(),
16841 contact: parsed.contact.clone(),
16842 latest_checkpoint: parsed.latest_checkpoint.clone(),
16843 declared_at: parsed.declared_at.clone(),
16844 })
16845 .unwrap_or_else(|e| fail_return(&format!("rebuild for validation: {e}")));
16846 if rebuilt.spec_id != parsed.spec_id {
16847 fail(&format!(
16848 "spec_id mismatch: declared {}, rebuilt {}",
16849 parsed.spec_id, rebuilt.spec_id
16850 ));
16851 }
16852 if json {
16853 let payload = json!({
16854 "ok": true,
16855 "command": "hub.validate",
16856 "spec_id": parsed.spec_id,
16857 "hub_id": parsed.hub_id,
16858 });
16859 println!(
16860 "{}",
16861 serde_json::to_string_pretty(&payload).expect("serialize")
16862 );
16863 } else {
16864 println!(
16865 "{} {} ({}) validates",
16866 style::ok("hub.validate"),
16867 parsed.spec_id,
16868 parsed.hub_id
16869 );
16870 }
16871 }
16872 }
16873}
16874
16875fn cmd_lean(action: LeanAction) {
16878 use crate::lean_anchors::{LeanAnchor, THEOREMS, lean_dir_default};
16879
16880 match action {
16881 LeanAction::List { json } => {
16882 if json {
16883 println!(
16884 "{}",
16885 serde_json::to_string_pretty(
16886 &THEOREMS
16887 .iter()
16888 .map(|d| serde_json::json!({
16889 "id": d.id,
16890 "title": d.title,
16891 "module": d.module,
16892 "decl": d.decl,
16893 }))
16894 .collect::<Vec<_>>()
16895 )
16896 .expect("serialize theorem list")
16897 );
16898 } else {
16899 println!(" registered theorems ({}):", THEOREMS.len());
16900 for d in THEOREMS {
16901 println!(" T{:<2} {} ({}::{})", d.id, d.title, d.module, d.decl);
16902 }
16903 }
16904 }
16905 LeanAction::Anchor {
16906 id,
16907 lean_dir,
16908 out,
16909 json,
16910 } => {
16911 let lean = lean_dir.unwrap_or_else(lean_dir_default);
16912 let descriptor = THEOREMS
16913 .iter()
16914 .find(|d| d.id == id)
16915 .unwrap_or_else(|| fail_return(&format!("unknown theorem id: T{id}")));
16916 let anchor =
16917 LeanAnchor::anchor_for(descriptor, &lean).unwrap_or_else(|e| fail_return(&e));
16918 let body = serde_json::to_string_pretty(&anchor).expect("serialize anchor");
16919 if let Some(path) = out {
16920 std::fs::write(&path, format!("{body}\n"))
16921 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", path.display())));
16922 if json {
16923 let payload = json!({
16924 "ok": true,
16925 "command": "lean.anchor",
16926 "theorem_id": id,
16927 "anchor_id": anchor.anchor_id,
16928 "module_sha256": anchor.module_sha256,
16929 "structurally_present": anchor.structurally_present,
16930 "out": path.display().to_string(),
16931 });
16932 println!(
16933 "{}",
16934 serde_json::to_string_pretty(&payload).expect("serialize summary")
16935 );
16936 } else {
16937 println!(
16938 "{} T{} -> {} ({})",
16939 style::ok("lean.anchor"),
16940 id,
16941 anchor.anchor_id,
16942 path.display()
16943 );
16944 }
16945 } else {
16946 println!("{body}");
16947 }
16948 }
16949 LeanAction::AnchorAll {
16950 lean_dir,
16951 out,
16952 json,
16953 } => {
16954 let lean = lean_dir.unwrap_or_else(lean_dir_default);
16955 if let Err(e) = std::fs::create_dir_all(&out) {
16956 fail(&format!("create {}: {e}", out.display()));
16957 }
16958 let mut summary = Vec::new();
16959 for d in THEOREMS {
16960 let anchor = LeanAnchor::anchor_for(d, &lean).unwrap_or_else(|e| fail_return(&e));
16961 let body = serde_json::to_string_pretty(&anchor).expect("serialize anchor");
16962 let path = out.join(format!("T{}.anchor.json", d.id));
16963 std::fs::write(&path, format!("{body}\n"))
16964 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", path.display())));
16965 summary.push(serde_json::json!({
16966 "theorem_id": d.id,
16967 "anchor_id": anchor.anchor_id,
16968 "module_sha256": anchor.module_sha256,
16969 "structurally_present": anchor.structurally_present,
16970 "path": path.display().to_string(),
16971 }));
16972 }
16973 if json {
16974 let payload = json!({
16975 "ok": true,
16976 "command": "lean.anchor-all",
16977 "anchored": summary.len(),
16978 "anchors": summary,
16979 });
16980 println!(
16981 "{}",
16982 serde_json::to_string_pretty(&payload).expect("serialize anchor-all")
16983 );
16984 } else {
16985 println!(
16986 "{} anchored {} theorem(s) to {}",
16987 style::ok("lean.anchor-all"),
16988 summary.len(),
16989 out.display()
16990 );
16991 }
16992 }
16993 LeanAction::Keygen {
16994 key_out,
16995 pub_out,
16996 actor,
16997 } => {
16998 use rand::rngs::OsRng;
16999 let signing = ed25519_dalek::SigningKey::generate(&mut OsRng);
17000 let priv_hex = hex::encode(signing.to_bytes());
17001 let pub_hex = hex::encode(signing.verifying_key().to_bytes());
17002 std::fs::write(&key_out, format!("{priv_hex}\n"))
17003 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", key_out.display())));
17004 let pub_record = json!({
17005 "schema": "vela.lean_verifier_pubkey.v0.1",
17006 "actor": actor,
17007 "pubkey_hex": pub_hex,
17008 "created_at": chrono::Utc::now().to_rfc3339(),
17009 });
17010 let body =
17011 serde_json::to_string_pretty(&pub_record).expect("serialize verifier pubkey");
17012 std::fs::write(&pub_out, format!("{body}\n"))
17013 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", pub_out.display())));
17014 println!(
17015 "{} verifier keypair generated; private key -> {}, public spec -> {}",
17016 style::ok("lean.keygen"),
17017 key_out.display(),
17018 pub_out.display()
17019 );
17020 }
17021 LeanAction::VerifyAll {
17022 anchors_dir,
17023 out_dir,
17024 build_log,
17025 key,
17026 actor,
17027 lean_toolchain,
17028 mathlib_revision,
17029 json,
17030 } => {
17031 use crate::lean_verification::{LeanVerification, VerificationDraft};
17032
17033 let key_hex = std::fs::read_to_string(&key)
17034 .unwrap_or_else(|e| fail_return(&format!("read key {}: {e}", key.display())));
17035 let key_bytes = hex::decode(key_hex.trim())
17036 .unwrap_or_else(|e| fail_return(&format!("decode key hex: {e}")));
17037 let key_arr: [u8; 32] = key_bytes
17038 .try_into()
17039 .unwrap_or_else(|_| fail_return("signing key must be 32 bytes"));
17040 let signing = ed25519_dalek::SigningKey::from_bytes(&key_arr);
17041
17042 let log_bytes = std::fs::read(&build_log).unwrap_or_else(|e| {
17043 fail_return(&format!("read build log {}: {e}", build_log.display()))
17044 });
17045 let mut hasher = sha2::Sha256::new();
17046 sha2::Digest::update(&mut hasher, &log_bytes);
17047 let verifier_output_hash = hex::encode(hasher.finalize());
17048
17049 let toolchain = lean_toolchain.unwrap_or_else(|| {
17050 std::fs::read_to_string("lean/lean-toolchain")
17051 .map(|s| s.trim().to_string())
17052 .unwrap_or_else(|_| "unknown".to_string())
17053 });
17054 let mathlib = mathlib_revision.unwrap_or_else(|| {
17055 std::fs::read_to_string("lean/lakefile.lean")
17056 .ok()
17057 .and_then(|t| {
17058 let needle = "mathlib4.git\" @ \"";
17059 let i = t.find(needle)?;
17060 let rest = &t[i + needle.len()..];
17061 let j = rest.find('"')?;
17062 Some(rest[..j].to_string())
17063 })
17064 .unwrap_or_else(|| "unknown".to_string())
17065 });
17066
17067 let out = out_dir.unwrap_or_else(|| anchors_dir.clone());
17068 if let Err(e) = std::fs::create_dir_all(&out) {
17069 fail(&format!("create {}: {e}", out.display()));
17070 }
17071
17072 let now = chrono::Utc::now().to_rfc3339();
17073 let mut summary = Vec::new();
17074 let entries: Vec<_> = std::fs::read_dir(&anchors_dir)
17075 .unwrap_or_else(|e| {
17076 fail_return(&format!("read anchors {}: {e}", anchors_dir.display()))
17077 })
17078 .filter_map(|r| r.ok())
17079 .collect();
17080 let mut anchor_paths: Vec<PathBuf> = entries
17081 .into_iter()
17082 .map(|e| e.path())
17083 .filter(|p| {
17084 p.file_name()
17085 .and_then(|s| s.to_str())
17086 .map(|s| s.starts_with('T') && s.ends_with(".anchor.json"))
17087 .unwrap_or(false)
17088 })
17089 .collect();
17090 anchor_paths.sort();
17091
17092 for path in anchor_paths {
17093 let body = std::fs::read_to_string(&path)
17094 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", path.display())));
17095 let anchor: crate::lean_anchors::LeanAnchor = serde_json::from_str(&body)
17096 .unwrap_or_else(|e| fail_return(&format!("parse {}: {e}", path.display())));
17097
17098 let record = LeanVerification::build(
17099 VerificationDraft {
17100 anchor_id: anchor.anchor_id.clone(),
17101 theorem_id: anchor.theorem_id,
17102 module: anchor.module.clone(),
17103 module_sha256: anchor.module_sha256.clone(),
17104 lean_toolchain: toolchain.clone(),
17105 mathlib_revision: mathlib.clone(),
17106 verifier_output_hash: verifier_output_hash.clone(),
17107 status: "verified".to_string(),
17108 verified_at: now.clone(),
17109 verifier_actor: actor.clone(),
17110 },
17111 &signing,
17112 )
17113 .unwrap_or_else(|e| fail_return(&e));
17114 let record_path = out.join(format!("T{}.vlv.json", anchor.theorem_id));
17115 let serialized =
17116 serde_json::to_string_pretty(&record).expect("serialize verification");
17117 std::fs::write(&record_path, format!("{serialized}\n")).unwrap_or_else(|e| {
17118 fail_return(&format!("write {}: {e}", record_path.display()))
17119 });
17120 summary.push(json!({
17121 "theorem_id": anchor.theorem_id,
17122 "anchor_id": anchor.anchor_id,
17123 "verification_id": record.verification_id,
17124 "out": record_path.display().to_string(),
17125 }));
17126 }
17127 if json {
17128 let payload = json!({
17129 "ok": true,
17130 "command": "lean.verify-all",
17131 "verified": summary.len(),
17132 "verifier_output_hash": verifier_output_hash,
17133 "lean_toolchain": toolchain,
17134 "mathlib_revision": mathlib,
17135 "records": summary,
17136 });
17137 println!(
17138 "{}",
17139 serde_json::to_string_pretty(&payload).expect("serialize")
17140 );
17141 } else {
17142 println!(
17143 "{} signed {} verification record(s) under {} (toolchain {})",
17144 style::ok("lean.verify-all"),
17145 summary.len(),
17146 out.display(),
17147 toolchain
17148 );
17149 }
17150 }
17151 LeanAction::VerifyCheck {
17152 record,
17153 anchor,
17154 json,
17155 } => {
17156 use crate::lean_verification::LeanVerification;
17157 let body = std::fs::read_to_string(&record)
17158 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", record.display())));
17159 let rec: LeanVerification = serde_json::from_str(&body)
17160 .unwrap_or_else(|e| fail_return(&format!("parse verification: {e}")));
17161 rec.verify()
17162 .unwrap_or_else(|e| fail_return(&format!("verify failed: {e}")));
17163 if let Some(anchor_path) = anchor {
17164 let abody = std::fs::read_to_string(&anchor_path).unwrap_or_else(|e| {
17165 fail_return(&format!("read {}: {e}", anchor_path.display()))
17166 });
17167 let a: crate::lean_anchors::LeanAnchor = serde_json::from_str(&abody)
17168 .unwrap_or_else(|e| fail_return(&format!("parse anchor: {e}")));
17169 if a.anchor_id != rec.anchor_id {
17170 fail(&format!(
17171 "anchor_id mismatch: record claims {}, anchor file is {}",
17172 rec.anchor_id, a.anchor_id
17173 ));
17174 }
17175 if a.module_sha256 != rec.module_sha256 {
17176 fail(&format!(
17177 "module_sha256 mismatch: record claims {}, anchor file is {}",
17178 rec.module_sha256, a.module_sha256
17179 ));
17180 }
17181 }
17182 if json {
17183 let payload = json!({
17184 "ok": true,
17185 "command": "lean.verify-check",
17186 "verification_id": rec.verification_id,
17187 "anchor_id": rec.anchor_id,
17188 "theorem_id": rec.theorem_id,
17189 "status": rec.status,
17190 });
17191 println!(
17192 "{}",
17193 serde_json::to_string_pretty(&payload).expect("serialize")
17194 );
17195 } else {
17196 println!(
17197 "{} {} (T{}) verifies under {}",
17198 style::ok("lean.verify-check"),
17199 rec.verification_id,
17200 rec.theorem_id,
17201 rec.verifier_actor
17202 );
17203 }
17204 }
17205 }
17206}
17207
17208fn cmd_diff_pack(action: DiffPackAction) {
17211 use crate::scientific_diff::{PackDraft, ScientificDiffPack};
17212
17213 match action {
17214 DiffPackAction::Create {
17215 frontier,
17216 proposals,
17217 summary,
17218 aggregate_kind,
17219 agent_run,
17220 parent_pack,
17221 key,
17222 out,
17223 json,
17224 } => {
17225 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
17226 for vpr in &proposals {
17230 let found = project.proposals.iter().any(|p| &p.id == vpr);
17231 if !found {
17232 fail(&format!(
17233 "proposal `{vpr}` not found on frontier `{}`",
17234 project.frontier_id()
17235 ));
17236 }
17237 }
17238 let draft = PackDraft {
17239 frontier_id: project.frontier_id().to_string(),
17240 created_at: chrono::Utc::now().to_rfc3339(),
17241 summary,
17242 proposals,
17243 aggregate_kind,
17244 agent_run,
17245 parent_pack,
17246 };
17247 let mut pack = ScientificDiffPack::build(draft).unwrap_or_else(|e| fail_return(&e));
17248 if let Some(key_path) = key {
17249 let key_hex = std::fs::read_to_string(&key_path).unwrap_or_else(|e| {
17250 fail_return(&format!("read key {}: {e}", key_path.display()))
17251 });
17252 let key_bytes = hex::decode(key_hex.trim())
17253 .unwrap_or_else(|e| fail_return(&format!("decode key hex: {e}")));
17254 let key_arr: [u8; 32] = key_bytes
17255 .try_into()
17256 .unwrap_or_else(|_| fail_return("signing key must be 32 bytes"));
17257 let signing = ed25519_dalek::SigningKey::from_bytes(&key_arr);
17258 pack.sign(&signing);
17259 }
17260 let body = serde_json::to_string_pretty(&pack).expect("serialize pack");
17261 if let Some(parent) = out.parent() {
17262 std::fs::create_dir_all(parent)
17263 .unwrap_or_else(|e| fail_return(&format!("create {}: {e}", parent.display())));
17264 }
17265 std::fs::write(&out, format!("{body}\n"))
17266 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
17267 if json {
17268 let payload = json!({
17269 "ok": true,
17270 "command": "diff-pack.create",
17271 "pack_id": pack.pack_id,
17272 "frontier_id": pack.frontier_id,
17273 "members": pack.proposals.len(),
17274 "signed": pack.signature.is_some(),
17275 "out": out.display().to_string(),
17276 });
17277 println!(
17278 "{}",
17279 serde_json::to_string_pretty(&payload).expect("serialize")
17280 );
17281 } else {
17282 println!(
17283 "{} {} ({} member{}) -> {}",
17284 style::ok("diff-pack"),
17285 pack.pack_id,
17286 pack.proposals.len(),
17287 if pack.proposals.len() == 1 { "" } else { "s" },
17288 out.display()
17289 );
17290 }
17291 }
17292 DiffPackAction::Show { pack, json } => {
17293 let body = std::fs::read_to_string(&pack)
17294 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", pack.display())));
17295 let p: ScientificDiffPack = serde_json::from_str(&body)
17296 .unwrap_or_else(|e| fail_return(&format!("parse pack: {e}")));
17297 if json {
17298 println!("{body}");
17299 } else {
17300 println!(
17301 "{} {}\n frontier: {}\n summary: {}\n kind: {}\n members: {}",
17302 style::ok("diff-pack.show"),
17303 p.pack_id,
17304 p.frontier_id,
17305 p.summary,
17306 p.aggregate_kind,
17307 p.proposals.len()
17308 );
17309 for (i, vpr) in p.proposals.iter().enumerate() {
17310 println!(" {:2}. {}", i + 1, vpr);
17311 }
17312 if let Some(agent) = &p.agent_run {
17313 println!(" agent_run: {agent}");
17314 }
17315 if let Some(parent) = &p.parent_pack {
17316 println!(" parent_pack: {parent}");
17317 }
17318 if p.signature.is_some() {
17319 println!(
17320 " signed by: {}",
17321 p.signer_pubkey_hex.as_deref().unwrap_or("?")
17322 );
17323 }
17324 }
17325 }
17326 DiffPackAction::Verify { pack, json } => {
17327 let body = std::fs::read_to_string(&pack)
17328 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", pack.display())));
17329 let p: ScientificDiffPack = serde_json::from_str(&body)
17330 .unwrap_or_else(|e| fail_return(&format!("parse pack: {e}")));
17331 p.verify()
17332 .unwrap_or_else(|e| fail_return(&format!("verify failed: {e}")));
17333 if json {
17334 let payload = json!({
17335 "ok": true,
17336 "command": "diff-pack.verify",
17337 "pack_id": p.pack_id,
17338 "signed": p.signature.is_some(),
17339 });
17340 println!(
17341 "{}",
17342 serde_json::to_string_pretty(&payload).expect("serialize")
17343 );
17344 } else {
17345 println!(
17346 "{} {} verifies ({} member{}, {})",
17347 style::ok("diff-pack.verify"),
17348 p.pack_id,
17349 p.proposals.len(),
17350 if p.proposals.len() == 1 { "" } else { "s" },
17351 if p.signature.is_some() {
17352 "signed"
17353 } else {
17354 "unsigned"
17355 }
17356 );
17357 }
17358 }
17359 DiffPackAction::BackfillRelease { frontier, json } => {
17360 use crate::diff_pack_release;
17361 let reports = diff_pack_release::backfill_all(&frontier)
17362 .unwrap_or_else(|e| fail_return(&format!("backfill-release failed: {e}")));
17363 let created = reports.iter().filter(|r| r.created).count();
17364 if json {
17365 let payload = json!({
17366 "ok": true,
17367 "command": "diff-pack.backfill-release",
17368 "created": created,
17369 "total": reports.len(),
17370 "reports": reports.iter().map(|r| json!({
17371 "pack_id": r.pack_id,
17372 "event_id": r.event_id,
17373 "created": r.created,
17374 })).collect::<Vec<_>>(),
17375 });
17376 println!(
17377 "{}",
17378 serde_json::to_string_pretty(&payload).expect("serialize")
17379 );
17380 } else {
17381 println!(
17382 "{} {} pack(s) on disk; {} new release event(s) emitted",
17383 style::ok("diff-pack.backfill-release"),
17384 reports.len(),
17385 created
17386 );
17387 for r in &reports {
17388 if r.created {
17389 println!(" + {} -> {}", r.pack_id, r.event_id);
17390 } else {
17391 println!(" = {} (existing {})", r.pack_id, r.event_id);
17392 }
17393 }
17394 }
17395 }
17396 DiffPackAction::PromoteVerdicts { frontier, json } => {
17397 use crate::diff_pack_promote;
17398 let reports = diff_pack_promote::promote_all(&frontier)
17399 .unwrap_or_else(|e| fail_return(&format!("promote-verdicts failed: {e}")));
17400 if json {
17401 let payload = json!({
17402 "ok": true,
17403 "command": "diff-pack.promote-verdicts",
17404 "promoted": reports.iter().map(|r| json!({
17405 "verdict_id": r.verdict_id,
17406 "pack_id": r.pack_id,
17407 "verdict": r.verdict.canonical(),
17408 "event_id": r.event_id,
17409 "applied_members": r.applied_members,
17410 "sdk_only_members": r.sdk_only_members,
17411 })).collect::<Vec<_>>(),
17412 });
17413 println!(
17414 "{}",
17415 serde_json::to_string_pretty(&payload).expect("serialize")
17416 );
17417 } else {
17418 println!(
17419 "{} {} verdict(s) promoted",
17420 style::ok("diff-pack.promote-verdicts"),
17421 reports.len()
17422 );
17423 for r in &reports {
17424 println!(
17425 " {} {} -> {} ({} applied, {} sdk-only)",
17426 r.pack_id,
17427 r.verdict.canonical(),
17428 r.event_id,
17429 r.applied_members.len(),
17430 r.sdk_only_members.len()
17431 );
17432 }
17433 }
17434 }
17435 DiffPackAction::WitnessCheck {
17436 pack_id,
17437 hubs,
17438 json,
17439 } => {
17440 if !pack_id.starts_with("vsd_") {
17441 fail(&format!("pack_id must start with `vsd_`, got `{pack_id}`"));
17442 }
17443 if hubs.is_empty() {
17444 fail("--hubs requires at least one hub URL");
17445 }
17446
17447 let client = reqwest::blocking::Client::builder()
17450 .timeout(std::time::Duration::from_secs(15))
17451 .build()
17452 .unwrap_or_else(|e| fail_return(&format!("http client: {e}")));
17453
17454 #[derive(serde::Serialize)]
17455 struct HubResult {
17456 hub: String,
17457 status: String,
17458 body_sha256: Option<String>,
17459 signature: Option<String>,
17460 http_status: Option<u16>,
17461 error: Option<String>,
17462 }
17463
17464 let mut results: Vec<HubResult> = Vec::new();
17465 for hub in &hubs {
17466 let url = format!("{}/diff-packs/{}", hub.trim_end_matches('/'), pack_id);
17467 match client.get(&url).send() {
17468 Ok(resp) => {
17469 let code = resp.status();
17470 if !code.is_success() {
17471 results.push(HubResult {
17472 hub: hub.clone(),
17473 status: if code.as_u16() == 404 {
17474 "missing".to_string()
17475 } else {
17476 "error".to_string()
17477 },
17478 body_sha256: None,
17479 signature: None,
17480 http_status: Some(code.as_u16()),
17481 error: None,
17482 });
17483 continue;
17484 }
17485 match resp.text() {
17486 Ok(body) => {
17487 let body_hash = {
17488 use sha2::{Digest, Sha256};
17489 hex::encode(Sha256::digest(body.as_bytes()))
17490 };
17491 let sig = serde_json::from_str::<serde_json::Value>(&body)
17492 .ok()
17493 .and_then(|v| {
17494 v.get("signature")
17495 .and_then(|s| s.as_str())
17496 .map(String::from)
17497 });
17498 results.push(HubResult {
17499 hub: hub.clone(),
17500 status: "present".to_string(),
17501 body_sha256: Some(body_hash),
17502 signature: sig,
17503 http_status: Some(code.as_u16()),
17504 error: None,
17505 });
17506 }
17507 Err(e) => results.push(HubResult {
17508 hub: hub.clone(),
17509 status: "error".to_string(),
17510 body_sha256: None,
17511 signature: None,
17512 http_status: Some(code.as_u16()),
17513 error: Some(format!("read body: {e}")),
17514 }),
17515 }
17516 }
17517 Err(e) => results.push(HubResult {
17518 hub: hub.clone(),
17519 status: "unreachable".to_string(),
17520 body_sha256: None,
17521 signature: None,
17522 http_status: None,
17523 error: Some(format!("{e}")),
17524 }),
17525 }
17526 }
17527
17528 let present: Vec<&HubResult> =
17532 results.iter().filter(|r| r.status == "present").collect();
17533 let verdict = if present.is_empty() {
17534 "no-witness".to_string()
17535 } else if present.len() < results.len() {
17536 "partial".to_string()
17537 } else {
17538 let first_sig = present[0].signature.as_deref().unwrap_or("");
17540 let all_match = present
17541 .iter()
17542 .all(|r| r.signature.as_deref().unwrap_or("") == first_sig);
17543 if all_match {
17544 "verified".to_string()
17545 } else {
17546 "split".to_string()
17547 }
17548 };
17549
17550 if json {
17551 let payload = json!({
17552 "ok": verdict == "verified",
17553 "command": "diff-pack.witness-check",
17554 "pack_id": pack_id,
17555 "verdict": verdict,
17556 "hubs": results,
17557 });
17558 println!(
17559 "{}",
17560 serde_json::to_string_pretty(&payload).expect("serialize")
17561 );
17562 } else {
17563 let glyph = match verdict.as_str() {
17564 "verified" => style::ok("witness-check"),
17565 _ => style::warn("witness-check"),
17566 };
17567 println!("{} {} {} (hubs={})", glyph, pack_id, verdict, hubs.len());
17568 for r in &results {
17569 let detail = match (&r.signature, &r.error) {
17570 (Some(s), _) => format!("sig={}...", &s[..16.min(s.len())]),
17571 (_, Some(e)) => format!("error: {e}"),
17572 _ => String::new(),
17573 };
17574 println!(" {} {} {}", r.hub, r.status, detail);
17575 }
17576 }
17577 }
17578 }
17579}
17580
17581fn cmd_tool(action: ToolCliAction) {
17584 use crate::tool_descriptor::{CallingConvention, DescriptorDraft, ToolDescriptor};
17585
17586 match action {
17587 ToolCliAction::Register {
17588 tool_name,
17589 tool_version,
17590 provider,
17591 calling_convention,
17592 input_schema,
17593 output_schema,
17594 evidence_url,
17595 cited_in_findings,
17596 out,
17597 json,
17598 } => {
17599 let conv = match calling_convention.as_str() {
17600 "http_json" => CallingConvention::HttpJson,
17601 "python_callable" => CallingConvention::PythonCallable,
17602 "cli_subprocess" => CallingConvention::CliSubprocess,
17603 "mcp_server" => CallingConvention::McpServer,
17604 other => fail_return(&format!(
17605 "calling_convention must be one of http_json | python_callable | cli_subprocess | mcp_server; got `{other}`"
17606 )),
17607 };
17608 let input_bytes = std::fs::read_to_string(&input_schema)
17609 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", input_schema.display())));
17610 let input_json: serde_json::Value = serde_json::from_str(&input_bytes)
17611 .unwrap_or_else(|e| fail_return(&format!("parse input_schema: {e}")));
17612 let output_bytes = std::fs::read_to_string(&output_schema)
17613 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", output_schema.display())));
17614 let output_json: serde_json::Value = serde_json::from_str(&output_bytes)
17615 .unwrap_or_else(|e| fail_return(&format!("parse output_schema: {e}")));
17616 let draft = DescriptorDraft {
17617 tool_name,
17618 tool_version,
17619 provider,
17620 calling_convention: conv,
17621 input_schema: input_json,
17622 output_schema: output_json,
17623 evidence_url,
17624 cited_in_findings,
17625 };
17626 let descriptor = ToolDescriptor::build(draft).unwrap_or_else(|e| fail_return(&e));
17627 let body = serde_json::to_string_pretty(&descriptor).expect("serialize descriptor");
17628 if let Some(parent) = out.parent() {
17629 std::fs::create_dir_all(parent)
17630 .unwrap_or_else(|e| fail_return(&format!("create {}: {e}", parent.display())));
17631 }
17632 std::fs::write(&out, format!("{body}\n"))
17633 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
17634 if json {
17635 let payload = json!({
17636 "ok": true,
17637 "command": "tool.register",
17638 "descriptor_id": descriptor.descriptor_id,
17639 "tool_name": descriptor.tool_name,
17640 "tool_version": descriptor.tool_version,
17641 "provider": descriptor.provider,
17642 "out": out.display().to_string(),
17643 });
17644 println!(
17645 "{}",
17646 serde_json::to_string_pretty(&payload).expect("serialize")
17647 );
17648 } else {
17649 println!(
17650 "{} {} {}@{} ({}) -> {}",
17651 style::ok("tool.register"),
17652 descriptor.descriptor_id,
17653 descriptor.tool_name,
17654 descriptor.tool_version,
17655 descriptor.provider,
17656 out.display()
17657 );
17658 }
17659 }
17660 ToolCliAction::Show { descriptor, json } => {
17661 let body = std::fs::read_to_string(&descriptor)
17662 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", descriptor.display())));
17663 let d: ToolDescriptor = serde_json::from_str(&body)
17664 .unwrap_or_else(|e| fail_return(&format!("parse descriptor: {e}")));
17665 if json {
17666 println!("{body}");
17667 } else {
17668 println!(
17669 "{} {}\n tool: {}@{}\n provider: {}\n conv: {}",
17670 style::ok("tool.show"),
17671 d.descriptor_id,
17672 d.tool_name,
17673 d.tool_version,
17674 d.provider,
17675 d.calling_convention.canonical()
17676 );
17677 if let Some(url) = &d.evidence_url {
17678 println!(" evidence: {url}");
17679 }
17680 if !d.cited_in_findings.is_empty() {
17681 println!(" cited in:");
17682 for vf in &d.cited_in_findings {
17683 println!(" - {vf}");
17684 }
17685 }
17686 }
17687 }
17688 ToolCliAction::Verify { descriptor, json } => {
17689 let body = std::fs::read_to_string(&descriptor)
17690 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", descriptor.display())));
17691 let d: ToolDescriptor = serde_json::from_str(&body)
17692 .unwrap_or_else(|e| fail_return(&format!("parse descriptor: {e}")));
17693 d.verify()
17694 .unwrap_or_else(|e| fail_return(&format!("verify failed: {e}")));
17695 if json {
17696 let payload = json!({
17697 "ok": true,
17698 "command": "tool.verify",
17699 "descriptor_id": d.descriptor_id,
17700 });
17701 println!(
17702 "{}",
17703 serde_json::to_string_pretty(&payload).expect("serialize")
17704 );
17705 } else {
17706 println!(
17707 "{} {} verifies ({}@{})",
17708 style::ok("tool.verify"),
17709 d.descriptor_id,
17710 d.tool_name,
17711 d.tool_version
17712 );
17713 }
17714 }
17715 }
17716}
17717
17718fn cmd_eval(action: EvalCliAction) {
17721 use crate::evaluation_record::{
17722 EvaluationKind, EvaluationRecord, Outcome, RecordDraft, TargetKind,
17723 };
17724
17725 fn parse_target_kind(s: &str) -> TargetKind {
17726 match s {
17727 "vsd" => TargetKind::Vsd,
17728 "vtr" => TargetKind::Vtr,
17729 "vf" => TargetKind::Vf,
17730 "vpf" => TargetKind::Vpf,
17731 "vtd" => TargetKind::Vtd,
17732 "vaa" => TargetKind::Vaa,
17733 other => fail_return(&format!(
17734 "target_kind must be one of vsd | vtr | vf | vpf | vtd | vaa; got `{other}`"
17735 )),
17736 }
17737 }
17738 fn parse_eval_kind(s: &str) -> EvaluationKind {
17739 match s {
17740 "replication" => EvaluationKind::Replication,
17741 "benchmark" => EvaluationKind::Benchmark,
17742 "validation" => EvaluationKind::Validation,
17743 "peer_review" => EvaluationKind::PeerReview,
17744 other => fail_return(&format!(
17745 "evaluation_kind must be one of replication | benchmark | validation | peer_review; got `{other}`"
17746 )),
17747 }
17748 }
17749 fn parse_outcome(s: &str) -> Outcome {
17750 match s {
17751 "succeeded" => Outcome::Succeeded,
17752 "failed" => Outcome::Failed,
17753 "partial" => Outcome::Partial,
17754 "inconclusive" => Outcome::Inconclusive,
17755 other => fail_return(&format!(
17756 "outcome must be one of succeeded | failed | partial | inconclusive; got `{other}`"
17757 )),
17758 }
17759 }
17760
17761 match action {
17762 EvalCliAction::Record {
17763 target_kind,
17764 target_id,
17765 evaluation_kind,
17766 outcome,
17767 evaluator,
17768 evidence_refs,
17769 benchmark_id,
17770 score,
17771 notes,
17772 key,
17773 out,
17774 json,
17775 } => {
17776 let draft = RecordDraft {
17777 target_kind: parse_target_kind(&target_kind),
17778 target_id,
17779 evaluation_kind: parse_eval_kind(&evaluation_kind),
17780 outcome: parse_outcome(&outcome),
17781 evaluator_actor: evaluator,
17782 evaluated_at: chrono::Utc::now().to_rfc3339(),
17783 evidence_refs,
17784 benchmark_id,
17785 score,
17786 notes,
17787 };
17788 let mut record = EvaluationRecord::build(draft).unwrap_or_else(|e| fail_return(&e));
17789 if let Some(key_path) = key {
17790 let key_hex = std::fs::read_to_string(&key_path).unwrap_or_else(|e| {
17791 fail_return(&format!("read key {}: {e}", key_path.display()))
17792 });
17793 let key_bytes = hex::decode(key_hex.trim())
17794 .unwrap_or_else(|e| fail_return(&format!("decode key hex: {e}")));
17795 let key_arr: [u8; 32] = key_bytes
17796 .try_into()
17797 .unwrap_or_else(|_| fail_return("signing key must be 32 bytes"));
17798 let signing = ed25519_dalek::SigningKey::from_bytes(&key_arr);
17799 record.sign(&signing);
17800 }
17801 let body = serde_json::to_string_pretty(&record).expect("serialize record");
17802 if let Some(parent) = out.parent() {
17803 std::fs::create_dir_all(parent)
17804 .unwrap_or_else(|e| fail_return(&format!("create {}: {e}", parent.display())));
17805 }
17806 std::fs::write(&out, format!("{body}\n"))
17807 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
17808 if json {
17809 let payload = json!({
17810 "ok": true,
17811 "command": "eval.record",
17812 "record_id": record.record_id,
17813 "target_id": record.target_id,
17814 "outcome": record.outcome.canonical(),
17815 "signed": record.signature.is_some(),
17816 "out": out.display().to_string(),
17817 });
17818 println!(
17819 "{}",
17820 serde_json::to_string_pretty(&payload).expect("serialize")
17821 );
17822 } else {
17823 println!(
17824 "{} {} {} {} -> {}",
17825 style::ok("eval.record"),
17826 record.record_id,
17827 record.target_id,
17828 record.outcome.canonical(),
17829 out.display()
17830 );
17831 }
17832 }
17833 EvalCliAction::Show { record, json } => {
17834 let body = std::fs::read_to_string(&record)
17835 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", record.display())));
17836 let r: EvaluationRecord = serde_json::from_str(&body)
17837 .unwrap_or_else(|e| fail_return(&format!("parse record: {e}")));
17838 if json {
17839 println!("{body}");
17840 } else {
17841 println!(
17842 "{} {}\n target: {} {}\n kind: {}\n outcome: {}\n evaluator: {}\n at: {}",
17843 style::ok("eval.show"),
17844 r.record_id,
17845 r.target_kind.canonical(),
17846 r.target_id,
17847 r.evaluation_kind.canonical(),
17848 r.outcome.canonical(),
17849 r.evaluator_actor,
17850 r.evaluated_at
17851 );
17852 if let Some(b) = &r.benchmark_id {
17853 println!(" benchmark: {b}");
17854 }
17855 if let Some(s) = r.score {
17856 println!(" score: {s}");
17857 }
17858 if r.signature.is_some() {
17859 println!(
17860 " signed by: {}",
17861 r.signer_pubkey_hex.as_deref().unwrap_or("?")
17862 );
17863 }
17864 }
17865 }
17866 EvalCliAction::Verify { record, json } => {
17867 let body = std::fs::read_to_string(&record)
17868 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", record.display())));
17869 let r: EvaluationRecord = serde_json::from_str(&body)
17870 .unwrap_or_else(|e| fail_return(&format!("parse record: {e}")));
17871 r.verify()
17872 .unwrap_or_else(|e| fail_return(&format!("verify failed: {e}")));
17873 if json {
17874 let payload = json!({
17875 "ok": true,
17876 "command": "eval.verify",
17877 "record_id": r.record_id,
17878 "signed": r.signature.is_some(),
17879 });
17880 println!(
17881 "{}",
17882 serde_json::to_string_pretty(&payload).expect("serialize")
17883 );
17884 } else {
17885 println!(
17886 "{} {} verifies ({}, {})",
17887 style::ok("eval.verify"),
17888 r.record_id,
17889 r.outcome.canonical(),
17890 if r.signature.is_some() {
17891 "signed"
17892 } else {
17893 "unsigned"
17894 }
17895 );
17896 }
17897 }
17898 }
17899}
17900
17901fn cmd_conflict(action: ConflictCliAction) {
17904 use crate::diff_pack_review;
17905 use crate::verdict_conflict::{ConflictDraft, ResolutionMode, VerdictConflict};
17906
17907 match action {
17908 ConflictCliAction::Detect { frontier, json } => {
17909 let pending = diff_pack_review::list_at_path(&frontier);
17916 let mut pack_members: std::collections::HashMap<String, Vec<String>> =
17918 std::collections::HashMap::new();
17919 for pv in &pending {
17920 if pack_members.contains_key(&pv.pack_id) {
17921 continue;
17922 }
17923 let path = frontier
17924 .join(".vela")
17925 .join("diff_packs")
17926 .join(format!("{}.json", pv.pack_id));
17927 if let Ok(body) = std::fs::read_to_string(&path)
17928 && let Ok(v) = serde_json::from_str::<Value>(&body)
17929 && let Some(arr) = v.get("proposals").and_then(Value::as_array)
17930 {
17931 let members: Vec<String> = arr
17932 .iter()
17933 .filter_map(|m| m.as_str().map(String::from))
17934 .collect();
17935 pack_members.insert(pv.pack_id.clone(), members);
17936 }
17937 }
17938 let mut candidates: Vec<Value> = Vec::new();
17940 for i in 0..pending.len() {
17941 for j in (i + 1)..pending.len() {
17942 let a = &pending[i];
17943 let b = &pending[j];
17944 if a.pack_id == b.pack_id {
17945 continue;
17946 }
17947 if a.verdict.canonical() == b.verdict.canonical() {
17948 continue;
17949 }
17950 let members_a = pack_members.get(&a.pack_id);
17951 let members_b = pack_members.get(&b.pack_id);
17952 if let (Some(ma), Some(mb)) = (members_a, members_b) {
17953 let shared: Vec<&String> = ma.iter().filter(|m| mb.contains(m)).collect();
17954 if shared.is_empty() {
17955 continue;
17956 }
17957 candidates.push(json!({
17958 "verdicts": [a.verdict_id, b.verdict_id],
17959 "packs": [a.pack_id, b.pack_id],
17960 "outcomes": [a.verdict.canonical(), b.verdict.canonical()],
17961 "reviewers": [a.reviewer_actor, b.reviewer_actor],
17962 "shared_member_ids": shared
17963 .iter()
17964 .map(|s| s.as_str())
17965 .collect::<Vec<_>>(),
17966 }));
17967 }
17968 }
17969 }
17970 if json {
17971 let payload = json!({
17972 "ok": true,
17973 "command": "conflict.detect",
17974 "frontier": frontier.display().to_string(),
17975 "candidate_count": candidates.len(),
17976 "candidates": candidates,
17977 });
17978 println!(
17979 "{}",
17980 serde_json::to_string_pretty(&payload).expect("serialize")
17981 );
17982 } else if candidates.is_empty() {
17983 println!(
17984 "{} {} no contradicting verdicts detected",
17985 style::ok("conflict.detect"),
17986 frontier.display()
17987 );
17988 } else {
17989 println!(
17990 "{} {} {} candidate conflict(s):",
17991 style::warn("conflict.detect"),
17992 frontier.display(),
17993 candidates.len()
17994 );
17995 for c in &candidates {
17996 let verdicts = c
17997 .get("verdicts")
17998 .and_then(Value::as_array)
17999 .map(|a| {
18000 a.iter()
18001 .filter_map(|v| v.as_str())
18002 .collect::<Vec<_>>()
18003 .join(" vs ")
18004 })
18005 .unwrap_or_default();
18006 let shared_count = c
18007 .get("shared_member_ids")
18008 .and_then(Value::as_array)
18009 .map_or(0, Vec::len);
18010 println!(" {verdicts} (shared members: {shared_count})");
18011 }
18012 }
18013 }
18014 ConflictCliAction::Resolve {
18015 frontier,
18016 verdicts,
18017 shared_members,
18018 mode,
18019 resolver,
18020 winning,
18021 rationale,
18022 key,
18023 json,
18024 } => {
18025 let resolution_mode = match mode.as_str() {
18026 "majority" => ResolutionMode::Majority,
18027 "owner_override" => ResolutionMode::OwnerOverride,
18028 "escalation" => ResolutionMode::Escalation,
18029 other => fail_return(&format!(
18030 "mode must be one of majority|owner_override|escalation; got `{other}`"
18031 )),
18032 };
18033 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
18034 let frontier_id = project.frontier_id().to_string();
18035 let draft = ConflictDraft {
18036 frontier_id: frontier_id.clone(),
18037 verdicts: verdicts.clone(),
18038 shared_member_ids: shared_members,
18039 resolution_mode,
18040 resolution_actor: resolver,
18041 resolved_at: chrono::Utc::now().to_rfc3339(),
18042 winning_verdict_id: winning,
18043 rationale,
18044 };
18045 let mut conflict = VerdictConflict::build(draft).unwrap_or_else(|e| fail_return(&e));
18046 if let Some(key_path) = key {
18047 let key_hex = std::fs::read_to_string(&key_path).unwrap_or_else(|e| {
18048 fail_return(&format!("read key {}: {e}", key_path.display()))
18049 });
18050 let key_bytes = hex::decode(key_hex.trim())
18051 .unwrap_or_else(|e| fail_return(&format!("decode key hex: {e}")));
18052 let key_arr: [u8; 32] = key_bytes
18053 .try_into()
18054 .unwrap_or_else(|_| fail_return("signing key must be 32 bytes"));
18055 let signing = ed25519_dalek::SigningKey::from_bytes(&key_arr);
18056 conflict.sign(&signing);
18057 }
18058 let dir = frontier.join(".vela").join("verdict_conflicts");
18060 std::fs::create_dir_all(&dir)
18061 .unwrap_or_else(|e| fail_return(&format!("create {}: {e}", dir.display())));
18062 let out_path = dir.join(format!("{}.json", conflict.conflict_id));
18063 let body = serde_json::to_string_pretty(&conflict).expect("serialize conflict");
18064 std::fs::write(&out_path, format!("{body}\n"))
18065 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out_path.display())));
18066 if json {
18067 let payload = json!({
18068 "ok": true,
18069 "command": "conflict.resolve",
18070 "conflict_id": conflict.conflict_id,
18071 "frontier_id": frontier_id,
18072 "verdicts": verdicts,
18073 "resolution_mode": conflict.resolution_mode.canonical(),
18074 "out": out_path.display().to_string(),
18075 });
18076 println!(
18077 "{}",
18078 serde_json::to_string_pretty(&payload).expect("serialize")
18079 );
18080 } else {
18081 println!(
18082 "{} {} {} -> {}",
18083 style::ok("conflict.resolve"),
18084 conflict.conflict_id,
18085 conflict.resolution_mode.canonical(),
18086 out_path.display()
18087 );
18088 }
18089 }
18090 ConflictCliAction::List { frontier, json } => {
18091 let dir = frontier.join(".vela").join("verdict_conflicts");
18092 let mut out: Vec<VerdictConflict> = Vec::new();
18093 if let Ok(entries) = std::fs::read_dir(&dir) {
18094 for e in entries.flatten() {
18095 let p = e.path();
18096 if p.extension().and_then(|s| s.to_str()) != Some("json") {
18097 continue;
18098 }
18099 if let Ok(body) = std::fs::read_to_string(&p)
18100 && let Ok(c) = serde_json::from_str::<VerdictConflict>(&body)
18101 {
18102 out.push(c);
18103 }
18104 }
18105 }
18106 out.sort_by(|a, b| b.resolved_at.cmp(&a.resolved_at));
18107 if json {
18108 let payload = json!({
18109 "ok": true,
18110 "command": "conflict.list",
18111 "frontier": frontier.display().to_string(),
18112 "conflicts": out,
18113 });
18114 println!(
18115 "{}",
18116 serde_json::to_string_pretty(&payload).expect("serialize")
18117 );
18118 } else {
18119 println!(
18120 "{} {} {} resolved conflict(s)",
18121 style::ok("conflict.list"),
18122 frontier.display(),
18123 out.len()
18124 );
18125 for c in &out {
18126 println!(
18127 " {} {} ({} verdicts, {} shared members)",
18128 c.conflict_id,
18129 c.resolution_mode.canonical(),
18130 c.verdicts.len(),
18131 c.shared_member_ids.len()
18132 );
18133 }
18134 }
18135 }
18136 }
18137}
18138
18139fn cmd_preprint(frontier: PathBuf, released_at: Option<String>, out: Option<PathBuf>, json: bool) {
18142 use crate::preprint::render_preprint;
18143
18144 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
18145 let stamp = released_at.unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
18146 let body = render_preprint(&project, &stamp);
18147
18148 if let Some(out_path) = out {
18149 std::fs::write(&out_path, &body)
18150 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out_path.display())));
18151 if json {
18152 let payload = json!({
18153 "ok": true,
18154 "command": "preprint",
18155 "frontier_id": project.frontier_id(),
18156 "released_at": stamp,
18157 "bytes": body.len(),
18158 "out": out_path.display().to_string(),
18159 });
18160 println!(
18161 "{}",
18162 serde_json::to_string_pretty(&payload).expect("serialize preprint summary")
18163 );
18164 } else {
18165 println!(
18166 "{} preprint for {} -> {} ({} bytes)",
18167 style::ok("preprint"),
18168 project.frontier_id(),
18169 out_path.display(),
18170 body.len()
18171 );
18172 }
18173 } else {
18174 println!("{body}");
18175 }
18176}
18177
18178fn cmd_handle_resolve(handle: String, site: String, json: bool) {
18181 use crate::resolver::resolve;
18182
18183 let resolved = resolve(&handle, &site);
18184 if json {
18185 println!(
18186 "{}",
18187 serde_json::to_string_pretty(&resolved).expect("serialize resolved")
18188 );
18189 return;
18190 }
18191 println!(" handle {}", resolved.handle);
18192 println!(" kind {}", resolved.label);
18193 match resolved.url {
18194 Some(u) => println!(" url {u}"),
18195 None => println!(" url (unknown handle shape)"),
18196 }
18197}
18198
18199#[allow(clippy::too_many_arguments)]
18204fn cmd_crossref(
18205 frontier: PathBuf,
18206 release: Option<String>,
18207 member: String,
18208 prefix: String,
18209 depositor_name: String,
18210 depositor_email: String,
18211 resource_url: String,
18212 title: Option<String>,
18213 description: Option<String>,
18214 license: Option<String>,
18215 xml: bool,
18216 out: Option<PathBuf>,
18217 json: bool,
18218) {
18219 use crate::credit::build_ledger;
18220 use crate::crossref::{CrossrefDepositManifest, DepositInput, Depositor};
18221 use crate::frontier_release::FrontierRelease;
18222
18223 let project = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
18224 let releases_dir = releases_dir_for(&frontier);
18225 let release_id = release.or_else(|| latest_release_id(&releases_dir));
18226 let release_id = match release_id {
18227 Some(id) => id,
18228 None => fail_return(
18229 "no release found: pass --release <vfrr_*> or cut one first with `vela frontier release --name v1.0`",
18230 ),
18231 };
18232 let release_path = releases_dir.join(format!("{release_id}.json"));
18233 let release_raw = std::fs::read_to_string(&release_path)
18234 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", release_path.display())));
18235 let release: FrontierRelease = serde_json::from_str(&release_raw)
18236 .unwrap_or_else(|e| fail_return(&format!("parse release {release_id}: {e}")));
18237
18238 let now = chrono::Utc::now().to_rfc3339();
18239 let ledger = build_ledger(&project, &now);
18240 let resolved_title = title.unwrap_or_else(|| project.project.name.clone());
18241
18242 let manifest = CrossrefDepositManifest::from_input(DepositInput {
18243 release: &release,
18244 title: resolved_title,
18245 resource_url,
18246 member_id: member,
18247 prefix,
18248 depositor: Depositor {
18249 name: depositor_name,
18250 email: depositor_email,
18251 },
18252 description,
18253 license,
18254 ledger: Some(&ledger),
18255 deposited_at: now,
18256 })
18257 .unwrap_or_else(|e| fail_return(&e));
18258
18259 let body = if xml {
18260 manifest.to_crossref_xml()
18261 } else {
18262 serde_json::to_string_pretty(&manifest).expect("serialize crossref manifest")
18263 };
18264
18265 if let Some(out_path) = out {
18266 std::fs::write(&out_path, format!("{body}\n"))
18267 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out_path.display())));
18268 if json {
18269 let payload = json!({
18270 "ok": true,
18271 "command": "crossref",
18272 "release_id": manifest.release.release_id,
18273 "frontier_id": manifest.release.frontier_id,
18274 "suggested_doi": manifest.suggested_doi,
18275 "contributor_count": manifest.contributors.len(),
18276 "out": out_path.display().to_string(),
18277 "format": if xml { "xml" } else { "json" },
18278 });
18279 println!(
18280 "{}",
18281 serde_json::to_string_pretty(&payload).expect("serialize crossref summary")
18282 );
18283 } else {
18284 println!(
18285 "{} crossref deposit for {} ({} contributor(s)) -> {} [{}]",
18286 style::ok("crossref"),
18287 manifest.release.release_id,
18288 manifest.contributors.len(),
18289 out_path.display(),
18290 if xml { "xml" } else { "json" }
18291 );
18292 }
18293 } else {
18294 println!("{body}");
18295 }
18296}
18297
18298fn cmd_citation(
18300 target: String,
18301 frontier: Option<PathBuf>,
18302 format: String,
18303 locator: Option<String>,
18304 out: Option<PathBuf>,
18305 json: bool,
18306) {
18307 use crate::citation::{CitationFormat, render_finding, render_frontier};
18308
18309 let fmt = CitationFormat::parse(&format).unwrap_or_else(|e| fail_return(&e));
18310
18311 let body = if target.starts_with("vf_") {
18313 let frontier_path = frontier.unwrap_or_else(|| {
18316 fail_return(
18317 "rendering a finding citation requires --frontier <path>; \
18318 pass the frontier the finding lives in.",
18319 )
18320 });
18321 let project = repo::load_from_path(&frontier_path).unwrap_or_else(|e| fail_return(&e));
18322 let finding = project
18323 .findings
18324 .iter()
18325 .find(|f| f.id == target)
18326 .cloned()
18327 .unwrap_or_else(|| {
18328 fail_return(&format!(
18329 "finding `{target}` not found in frontier `{}`",
18330 frontier_path.display()
18331 ))
18332 });
18333 render_finding(&project, &finding, fmt)
18334 } else {
18335 let frontier_path = PathBuf::from(&target);
18337 let project = repo::load_from_path(&frontier_path).unwrap_or_else(|e| fail_return(&e));
18338 render_frontier(&project, fmt, locator.as_deref())
18339 };
18340
18341 if let Some(out_path) = out {
18342 std::fs::write(&out_path, &body)
18343 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out_path.display())));
18344 if json {
18345 let payload = json!({
18346 "ok": true,
18347 "command": "citation",
18348 "target": target,
18349 "format": format,
18350 "out": out_path.display().to_string(),
18351 "byte_count": body.len(),
18352 });
18353 println!(
18354 "{}",
18355 serde_json::to_string_pretty(&payload).expect("serialize citation summary")
18356 );
18357 } else {
18358 println!(
18359 "{} citation {} -> {} ({} bytes)",
18360 style::ok("citation"),
18361 target,
18362 out_path.display(),
18363 body.len()
18364 );
18365 }
18366 } else {
18367 if json {
18370 let payload = json!({
18371 "ok": true,
18372 "command": "citation",
18373 "target": target,
18374 "format": format,
18375 "body": body,
18376 });
18377 println!(
18378 "{}",
18379 serde_json::to_string_pretty(&payload).expect("serialize citation envelope")
18380 );
18381 } else {
18382 print!("{body}");
18383 }
18384 }
18385}
18386
18387async fn cmd_search_index(action: SearchAction) {
18391 match action {
18392 SearchAction::Build {
18393 frontiers,
18394 out,
18395 include_bootstrap,
18396 include_broken,
18397 json,
18398 } => match SEARCH_BUILD_HANDLER.get() {
18399 Some(handler) => {
18400 handler(frontiers, out, include_bootstrap, include_broken, json).await;
18401 }
18402 None => fail("search build handler not registered"),
18403 },
18404 SearchAction::Query {
18405 query,
18406 index,
18407 kind,
18408 entity,
18409 status,
18410 frontier_id,
18411 source_id,
18412 chain_status,
18413 limit,
18414 json,
18415 } => match SEARCH_QUERY_HANDLER.get() {
18416 Some(handler) => {
18417 handler(
18418 query,
18419 index,
18420 kind,
18421 entity,
18422 status,
18423 frontier_id,
18424 source_id,
18425 chain_status,
18426 limit,
18427 json,
18428 )
18429 .await;
18430 }
18431 None => fail("search query handler not registered"),
18432 },
18433 }
18434}
18435
18436fn cmd_hub_federation(action: HubFederationAction) {
18438 use crate::checkpoint::RegistryCheckpoint;
18439
18440 match action {
18441 HubFederationAction::Status { sources, json } => {
18442 if sources.len() < 2 {
18443 fail("--source requires at least two id=url pairs (comma-separated or repeated).");
18444 }
18445
18446 #[derive(serde::Serialize)]
18447 struct SourceResponse {
18448 id: String,
18449 url: String,
18450 status: String,
18451 #[serde(skip_serializing_if = "Option::is_none")]
18452 checkpoint_id: Option<String>,
18453 #[serde(skip_serializing_if = "Option::is_none")]
18454 registry_root: Option<String>,
18455 #[serde(skip_serializing_if = "Option::is_none")]
18456 sequence: Option<u64>,
18457 #[serde(skip_serializing_if = "Option::is_none")]
18458 hub_id: Option<String>,
18459 #[serde(skip_serializing_if = "Option::is_none")]
18460 note: Option<String>,
18461 }
18462
18463 let client = reqwest::blocking::Client::builder()
18464 .timeout(std::time::Duration::from_secs(15))
18465 .build()
18466 .unwrap_or_else(|e| fail_return(&format!("http client init: {e}")));
18467
18468 let mut responses: Vec<SourceResponse> = Vec::new();
18469 let mut root_counts: std::collections::BTreeMap<(String, u64), usize> =
18470 std::collections::BTreeMap::new();
18471
18472 for entry in &sources {
18473 let (id, url) = match entry.split_once('=') {
18474 Some(pair) => pair,
18475 None => {
18476 responses.push(SourceResponse {
18477 id: entry.clone(),
18478 url: String::new(),
18479 status: "malformed".to_string(),
18480 checkpoint_id: None,
18481 registry_root: None,
18482 sequence: None,
18483 hub_id: None,
18484 note: Some("source must be `id=url`".to_string()),
18485 });
18486 continue;
18487 }
18488 };
18489
18490 let body_result: Result<String, String> =
18493 if let Some(path) = url.strip_prefix("file://") {
18494 std::fs::read_to_string(path).map_err(|e| format!("read {path}: {e}"))
18495 } else if url.starts_with("http://") || url.starts_with("https://") {
18496 match client.get(url).send() {
18497 Ok(resp) if resp.status().is_success() => {
18498 resp.text().map_err(|e| format!("body: {e}"))
18499 }
18500 Ok(resp) => Err(format!("HTTP {}", resp.status())),
18501 Err(e) => Err(format!("{e}")),
18502 }
18503 } else {
18504 Err(format!("unsupported url scheme: {url}"))
18505 };
18506
18507 match body_result {
18508 Ok(body) => match serde_json::from_str::<RegistryCheckpoint>(&body) {
18509 Ok(cp) => {
18510 let derived = cp.derive_id().unwrap_or_else(|_| String::new());
18512 if derived != cp.checkpoint_id {
18513 responses.push(SourceResponse {
18514 id: id.to_string(),
18515 url: url.to_string(),
18516 status: "id_mismatch".to_string(),
18517 checkpoint_id: Some(cp.checkpoint_id.clone()),
18518 registry_root: None,
18519 sequence: None,
18520 hub_id: Some(cp.hub_id.clone()),
18521 note: Some(format!(
18522 "id mismatch: stored {}, derived {}",
18523 cp.checkpoint_id, derived
18524 )),
18525 });
18526 } else {
18527 *root_counts
18528 .entry((cp.registry_root.clone(), cp.sequence))
18529 .or_insert(0) += 1;
18530 responses.push(SourceResponse {
18531 id: id.to_string(),
18532 url: url.to_string(),
18533 status: "ok".to_string(),
18534 checkpoint_id: Some(cp.checkpoint_id),
18535 registry_root: Some(cp.registry_root),
18536 sequence: Some(cp.sequence),
18537 hub_id: Some(cp.hub_id),
18538 note: None,
18539 });
18540 }
18541 }
18542 Err(e) => responses.push(SourceResponse {
18543 id: id.to_string(),
18544 url: url.to_string(),
18545 status: "parse_error".to_string(),
18546 checkpoint_id: None,
18547 registry_root: None,
18548 sequence: None,
18549 hub_id: None,
18550 note: Some(format!("parse: {e}")),
18551 }),
18552 },
18553 Err(e) => responses.push(SourceResponse {
18554 id: id.to_string(),
18555 url: url.to_string(),
18556 status: "unreachable".to_string(),
18557 checkpoint_id: None,
18558 registry_root: None,
18559 sequence: None,
18560 hub_id: None,
18561 note: Some(e),
18562 }),
18563 }
18564 }
18565
18566 let resolved_count = responses.iter().filter(|r| r.status == "ok").count();
18568 let consensus = if resolved_count < 2 {
18569 "insufficient"
18570 } else if root_counts.len() == 1 {
18571 "unanimous"
18572 } else {
18573 let max = root_counts.values().copied().max().unwrap_or(0);
18574 if max * 2 > resolved_count {
18575 "majority"
18576 } else {
18577 "split"
18578 }
18579 };
18580
18581 let payload = json!({
18582 "ok": consensus == "unanimous" || consensus == "majority",
18583 "command": "registry.federation.status",
18584 "sources_queried": sources.len(),
18585 "sources_resolved": resolved_count,
18586 "distinct_roots": root_counts.len(),
18587 "consensus": consensus,
18588 "responses": responses,
18589 });
18590
18591 if json {
18592 println!(
18593 "{}",
18594 serde_json::to_string_pretty(&payload).expect("serialize federation status")
18595 );
18596 } else {
18597 println!(
18598 "{} federation status across {} source(s): {}",
18599 style::ok("registry"),
18600 sources.len(),
18601 consensus
18602 );
18603 for r in &responses {
18604 let summary = match (&r.registry_root, r.sequence) {
18605 (Some(root), Some(seq)) => {
18606 format!("seq {seq} root {}...", &root[..root.len().min(23)])
18607 }
18608 _ => r.note.clone().unwrap_or_default(),
18609 };
18610 println!(" {} {} ({}) {summary}", r.status, r.id, r.url);
18611 }
18612 }
18613 if consensus == "split" {
18614 std::process::exit(1);
18615 }
18616 }
18617 }
18618}
18619
18620fn cmd_verify_all(from: Option<PathBuf>, json: bool) {
18622 use crate::registry;
18623
18624 let registry_path = match from {
18625 Some(p) => registry::resolve_local(p.to_str().unwrap_or_default())
18626 .unwrap_or_else(|e| fail_return(&e)),
18627 None => default_registry_path(),
18628 };
18629 let registry_data = registry::load_local(®istry_path).unwrap_or_else(|e| fail_return(&e));
18630
18631 #[derive(serde::Serialize)]
18632 struct EntryReport {
18633 vfr_id: String,
18634 signature_ok: bool,
18635 #[serde(skip_serializing_if = "Option::is_none")]
18636 error: Option<String>,
18637 }
18638
18639 let mut reports: Vec<EntryReport> = Vec::new();
18640 let mut pass = 0usize;
18641 let mut fail = 0usize;
18642 for entry in ®istry_data.entries {
18643 match registry::verify_entry(entry) {
18644 Ok(true) => {
18645 pass += 1;
18646 reports.push(EntryReport {
18647 vfr_id: entry.vfr_id.clone(),
18648 signature_ok: true,
18649 error: None,
18650 });
18651 }
18652 Ok(false) => {
18653 fail += 1;
18654 reports.push(EntryReport {
18655 vfr_id: entry.vfr_id.clone(),
18656 signature_ok: false,
18657 error: Some("signature did not verify against owner_pubkey".to_string()),
18658 });
18659 }
18660 Err(e) => {
18661 fail += 1;
18662 reports.push(EntryReport {
18663 vfr_id: entry.vfr_id.clone(),
18664 signature_ok: false,
18665 error: Some(e),
18666 });
18667 }
18668 }
18669 }
18670
18671 let ok = fail == 0;
18672 let payload = json!({
18673 "ok": ok,
18674 "command": "registry.verify-all",
18675 "registry": registry_path.display().to_string(),
18676 "entry_count": registry_data.entries.len(),
18677 "pass": pass,
18678 "fail": fail,
18679 "entries": reports,
18680 });
18681 if json {
18682 println!(
18683 "{}",
18684 serde_json::to_string_pretty(&payload).expect("serialize verify-all")
18685 );
18686 } else {
18687 println!(
18688 "{} verify-all over {}: {} pass, {} fail",
18689 style::ok("registry"),
18690 registry_path.display(),
18691 pass,
18692 fail
18693 );
18694 for r in &reports {
18695 let badge = if r.signature_ok { "ok" } else { "FAIL" };
18696 println!(" {badge} {}", r.vfr_id);
18697 if let Some(e) = &r.error {
18698 println!(" {e}");
18699 }
18700 }
18701 }
18702 if !ok {
18703 std::process::exit(1);
18704 }
18705}
18706
18707fn cmd_checkpoint(action: CheckpointAction) {
18709 use crate::checkpoint::{CheckpointDraft, RegistryCheckpoint};
18710 use crate::registry;
18711
18712 match action {
18713 CheckpointAction::Create {
18714 from,
18715 hub_id,
18716 sequence,
18717 previous,
18718 key,
18719 out,
18720 json,
18721 } => {
18722 let registry_path = registry::resolve_local(from.to_str().unwrap_or_default())
18723 .unwrap_or_else(|e| fail_return(&e));
18724 let registry_data =
18725 registry::load_local(®istry_path).unwrap_or_else(|e| fail_return(&e));
18726
18727 let key_hex = std::fs::read_to_string(&key)
18728 .map(|s| s.trim().to_string())
18729 .unwrap_or_else(|e| fail_return(&format!("read key: {e}")));
18730 let sk = parse_signing_key(&key_hex);
18731
18732 let draft = CheckpointDraft {
18733 hub_id,
18734 sequence,
18735 previous_checkpoint: previous,
18736 created_at: chrono::Utc::now().to_rfc3339(),
18737 };
18738 let checkpoint = RegistryCheckpoint::build(®istry_data, draft, &sk)
18739 .unwrap_or_else(|e| fail_return(&e));
18740
18741 let body = serde_json::to_string_pretty(&checkpoint).expect("serialize checkpoint");
18742 std::fs::write(&out, format!("{body}\n"))
18743 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", out.display())));
18744
18745 if json {
18746 let payload = json!({
18747 "ok": true,
18748 "command": "registry.checkpoint.create",
18749 "checkpoint_id": checkpoint.checkpoint_id,
18750 "hub_id": checkpoint.hub_id,
18751 "sequence": checkpoint.sequence,
18752 "entry_count": checkpoint.entry_count,
18753 "registry_root": checkpoint.registry_root,
18754 "previous_checkpoint": checkpoint.previous_checkpoint,
18755 "signer_pubkey": checkpoint.signer_pubkey,
18756 "out": out.display().to_string(),
18757 });
18758 println!(
18759 "{}",
18760 serde_json::to_string_pretty(&payload).expect("serialize create summary")
18761 );
18762 } else {
18763 println!(
18764 "{} checkpoint {} sequence {} over {} entries",
18765 style::ok("registry"),
18766 checkpoint.checkpoint_id,
18767 checkpoint.sequence,
18768 checkpoint.entry_count
18769 );
18770 println!(" registry_root: {}", checkpoint.registry_root);
18771 println!(" signer pubkey: {}...", &checkpoint.signer_pubkey[..16]);
18772 println!(" out: {}", out.display());
18773 }
18774 }
18775 CheckpointAction::Verify {
18776 checkpoint,
18777 registry,
18778 json,
18779 } => {
18780 let cp_raw = std::fs::read_to_string(&checkpoint).unwrap_or_else(|e| {
18781 fail_return(&format!("read checkpoint {}: {e}", checkpoint.display()))
18782 });
18783 let cp: RegistryCheckpoint = serde_json::from_str(&cp_raw)
18784 .unwrap_or_else(|e| fail_return(&format!("parse checkpoint: {e}")));
18785 let registry_path = registry::resolve_local(registry.to_str().unwrap_or_default())
18786 .unwrap_or_else(|e| fail_return(&e));
18787 let registry_data =
18788 registry::load_local(®istry_path).unwrap_or_else(|e| fail_return(&e));
18789
18790 if let Err(e) = cp.verify(®istry_data) {
18791 if json {
18792 let payload = json!({
18793 "ok": false,
18794 "command": "registry.checkpoint.verify",
18795 "checkpoint_id": cp.checkpoint_id,
18796 "error": e,
18797 });
18798 println!(
18799 "{}",
18800 serde_json::to_string_pretty(&payload).expect("serialize verify failure")
18801 );
18802 } else {
18803 eprintln!("err · {e}");
18804 }
18805 std::process::exit(1);
18806 }
18807
18808 if json {
18809 let payload = json!({
18810 "ok": true,
18811 "command": "registry.checkpoint.verify",
18812 "checkpoint_id": cp.checkpoint_id,
18813 "hub_id": cp.hub_id,
18814 "sequence": cp.sequence,
18815 "entry_count": cp.entry_count,
18816 "registry_root": cp.registry_root,
18817 "signer_pubkey": cp.signer_pubkey,
18818 });
18819 println!(
18820 "{}",
18821 serde_json::to_string_pretty(&payload).expect("serialize verify success")
18822 );
18823 } else {
18824 println!(
18825 "{} checkpoint {} verified (sequence {}, {} entries)",
18826 style::ok("verify"),
18827 cp.checkpoint_id,
18828 cp.sequence,
18829 cp.entry_count
18830 );
18831 }
18832 }
18833 }
18834}
18835
18836fn cmd_verify_chain(frontier: PathBuf, artifacts: PathBuf, json: bool) {
18838 use crate::governance::{
18839 ChainStatus, GovernancePolicy, OwnerEpochChain, OwnerRotateAttestationBundle,
18840 OwnerRotateProposal, verify_chain,
18841 };
18842
18843 let chain_path = governance_chain_path(&frontier);
18844 if !chain_path.exists() {
18845 if json {
18847 println!(
18848 "{}",
18849 serde_json::to_string_pretty(&json!({
18850 "ok": true,
18851 "command": "registry.verify-chain",
18852 "frontier": frontier.display().to_string(),
18853 "chain_status": "legacy",
18854 "reason": format!("no chain file at {}", chain_path.display()),
18855 }))
18856 .expect("serialize legacy")
18857 );
18858 } else {
18859 println!(
18860 "{} chain status: legacy ({} not present)",
18861 style::ok("verify-chain"),
18862 chain_path.display()
18863 );
18864 }
18865 return;
18866 }
18867
18868 let chain_raw = std::fs::read_to_string(&chain_path)
18869 .unwrap_or_else(|e| fail_return(&format!("read chain: {e}")));
18870 let chain: OwnerEpochChain = serde_json::from_str(&chain_raw)
18871 .unwrap_or_else(|e| fail_return(&format!("parse chain: {e}")));
18872
18873 let mut policies: std::collections::HashMap<String, GovernancePolicy> =
18875 std::collections::HashMap::new();
18876 let mut proposals: std::collections::HashMap<String, OwnerRotateProposal> =
18877 std::collections::HashMap::new();
18878 let mut bundles: std::collections::HashMap<String, OwnerRotateAttestationBundle> =
18879 std::collections::HashMap::new();
18880
18881 for transition in &chain.transitions {
18882 let policy_path = artifacts.join(format!("{}.json", transition.policy_id));
18883 let proposal_path = artifacts.join(format!("{}.json", transition.proposal_id));
18884 let bundle_path = artifacts.join(format!("{}.json", transition.bundle_id));
18885
18886 if !policies.contains_key(&transition.policy_id) {
18887 let raw = std::fs::read_to_string(&policy_path).unwrap_or_else(|e| {
18888 fail_return(&format!("read policy {}: {e}", policy_path.display()))
18889 });
18890 let p: GovernancePolicy = serde_json::from_str(&raw)
18891 .unwrap_or_else(|e| fail_return(&format!("parse policy: {e}")));
18892 policies.insert(transition.policy_id.clone(), p);
18893 }
18894 if !proposals.contains_key(&transition.proposal_id) {
18895 let raw = std::fs::read_to_string(&proposal_path).unwrap_or_else(|e| {
18896 fail_return(&format!("read proposal {}: {e}", proposal_path.display()))
18897 });
18898 let p: OwnerRotateProposal = serde_json::from_str(&raw)
18899 .unwrap_or_else(|e| fail_return(&format!("parse proposal: {e}")));
18900 proposals.insert(transition.proposal_id.clone(), p);
18901 }
18902 if !bundles.contains_key(&transition.bundle_id) {
18903 let raw = std::fs::read_to_string(&bundle_path).unwrap_or_else(|e| {
18904 fail_return(&format!("read bundle {}: {e}", bundle_path.display()))
18905 });
18906 let b: OwnerRotateAttestationBundle = serde_json::from_str(&raw)
18907 .unwrap_or_else(|e| fail_return(&format!("parse bundle: {e}")));
18908 bundles.insert(transition.bundle_id.clone(), b);
18909 }
18910 }
18911
18912 let frontier_data = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
18913 let revocation = FrontierRevocation {
18914 map: frontier_data
18915 .actors
18916 .iter()
18917 .filter_map(|a| a.revoked_at.as_ref().map(|r| (a.id.clone(), r.clone())))
18918 .collect(),
18919 };
18920 let now = chrono::Utc::now().to_rfc3339();
18921
18922 let status = verify_chain(&chain, &policies, &proposals, &bundles, &revocation, &now);
18923
18924 let status_str = match status {
18925 ChainStatus::Bootstrap => "bootstrap",
18926 ChainStatus::Verified => "verified",
18927 ChainStatus::Legacy => "legacy",
18928 ChainStatus::Broken => "broken",
18929 };
18930
18931 if json {
18932 let payload = json!({
18933 "ok": !matches!(status, ChainStatus::Broken),
18934 "command": "registry.verify-chain",
18935 "frontier": frontier.display().to_string(),
18936 "chain_status": status_str,
18937 "transition_count": chain.transitions.len(),
18938 "current_epoch": chain.transitions.last().map_or(0, |t| t.owner_epoch),
18939 });
18940 println!(
18941 "{}",
18942 serde_json::to_string_pretty(&payload).expect("serialize verify-chain")
18943 );
18944 } else {
18945 println!(
18946 "{} chain status: {} ({} transition(s))",
18947 style::ok("verify-chain"),
18948 status_str,
18949 chain.transitions.len()
18950 );
18951 if let Some(t) = chain.transitions.last() {
18952 println!(
18953 " current epoch: {} policy: {} bundle: {}",
18954 t.owner_epoch, t.policy_id, t.bundle_id
18955 );
18956 }
18957 }
18958
18959 if matches!(status, ChainStatus::Broken) {
18960 std::process::exit(1);
18961 }
18962}
18963
18964struct FrontierRevocation {
18966 map: std::collections::HashMap<String, String>,
18967}
18968
18969impl crate::governance::ActorRevocationLookup for FrontierRevocation {
18970 fn revoked_at(&self, actor_id: &str) -> Option<&str> {
18971 self.map.get(actor_id).map(String::as_str)
18972 }
18973}
18974
18975fn cmd_governance(action: GovernanceAction) {
18977 use crate::governance::{GovernancePolicy, PolicyDraft, Quorum};
18978
18979 match action {
18980 GovernanceAction::Init {
18981 frontier,
18982 threshold,
18983 eligible,
18984 bootstrap,
18985 owner_epoch,
18986 current_owner_counts,
18987 attestation_ttl_hours,
18988 out,
18989 json,
18990 } => {
18991 let frontier_data = repo::load_from_path(&frontier).unwrap_or_else(|e| fail_return(&e));
18992 let frontier_id = frontier_data.frontier_id().to_string();
18993
18994 let resolved_owner_epoch = match (bootstrap, owner_epoch) {
18995 (true, None) => 0,
18996 (true, Some(e)) if e != 0 => {
18997 fail_return("--bootstrap requires --owner-epoch 0 (or omit --owner-epoch).")
18998 }
18999 (true, Some(e)) => e,
19000 (false, None) => fail_return(
19001 "--owner-epoch is required for non-bootstrap policies (or pass --bootstrap).",
19002 ),
19003 (false, Some(e)) => e,
19004 };
19005
19006 if eligible.is_empty() {
19007 fail("--eligible must list at least one actor id (comma-separated).");
19008 }
19009
19010 let draft = PolicyDraft {
19011 frontier_id,
19012 owner_epoch: resolved_owner_epoch,
19013 bootstrap_epoch: if bootstrap { 0 } else { resolved_owner_epoch },
19014 rotate_quorum: Quorum {
19015 threshold,
19016 eligible_actors: eligible,
19017 current_owner_counts,
19018 role_constraints: None,
19019 timelock_hours: None,
19020 },
19021 emergency_quorum: None,
19022 policy_update_quorum: None,
19023 attestation_ttl_hours,
19024 created_at: chrono::Utc::now().to_rfc3339(),
19025 };
19026 let policy = GovernancePolicy::from_draft(draft).unwrap_or_else(|e| fail_return(&e));
19027
19028 let body = serde_json::to_string_pretty(&policy).expect("serialize governance policy");
19029
19030 if let Some(path) = out {
19031 std::fs::write(&path, format!("{body}\n"))
19032 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", path.display())));
19033 if json {
19034 let payload = json!({
19035 "ok": true,
19036 "command": "registry.governance.init",
19037 "policy_id": policy.policy_id,
19038 "frontier_id": policy.frontier_id,
19039 "owner_epoch": policy.owner_epoch,
19040 "bootstrap_epoch": policy.bootstrap_epoch,
19041 "out": path.display().to_string(),
19042 });
19043 println!(
19044 "{}",
19045 serde_json::to_string_pretty(&payload).expect("serialize init summary")
19046 );
19047 } else {
19048 println!(
19049 "{} governance policy {} (epoch {}, bootstrap_epoch {}) -> {}",
19050 style::ok("registry"),
19051 policy.policy_id,
19052 policy.owner_epoch,
19053 policy.bootstrap_epoch,
19054 path.display()
19055 );
19056 println!(" threshold: {}", policy.rotate_quorum.threshold);
19057 println!(
19058 " eligible: {}",
19059 policy.rotate_quorum.eligible_actors.join(", ")
19060 );
19061 println!(
19062 " current_owner_counts: {}",
19063 policy.rotate_quorum.current_owner_counts
19064 );
19065 }
19066 } else {
19067 println!("{body}");
19071 }
19072 }
19073 GovernanceAction::Show { policy, json } => {
19074 let raw = std::fs::read_to_string(&policy)
19075 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", policy.display())));
19076 let parsed: GovernancePolicy = serde_json::from_str(&raw)
19077 .unwrap_or_else(|e| fail_return(&format!("parse policy: {e}")));
19078 if json {
19079 println!(
19080 "{}",
19081 serde_json::to_string_pretty(&parsed).expect("serialize policy")
19082 );
19083 } else {
19084 println!(" vela registry governance policy");
19085 println!(" policy_id: {}", parsed.policy_id);
19086 println!(" frontier_id: {}", parsed.frontier_id);
19087 println!(" owner_epoch: {}", parsed.owner_epoch);
19088 println!(" bootstrap_epoch: {}", parsed.bootstrap_epoch);
19089 println!(" rotate threshold: {}", parsed.rotate_quorum.threshold);
19090 println!(
19091 " eligible: {}",
19092 parsed.rotate_quorum.eligible_actors.join(", ")
19093 );
19094 println!(
19095 " current_owner_counts: {}",
19096 parsed.rotate_quorum.current_owner_counts
19097 );
19098 if let Some(q) = &parsed.emergency_quorum {
19099 println!(" emergency threshold: {}", q.threshold);
19100 }
19101 if let Some(q) = &parsed.policy_update_quorum {
19102 println!(" policy_update threshold: {}", q.threshold);
19103 }
19104 println!(" attestation_ttl_hours: {}", parsed.attestation_ttl_hours);
19105 println!(" created_at: {}", parsed.created_at);
19106 }
19107 }
19108 GovernanceAction::Validate { policy, json } => {
19109 let raw = std::fs::read_to_string(&policy)
19110 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", policy.display())));
19111 let parsed: GovernancePolicy = serde_json::from_str(&raw)
19112 .unwrap_or_else(|e| fail_return(&format!("parse policy: {e}")));
19113 if let Err(e) = parsed.validate() {
19114 if json {
19115 let payload = json!({
19116 "ok": false,
19117 "command": "registry.governance.validate",
19118 "policy_id": parsed.policy_id,
19119 "error": e,
19120 });
19121 println!(
19122 "{}",
19123 serde_json::to_string_pretty(&payload).expect("serialize validate failure")
19124 );
19125 } else {
19126 eprintln!("err · {e}");
19127 }
19128 std::process::exit(1);
19129 }
19130 if let Err(e) = parsed.verify_content_address() {
19131 if json {
19132 let payload = json!({
19133 "ok": false,
19134 "command": "registry.governance.validate",
19135 "policy_id": parsed.policy_id,
19136 "error": e,
19137 });
19138 println!(
19139 "{}",
19140 serde_json::to_string_pretty(&payload)
19141 .expect("serialize content-address failure")
19142 );
19143 } else {
19144 eprintln!("err · {e}");
19145 }
19146 std::process::exit(1);
19147 }
19148 if json {
19149 let payload = json!({
19150 "ok": true,
19151 "command": "registry.governance.validate",
19152 "policy_id": parsed.policy_id,
19153 "frontier_id": parsed.frontier_id,
19154 "owner_epoch": parsed.owner_epoch,
19155 "bootstrap_epoch": parsed.bootstrap_epoch,
19156 });
19157 println!(
19158 "{}",
19159 serde_json::to_string_pretty(&payload).expect("serialize validate success")
19160 );
19161 } else {
19162 println!(
19163 "{} governance policy {} valid (epoch {})",
19164 style::ok("validate"),
19165 parsed.policy_id,
19166 parsed.owner_epoch
19167 );
19168 }
19169 }
19170 }
19171}
19172
19173fn print_stats_json(path: &Path) {
19174 let frontier = load_frontier_or_fail(path);
19175 let source_hash = hash_path_or_fail(path);
19176 let payload = json!({
19177 "ok": true,
19178 "command": "stats",
19179 "schema_version": project::VELA_SCHEMA_VERSION,
19180 "frontier": {
19181 "name": &frontier.project.name,
19182 "description": &frontier.project.description,
19183 "source": path.display().to_string(),
19184 "hash": format!("sha256:{source_hash}"),
19185 "compiled_at": &frontier.project.compiled_at,
19186 "compiler": &frontier.project.compiler,
19187 "papers_processed": frontier.project.papers_processed,
19188 "errors": frontier.project.errors,
19189 },
19190 "stats": frontier.stats,
19191 "proposals": proposals::summary(&frontier),
19192 "proof_state": frontier.proof_state,
19193 });
19194 println!(
19195 "{}",
19196 serde_json::to_string_pretty(&payload).expect("failed to serialize stats")
19197 );
19198}
19199
19200fn cmd_search(
19201 source: Option<&Path>,
19202 query: &str,
19203 entity: Option<&str>,
19204 assertion_type: Option<&str>,
19205 all: Option<&Path>,
19206 limit: usize,
19207 json_output: bool,
19208) {
19209 if let Some(dir) = all {
19210 search::run_all(dir, query, entity, assertion_type, limit);
19211 return;
19212 }
19213 let Some(src) = source else {
19214 fail("Provide --source <frontier> or --all <directory>.");
19215 };
19216 if json_output {
19217 let results = search::search(src, query, entity, assertion_type, limit);
19218 let loaded = load_frontier_or_fail(src);
19219 let source_hash = hash_path_or_fail(src);
19220 let payload = json!({
19221 "ok": true,
19222 "command": "search",
19223 "schema_version": project::VELA_SCHEMA_VERSION,
19224 "query": query,
19225 "frontier": {
19226 "name": &loaded.project.name,
19227 "source": src.display().to_string(),
19228 "hash": format!("sha256:{source_hash}"),
19229 },
19230 "filters": {
19231 "entity": entity,
19232 "assertion_type": assertion_type,
19233 "limit": limit,
19234 },
19235 "count": results.len(),
19236 "results": results.iter().map(|result| json!({
19237 "id": &result.id,
19238 "score": result.score,
19239 "assertion": &result.assertion,
19240 "assertion_type": &result.assertion_type,
19241 "confidence": result.confidence,
19242 "entities": &result.entities,
19243 "doi": &result.doi,
19244 })).collect::<Vec<_>>()
19245 });
19246 println!(
19247 "{}",
19248 serde_json::to_string_pretty(&payload).expect("failed to serialize search results")
19249 );
19250 } else {
19251 search::run(src, query, entity, assertion_type, limit);
19252 }
19253}
19254
19255fn cmd_tensions(source: &Path, both_high: bool, cross_domain: bool, top: usize, json_output: bool) {
19256 let frontier = load_frontier_or_fail(source);
19257 let result = tensions::analyze(&frontier, both_high, cross_domain, top);
19258 if json_output {
19259 let source_hash = hash_path_or_fail(source);
19260 let payload = json!({
19261 "ok": true,
19262 "command": "tensions",
19263 "schema_version": project::VELA_SCHEMA_VERSION,
19264 "frontier": {
19265 "name": &frontier.project.name,
19266 "source": source.display().to_string(),
19267 "hash": format!("sha256:{source_hash}"),
19268 },
19269 "filters": {
19270 "both_high": both_high,
19271 "cross_domain": cross_domain,
19272 "top": top,
19273 },
19274 "count": result.len(),
19275 "tensions": result.iter().map(|t| json!({
19276 "score": t.score,
19277 "resolved": t.resolved,
19278 "superseding_id": &t.superseding_id,
19279 "finding_a": {
19280 "id": &t.finding_a.id,
19281 "assertion": &t.finding_a.assertion,
19282 "confidence": t.finding_a.confidence,
19283 "assertion_type": &t.finding_a.assertion_type,
19284 "citation_count": t.finding_a.citation_count,
19285 "contradicts_count": t.finding_a.contradicts_count,
19286 },
19287 "finding_b": {
19288 "id": &t.finding_b.id,
19289 "assertion": &t.finding_b.assertion,
19290 "confidence": t.finding_b.confidence,
19291 "assertion_type": &t.finding_b.assertion_type,
19292 "citation_count": t.finding_b.citation_count,
19293 "contradicts_count": t.finding_b.contradicts_count,
19294 }
19295 })).collect::<Vec<_>>()
19296 });
19297 println!(
19298 "{}",
19299 serde_json::to_string_pretty(&payload).expect("failed to serialize tensions")
19300 );
19301 } else {
19302 tensions::print_tensions(&result);
19303 }
19304}
19305
19306fn cmd_gaps(action: GapsAction) {
19307 match action {
19308 GapsAction::Rank {
19309 frontier,
19310 top,
19311 domain,
19312 json,
19313 } => cmd_gap_rank(&frontier, top, domain.as_deref(), json),
19314 }
19315}
19316
19317fn cmd_gap_rank(frontier_path: &Path, top: usize, domain: Option<&str>, json_output: bool) {
19318 let frontier = load_frontier_or_fail(frontier_path);
19319 let mut ranked = frontier
19320 .findings
19321 .iter()
19322 .filter(|finding| finding.flags.gap || finding.flags.negative_space)
19323 .filter(|finding| {
19324 domain.is_none_or(|domain| {
19325 finding
19326 .assertion
19327 .text
19328 .to_lowercase()
19329 .contains(&domain.to_lowercase())
19330 || finding
19331 .assertion
19332 .entities
19333 .iter()
19334 .any(|entity| entity.name.to_lowercase().contains(&domain.to_lowercase()))
19335 })
19336 })
19337 .map(|finding| {
19338 let dependency_count = frontier
19339 .findings
19340 .iter()
19341 .flat_map(|candidate| candidate.links.iter())
19342 .filter(|link| link.target == finding.id)
19343 .count();
19344 let score = dependency_count as f64 + finding.confidence.score;
19345 json!({
19346 "id": &finding.id,
19347 "kind": "candidate_gap_review_lead",
19348 "assertion": &finding.assertion.text,
19349 "score": score,
19350 "dependency_count": dependency_count,
19351 "confidence": finding.confidence.score,
19352 "evidence_type": &finding.evidence.evidence_type,
19353 "entities": finding.assertion.entities.iter().map(|e| &e.name).collect::<Vec<_>>(),
19354 "recommended_action": "Review source scope and missing evidence before treating this as an experiment target.",
19355 "caveats": ["Candidate gap rankings are review leads, not guaranteed underexplored areas or experiment targets."],
19356 })
19357 })
19358 .collect::<Vec<_>>();
19359 ranked.sort_by(|a, b| {
19360 b.get("score")
19361 .and_then(Value::as_f64)
19362 .partial_cmp(&a.get("score").and_then(Value::as_f64))
19363 .unwrap_or(std::cmp::Ordering::Equal)
19364 });
19365 ranked.truncate(top);
19366 if json_output {
19367 let source_hash = hash_path_or_fail(frontier_path);
19368 let payload = json!({
19369 "ok": true,
19370 "command": "gaps rank",
19371 "schema_version": project::VELA_SCHEMA_VERSION,
19372 "frontier": {
19373 "name": &frontier.project.name,
19374 "source": frontier_path.display().to_string(),
19375 "hash": format!("sha256:{source_hash}"),
19376 },
19377 "filters": {
19378 "top": top,
19379 "domain": domain,
19380 },
19381 "count": ranked.len(),
19382 "ranking_label": "candidate gap review leads",
19383 "caveats": ["These rankings are navigation signals over flagged findings, not scientific conclusions."],
19384 "review_leads": ranked.clone(),
19385 "gaps": ranked,
19386 });
19387 println!(
19388 "{}",
19389 serde_json::to_string_pretty(&payload).expect("failed to serialize gap ranking")
19390 );
19391 } else {
19392 println!();
19393 println!(" {}", "CANDIDATE GAP REVIEW LEADS".dimmed());
19394 println!(" {}", style::tick_row(60));
19395 println!(" review source scope; these are not guaranteed experiment targets.");
19396 println!();
19397 for (idx, gap) in ranked.iter().enumerate() {
19398 println!(
19399 " {}. [{}] score={} {}",
19400 idx + 1,
19401 gap["id"].as_str().unwrap_or("?"),
19402 gap["score"].as_f64().unwrap_or(0.0),
19403 gap["assertion"].as_str().unwrap_or("")
19404 );
19405 }
19406 }
19407}
19408
19409async fn cmd_bridge(inputs: &[PathBuf], check_novelty: bool, top_n: usize) {
19410 if inputs.len() < 2 {
19411 fail("need at least 2 frontier files for bridge detection.");
19412 }
19413 println!();
19414 println!(" {}", "VELA · BRIDGE · V0.36.0".dimmed());
19415 println!(" {}", style::tick_row(60));
19416 println!(" loading {} frontiers...", inputs.len());
19417 let mut named_projects = Vec::<(String, project::Project)>::new();
19418 let mut total_findings = 0;
19419 for path in inputs {
19420 let frontier = load_frontier_or_fail(path);
19421 let name = path
19422 .file_stem()
19423 .unwrap_or_default()
19424 .to_string_lossy()
19425 .to_string();
19426 println!(" {} · {} findings", name, frontier.stats.findings);
19427 total_findings += frontier.stats.findings;
19428 named_projects.push((name, frontier));
19429 }
19430 let refs = named_projects
19431 .iter()
19432 .map(|(name, frontier)| (name.as_str(), frontier))
19433 .collect::<Vec<_>>();
19434 let mut bridges = bridge::detect_bridges(&refs);
19435 if check_novelty && !bridges.is_empty() {
19436 let client = Client::new();
19437 let check_count = bridges.len().min(top_n);
19438 println!(" running rough PubMed prior-art checks for top {check_count} bridges...");
19439 for bridge_item in bridges.iter_mut().take(check_count) {
19440 let query = bridge::novelty_query(&bridge_item.entity_name, bridge_item);
19441 match bridge::check_novelty(&client, &query).await {
19442 Ok(count) => bridge_item.pubmed_count = Some(count),
19443 Err(e) => eprintln!(
19444 " {} prior-art check failed for {}: {e}",
19445 style::err_prefix(),
19446 bridge_item.entity_name
19447 ),
19448 }
19449 tokio::time::sleep(std::time::Duration::from_millis(350)).await;
19450 }
19451 }
19452 print!("{}", bridge::format_report(&bridges, total_findings));
19453}
19454
19455struct BenchArgs {
19456 frontier: Option<PathBuf>,
19457 gold: Option<PathBuf>,
19458 entity_gold: Option<PathBuf>,
19459 link_gold: Option<PathBuf>,
19460 suite: Option<PathBuf>,
19461 suite_ready: bool,
19462 min_f1: Option<f64>,
19463 min_precision: Option<f64>,
19464 min_recall: Option<f64>,
19465 no_thresholds: bool,
19466 json: bool,
19467}
19468
19469fn cmd_agent_bench(
19474 gold: &Path,
19475 candidate: &Path,
19476 sources: Option<&Path>,
19477 threshold: Option<f64>,
19478 report_path: Option<&Path>,
19479 json_out: bool,
19480) {
19481 let input = crate::agent_bench::BenchInput {
19482 gold_path: gold.to_path_buf(),
19483 candidate_path: candidate.to_path_buf(),
19484 sources: sources.map(Path::to_path_buf),
19485 threshold: threshold.unwrap_or(0.0),
19486 };
19487 let report = match crate::agent_bench::run(input) {
19488 Ok(r) => r,
19489 Err(e) => {
19490 eprintln!("{} bench failed: {e}", style::err_prefix());
19491 std::process::exit(1);
19492 }
19493 };
19494
19495 let json = serde_json::to_string_pretty(&report).unwrap_or_default();
19496 if let Some(path) = report_path
19497 && let Err(e) = std::fs::write(path, &json)
19498 {
19499 eprintln!(
19500 "{} failed to write report to {}: {e}",
19501 style::err_prefix(),
19502 path.display()
19503 );
19504 }
19505
19506 if json_out {
19507 println!("{json}");
19508 } else {
19509 println!();
19510 println!(" {}", "VELA · BENCH · AGENT STATE-UPDATE".dimmed());
19511 println!(" {}", style::tick_row(60));
19512 print!("{}", crate::agent_bench::render_pretty(&report));
19513 println!();
19514 }
19515
19516 if !report.pass {
19517 std::process::exit(1);
19518 }
19519}
19520
19521fn cmd_bench(args: BenchArgs) {
19522 if args.suite_ready {
19523 let suite_path = args
19524 .suite
19525 .unwrap_or_else(|| PathBuf::from("benchmarks/suites/bbb-core.json"));
19526 let payload =
19527 benchmark::suite_ready_report(&suite_path).unwrap_or_else(|e| fail_return(&e));
19528 println!(
19529 "{}",
19530 serde_json::to_string_pretty(&payload).expect("failed to serialize suite-ready report")
19531 );
19532 if payload.get("ok").and_then(Value::as_bool) != Some(true) {
19533 std::process::exit(1);
19534 }
19535 return;
19536 }
19537 if let Some(suite_path) = args.suite {
19538 let payload = benchmark::run_suite(&suite_path).unwrap_or_else(|e| fail_return(&e));
19539 if args.json {
19540 println!(
19541 "{}",
19542 serde_json::to_string_pretty(&payload)
19543 .expect("failed to serialize benchmark suite")
19544 );
19545 } else {
19546 let ok = payload.get("ok").and_then(Value::as_bool) == Some(true);
19547 let metrics = payload.get("metrics").unwrap_or(&Value::Null);
19548 println!();
19549 println!(" {}", "VELA · BENCH · SUITE".dimmed());
19550 println!(" {}", style::tick_row(60));
19551 println!(" suite: {}", suite_path.display());
19552 println!(
19553 " status: {}",
19554 if ok {
19555 style::ok("pass")
19556 } else {
19557 style::lost("fail")
19558 }
19559 );
19560 println!(
19561 " tasks: {}/{} passed",
19562 metrics
19563 .get("tasks_passed")
19564 .and_then(Value::as_u64)
19565 .unwrap_or(0),
19566 metrics
19567 .get("tasks_total")
19568 .and_then(Value::as_u64)
19569 .unwrap_or(0)
19570 );
19571 }
19572 if payload.get("ok").and_then(Value::as_bool) != Some(true) {
19573 std::process::exit(1);
19574 }
19575 return;
19576 }
19577
19578 let frontier = args
19579 .frontier
19580 .unwrap_or_else(|| PathBuf::from("frontiers/bbb-alzheimer.json"));
19581 let thresholds = benchmark::BenchmarkThresholds {
19582 min_f1: if args.no_thresholds {
19583 None
19584 } else {
19585 args.min_f1.or(Some(0.05))
19586 },
19587 min_precision: if args.no_thresholds {
19588 None
19589 } else {
19590 args.min_precision
19591 },
19592 min_recall: if args.no_thresholds {
19593 None
19594 } else {
19595 args.min_recall
19596 },
19597 ..Default::default()
19598 };
19599 if let Some(path) = args.link_gold {
19600 print_benchmark_or_exit(benchmark::task_envelope(
19601 &frontier,
19602 None,
19603 benchmark::BenchmarkMode::Link,
19604 Some(&path),
19605 &thresholds,
19606 None,
19607 ));
19608 } else if let Some(path) = args.entity_gold {
19609 print_benchmark_or_exit(benchmark::task_envelope(
19610 &frontier,
19611 None,
19612 benchmark::BenchmarkMode::Entity,
19613 Some(&path),
19614 &thresholds,
19615 None,
19616 ));
19617 } else if let Some(path) = args.gold {
19618 if args.json {
19619 print_benchmark_or_exit(benchmark::task_envelope(
19620 &frontier,
19621 None,
19622 benchmark::BenchmarkMode::Finding,
19623 Some(&path),
19624 &thresholds,
19625 None,
19626 ));
19627 } else {
19628 benchmark::run(&frontier, &path, false);
19629 }
19630 } else {
19631 fail("Provide --suite, --gold, --entity-gold, or --link-gold.");
19632 }
19633}
19634
19635fn print_benchmark_or_exit(result: Result<Value, String>) {
19636 let payload = result.unwrap_or_else(|e| fail_return(&e));
19637 println!(
19638 "{}",
19639 serde_json::to_string_pretty(&payload).expect("failed to serialize benchmark report")
19640 );
19641 if payload.get("ok").and_then(Value::as_bool) != Some(true) {
19642 std::process::exit(1);
19643 }
19644}
19645
19646fn cmd_packet(action: PacketAction) {
19647 let (result, json_output) = match action {
19648 PacketAction::Inspect { path, json } => (packet::inspect(&path), json),
19649 PacketAction::Validate { path, json } => (packet::validate(&path), json),
19650 };
19651 match result {
19652 Ok(output) if json_output => {
19653 println!(
19654 "{}",
19655 serde_json::to_string_pretty(&json!({
19656 "ok": true,
19657 "command": "packet",
19658 "result": output,
19659 }))
19660 .expect("failed to serialize packet response")
19661 );
19662 }
19663 Ok(output) => println!("{output}"),
19664 Err(e) => fail(&e),
19665 }
19666}
19667
19668fn cmd_verify(path: &Path, json_output: bool) {
19673 let result = packet::validate(path);
19674 match result {
19675 Ok(output) if json_output => {
19676 println!(
19677 "{}",
19678 serde_json::to_string_pretty(&json!({
19679 "ok": true,
19680 "command": "verify",
19681 "result": output,
19682 }))
19683 .expect("failed to serialize verify response")
19684 );
19685 }
19686 Ok(output) => {
19687 println!("{output}");
19688 println!(
19689 "\nverify: ok\n every file in the manifest matched its claimed sha256.\n pull this packet on another machine, run the same command, see the same line."
19690 );
19691 }
19692 Err(e) => fail(&e),
19693 }
19694}
19695
19696fn cmd_init(path: &Path, name: &str, template: &str, initialize_git: bool, json_output: bool) {
19697 if path.join(".vela").exists() {
19698 fail(&format!(
19699 "already initialized: {} exists",
19700 path.join(".vela").display()
19701 ));
19702 }
19703 let payload = frontier_repo::initialize(
19704 path,
19705 frontier_repo::InitOptions {
19706 name,
19707 template,
19708 initialize_git,
19709 },
19710 )
19711 .unwrap_or_else(|e| fail_return(&e));
19712 if json_output {
19713 println!(
19714 "{}",
19715 serde_json::to_string_pretty(&payload).expect("failed to serialize init report")
19716 );
19717 } else {
19718 println!(
19719 "{} initialized frontier repository in {}",
19720 style::ok("ok"),
19721 path.display()
19722 );
19723 }
19724}
19725
19726fn cmd_agent(action: AgentAction) {
19744 use std::process::Command;
19745 match action {
19746 AgentAction::Init {
19747 name,
19748 framework,
19749 out,
19750 json,
19751 } => {
19752 let slug = name.trim();
19753 if slug.is_empty() {
19754 fail("agent name must be non-empty");
19755 }
19756 if !slug
19759 .chars()
19760 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
19761 {
19762 fail("agent name must be lowercase alphanumeric + hyphens");
19763 }
19764 let valid_frameworks = [
19765 "claude-code",
19766 "claude-api",
19767 "langchain",
19768 "openai",
19769 "agent4science",
19770 "scienceclaw",
19771 "custom",
19772 ];
19773 if !valid_frameworks.contains(&framework.as_str()) {
19774 fail(&format!(
19775 "--framework must be one of: {}",
19776 valid_frameworks.join(", ")
19777 ));
19778 }
19779
19780 let target = out
19781 .clone()
19782 .unwrap_or_else(|| PathBuf::from("agents").join(slug));
19783 if target.exists() {
19784 fail(&format!(
19785 "agent directory already exists: {}",
19786 target.display()
19787 ));
19788 }
19789 let keys_dir = target.join("keys");
19790 std::fs::create_dir_all(&keys_dir)
19791 .unwrap_or_else(|e| fail_return(&format!("create {}: {e}", keys_dir.display())));
19792
19793 let exe = std::env::current_exe()
19797 .unwrap_or_else(|e| fail_return(&format!("cannot locate current executable: {e}")));
19798 let keys_out_str = keys_dir.to_string_lossy().into_owned();
19799 let kp_out = Command::new(&exe)
19800 .args(["sign", "generate-keypair", "--out", &keys_out_str, "--json"])
19801 .output()
19802 .unwrap_or_else(|e| fail_return(&format!("sign.generate-keypair: spawn: {e}")));
19803 if !kp_out.status.success() {
19804 let stderr = String::from_utf8_lossy(&kp_out.stderr);
19805 fail(&format!("sign.generate-keypair failed:\n{stderr}"));
19806 }
19807 let kp_json: Value = serde_json::from_slice(&kp_out.stdout)
19808 .unwrap_or_else(|e| fail_return(&format!("sign.generate-keypair bad json: {e}")));
19809 let public_key = kp_json
19810 .get("public_key")
19811 .and_then(Value::as_str)
19812 .unwrap_or_else(|| fail_return("sign.generate-keypair: missing public_key"))
19813 .to_string();
19814
19815 let date = chrono::Utc::now().format("%Y-%m-%d").to_string();
19816 let agent_id = format!("agent:{slug}-{date}");
19817 let now = chrono::Utc::now().to_rfc3339();
19818
19819 let actor_record = json!({
19823 "schema": "vela.agent_kit.actor.v0.1",
19824 "id": agent_id,
19825 "public_key": public_key,
19826 "algorithm": "ed25519",
19827 "actor_type": "agent",
19828 "created_at": now,
19829 "framework": framework,
19830 "name": slug,
19831 });
19832 std::fs::write(
19833 target.join("actor.json"),
19834 serde_json::to_vec_pretty(&actor_record).expect("serialize actor.json"),
19835 )
19836 .unwrap_or_else(|e| fail_return(&format!("write actor.json: {e}")));
19837
19838 let yaml = format!(
19840 "# v0.131: portable AI-agent kit scaffolded by `vela agent init`.\n\
19841 # The substrate makes the agent-draft / human-verdict\n\
19842 # distinction load-bearing. See docs/AI_ATTRIBUTION.md.\n\
19843 \n\
19844 schema: vela.agent_kit.v0.1\n\
19845 id: {agent_id}\n\
19846 name: {slug}\n\
19847 framework: {framework}\n\
19848 created_at: {now}\n\
19849 \n\
19850 # Workflow:\n\
19851 # 1. A human reviewer registers this agent in a frontier:\n\
19852 # vela actor add <frontier> '{agent_id}' \\\n\
19853 # --pubkey {public_key}\n\
19854 # 2. The agent reads frontier state through the MCP\n\
19855 # server: `vela serve <frontier>` (stdio JSON-RPC).\n\
19856 # Tools include frontier_stats, search_findings,\n\
19857 # get_finding, list_events.\n\
19858 # 3. The agent drafts proposals signed under the\n\
19859 # keypair in keys/ via `vela propose ...` or by\n\
19860 # POSTing to `vela serve --http`.\n\
19861 # 4. A human reviewer adjudicates each proposal.\n\
19862 # No agent-drafted proposal becomes accepted state\n\
19863 # without a signed human verdict.\n"
19864 );
19865 std::fs::write(target.join("agent.yaml"), yaml)
19866 .unwrap_or_else(|e| fail_return(&format!("write agent.yaml: {e}")));
19867
19868 let payload = json!({
19869 "ok": true,
19870 "command": "agent.init",
19871 "agent_id": agent_id,
19872 "name": slug,
19873 "framework": framework,
19874 "public_key": public_key,
19875 "keys_dir": keys_dir.display().to_string(),
19876 "actor_json": target.join("actor.json").display().to_string(),
19877 "agent_yaml": target.join("agent.yaml").display().to_string(),
19878 });
19879 if json {
19880 println!(
19881 "{}",
19882 serde_json::to_string_pretty(&payload).expect("failed to serialize agent.init")
19883 );
19884 } else {
19885 println!("{} scaffolded agent {}", style::ok("agent.init"), agent_id);
19886 println!(" framework: {framework}");
19887 println!(" public_key: {}", &public_key[..16]);
19888 println!(" out: {}", target.display());
19889 println!();
19890 println!(" next: register this agent in a frontier:");
19891 println!(
19892 " vela actor add <frontier> '{agent_id}' --pubkey {}",
19893 &public_key[..16]
19894 );
19895 println!(" see docs/AGENT_QUICKSTART.md for the full workflow.");
19896 }
19897 }
19898 AgentAction::List { root, json } => {
19899 let mut entries: Vec<Value> = Vec::new();
19900 if root.is_dir() {
19901 for entry in std::fs::read_dir(&root)
19902 .unwrap_or_else(|e| fail_return(&format!("read {}: {e}", root.display())))
19903 {
19904 let entry = match entry {
19905 Ok(e) => e,
19906 Err(_) => continue,
19907 };
19908 let actor_json = entry.path().join("actor.json");
19909 if !actor_json.is_file() {
19910 continue;
19911 }
19912 if let Ok(text) = std::fs::read_to_string(&actor_json)
19913 && let Ok(v) = serde_json::from_str::<Value>(&text)
19914 {
19915 entries.push(v);
19916 }
19917 }
19918 }
19919 if json {
19920 println!(
19921 "{}",
19922 serde_json::to_string_pretty(&json!({
19923 "ok": true,
19924 "command": "agent.list",
19925 "root": root.display().to_string(),
19926 "agents": entries,
19927 }))
19928 .expect("failed to serialize agent.list")
19929 );
19930 } else {
19931 println!("agents under {}: {}", root.display(), entries.len());
19932 for a in &entries {
19933 let id = a.get("id").and_then(Value::as_str).unwrap_or("?");
19934 let fw = a.get("framework").and_then(Value::as_str).unwrap_or("?");
19935 println!(" · {id} framework={fw}");
19936 }
19937 }
19938 }
19939 }
19940}
19941
19942fn cmd_quickstart(
19943 path: &Path,
19944 name: &str,
19945 reviewer: &str,
19946 assertion: Option<&str>,
19947 keys_out: Option<&Path>,
19948 json_output: bool,
19949) {
19950 use std::process::Command;
19951
19952 if path.join(".vela").exists() {
19953 fail(&format!(
19954 "already initialized: {} exists",
19955 path.join(".vela").display()
19956 ));
19957 }
19958
19959 let exe = std::env::current_exe()
19960 .unwrap_or_else(|e| fail_return(&format!("cannot locate current executable: {e}")));
19961 let keys_dir = keys_out
19962 .map(Path::to_path_buf)
19963 .unwrap_or_else(|| path.join("keys"));
19964 let assertion_text =
19965 assertion.unwrap_or("Quickstart placeholder claim. Replace with your real assertion.");
19966
19967 let run_step = |label: &str, args: &[&str]| -> std::process::Output {
19968 let out = Command::new(&exe)
19969 .args(args)
19970 .output()
19971 .unwrap_or_else(|e| fail_return(&format!("{label}: failed to spawn: {e}")));
19972 if !out.status.success() {
19973 let stderr = String::from_utf8_lossy(&out.stderr);
19974 fail(&format!("{label} failed:\n{stderr}"));
19975 }
19976 out
19977 };
19978
19979 run_step(
19981 "init",
19982 &[
19983 "init",
19984 path.to_string_lossy().as_ref(),
19985 "--name",
19986 name,
19987 "--no-git",
19988 "--json",
19989 ],
19990 );
19991
19992 let keys_out_str = keys_dir.to_string_lossy().into_owned();
19994 let keypair_out = run_step(
19995 "sign.generate-keypair",
19996 &[
19997 "sign",
19998 "generate-keypair",
19999 "--out",
20000 keys_out_str.as_ref(),
20001 "--json",
20002 ],
20003 );
20004 let keypair_json: serde_json::Value = serde_json::from_slice(&keypair_out.stdout)
20005 .unwrap_or_else(|e| fail_return(&format!("sign.generate-keypair: bad json: {e}")));
20006 let public_key = keypair_json
20007 .get("public_key")
20008 .and_then(|v| v.as_str())
20009 .unwrap_or_else(|| fail_return("sign.generate-keypair: missing public_key in output"))
20010 .to_string();
20011
20012 run_step(
20014 "actor.add",
20015 &[
20016 "actor",
20017 "add",
20018 path.to_string_lossy().as_ref(),
20019 reviewer,
20020 "--pubkey",
20021 public_key.as_str(),
20022 "--json",
20023 ],
20024 );
20025
20026 let finding_out = run_step(
20028 "finding.add",
20029 &[
20030 "finding",
20031 "add",
20032 path.to_string_lossy().as_ref(),
20033 "--assertion",
20034 assertion_text,
20035 "--author",
20036 reviewer,
20037 "--apply",
20038 "--json",
20039 ],
20040 );
20041 let finding_json: serde_json::Value = serde_json::from_slice(&finding_out.stdout)
20042 .unwrap_or_else(|e| fail_return(&format!("finding.add: bad json: {e}")));
20043 let finding_id = finding_json
20044 .get("finding_id")
20045 .and_then(|v| v.as_str())
20046 .map(str::to_string);
20047
20048 if json_output {
20049 let payload = json!({
20050 "ok": true,
20051 "command": "quickstart",
20052 "frontier": path.display().to_string(),
20053 "name": name,
20054 "reviewer": reviewer,
20055 "public_key": public_key,
20056 "keys_dir": keys_dir.display().to_string(),
20057 "finding_id": finding_id,
20058 "next_steps": [
20059 format!("vela serve {}", path.display()),
20060 format!(
20061 "vela ingest <paper.pdf|doi:...> --frontier {}",
20062 path.display()
20063 ),
20064 format!("vela log {}", path.display()),
20065 ],
20066 });
20067 println!(
20068 "{}",
20069 serde_json::to_string_pretty(&payload).expect("failed to serialize quickstart")
20070 );
20071 return;
20072 }
20073
20074 println!();
20075 println!(
20076 " {}",
20077 format!("VELA · QUICKSTART · {}", path.display())
20078 .to_uppercase()
20079 .dimmed()
20080 );
20081 println!(" {}", style::tick_row(60));
20082 println!(" frontier: {}", path.display());
20083 println!(" name: {name}");
20084 println!(" reviewer: {reviewer}");
20085 println!(" keys: {}", keys_dir.display());
20086 println!(" pubkey: {}…", &public_key[..16]);
20087 if let Some(id) = finding_id.as_deref() {
20088 println!(" finding: {id}");
20089 }
20090 println!();
20091 println!(" {}", style::ok("done"));
20092 println!(" next:");
20093 println!(" vela serve {}", path.display());
20094 println!(
20095 " vela ingest <paper.pdf|doi:10.xxx|pmid:xxx> --frontier {}",
20096 path.display()
20097 );
20098 println!(" vela log {}", path.display());
20099 println!();
20100}
20101
20102fn cmd_lock(path: &Path, check: bool, json_output: bool) {
20108 if check {
20109 cmd_lock_check(path, json_output);
20110 return;
20111 }
20112 let payload = crate::frontier_repo::materialize(path).unwrap_or_else(|e| fail_return(&e));
20113 if json_output {
20114 println!(
20115 "{}",
20116 serde_json::to_string_pretty(&json!({
20117 "ok": true,
20118 "command": "lock",
20119 "path": path.display().to_string(),
20120 "snapshot_hash": payload.get("snapshot_hash"),
20121 "event_log_hash": payload.get("event_log_hash"),
20122 "proposal_state_hash": payload.get("proposal_state_hash"),
20123 }))
20124 .expect("failed to serialize lock report")
20125 );
20126 return;
20127 }
20128 println!();
20129 println!(
20130 " {}",
20131 format!("VELA · LOCK · {}", path.display())
20132 .to_uppercase()
20133 .dimmed()
20134 );
20135 println!(" {}", style::tick_row(60));
20136 println!(
20137 " snapshot_hash: {}",
20138 payload
20139 .get("snapshot_hash")
20140 .and_then(|v| v.as_str())
20141 .unwrap_or("?")
20142 );
20143 println!(
20144 " event_log_hash: {}",
20145 payload
20146 .get("event_log_hash")
20147 .and_then(|v| v.as_str())
20148 .unwrap_or("?")
20149 );
20150 println!(
20151 " proposal_state_hash: {}",
20152 payload
20153 .get("proposal_state_hash")
20154 .and_then(|v| v.as_str())
20155 .unwrap_or("?")
20156 );
20157 println!();
20158 println!(" {}", style::ok("locked"));
20159}
20160
20161fn cmd_lock_check(path: &Path, json_output: bool) {
20162 use crate::frontier_repo::read_lock;
20163 let lock = read_lock(path).unwrap_or_else(|e| fail_return(&e));
20164 let Some(lock) = lock else {
20165 fail("lock --check: no vela.lock found at path");
20166 };
20167 let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
20168 let current_snapshot = format!("sha256:{}", crate::events::snapshot_hash(&project));
20169 let current_event_log = format!("sha256:{}", crate::events::event_log_hash(&project.events));
20170 let mut drift: Vec<String> = Vec::new();
20171 if lock.snapshot_hash != current_snapshot {
20172 drift.push(format!(
20173 "snapshot_hash: lock={} current={}",
20174 lock.snapshot_hash, current_snapshot
20175 ));
20176 }
20177 if lock.event_log_hash != current_event_log {
20178 drift.push(format!(
20179 "event_log_hash: lock={} current={}",
20180 lock.event_log_hash, current_event_log
20181 ));
20182 }
20183 let ok = drift.is_empty();
20184 if json_output {
20185 println!(
20186 "{}",
20187 serde_json::to_string_pretty(&json!({
20188 "ok": ok,
20189 "command": "lock.check",
20190 "path": path.display().to_string(),
20191 "drift": drift,
20192 "lock_snapshot_hash": lock.snapshot_hash,
20193 "current_snapshot_hash": current_snapshot,
20194 "lock_event_log_hash": lock.event_log_hash,
20195 "current_event_log_hash": current_event_log,
20196 "dependency_count": lock.dependencies.len(),
20197 }))
20198 .expect("failed to serialize lock check report")
20199 );
20200 } else {
20201 println!();
20202 println!(
20203 " {}",
20204 format!("VELA · LOCK · CHECK · {}", path.display())
20205 .to_uppercase()
20206 .dimmed()
20207 );
20208 println!(" {}", style::tick_row(60));
20209 if ok {
20210 println!(" snapshot_hash: {}", lock.snapshot_hash);
20211 println!(" event_log_hash: {}", lock.event_log_hash);
20212 println!(" dependencies pinned: {}", lock.dependencies.len());
20213 println!();
20214 println!(" {} on-disk state matches vela.lock", style::ok("ok"));
20215 } else {
20216 println!(" {} drift detected:", style::err_prefix());
20217 for d in &drift {
20218 println!(" - {d}");
20219 }
20220 }
20221 }
20222 if !ok {
20223 std::process::exit(1);
20224 }
20225}
20226
20227fn cmd_doc(path: &Path, out: Option<&Path>, json_output: bool) {
20232 let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
20233 let out_dir = out
20234 .map(Path::to_path_buf)
20235 .unwrap_or_else(|| path.join("doc"));
20236 let report =
20237 crate::doc_render::write_site(&project, &out_dir).unwrap_or_else(|e| fail_return(&e));
20238 if json_output {
20239 println!(
20240 "{}",
20241 serde_json::to_string_pretty(&report).expect("failed to serialize doc report")
20242 );
20243 return;
20244 }
20245 println!();
20246 println!(
20247 " {}",
20248 format!("VELA · DOC · {}", path.display())
20249 .to_uppercase()
20250 .dimmed()
20251 );
20252 println!(" {}", style::tick_row(60));
20253 println!(" frontier_id: {}", report.frontier_id);
20254 println!(" out: {}", report.out);
20255 println!(" files written: {}", report.files_written);
20256 println!(" findings: {}", report.findings_documented);
20257 println!(" events: {}", report.events_documented);
20258 println!();
20259 println!(
20260 " {} open {}/index.html in a browser",
20261 style::ok("ok"),
20262 report.out
20263 );
20264}
20265
20266fn cmd_import(frontier_path: &Path, into: Option<&Path>) {
20267 let frontier = repo::load_from_path(frontier_path).unwrap_or_else(|e| fail_return(&e));
20268 let target = into
20269 .map(Path::to_path_buf)
20270 .unwrap_or_else(|| PathBuf::from(frontier.project.name.replace(' ', "-").to_lowercase()));
20271 repo::init_repo(&target, &frontier).unwrap_or_else(|e| fail(&e));
20272 println!(
20273 "{} {} findings · {}",
20274 style::ok("imported"),
20275 frontier.findings.len(),
20276 target.display()
20277 );
20278}
20279
20280fn cmd_locator_repair(
20281 path: &Path,
20282 atom_id: &str,
20283 locator_override: Option<&str>,
20284 reviewer: &str,
20285 reason: &str,
20286 apply: bool,
20287 json_output: bool,
20288) {
20289 let report = state::repair_evidence_atom_locator(
20290 path,
20291 atom_id,
20292 locator_override,
20293 reviewer,
20294 reason,
20295 apply,
20296 )
20297 .unwrap_or_else(|e| fail_return(&e));
20298 print_state_report(&report, json_output);
20299}
20300
20301async fn cmd_source_fetch(
20306 identifier: &str,
20307 cache_root: Option<&Path>,
20308 out_path: Option<&Path>,
20309 refresh: bool,
20310 _json_output: bool,
20311) {
20312 use sha2::{Digest, Sha256};
20313
20314 let normalized = normalize_source_identifier(identifier);
20315 let cache_path = cache_root.map(|root| {
20316 let hash = format!("{:x}", Sha256::digest(normalized.as_bytes()));
20317 root.join("sources")
20318 .join("cache")
20319 .join(format!("{hash}.json"))
20320 });
20321
20322 if !refresh
20323 && let Some(p) = cache_path.as_ref()
20324 && p.is_file()
20325 {
20326 let body = std::fs::read_to_string(p)
20327 .unwrap_or_else(|e| fail_return(&format!("read cache {}: {e}", p.display())));
20328 emit_source_fetch_result(&body, out_path);
20329 return;
20330 }
20331
20332 let result = fetch_source_metadata(&normalized).await;
20333 let json = match result {
20334 Ok(value) => serde_json::to_string_pretty(&value)
20335 .unwrap_or_else(|e| fail_return(&format!("serialize fetched record: {e}"))),
20336 Err(e) => fail_return(&format!("source-fetch '{identifier}': {e}")),
20337 };
20338
20339 if let Some(p) = cache_path.as_ref() {
20340 if let Some(parent) = p.parent() {
20341 std::fs::create_dir_all(parent)
20342 .unwrap_or_else(|e| fail_return(&format!("mkdir {}: {e}", parent.display())));
20343 }
20344 std::fs::write(p, &json)
20345 .unwrap_or_else(|e| fail_return(&format!("write cache {}: {e}", p.display())));
20346 }
20347 emit_source_fetch_result(&json, out_path);
20348}
20349
20350fn emit_source_fetch_result(body: &str, out_path: Option<&Path>) {
20351 if let Some(p) = out_path {
20352 if let Some(parent) = p.parent() {
20353 let _ = std::fs::create_dir_all(parent);
20354 }
20355 std::fs::write(p, body)
20356 .unwrap_or_else(|e| fail_return(&format!("write {}: {e}", p.display())));
20357 } else {
20358 println!("{body}");
20359 }
20360}
20361
20362fn normalize_source_identifier(raw: &str) -> String {
20363 let trimmed = raw.trim();
20364 if trimmed.starts_with("doi:")
20365 || trimmed.starts_with("pmid:")
20366 || trimmed.starts_with("nct:")
20367 || trimmed.starts_with("pmc:")
20368 {
20369 return trimmed.to_string();
20370 }
20371 if trimmed.starts_with("10.") {
20372 return format!("doi:{trimmed}");
20373 }
20374 if trimmed.starts_with("NCT") || trimmed.starts_with("nct") {
20375 return format!(
20376 "nct:{}",
20377 trimmed
20378 .to_uppercase()
20379 .trim_start_matches("NCT")
20380 .to_string()
20381 .split_at(0)
20382 .0
20383 );
20384 }
20385 if trimmed.chars().all(|c| c.is_ascii_digit()) {
20386 return format!("pmid:{trimmed}");
20387 }
20388 trimmed.to_string()
20389}
20390
20391async fn fetch_source_metadata(normalized: &str) -> Result<Value, String> {
20392 let client = Client::builder()
20393 .user_agent("vela/0.66.0 (vela-source-fetch; +https://vela-science.fly.dev)")
20394 .timeout(std::time::Duration::from_secs(30))
20395 .build()
20396 .map_err(|e| format!("client build: {e}"))?;
20397 if let Some(rest) = normalized.strip_prefix("doi:") {
20398 let mut record = fetch_via_crossref(&client, rest).await?;
20405 let crossref_abstract = record
20406 .get("abstract")
20407 .and_then(|v| v.as_str())
20408 .unwrap_or("");
20409 if crossref_abstract.is_empty()
20410 && let Some(pmid) = resolve_doi_to_pmid(&client, rest).await
20411 && let Ok(pubmed_record) = fetch_via_pubmed(&client, &pmid).await
20412 {
20413 let pubmed_abstract = pubmed_record
20414 .get("abstract")
20415 .and_then(|v| v.as_str())
20416 .unwrap_or("")
20417 .to_string();
20418 if !pubmed_abstract.is_empty()
20419 && let Some(obj) = record.as_object_mut()
20420 {
20421 obj.insert("abstract".to_string(), Value::String(pubmed_abstract));
20422 obj.insert(
20423 "abstract_source".to_string(),
20424 Value::String(format!("pubmed:{pmid}")),
20425 );
20426 }
20427 }
20428 return Ok(record);
20429 }
20430 if let Some(rest) = normalized.strip_prefix("pmid:") {
20431 return fetch_via_pubmed(&client, rest).await;
20432 }
20433 if let Some(rest) = normalized.strip_prefix("nct:") {
20434 return fetch_via_ctgov(&client, rest).await;
20435 }
20436 Err(format!(
20437 "unsupported source identifier '{normalized}'. Use doi:, pmid:, or nct: prefix."
20438 ))
20439}
20440
20441async fn resolve_doi_to_pmid(client: &Client, doi: &str) -> Option<String> {
20445 let url = format!(
20446 "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term={}[doi]&retmode=json",
20447 urlencoding::encode(doi)
20448 );
20449 let resp = client.get(&url).send().await.ok()?;
20450 if !resp.status().is_success() {
20451 return None;
20452 }
20453 let body: Value = resp.json().await.ok()?;
20454 let id_list = body.pointer("/esearchresult/idlist")?.as_array()?;
20455 if id_list.len() != 1 {
20456 return None;
20459 }
20460 id_list.first()?.as_str().map(|s| s.to_string())
20461}
20462
20463async fn fetch_via_crossref(client: &Client, doi: &str) -> Result<Value, String> {
20464 let url = format!("https://api.crossref.org/works/{doi}");
20465 let resp = client
20466 .get(&url)
20467 .send()
20468 .await
20469 .map_err(|e| format!("crossref get: {e}"))?;
20470 if !resp.status().is_success() {
20471 return Err(format!("crossref returned {}", resp.status()));
20472 }
20473 let body: Value = resp
20474 .json()
20475 .await
20476 .map_err(|e| format!("crossref json: {e}"))?;
20477 let work = body.get("message").cloned().unwrap_or(Value::Null);
20478 let title = work
20479 .get("title")
20480 .and_then(|v| v.as_array())
20481 .and_then(|a| a.first())
20482 .and_then(|v| v.as_str())
20483 .unwrap_or("")
20484 .to_string();
20485 let abstract_html = work
20486 .get("abstract")
20487 .and_then(|v| v.as_str())
20488 .unwrap_or("")
20489 .to_string();
20490 let abstract_text = strip_jats_tags(&abstract_html);
20491 let year = work
20492 .get("issued")
20493 .and_then(|v| v.get("date-parts"))
20494 .and_then(|v| v.as_array())
20495 .and_then(|a| a.first())
20496 .and_then(|v| v.as_array())
20497 .and_then(|a| a.first())
20498 .and_then(|v| v.as_i64());
20499 let journal = work
20500 .get("container-title")
20501 .and_then(|v| v.as_array())
20502 .and_then(|a| a.first())
20503 .and_then(|v| v.as_str())
20504 .unwrap_or("")
20505 .to_string();
20506 let authors = work
20507 .get("author")
20508 .and_then(|v| v.as_array())
20509 .map(|arr| {
20510 arr.iter()
20511 .filter_map(|a| {
20512 let given = a.get("given").and_then(|v| v.as_str()).unwrap_or("");
20513 let family = a.get("family").and_then(|v| v.as_str()).unwrap_or("");
20514 let combined = format!("{given} {family}").trim().to_string();
20515 if combined.is_empty() {
20516 None
20517 } else {
20518 Some(combined)
20519 }
20520 })
20521 .collect::<Vec<_>>()
20522 })
20523 .unwrap_or_default();
20524 Ok(json!({
20525 "schema": "vela.source_fetch.v0.1",
20526 "identifier": format!("doi:{doi}"),
20527 "source": "crossref",
20528 "title": title,
20529 "abstract": abstract_text,
20530 "year": year,
20531 "journal": journal,
20532 "authors": authors,
20533 "retrieved_at": chrono::Utc::now().to_rfc3339(),
20534 }))
20535}
20536
20537async fn fetch_via_pubmed(client: &Client, pmid: &str) -> Result<Value, String> {
20538 let url = format!(
20539 "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id={pmid}&retmode=xml"
20540 );
20541 let resp = client
20542 .get(&url)
20543 .send()
20544 .await
20545 .map_err(|e| format!("pubmed get: {e}"))?;
20546 if !resp.status().is_success() {
20547 return Err(format!("pubmed returned {}", resp.status()));
20548 }
20549 let xml = resp.text().await.map_err(|e| format!("pubmed text: {e}"))?;
20550 let title = extract_xml_text(&xml, "<ArticleTitle>", "</ArticleTitle>");
20551 let abstract_text = extract_xml_text(&xml, "<AbstractText>", "</AbstractText>");
20552 let year = extract_xml_text(&xml, "<Year>", "</Year>")
20553 .parse::<i64>()
20554 .ok();
20555 let journal = extract_xml_text(&xml, "<Title>", "</Title>");
20556 Ok(json!({
20557 "schema": "vela.source_fetch.v0.1",
20558 "identifier": format!("pmid:{pmid}"),
20559 "source": "pubmed",
20560 "title": title,
20561 "abstract": abstract_text,
20562 "year": year,
20563 "journal": journal,
20564 "authors": Vec::<String>::new(),
20565 "retrieved_at": chrono::Utc::now().to_rfc3339(),
20566 }))
20567}
20568
20569async fn fetch_via_ctgov(client: &Client, nct: &str) -> Result<Value, String> {
20570 let nct_clean = nct.trim();
20571 let nct_id = if nct_clean.starts_with("NCT") || nct_clean.starts_with("nct") {
20572 nct_clean.to_uppercase()
20573 } else {
20574 format!("NCT{nct_clean}")
20575 };
20576 let url = format!("https://clinicaltrials.gov/api/v2/studies/{nct_id}");
20577 let resp = client
20578 .get(&url)
20579 .send()
20580 .await
20581 .map_err(|e| format!("ctgov get: {e}"))?;
20582 if !resp.status().is_success() {
20583 return Err(format!("ctgov returned {}", resp.status()));
20584 }
20585 let body: Value = resp.json().await.map_err(|e| format!("ctgov json: {e}"))?;
20586 let title = body
20587 .pointer("/protocolSection/identificationModule/briefTitle")
20588 .and_then(|v| v.as_str())
20589 .unwrap_or("")
20590 .to_string();
20591 let abstract_text = body
20592 .pointer("/protocolSection/descriptionModule/briefSummary")
20593 .and_then(|v| v.as_str())
20594 .unwrap_or("")
20595 .to_string();
20596 let phase = body
20597 .pointer("/protocolSection/designModule/phases")
20598 .and_then(|v| v.as_array())
20599 .and_then(|a| a.first())
20600 .and_then(|v| v.as_str())
20601 .unwrap_or("")
20602 .to_string();
20603 Ok(json!({
20604 "schema": "vela.source_fetch.v0.1",
20605 "identifier": format!("nct:{nct_id}"),
20606 "source": "clinicaltrials.gov",
20607 "title": title,
20608 "abstract": abstract_text,
20609 "year": Value::Null,
20610 "journal": phase,
20611 "authors": Vec::<String>::new(),
20612 "retrieved_at": chrono::Utc::now().to_rfc3339(),
20613 }))
20614}
20615
20616fn extract_xml_text(xml: &str, open: &str, close: &str) -> String {
20617 if let Some(start) = xml.find(open) {
20618 let after = &xml[start + open.len()..];
20619 if let Some(end) = after.find(close) {
20620 return after[..end].trim().to_string();
20621 }
20622 }
20623 String::new()
20624}
20625
20626fn strip_jats_tags(html: &str) -> String {
20627 let mut out = String::with_capacity(html.len());
20628 let mut in_tag = false;
20629 for c in html.chars() {
20630 match c {
20631 '<' => in_tag = true,
20632 '>' => in_tag = false,
20633 _ if !in_tag => out.push(c),
20634 _ => {}
20635 }
20636 }
20637 out.split_whitespace().collect::<Vec<_>>().join(" ")
20638}
20639
20640fn cmd_span_repair(
20641 path: &Path,
20642 finding_id: &str,
20643 section: &str,
20644 text: &str,
20645 reviewer: &str,
20646 reason: &str,
20647 apply: bool,
20648 json_output: bool,
20649) {
20650 let report =
20651 state::repair_finding_span(path, finding_id, section, text, reviewer, reason, apply)
20652 .unwrap_or_else(|e| fail_return(&e));
20653 print_state_report(&report, json_output);
20654}
20655
20656#[allow(clippy::too_many_arguments)]
20657fn cmd_entity_resolve(
20658 path: &Path,
20659 finding_id: &str,
20660 entity_name: &str,
20661 source: &str,
20662 id: &str,
20663 confidence: f64,
20664 matched_name: Option<&str>,
20665 resolution_method: &str,
20666 reviewer: &str,
20667 reason: &str,
20668 apply: bool,
20669 json_output: bool,
20670) {
20671 let report = state::resolve_finding_entity(
20672 path,
20673 finding_id,
20674 entity_name,
20675 source,
20676 id,
20677 confidence,
20678 matched_name,
20679 resolution_method,
20680 reviewer,
20681 reason,
20682 apply,
20683 )
20684 .unwrap_or_else(|e| fail_return(&e));
20685 print_state_report(&report, json_output);
20686}
20687
20688fn cmd_propagate(
20689 path: &Path,
20690 retract: Option<String>,
20691 reduce_confidence: Option<String>,
20692 to: Option<f64>,
20693 output: Option<&Path>,
20694) {
20695 let mut frontier = load_frontier_or_fail(path);
20696 let (finding_id, action, label) = if let Some(id) = retract {
20697 (id, propagate::PropagationAction::Retracted, "retraction")
20698 } else if let Some(id) = reduce_confidence {
20699 let score = to.unwrap_or_else(|| fail_return("--reduce-confidence requires --to <score>"));
20700 if !(0.0..=1.0).contains(&score) {
20701 fail("--to must be between 0.0 and 1.0");
20702 }
20703 (
20704 id,
20705 propagate::PropagationAction::ConfidenceReduced { new_score: score },
20706 "confidence reduction",
20707 )
20708 } else {
20709 fail("specify --retract <id> or --reduce-confidence <id> --to <score>");
20710 };
20711 if !frontier.findings.iter().any(|f| f.id == finding_id) {
20712 fail(&format!("finding not found: {finding_id}"));
20713 }
20714 let result = propagate::propagate_correction(&mut frontier, &finding_id, action);
20715 frontier.review_events.extend(result.events.clone());
20720 project::recompute_stats(&mut frontier);
20721 propagate::print_result(&result, label, &finding_id);
20722 let out = output.unwrap_or(path);
20723 repo::save_to_path(out, &frontier).expect("Failed to save frontier");
20724 println!(" output: {}", out.display());
20725}
20726
20727fn cmd_mcp_setup(source: Option<&Path>, frontiers: Option<&Path>) {
20728 let source_desc = source
20729 .map(|p| p.display().to_string())
20730 .or_else(|| frontiers.map(|p| p.display().to_string()))
20731 .unwrap_or_else(|| "frontier.json".to_string());
20732 let args = if let Some(path) = source {
20733 format!(r#""serve", "{}""#, path.display())
20734 } else if let Some(path) = frontiers {
20735 format!(r#""serve", "--frontiers", "{}""#, path.display())
20736 } else {
20737 r#""serve", "frontier.json""#.to_string()
20738 };
20739 println!(
20740 r#"Add this MCP server configuration to your client:
20741
20742{{
20743 "mcpServers": {{
20744 "vela": {{
20745 "command": "vela",
20746 "args": [{args}]
20747 }}
20748 }}
20749}}
20750
20751Source: {source_desc}"#
20752 );
20753}
20754
20755fn parse_entities(input: &str) -> Vec<(String, String)> {
20756 if input.trim().is_empty() {
20757 return Vec::new();
20758 }
20759 input
20760 .split(',')
20761 .filter_map(|pair| {
20762 let parts = pair.trim().splitn(2, ':').collect::<Vec<_>>();
20763 if parts.len() == 2 {
20764 Some((parts[0].trim().to_string(), parts[1].trim().to_string()))
20765 } else {
20766 eprintln!(
20767 "{} skipping malformed entity '{}'",
20768 style::warn("warn"),
20769 pair.trim()
20770 );
20771 None
20772 }
20773 })
20774 .collect()
20775}
20776
20777fn parse_evidence_spans(inputs: &[String]) -> Vec<Value> {
20778 inputs
20779 .iter()
20780 .filter_map(|input| {
20781 let trimmed = input.trim();
20782 if trimmed.is_empty() {
20783 return None;
20784 }
20785 if trimmed.starts_with('{') {
20786 match serde_json::from_str::<Value>(trimmed) {
20787 Ok(value @ Value::Object(_)) => return Some(value),
20788 Ok(_) | Err(_) => {
20789 eprintln!(
20790 "{} evidence span JSON should be an object; storing as text",
20791 style::warn("warn")
20792 );
20793 }
20794 }
20795 }
20796 Some(json!({
20797 "section": "curator_source",
20798 "text": trimmed,
20799 }))
20800 })
20801 .collect()
20802}
20803
20804fn hash_path(path: &Path) -> Result<String, String> {
20805 let mut hasher = Sha256::new();
20806 if path.is_file() {
20807 let bytes = std::fs::read(path)
20808 .map_err(|e| format!("Failed to read {} for hashing: {e}", path.display()))?;
20809 hasher.update(&bytes);
20810 } else if path.is_dir() {
20811 let mut files = Vec::new();
20812 collect_hash_files(path, path, &mut files)?;
20813 files.sort();
20814 for rel in files {
20815 hasher.update(rel.to_string_lossy().as_bytes());
20816 let bytes = std::fs::read(path.join(&rel))
20817 .map_err(|e| format!("Failed to read {} for hashing: {e}", rel.display()))?;
20818 hasher.update(bytes);
20819 }
20820 } else {
20821 return Err(format!("Cannot hash missing path {}", path.display()));
20822 }
20823 Ok(format!("{:x}", hasher.finalize()))
20824}
20825
20826fn load_frontier_or_fail(path: &Path) -> project::Project {
20827 repo::load_from_path(path).unwrap_or_else(|e| {
20828 fail_return(&format!(
20829 "Failed to load frontier '{}': {e}",
20830 path.display()
20831 ))
20832 })
20833}
20834
20835fn hash_path_or_fail(path: &Path) -> String {
20836 hash_path(path).unwrap_or_else(|e| {
20837 fail_return(&format!(
20838 "Failed to hash frontier '{}': {e}",
20839 path.display()
20840 ))
20841 })
20842}
20843
20844fn collect_hash_files(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<(), String> {
20845 for entry in
20846 std::fs::read_dir(dir).map_err(|e| format!("Failed to read {}: {e}", dir.display()))?
20847 {
20848 let entry = entry.map_err(|e| format!("Failed to read directory entry: {e}"))?;
20849 let path = entry.path();
20850 if path.is_dir() {
20851 collect_hash_files(root, &path, files)?;
20852 } else if path.is_file() {
20853 files.push(
20854 path.strip_prefix(root)
20855 .map_err(|e| e.to_string())?
20856 .to_path_buf(),
20857 );
20858 }
20859 }
20860 Ok(())
20861}
20862
20863fn schema_error_suggestion(error: &str) -> &'static str {
20864 if schema_error_action(error).is_some() {
20865 "Run `vela normalize` to repair deterministic frontier state."
20866 } else {
20867 "Inspect and correct the referenced frontier field."
20868 }
20869}
20870
20871fn schema_error_fix(error: &str) -> bool {
20872 schema_error_action(error).is_some()
20873}
20874
20875fn schema_error_action(error: &str) -> Option<&'static str> {
20876 if error.contains("stats.findings")
20877 || error.contains("stats.links")
20878 || error.contains("Invalid compiler")
20879 || error.contains("Invalid vela_version")
20880 || error.contains("Invalid schema")
20881 {
20882 Some("normalize_metadata_and_stats")
20883 } else if error.contains("does not match content-address") {
20884 Some("rewrite_ids")
20885 } else {
20886 None
20887 }
20888}
20889
20890fn build_repair_plan(diagnostics: &[Value]) -> Vec<Value> {
20891 let mut actions = std::collections::BTreeMap::<String, usize>::new();
20892 for diagnostic in diagnostics {
20893 if let Some(action) = diagnostic.get("normalize_action").and_then(Value::as_str) {
20894 *actions.entry(action.to_string()).or_default() += 1;
20895 }
20896 }
20897 actions
20898 .into_iter()
20899 .map(|(action, count)| {
20900 let command = if action == "rewrite_ids" {
20901 "vela normalize <frontier> --write --rewrite-ids --id-map id-map.json"
20902 } else {
20903 "vela normalize <frontier> --write"
20904 };
20905 json!({
20906 "action": action,
20907 "count": count,
20908 "command": command,
20909 })
20910 })
20911 .collect()
20912}
20913
20914fn cmd_integrity(frontier: &Path, json: bool) {
20915 let report = state_integrity::analyze_path(frontier).unwrap_or_else(|e| fail_return(&e));
20916 if json {
20917 println!(
20918 "{}",
20919 serde_json::to_string_pretty(&report).expect("failed to serialize integrity report")
20920 );
20921 } else {
20922 println!("vela integrity");
20923 println!(" frontier: {}", frontier.display());
20924 println!(" status: {}", report.status);
20925 println!(" proof freshness: {}", report.proof_freshness);
20926 println!(" structural errors: {}", report.structural_errors.len());
20927 for error in report.structural_errors.iter().take(8) {
20928 println!(" - {}: {}", error.rule_id, error.message);
20929 }
20930 }
20931}
20932
20933fn cmd_impact(frontier: &Path, finding_id: &str, depth: Option<usize>, json: bool) {
20934 let report =
20935 impact::analyze_path(frontier, finding_id, depth).unwrap_or_else(|e| fail_return(&e));
20936 if json {
20937 println!(
20938 "{}",
20939 serde_json::to_string_pretty(&report).expect("failed to serialize impact report")
20940 );
20941 } else {
20942 println!("vela impact");
20943 println!(" finding: {}", report.target.id);
20944 println!(" frontier: {}", report.frontier.vfr_id);
20945 println!(" direct dependents: {}", report.summary.direct_dependents);
20946 println!(" downstream: {}", report.summary.total_downstream);
20947 println!(" open proposals: {}", report.summary.open_proposals);
20948 println!(" accepted events: {}", report.summary.accepted_events);
20949 println!(" proof: {}", report.summary.proof_status);
20950 }
20951}
20952
20953fn cmd_discord(frontier: &Path, json: bool, kind_filter: Option<&str>) {
20954 use crate::discord::DiscordKind;
20955 use crate::discord_compute::compute_discord_assignment;
20956
20957 let project = repo::load_from_path(frontier).unwrap_or_else(|e| fail_return(&e));
20958 let assignment = compute_discord_assignment(&project);
20959 let support = assignment.frontier_support();
20960
20961 let mut rows: Vec<(String, Vec<String>)> = Vec::new();
20964 for context in support.iter() {
20965 let set = assignment.get(context);
20966 let kinds: Vec<String> = set.iter().map(|k| k.as_str().to_string()).collect();
20967 if let Some(filter) = kind_filter
20968 && !kinds.iter().any(|k| k == filter)
20969 {
20970 continue;
20971 }
20972 rows.push((context.clone(), kinds));
20973 }
20974
20975 let mut histogram: std::collections::BTreeMap<&'static str, usize> =
20979 std::collections::BTreeMap::new();
20980 for kind in DiscordKind::ALL {
20981 let count = assignment
20982 .iter()
20983 .filter(|(_, set)| set.contains(*kind))
20984 .count();
20985 if count > 0 {
20986 histogram.insert(kind.as_str(), count);
20987 }
20988 }
20989
20990 let total_findings = project.findings.len();
20991 let frontier_id = project
20992 .frontier_id
20993 .clone()
20994 .unwrap_or_else(|| String::from("<unknown>"));
20995
20996 if json {
20997 let row_value = |row: &(String, Vec<String>)| {
20998 serde_json::json!({
20999 "finding_id": row.0,
21000 "discord_kinds": row.1,
21001 })
21002 };
21003 let report = serde_json::json!({
21004 "frontier_id": frontier_id,
21005 "total_findings": total_findings,
21006 "frontier_support_size": support.len(),
21007 "filtered_row_count": rows.len(),
21008 "filter_kind": kind_filter,
21009 "histogram": histogram,
21010 "rows": rows.iter().map(row_value).collect::<Vec<_>>(),
21011 });
21012 println!(
21013 "{}",
21014 serde_json::to_string_pretty(&report).expect("serialize discord report")
21015 );
21016 return;
21017 }
21018
21019 println!("vela discord");
21020 println!(" frontier: {frontier_id}");
21021 println!(" total findings: {total_findings}");
21022 println!(
21023 " frontier support (any discord): {} of {}",
21024 support.len(),
21025 total_findings
21026 );
21027 if let Some(k) = kind_filter {
21028 println!(" filter: kind = {k}");
21029 }
21030 println!();
21031 if histogram.is_empty() {
21032 println!(" no discord detected.");
21033 } else {
21034 println!(" discord histogram:");
21035 for (k, n) in &histogram {
21036 println!(" {n:>4} {k}");
21037 }
21038 }
21039 if !rows.is_empty() {
21040 println!();
21041 println!(" findings with discord (showing up to 50):");
21042 for (fid, kinds) in rows.iter().take(50) {
21043 println!(" {fid} · {}", kinds.join(", "));
21044 }
21045 if rows.len() > 50 {
21046 println!(" ... and {} more", rows.len() - 50);
21047 }
21048 }
21049}
21050
21051fn empty_signal_report() -> signals::SignalReport {
21052 signals::SignalReport {
21053 schema: "vela.signals.v0".to_string(),
21054 frontier: "unavailable".to_string(),
21055 signals: Vec::new(),
21056 review_queue: Vec::new(),
21057 proof_readiness: signals::ProofReadiness {
21058 status: "unavailable".to_string(),
21059 blockers: 0,
21060 warnings: 0,
21061 caveats: vec!["Frontier could not be loaded for signal analysis.".to_string()],
21062 },
21063 }
21064}
21065
21066fn print_signal_summary(report: &signals::SignalReport, strict: bool) {
21067 println!();
21068 println!(" {}", "SIGNALS".dimmed());
21069 println!(" {}", style::tick_row(60));
21070 println!(" total signals: {}", report.signals.len());
21071 println!(" proof readiness: {}", report.proof_readiness.status);
21072 if !report.review_queue.is_empty() {
21073 println!(" review queue: {} items", report.review_queue.len());
21074 }
21075 if strict && report.proof_readiness.status != "ready" {
21076 println!(
21077 " {} proof readiness has blocking signals.",
21078 style::lost("strict check failed")
21079 );
21080 }
21081}
21082
21083fn append_packet_json_file(
21084 packet_dir: &Path,
21085 relative_path: &str,
21086 value: &Value,
21087) -> Result<(), String> {
21088 let content = serde_json::to_vec_pretty(value)
21089 .map_err(|e| format!("Failed to serialize packet JSON file: {e}"))?;
21090 let path = packet_dir.join(relative_path);
21091 if let Some(parent) = path.parent() {
21092 std::fs::create_dir_all(parent)
21093 .map_err(|e| format!("Failed to create {}: {e}", parent.display()))?;
21094 }
21095 std::fs::write(&path, &content)
21096 .map_err(|e| format!("Failed to write {}: {e}", path.display()))?;
21097 let entry = json!({
21098 "path": relative_path,
21099 "sha256": hex::encode(Sha256::digest(&content)),
21100 "bytes": content.len(),
21101 });
21102
21103 for manifest_name in ["manifest.json", "packet.lock.json"] {
21104 let manifest_path = packet_dir.join(manifest_name);
21105 let data = std::fs::read_to_string(&manifest_path)
21106 .map_err(|e| format!("Failed to read {}: {e}", manifest_path.display()))?;
21107 let mut manifest: Value = serde_json::from_str(&data)
21108 .map_err(|e| format!("Failed to parse {}: {e}", manifest_path.display()))?;
21109 let array_key = if manifest_name == "manifest.json" {
21110 "included_files"
21111 } else {
21112 "files"
21113 };
21114 let files = manifest
21115 .get_mut(array_key)
21116 .and_then(Value::as_array_mut)
21117 .ok_or_else(|| format!("{} missing {array_key} array", manifest_path.display()))?;
21118 files.retain(|file| {
21119 file.get("path")
21120 .and_then(Value::as_str)
21121 .is_none_or(|path| path != relative_path)
21122 });
21123 files.push(entry.clone());
21124 std::fs::write(
21125 &manifest_path,
21126 serde_json::to_vec_pretty(&manifest)
21127 .map_err(|e| format!("Failed to serialize {}: {e}", manifest_path.display()))?,
21128 )
21129 .map_err(|e| format!("Failed to write {}: {e}", manifest_path.display()))?;
21130 }
21131
21132 let lock_path = packet_dir.join("packet.lock.json");
21133 let lock_content = std::fs::read(&lock_path)
21134 .map_err(|e| format!("Failed to read {}: {e}", lock_path.display()))?;
21135 let lock_entry = json!({
21136 "path": "packet.lock.json",
21137 "sha256": hex::encode(Sha256::digest(&lock_content)),
21138 "bytes": lock_content.len(),
21139 });
21140 let manifest_path = packet_dir.join("manifest.json");
21141 let data = std::fs::read_to_string(&manifest_path)
21142 .map_err(|e| format!("Failed to read {}: {e}", manifest_path.display()))?;
21143 let mut manifest: Value = serde_json::from_str(&data)
21144 .map_err(|e| format!("Failed to parse {}: {e}", manifest_path.display()))?;
21145 let files = manifest
21146 .get_mut("included_files")
21147 .and_then(Value::as_array_mut)
21148 .ok_or_else(|| format!("{} missing included_files array", manifest_path.display()))?;
21149 files.retain(|file| {
21150 file.get("path")
21151 .and_then(Value::as_str)
21152 .is_none_or(|path| path != "packet.lock.json")
21153 });
21154 files.push(lock_entry);
21155 std::fs::write(
21156 &manifest_path,
21157 serde_json::to_vec_pretty(&manifest)
21158 .map_err(|e| format!("Failed to serialize {}: {e}", manifest_path.display()))?,
21159 )
21160 .map_err(|e| format!("Failed to write {}: {e}", manifest_path.display()))?;
21161 Ok(())
21162}
21163
21164fn print_tool_check_report(report: &Value) {
21165 let summary = report.get("summary").unwrap_or(&Value::Null);
21166 let frontier = report.get("frontier").unwrap_or(&Value::Null);
21167 println!();
21168 println!(" {}", "VELA · SERVE · CHECK-TOOLS".dimmed());
21169 println!(" {}", style::tick_row(60));
21170 println!(
21171 "frontier: {}",
21172 frontier
21173 .get("name")
21174 .and_then(Value::as_str)
21175 .unwrap_or("unknown")
21176 );
21177 println!(
21178 "findings: {}",
21179 frontier
21180 .get("findings")
21181 .and_then(Value::as_u64)
21182 .unwrap_or_default()
21183 );
21184 println!(
21185 "checks: {} passed, {} failed",
21186 summary
21187 .get("passed")
21188 .and_then(Value::as_u64)
21189 .unwrap_or_default(),
21190 summary
21191 .get("failed")
21192 .and_then(Value::as_u64)
21193 .unwrap_or_default()
21194 );
21195 if let Some(tools) = report.get("tools").and_then(Value::as_array) {
21196 let names = tools
21197 .iter()
21198 .filter_map(Value::as_str)
21199 .collect::<Vec<_>>()
21200 .join(", ");
21201 println!("tools: {names}");
21202 }
21203 if let Some(checks) = report.get("checks").and_then(Value::as_array) {
21204 for check in checks {
21205 let status = if check.get("ok").and_then(Value::as_bool) == Some(true) {
21206 style::ok("ok")
21207 } else {
21208 style::lost("lost")
21209 };
21210 println!(
21211 " {} {}",
21212 status,
21213 check
21214 .get("tool")
21215 .and_then(Value::as_str)
21216 .unwrap_or("unknown")
21217 );
21218 }
21219 }
21220}
21221
21222fn print_state_report(report: &state::StateCommandReport, json_output: bool) {
21223 if json_output {
21224 println!(
21225 "{}",
21226 serde_json::to_string_pretty(report).expect("failed to serialize state command report")
21227 );
21228 } else {
21229 println!("{}", report.message);
21230 println!(" frontier: {}", report.frontier);
21231 println!(" finding: {}", report.finding_id);
21232 println!(" proposal: {}", report.proposal_id);
21233 println!(" status: {}", report.proposal_status);
21234 if let Some(event_id) = &report.applied_event_id {
21235 println!(" event: {}", event_id);
21236 }
21237 println!(" wrote: {}", report.wrote_to);
21238 }
21239}
21240
21241fn print_history(payload: &Value) {
21242 let finding = payload.get("finding").unwrap_or(&Value::Null);
21243 println!("vela history");
21244 println!(
21245 " finding: {}",
21246 finding
21247 .get("id")
21248 .and_then(Value::as_str)
21249 .unwrap_or("unknown")
21250 );
21251 println!(
21252 " assertion: {}",
21253 finding
21254 .get("assertion")
21255 .and_then(Value::as_str)
21256 .unwrap_or("")
21257 );
21258 println!(
21259 " confidence: {:.3}",
21260 finding
21261 .get("confidence")
21262 .and_then(Value::as_f64)
21263 .unwrap_or_default()
21264 );
21265 let reviews = payload
21266 .get("review_events")
21267 .and_then(Value::as_array)
21268 .map_or(0, Vec::len);
21269 let updates = payload
21270 .get("confidence_updates")
21271 .and_then(Value::as_array)
21272 .map_or(0, Vec::len);
21273 let annotations = finding
21274 .get("annotations")
21275 .and_then(Value::as_array)
21276 .map_or(0, Vec::len);
21277 let sources = payload
21278 .get("sources")
21279 .and_then(Value::as_array)
21280 .map_or(0, Vec::len);
21281 let atoms = payload
21282 .get("evidence_atoms")
21283 .and_then(Value::as_array)
21284 .map_or(0, Vec::len);
21285 let conditions = payload
21286 .get("condition_records")
21287 .and_then(Value::as_array)
21288 .map_or(0, Vec::len);
21289 let proposals = payload
21290 .get("proposals")
21291 .and_then(Value::as_array)
21292 .map_or(0, Vec::len);
21293 let events = payload
21294 .get("events")
21295 .and_then(Value::as_array)
21296 .map_or(0, Vec::len);
21297 println!(" review events: {reviews}");
21298 println!(" confidence updates: {updates}");
21299 println!(" annotations: {annotations}");
21300 println!(" sources: {sources}");
21301 println!(" evidence atoms: {atoms}");
21302 println!(" condition records: {conditions}");
21303 println!(" proposals: {proposals}");
21304 println!(" canonical events: {events}");
21305 if let Some(status) = payload
21306 .get("proof_state")
21307 .and_then(|value| value.get("latest_packet"))
21308 .and_then(|value| value.get("status"))
21309 .and_then(Value::as_str)
21310 {
21311 println!(" proof state: {status}");
21312 }
21313 if let Some(events) = payload.get("review_events").and_then(Value::as_array) {
21314 for event in events.iter().take(8) {
21315 println!(
21316 " - {} {} {}",
21317 event
21318 .get("reviewed_at")
21319 .and_then(Value::as_str)
21320 .unwrap_or(""),
21321 event.get("id").and_then(Value::as_str).unwrap_or(""),
21322 event.get("reason").and_then(Value::as_str).unwrap_or("")
21323 );
21324 }
21325 }
21326}
21327
21328#[derive(Debug, Serialize)]
21329pub struct ProofTrace {
21330 pub trace_version: String,
21331 pub command: Vec<String>,
21332 pub source: String,
21333 pub source_hash: String,
21334 pub schema_version: String,
21335 pub checked_artifacts: Vec<String>,
21336 pub benchmark: Option<Value>,
21337 pub packet_manifest: String,
21338 pub packet_validation: String,
21339 pub caveats: Vec<String>,
21340 pub status: String,
21341 pub trace_path: String,
21342}
21343
21344const SCIENCE_SUBCOMMANDS: &[&str] = &[
21345 "compile-notes",
21346 "compile-code",
21347 "compile-data",
21348 "review-pending",
21349 "find-tensions",
21350 "plan-experiments",
21351 "scout",
21352 "check",
21353 "normalize",
21354 "integrity",
21355 "impact",
21356 "discord",
21357 "quickstart",
21358 "proof",
21359 "repo",
21360 "serve",
21361 "stats",
21362 "search",
21363 "search-index",
21364 "citation",
21365 "credit",
21366 "crossref",
21367 "handle",
21368 "hub",
21369 "lean",
21370 "diff-pack",
21371 "tool",
21372 "eval",
21373 "conflict",
21374 "preprint",
21375 "review-thread",
21376 "proof-attest-verification",
21377 "proof-verify-attestation",
21378 "tensions",
21379 "gaps",
21380 "bridge",
21381 "export",
21382 "packet",
21383 "bench",
21384 "conformance",
21385 "version",
21386 "sign",
21387 "actor",
21388 "frontier",
21389 "queue",
21390 "registry",
21391 "init",
21392 "import",
21393 "lock",
21394 "doc",
21395 "diff",
21396 "proposals",
21397 "finding",
21398 "link",
21399 "entity",
21400 "review",
21401 "note",
21402 "caveat",
21403 "revise",
21404 "reject",
21405 "history",
21406 "import-events",
21407 "retract",
21408 "propagate",
21409 "replicate",
21411 "replications",
21412 "dataset-add",
21415 "datasets",
21416 "code-add",
21417 "code-artifacts",
21418 "artifact-add",
21419 "artifact-to-state",
21420 "bridge-kit",
21421 "source-adapter",
21422 "runtime-adapter",
21423 "artifacts",
21424 "artifact-audit",
21425 "decision-brief",
21426 "trial-summary",
21427 "source-verification",
21428 "source-ingest-plan",
21429 "clinical-trial-import",
21430 "negative-result-add",
21432 "negative-results",
21433 "trajectory-create",
21435 "trajectory-step",
21436 "trajectories",
21437 "tier-set",
21439 "locator-repair",
21441 "span-repair",
21443 "entity-resolve",
21445 "entity-add",
21447 "proof-add",
21449 "agent",
21451 "source-fetch",
21453 "predict",
21456 "resolve",
21457 "predictions",
21458 "predictions-expire",
21459 "calibration",
21460 "consensus",
21463 "federation",
21465 "causal",
21467 "status",
21471 "log",
21472 "inbox",
21473 "ask",
21474 "bridges",
21476 "workbench",
21478 "verify",
21480 "ingest",
21484 "propose",
21485 "accept",
21486 "attest",
21487 "lineage",
21488 "carina",
21491 "atlas",
21494 "constellation",
21497];
21498
21499pub fn is_science_subcommand(name: &str) -> bool {
21500 SCIENCE_SUBCOMMANDS.contains(&name)
21501}
21502
21503fn print_strict_help() {
21504 println!(
21505 r#"Vela {}
21506Version control for scientific state.
21507
21508Usage:
21509 vela <COMMAND>
21510
21511Core flow (v0.74):
21512 init Initialize a split frontier repo
21513 ingest Ingest a paper, dataset, or Carina packet (dispatches by file type)
21514 propose Create a finding.review proposal
21515 diff Preview a `vpr_*` proposal, or compare two frontier files
21516 accept Apply a proposal under reviewer authority
21517 attest Sign findings under your private key
21518 log Recent canonical state events
21519 lineage State-transition replay for one finding
21520 serve Local Workbench (findings, evidence, diff, lineage)
21521
21522Read-only inspection:
21523 check Validate a frontier, repo, or proof packet
21524 integrity Check accepted frontier state integrity
21525 impact Report downstream finding impact
21526 normalize Apply deterministic frontier-state repairs
21527 proof Export and validate a proof packet
21528 repo Inspect split frontier repository status and shape
21529 stats Show frontier statistics
21530 search Search findings
21531 tensions List candidate contradictions and tensions
21532 gaps Inspect and rank candidate gap review leads
21533 bridge Find candidate cross-domain connections
21534
21535Advanced (proposal-creation, agent inboxes, federation):
21536 scout Run Literature Scout against a folder of PDFs (writes proposals)
21537 compile-notes Run Notes Compiler against a Markdown vault (writes proposals)
21538 compile-code Run Code & Notebook Analyst against a research repo (writes proposals)
21539 compile-data Run Datasets agent against a folder of CSV/TSV data (writes proposals)
21540 review-pending Run Reviewer Agent: score every pending proposal (writes notes)
21541 find-tensions Run Contradiction Finder: surface real contradictions among findings
21542 plan-experiments Run Experiment Planner: propose experiments for open questions / hypotheses
21543 export Export frontier artifacts
21544 packet Inspect or validate proof packets
21545 bench Run deterministic benchmark gates
21546 conformance Run protocol conformance vectors
21547 sign Optional signing and signature verification
21548 runtime-adapter
21549 Normalize external runtime exports into reviewable proposals
21550 version Show version information
21551 import Import frontier.json into a .vela repo
21552 proposals Inspect, validate, export, import, accept, or reject write proposals
21553 artifact-to-state
21554 Import a Carina artifact packet as reviewable proposals
21555 bridge-kit
21556 Validate Carina artifact packets before importing runtime output
21557 source-adapter
21558 Run reviewed source adapters into artifact-to-state proposals
21559 finding Add or manage finding bundles as frontier state
21560 link Add typed links between findings (incl. cross-frontier vf_at-vfr targets)
21561 entity Resolve unresolved entities against a bundled common-entity table (v0.19)
21562 frontier Scaffold (`new`), materialize, and manage frontier metadata + deps
21563 actor Register Ed25519 publisher identities in a frontier
21564 registry Publish, list, or pull frontiers (open hub at https://vela-hub.fly.dev)
21565 review Create a review proposal or review interactively
21566 note Add a lightweight note to a finding
21567 caveat Create an explicit caveat proposal
21568 revise Create a confidence revision proposal
21569 reject Create a rejection proposal
21570 history Show state-transition history for one finding (v0.74 alias: `lineage`)
21571 import-events Import review/state events from a packet or JSON file
21572 retract Create a retraction proposal
21573 propagate Simulate impact over declared dependency links
21574 artifact-add Register a content-addressed artifact
21575 artifacts List content-addressed artifacts
21576 artifact-audit Audit artifact locators, hashes, references, and profiles
21577 decision-brief Show the validated decision brief projection
21578 trial-summary Show the validated trial outcome projection
21579 source-verification Show the validated source verification projection
21580 source-ingest-plan Show the validated source ingest plan
21581 clinical-trial-import Import a ClinicalTrials.gov record as an artifact
21582 locator-repair Mechanically repair an evidence atom's missing source locator
21583 span-repair Mechanically repair a finding's missing evidence span
21584 entity-resolve Resolve a finding entity to a canonical id
21585 source-fetch Fetch metadata + abstract for a doi:/pmid:/nct: source
21586 atlas Compose multiple frontiers into a domain-level Atlas (vat_*) (v0.78+)
21587 constellation Compose multiple Atlases into a cross-domain Constellation (vco_*) (v0.82+)
21588
21589Quick start (the demo):
21590 vela init demo --name "Your bounded question"
21591 vela ingest paper.pdf --frontier demo
21592 vela propose demo <vf_id> --status accepted --reason "..." --reviewer reviewer:you --apply
21593 vela diff <vpr_id> --frontier demo
21594 vela accept demo <vpr_id> --reviewer reviewer:you --reason "applied"
21595 vela serve --path demo
21596
21597Substrate health:
21598 vela frontier materialize my-frontier --json
21599 vela repo status my-frontier --json
21600 vela proof verify my-frontier --json
21601 vela check my-frontier --strict --json
21602
21603Monolithic frontier file:
21604 vela frontier new frontier.json --name "Your bounded question"
21605 vela finding add frontier.json --assertion "..." --author "reviewer:demo" --apply
21606 vela check frontier.json --json
21607 FINDING_ID=$(jq -r '.findings[0].id' frontier.json)
21608 vela review frontier.json "$FINDING_ID" --status contested --reason "Mouse-only evidence" --reviewer reviewer:demo --apply
21609
21610Publish your own frontier (see docs/PUBLISHING.md):
21611 vela frontier new ./frontier.json --name "Your bounded question"
21612 vela finding add ./frontier.json --assertion "..." --author "reviewer:you" --apply
21613 vela sign generate-keypair --out keys
21614 vela actor add ./frontier.json reviewer:you --pubkey "$(cat keys/public.key)"
21615 vela registry publish ./frontier.json --owner reviewer:you --key keys/private.key \
21616 --to https://vela-hub.fly.dev
21617"#,
21618 env!("CARGO_PKG_VERSION")
21619 );
21620}
21621
21622pub type ScoutHandler = fn(
21631 folder: PathBuf,
21632 frontier: PathBuf,
21633 backend: Option<String>,
21634 dry_run: bool,
21635 json: bool,
21636) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21637
21638static SCOUT_HANDLER: OnceLock<ScoutHandler> = OnceLock::new();
21639
21640pub fn register_scout_handler(handler: ScoutHandler) {
21644 let _ = SCOUT_HANDLER.set(handler);
21645}
21646
21647pub type AtlasInitHandler = fn(
21651 atlases_root: PathBuf,
21652 name: String,
21653 domain: String,
21654 scope_note: Option<String>,
21655 frontiers: Vec<PathBuf>,
21656 json: bool,
21657) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21658
21659static ATLAS_INIT_HANDLER: OnceLock<AtlasInitHandler> = OnceLock::new();
21660
21661pub fn register_atlas_init_handler(handler: AtlasInitHandler) {
21662 let _ = ATLAS_INIT_HANDLER.set(handler);
21663}
21664
21665pub type SearchBuildHandler = fn(
21667 frontiers: Vec<PathBuf>,
21668 out: PathBuf,
21669 include_bootstrap: bool,
21670 include_broken: bool,
21671 json: bool,
21672) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21673
21674static SEARCH_BUILD_HANDLER: OnceLock<SearchBuildHandler> = OnceLock::new();
21675
21676pub fn register_search_build_handler(handler: SearchBuildHandler) {
21677 let _ = SEARCH_BUILD_HANDLER.set(handler);
21678}
21679
21680#[allow(clippy::too_many_arguments)]
21682pub type SearchQueryHandler = fn(
21683 query: String,
21684 index: Option<PathBuf>,
21685 kind: Option<String>,
21686 entity: Option<String>,
21687 status: Option<String>,
21688 frontier_id: Option<String>,
21689 source_id: Option<String>,
21690 chain_status: Option<String>,
21691 limit: Option<usize>,
21692 json: bool,
21693) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21694
21695static SEARCH_QUERY_HANDLER: OnceLock<SearchQueryHandler> = OnceLock::new();
21696
21697pub fn register_search_query_handler(handler: SearchQueryHandler) {
21698 let _ = SEARCH_QUERY_HANDLER.set(handler);
21699}
21700
21701pub type AtlasMaterializeHandler =
21703 fn(atlases_root: PathBuf, name: String, json: bool) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21704
21705static ATLAS_MATERIALIZE_HANDLER: OnceLock<AtlasMaterializeHandler> = OnceLock::new();
21706
21707pub fn register_atlas_materialize_handler(handler: AtlasMaterializeHandler) {
21708 let _ = ATLAS_MATERIALIZE_HANDLER.set(handler);
21709}
21710
21711pub type AtlasServeHandler = fn(
21716 atlases_root: PathBuf,
21717 name: String,
21718 port: u16,
21719 open_browser: bool,
21720) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21721
21722static ATLAS_SERVE_HANDLER: OnceLock<AtlasServeHandler> = OnceLock::new();
21723
21724pub fn register_atlas_serve_handler(handler: AtlasServeHandler) {
21725 let _ = ATLAS_SERVE_HANDLER.set(handler);
21726}
21727
21728pub type AtlasUpdateHandler = fn(
21733 atlases_root: PathBuf,
21734 name: String,
21735 add_frontier: Vec<PathBuf>,
21736 remove_vfr_id: Vec<String>,
21737 json: bool,
21738) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21739
21740static ATLAS_UPDATE_HANDLER: OnceLock<AtlasUpdateHandler> = OnceLock::new();
21741
21742pub fn register_atlas_update_handler(handler: AtlasUpdateHandler) {
21743 let _ = ATLAS_UPDATE_HANDLER.set(handler);
21744}
21745
21746pub type ConstellationInitHandler = fn(
21750 constellations_root: PathBuf,
21751 name: String,
21752 scope_note: Option<String>,
21753 atlases: Vec<PathBuf>,
21754 json: bool,
21755) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21756
21757static CONSTELLATION_INIT_HANDLER: OnceLock<ConstellationInitHandler> = OnceLock::new();
21758
21759pub fn register_constellation_init_handler(handler: ConstellationInitHandler) {
21760 let _ = CONSTELLATION_INIT_HANDLER.set(handler);
21761}
21762
21763pub type ConstellationMaterializeHandler = fn(
21764 constellations_root: PathBuf,
21765 name: String,
21766 json: bool,
21767) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21768
21769static CONSTELLATION_MATERIALIZE_HANDLER: OnceLock<ConstellationMaterializeHandler> =
21770 OnceLock::new();
21771
21772pub fn register_constellation_materialize_handler(handler: ConstellationMaterializeHandler) {
21773 let _ = CONSTELLATION_MATERIALIZE_HANDLER.set(handler);
21774}
21775
21776pub type ConstellationServeHandler = fn(
21777 constellations_root: PathBuf,
21778 name: String,
21779 port: u16,
21780 open_browser: bool,
21781) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21782
21783static CONSTELLATION_SERVE_HANDLER: OnceLock<ConstellationServeHandler> = OnceLock::new();
21784
21785pub fn register_constellation_serve_handler(handler: ConstellationServeHandler) {
21786 let _ = CONSTELLATION_SERVE_HANDLER.set(handler);
21787}
21788
21789pub type NotesHandler = fn(
21793 vault: PathBuf,
21794 frontier: PathBuf,
21795 backend: Option<String>,
21796 max_files: Option<usize>,
21797 max_items_per_category: Option<usize>,
21798 dry_run: bool,
21799 json: bool,
21800) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21801
21802static NOTES_HANDLER: OnceLock<NotesHandler> = OnceLock::new();
21803
21804pub fn register_notes_handler(handler: NotesHandler) {
21806 let _ = NOTES_HANDLER.set(handler);
21807}
21808
21809pub type CodeHandler = fn(
21811 root: PathBuf,
21812 frontier: PathBuf,
21813 backend: Option<String>,
21814 max_files: Option<usize>,
21815 dry_run: bool,
21816 json: bool,
21817) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21818
21819static CODE_HANDLER: OnceLock<CodeHandler> = OnceLock::new();
21820
21821pub fn register_code_handler(handler: CodeHandler) {
21823 let _ = CODE_HANDLER.set(handler);
21824}
21825
21826pub type DatasetsHandler = fn(
21828 root: PathBuf,
21829 frontier: PathBuf,
21830 backend: Option<String>,
21831 sample_rows: Option<usize>,
21832 dry_run: bool,
21833 json: bool,
21834) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21835
21836static DATASETS_HANDLER: OnceLock<DatasetsHandler> = OnceLock::new();
21837
21838pub fn register_datasets_handler(handler: DatasetsHandler) {
21840 let _ = DATASETS_HANDLER.set(handler);
21841}
21842
21843pub type ReviewerHandler = fn(
21845 frontier: PathBuf,
21846 backend: Option<String>,
21847 max_proposals: Option<usize>,
21848 batch_size: usize,
21849 dry_run: bool,
21850 json: bool,
21851) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21852
21853static REVIEWER_HANDLER: OnceLock<ReviewerHandler> = OnceLock::new();
21854
21855pub fn register_reviewer_handler(handler: ReviewerHandler) {
21857 let _ = REVIEWER_HANDLER.set(handler);
21858}
21859
21860pub type TensionsHandler = fn(
21862 frontier: PathBuf,
21863 backend: Option<String>,
21864 max_findings: Option<usize>,
21865 dry_run: bool,
21866 json: bool,
21867) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21868
21869static TENSIONS_HANDLER: OnceLock<TensionsHandler> = OnceLock::new();
21870
21871pub fn register_tensions_handler(handler: TensionsHandler) {
21873 let _ = TENSIONS_HANDLER.set(handler);
21874}
21875
21876pub type ExperimentsHandler = fn(
21878 frontier: PathBuf,
21879 backend: Option<String>,
21880 max_findings: Option<usize>,
21881 dry_run: bool,
21882 json: bool,
21883) -> Pin<Box<dyn Future<Output = ()> + Send>>;
21884
21885static EXPERIMENTS_HANDLER: OnceLock<ExperimentsHandler> = OnceLock::new();
21886
21887pub fn register_experiments_handler(handler: ExperimentsHandler) {
21889 let _ = EXPERIMENTS_HANDLER.set(handler);
21890}
21891
21892fn find_vela_repo() -> Option<PathBuf> {
21908 let mut cur = std::env::current_dir().ok()?;
21909 loop {
21910 if cur.join(".vela").is_dir() {
21911 return Some(cur);
21912 }
21913 if !cur.pop() {
21914 return None;
21915 }
21916 }
21917}
21918
21919fn print_session_help() {
21920 println!();
21921 println!(
21922 " Vela {} · Version control for scientific state.",
21923 env!("CARGO_PKG_VERSION")
21924 );
21925 println!();
21926 println!(" USAGE");
21927 println!(" vela Open a session against the nearest .vela/ repo");
21928 println!(" vela <command> Run a specific subcommand");
21929 println!(" vela help advanced Full subcommand list (30+ commands)");
21930 println!();
21931 println!(" CORE FLOW (v0.74)");
21932 println!(" init Initialize a split frontier repo");
21933 println!(" ingest <path> Ingest a paper, dataset, or Carina packet");
21934 println!(" propose Create a finding.review proposal");
21935 println!(" diff <vpr_id> Preview a pending proposal vs current frontier");
21936 println!(" accept <vpr_id> Apply a proposal under reviewer authority");
21937 println!(" attest Sign findings under your private key");
21938 println!(" log Recent canonical state events");
21939 println!(" lineage <vf_id> State-transition replay for one finding");
21940 println!(" serve Local Workbench (find, evidence, diff, lineage)");
21941 println!();
21942 println!(" DAILY ALSO-RANS");
21943 println!(" status One-screen frontier health");
21944 println!(" inbox Pending review proposals");
21945 println!(" review Review a proposal interactively");
21946 println!(" ask <question> Plain-text query against the frontier");
21947 println!();
21948 println!(" REASONING (Pearl 1 → 2 → 3)");
21949 println!(" causal audit Per-finding identifiability");
21950 println!(" causal effect <src> --on <tgt> Pairwise back-door / front-door");
21951 println!(" causal counterfactual <src> --target <tgt> --set-to <0..1>");
21952 println!();
21953 println!(" COMPOSITION");
21954 println!(" bridge <a> <b> Cross-frontier hypotheses");
21955 println!(" consensus <vf> Field consensus over similar claims");
21956 println!();
21957 println!(" PUBLISH");
21958 println!(" registry publish Push a signed manifest to the hub");
21959 println!(" federation peer-add Federate with another hub");
21960 println!();
21961 println!(" In session, type a single letter for a quick verb, or any");
21962 println!(" question in plain text. `q` or `exit` quits.");
21963 println!();
21964}
21965
21966fn print_session_dashboard(project: &crate::project::Project, repo_path: &Path) {
21967 use crate::causal_reasoning::{audit_frontier, summarize_audit};
21968
21969 let label = frontier_label(project);
21970 let vfr = project.frontier_id();
21971 let vfr_short = vfr.chars().take(16).collect::<String>();
21972
21973 let mut pending = 0usize;
21974 let mut by_kind: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
21975 for p in &project.proposals {
21976 if p.status == "pending_review" {
21977 pending += 1;
21978 *by_kind.entry(p.kind.clone()).or_insert(0) += 1;
21979 }
21980 }
21981
21982 let audit = audit_frontier(project);
21983 let audit_summary = summarize_audit(&audit);
21984
21985 let bridges_dir = repo_path.join(".vela/bridges");
21986 let mut bridge_total = 0usize;
21987 let mut bridge_confirmed = 0usize;
21988 let mut bridge_derived = 0usize;
21989 if bridges_dir.is_dir()
21990 && let Ok(entries) = std::fs::read_dir(&bridges_dir)
21991 {
21992 for entry in entries.flatten() {
21993 let path = entry.path();
21994 if path.extension().and_then(|s| s.to_str()) != Some("json") {
21995 continue;
21996 }
21997 bridge_total += 1;
21998 if let Ok(data) = std::fs::read_to_string(&path)
21999 && let Ok(b) = serde_json::from_str::<crate::bridge::Bridge>(&data)
22000 {
22001 match b.status {
22002 crate::bridge::BridgeStatus::Confirmed => bridge_confirmed += 1,
22003 crate::bridge::BridgeStatus::Derived => bridge_derived += 1,
22004 _ => {}
22005 }
22006 }
22007 }
22008 }
22009
22010 let mut targets_with_success = std::collections::HashSet::new();
22011 let mut failed_replications = 0usize;
22012 for r in &project.replications {
22013 if r.outcome == "replicated" {
22014 targets_with_success.insert(r.target_finding.clone());
22015 } else if r.outcome == "failed" {
22016 failed_replications += 1;
22017 }
22018 }
22019
22020 println!();
22021 let version = crate::project::VELA_COMPILER_VERSION
22022 .strip_prefix("vela/")
22023 .unwrap_or(crate::project::VELA_COMPILER_VERSION);
22024 println!(
22025 " {}",
22026 format!("VELA · {version} · {label}")
22027 .to_uppercase()
22028 .dimmed()
22029 );
22030 println!(" {}", style::tick_row(60));
22031 println!(
22032 " vfr_id {}… repo {}",
22033 vfr_short,
22034 repo_path.display()
22035 );
22036 println!(
22037 " findings {:>4} events {} proposals pending {}",
22038 project.findings.len(),
22039 project.events.len(),
22040 pending
22041 );
22042
22043 if pending > 0 {
22044 let parts: Vec<String> = by_kind.iter().map(|(k, n)| format!("{n} {k}")).collect();
22045 println!(" {} · {}", style::warn("inbox"), parts.join(" "));
22046 }
22047 if audit_summary.underidentified > 0 || audit_summary.conditional > 0 {
22048 println!(
22049 " {} · {} underidentified · {} conditional",
22050 if audit_summary.underidentified > 0 {
22051 style::lost("audit")
22052 } else {
22053 style::warn("audit")
22054 },
22055 audit_summary.underidentified,
22056 audit_summary.conditional,
22057 );
22058 }
22059 if bridge_total > 0 {
22060 println!(
22061 " {} · {} total · {} confirmed · {} awaiting review",
22062 style::ok("bridges"),
22063 bridge_total,
22064 bridge_confirmed,
22065 bridge_derived
22066 );
22067 }
22068 if !project.replications.is_empty() {
22069 println!(
22070 " {} · {} records · {} findings replicated · {} failed",
22071 style::ok("replications"),
22072 project.replications.len(),
22073 targets_with_success.len(),
22074 failed_replications,
22075 );
22076 }
22077
22078 println!();
22079 println!(" type a verb or ask anything:");
22080 println!(" a audit problems i inbox (pending) b bridges");
22081 println!(" g causal graph l log (recent) c counterfactuals");
22082 println!(" s refresh status h help (more verbs) q quit");
22083 println!();
22084}
22085
22086fn run_session_verb(verb: &str, repo_path: &Path) -> bool {
22088 match verb {
22089 "a" | "audit" => {
22090 let action = CausalAction::Audit {
22091 frontier: repo_path.to_path_buf(),
22092 problems_only: true,
22093 json: false,
22094 };
22095 cmd_causal(action);
22096 true
22097 }
22098 "i" | "inbox" => {
22099 let action = ProposalAction::List {
22100 frontier: repo_path.to_path_buf(),
22101 status: Some("pending_review".into()),
22102 json: false,
22103 };
22104 cmd_proposals(action);
22105 true
22106 }
22107 "b" | "bridges" => {
22108 let action = BridgesAction::List {
22109 frontier: repo_path.to_path_buf(),
22110 status: None,
22111 json: false,
22112 };
22113 cmd_bridges(action);
22114 true
22115 }
22116 "g" | "graph" => {
22117 let action = CausalAction::Graph {
22118 frontier: repo_path.to_path_buf(),
22119 node: None,
22120 json: false,
22121 };
22122 cmd_causal(action);
22123 true
22124 }
22125 "l" | "log" => {
22126 cmd_log(repo_path, 10, None, false);
22127 true
22128 }
22129 "c" | "counterfactual" | "counterfactuals" => {
22130 let project = match repo::load_from_path(repo_path) {
22133 Ok(p) => p,
22134 Err(e) => {
22135 eprintln!("{} {e}", style::err_prefix());
22136 return true;
22137 }
22138 };
22139 println!();
22140 println!(" {}", "VELA · COUNTERFACTUAL · LIVE PAIRS".dimmed());
22141 println!(" {}", style::tick_row(60));
22142 let mut pairs = 0usize;
22146 for child in &project.findings {
22147 for link in &child.links {
22148 if !matches!(link.link_type.as_str(), "depends" | "supports") {
22149 continue;
22150 }
22151 if link.mechanism.is_none() {
22152 continue;
22153 }
22154 let parent = link
22155 .target
22156 .split_once(':')
22157 .map_or(link.target.as_str(), |(_, r)| r);
22158 pairs += 1;
22159 if pairs <= 10 {
22160 println!(" · do({parent}) → {}", child.id);
22161 }
22162 }
22163 }
22164 if pairs == 0 {
22165 println!(" no mechanism-annotated edges found.");
22166 println!(" add a mechanism via the link's `mechanism` field; see /counterfactual");
22167 } else {
22168 println!();
22169 println!(" {pairs} live pair(s). Run with:");
22170 println!(" vela causal counterfactual <repo> <src> --target <tgt> --set-to 0.5");
22171 }
22172 println!();
22173 true
22174 }
22175 "s" | "status" | "refresh" => {
22176 match repo::load_from_path(repo_path) {
22178 Ok(p) => print_session_dashboard(&p, repo_path),
22179 Err(e) => eprintln!("{} {e}", style::err_prefix()),
22180 }
22181 true
22182 }
22183 "h" | "help" | "?" => {
22184 print_session_help();
22185 true
22186 }
22187 _ => false,
22188 }
22189}
22190
22191fn run_session() {
22192 let repo_path = match find_vela_repo() {
22193 Some(p) => p,
22194 None => {
22195 println!();
22196 println!(
22197 " {}",
22198 "VELA · NO FRONTIER FOUND IN CWD OR ANY PARENT".dimmed()
22199 );
22200 println!(" {}", style::tick_row(60));
22201 println!(" Run `vela init` here to create a frontier, or cd into one.");
22202 println!(" Or run `vela help` for the command list.");
22203 println!();
22204 return;
22205 }
22206 };
22207
22208 let project = match repo::load_from_path(&repo_path) {
22209 Ok(p) => p,
22210 Err(e) => {
22211 eprintln!("{} failed to load .vela/ repo: {e}", style::err_prefix());
22212 std::process::exit(1);
22213 }
22214 };
22215
22216 print_session_dashboard(&project, &repo_path);
22217
22218 use std::io::{BufRead, Write};
22219 let stdin = std::io::stdin();
22220 let mut stdout = std::io::stdout();
22221 loop {
22222 print!(" > ");
22223 stdout.flush().ok();
22224 let mut line = String::new();
22225 if stdin.lock().read_line(&mut line).is_err() {
22226 break;
22227 }
22228 let input = line.trim();
22229 if input.is_empty() {
22230 continue;
22231 }
22232 if matches!(input, "q" | "quit" | "exit") {
22233 break;
22234 }
22235 if run_session_verb(input, &repo_path) {
22236 continue;
22237 }
22238 let project = match repo::load_from_path(&repo_path) {
22240 Ok(p) => p,
22241 Err(e) => {
22242 eprintln!("{} {e}", style::err_prefix());
22243 continue;
22244 }
22245 };
22246 answer(&project, input, false);
22247 }
22248}
22249
22250pub fn run_from_args() {
22251 style::init();
22252 let args = std::env::args().collect::<Vec<_>>();
22253 match args.get(1).map(String::as_str) {
22254 None => {
22258 run_session();
22259 return;
22260 }
22261 Some("-h" | "--help" | "help") => {
22262 if args.get(2).map(String::as_str) == Some("advanced") {
22265 print_strict_help();
22266 } else {
22267 print_session_help();
22268 }
22269 return;
22270 }
22271 Some("-V" | "--version" | "version") => {
22272 println!("vela {}", env!("CARGO_PKG_VERSION"));
22273 return;
22274 }
22275 Some("proof") if args.get(2).map(String::as_str) == Some("verify") => {
22276 let json = args.iter().any(|arg| arg == "--json");
22277 let frontier = args
22278 .iter()
22279 .skip(3)
22280 .find(|arg| !arg.starts_with('-'))
22281 .map(PathBuf::from)
22282 .unwrap_or_else(|| {
22283 eprintln!(
22284 "{} proof verify requires a frontier repo",
22285 style::err_prefix()
22286 );
22287 std::process::exit(2);
22288 });
22289 cmd_proof_verify(&frontier, json);
22290 return;
22291 }
22292 Some("proof") if args.get(2).map(String::as_str) == Some("explain") => {
22293 let frontier = args
22294 .iter()
22295 .skip(3)
22296 .find(|arg| !arg.starts_with('-'))
22297 .map(PathBuf::from)
22298 .unwrap_or_else(|| {
22299 eprintln!(
22300 "{} proof explain requires a frontier repo",
22301 style::err_prefix()
22302 );
22303 std::process::exit(2);
22304 });
22305 cmd_proof_explain(&frontier);
22306 return;
22307 }
22308 Some(cmd) if !is_science_subcommand(cmd) => {
22309 eprintln!(
22310 "{} unknown or non-release command: {cmd}",
22311 style::err_prefix()
22312 );
22313 eprintln!("run `vela --help` for the strict v0 command surface.");
22314 std::process::exit(2);
22315 }
22316 Some(_) => {}
22317 }
22318 let runtime = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
22319 runtime.block_on(run_command());
22320}
22321
22322fn fail(message: &str) -> ! {
22323 eprintln!("{} {message}", style::err_prefix());
22324 std::process::exit(1);
22325}
22326
22327fn validate_enum_arg(flag: &str, value: &str, valid: &[&str]) {
22332 if !valid.contains(&value) {
22333 fail(&format!(
22334 "invalid {flag} '{value}'. Valid: {}",
22335 valid.join(", ")
22336 ));
22337 }
22338}
22339
22340fn fail_return<T>(message: &str) -> T {
22341 fail(message)
22342}