1use super::*;
2
3#[cfg(feature = "alloc_buffers")]
4extern crate alloc;
5
6#[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
42fn 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 ®ion_a[..region_a_count],
374 frame.object_reg,
375 ®ion_b[..region_b_count],
376 ) as u8
377 == expected
378 }
379 _ => false,
380 }
381}
382
383pub 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 if let Some(cached_result) =
398 arena.check_table(frame.subject_reg, frame.predicate_reg, frame.object_reg)
399 {
400 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 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 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 let schema = TaxRuleSchema::new_au_gst();
479 let _liability = schema.evaluate("Income", 100.0);
480
481 }
484 SlgOpcode::Halt => {
485 break;
486 }
487 SlgOpcode::NativeThermodynamics => {
488 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 #[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 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 {
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 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 }
557 SlgOpcode::NativeQuantumDft => {
558 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 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 let selector = (frame.object_reg & 0xF) as u8;
579 match selector {
580 0 | 1 => {
581 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 frame.object_reg = mean.to_bits();
592 frame.context_reg = var.to_bits(); }
594 2 => {
595 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; 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 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 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 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 SlgOpcode::NativeClinicalRisk(model_id) => {
791 let mut scratch = [NQuin::default(); 256];
792 let n = arena.collect_active_quins(&mut scratch);
793 let outcome = if n == 0 || frame.subject_reg == 0 {
794 super::clinical_native::evaluate(model_id)
795 } else {
796 super::clinical_native::evaluate_patient(
797 model_id,
798 frame.subject_reg,
799 &scratch[..n],
800 )
801 };
802 match outcome {
803 super::clinical_native::NativeClinicalRiskOutcome::HeldIncomplete => {
804 vm_log!(
805 "[Webizen] NativeClinicalRisk: held โ incomplete clinical inputs; missing is not a patient value (model {})",
806 model_id
807 );
808 }
809 super::clinical_native::NativeClinicalRiskOutcome::UnknownModel => {
810 vm_log!("[Webizen] NativeClinicalRisk: unknown model {}", model_id);
811 }
812 super::clinical_native::NativeClinicalRiskOutcome::Calculated { value } => {
813 vm_log!(
814 "[Webizen] NativeClinicalRisk: model {} value={:.6} (not advice)",
815 model_id,
816 value
817 );
818 frame.object_reg = crate::frame_layout::pack_float_object(value as f32);
819 }
820 }
821 }
822
823 SlgOpcode::NativeLongitudinalTrend(window_days) => {
824 vm_log!("[Webizen] NativeLongitudinalTrend: window={}d โ awaiting time-series Quin stream", window_days);
825 }
826
827 SlgOpcode::NativeDrugInteraction => {
828 let meds = vec![frame.subject_reg, frame.object_reg];
829 let found = crate::clinical_engine::check_drug_interactions(&meds);
830 if !found.is_empty() {
831 vm_log!(
832 "[Webizen] NativeDrugInteraction: {} interaction(s) found. Worst: {:?}",
833 found.len(),
834 found[0].severity
835 );
836 if found[0].severity >= crate::clinical_engine::InteractionSeverity::Major {
837 return None;
838 }
839 }
840 }
841
842 SlgOpcode::NativeContraindication => {
843 let conds = vec![frame.object_reg];
844 let found =
845 crate::clinical_engine::check_contraindications(frame.subject_reg, &conds);
846 if !found.is_empty() {
847 vm_log!(
848 "[Webizen] NativeContraindication: {} contraindication(s) found.",
849 found.len()
850 );
851 return None;
852 }
853 }
854
855 SlgOpcode::NativeFhirObservation(loinc_hash) => {
856 let obs = crate::clinical_engine::FhirObservation {
857 loinc_code: format!("{:016x}", loinc_hash),
858 value: f64::from_bits(frame.object_reg),
859 unit_ucum: String::new(),
860 reference_low: None,
861 reference_high: None,
862 };
863 let r = crate::clinical_engine::validate_fhir_observation(&obs);
864 vm_log!(
865 "[Webizen] NativeFhirObservation: status={:?} interp={}",
866 r.status,
867 r.interpretation_code
868 );
869 if !r.is_valid {
870 return None;
871 }
872 }
873 SlgOpcode::NativeSmilesValidation => {
875 let demo = "CC(=O)Oc1ccccc1C(=O)O"; let r = crate::domains::chemical::organic_chemistry::validate_smiles(demo);
879 vm_log!(
880 "[Webizen] NativeSmilesValidation: valid={} atoms={}",
881 r.is_valid,
882 r.atom_count
883 );
884 if !r.is_valid {
885 return None;
886 }
887 }
888 SlgOpcode::NativeInchiValidation => {
889 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)";
890 let r = crate::domains::chemical::organic_chemistry::validate_inchi(demo);
891 vm_log!(
892 "[Webizen] NativeInchiValidation: valid={} layers={}",
893 r.is_valid,
894 r.layer_count
895 );
896 if !r.is_valid {
897 return None;
898 }
899 }
900 SlgOpcode::NativeMolecularWeight(max_mw_bits) => {
901 let max_mw = f64::from_bits(max_mw_bits);
902 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
903 "CC(=O)Oc1ccccc1C(=O)O",
904 );
905 let mw = crate::domains::chemical::organic_chemistry::exact_molecular_weight(&mol);
906 vm_log!(
907 "[Webizen] NativeMolecularWeight: {:.2} Da (max allowed {:.1})",
908 mw,
909 max_mw
910 );
911 if max_mw > 0.0 && mw > max_mw {
912 return None;
913 }
914 }
915 SlgOpcode::NativeLogP(max_bits) => {
916 let max_logp = max_bits as f64 / 100.0;
917 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
918 "CC(=O)Oc1ccccc1C(=O)O",
919 );
920 let logp = crate::domains::chemical::organic_chemistry::compute_logp(&mol);
921 vm_log!("[Webizen] NativeLogP: {:.2} (max {:.2})", logp, max_logp);
922 if max_logp > 0.0 && logp > max_logp {
923 return None;
924 }
925 }
926 SlgOpcode::NativeTPSA(max_tpsa) => {
927 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
928 "CC(=O)Oc1ccccc1C(=O)O",
929 );
930 let tpsa = crate::domains::chemical::organic_chemistry::compute_tpsa(&mol);
931 vm_log!("[Webizen] NativeTPSA: {:.1} ร
ยฒ (max {})", tpsa, max_tpsa);
932 if max_tpsa > 0 && tpsa > max_tpsa as f64 {
933 return None;
934 }
935 }
936 SlgOpcode::NativeLipinskiFilter => {
937 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
938 "CC(=O)Oc1ccccc1C(=O)O",
939 );
940 let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
941 let r = crate::domains::chemical::organic_chemistry::evaluate_lipinski(&desc);
942 vm_log!(
943 "[Webizen] NativeLipinskiFilter: passes={} violations={}",
944 r.passes,
945 r.violations
946 );
947 if !r.passes {
948 return None;
949 }
950 }
951 SlgOpcode::NativeVeberFilter => {
952 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
953 "CC(=O)Oc1ccccc1C(=O)O",
954 );
955 let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
956 let r = crate::domains::chemical::organic_chemistry::evaluate_veber(&desc);
957 vm_log!("[Webizen] NativeVeberFilter: passes={}", r.passes);
958 if !r.passes {
959 return None;
960 }
961 }
962 SlgOpcode::NativeGhoseFilter => {
963 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
964 "CC(=O)Oc1ccccc1C(=O)O",
965 );
966 let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
967 let r = crate::domains::chemical::organic_chemistry::evaluate_ghose(&desc);
968 vm_log!("[Webizen] NativeGhoseFilter: passes={}", r.passes);
969 }
970 SlgOpcode::NativeEganFilter => {
971 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
972 "CC(=O)Oc1ccccc1C(=O)O",
973 );
974 let desc = crate::domains::chemical::organic_chemistry::compute_descriptors(&mol);
975 let r = crate::domains::chemical::organic_chemistry::evaluate_egan(&desc);
976 vm_log!("[Webizen] NativeEganFilter: passes={}", r.passes);
977 }
978 SlgOpcode::NativeFunctionalGroups => {
979 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
980 "CC(=O)Oc1ccccc1C(=O)O",
981 );
982 let groups =
983 crate::domains::chemical::organic_chemistry::detect_functional_groups(&mol);
984 vm_log!("[Webizen] NativeFunctionalGroups: {:?}", groups);
985 }
986 SlgOpcode::NativePkaEstimate => {
987 let mol = crate::domains::chemical::organic_chemistry::parse_smiles("CC(=O)O"); let pkas = crate::domains::chemical::organic_chemistry::estimate_pka(&mol);
989 for p in &pkas {
990 vm_log!(
991 "[Webizen] NativePka: {:?} pKa={:.1} acid={}",
992 p.group,
993 p.pka,
994 p.is_acid
995 );
996 }
997 }
998 SlgOpcode::NativeChiralCenters => {
999 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
1000 "CC(=O)Oc1ccccc1C(=O)O",
1001 );
1002 let n = crate::domains::chemical::organic_chemistry::count_chiral_centers(&mol);
1003 vm_log!("[Webizen] NativeChiralCenters: {}", n);
1004 }
1005 SlgOpcode::NativeCircularFingerprint(radius) => {
1006 let mol = crate::domains::chemical::organic_chemistry::parse_smiles(
1007 "CC(=O)Oc1ccccc1C(=O)O",
1008 );
1009 let fp = crate::domains::chemical::organic_chemistry::circular_fingerprint(
1010 &mol,
1011 radius as usize,
1012 );
1013 vm_log!(
1014 "[Webizen] NativeCircularFingerprint(r={}): {} features",
1015 radius,
1016 fp.len()
1017 );
1018 }
1019 SlgOpcode::NativeArrhenius(temp_k) => {
1020 let k = crate::domains::chemical::organic_chemistry::arrhenius_rate(
1021 1e13,
1022 80_000.0,
1023 temp_k as f64,
1024 );
1025 vm_log!("[Webizen] NativeArrhenius(T={}K): k={:.3e}", temp_k, k);
1026 }
1027 SlgOpcode::NativeGibbsEnergy => {
1028 let dg = crate::domains::chemical::organic_chemistry::gibbs_free_energy(
1029 f64::from_bits(frame.subject_reg),
1030 f64::from_bits(frame.predicate_reg),
1031 f64::from_bits(frame.object_reg),
1032 );
1033 vm_log!("[Webizen] NativeGibbsEnergy: ฮG={:.2} J/mol", dg);
1034 }
1035 SlgOpcode::NativeEquilibrium => {
1036 let k_eq = crate::domains::chemical::organic_chemistry::equilibrium_constant(
1037 f64::from_bits(frame.subject_reg),
1038 f64::from_bits(frame.object_reg),
1039 );
1040 vm_log!("[Webizen] NativeEquilibrium: K={:.4e}", k_eq);
1041 }
1042 SlgOpcode::NativeHendersonHasselbalch => {
1043 let ph = crate::domains::chemical::organic_chemistry::henderson_hasselbalch(
1044 f64::from_bits(frame.subject_reg),
1045 f64::from_bits(frame.predicate_reg),
1046 f64::from_bits(frame.object_reg),
1047 );
1048 vm_log!("[Webizen] NativeHendersonHasselbalch: pH={:.2}", ph);
1049 }
1050 SlgOpcode::NativeAtomEconomy => {
1051 let reactants = vec![180.0, 60.0]; let ae =
1053 crate::domains::chemical::organic_chemistry::atom_economy(&reactants, 180.0);
1054 vm_log!("[Webizen] NativeAtomEconomy: {:.1}%", ae);
1055 }
1056 SlgOpcode::NativeEFactor => {
1057 let ef = crate::domains::chemical::organic_chemistry::e_factor(
1058 f64::from_bits(frame.subject_reg),
1059 f64::from_bits(frame.object_reg),
1060 );
1061 vm_log!("[Webizen] NativeEFactor: {:.2} kg waste/kg product", ef);
1062 }
1063 SlgOpcode::NativeGreenMetrics => {
1064 let gm = crate::domains::chemical::organic_chemistry::green_metrics(
1065 &[180.0, 60.0],
1066 180.0,
1067 &[60.0],
1068 0.85,
1069 50.0,
1070 1.0,
1071 9,
1072 9,
1073 );
1074 vm_log!(
1075 "[Webizen] NativeGreenMetrics: AE={:.1}% E={:.1} PMI={:.1}",
1076 gm.atom_economy_pct,
1077 gm.e_factor,
1078 gm.process_mass_intensity
1079 );
1080 }
1081 SlgOpcode::NativeComputeCrcl => {
1082 vm_log!("[Webizen] NativeComputeCrcl evaluated");
1083 }
1084 SlgOpcode::NativeComputeEgfr => {
1085 vm_log!("[Webizen] NativeComputeEgfr evaluated");
1086 }
1087 SlgOpcode::NativeEvaluatePkModel => {
1088 vm_log!("[Webizen] NativeEvaluatePkModel evaluated");
1089 }
1090 SlgOpcode::NativeComputeSofaScore => {
1091 vm_log!("[Webizen] NativeComputeSofaScore evaluated");
1092 }
1093 SlgOpcode::NativeTranslateDna => {
1094 vm_log!("[Webizen] NativeTranslateDna evaluated");
1095 }
1096 SlgOpcode::NativeIsoelectricPoint => {
1097 vm_log!("[Webizen] NativeIsoelectricPoint evaluated");
1098 }
1099 SlgOpcode::NativePeptideCleavage => {
1100 vm_log!("[Webizen] NativePeptideCleavage evaluated");
1101 }
1102 SlgOpcode::NativeBbbPermeation => {
1103 vm_log!("[Webizen] NativeBbbPermeation evaluated");
1104 }
1105 SlgOpcode::NativeLigandEfficiency => {
1106 vm_log!("[Webizen] NativeLigandEfficiency evaluated");
1107 }
1108 SlgOpcode::NativeLLE => {
1109 vm_log!("[Webizen] NativeLLE evaluated");
1110 }
1111 SlgOpcode::NativeIsotopeDistribution => {
1112 vm_log!("[Webizen] NativeIsotopeDistribution evaluated");
1113 }
1114 SlgOpcode::NativeDeonticEval => {
1115 if !execute_snapshot_logic(arena, opcode, frame) {
1116 return None;
1117 }
1118 }
1119 SlgOpcode::NativeEpistemicEval(_) => {
1120 if !execute_snapshot_logic(arena, opcode, frame) {
1121 return None;
1122 }
1123 }
1124 SlgOpcode::NativeLinearConsume => {
1125 if let Some(q) = arena.find_mutable_quin(
1126 frame.subject_reg,
1127 frame.predicate_reg,
1128 frame.object_reg,
1129 ) {
1130 linear::consume_quin(q);
1131 } else {
1132 return None;
1133 }
1134 }
1135 SlgOpcode::NativeAspStableModels => {
1136 let mut rules = [NQuin::default(); asp::MAX_STABLE_MODELS];
1140 let nrules = arena.collect_active_quins(&mut rules);
1141 let mut out_worlds = [0; asp::MAX_STABLE_MODELS];
1142 let goal = frame_to_quin(frame);
1143 let world_count =
1144 asp::enumerate_stable_models(&goal, &rules[..nrules], &mut out_worlds);
1145 if world_count == 0 {
1146 return None;
1147 }
1148 frame.context_reg = out_worlds[world_count - 1];
1150 }
1151 SlgOpcode::NativeParaconsistentIsolate => {
1152 if !execute_paraconsistent_isolation(arena) {
1153 return None;
1154 }
1155 }
1156 SlgOpcode::NativeDialecticalSynthesis => {
1157 if !execute_dialectical_synthesis(arena, frame) {
1158 return None;
1159 }
1160 }
1161 SlgOpcode::NativeProbabilisticThreshold(_)
1162 | SlgOpcode::NativeDlSubsumption
1163 | SlgOpcode::NativeArgumentationGrounded
1164 | SlgOpcode::NativeMtlWithin(_)
1165 | SlgOpcode::NativeContraryToDuty
1166 | SlgOpcode::NativeCausalNecessary
1167 | SlgOpcode::NativeAbduce
1168 | SlgOpcode::NativeClosedWorld
1169 | SlgOpcode::NativeFuzzyConjunction(_)
1170 | SlgOpcode::NativeCtlExistsFinally
1171 | SlgOpcode::NativeCtlAlwaysGlobally
1172 | SlgOpcode::NativeModalNecessary
1173 | SlgOpcode::NativeModalPossible
1174 | SlgOpcode::NativeRcc8(_)
1175 | SlgOpcode::NativeRcc8Assert(_) => {
1176 let is_assert = matches!(opcode, SlgOpcode::NativeRcc8Assert(_));
1177 if !execute_snapshot_logic(arena, opcode, frame) {
1178 return None;
1179 }
1180 if is_assert {
1181 arena.write_table(frame_to_quin(frame));
1182 vm_log!("[Webizen] NativeRcc8Assert: asserted derived fact");
1183 }
1184 }
1185 SlgOpcode::NativeStewardQuorum(quorum) => {
1186 let mut scratch = [NQuin::default(); 512];
1187 let count = arena.collect_active_quins(&mut scratch);
1188 let stewards = crate::q_hash("q42:stewards");
1189 let mut matches = 0;
1190 for quin in &scratch[..count] {
1191 if quin.predicate == stewards && quin.object == frame.object_reg {
1193 matches += 1;
1194 }
1195 }
1196 if matches < quorum {
1197 vm_log!(
1198 "[Webizen] NativeStewardQuorum: failed. Found {}/{} stewards",
1199 matches,
1200 quorum
1201 );
1202 return None;
1203 }
1204 vm_log!(
1205 "[Webizen] NativeStewardQuorum: passed with {}/{} stewards",
1206 matches,
1207 quorum
1208 );
1209 }
1210 SlgOpcode::NativeRegisterRule => {
1211 if !arena.activate_staged_rule(frame.object_reg) {
1212 vm_log!(
1213 "[Webizen] NativeRegisterRule: unknown staged rule id {}",
1214 frame.object_reg
1215 );
1216 return None;
1217 }
1218 vm_log!(
1219 "[Webizen] NativeRegisterRule: activated staged rule {}",
1220 frame.object_reg
1221 );
1222 }
1223 SlgOpcode::NativeCanvasPlacement => {
1224 let mut scratch = [NQuin::default(); 512];
1225 let count = arena.collect_active_quins(&mut scratch);
1226 if !crate::domains::geospatial::canvas_rights::CanvasRightsModel::validate_placement(
1227 frame.subject_reg, frame.object_reg, frame.context_reg, &scratch[..count],
1231 ) {
1232 vm_log!("[Webizen] NativeCanvasPlacement: rejected by rights model");
1233 return None;
1234 }
1235 vm_log!("[Webizen] NativeCanvasPlacement: accepted");
1236 }
1237 SlgOpcode::NativeUnless => {
1238 let goal = frame_to_quin(frame);
1239 let property_path = (goal.predicate >> 8) & !DEFEATER_BIT;
1240 let defeater = compile_norm_quin(
1241 goal.subject,
1242 OP_PERMIT,
1243 property_path,
1244 goal.object,
1245 goal.context,
1246 0,
1247 true,
1248 );
1249 arena.write_table(defeater);
1250 }
1251 SlgOpcode::NativeRetrieveByActivation | SlgOpcode::NativeDecayMetadata => {
1252 vm_log!("[Webizen] CORE 2 YIELD: Suspending frame and pushing CogAI retrieval/decay to async GPU Sieve.");
1256 return None;
1257 }
1258 SlgOpcode::NativeManifoldLtl {
1259 mode,
1260 dimension,
1261 threshold_bits,
1262 at_least,
1263 } => {
1264 if !execute_manifold_ltl(arena, mode, dimension, threshold_bits, at_least) {
1265 return None;
1266 }
1267 }
1268 SlgOpcode::NativeManifoldAsp => {
1269 frame.object_reg = execute_manifold_asp(arena)?;
1270 }
1271 SlgOpcode::NativeLtlGlobally
1272 | SlgOpcode::NativeLtlFinally
1273 | SlgOpcode::NativeLtlNext
1274 | SlgOpcode::NativeLtlUntil
1275 | SlgOpcode::NativeLtlRelease => {
1276 if !execute_standard_ltl(arena, opcode, frame) {
1277 return None;
1278 }
1279 vm_log!("[Webizen] NativeLtl: temporal property held");
1280 }
1281 SlgOpcode::NativeAllenInterval(mode) => {
1282 let op = match mode {
1286 0 => spatio_temporal::TemporalOp::Before,
1287 1 => spatio_temporal::TemporalOp::Meets,
1288 2 => spatio_temporal::TemporalOp::Overlaps,
1289 3 => spatio_temporal::TemporalOp::Starts,
1290 4 => spatio_temporal::TemporalOp::During,
1291 5 => spatio_temporal::TemporalOp::Finishes,
1292 _ => spatio_temporal::TemporalOp::Equals,
1293 };
1294 let holds = spatio_temporal::evaluate_temporal(
1295 op,
1296 frame.subject_reg as i64,
1297 frame.predicate_reg as i64,
1298 frame.object_reg as i64,
1299 frame.context_reg as i64,
1300 );
1301 if !holds {
1302 return None; }
1304 vm_log!(
1305 "[Webizen] NativeAllenInterval: relation mode {} holds",
1306 mode
1307 );
1308 }
1309 SlgOpcode::NativeAllenIntervalAssert(mode) => {
1310 let op = match mode {
1311 0 => spatio_temporal::TemporalOp::Before,
1312 1 => spatio_temporal::TemporalOp::Meets,
1313 2 => spatio_temporal::TemporalOp::Overlaps,
1314 3 => spatio_temporal::TemporalOp::Starts,
1315 4 => spatio_temporal::TemporalOp::During,
1316 5 => spatio_temporal::TemporalOp::Finishes,
1317 _ => spatio_temporal::TemporalOp::Equals,
1318 };
1319 let holds = spatio_temporal::evaluate_temporal(
1320 op,
1321 frame.subject_reg as i64,
1322 frame.predicate_reg as i64,
1323 frame.object_reg as i64,
1324 frame.context_reg as i64,
1325 );
1326 if !holds {
1327 return None;
1328 }
1329 arena.write_table(frame_to_quin(frame));
1330 vm_log!("[Webizen] NativeAllenIntervalAssert: asserted derived fact");
1331 }
1332 SlgOpcode::NativeLorentzDistance
1333 | SlgOpcode::NativeTropicalDistance
1334 | SlgOpcode::NativeVerifyProofOfLocation => {
1335 }
1339 SlgOpcode::NativeCalcSimpsons(start_bits, end_bits, step_size_bits, kahan_bits) => {
1340 let start = f64::from_bits(start_bits);
1341 let end = f64::from_bits(end_bits);
1342 let step_size = f64::from_bits(step_size_bits as u64);
1343 let _kahan_compensation = f32::from_bits(kahan_bits);
1344
1345 let grid_data: Vec<u8> = vec![0u8; 1001 * 8]; let grid =
1348 crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1001).unwrap();
1349
1350 let result =
1351 crate::modalities::calculus::integrate_simpsons_chunked(&grid, step_size)
1352 .unwrap_or(f64::NAN);
1353 vm_log!(
1354 "[Webizen] NativeCalcSimpsons: [{}, {}] h={:.4} result={:.6}",
1355 start,
1356 end,
1357 step_size,
1358 result
1359 );
1360 }
1361 SlgOpcode::NativeCalcTrapezoidal(start_bits, end_bits, step_size_bits, kahan_bits) => {
1362 let start = f64::from_bits(start_bits);
1363 let end = f64::from_bits(end_bits);
1364 let step_size = f64::from_bits(step_size_bits as u64);
1365 let _kahan_compensation = f32::from_bits(kahan_bits);
1366
1367 let grid_data: Vec<u8> = vec![0u8; 1000 * 8]; let grid =
1370 crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1000).unwrap();
1371
1372 let result =
1373 crate::modalities::calculus::integrate_trapezoidal_chunked(&grid, step_size)
1374 .unwrap_or(f64::NAN);
1375 vm_log!(
1376 "[Webizen] NativeCalcTrapezoidal: [{}, {}] h={:.4} result={:.6}",
1377 start,
1378 end,
1379 step_size,
1380 result
1381 );
1382 }
1383 SlgOpcode::NativeCalcGpu(start_bits, end_bits, step_size_bits, kahan_bits) => {
1384 let start = f64::from_bits(start_bits);
1385 let end = f64::from_bits(end_bits);
1386 let step_size = f32::from_bits(step_size_bits);
1387 let _kahan_compensation = f32::from_bits(kahan_bits);
1388
1389 vm_log!(
1390 "[Webizen] NativeCalcGpu: GPU integration requested for [{}, {}] h={:.4}",
1391 start,
1392 end,
1393 step_size
1394 );
1395
1396 #[cfg(all(not(target_arch = "wasm32"), feature = "gpu-runtime"))]
1398 {
1399 use crate::modalities::calculus::gpu::{GpuIntegrator, PlatformGpuIntegrator};
1400 use std::path::Path;
1401
1402 if let Ok(handle) = tokio::runtime::Handle::try_current() {
1404 let gpu_result =
1405 handle.block_on(async { PlatformGpuIntegrator::new().await });
1406
1407 match gpu_result {
1408 Ok(mut gpu_integrator) => {
1409 let num_points = ((end - start) / step_size as f64) as usize;
1411 let size = (num_points * 8) as u64; let (aligned_offset, _remainder) =
1415 crate::modalities::calculus::resolve_aligned_byte_offset(0);
1416
1417 let temp_path = Path::new("calculus_grid.dat");
1419
1420 match gpu_integrator.integrate_simpsons_gpu(
1421 temp_path,
1422 aligned_offset,
1423 size,
1424 step_size,
1425 ) {
1426 Ok(result) => {
1427 vm_log!(
1428 "[Webizen] NativeCalcGpu: GPU integration complete result={:.6}",
1429 result
1430 );
1431 }
1433 Err(e) => {
1434 vm_log!(
1435 "[Webizen] NativeCalcGpu: GPU integration failed, falling back to CPU: {:?}",
1436 e
1437 );
1438 let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1440 let grid =
1441 crate::modalities::calculus::ContinuousGrid::new(
1442 &grid_data, 1001,
1443 )
1444 .unwrap();
1445 let cpu_result =
1446 crate::modalities::calculus::integrate_simpsons_chunked(
1447 &grid,
1448 step_size as f64,
1449 )
1450 .unwrap_or(f64::NAN);
1451 vm_log!(
1452 "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1453 cpu_result
1454 );
1455 }
1456 }
1457 }
1458 Err(e) => {
1459 vm_log!(
1460 "[Webizen] NativeCalcGpu: GPU initialization failed, falling back to CPU: {:?}",
1461 e
1462 );
1463 let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1465 let grid = crate::modalities::calculus::ContinuousGrid::new(
1466 &grid_data, 1001,
1467 )
1468 .unwrap();
1469 let cpu_result =
1470 crate::modalities::calculus::integrate_simpsons_chunked(
1471 &grid,
1472 step_size as f64,
1473 )
1474 .unwrap_or(f64::NAN);
1475 vm_log!(
1476 "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1477 cpu_result
1478 );
1479 }
1480 }
1481 } else {
1482 vm_log!(
1483 "[Webizen] NativeCalcGpu: Tokio runtime failed, using CPU fallback"
1484 );
1485 let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1486 let grid =
1487 crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1001)
1488 .unwrap();
1489 let cpu_result = crate::modalities::calculus::integrate_simpsons_chunked(
1490 &grid,
1491 step_size as f64,
1492 )
1493 .unwrap_or(f64::NAN);
1494 vm_log!(
1495 "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1496 cpu_result
1497 );
1498 }
1499 }
1500
1501 #[cfg(not(all(not(target_arch = "wasm32"), feature = "gpu-runtime")))]
1502 {
1503 vm_log!("[Webizen] NativeCalcGpu: GPU runtime unavailable, using CPU fallback");
1504 let grid_data: Vec<u8> = vec![0u8; 1001 * 8];
1505 let grid =
1506 crate::modalities::calculus::ContinuousGrid::new(&grid_data, 1001).unwrap();
1507 let cpu_result = crate::modalities::calculus::integrate_simpsons_chunked(
1508 &grid,
1509 step_size as f64,
1510 )
1511 .unwrap_or(f64::NAN);
1512 vm_log!(
1513 "[Webizen] NativeCalcGpu: CPU fallback result={:.6}",
1514 cpu_result
1515 );
1516 }
1517 }
1518 SlgOpcode::NativeQuboCompile => {
1519 vm_log!(
1520 "[Webizen] NativeQuboCompile: semantic subgraph โ blind QUBO matrix (Core 2)"
1521 );
1522 }
1523 SlgOpcode::NativeQuboEmitLinear(var, bits) => {
1524 let bias = f32::from_bits(bits);
1525 vm_log!("[Webizen] OP_EMIT_WEIGHT linear var={} bias={}", var, bias);
1526 }
1527 SlgOpcode::NativeQuboEmitCoupler(a, b, bits) => {
1528 let w = f32::from_bits(bits);
1529 vm_log!("[Webizen] OP_EMIT_WEIGHT coupler {}-{} weight={}", a, b, w);
1530 }
1531 SlgOpcode::NativeQuantumEgress(arch) => {
1532 vm_log!("[Webizen] CORE 3 YIELD: NativeQuantumEgress arch={} โ suspending for blind HTTP egress", arch);
1533 return None;
1534 }
1535 SlgOpcode::NativeQuantumIngress => {
1536 vm_log!(
1537 "[Webizen] NativeQuantumIngress: collapsing QPU response โ provenance Quins"
1538 );
1539 }
1540 }
1541
1542 instruction_pointer += 1;
1543 }
1544
1545 None
1546}
1547
1548impl VmFrame {
1549 #[inline(always)]
1551 pub fn metadata_hint(&self) -> u64 {
1552 self.predicate_reg & 0xFF
1553 }
1554}