interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / adapters / aien / src / provenance_export.rs
| 1 | //! Export of one live adapter run as a provenance bundle (`provenance/` verifier input). |
| 2 | //! |
| 3 | //! After a live row against a real `aien-cli daemon`, [`export_bundle`] writes a directory that |
| 4 | //! `cd provenance && cargo run -q --locked -- verify <dir>` can judge: the daemon's own |
| 5 | //! `ComposeRecall` views of the claim, the settlement, the grant, the intent and the ack (raw, |
| 6 | //! unchanged), a `daemon-run.json` the harness writes from `/proc`, the daemon's load log, the |
| 7 | //! INTERPLANE trace of this run, the model files the daemon loaded (hard link, or copy), and a |
| 8 | //! `COMPANION.json` naming each by path, size and SHA-256. |
| 9 | //! |
| 10 | //! Fix-the-test slice: with [`LiveRun::slice`] the bundle also carries the harness's task, source pin |
| 11 | //! and test-run records (`vac-test-run/1`, see `crate::fix_the_test`). |
| 12 | //! |
| 13 | //! Honest labels, nothing invented: the proposal here is a SCRIPTED turn (the test wrote the tool |
| 14 | //! call), so the manifest says `proposal_origin: scripted_turn` and the verdict can never be |
| 15 | //! `PASS complete`; it is `PASS_LABELLED_INCOMPLETE missing=link:model_turn`. The model's training |
| 16 | //! history is unknown (`lineage.kind = unknown_pretraining`, with the origin the caller names). |
| 17 | //! No record is signed; the verifier cannot tell an export from a hand-written file (see |
| 18 | //! `provenance/BINDING.md`, Trust). This module reads the daemon and writes files; it grants and |
| 19 | //! decides nothing. |
| 20 | use crate::compose_ledger::LedgerClient; |
| 21 | use serde_json::{json, Map, Value}; |
| 22 | use sha2::{Digest, Sha256}; |
| 23 | use std::path::{Path, PathBuf}; |
| 24 | |
| 25 | /// What the exporter needs to know about the finished run. |
| 26 | pub struct LiveRun<'a> { |
| 27 | /// Bundle directory; created, and refused when it already holds a `COMPANION.json`. |
| 28 | pub out: &'a Path, |
| 29 | pub client: &'a LedgerClient, |
| 30 | /// The `aien-cli` binary the daemon was started from. |
| 31 | pub aien_bin: &'a Path, |
| 32 | /// Process id of that daemon (the harness spawned it). |
| 33 | pub daemon_pid: u32, |
| 34 | /// The daemon's stdout log (contains the model load line and the socket line). |
| 35 | pub daemon_log: &'a Path, |
| 36 | pub socket: &'a Path, |
| 37 | pub workspace: &'a Path, |
| 38 | /// Directory holding `model.safetensors`, `tokenizer.json` and `config.json`. |
| 39 | pub model_dir: &'a Path, |
| 40 | /// Where the weights came from (`model_id`, `revision`), restated and not judged. |
| 41 | pub model_origin: (&'a str, &'a str), |
| 42 | /// The label on the scripted "model" in the trace. |
| 43 | pub model_label: &'a str, |
| 44 | pub trace_id: &'a str, |
| 45 | /// `serde_json::to_value` of the pipeline's intent, of its `requires_approval` result and of |
| 46 | /// the final result of the approved continuation. |
| 47 | pub intent: &'a Value, |
| 48 | pub pending: &'a Value, |
| 49 | pub final_result: &'a Value, |
| 50 | /// RFC 3339 times of the request and of completion (see [`rfc3339_utc`]). |
| 51 | pub t_request: &'a str, |
| 52 | pub t_done: &'a str, |
| 53 | /// The fix-the-test slice: task, source pin and test-run records (harness evidence). |
| 54 | pub slice: Option<&'a crate::fix_the_test::TestRunEvidence>, |
| 55 | /// The M5 slice: the independent judge's signed receipt and the policy it ran under, as the |
| 56 | /// exact bytes the judge wrote and the operator pinned (never re-serialized). |
| 57 | pub evaluation: Option<&'a Evaluation>, |
| 58 | /// A real model turn: the daemon generated the proposal on the model it loaded. When set the |
| 59 | /// bundle says `proposal_origin: model_generation/2` and retains the request, the response and |
| 60 | /// the daemon's own generation record; the `model_label` is the id the trace names as sender. |
| 61 | pub model_turn: Option<&'a ModelTurnRun>, |
| 62 | } |
| 63 | |
| 64 | /// One real model turn as the harness saw it (see `LedgerClient::stream_turn`). All bytes are kept |
| 65 | /// exactly: `request` is the JSON `messages` array sent to the daemon, `response` the text it |
| 66 | /// returned. |
| 67 | #[derive(Debug, Clone)] |
| 68 | pub struct ModelTurnRun { |
| 69 | pub request: Vec<u8>, |
| 70 | pub response: String, |
| 71 | pub generation_record: u64, |
| 72 | pub total_tokens: u64, |
| 73 | pub max_tokens: u64, |
| 74 | pub temperature: f64, |
| 75 | pub started_at: String, |
| 76 | pub finished_at: String, |
| 77 | } |
| 78 | |
| 79 | /// The judge's evidence for one change (`rsi-eval/2`, spark-rsi docs/RECEIPT-V2.md). |
| 80 | #[derive(Debug, Clone)] |
| 81 | pub struct Evaluation { |
| 82 | pub receipt: Vec<u8>, |
| 83 | pub policy: Vec<u8>, |
| 84 | } |
| 85 | |
| 86 | /// What was written. |
| 87 | #[derive(Debug)] |
| 88 | pub struct ExportReport { |
| 89 | pub dir: PathBuf, |
| 90 | pub request_id: String, |
| 91 | pub claim: u64, |
| 92 | pub ack: u64, |
| 93 | pub executable_sha256: String, |
| 94 | pub model_hardlinked: bool, |
| 95 | } |
| 96 | |
| 97 | pub fn sha256_hex(b: &[u8]) -> String { |
| 98 | format!("{:x}", Sha256::digest(b)) |
| 99 | } |
| 100 | |
| 101 | fn sha256_file(p: &Path) -> Result<String, String> { |
| 102 | use std::io::Read; |
| 103 | let mut f = std::fs::File::open(p).map_err(|e| format!("{}: {e}", p.display()))?; |
| 104 | let (mut h, mut buf) = (Sha256::new(), vec![0u8; 1 << 20]); |
| 105 | loop { |
| 106 | let n = f.read(&mut buf).map_err(|e| e.to_string())?; |
| 107 | if n == 0 { |
| 108 | break; |
| 109 | } |
| 110 | h.update(&buf[..n]); |
| 111 | } |
| 112 | Ok(format!("{:x}", h.finalize())) |
| 113 | } |
| 114 | |
| 115 | /// `YYYY-MM-DDTHH:MM:SSZ` for a Unix time in seconds (proleptic Gregorian, UTC). |
| 116 | pub fn rfc3339_utc(secs: u64) -> String { |
| 117 | let (days, rem) = (secs / 86_400, secs % 86_400); |
| 118 | let z = days as i64 + 719_468; |
| 119 | let era = z.div_euclid(146_097); |
| 120 | let doe = z.rem_euclid(146_097); |
| 121 | let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; |
| 122 | let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); |
| 123 | let mp = (5 * doy + 2) / 153; |
| 124 | let d = doy - (153 * mp + 2) / 5 + 1; |
| 125 | let m = if mp < 10 { mp + 3 } else { mp - 9 }; |
| 126 | let y = yoe + era * 400 + i64::from(m <= 2); |
| 127 | format!( |
| 128 | "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", |
| 129 | rem / 3600, |
| 130 | rem % 3600 / 60, |
| 131 | rem % 60 |
| 132 | ) |
| 133 | } |
| 134 | |
| 135 | /// Now, as RFC 3339 UTC. |
| 136 | pub fn now_rfc3339() -> String { |
| 137 | let s = std::time::SystemTime::now() |
| 138 | .duration_since(std::time::UNIX_EPOCH) |
| 139 | .map(|d| d.as_secs()) |
| 140 | .unwrap_or(0); |
| 141 | rfc3339_utc(s) |
| 142 | } |
| 143 | |
| 144 | /// Field 22 of `/proc/<pid>/stat` (start time in clock ticks since boot), the same identity the |
| 145 | /// daemon writes into its replay claim as `executor.start`. |
| 146 | pub fn proc_start_ticks(pid: u32) -> Result<u64, String> { |
| 147 | let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).map_err(|e| e.to_string())?; |
| 148 | // `comm` may hold spaces and parentheses: split after the LAST ')'. |
| 149 | let rest = stat.rsplit_once(')').ok_or("stat: no ')'")?.1; |
| 150 | rest.split_whitespace() |
| 151 | .nth(19) |
| 152 | .and_then(|x| x.parse().ok()) |
| 153 | .ok_or_else(|| "stat: no start time".into()) |
| 154 | } |
| 155 | |
| 156 | fn write(dir: &Path, rel: &str, bytes: &[u8]) -> Result<(), String> { |
| 157 | let p = dir.join(rel); |
| 158 | std::fs::create_dir_all(p.parent().ok_or("no parent")?).map_err(|e| e.to_string())?; |
| 159 | std::fs::write(&p, bytes).map_err(|e| format!("{}: {e}", p.display())) |
| 160 | } |
| 161 | |
| 162 | /// Write a record file and list it in the manifest by path, digest and size. |
| 163 | fn put( |
| 164 | dir: &Path, |
| 165 | records: &mut Map<String, Value>, |
| 166 | name: &str, |
| 167 | rel: &str, |
| 168 | bytes: Vec<u8>, |
| 169 | ) -> Result<(), String> { |
| 170 | write(dir, rel, &bytes)?; |
| 171 | records.insert( |
| 172 | name.into(), |
| 173 | json!({"path": rel, "sha256": sha256_hex(&bytes), "bytes": bytes.len()}), |
| 174 | ); |
| 175 | Ok(()) |
| 176 | } |
| 177 | |
| 178 | fn pretty(v: &Value) -> Vec<u8> { |
| 179 | serde_json::to_vec_pretty(v).unwrap_or_default() |
| 180 | } |
| 181 | |
| 182 | /// The raw `ComposeRecall` view (`cited[]`) of one record id. |
| 183 | fn view(cited: &[Value], id: u64) -> Result<Value, String> { |
| 184 | cited |
| 185 | .iter() |
| 186 | .find(|v| v["id"].as_u64() == Some(id)) |
| 187 | .cloned() |
| 188 | .ok_or_else(|| format!("record {id} not returned by ComposeRecall")) |
| 189 | } |
| 190 | |
| 191 | fn text_of(v: &Value) -> Value { |
| 192 | v["text"] |
| 193 | .as_str() |
| 194 | .and_then(|t| serde_json::from_str(t).ok()) |
| 195 | .unwrap_or(Value::Null) |
| 196 | } |
| 197 | |
| 198 | /// Write the bundle and return what it holds. Errors say what was missing; nothing is guessed. |
| 199 | pub fn export_bundle(run: &LiveRun<'_>) -> Result<ExportReport, String> { |
| 200 | if run.out.join("COMPANION.json").exists() { |
| 201 | return Err(format!( |
| 202 | "{} already holds a COMPANION.json (a sealed record is never rewritten)", |
| 203 | run.out.display() |
| 204 | )); |
| 205 | } |
| 206 | std::fs::create_dir_all(run.out).map_err(|e| e.to_string())?; |
| 207 | let rc = &run.final_result["data"]["receipt"]; |
| 208 | let id_of = |k: &str| { |
| 209 | rc[k] |
| 210 | .as_u64() |
| 211 | .or_else(|| rc["handoff"][k].as_u64()) |
| 212 | .ok_or_else(|| format!("receipt has no {k}")) |
| 213 | }; |
| 214 | let (claim, grant, intent, ack) = ( |
| 215 | id_of("replay_claim")?, |
| 216 | id_of("grant_id")?, |
| 217 | id_of("intent_id")?, |
| 218 | id_of("ack_record_id")?, |
| 219 | ); |
| 220 | let request_id = run.final_result["request_id"] |
| 221 | .as_str() |
| 222 | .ok_or("final result has no request_id")? |
| 223 | .to_string(); |
| 224 | |
| 225 | // The daemon's own export command, over the window claim..=ack. |
| 226 | let ids: Vec<u64> = (claim..=ack).collect(); |
| 227 | let recalled = run.client.recall(&ids, None)?; |
| 228 | if !recalled["missing"].as_array().is_some_and(|m| m.is_empty()) { |
| 229 | return Err(format!( |
| 230 | "ComposeRecall missing records: {}", |
| 231 | recalled["missing"] |
| 232 | )); |
| 233 | } |
| 234 | let cited = recalled["cited"] |
| 235 | .as_array() |
| 236 | .ok_or("ComposeRecall: no cited")?; |
| 237 | let committed = cited |
| 238 | .iter() |
| 239 | .find(|v| { |
| 240 | let t = text_of(v); |
| 241 | t["approved_submission"] == "committed" && t["claim"].as_u64() == Some(claim) |
| 242 | }) |
| 243 | .cloned() |
| 244 | .ok_or("no committed settlement record for the claim")?; |
| 245 | |
| 246 | let mut records = Map::new(); |
| 247 | put( |
| 248 | run.out, |
| 249 | &mut records, |
| 250 | "ledger_claim", |
| 251 | "records/aien/ledger-claim.json", |
| 252 | pretty(&view(cited, claim)?), |
| 253 | )?; |
| 254 | put( |
| 255 | run.out, |
| 256 | &mut records, |
| 257 | "ledger_committed", |
| 258 | "records/aien/ledger-committed.json", |
| 259 | pretty(&committed), |
| 260 | )?; |
| 261 | put( |
| 262 | run.out, |
| 263 | &mut records, |
| 264 | "ledger_grant", |
| 265 | "records/aien/ledger-grant.json", |
| 266 | pretty(&view(cited, grant)?), |
| 267 | )?; |
| 268 | put( |
| 269 | run.out, |
| 270 | &mut records, |
| 271 | "ledger_intent", |
| 272 | "records/aien/ledger-intent.json", |
| 273 | pretty(&view(cited, intent)?), |
| 274 | )?; |
| 275 | put( |
| 276 | run.out, |
| 277 | &mut records, |
| 278 | "ledger_ack", |
| 279 | "records/aien/ledger-ack.json", |
| 280 | pretty(&view(cited, ack)?), |
| 281 | )?; |
| 282 | |
| 283 | // The daemon states whether its compose library is native (sovereign-core #346). An older |
| 284 | // daemon returns neither field: then `aien.native` is absent and the verdict says so. |
| 285 | let native = recalled["compose_native"].as_bool().map(|claimed| { |
| 286 | let sha = recalled["omega_sha"].as_str().unwrap_or(""); |
| 287 | json!({"claimed": claimed, "omega_sha": sha}) |
| 288 | }); |
| 289 | if native.is_some() { |
| 290 | put( |
| 291 | run.out, |
| 292 | &mut records, |
| 293 | "compose_recall", |
| 294 | "records/aien/compose-recall.json", |
| 295 | pretty(&recalled), |
| 296 | )?; |
| 297 | } |
| 298 | if let Some(s) = run.slice { |
| 299 | put( |
| 300 | run.out, |
| 301 | &mut records, |
| 302 | "task", |
| 303 | "records/task/task.json", |
| 304 | pretty(&s.task), |
| 305 | )?; |
| 306 | put( |
| 307 | run.out, |
| 308 | &mut records, |
| 309 | "source_pin", |
| 310 | "records/task/source-pin.json", |
| 311 | pretty(&s.source_pin), |
| 312 | )?; |
| 313 | put( |
| 314 | run.out, |
| 315 | &mut records, |
| 316 | "test_run_record", |
| 317 | "records/task/test-run.json", |
| 318 | pretty(&s.test_run), |
| 319 | )?; |
| 320 | put( |
| 321 | run.out, |
| 322 | &mut records, |
| 323 | "test_stdout", |
| 324 | "records/task/test-stdout.txt", |
| 325 | s.stdout.clone(), |
| 326 | )?; |
| 327 | put( |
| 328 | run.out, |
| 329 | &mut records, |
| 330 | "test_stderr", |
| 331 | "records/task/test-stderr.txt", |
| 332 | s.stderr.clone(), |
| 333 | )?; |
| 334 | } |
| 335 | if let Some(ev) = run.evaluation { |
| 336 | put( |
| 337 | run.out, |
| 338 | &mut records, |
| 339 | "evaluation_receipt", |
| 340 | "records/evaluation/receipt.json", |
| 341 | ev.receipt.clone(), |
| 342 | )?; |
| 343 | put( |
| 344 | run.out, |
| 345 | &mut records, |
| 346 | "evaluation_policy", |
| 347 | "records/evaluation/policy.json", |
| 348 | ev.policy.clone(), |
| 349 | )?; |
| 350 | } |
| 351 | let exe_sha = sha256_file(run.aien_bin)?; |
| 352 | let boot_id = std::fs::read_to_string("/proc/sys/kernel/random/boot_id") |
| 353 | .map(|s| s.trim().to_string()) |
| 354 | .unwrap_or_default(); |
| 355 | let daemon_run = json!({"kind": "aien-daemon-run", "pid": run.daemon_pid, |
| 356 | "start_ticks": proc_start_ticks(run.daemon_pid)?, |
| 357 | "socket": run.socket.to_str().ok_or("socket path")?, |
| 358 | "workspace": run.workspace.to_str().ok_or("workspace path")?, |
| 359 | "executable_sha256": exe_sha, "boot_id": boot_id, |
| 360 | "note": "written by the run harness from /proc/<pid>/stat and the spawned child pid, not by the daemon"}); |
| 361 | put( |
| 362 | run.out, |
| 363 | &mut records, |
| 364 | "daemon_run", |
| 365 | "records/aien/daemon-run.json", |
| 366 | pretty(&daemon_run), |
| 367 | )?; |
| 368 | put( |
| 369 | run.out, |
| 370 | &mut records, |
| 371 | "aien_load_log", |
| 372 | "records/aien/daemon-load.log", |
| 373 | std::fs::read(run.daemon_log).map_err(|e| format!("daemon log: {e}"))?, |
| 374 | )?; |
| 375 | |
| 376 | // The trace: the request the pipeline admitted, its requires_approval result, the final result. |
| 377 | let env = |
| 378 | |n: u32, parent: Option<&str>, src: (&str, &str), dst: (&str, &str), t: &str, p: &Value| { |
| 379 | let mut e = json!({"interplane_version": "0.1", "message_id": format!("m-{n}"), |
| 380 | "trace_id": run.trace_id, "timestamp": t, |
| 381 | "source": {"kind": src.0, "id": src.1}, "destination": {"kind": dst.0, "id": dst.1}, |
| 382 | "payload": p}); |
| 383 | if let Some(pp) = parent { |
| 384 | e["parent_id"] = json!(pp); |
| 385 | } |
| 386 | e |
| 387 | }; |
| 388 | let model = ("model", run.model_label); |
| 389 | let trace = json!([ |
| 390 | env( |
| 391 | 1, |
| 392 | None, |
| 393 | model, |
| 394 | ("runtime", "aien"), |
| 395 | run.t_request, |
| 396 | run.intent |
| 397 | ), |
| 398 | env( |
| 399 | 2, |
| 400 | Some("m-1"), |
| 401 | ("runtime", "aien"), |
| 402 | model, |
| 403 | run.t_request, |
| 404 | run.pending |
| 405 | ), |
| 406 | env( |
| 407 | 3, |
| 408 | Some("m-1"), |
| 409 | ("runtime", "aien"), |
| 410 | model, |
| 411 | run.t_done, |
| 412 | run.final_result |
| 413 | ), |
| 414 | ]); |
| 415 | for e in trace.as_array().into_iter().flatten() { |
| 416 | interplane_core::validate_envelope_value(e) |
| 417 | .map_err(|c| format!("trace envelope invalid {c:?}"))?; |
| 418 | } |
| 419 | put( |
| 420 | run.out, |
| 421 | &mut records, |
| 422 | "interplane_trace", |
| 423 | "records/interplane/trace.json", |
| 424 | pretty(&trace), |
| 425 | )?; |
| 426 | |
| 427 | // The model files the daemon loaded: hard link when on one filesystem, else a copy. |
| 428 | let mut hardlinked = true; |
| 429 | for (name, file) in [ |
| 430 | ("export_weights", "model.safetensors"), |
| 431 | ("export_tokenizer", "tokenizer.json"), |
| 432 | ("export_config", "config.json"), |
| 433 | ] { |
| 434 | let src = std::fs::canonicalize(run.model_dir.join(file)) |
| 435 | .map_err(|e| format!("{}: {e}", run.model_dir.join(file).display()))?; |
| 436 | let rel = format!("records/export/{file}"); |
| 437 | let dst = run.out.join(&rel); |
| 438 | std::fs::create_dir_all(dst.parent().ok_or("no parent")?).map_err(|e| e.to_string())?; |
| 439 | let _ = std::fs::remove_file(&dst); |
| 440 | if std::fs::hard_link(&src, &dst).is_err() { |
| 441 | hardlinked = false; |
| 442 | std::fs::copy(&src, &dst).map_err(|e| format!("copy {}: {e}", src.display()))?; |
| 443 | } |
| 444 | records.insert( |
| 445 | name.into(), |
| 446 | json!({"path": rel, "sha256": sha256_file(&dst)?, |
| 447 | "bytes": std::fs::metadata(&dst).map_err(|e| e.to_string())?.len()}), |
| 448 | ); |
| 449 | } |
| 450 | |
| 451 | // A real model turn: the request and response bytes, the daemon's own record of the |
| 452 | // generation (exported with its own read command) and a model-turn/2 record that names the |
| 453 | // digests that tie them to the weights and to the trace. |
| 454 | if let Some(t) = run.model_turn { |
| 455 | let log_text = std::fs::read_to_string(run.daemon_log).unwrap_or_default(); |
| 456 | let backend_line = log_text |
| 457 | .lines() |
| 458 | .find(|l| l.contains("Backend:")) |
| 459 | .map(|l| l.trim().to_string()) |
| 460 | .ok_or("the daemon log names no Backend: line; the turn's backend would be a guess")?; |
| 461 | let gview = run.client.recall(&[t.generation_record], None)?; |
| 462 | if !gview["missing"].as_array().is_some_and(|m| m.is_empty()) { |
| 463 | return Err(format!( |
| 464 | "ComposeRecall has no generation record {}: {}", |
| 465 | t.generation_record, gview["missing"] |
| 466 | )); |
| 467 | } |
| 468 | let gcited = gview["cited"].as_array().ok_or("ComposeRecall: no cited")?; |
| 469 | put( |
| 470 | run.out, |
| 471 | &mut records, |
| 472 | "ledger_generation", |
| 473 | "records/aien/ledger-generation.json", |
| 474 | pretty(&view(gcited, t.generation_record)?), |
| 475 | )?; |
| 476 | put( |
| 477 | run.out, |
| 478 | &mut records, |
| 479 | "model_request", |
| 480 | "records/model/request.json", |
| 481 | t.request.clone(), |
| 482 | )?; |
| 483 | let weights = records["export_weights"]["sha256"] |
| 484 | .as_str() |
| 485 | .ok_or("export_weights not recorded")? |
| 486 | .to_string(); |
| 487 | let turn = json!({"record": "model-turn/2", "dialect": "aien_legacy", |
| 488 | "model": run.model_label, "model_id": run.model_origin.0, |
| 489 | "trace_id": run.trace_id, "turn": 0, |
| 490 | "input": t.response, |
| 491 | "generation_record_id": t.generation_record, |
| 492 | "generation_record_source": "TurnFinished.generation_record", |
| 493 | "request_record": "model_request", |
| 494 | "request_sha256": sha256_hex(&t.request), |
| 495 | "response_sha256": sha256_hex(t.response.as_bytes()), |
| 496 | "weights_sha256": weights, |
| 497 | "backend": backend_line, |
| 498 | "sampling": {"max_tokens": t.max_tokens, "temperature": t.temperature, |
| 499 | "total_tokens": t.total_tokens}, |
| 500 | "stream_started": t.started_at, "stream_finished": t.finished_at}); |
| 501 | put( |
| 502 | run.out, |
| 503 | &mut records, |
| 504 | "model_turn", |
| 505 | "records/interplane/model-turn.json", |
| 506 | pretty(&turn), |
| 507 | )?; |
| 508 | } |
| 509 | |
| 510 | let mut missing: Vec<&str> = if run.model_turn.is_some() { |
| 511 | vec![] |
| 512 | } else { |
| 513 | vec!["link:model_turn"] |
| 514 | }; |
| 515 | if run.slice.is_some() && native.as_ref().is_none_or(|n| n["claimed"] != true) { |
| 516 | missing.push("link:native"); |
| 517 | } |
| 518 | let (origin, fixture_note, reason) = if run.model_turn.is_some() { |
| 519 | ("model_generation/2", |
| 520 | "Real daemon; the ledger records are the daemon's own ComposeRecall output (pretty-printed only); daemon_run.json and the 3-message trace are written by the test harness, including their timestamps. The model turn is REAL: the daemon generated the tool-call text (StreamTurn) and wrote its own generation record; the request bytes and timestamps are the harness's.", |
| 521 | "the proposal text was generated by the model this daemon loaded; the daemon's own generation record, the request and response bytes, the weights digest and the parsed request all chain to the effect") |
| 522 | } else { |
| 523 | ("scripted_turn", |
| 524 | "Real daemon; the five ledger records are the daemon's own ComposeRecall output (pretty-printed only); daemon_run.json and the 3-message trace are written by the test harness, including their timestamps. The model turn is SCRIPTED by the test (the tool call is a test constant), so authorship of the proposal is not claimed; the model only loaded.", |
| 525 | "the INTERPLANE model turn is scripted by the test: nothing links this model to the effect's content") |
| 526 | }; |
| 527 | let mut companion = json!({ |
| 528 | "kind": "interplane-provenance-companion", "schema": 0, |
| 529 | "fixture": {"class": "real", "note": fixture_note}, |
| 530 | "lineage": {"kind": "unknown_pretraining", |
| 531 | "origin": {"model_id": run.model_origin.0, "model_id_source": "caller-asserted (AIEN_LEDGER_MODEL_ID or default; not checked against the model directory)", "revision": run.model_origin.1, |
| 532 | "note": "weights as downloaded; no training evidence is held"}}, |
| 533 | "export": {"format": "huggingface", "chat_template": Value::Null}, |
| 534 | "load_support": {"declared": "supported_structural"}, |
| 535 | "aien": {"candidate_id": Value::Null, "executable": "aien-cli", "executable_sha256": exe_sha, |
| 536 | "note": "no frozen AIEN candidate: no candidate_manifest record; CPU-reference backend as printed in the daemon log; whether the compose library was native-linked is reported only when the daemon returns compose_native (sovereign-core #346); aien.native then names it"}, |
| 537 | "interplane": {"trace_id": run.trace_id, "request_id": request_id}, |
| 538 | "effect": {"binding": "aien-ledger-slice/1", "approval_binding": "aien.approval.v2", |
| 539 | "proposal_origin": origin}, |
| 540 | "completeness": {"state": if missing.is_empty() { "complete" } else { "incomplete" }, "missing": missing, |
| 541 | "reason": reason}, |
| 542 | "records": Value::Object(records), |
| 543 | }); |
| 544 | if let Some(n) = native { |
| 545 | companion["aien"]["native"] = n; |
| 546 | } |
| 547 | if let Some(s) = run.slice { |
| 548 | companion["test_run"] = json!({"binding": "vac-test-run/1", "task_id": s.task_id, |
| 549 | "record": "test_run_record"}); |
| 550 | } |
| 551 | if run.evaluation.is_some() { |
| 552 | companion["evaluation"] = json!({"binding": "rsi-eval/2", |
| 553 | "receipt": "evaluation_receipt", "policy": "evaluation_policy", |
| 554 | "note": if run.model_turn.is_some() { "the change was proposed by the model turn and evaluated by the separate judge process; the judge's public key is supplied to the verifier out of band" } else { "the change was proposed by spark-rsi and evaluated by the separate judge process; the judge's public key is supplied to the verifier out of band" }}); |
| 555 | } |
| 556 | write(run.out, "COMPANION.json", &pretty(&companion))?; |
| 557 | Ok(ExportReport { |
| 558 | dir: run.out.to_path_buf(), |
| 559 | request_id, |
| 560 | claim, |
| 561 | ack, |
| 562 | executable_sha256: exe_sha, |
| 563 | model_hardlinked: hardlinked, |
| 564 | }) |
| 565 | } |
| 566 | |
| 567 | #[cfg(test)] |
| 568 | mod tests { |
| 569 | use super::*; |
| 570 | |
| 571 | #[test] |
| 572 | fn rfc3339_known_instants() { |
| 573 | assert_eq!(rfc3339_utc(0), "1970-01-01T00:00:00Z"); |
| 574 | assert_eq!(rfc3339_utc(951_782_400), "2000-02-29T00:00:00Z"); |
| 575 | assert_eq!(rfc3339_utc(1_791_417_600), "2026-10-08T00:00:00Z"); |
| 576 | } |
| 577 | |
| 578 | #[test] |
| 579 | fn own_start_ticks_are_readable() { |
| 580 | assert!(proc_start_ticks(std::process::id()).unwrap() > 0); |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn refuses_to_overwrite_a_sealed_bundle() { |
| 585 | let d = tempfile::tempdir().unwrap(); |
| 586 | std::fs::write(d.path().join("COMPANION.json"), b"{}").unwrap(); |
| 587 | let c = LedgerClient::new(d.path().join("none.sock")); |
| 588 | let v = json!(null); |
| 589 | let r = export_bundle(&LiveRun { |
| 590 | out: d.path(), |
| 591 | client: &c, |
| 592 | aien_bin: Path::new("/nonexistent"), |
| 593 | daemon_pid: 1, |
| 594 | daemon_log: Path::new("/nonexistent"), |
| 595 | socket: Path::new("/x"), |
| 596 | workspace: Path::new("/x"), |
| 597 | model_dir: Path::new("/x"), |
| 598 | model_origin: ("m", "r"), |
| 599 | model_label: "m", |
| 600 | trace_id: "t", |
| 601 | intent: &v, |
| 602 | pending: &v, |
| 603 | final_result: &v, |
| 604 | t_request: "t", |
| 605 | t_done: "t", |
| 606 | slice: None, |
| 607 | evaluation: None, |
| 608 | model_turn: None, |
| 609 | }); |
| 610 | assert!(r.unwrap_err().contains("never rewritten")); |
| 611 | } |
| 612 | } |