1use crate::serve;
2use vela_edge::frontier_health;
3use vela_edge::lint;
4use vela_edge::signals;
5use vela_edge::state_integrity;
6use vela_edge::validate;
7use vela_protocol::events;
8use vela_protocol::evidence_ci;
9use vela_protocol::frontier_repo;
10use vela_protocol::project;
11use vela_protocol::proposals;
12use vela_protocol::repo;
13use vela_protocol::sign;
14use vela_protocol::sources;
15use vela_protocol::state;
16
17use std::path::{Path, PathBuf};
18
19use clap::Parser;
20use colored::Colorize;
21
22use serde::Serialize;
23use serde_json::{Value, json};
24use sha2::{Digest, Sha256};
25use vela_protocol::cli_style as style;
26
27#[derive(Parser)]
28#[command(name = "vela", version)]
29#[command(about = "Portable frontier state for science")]
30struct Cli {
31 #[arg(long, global = true)]
33 quiet: bool,
34 #[command(subcommand)]
35 command: Commands,
36}
37
38pub(crate) use crate::cli_admin::*;
39pub(crate) use crate::cli_check::*;
40use crate::cli_commands::*;
41pub(crate) use crate::cli_engine::*;
42pub(crate) use crate::cli_finding::*;
43pub(crate) use crate::cli_frontier::*;
44pub(crate) use crate::cli_proof::*;
45pub(crate) use crate::cli_read::*;
46pub(crate) use crate::cli_write::*;
47
48mod checks;
49mod frontier_audit;
50pub(crate) mod help_text;
51mod identity;
52mod json_edit;
53mod lifecycle;
54mod migration;
55mod output;
56pub(crate) mod progress;
57pub(crate) mod prompt;
58pub(crate) mod records;
59pub(crate) mod safe_text;
60mod session;
61pub(crate) mod sign_session;
62mod surface;
63pub(crate) mod table;
64#[cfg(test)]
65mod tests;
66pub(crate) use checks::*;
67pub(crate) use frontier_audit::*;
68pub(crate) use identity::*;
69pub(crate) use json_edit::*;
70pub(crate) use lifecycle::*;
71pub(crate) use migration::*;
72pub(crate) use output::*;
73pub(crate) use records::*;
74pub(crate) use session::*;
75pub(crate) use surface::*;
76pub use checks::scan_for_sensitive_paths;
78pub use surface::is_science_subcommand;
79
80pub async fn run_command() {
81 if std::env::var_os("NO_COLOR").is_some() {
92 colored::control::set_override(false);
93 } else {
94 match crate::config::settings::resolve("ui.color", None)
95 .0
96 .as_str()
97 {
98 "never" => colored::control::set_override(false),
99 "always" => colored::control::set_override(true),
100 _ => {}
101 }
102 }
103
104 let cli = Cli::parse();
105 crate::ui::set_quiet(cli.quiet);
106 match cli.command {
107 Commands::Check {
108 source,
109 schema,
110 stats,
111 evidence,
112 conformance,
113 conformance_dir,
114 all,
115 schema_only,
116 strict,
117 fix,
118 json,
119 } => {
120 if evidence {
121 let frontier = source.unwrap_or_else(|| {
124 fail_return("check --evidence needs a frontier path (e.g. `vela check <frontier> --evidence`)")
125 });
126 cmd_evidence_ci(&frontier, json);
127 } else {
128 cmd_check(
129 source.as_deref(),
130 schema,
131 stats,
132 conformance,
133 &conformance_dir,
134 all,
135 schema_only,
136 strict,
137 fix,
138 json,
139 );
140 }
141 }
142 Commands::Doctor {
143 frontier,
144 port,
145 all,
146 json,
147 } => cmd_doctor(frontier.as_deref(), port, all, json).await,
148 Commands::Proof {
149 frontier,
150 out,
151 template,
152 record_proof_state,
153 json,
154 } => cmd_proof(&frontier, &out, &template, record_proof_state, json),
155 Commands::Serve {
156 frontier,
157 frontiers,
158 backend,
159 http,
160 setup,
161 check_tools,
162 adoption,
163 profile,
164 json,
165 } => {
166 if setup {
167 cmd_mcp_setup(frontier.as_deref(), frontiers.as_deref());
168 } else if check_tools {
169 let source =
170 serve::ProjectSource::from_args(frontier.as_deref(), frontiers.as_deref());
171 match serve::check_tools(source, adoption) {
172 Ok(report) => {
173 if json {
174 print_json(&report);
175 } else {
176 print_tool_check_report(&report);
177 }
178 }
179 Err(e) => fail(&format!("Tool check failed: {e}")),
180 }
181 } else {
182 let mcp_profile = vela_edge::tool_registry::McpProfile::parse(&profile)
183 .unwrap_or_else(|e| fail_return(&e));
184 let source =
185 serve::ProjectSource::from_args(frontier.as_deref(), frontiers.as_deref());
186 if let Some(port) = http {
187 serve::run_http(source, backend.as_deref(), port, mcp_profile).await;
188 } else {
189 serve::run(source, backend.as_deref(), mcp_profile).await;
190 }
191 }
192 }
193 Commands::Status { frontier, json } => {
194 cmd_status_compact(&crate::ui::resolve_frontier(frontier), json)
195 }
196 Commands::Log {
197 frontier,
198 finding_id,
199 limit,
200 kind,
201 as_of,
202 json,
203 } => {
204 let (frontier, finding_id) =
205 crate::ui::resolve_frontier_with_id(frontier, finding_id, &["vf_"]);
206 if let Some(vf) = finding_id {
207 let payload = state::history_as_of(&frontier, &vf, as_of.as_deref())
208 .unwrap_or_else(|e| fail_return(&e));
209 if json {
210 print_json(&payload);
211 } else {
212 print_history(&payload);
213 }
214 } else {
215 cmd_log(&frontier, limit, kind.as_deref(), json);
216 }
217 }
218 Commands::Gate { action } => cmd_gate(action),
219 Commands::Verify { action } => cmd_verify_evidence(action),
220 Commands::Agents { action } => crate::cli_agents::cmd_agents(action),
221 Commands::Completions { shell } => {
222 use clap::CommandFactory;
223 let mut cmd = Cli::command();
224 let name = cmd.get_name().to_string();
225 let shell_kind: clap_complete::Shell = match shell.as_str() {
226 "bash" => clap_complete::Shell::Bash,
227 "zsh" => clap_complete::Shell::Zsh,
228 "fish" => clap_complete::Shell::Fish,
229 other => fail_return(&format!(
230 "unsupported shell '{other}'. Valid: bash, zsh, fish"
231 )),
232 };
233 clap_complete::generate(shell_kind, &mut cmd, name, &mut std::io::stdout());
234 }
235
236 Commands::Reproduce {
237 path,
238 proposal,
239 json,
240 } => cmd_reproduce(&path, proposal.as_deref(), json),
241 Commands::Ci { action } => match action {
242 crate::server::cli_commands::CiAction::Verdict {
243 frontier,
244 base,
245 json,
246 } => {
247 crate::config::cli_policy::cmd_ci_verdict(&frontier, &base, json);
248 }
249 },
250 Commands::Id { action } => cmd_id(action),
251 Commands::Actor { action } => cmd_actor(action),
252 Commands::Frontier { action } => cmd_frontier(action),
253 Commands::Init {
254 path,
255 name,
256 scope,
257 json,
258 } => cmd_init(&path, name.as_deref(), scope.as_deref(), json),
259 Commands::Review { action } => cmd_review(action),
260 Commands::Migrate {
261 frontier,
262 target_version,
263 check: _,
264 apply,
265 json,
266 } => cmd_migrate(&frontier, &target_version, apply, json),
267 Commands::Finding {
268 command:
269 FindingCommands::Show {
270 frontier,
271 finding_id,
272 view,
273 json,
274 },
275 } => cmd_finding_show(&frontier, &finding_id, &view, json),
276
277 Commands::Artifact { command } => match command {
278 ArtifactCommands::Retract {
279 frontier,
280 artifact_id,
281 reason,
282 actor,
283 json,
284 } => {
285 crate::ui::set_mode("artifact.retract", json);
286 cmd_artifact_retract(frontier, artifact_id, reason, actor, json)
287 }
288 },
289
290 Commands::Sign {
291 target,
292 frontier,
293 yes,
294 confirm_root,
295 confirm_at,
296 reason,
297 reset,
298 preview,
299 cursor,
300 limit,
301 sk,
302 key,
303 json,
304 } => {
305 crate::ui::set_mode("sign", json);
306 if sk {
307 crate::ui::fail_with(
308 crate::ui::ErrorKind::Usage,
309 "--sk (hardware touch-to-sign) is designed but not yet wired: the recommended path is a PKCS#11/OpenPGP Ed25519 token (raw Ed25519, zero verifier change); see docs/HARDWARE_SIGNING_PROPOSAL.md",
310 Some(
311 "run the ceremony with your file key; pin the binary with `vela id pin-binary`",
312 ),
313 );
314 }
315 if preview {
316 sign_session::cmd_sign_preview(frontier, cursor, limit, json);
317 } else if let Some(target) = target {
318 let as_path = std::path::Path::new(&target);
319 if as_path.exists() {
320 if confirm_root.is_some() || confirm_at.is_some() {
321 crate::ui::fail_with(
322 crate::ui::ErrorKind::Usage,
323 "--confirm-root applies only to proposal decisions, not detached file signatures",
324 None,
325 );
326 }
327 sign_session::cmd_sign_detached(as_path, key.as_deref(), json);
328 } else {
329 sign_session::cmd_sign_one(
330 frontier,
331 &target,
332 reason,
333 key,
334 yes,
335 confirm_root.as_deref(),
336 confirm_at.as_deref(),
337 json,
338 );
339 }
340 } else {
341 sign_session::cmd_sign_session(frontier, key, json, reset);
342 }
343 }
344 Commands::Next {
345 frontier,
346 limit,
347 json,
348 } => {
349 crate::ui::set_mode("next", json);
350 let dir = crate::ui::resolve_frontier(frontier);
351 let project =
352 vela_protocol::repo::load_from_path(&dir).unwrap_or_else(|e| fail_return(&e));
353 let observed_at = chrono::Utc::now().to_rfc3339();
354 let projection = vela_edge::frontier_next::try_frontier_next_projection(
355 &project,
356 Some(&dir),
357 &observed_at,
358 limit,
359 )
360 .unwrap_or_else(|error| fail_return(&error));
361 let targets = &projection.targets;
362 if json {
363 let offers = targets
364 .iter()
365 .enumerate()
366 .map(|(index, target)| {
367 let packet = target.task.as_ref().and_then(|task| task.get("packet_ref"));
368 let objective = target
369 .task
370 .as_ref()
371 .and_then(|task| task.get("objective"))
372 .and_then(serde_json::Value::as_str)
373 .unwrap_or(&target.why);
374 serde_json::json!({
375 "rank": index + 1,
376 "lane": target.lane,
377 "target_id": target.id,
378 "title": target.title,
379 "objective": objective,
380 "packet": packet,
381 "verifier_profile": target.task.as_ref()
382 .and_then(|task| task.get("verifier_profile"))
383 .or_else(|| packet.and_then(|packet| packet.get("schema"))),
384 "lease_state": "available",
385 "next_command": target.next_command,
386 })
387 })
388 .collect::<Vec<_>>();
389 print_json(&serde_json::json!({
390 "ok": true,
391 "command": "next",
392 "schema": "vela.offer.v1",
393 "frontier_id": project.frontier_id(),
394 "event_log_root": format!("sha256:{}", vela_protocol::events::event_log_hash(&project.events)),
395 "availability": {
396 "configured_open": projection.producer_work.configured_open,
397 "available": projection.producer_work.available,
398 "leased": projection.producer_work.leased,
399 },
400 "leased_targets": projection.producer_work.leased_targets,
401 "targets": offers,
402 }));
403 } else {
404 let tg = if targets.len() == 1 {
405 "target"
406 } else {
407 "targets"
408 };
409 crate::ui::header("NEXT", ".", Some(&format!("{} {tg}", targets.len())));
410 for t in targets {
411 let chip = match t.lane.as_str() {
412 "attack" => vela_protocol::cli_style::brass("attack"),
413 "verify" => vela_protocol::cli_style::moss("verify"),
414 other => vela_protocol::cli_style::dim(&safe_text::inline(other)),
415 };
416 println!(" {chip} {}", safe_text::inline(&t.title));
417 println!(
418 " {}",
419 vela_protocol::cli_style::dim(&safe_text::inline(&format!(
420 "{} · {}",
421 t.id, t.why
422 )))
423 );
424 println!(
425 " {}",
426 vela_protocol::cli_style::dim(&safe_text::inline(&t.next_command))
427 );
428 }
429 if targets.is_empty() {
430 if projection.producer_work.leased > 0 {
431 println!(
432 " · {} configured producer target(s) are currently leased",
433 projection.producer_work.leased
434 );
435 for target in &projection.producer_work.leased_targets {
436 let expiry = target.expires_at.as_deref().unwrap_or("unknown expiry");
437 println!(
438 " {} · {} · expires {}",
439 safe_text::inline(&target.target_id),
440 safe_text::inline(&target.actor),
441 safe_text::inline(expiry),
442 );
443 }
444 } else {
445 println!(" · no producer target is currently available");
446 }
447 }
448 }
449 }
450 Commands::Work {
451 target,
452 frontier,
453 ttl,
454 drop: drop_it,
455 reason,
456 r#as,
457 json,
458 } => {
459 crate::ui::set_mode("work", json);
460 let dir = crate::ui::resolve_frontier(frontier);
461 let Some(target) = target else {
462 let root = dir.join(".vela/work");
463 let mut sessions = std::fs::read_dir(&root)
464 .into_iter()
465 .flatten()
466 .filter_map(Result::ok)
467 .filter_map(|entry| {
468 entry
469 .path()
470 .join("session.json")
471 .is_file()
472 .then_some(entry.path())
473 })
474 .collect::<Vec<_>>();
475 sessions.sort();
476 if json {
477 print_json(&serde_json::json!({
478 "ok": true,
479 "command": "work",
480 "sessions": sessions.iter().map(|path| path.display().to_string()).collect::<Vec<_>>(),
481 }));
482 } else {
483 println!(" {} open session(s) under .vela/work/", sessions.len());
484 for session in sessions {
485 println!(" · {}", safe_text::inline(&session.display().to_string()));
486 }
487 }
488 return;
489 };
490 let actor = crate::cli_identity::resolve_actor(r#as.as_deref());
491 if drop_it {
492 let reason = reason
493 .as_deref()
494 .unwrap_or("producer released the work session without landing a receipt");
495 let result = crate::workflow::release_session(&dir, &target, &actor, reason)
496 .unwrap_or_else(|error| fail_return(&error));
497 if json {
498 let mut result = result;
499 result["command"] = serde_json::json!("work.drop");
500 print_json(&result);
501 } else {
502 crate::ui::header("WORK", &target, Some("lease released"));
503 println!(" reason {}", safe_text::inline(reason));
504 render_work_publication(&result["release"]);
505 println!(" another agent may claim this target immediately");
506 }
507 return;
508 }
509 if reason.is_some() {
510 crate::ui::fail_with(
511 crate::ui::ErrorKind::Usage,
512 "--reason is valid only with work --drop",
513 Some("remove --reason or add --drop"),
514 );
515 }
516 let ttl = ttl.unwrap_or_else(|| {
517 crate::config::settings::resolve("work.lease_ttl_seconds", Some(&dir))
518 .0
519 .parse()
520 .unwrap_or(86400)
521 });
522 match crate::workflow::open_session(&dir, &target, &actor, ttl) {
523 Ok(opened) => {
524 if json {
525 let session = &opened["session"];
526 let briefing = &opened["briefing"];
527 let task = briefing.get("task");
528 let packet = task.and_then(|task| task.get("packet_ref"));
529 print_json(&serde_json::json!({
530 "ok": true,
531 "command": "work",
532 "schema": "vela.work.v1",
533 "idempotent": opened.get("idempotent").and_then(serde_json::Value::as_bool).unwrap_or(false),
534 "frontier_id": session.get("frontier_id"),
535 "target_id": target,
536 "session": {
537 "id": session.get("session_id"),
538 "path": opened.get("session_path"),
539 "actor": session.get("actor"),
540 "expires_at": session.pointer("/lease/expires_at"),
541 },
542 "starting_roots": {
543 "event_log": session.get("base_event_log_root"),
544 "nonlease_event_log": session.get("base_nonlease_event_log_root"),
545 "task_contract": session.get("task_contract_root"),
546 "git_commit": session.get("source_git_commit_oid"),
547 },
548 "task": {
549 "objective": session.pointer("/task_contract/objective"),
550 "completion_condition": session.pointer("/task_contract/completion_condition"),
551 "required_outputs": session.pointer("/task_contract/required_outputs"),
552 "required_checks": session.pointer("/task_contract/required_checks"),
553 "authority_ceiling": session.pointer("/task_contract/authority_ceiling"),
554 },
555 "packet": packet,
556 "verifier_profile": task.and_then(|task| task.get("verifier_profile"))
557 .or_else(|| packet.and_then(|packet| packet.get("schema"))),
558 "next_command": format!("vela land --work {target} --claim <scoped-result> --type <type> --replayability <class> --artifact <path>:<kind> --caveat <limit> --as <agent> --json"),
559 }));
560 } else {
561 crate::ui::header("WORK", &target, Some("lease claimed, briefing loaded"));
562 let briefing = opened.get("briefing").unwrap_or(&opened);
563 let b = briefing.get("briefing").unwrap_or(briefing);
564 if let Some(s) = b.get("statement").and_then(|v| v.as_str()) {
565 println!(" {}", safe_text::multiline(s));
566 }
567 for (label, key) in [
568 ("gate", "gate"),
569 ("value to beat", "value_to_beat"),
570 ("attempts", "attempt_count"),
571 ] {
572 if let Some(v) = b.get(key) {
573 let vs = v
574 .as_str()
575 .map(str::to_string)
576 .unwrap_or_else(|| v.to_string());
577 if vs != "null" {
578 println!(
579 " {:<14} {}",
580 vela_protocol::cli_style::dim(label),
581 safe_text::inline(&vs)
582 );
583 }
584 }
585 }
586 println!(
587 " {:<14} {}",
588 vela_protocol::cli_style::dim("session"),
589 safe_text::inline(
590 opened
591 .get("session_path")
592 .and_then(|value| value.as_str())
593 .unwrap_or(".vela/work/<slug>--<target-sha256>/session.json")
594 )
595 );
596 render_work_publication(&opened["claim"]);
597 println!(
598 " {:<14} vela land --work {} --claim ...",
599 vela_protocol::cli_style::dim("when done"),
600 safe_text::inline(&target),
601 );
602 }
603 }
604 Err(e) => fail(&e),
605 }
606 }
607 Commands::Land {
608 receipt,
609 frontier,
610 claim,
611 claim_type,
612 replayability,
613 artifact,
614 caveat,
615 predicted_observable,
616 not_applicable,
617 performed_test,
618 result,
619 evidence,
620 counterevidence,
621 packet_root,
622 profile_root,
623 verifier_capsule_root,
624 result_contract_root,
625 work,
626 r#as,
627 push,
628 json,
629 } => {
630 crate::ui::set_mode("land", json);
631 let dir = crate::ui::resolve_frontier(frontier);
632 let actor = crate::cli_identity::resolve_actor(r#as.as_deref());
633 let preflight_identity =
634 vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
635 "schema": "vela.land-preflight.internal.v1",
636 "frontier": dir.display().to_string(),
637 "actor": actor,
638 "receipt": receipt.as_ref().map(|path| path.display().to_string()),
639 "claim": claim,
640 "claim_type": claim_type,
641 "replayability": replayability,
642 "artifacts": artifact,
643 "caveats": caveat,
644 "predicted_observable": predicted_observable,
645 "not_applicable": not_applicable,
646 "performed_test": performed_test,
647 "result": result,
648 "evidence": evidence,
649 "counterevidence": counterevidence,
650 "packet_root": packet_root,
651 "profile_root": profile_root,
652 "verifier_capsule_root": verifier_capsule_root,
653 "result_contract_root": result_contract_root,
654 "work": work,
655 "push": push,
656 }))
657 .unwrap_or_default();
658 let preflight_id =
659 crate::operation_journal::operation_id("land-preflight", &preflight_identity);
660 let fail_preflight = |kind, message: String| -> ! {
661 crate::ui::fail_unchanged(kind, &message, &preflight_id, "vela land --help")
662 };
663 let receipt = if let Some(path) = receipt {
664 if work.is_some() {
665 fail_preflight(
666 crate::ui::ErrorKind::Usage,
667 "--work selects the private flag-authoring path and cannot be combined with a foreign Receipt v1 file".to_string(),
668 );
669 }
670 let raw = crate::bounded_file::read_bounded_file(
671 &path,
672 crate::bounded_file::RECEIPT_MAX_BYTES,
673 "foreign Receipt v1",
674 )
675 .unwrap_or_else(|error| {
676 let kind = if error.code == "missing" {
677 crate::ui::ErrorKind::NotFound
678 } else {
679 crate::ui::ErrorKind::Domain
680 };
681 fail_preflight(kind, error.to_string())
682 });
683 vela_protocol::receipt_v1::ReceiptV1::parse(&raw).unwrap_or_else(|error| {
684 fail_preflight(crate::ui::ErrorKind::Domain, error.to_string())
685 })
686 } else {
687 let Some(claim) = claim else {
688 crate::ui::fail_unchanged(
689 crate::ui::ErrorKind::Usage,
690 "land needs a receipt file or --claim",
691 &preflight_id,
692 "vela land --help",
693 );
694 };
695 let claim_type = claim_type.unwrap_or_else(|| {
696 fail_preflight(
697 crate::ui::ErrorKind::Usage,
698 "flag authoring needs --type (computational, theoretical, empirical, negative, or contradiction)".to_string(),
699 )
700 });
701 let replayability = replayability.unwrap_or_else(|| {
702 fail_preflight(
703 crate::ui::ErrorKind::Usage,
704 "flag authoring needs --replayability (exact, bounded, approximate, unavailable, or unknown)".to_string(),
705 )
706 });
707 let execution_binding = match (
708 packet_root,
709 profile_root,
710 verifier_capsule_root,
711 result_contract_root,
712 ) {
713 (
714 Some(packet_root),
715 Some(profile_root),
716 Some(verifier_capsule_root),
717 Some(result_contract_root),
718 ) => {
719 let binding = vela_protocol::receipt_v1::ExecutionBindingV1 {
720 schema: vela_protocol::receipt_v1::EXECUTION_BINDING_SCHEMA.to_string(),
721 packet_root,
722 profile_root,
723 verifier_capsule_root,
724 result_contract_root,
725 };
726 binding.validate().unwrap_or_else(|error| {
727 fail_preflight(
728 crate::ui::ErrorKind::Usage,
729 format!("invalid exact execution binding: {error}"),
730 )
731 });
732 Some(binding)
733 }
734 (None, None, None, None) => None,
735 _ => fail_preflight(
736 crate::ui::ErrorKind::Usage,
737 "exact execution binding requires all four full roots".to_string(),
738 ),
739 };
740 crate::workflow::author_receipt(
741 &dir,
742 &actor,
743 work.as_deref(),
744 claim,
745 claim_type,
746 replayability,
747 &artifact,
748 caveat,
749 predicted_observable,
750 not_applicable,
751 performed_test,
752 result,
753 evidence,
754 counterevidence,
755 execution_binding,
756 )
757 .unwrap_or_else(|error| {
758 fail_preflight(
759 crate::ui::ErrorKind::Domain,
760 format!("receipt build: {error}"),
761 )
762 })
763 };
764 match crate::workflow::land(&dir, &receipt, &actor, push) {
765 Ok(outcome) => {
766 let wire = outcome.wire();
767 if json {
768 let mut payload = serde_json::to_value(&wire)
769 .expect("LandOutcomeWire contains only serializable values");
770 let fields = payload
771 .as_object_mut()
772 .expect("LandOutcomeWire serializes as an object");
773 fields.insert("ok".to_string(), serde_json::json!(true));
774 fields.insert("command".to_string(), serde_json::json!("land"));
775 fields.insert(
776 "request_id".to_string(),
777 serde_json::json!(wire.operation_id),
778 );
779 print_json(&payload);
780 } else {
781 render_land_outcome(
782 wire.proposal_id,
783 wire.route,
784 &wire.detail,
785 wire.operation_id,
786 wire.publication,
787 );
788 }
789 }
790 Err(e) => fail(&e),
791 }
792 }
793 Commands::Config { action } => match action {
794 ConfigAction::Get {
795 key,
796 frontier,
797 json,
798 } => {
799 crate::ui::set_mode("config", json);
800 crate::config::settings::cmd_config_get(&key, frontier.as_deref(), json)
801 }
802 ConfigAction::Set {
803 key,
804 value,
805 frontier,
806 json,
807 } => {
808 crate::ui::set_mode("config", json);
809 crate::config::settings::cmd_config_set(&key, &value, frontier.as_deref(), json)
810 }
811 ConfigAction::Unset {
812 key,
813 frontier,
814 json,
815 } => {
816 crate::ui::set_mode("config", json);
817 crate::config::settings::cmd_config_unset(&key, frontier.as_deref(), json)
818 }
819 ConfigAction::List { frontier, json } => {
820 crate::ui::set_mode("config", json);
821 crate::config::settings::cmd_config_list(frontier.as_deref(), json)
822 }
823 },
824 Commands::Policy { action } => match action {
825 PolicyAction::Show { frontier, json } => {
826 crate::ui::set_mode("policy", json);
827 crate::config::cli_policy::cmd_policy_show(
828 &crate::ui::resolve_frontier(frontier),
829 json,
830 )
831 }
832 PolicyAction::Suggest { frontier, json } => {
833 crate::ui::set_mode("policy", json);
834 crate::config::cli_policy::cmd_policy_suggest(
835 &crate::ui::resolve_frontier(frontier),
836 json,
837 )
838 }
839 PolicyAction::Draft {
840 operands,
841 from_suggest,
842 replace,
843 from_proposal,
844 packet_root,
845 profile_root,
846 verifier_capsule_root,
847 result_contract_root,
848 producer_credential_root,
849 json,
850 } => {
851 crate::ui::set_mode("policy", json);
852 if from_suggest {
853 if operands.len() > 1 {
854 crate::ui::fail_with(
855 crate::ui::ErrorKind::Usage,
856 "policy draft --from-suggest accepts only an optional frontier",
857 Some("vela policy draft --from-suggest <frontier>"),
858 );
859 }
860 let frontier = crate::ui::resolve_frontier(operands.first().map(PathBuf::from));
861 crate::config::cli_policy::cmd_policy_draft_from_suggest(
862 &frontier, replace, json,
863 )
864 } else {
865 let template = operands.first().cloned().unwrap_or_else(|| {
866 fail_return("policy draft needs a template or --from-suggest")
867 });
868 let frontier = crate::ui::resolve_frontier(operands.get(1).map(PathBuf::from));
869 let exact_binding = if let Some(proposal_id) = from_proposal {
870 if template != "search-witness" {
871 crate::ui::fail_with(
872 crate::ui::ErrorKind::Usage,
873 "--from-proposal is supported only by the search-witness template",
874 Some(
875 "use `vela policy draft search-witness <frontier> --from-proposal <vpr_id>`",
876 ),
877 );
878 }
879 Some(
880 crate::config::cli_policy::exact_permit_binding_from_proposal(
881 &frontier,
882 &proposal_id,
883 )
884 .unwrap_or_else(|error| error.fail()),
885 )
886 } else {
887 match (
888 packet_root,
889 profile_root,
890 verifier_capsule_root,
891 result_contract_root,
892 ) {
893 (Some(packet), Some(profile), Some(capsule), Some(result)) => {
894 Some(crate::config::cli_policy::ExactPermitBinding {
895 packet_root: packet,
896 profile_root: profile,
897 verifier_capsule_root: capsule,
898 result_contract_root: result,
899 producer_credential_root,
900 })
901 }
902 (None, None, None, None) => {
903 if producer_credential_root.is_some() {
904 crate::ui::fail_with(
905 crate::ui::ErrorKind::Usage,
906 "producer credential binding requires all four exact execution roots",
907 Some(
908 "provide --packet-root, --profile-root, --verifier-capsule-root, and --result-contract-root",
909 ),
910 );
911 }
912 None
913 }
914 _ => crate::ui::fail_with(
915 crate::ui::ErrorKind::Usage,
916 "exact policy binding requires all four full roots",
917 Some(
918 "provide --packet-root, --profile-root, --verifier-capsule-root, and --result-contract-root",
919 ),
920 ),
921 }
922 };
923 crate::config::cli_policy::cmd_policy_draft(
924 &frontier,
925 &template,
926 exact_binding.as_ref(),
927 replace,
928 json,
929 )
930 }
931 }
932 PolicyAction::Test { frontier, json } => {
933 crate::ui::set_mode("policy", json);
934 crate::config::cli_policy::cmd_policy_test(
935 &crate::ui::resolve_frontier(frontier),
936 json,
937 )
938 }
939 PolicyAction::EvaluateProposal { operands, json } => {
940 crate::ui::set_mode("policy", json);
941 let proposal_id = operands
942 .iter()
943 .find(|value| value.starts_with("vpr_"))
944 .cloned()
945 .unwrap_or_else(|| {
946 fail_return("policy evaluate-proposal needs one vpr_ proposal id")
947 });
948 let frontier = operands
949 .iter()
950 .find(|value| !value.starts_with("vpr_"))
951 .map(PathBuf::from);
952 crate::config::cli_policy::cmd_policy_evaluate_proposal(
953 &crate::ui::resolve_frontier(frontier),
954 &proposal_id,
955 json,
956 )
957 }
958 PolicyAction::Decide {
959 frontier,
960 activate,
961 rotate,
962 revoke,
963 reason,
964 confirm_root,
965 confirm_at,
966 json,
967 } => {
968 crate::ui::set_mode("policy", json);
969 let action = match (activate, rotate, revoke) {
970 (Some(policy_id), None, false) => {
971 (vela_signer::PolicyDecisionAction::Activate, policy_id)
972 }
973 (None, Some(policy_id), false) => {
974 (vela_signer::PolicyDecisionAction::Rotate, policy_id)
975 }
976 (None, None, true) => {
977 (vela_signer::PolicyDecisionAction::Revoke, String::new())
978 }
979 _ => crate::ui::fail_with(
980 crate::ui::ErrorKind::Usage,
981 "policy decide requires exactly one of --activate, --rotate, or --revoke",
982 Some("vela policy decide <frontier> --activate <vap_id> --reason <why>"),
983 ),
984 };
985 crate::config::cli_policy::cmd_policy_decide(
986 &crate::ui::resolve_frontier(frontier),
987 action.0,
988 &action.1,
989 &reason,
990 confirm_root.as_deref(),
991 confirm_at.as_deref(),
992 json,
993 )
994 }
995 PolicyAction::Sign {
996 frontier,
997 key,
998 yes,
999 json,
1000 } => {
1001 crate::ui::set_mode("policy", json);
1002 if json && !yes {
1003 crate::ui::fail_with(
1004 crate::ui::ErrorKind::Usage,
1005 "policy sign --json requires --yes (JSON mode is non-interactive)",
1006 Some("vela policy sign <frontier> --yes --json"),
1007 );
1008 }
1009 crate::config::cli_policy::cmd_policy_sign(
1010 &crate::ui::resolve_frontier(frontier),
1011 key.as_deref(),
1012 yes,
1013 json,
1014 )
1015 }
1016 PolicyAction::Revoke {
1017 frontier,
1018 key,
1019 reason,
1020 yes,
1021 json,
1022 } => {
1023 crate::ui::set_mode("policy", json);
1024 if json && !yes {
1025 crate::ui::fail_with(
1026 crate::ui::ErrorKind::Usage,
1027 "policy revoke --json requires --yes (JSON mode is non-interactive)",
1028 Some("vela policy revoke <frontier> --reason <why> --yes --json"),
1029 );
1030 }
1031 crate::config::cli_policy::cmd_policy_revoke(
1032 &crate::ui::resolve_frontier(frontier),
1033 key.as_deref(),
1034 &reason,
1035 yes,
1036 json,
1037 )
1038 }
1039 PolicyAction::RetireLegacy {
1040 frontier,
1041 reason,
1042 actor,
1043 json,
1044 } => {
1045 crate::ui::set_mode("policy", json);
1046 crate::config::policy_legacy_retirement::cmd_policy_retire_legacy(
1047 &crate::ui::resolve_frontier(frontier),
1048 &reason,
1049 &actor,
1050 json,
1051 )
1052 }
1053 PolicyAction::Log { frontier, json } => {
1054 crate::ui::set_mode("policy", json);
1055 crate::config::cli_policy::cmd_policy_log(
1056 &crate::ui::resolve_frontier(frontier),
1057 json,
1058 )
1059 }
1060 },
1061 }
1062}
1063
1064fn render_work_publication(operation: &serde_json::Value) {
1065 let Some(publication) = operation.get("publication") else {
1066 return;
1067 };
1068 let state = publication
1069 .get("state")
1070 .and_then(serde_json::Value::as_str)
1071 .unwrap_or("unknown");
1072 let detail = publication
1073 .get("commit")
1074 .and_then(serde_json::Value::as_str)
1075 .map(|commit| format!("{state} {commit}"))
1076 .or_else(|| {
1077 publication
1078 .get("reason")
1079 .and_then(serde_json::Value::as_str)
1080 .map(|reason| format!("{state}: {reason}"))
1081 })
1082 .unwrap_or_else(|| state.to_string());
1083 println!(
1084 " {:<14} {}",
1085 vela_protocol::cli_style::dim("git"),
1086 safe_text::inline(&detail)
1087 );
1088 if !matches!(state, "unchanged" | "committed_local" | "pushed") {
1089 println!(
1090 " {:<14} {}",
1091 vela_protocol::cli_style::dim("recover"),
1092 safe_text::inline(
1093 publication
1094 .get("recovery_command")
1095 .and_then(serde_json::Value::as_str)
1096 .unwrap_or("git status --short")
1097 )
1098 );
1099 }
1100}
1101
1102fn render_land_outcome(
1103 proposal_id: &str,
1104 route: &str,
1105 detail: &str,
1106 operation_id: &str,
1107 publication: &crate::config::git_publish::PublicationOutcome,
1108) {
1109 use crate::config::git_publish::PublicationState;
1110
1111 let (state, retained, changed_git, unchanged, remote, fallback_next) = match &publication.state
1112 {
1113 PublicationState::Unchanged { commit } => (
1114 "unchanged".to_string(),
1115 format!("existing local commit {commit} already contains every exact postimage"),
1116 "no Git ref or caller index entry moved".to_string(),
1117 "caller index/worktree entries".to_string(),
1118 "unverified; the exact local target commit is proven".to_string(),
1119 "git push".to_string(),
1120 ),
1121 PublicationState::Uncommitted { candidate, reason } => (
1122 format!("uncommitted: {reason}"),
1123 candidate
1124 .as_ref()
1125 .map(|oid| format!("candidate {oid} is not on the target ref"))
1126 .unwrap_or_else(|| "no publication commit on the target ref".to_string()),
1127 "no Git ref moved".to_string(),
1128 "unrelated index/worktree entries".to_string(),
1129 "not contacted by this publication attempt".to_string(),
1130 "git status --short".to_string(),
1131 ),
1132 PublicationState::Stale {
1133 candidate,
1134 expected,
1135 actual,
1136 } => (
1137 format!("stale: candidate {candidate} planned from {expected}; target is now {actual}"),
1138 format!("candidate {candidate} was not installed on the target ref"),
1139 "the competing Git ref update won; Vela did not merge or overwrite it".to_string(),
1140 "caller index/worktree entries".to_string(),
1141 "not contacted by this publication attempt".to_string(),
1142 "git status --short".to_string(),
1143 ),
1144 PublicationState::CommittedLocal { commit } => (
1145 "committed_local".to_string(),
1146 format!("local commit {commit}"),
1147 format!("local Git ref now retains commit {commit}"),
1148 "unrelated index/worktree entries".to_string(),
1149 "unverified; only the local commit is proven".to_string(),
1150 "git push".to_string(),
1151 ),
1152 PublicationState::Pushed { commit, remote } => (
1153 format!("pushed to {remote}"),
1154 format!("commit {commit}"),
1155 format!("commit {commit} is verified on {remote}"),
1156 "unrelated index/worktree entries".to_string(),
1157 format!("verified on {remote}"),
1158 "vela status --json".to_string(),
1159 ),
1160 PublicationState::Unknown { reason } => (
1161 format!("unknown: {reason}"),
1162 "publication state is not proven; inspect the recovery result".to_string(),
1163 "publication could not be proven".to_string(),
1164 "unrelated index/worktree entries".to_string(),
1165 "unverified".to_string(),
1166 "git status --short".to_string(),
1167 ),
1168 };
1169 let next = publication
1170 .recovery_command
1171 .as_deref()
1172 .unwrap_or(&fallback_next);
1173
1174 crate::ui::header("LAND", proposal_id, Some(route));
1175 println!(
1176 " {:<16} proposal {} routed {} ({})",
1177 style::dim("changed"),
1178 safe_text::inline(proposal_id),
1179 safe_text::inline(route),
1180 safe_text::inline(detail)
1181 );
1182 println!(
1183 " {:<16} {}",
1184 style::dim("git"),
1185 safe_text::inline(&changed_git)
1186 );
1187 println!(
1188 " {:<16} {}",
1189 style::dim("unchanged"),
1190 safe_text::inline(&unchanged)
1191 );
1192 println!(
1193 " {:<16} {}",
1194 style::dim("remote"),
1195 safe_text::inline(&remote)
1196 );
1197 println!(
1198 " {:<16} {}",
1199 style::dim("publication"),
1200 safe_text::inline(&state)
1201 );
1202 println!(
1203 " {:<16} {}",
1204 style::dim("request"),
1205 safe_text::inline(operation_id)
1206 );
1207 println!(
1208 " {:<16} {}",
1209 style::dim("retained"),
1210 safe_text::inline(&retained)
1211 );
1212 println!(" {:<16} {}", style::dim("next"), safe_text::inline(next));
1213}
1214
1215pub fn run_from_args() {
1227 style::init();
1228 let args = std::env::args().collect::<Vec<_>>();
1229 match args.get(1).map(String::as_str) {
1230 None => {
1234 run_session();
1235 return;
1236 }
1237 Some("-h" | "--help" | "help") => {
1238 if args.get(2).map(String::as_str) == Some("advanced") {
1241 print_strict_help();
1242 } else {
1243 print_session_help();
1244 }
1245 return;
1246 }
1247 Some("-V" | "--version" | "version") => {
1248 println!("vela {}", env!("CARGO_PKG_VERSION"));
1249 return;
1250 }
1251 Some("proof") if args.get(2).map(String::as_str) == Some("verify") => {
1252 let json = args.iter().any(|arg| arg == "--json");
1253 let frontier = args
1254 .iter()
1255 .skip(3)
1256 .find(|arg| !arg.starts_with('-'))
1257 .map(PathBuf::from)
1258 .inspect(|p| {
1259 if p.join("manifest.json").exists() && !p.join(".vela").is_dir() {
1263 crate::cli_read::cmd_verify(p, json);
1264 std::process::exit(0);
1265 }
1266 })
1267 .unwrap_or_else(|| {
1268 eprintln!(
1269 "{} proof verify requires a frontier repo",
1270 style::err_prefix()
1271 );
1272 std::process::exit(2);
1273 });
1274 cmd_proof_verify(&frontier, json);
1275 return;
1276 }
1277 Some("proof") if args.get(2).map(String::as_str) == Some("explain") => {
1278 let frontier = args
1279 .iter()
1280 .skip(3)
1281 .find(|arg| !arg.starts_with('-'))
1282 .map(PathBuf::from)
1283 .unwrap_or_else(|| {
1284 eprintln!(
1285 "{} proof explain requires a frontier repo",
1286 style::err_prefix()
1287 );
1288 std::process::exit(2);
1289 });
1290 cmd_proof_explain(&frontier);
1291 return;
1292 }
1293 Some("state") => {
1295 eprintln!("{} `vela state` retired in 0.900", style::err_prefix());
1296 eprintln!("use `vela finding show <frontier> <vf_id> --view record|standing|evidence`");
1297 std::process::exit(2);
1298 }
1299 Some("atlas") => {
1300 eprintln!(
1301 "{} `vela atlas` retired from the core binary in 0.900",
1302 style::err_prefix()
1303 );
1304 eprintln!("use the campaign reader or a Canopus verifier profile");
1305 std::process::exit(2);
1306 }
1307 Some(cmd) if !is_science_subcommand(cmd) => {
1308 let replacement = match cmd {
1309 "proposals" => Some(
1310 "vela review list <frontier> --json, then vela review show <frontier> <vpr_id> --json",
1311 ),
1312 "diff" => Some(
1313 "vela review preview <frontier> <vpr_id>, or vela frontier diff <left> <right>",
1314 ),
1315 "credit" => Some("vela finding show <frontier> <vf_id> --view attribution"),
1316 "publication" => Some("vela frontier recover-publication"),
1317 "hub" => Some("the separate vela-hub binary"),
1318 "foundry" | "reproduce-external" => {
1319 Some("a Canopus verifier profile or parent campaign script")
1320 }
1321 _ => None,
1322 };
1323 if let Some(replacement) = replacement {
1324 eprintln!("{} `vela {cmd}` retired in 0.900", style::err_prefix());
1325 eprintln!("use `{replacement}`");
1326 } else {
1327 eprintln!("{} unknown command: {cmd}", style::err_prefix());
1328 eprintln!("run `vela --help` for the product surface.");
1329 }
1330 std::process::exit(2);
1331 }
1332 Some(_) => {}
1333 }
1334 let runtime = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
1335 runtime.block_on(run_command());
1336}