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