aien-protocols-mv
Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem
Brought by drakestapleton
GitHub aien-dev/aien-protocols-mv#6 (code only)
Apply it
git checkout -b patch-a76e3776989c6a31 9e3d8ddd7681d29b5fa015a14f2db2cef8fa0bfb curl -fsSL https://interplane.io/drakestapleton/aien-protocols-mv/patches/a76e3776989c6a31.patch | git am
Provenance
github-import 1
aien-dev/aien-protocols-mv
6
e4c3e43421e67deec046a052be198ced987ca532
{"kind":"github-import","owner":"aien-dev","repo":"aien-protocols-mv","number":6,"url":"https://github.com/aien-dev/aien-protocols-mv/pull/6","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:46Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Cargo.lock b/Cargo.lock index 14a820c..1da2c0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -87,6 +87,25 @@ dependencies = [ "uuid", ] +[[package]] +name = "aien-probe" +version = "0.1.0" +dependencies = [ + "aien-evaluation-protocol", + "aien-protocol-types", + "async-trait", + "axum", + "hex", + "p256", + "reqwest", + "serde", + "serde_json", + "sha2 0.10.9", + "thiserror 1.0.69", + "tokio", + "uuid", +] + [[package]] name = "aien-protocol-types" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 846eed9..b24d8bf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "crates/aien-event-protocol", "crates/aien-evaluation-protocol", "crates/aien-provenance", + "crates/aien-probe", ] [workspace.package] diff --git a/crates/aien-probe/Cargo.toml b/crates/aien-probe/Cargo.toml new file mode 100644 index 0000000..5d59a33 --- /dev/null +++ b/crates/aien-probe/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "aien-probe" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Sovereign native probe evaluation engine for calibrated non-generative judgments over JSON state" + +[dependencies] +aien-protocol-types = { path = "../aien-protocol-types" } +aien-evaluation-protocol = { path = "../aien-evaluation-protocol" } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +hex = { workspace = true } +thiserror = { workspace = true } +async-trait = { workspace = true } +tokio = { workspace = true } +reqwest = { workspace = true } + +[dev-dependencies] +axum = "0.7" +p256 = { workspace = true } +uuid = { workspace = true } diff --git a/crates/aien-probe/README.md b/crates/aien-probe/README.md new file mode 100644 index 0000000..6f6f703 --- /dev/null +++ b/crates/aien-probe/README.md @@ -0,0 +1,70 @@ +# aien-probe + +Sovereign native probe evaluation engine for the AIEN platform. + +## What it is + +`aien-probe` implements a non-generative evaluation primitive. A caller supplies a JSON state and +a set of typed probes. Each probe asks one calibrated question about that state: + +- `Noul`: a yes or no question, answered by a calibrated probability. +- `Score`: a judgment on an ordered, described scale. +- `Choice`: a selection of one option out of a set. + +Every probe is evaluated against the same state. The answers come back calibrated, and the engine +is backend driven. + +## Why it exists + +This is the sovereign path. The engine runs inside the AIEN boundary with no external service, no +per token fee, and no state leaving the platform. It is AIEN's native implementation of the +calibrated probe idea, built to run on the local Grace Blackwell GB10 through the AIEN inference +service. + +## Backends + +| Backend | Network | Model | Use | +| --- | --- | --- | --- | +| `DeterministicReferenceBackend` | No | No | Offline conformance oracle for tests and continuous integration | +| `HttpProbeBackend` | Yes | GB10 service | Calibrated judgments on real content | + +`DeterministicReferenceBackend` derives a logit for every question from a SHA-256 feature hash of +the canonical state and the question label, then applies the same calibration math the device path +uses. Given the same state and probes it always returns the same answers. It is a reference oracle, +not a trained calibrator. + +`HttpProbeBackend` posts to `POST <endpoint>/v1/probe` and reads the calibrated answers back. On the +GB10 the service prefills the state into the paged KV cache once, forks one copy on write branch per +probe, and reads the distribution from a single forward step. + +## Usage + +```rust +use aien_probe::{ + Noul, Probe, ProbeEngine, ProbeSet, Score, DeterministicReferenceBackend, +}; +use serde_json::json; + +let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); +let probes = ProbeSet::new() + .with("telemetry", Probe::Noul(Noul::new("Does this patch add network telemetry?"))) + .with("quality", Probe::Score(Score::new( + "Rate the architectural quality.", + ["unacceptable", "needs_rework", "acceptable", "exemplary"], + ))); + +let response = engine.evaluate(&json!({"diff": "..."}), &probes).await?; +println!("telemetry probability {:.4}", response.noul("telemetry").unwrap().noul); +println!("quality score {:.2}", response.score("quality").unwrap().score); +``` + +## Evaluator protocol + +`ProbeEvaluator` implements the unified `Evaluator` trait from `aien-evaluation-protocol`, so a +probe set with gates drops straight into the `CanaryRollbackHarness`. Gates declare which answers +must hold for a subject to pass. A violated gate becomes a fatal finding and, in the harness, +triggers rollback. + +## License + +Apache-2.0. diff --git a/crates/aien-probe/src/backend.rs b/crates/aien-probe/src/backend.rs new file mode 100644 index 0000000..f848905 --- /dev/null +++ b/crates/aien-probe/src/backend.rs @@ -0,0 +1,304 @@ +//! Probe backends. +//! +//! A backend turns a state and a probe set into calibrated answers. Two backends ship here: a +//! deterministic in process reference oracle, and an HTTP client for an AIEN inference service. + +use crate::math; +use crate::{ + canonicalize, Answer, ChoiceAnswer, NoulAnswer, Probe, ProbeError, ProbeResponse, ProbeSet, + ScoreAnswer, +}; +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::cmp::Ordering; + +/// A source of calibrated probe answers. +#[async_trait] +pub trait ProbeBackend: Send + Sync { + /// A human readable name for the backend. + fn name(&self) -> &str; + + /// Evaluates every probe against the state. + async fn evaluate(&self, state: &Value, probes: &ProbeSet) + -> Result<ProbeResponse, ProbeError>; +} + +/// A deterministic, in process reference oracle. +/// +/// This backend runs no model and opens no socket. It derives a logit for every question from a +/// SHA-256 feature hash of the canonical state and the question label, then applies the same +/// calibration math the device path uses. Given the same state and probes it always returns the +/// same answers, which makes it the conformance oracle for tests and continuous integration. +/// +/// It is a reference oracle, not a trained calibrator. For calibrated judgments on real content, +/// point [`HttpProbeBackend`] at an AIEN inference service on the GB10. +pub struct DeterministicReferenceBackend { + temperature: f64, +} + +impl DeterministicReferenceBackend { + /// A reference oracle at the default temperature of one. + pub fn new() -> Self { + Self { temperature: 1.0 } + } + + /// A reference oracle at a chosen temperature. + pub fn with_temperature(temperature: f64) -> Self { + Self { temperature } + } + + /// The temperature in use. + pub fn temperature(&self) -> f64 { + self.temperature + } + + fn logit(seed: &[u8], label: &[u8], temperature: f64) -> f64 { + let mut hasher = Sha256::new(); + hasher.update(seed); + hasher.update([0u8]); + hasher.update(label); + let digest: [u8; 32] = hasher.finalize().into(); + let raw = u64::from_le_bytes(digest[..8].try_into().expect("eight bytes")); + let unit = (raw as f64) / ((u64::MAX as f64) + 1.0); + let centered = unit * 2.0 - 1.0; + math::temperature_scale(centered * 4.0, temperature) + } + + fn state_seed(state: &Value) -> Result<[u8; 32], ProbeError> { + let canonical = serde_json::to_vec(&canonicalize(state)) + .map_err(|e| ProbeError::Serialization(e.to_string()))?; + let mut hasher = Sha256::new(); + hasher.update(b"aien-probe-state-v1"); + hasher.update(canonical); + Ok(hasher.finalize().into()) + } + + fn probe_seed(state_seed: &[u8; 32], id: &str) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(state_seed); + hasher.update([0u8]); + hasher.update(id.as_bytes()); + hasher.finalize().into() + } + + fn answer_noul(&self, seed: &[u8; 32]) -> Answer { + let z_yes = Self::logit(seed, b"noul:yes", self.temperature); + let z_no = Self::logit(seed, b"noul:no", self.temperature); + Answer::Noul(NoulAnswer { + noul: math::sigmoid(z_yes - z_no), + }) + } + + fn answer_score(&self, seed: &[u8; 32], criteria: &[String]) -> Answer { + let logits: Vec<f64> = (0..criteria.len()) + .map(|level| { + let label = format!("score:{level}"); + Self::logit(seed, label.as_bytes(), self.temperature) + }) + .collect(); + let probabilities = math::softmax(&logits); + let score = math::expected_value(&probabilities); + let confidence = math::confidence(&probabilities); + let legend = criteria + .iter() + .enumerate() + .map(|(level, criterion)| (level as u32, criterion.clone())) + .collect(); + let by_level = probabilities + .iter() + .enumerate() + .map(|(level, probability)| (level as u32, *probability)) + .collect(); + Answer::Score(ScoreAnswer { + score, + confidence, + legend, + probabilities: by_level, + }) + } + + fn answer_choice(&self, seed: &[u8; 32], options: &[crate::ChoiceOption]) -> Answer { + let logits: Vec<f64> = options + .iter() + .map(|option| { + let label = format!("choice:{}", option.id); + Self::logit(seed, label.as_bytes(), self.temperature) + }) + .collect(); + let probabilities = math::softmax(&logits); + let confidence = math::confidence(&probabilities); + let best = probabilities + .iter() + .enumerate() + .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(Ordering::Equal)) + .map(|(index, _)| index) + .unwrap_or(0); + let choice = options + .get(best) + .map(|option| option.id.clone()) + .unwrap_or_default(); + let by_option = options + .iter() + .enumerate() + .map(|(index, option)| (option.id.clone(), probabilities[index])) + .collect(); + Answer::Choice(ChoiceAnswer { + choice, + confidence, + probabilities: by_option, + }) + } +} + +impl Default for DeterministicReferenceBackend { + fn default() -> Self { + Self::new() + } +} + +#[async_trait] +impl ProbeBackend for DeterministicReferenceBackend { + fn name(&self) -> &str { + "deterministic-reference-oracle" + } + + async fn evaluate( + &self, + state: &Value, + probes: &ProbeSet, + ) -> Result<ProbeResponse, ProbeError> { + let state_seed = Self::state_seed(state)?; + let mut answers = Vec::with_capacity(probes.len()); + + for (id, probe) in probes.iter() { + let seed = Self::probe_seed(&state_seed, id); + let answer = match probe { + Probe::Noul(_) => self.answer_noul(&seed), + Probe::Score(score) => self.answer_score(&seed, &score.criteria), + Probe::Choice(choice) => self.answer_choice(&seed, &choice.options), + }; + answers.push((id.clone(), answer)); + } + + Ok(ProbeResponse { + model: self.name().to_string(), + answers, + latency_micros: 0, + }) + } +} + +/// Wire request for the AIEN probe endpoint. +#[derive(Serialize)] +struct WireRequest<'a> { + state: &'a Value, + probes: &'a ProbeSet, +} + +/// Wire response from the AIEN probe endpoint. +#[derive(Deserialize)] +struct WireResponse { + #[serde(default)] + model: String, + answers: Vec<(String, Answer)>, +} + +/// An HTTP client for an AIEN inference service that taps logits on the device. +/// +/// The service exposes `POST <endpoint>/v1/probe` taking `{ "state": ..., "probes": ... }` and +/// returning `{ "model": ..., "answers": [[id, answer], ...] }`. On the GB10 the service prefills +/// the state into the paged KV cache once, forks one copy on write branch per probe, and reads +/// the calibrated distribution from a single forward step. +pub struct HttpProbeBackend { + client: reqwest::Client, + endpoint: String, + model: String, +} + +impl HttpProbeBackend { + /// Builds a backend for an endpoint and model name. + pub fn with_endpoint(endpoint: impl Into<String>, model: impl Into<String>) -> Self { + Self { + client: reqwest::Client::new(), + endpoint: endpoint.into(), + model: model.into(), + } + } + + /// Builds a backend for an endpoint with the default model name. + pub fn new(endpoint: impl Into<String>) -> Self { + Self::with_endpoint(endpoint, "aien-sovereign-probe") + } + + /// Builds a backend from `AIEN_PROBE_ENDPOINT` and `AIEN_PROBE_MODEL`. + pub fn from_env() -> Result<Self, ProbeError> { + let endpoint = std::env::var("AIEN_PROBE_ENDPOINT") + .map_err(|_| ProbeError::Evaluation("AIEN_PROBE_ENDPOINT is not set".to_string()))?; + let model = std::env::var("AIEN_PROBE_MODEL") + .unwrap_or_else(|_| "aien-sovereign-probe".to_string()); + Ok(Self::with_endpoint(endpoint, model)) + } + + /// The endpoint in use. + pub fn endpoint(&self) -> &str { + &self.endpoint + } + + fn probe_url(&self) -> String { + format!("{}/v1/probe", self.endpoint.trim_end_matches('/')) + } +} + +#[async_trait] +impl ProbeBackend for HttpProbeBackend { + fn name(&self) -> &str { + "aien-http-probe" + } + + async fn evaluate( + &self, + state: &Value, + probes: &ProbeSet, + ) -> Result<ProbeResponse, ProbeError> { + let body = WireRequest { state, probes }; + let response = self + .client + .post(self.probe_url()) + .json(&body) + .send() + .await + .map_err(|e| ProbeError::Transport(e.to_string()))?; + + let status = response.status(); + let text = response + .text() + .await + .map_err(|e| ProbeError::Transport(e.to_string()))?; + + if !status.is_success() { + return Err(ProbeError::Status { + status: status.as_u16(), + body: text.chars().take(400).collect(), + }); + } + + let parsed: WireResponse = serde_json::from_str(&text).map_err(|e| { + ProbeError::Malformed(format!( + "{e}; body: {}", + text.chars().take(200).collect::<String>() + )) + })?; + + Ok(ProbeResponse { + model: if parsed.model.is_empty() { + self.model.clone() + } else { + parsed.model + }, + answers: parsed.answers, + latency_micros: 0, + }) + } +} diff --git a/crates/aien-probe/src/evaluator.rs b/crates/aien-probe/src/evaluator.rs new file mode 100644 index 0000000..059a1ed --- /dev/null +++ b/crates/aien-probe/src/evaluator.rs @@ -0,0 +1,231 @@ +//! Adapter that plugs the probe engine into the unified Evaluator protocol. +//! +//! A [`ProbeEvaluator`] runs a [`ProbeSet`] over the evaluation subject and turns the calibrated +//! answers into an [`EvaluatorOutcome`]. Gates declare which answers must hold for the subject to +//! pass, so a [`ProbeEvaluator`] drops straight into the [`CanaryRollbackHarness`]. +//! +//! [`CanaryRollbackHarness`]: aien_evaluation_protocol::CanaryRollbackHarness + +use crate::{Answer, ProbeBackend, ProbeEngine, ProbeSet}; +use aien_evaluation_protocol::{ + EvaluationError, EvaluationPlan, Evaluator, EvaluatorDescriptor, EvaluatorIdentity, + EvaluatorOutcome, EvaluatorStatus, Finding, Measurement, +}; +use aien_protocol_types::{ArtifactRef, Digest32}; +use async_trait::async_trait; +use serde_json::json; +use std::sync::Arc; + +/// A requirement an answer must satisfy for the subject to pass. +#[derive(Clone, Debug)] +pub enum ProbeGate { + /// A [`Noul`](crate::Noul) probe whose probability must reach a minimum. + Noul { id: String, min: f64 }, + /// A [`Score`](crate::Score) probe whose position must reach a minimum. + Score { id: String, min: f64 }, + /// A [`Choice`](crate::Choice) probe whose selection must be in a set. + Choice { id: String, allowed: Vec<String> }, +} + +impl ProbeGate { + /// A noul gate. + pub fn noul(id: impl Into<String>, min: f64) -> Self { + Self::Noul { id: id.into(), min } + } + + /// A score gate. + pub fn score(id: impl Into<String>, min: f64) -> Self { + Self::Score { id: id.into(), min } + } + + /// A choice gate. + pub fn choice<I, S>(id: impl Into<String>, allowed: I) -> Self + where + I: IntoIterator<Item = S>, + S: Into<String>, + { + Self::Choice { + id: id.into(), + allowed: allowed.into_iter().map(Into::into).collect(), + } + } +} + +/// Configuration for a [`ProbeEvaluator`]. +#[derive(Clone, Debug, Default)] +pub struct ProbeEvaluatorConfig { + /// The gates a subject must satisfy. + pub gates: Vec<ProbeGate>, +} + +impl ProbeEvaluatorConfig { + /// A configuration with no gates. + pub fn new() -> Self { + Self { gates: Vec::new() } + } + + /// Adds a gate. + pub fn with_gate(mut self, gate: ProbeGate) -> Self { + self.gates.push(gate); + self + } +} + +/// An [`Evaluator`] backed by the sovereign probe engine. +pub struct ProbeEvaluator<B: ProbeBackend + 'static> { + engine: Arc<ProbeEngine<B>>, + probes: ProbeSet, + config: ProbeEvaluatorConfig, + descriptor: EvaluatorDescriptor, +} + +impl<B: ProbeBackend + 'static> ProbeEvaluator<B> { + /// Builds an evaluator over an engine, a probe set, and a gate configuration. + pub fn new(engine: ProbeEngine<B>, probes: ProbeSet, config: ProbeEvaluatorConfig) -> Self { + Self { + engine: Arc::new(engine), + probes, + config, + descriptor: EvaluatorDescriptor { + evaluator_id: "aien-sovereign-probe".to_string(), + version: "0.1.0".to_string(), + required: true, + }, + } + } + + /// Overrides the evaluator descriptor. + pub fn with_descriptor(mut self, descriptor: EvaluatorDescriptor) -> Self { + self.descriptor = descriptor; + self + } + + /// The probe set the evaluator runs. + pub fn probes(&self) -> &ProbeSet { + &self.probes + } +} + +#[async_trait] +impl<B: ProbeBackend + 'static> Evaluator for ProbeEvaluator<B> { + fn descriptor(&self) -> EvaluatorDescriptor { + self.descriptor.clone() + } + + async fn evaluate( + &self, + plan: &EvaluationPlan, + subject: &ArtifactRef, + ) -> Result<EvaluatorOutcome, EvaluationError> { + let state = json!({ + "evaluation_id": plan.evaluation_id.0.to_string(), + "profile": plan.profile, + "sandbox_profile": plan.sandbox_profile, + "subject": { + "artifact_id": subject.artifact_id.to_string(), + "media_type": subject.media_type, + "byte_size": subject.byte_size, + "digest": hex::encode(subject.digest.0), + } + }); + + let response = self + .engine + .evaluate(&state, &self.probes) + .await + .map_err(|e| EvaluationError::ExecutionFailed(format!("probe engine failure: {e}")))?; + + let mut findings = Vec::new(); + let mut measurements = Vec::new(); + + for (id, answer) in &response.answers { + match answer { + Answer::Noul(noul) => measurements.push(Measurement { + metric: format!("probe_noul_{id}"), + value: noul.noul, + unit: "ratio".to_string(), + }), + Answer::Score(score) => measurements.push(Measurement { + metric: format!("probe_score_{id}"), + value: score.score, + unit: "points".to_string(), + }), + Answer::Choice(choice) => measurements.push(Measurement { + metric: format!("probe_choice_confidence_{id}"), + value: choice.confidence, + unit: "ratio".to_string(), + }), + } + } + + for gate in &self.config.gates { + match gate { + ProbeGate::Noul { id, min } => { + let value = response.noul(id).map(|answer| answer.noul).unwrap_or(0.0); + if value < *min { + findings.push(Finding { + severity: "fatal".to_string(), + rule_id: format!("probe:noul:{id}"), + message: format!( + "noul probe {id} returned {value:.4}, below required {min:.4}" + ), + location: None, + }); + } + } + ProbeGate::Score { id, min } => { + let value = response.score(id).map(|answer| answer.score).unwrap_or(0.0); + if value < *min { + findings.push(Finding { + severity: "fatal".to_string(), + rule_id: format!("probe:score:{id}"), + message: format!( + "score probe {id} returned {value:.4}, below required {min:.4}" + ), + location: None, + }); + } + } + ProbeGate::Choice { id, allowed } => { + let chosen = response + .choice(id) + .map(|answer| answer.choice.clone()) + .unwrap_or_default(); + if !allowed.contains(&chosen) { + findings.push(Finding { + severity: "fatal".to_string(), + rule_id: format!("probe:choice:{id}"), + message: format!( + "choice probe {id} selected {chosen}, which is not in the allowed set" + ), + location: None, + }); + } + } + } + } + + let status = if findings.is_empty() { + EvaluatorStatus::Passed + } else { + EvaluatorStatus::Failed + }; + + let mut outcome = EvaluatorOutcome { + evaluator: EvaluatorIdentity { + evaluator_id: self.descriptor.evaluator_id.clone(), + version: self.descriptor.version.clone(), + binary_digest: Digest32([0u8; 32]), + config_digest: Digest32([0u8; 32]), + }, + status, + findings, + measurements, + evidence: vec![subject.clone()], + execution_digest: Digest32([0u8; 32]), + }; + outcome.execution_digest = outcome.compute_execution_digest(); + + Ok(outcome) + } +} diff --git a/crates/aien-probe/src/lib.rs b/crates/aien-probe/src/lib.rs new file mode 100644 index 0000000..7324bd3 --- /dev/null +++ b/crates/aien-probe/src/lib.rs @@ -0,0 +1,385 @@ +//! Sovereign native probe evaluation engine. +//! +//! This crate implements AIEN's native, non-generative evaluation primitive. A caller supplies +//! a JSON state and a set of typed probes. Each probe asks one calibrated question about that +//! state: a yes or no probability ([`Noul`]), a position on an ordered scale ([`Score`]), or one +//! option out of a set ([`Choice`]). Every probe is evaluated against the same state, and the +//! answers come back calibrated. +//! +//! The engine is backend driven: +//! +//! * [`DeterministicReferenceBackend`] runs entirely in process with no network and no model. +//! It is the offline oracle for conformance tests and continuous integration. +//! * [`HttpProbeBackend`] targets an AIEN inference service that taps logits at a single forward +//! boundary on the local Grace Blackwell GB10. +//! +//! This is the sovereign path: no external service, no per token fee, and no state leaving the +//! AIEN boundary. The engine plugs into the unified Evaluator protocol through +//! [`ProbeEvaluator`]. + +pub mod backend; +pub mod evaluator; +pub mod math; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::collections::BTreeMap; +use std::time::Instant; + +pub use backend::{DeterministicReferenceBackend, HttpProbeBackend, ProbeBackend}; +pub use evaluator::{ProbeEvaluator, ProbeEvaluatorConfig, ProbeGate}; + +/// Error type for probe evaluation. +#[derive(thiserror::Error, Debug)] +pub enum ProbeError { + #[error("probe serialization failed: {0}")] + Serialization(String), + #[error("probe backend transport failed: {0}")] + Transport(String), + #[error("probe backend returned status {status}: {body}")] + Status { status: u16, body: String }, + #[error("probe backend returned a malformed response: {0}")] + Malformed(String), + #[error("probe evaluation failed: {0}")] + Evaluation(String), +} + +/// A typed question about a JSON state. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum Probe { + /// A yes or no question answered by a calibrated probability. + Noul(Noul), + /// A judgment on an ordered, described scale. + Score(Score), + /// A selection of one option out of a set. + Choice(Choice), +} + +/// A yes or no question. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Noul { + /// What the question asks. + pub instructions: String, + /// An optional description of what a yes means. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub yes: Option<String>, + /// An optional description of what a no means. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub no: Option<String>, +} + +impl Noul { + /// A yes or no question with instructions only. + pub fn new(instructions: impl Into<String>) -> Self { + Self { + instructions: instructions.into(), + yes: None, + no: None, + } + } + + /// Adds a description of what a yes means. + pub fn with_yes(mut self, yes: impl Into<String>) -> Self { + self.yes = Some(yes.into()); + self + } + + /// Adds a description of what a no means. + pub fn with_no(mut self, no: impl Into<String>) -> Self { + self.no = Some(no.into()); + self + } +} + +/// A judgment on an ordered scale, one criterion per level. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Score { + /// What the question asks. + pub instructions: String, + /// The levels of the scale in order, lowest first. + pub criteria: Vec<String>, +} + +impl Score { + /// A score question with an ordered list of criteria. + pub fn new<I, S>(instructions: impl Into<String>, criteria: I) -> Self + where + I: IntoIterator<Item = S>, + S: Into<String>, + { + Self { + instructions: instructions.into(), + criteria: criteria.into_iter().map(Into::into).collect(), + } + } +} + +/// A selection of one option out of a set. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Choice { + /// What the question asks. + pub instructions: String, + /// The options to choose from. + pub options: Vec<ChoiceOption>, +} + +impl Choice { + /// A choice question over a list of options. + pub fn new<I>(instructions: impl Into<String>, options: I) -> Self + where + I: IntoIterator<Item = ChoiceOption>, + { + Self { + instructions: instructions.into(), + options: options.into_iter().collect(), + } + } +} + +/// One option of a choice question. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ChoiceOption { + /// The stable identifier of the option. + pub id: String, + /// An optional description of the option. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option<String>, +} + +impl ChoiceOption { + /// An option with an identifier only. + pub fn new(id: impl Into<String>) -> Self { + Self { + id: id.into(), + description: None, + } + } + + /// Adds a description to the option. + pub fn with_description(mut self, description: impl Into<String>) -> Self { + self.description = Some(description.into()); + self + } +} + +/// The answer to one probe, of the type the probe had. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum Answer { + /// The answer to a [`Noul`]. + Noul(NoulAnswer), + /// The answer to a [`Score`]. + Score(ScoreAnswer), + /// The answer to a [`Choice`]. + Choice(ChoiceAnswer), +} + +/// The answer to a yes or no question. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct NoulAnswer { + /// The calibrated probability that the answer is yes, from zero to one. + pub noul: f64, +} + +/// The answer to a score question. +#[derive(Clone, Debug, PartialEq, Serialize)] +pub struct ScoreAnswer { + /// The probability weighted position on the scale. + pub score: f64, + /// How concentrated the distribution is, from zero to one. + pub confidence: f64, + /// Each level and the criterion the question gave it. + pub legend: BTreeMap<u32, String>, + /// Each level and its probability. + pub probabilities: BTreeMap<u32, f64>, +} + +impl<'de> Deserialize<'de> for ScoreAnswer { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: serde::Deserializer<'de>, + { + #[derive(Deserialize)] + struct Raw { + score: f64, + confidence: f64, + legend: BTreeMap<String, String>, + probabilities: BTreeMap<String, f64>, + } + + fn by_level<T, E>(map: BTreeMap<String, T>, field: &str) -> Result<BTreeMap<u32, T>, E> + where + E: serde::de::Error, + { + map.into_iter() + .map(|(level, value)| match level.parse::<u32>() { + Ok(level) => Ok((level, value)), + Err(_) => Err(E::custom(format!( + "{field} has the key {level}, which is not a level number" + ))), + }) + .collect() + } + + let raw = Raw::deserialize(deserializer)?; + Ok(ScoreAnswer { + score: raw.score, + confidence: raw.confidence, + legend: by_level(raw.legend, "legend")?, + probabilities: by_level(raw.probabilities, "probabilities")?, + }) + } +} + +/// The answer to a choice question. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ChoiceAnswer { + /// The option with the highest probability. + pub choice: String, + /// How concentrated the distribution is, from zero to one. + pub confidence: f64, + /// Every option and its probability. + pub probabilities: BTreeMap<String, f64>, +} + +/// An ordered set of probes keyed by identifier. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct ProbeSet { + entries: Vec<(String, Probe)>, +} + +impl ProbeSet { + /// An empty probe set. + pub fn new() -> Self { + Self { + entries: Vec::new(), + } + } + + /// Adds a probe under an identifier, in builder style. + pub fn with(mut self, id: impl Into<String>, probe: Probe) -> Self { + self.entries.push((id.into(), probe)); + self + } + + /// Adds a probe under an identifier. + pub fn insert(&mut self, id: impl Into<String>, probe: Probe) { + self.entries.push((id.into(), probe)); + } + + /// The probe under an identifier. + pub fn get(&self, id: &str) -> Option<&Probe> { + self.entries + .iter() + .find(|(key, _)| key == id) + .map(|(_, probe)| probe) + } + + /// The number of probes. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Whether the set is empty. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Iterates over the probes in insertion order. + pub fn iter(&self) -> impl Iterator<Item = (&String, &Probe)> { + self.entries.iter().map(|(key, probe)| (key, probe)) + } +} + +/// The answers to one probe request. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct ProbeResponse { + /// The model or backend that produced the answers. + pub model: String, + /// One answer per probe, in request order. + pub answers: Vec<(String, Answer)>, + /// Wall clock time the evaluation took, in microseconds. + #[serde(default)] + pub latency_micros: u64, +} + +impl ProbeResponse { + /// The answer under an identifier. + pub fn answer(&self, id: &str) -> Option<&Answer> { + self.answers + .iter() + .find(|(key, _)| key == id) + .map(|(_, answer)| answer) + } + + /// The answer under an identifier, if it answers a [`Noul`]. + pub fn noul(&self, id: &str) -> Option<&NoulAnswer> { + match self.answer(id)? { + Answer::Noul(answer) => Some(answer), + _ => None, + } + } + + /// The answer under an identifier, if it answers a [`Score`]. + pub fn score(&self, id: &str) -> Option<&ScoreAnswer> { + match self.answer(id)? { + Answer::Score(answer) => Some(answer), + _ => None, + } + } + + /// The answer under an identifier, if it answers a [`Choice`]. + pub fn choice(&self, id: &str) -> Option<&ChoiceAnswer> { + match self.answer(id)? { + Answer::Choice(answer) => Some(answer), + _ => None, + } + } +} + +/// Runs a [`ProbeBackend`] over a state and a probe set. +pub struct ProbeEngine<B: ProbeBackend> { + backend: B, +} + +impl<B: ProbeBackend> ProbeEngine<B> { + /// Builds an engine over a backend. + pub fn new(backend: B) -> Self { + Self { backend } + } + + /// The backend the engine runs. + pub fn backend(&self) -> &B { + &self.backend + } + + /// Evaluates every probe against the state and returns the calibrated answers. + pub async fn evaluate( + &self, + state: &Value, + probes: &ProbeSet, + ) -> Result<ProbeResponse, ProbeError> { + let started = Instant::now(); + let mut response = self.backend.evaluate(state, probes).await?; + response.latency_micros = started.elapsed().as_micros() as u64; + Ok(response) + } +} + +/// Recursively orders object keys so the serialized form of a state is byte stable. +pub(crate) fn canonicalize(value: &Value) -> Value { + match value { + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + let mut out = serde_json::Map::new(); + for key in keys { + out.insert(key.clone(), canonicalize(&map[key])); + } + Value::Object(out) + } + Value::Array(items) => Value::Array(items.iter().map(canonicalize).collect()), + other => other.clone(), + } +} diff --git a/crates/aien-probe/src/math.rs b/crates/aien-probe/src/math.rs new file mode 100644 index 0000000..a1a8f04 --- /dev/null +++ b/crates/aien-probe/src/math.rs @@ -0,0 +1,128 @@ +//! Calibration primitives for the probe engine. +//! +//! These functions mirror the semantics of the Mojo SIMD helpers on the Grace Blackwell GB10 +//! path (temperature scaling, entropy, projection) in plain Rust, so the engine stays +//! deterministic and testable without a device. + +/// Scales a logit by a temperature. +/// +/// A non positive or non finite temperature leaves the logit unchanged, matching the Mojo +/// `temperature_scale` contract. A non finite logit collapses to zero. +pub fn temperature_scale(logit: f64, temperature: f64) -> f64 { + if !logit.is_finite() { + return 0.0; + } + if !temperature.is_finite() || temperature <= 1.0e-4 { + return logit; + } + let scaled = logit / temperature; + if scaled.is_finite() { + scaled + } else { + logit + } +} + +/// Numerically stable logistic function. +pub fn sigmoid(z: f64) -> f64 { + if z.is_nan() { + return 0.0; + } + if z >= 0.0 { + 1.0 / (1.0 + (-z).exp()) + } else { + let e = z.exp(); + e / (1.0 + e) + } +} + +/// Numerically stable softmax over a slice of logits. +/// +/// An empty slice yields an empty vector. A degenerate sum yields a uniform distribution. +pub fn softmax(logits: &[f64]) -> Vec<f64> { + if logits.is_empty() { + return Vec::new(); + } + let max = logits.iter().cloned().fold(f64::NEG_INFINITY, f64::max); + let exps: Vec<f64> = logits.iter().map(|l| (l - max).exp()).collect(); + let sum: f64 = exps.iter().sum(); + if !sum.is_finite() || sum <= 0.0 { + let uniform = 1.0 / logits.len() as f64; + return vec![uniform; logits.len()]; + } + exps.iter().map(|e| e / sum).collect() +} + +/// Probability weighted mean of the level indices, a position on the ordered scale. +pub fn expected_value(probabilities: &[f64]) -> f64 { + probabilities + .iter() + .enumerate() + .map(|(level, p)| level as f64 * p) + .sum() +} + +/// Shannon entropy of a probability distribution in nats. +pub fn entropy(probabilities: &[f64]) -> f64 { + probabilities + .iter() + .filter(|p| **p > 1.0e-12) + .map(|p| -p * p.ln()) + .sum() +} + +/// Confidence in a distribution: one minus entropy normalized by the uniform maximum. +pub fn confidence(probabilities: &[f64]) -> f64 { + let n = probabilities.len(); + if n <= 1 { + return 1.0; + } + let max_entropy = (n as f64).ln(); + if max_entropy <= 0.0 { + return 1.0; + } + (1.0 - entropy(probabilities) / max_entropy).clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_temperature_scale_edges() { + assert_eq!(temperature_scale(2.0, 0.5), 4.0); + assert_eq!(temperature_scale(5.0, 0.0), 5.0); + assert_eq!(temperature_scale(5.0, 0.00005), 5.0); + assert_eq!(temperature_scale(f64::NAN, 1.0), 0.0); + assert_eq!(temperature_scale(2.0, f64::INFINITY), 2.0); + } + + #[test] + fn test_sigmoid_symmetry() { + assert!((sigmoid(0.0) - 0.5).abs() < 1.0e-12); + assert!((sigmoid(1.0) + sigmoid(-1.0) - 1.0).abs() < 1.0e-12); + assert!(sigmoid(50.0) > 0.999); + assert!(sigmoid(-50.0) < 0.001); + } + + #[test] + fn test_softmax_sums_to_one() { + let probs = softmax(&[1.0, 2.0, 3.0, 4.0]); + let sum: f64 = probs.iter().sum(); + assert!((sum - 1.0).abs() < 1.0e-12); + assert!(softmax(&[]).is_empty()); + let uniform = softmax(&[0.0, 0.0, 0.0, 0.0]); + for p in uniform { + assert!((p - 0.25).abs() < 1.0e-12); + } + } + + #[test] + fn test_expected_value_and_confidence() { + let probs = vec![0.0, 0.0, 0.0, 1.0]; + assert!((expected_value(&probs) - 3.0).abs() < 1.0e-12); + assert!((confidence(&probs) - 1.0).abs() < 1.0e-12); + let flat = vec![0.25, 0.25, 0.25, 0.25]; + assert!((confidence(&flat)).abs() < 1.0e-12); + } +} diff --git a/crates/aien-probe/tests/probe_engine_tests.rs b/crates/aien-probe/tests/probe_engine_tests.rs new file mode 100644 index 0000000..4d83dcb --- /dev/null +++ b/crates/aien-probe/tests/probe_engine_tests.rs @@ -0,0 +1,355 @@ +use aien_evaluation_protocol::{ + CanaryRollbackHarness, EvaluationPlan, Evaluator, EvaluatorStatus, SoftwareP256Signer, Verdict, + VerifierIdentity, VerifierSigner, +}; +use aien_probe::{ + Choice, ChoiceOption, DeterministicReferenceBackend, HttpProbeBackend, Noul, Probe, + ProbeBackend, ProbeEngine, ProbeEvaluator, ProbeEvaluatorConfig, ProbeGate, ProbeSet, Score, +}; +use aien_protocol_types::{ArtifactRef, Digest32, EvaluationId, Timestamp}; +use p256::ecdsa::SigningKey; +use serde_json::json; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +fn sample_state() -> serde_json::Value { + json!({ + "diff": "fn add(a: i32, b: i32) -> i32 { a + b }", + "author": "contributor", + "files": ["src/lib.rs"], + }) +} + +fn sample_probes() -> ProbeSet { + ProbeSet::new() + .with( + "telemetry", + Probe::Noul(Noul::new( + "Does this patch introduce covert network telemetry?", + )), + ) + .with( + "quality", + Probe::Score(Score::new( + "Rate the architectural quality.", + ["unacceptable", "needs_rework", "acceptable", "exemplary"], + )), + ) + .with( + "severity", + Probe::Choice(Choice::new( + "Classify the finding.", + [ + ChoiceOption::new("clean").with_description("No issue"), + ChoiceOption::new("advisory").with_description("Minor note"), + ChoiceOption::new("critical").with_description("Blocks merge"), + ], + )), + ) +} + +#[tokio::test] +async fn test_deterministic_backend_is_reproducible() { + let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); + let probes = sample_probes(); + + let first = engine.evaluate(&sample_state(), &probes).await.unwrap(); + let second = engine.evaluate(&sample_state(), &probes).await.unwrap(); + + assert_eq!(first.answers, second.answers); + assert_eq!(first.model, "deterministic-reference-oracle"); + assert_eq!(first.answers.len(), 3); +} + +#[tokio::test] +async fn test_deterministic_backend_varies_with_state() { + let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); + let probes = sample_probes(); + + let a = engine + .evaluate(&json!({"diff": "alpha"}), &probes) + .await + .unwrap(); + let b = engine + .evaluate(&json!({"diff": "omega"}), &probes) + .await + .unwrap(); + + let a_noul = a.noul("telemetry").unwrap().noul; + let b_noul = b.noul("telemetry").unwrap().noul; + assert!((a_noul - b_noul).abs() > 1.0e-6); +} + +#[tokio::test] +async fn test_answer_ranges_and_distributions() { + let engine = ProbeEngine::new(DeterministicReferenceBackend::new()); + let probes = sample_probes(); + let response = engine.evaluate(&sample_state(), &probes).await.unwrap(); + + let noul = response.noul("telemetry").unwrap().noul; + assert!((0.0..=1.0).contains(&noul)); + + let score = response.score("quality").unwrap(); + let sum: f64 = score.probabilities.values().sum(); + assert!((sum - 1.0).abs() < 1.0e-9); + assert_eq!(score.legend.len(), 4); + let weighted: f64 = score + .probabilities + .iter() + .map(|(level, probability)| *level as f64 * probability) + .sum(); + assert!((weighted - score.score).abs() < 1.0e-9); + assert!((0.0..=1.0).contains(&score.confidence)); + + let choice = response.choice("severity").unwrap(); + let best = choice + .probabilities + .iter() + .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()) + .map(|(id, _)| id.clone()) + .unwrap(); + assert_eq!(choice.choice, best); +} + +#[tokio::test] +async fn test_probe_evaluator_gates_pass() { + let backend = DeterministicReferenceBackend::new(); + let config = ProbeEvaluatorConfig::new(); + let evaluator = ProbeEvaluator::new(ProbeEngine::new(backend), sample_probes(), config); + + let subject = ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([1u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 4096, + }; + let plan = build_plan(&evaluator, subject.clone()); + + let outcome = evaluator.evaluate(&plan, &subject).await.unwrap(); + assert_eq!(outcome.status, EvaluatorStatus::Passed); + assert!(outcome.findings.is_empty()); + assert_eq!(outcome.measurements.len(), 3); + assert_ne!(outcome.execution_digest, Digest32([0u8; 32])); +} + +#[tokio::test] +async fn test_probe_evaluator_gate_fails_closed() { + let backend = DeterministicReferenceBackend::new(); + let config = ProbeEvaluatorConfig::new() + .with_gate(ProbeGate::noul("telemetry", 0.999999)) + .with_gate(ProbeGate::score("quality", 3.999999)) + .with_gate(ProbeGate::choice("severity", ["clean"])); + let evaluator = ProbeEvaluator::new(ProbeEngine::new(backend), sample_probes(), config); + + let subject = ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([2u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 2048, + }; + let plan = build_plan(&evaluator, subject.clone()); + + let outcome = evaluator.evaluate(&plan, &subject).await.unwrap(); + assert_eq!(outcome.status, EvaluatorStatus::Failed); + assert!(outcome + .findings + .iter() + .any(|f| f.rule_id == "probe:noul:telemetry")); + assert!(outcome + .findings + .iter() + .any(|f| f.rule_id == "probe:score:quality")); +} + +#[tokio::test] +async fn test_probe_evaluator_plugs_into_canary_harness() { + let backend = DeterministicReferenceBackend::new(); + let evaluator = ProbeEvaluator::new( + ProbeEngine::new(backend), + sample_probes(), + ProbeEvaluatorConfig::new(), + ); + let descriptor = evaluator.descriptor(); + + let signing_key = SigningKey::from_slice(&[42u8; 32]).unwrap(); + let signer = Arc::new(SoftwareP256Signer::new(signing_key)); + let verifier = VerifierIdentity { + principal_id: "canary-daemon".to_string(), + key_id: signer.key_fingerprint(), + trust_epoch: 1, + trusted_build_digest: Digest32([10u8; 32]), + policy_bundle_digest: Digest32([11u8; 32]), + }; + let harness = CanaryRollbackHarness::new(verifier, signer); + + let subject = ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([12u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 8192, + }; + let mut plan = EvaluationPlan { + evaluation_id: EvaluationId(uuid::Uuid::new_v4()), + subject: subject.clone(), + profile: "canary".to_string(), + evaluators: vec![descriptor], + baseline: None, + sandbox_profile: "default".to_string(), + policy_digest: Digest32([13u8; 32]), + evaluator_manifest_digest: Digest32([14u8; 32]), + plan_digest: Digest32([0u8; 32]), + }; + plan.plan_digest = plan.compute_plan_digest(); + + let rollback = Arc::new(AtomicBool::new(false)); + let rollback_flag = rollback.clone(); + let evaluators: Vec<Box<dyn Evaluator>> = vec![Box::new(evaluator)]; + + let (receipt, outcomes) = harness + .evaluate_and_enforce( + &plan, + &subject, + &evaluators, + Timestamp(1000), + || async move { + rollback_flag.store(true, Ordering::SeqCst); + Ok(()) + }, + ) + .await + .unwrap(); + + assert_eq!(receipt.receipt.verdict, Verdict::Pass); + assert_eq!(outcomes[0].status, EvaluatorStatus::Passed); + assert!(!rollback.load(Ordering::SeqCst)); +} + +#[tokio::test] +async fn test_probe_evaluator_triggers_rollback_on_gate_failure() { + let backend = DeterministicReferenceBackend::new(); + let evaluator = ProbeEvaluator::new( + ProbeEngine::new(backend), + sample_probes(), + ProbeEvaluatorConfig::new().with_gate(ProbeGate::noul("telemetry", 0.999999)), + ); + let descriptor = evaluator.descriptor(); + + let signing_key = SigningKey::from_slice(&[7u8; 32]).unwrap(); + let signer = Arc::new(SoftwareP256Signer::new(signing_key)); + let verifier = VerifierIdentity { + principal_id: "canary-daemon".to_string(), + key_id: signer.key_fingerprint(), + trust_epoch: 1, + trusted_build_digest: Digest32([20u8; 32]), + policy_bundle_digest: Digest32([21u8; 32]), + }; + let harness = CanaryRollbackHarness::new(verifier, signer); + + let subject = ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([22u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 512, + }; + let mut plan = EvaluationPlan { + evaluation_id: EvaluationId(uuid::Uuid::new_v4()), + subject: subject.clone(), + profile: "canary".to_string(), + evaluators: vec![descriptor], + baseline: None, + sandbox_profile: "default".to_string(), + policy_digest: Digest32([23u8; 32]), + evaluator_manifest_digest: Digest32([24u8; 32]), + plan_digest: Digest32([0u8; 32]), + }; + plan.plan_digest = plan.compute_plan_digest(); + + let rollback = Arc::new(AtomicBool::new(false)); + let rollback_flag = rollback.clone(); + let evaluators: Vec<Box<dyn Evaluator>> = vec![Box::new(evaluator)]; + + let (receipt, outcomes) = harness + .evaluate_and_enforce( + &plan, + &subject, + &evaluators, + Timestamp(2000), + || async move { + rollback_flag.store(true, Ordering::SeqCst); + Ok(()) + }, + ) + .await + .unwrap(); + + assert_eq!(receipt.receipt.verdict, Verdict::Fail); + assert_eq!(outcomes[0].status, EvaluatorStatus::Failed); + assert!(rollback.load(Ordering::SeqCst)); +} + +#[tokio::test] +async fn test_http_backend_wire_lifecycle() { + let body = json!({ + "model": "atlas-lightning-omni", + "answers": [ + ["telemetry", {"type": "noul", "noul": 0.02}], + ["quality", { + "type": "score", + "score": 3.1, + "confidence": 0.9, + "legend": {"0": "unacceptable", "1": "needs_rework", "2": "acceptable", "3": "exemplary"}, + "probabilities": {"0": 0.0, "1": 0.02, "2": 0.08, "3": 0.9} + }] + ] + }) + .to_string(); + + let endpoint = spawn_mock_probe_server(body).await; + let backend = HttpProbeBackend::with_endpoint(endpoint, "atlas-lightning-omni"); + let probes = ProbeSet::new() + .with("telemetry", Probe::Noul(Noul::new("telemetry?"))) + .with( + "quality", + Probe::Score(Score::new("quality?", ["a", "b", "c", "d"])), + ); + + let response = backend.evaluate(&sample_state(), &probes).await.unwrap(); + assert_eq!(response.model, "atlas-lightning-omni"); + assert!((response.noul("telemetry").unwrap().noul - 0.02).abs() < 1.0e-9); + assert!((response.score("quality").unwrap().score - 3.1).abs() < 1.0e-9); +} + +fn build_plan<E: Evaluator>(evaluator: &E, subject: ArtifactRef) -> EvaluationPlan { + let mut plan = EvaluationPlan { + evaluation_id: EvaluationId(uuid::Uuid::new_v4()), + subject, + profile: "sovereign-audit".to_string(), + evaluators: vec![evaluator.descriptor()], + baseline: None, + sandbox_profile: "isolated".to_string(), + policy_digest: Digest32([2u8; 32]), + evaluator_manifest_digest: Digest32([3u8; 32]), + plan_digest: Digest32([0u8; 32]), + }; + plan.plan_digest = plan.compute_plan_digest(); + plan +} + +async fn spawn_mock_probe_server(body: String) -> String { + use axum::{routing::post, Router}; + + let app = Router::new().route( + "/v1/probe", + post(move || { + let body = body.clone(); + async move { body } + }), + ); + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = axum::serve(listener, app).await; + }); + format!("http://{}", addr) +}