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