Skip to main content

qualia_core_db/governance/webizen/
vm.rs

1use super::*;
2
3#[cfg(feature = "alloc_buffers")]
4extern crate alloc;
5
6/// The Execution Frame tracking variable bindings without touching the heap
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
8pub struct VmFrame {
9    pub subject_reg: u64,
10    pub predicate_reg: u64,
11    pub object_reg: u64,
12    pub context_reg: u64,
13}
14
15#[inline]
16fn frame_to_quin(frame: &VmFrame) -> NQuin {
17    let mut q = NQuin {
18        subject: frame.subject_reg,
19        predicate: frame.predicate_reg,
20        object: frame.object_reg,
21        context: frame.context_reg,
22        metadata: 1,
23        parity: 0,
24    };
25    q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
26    q
27}
28
29#[inline]
30fn current_unix32() -> u32 {
31    std::time::SystemTime::now()
32        .duration_since(std::time::UNIX_EPOCH)
33        .map(|d| d.as_secs() as u32)
34        .unwrap_or(0)
35}
36
37#[inline]
38fn rdf_type_hash() -> u64 {
39    crate::lexicon::generate_60bit_token(b"http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
40}
41
42/// Returns true when `node` has `rdf:type` = `class_hash` in the arena.
43fn node_has_class(arena: &SlgArena, node: u64, class_hash: u64) -> bool {
44    if node == 0 || class_hash == 0 {
45        return false;
46    }
47    let rdf_type = rdf_type_hash();
48    let mut scratch = [NQuin::default(); 256];
49    let count = arena.collect_active_quins(&mut scratch);
50    for q in &scratch[..count] {
51        if q.subject == node && q.predicate == rdf_type && q.object == class_hash {
52            return true;
53        }
54    }
55    false
56}
57
58fn unify_frame(arena: &SlgArena, frame: &mut VmFrame) -> bool {
59    if arena
60        .check_table(frame.subject_reg, frame.predicate_reg, frame.object_reg)
61        .is_some()
62    {
63        return true;
64    }
65
66    let mut scratch = [NQuin::default(); 256];
67    let count = arena.collect_active_quins(&mut scratch);
68    for q in &scratch[..count] {
69        let subject_ok = frame.subject_reg == 0 || q.subject == frame.subject_reg;
70        let predicate_ok = frame.predicate_reg == 0 || q.predicate == frame.predicate_reg;
71        let object_ok = frame.object_reg == 0 || q.object == frame.object_reg;
72        if subject_ok && predicate_ok && object_ok {
73            frame.subject_reg = q.subject;
74            frame.predicate_reg = q.predicate;
75            frame.object_reg = q.object;
76            frame.context_reg = q.context;
77            return true;
78        }
79    }
80
81    frame.subject_reg != 0 && frame.predicate_reg != 0
82}
83
84#[inline(never)]
85fn execute_manifold_ltl(
86    arena: &SlgArena,
87    mode: u8,
88    dimension: u8,
89    threshold_bits: u32,
90    at_least: bool,
91) -> bool {
92    let Some(dimension) = manifold::ManifoldDimension::from_u8(dimension) else {
93        return false;
94    };
95    let threshold = f32::from_bits(threshold_bits);
96    if !threshold.is_finite() {
97        return false;
98    }
99    let mut snapshot = [NQuin::default(); 512];
100    let snapshot_count = arena.collect_active_quins(&mut snapshot);
101    let mut states = [manifold::ManifoldState10D::default(); 128];
102    let state_count = manifold::collect_manifold_states(&snapshot[..snapshot_count], &mut states);
103    let mut trace = [NQuin::default(); 128];
104    let trace_count = manifold::project_manifold_ltl_trace(
105        &states[..state_count],
106        dimension,
107        threshold,
108        at_least,
109        &mut trace,
110    );
111    let formula = match mode {
112        0 => LtlFormula::Globally(manifold::MANIFOLD_THRESHOLD_HOLDS),
113        1 => LtlFormula::Finally(manifold::MANIFOLD_THRESHOLD_HOLDS),
114        2 => LtlFormula::Next(manifold::MANIFOLD_THRESHOLD_HOLDS),
115        _ => return false,
116    };
117    temporal_ltl::evaluate_ltl_trace(&trace[..trace_count], &formula)
118}
119
120#[inline(never)]
121fn execute_manifold_asp(arena: &SlgArena) -> Option<u64> {
122    let mut snapshot = [NQuin::default(); 512];
123    let snapshot_count = arena.collect_active_quins(&mut snapshot);
124    let mut states = [manifold::ManifoldState10D::default(); 128];
125    let state_count = manifold::collect_manifold_states(&snapshot[..snapshot_count], &mut states);
126    if state_count == 0 {
127        return None;
128    }
129    let mut models = [0u64; asp::MAX_STABLE_MODELS];
130    let model_count = manifold::evaluate_manifold_answer_sets(&states[..state_count], &mut models);
131    (model_count > 0).then(|| models[model_count - 1])
132}
133
134#[inline(never)]
135fn execute_paraconsistent_isolation(arena: &mut SlgArena) -> bool {
136    let mut scratch = [NQuin::default(); 64];
137    let count = arena.collect_active_quins(&mut scratch);
138    if count == 0 {
139        return false;
140    }
141    let mut consistent = [NQuin::default(); 64];
142    let mut isolated = [NQuin::default(); 64];
143    let Ok((_, isolated_count)) =
144        paraconsistent::route_paraconsistent(&scratch[..count], &mut consistent, &mut isolated)
145    else {
146        return false;
147    };
148    for quin in &isolated[..isolated_count] {
149        arena.write_table(*quin);
150    }
151    true
152}
153
154#[inline(never)]
155fn execute_dialectical_synthesis(arena: &mut SlgArena, frame: &mut VmFrame) -> bool {
156    let mut scratch = [NQuin::default(); 64];
157    let count = arena.collect_active_quins(&mut scratch);
158    if count < 2 {
159        return false;
160    }
161    let Some(synthesis) = dialectical::synthesize_dialectical(&scratch[0], &scratch[1]) else {
162        return false;
163    };
164    arena.write_table(synthesis);
165    frame.subject_reg = synthesis.subject;
166    frame.predicate_reg = synthesis.predicate;
167    frame.object_reg = synthesis.object;
168    frame.context_reg = synthesis.context;
169    true
170}
171
172#[inline(never)]
173fn execute_standard_ltl(arena: &SlgArena, opcode: SlgOpcode, frame: &VmFrame) -> bool {
174    let mut scratch = [NQuin::default(); 512];
175    let count = arena.collect_active_quins(&mut scratch);
176    let trace = &mut scratch[..count];
177    trace.reverse();
178    let formula = match opcode {
179        SlgOpcode::NativeLtlGlobally => LtlFormula::Globally(frame.predicate_reg),
180        SlgOpcode::NativeLtlFinally => LtlFormula::Finally(frame.predicate_reg),
181        SlgOpcode::NativeLtlNext => LtlFormula::Next(frame.predicate_reg),
182        SlgOpcode::NativeLtlUntil => LtlFormula::Until {
183            ante: frame.predicate_reg,
184            consequent: frame.object_reg,
185        },
186        SlgOpcode::NativeLtlRelease => LtlFormula::Release {
187            trigger: frame.predicate_reg,
188            invariant: frame.object_reg,
189        },
190        _ => return false,
191    };
192    temporal_ltl::evaluate_ltl_trace(trace, &formula)
193}
194
195#[inline(never)]
196fn execute_snapshot_logic(arena: &SlgArena, opcode: SlgOpcode, frame: &mut VmFrame) -> bool {
197    let mut scratch = [NQuin::default(); 512];
198    let count = arena.collect_active_quins(&mut scratch);
199    let quins = &scratch[..count];
200
201    match opcode {
202        SlgOpcode::CheckDefeaters => {
203            let mut fingerprints = [0u64; MAX_DEFEATER_SLOTS];
204            let fingerprint_count = harvest_defeater_fingerprints(quins, &mut fingerprints);
205            !norm_has_active_defeater(&frame_to_quin(frame), &fingerprints[..fingerprint_count])
206        }
207        SlgOpcode::NativeDeonticEval => {
208            let mut verdicts = [DeonticVerdict::default(); 64];
209            let verdict_count =
210                evaluate_deontic_contract(quins, current_unix32(), &mut verdicts).unwrap_or(0);
211            let goal = frame_to_quin(frame);
212            let valid = verdicts[..verdict_count].iter().all(|verdict| {
213                verdict.norm.subject != goal.subject
214                    || verdict.norm.predicate != goal.predicate
215                    || verdict.norm.object != goal.object
216                    || matches!(verdict.status, DeonticStatus::Active)
217            });
218            vm_log!(
219                "[Webizen] NativeDeonticEval: {} norms evaluated",
220                verdict_count
221            );
222            valid
223        }
224        SlgOpcode::NativeEpistemicEval(min_certainty) => {
225            let mut verdicts = [epistemic::EpistemicVerdict {
226                claim: NQuin::default(),
227                status: epistemic::EpistemicStatus::Skipped,
228                certainty: 0,
229            }; 64];
230            let verdict_count = epistemic::evaluate_epistemic_frame(
231                quins,
232                frame.subject_reg,
233                frame.context_reg,
234                &mut verdicts,
235            )
236            .unwrap_or(0);
237            verdicts[..verdict_count].iter().any(|verdict| {
238                verdict.certainty >= min_certainty
239                    && verdict.status == epistemic::EpistemicStatus::Active
240            })
241        }
242        SlgOpcode::NativeProbabilisticThreshold(threshold_bits) => {
243            let threshold = f32::from_bits(threshold_bits);
244            let weight = quins
245                .iter()
246                .find(|quin| {
247                    quin.subject == frame.subject_reg
248                        && quin.predicate == frame.predicate_reg
249                        && quin.object == frame.object_reg
250                })
251                .map(probabilistic::BayesianNetwork::extract_weight)
252                .unwrap_or(0.0);
253            probabilistic::evaluate_threshold(weight, threshold)
254        }
255        SlgOpcode::NativeDlSubsumption => {
256            dl::check_subsumption_quin(frame.subject_reg, frame.object_reg, quins)
257        }
258        SlgOpcode::NativeArgumentationGrounded => {
259            let asserts = crate::q_hash("arg:asserts");
260            let attacks_predicate = crate::q_hash("arg:attacks");
261            let mut arguments = [0u64; argumentation::MAX_GROUNDED_ARGS];
262            let mut argument_count = 0usize;
263            let mut attacks = [(0u64, 0u64); 256];
264            let mut attack_count = 0usize;
265            for quin in quins {
266                if quin.predicate == asserts && argument_count < arguments.len() {
267                    arguments[argument_count] = quin.subject;
268                    argument_count += 1;
269                } else if quin.predicate == attacks_predicate && attack_count < attacks.len() {
270                    attacks[attack_count] = (quin.subject, quin.object);
271                    attack_count += 1;
272                }
273            }
274            argumentation::grounded_contains(
275                &arguments[..argument_count],
276                &attacks[..attack_count],
277                frame.subject_reg,
278            )
279        }
280        SlgOpcode::NativeMtlWithin(window) => {
281            temporal_ltl::holds_within(quins, frame.predicate_reg, frame.object_reg, window as u64)
282        }
283        SlgOpcode::NativeContraryToDuty => {
284            crate::modalities::logic::deontic::evaluate_contrary_to_duty(
285                quins,
286                frame.subject_reg,
287                frame.predicate_reg,
288                frame.object_reg,
289            )
290        }
291        SlgOpcode::NativeCausalNecessary => dialectical::is_necessary_cause(
292            quins,
293            frame.context_reg,
294            frame.subject_reg,
295            frame.object_reg,
296        ),
297        SlgOpcode::NativeAbduce => {
298            let explains = crate::q_hash("abduces:explains");
299            if let Some(hypothesis) =
300                abductive::abductive_explanation(quins, frame.object_reg, explains)
301            {
302                frame.subject_reg = hypothesis;
303                true
304            } else {
305                false
306            }
307        }
308        SlgOpcode::NativeClosedWorld => defeasible::holds_by_default(quins, &frame_to_quin(frame)),
309        SlgOpcode::NativeFuzzyConjunction(threshold_bits) => {
310            let threshold = f32::from_bits(threshold_bits);
311            let mut accumulated = 1.0f32;
312            let mut found = false;
313            for quin in quins {
314                if quin.predicate == frame.predicate_reg {
315                    accumulated = fuzzy::t_norm_godel(accumulated, fuzzy::degree(quin));
316                    found = true;
317                }
318            }
319            found && accumulated >= threshold
320        }
321        SlgOpcode::NativeCtlExistsFinally => ctl::exists_finally(
322            quins,
323            frame.subject_reg,
324            frame.object_reg,
325            crate::q_hash("ctl:next"),
326            crate::q_hash("ctl:holds"),
327        ),
328        SlgOpcode::NativeCtlAlwaysGlobally => ctl::always_globally(
329            quins,
330            frame.subject_reg,
331            frame.object_reg,
332            crate::q_hash("ctl:next"),
333            crate::q_hash("ctl:holds"),
334        ),
335        SlgOpcode::NativeModalNecessary => modal::necessary(
336            quins,
337            frame.subject_reg,
338            frame.object_reg,
339            crate::q_hash("modal:accesses"),
340            crate::q_hash("modal:holds"),
341        ),
342        SlgOpcode::NativeModalPossible => modal::possible(
343            quins,
344            frame.subject_reg,
345            frame.object_reg,
346            crate::q_hash("modal:accesses"),
347            crate::q_hash("modal:holds"),
348        ),
349        SlgOpcode::NativeRcc8(expected) | SlgOpcode::NativeRcc8Assert(expected) => {
350            let boundary = crate::q_hash("spatial:boundary");
351            let mut region_a = [(0.0f64, 0.0f64); spatio_temporal::MAX_BOUNDARY_POINTS];
352            let mut region_a_count = 0usize;
353            let mut region_b = [(0.0f64, 0.0f64); spatio_temporal::MAX_BOUNDARY_POINTS];
354            let mut region_b_count = 0usize;
355            for quin in quins {
356                if quin.predicate != boundary {
357                    continue;
358                }
359                let index = quin.metadata as usize;
360                if index >= spatio_temporal::MAX_BOUNDARY_POINTS {
361                    continue;
362                }
363                if quin.subject == frame.subject_reg {
364                    region_a[index] = spatio_temporal::unpack_point(quin.object);
365                    region_a_count = region_a_count.max(index + 1);
366                } else if quin.subject == frame.object_reg {
367                    region_b[index] = spatio_temporal::unpack_point(quin.object);
368                    region_b_count = region_b_count.max(index + 1);
369                }
370            }
371            spatio_temporal::evaluate_rcc8_points(
372                frame.subject_reg,
373                &region_a[..region_a_count],
374                frame.object_reg,
375                &region_b[..region_b_count],
376            ) as u8
377                == expected
378        }
379        _ => false,
380    }
381}
382
383/// The Bytecode Evaluator for the Prolog Webizen
384pub fn execute_vm_frame(
385    arena: &mut SlgArena,
386    bytecode: &[SlgOpcode],
387    frame: &mut VmFrame,
388) -> Option<NQuin> {
389    let mut instruction_pointer = 0;
390
391    while instruction_pointer < bytecode.len() {
392        let opcode = bytecode[instruction_pointer];
393
394        match opcode {
395            SlgOpcode::CheckTable => {
396                // Hashing the current sub-goal to query the SlgArena
397                if let Some(cached_result) =
398                    arena.check_table(frame.subject_reg, frame.predicate_reg, frame.object_reg)
399                {
400                    // Match found! Push the cached result to the VM stack and bypass the graph traversal
401                    return Some(cached_result);
402                }
403            }
404            SlgOpcode::CheckDefeaters => {
405                if !execute_snapshot_logic(arena, opcode, frame) {
406                    return None;
407                }
408            }
409            SlgOpcode::CheckSubsumption => {
410                let is_subsumed =
411                    dl::check_subsumption_quin(frame.subject_reg, frame.object_reg, &[]);
412                if !is_subsumed {
413                    return None;
414                }
415            }
416            SlgOpcode::BranchWorld => {
417                let mut out_worlds = [0; asp::MAX_STABLE_MODELS];
418                let goal = frame_to_quin(frame);
419                let _count = asp::enumerate_stable_models(&goal, &[], &mut out_worlds);
420            }
421            SlgOpcode::CheckThreshold => {
422                let meets_threshold = probabilistic::evaluate_threshold(0.5, 0.8);
423                if !meets_threshold {
424                    return None;
425                }
426            }
427            SlgOpcode::ConsumeFact => {
428                if let Some(q) = arena.find_mutable_quin(
429                    frame.subject_reg,
430                    frame.predicate_reg,
431                    frame.object_reg,
432                ) {
433                    linear::consume_quin(q);
434                } else {
435                    return None;
436                }
437            }
438            SlgOpcode::ZkConsumeFact => {
439                // Gate exhaustion on a verified zk-entitlement marker for the resource's subject.
440                let proof_verified = arena
441                    .find_mutable_quin(
442                        frame.subject_reg,
443                        crate::q_hash("q42:zkVerified"),
444                        crate::q_hash("q42:true"),
445                    )
446                    .is_some();
447                if let Some(q) = arena.find_mutable_quin(
448                    frame.subject_reg,
449                    frame.predicate_reg,
450                    frame.object_reg,
451                ) {
452                    // Linear (consume-once) cryptographic token, gated on the zk proof.
453                    if !linear::zk_gated_consume(q, false, proof_verified) {
454                        return None;
455                    }
456                } else {
457                    return None;
458                }
459            }
460            SlgOpcode::Unify => {
461                if !unify_frame(arena, frame) {
462                    return None;
463                }
464            }
465            SlgOpcode::Call => {
466                let result = frame_to_quin(frame);
467                if result.subject == 0 || result.predicate == 0 {
468                    return None;
469                }
470                arena.write_table(result);
471            }
472            SlgOpcode::Return => {
473                return Some(frame_to_quin(frame));
474            }
475            SlgOpcode::ApplyTaxSchema => {
476                // In a full implementation, we'd pull the active Jurisdiction Profile
477                // and amount from the VM frame. For now, we mock the evaluation.
478                let schema = TaxRuleSchema::new_au_gst();
479                let _liability = schema.evaluate("Income", 100.0);
480
481                // We'd store this calculated liability back into the frame
482                // frame.tax_register = liability;
483            }
484            SlgOpcode::Halt => {
485                break;
486            }
487            SlgOpcode::NativeThermodynamics => {
488                // Mock execution of a thermodynamic state MCMC sampler
489                let mut sampler =
490                    crate::domains::physical::thermodynamics::ThermodynamicSampler::new(298.0, 100);
491                sampler.metropolis_step(50.0, 0.5);
492                vm_log!(
493                    "๐Ÿงช Webizen executed NativeThermodynamics step. Current Energy: {}",
494                    sampler.current_state.total_energy
495                );
496            }
497            SlgOpcode::NativeOdeSolver => {
498                // Mock execution of continuous dynamics via RK4
499                #[cfg(feature = "alloc_buffers")]
500                let initial = crate::ode_solver::PhysicalState {
501                    time: 0.0,
502                    values: alloc::vec![1.0],
503                };
504                #[cfg(not(feature = "alloc_buffers"))]
505                let initial = crate::ode_solver::PhysicalState {
506                    time: 0.0,
507                    values: std::vec![1.0],
508                };
509                let final_state = crate::ode_solver::evaluate_continuous_dynamics(initial, 10, 0.1);
510                vm_log!(
511                    "๐Ÿ“ˆ Webizen executed NativeOdeSolver. Final state: {:?}",
512                    final_state.values
513                );
514            }
515            SlgOpcode::NativeRk4Step(packed_params) => {
516                // Unpack parameters: step_size (lower 32 bits) | num_steps (upper 32 bits)
517                let step_size_bits = (packed_params & 0xFFFFFFFF) as u32;
518                let num_steps = (packed_params >> 32) as u32;
519                let step_size = f32::from_bits(step_size_bits) as f64;
520
521                vm_log!(
522                    "๐Ÿ”„ Webizen executing NativeRk4Step: step_size={}, num_steps={}",
523                    step_size,
524                    num_steps
525                );
526
527                // Calculus is a core capability in this crate, so RK4 dispatch stays wired.
528                {
529                    use crate::modalities::calculus::ode_solver::{ExponentialDecay, Rk4Solver};
530
531                    let system = ExponentialDecay::new(0.5);
532                    let mut solver = Rk4Solver::new(system, step_size);
533
534                    // Execute chained RK4 steps
535                    let mut quin = frame_to_quin(frame);
536                    for _ in 0..num_steps {
537                        quin = solver.step_quin(quin, step_size);
538                    }
539
540                    frame.subject_reg = quin.subject;
541                    frame.predicate_reg = quin.predicate;
542                    frame.object_reg = quin.object;
543                    frame.context_reg = quin.context;
544
545                    vm_log!(
546                        "โœ… Webizen completed {} RK4 steps. Final state: t={}, y={}",
547                        num_steps,
548                        f64::from_bits(quin.metadata),
549                        f64::from_bits(quin.object)
550                    );
551                }
552
553                /* Legacy fallback removed: calculus is always available in this crate.
554                    vm_log!("โš ๏ธ  Calculus feature not enabled, RK4 step skipped");
555                */
556            }
557            SlgOpcode::NativeQuantumDft => {
558                // Mock execution of Kohn-Sham density functional approximation
559                let mut dft = crate::quantum_dft::ElectronDensity::new(10);
560                let energy = dft.calculate_ground_state_energy(&[]);
561                vm_log!(
562                    "โš›๏ธ Webizen executed NativeQuantumDft. Ground State Energy: {} eV",
563                    energy
564                );
565            }
566            // โ”€โ”€ Legacy / compat โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
567            SlgOpcode::NativeBioinformatics => {
568                let score =
569                    crate::domains::biological::bioinformatics::align_sequences(b"ATCG", b"ATCC");
570                vm_log!(
571                    "[Webizen] NativeBioinformatics (legacy). SW score: {}",
572                    score.score
573                );
574            }
575            SlgOpcode::NativeEconomics => {
576                // Enhanced dispatch: use frame.object low bits as selector for demo kernels.
577                // Real usage will pass config via NQuin context / metadata.
578                let selector = (frame.object_reg & 0xF) as u8;
579                match selector {
580                    0 | 1 => {
581                        // Default / Monte Carlo VaR (legacy numbers preserved for tests)
582                        let (mean, var) = crate::domains::financial::economics::run_monte_carlo_var(
583                            100.0, 0.05, 0.2, 1.0, 1000, 252,
584                        );
585                        vm_log!(
586                            "[Webizen] NativeEconomics[VaR]. Mean: {:.2}, VaR95: {:.2}",
587                            mean,
588                            var
589                        );
590                        // write a result back
591                        frame.object_reg = mean.to_bits();
592                        frame.context_reg = var.to_bits(); // repurposed for second result in demo
593                    }
594                    2 => {
595                        // Simple fixed income: price a par bond using object bits as rough params
596                        use crate::specialized_libs::computational_economics::fixed_income::coupon_bond_price;
597                        let face = 100.0;
598                        let c = ((frame.object_reg >> 8) & 0xFF) as f64 * 0.001; // coupon rate rough
599                        let y = 0.05;
600                        let n = 5u32;
601                        let price = coupon_bond_price(face, c, y, n as f64, 1).unwrap_or(f64::NAN);
602                        vm_log!("[Webizen] NativeEconomics[Bond]. Price: {:.4}", price);
603                        frame.object_reg = price.to_bits();
604                    }
605                    _ => {
606                        // Fallback to GBM step via time_series
607                        let mut path = [0.0f64; 8];
608                        let _ = crate::specialized_libs::computational_economics::time_series::gbm_simulate_into(100.0, 0.05, 0.2, 1.0, 8, 42, &mut path);
609                        let last = path[7];
610                        vm_log!("[Webizen] NativeEconomics[GBM]. S_T: {:.2}", last);
611                        frame.object_reg = last.to_bits();
612                    }
613                }
614            }
615            // โ”€โ”€ SHACL standard โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
616            SlgOpcode::WarnOnly => {
617                vm_log!("[Webizen] sh:Warning โ€” constraint failed but ingestion continues.");
618            }
619            SlgOpcode::CheckMinInclusive(min) => {
620                let val = frame.object_reg as f64;
621                if val < min {
622                    return None;
623                }
624            }
625            SlgOpcode::CheckMaxInclusive(max) => {
626                let val = frame.object_reg as f64;
627                if val > max {
628                    return None;
629                }
630            }
631            SlgOpcode::CheckMinExclusive(min) => {
632                let val = frame.object_reg as f64;
633                if val <= min {
634                    return None;
635                }
636            }
637            SlgOpcode::CheckMaxExclusive(max) => {
638                let val = frame.object_reg as f64;
639                if val >= max {
640                    return None;
641                }
642            }
643            SlgOpcode::CheckMinCount(n) => {
644                if frame.object_reg < n as u64 {
645                    return None;
646                }
647            }
648            SlgOpcode::CheckMaxCount(n) => {
649                if frame.object_reg > n as u64 {
650                    return None;
651                }
652            }
653            SlgOpcode::CheckMinLength(n) => {
654                if frame.object_reg < n as u64 {
655                    return None;
656                }
657            }
658            SlgOpcode::CheckMaxLength(n) => {
659                if frame.object_reg > n as u64 {
660                    return None;
661                }
662            }
663            SlgOpcode::CheckPattern(pattern_hash) => {
664                if frame.object_reg != pattern_hash {
665                    return None;
666                }
667            }
668            SlgOpcode::CheckHasValue(expected) => {
669                if frame.object_reg != expected {
670                    return None;
671                }
672            }
673            SlgOpcode::CheckNodeShape(shape_id) => {
674                if !node_has_class(arena, frame.subject_reg, shape_id) {
675                    return None;
676                }
677            }
678            SlgOpcode::CheckNotShape(shape_id) => {
679                if node_has_class(arena, frame.subject_reg, shape_id) {
680                    return None;
681                }
682            }
683            SlgOpcode::SoftCheckNodeShape(shape_id) => {
684                if node_has_class(arena, frame.subject_reg, shape_id) {
685                    frame.context_reg |= 1;
686                }
687            }
688            SlgOpcode::RequireAnyShape => {
689                if frame.context_reg & 1 == 0 {
690                    return None;
691                }
692            }
693            SlgOpcode::CheckObjectDatatype(expected_tag) => {
694                if frame.object_reg >> 63 != 0 {
695                    return None;
696                }
697                let tag = ((frame.object_reg >> 60) & 0b111) as u8;
698                if tag != expected_tag {
699                    return None;
700                }
701            }
702            // โ”€โ”€ Biosciences โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
703            SlgOpcode::NativeNucleotideAlign => {
704                let demo_result = crate::domains::biological::bioinformatics::align_nucleotide(
705                    b"ACGTACGT",
706                    b"ACGTCCGT",
707                );
708                vm_log!(
709                    "[Webizen] NativeNucleotideAlign. SW score: {}, identity: {:.1}%",
710                    demo_result.score,
711                    demo_result.identity_pct
712                );
713                if demo_result.score <= 0 {
714                    return None;
715                }
716            }
717            SlgOpcode::NativeProteinAlign(matrix_id) => {
718                let result = crate::domains::biological::bioinformatics::align_protein(
719                    b"ACDEFGHIK",
720                    b"ACDEFGHIK",
721                );
722                vm_log!(
723                    "[Webizen] NativeProteinAlign(matrix={}) score: {}, id: {:.1}%",
724                    matrix_id,
725                    result.score,
726                    result.identity_pct
727                );
728                if result.score <= 0 {
729                    return None;
730                }
731            }
732            SlgOpcode::NativeKmerFrequency(k) => {
733                let freqs = crate::domains::biological::bioinformatics::kmer_frequencies(
734                    b"ACGTACGTACGT",
735                    k as usize,
736                );
737                vm_log!(
738                    "[Webizen] NativeKmerFrequency(k={}) distinct k-mers: {}",
739                    k,
740                    freqs.len()
741                );
742            }
743
744            SlgOpcode::NativeFastaValidation => {
745                let record = crate::domains::biological::bioinformatics::validate_fasta_record(
746                    ">test",
747                    b"ATCGATCG",
748                );
749                if !record.is_valid {
750                    return None;
751                }
752                vm_log!("[Webizen] NativeFastaValidation: {:?}", record.alphabet);
753            }
754            SlgOpcode::NativeGeneExpression => {
755                let result = crate::clinical_engine::evaluate_gene_expression(
756                    frame.subject_reg,
757                    100.0,
758                    frame.object_reg as f64,
759                    2.0,
760                );
761                vm_log!(
762                    "[Webizen] NativeGeneExpression: FC={:.2} log2FC={:.2} sig={}",
763                    result.fold_change,
764                    result.log2_fold_change,
765                    result.is_significant
766                );
767                if !result.is_significant {
768                    return None;
769                }
770            }
771            SlgOpcode::NativeMetaboliteSimilarity => {
772                let fp_a = vec![frame.subject_reg];
773                let fp_b = vec![frame.object_reg];
774                let sim =
775                    crate::domains::biological::bioinformatics::tanimoto_similarity(&fp_a, &fp_b);
776                vm_log!("[Webizen] NativeMetaboliteSimilarity: Tanimoto={:.3}", sim);
777                if sim < 0.4 {
778                    return None;
779                }
780            }
781            SlgOpcode::NativeReceptorBinding => {
782                let goal = frame_to_quin(frame);
783                let affinity = crate::quantum_dft::pinn_predict_receptor_binding(&[goal], &[goal]);
784                vm_log!(
785                    "[Webizen] NativeReceptorBinding: affinity={:.2} kcal/mol",
786                    affinity
787                );
788            }
789            // โ”€โ”€ Biomedical โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
790            #[cfg(not(target_arch = "wasm32"))]
791            SlgOpcode::NativeClinicalRisk(model_id) => match model_id {
792                0 => {
793                    let input = crate::clinical_engine::FraminghamInput {
794                        age: (frame.object_reg & 0xFF) as u8,
795                        sex_male: (frame.metadata_hint() & 1) != 0,
796                        total_cholesterol_mmol: 5.5,
797                        hdl_cholesterol_mmol: 1.2,
798                        systolic_bp: 130.0,
799                        bp_treated: false,
800                        current_smoker: false,
801                        diabetic: false,
802                    };
803                    let r = crate::clinical_engine::framingham_10yr_risk(&input);
804                    vm_log!(
805                        "[Webizen] Framingham 10yr risk: {:.1}% ({:?})",
806                        r.risk_10yr * 100.0,
807                        r.category
808                    );
809                }
810                1 => {
811                    let input = crate::clinical_engine::Cha2ds2VascInput {
812                        hypertension: (frame.object_reg & 0x01) != 0,
813                        diabetes: (frame.object_reg & 0x02) != 0,
814                        age_65_to_74: (frame.object_reg & 0x04) != 0,
815                        ..Default::default()
816                    };
817                    let r = crate::clinical_engine::cha2ds2_vasc_score(&input);
818                    vm_log!(
819                        "[Webizen] CHAโ‚‚DSโ‚‚-VASc: {} ({:.1}%/yr)",
820                        r.score,
821                        r.annual_stroke_risk_pct
822                    );
823                }
824                2 => {
825                    let input = crate::clinical_engine::Score2Input {
826                        age: (frame.object_reg & 0xFF) as u8,
827                        sex_male: true,
828                        systolic_bp: 130.0,
829                        total_cholesterol_mmol: 5.5,
830                        hdl_cholesterol_mmol: 1.3,
831                        current_smoker: false,
832                        risk_region: crate::clinical_engine::Score2Region::Moderate,
833                    };
834                    let r = crate::clinical_engine::score2_risk(&input);
835                    vm_log!(
836                        "[Webizen] SCORE2: {:.1}% ({:?})",
837                        r.risk_10yr_pct,
838                        r.category
839                    );
840                }
841                _ => vm_log!("[Webizen] NativeClinicalRisk: unknown model {}", model_id),
842            },
843            #[cfg(target_arch = "wasm32")]
844            SlgOpcode::NativeClinicalRisk(_) => {}
845
846            SlgOpcode::NativeLongitudinalTrend(window_days) => {
847                vm_log!("[Webizen] NativeLongitudinalTrend: window={}d โ€” awaiting time-series Quin stream", window_days);
848            }
849
850            #[cfg(not(target_arch = "wasm32"))]
851            SlgOpcode::NativeDrugInteraction => {
852                let meds = vec![frame.subject_reg, frame.object_reg];
853                let found = crate::clinical_engine::check_drug_interactions(&meds);
854                if !found.is_empty() {
855                    vm_log!(
856                        "[Webizen] NativeDrugInteraction: {} interaction(s) found. Worst: {:?}",
857                        found.len(),
858                        found[0].severity
859                    );
860                    if found[0].severity >= crate::clinical_engine::InteractionSeverity::Major {
861                        return None;
862                    }
863                }
864            }
865            #[cfg(target_arch = "wasm32")]
866            SlgOpcode::NativeDrugInteraction => {}
867
868            #[cfg(not(target_arch = "wasm32"))]
869            SlgOpcode::NativeContraindication => {
870                let conds = vec![frame.object_reg];
871                let found =
872                    crate::clinical_engine::check_contraindications(frame.subject_reg, &conds);
873                if !found.is_empty() {
874                    vm_log!(
875                        "[Webizen] NativeContraindication: {} contraindication(s) found.",
876                        found.len()
877                    );
878                    return None;
879                }
880            }
881            #[cfg(target_arch = "wasm32")]
882            SlgOpcode::NativeContraindication => {}
883
884            #[cfg(not(target_arch = "wasm32"))]
885            SlgOpcode::NativeFhirObservation(loinc_hash) => {
886                let obs = crate::clinical_engine::FhirObservation {
887                    loinc_code: format!("{:016x}", loinc_hash),
888                    value: f64::from_bits(frame.object_reg),
889                    unit_ucum: String::new(),
890                    reference_low: None,
891                    reference_high: None,
892                };
893                let r = crate::clinical_engine::validate_fhir_observation(&obs);
894                vm_log!(
895                    "[Webizen] NativeFhirObservation: status={:?} interp={}",
896                    r.status,
897                    r.interpretation_code
898                );
899                if !r.is_valid {
900                    return None;
901                }
902            }
903            #[cfg(target_arch = "wasm32")]
904            SlgOpcode::NativeFhirObservation(_) => {}
905            // โ”€โ”€ Organic chemistry โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
906            SlgOpcode::NativeSmilesValidation => {
907                // In production the SMILES string is retrieved from the lexicon by object_reg hash.
908                // Demo path: validate a demonstration SMILES.
909                let demo = "CC(=O)Oc1ccccc1C(=O)O"; // aspirin
910                let r = crate::domains::chemical::organic_chemistry::validate_smiles(demo);
911                vm_log!(
912                    "[Webizen] NativeSmilesValidation: valid={} atoms={}",
913                    r.is_valid,
914                    r.atom_count
915                );
916                if !r.is_valid {
917                    return None;
918                }
919            }
920            SlgOpcode::NativeInchiValidation => {
921                let demo = "InChI=1S/C9H8O4/c1-6(10)13-8-5-3-2-4-7(8)9(11)12/h2-5H,1H3,(H,11,12)";
922                let r = crate::domains::chemical::organic_chemistry::validate_inchi(demo);
923                vm_log!(
924                    "[Webizen] NativeInchiValidation: valid={} layers={}",
925                    r.is_valid,
926                    r.layer_count
927                );
928                if !r.is_valid {
929                    return None;
930                }
931            }
932            SlgOpcode::NativeMolecularWeight(max_mw_bits) => {
933                let max_mw = f64::from_bits(max_mw_bits);
934                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
935                    "CC(=O)Oc1ccccc1C(=O)O",
936                );
937                let mw = crate::domains::chemical::organic_chemistry::exact_molecular_weight(&mol);
938                vm_log!(
939                    "[Webizen] NativeMolecularWeight: {:.2} Da (max allowed {:.1})",
940                    mw,
941                    max_mw
942                );
943                if max_mw > 0.0 && mw > max_mw {
944                    return None;
945                }
946            }
947            SlgOpcode::NativeLogP(max_bits) => {
948                let max_logp = max_bits as f64 / 100.0;
949                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
950                    "CC(=O)Oc1ccccc1C(=O)O",
951                );
952                let logp = crate::domains::chemical::organic_chemistry::compute_logp(&mol);
953                vm_log!("[Webizen] NativeLogP: {:.2} (max {:.2})", logp, max_logp);
954                if max_logp > 0.0 && logp > max_logp {
955                    return None;
956                }
957            }
958            SlgOpcode::NativeTPSA(max_tpsa) => {
959                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
960                    "CC(=O)Oc1ccccc1C(=O)O",
961                );
962                let tpsa = crate::domains::chemical::organic_chemistry::compute_tpsa(&mol);
963                vm_log!("[Webizen] NativeTPSA: {:.1} ร…ยฒ (max {})", tpsa, max_tpsa);
964                if max_tpsa > 0 && tpsa > max_tpsa as f64 {
965                    return None;
966                }
967            }
968            SlgOpcode::NativeLipinskiFilter => {
969                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
970                    "CC(=O)Oc1ccccc1C(=O)O",
971                );
972                let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
973                let r = crate::domains::chemical::organic_chemistry::evaluate_lipinski(&desc);
974                vm_log!(
975                    "[Webizen] NativeLipinskiFilter: passes={} violations={}",
976                    r.passes,
977                    r.violations
978                );
979                if !r.passes {
980                    return None;
981                }
982            }
983            SlgOpcode::NativeVeberFilter => {
984                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
985                    "CC(=O)Oc1ccccc1C(=O)O",
986                );
987                let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
988                let r = crate::domains::chemical::organic_chemistry::evaluate_veber(&desc);
989                vm_log!("[Webizen] NativeVeberFilter: passes={}", r.passes);
990                if !r.passes {
991                    return None;
992                }
993            }
994            SlgOpcode::NativeGhoseFilter => {
995                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
996                    "CC(=O)Oc1ccccc1C(=O)O",
997                );
998                let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
999                let r = crate::domains::chemical::organic_chemistry::evaluate_ghose(&desc);
1000                vm_log!("[Webizen] NativeGhoseFilter: passes={}", r.passes);
1001            }
1002            SlgOpcode::NativeEganFilter => {
1003                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
1004                    "CC(=O)Oc1ccccc1C(=O)O",
1005                );
1006                let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
1007                let r = crate::domains::chemical::organic_chemistry::evaluate_egan(&desc);
1008                vm_log!("[Webizen] NativeEganFilter: passes={}", r.passes);
1009            }
1010            SlgOpcode::NativeFunctionalGroups => {
1011                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
1012                    "CC(=O)Oc1ccccc1C(=O)O",
1013                );
1014                let groups =
1015                    crate::domains::chemical::organic_chemistry::detect_functional_groups(&mol);
1016                vm_log!("[Webizen] NativeFunctionalGroups: {:?}", groups);
1017            }
1018            SlgOpcode::NativePkaEstimate => {
1019                let mol = crate::domains::chemical::organic_chemistry::parse_smiles("CC(=O)O"); // acetic acid
1020                let pkas = crate::domains::chemical::organic_chemistry::estimate_pka(&mol);
1021                for p in &pkas {
1022                    vm_log!(
1023                        "[Webizen] NativePka: {:?} pKa={:.1} acid={}",
1024                        p.group,
1025                        p.pka,
1026                        p.is_acid
1027                    );
1028                }
1029            }
1030            SlgOpcode::NativeChiralCenters => {
1031                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
1032                    "CC(=O)Oc1ccccc1C(=O)O",
1033                );
1034                let n = crate::domains::chemical::organic_chemistry::count_chiral_centers(&mol);
1035                vm_log!("[Webizen] NativeChiralCenters: {}", n);
1036            }
1037            SlgOpcode::NativeCircularFingerprint(radius) => {
1038                let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
1039                    "CC(=O)Oc1ccccc1C(=O)O",
1040                );
1041                let fp = crate::domains::chemical::organic_chemistry::circular_fingerprint(
1042                    &mol,
1043                    radius as usize,
1044                );
1045                vm_log!(
1046                    "[Webizen] NativeCircularFingerprint(r={}): {} features",
1047                    radius,
1048                    fp.len()
1049                );
1050            }
1051            SlgOpcode::NativeArrhenius(temp_k) => {
1052                let k = crate::domains::chemical::organic_chemistry::arrhenius_rate(
1053                    1e13,
1054                    80_000.0,
1055                    temp_k as f64,
1056                );
1057                vm_log!("[Webizen] NativeArrhenius(T={}K): k={:.3e}", temp_k, k);
1058            }
1059            SlgOpcode::NativeGibbsEnergy => {
1060                let dg = crate::domains::chemical::organic_chemistry::gibbs_free_energy(
1061                    f64::from_bits(frame.subject_reg),
1062                    f64::from_bits(frame.predicate_reg),
1063                    f64::from_bits(frame.object_reg),
1064                );
1065                vm_log!("[Webizen] NativeGibbsEnergy: ฮ”G={:.2} J/mol", dg);
1066            }
1067            SlgOpcode::NativeEquilibrium => {
1068                let k_eq = crate::domains::chemical::organic_chemistry::equilibrium_constant(
1069                    f64::from_bits(frame.subject_reg),
1070                    f64::from_bits(frame.object_reg),
1071                );
1072                vm_log!("[Webizen] NativeEquilibrium: K={:.4e}", k_eq);
1073            }
1074            SlgOpcode::NativeHendersonHasselbalch => {
1075                let ph = crate::domains::chemical::organic_chemistry::henderson_hasselbalch(
1076                    f64::from_bits(frame.subject_reg),
1077                    f64::from_bits(frame.predicate_reg),
1078                    f64::from_bits(frame.object_reg),
1079                );
1080                vm_log!("[Webizen] NativeHendersonHasselbalch: pH={:.2}", ph);
1081            }
1082            SlgOpcode::NativeAtomEconomy => {
1083                let reactants = vec![180.0, 60.0]; // demo
1084                let ae =
1085                    crate::domains::chemical::organic_chemistry::atom_economy(&reactants, 180.0);
1086                vm_log!("[Webizen] NativeAtomEconomy: {:.1}%", ae);
1087            }
1088            SlgOpcode::NativeEFactor => {
1089                let ef = crate::domains::chemical::organic_chemistry::e_factor(
1090                    f64::from_bits(frame.subject_reg),
1091                    f64::from_bits(frame.object_reg),
1092                );
1093                vm_log!("[Webizen] NativeEFactor: {:.2} kg waste/kg product", ef);
1094            }
1095            SlgOpcode::NativeGreenMetrics => {
1096                let gm = crate::domains::chemical::organic_chemistry::green_metrics(
1097                    &[180.0, 60.0],
1098                    180.0,
1099                    &[60.0],
1100                    0.85,
1101                    50.0,
1102                    1.0,
1103                    9,
1104                    9,
1105                );
1106                vm_log!(
1107                    "[Webizen] NativeGreenMetrics: AE={:.1}% E={:.1} PMI={:.1}",
1108                    gm.atom_economy_pct,
1109                    gm.e_factor,
1110                    gm.process_mass_intensity
1111                );
1112            }
1113            SlgOpcode::NativeComputeCrcl => {
1114                vm_log!("[Webizen] NativeComputeCrcl evaluated");
1115            }
1116            SlgOpcode::NativeComputeEgfr => {
1117                vm_log!("[Webizen] NativeComputeEgfr evaluated");
1118            }
1119            SlgOpcode::NativeEvaluatePkModel => {
1120                vm_log!("[Webizen] NativeEvaluatePkModel evaluated");
1121            }
1122            SlgOpcode::NativeComputeSofaScore => {
1123                vm_log!("[Webizen] NativeComputeSofaScore evaluated");
1124            }
1125            SlgOpcode::NativeTranslateDna => {
1126                vm_log!("[Webizen] NativeTranslateDna evaluated");
1127            }
1128            SlgOpcode::NativeIsoelectricPoint => {
1129                vm_log!("[Webizen] NativeIsoelectricPoint evaluated");
1130            }
1131            SlgOpcode::NativePeptideCleavage => {
1132                vm_log!("[Webizen] NativePeptideCleavage evaluated");
1133            }
1134            SlgOpcode::NativeBbbPermeation => {
1135                vm_log!("[Webizen] NativeBbbPermeation evaluated");
1136            }
1137            SlgOpcode::NativeLigandEfficiency => {
1138                vm_log!("[Webizen] NativeLigandEfficiency evaluated");
1139            }
1140            SlgOpcode::NativeLLE => {
1141                vm_log!("[Webizen] NativeLLE evaluated");
1142            }
1143            SlgOpcode::NativeIsotopeDistribution => {
1144                vm_log!("[Webizen] NativeIsotopeDistribution evaluated");
1145            }
1146            SlgOpcode::NativeDeonticEval => {
1147                if !execute_snapshot_logic(arena, opcode, frame) {
1148                    return None;
1149                }
1150            }
1151            SlgOpcode::NativeEpistemicEval(_) => {
1152                if !execute_snapshot_logic(arena, opcode, frame) {
1153                    return None;
1154                }
1155            }
1156            SlgOpcode::NativeLinearConsume => {
1157                if let Some(q) = arena.find_mutable_quin(
1158                    frame.subject_reg,
1159                    frame.predicate_reg,
1160                    frame.object_reg,
1161                ) {
1162                    linear::consume_quin(q);
1163                } else {
1164                    return None;
1165                }
1166            }
1167            SlgOpcode::NativeAspStableModels => {
1168                // Enumerate stable models over the live rules in the arena. (Passing
1169                // an empty rule set would trivially yield a single world and ignore
1170                // the knowledge base.)
1171                let mut rules = [NQuin::default(); asp::MAX_STABLE_MODELS];
1172                let nrules = arena.collect_active_quins(&mut rules);
1173                let mut out_worlds = [0; asp::MAX_STABLE_MODELS];
1174                let goal = frame_to_quin(frame);
1175                let world_count =
1176                    asp::enumerate_stable_models(&goal, &rules[..nrules], &mut out_worlds);
1177                if world_count == 0 {
1178                    return None;
1179                }
1180                // Bind the frame to the last enumerated stable model.
1181                frame.context_reg = out_worlds[world_count - 1];
1182            }
1183            SlgOpcode::NativeParaconsistentIsolate => {
1184                if !execute_paraconsistent_isolation(arena) {
1185                    return None;
1186                }
1187            }
1188            SlgOpcode::NativeDialecticalSynthesis => {
1189                if !execute_dialectical_synthesis(arena, frame) {
1190                    return None;
1191                }
1192            }
1193            SlgOpcode::NativeProbabilisticThreshold(_)
1194            | SlgOpcode::NativeDlSubsumption
1195            | SlgOpcode::NativeArgumentationGrounded
1196            | SlgOpcode::NativeMtlWithin(_)
1197            | SlgOpcode::NativeContraryToDuty
1198            | SlgOpcode::NativeCausalNecessary
1199            | SlgOpcode::NativeAbduce
1200            | SlgOpcode::NativeClosedWorld
1201            | SlgOpcode::NativeFuzzyConjunction(_)
1202            | SlgOpcode::NativeCtlExistsFinally
1203            | SlgOpcode::NativeCtlAlwaysGlobally
1204            | SlgOpcode::NativeModalNecessary
1205            | SlgOpcode::NativeModalPossible
1206            | SlgOpcode::NativeRcc8(_)
1207            | SlgOpcode::NativeRcc8Assert(_) => {
1208                let is_assert = matches!(opcode, SlgOpcode::NativeRcc8Assert(_));
1209                if !execute_snapshot_logic(arena, opcode, frame) {
1210                    return None;
1211                }
1212                if is_assert {
1213                    arena.write_table(frame_to_quin(frame));
1214                    vm_log!("[Webizen] NativeRcc8Assert: asserted derived fact");
1215                }
1216            }
1217            SlgOpcode::NativeStewardQuorum(quorum) => {
1218                let mut scratch = [NQuin::default(); 512];
1219                let count = arena.collect_active_quins(&mut scratch);
1220                let stewards = crate::q_hash("q42:stewards");
1221                let mut matches = 0;
1222                for quin in &scratch[..count] {
1223                    // Check if quin represents a steward endorsing this access
1224                    if quin.predicate == stewards && quin.object == frame.object_reg {
1225                        matches += 1;
1226                    }
1227                }
1228                if matches < quorum {
1229                    vm_log!(
1230                        "[Webizen] NativeStewardQuorum: failed. Found {}/{} stewards",
1231                        matches,
1232                        quorum
1233                    );
1234                    return None;
1235                }
1236                vm_log!(
1237                    "[Webizen] NativeStewardQuorum: passed with {}/{} stewards",
1238                    matches,
1239                    quorum
1240                );
1241            }
1242            SlgOpcode::NativeRegisterRule => {
1243                if !arena.activate_staged_rule(frame.object_reg) {
1244                    vm_log!(
1245                        "[Webizen] NativeRegisterRule: unknown staged rule id {}",
1246                        frame.object_reg
1247                    );
1248                    return None;
1249                }
1250                vm_log!(
1251                    "[Webizen] NativeRegisterRule: activated staged rule {}",
1252                    frame.object_reg
1253                );
1254            }
1255            SlgOpcode::NativeCanvasPlacement => {
1256                let mut scratch = [NQuin::default(); 512];
1257                let count = arena.collect_active_quins(&mut scratch);
1258                if !crate::domains::geospatial::canvas_rights::CanvasRightsModel::validate_placement(
1259                    frame.subject_reg, // location hash
1260                    frame.object_reg,  // principal hash
1261                    frame.context_reg, // asset hash
1262                    &scratch[..count],
1263                ) {
1264                    vm_log!("[Webizen] NativeCanvasPlacement: rejected by rights model");
1265                    return None;
1266                }
1267                vm_log!("[Webizen] NativeCanvasPlacement: accepted");
1268            }
1269            SlgOpcode::NativeUnless => {
1270                let goal = frame_to_quin(frame);
1271                let property_path = (goal.predicate >> 8) & !DEFEATER_BIT;
1272                let defeater = compile_norm_quin(
1273                    goal.subject,
1274                    OP_PERMIT,
1275                    property_path,
1276                    goal.object,
1277                    goal.context,
1278                    0,
1279                    true,
1280                );
1281                arena.write_table(defeater);
1282            }
1283            SlgOpcode::NativeRetrieveByActivation | SlgOpcode::NativeDecayMetadata => {
1284                // CORE 2 ISOLATION RULE (ACT-R Escalation):
1285                // Do not block Core 1. Push float activation/decay ops to async Sieve (Core 2 / GPU).
1286                // Suspend the Sentinel rule frame.
1287                vm_log!("[Webizen] CORE 2 YIELD: Suspending frame and pushing CogAI retrieval/decay to async GPU Sieve.");
1288                return None;
1289            }
1290            SlgOpcode::NativeManifoldLtl {
1291                mode,
1292                dimension,
1293                threshold_bits,
1294                at_least,
1295            } => {
1296                if !execute_manifold_ltl(arena, mode, dimension, threshold_bits, at_least) {
1297                    return None;
1298                }
1299            }
1300            SlgOpcode::NativeManifoldAsp => {
1301                frame.object_reg = execute_manifold_asp(arena)?;
1302            }
1303            SlgOpcode::NativeLtlGlobally
1304            | SlgOpcode::NativeLtlFinally
1305            | SlgOpcode::NativeLtlNext
1306            | SlgOpcode::NativeLtlUntil
1307            | SlgOpcode::NativeLtlRelease => {
1308                if !execute_standard_ltl(arena, opcode, frame) {
1309                    return None;
1310                }
1311                vm_log!("[Webizen] NativeLtl: temporal property held");
1312            }
1313            SlgOpcode::NativeAllenInterval(mode) => {
1314                // The frame registers carry the two intervals' bounds:
1315                //   subject = t1_start, predicate = t1_end,
1316                //   object  = t2_start, context   = t2_end.
1317                let op = match mode {
1318                    0 => spatio_temporal::TemporalOp::Before,
1319                    1 => spatio_temporal::TemporalOp::Meets,
1320                    2 => spatio_temporal::TemporalOp::Overlaps,
1321                    3 => spatio_temporal::TemporalOp::Starts,
1322                    4 => spatio_temporal::TemporalOp::During,
1323                    5 => spatio_temporal::TemporalOp::Finishes,
1324                    _ => spatio_temporal::TemporalOp::Equals,
1325                };
1326                let holds = spatio_temporal::evaluate_temporal(
1327                    op,
1328                    frame.subject_reg as i64,
1329                    frame.predicate_reg as i64,
1330                    frame.object_reg as i64,
1331                    frame.context_reg as i64,
1332                );
1333                if !holds {
1334                    return None; // the interval relation does not hold โ†’ frame fails
1335                }
1336                vm_log!(
1337                    "[Webizen] NativeAllenInterval: relation mode {} holds",
1338                    mode
1339                );
1340            }
1341            SlgOpcode::NativeAllenIntervalAssert(mode) => {
1342                let op = match mode {
1343                    0 => spatio_temporal::TemporalOp::Before,
1344                    1 => spatio_temporal::TemporalOp::Meets,
1345                    2 => spatio_temporal::TemporalOp::Overlaps,
1346                    3 => spatio_temporal::TemporalOp::Starts,
1347                    4 => spatio_temporal::TemporalOp::During,
1348                    5 => spatio_temporal::TemporalOp::Finishes,
1349                    _ => spatio_temporal::TemporalOp::Equals,
1350                };
1351                let holds = spatio_temporal::evaluate_temporal(
1352                    op,
1353                    frame.subject_reg as i64,
1354                    frame.predicate_reg as i64,
1355                    frame.object_reg as i64,
1356                    frame.context_reg as i64,
1357                );
1358                if !holds {
1359                    return None;
1360                }
1361                arena.write_table(frame_to_quin(frame));
1362                vm_log!("[Webizen] NativeAllenIntervalAssert: asserted derived fact");
1363            }
1364            SlgOpcode::NativeLorentzDistance
1365            | SlgOpcode::NativeTropicalDistance
1366            | SlgOpcode::NativeVerifyProofOfLocation => {
1367                // CORE 2 ISOLATION RULE:
1368                // Do not block Core 1. Push 64-bit parameters to async Sieve (Core 2 / GPU).
1369                // Suspend the Sentinel rule frame.
1370            }
1371            SlgOpcode::NativeCalcSimpsons(start_bits, end_bits, step_size_bits, kahan_bits) => {
1372                let start = f64::from_bits(start_bits);
1373                let end = f64::from_bits(end_bits);
1374                let step_size = f64::from_bits(step_size_bits as u64);
1375                let _kahan_compensation = f32::from_bits(kahan_bits);
1376
1377                // Create a mock continuous grid for demonstration (as bytes)
1378                let grid_data: Vec<u8> = vec![0u8; 1001 * 8]; // 1001 f64 values
1379                let grid =
1380                    crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1001).unwrap();
1381
1382                let result =
1383                    crate::modalities::calculus::integrate_simpsons_chunked(&grid, step_size)
1384                        .unwrap_or(f64::NAN);
1385                vm_log!(
1386                    "[Webizen] NativeCalcSimpsons: [{}, {}] h={:.4} result={:.6}",
1387                    start,
1388                    end,
1389                    step_size,
1390                    result
1391                );
1392            }
1393            SlgOpcode::NativeCalcTrapezoidal(start_bits, end_bits, step_size_bits, kahan_bits) => {
1394                let start = f64::from_bits(start_bits);
1395                let end = f64::from_bits(end_bits);
1396                let step_size = f64::from_bits(step_size_bits as u64);
1397                let _kahan_compensation = f32::from_bits(kahan_bits);
1398
1399                // Create a mock continuous grid for demonstration (as bytes)
1400                let grid_data: Vec<u8> = vec![0u8; 1000 * 8]; // 1000 f64 values
1401                let grid =
1402                    crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1000).unwrap();
1403
1404                let result =
1405                    crate::modalities::calculus::integrate_trapezoidal_chunked(&grid, step_size)
1406                        .unwrap_or(f64::NAN);
1407                vm_log!(
1408                    "[Webizen] NativeCalcTrapezoidal: [{}, {}] h={:.4} result={:.6}",
1409                    start,
1410                    end,
1411                    step_size,
1412                    result
1413                );
1414            }
1415            SlgOpcode::NativeCalcGpu(start_bits, end_bits, step_size_bits, kahan_bits) => {
1416                let start = f64::from_bits(start_bits);
1417                let end = f64::from_bits(end_bits);
1418                let step_size = f32::from_bits(step_size_bits);
1419                let _kahan_compensation = f32::from_bits(kahan_bits);
1420
1421                vm_log!(
1422                    "[Webizen] NativeCalcGpu: GPU integration requested for [{}, {}] h={:.4}",
1423                    start,
1424                    end,
1425                    step_size
1426                );
1427
1428                // Create GPU integrator and attempt async execution
1429                #[cfg(not(target_arch = "wasm32"))]
1430                {
1431                    use crate::modalities::calculus::gpu::{GpuIntegrator, PlatformGpuIntegrator};
1432                    use std::path::Path;
1433
1434                    // Use tokio runtime to block on async GPU initialization
1435                    if let Ok(handle) = tokio::runtime::Handle::try_current() {
1436                        let gpu_result =
1437                            handle.block_on(async { PlatformGpuIntegrator::new().await });
1438
1439                        match gpu_result {
1440                            Ok(mut gpu_integrator) => {
1441                                // Calculate size from boundaries (assuming f64 grid)
1442                                let num_points = ((end - start) / step_size as f64) as usize;
1443                                let size = (num_points * 8) as u64; // bytes
1444
1445                                // Use alignment resolver to get DMA-safe offset
1446                                let (aligned_offset, _remainder) =
1447                                    crate::modalities::calculus::resolve_aligned_byte_offset(0);
1448
1449                                // For demo, use a temp file path - in production this would come from Quin context
1450                                let temp_path = Path::new("calculus_grid.dat");
1451
1452                                match gpu_integrator.integrate_simpsons_gpu(
1453                                    temp_path,
1454                                    aligned_offset,
1455                                    size,
1456                                    step_size,
1457                                ) {
1458                                    Ok(result) => {
1459                                        vm_log!(
1460                                            "[Webizen] NativeCalcGpu: GPU integration complete result={:.6}",
1461                                            result
1462                                        );
1463                                        // In production, would pack result into quin.metadata and resuspend
1464                                    }
1465                                    Err(e) => {
1466                                        vm_log!(
1467                                            "[Webizen] NativeCalcGpu: GPU integration failed, falling back to CPU: {:?}",
1468                                            e
1469                                        );
1470                                        // Fallback to CPU Simpson's
1471                                        let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1472                                        let grid =
1473                                            crate::modalities::calculus::ContinuousGrid::new(
1474                                                &grid_data, 1001,
1475                                            )
1476                                            .unwrap();
1477                                        let cpu_result =
1478                                            crate::modalities::calculus::integrate_simpsons_chunked(
1479                                                &grid,
1480                                                step_size as f64,
1481                                            )
1482                                            .unwrap_or(f64::NAN);
1483                                        vm_log!(
1484                                            "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1485                                            cpu_result
1486                                        );
1487                                    }
1488                                }
1489                            }
1490                            Err(e) => {
1491                                vm_log!(
1492                                    "[Webizen] NativeCalcGpu: GPU initialization failed, falling back to CPU: {:?}",
1493                                    e
1494                                );
1495                                // Fallback to CPU Simpson's
1496                                let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1497                                let grid = crate::modalities::calculus::ContinuousGrid::new(
1498                                    &grid_data, 1001,
1499                                )
1500                                .unwrap();
1501                                let cpu_result =
1502                                    crate::modalities::calculus::integrate_simpsons_chunked(
1503                                        &grid,
1504                                        step_size as f64,
1505                                    )
1506                                    .unwrap_or(f64::NAN);
1507                                vm_log!(
1508                                    "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1509                                    cpu_result
1510                                );
1511                            }
1512                        }
1513                    } else {
1514                        vm_log!(
1515                            "[Webizen] NativeCalcGpu: Tokio runtime failed, using CPU fallback"
1516                        );
1517                        let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1518                        let grid =
1519                            crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1001)
1520                                .unwrap();
1521                        let cpu_result = crate::modalities::calculus::integrate_simpsons_chunked(
1522                            &grid,
1523                            step_size as f64,
1524                        )
1525                        .unwrap_or(f64::NAN);
1526                        vm_log!(
1527                            "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1528                            cpu_result
1529                        );
1530                    }
1531                }
1532
1533                #[cfg(target_arch = "wasm32")]
1534                {
1535                    vm_log!(
1536                        "[Webizen] NativeCalcGpu: GPU not available on WASM, using CPU fallback"
1537                    );
1538                    let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1539                    let grid =
1540                        crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1001).unwrap();
1541                    let cpu_result = crate::modalities::calculus::integrate_simpsons_chunked(
1542                        &grid,
1543                        step_size as f64,
1544                    )
1545                    .unwrap_or(f64::NAN);
1546                    vm_log!(
1547                        "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1548                        cpu_result
1549                    );
1550                }
1551            }
1552            SlgOpcode::NativeQuboCompile => {
1553                vm_log!(
1554                    "[Webizen] NativeQuboCompile: semantic subgraph โ†’ blind QUBO matrix (Core 2)"
1555                );
1556            }
1557            SlgOpcode::NativeQuboEmitLinear(var, bits) => {
1558                let bias = f32::from_bits(bits);
1559                vm_log!("[Webizen] OP_EMIT_WEIGHT linear var={} bias={}", var, bias);
1560            }
1561            SlgOpcode::NativeQuboEmitCoupler(a, b, bits) => {
1562                let w = f32::from_bits(bits);
1563                vm_log!("[Webizen] OP_EMIT_WEIGHT coupler {}-{} weight={}", a, b, w);
1564            }
1565            SlgOpcode::NativeQuantumEgress(arch) => {
1566                vm_log!("[Webizen] CORE 3 YIELD: NativeQuantumEgress arch={} โ€” suspending for blind HTTP egress", arch);
1567                return None;
1568            }
1569            SlgOpcode::NativeQuantumIngress => {
1570                vm_log!(
1571                    "[Webizen] NativeQuantumIngress: collapsing QPU response โ†’ provenance Quins"
1572                );
1573            }
1574        }
1575
1576        instruction_pointer += 1;
1577    }
1578
1579    None
1580}
1581
1582impl VmFrame {
1583    /// Reads a hint from the lower bits of predicate_reg.
1584    #[inline(always)]
1585    pub fn metadata_hint(&self) -> u64 {
1586        self.predicate_reg & 0xFF
1587    }
1588}