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