Skip to main content

vela_cli/cli/
mod.rs

1use vela_protocol::sign;
2
3use std::path::Path;
4
5use clap::Parser;
6use serde_json::json;
7use vela_protocol::cli_style as style;
8
9#[derive(Parser)]
10#[command(name = "vela", version)]
11#[command(about = "Portable frontier state for science")]
12struct Cli {
13    /// Suppress hint/advice lines (VELA_ADVICE=0 does the same).
14    #[arg(long, global = true)]
15    quiet: bool,
16    #[command(subcommand)]
17    command: Commands,
18}
19
20pub(crate) use crate::cli_admin::*;
21pub(crate) use crate::cli_check::*;
22use crate::cli_commands::*;
23use crate::cli_engine::{cmd_reproduce, cmd_verify_evidence};
24pub(crate) use crate::cli_read::*;
25pub(crate) use crate::cli_write::*;
26
27mod authority;
28pub(crate) mod help_text;
29mod identity;
30mod lifecycle;
31mod output;
32pub(crate) mod progress;
33pub(crate) mod records;
34pub(crate) mod review_decision;
35pub(crate) mod safe_text;
36mod surface;
37pub(crate) use authority::*;
38pub(crate) use identity::*;
39pub(crate) use lifecycle::*;
40pub(crate) use output::*;
41pub(crate) use records::*;
42pub(crate) use surface::*;
43pub async fn run_command() {
44    // Deliberately NO dotenv here. `dotenvy::dotenv()` walks the working
45    // tree upward, and vela runs inside CLONED frontier repos — a
46    // committed .env could silently inject VELA_ACTOR_ID / VELA_KEY_PATH /
47    // VELA_NO_PUBLISH for anyone who runs vela in it
48    // (the attack class git blocks via protected configuration and
49    // Codex blocks by refusing base-url keys in project config).
50    // Configuration comes from the real environment and ~/.vela only.
51
52    // Color contract: NO_COLOR always wins; ui.color=never/always
53    // overrides the tty heuristic.
54    if std::env::var_os("NO_COLOR").is_some() {
55        colored::control::set_override(false);
56    } else {
57        match crate::config::settings::resolve("ui.color", None)
58            .0
59            .as_str()
60        {
61            "never" => colored::control::set_override(false),
62            "always" => colored::control::set_override(true),
63            _ => {}
64        }
65    }
66
67    let cli = Cli::parse();
68    crate::ui::set_quiet(cli.quiet);
69    match cli.command {
70        Commands::Repository { action } => match action {
71            RepositoryAction::Verify { frontier, json } => {
72                crate::current_repository::cmd_repository_verify(&frontier, json)
73            }
74        },
75        Commands::Check {
76            source,
77            strict,
78            json,
79        } => cmd_check(source.as_deref(), strict, json),
80        Commands::Doctor {
81            frontier,
82            all,
83            json,
84        } => cmd_doctor(frontier.as_deref(), all, json).await,
85        Commands::Status { frontier, json } => {
86            cmd_status_compact(&crate::ui::resolve_frontier(frontier), json)
87        }
88        Commands::Log {
89            frontier,
90            object_id,
91            limit,
92            kind,
93            as_of,
94            json,
95        } => {
96            let frontier = crate::ui::resolve_frontier(frontier);
97            cmd_log(
98                &frontier,
99                object_id.as_deref(),
100                limit,
101                kind.as_deref(),
102                as_of.as_deref(),
103                json,
104            );
105        }
106        Commands::Verification { action } => cmd_verify_evidence(action),
107        Commands::Agents { action } => crate::cli_agents::cmd_agents(action),
108        Commands::Completions { shell } => {
109            use clap::CommandFactory;
110            let mut cmd = Cli::command();
111            let name = cmd.get_name().to_string();
112            let shell_kind: clap_complete::Shell = match shell.as_str() {
113                "bash" => clap_complete::Shell::Bash,
114                "zsh" => clap_complete::Shell::Zsh,
115                "fish" => clap_complete::Shell::Fish,
116                other => fail_return(&format!(
117                    "unsupported shell '{other}'. Valid: bash, zsh, fish"
118                )),
119            };
120            clap_complete::generate(shell_kind, &mut cmd, name, &mut std::io::stdout());
121        }
122
123        Commands::Reproduce {
124            path,
125            proposal,
126            json,
127        } => cmd_reproduce(&path, proposal.as_deref(), json),
128        Commands::Id { action } => cmd_id(action),
129        Commands::Authority { action } => match action {
130            AuthorityAction::Init {
131                frontier,
132                key,
133                reason,
134                json,
135            } => cmd_authority_init(&frontier, key.as_deref(), &reason, json),
136            AuthorityAction::Trust { action } => match action {
137                AuthorityTrustAction::Pin {
138                    frontier,
139                    record_root,
140                    previous_record_root,
141                    json,
142                } => cmd_authority_trust_pin(
143                    &frontier,
144                    &record_root,
145                    previous_record_root.as_deref(),
146                    json,
147                ),
148            },
149        },
150        Commands::Init {
151            path,
152            name,
153            scope,
154            json,
155        } => cmd_init(&path, name.as_deref(), scope.as_deref(), json),
156        Commands::Review { action } => cmd_review(action),
157        Commands::TargetIndex { action } => crate::target_index::cmd_target_index(action),
158        Commands::Claim {
159            command:
160                ClaimCommands::Show {
161                    frontier,
162                    claim_id,
163                    view,
164                    json,
165                },
166        } => crate::current_read::cmd_claim_show(&frontier, &claim_id, &view, json),
167        Commands::Show {
168            frontier,
169            object_id,
170            json,
171        } => crate::current_read::cmd_show(&frontier, &object_id, json),
172        Commands::Why {
173            frontier,
174            claim_id,
175            json,
176        } => crate::current_read::cmd_why(&frontier, &claim_id, json),
177        Commands::Next {
178            frontier,
179            limit,
180            json,
181        } => {
182            crate::ui::set_mode("next", json);
183            let dir = crate::ui::resolve_frontier(frontier);
184            crate::current_repository::cmd_current_next(&dir, limit, json);
185        }
186        Commands::Start {
187            target,
188            frontier,
189            ttl,
190            drop: drop_it,
191            reason,
192            r#as,
193            json,
194        } => {
195            crate::ui::set_mode("start", json);
196            let dir = crate::ui::resolve_frontier(frontier);
197            let actor = crate::cli_identity::resolve_actor(r#as.as_deref());
198            crate::current_work::cmd_start(
199                &dir,
200                target.as_deref(),
201                ttl,
202                drop_it,
203                reason.as_deref(),
204                &actor,
205                json,
206            );
207        }
208        Commands::Submit {
209            submission,
210            frontier,
211            claim,
212            claim_type,
213            condition,
214            replayability,
215            artifact,
216            caveat,
217            producer_check,
218            verification_requirement,
219            corrects,
220            supersedes,
221            target_root,
222            packet_root,
223            profile_root,
224            verifier_capsule_root,
225            result_contract_root,
226            attempt,
227            r#as,
228            push,
229            json,
230        } => {
231            crate::ui::set_mode("submit", json);
232            let dir = crate::ui::resolve_frontier(frontier);
233            let actor = crate::cli_identity::resolve_actor(r#as.as_deref());
234            let preflight_identity =
235                vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
236                    "schema": "vela.submit-preflight.internal.v1",
237                    "frontier": dir.display().to_string(),
238                    "actor": actor,
239                    "submission": submission.as_ref().map(|path| path.display().to_string()),
240                    "claim": claim,
241                    "claim_type": claim_type,
242                    "conditions": condition,
243                    "replayability": replayability,
244                    "artifacts": artifact,
245                    "caveats": caveat,
246                    "producer_checks": producer_check,
247                    "verification_requirements": verification_requirement,
248                    "corrects": corrects,
249                    "supersedes": supersedes,
250                    "target_root": target_root,
251                    "packet_root": packet_root,
252                    "profile_root": profile_root,
253                    "verifier_capsule_root": verifier_capsule_root,
254                    "result_contract_root": result_contract_root,
255                    "attempt": attempt,
256                    "push": push,
257                }))
258                .unwrap_or_default();
259            let preflight_id =
260                crate::operation_journal::operation_id("submit-preflight", &preflight_identity);
261            let fail_preflight = |kind, message: String| -> ! {
262                crate::ui::fail_unchanged(kind, &message, &preflight_id, "vela submit --help")
263            };
264            let (submission, bundle_root) = if let Some(path) = submission {
265                let raw =
266                    crate::bounded_file::read_bounded_file(&path, 8 * 1024 * 1024, "Submission v1")
267                        .unwrap_or_else(|error| {
268                            let kind = if error.code == "missing" {
269                                crate::ui::ErrorKind::NotFound
270                            } else {
271                                crate::ui::ErrorKind::Domain
272                            };
273                            fail_preflight(kind, error.to_string())
274                        });
275                let parsed = vela_protocol::submission_v1::SubmissionV1::parse(&raw)
276                    .unwrap_or_else(|error| {
277                        fail_preflight(crate::ui::ErrorKind::Domain, error.to_string())
278                    });
279                let root = path.parent().map(std::path::Path::to_path_buf);
280                (parsed, root)
281            } else {
282                let Some(claim) = claim else {
283                    crate::ui::fail_unchanged(
284                        crate::ui::ErrorKind::Usage,
285                        "submit needs a Submission file or --claim",
286                        &preflight_id,
287                        "vela submit --help",
288                    );
289                };
290                let claim_type = claim_type.unwrap_or_else(|| {
291                    fail_preflight(
292                        crate::ui::ErrorKind::Usage,
293                        "flag authoring needs --type (computational, theoretical, empirical, negative, or contradiction)".to_string(),
294                    )
295                });
296                let replayability = replayability.unwrap_or_else(|| {
297                    fail_preflight(
298                        crate::ui::ErrorKind::Usage,
299                        "flag authoring needs --replayability (exact, bounded, approximate, unavailable, or unknown)".to_string(),
300                    )
301                });
302                let execution_binding = match (
303                    packet_root,
304                    profile_root,
305                    verifier_capsule_root,
306                    result_contract_root,
307                ) {
308                    (
309                        Some(packet_root),
310                        Some(profile_root),
311                        Some(verifier_capsule_root),
312                        Some(result_contract_root),
313                    ) => {
314                        let binding = vela_protocol::execution_binding::ExecutionBindingV1 {
315                            schema: vela_protocol::execution_binding::EXECUTION_BINDING_SCHEMA
316                                .to_string(),
317                            packet_root,
318                            profile_root,
319                            verifier_capsule_root,
320                            result_contract_root,
321                        };
322                        binding.validate().unwrap_or_else(|error| {
323                            fail_preflight(
324                                crate::ui::ErrorKind::Usage,
325                                format!("invalid exact execution binding: {error}"),
326                            )
327                        });
328                        Some(binding)
329                    }
330                    (None, None, None, None) => None,
331                    _ => fail_preflight(
332                        crate::ui::ErrorKind::Usage,
333                        "exact execution binding requires all four full roots".to_string(),
334                    ),
335                };
336                let requested_change =
337                    crate::workflow::submission_requested_change(corrects, supersedes, target_root)
338                        .unwrap_or_else(|error| fail_preflight(crate::ui::ErrorKind::Usage, error));
339                let authored = crate::workflow::author_submission(
340                    &dir,
341                    &actor,
342                    attempt.as_deref(),
343                    claim,
344                    claim_type,
345                    condition,
346                    replayability,
347                    &artifact,
348                    caveat,
349                    producer_check,
350                    verification_requirement,
351                    requested_change,
352                    execution_binding,
353                )
354                .unwrap_or_else(|error| {
355                    fail_preflight(
356                        crate::ui::ErrorKind::Domain,
357                        format!("Submission build: {error}"),
358                    )
359                });
360                (authored, None)
361            };
362            match crate::workflow::submit(
363                &dir,
364                &submission,
365                &actor,
366                attempt.as_deref(),
367                bundle_root.as_deref(),
368                push,
369            ) {
370                Ok(outcome) => {
371                    if json {
372                        let mut payload = serde_json::to_value(&outcome)
373                            .expect("SubmitOutcome contains only serializable values");
374                        let fields = payload
375                            .as_object_mut()
376                            .expect("SubmitOutcome serializes as an object");
377                        fields.insert("ok".to_string(), serde_json::json!(true));
378                        fields.insert("command".to_string(), serde_json::json!("submit"));
379                        fields.insert(
380                            "request_id".to_string(),
381                            serde_json::json!(outcome.operation_id),
382                        );
383                        print_json(&payload);
384                    } else {
385                        crate::ui::header(
386                            "SUBMISSION",
387                            &outcome.submission_id,
388                            Some(outcome.route),
389                        );
390                        println!(
391                            "  {:<18} {}",
392                            vela_protocol::cli_style::dim("proposal"),
393                            safe_text::inline(&outcome.proposal_id)
394                        );
395                        println!(
396                            "  {:<18} {}",
397                            vela_protocol::cli_style::dim("registration"),
398                            safe_text::inline(&outcome.registration_record_id)
399                        );
400                        println!(
401                            "  {:<18} {}",
402                            vela_protocol::cli_style::dim("accepted delta"),
403                            outcome.accepted_event_delta
404                        );
405                    }
406                }
407                Err(e) => fail(&e),
408            }
409        }
410        Commands::Config { action } => match action {
411            ConfigAction::Get {
412                key,
413                frontier,
414                json,
415            } => {
416                crate::ui::set_mode("config", json);
417                crate::config::settings::cmd_config_get(&key, frontier.as_deref(), json)
418            }
419            ConfigAction::Set {
420                key,
421                value,
422                frontier,
423                json,
424            } => {
425                crate::ui::set_mode("config", json);
426                crate::config::settings::cmd_config_set(&key, &value, frontier.as_deref(), json)
427            }
428            ConfigAction::Unset {
429                key,
430                frontier,
431                json,
432            } => {
433                crate::ui::set_mode("config", json);
434                crate::config::settings::cmd_config_unset(&key, frontier.as_deref(), json)
435            }
436            ConfigAction::List { frontier, json } => {
437                crate::ui::set_mode("config", json);
438                crate::config::settings::cmd_config_list(frontier.as_deref(), json)
439            }
440        },
441    }
442}
443
444pub fn run_from_args() {
445    style::init();
446    let args = std::env::args().collect::<Vec<_>>();
447    match args.get(1).map(String::as_str) {
448        None => {
449            print_product_help();
450            return;
451        }
452        Some("-h" | "--help" | "help") => {
453            // v0.47: top-level help shows the daily flow. The full
454            // 30+ subcommand list lives behind `vela help advanced`.
455            if args.get(2).map(String::as_str) == Some("advanced") {
456                print_strict_help();
457            } else {
458                print_product_help();
459            }
460            return;
461        }
462        Some("-V" | "--version" | "version") => {
463            println!("vela {}", env!("CARGO_PKG_VERSION"));
464            return;
465        }
466        Some(_) => {}
467    }
468    let runtime = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
469    runtime.block_on(run_command());
470}