interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / provenance / src / lib.rs
| 1 | //! INTERPLANE companion provenance manifest, schema 0 (v0), and its offline verifier. |
| 2 | //! |
| 3 | //! The manifest (`COMPANION.json`) sits beside retained, immutable records and binds them link by |
| 4 | //! link: corpus BOM and license assertions -> training plan and run -> exported model files -> |
| 5 | //! AIEN candidate and loaded model -> INTERPLANE trace -> runtime effect receipt. It reuses the |
| 6 | //! identities those records already carry (WALDO record digests, raw-file SHA-256, the AIEN |
| 7 | //! candidate manifest, the aien-cli daemon load line, INTERPLANE envelopes and JCS digests, the |
| 8 | //! aien-cli effect receipt). It mints no ids, decides nothing and grants nothing: provenance is |
| 9 | //! evidence, not authority. Specification: provenance/README.md. |
| 10 | //! |
| 11 | //! `verify(dir)` returns one verdict line. It runs the checks in a fixed order and stops at the |
| 12 | //! first failure, so the same archive always yields the same bytes: |
| 13 | //! `PASS complete`, `PASS_LABELLED_INCOMPLETE missing=<sorted list>` or `FAIL <code>: <detail>`. |
| 14 | |
| 15 | pub mod binding; |
| 16 | pub mod evaluation; |
| 17 | pub mod gojson; |
| 18 | mod ledger; |
| 19 | mod modelturn; |
| 20 | mod strict; |
| 21 | pub mod synth; |
| 22 | mod testrun; |
| 23 | |
| 24 | use binding::{compact_sorted, LEDGER_BINDING, RECEIPT_BINDING, SERDE_DIGEST_FORM}; |
| 25 | use gojson::{compact, sha256_hex, top_level_member, waldo_sha256}; |
| 26 | use serde_json::Value; |
| 27 | use std::collections::{BTreeMap, BTreeSet}; |
| 28 | use std::path::{Component, Path}; |
| 29 | |
| 30 | pub const KIND: &str = "interplane-provenance-companion"; |
| 31 | pub const SCHEMA: u64 = 0; |
| 32 | pub const COMPANION_FILE: &str = "COMPANION.json"; |
| 33 | /// The only load-support result under which an `aien` link may be present. |
| 34 | pub const SUPPORTED: &str = "supported_structural"; |
| 35 | const LINKS: [&str; 6] = [ |
| 36 | "lineage", |
| 37 | "export", |
| 38 | "load_support", |
| 39 | "aien", |
| 40 | "interplane", |
| 41 | "effect", |
| 42 | ]; |
| 43 | |
| 44 | /// A refusal: stable code plus the exact place it was found. |
| 45 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 46 | pub struct Fail(pub String); |
| 47 | |
| 48 | fn fail<T>(code: &str, detail: impl AsRef<str>) -> Result<T, Fail> { |
| 49 | Err(Fail(format!("FAIL {code}: {}", detail.as_ref()))) |
| 50 | } |
| 51 | |
| 52 | /// One retained (or explicitly not retained) record. |
| 53 | struct Record { |
| 54 | path: String, |
| 55 | sha256: String, |
| 56 | waldo_sha256: Option<String>, |
| 57 | bytes: Option<Vec<u8>>, |
| 58 | } |
| 59 | |
| 60 | struct Archive { |
| 61 | records: BTreeMap<String, Record>, |
| 62 | } |
| 63 | |
| 64 | impl Archive { |
| 65 | fn has(&self, name: &str) -> bool { |
| 66 | self.records.contains_key(name) |
| 67 | } |
| 68 | /// Bytes of a retained record; None when the record is labelled not retained. |
| 69 | fn bytes(&self, name: &str) -> Result<Option<&[u8]>, Fail> { |
| 70 | match self.records.get(name) { |
| 71 | None => fail("missing_record_entry", name), |
| 72 | Some(r) => Ok(r.bytes.as_deref()), |
| 73 | } |
| 74 | } |
| 75 | fn json(&self, name: &str) -> Result<Option<Value>, Fail> { |
| 76 | match self.bytes(name)? { |
| 77 | None => Ok(None), |
| 78 | Some(b) => match strict::parse(b) { |
| 79 | Some(v) => Ok(Some(v)), |
| 80 | None => fail("unparseable_record", name), |
| 81 | }, |
| 82 | } |
| 83 | } |
| 84 | fn sha(&self, name: &str) -> Result<&str, Fail> { |
| 85 | match self.records.get(name) { |
| 86 | None => fail("missing_record_entry", name), |
| 87 | Some(r) => Ok(&r.sha256), |
| 88 | } |
| 89 | } |
| 90 | /// WALDO record digest: computed from retained bytes, else the declared `waldo_sha256`. |
| 91 | fn waldo(&self, name: &str) -> Result<Option<String>, Fail> { |
| 92 | match self.records.get(name) { |
| 93 | None => fail("missing_record_entry", name), |
| 94 | Some(r) => Ok(match &r.bytes { |
| 95 | Some(b) => Some(waldo_sha256(b)), |
| 96 | None => r.waldo_sha256.clone(), |
| 97 | }), |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | fn s<'a>(v: &'a Value, path: &[&str]) -> Option<&'a str> { |
| 103 | let mut cur = v; |
| 104 | for k in path { |
| 105 | cur = cur.get(*k)?; |
| 106 | } |
| 107 | cur.as_str() |
| 108 | } |
| 109 | |
| 110 | fn safe_relative(p: &str) -> bool { |
| 111 | let path = Path::new(p); |
| 112 | !p.is_empty() |
| 113 | && path.is_relative() |
| 114 | && path.components().all(|c| matches!(c, Component::Normal(_))) |
| 115 | } |
| 116 | |
| 117 | /// True when any component of `p` under `dir` (the record file included) is a symlink. A component |
| 118 | /// that does not exist is left to the read (`missing_record`). A link could point anywhere. |
| 119 | fn crosses_symlink(dir: &Path, p: &str) -> bool { |
| 120 | let mut cur = dir.to_path_buf(); |
| 121 | Path::new(p).components().any(|c| { |
| 122 | cur.push(c); |
| 123 | std::fs::symlink_metadata(&cur).is_ok_and(|m| m.file_type().is_symlink()) |
| 124 | }) |
| 125 | } |
| 126 | |
| 127 | /// What the operator supplies out of band. Nothing in here is ever read from the bundle. |
| 128 | #[derive(Debug, Clone, Default)] |
| 129 | pub struct Options { |
| 130 | /// The independent judge's P-256 public key. With it, a bundle must carry a valid |
| 131 | /// `rsi-eval/2` evaluation; without it, an evaluation in the bundle fails `evaluation_untrusted`. |
| 132 | pub judge_key: Option<p256::ecdsa::VerifyingKey>, |
| 133 | /// SHA-256 (hex) of the operator's own copy of the evaluation policy. With it, the retained |
| 134 | /// policy must be exactly that file (`evaluation_policy_mismatch` otherwise). |
| 135 | pub policy_sha256: Option<String>, |
| 136 | } |
| 137 | |
| 138 | /// Verify the archive rooted at `dir`. Never panics on hostile input; always one line. |
| 139 | pub fn verify(dir: &Path) -> String { |
| 140 | verify_with(dir, &Options::default()) |
| 141 | } |
| 142 | |
| 143 | pub fn verify_with(dir: &Path, opts: &Options) -> String { |
| 144 | match verify_inner(dir, opts) { |
| 145 | Ok((missing, effect, no_candidate)) => { |
| 146 | let complete = missing.is_empty(); |
| 147 | let mut line = if complete { |
| 148 | "PASS complete".to_string() |
| 149 | } else { |
| 150 | format!( |
| 151 | "PASS_LABELLED_INCOMPLETE missing={}", |
| 152 | missing.into_iter().collect::<Vec<_>>().join(",") |
| 153 | ) |
| 154 | }; |
| 155 | if let Some(e) = effect { |
| 156 | line.push_str(&format!(" effect={e}")); |
| 157 | } |
| 158 | // A complete chain run without a frozen candidate manifest says so on the line itself. |
| 159 | if complete && no_candidate { |
| 160 | line.push_str(" candidate=none"); |
| 161 | } |
| 162 | line |
| 163 | } |
| 164 | Err(Fail(line)) => line, |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// What the effect link proved, named by binding and strength. |
| 169 | /// `aien-ledger-slice/1:strong` binds request, trace, approval and bytes through records the |
| 170 | /// daemon wrote; `record_effect_receipt/1:weak` binds tool, outcome and digests only. |
| 171 | type EffectLabel = String; |
| 172 | |
| 173 | /// Missing items, the effect label, and whether the AIEN link names no frozen candidate. |
| 174 | fn verify_inner( |
| 175 | dir: &Path, |
| 176 | opts: &Options, |
| 177 | ) -> Result<(BTreeSet<String>, Option<EffectLabel>, bool), Fail> { |
| 178 | let raw = match std::fs::read(dir.join(COMPANION_FILE)) { |
| 179 | Ok(b) => b, |
| 180 | Err(_) => return fail("missing_companion", COMPANION_FILE), |
| 181 | }; |
| 182 | let m: Value = match strict::parse(&raw) { |
| 183 | Some(v) => v, |
| 184 | None => return fail("unparseable_companion", COMPANION_FILE), |
| 185 | }; |
| 186 | if s(&m, &["kind"]) != Some(KIND) || m.get("schema").and_then(Value::as_u64) != Some(SCHEMA) { |
| 187 | return fail("unsupported_companion", "kind/schema"); |
| 188 | } |
| 189 | |
| 190 | // 1. Records: retained bytes match their size and digest, or the record is labelled. |
| 191 | let mut archive = Archive { |
| 192 | records: BTreeMap::new(), |
| 193 | }; |
| 194 | let mut actually_missing = BTreeSet::new(); |
| 195 | let records = match m.get("records").and_then(Value::as_object) { |
| 196 | Some(r) => r, |
| 197 | None => return fail("malformed_companion", "records"), |
| 198 | }; |
| 199 | for (name, r) in records { |
| 200 | let retained = match r.get("retained") { |
| 201 | None => true, |
| 202 | Some(Value::Bool(b)) => *b, |
| 203 | Some(_) => return fail("malformed_companion", format!("records.{name}.retained")), |
| 204 | }; |
| 205 | let sha = match s(r, &["sha256"]) { |
| 206 | Some(x) if x.len() == 64 && x.bytes().all(|b| b.is_ascii_hexdigit()) => x.to_string(), |
| 207 | _ => return fail("malformed_companion", format!("records.{name}.sha256")), |
| 208 | }; |
| 209 | let declared_waldo = s(r, &["waldo_sha256"]).map(str::to_string); |
| 210 | let bytes = if retained { |
| 211 | let path = match s(r, &["path"]) { |
| 212 | Some(p) if safe_relative(p) => p, |
| 213 | _ => return fail("malformed_companion", format!("records.{name}.path")), |
| 214 | }; |
| 215 | if crosses_symlink(dir, path) { |
| 216 | return fail( |
| 217 | "malformed_companion", |
| 218 | format!("records.{name}.path (symlink)"), |
| 219 | ); |
| 220 | } |
| 221 | let b = match std::fs::read(dir.join(path)) { |
| 222 | Ok(b) => b, |
| 223 | Err(_) => return fail("missing_record", name), |
| 224 | }; |
| 225 | let want = r.get("bytes").and_then(Value::as_u64); |
| 226 | if want != Some(b.len() as u64) { |
| 227 | return fail( |
| 228 | "size_mismatch", |
| 229 | format!("{name} declared={} actual={}", want.unwrap_or(0), b.len()), |
| 230 | ); |
| 231 | } |
| 232 | if sha256_hex(&b) != sha { |
| 233 | return fail("digest_mismatch", name); |
| 234 | } |
| 235 | if let Some(w) = &declared_waldo { |
| 236 | if &waldo_sha256(&b) != w { |
| 237 | return fail("digest_mismatch", format!("{name}.waldo_sha256")); |
| 238 | } |
| 239 | } |
| 240 | Some(b) |
| 241 | } else { |
| 242 | actually_missing.insert(format!("record:{name}")); |
| 243 | None |
| 244 | }; |
| 245 | archive.records.insert( |
| 246 | name.clone(), |
| 247 | Record { |
| 248 | path: s(r, &["path"]).unwrap_or("").to_string(), |
| 249 | sha256: sha, |
| 250 | waldo_sha256: declared_waldo, |
| 251 | bytes, |
| 252 | }, |
| 253 | ); |
| 254 | } |
| 255 | |
| 256 | // 2. Completeness: every link is an object or an explicit null; the label matches reality. |
| 257 | for link in LINKS { |
| 258 | match m.get(link) { |
| 259 | Some(Value::Object(_)) => {} |
| 260 | Some(Value::Null) => { |
| 261 | actually_missing.insert(format!("link:{link}")); |
| 262 | } |
| 263 | _ => { |
| 264 | return fail( |
| 265 | "malformed_companion", |
| 266 | format!("{link} must be an object or null"), |
| 267 | ) |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | for item in modelturn::implied_missing(&archive, &m) { |
| 272 | actually_missing.insert(item); |
| 273 | } |
| 274 | actually_missing.extend(testrun::implied_missing(&m)); |
| 275 | let state = s(&m, &["completeness", "state"]); |
| 276 | let declared: BTreeSet<String> = m |
| 277 | .get("completeness") |
| 278 | .and_then(|c| c.get("missing")) |
| 279 | .and_then(Value::as_array) |
| 280 | .map(|a| { |
| 281 | a.iter() |
| 282 | .filter_map(|x| x.as_str().map(str::to_string)) |
| 283 | .collect() |
| 284 | }) |
| 285 | .unwrap_or_default(); |
| 286 | match state { |
| 287 | Some("complete") if actually_missing.is_empty() && declared.is_empty() => {} |
| 288 | Some("complete") => { |
| 289 | let first = actually_missing.iter().next().cloned().unwrap_or_default(); |
| 290 | return fail("unlabelled_missing", format!("{first} (declared complete)")); |
| 291 | } |
| 292 | Some("incomplete") if declared == actually_missing && !declared.is_empty() => {} |
| 293 | Some("incomplete") => { |
| 294 | let diff: Vec<_> = declared |
| 295 | .symmetric_difference(&actually_missing) |
| 296 | .cloned() |
| 297 | .collect(); |
| 298 | return fail("completeness_mismatch", diff.join(",")); |
| 299 | } |
| 300 | _ => return fail("malformed_companion", "completeness.state"), |
| 301 | } |
| 302 | let link = |name: &str| m.get(name).filter(|v| v.is_object()); |
| 303 | |
| 304 | // 3. Lineage: corpus BOM and licenses -> plan -> run -> managed model BOM. |
| 305 | let mut run_id: Option<String> = None; |
| 306 | let mut model_id: Option<String> = None; |
| 307 | if let Some(l) = link("lineage") { |
| 308 | match s(l, &["kind"]) { |
| 309 | Some("waldo_run") => { |
| 310 | let (r, mi) = check_waldo_lineage(&archive, l)?; |
| 311 | run_id = Some(r); |
| 312 | model_id = Some(mi); |
| 313 | } |
| 314 | Some("unknown_pretraining") => { |
| 315 | if let Some(n) = archive.records.keys().find(|n| n.starts_with("waldo_")) { |
| 316 | return fail( |
| 317 | "lineage_conflict", |
| 318 | format!("unknown_pretraining with record {n}"), |
| 319 | ); |
| 320 | } |
| 321 | if s(l, &["origin", "model_id"]).is_none() |
| 322 | || s(l, &["origin", "revision"]).is_none() |
| 323 | { |
| 324 | return fail("malformed_companion", "lineage.origin.model_id/revision"); |
| 325 | } |
| 326 | } |
| 327 | _ => return fail("malformed_companion", "lineage.kind"), |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | // 4. Export: the release BOM (a conversion is its own record) pins every exported file. |
| 332 | if let Some(e) = link("export") { |
| 333 | check_export(&archive, e, run_id.as_deref(), model_id.as_deref())?; |
| 334 | } |
| 335 | |
| 336 | // 5. Load support: a check result, never a promise. |
| 337 | let computed = match (link("export"), link("load_support")) { |
| 338 | (Some(_), Some(ls)) => { |
| 339 | let c = compute_load_support(&archive)?; |
| 340 | let d = s(ls, &["declared"]).unwrap_or(""); |
| 341 | if let Some(c) = &c { |
| 342 | if c != d { |
| 343 | return fail( |
| 344 | "load_support_mismatch", |
| 345 | format!("computed={c} declared={d}"), |
| 346 | ); |
| 347 | } |
| 348 | } |
| 349 | c |
| 350 | } |
| 351 | (None, Some(_)) => return fail("malformed_companion", "load_support without export"), |
| 352 | _ => None, |
| 353 | }; |
| 354 | |
| 355 | // 6. AIEN: candidate manifest and the daemon's load line name the exported bytes. |
| 356 | if let Some(a) = link("aien") { |
| 357 | if link("export").is_none() { |
| 358 | return fail("malformed_companion", "aien without export"); |
| 359 | } |
| 360 | if let Some(c) = &computed { |
| 361 | if c != SUPPORTED { |
| 362 | return fail("load_unsupported", c); |
| 363 | } |
| 364 | } |
| 365 | check_aien(&archive, a)?; |
| 366 | } |
| 367 | |
| 368 | // 7 and 8. INTERPLANE trace, then the effect for exactly that request. |
| 369 | let mut call: Option<Call> = None; |
| 370 | if let Some(t) = link("interplane") { |
| 371 | if link("aien").is_none() { |
| 372 | return fail("malformed_companion", "interplane without aien"); |
| 373 | } |
| 374 | call = check_trace(&archive, t)?; |
| 375 | } |
| 376 | let mut effect_label = None; |
| 377 | let mut ledger_checked = false; |
| 378 | if let Some(e) = link("effect") { |
| 379 | let (Some(t), Some(aien)) = (link("interplane"), link("aien")) else { |
| 380 | return fail("malformed_companion", "effect without interplane"); |
| 381 | }; |
| 382 | match s(e, &["binding"]) { |
| 383 | Some(LEDGER_BINDING) => { |
| 384 | // Who authored the proposal must be stated, never implied by silence. A scripted |
| 385 | // turn leaves `link:model_turn` missing; a model generation is checked in |
| 386 | // `modelturn` against the daemon's own generation record. |
| 387 | let origin = match s(e, &["proposal_origin"]) { |
| 388 | Some(modelturn::SCRIPTED) => modelturn::SCRIPTED, |
| 389 | Some(modelturn::GENERATED) => modelturn::GENERATED, |
| 390 | Some(modelturn::SUPERSEDED) => { |
| 391 | return fail( |
| 392 | "unsupported_binding", |
| 393 | "effect.proposal_origin=model_generation/1 (superseded by model_generation/2: needs the daemon's own record)", |
| 394 | ) |
| 395 | } |
| 396 | Some(other) => { |
| 397 | return fail( |
| 398 | "unsupported_binding", |
| 399 | format!("effect.proposal_origin={other}"), |
| 400 | ) |
| 401 | } |
| 402 | None => return fail("malformed_companion", "effect.proposal_origin"), |
| 403 | }; |
| 404 | ledger::check( |
| 405 | &archive, |
| 406 | e, |
| 407 | t, |
| 408 | aien, |
| 409 | call.as_ref(), |
| 410 | testrun::claims_test_run(&archive, &m), |
| 411 | )?; |
| 412 | if origin == modelturn::GENERATED { |
| 413 | modelturn::check(&archive, t, call.as_ref())?; |
| 414 | } |
| 415 | effect_label = Some(format!("{LEDGER_BINDING}:strong proposal={origin}")); |
| 416 | ledger_checked = true; |
| 417 | } |
| 418 | Some(RECEIPT_BINDING) => { |
| 419 | // Weaker: tool + digests only. The label stays on the verdict. |
| 420 | if s(e, &["digest_form"]) != Some(SERDE_DIGEST_FORM) { |
| 421 | return fail( |
| 422 | "canonicalization_mismatch", |
| 423 | format!( |
| 424 | "effect.digest_form={} (producer form is {SERDE_DIGEST_FORM})", |
| 425 | s(e, &["digest_form"]).unwrap_or("absent") |
| 426 | ), |
| 427 | ); |
| 428 | } |
| 429 | if let Some(c) = &call { |
| 430 | check_receipt(&archive, t, &c.args, &c.result)?; |
| 431 | } |
| 432 | effect_label = Some(format!("{RECEIPT_BINDING}:weak")); |
| 433 | } |
| 434 | Some(other) => return fail("unsupported_binding", format!("effect.binding={other}")), |
| 435 | None => return fail("malformed_companion", "effect.binding"), |
| 436 | } |
| 437 | } |
| 438 | testrun::check(&archive, &m, ledger_checked)?; |
| 439 | evaluation::check(&archive, &m, ledger_checked, opts)?; |
| 440 | // Test material may verify, but never as a complete chain: `fixture.class` other than `real` |
| 441 | // refuses `complete` whatever records it carries (#76 review). Checked last, so every deeper |
| 442 | // check above still runs on test material. |
| 443 | if let Some(f) = m.get("fixture") { |
| 444 | match s(f, &["class"]) { |
| 445 | Some("real") => {} |
| 446 | Some(c) if actually_missing.is_empty() => { |
| 447 | return fail("synthetic_complete", format!("fixture.class={c}")) |
| 448 | } |
| 449 | Some(_) => {} |
| 450 | None => return fail("malformed_companion", "fixture.class"), |
| 451 | } |
| 452 | } |
| 453 | let no_candidate = link("aien").is_some_and(|a| s(a, &["candidate_id"]).is_none()); |
| 454 | Ok((actually_missing, effect_label, no_candidate)) |
| 455 | } |
| 456 | |
| 457 | fn check_waldo_lineage(a: &Archive, l: &Value) -> Result<(String, String), Fail> { |
| 458 | let run_id = s(l, &["run_id"]).unwrap_or("").to_string(); |
| 459 | let Some(run_bom_bytes) = a.bytes("waldo_run_bom")? else { |
| 460 | return fail( |
| 461 | "malformed_companion", |
| 462 | "waldo_run_bom must be retained (it carries the corpus BOM)", |
| 463 | ); |
| 464 | }; |
| 465 | let run_bom: Value = a.json("waldo_run_bom")?.unwrap_or(Value::Null); |
| 466 | if s(&run_bom, &["kind"]) != Some("openwaldo-bom") |
| 467 | || s(&run_bom, &["subject"]) != Some("training-run") |
| 468 | || s(&run_bom, &["id"]) != Some(run_id.as_str()) |
| 469 | { |
| 470 | return fail("binding_mismatch", "run_bom.kind/subject/id"); |
| 471 | } |
| 472 | // Corpus BOM embedded in the run BOM: its WALDO digest is the run's corpus pin. |
| 473 | let c = compact(run_bom_bytes); |
| 474 | let corpus = match top_level_member(&c, "corpus_bom") { |
| 475 | Some(x) => x, |
| 476 | None => return fail("binding_mismatch", "run_bom.corpus_bom absent"), |
| 477 | }; |
| 478 | if Some(sha256_hex(corpus).as_str()) != s(&run_bom, &["corpus_bom_sha256"]) { |
| 479 | return fail("binding_mismatch", "run_bom.corpus_bom_sha256"); |
| 480 | } |
| 481 | let cb = &run_bom["corpus_bom"]; |
| 482 | if s(cb, &["kind"]) != Some("openwaldo-bom") || s(cb, &["subject"]) != Some("corpus") { |
| 483 | return fail("binding_mismatch", "corpus_bom.kind/subject"); |
| 484 | } |
| 485 | let licenses: Vec<Value> = cb |
| 486 | .get("licenses") |
| 487 | .and_then(Value::as_object) |
| 488 | .map(|o| o.keys().map(|k| Value::String(k.clone())).collect()) |
| 489 | .unwrap_or_default(); |
| 490 | if l.get("corpus_license_assertions") != Some(&Value::Array(licenses)) { |
| 491 | return fail("binding_mismatch", "lineage.corpus_license_assertions"); |
| 492 | } |
| 493 | if l.get("training_backend") != run_bom.get("execution").and_then(|e| e.get("backend")) { |
| 494 | return fail("binding_mismatch", "lineage.training_backend"); |
| 495 | } |
| 496 | let model_id = s(&run_bom, &["model_id"]).unwrap_or("").to_string(); |
| 497 | if s(l, &["model_id"]) != Some(model_id.as_str()) { |
| 498 | return fail("binding_mismatch", "lineage.model_id"); |
| 499 | } |
| 500 | // Preflight is pinned by raw bytes inside the run BOM. |
| 501 | if Some(a.sha("waldo_preflight")?) != s(&run_bom, &["preflight", "sha256"]) { |
| 502 | return fail("binding_mismatch", "run_bom.preflight.sha256"); |
| 503 | } |
| 504 | // Run record: same run BOM, terminal state complete. |
| 505 | if let Some(run) = a.json("waldo_run")? { |
| 506 | let rb = waldo_sha256(run_bom_bytes); |
| 507 | if s(&run, &["bom_sha256"]) != Some(rb.as_str()) |
| 508 | || s(&run, &["id"]) != Some(run_id.as_str()) |
| 509 | { |
| 510 | return fail("binding_mismatch", "run.bom_sha256"); |
| 511 | } |
| 512 | if s(&run, &["state"]) != Some("complete") { |
| 513 | return fail("run_not_complete", s(&run, &["state"]).unwrap_or("absent")); |
| 514 | } |
| 515 | } |
| 516 | // Plan: its WALDO digest is the model identity. |
| 517 | if let Some(p) = a.waldo("waldo_plan")? { |
| 518 | if p != model_id { |
| 519 | return fail("binding_mismatch", "plan_sha256 != run_bom.model_id"); |
| 520 | } |
| 521 | } |
| 522 | // Managed model BOM: pins the run BOM, selects the run, pins the run's weights. |
| 523 | if let Some(mb) = a.json("waldo_model_bom")? { |
| 524 | if s(&mb, &["model_id"]) != Some(model_id.as_str()) |
| 525 | || s(&mb, &["plan_sha256"]) != Some(model_id.as_str()) |
| 526 | { |
| 527 | return fail("binding_mismatch", "model_bom.model_id/plan_sha256"); |
| 528 | } |
| 529 | if s(&mb, &["current_run_id"]) != Some(run_id.as_str()) { |
| 530 | return fail("binding_mismatch", "model_bom.current_run_id"); |
| 531 | } |
| 532 | let pin = mb |
| 533 | .get("runs") |
| 534 | .and_then(Value::as_array) |
| 535 | .and_then(|r| r.iter().find(|p| s(p, &["id"]) == Some(run_id.as_str()))); |
| 536 | let Some(pin) = pin else { |
| 537 | return fail( |
| 538 | "binding_mismatch", |
| 539 | format!("model_bom.runs[{run_id}] absent"), |
| 540 | ); |
| 541 | }; |
| 542 | if s(pin, &["bom_sha256"]) != Some(waldo_sha256(run_bom_bytes).as_str()) { |
| 543 | return fail( |
| 544 | "binding_mismatch", |
| 545 | format!("model_bom.runs[{run_id}].bom_sha256"), |
| 546 | ); |
| 547 | } |
| 548 | if pin.get("simulated") != Some(&Value::Bool(false)) |
| 549 | || s(pin, &["state"]) != Some("complete") |
| 550 | { |
| 551 | return fail("run_not_complete", format!("model_bom.runs[{run_id}]")); |
| 552 | } |
| 553 | let w = pin |
| 554 | .get("artifacts") |
| 555 | .and_then(Value::as_array) |
| 556 | .and_then(|x| x.iter().find(|y| s(y, &["role"]) == Some("weights"))); |
| 557 | if w.and_then(|w| s(w, &["sha256"])) != Some(a.sha("run_weights")?) { |
| 558 | return fail( |
| 559 | "binding_mismatch", |
| 560 | format!("model_bom.runs[{run_id}].artifacts[weights]"), |
| 561 | ); |
| 562 | } |
| 563 | } |
| 564 | Ok((run_id, model_id)) |
| 565 | } |
| 566 | |
| 567 | fn file_name(p: &str) -> &str { |
| 568 | p.rsplit('/').next().unwrap_or(p) |
| 569 | } |
| 570 | |
| 571 | fn check_export( |
| 572 | a: &Archive, |
| 573 | e: &Value, |
| 574 | run_id: Option<&str>, |
| 575 | model_id: Option<&str>, |
| 576 | ) -> Result<(), Fail> { |
| 577 | for n in ["export_weights", "export_config", "export_tokenizer"] { |
| 578 | a.sha(n)?; |
| 579 | } |
| 580 | match (a.has("export_chat_template"), e.get("chat_template")) { |
| 581 | (true, Some(Value::String(r))) if r == "export_chat_template" => {} |
| 582 | (false, Some(Value::Null)) => {} |
| 583 | _ => { |
| 584 | return fail( |
| 585 | "malformed_companion", |
| 586 | "export.chat_template must name export_chat_template or be null", |
| 587 | ) |
| 588 | } |
| 589 | } |
| 590 | let Some(run_id) = run_id else { |
| 591 | // External lineage: no WALDO release record exists; files are pinned by this manifest |
| 592 | // and, when present, by the AIEN candidate manifest. |
| 593 | if a.has("release_bom") { |
| 594 | return fail("lineage_conflict", "release_bom without waldo_run lineage"); |
| 595 | } |
| 596 | return Ok(()); |
| 597 | }; |
| 598 | let Some(rel) = a.json("release_bom")? else { |
| 599 | return fail( |
| 600 | "malformed_companion", |
| 601 | "release_bom must be retained for waldo_run lineage", |
| 602 | ); |
| 603 | }; |
| 604 | if s(&rel, &["kind"]) != Some("openwaldo-bom") || s(&rel, &["subject"]) != Some("model-release") |
| 605 | { |
| 606 | return fail("binding_mismatch", "release_bom.kind/subject"); |
| 607 | } |
| 608 | if s(&rel, &["format"]) != s(e, &["format"]) { |
| 609 | return fail("binding_mismatch", "release_bom.format"); |
| 610 | } |
| 611 | if s(&rel, &["run_id"]) != Some(run_id) || s(&rel, &["model_id"]) != model_id { |
| 612 | return fail("binding_mismatch", "release_bom.run_id/model_id"); |
| 613 | } |
| 614 | if a.waldo("waldo_model_bom")?.as_deref() != s(&rel, &["source_bom_sha256"]) { |
| 615 | return fail("binding_mismatch", "release_bom.source_bom_sha256"); |
| 616 | } |
| 617 | let arts = rel |
| 618 | .get("artifacts") |
| 619 | .and_then(Value::as_array) |
| 620 | .cloned() |
| 621 | .unwrap_or_default(); |
| 622 | for n in [ |
| 623 | "export_weights", |
| 624 | "export_config", |
| 625 | "export_tokenizer", |
| 626 | "export_chat_template", |
| 627 | ] { |
| 628 | if !a.has(n) { |
| 629 | continue; |
| 630 | } |
| 631 | let name = file_name(&a.records[n].path); |
| 632 | let hit = arts.iter().find(|x| s(x, &["path"]) == Some(name)); |
| 633 | if hit.and_then(|h| s(h, &["sha256"])) != Some(a.sha(n)?) { |
| 634 | return fail("binding_mismatch", format!("release_bom.artifacts[{name}]")); |
| 635 | } |
| 636 | } |
| 637 | // Conversion check: WALDO's Hugging Face export rewrites the safetensors header and copies |
| 638 | // the tensor data section byte for byte (docs/MODEL-EXPORTS.md). |
| 639 | if s(e, &["format"]) == Some("huggingface") { |
| 640 | if let (Some(rw), Some(ew)) = (a.bytes("run_weights")?, a.bytes("export_weights")?) { |
| 641 | if safetensors_data(rw).is_none() || safetensors_data(rw) != safetensors_data(ew) { |
| 642 | return fail( |
| 643 | "conversion_mismatch", |
| 644 | "safetensors data section run_weights != export_weights", |
| 645 | ); |
| 646 | } |
| 647 | } |
| 648 | } |
| 649 | Ok(()) |
| 650 | } |
| 651 | |
| 652 | fn safetensors_data(b: &[u8]) -> Option<&[u8]> { |
| 653 | let n = u64::from_le_bytes(b.get(..8)?.try_into().ok()?) as usize; |
| 654 | b.get(8usize.checked_add(n)?..) |
| 655 | } |
| 656 | |
| 657 | /// Structural load-support check against what aien-cli loads today: a `LlamaForCausalLM` |
| 658 | /// config.json and a Hugging Face `tokenizer.json` (aien-inference-abi `Tokenizer::from_file`, |
| 659 | /// the `tokenizers` crate). Returns None when the needed bytes are not retained. |
| 660 | fn compute_load_support(a: &Archive) -> Result<Option<String>, Fail> { |
| 661 | let (Some(cfg), Some(tok)) = (a.json("export_config")?, a.bytes("export_tokenizer")?) else { |
| 662 | return Ok(None); |
| 663 | }; |
| 664 | let arch = cfg |
| 665 | .get("architectures") |
| 666 | .and_then(Value::as_array) |
| 667 | .and_then(|x| x.first()) |
| 668 | .and_then(Value::as_str) |
| 669 | .unwrap_or("absent"); |
| 670 | if arch != "LlamaForCausalLM" { |
| 671 | return Ok(Some(format!("unsupported_architecture:{arch}"))); |
| 672 | } |
| 673 | let tj: Value = strict::parse(tok).unwrap_or(Value::Null); |
| 674 | let vocab = tj |
| 675 | .get("model") |
| 676 | .and_then(|m| m.get("vocab")) |
| 677 | .and_then(Value::as_object); |
| 678 | let Some(vocab) = vocab else { |
| 679 | let class = s(&tj, &["tokenizer_class"]).unwrap_or("not_tokenizer_json"); |
| 680 | return Ok(Some(format!("unsupported_tokenizer:{class}"))); |
| 681 | }; |
| 682 | let mut ids: BTreeSet<u64> = vocab.values().filter_map(Value::as_u64).collect(); |
| 683 | if let Some(added) = tj.get("added_tokens").and_then(Value::as_array) { |
| 684 | ids.extend( |
| 685 | added |
| 686 | .iter() |
| 687 | .filter_map(|t| t.get("id").and_then(Value::as_u64)), |
| 688 | ); |
| 689 | } |
| 690 | let tok_n = ids.iter().next_back().map(|m| m + 1).unwrap_or(0); |
| 691 | let cfg_n = cfg.get("vocab_size").and_then(Value::as_u64).unwrap_or(0); |
| 692 | if tok_n != cfg_n { |
| 693 | return fail( |
| 694 | "incompatible", |
| 695 | format!("config.vocab_size={cfg_n} tokenizer_vocab={tok_n}"), |
| 696 | ); |
| 697 | } |
| 698 | Ok(Some(SUPPORTED.to_string())) |
| 699 | } |
| 700 | |
| 701 | /// Minimal reader for the CandidateManifestV1 subset used here: `[section]` and `key = "value"`. |
| 702 | /// None when a key repeats in a section (no last-wins reading). |
| 703 | fn toml_table(text: &str) -> Option<BTreeMap<(String, String), String>> { |
| 704 | let mut out = BTreeMap::new(); |
| 705 | let mut section = String::new(); |
| 706 | for line in text.lines() { |
| 707 | let line = line.trim(); |
| 708 | if line.starts_with('[') && line.ends_with(']') { |
| 709 | section = line[1..line.len() - 1].trim().to_string(); |
| 710 | } else if let Some((k, v)) = line.split_once('=') { |
| 711 | let v = v.trim(); |
| 712 | if let Some(rest) = v.strip_prefix('"') { |
| 713 | if let Some(end) = rest.find('"') { |
| 714 | let key = (section.clone(), k.trim().to_string()); |
| 715 | if out.insert(key, rest[..end].to_string()).is_some() { |
| 716 | return None; |
| 717 | } |
| 718 | } |
| 719 | } |
| 720 | } |
| 721 | } |
| 722 | Some(out) |
| 723 | } |
| 724 | |
| 725 | fn check_aien(a: &Archive, l: &Value) -> Result<(), Fail> { |
| 726 | // Optional record: no entry at all means no AIEN candidate manifest exists (not a missing record). |
| 727 | let cand = if a.has("candidate_manifest") { |
| 728 | a.bytes("candidate_manifest")? |
| 729 | } else { |
| 730 | None |
| 731 | }; |
| 732 | if cand.is_none() && s(l, &["candidate_id"]).is_some() { |
| 733 | // A candidate claim must be backed by its manifest; absence is only honest with candidate_id null. |
| 734 | return fail( |
| 735 | "binding_mismatch", |
| 736 | "candidate_id without candidate_manifest", |
| 737 | ); |
| 738 | } |
| 739 | if let Some(b) = cand { |
| 740 | let Some(t) = toml_table(&String::from_utf8_lossy(b)) else { |
| 741 | return fail("binding_mismatch", "candidate manifest repeats a key"); |
| 742 | }; |
| 743 | let get = |sec: &str, k: &str| t.get(&(sec.to_string(), k.to_string())).map(String::as_str); |
| 744 | if get("", "schema") != Some("CandidateManifestV1") { |
| 745 | return fail("binding_mismatch", "candidate.schema"); |
| 746 | } |
| 747 | if get("", "id") != s(l, &["candidate_id"]) { |
| 748 | return fail("binding_mismatch", "candidate.id"); |
| 749 | } |
| 750 | let exe = s(l, &["executable"]).unwrap_or(""); |
| 751 | if get("executables", exe).is_none() |
| 752 | || get("executables", exe) != s(l, &["executable_sha256"]) |
| 753 | { |
| 754 | return fail("binding_mismatch", format!("candidate.executables.{exe}")); |
| 755 | } |
| 756 | for (key, rec) in [ |
| 757 | ("model-safetensors-sha256", "export_weights"), |
| 758 | ("tokenizer-json-sha256", "export_tokenizer"), |
| 759 | ("config-json-sha256", "export_config"), |
| 760 | ] { |
| 761 | if get("model", key) != Some(a.sha(rec)?) { |
| 762 | return fail("binding_mismatch", format!("candidate.model.{key}")); |
| 763 | } |
| 764 | } |
| 765 | } |
| 766 | if let Some(b) = a.bytes("aien_load_log")? { |
| 767 | let text = String::from_utf8_lossy(b); |
| 768 | let Some(line) = text |
| 769 | .lines() |
| 770 | .rev() |
| 771 | .find(|x| x.contains("checkpoint loaded from ")) |
| 772 | else { |
| 773 | return fail("binding_mismatch", "aien_load.line absent"); |
| 774 | }; |
| 775 | let field = |k: &str| { |
| 776 | line.split([' ', ',', ')']) |
| 777 | .find_map(|w| w.strip_prefix(&format!("{k}="))) |
| 778 | .unwrap_or("") |
| 779 | .to_string() |
| 780 | }; |
| 781 | if !line.contains("(tokenizer loaded,") { |
| 782 | return fail("binding_mismatch", "aien_load.tokenizer missing"); |
| 783 | } |
| 784 | if field("model_sha256") != a.sha("export_weights")? { |
| 785 | return fail("binding_mismatch", "aien_load.model_sha256"); |
| 786 | } |
| 787 | if field("tokenizer_sha256") != a.sha("export_tokenizer")? { |
| 788 | return fail("binding_mismatch", "aien_load.tokenizer_sha256"); |
| 789 | } |
| 790 | } |
| 791 | Ok(()) |
| 792 | } |
| 793 | |
| 794 | /// The retained request, as the trace holds it. |
| 795 | pub(crate) struct Call { |
| 796 | pub tool: String, |
| 797 | pub args: Value, |
| 798 | pub result: Value, |
| 799 | /// The `tool_request` payload and the envelope's `source`, as the trace holds them. |
| 800 | pub req_payload: Value, |
| 801 | pub req_source: Value, |
| 802 | } |
| 803 | |
| 804 | /// Returns the request's tool, arguments and result payload, when the trace bytes are retained. |
| 805 | fn check_trace(a: &Archive, t: &Value) -> Result<Option<Call>, Fail> { |
| 806 | let Some(trace) = a.json("interplane_trace")? else { |
| 807 | return Ok(None); |
| 808 | }; |
| 809 | let (Some(tid), Some(rid)) = (s(t, &["trace_id"]), s(t, &["request_id"])) else { |
| 810 | return fail("malformed_companion", "interplane.trace_id/request_id"); |
| 811 | }; |
| 812 | let Some(envs) = trace.as_array() else { |
| 813 | return fail("unparseable_record", "interplane_trace"); |
| 814 | }; |
| 815 | let (mut req, mut result, mut final_seen) = (None, None, false); |
| 816 | for (i, e) in envs.iter().enumerate() { |
| 817 | if let Err(code) = interplane_core::validate_envelope_value(e) { |
| 818 | return fail( |
| 819 | "invalid_envelope", |
| 820 | format!("interplane_trace[{i}] {code:?}"), |
| 821 | ); |
| 822 | } |
| 823 | if s(e, &["trace_id"]) != Some(tid) { |
| 824 | return fail( |
| 825 | "binding_mismatch", |
| 826 | format!("interplane_trace[{i}].trace_id"), |
| 827 | ); |
| 828 | } |
| 829 | let p = &e["payload"]; |
| 830 | if s(p, &["request_id"]) == Some(rid) { |
| 831 | match s(p, &["kind"]) { |
| 832 | Some("tool_request") if req.is_some() => { |
| 833 | return fail( |
| 834 | "binding_mismatch", |
| 835 | format!("interplane_trace[{i}] second tool_request for {rid}"), |
| 836 | ) |
| 837 | } |
| 838 | Some("tool_request") => { |
| 839 | req = Some(( |
| 840 | s(p, &["tool", "name"]).unwrap_or("").to_string(), |
| 841 | p.get("arguments").cloned().unwrap_or(Value::Null), |
| 842 | p.clone(), |
| 843 | e.get("source").cloned().unwrap_or(Value::Null), |
| 844 | )) |
| 845 | } |
| 846 | Some("result") => { |
| 847 | // spec/CORE.md lifecycle: at most one `requires_approval`, then at most one final |
| 848 | // result, and nothing after the final one. |
| 849 | let pending = s(p, &["status"]) == Some("requires_approval"); |
| 850 | if final_seen || (pending && result.is_some()) { |
| 851 | return fail( |
| 852 | "binding_mismatch", |
| 853 | format!("interplane_trace[{i}] result after the final one for {rid}"), |
| 854 | ); |
| 855 | } |
| 856 | final_seen = !pending; |
| 857 | result = Some(p.clone()); |
| 858 | } |
| 859 | _ => {} |
| 860 | } |
| 861 | } |
| 862 | } |
| 863 | match (req, result) { |
| 864 | (Some((tool, args, req_payload, req_source)), Some(result)) => Ok(Some(Call { |
| 865 | tool, |
| 866 | args, |
| 867 | result, |
| 868 | req_payload, |
| 869 | req_source, |
| 870 | })), |
| 871 | _ => fail("not_in_trace", format!("{tid}/{rid}")), |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | /// SHA-256 of JCS (RFC 8785) bytes. Used only to recognise a digest made in the wrong form. |
| 876 | fn jcs_digest(v: &Value) -> String { |
| 877 | format!( |
| 878 | "sha256:{}", |
| 879 | sha256_hex(interplane_core::canonicalize(v).as_bytes()) |
| 880 | ) |
| 881 | } |
| 882 | |
| 883 | /// The digest aien-cli computes: SHA-256 of `serde_json::to_vec` (form |
| 884 | /// `serde_json.to_vec.sorted-keys/1`, see binding.rs), refused when not reproducible. |
| 885 | fn producer_digest(what: &str, v: &Value) -> Result<String, Fail> { |
| 886 | match compact_sorted(v) { |
| 887 | Ok(b) => Ok(format!("sha256:{}", sha256_hex(&b))), |
| 888 | Err(why) => fail( |
| 889 | "canonicalization_mismatch", |
| 890 | format!("{what}: producer form {SERDE_DIGEST_FORM} not reproduced: {why}"), |
| 891 | ), |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | /// Weaker binding. The aien-cli effect receipt (crates/aien-cli/src/tools.rs |
| 896 | /// `record_effect_receipt`, version 1) carries no trace or request id; it is bound to the request |
| 897 | /// only through its tool, outcome and the digests of the request's arguments and result data. |
| 898 | /// Two requests with identical tool, arguments and result data are not told apart. |
| 899 | fn check_receipt(a: &Archive, t: &Value, args: &Value, result: &Value) -> Result<(), Fail> { |
| 900 | let Some(r) = a.json("effect_receipt")? else { |
| 901 | return Ok(()); |
| 902 | }; |
| 903 | let rid = s(t, &["request_id"]).unwrap_or(""); |
| 904 | if r.get("version").and_then(Value::as_u64) != Some(1) { |
| 905 | return fail("binding_mismatch", "effect_receipt.version"); |
| 906 | } |
| 907 | if s(&r, &["tool"]) != s(result, &["provenance", "capability"]) { |
| 908 | return fail( |
| 909 | "binding_mismatch", |
| 910 | format!("effect_receipt.tool request={rid}"), |
| 911 | ); |
| 912 | } |
| 913 | for (field, value) in [ |
| 914 | ("arguments_digest", args), |
| 915 | ("result_digest", &result["data"]), |
| 916 | ] { |
| 917 | let what = format!("effect_receipt.{field}"); |
| 918 | let want = producer_digest(&what, value)?; |
| 919 | if s(&r, &[field]) != Some(want.as_str()) { |
| 920 | if s(&r, &[field]) == Some(jcs_digest(value).as_str()) { |
| 921 | return fail( |
| 922 | "canonicalization_mismatch", |
| 923 | format!("{what} is the JCS form; the producer form is {SERDE_DIGEST_FORM}"), |
| 924 | ); |
| 925 | } |
| 926 | return fail("binding_mismatch", format!("{what} request={rid}")); |
| 927 | } |
| 928 | } |
| 929 | let ok = s(result, &["status"]) == Some("ok"); |
| 930 | if r.get("success") != Some(&Value::Bool(ok)) { |
| 931 | return fail( |
| 932 | "binding_mismatch", |
| 933 | format!("effect_receipt.success request={rid}"), |
| 934 | ); |
| 935 | } |
| 936 | Ok(()) |
| 937 | } |