Skip to main content

vibe/extension_registry/
eval_router.rs

1//! Evaluator, Bytecode VM, and Task Scheduler Call-Site Cutover Router (`Stage S6`).
2//!
3//! Replaces direct string-based `crate::bind::dispatch` calls across
4//! `crates/vibe/src/{eval, bytecode, task_scheduler}` with unified
5//! `ExtensionRegistry` resolution, $O(1)$ `PreparedCallCache` lookup,
6//! zero-heap slice marshaling, `SentinelPolicyGate` enforcement, and budget charging.
7
8use super::dispatch_adapter::{dispatch_prepared_call, CallExecutionContext, DispatchOutcome};
9#[path = "native_budget.rs"]
10mod native_budget;
11use super::domain_providers::DeterministicMechanicsProvider;
12use super::gpu_inference_providers::{EtalonGpuComputeProvider, GovernedInferenceProvider};
13use super::graph_logic_providers::{DeonticTemporalProvider, StagedGraphMutationProvider};
14use super::prepare::prepare_extension_call;
15use super::registry::ExtensionRegistry;
16use crate::bind::Host;
17use crate::budget::Budget;
18use crate::error::{DiagCode, Diagnostic};
19use crate::span::Span;
20use crate::value::Value;
21use etalon_vibe::{
22    EtalonForgeProvider, EtalonModelProvider, EtalonNQuinProvider, EtalonRenderProvider,
23    EtalonSenseProvider, EtalonSignalProvider,
24};
25use vibescript_abi::{
26    q_hash_str, AdmissionRequest, BorrowedSliceView, CallerOutputSlice, CompletionStatus,
27    EffectSet, ExecutionMode, ExecutionReceiptHeader, FuncDescriptor, PreparedCallHandle,
28    PrimitiveKind, RegistryGeneration, ResourceEnvelope, SemVerReq, SentinelPolicyGate,
29    StableFuncId, TargetProfileMask, VibeOpCode, VibeTrap,
30};
31
32static MECH_PROVIDER: DeterministicMechanicsProvider = DeterministicMechanicsProvider;
33static GPU_PROVIDER: EtalonGpuComputeProvider = EtalonGpuComputeProvider;
34static FORGE_PROVIDER: EtalonForgeProvider = EtalonForgeProvider;
35static RENDER_PROVIDER: EtalonRenderProvider = EtalonRenderProvider;
36static SIGNAL_PROVIDER: EtalonSignalProvider = EtalonSignalProvider;
37static SENSE_PROVIDER: EtalonSenseProvider = EtalonSenseProvider;
38static MODEL_PROVIDER: EtalonModelProvider = EtalonModelProvider;
39static NQUIN_PROVIDER: EtalonNQuinProvider = EtalonNQuinProvider;
40static INFER_PROVIDER: GovernedInferenceProvider = GovernedInferenceProvider;
41static GRAPH_PROVIDER: StagedGraphMutationProvider = StagedGraphMutationProvider;
42static MODALITY_PROVIDER: DeonticTemporalProvider = DeonticTemporalProvider;
43
44/// Short aliases of all built-in extension providers registered by default.
45pub const BUILTIN_EXTENSION_ALIASES: &[&str] = &[
46    "mech", "gpu", "forge", "render", "signal", "sense", "p64", "nquin", "infer", "qgraph",
47    "modality",
48];
49
50/// Canonical namespace IRIs of all built-in extension providers registered by default.
51pub const BUILTIN_EXTENSION_IRIS: &[&str] = &[
52    "https://qualiadb.org/ext/etalon/mechanics",
53    "https://qualiadb.org/ext/etalon/gpu",
54    "https://qualiadb.org/ext/etalon/forge",
55    "https://qualiadb.org/ext/etalon/render",
56    "https://qualiadb.org/ext/etalon/signal",
57    "https://qualiadb.org/ext/etalon/sense",
58    "https://qualiadb.org/ext/etalon/model",
59    "https://qualiadb.org/ext/etalon/nquin",
60    "https://qualiadb.org/ext/qualia/inference",
61    "https://qualiadb.org/ext/qualia/graph",
62    "https://qualiadb.org/ext/qualia/modality",
63];
64
65impl ExtensionRegistry<'static> {
66    /// Constructs an `ExtensionRegistry` pre-populated with all 11 built-in Etalon and Qualia providers:
67    /// - `mech` (`DeterministicMechanicsProvider`)
68    /// - `gpu` (`EtalonGpuComputeProvider`)
69    /// - `forge` (`EtalonForgeProvider`)
70    /// - `render` (`EtalonRenderProvider`)
71    /// - `signal` (`EtalonSignalProvider`)
72    /// - `sense` (`EtalonSenseProvider`)
73    /// - `p64` (`EtalonModelProvider`)
74    /// - `nquin` (`EtalonNQuinProvider`)
75    /// - `infer` (`GovernedInferenceProvider`)
76    /// - `qgraph` (`StagedGraphMutationProvider`)
77    /// - `modality` (`DeonticTemporalProvider`)
78    pub fn with_builtin_providers() -> Self {
79        let mut reg = Self::new();
80        reg.register(&MECH_PROVIDER)
81            .expect("built-in mech provider registration failed");
82        reg.register(&GPU_PROVIDER)
83            .expect("built-in gpu provider registration failed");
84        reg.register(&FORGE_PROVIDER)
85            .expect("built-in forge provider registration failed");
86        reg.register(&RENDER_PROVIDER)
87            .expect("built-in render provider registration failed");
88        reg.register(&SIGNAL_PROVIDER)
89            .expect("built-in signal provider registration failed");
90        reg.register(&SENSE_PROVIDER)
91            .expect("built-in sense provider registration failed");
92        reg.register(&MODEL_PROVIDER)
93            .expect("built-in model provider registration failed");
94        reg.register(&NQUIN_PROVIDER)
95            .expect("built-in nquin provider registration failed");
96        reg.register(&INFER_PROVIDER)
97            .expect("built-in infer provider registration failed");
98        reg.register(&GRAPH_PROVIDER)
99            .expect("built-in qgraph provider registration failed");
100        reg.register(&MODALITY_PROVIDER)
101            .expect("built-in modality provider registration failed");
102        reg
103    }
104}
105
106/// Returns `true` if `ns` is a known built-in extension alias or canonical IRI.
107#[inline]
108pub fn is_extension_namespace(ns: &str) -> bool {
109    let stripped = ns.strip_prefix("vibe:0.3/").unwrap_or(ns);
110    BUILTIN_EXTENSION_ALIASES.contains(&stripped) || BUILTIN_EXTENSION_IRIS.contains(&stripped)
111}
112
113/// Returns `true` if `path` starts with a registered built-in extension alias or canonical IRI.
114#[inline]
115pub fn is_extension_call_path(path: &str) -> bool {
116    if let Some((head, _)) = path.split_once('.') {
117        if is_extension_namespace(head) {
118            return true;
119        }
120    }
121    BUILTIN_EXTENSION_IRIS
122        .iter()
123        .any(|iri| path.starts_with(iri))
124}
125
126/// Fixed-capacity, zero-heap cache mapping call-path FNV-1a hashes to `PreparedCallHandle`s.
127#[derive(Clone, Copy)]
128pub struct PreparedCallCache {
129    entries: [Option<(u64, PreparedCallHandle)>; 32],
130    cursor: usize,
131}
132
133impl Default for PreparedCallCache {
134    fn default() -> Self {
135        Self::new()
136    }
137}
138
139impl PreparedCallCache {
140    /// Creates an empty `PreparedCallCache`.
141    #[inline]
142    pub const fn new() -> Self {
143        Self {
144            entries: [None; 32],
145            cursor: 0,
146        }
147    }
148
149    /// Looks up a cached `PreparedCallHandle` for `(path_hash, current_gen)`.
150    #[inline]
151    pub fn get(
152        &self,
153        path_hash: u64,
154        current_gen: RegistryGeneration,
155    ) -> Option<PreparedCallHandle> {
156        let mut i = 0;
157        while i < self.entries.len() {
158            if let Some((h, handle)) = self.entries[i] {
159                if h == path_hash && handle.registry_generation == current_gen {
160                    return Some(handle);
161                }
162            }
163            i += 1;
164        }
165        None
166    }
167
168    /// Inserts a `PreparedCallHandle` into the ring cache.
169    #[inline]
170    pub fn insert(&mut self, path_hash: u64, handle: PreparedCallHandle) {
171        self.entries[self.cursor % self.entries.len()] = Some((path_hash, handle));
172        self.cursor = self.cursor.wrapping_add(1);
173    }
174}
175
176/// Maps a deterministic `VibeTrap` to a VibeScript `Diagnostic`.
177pub fn trap_to_diagnostic(trap: VibeTrap, path: &str, span: Span) -> Diagnostic {
178    let code = match trap {
179        VibeTrap::SentinelUnavailable
180        | VibeTrap::PolicyDenied
181        | VibeTrap::ExplicitDenyRule
182        | VibeTrap::AuthorityExpired
183        | VibeTrap::DelegationScopeMismatch
184        | VibeTrap::RevokedPolicyGeneration
185        | VibeTrap::EffectNotPermittedInMode
186        | VibeTrap::MidExecutionPolicyRevoked
187        | VibeTrap::ReceiptPersistenceFailed
188        | VibeTrap::StagingAbortRequired => DiagCode::E700,
189        VibeTrap::TickBudgetExhausted | VibeTrap::ResourceEnvelopeExceeded => DiagCode::E400,
190        VibeTrap::NamespaceNotFound | VibeTrap::FunctionNotFound => DiagCode::E300,
191        _ => DiagCode::E100,
192    };
193    Diagnostic::new(
194        code,
195        span,
196        format!(
197            "extension trap {:?} (code {}) on `{path}`",
198            trap, trap as u16
199        ),
200    )
201}
202
203/// Resolves a dotted or canonical IRI call path against `registry` into a `PreparedCallHandle`.
204///
205/// Supports:
206/// - 3-part dotted path: `"mech.kinematics.verlet_step"`, `"https://.../mechanics.kinematics.verlet_step"`
207/// - 2-part dotted path: `"mech.verlet_step"` (searches sub-namespaces of provider `"mech"`)
208/// - Full canonical function IRI: `"https://qualiadb.org/ext/etalon/mechanics/kinematics/verlet_step"`
209pub fn try_prepare_path(
210    registry: &ExtensionRegistry<'_>,
211    cache: &mut PreparedCallCache,
212    path: &str,
213    target_profile: TargetProfileMask,
214) -> Result<Option<PreparedCallHandle>, VibeTrap> {
215    let path_hash = q_hash_str(path) ^ ((target_profile.0 as u64) << 48);
216    if let Some(cached) = cache.get(path_hash, registry.generation()) {
217        return Ok(Some(cached));
218    }
219
220    // Case 1: Full canonical function IRI (`https://...`)
221    if path.starts_with("https://") || path.starts_with("http://") {
222        // Check if it has `.sub.func` appended after an alias-resolved IRI
223        if let Some((ns_iri, rest)) = split_iri_and_member_suffix(registry, path) {
224            if let Some((sub, func)) = rest.split_once('.') {
225                let handle = prepare_extension_call(
226                    registry,
227                    ns_iri,
228                    sub,
229                    func,
230                    SemVerReq::AnyStable,
231                    target_profile,
232                )?;
233                cache.insert(path_hash, handle);
234                return Ok(Some(handle));
235            } else if let Some((_slot, _prov, desc)) = registry.find_by_namespace_or_alias(ns_iri) {
236                for sub_desc in desc.sub_namespaces {
237                    if sub_desc.functions.iter().any(|f| f.name == rest) {
238                        let handle = prepare_extension_call(
239                            registry,
240                            ns_iri,
241                            sub_desc.name,
242                            rest,
243                            SemVerReq::AnyStable,
244                            target_profile,
245                        )?;
246                        cache.insert(path_hash, handle);
247                        return Ok(Some(handle));
248                    }
249                }
250                return Err(VibeTrap::FunctionNotFound);
251            }
252        }
253        // Check if `path` is an exact function canonical_iri in any registered provider
254        let mut slot_idx = 0u32;
255        while (slot_idx as usize) < super::registry::MAX_EXTENSION_PROVIDERS {
256            if let Some(prov) = registry.provider_at(slot_idx) {
257                let desc = prov.descriptor();
258                for sub in desc.sub_namespaces {
259                    for func in sub.functions {
260                        if func.canonical_iri.iri == path {
261                            let handle = prepare_extension_call(
262                                registry,
263                                desc.canonical_iri.iri,
264                                sub.name,
265                                func.name,
266                                SemVerReq::AnyStable,
267                                target_profile,
268                            )?;
269                            cache.insert(path_hash, handle);
270                            return Ok(Some(handle));
271                        }
272                    }
273                }
274            }
275            slot_idx += 1;
276        }
277        return Ok(None);
278    }
279
280    // Case 2: Dotted identifier path (`alias.sub.func` or `alias.func`)
281    let Some((first, tail)) = path.split_once('.') else {
282        return Ok(None);
283    };
284    let ns_key = first.strip_prefix("vibe:0.3/").unwrap_or(first);
285    let Some((_slot, _prov, desc)) = registry.find_by_namespace_or_alias(ns_key) else {
286        return Ok(None);
287    };
288
289    if let Some((sub, func)) = tail.split_once('.') {
290        let handle = prepare_extension_call(
291            registry,
292            ns_key,
293            sub,
294            func,
295            SemVerReq::AnyStable,
296            target_profile,
297        )?;
298        cache.insert(path_hash, handle);
299        return Ok(Some(handle));
300    }
301
302    // 2-segment shorthand `alias.func`: search sub-namespaces for `func`
303    for sub in desc.sub_namespaces {
304        if sub.functions.iter().any(|f| f.name == tail) {
305            let handle = prepare_extension_call(
306                registry,
307                ns_key,
308                sub.name,
309                tail,
310                SemVerReq::AnyStable,
311                target_profile,
312            )?;
313            cache.insert(path_hash, handle);
314            return Ok(Some(handle));
315        }
316    }
317    Err(VibeTrap::FunctionNotFound)
318}
319
320fn split_iri_and_member_suffix<'a>(
321    registry: &ExtensionRegistry<'_>,
322    path: &'a str,
323) -> Option<(&'a str, &'a str)> {
324    let mut slot_idx = 0u32;
325    while (slot_idx as usize) < super::registry::MAX_EXTENSION_PROVIDERS {
326        if let Some(prov) = registry.provider_at(slot_idx) {
327            let ns_iri = prov.descriptor().canonical_iri.iri;
328            if let Some(rest) = path.strip_prefix(ns_iri) {
329                if let Some(dot_rest) = rest.strip_prefix('.') {
330                    return Some((ns_iri, dot_rest));
331                }
332            }
333        }
334        slot_idx += 1;
335    }
336    None
337}
338
339#[repr(C, align(16))]
340struct AlignedScratch<const N: usize>([u8; N]);
341
342const STACK_INPUT_SCRATCH_BYTES: usize = 1024;
343const STACK_OUTPUT_SCRATCH_BYTES: usize = 512;
344const STACK_PARAM_SLOTS: usize = 16;
345
346fn estimate_input_scratch_bytes(func: &FuncDescriptor, args: &[&Value]) -> usize {
347    let mut total = 0usize;
348    for (idx, p) in func.params.iter().enumerate() {
349        let align = p.kind.elem_align();
350        total = (total + align - 1) & !(align - 1);
351        let arg_bytes = match args.get(idx) {
352            Some(Value::String(s) | Value::Iri(s) | Value::Blank(s))
353                if p.kind == PrimitiveKind::Utf8Bytes =>
354            {
355                s.len()
356            }
357            Some(Value::List(xs)) => xs.len().saturating_mul(p.kind.elem_size()),
358            _ => (p.max_elems as usize).saturating_mul(p.kind.elem_size()),
359        };
360        total = total.saturating_add(arg_bytes.max(p.kind.elem_size()));
361    }
362    if func.params.len() == 1 && args.len() > 1 {
363        let elem = func.params[0].kind.elem_size();
364        total = total.max(args.len().saturating_mul(elem));
365    }
366    total
367}
368
369/// Executes a resolved `PreparedCallHandle` by marshaling `pos_args` into stack-allocated
370/// `BorrowedSliceView`s (with descriptor-driven overflow sizing when needed), invoking
371/// `dispatch_prepared_call`, charging `budget`, and decoding `CallerOutputSlice` back to a `Value`.
372pub fn execute_prepared_value_call<'g>(
373    registry: &ExtensionRegistry<'_>,
374    handle: &PreparedCallHandle,
375    ctx: &CallExecutionContext,
376    gate: Option<&mut (dyn SentinelPolicyGate + 'g)>,
377    pos_args: &[Value],
378    budget: &mut Budget,
379    span: Span,
380    path_label: &str,
381) -> Result<(Value, DispatchOutcome), Diagnostic> {
382    let (_provider, func) = registry
383        .resolve_opcode(handle.opcode)
384        .map_err(|t| trap_to_diagnostic(t, path_label, span))?;
385
386    // Unpack record-style payload if called via `capability.invoke(id, { ... })`
387    // without shifting positional indices when keys are missing.
388    let mut stack_refs: [&Value; STACK_PARAM_SLOTS] = [const { &Value::Null }; STACK_PARAM_SLOTS];
389    let mut overflow_refs: Vec<&Value> = Vec::new();
390    let effective_args: &[&Value] = if pos_args.len() == 1 {
391        if let Value::Record(rec) = &pos_args[0] {
392            if func.params.len() == 1
393                && !rec.contains_key(func.params[0].name)
394                && func.params[0].kind == PrimitiveKind::ResourceHandle
395            {
396                stack_refs[0] = &pos_args[0];
397                &stack_refs[..1]
398            } else if func.params.len() <= STACK_PARAM_SLOTS {
399                for (idx, p) in func.params.iter().enumerate() {
400                    let v = rec.get(p.name).ok_or_else(|| {
401                        trap_to_diagnostic(VibeTrap::ArityMismatch, path_label, span)
402                    })?;
403                    stack_refs[idx] = v;
404                }
405                &stack_refs[..func.params.len()]
406            } else {
407                overflow_refs.reserve_exact(func.params.len());
408                for p in func.params {
409                    let v = rec.get(p.name).ok_or_else(|| {
410                        trap_to_diagnostic(VibeTrap::ArityMismatch, path_label, span)
411                    })?;
412                    overflow_refs.push(v);
413                }
414                &overflow_refs
415            }
416        } else {
417            stack_refs[0] = &pos_args[0];
418            &stack_refs[..1]
419        }
420    } else if pos_args.len() <= STACK_PARAM_SLOTS {
421        for (idx, v) in pos_args.iter().enumerate() {
422            stack_refs[idx] = v;
423        }
424        &stack_refs[..pos_args.len()]
425    } else {
426        overflow_refs = pos_args.iter().collect();
427        &overflow_refs
428    };
429
430    // Descriptor-driven input scratch sizing (zero-heap stack path for bounded calls)
431    let needed_in = estimate_input_scratch_bytes(func, effective_args);
432    let mut stack_in = AlignedScratch([0u8; STACK_INPUT_SCRATCH_BYTES]);
433    let mut heap_in: Vec<u8> = Vec::new();
434    let input_scratch: &mut [u8] = if needed_in <= STACK_INPUT_SCRATCH_BYTES {
435        &mut stack_in.0
436    } else {
437        heap_in.resize(needed_in, 0);
438        &mut heap_in
439    };
440
441    let mut stack_offsets = [(0usize, 0usize, PrimitiveKind::U8, 0usize); STACK_PARAM_SLOTS];
442    let mut heap_offsets = Vec::new();
443    let param_offsets: &mut [(usize, usize, PrimitiveKind, usize)] =
444        if func.params.len() <= STACK_PARAM_SLOTS {
445            &mut stack_offsets[..func.params.len()]
446        } else {
447            heap_offsets.resize(func.params.len(), (0, 0, PrimitiveKind::U8, 0));
448            &mut heap_offsets
449        };
450
451    super::scalar_compat::marshal_args_into_scratch(
452        func,
453        effective_args,
454        input_scratch,
455        param_offsets,
456    )
457    .map_err(|t| trap_to_diagnostic(t, path_label, span))?;
458
459    let empty_view = BorrowedSliceView::from_raw_bytes(&[], PrimitiveKind::U8, 0)
460        .expect("empty view");
461    let mut stack_views = [empty_view; STACK_PARAM_SLOTS];
462    let mut heap_views = Vec::new();
463    let view_slice: &mut [BorrowedSliceView<'_>] = if func.params.len() <= STACK_PARAM_SLOTS {
464        &mut stack_views[..func.params.len()]
465    } else {
466        heap_views.resize(func.params.len(), empty_view);
467        &mut heap_views
468    };
469    for idx in 0..func.params.len() {
470        let (start, end, kind, elems) = param_offsets[idx];
471        view_slice[idx] =
472            BorrowedSliceView::from_raw_bytes(&input_scratch[start..end], kind, elems)
473                .map_err(|t| trap_to_diagnostic(t, path_label, span))?;
474    }
475
476    let out_elem_size = func.output_kind.elem_size();
477    let out_byte_cap = (func.required_output_elems as usize)
478        .saturating_mul(out_elem_size)
479        .max(out_elem_size);
480    let mut stack_out = AlignedScratch([0u8; STACK_OUTPUT_SCRATCH_BYTES]);
481    let mut heap_out: Vec<u8> = Vec::new();
482    let out_buf: &mut [u8] = if out_byte_cap <= STACK_OUTPUT_SCRATCH_BYTES {
483        &mut stack_out.0[..out_byte_cap]
484    } else {
485        heap_out.resize(out_byte_cap, 0);
486        &mut heap_out
487    };
488    let mut out_slice = CallerOutputSlice::new(out_buf, func.output_kind)
489        .map_err(|t| trap_to_diagnostic(t, path_label, span))?;
490
491    let outcome = dispatch_prepared_call(
492        registry,
493        handle,
494        ctx,
495        gate,
496        view_slice,
497        &mut out_slice,
498    )
499    .map_err(|t| trap_to_diagnostic(t, path_label, span))?;
500
501    budget.charge(outcome.ticks_consumed, span)?;
502    let result_val = decode_output_slice(func, &out_slice)
503        .map_err(|t| trap_to_diagnostic(t, path_label, span))?;
504
505    Ok((result_val, outcome))
506}
507
508fn decode_output_slice(
509    func: &FuncDescriptor,
510    out: &CallerOutputSlice<'_>,
511) -> Result<Value, VibeTrap> {
512    let count = out.written_elems();
513    let view =
514        BorrowedSliceView::from_raw_bytes(out.written_byte_slice(), func.output_kind, count)?;
515    if func.output_kind == PrimitiveKind::Utf8Bytes {
516        let s = view.read_utf8_str()?;
517        return Ok(Value::String(s.to_owned()));
518    }
519    if count == 1 {
520        return decode_single_elem(&view, 0);
521    }
522    let mut items = Vec::with_capacity(count);
523    for i in 0..count {
524        items.push(decode_single_elem(&view, i)?);
525    }
526    Ok(Value::List(items))
527}
528
529fn decode_single_elem(view: &BorrowedSliceView<'_>, idx: usize) -> Result<Value, VibeTrap> {
530    match view.kind() {
531        PrimitiveKind::F64 => Ok(Value::F64(view.read_f64_le(idx)?)),
532        PrimitiveKind::F32 => Ok(Value::F64(view.read_f32_le(idx)? as f64)),
533        PrimitiveKind::I64 => Ok(Value::I64(view.read_i64_le(idx)?)),
534        PrimitiveKind::I32 => Ok(Value::I64(i64::from(view.read_i32_le(idx)?))),
535        PrimitiveKind::U64 => Ok(Value::U64(view.read_u64_le(idx)?)),
536        PrimitiveKind::U32 => Ok(Value::U64(view.read_u32_le(idx)? as u64)),
537        PrimitiveKind::Bool => Ok(Value::Bool(view.read_bool(idx)?)),
538        PrimitiveKind::U8 => Ok(Value::U64(u64::from(view.read_u8(idx)?))),
539        PrimitiveKind::NQuin48 => {
540            let q = view.read_nquin(idx)?;
541            Ok(Value::QuinRef(crate::value::QuinRef::from_raw(
542                q.0[0], q.0[1], q.0[2], q.0[3], q.0[4], q.0[5],
543            )))
544        }
545        PrimitiveKind::ResourceHandle => {
546            let h = view.read_resource_handle(idx)?;
547            let mut rec = std::collections::BTreeMap::new();
548            rec.insert(
549                "owner_provider_hash".to_string(),
550                Value::U64(h.owner_provider_hash),
551            );
552            rec.insert("kind".to_string(), Value::U64(u64::from(h.kind)));
553            rec.insert("flags".to_string(), Value::U64(u64::from(h.flags)));
554            rec.insert("generation".to_string(), Value::U64(u64::from(h.generation)));
555            rec.insert("slot".to_string(), Value::U64(u64::from(h.slot)));
556            rec.insert("reserved".to_string(), Value::U64(u64::from(h.reserved)));
557            Ok(Value::Record(rec))
558        }
559        PrimitiveKind::Utf8Bytes => {
560            let s = view.read_utf8_str()?;
561            Ok(Value::String(s.to_owned()))
562        }
563    }
564}
565
566/// Unified host and extension call router used by `eval`, `bytecode`, and `task_scheduler`.
567pub fn route_call<'g, H: Host>(
568    host: &mut H,
569    registry: &ExtensionRegistry<'_>,
570    cache: &mut PreparedCallCache,
571    ctx: &CallExecutionContext,
572    gate: Option<&mut (dyn SentinelPolicyGate + 'g)>,
573    last_outcome: &mut Option<DispatchOutcome>,
574    budget: &mut Budget,
575    path: &str,
576    pos_args: &[Value],
577    named_args: &[(String, Value)],
578    span: Span,
579) -> Result<Value, Diagnostic> {
580    let target_profile = match host.environment() {
581        crate::bind::HostEnvironment::NativeDesktop => TargetProfileMask::NATIVE_DESKTOP,
582        crate::bind::HostEnvironment::WasmSandbox => TargetProfileMask::WASM_SANDBOX,
583    };
584
585    // 1. Intercept `capability.invoke` when its target ID is a registered extension path/IRI
586    if path == "capability.invoke" {
587        if let Some(Value::String(target_id) | Value::Iri(target_id)) = pos_args.first() {
588            if let Some(handle) = try_prepare_path(registry, cache, target_id, target_profile)
589                .map_err(|t| trap_to_diagnostic(t, target_id, span))?
590            {
591                let payload_slice = if pos_args.len() > 1 {
592                    &pos_args[1..]
593                } else {
594                    &[]
595                };
596                let (val, outcome) = execute_prepared_value_call(
597                    registry,
598                    &handle,
599                    ctx,
600                    gate,
601                    payload_slice,
602                    budget,
603                    span,
604                    target_id,
605                )?;
606                *last_outcome = Some(outcome);
607                return Ok(val);
608            }
609        }
610    }
611
612    // 2. Check if `path` resolves directly to a registered `VibeNamespaceProvider` function
613    match try_prepare_path(registry, cache, path, target_profile) {
614        Ok(Some(handle)) => {
615            let (val, outcome) = execute_prepared_value_call(
616                registry, &handle, ctx, gate, pos_args, budget, span, path,
617            )?;
618            *last_outcome = Some(outcome);
619            return Ok(val);
620        }
621        Ok(None) => {}
622        Err(t) => return Err(trap_to_diagnostic(t, path, span)),
623    }
624
625    // 3. Otherwise route to built-in host capabilities (`math.*`, `graph.*`, `time.*`, etc.).
626    match ctx.mode {
627        ExecutionMode::StandaloneDeveloper => {
628            native_budget::dispatch(host, path, pos_args, named_args, span, budget)
629        }
630        ExecutionMode::GovernedApplication
631        | ExecutionMode::SimulatedGovernanceTest
632        | ExecutionMode::IntegratedGovernanceTest => {
633            let policy_gate = gate.ok_or_else(|| {
634                trap_to_diagnostic(VibeTrap::SentinelUnavailable, path, span)
635            })?;
636            if !policy_gate.is_controller_alive() {
637                return Err(trap_to_diagnostic(
638                    VibeTrap::SentinelUnavailable,
639                    path,
640                    span,
641                ));
642            }
643            let func_hash = q_hash_str(path);
644            let native_provider_hash = q_hash_str("vibe:native");
645            let native_handle = PreparedCallHandle {
646                opcode: VibeOpCode(0),
647                registry_generation: registry.generation(),
648                reserved: 0,
649                provider_iri_hash: native_provider_hash,
650                func_iri_hash: func_hash,
651                contract_digest: [0u8; 32],
652            };
653            let req_effects = if path.starts_with("math.") {
654                EffectSet::PURE_COMPUTE
655            } else if path == "graph.stage" || path == "graph.commit" {
656                EffectSet::GRAPH_MUTATE
657            } else {
658                EffectSet::GRAPH_READ
659            };
660            let req = AdmissionRequest {
661                handle: native_handle,
662                actor_did_hash: ctx.actor_did_hash,
663                context_world_hash: ctx.context_world_hash,
664                lamport_timestamp: ctx.lamport_timestamp,
665                mode: ctx.mode,
666                requested_effects: req_effects,
667                declared_envelope: ResourceEnvelope::hot_zero_heap(1000, 4096),
668                input_fingerprint: func_hash ^ (pos_args.len() as u64),
669            };
670            let ticket = policy_gate
671                .admit_call(&req)
672                .map_err(|t| trap_to_diagnostic(t, path, span))?;
673            if ctx.lamport_timestamp > ticket.expiry_lamport {
674                return Err(trap_to_diagnostic(VibeTrap::AuthorityExpired, path, span));
675            }
676            match native_budget::dispatch(host, path, pos_args, named_args, span, budget) {
677                Ok(val) => {
678                    policy_gate
679                        .validate_post_execution(&ticket, native_handle.opcode, 1, 0, func_hash)
680                        .map_err(|t| trap_to_diagnostic(t, path, span))?;
681                    let (status, simulated) = match ctx.mode {
682                        ExecutionMode::SimulatedGovernanceTest => {
683                            (CompletionStatus::SimulatedCommitted, true)
684                        }
685                        _ => (CompletionStatus::Committed, ticket.simulated),
686                    };
687                    let receipt = ExecutionReceiptHeader {
688                        ticket_id: ticket.ticket_id,
689                        actor_did_hash: ctx.actor_did_hash,
690                        provider_iri_hash: native_provider_hash,
691                        func_iri_hash: func_hash,
692                        stable_id: StableFuncId {
693                            sub_namespace_id: 0,
694                            func_id: 0,
695                        },
696                        mode: ctx.mode,
697                        status,
698                        simulated,
699                        reserved: [0; 5],
700                        policy_generation: ticket.policy_generation,
701                        registry_generation: registry.generation(),
702                        ticks_consumed: 1,
703                        output_bytes_written: 0,
704                        trap_code: 0,
705                        failure_stage: 0,
706                        input_output_fold_hash: func_hash,
707                        lamport_timestamp: ctx.lamport_timestamp,
708                    };
709                    let audit_nquins = policy_gate
710                        .commit_receipt(&receipt)
711                        .map_err(|t| trap_to_diagnostic(t, path, span))?;
712                    *last_outcome = Some(DispatchOutcome {
713                        ticks_consumed: 1,
714                        output_elems_written: 0,
715                        output_bytes_written: 0,
716                        receipt,
717                        audit_nquins,
718                    });
719                    Ok(val)
720                }
721                Err(diag) => {
722                    let abort_receipt = ExecutionReceiptHeader {
723                        ticket_id: ticket.ticket_id,
724                        actor_did_hash: ctx.actor_did_hash,
725                        provider_iri_hash: native_provider_hash,
726                        func_iri_hash: func_hash,
727                        stable_id: StableFuncId {
728                            sub_namespace_id: 0,
729                            func_id: 0,
730                        },
731                        mode: ctx.mode,
732                        status: CompletionStatus::TrappedExecution,
733                        simulated: ticket.simulated
734                            || ctx.mode == ExecutionMode::SimulatedGovernanceTest,
735                        reserved: [0; 5],
736                        policy_generation: ticket.policy_generation,
737                        registry_generation: registry.generation(),
738                        ticks_consumed: 0,
739                        output_bytes_written: 0,
740                        trap_code: 0,
741                        failure_stage: 4,
742                        input_output_fold_hash: func_hash,
743                        lamport_timestamp: ctx.lamport_timestamp,
744                    };
745                    policy_gate
746                        .commit_receipt(&abort_receipt)
747                        .map_err(|t| trap_to_diagnostic(t, path, span))?;
748                    Err(diag)
749                }
750            }
751        }
752    }
753}
754
755#[cfg(test)]
756mod up02_eval_router_tests {
757    use super::*;
758    use crate::bind::LocalHost;
759    use crate::budget::Budget;
760    use etalon_vibe::{
761        oracle_bioelectric_dipole_preview, oracle_decode_container_summary,
762        oracle_dicom_modality_check, oracle_evaluate_directivity_sh,
763        oracle_radiative_transfer_slice, oracle_render_binaural_frame,
764        oracle_sh_irradiance_probe, oracle_sonify_emf_envelope, oracle_verify_evidence_gate,
765    };
766
767    fn eval_route(path: &str, pos_args: &[Value]) -> Result<Value, Diagnostic> {
768        let mut host = LocalHost::default();
769        let registry = ExtensionRegistry::with_builtin_providers();
770        let mut cache = PreparedCallCache::new();
771        let actor = q_hash_str("did:q42:local_engine");
772        let ctx = CallExecutionContext {
773            actor_did_hash: actor,
774            context_world_hash: 1,
775            lamport_timestamp: 1,
776            mode: ExecutionMode::SimulatedGovernanceTest,
777        };
778        let mut sim_gate = super::super::dispatch_adapter::SimulatedPolicyGate::new_for_actor(actor);
779        sim_gate.budget.max_scratch_bytes = 1_048_576;
780        sim_gate.budget.max_vram_bytes = 1_048_576;
781        let mut last_outcome = None;
782        let mut budget = Budget::default();
783        route_call(
784            &mut host,
785            &registry,
786            &mut cache,
787            &ctx,
788            Some(&mut sim_gate),
789            &mut last_outcome,
790            &mut budget,
791            path,
792            pos_args,
793            &[],
794            Span::new(0, 0),
795        )
796    }
797
798    fn f32_list(vals: &[f32]) -> Value {
799        Value::List(vals.iter().map(|&v| Value::F64(f64::from(v))).collect())
800    }
801
802    fn f64_list(vals: &[f64]) -> Value {
803        Value::List(vals.iter().map(|&v| Value::F64(v)).collect())
804    }
805
806    fn u32_list(vals: &[u32]) -> Value {
807        Value::List(vals.iter().map(|&v| Value::U64(u64::from(v))).collect())
808    }
809
810    fn u64_list(vals: &[u64]) -> Value {
811        Value::List(vals.iter().map(|&v| Value::U64(v)).collect())
812    }
813
814    fn assert_f32_slice_eq(actual: Value, expected: &[f32]) {
815        match actual {
816            Value::List(xs) => {
817                assert_eq!(xs.len(), expected.len());
818                for (a, &e) in xs.iter().zip(expected.iter()) {
819                    let av = a.as_f64().expect("expected numeric Value") as f32;
820                    assert!(
821                        (av - e).abs() <= 1e-6,
822                        "mismatch: actual={av}, expected={e}"
823                    );
824                }
825            }
826            other => panic!("expected Value::List, got {other:?}"),
827        }
828    }
829
830    #[test]
831    fn up01_render_emf_routes_and_traps_on_invalid_args() {
832        let dipole = [1.0f32, 2.0, -0.5];
833        let probe = [0.1f32, 0.2, 0.3];
834        let gain = 2.0f32;
835        let res = eval_route(
836            "render.emf.bioelectric_dipole_preview",
837            &[f32_list(&dipole), f32_list(&probe), Value::F64(f64::from(gain))],
838        )
839        .expect("bioelectric_dipole_preview evaluates");
840        let exp = oracle_bioelectric_dipole_preview(dipole, probe, gain).unwrap();
841        assert_f32_slice_eq(res, &exp);
842        assert!(eval_route(
843            "render.emf.bioelectric_dipole_preview",
844            &[f32_list(&dipole), f32_list(&[0.0, 0.0, 0.0]), Value::F64(1.0)],
845        )
846        .is_err());
847        assert!(eval_route(
848            "render.emf.bioelectric_dipole_preview",
849            &[f32_list(&[1.0, 2.0]), f32_list(&probe), Value::F64(1.0)],
850        )
851        .is_err());
852
853        let opt = [0.5f32, 0.8, 0.4];
854        let inc = 12.0f32;
855        let res = eval_route(
856            "render.emf.radiative_transfer_slice",
857            &[f32_list(&opt), Value::F64(f64::from(inc))],
858        )
859        .expect("radiative_transfer_slice evaluates");
860        let exp = oracle_radiative_transfer_slice(opt, inc).unwrap();
861        assert_f32_slice_eq(res, &exp);
862        assert!(eval_route(
863            "render.emf.radiative_transfer_slice",
864            &[f32_list(&[-0.1, 0.5, 0.0]), Value::F64(1.0)],
865        )
866        .is_err());
867
868        let sh = [1.0f32, 0.2, -0.1, 0.3];
869        let norm = [0.0f32, 1.0, 0.0];
870        let res = eval_route(
871            "render.emf.sh_irradiance_probe",
872            &[f32_list(&sh), f32_list(&norm)],
873        )
874        .expect("sh_irradiance_probe evaluates");
875        let exp = oracle_sh_irradiance_probe(sh, norm).unwrap();
876        assert_f32_slice_eq(res, &exp);
877        assert!(eval_route(
878            "render.emf.sh_irradiance_probe",
879            &[f32_list(&sh), f32_list(&[0.0, 0.0, 0.0])],
880        )
881        .is_err());
882    }
883
884    #[test]
885    fn up01_signal_qac_routes_and_traps_on_invalid_args() {
886        let meta = [4u32, 48_000, 1024, 0x05];
887        let res = eval_route("signal.qac.decode_container_summary", &[u32_list(&meta)])
888            .expect("decode_container_summary evaluates");
889        let exp = oracle_decode_container_summary(meta).unwrap();
890        assert_eq!(res, Value::List(vec![Value::U64(exp[0]), Value::U64(exp[1])]));
891        assert!(eval_route(
892            "signal.qac.decode_container_summary",
893            &[u32_list(&[0, 48_000, 1024, 0x05])],
894        )
895        .is_err());
896        assert!(eval_route(
897            "signal.qac.decode_container_summary",
898            &[u32_list(&[4, 48_000, 1024, 0x10])],
899        )
900        .is_err());
901
902        let pose = [30.0f32, 10.0, 2.0];
903        let gain_lin = 0.75f32;
904        let res = eval_route(
905            "signal.qac.render_binaural_frame",
906            &[f32_list(&pose), Value::F64(f64::from(gain_lin))],
907        )
908        .expect("render_binaural_frame evaluates");
909        let exp = oracle_render_binaural_frame(pose, gain_lin).unwrap();
910        assert_f32_slice_eq(res, &exp);
911        assert!(eval_route(
912            "signal.qac.render_binaural_frame",
913            &[f32_list(&[30.0, 10.0, 0.01]), Value::F64(1.0)],
914        )
915        .is_err());
916
917        let angles = [0.4f32, 0.2];
918        let weights = [1.0f32, 0.25, -0.1, 0.15];
919        let res = eval_route(
920            "signal.qac.evaluate_directivity_sh",
921            &[f32_list(&angles), f32_list(&weights)],
922        )
923        .expect("evaluate_directivity_sh evaluates");
924        let exp = oracle_evaluate_directivity_sh(angles, weights).unwrap();
925        assert_f32_slice_eq(res, &exp);
926        assert!(eval_route(
927            "signal.qac.evaluate_directivity_sh",
928            &[f32_list(&[0.0, 2.5]), f32_list(&weights)],
929        )
930        .is_err());
931
932        let emf = [550.0f64, 1.5, 0.8];
933        let res = eval_route("signal.qac.sonify_emf_envelope", &[f64_list(&emf)])
934            .expect("sonify_emf_envelope evaluates");
935        let exp = oracle_sonify_emf_envelope(emf).unwrap();
936        match res {
937            Value::List(xs) => {
938                assert_eq!(xs.len(), 2);
939                assert!((xs[0].as_f64().unwrap() - exp[0]).abs() <= 1e-9);
940                assert!((xs[1].as_f64().unwrap() - exp[1]).abs() <= 1e-9);
941            }
942            other => panic!("expected Value::List, got {other:?}"),
943        }
944        assert!(eval_route(
945            "signal.qac.sonify_emf_envelope",
946            &[f64_list(&[300.0, 1.5, 0.8])],
947        )
948        .is_err());
949    }
950
951    #[test]
952    fn up01_sense_authority_routes_and_traps_on_invalid_args() {
953        let gate = [0b11u64, 500, 1000, 0x03];
954        let res = eval_route("sense.authority.verify_evidence_gate", &[u64_list(&gate)])
955            .expect("verify_evidence_gate evaluates");
956        let exp = oracle_verify_evidence_gate(gate).unwrap();
957        assert_eq!(res, Value::List(vec![Value::U64(exp[0]), Value::U64(exp[1])]));
958        assert!(eval_route(
959            "sense.authority.verify_evidence_gate",
960            &[u64_list(&[0, 500, 1000, 0x03])],
961        )
962        .is_err());
963        assert!(eval_route(
964            "sense.authority.verify_evidence_gate",
965            &[u64_list(&[1, 500, 1000, 0x04])],
966        )
967        .is_err());
968
969        let dicom = [2u32, 12, 1];
970        let res = eval_route("sense.authority.dicom_modality_check", &[u32_list(&dicom)])
971            .expect("dicom_modality_check evaluates");
972        let exp = oracle_dicom_modality_check(dicom).unwrap();
973        assert_eq!(
974            res,
975            Value::List(vec![Value::U64(u64::from(exp[0])), Value::U64(u64::from(exp[1]))])
976        );
977        assert!(eval_route(
978            "sense.authority.dicom_modality_check",
979            &[u32_list(&[9, 12, 1])],
980        )
981        .is_err());
982    }
983}