use crate::cli::{
active_policy_pair_snapshot, collect_witness_files, fail, fail_return, parse_witness,
print_json,
};
use crate::cli_commands::*;
use serde_json::{Value, json};
use std::path::Path;
use vela_protocol::cli_style as style;
use vela_protocol::evidence_ci;
use vela_protocol::repo;
pub(crate) fn cmd_gate(action: GateAction) {
use vela_edge::deliverable_grade::{self, DeliverableGrade, GradeGate};
use vela_protocol::verifier_attachment::{
self, GateStatus, ProbeKind, VerifierAttachment, VerifierMethod,
};
match action {
GateAction::Grade { claim, grade, json } => {
let gate = deliverable_grade::grade_gate(&claim, grade.as_deref());
let passed = gate.passed();
if json {
let grade_str = match &gate {
GradeGate::Ok(g) => Some(g.as_str().to_string()),
_ => grade.clone(),
};
println!(
"{}",
serde_json::to_string_pretty(&json!({
"command": "gate grade",
"passed": passed,
"grade": grade_str,
"reason": gate.reason(),
}))
.expect("serialize gate grade response")
);
} else if passed {
println!("gate grade: ok");
if let GradeGate::Ok(g) = gate {
println!(" deliverable_grade: {g} (claim text consistent with grade)");
}
} else {
eprintln!("gate grade: REJECTED\n {}", gate.reason());
}
if !passed {
std::process::exit(1);
}
}
GateAction::Check {
claim,
attachments,
json,
} => {
let raw = std::fs::read_to_string(&attachments)
.unwrap_or_else(|e| fail_return(&format!("read {}: {e}", attachments.display())));
let atts: Vec<VerifierAttachment> = serde_json::from_str(&raw).unwrap_or_else(|e| {
fail_return(&format!(
"parse {} as a JSON array of VerifierAttachment: {e}",
attachments.display()
))
});
for a in &atts {
if let Err(e) = a.verify() {
fail(&format!("attachment {} is malformed: {e}", a.id));
}
}
let digest = verifier_attachment::claim_digest(&claim);
let outcome = verifier_attachment::derive_gate_status(&digest, &atts);
let verified = outcome.status == GateStatus::Verified;
if json {
let status = match outcome.status {
GateStatus::Verified => "verified",
GateStatus::NeedsVerification => "needs_verification",
GateStatus::Refuted => "refuted",
};
println!(
"{}",
serde_json::to_string_pretty(&json!({
"command": "gate check",
"claim_digest": digest,
"attachments": atts.len(),
"status": status,
"reasons": outcome.reasons,
}))
.expect("serialize gate check response")
);
} else {
println!(
"gate check: {} attachment(s) over claim {digest}",
atts.len()
);
match outcome.status {
GateStatus::Verified => println!(
" status: VERIFIED\n >=2 independent matched attachments + a surviving adversarial probe."
),
GateStatus::Refuted => {
println!(" status: REFUTED");
for r in &outcome.reasons {
println!(" - {r}");
}
}
GateStatus::NeedsVerification => {
println!(" status: needs_verification");
for r in &outcome.reasons {
println!(" - {r}");
}
}
}
}
if !verified {
std::process::exit(1);
}
}
GateAction::Vocab { json } => {
let grades: Vec<&str> = DeliverableGrade::ALL.iter().map(|g| g.as_str()).collect();
let methods: Vec<&str> = VerifierMethod::ALL.iter().map(|m| m.as_str()).collect();
let probes = [
ProbeKind::CounterexampleSearch,
ProbeKind::CaseBConfig,
ProbeKind::BoundaryDualFeasibility,
ProbeKind::FiniteSizeExtrapolation,
ProbeKind::IndependentReimplementation,
ProbeKind::FormalismFidelity,
];
let probe_kinds: Vec<&str> = probes.iter().map(|p| p.as_str()).collect();
if json {
println!(
"{}",
serde_json::to_string_pretty(&json!({
"command": "gate vocab",
"deliverable_grades": grades,
"solve_grades": DeliverableGrade::ALL
.iter()
.filter(|g| g.is_solve())
.map(|g| g.as_str())
.collect::<Vec<_>>(),
"verifier_methods": methods,
"probe_kinds": probe_kinds,
}))
.expect("serialize gate vocab response")
);
} else {
println!("deliverable grades ({}):", grades.len());
for g in DeliverableGrade::ALL {
let mark = if g.is_solve() { " (solve)" } else { "" };
println!(" {}{mark}", g.as_str());
}
println!("\nverifier methods ({}):", methods.len());
for m in &methods {
println!(" {m}");
}
println!("\nadversarial probe kinds ({}):", probe_kinds.len());
for p in &probe_kinds {
println!(" {p}");
}
}
}
}
}
pub(crate) struct PolicyRouteVerdict {
pub would_permit: bool,
pub canonical_claim: Option<String>,
}
pub(crate) fn evaluate_exact_policy_route(
frontier: &Path,
finding_id: &str,
) -> Result<PolicyRouteVerdict, String> {
use std::collections::BTreeSet;
let source = repo::detect(frontier)?;
let proj = repo::load(&source)?;
let (finding, proposal) = resolve_finding_and_proposal(&proj, finding_id);
let finding = finding.ok_or_else(|| {
format!("no finding '{finding_id}' (landed or in a pending finding.add proposal)")
})?;
let proposal = proposal.ok_or_else(|| {
format!(
"no finding.add proposal targets '{finding_id}'; the exact lane admits a proposal, \
not an already-landed finding"
)
})?;
let (witness_ok, _witness_msg, witness) =
reproduce_finding_witness(&proj, frontier, finding_id);
let faithful = witness
.as_ref()
.map(|w| vela_verify::claim_witness_faithful(&finding.assertion.text, w));
let canonical_claim = witness.as_ref().and_then(vela_verify::canonical_claim);
let synthetic: BTreeSet<String> = proj
.findings
.iter()
.filter(|f| is_synthetic_source(&f.provenance.source_type))
.map(|f| f.id.clone())
.collect();
let mut synthetic = synthetic;
if is_synthetic_source(&finding.provenance.source_type) {
synthetic.insert(finding.id.clone());
}
let graph = vela_protocol::frontier_graph::FrontierGraph::from_project(&proj);
let open_contradictions: BTreeSet<String> = vela_protocol::contradiction::derive_candidates(
&graph,
proj.frontier_id.as_deref().unwrap_or_default(),
)
.into_iter()
.filter(|c| c.is_open())
.flat_map(|c| [c.finding_a.clone(), c.finding_b.clone()])
.collect();
let matched: Vec<_> = proj
.verifier_attachments
.iter()
.filter(|a| a.target == finding.id)
.cloned()
.collect();
let floor_ok = witness_ok && faithful.as_ref().map(|f| f.faithful).unwrap_or(false);
let (wrapper_ok, _wrapper_reasons) = vela_protocol::proposals::exact_lane_eligible(
&proposal,
&finding,
&matched,
&open_contradictions,
&synthetic,
floor_ok,
);
let (vouched_ok, _vouch_reason) = attachment_vouch_gate(floor_ok, matched.len());
let mut would_permit = floor_ok && wrapper_ok && vouched_ok;
let policy_snapshot = vela_protocol::acceptance_policy::load_active_policy_snapshot(frontier);
let now = chrono::Utc::now().to_rfc3339();
let policy_assessment = vela_protocol::proposals::policy_accept::assess_policy_readiness(
&proj,
policy_snapshot.as_ref().map_err(String::as_str),
&now,
);
if policy_assessment.permit_readiness()
== vela_protocol::proposals::policy_accept::PermitReadiness::Blocked
{
return Err(format!(
"active policy: {}",
policy_assessment
.detail()
.unwrap_or("policy readiness assessment is blocked")
));
}
match policy_snapshot {
Ok(snapshot) => {
if let Some(vp) = snapshot.verified {
let ctx = vela_protocol::acceptance_policy::PolicyContext {
claim_class: vela_protocol::proposals::policy_accept::proposal_claim_class(
&proposal,
),
..vela_protocol::acceptance_policy::PolicyContext::default()
};
let decision = vela_protocol::acceptance_policy::evaluate(&vp.policy, &ctx, &now);
let permitted = decision.outcome
== vela_protocol::acceptance_policy::Outcome::Permit
&& policy_assessment.permit_readiness()
== vela_protocol::proposals::policy_accept::PermitReadiness::Ready;
would_permit = would_permit && permitted;
}
}
Err(error) => return Err(format!("active policy: {error}")),
}
Ok(PolicyRouteVerdict {
would_permit,
canonical_claim,
})
}
fn resolve_finding_and_proposal(
proj: &vela_protocol::project::Project,
finding_id: &str,
) -> (
Option<vela_protocol::bundle::FindingBundle>,
Option<vela_protocol::proposals::StateProposal>,
) {
let proposal = proj
.proposals
.iter()
.find(|p| {
p.kind == "finding.add"
&& (p.target.id == finding_id
|| p.payload
.get("finding")
.and_then(|f| f.get("id"))
.and_then(|i| i.as_str())
== Some(finding_id))
})
.cloned();
let finding = proposal
.as_ref()
.and_then(|p| p.payload.get("finding").cloned())
.and_then(|v| serde_json::from_value::<vela_protocol::bundle::FindingBundle>(v).ok())
.or_else(|| proj.findings.iter().find(|f| f.id == finding_id).cloned());
(finding, proposal)
}
fn is_synthetic_source(source_type: &str) -> bool {
let s = source_type.trim().to_ascii_lowercase();
s == "synthetic_report" || s == "agent_trace"
}
fn attachment_vouch_gate(floor_ok: bool, matched_len: usize) -> (bool, String) {
if floor_ok {
if matched_len == 0 {
(true, String::new())
} else {
(
true,
format!(
"floor-sufficient: {matched_len} matched attachment(s) are non-load-bearing corroboration, not gating"
),
)
}
} else {
(
false,
"non-floor-sufficient admission would rest on attachment provenance, which is not yet owner-rooted (open actor self-enrollment is forgeable); lane refuses in the safe direction"
.to_string(),
)
}
}
fn reproduce_finding_witness(
proj: &vela_protocol::project::Project,
frontier: &Path,
finding_id: &str,
) -> (bool, String, Option<vela_verify::Witness>) {
for art in &proj.artifacts {
let is_json = art.media_type.as_deref() == Some("application/json");
if !(is_json && art.metadata.contains_key("verifier")) {
continue;
}
if !art.target_findings.iter().any(|t| t == finding_id) {
continue;
}
let content = match (art.storage_mode.as_str(), &art.locator) {
("local_blob" | "local_file", Some(loc)) => {
match std::fs::read_to_string(frontier.join(loc.as_str())) {
Ok(c) => c,
Err(e) => return (false, format!("witness unreadable: {e}"), None),
}
}
_ => continue,
};
match parse_witness(&content) {
Ok(w) => {
let r = vela_verify::verify_witness(&w);
return (r.ok, r.message, Some(w));
}
Err(e) => return (false, format!("witness parse failed: {e}"), None),
}
}
(
false,
"no local frozen-verifier witness artifact targets this finding".to_string(),
None,
)
}
pub(crate) fn cmd_reproduce(path: &Path, json_output: bool) {
crate::ui::set_mode("reproduce", json_output);
if !json_output {
crate::ui::header("REPRODUCE", &path.display().to_string(), None);
}
let mut files = collect_witness_files(path);
if let Ok(source) = repo::detect(path)
&& let Ok(proj) = repo::load(&source)
{
use sha2::{Digest, Sha256};
let loose: std::collections::HashSet<String> = files
.iter()
.filter_map(|f| std::fs::read(f).ok())
.map(|b| format!("sha256:{}", hex::encode(Sha256::digest(&b))))
.collect();
for art in &proj.artifacts {
if art.media_type.as_deref() != Some("application/json")
|| !art.metadata.contains_key("verifier")
|| loose.contains(&art.content_hash)
{
continue;
}
if let ("local_blob" | "local_file", Some(loc)) =
(art.storage_mode.as_str(), &art.locator)
{
let blob = path.join(loc);
if blob.exists() {
files.push(blob);
}
}
}
}
if files.is_empty() {
fail(&format!(
"no witnesses found at {} (expected a `*.witness.json` file, or a directory containing them / a `witnesses/` subdir)",
path.display()
));
}
let spinner = (!json_output).then(|| {
crate::cli::progress::Spinner::start(&format!(
"re-verifying {} witness(es) with the frozen verifiers",
files.len()
))
});
let mut results: Vec<Value> = Vec::new();
let mut passed = 0usize;
let mut failed = 0usize;
for file in &files {
let raw = match std::fs::read_to_string(file) {
Ok(r) => r,
Err(e) => {
failed += 1;
if !json_output {
println!(" FAIL {} ยท read error: {e}", file.display());
}
results.push(json!({"path": file.display().to_string(), "ok": false, "message": format!("read error: {e}")}));
continue;
}
};
let witness = match parse_witness(&raw) {
Ok(w) => w,
Err(e) => {
failed += 1;
if !json_output {
println!(" FAIL {} ยท parse error: {e}", file.display());
}
results.push(json!({"path": file.display().to_string(), "ok": false, "message": format!("parse error: {e}")}));
continue;
}
};
let mut outcome = vela_verify::verify_witness(&witness);
if outcome.ok
&& let Ok(value) = serde_json::from_str::<Value>(&raw)
&& let Some(prior_rel) = value.get("improves_on").and_then(Value::as_str)
{
let prior_path = file
.parent()
.map(|d| d.join(prior_rel))
.unwrap_or_else(|| std::path::PathBuf::from(prior_rel));
match std::fs::read_to_string(&prior_path)
.map_err(|e| format!("improves_on read {}: {e}", prior_path.display()))
.and_then(|p| parse_witness(&p))
.and_then(|prior| vela_verify::dominates(&witness, &prior))
{
Ok(true) => {
outcome.message =
format!("{} ยท strictly improves on {prior_rel}", outcome.message);
}
Ok(false) => {
outcome = vela_verify::VerifyResult::fail(format!(
"claims improves_on {prior_rel} but does NOT strictly dominate it"
));
}
Err(e) => {
outcome =
vela_verify::VerifyResult::fail(format!("improves_on check failed: {e}"));
}
}
}
if outcome.ok {
passed += 1;
} else {
failed += 1;
}
if !json_output {
let status = if outcome.ok { "ok " } else { "FAIL" };
println!(
" {status} {} [{}] ยท {}",
file.display(),
witness.kind(),
outcome.message
);
}
results.push(json!({
"path": file.display().to_string(),
"kind": witness.kind(),
"ok": outcome.ok,
"message": outcome.message,
}));
}
if let Some(s) = spinner {
s.finish(&format!("{passed} verified, {failed} failed"));
}
if json_output {
println!(
"{}",
serde_json::to_string_pretty(&json!({
"command": "reproduce",
"witnesses": files.len(),
"passed": passed,
"failed": failed,
"results": results,
}))
.expect("serialize reproduce response")
);
} else {
println!();
if failed == 0 {
println!(
" reproduce: ok ({passed}/{}) โ every witness re-verified from scratch by the frozen verifiers.",
files.len()
);
} else {
println!(
" reproduce: FAIL ({failed}/{} did not re-verify). Investigate before trusting.",
files.len()
);
}
}
if failed > 0 {
std::process::exit(1);
}
}
pub(crate) fn cmd_evidence_ci(frontier: &Path, json: bool) {
let project = repo::load_from_path(frontier)
.unwrap_or_else(|error| fail_return(&format!("evidence-ci failed: {error}")));
let snapshot = active_policy_pair_snapshot(frontier);
let policy = vela_protocol::proposals::policy_accept::assess_policy_readiness(
&project,
snapshot.as_ref().map_err(String::as_str),
&chrono::Utc::now().to_rfc3339(),
);
if policy.permit_readiness()
== vela_protocol::proposals::policy_accept::PermitReadiness::Blocked
{
if json {
print_json(&json!({
"ok": false,
"command": "evidence-ci",
"policy": {
"state": policy.state().as_str(),
"permit_readiness": policy.permit_readiness().as_str(),
"reason_codes": policy.reason_codes(),
"error": policy.detail(),
},
}));
std::process::exit(1);
}
fail_return::<()>(&format!(
"evidence-ci failed: active policy {}",
policy.detail().unwrap_or("readiness assessment is blocked")
));
}
let report = evidence_ci::run_frontier(frontier)
.unwrap_or_else(|e| fail_return(&format!("evidence-ci failed: {e}")));
if json {
print_json(&report);
return;
}
let status = if report.ok {
style::ok("evidence-ci")
} else {
style::lost("evidence-ci")
};
println!(
"{} {} ยท {} checks, {} warning(s), {} release-blocking failure(s)",
status,
report.frontier_id,
report.summary.total,
report.summary.warnings,
report.summary.release_blocking_failed
);
for check in report
.checks
.iter()
.filter(|check| check.status != evidence_ci::EvidenceCiStatus::Passed)
.take(40)
{
println!(
" {} {} {}: {}",
match check.status {
evidence_ci::EvidenceCiStatus::Passed => style::ok("pass"),
evidence_ci::EvidenceCiStatus::Warning => style::warn("warn"),
evidence_ci::EvidenceCiStatus::Failed => style::lost("fail"),
},
check.id,
check.target_id,
check.message
);
}
}
#[cfg(test)]
mod gate_tests {
use super::*;
#[test]
fn floor_sufficient_admits_without_any_vouch_even_with_attachments() {
let (ok, reason) = attachment_vouch_gate(true, 0);
assert!(ok, "floor-sufficient with no attachments admits");
assert!(reason.is_empty());
let (ok, reason) = attachment_vouch_gate(true, 3);
assert!(
ok,
"floor-sufficient admits even with attachments present (they do not gate)"
);
assert!(
reason.contains("non-load-bearing"),
"the reason is honest that attachments are not gating: {reason}"
);
}
#[test]
fn non_floor_sufficient_refuses_until_vouch_is_owner_rooted() {
for matched_len in [0usize, 1, 5] {
let (ok, reason) = attachment_vouch_gate(false, matched_len);
assert!(
!ok,
"non-floor-sufficient must refuse (matched_len={matched_len})"
);
assert!(
reason.contains("owner-rooted") || reason.contains("refuses"),
"the refusal names the missing owner-rooted vouch: {reason}"
);
}
}
}