Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion atomic-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ toml = { workspace = true }
redb = { workspace = true }
bytes = { workspace = true }
fs2 = "0.4"
tempfile = { workspace = true }
url = { workspace = true }

# Parallelism
Expand All @@ -113,7 +114,6 @@ libc = "0.2"
windows-sys = { version = "0.61", features = ["Win32_Foundation"] }

[dev-dependencies]
tempfile = { workspace = true }
serial_test = { workspace = true }
# The remote-sandbox end-to-end test serves libatomic over a temp Unix socket.
tokio-stream = { workspace = true, features = ["net"] }
Expand Down
93 changes: 86 additions & 7 deletions atomic-cli/src/commands/intent/validate.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
//! `atomic intent validate <ID|path>` — gate an intent against the canonical
//! shapes.

use std::path::Path;
use std::path::{Path, PathBuf};

use clap::Parser;

use atomic_canonical::lift::{lift_intent, parse_markdown};
use atomic_canonical::{validate_intent, ValidationReport, Violation};
use atomic_core::types::{Base32, Hash};
use atomic_repository::intent_evidence;
use atomic_repository::Repository;

use crate::commands::intent::bridge;
Expand All @@ -25,6 +26,18 @@ pub struct IntentValidate {
/// Output the validation report as JSON.
#[arg(long)]
pub json: bool,

/// Replay bounded evidence claims from a locally supplied manifest.
#[arg(long, requires = "evidence_checker")]
pub replay_evidence: Option<PathBuf>,

/// Trusted local checker executable (no shell; never loaded from the manifest).
#[arg(long, requires = "replay_evidence")]
pub evidence_checker: Option<PathBuf>,

/// Include native intent substance and view-chain pins in the JSON report.
#[arg(long, requires = "json")]
pub evidence_context: bool,
}

impl Command for IntentValidate {
Expand All @@ -40,6 +53,7 @@ impl Command for IntentValidate {
// if a FRESH attestation sidecar exists we gate the attested node (so a
// previously-attested intent reports conforms), a STALE one warns and
// falls back to the raw node.
let mut stored_inputs = None;
let node = if is_path_shaped(&self.id_or_path) {
let path = Path::new(&self.id_or_path);
if !path.is_file() {
Expand All @@ -58,7 +72,7 @@ impl Command for IntentValidate {
let root = find_repository_root()?;
let repo = Repository::open(&root).map_err(CliError::Repository)?;
let inputs = bridge::read_intent(&repo, &self.id_or_path)?;
match bridge::load_attestation(&repo, &self.id_or_path, &inputs)? {
let node = match bridge::load_attestation(&repo, &self.id_or_path, &inputs)? {
bridge::Attestation::Fresh(node) => *node,
bridge::Attestation::Stale(_) => {
eprintln!(
Expand All @@ -69,10 +83,29 @@ impl Command for IntentValidate {
bridge::lift(&inputs)?
}
bridge::Attestation::None => bridge::lift(&inputs)?,
}
};
stored_inputs = Some(inputs);
node
};

let mut report = validate_intent(&node);
let wants_context = self.evidence_context || self.replay_evidence.is_some();
if wants_context && is_path_shaped(&self.id_or_path) {
return Err(validation_failed(
"evidence replay/context requires a stored intent ID",
));
}
let context = if wants_context {
let inputs = stored_inputs.as_ref().ok_or_else(|| {
validation_failed("evidence replay/context requires a stored intent ID")
})?;
let root = find_repository_root()?;
let repo =
crate::commands::open_readonly_repository(&root).map_err(CliError::Repository)?;
Some(intent_evidence::context_from_inputs(&repo, inputs).map_err(evidence_error)?)
} else {
None
};

// Evidence URNs must RESOLVE to real changes when a repository is
// reachable — the gate only checks presence. (Recording the Why: a met
Expand All @@ -88,11 +121,47 @@ impl Command for IntentValidate {
report.results.extend(extra);
}

let replay = match (&self.replay_evidence, &self.evidence_checker, &context) {
(Some(manifest), Some(checker), Some(context)) => {
let replay = intent_evidence::replay(manifest, checker, context, &node)
.map_err(evidence_error)?;
// Release the repository before invoking a checker, then re-read.
// A checker result from another intent definition or view state
// must not be reused as a fresh validation result.
let root = find_repository_root()?;
let repo = crate::commands::open_readonly_repository(&root)
.map_err(CliError::Repository)?;
let after = intent_evidence::read_context(&repo, &self.id_or_path)
.map_err(evidence_error)?;
drop(repo);
let mut violations = replay.violations();
if &after != context {
violations.push(Violation {
focus_node: node.id.clone(),
shape: "EvidenceReplayFreshness".into(),
path: None,
message: "intent substance or view chain changed during evidence replay"
.into(),
});
}
if !violations.is_empty() {
report.conforms = false;
report.results.extend(violations);
}
Some(replay)
}
_ => None,
};

if self.json {
println!(
"{}",
serde_json::to_string_pretty(&report_json(&report)).unwrap()
);
let mut output = report_json(&report);
if let Some(context) = &context {
output["evidence_context"] = serde_json::to_value(context).unwrap();
}
if let Some(replay) = &replay {
output["evidence_replay"] = serde_json::to_value(replay).unwrap();
}
println!("{}", serde_json::to_string_pretty(&output).unwrap());
} else {
print!("{report}");
}
Expand All @@ -117,6 +186,16 @@ fn is_path_shaped(arg: &str) -> bool {
arg.ends_with(".md") || arg.contains('/') || arg.contains(std::path::MAIN_SEPARATOR)
}

/// Keep repository and I/O failures distinct; every other evidence refusal is
/// a user-fixable gate error (exit 2).
fn evidence_error(error: intent_evidence::EvidenceError) -> CliError {
match error {
intent_evidence::EvidenceError::Repository(error) => CliError::Repository(error),
intent_evidence::EvidenceError::Io(error) => CliError::Io(error),
other => validation_failed(other.to_string()),
}
}

/// Resolve `urn:atomic:change:<hash>` evidence URNs against the change store at
/// `repo_root`. One violation per URN that does not resolve. With no repository
/// the check is skipped — the gate still enforces presence; resolution needs a
Expand Down
188 changes: 188 additions & 0 deletions atomic-cli/src/commands/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ use std::path::{Path, PathBuf};

use atomic_client::proto as pb;
use atomic_core::types::{Base32, Merkle};
use atomic_repository::intent_evidence;
use libatomic::atomic::attestation_target::Kind as TargetKind;
use libatomic::atomic::update_vault_entity_request::Update as UpdateKind;
use libatomic::atomic::verify_attestation_request::Target as VerifyTarget;
use libatomic::atomic::VaultEntityKind as Kind;
use libatomic::atomic::VaultEntityStatus as Status;

use crate::commands::intent::validation_failed;
use crate::error::{CliError, CliResult};
use crate::output::{print_hint, print_info, print_success, print_warning};
use crate::service::{status_message, Service};
Expand Down Expand Up @@ -921,9 +923,195 @@ pub fn intent_validate(args: &super::intent::validate::IntentValidate) -> CliRes
let Some(session) = Service::open()? else {
return Ok(false);
};
// Evidence replay needs the manifest and checker on the service host; the
// handler owns the pins, the ordinary gate, and the post-checker freshness
// read. The local body remains the fallback when no service session exists.
if args.evidence_context || args.replay_evidence.is_some() {
return replay_evidence(&session, args);
}
validate_entity(&session, Kind::Intent, &args.id_or_path, args.json)
}

fn replay_evidence(
session: &Service,
args: &super::intent::validate::IntentValidate,
) -> CliResult<bool> {
let (manifest, manifest_base) = match &args.replay_evidence {
Some(path) => {
let bytes = intent_evidence::read_manifest(path).map_err(evidence_cli_error)?;
// Relative artifact roots must resolve against the manifest's
// directory on the service host, not the service process's cwd.
let absolute = std::path::absolute(path).map_err(CliError::Io)?;
let base = absolute.parent().unwrap_or_else(|| Path::new("."));
(bytes, base.display().to_string())
}
None => (Vec::new(), String::new()),
};
let request = pb::ReplayVaultEvidenceRequest {
repository: Some(session.reference.clone()),
kind: Kind::Intent as i32,
id: args.id_or_path.clone(),
evidence_context: true,
manifest,
manifest_base,
checker: args
.evidence_checker
.as_ref()
.map(|path| {
std::path::absolute(path)
.unwrap_or_else(|_| path.clone())
.display()
.to_string()
})
.unwrap_or_default(),
view: None,
};
let response = session
.replay_vault_evidence(request)
.map_err(validation_refusal)?;

let context = response
.evidence_context
.as_ref()
.map(evidence_context_json);
let replay = response.evidence_replay.as_ref().map(evidence_replay_json);
let mut results: Vec<serde_json::Value> = response
.issues
.iter()
.map(|message| serde_json::json!({ "message": message }))
.collect();
if let Some(report) = &response.evidence_replay {
for decision in &report.decisions {
if decision.decision != "supported" {
results.push(serde_json::json!({
"focus_node": decision.criterion_id,
"shape": "EvidenceReplay",
"path": "evidence",
"message": format!(
"{}: {} ({})",
decision.claim_type, decision.decision, decision.reason
),
}));
}
}
if report.freshness_changed {
let focus = response
.evidence_context
.as_ref()
.map(|context| context.intent_id.as_str())
.unwrap_or_default();
results.push(serde_json::json!({
"focus_node": focus,
"shape": "EvidenceReplayFreshness",
"path": serde_json::Value::Null,
"message": "intent substance or view chain changed during evidence replay",
}));
}
}
let conforms = response.valid;

if args.json {
let mut output = serde_json::json!({
"conforms": conforms,
"results": results,
});
if let Some(context) = context {
output["evidence_context"] = context;
}
if let Some(replay) = replay {
output["evidence_replay"] = replay;
}
println!("{}", serde_json::to_string_pretty(&output).unwrap());
} else {
if conforms {
println!("conforms: yes");
} else {
println!("conforms: no ({} violation(s))", results.len());
for result in &results {
if let Some(message) = result["message"].as_str() {
println!(" ✗ {message}");
}
}
}
if let Some(report) = &response.evidence_replay {
for decision in &report.decisions {
println!(
" evidence {}: {} ({})",
decision.claim_type, decision.decision, decision.reason
);
}
if report.freshness_changed {
println!(" evidence replay: intent or view chain changed during replay");
}
}
}

if conforms {
Ok(true)
} else {
Err(validation_failed(format!(
"intent does not conform ({} violation(s))",
results.len()
)))
}
}

/// Evidence refusals over the wire are user-fixable gate errors (exit 2), not
/// generic service refusals (exit 1).
fn validation_refusal(error: CliError) -> CliError {
match error {
CliError::ServiceRefusal { message } if message.contains("atomic:INVALID_ARGUMENT:") => {
validation_failed(message)
}
other => other,
}
}

fn evidence_cli_error(error: intent_evidence::EvidenceError) -> CliError {
match error {
intent_evidence::EvidenceError::Repository(error) => CliError::Repository(error),
intent_evidence::EvidenceError::Io(error) => CliError::Io(error),
other => validation_failed(other.to_string()),
}
}

fn evidence_context_json(context: &pb::EvidenceContext) -> serde_json::Value {
serde_json::json!({
"intent_id": context.intent_id,
"intent_substance_hash": context.intent_substance_hash,
"intent_source_hash": context.intent_source_hash,
"view_chain": context
.view_chain
.iter()
.map(|pin| serde_json::json!({
"name": pin.name,
"merkle": pin.merkle,
"scope": pin.scope,
}))
.collect::<Vec<_>>(),
})
}

fn evidence_replay_json(replay: &pb::EvidenceReplay) -> serde_json::Value {
serde_json::json!({
"schema_version": replay.schema_version,
"decisions": replay
.decisions
.iter()
.map(|decision| serde_json::json!({
"schema_version": decision.schema_version,
"request_digest": decision.request_digest,
"criterion_id": decision.criterion_id,
"claim_type": decision.claim_type,
"decision": decision.decision,
"reason": decision.reason,
"details": serde_json::from_str::<serde_json::Value>(&decision.details_json)
.unwrap_or(serde_json::Value::Null),
}))
.collect::<Vec<_>>(),
})
}

pub fn intent_verify(args: &super::intent::verify::IntentVerify) -> CliResult<bool> {
let Some(session) = Service::open()? else {
return Ok(false);
Expand Down
6 changes: 2 additions & 4 deletions atomic-cli/src/commands/vault/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,8 @@ impl Command for Context {
let md = render_md(&items);
if as_json {
println!("{}", render_json(&items, &md, self, limit));
} else {
if !md.is_empty() {
print!("{}", md);
}
} else if !md.is_empty() {
print!("{}", md);
}

Ok(())
Expand Down
Loading
Loading