interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / provenance / src / synth.rs

627 lines · 28095 bytes Raw Blame History
1//! Synthetic full-chain fixture generator and the record sealer.
2//!
3//! SYNTHETIC: every byte written by `write_synthetic` is made up here. The WALDO records follow
4//! the documented schema-1 shapes (docs/OPENWALDO-BOM.md, docs/MODEL-EXPORTS.md and
5//! internal/model/records.go at openwaldo/waldo 0fd421a) but carry only the fields this verifier
6//! reads plus a few for orientation. One deliberate deviation, labelled in the manifest: the
7//! export carries a Hugging Face `tokenizer.json`, which a real WALDO Hugging Face export does not
8//! (it ships `tokenizer_config.json` plus custom tokenizer code; see the real fixture).
9
10use crate::binding::{
11 approval_binding_bytes, approved_proposal_bytes, compact_sorted, compose_proposal_bytes,
12 ApprovalFields, APPROVAL_BINDING, LEDGER_BINDING, RECEIPT_BINDING, SERDE_DIGEST_FORM,
13};
14use crate::gojson::{sha256_hex, waldo_sha256};
15use crate::COMPANION_FILE;
16use serde_json::{json, Value};
17use std::path::Path;
18
19pub const TRACE_ID: &str = "trace-prov-01";
20pub const REQUEST_ID: &str = "call-prov-01";
21pub const OTHER_REQUEST_ID: &str = "call-prov-02";
22/// Same tool, arguments and result data as `REQUEST_ID`, in the same trace.
23pub const IDENTICAL_REQUEST_ID: &str = "call-prov-03";
24pub const WORKSPACE: &str = "/synthetic/workspace";
25pub const DAEMON_PID: u64 = 4242;
26pub const DAEMON_START_TICKS: u64 = 777_000;
27const RUN_ID: &str = "5e7a0c1d2b3f4a59";
28const CAND: &str = "CAND-SYNTH-0";
29const EXE: &str = "aien-cli-native-release";
30
31/// Knobs for negative fixtures that must stay internally consistent (all digests recomputed).
32#[derive(Default, Clone)]
33pub struct Opts {
34 /// Write this `vocab_size` into config.json instead of the tokenizer's real size.
35 pub config_vocab: Option<u64>,
36 /// Trace id of the INTERPLANE trace and the ledger (default [`TRACE_ID`]).
37 pub trace_id: Option<String>,
38 /// The request the effect link names (default [`REQUEST_ID`]).
39 pub request_id: Option<String>,
40 /// Write the weaker `record_effect_receipt/1` binding instead of the ledger slice.
41 pub weak: bool,
42 /// Write the fix-the-test slice: a write that replaces `src/clamp.c`, the `vac-test-run/1`
43 /// records and a `compose_recall` report (see [`fix_the_test`]).
44 pub fix_the_test: bool,
45 /// With `fix_the_test`: the native-claim variant of the recall report (default: no `aien.native`).
46 pub native: Option<bool>,
47}
48
49/// Arguments and prior digest of a write that replaces an existing file.
50#[derive(Clone)]
51pub struct Over {
52 pub args: Value,
53 pub prior_sha256: String,
54}
55
56fn pretty(v: &Value) -> Vec<u8> {
57 let mut b = serde_json::to_vec_pretty(v).expect("json");
58 b.push(b'\n');
59 b
60}
61
62fn put(dir: &Path, rel: &str, bytes: &[u8]) -> std::io::Result<()> {
63 let p = dir.join(rel);
64 std::fs::create_dir_all(p.parent().expect("parent"))?;
65 std::fs::write(p, bytes)
66}
67
68fn safetensors(tensor: &str, data: &[u8]) -> Vec<u8> {
69 let header =
70 json!({ tensor: {"dtype": "BF16", "shape": [8, 4], "data_offsets": [0, data.len()]} });
71 let mut h = serde_json::to_vec(&header).expect("json");
72 while !h.len().is_multiple_of(8) {
73 h.push(b' ');
74 }
75 let mut out = (h.len() as u64).to_le_bytes().to_vec();
76 out.extend_from_slice(&h);
77 out.extend_from_slice(data);
78 out
79}
80
81fn artifact(role: &str, path: &str, b: &[u8]) -> Value {
82 json!({"role": role, "path": path, "sha256": sha256_hex(b), "bytes": b.len()})
83}
84
85/// The aien-cli effect receipt shape (`record_effect_receipt`, version 1). Digests use the
86/// producer's form (`serde_json.to_vec.sorted-keys/1`, see binding.rs).
87pub fn receipt_bytes(tool: &str, args: &Value, data: &Value, success: bool) -> Vec<u8> {
88 let d = |v: &Value| {
89 format!(
90 "sha256:{}",
91 sha256_hex(&compact_sorted(v).expect("integers only"))
92 )
93 };
94 serde_json::to_vec_pretty(&json!({
95 "version": 1, "tool": tool, "success": success,
96 "arguments_digest": d(args), "result_digest": d(data),
97 "policy": "default_sovereign_engine", "timestamp": "2026-10-06T00:00:01+00:00"
98 }))
99 .expect("json")
100}
101
102/// Requests 01 and 03 are identical calls; 02 differs.
103pub fn request_args(request_id: &str) -> Value {
104 if request_id == OTHER_REQUEST_ID {
105 json!({"path": "notes/other.md", "content": "note append"})
106 } else {
107 json!({"path": "notes/today.md", "content": "hello world"})
108 }
109}
110
111pub fn result_data(request_id: &str) -> Value {
112 let a = request_args(request_id);
113 json!({"path": a["path"], "bytes_written": a["content"].as_str().unwrap_or("").len()})
114}
115
116/// One Cortex record as `ComposeRecall` exports it (`ComposeRecordView`). SYNTHETIC digest.
117fn record_view(id: u64, links: [u64; 4], note: &str, text: &Value) -> Value {
118 let text = text.to_string();
119 json!({"id": id, "cls": 0, "kind": 0, "subject": 0, "tag": 0, "links": links,
120 "digest": sha256_hex(format!("synthetic-record:{id}:{text}").as_bytes()),
121 "verified": true, "note": note, "text": text})
122}
123
124/// The five daemon-written ledger records of one approved write, SYNTHETIC but built through the
125/// same binding functions the verifier uses. `index` spaces the record ids apart.
126pub fn ledger_slice(trace_id: &str, request_id: &str, index: u64) -> Vec<(&'static str, Value)> {
127 ledger_slice_over(trace_id, request_id, index, None)
128}
129
130/// [`ledger_slice`] for a write that replaces an existing file: `over` names the arguments and the
131/// digest of the bytes the file held before.
132pub fn ledger_slice_over(
133 trace_id: &str,
134 request_id: &str,
135 index: u64,
136 over: Option<&Over>,
137) -> Vec<(&'static str, Value)> {
138 let a = over.map_or_else(|| request_args(request_id), |o| o.args.clone());
139 let prior = over.map_or(Value::Null, |o| json!(o.prior_sha256));
140 let (path, content) = (a["path"].as_str().unwrap(), a["content"].as_str().unwrap());
141 let base = 20 + 10 * index;
142 let (claim, evidence, promotion, committed, grant, intent, ack) = (
143 base,
144 base + 4,
145 base + 5,
146 base + 6,
147 base + 7,
148 base + 8,
149 base + 9,
150 );
151 let content_sha = sha256_hex(content.as_bytes());
152 let approved_sha = sha256_hex(&approved_proposal_bytes(path, content));
153 let compose_sha = sha256_hex(&compose_proposal_bytes(path, content));
154 let approval_id = format!("aien-approval:{request_id}:synthetic");
155 let desk = "0123456789abcdef";
156 let key = sha256_hex(&approval_binding_bytes(&ApprovalFields {
157 approval_id: &approval_id,
158 approved_proposal_sha256: &approved_sha,
159 approver: "drake",
160 content_sha256: &content_sha,
161 desk_key_id: desk,
162 path,
163 request_id,
164 trace_id,
165 workspace: WORKSPACE,
166 }));
167 let target = format!("{WORKSPACE}/{path}");
168 vec![
169 (
170 "ledger_claim",
171 record_view(
172 claim,
173 [0; 4],
174 "effect",
175 &json!({
176 "approved_submission": "accepted", "approval_key": key, "request_id": request_id,
177 "approval_id": approval_id, "trace_id": trace_id,
178 "executor": {"pid": DAEMON_PID, "start": DAEMON_START_TICKS}}),
179 ),
180 ),
181 (
182 "ledger_committed",
183 record_view(
184 committed,
185 [claim, 0, 0, 0],
186 "effect",
187 &json!({
188 "approved_submission": "committed", "claim": claim,
189 "evidence": {"compose_proposal_sha256": compose_sha, "cx_promotion": promotion,
190 "cx_evidence": evidence, "task": 1}}),
191 ),
192 ),
193 (
194 "ledger_grant",
195 record_view(
196 grant,
197 [promotion, evidence, claim, 0],
198 "authorization",
199 &json!({
200 "approved_grant": 1, "proposal_sha256": compose_sha, "path": path,
201 "content_sha256": content_sha, "approver": "drake", "target": target,
202 "workspace": WORKSPACE, "prior_sha256": prior, "approval_key": key,
203 "replay_claim": claim, "cx_promotion": promotion, "cx_evidence": evidence,
204 "request_id": request_id, "trace_id": trace_id, "approval_id": approval_id,
205 "desk_key_id": desk, "approved_proposal_sha256": approved_sha}),
206 ),
207 ),
208 (
209 "ledger_intent",
210 record_view(
211 intent,
212 [grant, 0, 0, 0],
213 "effect",
214 &json!({
215 "phase": "intent", "tool": "write_file", "authorization": grant,
216 "proposal_sha256": compose_sha, "path": path, "target": target,
217 "content_sha256": content_sha, "prior_sha256": prior,
218 "executor": {"pid": 9, "start": 9}}),
219 ),
220 ),
221 (
222 "ledger_ack",
223 record_view(
224 ack,
225 [intent, grant, 0, 0],
226 "effect",
227 &json!({
228 "phase": "ack", "intent": intent, "authorization": grant, "tool": "write_file",
229 "path": path, "content_sha256": content_sha, "state": "DONE",
230 "disk_sha256": content_sha, "disk_error": null}),
231 ),
232 ),
233 ]
234}
235
236/// The adapter's receipt as it appears in the INTERPLANE result (`data.receipt`).
237fn adapter_receipt(trace_id: &str, request_id: &str, index: u64, over: Option<&Over>) -> Value {
238 let s = ledger_slice_over(trace_id, request_id, index, over);
239 let r = |n: &str| {
240 s.iter()
241 .find(|(k, _)| *k == n)
242 .map(|(_, v)| v)
243 .expect("record")
244 };
245 json!({"state": "DONE", "trace_id": trace_id, "request_id": request_id,
246 "grant_id": r("ledger_grant")["id"], "grant_digest": r("ledger_grant")["digest"],
247 "intent_id": r("ledger_intent")["id"], "intent_digest": r("ledger_intent")["digest"],
248 "ack_record_id": r("ledger_ack")["id"], "ack_digest": r("ledger_ack")["digest"]})
249}
250
251fn envelope(
252 trace_id: &str,
253 n: u32,
254 parent: Option<String>,
255 src: (&str, &str),
256 dst: (&str, &str),
257 payload: Value,
258) -> Value {
259 json!({
260 "interplane_version": "0.1", "message_id": format!("m-{n}"), "trace_id": trace_id,
261 "parent_id": parent, "timestamp": format!("2026-10-06T00:00:{n:02}Z"),
262 "source": {"kind": src.0, "id": src.1}, "destination": {"kind": dst.0, "id": dst.1},
263 "payload": payload
264 })
265}
266
267fn args_of(rid: &str, over: Option<&Over>) -> Value {
268 match over.filter(|_| rid == REQUEST_ID) {
269 Some(o) => o.args.clone(),
270 None => request_args(rid),
271 }
272}
273
274/// Three requests in one trace: 01, 02 and 03, where 03 repeats 01 exactly. In ledger mode each
275/// result carries the adapter receipt of its own request.
276fn trace(trace_id: &str, weak: bool, over: Option<&Over>) -> Value {
277 let mut envs = Vec::new();
278 let mut n = 0;
279 for (i, rid) in [REQUEST_ID, OTHER_REQUEST_ID, IDENTICAL_REQUEST_ID]
280 .into_iter()
281 .enumerate()
282 {
283 n += 1;
284 let req = n;
285 envs.push(envelope(
286 trace_id,
287 n,
288 None,
289 ("model", "synthetic-notes"),
290 ("runtime", "aien"),
291 json!({
292 "kind": "tool_request", "request_id": rid,
293 "tool": {"namespace": null, "name": "write_file"},
294 "arguments": args_of(rid, over),
295 "provenance": {"dialect": "openai", "parser_version": "1"}
296 }),
297 ));
298 n += 1;
299 let mut data = match over.filter(|_| rid == REQUEST_ID) {
300 Some(o) => {
301 json!({"path": o.args["path"], "bytes_written": o.args["content"].as_str().unwrap_or("").len()})
302 }
303 None => result_data(rid),
304 };
305 if !weak {
306 data["receipt"] =
307 adapter_receipt(trace_id, rid, i as u64, over.filter(|_| rid == REQUEST_ID));
308 }
309 envs.push(envelope(trace_id, n, Some(format!("m-{req}")), ("runtime", "aien"), ("model", "synthetic-notes"), json!({
310 "kind": "result", "request_id": rid, "status": "ok", "data": data,
311 "error": null, "decision": null,
312 "provenance": {"capability": "write_file", "content_kind": "tool_result", "duration_ms": null,
313 "runtime": "aien", "trust": "trusted_runtime", "trusted": true}
314 })));
315 }
316 Value::Array(envs)
317}
318
319/// Write the synthetic full-chain archive (records + sealed COMPANION.json) into `dir`.
320pub fn write_synthetic(dir: &Path, o: &Opts) -> std::io::Result<()> {
321 // Export-side files.
322 let names = [
323 "<unk>", "<s>", "</s>", "hello", "world", "note", "append", "ok",
324 ];
325 let vocab: serde_json::Map<String, Value> = names
326 .iter()
327 .enumerate()
328 .map(|(i, t)| (t.to_string(), json!(i)))
329 .collect();
330 let added: Vec<Value> = (0..3)
331 .map(|i| json!({"id": i, "content": names[i], "special": true}))
332 .collect();
333 let tokenizer = pretty(&json!({
334 "version": "1.0",
335 "added_tokens": added,
336 "pre_tokenizer": {"type": "Whitespace"},
337 "model": {"type": "WordLevel", "vocab": vocab, "unk_token": "<unk>"}
338 }));
339 let config = pretty(&json!({
340 "architectures": ["LlamaForCausalLM"], "model_type": "llama",
341 "vocab_size": o.config_vocab.unwrap_or(names.len() as u64),
342 "hidden_size": 4, "intermediate_size": 8, "num_hidden_layers": 1,
343 "num_attention_heads": 1, "num_key_value_heads": 1, "max_position_embeddings": 16,
344 "tie_word_embeddings": true, "torch_dtype": "bfloat16", "bos_token_id": 1, "eos_token_id": 2
345 }));
346 let chat = b"{% for m in messages %}<|{{ m.role }}|>\n{{ m.content }}</s>\n{% endfor %}<|assistant|>\n".to_vec();
347 let data: Vec<u8> = (0u8..64).map(|i| i.wrapping_mul(37)).collect();
348 let run_w = safetensors("tok_embeddings.weight", &data);
349 let exp_w = safetensors("model.embed_tokens.weight", &data);
350
351 // WALDO training side.
352 let corpus = json!({
353 "kind": "openwaldo-bom", "schema": 1, "subject": "corpus",
354 "index": {"remote": "synthetic", "commit": "0".repeat(40), "dirty": false},
355 "paths": ["synthetic/notes"], "license_policy": {}, "manifests": [], "shards": [],
356 "totals": {"files": 1, "docs": 1, "tokens": 20, "bytes": 64},
357 "licenses": {"CC0-1.0": {"shards": 1, "docs": 1, "tokens": 20, "bytes": 64}}
358 });
359 let plan = pretty(
360 &json!({"kind": "waldo-model-plan", "schema": 1, "name": "synthetic-notes",
361 "architecture_sha256": sha256_hex(b"synthetic-architecture")}),
362 );
363 let model_id = waldo_sha256(&plan);
364 let preflight = pretty(&json!({"kind": "waldo-preflight", "schema": 1, "held_out_rows": []}));
365 let backend = json!({"name": "pytorch", "revision": "synthetic-worker-r0"});
366 let run_bom = pretty(&json!({
367 "kind": "openwaldo-bom", "schema": 1, "subject": "training-run", "id": RUN_ID,
368 "model_id": model_id, "stage": "pretrain", "objective": "causal-lm",
369 "execution": {"backend": backend, "framework": "pytorch"},
370 "corpus_bom_sha256": sha256_hex(serde_json::to_string(&corpus).expect("json").as_bytes()),
371 "corpus_bom": corpus,
372 "preflight": {"path": "PREFLIGHT.json", "sha256": sha256_hex(&preflight), "bytes": preflight.len()}
373 }));
374 let run_dir = format!("runs/0001-pretrain-{RUN_ID}/artifacts");
375 let run = pretty(
376 &json!({"kind": "waldo-training-run", "schema": 1, "id": RUN_ID,
377 "state": "complete", "bom_sha256": waldo_sha256(&run_bom)}),
378 );
379 let model_bom = pretty(&json!({
380 "kind": "openwaldo-bom", "schema": 1, "subject": "model", "model_id": model_id,
381 "name": "synthetic-notes", "plan_sha256": model_id, "path_base": "model-root",
382 "current_run_id": RUN_ID,
383 "runs": [{"id": RUN_ID, "stage": "pretrain", "ordinal": 1, "bom_sha256": waldo_sha256(&run_bom),
384 "state": "complete", "backend": backend, "simulated": false,
385 "artifacts": [artifact("weights", &format!("{run_dir}/model.safetensors"), &run_w)]}]
386 }));
387 let release = pretty(&json!({
388 "kind": "openwaldo-bom", "schema": 1, "subject": "model-release", "format": "huggingface",
389 "model_id": model_id, "name": "synthetic-notes", "source_type": "run", "source_id": RUN_ID,
390 "run_id": RUN_ID, "source_bom_sha256": waldo_sha256(&model_bom),
391 "artifacts": [artifact("interaction-template", "chat_template.jinja", &chat),
392 artifact("configuration", "config.json", &config),
393 artifact("weights", "model.safetensors", &exp_w),
394 artifact("tokenizer", "tokenizer.json", &tokenizer)],
395 "generated": "2026-10-06T00:00:00Z"
396 }));
397
398 // AIEN side: candidate manifest (CandidateManifestV1 subset) and the daemon load line.
399 let exe_sha = sha256_hex(b"synthetic aien-cli executable");
400 let cand = format!(
401 "# SYNTHETIC candidate manifest, CandidateManifestV1 subset (aien-architecture qualification/candidates).\n\
402 schema = \"CandidateManifestV1\"\nid = \"{CAND}\"\nstatus = \"synthetic\"\n\n[executables]\n{EXE} = \"{exe_sha}\"\n\n\
403 [model]\nmodel-id = \"synthetic-notes\"\nmodel-safetensors-sha256 = \"{}\"\ntokenizer-json-sha256 = \"{}\"\nconfig-json-sha256 = \"{}\"\n",
404 sha256_hex(&exp_w), sha256_hex(&tokenizer), sha256_hex(&config)
405 );
406 let load = format!(
407 "checkpoint loaded from /models/synthetic-notes/model.safetensors (tokenizer loaded, model_id=synthetic-notes, config=synthetic-notes (config.json), model_sha256={}, tokenizer_sha256={})\n\u{2713} Binding socket at /synthetic/run/aien.sock\n",
408 sha256_hex(&exp_w), sha256_hex(&tokenizer)
409 );
410 let trace_id = o.trace_id.clone().unwrap_or_else(|| TRACE_ID.to_string());
411 let request_id = o
412 .request_id
413 .clone()
414 .unwrap_or_else(|| REQUEST_ID.to_string());
415 let index = [REQUEST_ID, OTHER_REQUEST_ID, IDENTICAL_REQUEST_ID]
416 .iter()
417 .position(|r| *r == request_id)
418 .expect("request id is one of the synthetic requests") as u64;
419 let over = fix_over(o);
420 let trace = pretty(&trace(&trace_id, o.weak, over.as_ref()));
421
422 let files: Vec<(&str, &str, Vec<u8>)> = vec![
423 ("waldo_plan", "records/waldo/PLAN.json", plan),
424 ("waldo_model_bom", "records/waldo/MODEL-BOM.json", model_bom),
425 ("waldo_run_bom", "records/waldo/RUN-BOM.json", run_bom),
426 ("waldo_run", "records/waldo/RUN.json", run),
427 ("waldo_preflight", "records/waldo/PREFLIGHT.json", preflight),
428 ("run_weights", "records/waldo/model.safetensors", run_w),
429 ("release_bom", "records/export/BOM.json", release),
430 ("export_weights", "records/export/model.safetensors", exp_w),
431 ("export_config", "records/export/config.json", config),
432 (
433 "export_tokenizer",
434 "records/export/tokenizer.json",
435 tokenizer,
436 ),
437 (
438 "export_chat_template",
439 "records/export/chat_template.jinja",
440 chat,
441 ),
442 (
443 "candidate_manifest",
444 "records/aien/CAND-SYNTH-0.toml",
445 cand.into_bytes(),
446 ),
447 (
448 "aien_load_log",
449 "records/aien/daemon-load.log",
450 load.into_bytes(),
451 ),
452 ("interplane_trace", "records/interplane/trace.json", trace),
453 ];
454 let mut files = files;
455 if o.weak {
456 files.push((
457 "effect_receipt",
458 "records/aien/effect-receipt.json",
459 receipt_bytes(
460 "write_file",
461 &request_args(&request_id),
462 &result_data(&request_id),
463 true,
464 ),
465 ));
466 } else {
467 for (name, view) in ledger_slice_over(&trace_id, &request_id, index, over.as_ref()) {
468 files.push((name, ledger_path(name), pretty(&view)));
469 }
470 files.push((
471 "daemon_run",
472 "records/aien/daemon-run.json",
473 pretty(&json!({"kind": "aien-daemon-run", "pid": DAEMON_PID,
474 "start_ticks": DAEMON_START_TICKS, "boot_id": "synthetic-boot",
475 "socket": "/synthetic/run/aien.sock", "workspace": WORKSPACE,
476 "executable_sha256": exe_sha,
477 "note": "SYNTHETIC: written by the generator, not by a run harness"})),
478 ));
479 }
480 let fix = o.fix_the_test.then(|| fix_the_test(o));
481 if let Some((extra_files, _)) = &fix {
482 for (n, p, b) in extra_files {
483 files.push((n, p, b.clone()));
484 }
485 }
486 let mut records = serde_json::Map::new();
487 for (name, rel, bytes) in &files {
488 put(dir, rel, bytes)?;
489 records.insert(name.to_string(), json!({"path": rel}));
490 }
491 let mut skeleton = json!({
492 "kind": crate::KIND, "schema": crate::SCHEMA,
493 "fixture": {"class": "synthetic", "generator": "provenance/src/synth.rs",
494 "note": "Every byte is synthetic. The export carries a Hugging Face tokenizer.json, which a real WALDO Hugging Face export does not; no AIEN process loaded this model and no runtime wrote this receipt."},
495 "completeness": {"state": "incomplete", "missing": ["link:model_turn"],
496 "reason": "the INTERPLANE model turn is synthetic: nothing links this model to the effect's content"},
497 "records": records,
498 "lineage": {"kind": "waldo_run", "run_id": RUN_ID, "model_id": model_id,
499 "corpus_license_assertions": ["CC0-1.0"], "training_backend": backend,
500 "training_code": {"repository": "github.com/openwaldo/waldo", "commit": "synthetic", "checked": false}},
501 "export": {"format": "huggingface", "model_revision": format!("{model_id}/{RUN_ID}"),
502 "chat_template": "export_chat_template",
503 "conversion_tool": {"name": "waldo model export --format huggingface", "commit": "synthetic", "checked": false}},
504 "load_support": {"declared": crate::SUPPORTED},
505 "aien": {"candidate_id": CAND, "executable": EXE, "executable_sha256": exe_sha},
506 "interplane": {"trace_id": trace_id, "request_id": request_id},
507 "effect": if o.weak {
508 json!({"binding": RECEIPT_BINDING, "digest_form": SERDE_DIGEST_FORM, "receipt": "effect_receipt"})
509 } else {
510 json!({"binding": LEDGER_BINDING, "approval_binding": APPROVAL_BINDING, "proposal_origin": "scripted_turn"})
511 }
512 });
513 if let Some((_, extra)) = fix {
514 skeleton["test_run"] = extra["test_run"].clone();
515 let mut missing = vec!["link:model_turn"];
516 match o.native {
517 Some(true) => {}
518 _ => missing.push("link:native"),
519 }
520 if !extra["aien_native"].is_null() {
521 skeleton["aien"]["native"] = extra["aien_native"].clone();
522 }
523 skeleton["completeness"]["missing"] = json!(missing);
524 }
525 seal(dir, skeleton)
526}
527
528fn ledger_path(name: &str) -> &'static str {
529 match name {
530 "ledger_claim" => "records/aien/ledger-claim.json",
531 "ledger_committed" => "records/aien/ledger-committed.json",
532 "ledger_grant" => "records/aien/ledger-grant.json",
533 "ledger_intent" => "records/aien/ledger-intent.json",
534 _ => "records/aien/ledger-ack.json",
535 }
536}
537
538/// Fill `sha256`, `bytes` (and `waldo_sha256` for WALDO JSON records) of every retained record
539/// from the files under `dir`, then write COMPANION.json. Refuses to overwrite an existing
540/// manifest: a sealed record is never rewritten to match a new result.
541pub fn seal(dir: &Path, mut skeleton: Value) -> std::io::Result<()> {
542 let out = dir.join(COMPANION_FILE);
543 if out.exists() {
544 return Err(std::io::Error::new(
545 std::io::ErrorKind::AlreadyExists,
546 "COMPANION.json exists; never rewritten",
547 ));
548 }
549 if let Some(recs) = skeleton.get_mut("records").and_then(Value::as_object_mut) {
550 for (name, r) in recs.iter_mut() {
551 if r.get("retained") == Some(&Value::Bool(false)) {
552 continue;
553 }
554 let rel = r["path"].as_str().unwrap_or("").to_string();
555 let b = std::fs::read(dir.join(&rel))?;
556 r["sha256"] = json!(sha256_hex(&b));
557 r["bytes"] = json!(b.len());
558 let waldo_json = matches!(
559 name.as_str(),
560 "waldo_plan" | "waldo_model_bom" | "waldo_run_bom" | "waldo_run" | "release_bom"
561 );
562 if waldo_json {
563 r["waldo_sha256"] = json!(waldo_sha256(&b));
564 }
565 }
566 }
567 std::fs::write(out, pretty(&skeleton))
568}
569
570/// The SYNTHETIC buggy and fixed `src/clamp.c` of the fix-the-test slice (a stand-in for the
571/// adapter fixture; the verifier never reads either, only their digests).
572pub const BUGGY_C: &str = "int clamp(int v, int lo, int hi)\n{\n if (v < lo)\n return lo;\n if (v > hi)\n return lo;\n return v;\n}\n";
573pub const FIXED_C: &str = "int clamp(int v, int lo, int hi)\n{\n if (v < lo)\n return lo;\n if (v > hi)\n return hi;\n return v;\n}\n";
574pub const TASK_ID: &str = "fix-the-test/clamp-1";
575pub const SOURCE_COMMIT: &str = "1111111111111111111111111111111111111111";
576pub const TREE_AFTER: &str = "2222222222222222222222222222222222222222";
577pub const OMEGA_SHA: &str = "6c6180cf378075b61291f4565d226eba38b4decd";
578pub const TEST_STDOUT: &str = "ok inside\nok below\nok above\nok at_low\nok at_high\n";
579
580fn fix_over(o: &Opts) -> Option<Over> {
581 o.fix_the_test.then(|| Over {
582 args: json!({"path": "src/clamp.c", "content": FIXED_C}),
583 prior_sha256: sha256_hex(BUGGY_C.as_bytes()),
584 })
585}
586
587/// Extra records and companion sections of the fix-the-test slice, merged into the skeleton by
588/// `write_synthetic`: `(name, path, bytes)` files, and companion keys to set.
589type ExtraFile = (&'static str, &'static str, Vec<u8>);
590
591fn fix_the_test(o: &Opts) -> (Vec<ExtraFile>, Value) {
592 let task = pretty(
593 &json!({"kind": "vac-task", "task_id": TASK_ID, "repo_commit": SOURCE_COMMIT,
594 "test_cmd": ["make", "test"], "target_path": "src/clamp.c"}),
595 );
596 let pin = pretty(
597 &json!({"kind": "vac-source-pin", "repo": "fix_the_test", "commit": SOURCE_COMMIT,
598 "target_path": "src/clamp.c", "target_blob_sha256": sha256_hex(BUGGY_C.as_bytes())}),
599 );
600 let stdout = TEST_STDOUT.as_bytes().to_vec();
601 let stderr = Vec::new();
602 let run = pretty(&json!({"kind": "vac-test-run", "v": 1, "task_id": TASK_ID,
603 "argv": ["make", "test"], "cwd_rel": ".", "exit_code": 0, "test_exit_before": 2,
604 "stdout_sha256": sha256_hex(&stdout), "stderr_sha256": sha256_hex(&stderr),
605 "started_unix_ms": 1_791_000_000_000u64, "duration_ms": 120,
606 "tree_commit_after": TREE_AFTER, "target_blob_sha256_after": sha256_hex(FIXED_C.as_bytes())}));
607 let mut files = vec![
608 ("task", "records/task/task.json", task),
609 ("source_pin", "records/task/source-pin.json", pin),
610 ("test_run_record", "records/task/test-run.json", run),
611 ("test_stdout", "records/task/test-stdout.txt", stdout),
612 ("test_stderr", "records/task/test-stderr.txt", stderr),
613 ];
614 let mut extra = json!({"test_run": {"binding": "vac-test-run/1", "task_id": TASK_ID,
615 "record": "test_run_record"}});
616 if let Some(claimed) = o.native {
617 let recall = pretty(
618 &json!({"compose_dir": "/synthetic/compose", "machine_id": "synthetic",
619 "records_total": 30, "host": [], "cited": [], "missing": [],
620 "compose_native": claimed, "omega_sha": if claimed { OMEGA_SHA } else { "" }}),
621 );
622 files.push(("compose_recall", "records/aien/compose-recall.json", recall));
623 extra["aien_native"] =
624 json!({"claimed": claimed, "omega_sha": if claimed { OMEGA_SHA } else { "" }});
625 }
626 (files, extra)
627}