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
//! Verification-side output: proof loading, report emission, exit codes.
//! Exit code contract: 0 = PASS, 1 = FAIL/INDETERMINATE, 2 = error.

use proof_verify::Validity;
use proof_verify::VerifyReport;

/// A loaded proof artifact. The pipeline re-verifies every stage over the
/// canonical bytes (including the envelope id), so loading only needs to
/// extract schema-valid bytes; nothing here is trusted.
pub struct LoadedProof {
    pub canonical: Vec<u8>,
    #[allow(dead_code)]
    pub proof: proof_core::model::Proof,
}

/// Load a proof artifact file (JSON wrapper, canonical CBOR hex inside).
// PE-CLI-002: schema-decode only; pipeline re-verifies id/canonical/sigs.
pub fn load_proof(path: &str) -> Result<LoadedProof, String> {
    let text = crate::read_input_file(path)?;
    let v: serde_json::Value =
        serde_json::from_str(&text).map_err(|e| format!("parse {path}: {e}"))?;
    let hex_str = v
        .get("cbor")
        .and_then(|x| x.as_str())
        .ok_or_else(|| format!("{path}: missing `cbor`"))?;
    let bytes = hex::decode(hex_str).map_err(|e| format!("{path}: bad hex: {e}"))?;
    let limits = crate::limits();
    let value = proof_format::decode_strict(&bytes, &limits).map_err(|e| format!("{path}: {e}"))?;
    let proof =
        proof_format::schema::cbor_to_proof(&value, &limits).map_err(|e| format!("{path}: {e}"))?;
    eprintln!("loaded proof {} ({path})", proof.proof_id);
    Ok(LoadedProof {
        canonical: bytes,
        proof,
    })
}

fn validity_str(v: Validity) -> &'static str {
    if v == Validity::Valid {
        "valid"
    } else {
        "invalid"
    }
}

/// Explicit JSON projection of the report (the report type is not Serialize;
/// the CLI owns its output format). Stable field order, machine-readable.
// PE-CLI-004 ยท PE-CLI-007: pub(crate) so `evaluate --json` can embed the
// pipeline report alongside the policy outcome.
pub fn report_json(r: &VerifyReport) -> serde_json::Value {
    serde_json::json!({
        "proof_id": r.proof_id,
        "cryptographic_validity": validity_str(r.cryptographic_validity),
        "evidence_validity": validity_str(r.evidence_validity),
        "policy_decision": r.policy_decision.as_str(),
        "lifecycle_checked": r.lifecycle_checked,
        "lifecycle": r
            .lifecycle
            .iter()
            .map(|l| {
                serde_json::json!({
                    "object": l.object,
                    "status": l.status.as_str(),
                    "code": l.code.map(|c| c.as_str()),
                    "message": l.message,
                })
            })
            .collect::<Vec<_>>(),
        "status_objects": r.status_objects,
        "checks": r
            .checks
            .iter()
            .map(|c| {
                serde_json::json!({
                    "stage": c.stage,
                    "object": c.object,
                    "ok": c.ok,
                    "code": c.code.map(|c| c.as_str()),
                    "message": c.message,
                })
            })
            .collect::<Vec<_>>(),
    })
}

/// Emit the report: stdout (machine-readable) when no `--out` is given,
/// otherwise written to the file with only a progress note on stderr.
// PE-CLI-004: machine-readable stdout/file; progress stderr.
pub fn emit_report(report: &VerifyReport, out: Option<String>) -> Result<(), String> {
    let v = report_json(report);
    let text = serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?;
    match out {
        Some(path) => {
            std::fs::write(
                &path,
                text + "
",
            )
            .map_err(|e| format!("write {path}: {e}"))?;
            eprintln!("report  -> {path}");
        }
        None => println!("{text}"),
    }
    Ok(())
}

/// `verify` exit code: PASS only when both crypto AND evidence are valid.
pub fn verdict_exit(report: &VerifyReport) -> i32 {
    if report.passed_crypto() && report.evidence_validity == Validity::Valid {
        crate::EXIT_OK
    } else {
        crate::EXIT_FAIL
    }
}

/// PE-CLI-007: stable JSON projection of the policy outcome for `evaluate
/// --json` (`proof-cli/src/make.rs`). Field set is the machine contract.
pub fn outcome_json(outcome: &proof_policy::PolicyOutcome) -> serde_json::Value {
    serde_json::json!({
        "policy_id": outcome.policy_id,
        "decision": outcome.decision.as_str(),
        "note": outcome.note,
        "results": outcome
            .results
            .iter()
            .map(|r| {
                serde_json::json!({
                    "requirement": r.requirement,
                    "passed": r.passed,
                    "message": r.message,
                })
            })
            .collect::<Vec<_>>(),
    })
}