Skip to main content

vela_cli/cli/
mod.rs

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    /// Suppress hint/advice lines (VELA_ADVICE=0 does the same).
32    #[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::*;
76// Preserve the crate-public paths these two had when they lived in mod.rs.
77pub use checks::scan_for_sensitive_paths;
78pub use surface::is_science_subcommand;
79
80pub async fn run_command() {
81    // Deliberately NO dotenv here. `dotenvy::dotenv()` walks the working
82    // tree upward, and vela runs inside CLONED frontier repos — a
83    // committed .env could silently inject VELA_HUB_URL / VELA_ACTOR_ID /
84    // VELA_KEY_PATH / VELA_NO_PUBLISH for anyone who runs vela in it
85    // (the attack class git blocks via protected configuration and
86    // Codex blocks by refusing base-url keys in project config).
87    // Configuration comes from the real environment and ~/.vela only.
88
89    // Color contract: NO_COLOR always wins; ui.color=never/always
90    // overrides the tty heuristic.
91    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                // `check --evidence` folds in the standalone `evidence-ci` verb,
122                // routing to the same handler. A source/frontier is required.
123                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                            "idempotent": opened.get("idempotent").and_then(serde_json::Value::as_bool).unwrap_or(false),
530                            "frontier_id": session.get("frontier_id"),
531                            "target_id": target,
532                            "session": {
533                                "id": session.get("session_id"),
534                                "path": opened.get("session_path"),
535                                "actor": session.get("actor"),
536                                "expires_at": session.pointer("/lease/expires_at"),
537                            },
538                            "starting_roots": {
539                                "event_log": session.get("base_event_log_root"),
540                                "nonlease_event_log": session.get("base_nonlease_event_log_root"),
541                                "task_contract": session.get("task_contract_root"),
542                                "git_commit": session.get("source_git_commit_oid"),
543                            },
544                            "task": {
545                                "objective": session.pointer("/task_contract/objective"),
546                                "completion_condition": session.pointer("/task_contract/completion_condition"),
547                                "required_outputs": session.pointer("/task_contract/required_outputs"),
548                                "required_checks": session.pointer("/task_contract/required_checks"),
549                                "authority_ceiling": session.pointer("/task_contract/authority_ceiling"),
550                            },
551                            "packet": packet,
552                            "verifier_profile": task.and_then(|task| task.get("verifier_profile"))
553                                .or_else(|| packet.and_then(|packet| packet.get("schema"))),
554                            "next_command": format!("vela land --work {target} --claim <scoped-result> --type <type> --replayability <class> --artifact <path>:<kind> --caveat <limit> --as <agent> --json"),
555                        }));
556                    } else {
557                        crate::ui::header("WORK", &target, Some("lease claimed, briefing loaded"));
558                        let briefing = opened.get("briefing").unwrap_or(&opened);
559                        let b = briefing.get("briefing").unwrap_or(briefing);
560                        if let Some(s) = b.get("statement").and_then(|v| v.as_str()) {
561                            println!("  {}", safe_text::multiline(s));
562                        }
563                        for (label, key) in [
564                            ("gate", "gate"),
565                            ("value to beat", "value_to_beat"),
566                            ("attempts", "attempt_count"),
567                        ] {
568                            if let Some(v) = b.get(key) {
569                                let vs = v
570                                    .as_str()
571                                    .map(str::to_string)
572                                    .unwrap_or_else(|| v.to_string());
573                                if vs != "null" {
574                                    println!(
575                                        "  {:<14} {}",
576                                        vela_protocol::cli_style::dim(label),
577                                        safe_text::inline(&vs)
578                                    );
579                                }
580                            }
581                        }
582                        println!(
583                            "  {:<14} {}",
584                            vela_protocol::cli_style::dim("session"),
585                            safe_text::inline(
586                                opened
587                                    .get("session_path")
588                                    .and_then(|value| value.as_str())
589                                    .unwrap_or(".vela/work/<slug>--<target-sha256>/session.json")
590                            )
591                        );
592                        render_work_publication(&opened["claim"]);
593                        println!(
594                            "  {:<14} vela land --work {} --claim ...",
595                            vela_protocol::cli_style::dim("when done"),
596                            safe_text::inline(&target),
597                        );
598                    }
599                }
600                Err(e) => fail(&e),
601            }
602        }
603        Commands::Land {
604            receipt,
605            frontier,
606            claim,
607            claim_type,
608            replayability,
609            artifact,
610            caveat,
611            predicted_observable,
612            not_applicable,
613            performed_test,
614            result,
615            evidence,
616            counterevidence,
617            packet_root,
618            profile_root,
619            verifier_capsule_root,
620            result_contract_root,
621            work,
622            r#as,
623            push,
624            json,
625        } => {
626            crate::ui::set_mode("land", json);
627            let dir = crate::ui::resolve_frontier(frontier);
628            let actor = crate::cli_identity::resolve_actor(r#as.as_deref());
629            let preflight_identity =
630                vela_protocol::canonical::to_canonical_bytes(&serde_json::json!({
631                    "schema": "vela.land-preflight.internal.v1",
632                    "frontier": dir.display().to_string(),
633                    "actor": actor,
634                    "receipt": receipt.as_ref().map(|path| path.display().to_string()),
635                    "claim": claim,
636                    "claim_type": claim_type,
637                    "replayability": replayability,
638                    "artifacts": artifact,
639                    "caveats": caveat,
640                    "predicted_observable": predicted_observable,
641                    "not_applicable": not_applicable,
642                    "performed_test": performed_test,
643                    "result": result,
644                    "evidence": evidence,
645                    "counterevidence": counterevidence,
646                    "packet_root": packet_root,
647                    "profile_root": profile_root,
648                    "verifier_capsule_root": verifier_capsule_root,
649                    "result_contract_root": result_contract_root,
650                    "work": work,
651                    "push": push,
652                }))
653                .unwrap_or_default();
654            let preflight_id =
655                crate::operation_journal::operation_id("land-preflight", &preflight_identity);
656            let fail_preflight = |kind, message: String| -> ! {
657                crate::ui::fail_unchanged(kind, &message, &preflight_id, "vela land --help")
658            };
659            let receipt = if let Some(path) = receipt {
660                if work.is_some() {
661                    fail_preflight(
662                        crate::ui::ErrorKind::Usage,
663                        "--work selects the private flag-authoring path and cannot be combined with a foreign Receipt v1 file".to_string(),
664                    );
665                }
666                let raw = crate::bounded_file::read_bounded_file(
667                    &path,
668                    crate::bounded_file::RECEIPT_MAX_BYTES,
669                    "foreign Receipt v1",
670                )
671                .unwrap_or_else(|error| {
672                    let kind = if error.code == "missing" {
673                        crate::ui::ErrorKind::NotFound
674                    } else {
675                        crate::ui::ErrorKind::Domain
676                    };
677                    fail_preflight(kind, error.to_string())
678                });
679                vela_protocol::receipt_v1::ReceiptV1::parse(&raw).unwrap_or_else(|error| {
680                    fail_preflight(crate::ui::ErrorKind::Domain, error.to_string())
681                })
682            } else {
683                let Some(claim) = claim else {
684                    crate::ui::fail_unchanged(
685                        crate::ui::ErrorKind::Usage,
686                        "land needs a receipt file or --claim",
687                        &preflight_id,
688                        "vela land --help",
689                    );
690                };
691                let claim_type = claim_type.unwrap_or_else(|| {
692                    fail_preflight(
693                        crate::ui::ErrorKind::Usage,
694                        "flag authoring needs --type (computational, theoretical, empirical, negative, or contradiction)".to_string(),
695                    )
696                });
697                let replayability = replayability.unwrap_or_else(|| {
698                    fail_preflight(
699                        crate::ui::ErrorKind::Usage,
700                        "flag authoring needs --replayability (exact, bounded, approximate, unavailable, or unknown)".to_string(),
701                    )
702                });
703                let execution_binding = match (
704                    packet_root,
705                    profile_root,
706                    verifier_capsule_root,
707                    result_contract_root,
708                ) {
709                    (
710                        Some(packet_root),
711                        Some(profile_root),
712                        Some(verifier_capsule_root),
713                        Some(result_contract_root),
714                    ) => {
715                        let binding = vela_protocol::receipt_v1::ExecutionBindingV1 {
716                            schema: vela_protocol::receipt_v1::EXECUTION_BINDING_SCHEMA.to_string(),
717                            packet_root,
718                            profile_root,
719                            verifier_capsule_root,
720                            result_contract_root,
721                        };
722                        binding.validate().unwrap_or_else(|error| {
723                            fail_preflight(
724                                crate::ui::ErrorKind::Usage,
725                                format!("invalid exact execution binding: {error}"),
726                            )
727                        });
728                        Some(binding)
729                    }
730                    (None, None, None, None) => None,
731                    _ => fail_preflight(
732                        crate::ui::ErrorKind::Usage,
733                        "exact execution binding requires all four full roots".to_string(),
734                    ),
735                };
736                crate::workflow::author_receipt(
737                    &dir,
738                    &actor,
739                    work.as_deref(),
740                    claim,
741                    claim_type,
742                    replayability,
743                    &artifact,
744                    caveat,
745                    predicted_observable,
746                    not_applicable,
747                    performed_test,
748                    result,
749                    evidence,
750                    counterevidence,
751                    execution_binding,
752                )
753                .unwrap_or_else(|error| {
754                    fail_preflight(
755                        crate::ui::ErrorKind::Domain,
756                        format!("receipt build: {error}"),
757                    )
758                })
759            };
760            match crate::workflow::land(&dir, &receipt, &actor, push) {
761                Ok(outcome) => {
762                    let wire = outcome.wire();
763                    if json {
764                        let mut payload = serde_json::to_value(&wire)
765                            .expect("LandOutcomeWire contains only serializable values");
766                        let fields = payload
767                            .as_object_mut()
768                            .expect("LandOutcomeWire serializes as an object");
769                        fields.insert("ok".to_string(), serde_json::json!(true));
770                        fields.insert("command".to_string(), serde_json::json!("land"));
771                        fields.insert(
772                            "request_id".to_string(),
773                            serde_json::json!(wire.operation_id),
774                        );
775                        print_json(&payload);
776                    } else {
777                        render_land_outcome(
778                            wire.proposal_id,
779                            wire.route,
780                            &wire.detail,
781                            wire.operation_id,
782                            wire.publication,
783                        );
784                    }
785                }
786                Err(e) => fail(&e),
787            }
788        }
789        Commands::Config { action } => match action {
790            ConfigAction::Get {
791                key,
792                frontier,
793                json,
794            } => {
795                crate::ui::set_mode("config", json);
796                crate::config::settings::cmd_config_get(&key, frontier.as_deref(), json)
797            }
798            ConfigAction::Set {
799                key,
800                value,
801                frontier,
802                json,
803            } => {
804                crate::ui::set_mode("config", json);
805                crate::config::settings::cmd_config_set(&key, &value, frontier.as_deref(), json)
806            }
807            ConfigAction::Unset {
808                key,
809                frontier,
810                json,
811            } => {
812                crate::ui::set_mode("config", json);
813                crate::config::settings::cmd_config_unset(&key, frontier.as_deref(), json)
814            }
815            ConfigAction::List { frontier, json } => {
816                crate::ui::set_mode("config", json);
817                crate::config::settings::cmd_config_list(frontier.as_deref(), json)
818            }
819        },
820        Commands::Policy { action } => match action {
821            PolicyAction::Show { frontier, json } => {
822                crate::ui::set_mode("policy", json);
823                crate::config::cli_policy::cmd_policy_show(
824                    &crate::ui::resolve_frontier(frontier),
825                    json,
826                )
827            }
828            PolicyAction::Suggest { frontier, json } => {
829                crate::ui::set_mode("policy", json);
830                crate::config::cli_policy::cmd_policy_suggest(
831                    &crate::ui::resolve_frontier(frontier),
832                    json,
833                )
834            }
835            PolicyAction::Draft {
836                operands,
837                from_suggest,
838                replace,
839                from_proposal,
840                packet_root,
841                profile_root,
842                verifier_capsule_root,
843                result_contract_root,
844                producer_credential_root,
845                json,
846            } => {
847                crate::ui::set_mode("policy", json);
848                if from_suggest {
849                    if operands.len() > 1 {
850                        crate::ui::fail_with(
851                            crate::ui::ErrorKind::Usage,
852                            "policy draft --from-suggest accepts only an optional frontier",
853                            Some("vela policy draft --from-suggest <frontier>"),
854                        );
855                    }
856                    let frontier = crate::ui::resolve_frontier(operands.first().map(PathBuf::from));
857                    crate::config::cli_policy::cmd_policy_draft_from_suggest(
858                        &frontier, replace, json,
859                    )
860                } else {
861                    let template = operands.first().cloned().unwrap_or_else(|| {
862                        fail_return("policy draft needs a template or --from-suggest")
863                    });
864                    let frontier = crate::ui::resolve_frontier(operands.get(1).map(PathBuf::from));
865                    let exact_binding = if let Some(proposal_id) = from_proposal {
866                        if template != "search-witness" {
867                            crate::ui::fail_with(
868                                crate::ui::ErrorKind::Usage,
869                                "--from-proposal is supported only by the search-witness template",
870                                Some(
871                                    "use `vela policy draft search-witness <frontier> --from-proposal <vpr_id>`",
872                                ),
873                            );
874                        }
875                        Some(
876                            crate::config::cli_policy::exact_permit_binding_from_proposal(
877                                &frontier,
878                                &proposal_id,
879                            )
880                            .unwrap_or_else(|error| error.fail()),
881                        )
882                    } else {
883                        match (
884                            packet_root,
885                            profile_root,
886                            verifier_capsule_root,
887                            result_contract_root,
888                        ) {
889                            (Some(packet), Some(profile), Some(capsule), Some(result)) => {
890                                Some(crate::config::cli_policy::ExactPermitBinding {
891                                    packet_root: packet,
892                                    profile_root: profile,
893                                    verifier_capsule_root: capsule,
894                                    result_contract_root: result,
895                                    producer_credential_root,
896                                })
897                            }
898                            (None, None, None, None) => {
899                                if producer_credential_root.is_some() {
900                                    crate::ui::fail_with(
901                                        crate::ui::ErrorKind::Usage,
902                                        "producer credential binding requires all four exact execution roots",
903                                        Some(
904                                            "provide --packet-root, --profile-root, --verifier-capsule-root, and --result-contract-root",
905                                        ),
906                                    );
907                                }
908                                None
909                            }
910                            _ => crate::ui::fail_with(
911                                crate::ui::ErrorKind::Usage,
912                                "exact policy binding requires all four full roots",
913                                Some(
914                                    "provide --packet-root, --profile-root, --verifier-capsule-root, and --result-contract-root",
915                                ),
916                            ),
917                        }
918                    };
919                    crate::config::cli_policy::cmd_policy_draft(
920                        &frontier,
921                        &template,
922                        exact_binding.as_ref(),
923                        replace,
924                        json,
925                    )
926                }
927            }
928            PolicyAction::Test { frontier, json } => {
929                crate::ui::set_mode("policy", json);
930                crate::config::cli_policy::cmd_policy_test(
931                    &crate::ui::resolve_frontier(frontier),
932                    json,
933                )
934            }
935            PolicyAction::EvaluateProposal { operands, json } => {
936                crate::ui::set_mode("policy", json);
937                let proposal_id = operands
938                    .iter()
939                    .find(|value| value.starts_with("vpr_"))
940                    .cloned()
941                    .unwrap_or_else(|| {
942                        fail_return("policy evaluate-proposal needs one vpr_ proposal id")
943                    });
944                let frontier = operands
945                    .iter()
946                    .find(|value| !value.starts_with("vpr_"))
947                    .map(PathBuf::from);
948                crate::config::cli_policy::cmd_policy_evaluate_proposal(
949                    &crate::ui::resolve_frontier(frontier),
950                    &proposal_id,
951                    json,
952                )
953            }
954            PolicyAction::Decide {
955                frontier,
956                activate,
957                rotate,
958                revoke,
959                reason,
960                confirm_root,
961                confirm_at,
962                json,
963            } => {
964                crate::ui::set_mode("policy", json);
965                let action = match (activate, rotate, revoke) {
966                    (Some(policy_id), None, false) => {
967                        (vela_signer::PolicyDecisionAction::Activate, policy_id)
968                    }
969                    (None, Some(policy_id), false) => {
970                        (vela_signer::PolicyDecisionAction::Rotate, policy_id)
971                    }
972                    (None, None, true) => {
973                        (vela_signer::PolicyDecisionAction::Revoke, String::new())
974                    }
975                    _ => crate::ui::fail_with(
976                        crate::ui::ErrorKind::Usage,
977                        "policy decide requires exactly one of --activate, --rotate, or --revoke",
978                        Some("vela policy decide <frontier> --activate <vap_id> --reason <why>"),
979                    ),
980                };
981                crate::config::cli_policy::cmd_policy_decide(
982                    &crate::ui::resolve_frontier(frontier),
983                    action.0,
984                    &action.1,
985                    &reason,
986                    confirm_root.as_deref(),
987                    confirm_at.as_deref(),
988                    json,
989                )
990            }
991            PolicyAction::Sign {
992                frontier,
993                key,
994                yes,
995                json,
996            } => {
997                crate::ui::set_mode("policy", json);
998                if json && !yes {
999                    crate::ui::fail_with(
1000                        crate::ui::ErrorKind::Usage,
1001                        "policy sign --json requires --yes (JSON mode is non-interactive)",
1002                        Some("vela policy sign <frontier> --yes --json"),
1003                    );
1004                }
1005                crate::config::cli_policy::cmd_policy_sign(
1006                    &crate::ui::resolve_frontier(frontier),
1007                    key.as_deref(),
1008                    yes,
1009                    json,
1010                )
1011            }
1012            PolicyAction::Revoke {
1013                frontier,
1014                key,
1015                reason,
1016                yes,
1017                json,
1018            } => {
1019                crate::ui::set_mode("policy", json);
1020                if json && !yes {
1021                    crate::ui::fail_with(
1022                        crate::ui::ErrorKind::Usage,
1023                        "policy revoke --json requires --yes (JSON mode is non-interactive)",
1024                        Some("vela policy revoke <frontier> --reason <why> --yes --json"),
1025                    );
1026                }
1027                crate::config::cli_policy::cmd_policy_revoke(
1028                    &crate::ui::resolve_frontier(frontier),
1029                    key.as_deref(),
1030                    &reason,
1031                    yes,
1032                    json,
1033                )
1034            }
1035            PolicyAction::RetireLegacy {
1036                frontier,
1037                reason,
1038                actor,
1039                json,
1040            } => {
1041                crate::ui::set_mode("policy", json);
1042                crate::config::policy_legacy_retirement::cmd_policy_retire_legacy(
1043                    &crate::ui::resolve_frontier(frontier),
1044                    &reason,
1045                    &actor,
1046                    json,
1047                )
1048            }
1049            PolicyAction::Log { frontier, json } => {
1050                crate::ui::set_mode("policy", json);
1051                crate::config::cli_policy::cmd_policy_log(
1052                    &crate::ui::resolve_frontier(frontier),
1053                    json,
1054                )
1055            }
1056        },
1057    }
1058}
1059
1060fn render_work_publication(operation: &serde_json::Value) {
1061    let Some(publication) = operation.get("publication") else {
1062        return;
1063    };
1064    let state = publication
1065        .get("state")
1066        .and_then(serde_json::Value::as_str)
1067        .unwrap_or("unknown");
1068    let detail = publication
1069        .get("commit")
1070        .and_then(serde_json::Value::as_str)
1071        .map(|commit| format!("{state} {commit}"))
1072        .or_else(|| {
1073            publication
1074                .get("reason")
1075                .and_then(serde_json::Value::as_str)
1076                .map(|reason| format!("{state}: {reason}"))
1077        })
1078        .unwrap_or_else(|| state.to_string());
1079    println!(
1080        "  {:<14} {}",
1081        vela_protocol::cli_style::dim("git"),
1082        safe_text::inline(&detail)
1083    );
1084    if !matches!(state, "unchanged" | "committed_local" | "pushed") {
1085        println!(
1086            "  {:<14} {}",
1087            vela_protocol::cli_style::dim("recover"),
1088            safe_text::inline(
1089                publication
1090                    .get("recovery_command")
1091                    .and_then(serde_json::Value::as_str)
1092                    .unwrap_or("git status --short")
1093            )
1094        );
1095    }
1096}
1097
1098fn render_land_outcome(
1099    proposal_id: &str,
1100    route: &str,
1101    detail: &str,
1102    operation_id: &str,
1103    publication: &crate::config::git_publish::PublicationOutcome,
1104) {
1105    use crate::config::git_publish::PublicationState;
1106
1107    let (state, retained, changed_git, unchanged, remote, fallback_next) = match &publication.state
1108    {
1109        PublicationState::Unchanged { commit } => (
1110            "unchanged".to_string(),
1111            format!("existing local commit {commit} already contains every exact postimage"),
1112            "no Git ref or caller index entry moved".to_string(),
1113            "caller index/worktree entries".to_string(),
1114            "unverified; the exact local target commit is proven".to_string(),
1115            "git push".to_string(),
1116        ),
1117        PublicationState::Uncommitted { candidate, reason } => (
1118            format!("uncommitted: {reason}"),
1119            candidate
1120                .as_ref()
1121                .map(|oid| format!("candidate {oid} is not on the target ref"))
1122                .unwrap_or_else(|| "no publication commit on the target ref".to_string()),
1123            "no Git ref moved".to_string(),
1124            "unrelated index/worktree entries".to_string(),
1125            "not contacted by this publication attempt".to_string(),
1126            "git status --short".to_string(),
1127        ),
1128        PublicationState::Stale {
1129            candidate,
1130            expected,
1131            actual,
1132        } => (
1133            format!("stale: candidate {candidate} planned from {expected}; target is now {actual}"),
1134            format!("candidate {candidate} was not installed on the target ref"),
1135            "the competing Git ref update won; Vela did not merge or overwrite it".to_string(),
1136            "caller index/worktree entries".to_string(),
1137            "not contacted by this publication attempt".to_string(),
1138            "git status --short".to_string(),
1139        ),
1140        PublicationState::CommittedLocal { commit } => (
1141            "committed_local".to_string(),
1142            format!("local commit {commit}"),
1143            format!("local Git ref now retains commit {commit}"),
1144            "unrelated index/worktree entries".to_string(),
1145            "unverified; only the local commit is proven".to_string(),
1146            "git push".to_string(),
1147        ),
1148        PublicationState::Pushed { commit, remote } => (
1149            format!("pushed to {remote}"),
1150            format!("commit {commit}"),
1151            format!("commit {commit} is verified on {remote}"),
1152            "unrelated index/worktree entries".to_string(),
1153            format!("verified on {remote}"),
1154            "vela status --json".to_string(),
1155        ),
1156        PublicationState::Unknown { reason } => (
1157            format!("unknown: {reason}"),
1158            "publication state is not proven; inspect the recovery result".to_string(),
1159            "publication could not be proven".to_string(),
1160            "unrelated index/worktree entries".to_string(),
1161            "unverified".to_string(),
1162            "git status --short".to_string(),
1163        ),
1164    };
1165    let next = publication
1166        .recovery_command
1167        .as_deref()
1168        .unwrap_or(&fallback_next);
1169
1170    crate::ui::header("LAND", proposal_id, Some(route));
1171    println!(
1172        "  {:<16} proposal {} routed {} ({})",
1173        style::dim("changed"),
1174        safe_text::inline(proposal_id),
1175        safe_text::inline(route),
1176        safe_text::inline(detail)
1177    );
1178    println!(
1179        "  {:<16} {}",
1180        style::dim("git"),
1181        safe_text::inline(&changed_git)
1182    );
1183    println!(
1184        "  {:<16} {}",
1185        style::dim("unchanged"),
1186        safe_text::inline(&unchanged)
1187    );
1188    println!(
1189        "  {:<16} {}",
1190        style::dim("remote"),
1191        safe_text::inline(&remote)
1192    );
1193    println!(
1194        "  {:<16} {}",
1195        style::dim("publication"),
1196        safe_text::inline(&state)
1197    );
1198    println!(
1199        "  {:<16} {}",
1200        style::dim("request"),
1201        safe_text::inline(operation_id)
1202    );
1203    println!(
1204        "  {:<16} {}",
1205        style::dim("retained"),
1206        safe_text::inline(&retained)
1207    );
1208    println!("  {:<16} {}", style::dim("next"), safe_text::inline(next));
1209}
1210
1211// Bare `vela` (no args) opens a session against the nearest `.vela/`
1212// repo, walking up from cwd. The session prints a one-screen
1213// dashboard, then accepts single-letter verb shortcuts or
1214// natural-language questions routed through `cmd_ask`.
1215//
1216// Doctrine: this is the daily-driver entry, not a kitchen-sink IDE.
1217// Single screen, no scroll, no full TUI redraw. Each verb spawns the
1218// existing kernel command and prints its output inline. The session
1219// stays out of the user's way: type something, get an answer, type
1220// again. OpenCode/Claude Code shape.
1221
1222pub fn run_from_args() {
1223    style::init();
1224    let args = std::env::args().collect::<Vec<_>>();
1225    match args.get(1).map(String::as_str) {
1226        // v0.47: bare `vela` opens a session against the nearest
1227        // `.vela/` repo. The 30+ subcommand list is still there for
1228        // direct invocation; the session is the daily-driver entry.
1229        None => {
1230            run_session();
1231            return;
1232        }
1233        Some("-h" | "--help" | "help") => {
1234            // v0.47: top-level help shows the daily flow. The full
1235            // 30+ subcommand list lives behind `vela help advanced`.
1236            if args.get(2).map(String::as_str) == Some("advanced") {
1237                print_strict_help();
1238            } else {
1239                print_session_help();
1240            }
1241            return;
1242        }
1243        Some("-V" | "--version" | "version") => {
1244            println!("vela {}", env!("CARGO_PKG_VERSION"));
1245            return;
1246        }
1247        Some("proof") if args.get(2).map(String::as_str) == Some("verify") => {
1248            let json = args.iter().any(|arg| arg == "--json");
1249            let frontier = args
1250                .iter()
1251                .skip(3)
1252                .find(|arg| !arg.starts_with('-'))
1253                .map(PathBuf::from)
1254                .inspect(|p| {
1255                    // An exported proof-packet DIR (has manifest.json but no
1256                    // .vela/) verifies via the packet validator — the path
1257                    // packets themselves stamp into their receipts.
1258                    if p.join("manifest.json").exists() && !p.join(".vela").is_dir() {
1259                        crate::cli_read::cmd_verify(p, json);
1260                        std::process::exit(0);
1261                    }
1262                })
1263                .unwrap_or_else(|| {
1264                    eprintln!(
1265                        "{} proof verify requires a frontier repo",
1266                        style::err_prefix()
1267                    );
1268                    std::process::exit(2);
1269                });
1270            cmd_proof_verify(&frontier, json);
1271            return;
1272        }
1273        Some("proof") if args.get(2).map(String::as_str) == Some("explain") => {
1274            let frontier = args
1275                .iter()
1276                .skip(3)
1277                .find(|arg| !arg.starts_with('-'))
1278                .map(PathBuf::from)
1279                .unwrap_or_else(|| {
1280                    eprintln!(
1281                        "{} proof explain requires a frontier repo",
1282                        style::err_prefix()
1283                    );
1284                    std::process::exit(2);
1285                });
1286            cmd_proof_explain(&frontier);
1287            return;
1288        }
1289        // The pre-0.9 projection namespace was consolidated under `finding`.
1290        Some("state") => {
1291            eprintln!("{} `vela state` retired in 0.900", style::err_prefix());
1292            eprintln!("use `vela finding show <frontier> <vf_id> --view record|standing|evidence`");
1293            std::process::exit(2);
1294        }
1295        Some("atlas") => {
1296            eprintln!(
1297                "{} `vela atlas` retired from the core binary in 0.900",
1298                style::err_prefix()
1299            );
1300            eprintln!("use the campaign reader or a Canopus verifier profile");
1301            std::process::exit(2);
1302        }
1303        Some(cmd) if !is_science_subcommand(cmd) => {
1304            let replacement = match cmd {
1305                "proposals" => Some(
1306                    "vela review list <frontier> --json, then vela review show <frontier> <vpr_id> --json",
1307                ),
1308                "diff" => Some(
1309                    "vela review preview <frontier> <vpr_id>, or vela frontier diff <left> <right>",
1310                ),
1311                "credit" => Some("vela finding show <frontier> <vf_id> --view attribution"),
1312                "publication" => Some("vela frontier recover-publication"),
1313                "hub" => Some("the separate vela-hub binary"),
1314                "foundry" | "reproduce-external" => {
1315                    Some("a Canopus verifier profile or parent campaign script")
1316                }
1317                _ => None,
1318            };
1319            if let Some(replacement) = replacement {
1320                eprintln!("{} `vela {cmd}` retired in 0.900", style::err_prefix());
1321                eprintln!("use `{replacement}`");
1322            } else {
1323                eprintln!("{} unknown command: {cmd}", style::err_prefix());
1324                eprintln!("run `vela --help` for the product surface.");
1325            }
1326            std::process::exit(2);
1327        }
1328        Some(_) => {}
1329    }
1330    let runtime = tokio::runtime::Runtime::new().expect("failed to create tokio runtime");
1331    runtime.block_on(run_command());
1332}