Skip to main content

vibe/stdlib_v2/topology_and_manifold/
effects_and_systems.rs

1//! Algebraic Effects, Content-Addressed Code, Structured Concurrency, Design-by-Contract,
2//! CRDTs, Provenance, ZK Predicates & Hardware-Sympathetic Systems (ยงยง14, 16, 17, 18, 19).
3
4use super::{extract_i64, extract_list, extract_record, extract_str, fnv1a_64, fnv1a_value};
5use crate::cbor_ast::{encode, TAG_VIBE_AST};
6use crate::error::{DiagCode, Diagnostic};
7use crate::span::Span;
8use crate::value::Value;
9use crate::{parse_program, SENTINEL_BYTES};
10use std::collections::BTreeMap;
11
12pub fn call_effects_and_systems(
13    path: &str,
14    args: &[Value],
15    span: Span,
16) -> Result<Option<Value>, Diagnostic> {
17    match path {
18        "effect.perform" => Ok(Some(effect_perform(args, span)?)),
19        "effect.handle" => Ok(Some(effect_handle(args, span)?)),
20        "effect.resume" => Ok(Some(effect_resume(args, span)?)),
21        "code.hash_ast" => Ok(Some(code_hash_ast(args, span)?)),
22        "code.resolve" => Ok(Some(code_resolve(args, span)?)),
23        "code.spawn_at" => Ok(Some(code_spawn_at(args, span)?)),
24        "task.spawn" => Ok(Some(task_spawn(args, span)?)),
25        "task.await" => Ok(Some(task_await(args, span)?)),
26        "task.status" => Ok(Some(task_status(args, span)?)),
27        "task.nursery" => Ok(Some(task_nursery(args, span)?)),
28        "task.cancel" => Ok(Some(task_cancel(args, span)?)),
29        "task.with_timeout" => Ok(Some(task_with_timeout(args, span)?)),
30        "supervisor.start_link" => Ok(Some(supervisor_start_link(args, span)?)),
31        "contract.requires" => Ok(Some(contract_check("requires", args, span)?)),
32        "contract.ensures" => Ok(Some(contract_check("ensures", args, span)?)),
33        "contract.invariant" => Ok(Some(contract_check("invariant", args, span)?)),
34        "contract.decreases" => Ok(Some(contract_decreases(args, span)?)),
35        "state.crdt_merge" => Ok(Some(state_crdt_merge(args, span)?)),
36        "value.attach_provenance" => Ok(Some(value_attach_provenance(args, span)?)),
37        "value.verify_provenance" => Ok(Some(value_verify_provenance(args, span)?)),
38        "crypto.prove_zk_predicate" => {
39            Err(unsupported_proof_route("crypto.prove_zk_predicate", span))
40        }
41        "crypto.verify_zk_predicate" => {
42            Err(unsupported_proof_route("crypto.verify_zk_predicate", span))
43        }
44        "crypto.commit_predicate" => Ok(Some(crypto_commit_predicate(args, span)?)),
45        "crypto.verify_commitment" => Ok(Some(crypto_verify_commitment(args, span)?)),
46        "runtime.with_budget" => Ok(Some(runtime_with_budget(args, span)?)),
47        "continuation.snapshot" => Ok(Some(continuation_snapshot(args, span)?)),
48        "continuation.rollback_to" => Ok(Some(continuation_rollback_to(args, span)?)),
49        "memory.with_arena" => Ok(Some(memory_with_arena(args, span)?)),
50        "memory.perceus_plan" => Ok(Some(memory_perceus_plan(args, span)?)),
51        "memory.layout_soa" => Ok(Some(memory_layout_soa(args, span)?)),
52        "simd.validate_boundary" => Ok(Some(simd_validate_boundary(args, span)?)),
53        "channel.lock_free_spsc" => Ok(Some(channel_lock_free_spsc(args, span)?)),
54        _ => Ok(None),
55    }
56}
57
58fn stamp_descriptor_only(out: &mut BTreeMap<String, Value>, kind: &str) {
59    out.insert("descriptor_only".into(), Value::Bool(true));
60    out.insert(
61        "execution_qualification".into(),
62        Value::String(kind.to_string()),
63    );
64}
65
66fn effect_perform(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
67    let op = extract_str(args, 0, "effect.perform", span)?;
68    let payload = args.get(1).cloned().unwrap_or(Value::Null);
69    let mut out = BTreeMap::new();
70    out.insert("__effect".into(), Value::Bool(true));
71    out.insert("op".into(), Value::String(op.to_string()));
72    out.insert("payload".into(), payload);
73    out.insert("resumed".into(), Value::Bool(false));
74    stamp_descriptor_only(&mut out, "checked_effect_descriptor_only");
75    Ok(Value::Record(out))
76}
77
78fn effect_handle(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
79    let eff = extract_record(args, 0, "effect.handle", span)?;
80    let handlers = extract_record(args, 1, "effect.handle", span)?;
81    let op = eff.get("op").and_then(|v| v.as_str()).unwrap_or("");
82    let handled_val = handlers
83        .get(op)
84        .or_else(|| handlers.get("_"))
85        .cloned()
86        .unwrap_or_else(|| eff.get("payload").cloned().unwrap_or(Value::Null));
87    let mut out = BTreeMap::new();
88    out.insert(
89        "handled".into(),
90        Value::Bool(handlers.contains_key(op) || handlers.contains_key("_")),
91    );
92    out.insert("op".into(), Value::String(op.to_string()));
93    out.insert("result".into(), handled_val);
94    stamp_descriptor_only(&mut out, "checked_effect_descriptor_only");
95    Ok(Value::Record(out))
96}
97
98fn effect_resume(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
99    let cont = extract_record(args, 0, "effect.resume", span)?;
100    let val = args.get(1).cloned().unwrap_or(Value::Null);
101    let mut out = cont.clone();
102    out.insert("resumed".into(), Value::Bool(true));
103    out.insert("value".into(), val);
104    stamp_descriptor_only(&mut out, "checked_effect_descriptor_only");
105    Ok(Value::Record(out))
106}
107
108#[derive(Debug, Clone)]
109pub(crate) struct StoredAstArtifact {
110    pub fast_index_u64: u64,
111    pub normalized_src: String,
112    /// Original checked source supplied by the caller. A normalized AST cell
113    /// wrapper is suitable for hashing but is not the source to execute.
114    pub execution_src: String,
115    pub cbor_bytes: Vec<u8>,
116}
117
118static AST_CONTENT_STORE: std::sync::OnceLock<
119    std::sync::Mutex<BTreeMap<String, StoredAstArtifact>>,
120> = std::sync::OnceLock::new();
121
122fn ast_content_store() -> &'static std::sync::Mutex<BTreeMap<String, StoredAstArtifact>> {
123    AST_CONTENT_STORE.get_or_init(|| std::sync::Mutex::new(BTreeMap::new()))
124}
125
126fn parse_sha256_address(raw: &str) -> Option<String> {
127    let hex_part = raw
128        .strip_prefix("sha256:vibe:")
129        .or_else(|| raw.strip_prefix("sha256:vibe-ast-0.1:"))
130        .or_else(|| raw.strip_prefix("sha256:"))
131        .unwrap_or(raw)
132        .trim();
133    if hex_part.len() != 64 || !hex_part.bytes().all(|b| b.is_ascii_hexdigit()) {
134        return None;
135    }
136    Some(hex_part.to_ascii_lowercase())
137}
138
139fn normalize_ast_source(src: &str) -> String {
140    if let Some(rest) = src.trim_start().strip_prefix('=') {
141        format!("const __cell = {};", rest.trim().trim_end_matches(';'))
142    } else {
143        src.to_string()
144    }
145}
146
147/// Look up a previously content-addressed AST source by its `sha256:...` digest.
148pub(crate) fn lookup_verified_ast_source(raw_address: &str) -> Option<String> {
149    let expected_hex = parse_sha256_address(raw_address)?;
150    let guard = ast_content_store().lock().ok()?;
151    let art = guard.get(&expected_hex)?;
152    let normalized = normalize_ast_source(&art.execution_src);
153    let source_matches_stored_bytes = parse_program(&normalized)
154        .ok()
155        .map(|program| encode(&program) == art.cbor_bytes)
156        .unwrap_or(false);
157    if source_matches_stored_bytes && crate::crypto::sha256_hex(&art.cbor_bytes) == expected_hex {
158        Some(art.execution_src.clone())
159    } else {
160        None
161    }
162}
163
164fn code_hash_ast(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
165    let src = extract_str(args, 0, "code.hash_ast", span)?;
166    let normalized_src = normalize_ast_source(src);
167    let prog = parse_program(&normalized_src)?;
168    let bytes = encode(&prog);
169    let fast_index_u64 = fnv1a_64(&bytes);
170    let digest_hex = crate::crypto::sha256_hex(&bytes);
171    let canonical_addr = format!("sha256:vibe:{digest_hex}");
172
173    if let Ok(mut store) = ast_content_store().lock() {
174        store.insert(
175            digest_hex.clone(),
176            StoredAstArtifact {
177                fast_index_u64,
178                normalized_src: normalized_src.clone(),
179                execution_src: src.to_string(),
180                cbor_bytes: bytes.clone(),
181            },
182        );
183    }
184
185    let mut out = BTreeMap::new();
186    out.insert("algorithm".into(), Value::String("SHA-256".into()));
187    out.insert(
188        "canonical_format".into(),
189        Value::String("cbor-ld:vibe-ast-0.1".into()),
190    );
191    out.insert("sha256_hex".into(), Value::String(digest_hex));
192    out.insert("hash_hex".into(), Value::String(canonical_addr));
193    out.insert(
194        "fast_index_algorithm".into(),
195        Value::String("FNV-1a-64".into()),
196    );
197    out.insert("fast_index_u64".into(), Value::U64(fast_index_u64));
198    out.insert("hash_u64".into(), Value::U64(fast_index_u64));
199    out.insert("ast_cbor_tag".into(), Value::I64(TAG_VIBE_AST as i64));
200    out.insert("byte_len".into(), Value::I64(bytes.len() as i64));
201    Ok(Value::Record(out))
202}
203
204fn code_resolve(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
205    let hash_ref = extract_str(args, 0, "code.resolve", span)?;
206    let mut out = BTreeMap::new();
207    out.insert("code_hash".into(), Value::String(hash_ref.to_string()));
208    out.insert("algorithm".into(), Value::String("SHA-256".into()));
209
210    let Some(expected_hex) = parse_sha256_address(hash_ref) else {
211        out.insert("resolved".into(), Value::Bool(false));
212        out.insert("verified".into(), Value::Bool(false));
213        out.insert("immutable".into(), Value::Bool(false));
214        out.insert(
215            "reason".into(),
216            Value::String("invalid_sha256_digest_format".into()),
217        );
218        return Ok(Value::Record(out));
219    };
220
221    // Optional second argument: candidate source or CBOR bytes to verify against expected_hex.
222    if let Some(Value::String(candidate_src)) = args.get(1) {
223        let normalized_cand = normalize_ast_source(candidate_src);
224        if let Ok(cand_prog) = parse_program(&normalized_cand) {
225            let cand_bytes = encode(&cand_prog);
226            let actual_hex = crate::crypto::sha256_hex(&cand_bytes);
227            if actual_hex != expected_hex {
228                out.insert("resolved".into(), Value::Bool(false));
229                out.insert("verified".into(), Value::Bool(false));
230                out.insert("immutable".into(), Value::Bool(false));
231                out.insert("reason".into(), Value::String("digest_mismatch".into()));
232                return Ok(Value::Record(out));
233            }
234        } else {
235            out.insert("resolved".into(), Value::Bool(false));
236            out.insert("verified".into(), Value::Bool(false));
237            out.insert("immutable".into(), Value::Bool(false));
238            out.insert(
239                "reason".into(),
240                Value::String("invalid_candidate_ast".into()),
241            );
242            return Ok(Value::Record(out));
243        }
244    }
245
246    let stored_opt = ast_content_store()
247        .lock()
248        .ok()
249        .and_then(|guard| guard.get(&expected_hex).cloned());
250
251    let Some(artifact) = stored_opt else {
252        out.insert("resolved".into(), Value::Bool(false));
253        out.insert("verified".into(), Value::Bool(false));
254        out.insert("immutable".into(), Value::Bool(false));
255        out.insert("reason".into(), Value::String("content_not_found".into()));
256        return Ok(Value::Record(out));
257    };
258
259    let recomputed_hex = crate::crypto::sha256_hex(&artifact.cbor_bytes);
260    if recomputed_hex != expected_hex {
261        out.insert("resolved".into(), Value::Bool(false));
262        out.insert("verified".into(), Value::Bool(false));
263        out.insert("immutable".into(), Value::Bool(false));
264        out.insert("reason".into(), Value::String("digest_mismatch".into()));
265        return Ok(Value::Record(out));
266    }
267
268    out.insert("resolved".into(), Value::Bool(true));
269    out.insert("verified".into(), Value::Bool(true));
270    out.insert("immutable".into(), Value::Bool(true));
271    out.insert("sha256_hex".into(), Value::String(expected_hex));
272    out.insert("fast_index_u64".into(), Value::U64(artifact.fast_index_u64));
273    out.insert(
274        "byte_len".into(),
275        Value::I64(artifact.cbor_bytes.len() as i64),
276    );
277    out.insert("source".into(), Value::String(artifact.normalized_src));
278    Ok(Value::Record(out))
279}
280
281fn code_spawn_at(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
282    let node_did = extract_str(args, 0, "code.spawn_at", span)?;
283    if node_did != "did:q42:local_scheduler" {
284        return Err(Diagnostic::new(
285            DiagCode::E600,
286            span,
287            format!("code.spawn_at: remote or unknown scheduler '{node_did}' is unsupported; only did:q42:local_scheduler is available"),
288        ));
289    }
290    let code_hash = extract_str(args, 1, "code.spawn_at", span)?;
291    if code_hash.starts_with("sha256:") && lookup_verified_ast_source(code_hash).is_none() {
292        return Err(Diagnostic::new(
293            DiagCode::E400,
294            span,
295            format!("code.spawn_at: content-addressed code '{code_hash}' is unavailable or failed SHA-256 verification"),
296        ));
297    }
298    let call_args = args.get(2).cloned().unwrap_or_else(|| Value::List(vec![]));
299    crate::task_scheduler::spawn_scheduled_task(node_did, code_hash, call_args, 0, span)
300}
301
302fn task_spawn(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
303    let code_or_spec = extract_str(args, 0, "task.spawn", span)?;
304    let call_args = args.get(1).cloned().unwrap_or(Value::Null);
305    let elapsed_ms = match &call_args {
306        Value::Record(r) => r.get("elapsed_ms").and_then(|v| v.as_i64()).unwrap_or(0),
307        _ => 0,
308    };
309    crate::task_scheduler::spawn_scheduled_task(
310        "did:q42:local_scheduler",
311        code_or_spec,
312        call_args,
313        elapsed_ms,
314        span,
315    )
316}
317
318fn task_await(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
319    let val = args.first().cloned().unwrap_or(Value::Null);
320    crate::task_scheduler::await_value_standalone(val, span)
321}
322
323fn task_status(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
324    let target = args.first().ok_or_else(|| {
325        Diagnostic::new(
326            DiagCode::E100,
327            span,
328            "task.status: missing task record or task_id argument",
329        )
330    })?;
331    crate::task_scheduler::query_task_status(target, span)
332}
333
334fn task_nursery(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
335    let tasks = extract_list(args, 0, "task.nursery", span)?;
336    let any_failed = tasks.iter().any(|t| match t {
337        Value::Record(r) => {
338            r.get("status").and_then(|v| v.as_str()) == Some("failed")
339                || r.get("ok") == Some(&Value::Bool(false))
340        }
341        _ => false,
342    });
343    let mut results = Vec::with_capacity(tasks.len());
344    let mut live_siblings_cancelled = 0u64;
345    for t in tasks {
346        if let Value::Record(r) = t {
347            if any_failed && r.get("status").and_then(|v| v.as_str()) != Some("failed") {
348                let cancelled_val = crate::task_scheduler::cancel_scheduled_task(r, span)?;
349                if let Value::Record(ref cr) = cancelled_val {
350                    if cr.get("live_job_cancelled") == Some(&Value::Bool(true)) {
351                        live_siblings_cancelled += 1;
352                    }
353                }
354                results.push(cancelled_val);
355            } else if !r.contains_key("status")
356                || r.get("status").and_then(|v| v.as_str()) == Some("running")
357            {
358                if crate::task_scheduler::extract_task_id(r).is_some() {
359                    let awaited = crate::task_scheduler::await_value_standalone(
360                        Value::Record(r.clone()),
361                        span,
362                    )?;
363                    results.push(awaited);
364                } else {
365                    let mut tr = r.clone();
366                    tr.insert("status".into(), Value::String("completed".into()));
367                    results.push(Value::Record(tr));
368                }
369            } else {
370                results.push(Value::Record(r.clone()));
371            }
372        } else {
373            results.push(t.clone());
374        }
375    }
376    let mut out = BTreeMap::new();
377    out.insert("all_succeeded".into(), Value::Bool(!any_failed));
378    out.insert("cancelled_siblings".into(), Value::Bool(any_failed));
379    out.insert(
380        "live_siblings_cancelled".into(),
381        Value::U64(live_siblings_cancelled),
382    );
383    out.insert("tasks".into(), Value::List(results));
384    Ok(Value::Record(out))
385}
386
387fn task_cancel(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
388    let rec = extract_record(args, 0, "task.cancel", span)?;
389    crate::task_scheduler::cancel_scheduled_task(rec, span)
390}
391
392fn task_with_timeout(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
393    let rec = extract_record(args, 0, "task.with_timeout", span)?;
394    let timeout_ms = extract_i64(args, 1, "task.with_timeout", span)?;
395    crate::task_scheduler::apply_task_timeout(rec, timeout_ms, span).map(Value::Record)
396}
397
398fn supervisor_start_link(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
399    let children = extract_list(args, 0, "supervisor.start_link", span)?;
400    let strategy = extract_str(args, 1, "supervisor.start_link", span)?;
401    let max_restarts = args.get(2).and_then(|v| v.as_i64()).unwrap_or(3);
402    let mut restarted = Vec::new();
403    let mut restart_rest = false;
404    for (idx, child) in children.iter().enumerate() {
405        if let Value::Record(r) = child {
406            let crashed = r.get("status").and_then(|v| v.as_str()) == Some("crashed");
407            if crashed || (strategy == "RestForOne" && restart_rest) {
408                restart_rest = true;
409                restarted.push(Value::I64(idx as i64));
410            }
411        }
412    }
413    let mut out = BTreeMap::new();
414    out.insert("strategy".into(), Value::String(strategy.to_string()));
415    out.insert("max_restarts".into(), Value::I64(max_restarts));
416    out.insert("restarted_indices".into(), Value::List(restarted.clone()));
417    out.insert(
418        "healthy".into(),
419        Value::Bool((restarted.len() as i64) <= max_restarts),
420    );
421    stamp_descriptor_only(&mut out, "checked_supervisor_plan_descriptor_only");
422    Ok(Value::Record(out))
423}
424
425fn contract_check(kind: &str, args: &[Value], span: Span) -> Result<Value, Diagnostic> {
426    let ok = match args.first() {
427        Some(Value::Bool(b)) => *b,
428        _ => false,
429    };
430    let msg = args
431        .get(1)
432        .and_then(|v| v.as_str())
433        .unwrap_or("contract failed");
434    if !ok {
435        return Err(Diagnostic::new(
436            DiagCode::E500,
437            span,
438            format!("contract.{kind} violated: {msg}"),
439        ));
440    }
441    let mut out = BTreeMap::new();
442    out.insert("contract".into(), Value::String(kind.to_string()));
443    out.insert("verified".into(), Value::Bool(true));
444    Ok(Value::Record(out))
445}
446
447fn contract_decreases(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
448    let prev = extract_i64(args, 0, "contract.decreases", span)?;
449    let curr = extract_i64(args, 1, "contract.decreases", span)?;
450    if curr >= prev || curr < 0 {
451        return Err(Diagnostic::new(
452            DiagCode::E500,
453            span,
454            format!("contract.decreases violated: measure {curr} did not strictly decrease from {prev} >= 0"),
455        ));
456    }
457    let mut out = BTreeMap::new();
458    out.insert("decreasing".into(), Value::Bool(true));
459    out.insert("delta".into(), Value::I64(prev - curr));
460    Ok(Value::Record(out))
461}
462
463fn state_crdt_merge(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
464    let local = extract_record(args, 0, "state.crdt_merge", span)?;
465    let remote = extract_record(args, 1, "state.crdt_merge", span)?;
466    let mut merged = local.clone();
467    for (k, rv) in remote {
468        match merged.get(k) {
469            Some(Value::I64(lv)) if rv.as_i64().is_some() => {
470                merged.insert(k.clone(), Value::I64((*lv).max(rv.as_i64().unwrap())));
471            }
472            Some(lv) => {
473                if fnv1a_value(rv) >= fnv1a_value(lv) {
474                    merged.insert(k.clone(), rv.clone());
475                }
476            }
477            None => {
478                merged.insert(k.clone(), rv.clone());
479            }
480        }
481    }
482    Ok(Value::Record(merged))
483}
484
485static PROVENANCE_SEAL_STORE: std::sync::OnceLock<std::sync::Mutex<BTreeMap<String, String>>> =
486    std::sync::OnceLock::new();
487
488fn provenance_seal_store() -> &'static std::sync::Mutex<BTreeMap<String, String>> {
489    PROVENANCE_SEAL_STORE.get_or_init(|| std::sync::Mutex::new(BTreeMap::new()))
490}
491
492fn canonical_provenance_digest(data: &Value, prov: &Value) -> String {
493    let payload = format!("vibe-provenance-v1|data={data:?}|prov={prov:?}");
494    crate::crypto::sha256_hex(payload.as_bytes())
495}
496
497fn value_attach_provenance(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
498    let data = args.first().cloned().unwrap_or(Value::Null);
499    let prov = extract_record(args, 1, "value.attach_provenance", span)?;
500    let prov_val = Value::Record(prov.clone());
501    let fast_checksum = fnv1a_value(&data) ^ fnv1a_value(&prov_val);
502    let digest_sha256 = canonical_provenance_digest(&data, &prov_val);
503    let seal = crate::crypto::sha256_hex(
504        format!("vibe-prov-seal-v1|{digest_sha256}|{fast_checksum}").as_bytes(),
505    );
506    if let Ok(mut guard) = provenance_seal_store().lock() {
507        guard.insert(digest_sha256.clone(), seal.clone());
508    }
509    let mut out = BTreeMap::new();
510    out.insert("value".into(), data);
511    out.insert("provenance".into(), prov_val);
512    out.insert("digest_algorithm".into(), Value::String("SHA-256".into()));
513    out.insert("digest_sha256".into(), Value::String(digest_sha256));
514    out.insert("__provenance_seal".into(), Value::String(seal));
515    out.insert("signature_u64".into(), Value::U64(fast_checksum));
516    out.insert(
517        "fast_checksum_algorithm".into(),
518        Value::String("FNV-1a-64-non-cryptographic".into()),
519    );
520    out.insert(
521        "verification_kind".into(),
522        Value::String("content_sha256_integrity_not_external_pki".into()),
523    );
524    Ok(Value::Record(out))
525}
526
527fn value_verify_provenance(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
528    let wrapped = extract_record(args, 0, "value.verify_provenance", span)?;
529    let data = wrapped.get("value").cloned().unwrap_or(Value::Null);
530    let prov = wrapped.get("provenance").cloned().unwrap_or(Value::Null);
531    let expected_u64 = fnv1a_value(&data) ^ fnv1a_value(&prov);
532    let actual_u64 = match wrapped.get("signature_u64") {
533        Some(Value::U64(u)) => *u,
534        _ => 0,
535    };
536    let expected_sha256 = canonical_provenance_digest(&data, &prov);
537    let claimed_sha256 = wrapped
538        .get("digest_sha256")
539        .and_then(|v| v.as_str())
540        .unwrap_or("");
541    let claimed_seal = wrapped
542        .get("__provenance_seal")
543        .and_then(|v| v.as_str())
544        .unwrap_or("");
545    let seal_registered = provenance_seal_store()
546        .lock()
547        .ok()
548        .and_then(|g| g.get(&expected_sha256).cloned())
549        .map(|s| s == claimed_seal && !claimed_seal.is_empty())
550        .unwrap_or(false);
551    let integrity_verified = !claimed_sha256.is_empty()
552        && claimed_sha256 == expected_sha256
553        && seal_registered
554        && expected_u64 == actual_u64
555        && actual_u64 != 0;
556    let mut out = BTreeMap::new();
557    out.insert("authentic".into(), Value::Bool(integrity_verified));
558    out.insert("integrity_verified".into(), Value::Bool(integrity_verified));
559    out.insert("issuer_signature_verified".into(), Value::Bool(false));
560    out.insert(
561        "verification_kind".into(),
562        Value::String("content_sha256_integrity_not_external_pki".into()),
563    );
564    out.insert(
565        "expected_digest_sha256".into(),
566        Value::String(expected_sha256),
567    );
568    out.insert("expected_signature".into(), Value::U64(expected_u64));
569    Ok(Value::Record(out))
570}
571
572fn unsupported_proof_route(name: &str, span: Span) -> Diagnostic {
573    Diagnostic::new(
574        DiagCode::E600,
575        span,
576        format!("{name}: unsupported; no native zero-knowledge proof provider is configured"),
577    )
578}
579
580fn local_predicate_commitment(predicate: &str, public_input: &Value) -> String {
581    let payload =
582        format!("vibe-local-predicate-commitment-v1|predicate={predicate}|public={public_input:?}");
583    crate::crypto::sha256_hex(payload.as_bytes())
584}
585
586fn crypto_commit_predicate(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
587    let predicate = extract_str(args, 0, "crypto.commit_predicate", span)?;
588    if predicate.trim().is_empty() {
589        return Err(Diagnostic::new(
590            DiagCode::E400,
591            span,
592            "crypto.commit_predicate: predicate must not be empty",
593        ));
594    }
595    let public_input = args.get(1).cloned().unwrap_or(Value::Null);
596    let mut out = BTreeMap::new();
597    out.insert("predicate".into(), Value::String(predicate.to_string()));
598    out.insert(
599        "commitment_sha256".into(),
600        Value::String(local_predicate_commitment(predicate, &public_input)),
601    );
602    out.insert(
603        "commitment_kind".into(),
604        Value::String(
605            "local_deterministic_binding_integrity_not_zkp_or_predicate_evaluation".into(),
606        ),
607    );
608    out.insert("predicate_truth_verified".into(), Value::Bool(false));
609    out.insert("issuer_authenticity_verified".into(), Value::Bool(false));
610    Ok(Value::Record(out))
611}
612
613fn crypto_verify_commitment(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
614    let commitment = extract_record(args, 0, "crypto.verify_commitment", span)?;
615    let pred_arg = [commitment.get("predicate").cloned().unwrap_or(Value::Null)];
616    let predicate = extract_str(
617        &pred_arg,
618        0,
619        "crypto.verify_commitment.predicate",
620        span,
621    )?;
622    let public_input = args.get(1).cloned().unwrap_or(Value::Null);
623    let claimed = commitment
624        .get("commitment_sha256")
625        .and_then(Value::as_str)
626        .unwrap_or("");
627    let expected = local_predicate_commitment(predicate, &public_input);
628    let mut out = BTreeMap::new();
629    out.insert(
630        "integrity_verified".into(),
631        Value::Bool(!claimed.is_empty() && claimed == expected),
632    );
633    out.insert("predicate_truth_verified".into(), Value::Bool(false));
634    out.insert("issuer_authenticity_verified".into(), Value::Bool(false));
635    out.insert(
636        "verification_kind".into(),
637        Value::String(
638            "local_deterministic_binding_integrity_not_zkp_or_predicate_evaluation".into(),
639        ),
640    );
641    Ok(Value::Record(out))
642}
643
644fn runtime_with_budget(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
645    let budget = extract_record(args, 0, "runtime.with_budget", span)?;
646    let val = args.get(1).cloned().unwrap_or(Value::Null);
647    let max_bytes = budget
648        .get("max_bytes")
649        .and_then(|v| v.as_i64())
650        .unwrap_or(SENTINEL_BYTES as i64);
651    if max_bytes < 0 || (max_bytes as u64) > SENTINEL_BYTES {
652        return Err(Diagnostic::new(
653            DiagCode::E400,
654            span,
655            format!("runtime.with_budget: max_bytes {max_bytes} exceeds 42 MiB Sentinel"),
656        ));
657    }
658    let mut out = BTreeMap::new();
659    out.insert("within_budget".into(), Value::Bool(true));
660    out.insert("max_bytes".into(), Value::I64(max_bytes));
661    out.insert("result".into(), val);
662    stamp_descriptor_only(&mut out, "checked_budget_descriptor_only");
663    Ok(Value::Record(out))
664}
665
666fn continuation_snapshot(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
667    let state = extract_record(args, 0, "continuation.snapshot", span)?;
668    let step = state.get("step").and_then(|v| v.as_i64()).unwrap_or(0);
669    let digest = fnv1a_value(&Value::Record(state.clone()));
670    let mut out = BTreeMap::new();
671    out.insert("snapshot_digest".into(), Value::U64(digest));
672    out.insert("step".into(), Value::I64(step));
673    out.insert("state".into(), Value::Record(state.clone()));
674    stamp_descriptor_only(&mut out, "checked_state_snapshot_descriptor_only");
675    Ok(Value::Record(out))
676}
677
678fn continuation_rollback_to(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
679    let snap = extract_record(args, 0, "continuation.rollback_to", span)?;
680    let target_step = extract_i64(args, 1, "continuation.rollback_to", span)?;
681    let mut restored = match snap.get("state") {
682        Some(Value::Record(r)) => r.clone(),
683        _ => snap.clone(),
684    };
685    restored.insert("step".into(), Value::I64(target_step));
686    restored.insert("rolled_back".into(), Value::Bool(true));
687    stamp_descriptor_only(&mut restored, "checked_state_rollback_descriptor_only");
688    Ok(Value::Record(restored))
689}
690
691fn memory_with_arena(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
692    let byte_cap = extract_i64(args, 0, "memory.with_arena", span)?;
693    if byte_cap < 0 || (byte_cap as u64) > SENTINEL_BYTES {
694        return Err(Diagnostic::new(
695            DiagCode::E400,
696            span,
697            format!("memory.with_arena: requested {byte_cap} B exceeds 42 MiB Sentinel limit"),
698        ));
699    }
700    let payload = args.get(1).cloned().unwrap_or(Value::Null);
701    let mut out = BTreeMap::new();
702    out.insert("arena_capacity".into(), Value::I64(byte_cap));
703    out.insert("zero_heap_escape".into(), Value::Bool(true));
704    out.insert("result".into(), payload);
705    stamp_descriptor_only(&mut out, "checked_arena_descriptor_only");
706    Ok(Value::Record(out))
707}
708
709fn memory_perceus_plan(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
710    let val = args.first().cloned().unwrap_or(Value::Null);
711    let ref_count = extract_i64(args, 1, "memory.perceus_plan", span)?;
712    let mut out = BTreeMap::new();
713    out.insert("in_place_reuse".into(), Value::Bool(ref_count == 1));
714    out.insert("ref_count".into(), Value::I64(ref_count));
715    out.insert("value".into(), val);
716    stamp_descriptor_only(&mut out, "checked_perceus_plan_descriptor_only");
717    Ok(Value::Record(out))
718}
719
720fn memory_layout_soa(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
721    let schema = extract_record(args, 0, "memory.layout_soa", span)?;
722    let count = args
723        .get(1)
724        .and_then(|v| match v {
725            Value::Record(r) => r.get("count").and_then(|c| c.as_i64()),
726            Value::I64(n) => Some(*n),
727            _ => None,
728        })
729        .unwrap_or(64)
730        .max(1);
731    let mut offsets = BTreeMap::new();
732    let mut cursor = 0i64;
733    for k in schema.keys() {
734        offsets.insert(k.clone(), Value::I64(cursor));
735        let raw_bytes = count * 8;
736        cursor += (raw_bytes + 63) & !63;
737    }
738    let mut out = BTreeMap::new();
739    out.insert("layout".into(), Value::String("SoA".into()));
740    out.insert("alignment_bytes".into(), Value::I64(64));
741    out.insert("column_offsets".into(), Value::Record(offsets));
742    out.insert("total_bytes".into(), Value::I64(cursor));
743    stamp_descriptor_only(&mut out, "checked_soa_layout_descriptor_only");
744    Ok(Value::Record(out))
745}
746
747fn simd_validate_boundary(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
748    let batch = extract_list(args, 0, "simd.validate_boundary", span)?;
749    let all_intact = batch.iter().all(|item| match item {
750        Value::Record(r) => r.get("intact") != Some(&Value::Bool(false)),
751        _ => true,
752    });
753    let mut out = BTreeMap::new();
754    out.insert("lanes_processed".into(), Value::I64(batch.len() as i64));
755    out.insert("all_intact".into(), Value::Bool(all_intact));
756    Ok(Value::Record(out))
757}
758
759fn channel_lock_free_spsc(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
760    let cap = extract_i64(args, 0, "channel.lock_free_spsc", span)?.max(1) as usize;
761    let items = extract_list(args, 1, "channel.lock_free_spsc", span)?;
762    let accepted: Vec<Value> = items.iter().take(cap).cloned().collect();
763    let dropped = items.len().saturating_sub(cap) as i64;
764    let mut out = BTreeMap::new();
765    out.insert("capacity".into(), Value::I64(cap as i64));
766    out.insert("queued".into(), Value::List(accepted));
767    out.insert("dropped".into(), Value::I64(dropped));
768    out.insert("lock_free".into(), Value::Bool(true));
769    stamp_descriptor_only(&mut out, "checked_spsc_queue_descriptor_only");
770    Ok(Value::Record(out))
771}