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 / ledger.rs
| 1 | //! Effect binding `aien-ledger-slice/1`: the companion's `effect` link bound to the records the |
| 2 | //! AIEN daemon itself wrote for one approved write. Specification: provenance/BINDING.md. |
| 3 | //! |
| 4 | //! The slice is five records exported with `ComposeRecall` (the daemon's own read command): |
| 5 | //! the replay claim (`approved_submission: accepted`), its `committed` settlement, the reserved |
| 6 | //! `approved_grant`, the effect `intent` and the `ack`. The daemon writes all five under its home |
| 7 | //! lock; `ComposeNote` refuses to write any of them. A sixth record, `daemon_run`, is written by |
| 8 | //! the run harness (not by the daemon) and names the daemon process. |
| 9 | //! |
| 10 | //! This module reads and compares. It never authorizes, executes or repairs anything. |
| 11 | |
| 12 | use super::{fail, s, Archive, Call, Fail}; |
| 13 | use crate::binding::{ |
| 14 | approval_binding_bytes, approved_proposal_bytes, compose_proposal_bytes, ApprovalFields, |
| 15 | APPROVAL_BINDING, |
| 16 | }; |
| 17 | use crate::gojson::sha256_hex; |
| 18 | use serde_json::Value; |
| 19 | |
| 20 | /// Record names of the slice, in ledger order. |
| 21 | pub const SLICE: [&str; 5] = [ |
| 22 | "ledger_claim", |
| 23 | "ledger_committed", |
| 24 | "ledger_grant", |
| 25 | "ledger_intent", |
| 26 | "ledger_ack", |
| 27 | ]; |
| 28 | pub const DAEMON_RUN: &str = "daemon_run"; |
| 29 | |
| 30 | /// One exported Cortex record (`ComposeRecordView`). |
| 31 | struct View { |
| 32 | id: u64, |
| 33 | links: Vec<u64>, |
| 34 | digest: String, |
| 35 | text: Value, |
| 36 | } |
| 37 | |
| 38 | fn view(a: &Archive, name: &str, note: &str) -> Result<View, Fail> { |
| 39 | let Some(v) = a.json(name)? else { |
| 40 | return fail("missing_record", format!("{name} (not retained)")); |
| 41 | }; |
| 42 | let bad = |
| 43 | |what: &str| -> Result<View, Fail> { fail("binding_mismatch", format!("{name}.{what}")) }; |
| 44 | let Some(id) = v.get("id").and_then(Value::as_u64) else { |
| 45 | return bad("id"); |
| 46 | }; |
| 47 | if v.get("verified") != Some(&Value::Bool(true)) { |
| 48 | return bad("verified"); |
| 49 | } |
| 50 | if s(&v, &["note"]) != Some(note) { |
| 51 | return bad("note"); |
| 52 | } |
| 53 | let digest = match s(&v, &["digest"]) { |
| 54 | Some(d) if d.len() == 64 && d.bytes().all(|b| b.is_ascii_hexdigit()) => d.to_string(), |
| 55 | _ => return bad("digest"), |
| 56 | }; |
| 57 | let Some(links) = v |
| 58 | .get("links") |
| 59 | .and_then(Value::as_array) |
| 60 | .map(|l| l.iter().map(|x| x.as_u64()).collect::<Option<Vec<u64>>>()) |
| 61 | else { |
| 62 | return bad("links"); |
| 63 | }; |
| 64 | let Some(links) = links else { |
| 65 | return bad("links"); |
| 66 | }; |
| 67 | let Some(text) = v |
| 68 | .get("text") |
| 69 | .and_then(Value::as_str) |
| 70 | .and_then(|t| crate::strict::parse(t.as_bytes())) |
| 71 | .filter(Value::is_object) |
| 72 | else { |
| 73 | return bad("text"); |
| 74 | }; |
| 75 | Ok(View { |
| 76 | id, |
| 77 | links, |
| 78 | digest, |
| 79 | text, |
| 80 | }) |
| 81 | } |
| 82 | |
| 83 | fn st<'a>(v: &'a View, name: &str, k: &str) -> Result<&'a str, Fail> { |
| 84 | match v.text.get(k).and_then(Value::as_str) { |
| 85 | Some(x) => Ok(x), |
| 86 | None => fail("binding_mismatch", format!("{name}.{k}")), |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | fn nu(v: &View, name: &str, k: &str) -> Result<u64, Fail> { |
| 91 | match v.text.get(k).and_then(Value::as_u64) { |
| 92 | Some(x) => Ok(x), |
| 93 | None => fail("binding_mismatch", format!("{name}.{k}")), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn eq<T: PartialEq>(a: T, b: T, what: &str) -> Result<(), Fail> { |
| 98 | if a == b { |
| 99 | Ok(()) |
| 100 | } else { |
| 101 | fail("binding_mismatch", what) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Check the slice against the INTERPLANE link `t`, the retained call and the AIEN link `aien`. |
| 106 | pub fn check( |
| 107 | a: &Archive, |
| 108 | e: &Value, |
| 109 | t: &Value, |
| 110 | aien: &Value, |
| 111 | call: Option<&Call>, |
| 112 | claims_test_run: bool, |
| 113 | ) -> Result<(), Fail> { |
| 114 | if s(e, &["approval_binding"]) != Some(APPROVAL_BINDING) { |
| 115 | return fail( |
| 116 | "unsupported_binding", |
| 117 | format!( |
| 118 | "effect.approval_binding != {APPROVAL_BINDING} (got {})", |
| 119 | s(e, &["approval_binding"]).unwrap_or("absent") |
| 120 | ), |
| 121 | ); |
| 122 | } |
| 123 | // An intent without an ack is an interrupted effect (checked below), not a missing record. |
| 124 | for n in SLICE.iter().chain([&DAEMON_RUN]) { |
| 125 | if *n != "ledger_ack" && !a.has(n) { |
| 126 | return fail("missing_record_entry", *n); |
| 127 | } |
| 128 | } |
| 129 | let claim = view(a, "ledger_claim", "effect")?; |
| 130 | let committed = view(a, "ledger_committed", "effect")?; |
| 131 | let grant = view(a, "ledger_grant", "authorization")?; |
| 132 | let intent = view(a, "ledger_intent", "effect")?; |
| 133 | // Record kinds. |
| 134 | eq( |
| 135 | st(&claim, "ledger_claim", "approved_submission")?, |
| 136 | "accepted", |
| 137 | "ledger_claim.approved_submission", |
| 138 | )?; |
| 139 | eq( |
| 140 | st(&committed, "ledger_committed", "approved_submission")?, |
| 141 | "committed", |
| 142 | "ledger_committed.approved_submission", |
| 143 | )?; |
| 144 | eq( |
| 145 | nu(&grant, "ledger_grant", "approved_grant")?, |
| 146 | 1, |
| 147 | "ledger_grant.approved_grant", |
| 148 | )?; |
| 149 | eq( |
| 150 | st(&intent, "ledger_intent", "phase")?, |
| 151 | "intent", |
| 152 | "ledger_intent.phase", |
| 153 | )?; |
| 154 | if !a.has("ledger_ack") { |
| 155 | return unlanded( |
| 156 | "effect_interrupted", |
| 157 | "ledger_intent is the last record: no ack, the write may or may not have landed", |
| 158 | claims_test_run, |
| 159 | ); |
| 160 | } |
| 161 | let ack = view(a, "ledger_ack", "effect")?; |
| 162 | eq(st(&ack, "ledger_ack", "phase")?, "ack", "ledger_ack.phase")?; |
| 163 | |
| 164 | // Ledger order: claim < committed < grant < intent < ack. |
| 165 | let ids = [claim.id, committed.id, grant.id, intent.id, ack.id]; |
| 166 | if ids.windows(2).any(|w| w[0] >= w[1]) { |
| 167 | return fail("binding_mismatch", format!("ledger record order {ids:?}")); |
| 168 | } |
| 169 | |
| 170 | // Settlement and links between the records. |
| 171 | eq( |
| 172 | nu(&committed, "ledger_committed", "claim")?, |
| 173 | claim.id, |
| 174 | "ledger_committed.claim", |
| 175 | )?; |
| 176 | eq( |
| 177 | committed.links.contains(&claim.id), |
| 178 | true, |
| 179 | "ledger_committed.links", |
| 180 | )?; |
| 181 | eq( |
| 182 | nu(&grant, "ledger_grant", "replay_claim")?, |
| 183 | claim.id, |
| 184 | "ledger_grant.replay_claim", |
| 185 | )?; |
| 186 | let (promotion, evidence) = ( |
| 187 | nu(&grant, "ledger_grant", "cx_promotion")?, |
| 188 | nu(&grant, "ledger_grant", "cx_evidence")?, |
| 189 | ); |
| 190 | for x in [promotion, evidence, claim.id] { |
| 191 | eq(grant.links.contains(&x), true, "ledger_grant.links")?; |
| 192 | } |
| 193 | let ev = &committed.text["evidence"]; |
| 194 | eq( |
| 195 | ev.get("compose_proposal_sha256").and_then(Value::as_str), |
| 196 | Some(st(&grant, "ledger_grant", "proposal_sha256")?), |
| 197 | "ledger_committed.evidence.compose_proposal_sha256", |
| 198 | )?; |
| 199 | eq( |
| 200 | ev.get("cx_promotion").and_then(Value::as_u64), |
| 201 | Some(promotion), |
| 202 | "ledger_committed.evidence.cx_promotion", |
| 203 | )?; |
| 204 | eq( |
| 205 | ev.get("cx_evidence").and_then(Value::as_u64), |
| 206 | Some(evidence), |
| 207 | "ledger_committed.evidence.cx_evidence", |
| 208 | )?; |
| 209 | |
| 210 | // The approval: recompute the key from the grant's own fields, in the named byte form. |
| 211 | let g = |k: &str| st(&grant, "ledger_grant", k); |
| 212 | let bound = ApprovalFields { |
| 213 | approval_id: g("approval_id")?, |
| 214 | approved_proposal_sha256: g("approved_proposal_sha256")?, |
| 215 | approver: g("approver")?, |
| 216 | content_sha256: g("content_sha256")?, |
| 217 | desk_key_id: g("desk_key_id")?, |
| 218 | path: g("path")?, |
| 219 | request_id: g("request_id")?, |
| 220 | trace_id: g("trace_id")?, |
| 221 | workspace: g("workspace")?, |
| 222 | }; |
| 223 | let key = sha256_hex(&approval_binding_bytes(&bound)); |
| 224 | eq( |
| 225 | key.as_str(), |
| 226 | g("approval_key")?, |
| 227 | "ledger_grant.approval_key (recomputed from its approval fields)", |
| 228 | )?; |
| 229 | eq( |
| 230 | key.as_str(), |
| 231 | st(&claim, "ledger_claim", "approval_key")?, |
| 232 | "ledger_claim.approval_key", |
| 233 | )?; |
| 234 | eq( |
| 235 | st(&claim, "ledger_claim", "approval_id")?, |
| 236 | bound.approval_id, |
| 237 | "ledger_claim.approval_id", |
| 238 | )?; |
| 239 | |
| 240 | // Request and trace identity: the daemon's records against the INTERPLANE link. |
| 241 | let (Some(tid), Some(rid)) = (s(t, &["trace_id"]), s(t, &["request_id"])) else { |
| 242 | return fail("malformed_companion", "interplane.trace_id/request_id"); |
| 243 | }; |
| 244 | for (who, rec) in [ |
| 245 | ("ledger_grant", g("trace_id")?), |
| 246 | ("ledger_claim", st(&claim, "ledger_claim", "trace_id")?), |
| 247 | ] { |
| 248 | eq(rec, tid, &format!("{who}.trace_id ledger={rec} link={tid}"))?; |
| 249 | } |
| 250 | for (who, rec) in [ |
| 251 | ("ledger_grant", g("request_id")?), |
| 252 | ("ledger_claim", st(&claim, "ledger_claim", "request_id")?), |
| 253 | ] { |
| 254 | eq( |
| 255 | rec, |
| 256 | rid, |
| 257 | &format!("{who}.request_id ledger={rec} link={rid}"), |
| 258 | )?; |
| 259 | } |
| 260 | |
| 261 | // Intent and ack name the grant and each other. |
| 262 | eq( |
| 263 | nu(&intent, "ledger_intent", "authorization")?, |
| 264 | grant.id, |
| 265 | "ledger_intent.authorization", |
| 266 | )?; |
| 267 | eq( |
| 268 | intent.links.contains(&grant.id), |
| 269 | true, |
| 270 | "ledger_intent.links", |
| 271 | )?; |
| 272 | for k in ["proposal_sha256", "path", "target", "content_sha256"] { |
| 273 | eq( |
| 274 | st(&intent, "ledger_intent", k)?, |
| 275 | g(k)?, |
| 276 | &format!("ledger_intent.{k}"), |
| 277 | )?; |
| 278 | } |
| 279 | eq( |
| 280 | intent.text.get("prior_sha256"), |
| 281 | grant.text.get("prior_sha256"), |
| 282 | "ledger_intent.prior_sha256", |
| 283 | )?; |
| 284 | eq( |
| 285 | st(&intent, "ledger_intent", "tool")?, |
| 286 | "write_file", |
| 287 | "ledger_intent.tool", |
| 288 | )?; |
| 289 | eq( |
| 290 | g("target")?, |
| 291 | format!("{}/{}", g("workspace")?.trim_end_matches('/'), g("path")?).as_str(), |
| 292 | "ledger_grant.target (workspace + path)", |
| 293 | )?; |
| 294 | eq( |
| 295 | nu(&ack, "ledger_ack", "intent")?, |
| 296 | intent.id, |
| 297 | "ledger_ack.intent", |
| 298 | )?; |
| 299 | eq( |
| 300 | nu(&ack, "ledger_ack", "authorization")?, |
| 301 | grant.id, |
| 302 | "ledger_ack.authorization", |
| 303 | )?; |
| 304 | eq( |
| 305 | ack.links.contains(&intent.id) && ack.links.contains(&grant.id), |
| 306 | true, |
| 307 | "ledger_ack.links", |
| 308 | )?; |
| 309 | match st(&ack, "ledger_ack", "state")? { |
| 310 | "DONE" => {} |
| 311 | "NOT_DONE" => return unlanded( |
| 312 | "effect_not_done", |
| 313 | "ledger_ack.state=NOT_DONE: the daemon read the world back and the write did not land", |
| 314 | claims_test_run, |
| 315 | ), |
| 316 | "UNRESOLVED" => { |
| 317 | return unlanded( |
| 318 | "effect_unresolved", |
| 319 | "ledger_ack.state=UNRESOLVED: the daemon could not tell whether the write landed", |
| 320 | claims_test_run, |
| 321 | ) |
| 322 | } |
| 323 | other => return fail("binding_mismatch", format!("ledger_ack.state={other}")), |
| 324 | } |
| 325 | eq( |
| 326 | st(&ack, "ledger_ack", "content_sha256")?, |
| 327 | g("content_sha256")?, |
| 328 | "ledger_ack.content_sha256", |
| 329 | )?; |
| 330 | eq( |
| 331 | st(&ack, "ledger_ack", "disk_sha256")?, |
| 332 | g("content_sha256")?, |
| 333 | "ledger_ack.disk_sha256", |
| 334 | )?; |
| 335 | |
| 336 | // The daemon process that wrote the claim is the process the run harness started, and that |
| 337 | // process is the executable named in the AIEN link. |
| 338 | let Some(run) = a.json(DAEMON_RUN)? else { |
| 339 | return fail("missing_record", format!("{DAEMON_RUN} (not retained)")); |
| 340 | }; |
| 341 | if s(&run, &["kind"]) != Some("aien-daemon-run") { |
| 342 | return fail("binding_mismatch", "daemon_run.kind"); |
| 343 | } |
| 344 | let exec = &claim.text["executor"]; |
| 345 | eq( |
| 346 | exec.get("pid").and_then(Value::as_u64), |
| 347 | run.get("pid").and_then(Value::as_u64), |
| 348 | "ledger_claim.executor.pid vs daemon_run.pid", |
| 349 | )?; |
| 350 | eq( |
| 351 | exec.get("start").and_then(Value::as_u64), |
| 352 | run.get("start_ticks").and_then(Value::as_u64), |
| 353 | "ledger_claim.executor.start vs daemon_run.start_ticks", |
| 354 | )?; |
| 355 | if run.get("pid").and_then(Value::as_u64).is_none() { |
| 356 | return fail("binding_mismatch", "daemon_run.pid"); |
| 357 | } |
| 358 | eq( |
| 359 | s(&run, &["workspace"]), |
| 360 | Some(g("workspace")?), |
| 361 | "daemon_run.workspace vs ledger_grant.workspace", |
| 362 | )?; |
| 363 | eq( |
| 364 | s(&run, &["executable_sha256"]), |
| 365 | s(aien, &["executable_sha256"]), |
| 366 | "daemon_run.executable_sha256 vs aien.executable_sha256", |
| 367 | )?; |
| 368 | if let Some(log) = a.bytes("aien_load_log")? { |
| 369 | let text = String::from_utf8_lossy(log); |
| 370 | let sock = text |
| 371 | .lines() |
| 372 | .find_map(|l| l.split_once("Binding socket at ")) |
| 373 | .map(|(_, p)| p.trim()); |
| 374 | eq( |
| 375 | sock, |
| 376 | s(&run, &["socket"]), |
| 377 | "aien_load.socket vs daemon_run.socket", |
| 378 | )?; |
| 379 | } |
| 380 | |
| 381 | // The INTERPLANE call: same file, same bytes, same result ids. |
| 382 | if let Some(c) = call { |
| 383 | check_call(c, &grant, &intent, &ack, &bound)?; |
| 384 | } |
| 385 | Ok(()) |
| 386 | } |
| 387 | |
| 388 | fn check_call( |
| 389 | c: &Call, |
| 390 | grant: &View, |
| 391 | intent: &View, |
| 392 | ack: &View, |
| 393 | b: &ApprovalFields<'_>, |
| 394 | ) -> Result<(), Fail> { |
| 395 | let rid = b.request_id; |
| 396 | eq( |
| 397 | c.tool.as_str(), |
| 398 | "write_file", |
| 399 | &format!("interplane.tool request={rid}"), |
| 400 | )?; |
| 401 | let (Some(path), Some(content)) = (s(&c.args, &["path"]), s(&c.args, &["content"])) else { |
| 402 | return fail( |
| 403 | "binding_mismatch", |
| 404 | format!("interplane.arguments path/content request={rid}"), |
| 405 | ); |
| 406 | }; |
| 407 | eq( |
| 408 | path, |
| 409 | b.path, |
| 410 | &format!("interplane.arguments.path request={rid}"), |
| 411 | )?; |
| 412 | eq( |
| 413 | sha256_hex(content.as_bytes()).as_str(), |
| 414 | b.content_sha256, |
| 415 | &format!("interplane.arguments.content request={rid}"), |
| 416 | )?; |
| 417 | eq( |
| 418 | sha256_hex(&approved_proposal_bytes(path, content)).as_str(), |
| 419 | b.approved_proposal_sha256, |
| 420 | &format!("interplane.arguments approved_proposal_sha256 request={rid}"), |
| 421 | )?; |
| 422 | eq( |
| 423 | sha256_hex(&compose_proposal_bytes(path, content)).as_str(), |
| 424 | st(grant, "ledger_grant", "proposal_sha256")?, |
| 425 | &format!("interplane.arguments compose_proposal_sha256 request={rid}"), |
| 426 | )?; |
| 427 | eq( |
| 428 | s(&c.result, &["status"]), |
| 429 | Some("ok"), |
| 430 | &format!("interplane.result.status request={rid}"), |
| 431 | )?; |
| 432 | let rc = &c.result["data"]["receipt"]; |
| 433 | let want = [ |
| 434 | ("grant_id", Value::from(grant.id)), |
| 435 | ("intent_id", Value::from(intent.id)), |
| 436 | ("ack_record_id", Value::from(ack.id)), |
| 437 | ("grant_digest", Value::from(grant.digest.as_str())), |
| 438 | ("intent_digest", Value::from(intent.digest.as_str())), |
| 439 | ("ack_digest", Value::from(ack.digest.as_str())), |
| 440 | ("state", Value::from("DONE")), |
| 441 | ("request_id", Value::from(b.request_id)), |
| 442 | ("trace_id", Value::from(b.trace_id)), |
| 443 | ]; |
| 444 | for (k, v) in want { |
| 445 | if rc.get(k) != Some(&v) { |
| 446 | return fail( |
| 447 | "binding_mismatch", |
| 448 | format!("interplane.result.data.receipt.{k} request={rid}"), |
| 449 | ); |
| 450 | } |
| 451 | } |
| 452 | Ok(()) |
| 453 | } |
| 454 | |
| 455 | /// What the daemon's own records say about the written file, for the `vac-test-run/1` checks. |
| 456 | pub struct Facts { |
| 457 | pub path: String, |
| 458 | /// The file's digest before the write (`null` in the grant means a new file). |
| 459 | pub prior_sha256: Option<String>, |
| 460 | pub content_sha256: String, |
| 461 | /// The ack's `disk_sha256`: the daemon read the file back after the write. |
| 462 | pub disk_sha256: String, |
| 463 | } |
| 464 | |
| 465 | /// Read the grant and ack facts. Only meaningful after [`check`] passed. |
| 466 | pub fn facts(a: &Archive) -> Result<Facts, Fail> { |
| 467 | let grant = view(a, "ledger_grant", "authorization")?; |
| 468 | let ack = view(a, "ledger_ack", "effect")?; |
| 469 | Ok(Facts { |
| 470 | path: st(&grant, "ledger_grant", "path")?.to_string(), |
| 471 | prior_sha256: grant |
| 472 | .text |
| 473 | .get("prior_sha256") |
| 474 | .and_then(Value::as_str) |
| 475 | .map(str::to_string), |
| 476 | content_sha256: st(&grant, "ledger_grant", "content_sha256")?.to_string(), |
| 477 | disk_sha256: st(&ack, "ledger_ack", "disk_sha256")?.to_string(), |
| 478 | }) |
| 479 | } |
| 480 | |
| 481 | /// An effect the daemon's own ledger does not show as landed. The code names which of the three |
| 482 | /// cases it is. A bundle that also carries a test run is refused as `test_run_on_unlanded_effect` |
| 483 | /// instead: a test cannot certify a write that did not land, and the state is in the detail. |
| 484 | fn unlanded<T>(code: &str, detail: &str, claims_test_run: bool) -> Result<T, Fail> { |
| 485 | if claims_test_run { |
| 486 | return fail("test_run_on_unlanded_effect", format!("{code}: {detail}")); |
| 487 | } |
| 488 | fail(code, detail) |
| 489 | } |