proof-cli 1.0.0

Command-line interface for creating, verifying, and evaluating Proof Engine proofs
Documentation
// Copyright 2026 Proof Engine Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Creation commands: build artifacts and assemble/verify proofs.
//! Every command re-derives ids and signatures through the library crates;
//! this module contains no trust logic of its own.

use crate::artifact::{
    input_list, load_attestation, load_event, load_evidence, load_relationship, load_status,
};
use crate::Cli;
use proof_core::model::Proposition;
use proof_crypto::build::{CreatedEvent, CreatedEvidence, CreatedRelationship};
use proof_verify::builder::ProofBuilder;

fn created_event(content: proof_core::model::EventContent) -> Result<CreatedEvent, String> {
    proof_crypto::build::create_event(content, &crate::limits()).map_err(|e| e.to_string())
}

fn created_evidence(content: proof_core::model::Evidence) -> Result<CreatedEvidence, String> {
    proof_crypto::build::make_evidence(
        content.kind,
        content.digest.clone(),
        content.attestation_ref,
        content.hint,
        &crate::limits(),
    )
    .map_err(|e| e.to_string())
}

fn created_relationship(
    content: proof_core::model::Relationship,
) -> Result<CreatedRelationship, String> {
    proof_crypto::build::make_relationship(content, &crate::limits()).map_err(|e| e.to_string())
}

/// `build`: assemble proof artifacts into a canonical, id-bound proof file.
/// Topology validation (grounding, dangling refs) is proof-graph's job and
/// runs inside `ProofBuilder::build` — the CLI adds nothing on top.
pub fn build(cli: &Cli) -> Result<String, String> {
    let context = crate::parse_fields(cli.opt("context"))?;
    let proposition = Proposition {
        v: 1,
        kind: cli.req("kind")?,
        subject: cli.req("subject")?,
        predicate: cli.req("predicate")?,
        object: cli.opt("object"),
        at_time: cli.opt_u64("at-time")?,
        context,
    };
    let mut b = ProofBuilder::new(proposition, cli.req_u64("created-at")?);
    for path in input_list(cli, "events")? {
        let content = load_event(&path, &crate::limits())?;
        b.add_event(created_event(content)?);
    }
    for path in input_list(cli, "attestations")? {
        b.add_attestation(load_attestation(&path, &crate::limits())?);
    }
    for path in input_list(cli, "evidence")? {
        let content = load_evidence(&path, &crate::limits())?;
        b.add_evidence(created_evidence(content)?);
    }
    for path in input_list(cli, "relationships")? {
        let content = load_relationship(&path, &crate::limits())?;
        b.add_relationship(created_relationship(content)?);
    }
    let built = b
        .build(&crate::limits())
        .map_err(|e| format!("build: {e}"))?;
    let out = cli.req("out")?;
    crate::artifact::write_proof_file(&out, &built.id, &built.canonical)?;
    println!("proof   {} -> {out}", built.id);
    Ok(built.id)
}

/// Flags shared by verify/evaluate/explain: an explicit clock is mandatory —
/// the CLI never reads the wall clock (PROPOSAL rule 4).
pub struct CommonInputs {
    pub verified_at: u64,
    pub skew: u64,
    pub revocations_known_at: Option<u64>,
}

// PE-CLI-003: explicit clock mandatory; wall clock never read.
pub fn common(cli: &Cli) -> Result<CommonInputs, String> {
    Ok(CommonInputs {
        verified_at: cli.req_u64("clock")?,
        skew: cli
            .opt("skew")
            .map(|v| v.parse().map_err(|_| "--skew must be a u64".to_string()))
            .transpose()?
            .unwrap_or(300),
        revocations_known_at: cli.opt_u64("revocations-known-at")?,
    })
}

/// All trust inputs are explicit flags; nothing is guessed from the proof.
pub fn eval_inputs(cli: &Cli, c: &CommonInputs) -> proof_policy::EvalInputs {
    let mut revoked: Vec<String> = vec![];
    for item in cli.many("revoked") {
        revoked.extend(item.split(',').map(str::to_string));
    }
    proof_policy::EvalInputs {
        trusted_issuers: cli.many("trusted"),
        revocations: proof_policy::RevocationSet::new(revoked),
        verified_at: c.verified_at,
        skew_leeway: c.skew,
    }
}

/// `verify`: run the 10-stage pipeline. Authority keyrefs must be supplied
/// explicitly via --authority; revocation status objects via --status.
pub fn verify(cli: &Cli) -> Result<i32, String> {
    let proof = crate::check::load_proof(&cli.req("proof")?)?;
    let c = common(cli)?;
    let statuses: Vec<proof_crypto::SignedStatus> = cli
        .many("status")
        .iter()
        .map(|p| load_status(p, &crate::limits()))
        .collect::<Result<_, _>>()?;
    let authorities = cli.many("authority");
    let report = proof_verify::verify_proof(
        &proof.canonical,
        &proof_verify::VerifyCtx {
            verified_at: c.verified_at,
            clock_skew_leeway: c.skew,
            status_objects: statuses,
            revocation_authorities: authorities,
            revocations_known_at: c.revocations_known_at,
            ..Default::default()
        },
    )
    .map_err(|e| format!("verify: {e}"))?;
    crate::check::emit_report(&report, cli.opt("out"))?;
    Ok(crate::check::verdict_exit(&report))
}

/// `evaluate` / `explain`: pipeline + declarative policy over its output.
// PE-CLI-006: explain prints prose only, never JSON over prose.
pub fn evaluate(cli: &Cli, explain: bool) -> Result<i32, String> {
    let proof = crate::check::load_proof(&cli.req("proof")?)?;
    let c = common(cli)?;
    let policy_path = cli.req("policy")?;
    let policy_text =
        crate::read_input_file(&policy_path).map_err(|e| format!("read policy: {e}"))?;
    let policy_val: serde_json::Value =
        serde_json::from_str(&policy_text).map_err(|e| format!("parse policy: {e}"))?;
    let policy = proof_policy::parse_policy(&policy_val, &crate::limits())
        .map_err(|e| format!("policy: {e}"))?;
    let statuses: Vec<proof_crypto::SignedStatus> = cli
        .many("status")
        .iter()
        .map(|p| load_status(p, &crate::limits()))
        .collect::<Result<_, _>>()?;
    let report = proof_verify::verify_proof(
        &proof.canonical,
        &proof_verify::VerifyCtx {
            verified_at: c.verified_at,
            clock_skew_leeway: c.skew,
            trusted_issuers: cli.many("trusted"),
            status_objects: statuses,
            revocation_authorities: cli.many("authority"),
            revocations_known_at: c.revocations_known_at,
            ..Default::default()
        },
    )
    .map_err(|e| format!("verify: {e}"))?;
    let state = proof_policy::state_from_report_and_proof(&report, &proof.proof)
        .map_err(|e| format!("state: {e}"))?;
    let outcome = proof_policy::evaluate_policy(&state, &policy, &eval_inputs(cli, &c));
    // Report emission: `evaluate` prints JSON to stdout unless --out is
    // given; `explain` never dumps JSON on top of the prose (file via --out
    // is still honored).
    // Report emission: prose mode keeps the historical stdout report (then
    // the decision text below); `--json` owns stdout exclusively so stdout is
    // one script-parsable document; `--out` always writes the report file and
    // `explain` never mixes JSON with prose (PE-CLI-006).
    let json_mode = cli.has("json") && !explain;
    match (explain, cli.opt("out")) {
        (false, Some(path)) => crate::check::emit_report(&report, Some(path))?,
        (false, None) if json_mode => {}
        (false, None) => crate::check::emit_report(&report, None)?,
        (true, Some(path)) => crate::check::emit_report(&report, Some(path))?,
        (true, None) => {}
    }
    if explain {
        print!("{}", proof_policy::explain_full(&report, &outcome));
    } else if cli.has("json") {
        // PE-CLI-007: machine-readable policy decision. Same exit-code
        // contract as prose mode; `explain` never takes this path (PE-CLI-006).
        let merged = serde_json::json!({
            "policy_outcome": crate::check::outcome_json(&outcome),
            "report": crate::check::report_json(&report),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&merged).map_err(|e| e.to_string())?
        );
    } else {
        println!("decision {}", outcome.decision.as_str());
        for r in &outcome.results {
            println!(
                "  [{}] {} — {}",
                if r.passed { "ok" } else { "NO" },
                r.requirement,
                r.message
            );
        }
    }
    Ok(match outcome.decision {
        proof_verify::PolicyDecision::Pass => crate::EXIT_OK,
        proof_verify::PolicyDecision::Fail | proof_verify::PolicyDecision::Indeterminate => {
            crate::EXIT_FAIL
        }
    })
}