Skip to main content

vela_protocol/
cli.rs

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    /// v0.22 Agent Inbox: run Literature Scout against a folder of
33    /// PDFs. Each candidate finding becomes a `finding.add`
34    /// `StateProposal` tagged with the scout's `AgentRun`, written
35    /// to the frontier's `proposals` array. Reviewers accept or
36    /// reject in the Workbench Inbox; nothing becomes a canonical
37    /// finding without a signed accept.
38    Scout {
39        /// Folder of PDFs to read.
40        folder: PathBuf,
41        /// Frontier file the proposals are appended to.
42        #[arg(long)]
43        frontier: PathBuf,
44        /// LLM backend override (matches `vela ingest --backend`).
45        #[arg(short, long)]
46        backend: Option<String>,
47        /// Preview without writing to the frontier file.
48        #[arg(long)]
49        dry_run: bool,
50        /// Output stable JSON for programmatic callers.
51        #[arg(long)]
52        json: bool,
53    },
54    /// v0.23 Agent Inbox: run Notes Compiler against a folder of
55    /// Markdown / Obsidian notes. Each open question, hypothesis,
56    /// candidate finding, or tension becomes a `finding.add`
57    /// `StateProposal` tagged with the compiler's `AgentRun`,
58    /// written to the frontier's `proposals` array. Same review
59    /// loop as Literature Scout.
60    CompileNotes {
61        /// Vault or folder of Markdown notes to read.
62        vault: PathBuf,
63        /// Frontier file the proposals are appended to.
64        #[arg(long)]
65        frontier: PathBuf,
66        /// Optional model alias (`sonnet`, `opus`, …).
67        #[arg(short, long)]
68        backend: Option<String>,
69        /// Cap on files processed (default 50).
70        #[arg(long)]
71        max_files: Option<usize>,
72        /// Per-note cap on items emitted in *each* category
73        /// (open_questions / hypotheses / candidate_findings /
74        /// tensions). Default 4. Trims the strongest items the model
75        /// returns so dense notes don't drown the Inbox.
76        #[arg(long)]
77        max_items_per_category: Option<usize>,
78        /// Preview without writing to the frontier file.
79        #[arg(long)]
80        dry_run: bool,
81        /// Output stable JSON for programmatic callers.
82        #[arg(long)]
83        json: bool,
84    },
85    /// v0.24 Agent Inbox: run Code & Notebook Analyst against a
86    /// research repo (Jupyter `.ipynb`, Python / R / Julia / Quarto
87    /// / Rmd scripts). Each analysis, code-derived finding, or
88    /// experiment intent becomes a `finding.add` `StateProposal`
89    /// tagged with the analyst's `AgentRun`. Same review loop.
90    CompileCode {
91        /// Repo / folder root to walk.
92        root: PathBuf,
93        /// Frontier file the proposals are appended to.
94        #[arg(long)]
95        frontier: PathBuf,
96        /// Optional model alias (`sonnet`, `opus`, …).
97        #[arg(short, long)]
98        backend: Option<String>,
99        /// Cap on files processed (default 30).
100        #[arg(long)]
101        max_files: Option<usize>,
102        /// Preview without writing to the frontier file.
103        #[arg(long)]
104        dry_run: bool,
105        /// Output stable JSON for programmatic callers.
106        #[arg(long)]
107        json: bool,
108    },
109    /// v0.28 Agent Inbox: run Reviewer Agent against a frontier's
110    /// pending proposals. Each scored proposal gets a
111    /// `finding.note` proposal attached with plausibility +
112    /// evidence + scope + duplicate-risk scores so reviewers can
113    /// triage faster.
114    ReviewPending {
115        #[arg(long)]
116        frontier: PathBuf,
117        #[arg(short, long)]
118        backend: Option<String>,
119        #[arg(long)]
120        max_proposals: Option<usize>,
121        /// Number of proposals scored per `claude -p` call.
122        /// 1 = per-proposal mode (full transcript). 5–10 = ~5×
123        /// faster wall-clock, single response covers the batch.
124        /// Capped at 12 internally.
125        #[arg(long, default_value = "1")]
126        batch_size: usize,
127        #[arg(long)]
128        dry_run: bool,
129        #[arg(long)]
130        json: bool,
131    },
132    /// v0.28 Agent Inbox: run Contradiction Finder against a
133    /// frontier's findings. Pairs that contradict get emitted as
134    /// `tension`-typed `finding.add` proposals.
135    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    /// v0.28 Agent Inbox: run Experiment Planner against a
148    /// frontier's open questions and hypotheses. Each gets 1–3
149    /// `experiment_intent`-typed `finding.add` proposals.
150    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    /// v0.25 Agent Inbox: run Datasets agent against a folder of
163    /// CSV / TSV files. Each dataset gets a summary
164    /// proposal + optional supported-claim proposals tagged with
165    /// the agent's `AgentRun`. Same review loop.
166    CompileData {
167        /// Folder root to walk (top level only in v0.25).
168        root: PathBuf,
169        /// Frontier file the proposals are appended to.
170        #[arg(long)]
171        frontier: PathBuf,
172        /// Optional model alias (`sonnet`, `opus`, …).
173        #[arg(short, long)]
174        backend: Option<String>,
175        /// Sample rows sent to the model per dataset (default 50).
176        #[arg(long)]
177        sample_rows: Option<usize>,
178        /// Preview without writing to the frontier file.
179        #[arg(long)]
180        dry_run: bool,
181        /// Output stable JSON for programmatic callers.
182        #[arg(long)]
183        json: bool,
184    },
185    /// Check frontier quality and proof readiness
186    Check {
187        /// Frontier JSON file, Vela repo, or proof packet
188        source: Option<PathBuf>,
189        /// Run schema validation
190        #[arg(long)]
191        schema: bool,
192        /// Run frontier lint checks
193        #[arg(long)]
194        stats: bool,
195        /// Run conformance vectors
196        #[arg(long)]
197        conformance: bool,
198        /// Conformance test directory
199        #[arg(long, default_value = "tests/conformance")]
200        conformance_dir: PathBuf,
201        /// Run all checks
202        #[arg(long)]
203        all: bool,
204        /// Run only structural schema validation
205        #[arg(long)]
206        schema_only: bool,
207        /// Treat warnings and blocking signals as failures
208        #[arg(long)]
209        strict: bool,
210        /// Show fix suggestions
211        #[arg(long)]
212        fix: bool,
213        /// Output stable JSON
214        #[arg(long)]
215        json: bool,
216    },
217    /// Check structural integrity of accepted frontier state
218    Integrity {
219        /// Frontier JSON file or Vela repo
220        frontier: PathBuf,
221        /// Output stable JSON
222        #[arg(long)]
223        json: bool,
224    },
225    /// Report downstream impact for one finding without mutating state
226    Impact {
227        /// Frontier JSON file or Vela repo
228        frontier: PathBuf,
229        /// Finding id to inspect
230        finding_id: String,
231        /// Maximum dependency depth
232        #[arg(long)]
233        depth: Option<usize>,
234        /// Output stable JSON
235        #[arg(long)]
236        json: bool,
237    },
238    /// v0.95: Aggregate discord report across every finding in the
239    /// frontier. Runs the v0.83 detectors (`evidence_gap`,
240    /// `provenance_fragile`, `status_divergent`) over the live event
241    /// log and reports the support set. Useful for surfacing
242    /// retraction-fragile claims, missing-evidence findings, and
243    /// drift between on-disk flags and substrate-derived BelnapStatus.
244    Discord {
245        /// Frontier JSON file or Vela repo
246        frontier: PathBuf,
247        /// Output stable JSON
248        #[arg(long)]
249        json: bool,
250        /// Filter to a single discord kind (e.g.
251        /// `provenance_fragile`, `evidence_gap`, `status_divergent`).
252        /// When omitted, all kinds are included.
253        #[arg(long)]
254        kind: Option<String>,
255    },
256    /// Normalize deterministic frontier state without changing claims
257    Normalize {
258        /// Frontier JSON file or Vela repo
259        source: PathBuf,
260        /// Output normalized frontier copy
261        #[arg(short, long)]
262        out: Option<PathBuf>,
263        /// Write changes back to the input
264        #[arg(long)]
265        write: bool,
266        /// Force dry-run
267        #[arg(long)]
268        dry_run: bool,
269        /// Rewrite finding IDs to content addresses and update links
270        #[arg(long)]
271        rewrite_ids: bool,
272        /// Write old-to-new ID map when rewriting IDs
273        #[arg(long)]
274        id_map: Option<PathBuf>,
275        /// Phase N: regenerate finding.provenance fields (title, year,
276        /// journal, authors, license, publisher, funders) from the
277        /// canonical SourceRecord matched by DOI / PMID / title.
278        #[arg(long)]
279        resync_provenance: bool,
280        /// Output stable JSON
281        #[arg(long)]
282        json: bool,
283    },
284    /// Export and validate a proof packet
285    Proof {
286        /// Frontier JSON file or Vela repo
287        frontier: PathBuf,
288        /// Output proof packet directory
289        #[arg(long, short = 'o', default_value = "proof-packet")]
290        out: PathBuf,
291        /// Proof packet template
292        #[arg(long, default_value = "bbb-alzheimer")]
293        template: String,
294        /// Optional benchmark suite to include
295        #[arg(long)]
296        gold: Option<PathBuf>,
297        /// Record latest proof packet state back into the input frontier
298        #[arg(long)]
299        record_proof_state: bool,
300        /// Output stable JSON
301        #[arg(long)]
302        json: bool,
303    },
304    /// Inspect a split frontier repository as a state machine
305    Repo {
306        #[command(subcommand)]
307        action: RepoAction,
308    },
309    /// Serve a read-only frontier over MCP stdio or HTTP
310    Serve {
311        /// Frontier JSON file or Vela repo
312        #[arg(required_unless_present_any = ["frontiers", "setup"])]
313        frontier: Option<PathBuf>,
314        /// Directory of frontier files
315        #[arg(long)]
316        frontiers: Option<PathBuf>,
317        /// LLM backend reserved for future optional tools
318        #[arg(short, long)]
319        backend: Option<String>,
320        /// Run an HTTP server on this port instead of MCP stdio
321        #[arg(long)]
322        http: Option<u16>,
323        /// Print MCP setup instructions
324        #[arg(long)]
325        setup: bool,
326        /// Validate public tool contracts and exit
327        #[arg(long)]
328        check_tools: bool,
329        /// Output stable JSON for --check-tools
330        #[arg(long)]
331        json: bool,
332        /// Serve the local Workbench web UI (`web/`) alongside the
333        /// HTTP API. Implies `--http` if no port is specified
334        /// (default 3848). Phase R, v0.5.
335        #[arg(long)]
336        workbench: bool,
337    },
338    /// v0.42: Show what's pending right now — the daily-driver
339    /// equivalent of `git status`. One screen: counts, the inbox,
340    /// the audit, the federation health. Read in two seconds.
341    Status {
342        frontier: PathBuf,
343        /// Output stable JSON for programmatic callers.
344        #[arg(long)]
345        json: bool,
346    },
347    /// v0.42: Recent canonical events in human-readable form. The
348    /// `git log` analogue. Default newest-first; cap on count.
349    Log {
350        frontier: PathBuf,
351        /// How many recent events to show.
352        #[arg(long, default_value = "20")]
353        limit: usize,
354        /// Filter to events matching this kind (substring match).
355        #[arg(long)]
356        kind: Option<String>,
357        /// Output stable JSON.
358        #[arg(long)]
359        json: bool,
360    },
361    /// v0.42: Triage list of pending proposals. What you sit down to
362    /// review. Reviewer-agent scores surface where present; flagged
363    /// items rise to the top.
364    Inbox {
365        frontier: PathBuf,
366        /// Show only proposals matching this kind (substring match).
367        #[arg(long)]
368        kind: Option<String>,
369        /// Cap on entries shown.
370        #[arg(long, default_value = "30")]
371        limit: usize,
372        /// Output stable JSON.
373        #[arg(long)]
374        json: bool,
375    },
376    /// v0.42: Conversational substrate access. Type a natural-language
377    /// question; the substrate routes it to a structured query and
378    /// renders the answer. No agent in the loop — kernel queries only.
379    /// Codex-flavored REPL that doesn't pretend to be an agent.
380    Ask {
381        frontier: PathBuf,
382        /// The question. If omitted, drops into a REPL.
383        #[arg(trailing_var_arg = true)]
384        question: Vec<String>,
385        /// Output stable JSON when the answer has structure.
386        #[arg(long)]
387        json: bool,
388    },
389    /// Show frontier statistics
390    Stats {
391        /// Frontier JSON file, Vela repo, or packet
392        frontier: PathBuf,
393        /// Output stable JSON
394        #[arg(long)]
395        json: bool,
396    },
397    /// Search findings
398    Search {
399        /// Search query
400        query: String,
401        /// Frontier JSON file, Vela repo, or packet
402        #[arg(long)]
403        source: Option<PathBuf>,
404        /// Filter by entity
405        #[arg(long)]
406        entity: Option<String>,
407        /// Filter by assertion type
408        #[arg(long)]
409        r#type: Option<String>,
410        /// Search every frontier in a directory
411        #[arg(long)]
412        all: Option<PathBuf>,
413        /// Maximum results
414        #[arg(long, default_value = "20")]
415        limit: usize,
416        /// Output stable JSON
417        #[arg(long)]
418        json: bool,
419    },
420    /// List candidate contradictions and tensions
421    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    /// Inspect and rank candidate gap review leads
433    Gaps {
434        #[command(subcommand)]
435        action: GapsAction,
436    },
437    /// Find candidate cross-domain connections
438    Bridge {
439        /// Input frontier JSON files or Vela repos
440        #[arg(required = true)]
441        inputs: Vec<PathBuf>,
442        /// Run rough PubMed prior-art checks for top bridges
443        #[arg(long, default_value = "true", action = clap::ArgAction::Set)]
444        novelty: bool,
445        /// Max bridges to check
446        #[arg(long, default_value = "30")]
447        top: usize,
448    },
449    /// Export frontier artifacts
450    Export {
451        frontier: PathBuf,
452        #[arg(short, long, default_value = "csv")]
453        format: String,
454        #[arg(short, long)]
455        output: Option<PathBuf>,
456    },
457    /// Inspect or validate proof packets
458    Packet {
459        #[command(subcommand)]
460        action: PacketAction,
461    },
462    /// Recompute SHA-256 over every file in a proof packet, compare to
463    /// the manifest, and validate the proof-trace chain. Friendlier
464    /// alias for `vela packet validate <path>` — same code path, same
465    /// guarantee. Use this when you've pulled a packet from someone
466    /// else and want one command that says "yes, this is what they
467    /// signed, byte for byte."
468    Verify {
469        /// Path to the proof packet directory (the one with manifest.json)
470        path: PathBuf,
471        #[arg(long)]
472        json: bool,
473    },
474    /// Run deterministic benchmark gates.
475    ///
476    /// Two modes:
477    ///   - **legacy** (extraction quality): `--gold <gold.json>`
478    ///     against an extracted-findings frontier. Pre-v0.26
479    ///     behaviour, unchanged.
480    ///   - **v0.26 VelaBench** (agent state-update scoring): pass
481    ///     `--candidate <frontier.json>` together with `--gold`
482    ///     to compare a candidate frontier (typically agent-
483    ///     generated) against a curator-validated gold. Composite
484    ///     score with optional `--threshold` for CI gating.
485    Bench {
486        /// Frontier file for single-task benchmark (legacy mode).
487        frontier: Option<PathBuf>,
488        /// Gold frontier (used by both modes).
489        #[arg(long)]
490        gold: Option<PathBuf>,
491        /// v0.26: Candidate frontier to score against `--gold`.
492        /// Presence of this flag selects VelaBench (agent state-
493        /// update scoring) instead of the legacy extraction harness.
494        #[arg(long)]
495        candidate: Option<PathBuf>,
496        /// v0.26: Optional source-files directory for
497        /// `evidence_fidelity` checks. Without it, that metric is
498        /// dropped from the composite (weights rebalanced).
499        #[arg(long)]
500        sources: Option<PathBuf>,
501        /// v0.26: Composite-score threshold; non-zero exit if
502        /// composite < threshold. Default 0.0 (report only).
503        #[arg(long)]
504        threshold: Option<f64>,
505        /// v0.26: Write the JSON report to this path in addition
506        /// to printing.
507        #[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    /// Run protocol conformance vectors
529    Conformance {
530        #[arg(default_value = "tests/conformance")]
531        dir: PathBuf,
532    },
533    /// Show version information
534    Version,
535    /// Optional signing and signature verification
536    Sign {
537        #[command(subcommand)]
538        action: SignAction,
539    },
540    /// Manage the frontier's registered actor identities (Phase M, v0.4)
541    Actor {
542        #[command(subcommand)]
543        action: ActorAction,
544    },
545    /// v0.39: Manage the frontier's federation peer registry. A peer
546    /// is another hub this frontier knows about — id, HTTPS URL, and
547    /// the Ed25519 pubkey they sign manifests with. Adding a peer
548    /// declares awareness; the actual sync runtime ships in v0.39.1+.
549    Federation {
550        #[command(subcommand)]
551        action: FederationAction,
552    },
553    /// v0.40: Causal reasoning over the schema landed in v0.38. Audits
554    /// every finding for identifiability: does the declared
555    /// study-design grade actually support the causal claim being
556    /// made? Surfaces underidentified findings (intervention from
557    /// observational) and conditional ones (intervention from
558    /// quasi-experimental designs that need explicit assumptions).
559    Causal {
560        #[command(subcommand)]
561        action: CausalAction,
562    },
563    /// Manage frontier-level metadata: cross-frontier dependencies (v0.8).
564    /// Use `vela frontier add-dep` to declare a remote frontier this
565    /// frontier links into via `vf_…@vfr_…` references.
566    Frontier {
567        #[command(subcommand)]
568        action: FrontierAction,
569    },
570    /// Walk the local Workbench draft queue (Phase R, v0.5):
571    /// list, sign-and-apply, or clear queued review actions
572    Queue {
573        #[command(subcommand)]
574        action: QueueAction,
575    },
576    /// Publish, list, or pull frontiers through a registry
577    /// (Phase S, v0.5: verifiable distribution)
578    Registry {
579        #[command(subcommand)]
580        action: RegistryAction,
581    },
582    /// Initialize a .vela frontier repo
583    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    /// v0.103: scaffold a fresh frontier end-to-end in one command.
596    /// Composes init + sign generate-keypair + actor add + finding add
597    /// + a print-ready next-steps banner. Designed for the
598    /// fresh-from-`cargo install` user who wants to feel the substrate
599    /// in 30 seconds without memorizing the demo sequence.
600    /// v0.131: scaffold an AI-agent identity kit. Generates an
601    /// Ed25519 keypair, writes an `actor.json` with the canonical
602    /// `actor:<slug>-<date>` id and `actor.type: "agent"`, plus a
603    /// minimal `agent.yaml` config file documenting which
604    /// frameworks the agent supports. The output is portable: a
605    /// human reviewer can register the agent into any frontier
606    /// with `vela actor add <frontier> <agent_id> --pubkey
607    /// <hex>`, after which the agent can draft proposals that
608    /// flow through the reviewer-gated truth-claim discipline.
609    /// See docs/AI_ATTRIBUTION.md for the full doctrine and
610    /// docs/AGENT_QUICKSTART.md for the workflow.
611    Agent {
612        #[command(subcommand)]
613        action: AgentAction,
614    },
615    Quickstart {
616        /// Frontier directory to create. Defaults to ./demo
617        #[arg(default_value = "demo")]
618        path: PathBuf,
619        /// Frontier display name. Defaults to "Quickstart frontier".
620        #[arg(long, default_value = "Quickstart frontier")]
621        name: String,
622        /// Reviewer / actor id under which the first finding lands.
623        /// Defaults to `reviewer:you`. Override with e.g.
624        /// `--reviewer reviewer:will-blair`.
625        #[arg(long, default_value = "reviewer:you")]
626        reviewer: String,
627        /// First-finding assertion text. Defaults to a generic placeholder.
628        /// Override with `--assertion "your real claim"`.
629        #[arg(long)]
630        assertion: Option<String>,
631        /// Where to drop the generated keypair. Defaults to
632        /// `<path>/keys/`.
633        #[arg(long)]
634        keys_out: Option<PathBuf>,
635        /// Output stable JSON instead of the human-readable banner.
636        #[arg(long)]
637        json: bool,
638    },
639    /// v0.109: regenerate or verify the frontier's `vela.lock`
640    /// pinning every cross-frontier dependency by snapshot hash.
641    /// The lockfile is the substrate's "I used this exact
642    /// scientific state" artifact. Default mode regenerates the
643    /// lock from current state; `--check` verifies on-disk state
644    /// matches the recorded lock and exits non-zero on drift.
645    Lock {
646        /// Frontier path (the .vela/ repo root)
647        path: PathBuf,
648        /// Verify the existing lock against current on-disk
649        /// state instead of regenerating.
650        #[arg(long)]
651        check: bool,
652        /// Emit JSON to stdout instead of the human banner.
653        #[arg(long)]
654        json: bool,
655    },
656    /// v0.110: generate a static HTML site documenting the
657    /// frontier. Self-contained: no JS framework, no external
658    /// dependencies, browseable from disk in any browser.
659    /// Cargo's docs.rs analog for scientific state. Renders
660    /// index, findings table, events table, and per-finding
661    /// detail pages.
662    Doc {
663        /// Frontier path (the .vela/ repo root)
664        path: PathBuf,
665        /// Output directory. Defaults to `<path>/doc/`.
666        #[arg(long)]
667        out: Option<PathBuf>,
668        /// Emit a JSON report to stdout instead of the human
669        /// banner. The HTML files are written either way.
670        #[arg(long)]
671        json: bool,
672    },
673    /// Import frontier JSON into a .vela repo
674    Import {
675        frontier: PathBuf,
676        #[arg(long)]
677        into: Option<PathBuf>,
678    },
679    /// Compare two frontiers, or preview one pending proposal
680    /// against the current frontier.
681    ///
682    /// v0.74: when the first positional arg starts with `vpr_`,
683    /// route to the existing `proposals preview` path so a single
684    /// `vela diff <proposal_id>` shows the proposal-vs-frontier
685    /// delta the README quotes. The two-arg form
686    /// (`vela diff <frontier_a> <frontier_b>`) keeps its existing
687    /// behavior.
688    Diff {
689        /// Frontier path A, a `vpr_*` proposal id for preview
690        /// mode, or a `vfr_*` registry id (v0.140) resolved via
691        /// the registry into a pulled snapshot before diffing.
692        target: String,
693        /// Frontier path B for two-frontier compare. Accepts a
694        /// filesystem path or a `vfr_*` registry id (v0.140). Omit
695        /// when `target` is a proposal id.
696        frontier_b: Option<String>,
697        /// Frontier root for proposal-preview mode. Defaults to
698        /// `.` if the first positional is a proposal id and no
699        /// `--frontier` flag is provided.
700        #[arg(long)]
701        frontier: Option<PathBuf>,
702        /// Reviewer attribution for the proposal-preview mode.
703        #[arg(long, default_value = "reviewer:preview")]
704        reviewer: String,
705        /// v0.140: registry locator to resolve `vfr_*` ids
706        /// against. Accepts a hub URL (`https://...`) or a local
707        /// registry path. Defaults to `~/.vela/registry/entries.json`.
708        /// Only consulted when `target` or `frontier_b` starts
709        /// with `vfr_`.
710        #[arg(long)]
711        from: Option<String>,
712        #[arg(long)]
713        json: bool,
714        #[arg(long)]
715        quiet: bool,
716    },
717    /// Inspect or apply proposal-first frontier writes
718    Proposals {
719        #[command(subcommand)]
720        action: ProposalAction,
721    },
722    /// v0.149: build or query the cross-frontier search index.
723    /// `build` walks a set of frontier paths and writes a
724    /// content-addressed `vsi_*` index JSON. `query` reads the
725    /// index and returns matching entries.
726    SearchIndex {
727        #[command(subcommand)]
728        action: SearchAction,
729    },
730    /// v0.157: render a CRediT-style contributor ledger for a
731    /// frontier. Walks the canonical event log, maps each event
732    /// kind to one or more CRediT roles (CASRAI 2014), and
733    /// aggregates per actor.
734    Credit {
735        frontier: PathBuf,
736        #[arg(long)]
737        out: Option<PathBuf>,
738        #[arg(long)]
739        json: bool,
740    },
741    /// v0.156: render a Vela frontier or finding as a citation
742    /// in BibTeX, RIS, or CSL-JSON. Downstream-tooling-ready:
743    /// BibTeX into LaTeX, RIS into Zotero/EndNote/Mendeley,
744    /// CSL-JSON into Pandoc + most reference managers.
745    Citation {
746        /// Frontier path (renders the whole frontier) or
747        /// `vf_*` finding id (renders that finding; requires
748        /// `--frontier <path>`).
749        target: String,
750        /// Frontier path when `target` is a `vf_*` id.
751        #[arg(long)]
752        frontier: Option<PathBuf>,
753        /// Citation format: bibtex (alias bib) | ris |
754        /// csl-json (alias csl, json).
755        #[arg(long, default_value = "bibtex")]
756        format: String,
757        /// Optional network locator to include in the citation
758        /// URL field; defaults to a substrate-internal
759        /// `vela://...` URI.
760        #[arg(long)]
761        locator: Option<String>,
762        /// Output path (default: stdout).
763        #[arg(long)]
764        out: Option<PathBuf>,
765        #[arg(long)]
766        json: bool,
767    },
768    /// v0.164: anchor Lean theorems to their content-addressed
769    /// source bytes. Walks the substrate's theorem registry
770    /// (T1-T19 by v0.166) and emits a `vla_*` anchor per
771    /// theorem pinning (id, module path, decl, module sha256).
772    /// Structural — does not run lake build.
773    Lean {
774        #[command(subcommand)]
775        action: LeanAction,
776    },
777    /// v0.193: Scientific Diff Pack (`vsd_*`). Bundle N proposals
778    /// into one reviewable change-set. The per-proposal Carina
779    /// Diff (v0.3) stays for atomic event diffs; this primitive
780    /// sits one level up and is what a reviewer reads.
781    DiffPack {
782        #[command(subcommand)]
783        action: DiffPackAction,
784    },
785    /// v0.199: Tool Descriptor (`vtd_*`). Declare "this frontier
786    /// consumes outputs from this tool" as a first-class Carina
787    /// primitive. ToolUniverse-compatible. The descriptor pins
788    /// tool name + version + provider + calling convention +
789    /// input/output schemas; the id is content-addressed.
790    Tool {
791        #[command(subcommand)]
792        action: ToolCliAction,
793    },
794    /// v0.200: Evaluation Record (`ver_*`). A unified signed
795    /// record for replication, benchmark, validation, and
796    /// peer-review outcomes against any substrate object
797    /// (vsd_*, vtr_*, vf_*, vpf_*, vtd_*, vaa_*).
798    Eval {
799        #[command(subcommand)]
800        action: EvalCliAction,
801    },
802    /// v0.218: Verdict Conflict (`vdc_*`). Detect contradicting
803    /// pending verdicts on overlapping Diff Pack members, and
804    /// resolve them as signed canonical events. Reviewer
805    /// disagreement is recorded as an audit trail, not silenced.
806    Conflict {
807        #[command(subcommand)]
808        action: ConflictCliAction,
809    },
810    /// v0.167: declare a federated-hub spec primitive (`vhs_*`).
811    /// Pure data; content-addressed over (hub_id, base_url,
812    /// operator_pubkey_hex, substrate_version, declared_at).
813    /// No network calls.
814    Hub {
815        #[command(subcommand)]
816        action: HubSpecCli,
817    },
818    /// v0.168: review-comment thread primitive (`vrt_*` + signed
819    /// `vrm_*` messages). Append-only chain of signed messages
820    /// attached to a proposal (`vpr_*`) or finding (`vf_*`).
821    /// Substrate-honest: documents deliberation; does not gate
822    /// proposal acceptance (that path stays on the canonical
823    /// event-log).
824    ReviewThread {
825        #[command(subcommand)]
826        action: ReviewThreadCli,
827    },
828    /// v0.163: render a frontier as a Markdown preprint
829    /// (abstract, contributors with CRediT roles, findings as
830    /// evidence sections, BibTeX citation block). Pure derived
831    /// view from the canonical substrate state.
832    Preprint {
833        /// Frontier path.
834        frontier: PathBuf,
835        /// Optional release timestamp to pin in the footer.
836        /// Defaults to now (UTC).
837        #[arg(long)]
838        released_at: Option<String>,
839        /// Output path (default: stdout).
840        #[arg(long)]
841        out: Option<PathBuf>,
842        #[arg(long)]
843        json: bool,
844    },
845    /// v0.163: resolve a persistent identifier (vfr_*, vfrr_*,
846    /// vf_*, DOI, arXiv, ORCID, etc.) to a structured reference
847    /// plus a canonical site URL. Pure derivation from the
848    /// handle's shape; no network calls.
849    Handle {
850        /// The identifier to classify (e.g. `vfr_5076e7b3ff8e6b0f`,
851        /// `10.1234/abc`, `2403.01234`, `0000-0001-2345-6789`).
852        handle: String,
853        /// Override the live-site base URL. Defaults to the
854        /// public Vela site.
855        #[arg(long, default_value = "https://vela-site.fly.dev")]
856        site: String,
857        #[arg(long)]
858        json: bool,
859    },
860    /// v0.162: render a Crossref deposit manifest for a frontier
861    /// release. Substrate generates the deposit body the operator
862    /// then submits to Crossref under their own member account.
863    /// Substrate does not call the Crossref API itself.
864    Crossref {
865        /// Frontier path (the source the release was cut from).
866        frontier: PathBuf,
867        /// Release id (`vfrr_*`) to deposit. Defaults to latest
868        /// release in the frontier.
869        #[arg(long)]
870        release: Option<String>,
871        /// Crossref member id.
872        #[arg(long)]
873        member: String,
874        /// DOI prefix you are authorized to mint under
875        /// (e.g. `10.5555`).
876        #[arg(long)]
877        prefix: String,
878        /// Depositor display name.
879        #[arg(long)]
880        depositor_name: String,
881        /// Depositor contact email.
882        #[arg(long)]
883        depositor_email: String,
884        /// Resource URL the DOI should resolve to.
885        #[arg(long)]
886        resource_url: String,
887        /// Optional display title (defaults to project.name).
888        #[arg(long)]
889        title: Option<String>,
890        /// Optional abstract / description.
891        #[arg(long)]
892        description: Option<String>,
893        /// Optional SPDX license id.
894        #[arg(long)]
895        license: Option<String>,
896        /// Emit Crossref deposit XML (subset of schema 5.3.1)
897        /// instead of JSON.
898        #[arg(long)]
899        xml: bool,
900        /// Output path (default: stdout).
901        #[arg(long)]
902        out: Option<PathBuf>,
903        #[arg(long)]
904        json: bool,
905    },
906    /// Import a Carina artifact packet as reviewable frontier proposals
907    ArtifactToState {
908        /// Frontier JSON file or Vela repo
909        frontier: PathBuf,
910        /// Artifact packet JSON
911        packet: PathBuf,
912        /// Actor importing the packet
913        #[arg(long)]
914        actor: String,
915        /// Apply artifact proposals immediately while leaving truth changes pending
916        #[arg(long)]
917        apply_artifacts: bool,
918        #[arg(long)]
919        json: bool,
920    },
921    /// Validate Carina artifact packets before importing runtime output
922    BridgeKit {
923        #[command(subcommand)]
924        action: BridgeKitAction,
925    },
926    /// Run reviewed source adapters into artifact-to-state proposals
927    SourceAdapter {
928        #[command(subcommand)]
929        action: SourceAdapterAction,
930    },
931    /// Run external runtime adapters into artifact-to-state proposals
932    RuntimeAdapter {
933        #[command(subcommand)]
934        action: RuntimeAdapterAction,
935    },
936    /// Manage finding bundles as the core frontier primitive
937    Finding {
938        #[command(subcommand)]
939        command: FindingCommands,
940    },
941    /// Add typed links between findings — including cross-frontier
942    /// references of the form `vf_<id>@vfr_<id>` (v0.8). Until v0.9
943    /// link state lived only in JSON; `vela link add` is the CLI on-ramp.
944    Link {
945        #[command(subcommand)]
946        action: LinkAction,
947    },
948    /// v0.48: launch the local workbench web app — a localhost UI
949    /// rendering the substrate against the cwd's `.vela/` repo.
950    /// Read+write: confirm/refute bridges, browse findings, audit.
951    /// Pure Rust, no node/bun dependency, single binary.
952    Workbench {
953        /// Path to a Vela repo. Defaults to cwd.
954        #[arg(default_value = ".")]
955        path: PathBuf,
956        /// Port to bind on localhost. Default 3850.
957        #[arg(long, default_value_t = 3850)]
958        port: u16,
959        /// Skip auto-opening the default browser.
960        #[arg(long)]
961        no_open: bool,
962    },
963    /// v0.46: derive, list, and review cross-frontier bridges.
964    /// A bridge is a content-addressed `vbr_<id>` record asserting
965    /// "this entity links findings in two frontiers." Bridges are
966    /// derived deterministically; reviewer judgment promotes them
967    /// from `derived` to `confirmed` or `refuted`.
968    Bridges {
969        #[command(subcommand)]
970        action: BridgesAction,
971    },
972    /// v0.19: resolve unresolved entities against a bundled common-entity
973    /// table (UniProt for proteins, MeSH for diseases, ChEBI/DrugBank for
974    /// compounds, etc.). Lowers `needs_review` for matched entities and
975    /// populates `canonical_id`. Idempotent unless `--force` is passed.
976    Entity {
977        #[command(subcommand)]
978        action: EntityAction,
979    },
980    /// Create or apply one proposal-backed finding review
981    Review {
982        /// Frontier JSON file or Vela repo
983        frontier: PathBuf,
984        /// Finding ID to review
985        finding_id: String,
986        /// accepted, contested, needs_revision, or rejected
987        #[arg(long)]
988        status: Option<String>,
989        /// Reason for the review
990        #[arg(long)]
991        reason: Option<String>,
992        /// Reviewer identifier
993        #[arg(long)]
994        reviewer: String,
995        /// Immediately accept and apply the proposal locally
996        #[arg(long)]
997        apply: bool,
998        /// Output stable JSON
999        #[arg(long)]
1000        json: bool,
1001    },
1002    /// Add a lightweight note to a finding
1003    Note {
1004        frontier: PathBuf,
1005        finding_id: String,
1006        #[arg(long)]
1007        text: String,
1008        #[arg(long)]
1009        author: String,
1010        /// Immediately accept and apply the proposal locally
1011        #[arg(long)]
1012        apply: bool,
1013        #[arg(long)]
1014        json: bool,
1015    },
1016    /// Add an explicit caveat to a finding
1017    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 an interpretation field while preserving history
1030    Revise {
1031        frontier: PathBuf,
1032        finding_id: String,
1033        /// New confidence score from 0.0 to 1.0
1034        #[arg(long)]
1035        confidence: f64,
1036        /// Reason for the revision
1037        #[arg(long)]
1038        reason: String,
1039        /// Reviewer identifier
1040        #[arg(long)]
1041        reviewer: String,
1042        #[arg(long)]
1043        apply: bool,
1044        #[arg(long)]
1045        json: bool,
1046    },
1047    /// Mark a finding as rejected without deleting it
1048    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    /// Show state-transition history for one finding
1061    History {
1062        frontier: PathBuf,
1063        finding_id: String,
1064        #[arg(long)]
1065        json: bool,
1066        /// v0.55: time-travel replay — show only events at-or-before
1067        /// this RFC3339 timestamp, and report the confidence score
1068        /// the finding had at that moment (last revision <= cutoff).
1069        #[arg(long, value_name = "RFC3339_TIMESTAMP")]
1070        as_of: Option<String>,
1071    },
1072    /// Import review/state events from a packet or JSON file into a frontier
1073    ImportEvents {
1074        source: PathBuf,
1075        #[arg(long)]
1076        into: PathBuf,
1077        #[arg(long)]
1078        json: bool,
1079    },
1080    /// Retract a finding
1081    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    /// v0.117: Register a machine-checked Proof primitive (`vpf_*`)
1094    /// against an existing finding. The proof script is hashed with
1095    /// sha256 to produce a content-addressed locator; the artifact
1096    /// rides as a `kind: source_file` artifact carrying
1097    /// `metadata.carina_kind: proof_script` plus tool + tool-version
1098    /// (matching the v0.75.6 sidon-sets pattern). Routes to
1099    /// `state::add_artifact`; the artifact event is signed under the
1100    /// reviewer's actor id. Closes the v0.75.6 Carina Proof primitive
1101    /// loop end-to-end: every proof script lives in the frontier's
1102    /// canonical event log with a content-addressed locator the
1103    /// substrate's verifier can pin against.
1104    ProofAdd {
1105        frontier: PathBuf,
1106        /// Finding the proof targets (`vf_*`).
1107        #[arg(long = "target-finding")]
1108        target_finding: String,
1109        /// Proof-assistant identifier. One of: lean4 (default), coq,
1110        /// isabelle, agda, metamath, rocq, other.
1111        #[arg(long, default_value = "lean4")]
1112        tool: String,
1113        /// Tool version pin (e.g. `4.29.1` for Lean 4).
1114        #[arg(long = "tool-version", default_value = "4.29.1")]
1115        tool_version: String,
1116        /// Path to the proof script on disk.
1117        #[arg(long = "script-path")]
1118        script_path: PathBuf,
1119        /// Human-readable label for the proof artifact.
1120        #[arg(long, default_value = "Proof script")]
1121        name: String,
1122        /// Reviewer actor id (e.g. `reviewer:will-blair`).
1123        #[arg(long)]
1124        reviewer: String,
1125        /// Reason for registering the proof artifact.
1126        #[arg(long)]
1127        reason: String,
1128        #[arg(long)]
1129        json: bool,
1130    },
1131    /// v0.151: attest that an external verifier ran a Carina
1132    /// Proof artifact and produced a specific output hash. Writes
1133    /// a signed `vpv_*` record next to the proof; consumers
1134    /// verify the attestation via `proof-verify-attestation`.
1135    /// The verifier itself (Lean kernel, Coq, etc.) runs
1136    /// outside the substrate; this command records the
1137    /// verifier's signed output and pubkey.
1138    ProofAttestVerification {
1139        /// Proof artifact id (`vpf_*`) the verification covers.
1140        #[arg(long)]
1141        proof_id: String,
1142        /// Verifier tool: lean4|coq|isabelle|agda|metamath|rocq|other.
1143        #[arg(long, default_value = "lean4")]
1144        tool: String,
1145        #[arg(long = "tool-version", default_value = "4.29.1")]
1146        tool_version: String,
1147        /// Content-addressed locator (sha256:HEX) of the proof
1148        /// script the verifier ran.
1149        #[arg(long)]
1150        script_locator: String,
1151        /// Optional sha256 over the Lake manifest (or equivalent).
1152        #[arg(long = "lake-manifest-hash")]
1153        lake_manifest_hash: Option<String>,
1154        /// sha256:HEX over the verifier's standard output.
1155        #[arg(long = "verifier-output-hash")]
1156        verifier_output_hash: String,
1157        /// `verified` | `failed` | `toolchain_mismatch`.
1158        #[arg(long, default_value = "verified")]
1159        status: String,
1160        /// Verifier actor identifier (GitHub Action url, Vela
1161        /// actor id, institutional steward id).
1162        #[arg(long = "verifier-actor")]
1163        verifier_actor: String,
1164        /// Verifier's Ed25519 signing key.
1165        #[arg(long)]
1166        key: PathBuf,
1167        /// Output path for the verification record JSON.
1168        #[arg(long)]
1169        out: PathBuf,
1170        #[arg(long)]
1171        json: bool,
1172    },
1173    /// v0.151: verify a `vpv_*` proof-verification record:
1174    /// re-derive the id, verify the Ed25519 signature against
1175    /// `verifier_pubkey`. Exits non-zero on any mismatch.
1176    ProofVerifyAttestation {
1177        /// Path to the `vpv_*` verification record JSON.
1178        record: PathBuf,
1179        #[arg(long)]
1180        json: bool,
1181    },
1182    /// v0.79: Add a new entity tag to an existing finding.
1183    /// Append-only: re-applying with the same name is a no-op.
1184    /// Closes the v0.78.4 honest gap that forced reviewers to
1185    /// append new findings just to add a tag.
1186    EntityAdd {
1187        frontier: PathBuf,
1188        finding_id: String,
1189        #[arg(long)]
1190        entity: String,
1191        /// Entity type. One of: gene, protein, compound, disease,
1192        /// cell_type, organism, pathway, assay, anatomical_structure,
1193        /// particle, instrument, dataset, quantity, other.
1194        #[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    /// v0.57: Resolve a named entity inside a finding's
1206    /// assertion.entities to a canonical id. Clears the entity's
1207    /// needs_review flag.
1208    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    /// v0.57: Mechanically repair a missing evidence-span on a
1233    /// finding by appending a `{section, text}` span. Emits a signed
1234    /// v0.57: Fetch metadata + abstract for an external source by
1235    /// stable identifier (doi:, pmid:, nct:). Cached locally so a
1236    /// rerun doesn't hit the network. Used by the BBB span-repair
1237    /// curation wave to propose evidence_spans from fetched
1238    /// abstract text.
1239    SourceFetch {
1240        /// Source identifier. Accepts `doi:<doi>`, `pmid:<id>`,
1241        /// `nct:<id>`, or a bare DOI / PMID / NCT id.
1242        identifier: String,
1243        /// Frontier to use as the cache root. If set, fetched
1244        /// records are cached under
1245        /// `<frontier>/sources/cache/<sha256>.json` and reused.
1246        #[arg(long)]
1247        cache: Option<PathBuf>,
1248        /// Where to write the JSON output. Defaults to stdout.
1249        #[arg(long)]
1250        out: Option<PathBuf>,
1251        /// Force a network fetch even if a cache hit exists.
1252        #[arg(long)]
1253        refresh: bool,
1254        #[arg(long)]
1255        json: bool,
1256    },
1257    /// `finding.span_repaired` canonical event when `--apply` is
1258    /// passed.
1259    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    /// v0.56: Mechanically repair a missing evidence-atom locator by
1276    /// copying the locator from the parent source record. Emits a
1277    /// signed `evidence_atom.locator_repaired` canonical event when
1278    /// `--apply` is passed.
1279    LocatorRepair {
1280        frontier: PathBuf,
1281        atom_id: String,
1282        /// Resolved locator string (e.g. doi:10.1038/s41586-020-2247-3).
1283        /// If omitted, the CLI looks up the parent source's locator.
1284        #[arg(long)]
1285        locator: Option<String>,
1286        /// Reviewer identifier (e.g. agent:vela-curation-bot or
1287        /// reviewer:will-blair).
1288        #[arg(long)]
1289        reviewer: String,
1290        /// Reason for the repair, recorded on the canonical event.
1291        #[arg(long)]
1292        reason: String,
1293        /// Immediately accept and apply the proposal locally.
1294        #[arg(long)]
1295        apply: bool,
1296        #[arg(long)]
1297        json: bool,
1298    },
1299    /// Simulate correction impact over declared dependency links
1300    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    /// v0.32: Record an independent replication attempt against a
1312    /// canonical finding. Each attempt becomes a `vrep_<hash>` object
1313    /// in `.vela/replications/`, content-addressed by target +
1314    /// attempting actor + canonical conditions + outcome. Replication
1315    /// is the empirical bedrock of science; making it kernel-level
1316    /// means downstream tools (site, bench, agents) can reason about
1317    /// "this lab tried in human iPSC, that lab failed in mouse OPCs"
1318    /// as distinct epistemic facts.
1319    Replicate {
1320        /// Path to the frontier (project dir, `.vela/` repo, or `.json`).
1321        frontier: PathBuf,
1322        /// Target finding id (`vf_<hash>`) being replicated.
1323        target: String,
1324        /// Outcome label: `replicated` | `failed` | `partial` | `inconclusive`.
1325        #[arg(long)]
1326        outcome: String,
1327        /// Stable actor id of the lab/curator/agent attempting.
1328        #[arg(long)]
1329        by: String,
1330        /// One-paragraph description of conditions (model system,
1331        /// species, sample size, in_vivo / in_vitro / human_data).
1332        /// Goes into the content-address preimage.
1333        #[arg(long)]
1334        conditions: String,
1335        /// Source paper title for the replicating work.
1336        #[arg(long)]
1337        source_title: String,
1338        /// Optional DOI for the replicating paper.
1339        #[arg(long)]
1340        doi: Option<String>,
1341        /// Optional PMID for the replicating paper.
1342        #[arg(long)]
1343        pmid: Option<String>,
1344        /// Sample size description (e.g. "n=42").
1345        #[arg(long)]
1346        sample_size: Option<String>,
1347        /// Free-text reviewer note. Especially important for
1348        /// `partial` and `inconclusive` outcomes.
1349        #[arg(long, default_value = "")]
1350        note: String,
1351        /// `vrep_<id>` of a previous attempt this one extends/refines.
1352        #[arg(long)]
1353        previous_attempt: Option<String>,
1354        /// v0.36.2: skip the propagation cascade. By default,
1355        /// recording a replication recomputes the target finding's
1356        /// confidence from the live `Project.replications` collection
1357        /// and flags downstream dependents linked via `supports` /
1358        /// `depends`. Use this flag to stage replications without
1359        /// immediate review-queue churn.
1360        #[arg(long, default_value_t = false)]
1361        no_cascade: bool,
1362        /// Emit JSON to stdout.
1363        #[arg(long)]
1364        json: bool,
1365    },
1366    /// v0.32: List replication attempts in a frontier, optionally
1367    /// filtered by target finding id.
1368    Replications {
1369        /// Path to the frontier (project dir, `.vela/` repo, or `.json`).
1370        frontier: PathBuf,
1371        /// Optional target finding id to filter by.
1372        #[arg(long)]
1373        target: Option<String>,
1374        /// Emit JSON to stdout.
1375        #[arg(long)]
1376        json: bool,
1377    },
1378    /// v0.33: Register a Dataset as a first-class kernel object
1379    /// (`vd_<hash>`). Datasets anchor empirical claims that rest on
1380    /// data — the canonical Alzheimer's frontier should know that
1381    /// "ATV:TREM2 reduces plaque density" rests on a specific cohort
1382    /// of n=24 iPSC-derived microglia, not on "the iPSC dataset" in
1383    /// the abstract.
1384    DatasetAdd {
1385        /// Path to the frontier (project dir, `.vela/` repo, or `.json`).
1386        frontier: PathBuf,
1387        /// Human-readable dataset name (e.g. `ADNI`, `TRAILBLAZER-ALZ`).
1388        #[arg(long)]
1389        name: String,
1390        /// Semantic version or release tag (e.g. `ADNI-3`, `v2.2`).
1391        #[arg(long)]
1392        version: Option<String>,
1393        /// SHA-256 of canonical contents. For remote datasets, the
1394        /// publisher's declared content hash; integrity verification
1395        /// is the puller's responsibility.
1396        #[arg(long)]
1397        content_hash: String,
1398        /// Where the dataset is reachable (https / file / s3 URL).
1399        #[arg(long)]
1400        url: Option<String>,
1401        /// License identifier or URL.
1402        #[arg(long)]
1403        license: Option<String>,
1404        /// Source paper title or release name (for provenance).
1405        #[arg(long)]
1406        source_title: String,
1407        /// Optional DOI for the source publication.
1408        #[arg(long)]
1409        doi: Option<String>,
1410        /// Optional row count.
1411        #[arg(long)]
1412        row_count: Option<u64>,
1413        /// Emit JSON to stdout.
1414        #[arg(long)]
1415        json: bool,
1416    },
1417    /// v0.33: List datasets in a frontier.
1418    Datasets {
1419        frontier: PathBuf,
1420        #[arg(long)]
1421        json: bool,
1422    },
1423    /// v0.33: Register a CodeArtifact as a first-class kernel object
1424    /// (`vc_<hash>`). Claims can reference the code that produced
1425    /// them, pinned to a specific git commit and path.
1426    CodeAdd {
1427        /// Path to the frontier.
1428        frontier: PathBuf,
1429        /// Source language: `python`, `r`, `julia`, `rust`, `bash`, etc.
1430        #[arg(long)]
1431        language: String,
1432        /// Repository URL (e.g. `https://github.com/vela-science/vela`).
1433        #[arg(long)]
1434        repo_url: Option<String>,
1435        /// Specific git commit SHA. Required for reproducibility;
1436        /// `None` means "unpinned" and weakens the substrate claim.
1437        #[arg(long)]
1438        commit: Option<String>,
1439        /// Path within the repository.
1440        #[arg(long)]
1441        path: String,
1442        /// SHA-256 of the snippet body.
1443        #[arg(long)]
1444        content_hash: String,
1445        /// Optional starting line.
1446        #[arg(long)]
1447        line_start: Option<u32>,
1448        /// Optional ending line.
1449        #[arg(long)]
1450        line_end: Option<u32>,
1451        /// Optional entry point: function name, notebook cell id.
1452        #[arg(long)]
1453        entry_point: Option<String>,
1454        /// Emit JSON to stdout.
1455        #[arg(long)]
1456        json: bool,
1457    },
1458    /// v0.33: List code artifacts in a frontier.
1459    CodeArtifacts {
1460        frontier: PathBuf,
1461        #[arg(long)]
1462        json: bool,
1463    },
1464    /// Register a generic content-addressed artifact. Use this for
1465    /// protocols, trial records, supplements, notebooks, source files,
1466    /// tables, and dataset manifests that need durable byte or pointer
1467    /// provenance.
1468    ArtifactAdd {
1469        /// Path to the frontier.
1470        frontier: PathBuf,
1471        /// Artifact kind. Examples: clinical_trial_record, protocol,
1472        /// supplement, notebook, source_file, dataset.
1473        #[arg(long)]
1474        kind: String,
1475        /// Human-readable artifact name.
1476        #[arg(long)]
1477        name: String,
1478        /// Local file to hash and, for .vela repos, mirror under
1479        /// `.vela/artifact-blobs/sha256/`.
1480        #[arg(long)]
1481        file: Option<PathBuf>,
1482        /// Remote URL or accession locator.
1483        #[arg(long)]
1484        url: Option<String>,
1485        /// SHA-256 commitment. Required unless `--file` is provided.
1486        #[arg(long)]
1487        content_hash: Option<String>,
1488        /// MIME type or close equivalent.
1489        #[arg(long)]
1490        media_type: Option<String>,
1491        /// License identifier, URL, or access terms note.
1492        #[arg(long)]
1493        license: Option<String>,
1494        /// Source title for artifact provenance. Defaults to `--name`.
1495        #[arg(long)]
1496        source_title: Option<String>,
1497        /// Source URL when distinct from `--url`.
1498        #[arg(long)]
1499        source_url: Option<String>,
1500        /// Optional DOI for the source publication.
1501        #[arg(long)]
1502        doi: Option<String>,
1503        /// Target finding ids this artifact bears on.
1504        #[arg(long)]
1505        target: Vec<String>,
1506        /// Structured metadata as key=value. Repeatable.
1507        #[arg(long)]
1508        metadata: Vec<String>,
1509        /// Access tier: public, restricted, or classified.
1510        #[arg(long, default_value = "public")]
1511        access_tier: String,
1512        /// Stable actor id of the depositor.
1513        #[arg(long, default_value = "reviewer:manual")]
1514        deposited_by: String,
1515        /// Reason recorded on the canonical event.
1516        #[arg(long, default_value = "artifact deposit")]
1517        reason: String,
1518        /// Emit JSON to stdout.
1519        #[arg(long)]
1520        json: bool,
1521    },
1522    /// List generic artifacts in a frontier.
1523    Artifacts {
1524        frontier: PathBuf,
1525        /// Optional target finding id to filter by.
1526        #[arg(long)]
1527        target: Option<String>,
1528        #[arg(long)]
1529        json: bool,
1530    },
1531    /// Audit artifact locators, hashes, references, and profile fields.
1532    ArtifactAudit {
1533        frontier: PathBuf,
1534        /// Emit JSON to stdout.
1535        #[arg(long)]
1536        json: bool,
1537    },
1538    /// Show the validated decision brief projection for a frontier.
1539    DecisionBrief {
1540        frontier: PathBuf,
1541        /// Emit JSON to stdout.
1542        #[arg(long)]
1543        json: bool,
1544    },
1545    /// Show the validated trial outcome projection for a frontier.
1546    TrialSummary {
1547        frontier: PathBuf,
1548        /// Emit JSON to stdout.
1549        #[arg(long)]
1550        json: bool,
1551    },
1552    /// Show the validated source verification projection for a frontier.
1553    SourceVerification {
1554        frontier: PathBuf,
1555        /// Emit JSON to stdout.
1556        #[arg(long)]
1557        json: bool,
1558    },
1559    /// Show the validated source ingest plan for a frontier.
1560    SourceIngestPlan {
1561        frontier: PathBuf,
1562        /// Emit JSON to stdout.
1563        #[arg(long)]
1564        json: bool,
1565    },
1566    /// Import a ClinicalTrials.gov v2 study record as a content-addressed
1567    /// `clinical_trial_record` artifact.
1568    ClinicalTrialImport {
1569        /// Path to the frontier.
1570        frontier: PathBuf,
1571        /// ClinicalTrials.gov NCT identifier.
1572        nct_id: String,
1573        /// Read a saved ClinicalTrials.gov v2 JSON record instead of
1574        /// fetching from the network.
1575        #[arg(long)]
1576        input_json: Option<PathBuf>,
1577        /// Target finding ids this trial record bears on.
1578        #[arg(long)]
1579        target: Vec<String>,
1580        /// Stable actor id of the depositor.
1581        #[arg(long, default_value = "reviewer:manual")]
1582        deposited_by: String,
1583        /// Reason recorded on the canonical event.
1584        #[arg(long, default_value = "clinical trial record import")]
1585        reason: String,
1586        /// License or access terms note.
1587        #[arg(long, default_value = "ClinicalTrials.gov public record")]
1588        license: String,
1589        /// Emit JSON to stdout.
1590        #[arg(long)]
1591        json: bool,
1592    },
1593    /// v0.49: Deposit a NegativeResult (`vnr_<hash>`). Two flavors:
1594    /// `--kind registered_trial` for pre-registered trial readouts
1595    /// (carries `power`, `effect_size_ci`, and pre-registered MCID
1596    /// so an underpowered null does not poison downstream confidence);
1597    /// `--kind exploratory` for wet-lab dead ends (the
1598    /// (reagent, observation, attempts) tuple where most failures
1599    /// cannot be statistically bounded).
1600    NegativeResultAdd {
1601        /// Path to the frontier (project dir, `.vela/` repo, or `.json`).
1602        frontier: PathBuf,
1603        /// `registered_trial` or `exploratory`.
1604        #[arg(long)]
1605        kind: String,
1606        /// Stable actor id of the depositor.
1607        #[arg(long)]
1608        deposited_by: String,
1609        /// Free-text reason recorded on the canonical event.
1610        #[arg(long)]
1611        reason: String,
1612        /// Conditions narrative (free text). Reuses the standard
1613        /// `Conditions` shape; structured flags are optional.
1614        #[arg(long)]
1615        conditions_text: String,
1616        /// Free-text reviewer note attached to the deposit.
1617        #[arg(long, default_value = "")]
1618        notes: String,
1619        /// Optional `vf_*` finding ids the null bears against.
1620        /// Repeatable.
1621        #[arg(long)]
1622        target: Vec<String>,
1623        // ── registered_trial fields ──────────────────────────────
1624        /// Pre-specified primary endpoint
1625        /// (e.g. "CDR-SB change at 18 months").
1626        #[arg(long)]
1627        endpoint: Option<String>,
1628        /// Intervention arm description (drug + dose, etc.).
1629        #[arg(long)]
1630        intervention: Option<String>,
1631        /// Comparator arm description (placebo, active, SoC).
1632        #[arg(long)]
1633        comparator: Option<String>,
1634        /// Population scope (indication, stage, biomarker eligibility).
1635        #[arg(long)]
1636        population: Option<String>,
1637        /// Total participants enrolled (any arm).
1638        #[arg(long)]
1639        n_enrolled: Option<u32>,
1640        /// Statistical power for primary endpoint, on [0, 1].
1641        #[arg(long)]
1642        power: Option<f64>,
1643        /// CI lower bound for the observed primary effect size.
1644        #[arg(long)]
1645        ci_lower: Option<f64>,
1646        /// CI upper bound for the observed primary effect size.
1647        #[arg(long)]
1648        ci_upper: Option<f64>,
1649        /// Pre-registered minimum effect size of interest (MCID).
1650        #[arg(long)]
1651        effect_size_threshold: Option<f64>,
1652        /// Trial registry id (e.g. "NCT04532333").
1653        #[arg(long)]
1654        registry_id: Option<String>,
1655        // ── exploratory fields ───────────────────────────────────
1656        /// Reagent / compound / vector / perturbation tried.
1657        #[arg(long)]
1658        reagent: Option<String>,
1659        /// Free-text observed outcome.
1660        #[arg(long)]
1661        observation: Option<String>,
1662        /// Number of independent attempts that agreed.
1663        #[arg(long)]
1664        attempts: Option<u32>,
1665        // ── provenance ───────────────────────────────────────────
1666        /// Provenance source title (paper title, trial readout, etc.).
1667        #[arg(long)]
1668        source_title: String,
1669        /// Optional DOI for the source.
1670        #[arg(long)]
1671        doi: Option<String>,
1672        /// Optional URL for the source (registry page, preprint).
1673        #[arg(long)]
1674        url: Option<String>,
1675        /// Optional source year.
1676        #[arg(long)]
1677        year: Option<i32>,
1678        /// Emit JSON to stdout.
1679        #[arg(long)]
1680        json: bool,
1681    },
1682    /// v0.49: List NegativeResults in a frontier.
1683    NegativeResults {
1684        frontier: PathBuf,
1685        /// Filter to deposits bearing on a specific `vf_*` finding.
1686        #[arg(long)]
1687        target: Option<String>,
1688        #[arg(long)]
1689        json: bool,
1690    },
1691    /// v0.50: Open a Trajectory (`vtr_<hash>`) — the search path that
1692    /// produced (or did not produce) a finding. Steps are appended
1693    /// via `vela trajectory-step` so the search becomes visible as
1694    /// it unfolds rather than only after the fact.
1695    TrajectoryCreate {
1696        /// Path to the frontier.
1697        frontier: PathBuf,
1698        /// Stable actor id of the depositor.
1699        #[arg(long)]
1700        deposited_by: String,
1701        /// Free-text reason recorded on the canonical event.
1702        #[arg(long)]
1703        reason: String,
1704        /// Optional `vf_*` finding ids the trajectory targets.
1705        /// Repeatable. May be empty when the trajectory leads
1706        /// nowhere yet — the search can be opened before its target
1707        /// finding exists.
1708        #[arg(long)]
1709        target: Vec<String>,
1710        /// Free-text reviewer note on the trajectory as a whole.
1711        #[arg(long, default_value = "")]
1712        notes: String,
1713        #[arg(long)]
1714        json: bool,
1715    },
1716    /// v0.50: Append one step to an existing Trajectory. Steps are
1717    /// content-addressed and idempotent on duplicate content.
1718    TrajectoryStep {
1719        /// Path to the frontier.
1720        frontier: PathBuf,
1721        /// Trajectory `vtr_<hash>` to append to.
1722        trajectory_id: String,
1723        /// Step kind: `hypothesis | tried | ruled_out | observed | refined`.
1724        #[arg(long)]
1725        kind: String,
1726        /// Free-text description. For `ruled_out`, prose should name
1727        /// the reason for exclusion — that's the load-bearing field
1728        /// for the next agent reading the search.
1729        #[arg(long)]
1730        description: String,
1731        /// Stable actor id of who took the step.
1732        #[arg(long)]
1733        actor: String,
1734        /// Free-text reason recorded on the canonical event.
1735        #[arg(long)]
1736        reason: String,
1737        /// Optional referenced kernel objects (`vf_*`, `vnr_*`,
1738        /// `vrep_*`, `vpred_*`, `vd_*`, `vc_*`). Repeatable.
1739        #[arg(long)]
1740        reference: Vec<String>,
1741        #[arg(long)]
1742        json: bool,
1743    },
1744    /// v0.50: List trajectories in a frontier.
1745    Trajectories {
1746        frontier: PathBuf,
1747        /// Filter to trajectories bearing on a specific `vf_*` finding.
1748        #[arg(long)]
1749        target: Option<String>,
1750        #[arg(long)]
1751        json: bool,
1752    },
1753    /// v0.51: Re-classify the read-side access tier of a finding,
1754    /// negative_result, or trajectory. Emits a `tier.set` canonical
1755    /// event so the reclassification is replay-deterministic and
1756    /// auditable. Higher tiers are gated in MCP/HTTP read paths
1757    /// against the requesting actor's `access_clearance`.
1758    TierSet {
1759        /// Path to the frontier.
1760        frontier: PathBuf,
1761        /// One of `finding`, `negative_result`, `trajectory`.
1762        #[arg(long)]
1763        object_type: String,
1764        /// `vf_*`, `vnr_*`, or `vtr_*` id.
1765        #[arg(long)]
1766        object_id: String,
1767        /// New tier: `public`, `restricted`, or `classified`.
1768        #[arg(long)]
1769        tier: String,
1770        /// Stable actor id of the classifier (must already be
1771        /// registered if signed events are required by the frontier).
1772        #[arg(long)]
1773        actor: String,
1774        /// Free-text reason recorded on the canonical event. Often
1775        /// the load-bearing audit field — "why was this classified."
1776        #[arg(long)]
1777        reason: String,
1778        #[arg(long)]
1779        json: bool,
1780    },
1781    /// v0.34: Make a falsifiable Prediction (`vpred_<hash>`) about a
1782    /// future observation. Predictions are scoped to one or more
1783    /// existing findings, carry an explicit resolution criterion,
1784    /// and live in the kernel's epistemic accountability ledger.
1785    /// When a Resolution arrives later, the prediction's confidence
1786    /// flows into the predictor's Brier score and log score.
1787    Predict {
1788        /// Path to the frontier (project dir, `.vela/` repo, or `.json`).
1789        frontier: PathBuf,
1790        /// Stable actor id of the predictor.
1791        #[arg(long)]
1792        by: String,
1793        /// Plain-prose prediction (e.g. "lecanemab Phase 4 will show
1794        /// >0.4 SD CDR-SB effect").
1795        #[arg(long)]
1796        claim: String,
1797        /// Unambiguous criterion describing how to recognize resolution.
1798        #[arg(long)]
1799        criterion: String,
1800        /// RFC 3339 deadline for resolution.
1801        #[arg(long)]
1802        resolves_by: Option<String>,
1803        /// Confidence on [0, 1] in the expected outcome.
1804        #[arg(long)]
1805        confidence: f64,
1806        /// Comma-separated `vf_*` finding ids this prediction depends on.
1807        #[arg(long, default_value = "")]
1808        target: String,
1809        /// Outcome shape: `affirmed` | `falsified` | `quant:V±T units` | `cat:value`.
1810        #[arg(long, default_value = "affirmed")]
1811        outcome: String,
1812        /// Free-text scope/conditions of the prediction.
1813        #[arg(long, default_value = "")]
1814        conditions: String,
1815        /// Emit JSON to stdout.
1816        #[arg(long)]
1817        json: bool,
1818    },
1819    /// v0.34: Resolve an open Prediction. Records what actually
1820    /// happened, who observed it, and whether it matched the
1821    /// prediction. Drives Brier / log-score / hit-rate calibration
1822    /// over the resolved subset.
1823    Resolve {
1824        /// Path to the frontier.
1825        frontier: PathBuf,
1826        /// `vpred_<id>` of the prediction being resolved.
1827        prediction: String,
1828        /// Free-text description of what actually happened.
1829        #[arg(long)]
1830        outcome: String,
1831        /// Whether the actual outcome matched the predicted one.
1832        #[arg(long)]
1833        matched: bool,
1834        /// Stable actor id of the resolver. Independent resolvers
1835        /// (different from the predictor) produce stronger signal.
1836        #[arg(long)]
1837        by: String,
1838        /// Resolver's confidence in the match judgment, on [0, 1].
1839        #[arg(long, default_value = "1.0")]
1840        confidence: f64,
1841        /// Source paper / trial readout title for the resolution.
1842        #[arg(long, default_value = "")]
1843        source_title: String,
1844        /// Optional DOI for the resolving source.
1845        #[arg(long)]
1846        doi: Option<String>,
1847        /// Emit JSON to stdout.
1848        #[arg(long)]
1849        json: bool,
1850    },
1851    /// v0.34: List predictions in a frontier with their resolution state.
1852    Predictions {
1853        frontier: PathBuf,
1854        /// Optional actor filter.
1855        #[arg(long)]
1856        by: Option<String>,
1857        /// Show only unresolved predictions.
1858        #[arg(long)]
1859        open: bool,
1860        /// Emit JSON to stdout.
1861        #[arg(long)]
1862        json: bool,
1863    },
1864    /// v0.34: Compute calibration scores (Brier, log score, hit rate)
1865    /// for one or all actors with predictions in the frontier.
1866    Calibration {
1867        frontier: PathBuf,
1868        /// Optional actor filter (e.g. `reviewer:will-blair`).
1869        #[arg(long)]
1870        actor: Option<String>,
1871        /// Emit JSON to stdout.
1872        #[arg(long)]
1873        json: bool,
1874    },
1875    /// v0.40.1: Walk every prediction and mark as `expired_unresolved`
1876    /// any whose deadline has passed without an explicit Resolution.
1877    /// Emits one `prediction.expired_unresolved` event per newly-
1878    /// expired prediction. Idempotent. Calibration counts expired
1879    /// predictions separately from resolved ones — the predictor is
1880    /// answering for the missing commitment without their Brier or
1881    /// log score being moved by it.
1882    PredictionsExpire {
1883        frontier: PathBuf,
1884        /// Override the system clock (RFC 3339). Useful for tests
1885        /// and reproducibility; defaults to `now`.
1886        #[arg(long)]
1887        now: Option<String>,
1888        /// Run the check but don't write any events or flag any
1889        /// predictions. Reports what *would* expire.
1890        #[arg(long)]
1891        dry_run: bool,
1892        #[arg(long)]
1893        json: bool,
1894    },
1895    /// v0.35: Compute consensus over claim-similar findings, weighted
1896    /// by evidence quality. Takes a target `vf_<id>` and finds other
1897    /// findings making a similar assertion (shared entities + text
1898    /// overlap), weighs them by replication count + citation count
1899    /// + review state, and returns a consensus confidence with a
1900    /// credible interval. The substrate move that turns "what does
1901    /// the field hold about X?" from a manual graph walk into a
1902    /// queryable result.
1903    Consensus {
1904        /// Path to the frontier (project dir, `.vela/` repo, or `.json`).
1905        frontier: PathBuf,
1906        /// Target finding id (`vf_<hash>`).
1907        target: String,
1908        /// Weighting scheme: `unweighted` | `replication` | `citation` |
1909        /// `composite`. Default is `composite`.
1910        #[arg(long, default_value = "composite")]
1911        weighting: String,
1912        /// v0.38.2: restrict neighbor findings to a specific causal
1913        /// claim type: `correlation` | `mediation` | `intervention`.
1914        /// Useful for asking "what does the field hold *as
1915        /// causation*?" — distinct from the global blend.
1916        #[arg(long)]
1917        causal_claim: Option<String>,
1918        /// v0.38.2: restrict neighbor findings to study designs at or
1919        /// above the given grade: `theoretical` | `observational` |
1920        /// `quasi_experimental` | `rct`. Findings with no grade are
1921        /// excluded when this is set.
1922        #[arg(long)]
1923        causal_grade_min: Option<String>,
1924        /// Emit JSON to stdout.
1925        #[arg(long)]
1926        json: bool,
1927    },
1928
1929    // v0.74: top-level alias verbs. Each variant is a thin wrapper
1930    // routing to an existing canonical-event emission path. No new
1931    // substrate logic. The aliases exist so the daily flow reads
1932    // `init / ingest / propose / diff / accept / attest / log /
1933    // lineage / serve` rather than burying the verbs under
1934    // `proposals accept`, `sign apply`, `history`. See plan
1935    // v0.74.1.
1936    /// v0.74: ingest a single file or folder, dispatching by
1937    /// extension to the right backing path. Aliases:
1938    ///   `.pdf` or folder of pdfs -> `scout`
1939    ///   `.md` or folder of notes -> `compile-notes`
1940    ///   `.csv` / `.tsv`          -> `compile-data`
1941    ///   `.json` (Carina packet)  -> `artifact-to-state`
1942    ///   `doi:` / `pmid:` / `nct:` URI -> `source-fetch`
1943    ///   repo dir                 -> `compile-code`
1944    Ingest {
1945        /// File path or folder to ingest. Also accepts a stable
1946        /// identifier URI (`doi:<doi>`, `pmid:<id>`, `nct:<id>`).
1947        path: String,
1948        /// Frontier file or `.vela/` repo the proposals or sources
1949        /// land in.
1950        #[arg(long)]
1951        frontier: PathBuf,
1952        /// LLM backend override for agent-driven paths
1953        /// (scout/compile-*). Ignored for source-fetch and
1954        /// artifact-to-state.
1955        #[arg(short, long)]
1956        backend: Option<String>,
1957        /// Actor recording the ingest. Required for
1958        /// artifact-to-state; defaults to
1959        /// `agent:vela-ingest-bot` for agent paths.
1960        #[arg(long)]
1961        actor: Option<String>,
1962        /// Preview without writing.
1963        #[arg(long)]
1964        dry_run: bool,
1965        #[arg(long)]
1966        json: bool,
1967    },
1968
1969    /// v0.74: shortcut for the most common reviewer proposal, a
1970    /// `finding.review` verdict. Mirrors `vela review`. Other
1971    /// proposal kinds (note, caveat, revise, reject, retract)
1972    /// keep their existing top-level verbs and stay reachable via
1973    /// `vela help advanced`.
1974    Propose {
1975        frontier: PathBuf,
1976        finding_id: String,
1977        /// One of: accepted | needs_revision | contested | rejected.
1978        #[arg(long)]
1979        status: String,
1980        #[arg(long)]
1981        reason: String,
1982        #[arg(long)]
1983        reviewer: String,
1984        /// Apply the proposal immediately under reviewer authority
1985        /// (writes a signed canonical event).
1986        #[arg(long)]
1987        apply: bool,
1988        #[arg(long)]
1989        json: bool,
1990    },
1991
1992    /// v0.74: alias for `proposals accept`. Apply a pending
1993    /// proposal under the configured reviewer id, emitting the
1994    /// signed canonical event.
1995    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    /// v0.74: alias for `sign apply`. Sign every unsigned finding
2007    /// in the frontier under the supplied private key.
2008    ///
2009    /// v0.80: extended with `--event <vev_id>` for per-event
2010    /// attestation. When `--event` is supplied, instead of signing
2011    /// findings frontier-wide, the substrate emits an
2012    /// `attestation.recorded` canonical event pointing at the
2013    /// target event id. Useful for layered attestation
2014    /// (e.g. a second reviewer countersigning a finding.reviewed
2015    /// event, or a Lean run attesting a Stupp-protocol claim by
2016    /// pointing at its accept event).
2017    Attest {
2018        /// Frontier path. Required.
2019        frontier: PathBuf,
2020        /// Per-event mode: target event id (`vev_*`).
2021        /// When omitted, runs the v0.74 frontier-wide
2022        /// `sign apply` path.
2023        #[arg(long)]
2024        event: Option<String>,
2025        /// Reviewer attester id (`reviewer:<name>` or
2026        /// `agent:<name>`). Required for per-event mode.
2027        #[arg(long)]
2028        attester: Option<String>,
2029        /// Scope note explaining what this attestation covers.
2030        /// Required for per-event mode.
2031        #[arg(long)]
2032        scope_note: Option<String>,
2033        /// Optional Carina Proof primitive id (`vpf_*`) the
2034        /// attestation is backed by.
2035        #[arg(long)]
2036        proof_id: Option<String>,
2037        /// Optional Ed25519 signature over the target event's
2038        /// canonical preimage. Future-cycle work to verify; today
2039        /// the substrate stores the signature and trusts the
2040        /// emitter's keypair.
2041        #[arg(long)]
2042        signature: Option<String>,
2043        /// v0.74 frontier-wide path: private key for `sign apply`.
2044        /// Ignored in per-event mode.
2045        #[arg(long)]
2046        key: Option<PathBuf>,
2047        #[arg(long)]
2048        json: bool,
2049    },
2050
2051    /// v0.74: alias for `history`. Show the state-transition replay
2052    /// for one finding, optionally as-of an RFC3339 timestamp.
2053    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    /// v0.75: validate Carina-shaped JSON against the bundled
2063    /// schemas, list bundled primitives, or print one schema.
2064    Carina {
2065        #[command(subcommand)]
2066        action: CarinaAction,
2067    },
2068
2069    /// v0.78: Atlas-level surface. Compose multiple Vela
2070    /// frontiers into a domain-level living map (`vat_*`).
2071    /// Read-only over per-frontier event logs. See
2072    /// `docs/MISSION_ATLAS.md`.
2073    Atlas {
2074        #[command(subcommand)]
2075        action: AtlasAction,
2076    },
2077
2078    /// v0.82: Constellation-level surface. Compose multiple
2079    /// Atlases into a cross-domain network (`vco_*`). The
2080    /// fifteenth Carina primitive's CLI surface. Read-only
2081    /// over per-Atlas snapshots. See `docs/MISSION_ATLAS.md`
2082    /// and `docs/CONSTELLATE.md`.
2083    Constellation {
2084        #[command(subcommand)]
2085        action: ConstellationAction,
2086    },
2087}
2088
2089/// v0.78: actions on the Atlas-level surface. Each routes through
2090/// a handler registered by the binary at startup, calling into the
2091/// `vela-atlas` crate. Doctrine: read-only over per-frontier event
2092/// logs; never mutates frontier state.
2093#[derive(Subcommand)]
2094enum AtlasAction {
2095    /// Scaffold a new Atlas at `<atlases-root>/<name>/manifest.yaml`
2096    /// pointing at one or more existing frontier paths. Computes a
2097    /// content-addressed `vat_*` id from the composing frontier
2098    /// vfr_ids.
2099    Init {
2100        /// Atlas name (also used for the directory under
2101        /// `<atlases-root>/`).
2102        name: String,
2103        /// Frontier paths to compose. At least one required.
2104        #[arg(long, value_delimiter = ',', num_args = 1..)]
2105        frontiers: Vec<PathBuf>,
2106        /// Scientific domain (e.g. `oncology`,
2107        /// `additive combinatorics`).
2108        #[arg(long, default_value = "general")]
2109        domain: String,
2110        /// Optional bounded-question scope text.
2111        #[arg(long)]
2112        scope_note: Option<String>,
2113        /// Atlases root directory. Defaults to `./atlases/`.
2114        #[arg(long, default_value = "atlases")]
2115        atlases_root: PathBuf,
2116        #[arg(long)]
2117        json: bool,
2118    },
2119    /// Materialize an Atlas: read each composing frontier, union
2120    /// accepted-core findings, compute composition hash, write
2121    /// `<atlases-root>/<name>/snapshot.json`.
2122    Materialize {
2123        /// Atlas name (directory under `<atlases-root>/`).
2124        name: String,
2125        #[arg(long, default_value = "atlases")]
2126        atlases_root: PathBuf,
2127        #[arg(long)]
2128        json: bool,
2129    },
2130    /// Open the local Workbench against the Atlas-level snapshot.
2131    /// At v0.78 this delegates to the per-frontier Workbench for
2132    /// the first composing frontier; the dedicated Atlas-level
2133    /// Workbench page lands in v0.79+.
2134    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    /// v0.81.2: Update an existing Atlas by adding or removing
2144    /// composing frontiers. Re-computes the Atlas's `vat_*` id
2145    /// from the new composing-frontier list (content-addressing
2146    /// is honest about composition changes). Avoids the
2147    /// `rm -rf atlases/<name> && atlas init` workflow that the
2148    /// v0.78 substrate forced.
2149    Update {
2150        name: String,
2151        /// Frontier paths to add (idempotent: already-composed
2152        /// frontiers are skipped).
2153        #[arg(long, value_delimiter = ',')]
2154        add_frontier: Vec<PathBuf>,
2155        /// `vfr_*` ids to remove from the Atlas. Errors if any
2156        /// id isn't currently composed.
2157        #[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/// v0.82: actions on the Constellation-level surface.
2167/// Mirrors AtlasAction one layer up: Atlases compose into a
2168/// Constellation just as frontiers compose into an Atlas.
2169#[derive(Subcommand)]
2170enum ConstellationAction {
2171    /// Scaffold a new Constellation pointing at one or more
2172    /// Atlas dirs. Computes a content-addressed `vco_*` id
2173    /// from the composing-atlas vat_id list.
2174    Init {
2175        name: String,
2176        /// Atlas directories to compose. At least one required.
2177        #[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 a Constellation: re-materialize each
2187    /// composing Atlas on demand, sum findings + events +
2188    /// bridges across, compute composition hash, write
2189    /// `snapshot.json` and a static `index.html`.
2190    Materialize {
2191        name: String,
2192        #[arg(long, default_value = "constellations")]
2193        constellations_root: PathBuf,
2194        #[arg(long)]
2195        json: bool,
2196    },
2197    /// Serve the Constellation snapshot over HTTP. Static-file
2198    /// only at v0.82; interactive cross-Atlas surfaces are
2199    /// future cycles.
2200    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/// v0.75: actions on the Carina spec deliverable. Each one talks
2212/// to the schemas embedded under
2213/// `crates/vela-protocol/embedded/carina-schemas/`.
2214#[derive(Subcommand)]
2215enum CarinaAction {
2216    /// Validate a JSON file against the matching Carina schema.
2217    /// Detects the primitive automatically from the input's
2218    /// `schema: "carina.<name>.v0.X"` field, or accepts an
2219    /// explicit `--primitive <name>`.
2220    Validate {
2221        /// Path to a JSON file containing one Carina primitive,
2222        /// or a `primitives.v0.X.json`-style aggregate object
2223        /// with a `primitives` map.
2224        path: PathBuf,
2225        /// Override auto-detection: validate as a specific
2226        /// primitive (`finding`, `evidence`, `proof`, ...).
2227        #[arg(long)]
2228        primitive: Option<String>,
2229        #[arg(long)]
2230        json: bool,
2231    },
2232    /// List the 14 bundled Carina primitives.
2233    List {
2234        #[arg(long)]
2235        json: bool,
2236    },
2237    /// Print one bundled Carina schema to stdout.
2238    Schema { primitive: String },
2239}
2240
2241#[derive(Subcommand)]
2242enum PacketAction {
2243    /// Inspect a proof packet manifest
2244    Inspect {
2245        path: PathBuf,
2246        #[arg(long)]
2247        json: bool,
2248    },
2249    /// Validate a proof packet
2250    Validate {
2251        path: PathBuf,
2252        #[arg(long)]
2253        json: bool,
2254    },
2255}
2256
2257#[derive(Subcommand)]
2258enum SignAction {
2259    /// Generate an Ed25519 keypair
2260    GenerateKeypair {
2261        #[arg(long, default_value = ".vela/keys")]
2262        out: PathBuf,
2263        #[arg(long)]
2264        json: bool,
2265    },
2266    /// Sign unsigned findings in a frontier
2267    Apply {
2268        frontier: PathBuf,
2269        #[arg(long)]
2270        private_key: PathBuf,
2271        #[arg(long)]
2272        json: bool,
2273    },
2274    /// Verify frontier signatures
2275    Verify {
2276        frontier: PathBuf,
2277        #[arg(long)]
2278        public_key: Option<PathBuf>,
2279        #[arg(long)]
2280        json: bool,
2281    },
2282    /// v0.37: Attach a multi-signature threshold to a finding. Once
2283    /// `k` distinct registered actors have each signed the finding, it
2284    /// is marked `jointly_accepted`. Setting `--to 1` is equivalent to
2285    /// the default single-sig regime.
2286    ThresholdSet {
2287        frontier: PathBuf,
2288        /// Target finding id (`vf_<hash>`).
2289        finding_id: String,
2290        /// Number of unique valid signatures required (>= 1).
2291        #[arg(long)]
2292        to: u32,
2293        #[arg(long)]
2294        json: bool,
2295    },
2296}
2297
2298#[derive(Subcommand)]
2299enum ActorAction {
2300    /// Register an Ed25519 public key for a stable actor identity
2301    Add {
2302        frontier: PathBuf,
2303        /// Stable actor id (e.g. "reviewer:will-blair")
2304        id: String,
2305        /// Hex-encoded Ed25519 public key (64 hex chars)
2306        #[arg(long)]
2307        pubkey: String,
2308        /// Optional trust tier (Phase α, v0.6). Currently recognized:
2309        /// "auto-notes" — permits one-call propose_and_apply_note.
2310        /// Unknown tier strings load fine but never grant auto-apply.
2311        #[arg(long)]
2312        tier: Option<String>,
2313        /// v0.43: Optional ORCID identifier for cross-system identity.
2314        /// Format `0000-0000-0000-000X`. Accepts bare form, URL form
2315        /// (`https://orcid.org/0000-...`), or `orcid:` prefix.
2316        #[arg(long)]
2317        orcid: Option<String>,
2318        /// v0.51: Optional read-side access clearance.
2319        /// `public` (default), `restricted`, or `classified`. Higher
2320        /// clearance permits reading lower-tier objects through
2321        /// `vela serve`'s actor-aware MCP/HTTP read paths.
2322        #[arg(long)]
2323        clearance: Option<String>,
2324        #[arg(long)]
2325        json: bool,
2326    },
2327    /// List registered actors in a frontier
2328    List {
2329        frontier: PathBuf,
2330        #[arg(long)]
2331        json: bool,
2332    },
2333    /// v0.127: Rotate an actor's signing key. Registers a new actor
2334    /// record under a versioned id, marks the prior actor as revoked
2335    /// at the current timestamp, and pins a free-form reason. Closes
2336    /// THREAT_MODEL.md A7 (compromised reviewer key) by giving
2337    /// reviewers a primitive for retiring a key without inventing
2338    /// per-frontier ceremony. Historical signatures under the
2339    /// retired key remain valid (the substrate does not retroactively
2340    /// invalidate canonical history); new signatures with the retired
2341    /// key are flagged as `post_revocation_signature` errors by the
2342    /// signals layer.
2343    Rotate {
2344        frontier: PathBuf,
2345        /// Existing actor id to retire (e.g. `reviewer:will-blair`).
2346        /// Must be currently registered and not already revoked.
2347        #[arg(long)]
2348        id: String,
2349        /// New actor id to register (e.g.
2350        /// `reviewer:will-blair-v2-2026-05-10`). Must not collide
2351        /// with an existing actor id. Convention: append `-v<N>` or
2352        /// `-v<N>-<date>` to the prior id.
2353        #[arg(long = "new-id")]
2354        new_id: String,
2355        /// New Ed25519 public key (64 hex chars).
2356        #[arg(long = "new-pubkey")]
2357        new_pubkey: String,
2358        /// Free-form reason recorded against the retired actor's
2359        /// `revoked_reason` field.
2360        #[arg(long)]
2361        reason: String,
2362        #[arg(long)]
2363        json: bool,
2364    },
2365    /// v0.155: Look up an ORCID identifier via the public ORCID
2366    /// API and emit the resolved name + affiliation. Optionally
2367    /// auto-register an actor record on a frontier with the
2368    /// resolved name. Skip-graceful when offline.
2369    LookupOrcid {
2370        /// Bare ORCID (`0000-0000-0000-000X`), `orcid:` prefix,
2371        /// or full URL form.
2372        orcid: String,
2373        /// When set, auto-register an actor record on this
2374        /// frontier with the resolved ORCID + the supplied
2375        /// `--id` + `--pubkey`. Without this flag, the command
2376        /// just prints the lookup result.
2377        #[arg(long)]
2378        register_on: Option<PathBuf>,
2379        /// Stable actor id (required when `--register-on` is
2380        /// set; e.g. `reviewer:will-blair`).
2381        #[arg(long)]
2382        id: Option<String>,
2383        /// Hex-encoded Ed25519 pubkey (required when
2384        /// `--register-on` is set).
2385        #[arg(long)]
2386        pubkey: Option<String>,
2387        #[arg(long)]
2388        json: bool,
2389    },
2390}
2391
2392/// v0.131: AI-agent scaffolding subcommands. The agent layer is
2393/// purely substrate-side: an agent gets an Ed25519 keypair and an
2394/// `agent:<slug>-<date>` actor id; the agent then drafts proposals
2395/// against frontiers it has been registered in. The substrate
2396/// makes the agent-draft / human-verdict distinction load-bearing
2397/// (see docs/AI_ATTRIBUTION.md).
2398#[derive(Subcommand)]
2399enum AgentAction {
2400    /// Scaffold an agent identity kit at `agents/<slug>/`. Creates
2401    /// `agent.yaml` (config), `actor.json` (the substrate-side
2402    /// actor record for `actor add`), `keys/` (Ed25519 keypair).
2403    Init {
2404        /// Short agent name (slug). The canonical actor id becomes
2405        /// `agent:<slug>-<rfc3339-date>`.
2406        name: String,
2407        /// Framework hint stored in `agent.yaml`. One of:
2408        /// `claude-code`, `claude-api`, `langchain`, `openai`,
2409        /// `agent4science`, `scienceclaw`, `custom`.
2410        #[arg(long, default_value = "custom")]
2411        framework: String,
2412        /// Output directory. Defaults to `agents/<slug>/`.
2413        #[arg(long)]
2414        out: Option<PathBuf>,
2415        #[arg(long)]
2416        json: bool,
2417    },
2418    /// List every scaffolded agent under `agents/`.
2419    List {
2420        /// Agents root directory. Defaults to `./agents/`.
2421        #[arg(long, default_value = "agents")]
2422        root: PathBuf,
2423        #[arg(long)]
2424        json: bool,
2425    },
2426}
2427
2428#[derive(Subcommand)]
2429enum CausalAction {
2430    /// v0.40: Audit every finding's (causal_claim, causal_evidence_grade)
2431    /// for identifiability. Reports underidentified, conditional,
2432    /// and underdetermined findings with rationale + remediation.
2433    Audit {
2434        frontier: PathBuf,
2435        /// Restrict the report to entries needing reviewer attention
2436        /// (Underidentified or Conditional). Useful for triage.
2437        #[arg(long)]
2438        problems_only: bool,
2439        #[arg(long)]
2440        json: bool,
2441    },
2442    /// v0.44 (Pearl level 2): Identify the causal effect of a source
2443    /// finding on a target finding by searching for a back-door
2444    /// adjustment set in the frontier's directed link graph. Reports
2445    /// either the adjustment set Z that identifies P(target | do(source))
2446    /// from observational data alone, or surfaces the open back-door
2447    /// paths that prevent identification.
2448    ///
2449    /// The link graph used: `depends` and `supports` edges. Every
2450    /// finding's parents are the findings it relies on as evidence;
2451    /// every finding's children are the findings that build on it.
2452    /// `contradicts` and other link types are excluded from the
2453    /// causal DAG.
2454    Effect {
2455        frontier: PathBuf,
2456        /// Source finding id (`vf_<hash>`).
2457        source: String,
2458        /// Target finding id, given via `--on`.
2459        #[arg(long)]
2460        on: String,
2461        #[arg(long)]
2462        json: bool,
2463    },
2464    /// v0.44: Print the causal-graph topology over the frontier.
2465    /// Lists each node's parents and children for inspection.
2466    Graph {
2467        frontier: PathBuf,
2468        /// Limit output to a single node's neighborhood.
2469        #[arg(long)]
2470        node: Option<String>,
2471        #[arg(long)]
2472        json: bool,
2473    },
2474    /// v0.45 (Pearl level 3): answer a counterfactual query of the form
2475    /// "if we had observed `intervene_on` at `value`, what would
2476    /// `target`'s confidence have been?" Twin-network propagation
2477    /// requires every edge on the source→target paths to declare a
2478    /// `mechanism`; edges without one block propagation honestly with
2479    /// a `mechanism_unspecified` verdict.
2480    Counterfactual {
2481        frontier: PathBuf,
2482        /// The finding to intervene on (`vf_<hash>`).
2483        intervene_on: String,
2484        /// The confidence value to set on the intervened finding (in [0,1]).
2485        #[arg(long)]
2486        set_to: f64,
2487        /// The target finding whose counterfactual confidence we want (`vf_<hash>`).
2488        #[arg(long)]
2489        target: String,
2490        #[arg(long)]
2491        json: bool,
2492    },
2493}
2494
2495#[derive(Subcommand)]
2496enum BridgesAction {
2497    /// Derive bridges between two frontiers and persist the resulting
2498    /// `vbr_<id>` records under the *first* frontier's `.vela/bridges/`
2499    /// directory. Idempotent on (entity, sorted-frontier-pair).
2500    Derive {
2501        /// First frontier (Vela repo or frontier JSON file).
2502        /// Bridges are persisted under this frontier.
2503        frontier_a: PathBuf,
2504        /// Human label for the first frontier in bridge records.
2505        #[arg(long, default_value = "a")]
2506        label_a: String,
2507        /// Second frontier (Vela repo or frontier JSON file).
2508        frontier_b: PathBuf,
2509        /// Human label for the second frontier in bridge records.
2510        #[arg(long, default_value = "b")]
2511        label_b: String,
2512        #[arg(long)]
2513        json: bool,
2514    },
2515    /// List bridges persisted under a frontier's `.vela/bridges/` dir.
2516    List {
2517        /// Frontier (must be a Vela repo with a `.vela/` directory).
2518        frontier: PathBuf,
2519        /// Filter by status: derived, confirmed, refuted.
2520        #[arg(long)]
2521        status: Option<String>,
2522        #[arg(long)]
2523        json: bool,
2524    },
2525    /// Show a single bridge by `vbr_<id>`.
2526    Show {
2527        frontier: PathBuf,
2528        bridge_id: String,
2529        #[arg(long)]
2530        json: bool,
2531    },
2532    /// Promote a bridge from `derived` to `confirmed`. Persists in
2533    /// place; the content-address `vbr_<id>` is unchanged. v0.67:
2534    /// emits a `bridge.reviewed` canonical event under the configured
2535    /// reviewer id so federation sync can propagate the verdict.
2536    Confirm {
2537        frontier: PathBuf,
2538        bridge_id: String,
2539        /// Reviewer identity attaching the verdict. Defaults to
2540        /// $VELA_REVIEWER_ID or `reviewer:will-blair`.
2541        #[arg(long)]
2542        reviewer: Option<String>,
2543        /// Optional verdict note.
2544        #[arg(long)]
2545        note: Option<String>,
2546        #[arg(long)]
2547        json: bool,
2548    },
2549    /// Mark a bridge `refuted`. Persists in place. v0.67: emits a
2550    /// `bridge.reviewed` canonical event with `status: refuted`.
2551    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    /// v0.39: Register a peer hub in this frontier. Adding a peer
2566    /// declares awareness — it does not trust their state. Sync /
2567    /// merge runtime ships in v0.39.1+.
2568    PeerAdd {
2569        frontier: PathBuf,
2570        /// Stable peer id (e.g. `hub:vela-mirror-eu`).
2571        id: String,
2572        /// HTTPS URL where the peer publishes signed manifests.
2573        #[arg(long)]
2574        url: String,
2575        /// Hex-encoded Ed25519 public key (64 hex chars).
2576        #[arg(long)]
2577        pubkey: String,
2578        /// Optional human-readable note (e.g. "EU mirror, run by lab Z").
2579        #[arg(long, default_value = "")]
2580        note: String,
2581        #[arg(long)]
2582        json: bool,
2583    },
2584    /// List federation peers registered in a frontier.
2585    PeerList {
2586        frontier: PathBuf,
2587        #[arg(long)]
2588        json: bool,
2589    },
2590    /// Remove a peer from the registry. Does not retroactively
2591    /// invalidate events that referenced the peer; just stops further
2592    /// sync attempts.
2593    PeerRemove {
2594        frontier: PathBuf,
2595        id: String,
2596        #[arg(long)]
2597        json: bool,
2598    },
2599    /// v0.39.1 / v0.41.0: Sync our frontier against a peer's
2600    /// published view. Three modes:
2601    ///   1. `--via-hub --vfr-id <id>`: route through the peer hub's
2602    ///      `/entries/<vfr_id>` endpoint, verify the registry entry
2603    ///      signature, follow the locator. The "real federation"
2604    ///      path. Surfaces broken-locator and unverified-entry
2605    ///      conflicts when the peer is reachable but stale.
2606    ///   2. `--url <override>`: fetch directly from a manifest URL,
2607    ///      bypassing the hub's registry. Useful for static-mirror
2608    ///      peers (raw GitHub) or for testing.
2609    ///   3. (default): tries `<peer.url>/manifest/<frontier_id>.json`.
2610    /// Diffs the resulting Project against ours, appends one
2611    /// `frontier.synced_with_peer` event + one
2612    /// `frontier.conflict_detected` event per disagreement.
2613    /// Read-only with respect to findings; conflict resolution
2614    /// happens through subsequent reviewer-signed proposals.
2615    Sync {
2616        frontier: PathBuf,
2617        /// Peer id (must already be in the registry).
2618        peer_id: String,
2619        /// Direct manifest URL override.
2620        #[arg(long)]
2621        url: Option<String>,
2622        /// Route through the peer hub's `/entries/<vfr-id>` endpoint
2623        /// (verify entry signature, follow locator). Requires
2624        /// `--vfr-id`.
2625        #[arg(long)]
2626        via_hub: bool,
2627        /// vfr_id to fetch when using `--via-hub`. Defaults to our
2628        /// local frontier_id when omitted.
2629        #[arg(long)]
2630        vfr_id: Option<String>,
2631        /// v0.64: opt-in flag to allow `--via-hub --vfr-id <peer_vfr>`
2632        /// where `<peer_vfr>` differs from the local frontier's id.
2633        /// Without this flag, cross-vfr sync is refused because every
2634        /// peer-side finding gets recorded as a "missing_locally"
2635        /// conflict, flooding the inbox with substrate-honest but
2636        /// operationally noisy events.
2637        #[arg(long)]
2638        allow_cross_vfr: bool,
2639        /// Run the diff but don't append events.
2640        #[arg(long)]
2641        dry_run: bool,
2642        #[arg(long)]
2643        json: bool,
2644    },
2645    /// v0.70: Push a single locally-resolved
2646    /// `frontier.conflict_resolved` event back to the originating
2647    /// peer hub. Reads the event from the local frontier, signs the
2648    /// canonical bytes with the supplied private key (or the actor's
2649    /// key under `~/.config/vela/keys/`), and POSTs to the peer's
2650    /// `/entries/<vfr_id>/events` endpoint with paired
2651    /// `X-Vela-Signer-Pubkey` and `X-Vela-Signature` headers.
2652    /// One event at a time; the hub validates signature, actor
2653    /// pubkey, pairing against an existing
2654    /// `frontier.conflict_detected`, and idempotency on the
2655    /// resolution. Subsequent `vela federation sync` calls against
2656    /// that hub return the resolution to anyone else who pulls.
2657    PushResolution {
2658        frontier: PathBuf,
2659        /// The id of the original `frontier.conflict_detected`
2660        /// event whose paired `frontier.conflict_resolved` event
2661        /// should be pushed.
2662        conflict_event_id: String,
2663        /// Peer id (must already be in the registry).
2664        #[arg(long = "to")]
2665        to: String,
2666        /// Path to the actor's Ed25519 private key file (hex). If
2667        /// omitted, looks up `~/.config/vela/keys/<actor_id>.key`,
2668        /// then `~/.config/vela/keys/private.key`.
2669        #[arg(long)]
2670        key: Option<PathBuf>,
2671        /// Override the vfr_id sent to the peer (defaults to the
2672        /// local frontier_id).
2673        #[arg(long)]
2674        vfr_id: Option<String>,
2675        #[arg(long)]
2676        json: bool,
2677    },
2678}
2679
2680#[derive(Subcommand)]
2681enum ReviewThreadCli {
2682    /// Create a fresh review thread on a target (`vpr_*`,
2683    /// `vf_*`, or `vsd_*` Scientific Diff Pack). Writes the
2684    /// empty thread JSON to `--out`.
2685    Create {
2686        /// `vpr_*`, `vf_*`, or `vsd_*` target id.
2687        target: String,
2688        #[arg(long)]
2689        frontier_id: String,
2690        #[arg(long)]
2691        out: PathBuf,
2692        #[arg(long)]
2693        json: bool,
2694    },
2695    /// Append a signed message to an existing thread. The
2696    /// signing key is read from disk in raw 32-byte hex form.
2697    Post {
2698        /// Existing thread JSON file (will be rewritten in
2699        /// place to include the new message).
2700        thread: PathBuf,
2701        #[arg(long)]
2702        author_actor_id: String,
2703        /// Path to a 32-byte hex-encoded Ed25519 signing key.
2704        #[arg(long)]
2705        key: PathBuf,
2706        /// Message body (free-form text).
2707        #[arg(long)]
2708        message: String,
2709        /// Optional parent `vrm_*` id (for threaded replies).
2710        #[arg(long)]
2711        parent: Option<String>,
2712        #[arg(long)]
2713        json: bool,
2714    },
2715    /// Verify every message in a thread: signature against
2716    /// declared pubkey + id matches preimage.
2717    Verify {
2718        thread: PathBuf,
2719        #[arg(long)]
2720        json: bool,
2721    },
2722}
2723
2724#[derive(Subcommand)]
2725enum HubSpecCli {
2726    /// Build a `vhs_*` spec record and write it to `--out`.
2727    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 an existing `vhs_*` spec file: re-derive the id
2748    /// and check it matches the record.
2749    Validate {
2750        spec: PathBuf,
2751        #[arg(long)]
2752        json: bool,
2753    },
2754}
2755
2756#[derive(Subcommand)]
2757enum LeanAction {
2758    /// Anchor every theorem in the substrate registry. Writes
2759    /// one `vla_*` anchor JSON per theorem under <output>/.
2760    AnchorAll {
2761        /// Path to the `lean/` directory (defaults to repo root).
2762        #[arg(long)]
2763        lean_dir: Option<PathBuf>,
2764        /// Output directory for anchor JSON files. Defaults to
2765        /// `./theorems/`.
2766        #[arg(long, default_value = "./theorems")]
2767        out: PathBuf,
2768        #[arg(long)]
2769        json: bool,
2770    },
2771    /// Anchor a single theorem by its id (1..=6 in Arc 6 wave 1).
2772    Anchor {
2773        /// Theorem id (e.g. 1 for T1).
2774        id: u32,
2775        #[arg(long)]
2776        lean_dir: Option<PathBuf>,
2777        /// Output path for the anchor record (default: stdout).
2778        #[arg(long)]
2779        out: Option<PathBuf>,
2780        #[arg(long)]
2781        json: bool,
2782    },
2783    /// List the substrate's registered theorems.
2784    List {
2785        #[arg(long)]
2786        json: bool,
2787    },
2788    /// v0.170: generate a fresh Ed25519 verifier keypair. Writes
2789    /// the 32-byte private key (hex) to `--key-out` and the
2790    /// public-key spec JSON to `--pub-out`.
2791    Keygen {
2792        #[arg(long)]
2793        key_out: PathBuf,
2794        #[arg(long)]
2795        pub_out: PathBuf,
2796        /// Free-form identity to embed in the public-key spec
2797        /// (e.g. "github-action:vela-science/vela:verify-lean-bundle").
2798        #[arg(long)]
2799        actor: String,
2800    },
2801    /// v0.170: sign verification records for every anchor in
2802    /// `--anchors-dir`. Reads `--build-log` and computes its
2803    /// sha256 as the verifier_output_hash; the lake build that
2804    /// produced that log must have completed cleanly.
2805    VerifyAll {
2806        /// Directory containing T<N>.anchor.json files (default:
2807        /// `./theorems`).
2808        #[arg(long, default_value = "./theorems")]
2809        anchors_dir: PathBuf,
2810        /// Output directory for T<N>.vlv.json verification records
2811        /// (default: same as anchors_dir).
2812        #[arg(long)]
2813        out_dir: Option<PathBuf>,
2814        /// Path to a lake build log file. Its sha256 becomes the
2815        /// verifier_output_hash; the file content is opaque to
2816        /// the substrate.
2817        #[arg(long)]
2818        build_log: PathBuf,
2819        /// Path to a 32-byte hex-encoded Ed25519 private key.
2820        #[arg(long)]
2821        key: PathBuf,
2822        /// Free-form verifier identity (e.g. github-action URL).
2823        #[arg(long)]
2824        actor: String,
2825        /// Lean toolchain pin (e.g. `leanprover/lean4:v4.29.1`).
2826        /// Defaults to the contents of `lean/lean-toolchain` if
2827        /// present.
2828        #[arg(long)]
2829        lean_toolchain: Option<String>,
2830        /// Mathlib revision (e.g. `v4.29.1`). Defaults to the
2831        /// `mathlib4.git` pin in `lean/lakefile.lean`.
2832        #[arg(long)]
2833        mathlib_revision: Option<String>,
2834        #[arg(long)]
2835        json: bool,
2836    },
2837    /// v0.170: verify a single `vlv_*` record: signature against
2838    /// declared pubkey + id derivation + anchor cross-check.
2839    VerifyCheck {
2840        record: PathBuf,
2841        /// Path to the matching T<N>.anchor.json. Confirms the
2842        /// record's anchor_id + module_sha256 still match.
2843        #[arg(long)]
2844        anchor: Option<PathBuf>,
2845        #[arg(long)]
2846        json: bool,
2847    },
2848}
2849
2850#[derive(Subcommand)]
2851enum DiffPackAction {
2852    /// Bundle N existing proposals into a Scientific Diff Pack.
2853    /// The pack is signed (if --key is supplied), content-addressed,
2854    /// and written to --out. The pack id can then be cited from a
2855    /// reviewer surface or a federated event.
2856    Create {
2857        /// Path to the frontier (project root or frontier.json file).
2858        frontier: PathBuf,
2859        /// Ordered list of vpr_* ids the pack bundles. Order matters
2860        /// (it's part of the canonical preimage).
2861        #[arg(long, value_delimiter = ',', required = true)]
2862        proposals: Vec<String>,
2863        /// Reviewer-readable summary (<=280 chars).
2864        #[arg(long)]
2865        summary: String,
2866        /// Plain-language category (e.g. finding.cluster_revision,
2867        /// evidence.refresh, correction.batch, agent.proposal_set).
2868        #[arg(long)]
2869        aggregate_kind: String,
2870        /// Optional v0.195 agent attestation envelope id.
2871        #[arg(long)]
2872        agent_run: Option<String>,
2873        /// Optional parent pack this one amends.
2874        #[arg(long)]
2875        parent_pack: Option<String>,
2876        /// Optional path to a 32-byte hex-encoded Ed25519 signing
2877        /// key. When present, the pack is signed under it.
2878        #[arg(long)]
2879        key: Option<PathBuf>,
2880        /// Output path for the pack JSON.
2881        #[arg(long)]
2882        out: PathBuf,
2883        #[arg(long)]
2884        json: bool,
2885    },
2886    /// Pretty-print the contents of a `vsd_*` pack file.
2887    Show {
2888        pack: PathBuf,
2889        #[arg(long)]
2890        json: bool,
2891    },
2892    /// Verify a pack: pack_id matches re-derivation; signature
2893    /// verifies under declared pubkey if present.
2894    Verify {
2895        pack: PathBuf,
2896        #[arg(long)]
2897        json: bool,
2898    },
2899    /// v0.205: walk `.vela/pending_verdicts/` on the given
2900    /// frontier and promote each pending verdict to a canonical
2901    /// `diff_pack.reviewed` event. Atomic per-verdict: accept
2902    /// applies every canonical member or rolls back.
2903    PromoteVerdicts {
2904        /// Path to the frontier repo (with a `.vela/` directory).
2905        frontier: PathBuf,
2906        #[arg(long)]
2907        json: bool,
2908    },
2909    /// v0.221: scan `.vela/diff_packs/` and emit a canonical
2910    /// `diff_pack.released` event for every pack that does not
2911    /// already have one. Idempotent — re-running is a no-op once
2912    /// every pack has a release event. Closes the v0.213 reducer
2913    /// arm for frontiers built by pre-v0.221 scaffolding scripts
2914    /// that wrote packs to disk without emitting release events.
2915    BackfillRelease {
2916        /// Path to the frontier repo (with a `.vela/` directory).
2917        frontier: PathBuf,
2918        #[arg(long)]
2919        json: bool,
2920    },
2921    /// v0.216: witness-check a Scientific Diff Pack across N hubs.
2922    /// GETs `<hub>/diff-packs/<pack_id>` from each hub in --hubs
2923    /// and compares the signed body byte-for-byte. Reports verified
2924    /// / split / missing. Theorem 30 pins the soundness: verified
2925    /// responses imply N-way agreement on the pack body.
2926    WitnessCheck {
2927        /// The `vsd_*` pack id to witness-check.
2928        pack_id: String,
2929        /// Comma-separated list of hub base URLs.
2930        #[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 a tool descriptor (`vtd_*`). The descriptor is
2940    /// content-addressed over (tool_name, tool_version, provider,
2941    /// calling_convention, input_schema, output_schema) and written
2942    /// to --out. Input/output schemas are JSON files on disk.
2943    Register {
2944        #[arg(long)]
2945        tool_name: String,
2946        #[arg(long)]
2947        tool_version: String,
2948        /// Free-form provider identifier
2949        /// (e.g. tooluniverse:protein-fold:2024.10).
2950        #[arg(long)]
2951        provider: String,
2952        /// One of: http_json, python_callable, cli_subprocess,
2953        /// mcp_server.
2954        #[arg(long)]
2955        calling_convention: String,
2956        /// Path to a JSON file containing the tool's input schema.
2957        #[arg(long)]
2958        input_schema: PathBuf,
2959        /// Path to a JSON file containing the tool's output schema.
2960        #[arg(long)]
2961        output_schema: PathBuf,
2962        /// Optional URL evidencing the tool (paper, doc, release).
2963        #[arg(long)]
2964        evidence_url: Option<String>,
2965        /// Optional comma-separated list of vf_* finding ids that
2966        /// cite outputs from this tool.
2967        #[arg(long, value_delimiter = ',')]
2968        cited_in_findings: Vec<String>,
2969        /// Output path for the descriptor JSON.
2970        #[arg(long)]
2971        out: PathBuf,
2972        #[arg(long)]
2973        json: bool,
2974    },
2975    /// Pretty-print the contents of a `vtd_*` descriptor file.
2976    Show {
2977        descriptor: PathBuf,
2978        #[arg(long)]
2979        json: bool,
2980    },
2981    /// Verify a descriptor: descriptor_id matches re-derivation.
2982    Verify {
2983        descriptor: PathBuf,
2984        #[arg(long)]
2985        json: bool,
2986    },
2987}
2988
2989#[derive(Subcommand)]
2990enum EvalCliAction {
2991    /// Record an evaluation outcome against a substrate object.
2992    /// The record is content-addressed over its body and optionally
2993    /// signed under --key.
2994    Record {
2995        /// One of: vsd, vtr, vf, vpf, vtd, vaa.
2996        #[arg(long)]
2997        target_kind: String,
2998        /// Id of the targeted object (must match target_kind prefix).
2999        #[arg(long)]
3000        target_id: String,
3001        /// One of: replication, benchmark, validation, peer_review.
3002        #[arg(long)]
3003        evaluation_kind: String,
3004        /// One of: succeeded, failed, partial, inconclusive.
3005        #[arg(long)]
3006        outcome: String,
3007        /// Stable actor id (e.g. lab:replication_site_42).
3008        #[arg(long)]
3009        evaluator: String,
3010        /// Comma-separated evidence references (any kernel-object ids).
3011        #[arg(long, value_delimiter = ',')]
3012        evidence_refs: Vec<String>,
3013        /// Optional benchmark id (e.g. astabench:protein-fold:v1).
3014        #[arg(long)]
3015        benchmark_id: Option<String>,
3016        /// Optional numeric score.
3017        #[arg(long)]
3018        score: Option<f64>,
3019        /// Optional free-text notes.
3020        #[arg(long)]
3021        notes: Option<String>,
3022        /// Optional path to a 32-byte hex Ed25519 signing key.
3023        #[arg(long)]
3024        key: Option<PathBuf>,
3025        /// Output path for the record JSON.
3026        #[arg(long)]
3027        out: PathBuf,
3028        #[arg(long)]
3029        json: bool,
3030    },
3031    /// Pretty-print the contents of a `ver_*` record file.
3032    Show {
3033        record: PathBuf,
3034        #[arg(long)]
3035        json: bool,
3036    },
3037    /// Verify a record: record_id matches re-derivation; signature
3038    /// verifies under declared pubkey if present.
3039    Verify {
3040        record: PathBuf,
3041        #[arg(long)]
3042        json: bool,
3043    },
3044}
3045
3046#[derive(Subcommand)]
3047enum ConflictCliAction {
3048    /// Scan `.vela/pending_verdicts/` for contradicting verdicts
3049    /// on overlapping Diff Pack members. Returns a list of
3050    /// candidate-conflict records — pairs of vpv_* ids that
3051    /// disagree on at least one shared vpr_*.
3052    Detect {
3053        /// Path to the frontier repo (with a `.vela/` directory).
3054        frontier: PathBuf,
3055        #[arg(long)]
3056        json: bool,
3057    },
3058    /// Resolve a candidate conflict by recording a signed `vdc_*`
3059    /// and emitting a canonical `verdict_conflict.resolved` event.
3060    /// The losing verdicts stay on the log; this record cites them
3061    /// explicitly and pins why one won.
3062    Resolve {
3063        /// Path to the frontier repo (with a `.vela/` directory).
3064        frontier: PathBuf,
3065        /// Comma-separated list of vpv_* ids that contradict.
3066        #[arg(long, value_delimiter = ',', required = true)]
3067        verdicts: Vec<String>,
3068        /// Comma-separated list of shared vpr_* member ids.
3069        #[arg(long, value_delimiter = ',', required = true)]
3070        shared_members: Vec<String>,
3071        /// One of: majority | owner_override | escalation.
3072        #[arg(long)]
3073        mode: String,
3074        /// Stable actor id authorizing the resolution.
3075        #[arg(long)]
3076        resolver: String,
3077        /// Optional: the winning vpv_* (must be in --verdicts).
3078        #[arg(long)]
3079        winning: Option<String>,
3080        /// Free-text rationale for the resolution.
3081        #[arg(long)]
3082        rationale: Option<String>,
3083        /// Optional path to a 32-byte hex Ed25519 signing key.
3084        #[arg(long)]
3085        key: Option<PathBuf>,
3086        #[arg(long)]
3087        json: bool,
3088    },
3089    /// List every resolved `vdc_*` on the frontier.
3090    List {
3091        frontier: PathBuf,
3092        #[arg(long)]
3093        json: bool,
3094    },
3095}
3096
3097#[derive(Subcommand)]
3098enum FrontierAction {
3099    /// Scaffold a fresh, publishable `frontier.json` stub. The result
3100    /// passes `vela check --strict` immediately and is ready to accept
3101    /// findings via `vela finding add` and a publish via `vela registry
3102    /// publish`. Use this instead of `vela init` when you intend to
3103    /// publish to a hub — `init` creates a `.vela/` repo, which is not
3104    /// directly publishable in v0.
3105    New {
3106        /// Path to write the new frontier file (e.g. `./frontier.json`).
3107        path: PathBuf,
3108        /// Human-readable frontier name.
3109        #[arg(long)]
3110        name: String,
3111        /// Optional one-paragraph description of the bounded question.
3112        #[arg(long, default_value = "")]
3113        description: String,
3114        /// Overwrite if the file already exists.
3115        #[arg(long)]
3116        force: bool,
3117        #[arg(long)]
3118        json: bool,
3119    },
3120    /// Replay a split frontier repository into frontier.json and vela.lock.
3121    Materialize {
3122        /// Frontier repository directory.
3123        frontier: PathBuf,
3124        #[arg(long)]
3125        json: bool,
3126    },
3127    /// Declare a cross-frontier dependency. Subsequent links of the
3128    /// form `vf_<id>@vfr_<id>` resolve through this entry; strict
3129    /// validation refuses cross-frontier targets without one.
3130    AddDep {
3131        /// Path to the frontier file
3132        frontier: PathBuf,
3133        /// The remote frontier's content-addressed id (`vfr_…`)
3134        vfr_id: String,
3135        /// Where to fetch the remote frontier file from. Typically
3136        /// an `https://…` URL pointing at raw JSON.
3137        #[arg(long)]
3138        locator: String,
3139        /// SHA-256 of the remote's canonical snapshot. Strict pull
3140        /// verifies the fetched dependency's snapshot matches this.
3141        #[arg(long)]
3142        snapshot: String,
3143        /// Optional human-readable name for the dependency.
3144        #[arg(long)]
3145        name: Option<String>,
3146        #[arg(long)]
3147        json: bool,
3148    },
3149    /// List the frontier's declared dependencies.
3150    ListDeps {
3151        frontier: PathBuf,
3152        #[arg(long)]
3153        json: bool,
3154    },
3155    /// Remove a previously-declared cross-frontier dependency by `vfr_id`.
3156    /// Refuses if any link target still references it.
3157    RemoveDep {
3158        frontier: PathBuf,
3159        vfr_id: String,
3160        #[arg(long)]
3161        json: bool,
3162    },
3163    /// v0.11: re-pin every declared cross-frontier dependency to the
3164    /// hub's current snapshot for that `vfr_id`. Useful when a dep
3165    /// (e.g. BBB) republishes weekly and your local pin goes stale.
3166    /// Reports per-dep status: unchanged, refreshed (with old → new
3167    /// snapshot), missing (vfr_id not on hub), or unreachable. Does
3168    /// nothing destructive if --dry-run is passed.
3169    RefreshDeps {
3170        frontier: PathBuf,
3171        /// Hub URL to query. Defaults to https://vela-hub.fly.dev.
3172        #[arg(long, default_value = "https://vela-hub.fly.dev")]
3173        from: String,
3174        /// Show what would change without writing.
3175        #[arg(long)]
3176        dry_run: bool,
3177        #[arg(long)]
3178        json: bool,
3179    },
3180    /// v0.32: emit a structured diff of findings added, updated, and
3181    /// contradicted in a time window. The canonical replacement for the
3182    /// `scripts/weekly-diff.sh` Python fallback shipped in v0.31.
3183    ///
3184    /// Default window is the current ISO week (Monday 00:00 UTC →
3185    /// next Monday 00:00 UTC). Use `--since <RFC3339>` for an arbitrary
3186    /// start, or `--week YYYY-Www` for a specific ISO week.
3187    ///
3188    /// Output is JSON if `--json` is set; otherwise a human summary.
3189    /// The diff is read-only over the canonical state — it does not
3190    /// modify the frontier and does not require a signing key.
3191    Diff {
3192        /// Path to the frontier (project dir, `.vela/` repo, or `.json` file).
3193        frontier: PathBuf,
3194        /// Compute diff since this RFC 3339 timestamp.
3195        /// Mutually exclusive with `--week`.
3196        #[arg(long)]
3197        since: Option<String>,
3198        /// Compute diff for a specific ISO week (e.g. `2026-W18`).
3199        /// If absent and no `--since`, defaults to the current ISO week.
3200        #[arg(long)]
3201        week: Option<String>,
3202        /// Emit JSON to stdout.
3203        #[arg(long)]
3204        json: bool,
3205    },
3206    /// v0.158: tag the current frontier state as a versioned
3207    /// release. Writes a content-addressed `vfrr_*` record to
3208    /// `<frontier-dir>/.vela/releases/<vfrr_*>.json`. Releases
3209    /// are immutable; the substrate-side equivalent of a paper
3210    /// edition or software version tag.
3211    Release {
3212        /// Frontier path.
3213        frontier: PathBuf,
3214        /// Human-readable release name (e.g. `v1.0`, `2026-Q2`,
3215        /// `pre-print`). Required, non-empty.
3216        #[arg(long)]
3217        name: String,
3218        /// Optional release notes (changelog, scope, attribution).
3219        #[arg(long)]
3220        notes: Option<String>,
3221        /// Optional previous release id to chain. When omitted,
3222        /// the substrate looks up the latest release in
3223        /// `<frontier-dir>/.vela/releases/` and chains there.
3224        #[arg(long)]
3225        previous: Option<String>,
3226        #[arg(long)]
3227        json: bool,
3228    },
3229    /// v0.158: list every release recorded for a frontier.
3230    Releases {
3231        /// Frontier path.
3232        frontier: PathBuf,
3233        #[arg(long)]
3234        json: bool,
3235    },
3236}
3237
3238#[derive(Subcommand)]
3239enum RepoAction {
3240    /// Show materialization, proof, proposal, and hash status.
3241    Status {
3242        /// Frontier repository directory.
3243        frontier: PathBuf,
3244        /// Output stable JSON.
3245        #[arg(long)]
3246        json: bool,
3247    },
3248    /// Check folder shape, manifest paths, stale proof, and root clutter.
3249    Doctor {
3250        /// Frontier repository directory.
3251        frontier: PathBuf,
3252        /// Output stable JSON.
3253        #[arg(long)]
3254        json: bool,
3255    },
3256}
3257
3258#[derive(Subcommand)]
3259enum QueueAction {
3260    /// List queued draft actions (no signing)
3261    List {
3262        #[arg(long)]
3263        queue_file: Option<PathBuf>,
3264        #[arg(long)]
3265        json: bool,
3266    },
3267    /// Sign each queued draft with the actor's Ed25519 key and apply
3268    /// it locally. Removes signed entries from the queue on success.
3269    Sign {
3270        /// Stable actor id matching a registered entry in the frontier
3271        #[arg(long)]
3272        actor: String,
3273        /// Path to the actor's Ed25519 private key (hex-encoded)
3274        #[arg(long)]
3275        key: PathBuf,
3276        /// Override the queue file location
3277        #[arg(long)]
3278        queue_file: Option<PathBuf>,
3279        /// Skip per-action confirmation prompts and sign every queued
3280        /// draft. Required in non-interactive contexts. The `--all`
3281        /// alias is accepted for muscle-memory convenience (the v0.28
3282        /// sim-user docs and an early friction report both wrote it
3283        /// that way; cheaper to accept the alias than to retrain).
3284        #[arg(long, alias = "all")]
3285        yes_to_all: bool,
3286        #[arg(long)]
3287        json: bool,
3288    },
3289    /// Drop all queued draft actions
3290    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 all entries in a local registry
3301    List {
3302        /// Path or file:// URL of the registry; defaults to ~/.vela/registry/entries.json
3303        #[arg(long)]
3304        from: Option<String>,
3305        #[arg(long)]
3306        json: bool,
3307    },
3308    /// Publish a frontier's current snapshot+event_log hashes to a registry
3309    Publish {
3310        /// Path to the frontier file
3311        frontier: PathBuf,
3312        /// Stable owner actor id (must be registered in the frontier)
3313        #[arg(long)]
3314        owner: String,
3315        /// Path to the owner's Ed25519 private key (hex-encoded)
3316        #[arg(long)]
3317        key: PathBuf,
3318        /// Network locator under which the frontier is reachable
3319        /// (file:// path or HTTP URL the publisher serves). Optional
3320        /// since v0.55: when publishing to an HTTP hub, the hub's own
3321        /// `/entries/<vfr>/snapshot` URL is auto-filled if omitted, and
3322        /// the substrate is uploaded inline so locator divergence is
3323        /// no longer a failure mode.
3324        #[arg(long)]
3325        locator: Option<String>,
3326        /// Registry to publish to (path/URL); default ~/.vela/registry/entries.json
3327        #[arg(long)]
3328        to: Option<String>,
3329        /// v0.154: optional SPDX license identifier
3330        /// (e.g. `CC-BY-4.0`, `CC0-1.0`, `MIT`, `Apache-2.0`). The
3331        /// license rides on the registry entry so consumers can
3332        /// audit reuse rights without re-fetching the frontier.
3333        #[arg(long)]
3334        license: Option<String>,
3335        #[arg(long)]
3336        json: bool,
3337    },
3338    /// v0.15: list registry entries whose frontier declares a
3339    /// cross-frontier dependency on the given `vfr_id`. Surfaces
3340    /// "who is referencing my frontier" — the bidirectional view
3341    /// of cross-frontier composition. Hub-only (no local-registry
3342    /// equivalent yet); requires the hub to support
3343    /// `GET /entries/{vfr_id}/depends-on`.
3344    DependsOn {
3345        /// Frontier address (`vfr_…`) to look up dependents of.
3346        vfr_id: String,
3347        /// Hub URL. Required for v0.15 (no local file walk yet).
3348        #[arg(long, default_value = "https://vela-hub.fly.dev")]
3349        from: String,
3350        #[arg(long)]
3351        json: bool,
3352    },
3353    /// v0.20: federation primitive. Pull a signed manifest from one hub
3354    /// (`--from`) and POST it verbatim to another (`--to`). Both hubs
3355    /// validate the signature against the manifest's embedded
3356    /// `owner_pubkey`; mirroring is a no-op for authenticity. Use this
3357    /// to replicate a frontier across hubs (resilience), seed a fresh
3358    /// hub from an established one, or test a hub deployment with real
3359    /// signed bytes.
3360    Mirror {
3361        /// Frontier address (`vfr_…`) to mirror.
3362        vfr_id: String,
3363        /// Source hub URL.
3364        #[arg(long)]
3365        from: String,
3366        /// Destination hub URL.
3367        #[arg(long)]
3368        to: String,
3369        #[arg(long)]
3370        json: bool,
3371    },
3372    /// v0.129: fetch the same registry entry from multiple hubs and
3373    /// assert byte-identical agreement. Closes part of
3374    /// THREAT_MODEL.md A11 (compromised hub) by giving operators a
3375    /// substrate-side cross-hub divergence detector. The
3376    /// substrate-honest claim: if two or more trustworthy mirrors
3377    /// agree on the entry's canonical bytes, a third hub's diverging
3378    /// copy is identifiable.
3379    WitnessCheck {
3380        /// Frontier address (`vfr_…`) to fetch from every hub.
3381        vfr_id: String,
3382        /// Comma-separated list of hub URLs to query. Requires
3383        /// at least two; three or more makes the consensus
3384        /// substrate-honest (a majority can outvote a single
3385        /// divergent hub).
3386        #[arg(long, value_delimiter = ',')]
3387        hubs: Vec<String>,
3388        #[arg(long)]
3389        json: bool,
3390    },
3391    /// v0.144: Registry governance policy primitive. Declare per-
3392    /// frontier governance: who can authorize owner rotation, what
3393    /// threshold of distinct attestations is required, and (during
3394    /// bootstrap only) whether the current owner alone can satisfy
3395    /// quorum. This cycle ships construction + validation; v0.145
3396    /// binds the policy to `owner-rotate`.
3397    Governance {
3398        #[command(subcommand)]
3399        action: GovernanceAction,
3400    },
3401    /// v0.148: hub federation status. Fetch the latest signed
3402    /// checkpoint from each named source (HTTPS URL pointing at
3403    /// a hub endpoint that serves the checkpoint JSON, or a
3404    /// `file://` URL pointing at a local checkpoint file).
3405    /// Compute consensus on the `(registry_root, sequence)`
3406    /// pair across the resolved set. Surfaces hub-operator
3407    /// divergence at the registry-state level, not just the
3408    /// per-entry level that witness-check covers.
3409    HubFederation {
3410        #[command(subcommand)]
3411        action: HubFederationAction,
3412    },
3413    /// v0.147: signed registry checkpoint flow.
3414    ///   create:  read a local registry, compute the
3415    ///            content-addressed registry root, sign the
3416    ///            checkpoint body, write the resulting `vrc_*`
3417    ///            checkpoint to `--out`.
3418    ///   verify:  given a checkpoint file + the registry it
3419    ///            claims to summarize, re-derive the id,
3420    ///            re-compute the root, verify the Ed25519
3421    ///            signature.
3422    Checkpoint {
3423        #[command(subcommand)]
3424        action: CheckpointAction,
3425    },
3426    /// v0.153: registry-wide verification. Reads a local
3427    /// registry, walks every entry, runs entry-signature
3428    /// verification per row, and surfaces a pass/fail summary.
3429    /// Used by operators + dashboards to attest the registry is
3430    /// internally consistent.
3431    VerifyAll {
3432        /// Local registry path. Defaults to
3433        /// `~/.vela/registry/entries.json`.
3434        #[arg(long)]
3435        from: Option<PathBuf>,
3436        #[arg(long)]
3437        json: bool,
3438    },
3439    /// v0.146: verify a frontier's owner-epoch chain transcript.
3440    /// Walks each transition, loads the corresponding policy,
3441    /// proposal, and attestation bundle, and re-runs the v0.145
3442    /// quorum verification. Surfaces `bootstrap` (chain empty),
3443    /// `verified` (every transition checks out), `legacy` (no
3444    /// chain file present; the entry pre-dates v0.144), or
3445    /// `broken` (at least one transition fails verification).
3446    VerifyChain {
3447        /// Frontier path. The chain is read from
3448        /// `<frontier-dir>/.vela/governance/chain.json`.
3449        frontier: PathBuf,
3450        /// Directory holding the `vgp_*.json`, `vop_*.json`,
3451        /// `vab_*.json` artifacts referenced by the chain. Files
3452        /// must be named `<id>.json` (e.g. `vop_abc123.json`).
3453        #[arg(long)]
3454        artifacts: PathBuf,
3455        #[arg(long)]
3456        json: bool,
3457    },
3458    /// v0.145: governed owner-rotate flow.
3459    ///   propose: emit a `vop_*` proposal bound to a frontier +
3460    ///            governance policy + previous registry entry hash.
3461    ///   attest:  a single governance attester signs the proposal
3462    ///            preimage and writes the signature into a bundle.
3463    ///   apply:   verify the bundle satisfies the policy's
3464    ///            rotate_quorum, then execute the v0.138
3465    ///            owner-rotate mutation (revoke old owner, register
3466    ///            new owner, re-publish under new key).
3467    /// The v0.138 flat `owner-rotate` form is kept for the
3468    /// bootstrap epoch case (`vela registry owner-rotate ...` with
3469    /// no proposal); for non-bootstrap rotations, this subcommand
3470    /// is the only authorized path.
3471    OwnerRotateGoverned {
3472        #[command(subcommand)]
3473        action: OwnerRotateGovernedAction,
3474    },
3475    /// v0.138: A8 graduation primitive. Rotate the owner key of a
3476    /// published frontier. Revokes the current owner actor record
3477    /// (sets `revoked_at` / `revoked_reason`), registers (or
3478    /// promotes) the new owner actor record, and re-publishes the
3479    /// frontier under the new owner key. Consumers who re-pull
3480    /// after rotation receive the new entry signed under the new
3481    /// `owner_pubkey`; the in-frontier actor record retains the
3482    /// rotation timeline so the audit chain is reconstructable
3483    /// from the frontier itself.
3484    OwnerRotate {
3485        /// Path to the frontier file
3486        frontier: PathBuf,
3487        /// Current owner actor id (must be registered and not revoked).
3488        #[arg(long)]
3489        current_owner: String,
3490        /// New owner actor id (auto-registered if not already present).
3491        #[arg(long)]
3492        new_owner: String,
3493        /// Path to the new owner's Ed25519 private key (hex-encoded).
3494        #[arg(long)]
3495        new_key: PathBuf,
3496        /// Required reason (non-empty); recorded on the retired
3497        /// owner's `revoked_reason` for the audit chain.
3498        #[arg(long)]
3499        reason: String,
3500        /// Network locator under which the rotated frontier is
3501        /// reachable. Same shape as `registry publish`: optional
3502        /// when `--to` is an HTTP hub (auto-filled), required for
3503        /// local registries.
3504        #[arg(long)]
3505        locator: Option<String>,
3506        /// Registry to publish the rotated entry to. Same shape as
3507        /// `registry publish --to`.
3508        #[arg(long)]
3509        to: Option<String>,
3510        #[arg(long)]
3511        json: bool,
3512    },
3513    /// Pull and verify a frontier from a registry by `vfr_id`
3514    Pull {
3515        /// Frontier address (`vfr_…`)
3516        vfr_id: String,
3517        /// Registry to pull from
3518        #[arg(long)]
3519        from: Option<String>,
3520        /// Output path for the pulled frontier. With --transitive, this
3521        /// is the directory dependencies are also written into; without
3522        /// it, this is the file path the primary lands at.
3523        #[arg(long)]
3524        out: PathBuf,
3525        /// v0.8: also pull every cross-frontier dependency the primary
3526        /// declares, recursively, verifying each pinned snapshot.
3527        #[arg(long)]
3528        transitive: bool,
3529        /// v0.8: maximum recursion depth when --transitive is set.
3530        /// Primary is depth 0; its direct deps are depth 1.
3531        #[arg(long, default_value = "4")]
3532        depth: usize,
3533        #[arg(long)]
3534        json: bool,
3535    },
3536}
3537
3538#[derive(Subcommand)]
3539enum GovernanceAction {
3540    /// Construct a new governance policy from CLI flags and write it
3541    /// to `--out`. The policy id (`vgp_*`) is derived from the
3542    /// canonical bytes of the policy body.
3543    Init {
3544        /// Frontier path the policy will govern.
3545        frontier: PathBuf,
3546        /// Threshold for the standard rotate quorum.
3547        #[arg(long)]
3548        threshold: u32,
3549        /// Comma-separated list of eligible actor ids.
3550        #[arg(long, value_delimiter = ',')]
3551        eligible: Vec<String>,
3552        /// Whether this is a bootstrap policy (owner_epoch = 0,
3553        /// bootstrap_epoch = 0). When set, `current_owner_counts`
3554        /// is permitted to be `true`; this is the only way a
3555        /// freshly published frontier can authorize its first
3556        /// rotation.
3557        #[arg(long)]
3558        bootstrap: bool,
3559        /// Owner epoch this policy applies to. Defaults to 0 when
3560        /// `--bootstrap` is set, otherwise required to be >= 1.
3561        #[arg(long)]
3562        owner_epoch: Option<u64>,
3563        /// Whether the current owner counts toward the rotate
3564        /// quorum. Only permitted (and only sensible) for bootstrap
3565        /// policies; the v0.144 validator rejects otherwise.
3566        #[arg(long)]
3567        current_owner_counts: bool,
3568        /// Attestation TTL in hours (default 168).
3569        #[arg(long, default_value = "168")]
3570        attestation_ttl_hours: u32,
3571        /// Output path for the policy JSON. When omitted, the
3572        /// policy is printed to stdout.
3573        #[arg(long)]
3574        out: Option<PathBuf>,
3575        #[arg(long)]
3576        json: bool,
3577    },
3578    /// Read a policy JSON file and pretty-print its core fields.
3579    Show {
3580        /// Path to a policy JSON file.
3581        policy: PathBuf,
3582        #[arg(long)]
3583        json: bool,
3584    },
3585    /// Validate a policy JSON file against the v0.144 rules and
3586    /// re-derive its content address. Exits non-zero on violation.
3587    Validate {
3588        /// Path to a policy JSON file.
3589        policy: PathBuf,
3590        #[arg(long)]
3591        json: bool,
3592    },
3593}
3594
3595#[derive(Subcommand)]
3596enum SearchAction {
3597    /// Build a search index over one or more frontier paths.
3598    Build {
3599        /// One or more frontier paths to index (positional).
3600        #[arg(required = true)]
3601        frontiers: Vec<PathBuf>,
3602        /// Output index JSON path.
3603        #[arg(long)]
3604        out: PathBuf,
3605        /// Include bootstrap (no governed rotations) + legacy
3606        /// (pre-v0.144) frontiers in the index. Off by default;
3607        /// strict consumers want only `verified` chains.
3608        #[arg(long)]
3609        include_bootstrap: bool,
3610        /// Include `broken` chains too. Useful for ops
3611        /// dashboards that want failure visibility.
3612        #[arg(long)]
3613        include_broken: bool,
3614        #[arg(long)]
3615        json: bool,
3616    },
3617    /// Query an existing index.
3618    Query {
3619        /// Query string. Empty matches every entry (subject to
3620        /// filters).
3621        #[arg(default_value = "")]
3622        query: String,
3623        /// Path to the index JSON file. Defaults to
3624        /// `~/.vela/search-index.json` when omitted.
3625        #[arg(long)]
3626        index: Option<PathBuf>,
3627        /// Filter by entry kind (`finding` | `actor`).
3628        #[arg(long)]
3629        kind: Option<String>,
3630        /// Filter by entity tag.
3631        #[arg(long)]
3632        entity: Option<String>,
3633        /// Filter by Belnap status (`accepted` | `accepted_core`
3634        /// | `pending` | `retracted` | ...).
3635        #[arg(long)]
3636        status: Option<String>,
3637        /// Filter by frontier id.
3638        #[arg(long)]
3639        frontier_id: Option<String>,
3640        /// Filter by source identifier (DOI or PMID).
3641        #[arg(long)]
3642        source_id: Option<String>,
3643        /// Restrict to entries whose owner-epoch chain status
3644        /// equals the given value (e.g. `verified` for strict
3645        /// mode).
3646        #[arg(long)]
3647        chain_status: Option<String>,
3648        /// Cap result count.
3649        #[arg(long)]
3650        limit: Option<usize>,
3651        #[arg(long)]
3652        json: bool,
3653    },
3654}
3655
3656#[derive(Subcommand)]
3657enum HubFederationAction {
3658    /// Fetch + verify the latest checkpoint from each source and
3659    /// compute cross-source consensus on `(registry_root,
3660    /// sequence)`.
3661    ///
3662    /// Sources are `--source <id>=<url>` pairs. The `<id>` is a
3663    /// free-form label (typically the hub id); the `<url>` is
3664    /// either `https://...` pointing at the checkpoint JSON or
3665    /// `file://...` pointing at a local file. At least two
3666    /// sources are required.
3667    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    /// Build and sign a new registry checkpoint.
3678    Create {
3679        /// Local registry file path (e.g. `~/.vela/registry/entries.json`).
3680        #[arg(long)]
3681        from: PathBuf,
3682        /// Hub operator identifier (free-form).
3683        #[arg(long)]
3684        hub_id: String,
3685        /// Sequence number. Use 0 for the first checkpoint.
3686        #[arg(long)]
3687        sequence: u64,
3688        /// Optional `vrc_*` id of the predecessor checkpoint.
3689        #[arg(long)]
3690        previous: Option<String>,
3691        /// Hub operator's Ed25519 private key.
3692        #[arg(long)]
3693        key: PathBuf,
3694        /// Output path.
3695        #[arg(long)]
3696        out: PathBuf,
3697        #[arg(long)]
3698        json: bool,
3699    },
3700    /// Verify a checkpoint against a registry: re-derive id,
3701    /// re-compute root, verify signature.
3702    Verify {
3703        /// Checkpoint JSON file.
3704        checkpoint: PathBuf,
3705        /// Registry file the checkpoint claims to summarize.
3706        #[arg(long)]
3707        registry: PathBuf,
3708        #[arg(long)]
3709        json: bool,
3710    },
3711}
3712
3713#[derive(Subcommand)]
3714enum OwnerRotateGovernedAction {
3715    /// Construct a `vop_*` proposal for a specific rotation and
3716    /// write it to `--out`. The proposal binds frontier id, old
3717    /// owner id+pubkey, new owner id+pubkey, target owner epoch,
3718    /// previous registry entry hash, governance policy id,
3719    /// reason, expiry, and nonce. Governance attesters sign the
3720    /// canonical preimage of this object.
3721    Propose {
3722        frontier: PathBuf,
3723        #[arg(long)]
3724        old_owner: String,
3725        #[arg(long)]
3726        new_owner: String,
3727        /// Path to the new owner's public key (used to derive the
3728        /// pubkey hex; the corresponding private key is supplied
3729        /// at `apply` time).
3730        #[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    /// Sign a proposal's preimage with the attester's key. Writes
3748    /// or extends an attestation bundle at `--bundle`. Idempotent
3749    /// on `(attester_id, proposal_id)` pairs: re-signing replaces
3750    /// the previous entry under the same id.
3751    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    /// Verify the bundle satisfies the policy's rotate_quorum
3764    /// (signatures valid, attesters eligible + unrevoked, distinct
3765    /// signers >= threshold, proposal not expired), then execute
3766    /// the v0.138 owner-rotate mutation under the new owner key.
3767    Apply {
3768        frontier: PathBuf,
3769        #[arg(long)]
3770        proposal: PathBuf,
3771        #[arg(long)]
3772        bundle: PathBuf,
3773        #[arg(long)]
3774        policy: PathBuf,
3775        /// New owner's private key. Must derive to the pubkey
3776        /// declared in the proposal's `new_owner_pubkey`.
3777        #[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 candidate gap review leads
3791    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    /// Append a typed link from one finding to another. The target
3805    /// may be a local `vf_<hex>` or a cross-frontier `vf_<hex>@vfr_<hex>`
3806    /// (v0.8). Cross-frontier targets require a matching declared dep —
3807    /// run `vela frontier add-dep` first or strict validation will refuse.
3808    Add {
3809        /// Frontier JSON file or Vela repo
3810        frontier: PathBuf,
3811        /// Source finding id (`vf_<hex>`)
3812        #[arg(long)]
3813        from: String,
3814        /// Target. Either `vf_<hex>` (local) or `vf_<hex>@vfr_<hex>` (cross).
3815        #[arg(long)]
3816        to: String,
3817        /// Link type. One of: supports, contradicts, extends, depends, replicates, supersedes, synthesized_from
3818        #[arg(long, default_value = "supports")]
3819        r#type: String,
3820        /// Optional human-readable note
3821        #[arg(long, default_value = "")]
3822        note: String,
3823        /// Who inferred the link. One of: compiler, reviewer, author
3824        #[arg(long, default_value = "reviewer")]
3825        inferred_by: String,
3826        /// v0.16: skip the cross-frontier target-status check. By
3827        /// default, when adding a cross-frontier link, the substrate
3828        /// fetches the dep's frontier from its declared locator and
3829        /// warns if the target finding has `flags.superseded = true`
3830        /// (you'd be linking to an outdated wording). The link is
3831        /// still recorded — this is a best-effort review hint, not a
3832        /// hard refusal. Set this flag to skip the network fetch
3833        /// (useful in CI or when offline).
3834        #[arg(long)]
3835        no_check_target: bool,
3836        #[arg(long)]
3837        json: bool,
3838    },
3839}
3840
3841#[derive(Subcommand)]
3842enum EntityAction {
3843    /// Walk every finding's entities and try to resolve each against
3844    /// the bundled common-entity table. Matched entities get
3845    /// `canonical_id` populated, `resolution_method = manual`,
3846    /// `resolution_confidence = 0.95`, `needs_review = false`. Already-
3847    /// resolved entities are skipped unless `--force` is passed. The
3848    /// frontier file is written back atomically.
3849    Resolve {
3850        frontier: PathBuf,
3851        /// Re-resolve entities that already have a canonical_id.
3852        #[arg(long)]
3853        force: bool,
3854        #[arg(long)]
3855        json: bool,
3856    },
3857    /// List the bundled lookup table.
3858    List {
3859        #[arg(long)]
3860        json: bool,
3861    },
3862}
3863
3864#[derive(Subcommand)]
3865enum FindingCommands {
3866    /// Add a manual finding bundle with an assertion field
3867    Add {
3868        /// Frontier JSON file or Vela repo
3869        frontier: PathBuf,
3870        /// Assertion text inside the finding bundle
3871        #[arg(long)]
3872        assertion: String,
3873        /// Assertion type. One of: mechanism, therapeutic, diagnostic, epidemiological, observational, review, methodological, computational, theoretical, negative
3874        #[arg(long, default_value = "mechanism")]
3875        r#type: String,
3876        /// Source label for the finding
3877        #[arg(long, default_value = "manual finding")]
3878        source: String,
3879        /// Source type. One of: published_paper, preprint, clinical_trial, lab_notebook, model_output, expert_assertion, database_record
3880        #[arg(long, default_value = "expert_assertion")]
3881        source_type: String,
3882        /// Author/reviewer identifier
3883        #[arg(long)]
3884        author: String,
3885        /// Initial confidence score from 0.0 to 1.0
3886        #[arg(long, default_value = "0.3")]
3887        confidence: f64,
3888        /// Evidence type. One of: experimental, observational, computational, theoretical, meta_analysis, systematic_review, case_report
3889        #[arg(long, default_value = "theoretical")]
3890        evidence_type: String,
3891        /// Entities as comma-separated name:type pairs. Entity types: gene, protein, compound, disease, cell_type, organism, pathway, assay, anatomical_structure, particle, instrument, dataset, quantity, other
3892        #[arg(long, default_value = "")]
3893        entities: String,
3894        /// Mark manually supplied entities as curator-reviewed
3895        #[arg(long)]
3896        entities_reviewed: bool,
3897        /// Evidence span text or JSON. Repeat to attach multiple source spans
3898        #[arg(long)]
3899        evidence_span: Vec<String>,
3900        /// Mark this finding as a candidate gap
3901        #[arg(long)]
3902        gap: bool,
3903        /// Mark this finding as negative-space evidence
3904        #[arg(long)]
3905        negative_space: bool,
3906        /// v0.11: DOI of the source artifact (e.g. "10.1038/s41586-024-...")
3907        #[arg(long)]
3908        doi: Option<String>,
3909        /// v0.11: PubMed ID
3910        #[arg(long)]
3911        pmid: Option<String>,
3912        /// v0.11: Publication year
3913        #[arg(long)]
3914        year: Option<i32>,
3915        /// v0.11: Journal name
3916        #[arg(long)]
3917        journal: Option<String>,
3918        /// v0.11: Generic source URL when none of the structured identifiers fit
3919        #[arg(long)]
3920        url: Option<String>,
3921        /// v0.11: Source-paper authors as semicolon-separated list (distinct from --author which is the curating Vela actor)
3922        #[arg(long)]
3923        source_authors: Option<String>,
3924        /// v0.11: Conditions/scope text. Replaces the placeholder otherwise written. Should describe scope boundaries (species, dosing, age range, model, etc.)
3925        #[arg(long)]
3926        conditions_text: Option<String>,
3927        /// v0.11: Verified species as semicolon-separated list (e.g. "Mus musculus;Homo sapiens")
3928        #[arg(long)]
3929        species: Option<String>,
3930        /// v0.11: Mark the finding as in vivo
3931        #[arg(long)]
3932        in_vivo: bool,
3933        /// v0.11: Mark the finding as in vitro
3934        #[arg(long)]
3935        in_vitro: bool,
3936        /// v0.11: Mark the finding as having human data
3937        #[arg(long)]
3938        human_data: bool,
3939        /// v0.11: Mark the finding as a clinical trial
3940        #[arg(long)]
3941        clinical_trial: bool,
3942        /// Output stable JSON
3943        #[arg(long)]
3944        json: bool,
3945        /// Immediately accept and apply the proposal locally
3946        #[arg(long)]
3947        apply: bool,
3948    },
3949    /// v0.14: Supersede an existing finding with a new content-addressed
3950    /// claim. The new finding gets its own `vf_…` id; an auto-injected
3951    /// `supersedes` link points back at the old id; the old finding is
3952    /// flagged `superseded`. Both remain queryable. Real corrections
3953    /// (Phase 4 follow-up data, retraction, refined wording) belong here
3954    /// rather than as caveats stacked on top of an immutable claim.
3955    Supersede {
3956        /// Frontier JSON file or Vela repo
3957        frontier: PathBuf,
3958        /// `vf_…` id of the finding to supersede
3959        old_id: String,
3960        /// New assertion text (drives the new finding's content address)
3961        #[arg(long)]
3962        assertion: String,
3963        /// New assertion type
3964        #[arg(long, default_value = "mechanism")]
3965        r#type: String,
3966        /// Source label
3967        #[arg(long, default_value = "manual finding")]
3968        source: String,
3969        /// Source type
3970        #[arg(long, default_value = "expert_assertion")]
3971        source_type: String,
3972        /// Curating Vela actor id
3973        #[arg(long)]
3974        author: String,
3975        /// Reason for the supersede (becomes the proposal/event reason)
3976        #[arg(long)]
3977        reason: String,
3978        /// New confidence score 0.0..=1.0
3979        #[arg(long, default_value = "0.5")]
3980        confidence: f64,
3981        /// New evidence type
3982        #[arg(long, default_value = "experimental")]
3983        evidence_type: String,
3984        /// New entities (`name:type` pairs, comma-separated)
3985        #[arg(long, default_value = "")]
3986        entities: String,
3987        /// DOI of the source artifact
3988        #[arg(long)]
3989        doi: Option<String>,
3990        /// PubMed ID
3991        #[arg(long)]
3992        pmid: Option<String>,
3993        /// Publication year
3994        #[arg(long)]
3995        year: Option<i32>,
3996        /// Journal name
3997        #[arg(long)]
3998        journal: Option<String>,
3999        /// Generic source URL
4000        #[arg(long)]
4001        url: Option<String>,
4002        /// Source-paper authors (semicolon-separated)
4003        #[arg(long)]
4004        source_authors: Option<String>,
4005        /// Conditions/scope text
4006        #[arg(long)]
4007        conditions_text: Option<String>,
4008        /// Verified species (semicolon-separated)
4009        #[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        /// Immediately accept and apply the proposal locally
4022        #[arg(long)]
4023        apply: bool,
4024    },
4025    /// v0.38: Set or revise the Pearlian causal type and study-design
4026    /// grade for a finding. Appends an `assertion.reinterpreted_causal`
4027    /// event capturing the prior reading, the new reading, and the
4028    /// reviewer who re-graded. Pre-v0.38 findings carry no causal
4029    /// metadata; the first call materializes both fields.
4030    CausalSet {
4031        /// Frontier JSON file or Vela repo
4032        frontier: PathBuf,
4033        /// `vf_<id>` of the finding to re-grade.
4034        finding_id: String,
4035        /// Causal claim kind: correlation | mediation | intervention.
4036        #[arg(long)]
4037        claim: String,
4038        /// Optional study-design grade: rct | quasi_experimental |
4039        /// observational | theoretical.
4040        #[arg(long)]
4041        grade: Option<String>,
4042        /// Reviewer/curator id (must match a registered actor under
4043        /// `--strict`). Recorded on the appended event.
4044        #[arg(long)]
4045        actor: String,
4046        /// One-paragraph reason. Becomes the event's `reason` field
4047        /// and ships with the proposal.
4048        #[arg(long)]
4049        reason: String,
4050        #[arg(long)]
4051        json: bool,
4052    },
4053}
4054
4055#[derive(Subcommand)]
4056enum ProposalAction {
4057    /// List proposals in a frontier
4058    List {
4059        frontier: PathBuf,
4060        #[arg(long)]
4061        status: Option<String>,
4062        #[arg(long)]
4063        json: bool,
4064    },
4065    /// Show one proposal
4066    Show {
4067        frontier: PathBuf,
4068        proposal_id: String,
4069        #[arg(long)]
4070        json: bool,
4071    },
4072    /// Preview applying one proposal without mutating the frontier
4073    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 proposal files into a frontier
4082    Import {
4083        frontier: PathBuf,
4084        source: PathBuf,
4085        #[arg(long)]
4086        json: bool,
4087    },
4088    /// Validate standalone proposal files or directories
4089    Validate {
4090        source: PathBuf,
4091        #[arg(long)]
4092        json: bool,
4093    },
4094    /// Export proposal records from a frontier
4095    Export {
4096        frontier: PathBuf,
4097        output: PathBuf,
4098        #[arg(long)]
4099        status: Option<String>,
4100        #[arg(long)]
4101        json: bool,
4102    },
4103    /// Accept and apply one proposal
4104    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 one proposal
4115    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 a source adapter over a frontier-owned ingest plan
4130    Run {
4131        /// Frontier JSON file or Vela repo
4132        frontier: PathBuf,
4133        /// Adapter id. Currently: clinicaltrials-gov-v2 or regulatory-documents-v1
4134        adapter: String,
4135        /// Stable actor id recorded on generated proposals
4136        #[arg(long)]
4137        actor: String,
4138        /// Restrict to source ingest entry ids
4139        #[arg(long = "entry")]
4140        entries: Vec<String>,
4141        /// Restrict to P0, P1, or P2 entries
4142        #[arg(long)]
4143        priority: Option<String>,
4144        /// Include entries marked excluded
4145        #[arg(long)]
4146        include_excluded: bool,
4147        /// Continue when one source record fails
4148        #[arg(long)]
4149        allow_partial: bool,
4150        /// Report planned work without writing packets, proposals, or run files
4151        #[arg(long)]
4152        dry_run: bool,
4153        /// Read saved source fixtures from this directory
4154        #[arg(long)]
4155        input_dir: Option<PathBuf>,
4156        /// Apply artifact proposals while leaving truth changes pending
4157        #[arg(long)]
4158        apply_artifacts: bool,
4159        /// Emit JSON to stdout
4160        #[arg(long)]
4161        json: bool,
4162    },
4163}
4164
4165#[derive(Subcommand)]
4166enum RuntimeAdapterAction {
4167    /// Normalize an external runtime export into reviewable frontier proposals
4168    Run {
4169        /// Frontier JSON file or Vela repo
4170        frontier: PathBuf,
4171        /// Adapter id. Currently: scienceclaw-artifact-v1 or agent-discourse-v1
4172        adapter: String,
4173        /// External runtime export JSON file or directory
4174        #[arg(long)]
4175        input: PathBuf,
4176        /// Stable actor id recorded on generated proposals
4177        #[arg(long)]
4178        actor: String,
4179        /// Report planned work without writing packets, proposals, or run files
4180        #[arg(long)]
4181        dry_run: bool,
4182        /// Apply artifact proposals while leaving truth changes pending
4183        #[arg(long)]
4184        apply_artifacts: bool,
4185        /// Emit JSON to stdout
4186        #[arg(long)]
4187        json: bool,
4188    },
4189}
4190
4191#[derive(Subcommand)]
4192enum BridgeKitAction {
4193    /// Validate one packet JSON file or a directory of packet JSON files
4194    Validate {
4195        /// Packet JSON file or directory
4196        source: PathBuf,
4197        /// Emit JSON to stdout
4198        #[arg(long)]
4199        json: bool,
4200    },
4201    /// v0.108.3: Verify that DOIs and PMIDs claimed in a Carina
4202    /// packet's artifact locators and candidate-claim source_refs
4203    /// actually resolve through Crossref / PubMed eutils. Closes
4204    /// part of THREAT_MODEL.md A6 (citation poisoning: a fabricated
4205    /// DOI passes structural validation today). Network call;
4206    /// skips identifiers if the upstream is unreachable.
4207    VerifyProvenance {
4208        /// Packet JSON file
4209        packet: PathBuf,
4210        /// Emit JSON to stdout
4211        #[arg(long)]
4212        json: bool,
4213        /// v0.126: cross-source agreement pass. For each artifact /
4214        /// candidate-claim that resolves through more than one
4215        /// upstream source (Crossref + PubMed + S2 + ArXiv), compare
4216        /// the title and first-author last-name. Disagreement
4217        /// surfaces as a `disagreement` consensus signal. Closes
4218        /// more of THREAT_MODEL.md A6 (citation poisoning).
4219        #[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                // Phase R: --workbench implies HTTP and serves web/.
4432                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            // v0.26 VelaBench routing: presence of `--candidate`
4524            // selects the agent state-update scorer. The legacy
4525            // extraction harness keeps every other invocation
4526            // unchanged.
4527            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            // v0.74.3: if the first positional looks like a
4606            // proposal id, route to proposals preview. Otherwise
4607            // treat it as a frontier path or `vfr_*` registry id
4608            // and run the two-frontier diff (v0.140 cross-frontier).
4609            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                // v0.140: when either side is a `vfr_*` id, pull
4659                // the frontier through the registry into a temp
4660                // dir and run the diff against the pulled path.
4661                // The tempdir lives for the duration of the diff
4662                // and is reclaimed on drop.
4663                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                &section,
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            &note,
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            &notes,
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, &notes, 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        // v0.74: alias verb dispatch. Each arm calls into an
5640        // existing canonical-event emission path.
5641        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            // Mirror the existing `Commands::Review` arm: emit a
5670            // finding.review proposal under reviewer authority.
5671            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            // Mirror ProposalAction::Accept at cli.rs:8000.
5689            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            // v0.80.1: per-event mode. When --event is supplied,
5726            // emit an attestation.recorded canonical event
5727            // targeting the named event id.
5728            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            // v0.74 frontier-wide path: --key required.
5770            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            // Mirror Commands::History at cli.rs:3231.
5806            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
5827/// v0.78: handler for `vela atlas <action>`. Routes through the
5828/// binary-installed handlers (registered in `vela-cli/src/main.rs`)
5829/// so the substrate library stays free of the `vela-atlas`
5830/// dependency.
5831async 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            // v0.78 stub: route to the per-frontier Workbench for
5861            // the first composing frontier in the manifest.
5862            // Atlas-level Workbench page lands in v0.79+.
5863            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
5883/// v0.82: handler for `vela constellation <action>`. Routes
5884/// through binary-installed handlers calling into the
5885/// `vela-constellation` crate.
5886async 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
5922/// v0.75: handler for `vela carina <action>`. Each branch reaches
5923/// into the bundled schemas under `embedded/carina-schemas/`.
5924fn 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            // If the file is a primitives.v0.X.json aggregate,
5958            // validate every entry under `primitives`. Otherwise
5959            // validate the value as one primitive.
5960            // Each report entry: (input key, validation result with
5961            // optional detected-primitive name in the Ok branch).
5962            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/// v0.117: register a Carina Proof primitive (`vpf_*`) against a
6050/// finding. Hashes the proof script with sha256, builds a Carina
6051/// `Proof` JSON object (validated against the bundled
6052/// `proof.schema.json`), then deposits an artifact carrying the
6053/// proof metadata under the v0.75.6 pattern: `kind: source_file`,
6054/// `metadata.carina_kind: proof_script`, `metadata.carina_proof_tool`,
6055/// `metadata.carina_proof_tool_version`. The artifact event is
6056/// signed under the reviewer's actor id via `state::add_artifact`.
6057/// Returns a JSON envelope with the `vpf_*` id, the `va_*` id, the
6058/// applied event id, and the script's content hash.
6059#[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    // 1. Validate the target finding shape.
6074    if !target_finding.starts_with("vf_") {
6075        fail(&format!(
6076            "--target-finding must be a vf_* finding id; got `{target_finding}`"
6077        ));
6078    }
6079    // 2. Validate the tool against the proof.schema.json enum.
6080    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    // 3. Read + hash the proof script.
6090    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    // 4. Compute the vpf_* id deterministically from script hash +
6096    // tool + target_finding so re-running with the same inputs is
6097    // a stable no-op.
6098    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    // 5. Build the Carina Proof primitive and validate it against
6105    // the bundled schema. The Rust validator stays authoritative.
6106    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        // No verifier-output capture yet; reviewers attest the
6114        // proof verifies under their own toolchain. Future cycles
6115        // may auto-capture `lake build` output and hash it here.
6116        "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    // 6. Build the Artifact (mirrors the v0.75.6 sidon-sets pattern).
6128    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    // 7. Deposit via the existing state::add_artifact path. This
6205    // emits an artifact.asserted canonical event signed under the
6206    // reviewer's actor id.
6207    let report = state::add_artifact(frontier, artifact, reviewer, reason)
6208        .unwrap_or_else(|e| fail_return(&e));
6209
6210    // 8. Emit the JSON envelope or a human-readable summary.
6211    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
6248/// v0.35 / v0.38.2: print consensus over claim-similar findings,
6249/// optionally filtered by causal claim type / minimum study grade.
6250fn 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
6347/// v0.34: parse the `--outcome` CLI string into a structured
6348/// `ExpectedOutcome`. Accepted forms:
6349///   - `affirmed` / `falsified`
6350///   - `quant:VALUE±TOL UNITS`  (e.g. `quant:0.4±0.1 SD`)
6351///   - `cat:LABEL`              (e.g. `cat:full_approval`)
6352fn 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/// v0.34: append a Prediction to a frontier and persist it.
6389#[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/// v0.34: append a Resolution that closes out a Prediction.
6516#[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    // If the resolver provided source provenance, embed it via the
6559    // evidence span (the Resolution carries Evidence; for v0.34 we
6560    // keep the structure minimal). DOI flows through evidence_spans
6561    // commentary; richer linking lands in v0.34.x.
6562    let _ = doi; // currently unused — placeholder for v0.34.x.
6563
6564    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
6642/// v0.34: list predictions, with resolution state.
6643fn 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
6727/// v0.34: print calibration scores per actor.
6728/// v0.40.1: Walk every prediction whose deadline has passed and mark
6729/// them as `expired_unresolved`. Emits one
6730/// `prediction.expired_unresolved` event per newly-expired prediction.
6731fn 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        // Run on a clone so we don't actually mutate.
6744        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/// v0.33: append a Dataset record to a frontier and persist it.
6869#[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/// v0.49: deposit a NegativeResult through `state::add_negative_result`.
6987/// Builds the kind-specific payload, validates the variant fields up
6988/// front (so a missing `--power` for a registered_trial deposit fails
6989/// at the CLI boundary rather than deep in the validator), and prints
6990/// either a stable JSON envelope or a formatted summary.
6991#[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
7149/// v0.49: list NegativeResults in a frontier, optionally filtered by
7150/// the `vf_*` finding they bear against.
7151fn 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/// v0.51: re-classify a kernel object's read-side access tier.
7215#[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/// v0.50: open a Trajectory.
7255#[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/// v0.50: append a step to a Trajectory.
7294#[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        // v0.50 legacy kinds
7307        "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        // v0.194 vision-taxonomy kinds
7313        "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
7365/// v0.50: list Trajectories in a frontier.
7366fn 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            // v0.194: delegate to canonical() so adding new enum
7420            // variants doesn't require updating this site.
7421            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
7429/// v0.33: list datasets in a frontier.
7430fn 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/// v0.33: append a CodeArtifact record to a frontier and persist it.
7473#[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
7572/// v0.33: list code artifacts in a frontier.
7573fn 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/// v0.32: append a Replication attempt to a frontier.
8374///
8375/// Validates the outcome label, builds a `Replication` with a fresh
8376/// content-addressed id, persists it, and prints either a structured
8377/// JSON receipt or a human summary. Refuses to write if the target
8378/// finding is not present in the frontier.
8379#[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    // Build the conditions, evidence, provenance for the replication.
8415    // Conditions text is what enters the content-address preimage; we
8416    // also lift in_vivo/in_vitro/human_data flags from common keywords
8417    // so confidence math behaves sensibly downstream.
8418    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    // Refuse to write if the same vrep_id already exists (idempotent
8485    // re-runs are safe; conflicts surface here).
8486    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    // v0.36.2: trigger the replication-aware propagation cascade. The
8513    // target's confidence is recomputed from the now-updated
8514    // `project.replications` collection (closes the A.1 loop) and
8515    // dependents are flagged for review with `upstream_replication_*`.
8516    // `inconclusive` outcomes do not cascade; we still call propagate
8517    // so the source-side recompute always runs.
8518    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        // Persist propagation events into the canonical review log.
8530        // Without this, the events are emitted to stdout and lost.
8531        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
8595/// v0.32: list replications in a frontier, optionally filtered by target.
8596fn 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
8654/// v0.74: file-extension dispatcher for `vela ingest`. Routes one
8655/// path or stable identifier URI to the right backing path.
8656///
8657/// - `doi:` / `pmid:` / `nct:` URI -> `cmd_source_fetch`.
8658/// - JSON file (Carina-shaped artifact packet) -> `cmd_artifact_to_state`.
8659/// - PDF file or folder of PDFs -> `cmd_scout`. Folder is the
8660///   supported shape today; single-file mode lands in v0.74.2.
8661/// - Markdown file or folder -> `cmd_compile_notes`.
8662/// - CSV / TSV file or folder -> `cmd_compile_data`.
8663/// - Other directory -> `cmd_compile_code`.
8664///
8665/// No new substrate logic; just routing under one verb.
8666async 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    // Stable identifier URI: dispatch to source-fetch.
8675    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        // v0.102: source-fetch only retrieves metadata into a local
8679        // cache; it does not create frontier state. Without this hint,
8680        // a fresh user thinks `vela ingest doi:...` "ingested the
8681        // paper" because the success-shaped output looks like a
8682        // proposal landed. It didn't. Tell them what to do next.
8683        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    // Single-file vs folder + extension routing.
8704    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                // v0.74.2: discover_files now accepts a single file
8713                // and returns a one-element vec, so we can pass
8714                // the PDF path itself directly to scout.
8715                cmd_scout(&p, frontier, backend, dry_run, json).await;
8716            }
8717            Some("md") | Some("markdown") => {
8718                // compile-notes also routes through discover_files
8719                // which handles the single-file case as of v0.74.2.
8720                cmd_compile_notes(&p, frontier, backend, None, None, dry_run, json).await;
8721            }
8722            Some("csv") | Some("tsv") => {
8723                // compile-data routes through discover_files; pass
8724                // the file path directly (v0.74.2).
8725                cmd_compile_data(&p, frontier, backend, None, dry_run, json).await;
8726            }
8727            Some("json") => {
8728                // Carina artifact packet path. Requires an actor id.
8729                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        // v0.99: count files per handlable extension across the
8744        // first level. If multiple content types are present,
8745        // dispatch each handler in sequence rather than dropping
8746        // the non-dominant types silently. The previous v0.74
8747        // behavior picked one dominant type and ignored the rest,
8748        // which silently dropped mixed-source folders.
8749        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                            // Track the unhandled extensions so we can
8772                            // report them at the end. Skip dotfiles.
8773                            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            // No handlable content; treat as a code repo (the
8789            // pre-v0.99 fallback path).
8790            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        // Dispatch in a stable order: PDFs first (richest content),
8804        // then notes, then data, then carina packets. Each handler
8805        // only opens files matching its own extension via
8806        // discover_files; non-matching files are silently skipped
8807        // by the inner handler, so dispatching all four against the
8808        // same folder is safe and idempotent on per-extension subsets.
8809        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            // Carina artifact packets are file-at-a-time. Walk the
8820            // directory and import each .json individually.
8821            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)]
8855/// v0.25 Agent Inbox: dispatches the registered datasets handler.
8856async 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
8886/// v0.28 Agent Inbox: dispatches the registered reviewer-agent
8887/// handler.
8888async 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
8918/// v0.28 Agent Inbox: dispatches the registered contradiction-finder
8919/// handler.
8920async 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
8948/// v0.28 Agent Inbox: dispatches the registered experiment-planner
8949/// handler.
8950async 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
8978/// v0.24 Agent Inbox: dispatches the registered code-analyst
8979/// handler.
8980async 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
9010/// v0.23 Agent Inbox: dispatches the registered notes-compiler
9011/// handler. Same rationale as `cmd_scout` — the substrate stays
9012/// agent-free; the `vela` CLI binary registers the handler at
9013/// startup.
9014async 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
9046/// v0.22 Agent Inbox: dispatches the registered scout handler. The
9047/// substrate library does not import `vela-scientist` (it would induce
9048/// a Cargo cycle); the `vela` CLI binary in `crates/vela-cli`
9049/// registers a handler at startup that calls into the scientist
9050/// crate. Running the lib directly without that registration prints
9051/// a clear error.
9052async 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)]
9081/// v0.113: walk a frontier path and return any files whose names
9082/// match shapes commonly associated with secrets: literal extensions
9083/// (`*.key`, `*.pem`, `*.p12`) and substring patterns (`private`,
9084/// `secret`, `credential`). Skips standard noise (`.git/`, `target/`,
9085/// `node_modules/`, `dist/`, `build/`). Used by `vela check --strict`
9086/// and by `scripts/test-secret-audit.sh`. Closes part of
9087/// THREAT_MODEL.md A17 with active detection on top of the passive
9088/// .gitignore exclusion shipped at v0.111.1.
9089pub 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            // .pub and .pubkey files are public-key material; skip.
9114            if lower.ends_with(".pub") || lower.ends_with(".pubkey") {
9115                continue;
9116            }
9117            // public.key by name is an Ed25519 PUBLIC key; safe.
9118            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    // v0.113: secret-audit pass under --strict runs first, before any
9170    // signal/replay check that could short-circuit via process::exit.
9171    // Scans the frontier tree for files matching sensitive-path shapes
9172    // (private keys, PEM files, files whose names contain "credential",
9173    // "private", "secret"). Closes part of THREAT_MODEL.md A17 by giving
9174    // every user's frontier active detection on top of the passive
9175    // .gitignore exclusion shipped at v0.111.1. Only runs in strict
9176    // mode so the default vela check stays quiet when a user has
9177    // intentionally placed a key under their frontier (e.g. for local
9178    // signing) that they have NOT committed.
9179    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        // v0.106: a fresh `cargo install vela-cli` user runs `vela check`
9239        // from a directory without `tests/conformance/` (those vectors
9240        // live in the source repo). Pre-v0.106 the default
9241        // `run_all` path called `conformance::run` unconditionally,
9242        // which `process::exit(1)`'d with a confusing error. Skip
9243        // gracefully when the conformance dir is missing AND the
9244        // user did not pass `--conformance` explicitly. The
9245        // explicit `--conformance` flag still errors, which is the
9246        // right behavior for someone who asked for it.
9247        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    // Phase J: every v0.4 frontier carries a `frontier.created` genesis
9621    // event in events[0]. That's identity metadata, not a substantive
9622    // mutation, so it doesn't disqualify normalization. Any non-genesis
9623    // canonical event still blocks normalize.
9624    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    // Phase N: optionally rewrite finding.provenance from the canonical
9640    // SourceRecord. The source registry is the authority; provenance is
9641    // the denormalized cache.
9642    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
9881// ── v0.42 daily-driver triad ────────────────────────────────────────
9882
9883/// v0.42: One-screen status. The `git status` analogue.
9884fn cmd_status(path: &Path, json: bool) {
9885    let project = repo::load_from_path(path).unwrap_or_else(|e| fail_return(&e));
9886
9887    // Inbox counts.
9888    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    // Causal audit summary.
9899    let audit = crate::causal_reasoning::audit_frontier(&project);
9900    let audit_summary = crate::causal_reasoning::summarize_audit(&audit);
9901
9902    // Federation health: peers + last sync.
9903    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    // Replication health.
9930    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
10079/// v0.42: Recent canonical events. The `git log` analogue.
10080fn 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
10148/// v0.42: Pending-proposals triage. The thing you sit down to review.
10149fn 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    // Collect reviewer-agent score map (composite shown alongside each
10153    // proposal where present).
10154    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    // Sort: high reviewer-agent composite first, then untyped.
10198    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
10307/// v0.42: Conversational substrate access. Thin REPL over kernel
10308/// queries. Doesn't pretend to be an agent — every answer comes from
10309/// a structured query the kernel can produce deterministically. The
10310/// goal is fluency, not magic.
10311fn 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        // REPL mode.
10316        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    // Pattern: pending / inbox.
10361    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    // Pattern: underidentified / conditional / audit.
10400    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    // Pattern: recent / changed / log.
10453    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    // Pattern: how many / count.
10484    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    // Pattern: calibration.
10517    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    // Pattern: federation / peers / sync.
10541    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    // Fallback.
10573    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    // RFC 3339 → "MM-DD HH:MM" for human reading. Falls back to first
10599    // 16 chars if parsing fails (which is enough to be readable).
10600    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    /// v0.126: when `--cross-check` is requested, this carries one
11048    /// entry per artifact that resolved on at least two sources.
11049    /// Records per-source title + first-author and a per-pair
11050    /// agreement signal.
11051    #[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    /// v0.126: populated when status == "resolved" and the upstream
11063    /// response carried a title. Used by the `--cross-check` mode.
11064    #[serde(skip_serializing_if = "Option::is_none")]
11065    title: Option<String>,
11066    /// v0.126: populated when status == "resolved" and the upstream
11067    /// response carried at least one author. Lowercased last-name.
11068    #[serde(skip_serializing_if = "Option::is_none")]
11069    first_author: Option<String>,
11070}
11071
11072/// v0.126: per-artifact cross-source agreement record.
11073/// An artifact resolves through one or more sources; this struct
11074/// captures whether the sources agree on title and first-author.
11075#[derive(Debug, Clone, Serialize)]
11076struct CrossCheckEntry {
11077    /// All identifiers that resolved for this artifact.
11078    identifiers: Vec<String>,
11079    /// One entry per resolved source.
11080    sources: Vec<CrossCheckSource>,
11081    /// "agree" when all sources match (normalized); "title_mismatch",
11082    /// "author_mismatch", "both_mismatch" otherwise; "insufficient"
11083    /// when fewer than 2 sources resolved.
11084    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
11099/// v0.108.3: walk a packet's artifacts and candidate-claim
11100/// source_refs, extract recognized DOI/PMID identifiers, ask
11101/// the upstream registry whether each one resolves. Closes
11102/// part of THREAT_MODEL.md A6 (citation poisoning).
11103async 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    // Collect candidate identifiers from every locator and source_ref.
11114    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
11176/// v0.126: cross-source agreement pass over an already-verified
11177/// provenance report. Looks at packet artifacts that carry more than
11178/// one identifier across sources (e.g., a paper with both a DOI and
11179/// an ArXiv id) and emits one `CrossCheckEntry` per such artifact
11180/// recording per-source title + first-author and a consensus
11181/// signal. Sources that did not return a title or first-author are
11182/// skipped in the comparison. Two sources with matching normalized
11183/// title AND first-author count as agreement; mismatches surface
11184/// the disagreement with which fields disagree.
11185async fn cross_check_packet_provenance(
11186    packet_path: &Path,
11187    report: &mut ProvenanceVerificationReport,
11188) {
11189    use crate::artifact_to_state::ArtifactPacket;
11190    // Re-read the packet to discover which identifiers cluster on
11191    // the same artifact. The first pass treated each identifier
11192    // independently; the cross-check pass groups by artifact id.
11193    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    // Index resolved entries by canonical identifier.
11202    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        // Collect every recognized identifier that appears in this
11212        // artifact's locator (the packet contract only carries one
11213        // locator per artifact today, so we cannot detect a cluster
11214        // here in the strict sense yet). For now, the cross-check
11215        // pass surfaces single-source artifacts with "insufficient"
11216        // consensus; multi-identifier clusters can be added once the
11217        // packet contract carries them.
11218        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    // Also scan candidate-claims for identifier clusters. Each
11239    // candidate-claim source_refs list may carry several
11240    // identifiers for the same underlying paper; if it does, the
11241    // cluster is a real cross-source agreement opportunity.
11242    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            // Compare pairwise: every pair must agree on both title
11262            // and first-author (when both populated) for the cluster
11263            // to count as "agree". If any pair disagrees on title,
11264            // record title_mismatch; on author, author_mismatch.
11265            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                        // v0.126: prefix-tolerant agreement so
11278                        // PubMed esummary's "Family Initial" format
11279                        // (e.g. "Jumper J" normalized to "j" by the
11280                        // last-token rule) still agrees with
11281                        // Crossref's full "Jumper". Either string
11282                        // being a prefix of the other counts as
11283                        // agreement; only when both are populated
11284                        // and neither is a prefix do we flag
11285                        // mismatch.
11286                        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
11314/// Extract a recognizable identifier from an artifact locator or
11315/// candidate-claim source_ref. Returns canonical `doi:<doi>` or
11316/// `pmid:<pmid>` form, or None when the string carries no
11317/// resolvable identifier.
11318fn extract_identifier(s: &str) -> Option<String> {
11319    let trimmed = s.trim();
11320    if trimmed.is_empty() {
11321        return None;
11322    }
11323    // Already prefixed.
11324    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    // doi.org / dx.doi.org URL forms.
11332    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    // PubMed URL forms.
11338    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    // v0.118: Semantic Scholar URL forms. Two shapes are common:
11348    // the paper page (/paper/<paperId>) and the API URL
11349    // (api.semanticscholar.org/graph/v1/paper/<paperId>). Both
11350    // resolve to the same paperId, which is what we normalize to.
11351    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    // v0.119: ArXiv URL forms. The canonical paper URL is
11371    // arxiv.org/abs/<id>; alternates include /pdf/<id>(.pdf) and
11372    // the legacy hep-th/9711200-style category slugs. All resolve
11373    // to the same paper id (modulo version suffix vN).
11374    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    // Bare DOI shape: "10.<numbers>/<rest>".
11394    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            // v0.126: capture title + first-author from the Crossref
11405            // response so the cross-check mode can compare across
11406            // sources.
11407            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
11444/// v0.126: normalize a title for cross-source comparison. Lower-cases,
11445/// trims, collapses whitespace, and drops punctuation. The
11446/// substrate-honest comparison: titles from Crossref vs PubMed
11447/// frequently differ in capitalization, trailing periods, smart
11448/// quotes, or whitespace runs.
11449fn 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
11458/// v0.126: normalize a person's name (or last-name field) for
11459/// cross-source comparison. The substrate's most common shape is
11460/// "Family, Given" or just "Family"; we extract the last
11461/// whitespace-separated token or the substring before the first
11462/// comma, lowercased.
11463fn 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            // PubMed esummary returns 200 even for nonexistent ids;
11486            // we have to inspect the result body for the id key.
11487            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                // v0.126: extract title + first-author from the
11495                // eutils esummary response. The record is keyed by
11496                // the pmid string under `result`.
11497                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
11547/// v0.118: verify a Semantic Scholar paper id against the public
11548/// Graph API. Accepts S2 paper-id shapes including the 40-char hex
11549/// (corpusId), the SHA, or `DOI:<doi>`-style query strings. Returns
11550/// `resolved` when the API returns 200 with a paperId in the body,
11551/// `unresolved` when 404 or empty, `skipped` when the network is
11552/// unreachable (gates honor skips).
11553async 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                // v0.126: title + first-author from the S2 graph
11564                // response. Title is at `.title`; first author's
11565                // last name comes from `.authors[0].name` (S2's
11566                // name field is typically "Given Family").
11567                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
11616/// v0.119: verify an ArXiv paper id against the public Atom API.
11617/// Accepts ArXiv ids in canonical new form (`<YYMM>.<NNNN>`(`vN`)?)
11618/// or legacy form (`<category>/<YYMMNNN>`). Returns `resolved` when
11619/// the Atom feed contains at least one `<entry>` element naming a
11620/// paper id; `unresolved` when 4xx or empty feed; `skipped` on
11621/// network errors. The ArXiv export API has lighter rate-limiting
11622/// than Semantic Scholar; gates honor the skip-on-network-fail
11623/// contract.
11624async 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            // The Atom feed for an unresolved id still returns 200
11630            // but with `<opensearch:totalResults>0</...>` and zero
11631            // `<entry>` elements. Inspect for the entry tag.
11632            let has_entry = body.contains("<entry>") || body.contains("<entry ");
11633            // Also require an arxiv:id-style tag inside the entry
11634            // to distinguish empty feeds with a default <entry>
11635            // wrapper.
11636            let has_id_url = body.contains("http://arxiv.org/abs/");
11637            if has_entry && has_id_url {
11638                // v0.126: extract title + first-author from the
11639                // Atom feed. Atom titles wrap in <title> and the
11640                // first author's name lives in
11641                // <entry>...<author><name>FAMILY GIVEN</name>.
11642                // The substrate's normalize_last_name picks the
11643                // final whitespace-separated token, which matches
11644                // ArXiv's "First Last" convention. A more robust
11645                // parse would use quick-xml; this conservative
11646                // string match is enough for the agreement signal.
11647                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
11691/// v0.126: extract the inner text of an Atom XML element nested
11692/// inside a scope element. `scope_open` (e.g. `<entry>`) bounds the
11693/// search; `open` / `close` (e.g. `<title>` / `</title>`) bracket
11694/// the text. Returns the first occurrence inside the scope, with
11695/// surrounding whitespace trimmed. Returns None when any anchor is
11696/// missing. Conservative: does not parse attributes or handle CDATA.
11697fn 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            // Re-derive the joint-accept flag immediately; if the
11912            // existing signature pool already meets the threshold, the
11913            // finding becomes jointly_accepted on the same write.
11914            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            // Validate the pubkey shape before mutating the frontier.
11958            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            // v0.43: Validate ORCID shape if supplied. Stored in bare form.
11963            let orcid_normalized = orcid
11964                .as_deref()
11965                .map(|s| sign::validate_orcid(s).unwrap_or_else(|e| fail_return(&e)));
11966            // v0.51: parse clearance up front so a typo fails at the
11967            // CLI boundary rather than silently degrading.
11968            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            // v0.127: validate the new pubkey shape up front.
12026            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            // The new id must not already exist.
12040            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            // The old id must exist and must not already be revoked.
12047            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            // Register the new actor record.
12071            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
12161/// v0.155: resolve an ORCID via the ORCID public API + optionally
12162/// register the resolved person as an actor on a frontier.
12163fn 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    // Normalize ORCID via the existing v0.43 validator.
12171    let normalized = sign::validate_orcid(&orcid).unwrap_or_else(|e| fail_return(&e));
12172
12173    // Call the public ORCID API (`https://pub.orcid.org/v3.0/...`).
12174    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    // Optionally auto-register the actor on the supplied frontier.
12230    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) = &registered_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); // Skip-gracefully: offline ORCID is not a hard error
12312    }
12313}
12314
12315/// v0.40: Causal-typing audit over a frontier.
12316fn 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            // Build a serializable view: each node with its parents
12506            // and children. Optionally restrict to a single node.
12507            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; // hide isolated nodes when listing all
12562                }
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
12670/// v0.46: Cross-frontier bridge runtime — derive, list, show,
12671/// confirm, and refute first-class `vbr_<id>` records.
12672fn 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    /// v0.67: shared default for the agent-driven write paths
12698    /// (bridge confirm/refute).
12699    fn default_reviewer_id() -> String {
12700        std::env::var("VELA_REVIEWER_ID").unwrap_or_else(|_| "reviewer:will-blair".to_string())
12701    }
12702
12703    /// v0.67: emit a `bridge.reviewed` canonical event into the
12704    /// frontier's `.vela/events/` directory so federation sync can
12705    /// propagate the verdict. The bridge file mutation is the
12706    /// projection; this event is the authority.
12707    ///
12708    /// v0.73: tightens the spec gap surfaced in v0.72. Before
12709    /// emission, the function asks `validate_bridge_reviewed_against_state`
12710    /// to confirm the bridge is present on this frontier. The
12711    /// signature-pure validator already rejects bad payload shapes;
12712    /// this second pass rejects bridge_ids that don't exist locally.
12713    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        // v0.73: state-aware validation.
12730        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            // Merge: preserve status from existing bridges with the
12793            // same vbr_<id> (we don't blindly overwrite a Confirmed
12794            // bridge with a fresh Derived one).
12795            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                    // Reviewer judgment is sticky.
12806                    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            // v0.67: emit canonical event so federation sync
12968            // propagates the verdict. The bridge file mutation above
12969            // is the projection; this event is the authority.
12970            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
13014/// v0.39: Manage the federation peer registry.
13015fn 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            // v0.64: refuse cross-vfr sync without explicit opt-in.
13127            // The substrate path is honest about cross-vfr divergence
13128            // (every peer-side finding becomes a "missing_locally"
13129            // conflict), but in practice that floods the inbox with
13130            // noise. The intended use of `--via-hub --vfr-id` is to
13131            // sync against your OWN frontier_id on the peer hub.
13132            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            // v0.41.0: three sync modes (via-hub / direct-url / default-manifest-path).
13145            #[derive(Debug)]
13146            enum SyncOutcome {
13147                Resolved(crate::project::Project, String), // (peer state, source description)
13148                BrokenLocator(String, String, u16),        // (vfr_id, locator, status)
13149                UnverifiedEntry(String, String),           // (vfr_id, reason)
13150                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            // Handle the non-resolved cases by emitting a single
13192            // synthetic conflict event and a sync record.
13193            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
13442/// v0.70: Push a single locally-resolved
13443/// `frontier.conflict_resolved` event to the peer hub's intake
13444/// endpoint. The reviewer is the only one who can sign the push —
13445/// the browser/Workbench never sees the key, same as for proposal
13446/// signing under Phase R.
13447///
13448/// Substrate doctrine: one event per push (no bulk), the hub
13449/// verifies the signature against an actor record on its own copy
13450/// of the frontier, the hub refuses unpaired or already-resolved
13451/// events. The CLI does the matching work locally to fail fast
13452/// when the consumer's own log is missing the resolution.
13453fn 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    // Locate the resolution event paired with conflict_event_id.
13473    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    // Resolve the actor record so we know which public key to send
13490    // and which key file to load.
13491    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    // Resolve the private key path. Caller can pass --key explicitly;
13500    // otherwise look in the conventional locations.
13501    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    // Sign canonical bytes. Same preimage `verify_event_signature`
13535    // checks on the hub side.
13536    let signature_hex = sign::sign_event(&resolution, &signing_key)
13537        .unwrap_or_else(|e| fail_return(&format!("sign event: {e}")));
13538
13539    // The wire body is the canonical event JSON without the
13540    // signature field; the signature travels in the header. This
13541    // keeps the body byte-exact with what the hub will canonicalize
13542    // for verification.
13543    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    // Same blocking-thread escape pattern as the rest of federation.rs.
13558    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
13619/// Phase R (v0.5): walk the local Workbench draft queue. The Workbench
13620/// browser writes unsigned drafts to a queue file; this CLI is the only
13621/// place where the actor's private key reads its drafts and signs them.
13622/// The browser never sees the key.
13623fn 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                        // Keep failed actions in the queue so the user can retry.
13726                        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
13761/// v0.146: derive the on-disk owner-epoch chain transcript path
13762/// for a given frontier. Sits at
13763/// `<frontier-dir>/.vela/governance/chain.json` regardless of
13764/// whether the input is a frontier file or a frontier directory.
13765fn 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
13776/// Default local registry path (`~/.vela/registry/entries.json`).
13777/// Free helper so non-`cmd_registry` callers can resolve it too.
13778fn 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
13786/// v0.140: resolve a `vfr_*` registry id to a concrete frontier
13787/// path on disk. Loads the registry (local or hub URL), looks up
13788/// the latest matching entry, fetches its substrate to `dest`,
13789/// and runs the same verify-pull check `registry pull` uses. The
13790/// caller is responsible for the lifetime of `dest` (typically a
13791/// tempdir entry that is dropped after the consumer is done).
13792fn 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(&registry_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
13846/// Sign and apply a queued action. Returns a short summary string on
13847/// success (the resulting `vpr_…` or `vev_…`). The action is signed
13848/// locally and applied via the same `proposals::*_at_path` functions the
13849/// CLI uses — no HTTP roundtrip required.
13850fn 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            // Sign the proposal locally to validate parity with what the
13921            // server-side write tool would have signed; the queue-sign
13922            // path applies via the local file, not via HTTP.
13923            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            // Sign for parity; `accept_at_path`/`reject_at_path` apply locally.
13943            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
13968/// v0.8: frontier-level metadata commands. Manages cross-frontier
13969/// dependency declarations on a frontier file. The substrate enforces
13970/// that any link target of the form `vf_…@vfr_…` references a declared
13971/// dependency; these commands edit the declaration list.
13972/// v0.9: typed link addition. Until v0.9 the only way to add a link
13973/// was to hand-edit JSON; this command is the CLI on-ramp. Links go
13974/// directly onto `findings[i].links` (links are not a state-changing
13975/// proposal kind in v0).
13976/// v0.19: bundled entity resolution. See `crate::entity_resolve` for the
13977/// table + algorithm. CLI surface is two subcommands: `resolve` (mutates
13978/// the frontier file) and `list` (read-only inspection of the table).
13979fn 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            // v0.16: best-effort cross-frontier target-status check. The
14112            // substrate doctrine is "client verifies on read", but at
14113            // link-add time it's worth a one-shot fetch to warn the user
14114            // if their target has been superseded. Failure to fetch is
14115            // a hint, not a hard error — the link still records.
14116            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            // Refuse if any link still references this vfr_id.
14432            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                            // Locate the dep in our project to compare + (maybe) mutate.
14545                            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
14656/// v0.158: tag the current frontier state as a versioned release.
14657fn 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    // Derive releases dir + chain on the latest existing release
14672    // (if no --previous was supplied).
14673    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    // Owner epoch: the chain transcript at v0.146 has it. If
14681    // present, take the latest transition's owner_epoch;
14682    // otherwise default to 0 (bootstrap).
14683    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
14742/// v0.158: list every release recorded for a frontier.
14743fn 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
14969/// v0.32: structured diff of findings added/updated/contradicted in a
14970/// time window. Read-only over canonical state; does not modify the
14971/// frontier and does not need a signing key.
14972///
14973/// Window resolution priority: `--since` > `--week` > current ISO week.
14974/// If `--since` is given, the upper bound is "now" (UTC); the diff
14975/// covers `[since, now)`. If `--week` is given (or defaulted), the
14976/// window is `[Mon 00:00 UTC, next Mon 00:00 UTC)`.
14977fn 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    // ── Resolve the window ──
14981    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    // ── Bucket findings ──
15001    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    // ── Render ──
15042    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
15143/// ISO 8601 week key in `YYYY-Www` form for a given calendar date.
15144fn 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
15150/// Resolve `YYYY-Www` to its UTC bounds:
15151/// `[Monday 00:00 UTC, next Monday 00:00 UTC)`.
15152fn 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
15175/// Phase S (v0.5): registry CLI — publish/pull a frontier through a
15176/// signed manifest. Verifiable distribution: any third party can pull
15177/// and confirm the snapshot and event-log hashes match what the owner
15178/// signed.
15179fn 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            // v0.129: A11 mitigation. Pull `vfr_id` from every named
15324            // hub, canonicalize each entry, compare. Reports per-hub
15325            // canonical hash plus consensus signal:
15326            //   `unanimous`  — every hub returned byte-identical
15327            //                   canonical bytes.
15328            //   `majority`   — most hubs agree; some diverge.
15329            //   `split`      — no hub has a majority.
15330            //   `insufficient` — fewer than 2 hubs responded.
15331            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                                // Canonicalize via the substrate's
15361                                // canonical-bytes helper so hub-side
15362                                // key ordering or whitespace
15363                                // differences do not falsely split.
15364                                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            // Consensus signal.
15400            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            // Phase γ-hub (v0.7): `--from <https://...>` fetches the
15457            // registry over HTTPS; bare paths and file:// resolve locally.
15458            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            // Read and parse the private key first so we can derive
15528            // the pubkey before we look at the actor registry.
15529            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            // Load frontier and look up (or auto-register) the owner.
15536            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                    // v0.101 auto-bootstrap: an unregistered owner who
15543                    // supplies a valid private key gets registered on
15544                    // the fly using the derived pubkey. Eliminates the
15545                    // "publish fails, run `vela actor add`, retry" loop
15546                    // for fresh frontiers. The auto-registration is
15547                    // recorded as a normal actor entry; subsequent
15548                    // publishes go through the registered-path.
15549                    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            // Compute snapshot+event_log hashes after any auto-
15571            // registration write so the published manifest reflects
15572            // the actor record we just persisted.
15573            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            // Sanity check: pubkey on disk matches pubkey in the registry.
15579            if derived != pubkey {
15580                fail(&format!(
15581                    "private key does not match registered pubkey for owner '{owner}'"
15582                ));
15583            }
15584
15585            // Phase A2 (v0.7): when `--to` is an HTTPS URL we POST the
15586            // signed entry to a hub; otherwise we resolve a local file
15587            // and append. v0.55: the locator can be auto-filled when
15588            // publishing to a remote hub: the hub's own
15589            // `/entries/<vfr>/snapshot` endpoint is the canonical fetch
15590            // location once substrate is promoted into event/projection
15591            // tables.
15592            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                // v0.55: include the substrate inline so the hub can
15631                // verify hashes, store the snapshot export, and promote
15632                // event/projection rows for live reads.
15633                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(&registry_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            // Read and parse the new owner's private key first so
15698            // we can derive the new pubkey before we mutate the
15699            // frontier.
15700            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            // Revoke the current owner. Must exist and not already be revoked.
15712            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            // Register the new owner actor record. Auto-bootstrap
15736            // if the id is not already present (mirrors the publish
15737            // auto-registration path from v0.101). If it IS already
15738            // present, the pubkey must match the derived pubkey.
15739            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            // Re-publish under the new owner credentials. Mirrors
15774            // the RegistryAction::Publish path verbatim so the hub
15775            // sees a normal signed entry under the new pubkey.
15776            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(&registry_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            // Phase γ-hub (v0.7): both the registry and the frontier
15881            // can live behind https:// now. Local file:// and bare-path
15882            // remain supported.
15883            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(&registry_data, &vfr_id)
15904                .unwrap_or_else(|| fail_return(&format!("{vfr_id} not found in registry")));
15905
15906            if transitive {
15907                // v0.8: --transitive walks the dep graph. `out` is
15908                // interpreted as a directory; the primary lands at
15909                // out/<vfr>.json, deps at out/<dep_vfr>.json.
15910                let result = registry::pull_transitive(&registry_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            // Fetch the frontier from its locator (file:// or https://)
15954            // and verify hashes + signature.
15955            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
15990/// v0.145: handle `vela registry owner-rotate-governed {propose|attest|apply}`.
15991fn 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            // Re-derive proposal id and assert match.
16108            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            // Load existing bundle if present; else start fresh.
16136            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            // Idempotency: replace any existing entry from the same
16152            // attester_id under the same proposal.
16153            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            // Load proposal, bundle, policy.
16202            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            // Build the revocation lookup from the frontier's actors.
16222            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            // The proposal's new_owner_pubkey must match the
16237            // supplied --new-key. Read the key, derive the pubkey,
16238            // compare.
16239            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            // Mutate the frontier: revoke the current owner, register
16252            // (or promote) the new owner. Mirrors the v0.138 rotate
16253            // path.
16254            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            // Re-publish under the new owner key. Mirrors the
16292            // v0.138 publish path with the rotated entry pointing
16293            // at the new owner pubkey.
16294            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(&registry_path, entry.clone())
16345                    .unwrap_or_else(|e| fail_return(&e));
16346                (registry_path.display().to_string(), false)
16347            };
16348
16349            // v0.146: append a transition to the owner-epoch chain
16350            // transcript sitting at <frontier-dir>/.vela/governance/chain.json.
16351            // The chain is the audit transcript a consumer pulls
16352            // and replays to verify the entire epoch chain from
16353            // genesis to the current entry.
16354            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/// v0.151: handle `vela proof-attest-verification ...`.
16434#[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
16504/// v0.151: handle `vela proof-verify-attestation <record>`.
16505fn 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
16559/// v0.157: handle `vela credit <frontier>`.
16560fn 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
16614/// v0.168: handle `vela review-thread ...`. Substrate-honest
16615/// review threads on proposals or findings; append-only,
16616/// signed, content-addressed.
16617fn 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
16771/// v0.167: handle `vela hub ...`. Build + validate hub-spec
16772/// primitive records.
16773fn 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            // Re-derive id from a fresh draft.
16835            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
16875/// v0.164: handle `vela lean ...`. Anchors substrate theorems to
16876/// their content-addressed source bytes.
16877fn 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
17208/// v0.193: handle `vela diff-pack <action>`. Build, show, or
17209/// verify a Scientific Diff Pack (`vsd_*`).
17210fn 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            // Validate that every cited proposal exists on the
17227            // frontier. The pack is meaningless if it cites a
17228            // proposal that isn't there.
17229            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            // GET <hub>/diff-packs/<pack_id> from each hub; collect
17448            // canonical-bytes hashes for comparison.
17449            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            // Classify: verified (all present + same signature),
17529            // split (present but different signatures), partial
17530            // (some missing), unreachable (network errors).
17531            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                // All present — compare signatures byte-for-byte.
17539                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
17581/// v0.199: handle `vela tool` — register / show / verify a Tool
17582/// Descriptor (`vtd_*`).
17583fn 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
17718/// v0.200: handle `vela eval` — record / show / verify an
17719/// Evaluation Record (`ver_*`).
17720fn 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
17901/// v0.218: handle `vela conflict` — detect / resolve / list
17902/// Verdict Conflicts on a frontier.
17903fn 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            // Scan .vela/pending_verdicts/<vpv>.json for contradictions.
17910            // Two verdicts contradict when:
17911            //   * they target distinct packs (different pack_id),
17912            //   * the packs share at least one member vpr_*,
17913            //   * the verdict outcomes are different (accept vs reject,
17914            //     or accept vs revise, or reject vs revise).
17915            let pending = diff_pack_review::list_at_path(&frontier);
17916            // Load every pack referenced so we know its members.
17917            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            // Compare every pair of pending verdicts.
17939            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            // Persist the vdc_* under .vela/verdict_conflicts/.
18059            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
18139/// v0.163: handle `vela preprint <frontier>`. Renders a Markdown
18140/// preprint body for the frontier.
18141fn 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
18178/// v0.163: handle `vela handle <id>`. Classifies a persistent
18179/// identifier and prints the resolved kind + canonical URL.
18180fn 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/// v0.162: handle `vela crossref --frontier <path> ...`. Generates
18200/// a Crossref deposit manifest for a frontier release. The
18201/// substrate emits the deposit body; submission to Crossref is the
18202/// operator's responsibility under their own member account.
18203#[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
18298/// v0.156: handle `vela citation <target> --format <fmt>`.
18299fn 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    // Two modes: frontier path | finding id.
18312    let body = if target.starts_with("vf_") {
18313        // Finding mode: require --frontier and look up the
18314        // finding inside that frontier's bundle list.
18315        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        // Frontier mode: target IS the frontier path.
18336        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        // Default: print to stdout. --json wraps the body in a
18368        // JSON envelope; otherwise dumps the raw citation text.
18369        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
18387/// v0.149: handle `vela search-index {build|query}` via
18388/// registered handlers (the substrate-side vela-search crate
18389/// is wired in from vela-cli's main.rs).
18390async 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
18436/// v0.148: handle `vela registry hub-federation status`.
18437fn 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                // Fetch the checkpoint JSON. Two transports: file://
18491                // for local files, https?:// for hub endpoints.
18492                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                            // Re-derive the id to catch tampered signatures.
18511                            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            // Consensus on (registry_root, sequence).
18567            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
18620/// v0.153: handle `vela registry verify-all`.
18621fn 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(&registry_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 &registry_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
18707/// v0.147: handle `vela registry checkpoint {create|verify}`.
18708fn 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(&registry_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(&registry_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(&registry_path).unwrap_or_else(|e| fail_return(&e));
18789
18790            if let Err(e) = cp.verify(&registry_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
18836/// v0.146: verify the owner-epoch chain transcript for a frontier.
18837fn 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        // Legacy entry (pre-v0.144): no chain file.
18846        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    // Load artifacts up front so the closure-borrow stays simple.
18874    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
18964/// Revocation lookup backed by the frontier's actor records.
18965struct 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
18975/// v0.144: handle `vela registry governance {init|show|validate}`.
18976fn 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                // No --out: print policy JSON to stdout (the
19068                // envelope is JSON whether --json was passed or
19069                // not; the flag is for the summary, not the body).
19070                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
19469/// v0.26 VelaBench: compare a candidate frontier (typically agent-
19470/// generated) against a gold frontier. Pure data comparison —
19471/// no LLM call, no network, deterministic. Exits non-zero when
19472/// the composite falls below `threshold` (default 0.0 = report only).
19473fn 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
19668/// `vela verify <packet_dir>` — same code path as
19669/// `vela packet validate`, surfaced under a friendlier top-level name.
19670/// Reads every file in the manifest, recomputes SHA-256, validates the
19671/// proof-trace chain. Exit 0 on all-match, 1 on any mismatch.
19672fn 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
19726/// v0.103: end-to-end first-run wizard. Composes `vela init`, `vela
19727/// sign generate-keypair`, `vela actor add`, and `vela finding add
19728/// --apply` into a single command. Each step shells out to the
19729/// current binary so the wizard's behavior matches running the
19730/// commands directly. Failure of any step aborts; partial state is
19731/// left on disk for the user to inspect.
19732/// v0.131: scaffold an AI-agent identity kit. Generates an Ed25519
19733/// keypair via the existing `sign generate-keypair` path, writes
19734/// the agent's portable record to `agents/<slug>/actor.json`
19735/// (`id: agent:<slug>-<date>`, `type: agent`, `public_key: ...`),
19736/// plus a minimal `agent.yaml` config naming the framework. The
19737/// substrate-honest contract: the agent record is portable — a
19738/// reviewer can register it into any frontier with
19739/// `vela actor add <frontier> <agent_id> --pubkey <hex>`. The
19740/// agent has no special privilege at registration time; its
19741/// proposals flow through the same reviewer-gated truth-claim
19742/// discipline as any other actor.
19743fn 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            // Conservative slug validation: lowercase alphanumeric +
19757            // hyphens. Reject path traversal, spaces, etc.
19758            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            // Generate a keypair via the existing CLI surface. This
19794            // keeps the agent kit's keypair generation byte-identical
19795            // to `vela sign generate-keypair`.
19796            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            // actor.json — the substrate's portable record. A
19820            // reviewer feeds this into `vela actor add` to register
19821            // the agent in a specific frontier.
19822            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            // agent.yaml — minimal config; framework + workflow notes.
19839            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    // Step 1: init the frontier.
19980    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    // Step 2: generate keypair.
19993    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    // Step 3: register the reviewer actor.
20013    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    // Step 4: add and apply the first finding.
20027    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
20102/// v0.109: regenerate or verify the frontier's vela.lock.
20103/// Default mode runs `frontier_repo::materialize` which rebuilds
20104/// the lock from current state. `--check` reads the existing
20105/// lock and verifies on-disk hashes match the recorded values
20106/// without writing anything; exits 1 on drift.
20107fn 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
20227/// v0.110: write a static HTML documentation site for the
20228/// frontier at `path`. Output lands in `<path>/doc/` by default
20229/// or in the user-supplied `--out` directory. Cargo's docs.rs
20230/// analog for scientific state.
20231fn 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
20301/// v0.57: Fetch metadata + abstract for an external source.
20302/// Cache-first: if a cache hit exists and `--refresh` was not
20303/// passed, return the cached JSON. Otherwise call the right
20304/// upstream (Crossref / NCBI eutils / ClinicalTrials.gov v2).
20305async 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        // v0.66: DOI primary path is Crossref. If Crossref returns
20399        // an empty abstract (common for NEJM, JAMA, gated journals),
20400        // fall through to a PubMed lookup via DOI -> PMID and merge
20401        // the abstract back into the Crossref record. Keeps Crossref
20402        // metadata (title, year, journal, authors) authoritative;
20403        // only fills the abstract gap.
20404        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
20441/// v0.66: resolve a DOI to a PubMed PMID via eutils esearch. Returns
20442/// None if no PMID is found or the lookup fails. The abstract-fallback
20443/// path uses this to enrich Crossref records that have empty abstracts.
20444async 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        // Refuse ambiguous matches; the substrate would rather have
20457        // an empty abstract than the wrong paper's text.
20458        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    // v0.36.2: persist propagation events into the canonical review
20716    // log. Pre-v0.36.2 these were emitted to stdout and lost — the
20717    // kernel forgot why a finding was flagged the moment the command
20718    // returned.
20719    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    // Build the per-finding rows: only those with non-empty discord
20962    // (i.e. those in support), filtered by kind if requested.
20963    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    // Per-kind histogram across the full assignment (independent of
20976    // the row filter, so the histogram reflects the substrate's real
20977    // discord landscape).
20978    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    // v0.32: replication as a first-class kernel object.
21410    "replicate",
21411    "replications",
21412    // v0.33: computational provenance — datasets and code as
21413    // first-class kernel objects.
21414    "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    // v0.49: NegativeResult deposits (registered_trial + exploratory).
21431    "negative-result-add",
21432    "negative-results",
21433    // v0.50: Trajectory — search-path deposits.
21434    "trajectory-create",
21435    "trajectory-step",
21436    "trajectories",
21437    // v0.51: dual-use access tier classification.
21438    "tier-set",
21439    // v0.56: mechanical evidence-atom locator repair.
21440    "locator-repair",
21441    // v0.57: mechanical finding-level span repair.
21442    "span-repair",
21443    // v0.57: entity resolution.
21444    "entity-resolve",
21445    // v0.79: append a new entity tag to an existing finding.
21446    "entity-add",
21447    // v0.117: register a Carina Proof primitive (vpf_*) against a finding.
21448    "proof-add",
21449    // v0.131: scaffold an AI-agent identity kit (agent init / list).
21450    "agent",
21451    // v0.57: external source fetch (Crossref / PubMed / CT.gov).
21452    "source-fetch",
21453    // v0.34: predictions and resolutions — the epistemic accountability
21454    // ledger.
21455    "predict",
21456    "resolve",
21457    "predictions",
21458    "predictions-expire",
21459    "calibration",
21460    // v0.35: inference layer — consensus aggregation over claim-similar
21461    // findings.
21462    "consensus",
21463    // v0.39: federation — peer registry + sync runtime.
21464    "federation",
21465    // v0.40: causal reasoning — identifiability audit.
21466    "causal",
21467    // v0.42: daily-driver triad + conversational REPL. The
21468    // "git status / git log / inbox" of the substrate, plus a
21469    // thin natural-language router over the same kernel queries.
21470    "status",
21471    "log",
21472    "inbox",
21473    "ask",
21474    // v0.46: cross-frontier bridge runtime.
21475    "bridges",
21476    // v0.48: local workbench web app.
21477    "workbench",
21478    // v0.49: friendlier alias for `vela packet validate <path>`.
21479    "verify",
21480    // v0.74: top-level alias verbs that surface the daily flow
21481    // (init/ingest/propose/diff/accept/attest/log/lineage/serve)
21482    // without burying the verbs inside subcommand groups.
21483    "ingest",
21484    "propose",
21485    "accept",
21486    "attest",
21487    "lineage",
21488    // v0.75: Carina spec deliverable (list/schema/validate
21489    // against the 14 bundled primitive schemas).
21490    "carina",
21491    // v0.78: Atlas-level surface (init / materialize / serve).
21492    // Routes through handlers the binary installs.
21493    "atlas",
21494    // v0.82: Constellation-level surface (init / materialize /
21495    // serve). Network of Atlases (vco_*).
21496    "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
21622/// v0.22 Agent Inbox: pluggable handler for `vela scout`.
21623///
21624/// The substrate library can't import `vela-scientist` (cyclic
21625/// dependency), so the scout dispatch in this module looks up a
21626/// handler installed by the binary at startup. The `vela` CLI in
21627/// `crates/vela-cli` registers a real handler via
21628/// `register_scout_handler`. Library callers that want scout
21629/// behaviour install their own.
21630pub 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
21640/// Install the scout handler. Idempotent — second registrations are
21641/// silently ignored so a misbehaving consumer can't unseat the
21642/// binary's wiring mid-run.
21643pub fn register_scout_handler(handler: ScoutHandler) {
21644    let _ = SCOUT_HANDLER.set(handler);
21645}
21646
21647/// v0.78: pluggable handler for `vela atlas init`. The binary in
21648/// `vela-cli/src/main.rs` installs a real handler that calls into
21649/// the `vela-atlas` crate.
21650pub 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
21665/// v0.149: pluggable handler for `vela search build`.
21666pub 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/// v0.149: pluggable handler for `vela search query`.
21681#[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
21701/// v0.78: pluggable handler for `vela atlas materialize`.
21702pub 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
21711/// v0.78: pluggable handler for `vela atlas serve`. v0.78 stub
21712/// delegates to the per-frontier Workbench for the first
21713/// composing frontier. Dedicated Atlas-level Workbench page is
21714/// v0.79+.
21715pub 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
21728/// v0.81.2: pluggable handler for `vela atlas update`. Lets the
21729/// binary update an Atlas's composing-frontier list without the
21730/// rm-and-init dance. The handler re-computes the Atlas's
21731/// content-addressed id and writes the updated manifest.
21732pub 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
21746/// v0.82: Constellation-level handlers. Mirror the Atlas
21747/// pattern one layer up. The binary registers handlers that
21748/// call into the `vela-constellation` crate.
21749pub 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
21789/// v0.23 Agent Inbox: pluggable handler for `vela compile-notes`.
21790/// Same OnceLock pattern as the scout handler; the binary
21791/// registers it at startup.
21792pub 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
21804/// Install the notes-compiler handler. Idempotent.
21805pub fn register_notes_handler(handler: NotesHandler) {
21806    let _ = NOTES_HANDLER.set(handler);
21807}
21808
21809/// v0.24 Agent Inbox: pluggable handler for `vela compile-code`.
21810pub 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
21821/// Install the code-analyst handler. Idempotent.
21822pub fn register_code_handler(handler: CodeHandler) {
21823    let _ = CODE_HANDLER.set(handler);
21824}
21825
21826/// v0.25 Agent Inbox: pluggable handler for `vela compile-data`.
21827pub 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
21838/// Install the datasets handler. Idempotent.
21839pub fn register_datasets_handler(handler: DatasetsHandler) {
21840    let _ = DATASETS_HANDLER.set(handler);
21841}
21842
21843/// v0.28 Agent Inbox: handler for `vela review-pending`.
21844pub 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
21855/// Install the reviewer-agent handler. Idempotent.
21856pub fn register_reviewer_handler(handler: ReviewerHandler) {
21857    let _ = REVIEWER_HANDLER.set(handler);
21858}
21859
21860/// v0.28 Agent Inbox: handler for `vela find-tensions`.
21861pub 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
21871/// Install the contradiction-finder handler. Idempotent.
21872pub fn register_tensions_handler(handler: TensionsHandler) {
21873    let _ = TENSIONS_HANDLER.set(handler);
21874}
21875
21876/// v0.28 Agent Inbox: handler for `vela plan-experiments`.
21877pub 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
21887/// Install the experiment-planner handler. Idempotent.
21888pub fn register_experiments_handler(handler: ExperimentsHandler) {
21889    let _ = EXPERIMENTS_HANDLER.set(handler);
21890}
21891
21892// ── v0.47: session entry ─────────────────────────────────────────────
21893//
21894// Bare `vela` (no args) opens a session against the nearest `.vela/`
21895// repo, walking up from cwd. The session prints a one-screen
21896// dashboard, then accepts single-letter verb shortcuts or
21897// natural-language questions routed through `cmd_ask`.
21898//
21899// Doctrine: this is the daily-driver entry, not a kitchen-sink IDE.
21900// Single screen, no scroll, no full TUI redraw. Each verb spawns the
21901// existing kernel command and prints its output inline. The session
21902// stays out of the user's way: type something, get an answer, type
21903// again. OpenCode/Claude Code shape.
21904
21905/// Walk up from `cwd` looking for a `.vela/` directory. Returns the
21906/// first parent that contains one, or `None` if none found.
21907fn 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
22086/// Run a single verb shortcut. Returns true if the verb was recognized.
22087fn 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            // No specific source/target — print the live pairs the
22131            // user can run counterfactual queries against.
22132            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            // Walk every finding's `depends`/`supports` links; a live
22143            // counterfactual pair is (target, child) where the link
22144            // from child to target carries a mechanism.
22145            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            // Reload + re-render dashboard.
22177            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        // Fall through: treat as natural-language question.
22239        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        // v0.47: bare `vela` opens a session against the nearest
22255        // `.vela/` repo. The 30+ subcommand list is still there for
22256        // direct invocation; the session is the daily-driver entry.
22257        None => {
22258            run_session();
22259            return;
22260        }
22261        Some("-h" | "--help" | "help") => {
22262            // v0.47: top-level help shows the daily flow. The full
22263            // 30+ subcommand list lives behind `vela help advanced`.
22264            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
22327/// Validate that a CLI string argument is one of the allowed enum values.
22328/// On mismatch, prints a friendly error naming the flag and the valid set
22329/// and exits with code 1. Used at finding-add time so users learn before
22330/// strict validation rejects the resulting frontier.
22331fn 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}