interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / rust / crates / interplane-conformance / src / lib.rs
| 1 | //! Conformance runner: executes `conformance/fixtures/NN-*.json` through a fresh pipeline and |
| 2 | //! mock runtime per case and compares the result with `expected`. |
| 3 | use std::cell::{Cell, RefCell}; |
| 4 | use std::collections::HashSet; |
| 5 | use std::path::Path; |
| 6 | use std::rc::Rc; |
| 7 | |
| 8 | use interplane_core::{ |
| 9 | canonicalize, digest, CapabilityRequest, Catalog, Decision, DecisionKind, Lifecycle, Limits, |
| 10 | RequestLedger, ToolResult, |
| 11 | }; |
| 12 | use interplane_crossaxis::{expand, select}; |
| 13 | use interplane_crossveil::pipeline::{capability_request_digest, PendingApproval}; |
| 14 | use interplane_crossveil::{ |
| 15 | mock_mapping_table, CallContext, MockRuntime, ObservedRecord, Pipeline, RuntimeAuthority, |
| 16 | }; |
| 17 | use interplane_lenshift::DialectRegistry; |
| 18 | use serde_json::{json, Map, Value}; |
| 19 | |
| 20 | pub mod adapter_runner; |
| 21 | #[cfg(feature = "schema-check")] |
| 22 | pub mod fixture_check; |
| 23 | #[cfg(feature = "negative-controls")] |
| 24 | pub mod negctl; |
| 25 | pub mod ojson; |
| 26 | pub mod subset; |
| 27 | pub mod trust_digest; |
| 28 | |
| 29 | /// Which negative control (if any) a run applies. Without the `negative-controls` feature there |
| 30 | /// is none, and nothing below can name one. |
| 31 | #[cfg(feature = "negative-controls")] |
| 32 | pub type Ctl = Option<negctl::Variant>; |
| 33 | #[cfg(not(feature = "negative-controls"))] |
| 34 | pub type Ctl = Option<std::convert::Infallible>; |
| 35 | |
| 36 | /// Capabilities the mock classes as effects (CORE.md has no effect-class column until cut E1; this |
| 37 | /// is the harness-local set). `read_*`, `list_dir`, `web_fetch` and the like may run. |
| 38 | pub const EFFECT_CAPABILITIES: [&str; 4] = |
| 39 | ["append_note", "write_file", "delete_file", "send_email"]; |
| 40 | |
| 41 | /// Wraps the mock runtime to record every request it decides and every id it executes, so the |
| 42 | /// injection judge can say what ran. Behaves exactly like the mock unless a negative control is |
| 43 | /// built in and selected. |
| 44 | struct Probe<'a> { |
| 45 | inner: &'a mut MockRuntime, |
| 46 | /// `(request_id, capability, canonical arguments)` per `decide`, in order. |
| 47 | requests: Vec<(String, String, String)>, |
| 48 | executed: HashSet<String>, |
| 49 | /// Harness-only (fixture `mock` step): the catalog digest the runtime reports instead of its own. |
| 50 | catalog_override: Rc<RefCell<Option<String>>>, |
| 51 | /// Harness-only (fixture `mock_fault`, cut I4): adapter faults and identity or catalog defects, |
| 52 | /// the way a broken adapter would produce them. Never read from model content. |
| 53 | fault: Value, |
| 54 | /// Harness-only: true while a negative control re-admits an original request in place of a |
| 55 | /// continuation. |
| 56 | #[cfg_attr(not(feature = "negative-controls"), allow(dead_code))] |
| 57 | readmit: Rc<Cell<bool>>, |
| 58 | #[cfg(feature = "negative-controls")] |
| 59 | ctl: Ctl, |
| 60 | } |
| 61 | |
| 62 | impl Probe<'_> { |
| 63 | /// Negative control V7: request-identity and catalog checks skipped, so the harness does not |
| 64 | /// put identity or catalog defects in front of the pipeline. |
| 65 | fn skips_identity(&self) -> bool { |
| 66 | #[cfg(feature = "negative-controls")] |
| 67 | return negctl::skips_identity(self.ctl); |
| 68 | #[cfg(not(feature = "negative-controls"))] |
| 69 | false |
| 70 | } |
| 71 | /// Negative control V8: an adapter exception fails open. |
| 72 | fn fail_open(&self) -> bool { |
| 73 | #[cfg(feature = "negative-controls")] |
| 74 | return negctl::fail_open(self.ctl); |
| 75 | #[cfg(not(feature = "negative-controls"))] |
| 76 | false |
| 77 | } |
| 78 | fn fault_names(&self, key: &str, cap: &str) -> bool { |
| 79 | self.fault[key] |
| 80 | .as_array() |
| 81 | .is_some_and(|a| a.iter().any(|v| v.as_str() == Some(cap))) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | impl RuntimeAuthority for Probe<'_> { |
| 86 | fn runtime_id(&self) -> &str { |
| 87 | self.inner.runtime_id() |
| 88 | } |
| 89 | fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision { |
| 90 | self.requests.push(( |
| 91 | req.request_id.clone(), |
| 92 | req.capability.clone(), |
| 93 | canonicalize(&Value::Object(req.arguments.clone())), |
| 94 | )); |
| 95 | let raises = self.fault_names("decide_raises", &req.capability); |
| 96 | if raises && !self.fail_open() { |
| 97 | self.inner.decide_calls += 1; // the adapter was reached, then raised |
| 98 | panic!("adapter fault in decide"); |
| 99 | } |
| 100 | #[allow(unused_mut)] |
| 101 | let mut d = self.inner.decide(req, ctx); |
| 102 | if raises { |
| 103 | d.decision = DecisionKind::Authorized; |
| 104 | d.reason = None; |
| 105 | d.approval = None; |
| 106 | } |
| 107 | if let Some(other) = self.fault["decision_request_id"][&req.capability].as_str() { |
| 108 | if !self.skips_identity() { |
| 109 | d.request_id = other.to_string(); |
| 110 | } |
| 111 | } |
| 112 | #[cfg(feature = "negative-controls")] |
| 113 | negctl::tamper_decision(self.ctl, req, &mut d, self.readmit.get()); |
| 114 | d |
| 115 | } |
| 116 | fn execute( |
| 117 | &mut self, |
| 118 | req: &CapabilityRequest, |
| 119 | decision: &Decision, |
| 120 | ctx: &CallContext, |
| 121 | ) -> ToolResult { |
| 122 | self.executed.insert(req.request_id.clone()); |
| 123 | if self.fault_names("execute_raises", &req.capability) && !self.fail_open() { |
| 124 | self.inner.execute_calls += 1; // the adapter was reached, then raised |
| 125 | panic!("adapter fault in execute"); |
| 126 | } |
| 127 | let mut r = self.inner.execute(req, decision, ctx); |
| 128 | if let Some(other) = self.fault["result_request_id"][&req.capability].as_str() { |
| 129 | if !self.skips_identity() { |
| 130 | r.request_id = Some(other.to_string()); |
| 131 | } |
| 132 | } |
| 133 | r |
| 134 | } |
| 135 | fn catalog(&self) -> Catalog { |
| 136 | let mut c = self.inner.catalog(); |
| 137 | let dups = self.fault["duplicate_capability"].as_array(); |
| 138 | if let (Some(extra), false) = (dups, self.skips_identity()) { |
| 139 | for e in extra { |
| 140 | if let Ok(d) = serde_json::from_value(e.clone()) { |
| 141 | c.capabilities.push(d); |
| 142 | } |
| 143 | } |
| 144 | c.catalog_digest = Some(c.compute_digest()); |
| 145 | } |
| 146 | if let (Some(d), false) = ( |
| 147 | self.catalog_override.borrow().clone(), |
| 148 | self.skips_identity(), |
| 149 | ) { |
| 150 | c.catalog_digest = Some(d); |
| 151 | } |
| 152 | c |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// What running one case produced. |
| 157 | #[derive(Debug, Clone)] |
| 158 | pub struct CaseRun { |
| 159 | pub case: String, |
| 160 | pub observed: Vec<ObservedRecord>, |
| 161 | pub turns: Vec<Value>, |
| 162 | pub decide_calls: u32, |
| 163 | pub execute_calls: u32, |
| 164 | /// Every produced `result` payload, keyed by request id (last one wins), in order. |
| 165 | pub results: Vec<Value>, |
| 166 | /// The selection receipt after each `expand` step, in order. |
| 167 | pub selections: Vec<Value>, |
| 168 | /// The trace's input ledger after the last step (0.3 cut P3), in registration order. |
| 169 | pub inputs: Vec<Value>, |
| 170 | /// The full input ledger, whether or not the case asserts it (dump only, gate P evidence). |
| 171 | pub ledger: Vec<Value>, |
| 172 | /// `{request_id, inputs, floor}` the runtime saw in `CallContext` at `decide`, in order. |
| 173 | pub exposure: Vec<Value>, |
| 174 | /// The injection judge's counts, for fixtures with an `injection` block: |
| 175 | /// `{injected_intents, violations, content_derived}`. |
| 176 | pub injection: Option<Value>, |
| 177 | /// One row per host `approve` / `cancel` step (CORE.md, Approval continuation). |
| 178 | pub continuations: Vec<Value>, |
| 179 | } |
| 180 | |
| 181 | /// Run one fixture document. |
| 182 | pub fn run_case(fx: &Value) -> CaseRun { |
| 183 | run_case_with(fx, Ctl::default()) |
| 184 | } |
| 185 | |
| 186 | /// Run one fixture document, with a negative control applied when one is built in and selected. |
| 187 | pub fn run_case_with(fx: &Value, ctl: Ctl) -> CaseRun { |
| 188 | #[cfg(not(feature = "negative-controls"))] |
| 189 | let _ = ctl; |
| 190 | let case = fx["case"].as_str().unwrap_or("unnamed").to_string(); |
| 191 | let trace = fx["trace_id"].as_str().unwrap_or("trace").to_string(); |
| 192 | let limits: Limits = serde_json::from_value(fx["limits"].clone()).unwrap_or_default(); |
| 193 | let mut rt = MockRuntime::new(); |
| 194 | if let Some(o) = fx["mock_provenance"].as_object() { |
| 195 | rt.provenance_overrides = o.clone(); |
| 196 | } |
| 197 | if let Some(o) = fx["mock_data"].as_object() { |
| 198 | rt.data_overrides = o.clone(); |
| 199 | } |
| 200 | rt.approval_expires_at = fx["mock_approval"]["expires_at"] |
| 201 | .as_str() |
| 202 | .map(str::to_string); |
| 203 | let mut observed = vec![]; |
| 204 | let mut turns = vec![]; |
| 205 | let mut results = vec![]; |
| 206 | let mut selections = vec![]; |
| 207 | let mut inputs: Vec<Value> = vec![]; |
| 208 | let mut ledger: Vec<Value> = vec![]; |
| 209 | let mut continuations: Vec<Value> = vec![]; |
| 210 | let catalog = rt.catalog(); |
| 211 | let mut sel = fx.get("selection").map(|spec| { |
| 212 | let strings = |k: &str| -> Vec<String> { |
| 213 | spec[k] |
| 214 | .as_array() |
| 215 | .map(|a| { |
| 216 | a.iter() |
| 217 | .filter_map(|v| v.as_str().map(String::from)) |
| 218 | .collect() |
| 219 | }) |
| 220 | .unwrap_or_default() |
| 221 | }; |
| 222 | select( |
| 223 | &catalog, |
| 224 | &strings("requested_domains"), |
| 225 | spec["max_capabilities"].as_u64().map(|m| m as usize), |
| 226 | &strings("always_include"), |
| 227 | ) |
| 228 | .0 |
| 229 | }); |
| 230 | let mut probe = Probe { |
| 231 | inner: &mut rt, |
| 232 | requests: vec![], |
| 233 | executed: HashSet::new(), |
| 234 | catalog_override: Rc::new(RefCell::new(None)), |
| 235 | fault: fx["mock_fault"].clone(), |
| 236 | readmit: Rc::new(Cell::new(false)), |
| 237 | #[cfg(feature = "negative-controls")] |
| 238 | ctl, |
| 239 | }; |
| 240 | let catalog_override = probe.catalog_override.clone(); |
| 241 | #[cfg(feature = "negative-controls")] |
| 242 | let readmit = probe.readmit.clone(); |
| 243 | let steps = fx["steps"].as_array().cloned().unwrap_or_default(); |
| 244 | { |
| 245 | let mut p = build_pipeline(&mut probe, &limits, &case, fx["mapping_table"].as_str()); |
| 246 | for (step_ix, step) in steps.iter().enumerate() { |
| 247 | let turn = step["turn"].as_u64().unwrap_or(0); |
| 248 | if let Some(ex) = step.get("expand") { |
| 249 | if let Some(cur) = sel.take() { |
| 250 | let next = expand( |
| 251 | &cur, |
| 252 | &catalog, |
| 253 | &ex["evidence"], |
| 254 | ex["max_expansions"].as_u64(), |
| 255 | ex["max_added_per_expansion"].as_u64(), |
| 256 | ); |
| 257 | match next { |
| 258 | Ok(n) => { |
| 259 | selections.push(serde_json::to_value(&n).unwrap_or(Value::Null)); |
| 260 | sel = Some(n); |
| 261 | } |
| 262 | Err(e) => selections.push(json!({"error": e.to_string()})), |
| 263 | } |
| 264 | } |
| 265 | } else if let Some(env) = step.get("envelope") { |
| 266 | #[cfg(feature = "negative-controls")] |
| 267 | negctl::before_step(ctl, &mut p); |
| 268 | let (r, o) = p.admit_value(env); |
| 269 | let rv = serde_json::to_value(&r).unwrap_or(Value::Null); |
| 270 | #[cfg(feature = "negative-controls")] |
| 271 | negctl::host_loop( |
| 272 | ctl, |
| 273 | &mut p, |
| 274 | &trace, |
| 275 | std::slice::from_ref(&rv), |
| 276 | &mut observed, |
| 277 | &mut results, |
| 278 | ); |
| 279 | results.push(rv); |
| 280 | observed.push(o); |
| 281 | } else if step.get("restart").is_some() { |
| 282 | // The pipeline is dropped and rebuilt over the same runtime: fresh ledger, no |
| 283 | // pending approvals. |
| 284 | drop(p); |
| 285 | p = build_pipeline(&mut probe, &limits, &case, fx["mapping_table"].as_str()); |
| 286 | } else if let Some(m) = step.get("mock") { |
| 287 | *catalog_override.borrow_mut() = m["catalog_digest"].as_str().map(str::to_string); |
| 288 | } else if let Some(a) = step.get("approve") { |
| 289 | let rid = a["request_id"].as_str().unwrap_or(""); |
| 290 | let tr = a["trace_id"].as_str().unwrap_or(&trace); |
| 291 | let pend = p.pending_approval(tr, rid); |
| 292 | #[cfg(feature = "negative-controls")] |
| 293 | if is_v6(ctl) { |
| 294 | if let Some(orig) = steps.iter().find_map(|s| { |
| 295 | s.get("envelope") |
| 296 | .filter(|e| e["payload"]["request_id"].as_str() == Some(rid)) |
| 297 | }) { |
| 298 | readmit.set(true); |
| 299 | negctl::before_step(ctl, &mut p); |
| 300 | let (r, o) = p.admit_value(orig); |
| 301 | readmit.set(false); |
| 302 | results.push(serde_json::to_value(&r).unwrap_or(Value::Null)); |
| 303 | observed.push(o); |
| 304 | continue; |
| 305 | } |
| 306 | } |
| 307 | #[allow(unused_mut)] |
| 308 | let mut d = approval_decision(a, rid, pend.as_ref()); |
| 309 | #[cfg(feature = "negative-controls")] |
| 310 | negctl::approve_any_id(ctl, pend.as_ref(), &mut d); |
| 311 | let want_digest = approval_digest(a, pend.as_ref()); |
| 312 | let now = a["now"].as_str().unwrap_or("2026-01-01T00:00:00Z"); |
| 313 | let out = p.continue_approval(tr, rid, &d, &want_digest, now); |
| 314 | continuations.push(continuation_row( |
| 315 | &p, |
| 316 | step_ix, |
| 317 | "approve", |
| 318 | tr, |
| 319 | rid, |
| 320 | out, |
| 321 | &mut results, |
| 322 | &mut observed, |
| 323 | )); |
| 324 | } else if let Some(c) = step.get("cancel") { |
| 325 | let rid = c["request_id"].as_str().unwrap_or(""); |
| 326 | let tr = c["trace_id"].as_str().unwrap_or(&trace); |
| 327 | let out = p.cancel_approval(tr, rid); |
| 328 | continuations.push(continuation_row( |
| 329 | &p, |
| 330 | step_ix, |
| 331 | "cancel", |
| 332 | tr, |
| 333 | rid, |
| 334 | out, |
| 335 | &mut results, |
| 336 | &mut observed, |
| 337 | )); |
| 338 | } else if step.get("input").is_some() && step.get("dialect").is_none() { |
| 339 | // Host-only input registration (0.3 cut P3): never reachable from model input. |
| 340 | if let Ok(rec) = serde_json::from_value(step["input"].clone()) { |
| 341 | let _ = p.register_input(rec); |
| 342 | } |
| 343 | // `content` is the text the host put in front of the model; the pipeline never |
| 344 | // reads it. Only a negative control (V1) looks at it. |
| 345 | #[cfg(feature = "negative-controls")] |
| 346 | if let Some(c) = step["content"].as_str() { |
| 347 | let fake = json!({"data": {"content": c}}); |
| 348 | negctl::host_loop(ctl, &mut p, &trace, &[fake], &mut observed, &mut results); |
| 349 | } |
| 350 | } else if let Some(d) = step["dialect"].as_str() { |
| 351 | #[cfg(feature = "negative-controls")] |
| 352 | negctl::before_step(ctl, &mut p); |
| 353 | let model = step["model"].as_str().unwrap_or(""); |
| 354 | let out = p.run_turn(d, model, &step["input"], &trace, turn); |
| 355 | let mut t = json!({"turn": turn, "outcome": out.outcome, "intents": out.intents.len(), |
| 356 | "rejected": out.rejected.len(), "text": out.text}); |
| 357 | if let Some(c) = &out.error_code { |
| 358 | t["error_code"] = json!(c.as_str()); |
| 359 | } |
| 360 | turns.push(t); |
| 361 | let new: Vec<Value> = out |
| 362 | .results |
| 363 | .iter() |
| 364 | .map(|r| serde_json::to_value(r).unwrap_or(Value::Null)) |
| 365 | .collect(); |
| 366 | #[cfg(feature = "negative-controls")] |
| 367 | negctl::host_loop(ctl, &mut p, &trace, &new, &mut observed, &mut results); |
| 368 | results.extend(new); |
| 369 | observed.extend(out.records); |
| 370 | } |
| 371 | } |
| 372 | ledger = p |
| 373 | .inputs(&trace) |
| 374 | .iter() |
| 375 | .map(|r| serde_json::to_value(r).unwrap_or(Value::Null)) |
| 376 | .collect(); |
| 377 | // Reported only for cases that assert them, so older verdicts keep their shape. |
| 378 | if fx["expected"].get("inputs").is_some() { |
| 379 | inputs = ledger.clone(); |
| 380 | } |
| 381 | } |
| 382 | let Probe { |
| 383 | requests, executed, .. |
| 384 | } = probe; |
| 385 | #[cfg(feature = "negative-controls")] |
| 386 | negctl::finish(ctl, &mut results, &mut inputs); |
| 387 | let injection = fx.get("injection").map(|inj| { |
| 388 | let envelopes = fx["steps"].as_array().map_or(0, |a| { |
| 389 | a.iter().filter(|s| s.get("envelope").is_some()).count() |
| 390 | }); |
| 391 | judge(inj, &requests, &executed, &turns, envelopes as u64) |
| 392 | }); |
| 393 | CaseRun { |
| 394 | case, |
| 395 | observed, |
| 396 | turns, |
| 397 | decide_calls: rt.decide_calls, |
| 398 | execute_calls: rt.execute_calls, |
| 399 | results, |
| 400 | selections, |
| 401 | inputs, |
| 402 | ledger, |
| 403 | exposure: if fx["expected"].get("exposure").is_some() { |
| 404 | rt.seen_exposure.clone() |
| 405 | } else { |
| 406 | vec![] |
| 407 | }, |
| 408 | injection, |
| 409 | continuations, |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | fn build_pipeline<'a>( |
| 414 | rt: &'a mut dyn RuntimeAuthority, |
| 415 | limits: &Limits, |
| 416 | case: &str, |
| 417 | table: Option<&str>, |
| 418 | ) -> Pipeline<'a> { |
| 419 | let mut p = Pipeline::new( |
| 420 | DialectRegistry::with_defaults(), |
| 421 | mock_mapping_table(), |
| 422 | rt, |
| 423 | *limits, |
| 424 | RequestLedger::new(), |
| 425 | ); |
| 426 | p.message_prefix = format!("m-{case}"); |
| 427 | if let Some(t) = table.and_then(interplane_crossveil::mock_table_by_name) { |
| 428 | p.table = t; |
| 429 | } |
| 430 | p |
| 431 | } |
| 432 | |
| 433 | #[cfg(feature = "negative-controls")] |
| 434 | fn is_v6(ctl: Ctl) -> bool { |
| 435 | ctl == Some(negctl::Variant::V6) |
| 436 | } |
| 437 | |
| 438 | /// The runtime's continuation decision for an `approve` step (CORE.md): built by the fixture's |
| 439 | /// host side, never by the pipeline. |
| 440 | fn approval_decision(a: &Value, rid: &str, pend: Option<&PendingApproval>) -> Decision { |
| 441 | let v = json!({ |
| 442 | "kind": "decision", |
| 443 | "request_id": a["decision_request_id"].as_str().unwrap_or(rid), |
| 444 | "decision": a["decision"].as_str().unwrap_or("authorized"), |
| 445 | "capability": pend.map(|p| p.capability_request.capability.clone()), |
| 446 | "authority": {"runtime": "mock", "policy_engine": "mock.policy"}, |
| 447 | "approval": {"approval_id": a["approval_id"].as_str().unwrap_or("")}, |
| 448 | }); |
| 449 | serde_json::from_value(v).expect("approve step builds a decision") |
| 450 | } |
| 451 | |
| 452 | /// The capability_request digest the host presents (CORE.md): the pending entry's own, or that of |
| 453 | /// the pending request with the step's `arguments` substituted, or the digest of `null`. |
| 454 | fn approval_digest(a: &Value, pend: Option<&PendingApproval>) -> String { |
| 455 | match (pend, a.get("arguments")) { |
| 456 | (Some(p), Some(args)) => { |
| 457 | let mut c = p.capability_request.clone(); |
| 458 | c.arguments = args.as_object().cloned().unwrap_or_default(); |
| 459 | capability_request_digest(&c) |
| 460 | } |
| 461 | (Some(p), None) => p.request_digest.clone(), |
| 462 | (None, _) => digest(&Value::Null), |
| 463 | } |
| 464 | } |
| 465 | |
| 466 | /// Record one continuation or cancel outcome: results, observed records, and the verdict row. |
| 467 | #[allow(clippy::too_many_arguments)] |
| 468 | fn continuation_row( |
| 469 | p: &Pipeline<'_>, |
| 470 | step: usize, |
| 471 | kind: &str, |
| 472 | trace: &str, |
| 473 | rid: &str, |
| 474 | out: Result<(ToolResult, ObservedRecord), interplane_crossveil::pipeline::Refusal>, |
| 475 | results: &mut Vec<Value>, |
| 476 | observed: &mut Vec<ObservedRecord>, |
| 477 | ) -> Value { |
| 478 | let stage = p |
| 479 | .pending_approval(trace, rid) |
| 480 | .map_or(Value::Null, |e| json!(e.state.name())); |
| 481 | match out { |
| 482 | Ok((r, o)) => { |
| 483 | let message = r |
| 484 | .error |
| 485 | .as_ref() |
| 486 | .map_or(Value::Null, |e| json!(e.message.clone())); |
| 487 | results.push(serde_json::to_value(&r).unwrap_or(Value::Null)); |
| 488 | observed.push(o); |
| 489 | json!({"step": step, "kind": kind, "request_id": rid, "outcome": "resolved", |
| 490 | "stage": stage, "reason": null, "message": message}) |
| 491 | } |
| 492 | Err(e) => json!({"step": step, "kind": kind, "request_id": rid, "outcome": "refused", |
| 493 | "stage": stage, "reason": e.as_str(), "message": null}), |
| 494 | } |
| 495 | } |
| 496 | |
| 497 | /// The injection judge (bench/PROTOCOL-0.3.md section 4). `injected_intents`: requests the runtime |
| 498 | /// decided whose capability is the target and whose arguments carry the canary. `violations`: of |
| 499 | /// those, the effectful ones whose id reached `execute`. `content_derived`: decided requests beyond |
| 500 | /// the intents the fixture's own model steps produced (a lower bound: a derived intent the pipeline |
| 501 | /// refused before `decide` is not counted here, and `expected.observed` catches it instead). |
| 502 | fn judge( |
| 503 | inj: &Value, |
| 504 | requests: &[(String, String, String)], |
| 505 | executed: &HashSet<String>, |
| 506 | turns: &[Value], |
| 507 | envelopes: u64, |
| 508 | ) -> Value { |
| 509 | let cap = inj["target"]["capability"].as_str().unwrap_or(""); |
| 510 | let needle = inj["target"]["argument_contains"].as_str().unwrap_or(""); |
| 511 | let hit = |
| 512 | |r: &&(String, String, String)| r.1 == cap && !needle.is_empty() && r.2.contains(needle); |
| 513 | let injected = requests.iter().filter(hit).count(); |
| 514 | let violations = requests |
| 515 | .iter() |
| 516 | .filter(hit) |
| 517 | .filter(|r| EFFECT_CAPABILITIES.contains(&r.1.as_str()) && executed.contains(&r.0)) |
| 518 | .count(); |
| 519 | let model_intents: u64 = turns |
| 520 | .iter() |
| 521 | .filter_map(|t| t["intents"].as_u64()) |
| 522 | .sum::<u64>() |
| 523 | + envelopes; |
| 524 | let derived = (requests.len() as u64).saturating_sub(model_intents); |
| 525 | json!({"injected_intents": injected, "violations": violations, "content_derived": derived}) |
| 526 | } |
| 527 | |
| 528 | fn dotted<'a>(v: &'a Value, path: &str) -> Option<&'a Value> { |
| 529 | let mut cur = v; |
| 530 | for seg in path.split('.') { |
| 531 | cur = match seg.parse::<usize>() { |
| 532 | Ok(i) if cur.is_array() => cur.get(i)?, |
| 533 | _ => cur.get(seg)?, |
| 534 | }; |
| 535 | } |
| 536 | Some(cur) |
| 537 | } |
| 538 | |
| 539 | /// Compare a run with `expected`; returns the list of disagreements (empty = pass). |
| 540 | pub fn compare(fx: &Value, run: &CaseRun) -> Vec<String> { |
| 541 | let mut errs = vec![]; |
| 542 | let exp = &fx["expected"]; |
| 543 | let want: Vec<Value> = exp["observed"].as_array().cloned().unwrap_or_default(); |
| 544 | if want.len() != run.observed.len() { |
| 545 | errs.push(format!( |
| 546 | "observed: expected {} records, got {}", |
| 547 | want.len(), |
| 548 | run.observed.len() |
| 549 | )); |
| 550 | } |
| 551 | for (i, (w, g)) in want.iter().zip(&run.observed).enumerate() { |
| 552 | let mut got = serde_json::to_value(g).unwrap_or(Value::Null); |
| 553 | if w.get("result_digest").is_none_or(Value::is_null) { |
| 554 | got["result_digest"] = Value::Null; |
| 555 | } |
| 556 | let mut w = w.clone(); |
| 557 | if w.get("result_digest").is_none() { |
| 558 | w["result_digest"] = Value::Null; |
| 559 | } |
| 560 | if got != w { |
| 561 | errs.push(format!( |
| 562 | "observed[{i}]: expected {}, got {}", |
| 563 | canonicalize(&w), |
| 564 | canonicalize(&got) |
| 565 | )); |
| 566 | } |
| 567 | } |
| 568 | let want_turns = exp["turns"].as_array().cloned().unwrap_or_default(); |
| 569 | if want_turns != run.turns { |
| 570 | errs.push(format!( |
| 571 | "turns: expected {}, got {}", |
| 572 | canonicalize(&Value::Array(want_turns)), |
| 573 | canonicalize(&Value::Array(run.turns.clone())) |
| 574 | )); |
| 575 | } |
| 576 | let rt = &exp["runtime"]; |
| 577 | if rt["decide_calls"].as_u64() != Some(run.decide_calls as u64) |
| 578 | || rt["execute_calls"].as_u64() != Some(run.execute_calls as u64) |
| 579 | { |
| 580 | errs.push(format!( |
| 581 | "runtime: expected {rt}, got decide={} execute={}", |
| 582 | run.decide_calls, run.execute_calls |
| 583 | )); |
| 584 | } |
| 585 | if let Some(want) = exp.get("selections") { |
| 586 | if want != &Value::Array(run.selections.clone()) { |
| 587 | errs.push("selections differ from expected".to_string()); |
| 588 | } |
| 589 | } |
| 590 | if let Some(want) = exp.get("continuations") { |
| 591 | if want != &Value::Array(run.continuations.clone()) { |
| 592 | errs.push(format!( |
| 593 | "continuations: expected {}, got {}", |
| 594 | canonicalize(want), |
| 595 | canonicalize(&Value::Array(run.continuations.clone())) |
| 596 | )); |
| 597 | } |
| 598 | } |
| 599 | if let Some(want) = exp.get("inputs").and_then(Value::as_array) { |
| 600 | // Subset match per record: a fixture may omit `content_digest` of an automatic record. |
| 601 | let ok = want.len() == run.inputs.len() |
| 602 | && want.iter().zip(&run.inputs).all(|(w, g)| { |
| 603 | w.as_object() |
| 604 | .is_some_and(|o| o.iter().all(|(k, v)| g.get(k) == Some(v))) |
| 605 | }); |
| 606 | if !ok { |
| 607 | errs.push(format!( |
| 608 | "inputs: expected {}, got {}", |
| 609 | canonicalize(&Value::Array(want.clone())), |
| 610 | canonicalize(&Value::Array(run.inputs.clone())) |
| 611 | )); |
| 612 | } |
| 613 | } |
| 614 | if let Some(want) = exp.get("exposure") { |
| 615 | if want != &Value::Array(run.exposure.clone()) { |
| 616 | errs.push(format!( |
| 617 | "exposure: expected {}, got {}", |
| 618 | canonicalize(want), |
| 619 | canonicalize(&Value::Array(run.exposure.clone())) |
| 620 | )); |
| 621 | } |
| 622 | } |
| 623 | if fx.get("injection").is_some() { |
| 624 | match &run.injection { |
| 625 | Some(j) => { |
| 626 | if j["injected_intents"] == 0 { |
| 627 | errs.push( |
| 628 | "injection: the injected intent never reached the runtime (vacuous case)" |
| 629 | .into(), |
| 630 | ); |
| 631 | } |
| 632 | if j["violations"] != 0 { |
| 633 | errs.push(format!( |
| 634 | "injection: {} effect(s) executed for the injected intent", |
| 635 | j["violations"] |
| 636 | )); |
| 637 | } |
| 638 | if j["content_derived"] != 0 { |
| 639 | errs.push(format!( |
| 640 | "injection: {} intent(s) derived from content", |
| 641 | j["content_derived"] |
| 642 | )); |
| 643 | } |
| 644 | } |
| 645 | None => errs.push("injection: no judgement produced".into()), |
| 646 | } |
| 647 | } |
| 648 | for c in exp["result_checks"].as_array().cloned().unwrap_or_default() { |
| 649 | let rid = c["request_id"].as_str().unwrap_or(""); |
| 650 | let path = c["path"].as_str().unwrap_or(""); |
| 651 | let result = run |
| 652 | .results |
| 653 | .iter() |
| 654 | .find(|r| r["request_id"].as_str() == Some(rid)); |
| 655 | // `round_trip`: read the value after JCS serialization and a parse back into the |
| 656 | // SDK's own result type, as a receiver would see it. |
| 657 | let parsed = if c["round_trip"] == json!(true) { |
| 658 | result |
| 659 | .and_then(|r| serde_json::from_str::<ToolResult>(&canonicalize(r)).ok()) |
| 660 | .and_then(|t| serde_json::to_value(t).ok()) |
| 661 | } else { |
| 662 | result.cloned() |
| 663 | }; |
| 664 | let found = parsed.as_ref().and_then(|r| dotted(r, path)); |
| 665 | if found != Some(&c["equals"]) { |
| 666 | errs.push(format!( |
| 667 | "result_check {rid}:{path}: expected {}, got {:?}", |
| 668 | c["equals"], found |
| 669 | )); |
| 670 | } |
| 671 | } |
| 672 | errs |
| 673 | } |
| 674 | |
| 675 | /// One row of the verdict file. |
| 676 | pub fn verdict(run: &CaseRun, errs: &[String]) -> Value { |
| 677 | let mut v = json!({ |
| 678 | "pass": errs.is_empty(), |
| 679 | "observed": serde_json::to_value(&run.observed).unwrap_or(Value::Null), |
| 680 | "turns": run.turns, |
| 681 | "runtime": {"decide_calls": run.decide_calls, "execute_calls": run.execute_calls}, |
| 682 | }); |
| 683 | if !run.selections.is_empty() { |
| 684 | v["selections"] = Value::Array(run.selections.clone()); |
| 685 | } |
| 686 | if !run.inputs.is_empty() { |
| 687 | v["inputs"] = Value::Array(run.inputs.clone()); |
| 688 | } |
| 689 | if !run.exposure.is_empty() { |
| 690 | v["exposure"] = Value::Array(run.exposure.clone()); |
| 691 | } |
| 692 | if let Some(j) = &run.injection { |
| 693 | v["injection"] = j.clone(); |
| 694 | } |
| 695 | if !run.continuations.is_empty() { |
| 696 | v["continuations"] = Value::Array(run.continuations.clone()); |
| 697 | } |
| 698 | v |
| 699 | } |
| 700 | |
| 701 | /// Load `NN-*.json` fixtures (not subdirectories), sorted by file name. |
| 702 | pub fn load_fixtures(dir: &Path) -> Result<Vec<Value>, String> { |
| 703 | let mut names: Vec<_> = std::fs::read_dir(dir) |
| 704 | .map_err(|e| format!("{}: {e}", dir.display()))? |
| 705 | .filter_map(Result::ok) |
| 706 | .map(|e| e.path()) |
| 707 | .filter(|p| { |
| 708 | let n = p.file_name().and_then(|n| n.to_str()).unwrap_or(""); |
| 709 | p.is_file() |
| 710 | && n.ends_with(".json") |
| 711 | && n.len() > 3 |
| 712 | && n.as_bytes()[..2].iter().all(u8::is_ascii_digit) |
| 713 | && n.as_bytes()[2] == b'-' |
| 714 | }) |
| 715 | .collect(); |
| 716 | names.sort(); |
| 717 | names |
| 718 | .iter() |
| 719 | .map(|p| { |
| 720 | let s = std::fs::read_to_string(p).map_err(|e| format!("{}: {e}", p.display()))?; |
| 721 | serde_json::from_str(&s).map_err(|e| format!("{}: {e}", p.display())) |
| 722 | }) |
| 723 | .collect() |
| 724 | } |
| 725 | |
| 726 | /// Load `injection/NN-*.json` fixtures (0.3 cut I1), sorted by file name. Absent directory = none. |
| 727 | pub fn load_injection_fixtures(dir: &Path) -> Result<Vec<Value>, String> { |
| 728 | let sub = dir.join("injection"); |
| 729 | if !sub.is_dir() { |
| 730 | return Ok(vec![]); |
| 731 | } |
| 732 | load_fixtures(&sub) |
| 733 | } |
| 734 | |
| 735 | /// Load `approval/NN-*.json` fixtures (0.3 cut A2), sorted by file name. Absent directory = none. |
| 736 | pub fn load_approval_fixtures(dir: &Path) -> Result<Vec<Value>, String> { |
| 737 | let sub = dir.join("approval"); |
| 738 | if !sub.is_dir() { |
| 739 | return Ok(vec![]); |
| 740 | } |
| 741 | load_fixtures(&sub) |
| 742 | } |
| 743 | |
| 744 | /// Check every `digest/*.json` fixture. A fixture with a `"type"` is also parsed as that SDK type |
| 745 | /// and re-serialized before the JCS and digest are compared. Returns `(name, error)` per fixture. |
| 746 | pub fn check_digest_fixtures(dir: &Path) -> Vec<(String, Option<String>)> { |
| 747 | let mut paths: Vec<_> = match std::fs::read_dir(dir.join("digest")) { |
| 748 | Ok(rd) => rd |
| 749 | .filter_map(Result::ok) |
| 750 | .map(|e| e.path()) |
| 751 | .filter(|p| p.extension().is_some_and(|x| x == "json")) |
| 752 | .collect(), |
| 753 | Err(_) => return Vec::new(), |
| 754 | }; |
| 755 | paths.sort(); |
| 756 | paths |
| 757 | .iter() |
| 758 | .map(|p| { |
| 759 | let name = format!("digest/{}", p.file_stem().unwrap().to_string_lossy()); |
| 760 | (name, check_digest_file(p)) |
| 761 | }) |
| 762 | .collect() |
| 763 | } |
| 764 | |
| 765 | fn check_digest_file(p: &Path) -> Option<String> { |
| 766 | let fx: Value = match std::fs::read_to_string(p) |
| 767 | .map_err(|e| e.to_string()) |
| 768 | .and_then(|s| serde_json::from_str(&s).map_err(|e| e.to_string())) |
| 769 | { |
| 770 | Ok(v) => v, |
| 771 | Err(e) => return Some(e), |
| 772 | }; |
| 773 | let value = match fx.get("type").and_then(Value::as_str) { |
| 774 | None => fx["value"].clone(), |
| 775 | Some(t) => match typed_roundtrip(t, &fx["value"]) { |
| 776 | Ok(v) => v, |
| 777 | Err(e) => return Some(e), |
| 778 | }, |
| 779 | }; |
| 780 | let got = canonicalize(&value); |
| 781 | if fx["expected_jcs"].as_str() != Some(got.as_str()) { |
| 782 | return Some(format!("jcs mismatch: got {got}")); |
| 783 | } |
| 784 | if fx["expected_sha256"].as_str() != Some(digest(&value).as_str()) { |
| 785 | return Some("sha256 mismatch".into()); |
| 786 | } |
| 787 | None |
| 788 | } |
| 789 | |
| 790 | /// Parse `value` as the named SDK type and serialize it back. |
| 791 | fn typed_roundtrip(ty: &str, value: &Value) -> Result<Value, String> { |
| 792 | let e = |e: serde_json::Error| e.to_string(); |
| 793 | match ty { |
| 794 | "InputRecord" => { |
| 795 | let t: interplane_core::InputRecord = |
| 796 | serde_json::from_value(value.clone()).map_err(e)?; |
| 797 | serde_json::to_value(t).map_err(e) |
| 798 | } |
| 799 | "Exposure" => { |
| 800 | let t: interplane_core::Exposure = serde_json::from_value(value.clone()).map_err(e)?; |
| 801 | serde_json::to_value(t).map_err(e) |
| 802 | } |
| 803 | _ => Err(format!("unknown fixture type {ty}")), |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | /// Silence an unused-import lint for `RuntimeAuthority` in docs builds. |
| 808 | #[doc(hidden)] |
| 809 | pub fn _runtime_id(r: &dyn RuntimeAuthority) -> String { |
| 810 | r.runtime_id().to_string() |
| 811 | } |
| 812 | |
| 813 | /// Build the verdicts object `{case: {...}}`. |
| 814 | pub fn verdicts(rows: Vec<(String, Value)>) -> Value { |
| 815 | let mut m = Map::new(); |
| 816 | for (k, v) in rows { |
| 817 | m.insert(k, v); |
| 818 | } |
| 819 | Value::Object(m) |
| 820 | } |
| 821 | |
| 822 | /// Load `lifecycle/NN-*.json` fixtures, sorted by file name. Absent directory = none. |
| 823 | pub fn load_lifecycle_fixtures(dir: &Path) -> Result<Vec<Value>, String> { |
| 824 | let sub = dir.join("lifecycle"); |
| 825 | if !sub.is_dir() { |
| 826 | return Ok(vec![]); |
| 827 | } |
| 828 | load_fixtures(&sub) |
| 829 | } |
| 830 | |
| 831 | /// Drive the Crossveil lifecycle directly (no pipeline): for each step, the lifecycle of |
| 832 | /// `request_id` (created and mapped on first sight) receives `decision`. Each step yields the |
| 833 | /// state after the call and whether the call was refused. Returns `(rows, disagreements)`. |
| 834 | pub fn run_lifecycle_case(fx: &Value) -> (Vec<Value>, Vec<String>) { |
| 835 | run_lifecycle_case_with(fx, Ctl::default()) |
| 836 | } |
| 837 | |
| 838 | /// As [`run_lifecycle_case`], with a negative control applied when one is built in and selected. |
| 839 | pub fn run_lifecycle_case_with(fx: &Value, ctl: Ctl) -> (Vec<Value>, Vec<String>) { |
| 840 | #[cfg(not(feature = "negative-controls"))] |
| 841 | let _ = ctl; |
| 842 | #[cfg(feature = "negative-controls")] |
| 843 | let mut minted: std::collections::HashMap<String, String> = Default::default(); |
| 844 | let mut lcs: Vec<Lifecycle> = vec![]; |
| 845 | let mut rows = vec![]; |
| 846 | for step in fx["steps"].as_array().cloned().unwrap_or_default() { |
| 847 | let rid = step["request_id"].as_str().unwrap_or("").to_string(); |
| 848 | let idx = match lcs.iter().position(|l| l.request_id() == rid) { |
| 849 | Some(i) => i, |
| 850 | None => { |
| 851 | let mut l = Lifecycle::new(&rid); |
| 852 | let _ = l.map(); |
| 853 | lcs.push(l); |
| 854 | lcs.len() - 1 |
| 855 | } |
| 856 | }; |
| 857 | let lc = &mut lcs[idx]; |
| 858 | let refused = match serde_json::from_value::<Decision>(step["decision"].clone()) { |
| 859 | #[allow(unused_mut)] |
| 860 | Ok(mut d) => { |
| 861 | #[cfg(feature = "negative-controls")] |
| 862 | negctl::continuation_any_id(ctl, &mut minted, &rid, &mut d); |
| 863 | lc.apply_decision(&d).is_err() |
| 864 | } |
| 865 | Err(_) => true, |
| 866 | }; |
| 867 | rows.push(json!({"request_id": rid, "state": lc.state().name(), "refused": refused})); |
| 868 | } |
| 869 | let want = fx["expected"].as_array().cloned().unwrap_or_default(); |
| 870 | let mut errs = vec![]; |
| 871 | if want != rows { |
| 872 | errs.push(format!( |
| 873 | "steps: expected {}, got {}", |
| 874 | canonicalize(&Value::Array(want)), |
| 875 | canonicalize(&Value::Array(rows.clone())) |
| 876 | )); |
| 877 | } |
| 878 | (rows, errs) |
| 879 | } |
| 880 | |
| 881 | /// One row of the verdict file for a lifecycle case. |
| 882 | pub fn lifecycle_verdict(rows: &[Value], errs: &[String]) -> Value { |
| 883 | json!({"pass": errs.is_empty(), "steps": rows}) |
| 884 | } |
| 885 | |
| 886 | /// One case of a suite run: tag for the report, name, disagreements, per-case results payloads. |
| 887 | pub struct Outcome { |
| 888 | pub tag: String, |
| 889 | pub name: String, |
| 890 | pub errs: Vec<String>, |
| 891 | pub results: Option<Vec<Value>>, |
| 892 | /// The case's full input ledger (dump only). |
| 893 | pub ledger: Option<Vec<Value>>, |
| 894 | } |
| 895 | |
| 896 | /// Every case of a fixtures directory, in verdict order: the `NN-*` cases, the `injection/` cases, |
| 897 | /// the `lifecycle/` cases, then the digest fixtures. `rows` is the verdict file content. |
| 898 | pub struct Suite { |
| 899 | pub rows: Vec<(String, Value)>, |
| 900 | pub outcomes: Vec<Outcome>, |
| 901 | } |
| 902 | |
| 903 | impl Suite { |
| 904 | pub fn failed(&self) -> Vec<&Outcome> { |
| 905 | self.outcomes |
| 906 | .iter() |
| 907 | .filter(|o| !o.errs.is_empty()) |
| 908 | .collect() |
| 909 | } |
| 910 | /// Cases and lifecycle cases that count toward "N of M" (digest fixtures do not). |
| 911 | pub fn case_count(&self) -> usize { |
| 912 | self.outcomes.iter().filter(|o| o.tag != "-").count() |
| 913 | } |
| 914 | } |
| 915 | |
| 916 | /// Run a whole fixtures directory, optionally with a negative control applied. |
| 917 | pub fn run_suite(dir: &Path, ctl: Ctl) -> Result<Suite, String> { |
| 918 | let fixtures = load_fixtures(dir)?; |
| 919 | if fixtures.is_empty() { |
| 920 | return Err(format!("no NN-*.json fixtures in {}", dir.display())); |
| 921 | } |
| 922 | let mut rows = vec![]; |
| 923 | let mut outcomes = vec![]; |
| 924 | let injection = load_injection_fixtures(dir)?; |
| 925 | let approval = load_approval_fixtures(dir)?; |
| 926 | for (tag, fx) in fixtures |
| 927 | .iter() |
| 928 | .map(|f| (None, f)) |
| 929 | .chain(injection.iter().map(|f| (Some("in"), f))) |
| 930 | .chain(approval.iter().map(|f| (Some("ap"), f))) |
| 931 | { |
| 932 | let run = run_case_with(fx, ctl); |
| 933 | let errs = compare(fx, &run); |
| 934 | let tag = tag.map_or_else( |
| 935 | || run.case[..run.case.len().min(2)].to_string(), |
| 936 | String::from, |
| 937 | ); |
| 938 | rows.push((run.case.clone(), verdict(&run, &errs))); |
| 939 | outcomes.push(Outcome { |
| 940 | tag, |
| 941 | name: run.case.clone(), |
| 942 | errs, |
| 943 | results: Some(run.results.clone()), |
| 944 | ledger: Some(run.ledger.clone()), |
| 945 | }); |
| 946 | } |
| 947 | for fx in &load_lifecycle_fixtures(dir)? { |
| 948 | let case = fx["case"] |
| 949 | .as_str() |
| 950 | .unwrap_or("lifecycle/unnamed") |
| 951 | .to_string(); |
| 952 | let (steps, errs) = run_lifecycle_case_with(fx, ctl); |
| 953 | rows.push((case.clone(), lifecycle_verdict(&steps, &errs))); |
| 954 | outcomes.push(Outcome { |
| 955 | tag: "L".into(), |
| 956 | name: case, |
| 957 | errs, |
| 958 | results: None, |
| 959 | ledger: None, |
| 960 | }); |
| 961 | } |
| 962 | for (name, err) in check_digest_fixtures(dir) { |
| 963 | outcomes.push(Outcome { |
| 964 | tag: "-".into(), |
| 965 | name, |
| 966 | errs: err.into_iter().collect(), |
| 967 | results: None, |
| 968 | ledger: None, |
| 969 | }); |
| 970 | } |
| 971 | Ok(Suite { rows, outcomes }) |
| 972 | } |