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 / subset.rs

615 lines · 21474 bytes Raw Blame History
1//! The T3 and T4 subset rule and fixture translation (bench/PROTOCOL-0.3.md section 2; the normative
2//! text is spec/CORE.md, "Adapter subsets").
3//!
4//! The rule reads only fixture metadata and `conformance/adapter-translation.json`, never a
5//! result. The AIEN T4 runner and [`crate::adapter_runner`] execute exactly these plans. Values
6//! keep their key order ([`OJson`]) because translated tool-call arguments are written back as
7//! text in the order of the table, and `interplane-corpus subset --plans` must match the frozen
8//! byte form.
9use std::path::{Path, PathBuf};
10
11use regex::{Captures, Regex};
12use sha2::{Digest, Sha256};
13
14use crate::ojson::{dumps, obj, OJson, Style};
15
16fn qwen() -> Regex {
17 Regex::new(r"(?s)<tool_call>\s*<function=(\w+)>(.*?)</function>\s*</tool_call>").unwrap()
18}
19
20fn param() -> Regex {
21 Regex::new(r"(?s)<parameter=(\w+)>\n?(.*?)\n?</parameter>").unwrap()
22}
23
24/// The repository paths the rule reads.
25#[derive(Debug, Clone)]
26pub struct Corpus {
27 pub root: PathBuf,
28}
29
30impl Corpus {
31 pub fn new(root: &Path) -> Self {
32 Corpus {
33 root: root.to_path_buf(),
34 }
35 }
36
37 pub fn load_table(&self) -> Result<OJson, String> {
38 OJson::read(&self.root.join("conformance/adapter-translation.json"))
39 }
40
41 /// `(name, case)` for the injection and approval fixtures, `injection/NN-slug` order then approval.
42 pub fn fixtures(&self) -> Result<Vec<(String, OJson)>, String> {
43 let mut out = vec![];
44 for sub in ["injection", "approval"] {
45 let dir = self.root.join("conformance/fixtures").join(sub);
46 let mut names: Vec<String> = std::fs::read_dir(&dir)
47 .map_err(|e| format!("{}: {e}", dir.display()))?
48 .filter_map(|e| e.ok())
49 .map(|e| e.file_name().to_string_lossy().into_owned())
50 .filter(|n| n.ends_with(".json"))
51 .collect();
52 names.sort();
53 for n in names {
54 let case = OJson::read(&dir.join(&n))?;
55 out.push((format!("{sub}/{}", &n[..n.len() - 5]), case));
56 }
57 }
58 Ok(out)
59 }
60
61 /// The fixtures `adapter` must run, in corpus order.
62 pub fn subset(&self, adapter: &str, table: &OJson) -> Result<Vec<String>, String> {
63 let mut out = vec![];
64 for (n, c) in self.fixtures()? {
65 if decide_subset(&n, &c, adapter, table)?.0 {
66 out.push(n);
67 }
68 }
69 Ok(out)
70 }
71
72 /// The translated plans of `adapter`'s subset.
73 pub fn plans(&self, adapter: &str, table: &OJson) -> Result<Vec<OJson>, String> {
74 let fixtures = self.fixtures()?;
75 let mut out = vec![];
76 for (n, c) in &fixtures {
77 if decide_subset(n, c, adapter, table)?.0 {
78 out.push(translate(n, c, adapter, table)?);
79 }
80 }
81 Ok(out)
82 }
83}
84
85fn strs(v: &OJson) -> Vec<&str> {
86 v.as_arr().iter().filter_map(OJson::as_str).collect()
87}
88
89fn adapter_entry<'a>(table: &'a OJson, adapter: &str) -> Result<&'a OJson, String> {
90 let ad = table
91 .get("adapters")
92 .get_opt(adapter)
93 .ok_or_else(|| format!("{adapter} is not in the translation table"))?;
94 check_entry(adapter, ad)?;
95 Ok(ad)
96}
97
98/// Refuse a malformed table entry by name instead of reading it as empty: the effect-class maps
99/// must be objects, and every argument mapping's `from` a list of strings, `as` and `prefix` strings.
100fn check_entry(adapter: &str, ad: &OJson) -> Result<(), String> {
101 for key in ["effects", "approval_effects", "provider_failure_effects"] {
102 let Some(classes) = ad.get_opt(key) else {
103 continue;
104 };
105 let OJson::Obj(classes) = classes else {
106 return Err(format!("{adapter}: {key} must be an object"));
107 };
108 for (cap, spec) in classes {
109 for (arg, m) in spec.get("args").entries() {
110 let at = format!("{adapter}: {key}.{cap}.args.{arg}");
111 if m.get_opt("from").is_some_and(
112 |f| !matches!(f, OJson::Arr(a) if a.iter().all(|x| x.as_str().is_some())),
113 ) {
114 return Err(format!("{at}.from must be a list of strings"));
115 }
116 for k in ["as", "prefix"] {
117 if m.get_opt(k).is_some_and(|v| v.as_str().is_none()) {
118 return Err(format!("{at}.{k} must be a string"));
119 }
120 }
121 }
122 }
123 }
124 Ok(())
125}
126
127/// `ad[key]`, or the error Python's `KeyError` raised.
128fn class_map<'a>(adapter: &str, ad: &'a OJson, key: &str) -> Result<&'a OJson, String> {
129 ad.get_opt(key)
130 .ok_or_else(|| format!("{adapter}: table entry has no {key}"))
131}
132
133/// `[(capability, shape)]` a step calls, or `None` when the step is not an openai, qwen35 or
134/// envelope call.
135fn calls(step: &OJson) -> Option<Vec<(Option<String>, &'static str)>> {
136 if step.has("envelope") {
137 let name = step.get("envelope").get("payload").get("tool").get("name");
138 return Some(vec![(name.as_str().map(String::from), "envelope")]);
139 }
140 if step.has("dialect") {
141 return match step.get("dialect").as_str() {
142 Some("openai") => Some(
143 step.get("input")
144 .get("tool_calls")
145 .as_arr()
146 .iter()
147 .map(|c| {
148 (
149 c.get("function").get("name").as_str().map(String::from),
150 "openai",
151 )
152 })
153 .collect(),
154 ),
155 Some("qwen35") => Some(
156 qwen()
157 .captures_iter(step.get("input").as_str().unwrap_or(""))
158 .map(|m| (Some(m[1].to_string()), "qwen35"))
159 .collect(),
160 ),
161 _ => None,
162 };
163 }
164 Some(vec![])
165}
166
167/// `(in_subset, reason)`. The rule, in order; the first failing clause names the reason.
168pub fn decide_subset(
169 name: &str,
170 case: &OJson,
171 adapter: &str,
172 table: &OJson,
173) -> Result<(bool, Option<String>), String> {
174 let ad = adapter_entry(table, adapter)?;
175 let is_approval = name.starts_with("approval/");
176 let is_pf = strs(table.get("provider_failure_cases")).contains(&name);
177 let no = |r: String| Ok((false, Some(r)));
178 if is_pf && !ad.has("provider_failure_effects") {
179 return no("provider-failure case (protocol A15) runs on T4 only".into());
180 }
181 if strs(table.get("harness_keys"))
182 .iter()
183 .filter(|k| !(is_pf && **k == "mock_fault"))
184 .any(|k| case.has(k))
185 {
186 return no("carries a harness-only mock key".into());
187 }
188 let harness_steps = strs(table.get("harness_steps"));
189 for s in case.get("steps").as_arr() {
190 if harness_steps.iter().any(|k| s.has(k)) {
191 return no("has a harness-only mock step".into());
192 }
193 }
194 let classes = if is_approval {
195 let num: i64 = name
196 .split('/')
197 .nth(1)
198 .and_then(|s| s.get(..2))
199 .and_then(|s| s.parse().ok())
200 .ok_or_else(|| format!("{name}: approval fixture without a number"))?;
201 let range = table.get("approval_cases");
202 let (first, last) = (int(range.get("first")), int(range.get("last")));
203 if !is_pf && !(first <= num && num <= last) {
204 return no("not a protocol approval case (A01 to A14)".into());
205 }
206 class_map(
207 adapter,
208 ad,
209 if is_pf {
210 "provider_failure_effects"
211 } else {
212 "approval_effects"
213 },
214 )?
215 } else {
216 let target = case
217 .get("injection")
218 .get("target")
219 .get("capability")
220 .as_str()
221 .unwrap_or("");
222 let effects = class_map(adapter, ad, "effects")?;
223 if !effects.has(target) {
224 return no(format!(
225 "target capability class {target} not in the adapter catalog"
226 ));
227 }
228 effects
229 };
230 let mock_only = strs(table.get("mock_only_capabilities"));
231 for s in case.get("steps").as_arr() {
232 let Some(cs) = calls(s) else {
233 return no("dialect step the rule cannot translate".into());
234 };
235 for (cap, shape) in cs {
236 let cap = cap.unwrap_or_default();
237 if mock_only.contains(&cap.as_str()) {
238 return no(format!("uses mock-only capability {cap}"));
239 }
240 if classes.has(&cap) || ad.get("native_reads").has(&cap) {
241 continue;
242 }
243 if table.get("delivered_reads").has(&cap) && shape != "envelope" {
244 continue;
245 }
246 return no(format!("capability {cap} has no counterpart"));
247 }
248 }
249 Ok((true, None))
250}
251
252fn int(v: &OJson) -> i64 {
253 match v {
254 OJson::Int(i) => *i as i64,
255 _ => 0,
256 }
257}
258
259/// Translate an argument object by one adapter mapping; keys the mapping does not consume stay.
260fn map_args(spec: &OJson, args: &OJson) -> OJson {
261 let mut out = OJson::Obj(vec![]);
262 let mut used: Vec<String> = vec![];
263 for (key, m) in spec.get("args").entries() {
264 let keys: Vec<String> = match m.get_opt("from") {
265 Some(f) => strs(f).into_iter().map(String::from).collect(),
266 None => vec![key.clone()],
267 };
268 used.extend(keys.iter().cloned());
269 let mut val = keys
270 .iter()
271 .find_map(|k| args.get_opt(k))
272 .cloned()
273 .unwrap_or(OJson::Null);
274 if val.is_null() {
275 val = match m.get_opt("const") {
276 Some(c) => c.clone(),
277 None => m.get("default").clone(),
278 };
279 }
280 if val.is_null() {
281 continue;
282 }
283 if let OJson::Str(s) = &val {
284 let mut s = s.clone();
285 if m.get("as").as_str() == Some("basename") {
286 s = s.rsplit('/').next().unwrap_or("").to_string();
287 }
288 if let Some(p) = m.get("prefix").as_str() {
289 s = format!("{p}{s}");
290 }
291 val = OJson::Str(s);
292 }
293 out.set(key, val);
294 }
295 for (k, v) in args.entries() {
296 if !used.contains(k) {
297 out.set(k, v.clone());
298 }
299 }
300 out
301}
302
303fn target<'a>(cap: &str, ad: &'a OJson, classes: &'a OJson) -> Result<&'a OJson, String> {
304 classes
305 .get_opt(cap)
306 .or_else(|| ad.get("native_reads").get_opt(cap))
307 .ok_or_else(|| format!("capability {cap} has no counterpart"))
308}
309
310/// `"sha256:" + sha256(json.dumps(obj, sort_keys=True, separators=(",", ":")))`
311pub fn py_digest(v: &OJson) -> String {
312 let text = dumps(v, Style::SORTED_COMPACT);
313 format!("sha256:{:x}", Sha256::digest(text.as_bytes()))
314}
315
316fn delivery(cap: &str, rid: &str, case: &OJson, table: &OJson) -> OJson {
317 let lab = table.get("delivered_reads").get(cap);
318 let stored = case.get("mock_data").get(cap);
319 let content = if stored.truthy() {
320 stored
321 .get_opt("data")
322 .cloned()
323 .unwrap_or_else(|| format!("mock-delivered:{cap}").into())
324 } else {
325 format!("mock-delivered:{cap}").into()
326 };
327 obj([(
328 "host_input",
329 obj([(
330 "input",
331 obj([
332 ("input_id", format!("in-delivered-{rid}").into()),
333 ("content_kind", lab.get("content_kind").clone()),
334 ("trust", lab.get("trust").clone()),
335 (
336 "source",
337 obj([("kind", "runtime".into()), ("id", "host-delivery".into())]),
338 ),
339 ("origin", format!("runtime:delivery:{cap}").into()),
340 ("content_digest", py_digest(&content).into()),
341 ("trace_id", case.get("trace_id").clone()),
342 ("parent_id", OJson::Null),
343 ("derived_from", OJson::Arr(vec![])),
344 ]),
345 )]),
346 )])
347}
348
349fn py_int_text(v: &OJson) -> String {
350 match v {
351 OJson::Int(i) => i.to_string(),
352 OJson::Float(f) => (f.trunc() as i128).to_string(),
353 OJson::Bool(b) => (*b as i32).to_string(),
354 other => dumps(other, Style::PLAIN),
355 }
356}
357
358fn is_delivered(cap: &str, ad: &OJson, classes: &OJson, table: &OJson) -> bool {
359 table.get("delivered_reads").has(cap) && !classes.has(cap) && !ad.get("native_reads").has(cap)
360}
361
362/// Translate one call step. Calls the adapter lacks as read tools are dropped and queued as
363/// host-registered deliveries, appended to `plan` after the step itself.
364fn xlate_step(
365 step: &OJson,
366 case: &OJson,
367 ad: &OJson,
368 classes: &OJson,
369 table: &OJson,
370 plan: &mut Vec<OJson>,
371) -> Result<(), String> {
372 let mut deliveries = vec![];
373 let mut s = step.clone();
374 if s.has("envelope") {
375 let env = s.get_mut("envelope").unwrap();
376 let p = env.get_mut("payload").ok_or("envelope without payload")?;
377 let name = p.get("tool").get("name").as_str().unwrap_or("").to_string();
378 let spec = target(&name, ad, classes)?;
379 let new_name = spec.get("name").clone();
380 if let Some(tool) = p.get_mut("tool") {
381 tool.set("name", new_name.clone());
382 }
383 if let Some(prov) = p.get_mut("provenance") {
384 if prov.is_obj() {
385 prov.set("raw_name", new_name);
386 }
387 }
388 let args = p.get("arguments");
389 let args = if args.truthy() {
390 args.clone()
391 } else {
392 OJson::Obj(vec![])
393 };
394 p.set("arguments", map_args(spec, &args));
395 env.set(
396 "destination",
397 obj([
398 ("kind", "runtime".into()),
399 ("id", ad.get("runtime_id").clone()),
400 ]),
401 );
402 plan.push(s);
403 return Ok(());
404 }
405 let turn = py_int_text(step.get("turn"));
406 if s.get("dialect").as_str() == Some("openai") {
407 let mut kept = vec![];
408 for (i, c) in s.get("input").get("tool_calls").as_arr().iter().enumerate() {
409 let mut c = c.clone();
410 let cap = c
411 .get("function")
412 .get("name")
413 .as_str()
414 .unwrap_or("")
415 .to_string();
416 if is_delivered(&cap, ad, classes, table) {
417 let id = c.get("id");
418 let rid = if id.truthy() {
419 id.as_str()
420 .ok_or_else(|| {
421 format!("tool call id must be a string, not {}", py_str(id))
422 })?
423 .to_string()
424 } else {
425 format!("t{turn}c{i}")
426 };
427 deliveries.push(delivery(&cap, &rid, case, table));
428 continue;
429 }
430 let spec = target(&cap, ad, classes)?;
431 let f = c.get_mut("function").ok_or("tool call without function")?;
432 f.set("name", spec.get("name").clone());
433 let parsed = f
434 .get("arguments")
435 .as_str()
436 .and_then(|t| OJson::parse(t).ok());
437 if let Some(args @ OJson::Obj(_)) = parsed {
438 f.set(
439 "arguments",
440 dumps(&map_args(spec, &args), Style::PLAIN).into(),
441 );
442 }
443 kept.push(c);
444 }
445 let input = s.get_mut("input").ok_or("openai step without input")?;
446 input.set(
447 "tool_calls",
448 if kept.is_empty() {
449 OJson::Null
450 } else {
451 OJson::Arr(kept)
452 },
453 );
454 } else {
455 let text = s.get("input").as_str().unwrap_or("").to_string();
456 let trace = s_trace(case);
457 let mut idx = 0usize;
458 let mut err = None;
459 let params = param();
460 let replaced = qwen().replace_all(&text, |m: &Captures| {
461 let (cap, i) = (m[1].to_string(), idx);
462 idx += 1;
463 if is_delivered(&cap, ad, classes, table) {
464 deliveries.push(delivery(
465 &cap,
466 &format!("{trace}:t{turn}:c{i}"),
467 case,
468 table,
469 ));
470 return String::new();
471 }
472 let spec = match target(&cap, ad, classes) {
473 Ok(s) => s,
474 Err(e) => {
475 err = Some(e);
476 return String::new();
477 }
478 };
479 let mut found = OJson::Obj(vec![]);
480 for p in params.captures_iter(&m[2]) {
481 found.set(&p[1], p[2].to_string().into());
482 }
483 let args = map_args(spec, &found);
484 let body: String = args
485 .entries()
486 .iter()
487 .map(|(k, v)| format!("<parameter={k}>\n{}\n</parameter>\n", py_str(v)))
488 .collect();
489 format!(
490 "<tool_call>\n<function={}>\n{body}</function>\n</tool_call>",
491 spec.get("name").as_str().unwrap_or("")
492 )
493 });
494 if let Some(e) = err {
495 return Err(e);
496 }
497 s.set("input", replaced.trim().to_string().into());
498 }
499 plan.push(s);
500 plan.extend(deliveries);
501 Ok(())
502}
503
504fn s_trace(case: &OJson) -> String {
505 case.get("trace_id").as_str().unwrap_or("").to_string()
506}
507
508/// Python `"%s" % v` for the values a translated parameter can hold.
509fn py_str(v: &OJson) -> String {
510 match v {
511 OJson::Str(s) => s.clone(),
512 OJson::Null => "None".into(),
513 OJson::Bool(true) => "True".into(),
514 OJson::Bool(false) => "False".into(),
515 other => dumps(other, Style::PLAIN),
516 }
517}
518
519fn approval_id(a: &OJson) -> Result<OJson, String> {
520 let id = match a.get("approval_id") {
521 OJson::Str(s) => s.clone(),
522 v if !v.truthy() => String::new(),
523 v => return Err(format!("approval_id must be a string, not {}", py_str(v))),
524 };
525 Ok(match id.strip_prefix("mock-approval-") {
526 Some(rest) if !rest.is_empty() && !rest.contains('\n') => {
527 obj([("minted_for", rest.to_string().into())])
528 }
529 _ => obj([("literal", id.into())]),
530 })
531}
532
533/// The plan of one fixture for `adapter`.
534pub fn translate(name: &str, case: &OJson, adapter: &str, table: &OJson) -> Result<OJson, String> {
535 let ad = adapter_entry(table, adapter)?;
536 let is_approval = name.starts_with("approval/");
537 let classes = if strs(table.get("provider_failure_cases")).contains(&name) {
538 class_map(adapter, ad, "provider_failure_effects")?
539 } else if is_approval {
540 class_map(adapter, ad, "approval_effects")?
541 } else {
542 class_map(adapter, ad, "effects")?
543 };
544 let mut plan = vec![];
545 for step in case.get("steps").as_arr() {
546 if step.has("approve") || step.has("cancel") {
547 let kind = if step.has("approve") {
548 "approve"
549 } else {
550 "cancel"
551 };
552 let mut a = step.get(kind).clone();
553 if kind == "approve" {
554 a.set("approval_id", approval_id(&a)?);
555 if a.has("arguments") {
556 let spec = classes
557 .get_opt("delete_file")
558 .ok_or("approval arguments without a delete_file mapping")?;
559 let mapped = map_args(spec, a.get("arguments"));
560 a.set("arguments", mapped);
561 }
562 }
563 plan.push(obj([(kind, a)]));
564 } else if step.has("restart") {
565 plan.push(obj([("restart", OJson::Bool(true))]));
566 } else if step.has("envelope") || step.has("dialect") {
567 xlate_step(step, case, ad, classes, table, &mut plan)?;
568 } else {
569 plan.push(obj([("host_input", step.clone())]));
570 }
571 }
572 let mut out = obj([
573 ("name", name.into()),
574 ("case", case.get("case").clone()),
575 (
576 "kind",
577 if is_approval { "approval" } else { "injection" }.into(),
578 ),
579 ("trace_id", case.get("trace_id").clone()),
580 ("steps", OJson::Arr(plan)),
581 ]);
582 if is_approval {
583 out.set(
584 "expires_at",
585 case.get("mock_approval").get("expires_at").clone(),
586 );
587 let exp = case.get("expected");
588 out.set(
589 "expected",
590 obj([
591 ("observed", exp.get("observed").clone()),
592 (
593 "continuations",
594 exp.get_opt("continuations")
595 .cloned()
596 .unwrap_or(OJson::Arr(vec![])),
597 ),
598 ]),
599 );
600 } else {
601 let t = case.get("injection").get("target");
602 let cap = t.get("capability").as_str().unwrap_or("");
603 let spec = classes
604 .get_opt(cap)
605 .ok_or_else(|| format!("{name}: target {cap} has no mapping"))?;
606 out.set(
607 "target",
608 obj([
609 ("capability", spec.get("name").clone()),
610 ("argument_contains", t.get("argument_contains").clone()),
611 ]),
612 );
613 }
614 Ok(out)
615}