interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / rust / crates / interplane-conformance / src / adapter_runner.rs

499 lines · 19661 bytes Raw Blame History
1//! Run a new adapter through its computed subset and judge it (spec/CORE.md, "Adding an adapter").
2//!
3//! An adapter implements [`AdapterHost`]: its runtime and policy names, a fresh authority per case
4//! (`no_exposure_check` drops the authority's exposure floor check: the negative control) and the
5//! pipeline it runs behind. The table entry is added to an in-memory copy of
6//! `conformance/adapter-translation.json`, which is never written, so TRUST-DIGEST is untouched.
7//!
8//! Approval cases are judged by the A-AIEN rule (the adapter supports approval continuation). The
9//! judge is the one the independent reproduction wrote from the spec text
10//! (bench/runs/adapter-repro-20261005T1215Z), with the adapter-specific names taken from the host
11//! and the table entry. [`run`] returns the per-case verdicts and a summary; `pass` holds when
12//! every case passes. `tests/adapter_runner.rs` reproduces both recorded adapter runs (see there).
13use std::collections::{HashMap, HashSet};
14use std::path::Path;
15
16use interplane_core::{digest, CapabilityRequest, Catalog, Decision, InputRecord, ToolResult};
17use interplane_crossveil::{
18 capability_request_digest, CallContext, ObservedRecord, Pipeline, RuntimeAuthority,
19};
20use regex::Regex;
21use serde_json::{json, Value};
22
23use crate::ojson::{dumps, obj, OJson, Style};
24use crate::subset::Corpus;
25
26/// What an adapter supplies to be judged.
27pub trait AdapterHost {
28 /// The authority's runtime id (`authority.runtime` in its decisions).
29 fn runtime(&self) -> &str;
30 /// The authority's policy engine name.
31 fn policy(&self) -> &str;
32 /// A fresh authority for one case. `expires_at` is the case's approval expiry, if any.
33 fn make_authority(
34 &self,
35 no_exposure_check: bool,
36 expires_at: Option<&str>,
37 ) -> Box<dyn RuntimeAuthority>;
38 /// The pipeline the adapter runs behind, over `authority` (called again on a restart step).
39 fn make_pipeline<'a>(&self, authority: &'a mut dyn RuntimeAuthority) -> Pipeline<'a>;
40}
41
42/// Wraps the host authority and keeps its callback evidence, including attempted effects.
43struct Recorder {
44 inner: Box<dyn RuntimeAuthority>,
45 decided: Vec<(String, String, Value)>,
46 executed: Vec<(String, String, Value)>,
47}
48
49impl RuntimeAuthority for Recorder {
50 fn runtime_id(&self) -> &str {
51 self.inner.runtime_id()
52 }
53 fn decide(&mut self, req: &CapabilityRequest, ctx: &CallContext) -> Decision {
54 self.decided.push((
55 req.request_id.clone(),
56 req.capability.clone(),
57 Value::Object(req.arguments.clone()),
58 ));
59 self.inner.decide(req, ctx)
60 }
61 fn execute(&mut self, req: &CapabilityRequest, d: &Decision, ctx: &CallContext) -> ToolResult {
62 self.executed.push((
63 req.request_id.clone(),
64 req.capability.clone(),
65 Value::Object(req.arguments.clone()),
66 ));
67 self.inner.execute(req, d, ctx)
68 }
69 fn catalog(&self) -> Catalog {
70 self.inner.catalog()
71 }
72}
73
74fn public_observed(o: &ObservedRecord) -> OJson {
75 let v = serde_json::to_value(o).expect("observed record serializes");
76 OJson::Obj(
77 [
78 "request_id",
79 "stage",
80 "decision",
81 "status",
82 "error_code",
83 "decide_invoked",
84 "execute_invoked",
85 "result_digest",
86 ]
87 .iter()
88 .map(|k| (k.to_string(), OJson::from_value(&v[*k])))
89 .collect(),
90 )
91}
92
93/// IDs of calls explicitly emitted by model steps, before host deliveries.
94fn model_request_ids(plan: &OJson) -> HashSet<String> {
95 let qwen =
96 Regex::new(r"(?s)<tool_call>\s*<function=(\w+)>(.*?)</function>\s*</tool_call>").unwrap();
97 let trace = plan.get("trace_id").as_str().unwrap_or("");
98 let mut ids = HashSet::new();
99 for step in plan.get("steps").as_arr() {
100 let turn = dumps(step.get("turn"), Style::PLAIN);
101 if step.has("envelope") {
102 if let Some(id) = step
103 .get("envelope")
104 .get("payload")
105 .get("request_id")
106 .as_str()
107 {
108 ids.insert(id.to_string());
109 }
110 } else if step.get("dialect").as_str() == Some("openai") {
111 for (i, call) in step
112 .get("input")
113 .get("tool_calls")
114 .as_arr()
115 .iter()
116 .enumerate()
117 {
118 let id = call.get("id");
119 ids.insert(match id.as_str() {
120 Some(s) if !s.is_empty() => s.to_string(),
121 _ => format!("{trace}:t{turn}:c{i}"),
122 });
123 }
124 } else if step.get("dialect").as_str() == Some("qwen35") {
125 let n = qwen
126 .find_iter(step.get("input").as_str().unwrap_or(""))
127 .count();
128 ids.extend((0..n).map(|i| format!("{trace}:t{turn}:c{i}")));
129 }
130 }
131 ids
132}
133
134fn opt(s: Option<&str>) -> OJson {
135 s.map_or(OJson::Null, |s| s.into())
136}
137
138struct Adapter<'h, H: AdapterHost + ?Sized> {
139 name: String,
140 host: &'h H,
141 approval_capability: Option<String>,
142}
143
144/// `v[key]`, or the error text Python's `KeyError` gave.
145fn need<'a>(v: &'a OJson, key: &str) -> Result<&'a OJson, String> {
146 if v.has(key) {
147 Ok(v.get(key))
148 } else {
149 Err(format!("KeyError: '{key}'"))
150 }
151}
152
153fn run_case<H: AdapterHost + ?Sized>(
154 plan: &OJson,
155 fixture: &OJson,
156 adapter: &Adapter<'_, H>,
157 no_exposure_check: bool,
158) -> Result<OJson, String> {
159 let host = adapter.host;
160 let mut rec = Recorder {
161 inner: host.make_authority(no_exposure_check, plan.get("expires_at").as_str()),
162 decided: vec![],
163 executed: vec![],
164 };
165 let trace = plan.get("trace_id").as_str().unwrap_or("").to_string();
166 let explicit_ids = model_request_ids(plan);
167 let mut observed: Vec<OJson> = vec![];
168 let mut continuations: Vec<OJson> = vec![];
169 let mut minted: HashMap<String, String> = HashMap::new();
170 let mut stages: HashMap<String, String> = HashMap::new();
171 {
172 let mut pipe = host.make_pipeline(&mut rec);
173 let note = |pipe: &Pipeline<'_>,
174 o: &ObservedRecord,
175 stages: &mut HashMap<String, String>,
176 minted: &mut HashMap<String, String>| {
177 if let Some(rid) = &o.request_id {
178 stages.insert(rid.clone(), o.stage.clone());
179 if let Some(p) = pipe.pending_approval(&trace, rid) {
180 minted.insert(rid.clone(), p.approval_id);
181 }
182 }
183 };
184 for (index, step) in plan.get("steps").as_arr().iter().enumerate() {
185 if let Some(h) = step.get_opt("host_input") {
186 let r: InputRecord = serde_json::from_value(h.get("input").to_value())
187 .map_err(|e| format!("ValueError: {e}"))?;
188 pipe.register_input(r)
189 .map_err(|e| format!("ValueError: {e}"))?;
190 } else if step.has("dialect") {
191 let turn = match step.get("turn") {
192 OJson::Int(i) => *i as u64,
193 _ => 0,
194 };
195 let out = pipe.run_turn(
196 step.get("dialect").as_str().unwrap_or(""),
197 step.get("model").as_str().unwrap_or(""),
198 &step.get("input").to_value(),
199 &trace,
200 turn,
201 );
202 for o in &out.records {
203 observed.push(public_observed(o));
204 note(&pipe, o, &mut stages, &mut minted);
205 }
206 } else if step.has("envelope") {
207 let (_, o) = pipe.admit_value(&step.get("envelope").to_value());
208 observed.push(public_observed(&o));
209 note(&pipe, &o, &mut stages, &mut minted);
210 } else if step.has("restart") {
211 drop(pipe);
212 pipe = host.make_pipeline(&mut rec);
213 stages.clear();
214 } else if step.has("approve") || step.has("cancel") {
215 let kind = if step.has("approve") {
216 "approve"
217 } else {
218 "cancel"
219 };
220 let action = step.get(kind);
221 let rid = action.get("request_id").as_str().unwrap_or("").to_string();
222 let tr = action
223 .get("trace_id")
224 .as_str()
225 .unwrap_or(&trace)
226 .to_string();
227 let out = if kind == "cancel" {
228 pipe.cancel_approval(&tr, &rid)
229 } else {
230 let pending = pipe.pending_approval(&tr, &rid);
231 let spec = action.get("approval_id");
232 let approval_id = match spec.get("minted_for").as_str() {
233 Some(owner) => minted
234 .get(owner)
235 .cloned()
236 .unwrap_or(format!("{}-approval-{owner}", adapter.name)),
237 None => spec.get("literal").as_str().unwrap_or("").to_string(),
238 };
239 let (request_digest, capability) = match &pending {
240 Some(p) => {
241 let d = match action.get_opt("arguments") {
242 Some(args) => {
243 let mut changed = p.capability_request.clone();
244 changed.arguments =
245 args.to_value().as_object().cloned().unwrap_or_default();
246 capability_request_digest(&changed)
247 }
248 None => p.request_digest.clone(),
249 };
250 (d, Some(p.capability_request.capability.clone()))
251 }
252 None => (digest(&Value::Null), adapter.approval_capability.clone()),
253 };
254 let decision: Decision = serde_json::from_value(json!({
255 "kind": "decision",
256 "request_id": action.get_opt("decision_request_id").map_or(json!(rid), OJson::to_value),
257 "decision": action.get_opt("decision").map_or(json!("authorized"), OJson::to_value),
258 "capability": capability,
259 "authority": {"runtime": host.runtime(), "policy_engine": host.policy(),
260 "decision_id": format!("{}-host-grant-{rid}", adapter.name)},
261 "approval": {"approval_id": approval_id, "scope": "single_action",
262 "expires_at": pending.as_ref().and_then(|p| p.expires_at.clone())},
263 }))
264 .map_err(|e| format!("ValueError: {e}"))?;
265 let now = action
266 .get("now")
267 .as_str()
268 .unwrap_or("2026-01-01T00:00:00Z")
269 .to_string();
270 pipe.continue_approval(&tr, &rid, &decision, &request_digest, &now)
271 };
272 match out {
273 Ok((result, o)) => {
274 observed.push(public_observed(&o));
275 stages.insert(rid.clone(), o.stage.clone());
276 continuations.push(obj([
277 ("step", OJson::Int(index as i128)),
278 ("kind", kind.into()),
279 ("request_id", rid.into()),
280 ("outcome", "resolved".into()),
281 ("stage", o.stage.clone().into()),
282 ("reason", OJson::Null),
283 (
284 "message",
285 opt(result.error.as_ref().map(|e| e.message.as_str())),
286 ),
287 ]));
288 }
289 Err(refusal) => {
290 let stage = opt(stages.get(&rid).map(String::as_str));
291 continuations.push(obj([
292 ("step", OJson::Int(index as i128)),
293 ("kind", kind.into()),
294 ("request_id", rid.into()),
295 ("outcome", "refused".into()),
296 ("stage", stage),
297 ("reason", refusal.as_str().into()),
298 ("message", OJson::Null),
299 ]));
300 }
301 }
302 } else {
303 return Err(format!(
304 "ValueError: untranslated step at index {index}: {:?}",
305 step.keys()
306 ));
307 }
308 }
309 }
310 let decide_calls = rec.decided.len() as i128;
311 let execute_calls = rec.executed.len() as i128;
312 let mut row = obj([
313 ("name", plan.get("name").clone()),
314 ("pass", OJson::Bool(false)),
315 ("executed", OJson::Bool(true)),
316 ("observed", OJson::Arr(observed.clone())),
317 ]);
318 if plan.get("kind").as_str() == Some("injection") {
319 let target = plan.get("target").get("capability").as_str().unwrap_or("");
320 let canary = plan
321 .get("target")
322 .get("argument_contains")
323 .as_str()
324 .unwrap_or("");
325 let injected = |e: &&(String, String, Value)| {
326 e.1 == target && dumps(&OJson::from_value(&e.2), Style::SORTED).contains(canary)
327 };
328 let intents = rec.decided.iter().filter(injected).count() as i128;
329 let violations = rec.executed.iter().filter(injected).count() as i128;
330 let derived = rec
331 .decided
332 .iter()
333 .filter(|(rid, _, _)| !explicit_ids.contains(rid))
334 .count() as i128;
335 row.set(
336 "injection",
337 obj([
338 ("injected_intents", OJson::Int(intents)),
339 ("violations", OJson::Int(violations)),
340 ("content_derived", OJson::Int(derived)),
341 ]),
342 );
343 row.set(
344 "pass",
345 OJson::Bool(intents > 0 && violations == 0 && derived == 0),
346 );
347 } else {
348 // A missing key is an error row, as the Python runner gave (`KeyError: 'runtime'`).
349 let expected = need(fixture, "expected")?;
350 let want_runtime = need(expected, "runtime")?.to_value();
351 let left: Vec<Value> = observed
352 .iter()
353 .map(|r| {
354 let mut r = r.clone();
355 r.set("result_digest", OJson::Null);
356 r.to_value()
357 })
358 .collect();
359 let want: Vec<Value> = need(expected, "observed")?
360 .as_arr()
361 .iter()
362 .map(OJson::to_value)
363 .collect();
364 let keys = ["step", "kind", "request_id", "outcome", "stage", "reason"];
365 let pick = |rows: &[OJson]| -> Vec<Value> {
366 rows.iter()
367 .map(|r| {
368 Value::Object(
369 keys.iter()
370 .map(|k| (k.to_string(), r.get(k).to_value()))
371 .collect(),
372 )
373 })
374 .collect()
375 };
376 let runtime = json!({"decide_calls": decide_calls, "execute_calls": execute_calls});
377 let checks = obj([
378 ("observed", OJson::Bool(left == want)),
379 (
380 "continuations",
381 OJson::Bool(pick(&continuations) == pick(expected.get("continuations").as_arr())),
382 ),
383 ("runtime", OJson::Bool(runtime == want_runtime)),
384 ]);
385 let all = checks
386 .entries()
387 .iter()
388 .all(|(_, v)| *v == OJson::Bool(true));
389 row.set("continuations", OJson::Arr(continuations));
390 row.set("checks", checks);
391 row.set("pass", OJson::Bool(all));
392 }
393 Ok(row)
394}
395
396/// Per-case verdicts and the summary of one adapter run.
397#[derive(Debug, Clone)]
398pub struct Verdicts {
399 pub adapter: String,
400 /// `{"rows": [...], "summary": {...}}`
401 pub value: OJson,
402}
403
404impl Verdicts {
405 pub fn summary(&self) -> &OJson {
406 self.value.get("summary")
407 }
408
409 /// True when every case in the subset passed.
410 pub fn passed(&self) -> bool {
411 matches!(self.summary().get("failed"), OJson::Int(0))
412 }
413
414 /// The verdict file: indented, keys sorted, one trailing newline.
415 pub fn file_text(&self) -> String {
416 dumps(&self.value, Style::SORTED_INDENT2) + "\n"
417 }
418}
419
420/// Run `host` through its subset. `entry` adds `{name: entry}` to an in-memory copy of the shared
421/// table; `None` uses the adapter already in the table under `name`.
422pub fn run<H: AdapterHost + ?Sized>(
423 root: &Path,
424 name: &str,
425 entry: Option<&OJson>,
426 host: &H,
427 no_exposure_check: bool,
428) -> Result<Verdicts, String> {
429 let corpus = Corpus::new(root);
430 let mut table = corpus.load_table()?;
431 if let Some(e) = entry {
432 let adapters = table
433 .get_mut("adapters")
434 .ok_or("translation table without adapters")?;
435 adapters.set(name, e.clone());
436 }
437 let entry = table
438 .get("adapters")
439 .get_opt(name)
440 .ok_or_else(|| format!("{name} is not in conformance/adapter-translation.json"))?
441 .clone();
442 let adapter = Adapter {
443 name: name.to_string(),
444 host,
445 approval_capability: entry
446 .get("approval_effects")
447 .get("delete_file")
448 .get("name")
449 .as_str()
450 .map(String::from),
451 };
452 let plans = corpus.plans(name, &table)?;
453 let fixtures: HashMap<String, OJson> = corpus.fixtures()?.into_iter().collect();
454 let mut rows = vec![];
455 for plan in &plans {
456 let pname = plan.get("name").as_str().unwrap_or("").to_string();
457 let case = fixtures
458 .get(&pname)
459 .ok_or_else(|| format!("KeyError: '{pname}'"))
460 .and_then(|f| run_case(plan, f, &adapter, no_exposure_check));
461 let row = match case {
462 Ok(r) => r,
463 Err(e) => obj([
464 ("name", pname.into()),
465 ("pass", OJson::Bool(false)),
466 ("executed", OJson::Bool(false)),
467 ("error", e.into()),
468 ]),
469 };
470 rows.push(row);
471 }
472 let count = |f: &dyn Fn(&OJson) -> bool| rows.iter().filter(|r| f(r)).count() as i128;
473 let sum = |k: &str| -> i128 {
474 rows.iter()
475 .map(|r| match r.get("injection").get(k) {
476 OJson::Int(i) => *i,
477 _ => 0,
478 })
479 .sum()
480 };
481 let summary = obj([
482 ("subset_size", OJson::Int(plans.len() as i128)),
483 (
484 "executed",
485 OJson::Int(count(&|r| *r.get("executed") == OJson::Bool(true))),
486 ),
487 (
488 "failed",
489 OJson::Int(count(&|r| *r.get("pass") != OJson::Bool(true))),
490 ),
491 ("violations", OJson::Int(sum("violations"))),
492 ("content_derived", OJson::Int(sum("content_derived"))),
493 ("injected_intents", OJson::Int(sum("injected_intents"))),
494 ]);
495 Ok(Verdicts {
496 adapter: name.to_string(),
497 value: obj([("rows", OJson::Arr(rows)), ("summary", summary)]),
498 })
499}