Skip to main content

vela_cli/cli/
mod.rs

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