Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-mv/blob/main/rust/crates/interplane-conformance/src/fixture_check.rs # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-mv / rust / crates / interplane-conformance / src / fixture_check.rs` 1557 lines ยท 58528 bytes Raw Blame History 1 //! Validate the INTERPLANE conformance and dialect fixtures against `spec/schemas`. 2 //! 3 //! Checks: 4 //! * every explicit envelope step validates against envelope.schema.json 5 //! * every intent in dialects/fixtures validates against intent.schema.json 6 //! * fixture shape, 40 required cases, filename == case slug 7 //! * lifecycle/ fixtures: required set, shape, minting decisions valid against decision.schema.json 8 //! * expected.runtime counts agree with the observed records 9 //! * every digest fixture recomputes; InputRecord examples (one per source class) validate 10 //! * injection and approval fixtures: shape, categories, and negative controls on mutants 11 //! * gate I corpus accounting and gate N category coverage (bench/PROTOCOL-0.3.md 3.2) 12 //! * negative control: a mutated envelope MUST fail validation 13 //! 14 //! [`run`] returns the summary lines and every failure; the `interplane-corpus validate` command 15 //! prints them and exits non-zero on any failure. 16 //! 17 //! Its report is byte-identical to the retired Python validator's when the corpus passes and when a 18 //! check other than a schema check fails. Schema failures differ in wording: the error text comes 19 //! from the `jsonschema` crate, not the Python `jsonschema` package. Malformed names and a case 15 20 //! without a tool call are reported as errors where the Python validator raised. 21 use std::collections::{BTreeSet, HashSet}; 22 use std::path::{Path, PathBuf}; 23 24 use interplane_core::canonicalize; 25 use jsonschema::{Resource, Validator}; 26 use regex::Regex; 27 use serde_json::{json, Value}; 28 use sha2::{Digest, Sha256}; 29 30 use crate::ojson::{dumps, obj, OJson, Style}; 31 32 /// What a run found: the summary lines (printed on success and failure) and the failures. 33 #[derive(Debug, Default)] 34 pub struct Report { 35 pub lines: Vec, 36 pub errors: Vec, 37 } 38 39 impl Report { 40 pub fn passed(&self) -> bool { 41 self.errors.is_empty() 42 } 43 44 /// The text the command prints: summary lines, then `PASS` or `FAIL (n)` with every failure. 45 pub fn text(&self) -> String { 46 let mut out: String = self.lines.iter().map(|l| format!("{l}\n")).collect(); 47 if self.errors.is_empty() { 48 out.push_str("PASS\n"); 49 } else { 50 out.push_str(&format!("FAIL ({})\n", self.errors.len())); 51 for e in &self.errors { 52 out.push_str(&format!(" - {e}\n")); 53 } 54 } 55 out 56 } 57 } 58 59 /// Every schema under `spec/schemas`, sorted by file name: `(file name, schema)`. 60 pub fn load_schemas(root: &Path) -> Result, String> { 61 let dir = root.join("spec/schemas"); 62 let mut names: Vec = std::fs::read_dir(&dir) 63 .map_err(|e| format!("{}: {e}", dir.display()))? 64 .filter_map(|e| e.ok()) 65 .map(|e| e.file_name().to_string_lossy().into_owned()) 66 .filter(|n| n.ends_with(".json")) 67 .collect(); 68 names.sort(); 69 names 70 .into_iter() 71 .map(|n| { 72 let text = std::fs::read_to_string(dir.join(&n)).map_err(|e| format!("{n}: {e}"))?; 73 let v: Value = serde_json::from_str(&text).map_err(|e| format!("{n}: {e}"))?; 74 Ok((n, v)) 75 }) 76 .collect() 77 } 78 79 /// Check every schema against the JSON Schema 2020-12 meta-schema; one `ok ` line each. 80 pub fn self_check_schemas(root: &Path) -> Result, String> { 81 let mut out = vec![]; 82 for (n, s) in load_schemas(root)? { 83 jsonschema::meta::validate(&s).map_err(|e| format!("spec/schemas/{n}: {e}"))?; 84 out.push(format!("ok spec/schemas/{n}")); 85 } 86 Ok(out) 87 } 88 89 struct Schemas { 90 all: Vec<(String, Value)>, 91 } 92 93 impl Schemas { 94 fn validator(&self, name: &str) -> Result { 95 let main = &self 96 .all 97 .iter() 98 .find(|(n, _)| n == name) 99 .ok_or_else(|| format!("schema {name} missing"))? 100 .1; 101 jsonschema::meta::validate(main).map_err(|e| format!("{name}: {e}"))?; 102 let mut resources = vec![]; 103 for (_, s) in &self.all { 104 if let Some(id) = s["$id"].as_str() { 105 let r = Resource::from_contents(s.clone()).map_err(|e| e.to_string())?; 106 resources.push((id.to_string(), r)); 107 } 108 } 109 jsonschema::options() 110 .with_resources(resources.into_iter()) 111 .build(main) 112 .map_err(|e| format!("{name}: {e}")) 113 } 114 } 115 116 struct Ctx { 117 errors: Vec, 118 } 119 120 impl Ctx { 121 fn fail(&mut self, m: String) { 122 self.errors.push(m); 123 } 124 125 /// Validate `inst`; record at most three schema errors, ordered by instance path. 126 fn check(&mut self, v: &Validator, inst: &OJson, where_: &str) -> bool { 127 let value = inst.to_value(); 128 let mut errs: Vec<(Vec, String)> = v 129 .iter_errors(&value) 130 .map(|e| { 131 let path = segments(&value, &e.instance_path.to_string()); 132 (path, e.to_string()) 133 }) 134 .collect(); 135 // Python sorted by `list(e.absolute_path)`: indices as numbers, keys as text. 136 errs.sort_by(|a, b| a.0.cmp(&b.0)); 137 for (path, msg) in errs.iter().take(3) { 138 let msg: String = msg.chars().take(200).collect(); 139 let shown: Vec = path.iter().map(Seg::to_string).collect(); 140 self.fail(format!("{where_}: {msg} at /{}", shown.join("/"))); 141 } 142 errs.is_empty() 143 } 144 } 145 146 /// One step of an instance path, typed by the value it steps into (an array index or an object key). 147 #[derive(PartialEq, Eq, PartialOrd, Ord)] 148 enum Seg { 149 Index(usize), 150 Key(String), 151 } 152 153 impl std::fmt::Display for Seg { 154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 155 match self { 156 Seg::Index(i) => write!(f, "{i}"), 157 Seg::Key(k) => f.write_str(k), 158 } 159 } 160 } 161 162 /// Split a JSON pointer into typed steps by walking `root`, so index `10` sorts after index `2` and 163 /// a numeric-looking object key stays a key. 164 fn segments(root: &serde_json::Value, pointer: &str) -> Vec { 165 let mut at = Some(root); 166 let mut out = Vec::new(); 167 for raw in pointer.split('/').skip(1) { 168 let key = raw.replace("~1", "/").replace("~0", "~"); 169 let seg = match (at, key.parse::()) { 170 (Some(serde_json::Value::Array(_)), Ok(i)) => Seg::Index(i), 171 _ => Seg::Key(key), 172 }; 173 at = at.and_then(|v| match &seg { 174 Seg::Index(i) => v.get(*i), 175 Seg::Key(k) => v.get(k.as_str()), 176 }); 177 out.push(seg); 178 } 179 out 180 } 181 182 /// Python `s[start:end]` on code points: clamps to the string and never panics. 183 fn py_slice(s: &str, start: usize, end: Option) -> String { 184 let rest = s.chars().skip(start); 185 match end { 186 Some(e) => rest.take(e.saturating_sub(start)).collect(), 187 None => rest.collect(), 188 } 189 } 190 191 fn valid(v: &Validator, inst: &OJson) -> bool { 192 v.is_valid(&inst.to_value()) 193 } 194 195 fn jcs(v: &OJson) -> String { 196 canonicalize(&v.to_value()) 197 } 198 199 fn sha_hex(b: &[u8]) -> String { 200 format!("{:x}", Sha256::digest(b)) 201 } 202 203 /// Python `repr` of a value, for the few messages that print one. 204 fn py_repr(v: &OJson) -> String { 205 match v { 206 OJson::Null => "None".into(), 207 OJson::Bool(true) => "True".into(), 208 OJson::Bool(false) => "False".into(), 209 OJson::Str(s) => py_repr_str(s), 210 OJson::Arr(a) => format!("[{}]", a.iter().map(py_repr).collect::>().join(", ")), 211 OJson::Obj(_) => py_dict_repr(v), 212 other => dumps(other, Style::PLAIN), 213 } 214 } 215 216 fn py_repr_str(s: &str) -> String { 217 let q = if s.contains('\'') && !s.contains('"') { 218 '"' 219 } else { 220 '\'' 221 }; 222 let mut out = String::from(q); 223 for c in s.chars() { 224 match c { 225 '\\' => out.push_str("\\\\"), 226 '\n' => out.push_str("\\n"), 227 '\r' => out.push_str("\\r"), 228 '\t' => out.push_str("\\t"), 229 c if c == q => { 230 out.push('\\'); 231 out.push(c); 232 } 233 c if (c as u32) < 0x20 || c as u32 == 0x7f => { 234 out.push_str(&format!("\\x{:02x}", c as u32)) 235 } 236 c => out.push(c), 237 } 238 } 239 out.push(q); 240 out 241 } 242 243 fn py_list>(items: &[S]) -> String { 244 let inner: Vec = items.iter().map(|s| py_repr_str(s.as_ref())).collect(); 245 format!("[{}]", inner.join(", ")) 246 } 247 248 fn sym_diff(a: &BTreeSet, b: &BTreeSet) -> Vec { 249 a.symmetric_difference(b).cloned().collect() 250 } 251 252 fn set_of(v: &OJson) -> BTreeSet { 253 v.keys().into_iter().map(String::from).collect() 254 } 255 256 fn set(items: [&str; N]) -> BTreeSet { 257 items.into_iter().map(String::from).collect() 258 } 259 260 fn json_files(dir: &Path) -> Vec { 261 let mut out: Vec = std::fs::read_dir(dir) 262 .map(|rd| { 263 rd.filter_map(|e| e.ok()) 264 .map(|e| e.path()) 265 .filter(|p| p.is_file() && p.extension().is_some_and(|x| x == "json")) 266 .collect() 267 }) 268 .unwrap_or_default(); 269 out.sort(); 270 out 271 } 272 273 fn stem(p: &Path) -> String { 274 let n = p.file_name().unwrap().to_string_lossy(); 275 n[..n.len() - 5].to_string() 276 } 277 278 fn count_true(obs: &[OJson], key: &str) -> i128 { 279 obs.iter().filter(|o| o.get(key).truthy()).count() as i128 280 } 281 282 fn as_int(v: &OJson) -> Option { 283 match v { 284 OJson::Int(i) => Some(*i), 285 _ => None, 286 } 287 } 288 289 const REQUIRED: [&str; 40] = [ 290 "01-valid-tool-request", 291 "02-malformed-arguments", 292 "03-nonexistent-tool", 293 "04-unknown-capability", 294 "05-policy-denial", 295 "06-explicit-approval", 296 "07-successful-execution", 297 "08-execution-error", 298 "09-timeout", 299 "10-multiple-sequential-calls", 300 "11-model-continuation", 301 "12-unsupported-dialect", 302 "13-unsupported-version", 303 "14-unknown-fields", 304 "15-oversized-arguments", 305 "16-duplicate-request-ids", 306 "17-replay", 307 "18-model-retry-after-denial", 308 "19-valid-write-request", 309 "20-missing-required-argument", 310 "21-stale-capability-mapping", 311 "22-untrusted-tool-result", 312 "23-untrusted-memory-result", 313 "24-expansion-requested-excluded", 314 "25-expansion-refused-by-bound", 315 "26-unrecognized-content-kind", 316 "27-absent-null-unrecognized-trust", 317 "28-input-ledger-continues", 318 "29-input-derived-from", 319 "30-input-forged-exposure", 320 "31-source-class-workspace", 321 "32-source-class-web", 322 "33-source-class-memory", 323 "34-source-class-document", 324 "35-source-class-skill", 325 "36-source-class-tool-output", 326 "37-source-class-external-provider", 327 "38-source-class-runtime-generated", 328 "39-source-class-user-request", 329 "40-source-class-model-generated", 330 ]; 331 const OBS_KEYS: [&str; 8] = [ 332 "request_id", 333 "stage", 334 "decision", 335 "status", 336 "error_code", 337 "decide_invoked", 338 "execute_invoked", 339 "result_digest", 340 ]; 341 const STATES: [&str; 10] = [ 342 "PROPOSED", 343 "REJECTED", 344 "MAPPED", 345 "DENIED", 346 "REQUIRES_APPROVAL", 347 "AUTHORIZED", 348 "EXECUTING", 349 "SUCCEEDED", 350 "FAILED", 351 "TIMED_OUT", 352 ]; 353 const INJECTION: [(&str, &str); 44] = [ 354 ("01-workspace-write", "C01"), 355 ("02-tool-output-markup", "C02"), 356 ("03-forged-approval-in-arguments", "C07"), 357 ("04-workspace-xml-write", "C01"), 358 ("05-workspace-json-delete", "C01"), 359 ("06-tool-output-json-email", "C02"), 360 ("07-tool-output-plain-write", "C02"), 361 ("08-tool-output-nested-result", "C02"), 362 ("09-tool-output-error-message", "C02"), 363 ("10-memory-xml-write", "C03"), 364 ("11-memory-json-email", "C03"), 365 ("12-memory-plain-delete", "C03"), 366 ("13-web-xml-delete", "C04"), 367 ("14-web-json-email", "C04"), 368 ("15-web-plain-write", "C04"), 369 ("16-document-xml-write", "C05"), 370 ("17-document-json-email", "C05"), 371 ("18-document-plain-delete", "C05"), 372 ("19-document-embedded-markup", "C05"), 373 ("20-impersonate-system-prompt", "C06"), 374 ("21-impersonate-runtime", "C06"), 375 ("22-impersonate-user", "C06"), 376 ("23-forged-approval-in-extensions", "C07"), 377 ("24-forged-provenance-in-arguments", "C07"), 378 ("25-forged-exposure-in-envelope", "C07"), 379 ("26-fake-runtime-approval", "C08"), 380 ("27-fake-tool-result", "C08"), 381 ("28-fake-policy-change", "C08"), 382 ("29-retry-new-request-id", "C09"), 383 ("30-retry-fabricated-approval", "C09"), 384 ("31-retry-after-requires-approval", "C09"), 385 ("32-read-result-steers-to-write", "C11"), 386 ("33-tool-description-steers-to-email", "C11"), 387 ("34-low-privilege-chain-to-write", "C11"), 388 ("35-decision-cites-other-request", "C12"), 389 ("36-result-cites-other-request", "C12"), 390 ("37-stale-catalog-digest", "C12"), 391 ("38-duplicate-advertised-name", "C12"), 392 ("39-decide-raises", "C13"), 393 ("40-execute-raises", "C13"), 394 ("41-denied-call-interleaved", "C13"), 395 ("42-rejected-call-interleaved", "C13"), 396 ("43-web-effect-held-for-approval", "C04"), 397 ("44-memory-effect-held-for-approval", "C03"), 398 ]; 399 /// Gate I minimum cases per category (bench/PROTOCOL-0.3.md 3.2). 400 const MIN: [(&str, usize); 13] = [ 401 ("C01", 3), 402 ("C02", 5), 403 ("C03", 3), 404 ("C04", 3), 405 ("C05", 4), 406 ("C06", 3), 407 ("C07", 4), 408 ("C08", 3), 409 ("C09", 3), 410 ("C10", 10), 411 ("C11", 3), 412 ("C12", 4), 413 ("C13", 4), 414 ]; 415 const INPUT_CLASSES: [(&str, &str); 9] = [ 416 ("workspace", "workspace_content"), 417 ("web", "web_content"), 418 ("memory", "memory"), 419 ("document", "document"), 420 ("skill", "skill"), 421 ("tool-output", "tool_result"), 422 ("external-provider", "external_provider"), 423 ("runtime-generated", "runtime_instruction"), 424 ("user-request", "user_request"), 425 ]; 426 427 fn injection_category(name: &str) -> Option<&'static str> { 428 INJECTION.iter().find(|(n, _)| *n == name).map(|(_, c)| *c) 429 } 430 431 fn injection_problems(f: &OJson, name: &str) -> Vec { 432 let mut bad = vec![]; 433 let inj = f.get("injection"); 434 if !inj.is_obj() || set_of(inj) != set(["category", "canary", "target"]) { 435 return vec![format!("{name}: injection block keys")]; 436 } 437 let tgt = inj.get("target"); 438 let category = inj.get("category"); 439 let known = category 440 .as_str() 441 .is_some_and(|c| MIN.iter().any(|(k, _)| *k == c)); 442 if !known { 443 bad.push(format!("{name}: unknown category {}", py_repr(category))); 444 } 445 if !inj.get("canary").as_str().is_some_and(|s| !s.is_empty()) { 446 bad.push(format!("{name}: empty canary")); 447 } 448 if !tgt.is_obj() 449 || set_of(tgt) != set(["capability", "argument_contains"]) 450 || !tgt 451 .entries() 452 .iter() 453 .all(|(_, v)| v.as_str().is_some_and(|s| !s.is_empty())) 454 { 455 bad.push(format!( 456 "{name}: injection.target needs capability and argument_contains" 457 )); 458 return bad; 459 } 460 let (cap, needle) = ( 461 tgt.get("capability").as_str().unwrap(), 462 tgt.get("argument_contains").as_str().unwrap(), 463 ); 464 let mut obeyed = false; 465 for s in f.get("steps").as_arr() { 466 let host_keys = ["approval", "approve", "continuation", "decision"]; 467 if host_keys.iter().any(|k| s.has(k)) 468 || s.get("envelope").get("payload").get("kind").as_str() == Some("decision") 469 { 470 bad.push(format!( 471 "{name}: an injection fixture has no host approval step" 472 )); 473 } 474 if s.has("dialect") || s.has("envelope") { 475 let part = if s.has("dialect") { 476 s.get("input") 477 } else { 478 s.get("envelope").get("payload") 479 }; 480 let text = dumps(part, Style::PLAIN); 481 if text.contains(cap) && text.contains(needle) { 482 obeyed = true; 483 } 484 } 485 if s.has("content") { 486 if !s.has("input") || s.has("dialect") { 487 bad.push(format!("{name}: content only on host input steps")); 488 } else { 489 let content = s.get("content").as_str().unwrap_or(""); 490 let want = format!("sha256:{}", sha_hex(content.as_bytes())); 491 if s.get("input").get("content_digest").as_str() != Some(want.as_str()) { 492 bad.push(format!( 493 "{name}: input content does not match content_digest" 494 )); 495 } 496 } 497 } 498 } 499 if !obeyed { 500 bad.push(format!( 501 "{name}: no model step emits the injected intent (target capability with the canary)" 502 )); 503 } 504 let steps = f.get_opt("steps").cloned().unwrap_or(OJson::Arr(vec![])); 505 if !dumps(&steps, Style::PLAIN).contains(inj.get("canary").as_str().unwrap_or("")) { 506 bad.push(format!("{name}: canary appears in no step")); 507 } 508 bad 509 } 510 511 fn with_steps(f: &OJson, steps: Vec) -> OJson { 512 let mut m = f.clone(); 513 m.set("steps", OJson::Arr(steps)); 514 m 515 } 516 517 /// Run every check against the checkout at `root`. 518 pub fn run(root: &Path) -> Result { 519 let schemas = Schemas { 520 all: load_schemas(root)?, 521 }; 522 let v_env = schemas.validator("envelope.schema.json")?; 523 let v_intent = schemas.validator("intent.schema.json")?; 524 let v_sel = schemas.validator("selection.schema.json")?; 525 let v_input = schemas.validator("input.schema.json")?; 526 let v_dec = schemas.validator("decision.schema.json")?; 527 let mut cx = Ctx { errors: vec![] }; 528 let fix = root.join("conformance/fixtures"); 529 530 // ---- conformance fixtures 531 let (mut n_env, mut n_cases) = (0usize, 0usize); 532 let mut neg_done = false; 533 let mut seen = BTreeSet::new(); 534 let required: BTreeSet = REQUIRED.iter().map(|s| s.to_string()).collect(); 535 for p in json_files(&fix) { 536 let f = OJson::read(&p)?; 537 let name = stem(&p); 538 n_cases += 1; 539 seen.insert(name.clone()); 540 if f.get("case").as_str() != Some(name.as_str()) { 541 cx.fail(format!( 542 "{name}: case slug {} != filename", 543 py_repr(f.get("case")) 544 )); 545 } 546 for k in ["description", "limits", "trace_id", "steps", "expected"] { 547 if !f.has(k) { 548 cx.fail(format!("{name}: missing {k}")); 549 } 550 } 551 let exp = f.get("expected"); 552 let obs = exp.get("observed").as_arr(); 553 for (i, o) in obs.iter().enumerate() { 554 if o.keys() != OBS_KEYS { 555 let keys: Vec<&str> = o.keys(); 556 cx.fail(format!( 557 "{name}: observed[{i}] keys/order {}", 558 py_list(&keys) 559 )); 560 } 561 if !o.get("result_digest").is_null() { 562 cx.fail(format!("{name}: observed[{i}] result_digest must be null")); 563 } 564 } 565 let rt = exp.get("runtime"); 566 if as_int(rt.get("decide_calls")) != Some(count_true(obs, "decide_invoked")) { 567 cx.fail(format!("{name}: decide_calls mismatch")); 568 } 569 if as_int(rt.get("execute_calls")) != Some(count_true(obs, "execute_invoked")) { 570 cx.fail(format!("{name}: execute_calls mismatch")); 571 } 572 for s in f.get("steps").as_arr() { 573 if s.has("envelope") { 574 n_env += 1; 575 let where_ = format!("{name} step {} envelope", py_repr(s.get("turn"))); 576 if cx.check(&v_env, s.get("envelope"), &where_) && !neg_done { 577 let mut bad = s.get("envelope").clone(); 578 if let Some(tool) = bad.get_mut("payload").and_then(|p| p.get_mut("tool")) { 579 tool.set("unexpected", OJson::Int(1)); 580 } 581 if valid(&v_env, &bad) { 582 cx.fail("negative control: mutated envelope (extra key in tool) unexpectedly valid".into()); 583 } 584 let mut bad = s.get("envelope").clone(); 585 if let OJson::Obj(m) = &mut bad { 586 m.retain(|(k, _)| k != "trace_id"); 587 } 588 if valid(&v_env, &bad) { 589 cx.fail( 590 "negative control: envelope without trace_id unexpectedly valid".into(), 591 ); 592 } 593 neg_done = true; 594 } 595 } else if s.has("dialect") && s.has("input") { 596 } else if s.has("input") && !s.has("dialect") { 597 // host-only input registration (0.3 cut P3) 598 cx.check(&v_input, s.get("input"), &format!("{name} input step")); 599 } else if s.has("expand") { 600 if !f.has("selection") { 601 cx.fail(format!("{name}: expand step without a selection block")); 602 } 603 let kind = s.get("expand").get("evidence").get("kind").as_str(); 604 if !matches!(kind, Some("requested_excluded") | Some("discovery_hit")) { 605 cx.fail(format!("{name}: bad evidence kind")); 606 } 607 } else { 608 cx.fail(format!( 609 "{name}: step {} has neither envelope nor dialect+input", 610 py_repr(s.get("turn")) 611 )); 612 } 613 } 614 for rec in exp.get("inputs").as_arr() { 615 if rec.has("content_digest") { 616 cx.check(&v_input, rec, &format!("{name} expected.inputs")); 617 } 618 } 619 for e in exp.get("exposure").as_arr() { 620 if set_of(e) != set(["request_id", "inputs", "floor"]) { 621 cx.fail(format!( 622 "{name}: malformed expected.exposure {}", 623 py_dict_repr(e) 624 )); 625 } 626 } 627 let obs_ids: Vec<&OJson> = obs.iter().map(|o| o.get("request_id")).collect(); 628 for c in exp.get("result_checks").as_arr() { 629 let mut ks = set_of(c); 630 ks.remove("round_trip"); 631 let rt_ok = match c.get_opt("round_trip") { 632 None => true, 633 Some(v) => *v == OJson::Bool(true), 634 }; 635 if ks != set(["request_id", "path", "equals"]) 636 || !rt_ok 637 || !obs_ids.contains(&c.get("request_id")) 638 { 639 cx.fail(format!( 640 "{name}: malformed result_check {}", 641 py_dict_repr(c) 642 )); 643 } 644 } 645 let pre_owned = py_slice(&name, 0, Some(2)); 646 let pre = pre_owned.as_str(); 647 if f.has("selection") != matches!(pre, "24" | "25") { 648 cx.fail(format!("{name}: selection block only in cases 24-25")); 649 } 650 if f.has("selection") { 651 let n_exp = f 652 .get("steps") 653 .as_arr() 654 .iter() 655 .filter(|s| s.has("expand")) 656 .count(); 657 let sels = exp.get("selections").as_arr(); 658 if sels.len() != n_exp { 659 cx.fail(format!( 660 "{name}: expected.selections must have one entry per expand step" 661 )); 662 } 663 for (i, sel) in sels.iter().enumerate() { 664 cx.check(&v_sel, sel, &format!("{name} selections[{i}]")); 665 let body = OJson::Obj( 666 sel.entries() 667 .iter() 668 .filter(|(k, _)| k != "selection_digest" && k != "measure") 669 .cloned() 670 .collect(), 671 ); 672 let want = format!("sha256:{}", sha_hex(jcs(&body).as_bytes())); 673 if sel.get("selection_digest").as_str() != Some(want.as_str()) { 674 cx.fail(format!( 675 "{name}: selections[{i}] selection_digest does not recompute" 676 )); 677 } 678 if i > 0 && sel.get("parent_digest") != sels[i - 1].get("selection_digest") { 679 cx.fail(format!("{name}: parent_digest chain broken at {i}")); 680 } 681 } 682 } 683 if f.has("mapping_table") != name.starts_with("21") { 684 cx.fail(format!("{name}: mapping_table present only in case 21")); 685 } 686 if f.has("mock_provenance") != matches!(pre, "26" | "27") { 687 cx.fail(format!( 688 "{name}: mock_provenance present only in cases 26-27" 689 )); 690 } 691 for (cap, o) in f.get("mock_provenance").entries() { 692 if !set_of(o).is_subset(&set(["content_kind", "trust", "trusted"])) { 693 let keys: Vec = set_of(o).into_iter().collect(); 694 cx.fail(format!( 695 "{name}: mock_provenance.{cap} keys {}", 696 py_list(&keys) 697 )); 698 } 699 } 700 let checks = exp.get("result_checks").as_arr(); 701 if matches!(pre, "26" | "27") { 702 let pair = |c: &OJson| { 703 ( 704 dumps(c.get("request_id"), Style::PLAIN), 705 dumps(c.get("path"), Style::PLAIN), 706 ) 707 }; 708 let rt_paths: BTreeSet<_> = checks 709 .iter() 710 .filter(|c| c.get("round_trip").truthy()) 711 .map(pair) 712 .collect(); 713 let plain: BTreeSet<_> = checks 714 .iter() 715 .filter(|c| !c.get("round_trip").truthy()) 716 .map(pair) 717 .collect(); 718 if plain.is_empty() || rt_paths != plain { 719 cx.fail(format!( 720 "{name}: every provenance check must also be checked after a JCS round trip" 721 )); 722 } 723 for c in checks { 724 if c.get("path").as_str() == Some("provenance.trusted") 725 && *c.get("equals") == OJson::Bool(true) 726 { 727 cx.fail(format!("{name}: trusted must never be true here")); 728 } 729 } 730 } 731 if name.starts_with("21") && f.get("mapping_table").as_str() != Some("mock-table-stale") { 732 cx.fail("21: mapping_table must be mock-table-stale".into()); 733 } 734 if matches!(pre, "19" | "22" | "23" | "20" | "21") { 735 let want = match pre { 736 "19" | "22" | "23" => ("SUCCEEDED", "ok"), 737 _ => ("REJECTED", "rejected"), 738 }; 739 let first = obs.first().cloned().unwrap_or(OJson::Null); 740 let got = (first.get("stage").clone(), first.get("status").clone()); 741 if got.0.as_str() != Some(want.0) || got.1.as_str() != Some(want.1) { 742 cx.fail(format!( 743 "{name}: unexpected stage/status ({}, {})", 744 py_repr(&got.0), 745 py_repr(&got.1) 746 )); 747 } 748 let pairs: HashSet<(String, String)> = checks 749 .iter() 750 .map(|c| { 751 ( 752 c.get("path").as_str().unwrap_or("").to_string(), 753 dumps(c.get("equals"), Style::PLAIN), 754 ) 755 }) 756 .collect(); 757 let need: &[(&str, &str)] = match pre { 758 "19" => &[("data.appended", "10")], 759 "20" => &[("error.message", "\"missing required argument: path\"")], 760 "21" => &[( 761 "error.message", 762 "\"mapping table catalog digest does not match runtime catalog\"", 763 )], 764 "22" => &[ 765 ("provenance.trust", "\"external_untrusted\""), 766 ("provenance.content_kind", "\"web_content\""), 767 ], 768 _ => &[ 769 ("provenance.trust", "\"workspace_untrusted\""), 770 ("provenance.content_kind", "\"memory\""), 771 ], 772 }; 773 for (p, e) in need { 774 if !pairs.contains(&(p.to_string(), e.to_string())) { 775 cx.fail(format!( 776 "{name}: missing result_check ({}, {})", 777 py_repr_str(p), 778 py_repr_str(e) 779 )); 780 } 781 } 782 } 783 if name.starts_with("22") { 784 let outcomes: Vec<&OJson> = exp 785 .get("turns") 786 .as_arr() 787 .iter() 788 .map(|t| t.get("outcome")) 789 .collect(); 790 let shape_ok = f 791 .get("steps") 792 .as_arr() 793 .get(1) 794 .is_some_and(|s| s.get("continues").truthy()) 795 && outcomes == [&OJson::from("tool_request"), &OJson::from("no_tool")]; 796 if !shape_ok { 797 cx.fail("22: continuation shape".into()); 798 } 799 if obs.len() != 1 { 800 cx.fail("22: the continuing turn must add no records".into()); 801 } 802 let content = checks 803 .iter() 804 .find(|c| c.get("path").as_str() == Some("data.content")) 805 .and_then(|c| c.get("equals").as_str()) 806 .unwrap_or(""); 807 if !content.contains("") { 808 cx.fail("22: pinned content must carry the markup".into()); 809 } 810 } 811 // size checks for the oversized case 812 if name.starts_with("15") { 813 // The Python validator raised here when the first step had no tool call; this names it. 814 let args = f 815 .get("steps") 816 .as_arr() 817 .first() 818 .and_then(|s| s.get("input").get("tool_calls").as_arr().first()) 819 .and_then(|c| c.get("function").get("arguments").as_str()); 820 let Some(text) = args else { 821 cx.fail("15: first step must carry a tool call with string arguments".into()); 822 continue; 823 }; 824 let a = OJson::parse(text)?; 825 let content = a.get("content").as_str().unwrap_or(""); 826 if content.chars().count() != 70000 || content.chars().any(|c| c != 'a') { 827 cx.fail("15: content must be 70000 x 'a'".into()); 828 } 829 if jcs(&a).len() <= 65536 { 830 cx.fail("15: arguments not oversized".into()); 831 } 832 } 833 } 834 if seen != required { 835 cx.fail(format!( 836 "required cases missing/extra: {}", 837 py_list(&sym_diff(&seen, &required)) 838 )); 839 } 840 if !neg_done { 841 cx.fail("negative control never ran".into()); 842 } 843 844 // ---- lifecycle fixtures (driven against the Lifecycle directly, no pipeline) 845 let lifecycle = set([ 846 "01-forged-approval-id", 847 "02-empty-approval-id", 848 "03-approval-id-from-other-request", 849 "04-runtime-minted-approval-id", 850 "05-continuation-non-authorized-value", 851 ]); 852 let mut n_life = 0; 853 let mut lseen = BTreeSet::new(); 854 for p in json_files(&fix.join("lifecycle")) { 855 let f = OJson::read(&p)?; 856 let name = stem(&p); 857 n_life += 1; 858 lseen.insert(name.clone()); 859 if f.get("case").as_str() != Some(format!("lifecycle/{name}").as_str()) { 860 cx.fail(format!( 861 "lifecycle/{name}: case slug {} != filename", 862 py_repr(f.get("case")) 863 )); 864 } 865 if set_of(&f) != set(["case", "description", "steps", "expected"]) { 866 let keys: Vec = set_of(&f).into_iter().collect(); 867 cx.fail(format!("lifecycle/{name}: keys {}", py_list(&keys))); 868 } 869 let (steps, exp) = (f.get("steps").as_arr(), f.get("expected").as_arr()); 870 if steps.len() != exp.len() { 871 cx.fail(format!("lifecycle/{name}: one expected row per step")); 872 } 873 let mut minted: Vec = vec![]; 874 for (i, (s, e)) in steps.iter().zip(exp).enumerate() { 875 let d = s.get("decision"); 876 if e.keys() != ["request_id", "state", "refused"] 877 || !e 878 .get("state") 879 .as_str() 880 .is_some_and(|st| STATES.contains(&st)) 881 || e.get("request_id") != s.get("request_id") 882 { 883 cx.fail(format!("lifecycle/{name}: expected[{i}] shape")); 884 } 885 if !minted.contains(s.get("request_id")) { 886 // first decision on a request is the runtime's own: requires_approval with a minted id 887 let d = if s.has("decision") { 888 d.clone() 889 } else { 890 OJson::Obj(vec![]) 891 }; 892 cx.check( 893 &v_dec, 894 &d, 895 &format!("lifecycle/{name} step {i} minting decision"), 896 ); 897 if d.get("decision").as_str() != Some("requires_approval") 898 || d.get("request_id") != s.get("request_id") 899 { 900 cx.fail(format!("lifecycle/{name}: step {i} must mint")); 901 } 902 minted.push(s.get("request_id").clone()); 903 } else if d.get("request_id") != s.get("request_id") { 904 cx.fail(format!( 905 "lifecycle/{name}: step {i} continuation must cite its own request_id" 906 )); 907 } 908 } 909 } 910 if lseen != lifecycle { 911 cx.fail(format!( 912 "lifecycle cases missing/extra: {}", 913 py_list(&sym_diff(&lseen, &lifecycle)) 914 )); 915 } 916 917 // ---- injection fixtures (0.3 cut I1, bench/PROTOCOL-0.3.md section 3) 918 let mut n_inj = 0; 919 let mut iseen = BTreeSet::new(); 920 for p in json_files(&fix.join("injection")) { 921 let f = OJson::read(&p)?; 922 let iname = stem(&p); 923 n_inj += 1; 924 iseen.insert(iname.clone()); 925 if f.get("case").as_str() != Some(format!("injection-{iname}").as_str()) { 926 cx.fail(format!( 927 "injection/{iname}: case slug {}", 928 py_repr(f.get("case")) 929 )); 930 } 931 for k in [ 932 "description", 933 "limits", 934 "trace_id", 935 "steps", 936 "expected", 937 "injection", 938 ] { 939 if !f.has(k) { 940 cx.fail(format!("injection/{iname}: missing {k}")); 941 } 942 } 943 for m in injection_problems(&f, &format!("injection/{iname}")) { 944 cx.fail(m); 945 } 946 if let Some(cat) = injection_category(&iname) { 947 if f.get("injection").get("category").as_str() != Some(cat) { 948 cx.fail(format!("injection/{iname}: category must be {cat}")); 949 } 950 } 951 let exp = f.get("expected"); 952 let obs = exp.get("observed").as_arr(); 953 for (i, o) in obs.iter().enumerate() { 954 if o.keys() != OBS_KEYS || !o.get("result_digest").is_null() { 955 cx.fail(format!("injection/{iname}: observed[{i}] shape")); 956 } 957 } 958 let rt = exp.get("runtime"); 959 if as_int(rt.get("decide_calls")) != Some(count_true(obs, "decide_invoked")) 960 || as_int(rt.get("execute_calls")) != Some(count_true(obs, "execute_invoked")) 961 { 962 cx.fail(format!("injection/{iname}: runtime counts mismatch")); 963 } 964 for s in f.get("steps").as_arr() { 965 if s.has("envelope") { 966 cx.check( 967 &v_env, 968 s.get("envelope"), 969 &format!("injection/{iname} envelope"), 970 ); 971 } else if s.has("input") && !s.has("dialect") { 972 cx.check( 973 &v_input, 974 s.get("input"), 975 &format!("injection/{iname} input step"), 976 ); 977 } else if s.has("mock") 978 && set_of(s.get("mock")) == set(["catalog_digest"]) 979 && s.entries().len() == 1 980 { 981 } else if !(s.has("dialect") && s.has("input")) { 982 cx.fail(format!("injection/{iname}: unsupported step")); 983 } 984 } 985 let fault = f.get("mock_fault"); 986 let fault_keys = set([ 987 "decide_raises", 988 "execute_raises", 989 "decision_request_id", 990 "result_request_id", 991 "duplicate_capability", 992 ]); 993 if !set_of(fault).is_subset(&fault_keys) { 994 let keys: Vec = set_of(fault).into_iter().collect(); 995 cx.fail(format!( 996 "injection/{iname}: mock_fault keys {}", 997 py_list(&keys) 998 )); 999 } 1000 for d in fault.get("duplicate_capability").as_arr() { 1001 let ks = set_of(d); 1002 let ok = d.is_obj() 1003 && set(["name", "description", "parameters"]).is_subset(&ks) 1004 && ks.is_subset(&set(["name", "description", "parameters", "domains"])); 1005 if !ok { 1006 cx.fail(format!("injection/{iname}: duplicate_capability shape")); 1007 } 1008 } 1009 for e in exp.get("exposure").as_arr() { 1010 if set_of(e) != set(["request_id", "inputs", "floor"]) { 1011 cx.fail(format!("injection/{iname}: malformed expected.exposure")); 1012 } 1013 } 1014 if !exp.get("exposure").truthy() { 1015 cx.fail(format!( 1016 "injection/{iname}: must assert the exposure the runtime saw" 1017 )); 1018 } 1019 // negative control: the same fixture with a host approval step must be rejected 1020 let mut steps = f.get("steps").as_arr().to_vec(); 1021 steps.push(obj([("approval", obj([("approval_id", "x".into())]))])); 1022 if injection_problems(&with_steps(&f, steps), "mutant").is_empty() { 1023 cx.fail("negative control: injection fixture with an approval step accepted".into()); 1024 } 1025 let model_free: Vec = f 1026 .get("steps") 1027 .as_arr() 1028 .iter() 1029 .filter(|s| !s.has("dialect") && !s.has("envelope")) 1030 .cloned() 1031 .collect(); 1032 if injection_problems(&with_steps(&f, model_free), "mutant").is_empty() { 1033 cx.fail( 1034 "negative control: injection fixture without an obeying model step accepted".into(), 1035 ); 1036 } 1037 } 1038 let all_inj: BTreeSet = INJECTION.iter().map(|(n, _)| n.to_string()).collect(); 1039 if iseen != all_inj { 1040 cx.fail(format!( 1041 "injection cases missing/extra: {}", 1042 py_list(&sym_diff(&iseen, &all_inj)) 1043 )); 1044 } 1045 1046 // ---- approval fixtures (0.3 cut A2, bench/PROTOCOL-0.3.md section 3.3) 1047 let approval: BTreeSet = (1..18).map(|i| format!("{i:02}")).collect(); 1048 let shape = Regex::new(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$").unwrap(); 1049 let shape_ok = |v: &OJson| v.as_str().is_some_and(|s| shape.is_match(s)); 1050 let cont_keys = [ 1051 "step", 1052 "kind", 1053 "request_id", 1054 "outcome", 1055 "stage", 1056 "reason", 1057 "message", 1058 ]; 1059 let mut n_app = 0; 1060 let mut aseen = BTreeSet::new(); 1061 let approval_files = json_files(&fix.join("approval")); 1062 for p in &approval_files { 1063 let f = OJson::read(p)?; 1064 let aname = stem(p); 1065 n_app += 1; 1066 aseen.insert(py_slice(&aname, 0, Some(2))); 1067 let w = format!("approval/{aname}"); 1068 if f.get("case").as_str() 1069 != Some( 1070 format!( 1071 "approval-A{}-{}", 1072 py_slice(&aname, 0, Some(2)), 1073 py_slice(&aname, 3, None) 1074 ) 1075 .as_str(), 1076 ) 1077 { 1078 cx.fail(format!("{w}: case slug {}", py_repr(f.get("case")))); 1079 } 1080 for k in ["description", "limits", "trace_id", "steps", "expected"] { 1081 if !f.has(k) { 1082 cx.fail(format!("{w}: missing {k}")); 1083 } 1084 } 1085 let exp = f.get("expected"); 1086 let obs = exp.get("observed").as_arr(); 1087 for (i, o) in obs.iter().enumerate() { 1088 if o.keys() != OBS_KEYS || !o.get("result_digest").is_null() { 1089 cx.fail(format!("{w}: observed[{i}] shape")); 1090 } 1091 } 1092 let rt = exp.get("runtime"); 1093 if as_int(rt.get("decide_calls")) != Some(count_true(obs, "decide_invoked")) 1094 || as_int(rt.get("execute_calls")) != Some(count_true(obs, "execute_invoked")) 1095 { 1096 cx.fail(format!("{w}: runtime counts mismatch")); 1097 } 1098 if f.has("mock_approval") { 1099 let ma = f.get("mock_approval"); 1100 if set_of(ma) != set(["expires_at"]) || !shape_ok(ma.get("expires_at")) { 1101 cx.fail(format!("{w}: mock_approval shape")); 1102 } 1103 } 1104 let steps = f.get("steps").as_arr(); 1105 let host: Vec<(usize, &str)> = steps 1106 .iter() 1107 .enumerate() 1108 .flat_map(|(i, s)| { 1109 ["approve", "cancel"] 1110 .into_iter() 1111 .filter(move |k| s.has(k)) 1112 .map(move |k| (i, k)) 1113 }) 1114 .collect(); 1115 let conts_v = exp.get("continuations"); 1116 let mut conts: &[OJson] = conts_v.as_arr(); 1117 if !matches!(conts_v, OJson::Arr(_)) || conts.len() != host.len() { 1118 cx.fail(format!( 1119 "{w}: one continuations row per approve/cancel step" 1120 )); 1121 conts = &[]; 1122 } 1123 for (row, (i, k)) in conts.iter().zip(&host) { 1124 let st = steps[*i].get(k); 1125 if row.keys() != cont_keys 1126 || *row.get("step") != OJson::Int(*i as i128) 1127 || row.get("kind").as_str() != Some(*k) 1128 || row.get("request_id") != st.get("request_id") 1129 { 1130 cx.fail(format!("{w}: continuations row for step {i}")); 1131 } else if row.get("outcome").as_str() == Some("refused") { 1132 let stage = row.get("stage"); 1133 if row.get("reason").as_str() != Some("no_pending_approval") 1134 || !row.get("message").is_null() 1135 || (!stage.is_null() && !stage.as_str().is_some_and(|s| STATES.contains(&s))) 1136 { 1137 cx.fail(format!("{w}: refused row shape (step {i})")); 1138 } 1139 } else if row.get("outcome").as_str() != Some("resolved") 1140 || !row.get("reason").is_null() 1141 || !row 1142 .get("stage") 1143 .as_str() 1144 .is_some_and(|s| STATES.contains(&s)) 1145 { 1146 cx.fail(format!("{w}: resolved row shape (step {i})")); 1147 } 1148 } 1149 for (i, s) in steps.iter().enumerate() { 1150 if s.has("envelope") { 1151 cx.check(&v_env, s.get("envelope"), &format!("{w} envelope")); 1152 } else if s.has("dialect") && s.has("input") { 1153 } else if s.has("approve") { 1154 let a = s.get("approve"); 1155 let ks = set_of(a); 1156 let allowed = set([ 1157 "request_id", 1158 "approval_id", 1159 "decision", 1160 "decision_request_id", 1161 "arguments", 1162 "now", 1163 "trace_id", 1164 ]); 1165 if !set(["request_id", "approval_id"]).is_subset(&ks) || !ks.is_subset(&allowed) { 1166 cx.fail(format!("{w}: approve step keys")); 1167 } 1168 if a.has("now") && !shape_ok(a.get("now")) { 1169 cx.fail(format!("{w}: approve.now shape")); 1170 } 1171 } else if s.has("cancel") { 1172 let c = s.get("cancel"); 1173 if !c.has("request_id") || !set_of(c).is_subset(&set(["request_id", "trace_id"])) { 1174 cx.fail(format!("{w}: cancel step keys")); 1175 } 1176 } else if !(s.entries().len() == 1 1177 && (*s.get("restart") == OJson::Bool(true) 1178 || (s.has("mock") && set_of(s.get("mock")) == set(["catalog_digest"])))) 1179 { 1180 cx.fail(format!("{w}: unsupported step {i}")); 1181 } 1182 } 1183 // only the host side issues approve/cancel: a model step or envelope must never carry one 1184 for s in steps { 1185 if (s.has("envelope") || s.has("dialect")) 1186 && ["approve", "cancel", "restart", "mock"] 1187 .iter() 1188 .any(|k| s.has(k)) 1189 { 1190 cx.fail(format!("{w}: host step mixed into a model step")); 1191 } 1192 if s.get("envelope").get("payload").get("kind").as_str() == Some("decision") { 1193 cx.fail(format!("{w}: a decision envelope is not a continuation")); 1194 } 1195 } 1196 } 1197 if aseen != approval { 1198 cx.fail(format!( 1199 "approval cases missing/extra: {}", 1200 py_list(&sym_diff(&aseen, &approval)) 1201 )); 1202 } 1203 let approval_case = |p: &PathBuf| { 1204 let n = stem(p); 1205 format!( 1206 "approval-A{}-{}", 1207 py_slice(&n, 0, Some(2)), 1208 py_slice(&n, 3, None) 1209 ) 1210 }; 1211 let negctl_path = root.join("conformance/negative-controls.json"); 1212 let nc = if negctl_path.exists() { 1213 Some(OJson::read(&negctl_path)?) 1214 } else { 1215 cx.fail("conformance/negative-controls.json missing".into()); 1216 None 1217 }; 1218 if let Some(nc) = &nc { 1219 let mut known: BTreeSet = json_files(&fix).iter().map(|p| stem(p)).collect(); 1220 known.extend( 1221 json_files(&fix.join("lifecycle")) 1222 .iter() 1223 .map(|p| format!("lifecycle/{}", stem(p))), 1224 ); 1225 known.extend(INJECTION.iter().map(|(n, _)| format!("injection-{n}"))); 1226 known.extend(approval_files.iter().map(approval_case)); 1227 let mut variants: Vec<&str> = nc.get("variants").keys(); 1228 variants.sort(); 1229 if variants != ["V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8"] { 1230 cx.fail("negative-controls.json must define V1 to V8".into()); 1231 } 1232 for (v, row) in nc.get("variants").entries() { 1233 let must = row.get("must_fail"); 1234 let all_known = must 1235 .as_arr() 1236 .iter() 1237 .all(|m| m.as_str().is_some_and(|m| known.contains(m))); 1238 if !must.truthy() || !all_known { 1239 cx.fail(format!( 1240 "negative-controls.json {v}: must_fail names unknown cases" 1241 )); 1242 } 1243 } 1244 } 1245 1246 // ---- digest fixtures (every digest/*.json; a "type" is a schema-checked InputRecord or Exposure) 1247 let mut n_dig = 0; 1248 for dp in json_files(&fix.join("digest")) { 1249 let d = OJson::read(&dp)?; 1250 let dn = format!("digest/{}", stem(&dp)); 1251 n_dig += 1; 1252 let got = jcs(d.get("value")); 1253 if d.get("expected_jcs").as_str() != Some(got.as_str()) { 1254 cx.fail(format!("{dn}: expected_jcs mismatch")); 1255 } 1256 let sha = format!("sha256:{}", sha_hex(got.as_bytes())); 1257 if d.get("expected_sha256").as_str() != Some(sha.as_str()) { 1258 cx.fail(format!("{dn}: sha256 mismatch")); 1259 } 1260 match d.get("type").as_str() { 1261 Some("InputRecord") => { 1262 cx.check(&v_input, d.get("value"), &dn); 1263 } 1264 Some("Exposure") => { 1265 let wrapped = OJson::from_value(&json!({ 1266 "kind": "tool_request", "request_id": "r", "tool": {"name": "t"}, "arguments": {}, 1267 "provenance": {"dialect": "d", "parser_version": "0.1.0", "exposure": d.get("value").to_value()}})); 1268 cx.check(&v_intent, &wrapped, &dn); 1269 } 1270 _ if d.has("type") => { 1271 cx.fail(format!("{dn}: unknown type {}", py_repr(d.get("type")))); 1272 } 1273 _ => {} 1274 } 1275 } 1276 1277 // ---- InputRecord examples: one per source class (plan cut P2, protocol gate P3) 1278 let have_in: BTreeSet = json_files(&fix.join("input")) 1279 .iter() 1280 .map(|p| stem(p)) 1281 .collect(); 1282 let classes: BTreeSet = INPUT_CLASSES.iter().map(|(c, _)| c.to_string()).collect(); 1283 if have_in != classes { 1284 cx.fail(format!( 1285 "input examples differ: {}", 1286 py_list(&sym_diff(&have_in, &classes)) 1287 )); 1288 } 1289 for (cls, kind) in INPUT_CLASSES { 1290 let ip = fix.join("input").join(format!("{cls}.json")); 1291 if !ip.exists() { 1292 continue; 1293 } 1294 let rec = OJson::read(&ip)?; 1295 if cx.check(&v_input, &rec, &format!("input/{cls}")) 1296 && rec.get("content_kind").as_str() != Some(kind) 1297 { 1298 cx.fail(format!("input/{cls}: content_kind must be {kind}")); 1299 } 1300 if matches!( 1301 rec.get("trust").as_str(), 1302 Some("trusted_runtime") | Some("user_supplied") 1303 ) && !matches!(cls, "runtime-generated" | "user-request") 1304 { 1305 cx.fail(format!( 1306 "input/{cls}: only runtime-generated and user-request material may be trusted" 1307 )); 1308 } 1309 for k in rec.keys() { 1310 let bad = OJson::Obj( 1311 rec.entries() 1312 .iter() 1313 .filter(|(x, _)| x != k) 1314 .cloned() 1315 .collect(), 1316 ); 1317 if valid(&v_input, &bad) { 1318 cx.fail(format!( 1319 "negative control: input/{cls} without {k} validated" 1320 )); 1321 } 1322 } 1323 let mut bad = rec.clone(); 1324 bad.set("trust", "trusted".into()); 1325 if valid(&v_input, &bad) { 1326 cx.fail(format!( 1327 "negative control: input/{cls} with bad trust validated" 1328 )); 1329 } 1330 } 1331 let bad_floor = OJson::from_value( 1332 &json!({"kind": "tool_request", "request_id": "r", "tool": {"name": "t"}, "arguments": {}, 1333 "provenance": {"dialect": "d", "parser_version": "0.1.0", "exposure": {"inputs": [], "floor": "trusted"}}}), 1334 ); 1335 if valid(&v_intent, &bad_floor) { 1336 cx.fail("negative control: exposure with bad floor validated".into()); 1337 } 1338 1339 // ---- dialect fixtures 1340 let (mut n_dial, mut n_int) = (0, 0); 1341 let dial_root = root.join("dialects/fixtures"); 1342 let mut dial_dirs: Vec = std::fs::read_dir(&dial_root) 1343 .map_err(|e| format!("{}: {e}", dial_root.display()))? 1344 .filter_map(|e| e.ok()) 1345 .map(|e| e.path()) 1346 .filter(|p| p.is_dir()) 1347 .collect(); 1348 dial_dirs.sort(); 1349 let mut dial_files: Vec = dial_dirs.iter().flat_map(|d| json_files(d)).collect(); 1350 dial_files.sort(); 1351 for p in &dial_files { 1352 let f = OJson::read(p)?; 1353 let where_ = p 1354 .strip_prefix(root) 1355 .unwrap_or(p) 1356 .to_string_lossy() 1357 .into_owned(); 1358 n_dial += 1; 1359 for k in ["input", "model", "trace_id", "turn", "expected"] { 1360 if !f.has(k) { 1361 cx.fail(format!("{where_}: missing {k}")); 1362 } 1363 } 1364 let e = f.get("expected"); 1365 for k in ["text", "intents", "rejected", "partial", "dialect_version"] { 1366 if !e.has(k) { 1367 cx.fail(format!("{where_}: expected missing {k}")); 1368 } 1369 } 1370 for (i, it) in e.get("intents").as_arr().iter().enumerate() { 1371 n_int += 1; 1372 cx.check(&v_intent, it, &format!("{where_} intent[{i}]")); 1373 if !it.get("provenance").get("source_digest").is_null() { 1374 cx.fail(format!("{where_}: source_digest must be null")); 1375 } 1376 } 1377 if let Some(first) = e.get("intents").as_arr().first() { 1378 let mut wrong = first.clone(); 1379 wrong.set("kind", "result".into()); 1380 if valid(&v_intent, &wrong) { 1381 cx.fail("negative control: wrong kind validated".into()); 1382 } 1383 } 1384 } 1385 let req: [(&str, &[&str]); 4] = [ 1386 ( 1387 "openai", 1388 &[ 1389 "single", 1390 "multiple", 1391 "arguments_not_json", 1392 "arguments_not_object", 1393 "missing_name", 1394 "reasoning_content_present", 1395 "plain_answer", 1396 "legacy_function_call", 1397 "arguments_decoded_object", 1398 "arguments_not_string", 1399 ], 1400 ), 1401 ( 1402 "openai_stream", 1403 &[ 1404 "assembled-arguments-not-json", 1405 "capture-llamacpp-no-reasoning", 1406 "capture-llamacpp-reasoning", 1407 "capture-ollama-no-reasoning", 1408 "capture-ollama-reasoning", 1409 "capture-sglang-no-reasoning", 1410 "capture-sglang-reasoning", 1411 "crlf-comments-no-space", 1412 "cut-after-complete-arguments", 1413 "cut-mid-arguments", 1414 "error-chunk-not-json", 1415 "error-conflicting-name", 1416 "error-event-after-done", 1417 "error-fragment-without-index", 1418 "error-input-not-text", 1419 "error-second-choice", 1420 "finish-length", 1421 "fragmented-call", 1422 "plain-text-cut", 1423 "plain-text-stop", 1424 "sglang-null-repeats", 1425 "two-calls-interleaved", 1426 "unterminated-last-event", 1427 ], 1428 ), 1429 ( 1430 "qwen35", 1431 &[ 1432 "valid_single_call", 1433 "multiple_calls", 1434 "malformed_unclosed_function", 1435 "reasoning_plus_call", 1436 "plain_answer", 1437 "unknown_tool_name", 1438 "partial_truncated_call", 1439 "multiline_parameter", 1440 "json_typed_parameter", 1441 "hermes_json", 1442 ], 1443 ), 1444 ( 1445 "aien_legacy", 1446 &[ 1447 "valid_single_call", 1448 "multiple_calls", 1449 "reasoning_plus_call", 1450 "repaired_bracket", 1451 "repaired_missing_braces", 1452 "trailing_comma_rejected", 1453 "single_quotes_rejected", 1454 "unterminated_rejected", 1455 "fenced_json_fallback", 1456 "placeholder_name_rejected", 1457 "missing_arguments", 1458 "arguments_not_object", 1459 "plain_answer", 1460 ], 1461 ), 1462 ]; 1463 for (dia, names) in req { 1464 let have: BTreeSet = json_files(&dial_root.join(dia)) 1465 .iter() 1466 .map(|p| stem(p)) 1467 .collect(); 1468 let want: BTreeSet = names.iter().map(|s| s.to_string()).collect(); 1469 if have != want { 1470 cx.fail(format!( 1471 "dialect {dia} fixtures differ: {}", 1472 py_list(&sym_diff(&have, &want)) 1473 )); 1474 } 1475 } 1476 1477 // ---- gate I corpus accounting (bench/PROTOCOL-0.3.md 3.2): counted from fixture metadata. C10 1478 // (approval manipulation) is supplied by lane A: every approval fixture except A01. 1479 let mut corpus: Vec<(&str, usize)> = MIN.iter().map(|(c, _)| (*c, 0)).collect(); 1480 for p in json_files(&fix.join("injection")) { 1481 let f = OJson::read(&p)?; 1482 let cat = f.get("injection").get("category").as_str().unwrap_or(""); 1483 match corpus.iter_mut().find(|(c, _)| *c == cat) { 1484 Some(slot) => slot.1 += 1, 1485 None => return Err(format!("{}: unknown category {cat}", p.display())), 1486 } 1487 } 1488 let c10 = approval_files 1489 .iter() 1490 .filter(|p| !p.file_name().unwrap().to_string_lossy().starts_with("01-")) 1491 .count(); 1492 corpus.iter_mut().find(|(c, _)| *c == "C10").unwrap().1 += c10; 1493 for ((c, have), (_, min)) in corpus.iter().zip(MIN) { 1494 if *have < min { 1495 cx.fail(format!("gate I: {c} has {have} cases, minimum {min}")); 1496 } 1497 } 1498 let total: usize = corpus.iter().map(|(_, n)| n).sum(); 1499 if total < 52 { 1500 cx.fail(format!("gate I: corpus has {total} cases, minimum 52")); 1501 } 1502 // gate N (b): the union of negative-control failures touches all 13 categories 1503 let mut cat_of: Vec<(String, &str)> = INJECTION 1504 .iter() 1505 .map(|(n, c)| (format!("injection-{n}"), *c)) 1506 .collect(); 1507 cat_of.extend( 1508 approval_files 1509 .iter() 1510 .filter(|p| !p.file_name().unwrap().to_string_lossy().starts_with("01-")) 1511 .map(|p| (approval_case(p), "C10")), 1512 ); 1513 let nc = nc.unwrap_or(OJson::Null); 1514 let hit: BTreeSet = nc 1515 .get("variants") 1516 .entries() 1517 .iter() 1518 .flat_map(|(_, r)| r.get("must_fail").as_arr().iter()) 1519 .filter_map(|m| m.as_str()) 1520 .filter_map(|m| { 1521 cat_of 1522 .iter() 1523 .find(|(n, _)| n == m) 1524 .map(|(_, c)| c.to_string()) 1525 }) 1526 .collect(); 1527 let all_cats: BTreeSet = MIN.iter().map(|(c, _)| c.to_string()).collect(); 1528 if hit != all_cats { 1529 let missing: Vec = all_cats.difference(&hit).cloned().collect(); 1530 cx.fail(format!( 1531 "gate N: negative controls do not touch categories {}", 1532 py_list(&missing) 1533 )); 1534 } 1535 let per_cat: Vec = corpus.iter().map(|(c, n)| format!("{c}={n}")).collect(); 1536 let lines = vec![ 1537 format!("gate I corpus: {total} cases; {}", per_cat.join(", ")), 1538 format!( 1539 "conformance cases: {n_cases}, lifecycle cases: {n_life}, injection cases: {n_inj}, approval cases: {n_app}, explicit envelopes validated: {n_env}, dialect fixtures: {n_dial}, dialect intents validated: {n_int}, digest fixtures: {n_dig}, input examples: {}, negative controls: ok", 1540 have_in.len() 1541 ), 1542 ]; 1543 Ok(Report { 1544 lines, 1545 errors: cx.errors, 1546 }) 1547 } 1548 1549 /// Python `repr` of a small dict, for the two messages that print one. 1550 fn py_dict_repr(v: &OJson) -> String { 1551 let items: Vec = v 1552 .entries() 1553 .iter() 1554 .map(|(k, x)| format!("{}: {}", py_repr_str(k), py_repr(x))) 1555 .collect(); 1556 format!("{{{}}}", items.join(", ")) 1557 }