Skip to main content

qualia_core_db/modalities/logic/
core.rs

1//! Core 1 Webizen Bytecode VM
2//! A `#![no_std]` compatible virtual machine that executes a fixed-size
3//! instruction set across the 48-byte Quins without triggering heap allocations.
4
5use crate::NQuin;
6
7/// The micro-instruction set (ISA) for the Core 1 Logic Engine.
8#[derive(Debug, Clone, Copy, PartialEq)]
9pub enum WebizenOpcode {
10    /// Compares the Quin's Subject to a hardcoded 60-bit ID
11    MatchSubject(u64),
12    /// Compares the Quin's Predicate to a hardcoded 60-bit ID
13    MatchPredicate(u64),
14    /// Compares the Quin's Object to a hardcoded 60-bit ID
15    MatchObject(u64),
16    /// Evaluates if the 5th Vector's bits match the target mask exactly
17    EvalMetadataMask(u32),
18    /// Extracts a u64 from the Quin (0=Subj, 1=Pred, 2=Obj, 3=Ctx) and stores it in the VM Register
19    BindRegister {
20        vector_id: u8,
21        register_index: usize,
22    },
23    /// Asserts that a VM register equals the given Quin vector
24    MatchRegister {
25        vector_id: u8,
26        register_index: usize,
27    },
28    /// Halts execution and returns false immediately if the prior condition failed
29    HaltIfFalse,
30    /// Yields a new generated Quin (The consequent of an implication `=>`)
31    EmitQuin {
32        subject_reg: usize,
33        predicate: u64,
34        object: u64,
35        context_reg: usize,
36    },
37    /// Continuous Constraint: Evaluates <
38    LessThan { vector_id: u8, value: f32 },
39    /// Continuous Constraint: Evaluates >
40    GreaterThan { vector_id: u8, value: f32 },
41    /// Continuous Constraint: Evaluates <=
42    LessOrEqual { vector_id: u8, value: f32 },
43    /// Continuous Constraint: Evaluates >=
44    GreaterOrEqual { vector_id: u8, value: f32 },
45    /// Temporal Logic: Always constraint (LTL)
46    Always(u64),
47    /// Temporal Logic: Eventually constraint (LTL)
48    Eventually(u64),
49    /// Temporal Logic: Next constraint (LTL)
50    Next(u64),
51    /// Yields a mathematically calculated Quin consequence
52    EmitCalculatedQuin {
53        subject_reg: usize,
54        predicate: u64,
55        object_calc_op: u8,
56        context_reg: usize,
57    },
58    /// Evaluates the 5th Metadata Vector confidence weight. If below threshold, tags consequence as Defeasible.
59    YieldConfidence(f32),
60    /// Triggers native mapping of a GGUF model pointer into the OS page cache
61    LoadModel(u64),
62    /// Cryptographically flushes a 512MB model mapping using Volatile Scrubbing
63    EvictModel(u64),
64}
65
66/// The Zero-Allocation Virtual Machine for N3Logic and Constraints.
67pub struct WebizenVM {
68    /// The local L1-cached execution stack for bound variables
69    pub registers: [Option<u64>; 16],
70    /// The maximum number of instructions allowed in a single rule block
71    pub bytecode_buffer: [Option<WebizenOpcode>; 64],
72    /// Shared reference to the orchestrator's cryptographic memory flush lock
73    pub scrubbing_lock: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
74    /// State tracking for suspended opcodes that yielded due to a hardware lock
75    pub yielded_op: Option<WebizenOpcode>,
76}
77
78impl WebizenVM {
79    /// Creates `WebizenVM` with the given state.
80    pub fn new() -> Self {
81        Self {
82            registers: [None; 16],
83            bytecode_buffer: [None; 64],
84            scrubbing_lock: None,
85            yielded_op: None,
86        }
87    }
88
89    /// Builder: sets `scrubbing_lock`.
90    pub fn with_scrubbing_lock(lock: std::sync::Arc<std::sync::atomic::AtomicBool>) -> Self {
91        let mut vm = Self::new();
92        vm.scrubbing_lock = Some(lock);
93        vm
94    }
95
96    /// Loads `bytecode`; error when absent/invalid.
97    pub fn load_bytecode(&mut self, instructions: &[WebizenOpcode]) {
98        self.bytecode_buffer.fill(None);
99        for (i, &op) in instructions.iter().enumerate().take(64) {
100            self.bytecode_buffer[i] = Some(op);
101        }
102    }
103
104    /// Serializes the current VM execution frame into a strictly-sized zero-allocation buffer
105    /// for offline suspension in the CRDT queue while awaiting M:N Guardianship signatures.
106    pub fn flatten_to_suspended(
107        &self,
108        agreement_id: u64,
109        threshold: u8,
110        current_quin: crate::NQuin,
111    ) -> crate::crdt::SuspendedTransaction {
112        crate::crdt::SuspendedTransaction {
113            agreement_id,
114            threshold,
115            collected_signatures: 0,
116            registers: self.registers,
117            bytecode_buffer: self.bytecode_buffer,
118            yielded_op: self.yielded_op,
119            suspended_quin: current_quin,
120        }
121    }
122
123    /// Evaluates a loaded constraint block against a target Quin.
124    pub fn execute_constraint(&mut self, quin: &NQuin) -> bool {
125        let mut condition_flag = true;
126
127        // Stochastic/Fuzzy confidence weight via the canonical FrameLayout ABI
128        // (shared encoding with fuzzy/probabilistic — was a divergent 16-bit form).
129        let _stochastic_weight = crate::frame_layout::truth_degree(quin.metadata);
130
131        for op in self.bytecode_buffer.iter().flatten() {
132            crate::telemetry::VM_CYCLES_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
133
134            match op {
135                WebizenOpcode::MatchSubject(val) => {
136                    condition_flag = quin.subject == *val;
137                }
138                WebizenOpcode::MatchPredicate(val) => {
139                    condition_flag = quin.predicate == *val;
140                }
141                WebizenOpcode::MatchObject(val) => {
142                    condition_flag = quin.object == *val;
143                }
144                WebizenOpcode::EvalMetadataMask(mask) => {
145                    let quin_mask = (quin.metadata & 0xFFFF) as u32;
146                    condition_flag = (quin_mask & mask) == *mask;
147                }
148                WebizenOpcode::BindRegister {
149                    vector_id,
150                    register_index,
151                } => {
152                    let value = match vector_id {
153                        0 => quin.subject,
154                        1 => quin.predicate,
155                        2 => quin.object,
156                        3 => quin.context,
157                        _ => 0,
158                    };
159                    self.registers[*register_index] = Some(value);
160                    condition_flag = true;
161                }
162                WebizenOpcode::MatchRegister {
163                    vector_id,
164                    register_index,
165                } => {
166                    if let Some(bound_val) = self.registers[*register_index] {
167                        let value = match vector_id {
168                            0 => quin.subject,
169                            1 => quin.predicate,
170                            2 => quin.object,
171                            3 => quin.context,
172                            _ => 0,
173                        };
174                        condition_flag = value == bound_val;
175                    } else {
176                        // Register unbound
177                        condition_flag = false;
178                    }
179                }
180                WebizenOpcode::HaltIfFalse => {
181                    if !condition_flag {
182                        return false;
183                    }
184                }
185                WebizenOpcode::LessThan { vector_id, value } => {
186                    condition_flag =
187                        Self::extract_float(quin, *vector_id).map_or(false, |v| v < *value);
188                }
189                WebizenOpcode::GreaterThan { vector_id, value } => {
190                    condition_flag =
191                        Self::extract_float(quin, *vector_id).map_or(false, |v| v > *value);
192                }
193                WebizenOpcode::LessOrEqual { vector_id, value } => {
194                    condition_flag =
195                        Self::extract_float(quin, *vector_id).map_or(false, |v| v <= *value);
196                }
197                WebizenOpcode::GreaterOrEqual { vector_id, value } => {
198                    condition_flag =
199                        Self::extract_float(quin, *vector_id).map_or(false, |v| v >= *value);
200                }
201                WebizenOpcode::Always(stress_threshold) => {
202                    crate::telemetry::ATOMIC_INTEGRATION_STEPS
203                        .fetch_add(50, std::sync::atomic::Ordering::Relaxed);
204                    condition_flag = Self::extract_float(quin, 2)
205                        .map_or(false, |stress| stress < *stress_threshold as f32);
206                }
207                WebizenOpcode::Eventually(stress_threshold) => {
208                    crate::telemetry::ATOMIC_INTEGRATION_STEPS
209                        .fetch_add(50, std::sync::atomic::Ordering::Relaxed);
210                    condition_flag = Self::extract_float(quin, 2)
211                        .map_or(false, |stress| stress >= *stress_threshold as f32);
212                }
213                WebizenOpcode::Next(stress_threshold) => {
214                    crate::telemetry::ATOMIC_INTEGRATION_STEPS
215                        .fetch_add(50, std::sync::atomic::Ordering::Relaxed);
216                    condition_flag = Self::extract_float(quin, 2)
217                        .map_or(false, |stress| stress == *stress_threshold as f32);
218                }
219                WebizenOpcode::YieldConfidence(threshold) => {
220                    let stochastic_weight = crate::frame_layout::truth_degree(quin.metadata);
221                    if stochastic_weight < *threshold {
222                        condition_flag = false; // For raw constraints, it fails the assertion
223                    }
224                }
225                WebizenOpcode::LoadModel(model_id) => {
226                    if let Some(ref lock) = self.scrubbing_lock {
227                        if lock.load(std::sync::atomic::Ordering::Acquire) {
228                            self.yielded_op = Some(WebizenOpcode::LoadModel(*model_id));
229                            return false; // Suspend execution
230                        }
231                    }
232                }
233                WebizenOpcode::EvictModel(_) => {}
234                WebizenOpcode::EmitQuin { .. } | WebizenOpcode::EmitCalculatedQuin { .. } => {
235                    // Handled exclusively by `execute_implication`
236                }
237            }
238        }
239
240        condition_flag
241    }
242
243    /// Evaluates an N3 Implication `=>` constraint against a target Quin.
244    /// Returns `Some(NQuin)` if the antecedent passes and yields a consequence.
245    pub fn execute_implication(&mut self, quin: &NQuin) -> Option<NQuin> {
246        let mut condition_flag = true;
247        let mut emitted_quin = None;
248        let mut defeasible_tag = false;
249
250        for op in self.bytecode_buffer.iter().flatten() {
251            crate::telemetry::VM_CYCLES_COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
252
253            match op {
254                WebizenOpcode::MatchSubject(val) => condition_flag = quin.subject == *val,
255                WebizenOpcode::MatchPredicate(val) => condition_flag = quin.predicate == *val,
256                WebizenOpcode::MatchObject(val) => condition_flag = quin.object == *val,
257                WebizenOpcode::EvalMetadataMask(mask) => {
258                    let quin_mask = (quin.metadata & 0xFFFF) as u32;
259                    condition_flag = (quin_mask & mask) == *mask;
260                }
261                WebizenOpcode::BindRegister {
262                    vector_id,
263                    register_index,
264                } => {
265                    let value = match vector_id {
266                        0 => quin.subject,
267                        1 => quin.predicate,
268                        2 => quin.object,
269                        3 => quin.context,
270                        _ => 0,
271                    };
272                    self.registers[*register_index] = Some(value);
273                    condition_flag = true;
274                }
275                WebizenOpcode::MatchRegister {
276                    vector_id,
277                    register_index,
278                } => {
279                    if let Some(bound_val) = self.registers[*register_index] {
280                        let value = match vector_id {
281                            0 => quin.subject,
282                            1 => quin.predicate,
283                            2 => quin.object,
284                            3 => quin.context,
285                            _ => 0,
286                        };
287                        condition_flag = value == bound_val;
288                    } else {
289                        condition_flag = false;
290                    }
291                }
292                WebizenOpcode::HaltIfFalse => {
293                    if !condition_flag {
294                        return None;
295                    }
296                }
297                WebizenOpcode::EmitQuin {
298                    subject_reg,
299                    predicate,
300                    object,
301                    context_reg,
302                } => {
303                    if condition_flag {
304                        let s = self.registers[*subject_reg].unwrap_or(0);
305                        let c = self.registers[*context_reg].unwrap_or(0);
306
307                        let mut resulting_quin = NQuin {
308                            subject: s,
309                            predicate: *predicate,
310                            object: *object,
311                            context: c,
312                            metadata: quin.metadata,
313                            parity: 0,
314                        };
315
316                        let clock = quin.extract_lamport_clock();
317                        if clock < 0x1FFF_FFFF {
318                            resulting_quin.set_lamport_clock(clock + 1);
319                        }
320                        if defeasible_tag {
321                            resulting_quin.metadata |= 1 << 60;
322                        }
323                        emitted_quin = Some(resulting_quin);
324                    }
325                }
326                WebizenOpcode::LessThan { vector_id, value } => {
327                    condition_flag =
328                        Self::extract_float(quin, *vector_id).map_or(false, |v| v < *value);
329                }
330                WebizenOpcode::GreaterThan { vector_id, value } => {
331                    condition_flag =
332                        Self::extract_float(quin, *vector_id).map_or(false, |v| v > *value);
333                }
334                WebizenOpcode::LessOrEqual { vector_id, value } => {
335                    condition_flag =
336                        Self::extract_float(quin, *vector_id).map_or(false, |v| v <= *value);
337                }
338                WebizenOpcode::GreaterOrEqual { vector_id, value } => {
339                    condition_flag =
340                        Self::extract_float(quin, *vector_id).map_or(false, |v| v >= *value);
341                }
342                WebizenOpcode::Always(stress_threshold) => {
343                    crate::telemetry::ATOMIC_INTEGRATION_STEPS
344                        .fetch_add(50, std::sync::atomic::Ordering::Relaxed);
345                    condition_flag = Self::extract_float(quin, 2)
346                        .map_or(false, |stress| stress < *stress_threshold as f32);
347                }
348                WebizenOpcode::Eventually(stress_threshold) => {
349                    crate::telemetry::ATOMIC_INTEGRATION_STEPS
350                        .fetch_add(50, std::sync::atomic::Ordering::Relaxed);
351                    condition_flag = Self::extract_float(quin, 2)
352                        .map_or(false, |stress| stress >= *stress_threshold as f32);
353                }
354                WebizenOpcode::Next(stress_threshold) => {
355                    crate::telemetry::ATOMIC_INTEGRATION_STEPS
356                        .fetch_add(50, std::sync::atomic::Ordering::Relaxed);
357                    condition_flag = Self::extract_float(quin, 2)
358                        .map_or(false, |stress| stress == *stress_threshold as f32);
359                }
360                WebizenOpcode::EmitCalculatedQuin {
361                    subject_reg,
362                    predicate,
363                    object_calc_op,
364                    context_reg,
365                } => {
366                    if condition_flag {
367                        let s = self.registers[*subject_reg].unwrap_or(0);
368                        let c = self.registers[*context_reg].unwrap_or(0);
369
370                        // Example calculated transformation (e.g. op 1 = mass * accel placeholder)
371                        let calc_val = match object_calc_op {
372                            1 => 42.0_f32, // Mocked math transformation
373                            _ => 0.0_f32,
374                        };
375
376                        let mut resulting_quin = NQuin {
377                            subject: s,
378                            predicate: *predicate,
379                            // Tag the object as a canonical inline float (FrameLayout).
380                            object: crate::frame_layout::pack_float_object(calc_val),
381                            context: c,
382                            metadata: quin.metadata,
383                            parity: 0,
384                        };
385
386                        let clock = quin.extract_lamport_clock();
387                        if clock < 0x1FFF_FFFF {
388                            resulting_quin.set_lamport_clock(clock + 1);
389                        }
390                        if defeasible_tag {
391                            resulting_quin.metadata |= 1 << 60;
392                        }
393                        emitted_quin = Some(resulting_quin);
394                    }
395                }
396                WebizenOpcode::YieldConfidence(threshold) => {
397                    let stochastic_weight = crate::frame_layout::truth_degree(quin.metadata);
398                    if stochastic_weight < *threshold {
399                        defeasible_tag = true;
400                    }
401                }
402                WebizenOpcode::LoadModel(model_id) => {
403                    if let Some(ref lock) = self.scrubbing_lock {
404                        if lock.load(std::sync::atomic::Ordering::Acquire) {
405                            self.yielded_op = Some(WebizenOpcode::LoadModel(*model_id));
406                            return None; // Suspend execution yielding no consequence yet
407                        }
408                    }
409                }
410                WebizenOpcode::EvictModel(_) => {}
411            }
412        }
413
414        emitted_quin
415    }
416
417    /// Extracts a tagged floating point value from a given 64-bit Quin vector.
418    ///
419    /// Uses the canonical inline datatype tag (`frame_layout::INLINE_TAG_FLOAT`,
420    /// `0b101 << 60`). This resolves the previously-deferred conflict where `core.rs`
421    /// tagged f32s with `0x1` — the same bits `resolver` uses for `xsd:integer`. The
422    /// alignment now lives in the FrameLayout ABI (the coordinating module), so the
423    /// float tag no longer collides with the integer tag.
424    #[inline(always)]
425    fn extract_float(quin: &NQuin, vector_id: u8) -> Option<f32> {
426        let val = match vector_id {
427            0 => quin.subject,
428            1 => quin.predicate,
429            2 => quin.object,
430            3 => quin.context,
431            _ => return None,
432        };
433
434        if val & crate::frame_layout::INLINE_TAG_MASK == crate::frame_layout::INLINE_TAG_FLOAT {
435            Some(extract_inline_float(val))
436        } else {
437            None
438        }
439    }
440
441    /// Prunes neural hallucinations: If a Defeasible claim is contradicted by a hard physical fact, it is removed.
442    pub fn prune_defeasible_claims(qualia_graph: &mut [NQuin]) -> usize {
443        let mut retained = 0;
444
445        for read_idx in 0..qualia_graph.len() {
446            let quin = qualia_graph[read_idx];
447            let is_defeasible = (quin.metadata & (1 << 60)) != 0;
448            let has_hard_fact_for_subject = qualia_graph.iter().any(|candidate| {
449                candidate.subject == quin.subject && (candidate.metadata & (1 << 60)) == 0
450            });
451
452            if is_defeasible && has_hard_fact_for_subject {
453                continue;
454            }
455
456            qualia_graph[retained] = quin;
457            retained += 1;
458        }
459
460        for slot in &mut qualia_graph[retained..] {
461            *slot = NQuin::default();
462        }
463
464        retained
465    }
466}
467
468/// Zero-allocation float extraction fast-path.
469/// Extracts a single-precision float stored in the lower 32 bits of a u64 vector.
470#[inline(always)]
471pub fn extract_inline_float(object_vector: u64) -> f32 {
472    // Mask out the top 32 bits entirely (dropping the Tag and Padding)
473    let raw_bits = (object_vector & 0x0000_0000_FFFF_FFFF) as u32;
474    f32::from_bits(raw_bits)
475}
476
477/// The Translation Layer. Parses N3Logic/SHACL into bytecode arrays.
478pub struct WebizenCompiler;
479
480impl WebizenCompiler {
481    const MOCK_CONSTRAINT: [WebizenOpcode; 4] = [
482        WebizenOpcode::MatchPredicate(100), // Predicate 100 = 'age'
483        WebizenOpcode::HaltIfFalse,
484        // (A true engine would have a GreaterThan opcode here, using MatchObject for now)
485        WebizenOpcode::MatchObject(18),
486        WebizenOpcode::HaltIfFalse,
487    ];
488
489    const DIAGNOSTIC_CONSTRAINT: [WebizenOpcode; 6] = [
490        WebizenOpcode::MatchPredicate(100), // e.g. "has_symptom"
491        WebizenOpcode::MatchObject(200),    // e.g. "Fever"
492        WebizenOpcode::HaltIfFalse,
493        WebizenOpcode::BindRegister {
494            vector_id: 0,
495            register_index: 0,
496        },
497        WebizenOpcode::BindRegister {
498            vector_id: 3,
499            register_index: 1,
500        },
501        // Emits a Diagnosis Quin
502        WebizenOpcode::EmitQuin {
503            subject_reg: 0,
504            predicate: 300,
505            object: 400,
506            context_reg: 1,
507        },
508    ];
509
510    /// Provides a deterministic SHACL constraint fixture as Webizen bytecode.
511    /// Example: `[Shape] sh:property [ sh:path ex:age ; sh:minInclusive 18 ]`
512    pub fn compile_mock_constraint() -> &'static [WebizenOpcode] {
513        &Self::MOCK_CONSTRAINT
514    }
515
516    /// Compiles a medical N3 constraint for Differential Diagnostics.
517    /// Example: IF Subject has symptom SNOMED:Fever => Yield Diagnosis Potential
518    pub fn compile_diagnostic_constraint() -> &'static [WebizenOpcode] {
519        &Self::DIAGNOSTIC_CONSTRAINT
520    }
521}
522
523#[derive(Debug, Clone, Copy, PartialEq, Eq)]
524pub enum DiagnosticError {
525    OutputBufferFull,
526}
527
528/// The Informatics Subsystem (Differential Diagnostics)
529/// Executes N3Logic bytecode constraints over a subset of Quins (e.g., from a .q42 file)
530/// to derive deterministic inferences natively on the edge, replacing the legacy WebAssembly/Prolog engine.
531pub fn execute_differential_diagnostics(
532    qualia_graph: &[NQuin],
533    out: &mut [NQuin],
534) -> Result<usize, DiagnosticError> {
535    let mut written = 0;
536    let mut vm = WebizenVM::new();
537    let diagnostic_rules = WebizenCompiler::compile_diagnostic_constraint();
538    vm.load_bytecode(diagnostic_rules);
539
540    for quin in qualia_graph {
541        if let Some(inferred_quin) = vm.execute_implication(quin) {
542            if written >= out.len() {
543                return Err(DiagnosticError::OutputBufferFull);
544            }
545
546            out[written] = inferred_quin;
547            written += 1;
548        }
549    }
550
551    Ok(written)
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    #[test]
559    fn test_webizen_vm_execution() {
560        let mut vm = WebizenVM::new();
561        let bytecode = vec![
562            WebizenOpcode::MatchPredicate(42),
563            WebizenOpcode::HaltIfFalse,
564            WebizenOpcode::BindRegister {
565                vector_id: 0,
566                register_index: 0,
567            },
568            WebizenOpcode::HaltIfFalse,
569        ];
570        vm.load_bytecode(&bytecode);
571
572        // Matching Quin
573        let valid_quin = NQuin {
574            subject: 999,
575            predicate: 42,
576            object: 0,
577            context: 0,
578            metadata: 0,
579            parity: 0,
580        };
581
582        // Fails predicate match
583        let invalid_quin = NQuin {
584            subject: 999,
585            predicate: 99,
586            object: 0,
587            context: 0,
588            metadata: 0,
589            parity: 0,
590        };
591
592        assert_eq!(
593            vm.execute_constraint(&valid_quin),
594            true,
595            "VM failed to execute valid bytecode constraint"
596        );
597        assert_eq!(
598            vm.registers[0],
599            Some(999),
600            "VM failed to bind Subject to Register 0"
601        );
602
603        assert_eq!(
604            vm.execute_constraint(&invalid_quin),
605            false,
606            "VM erroneously passed invalid quin constraint"
607        );
608    }
609
610    #[test]
611    fn test_qualia_n3_implication() {
612        let mut vm = WebizenVM::new();
613        // Rule: { ?x predicate 42 } => { ?x predicate 100 }
614        let bytecode = vec![
615            WebizenOpcode::MatchPredicate(42),
616            WebizenOpcode::HaltIfFalse,
617            WebizenOpcode::BindRegister {
618                vector_id: 0,
619                register_index: 0,
620            }, // Bind Subject
621            WebizenOpcode::BindRegister {
622                vector_id: 3,
623                register_index: 1,
624            }, // Bind Context
625            WebizenOpcode::EmitQuin {
626                subject_reg: 0,
627                predicate: 100,
628                object: 999,
629                context_reg: 1,
630            },
631        ];
632        vm.load_bytecode(&bytecode);
633
634        // The input antecedent
635        let _input_quin = crate::q_turtle!("Alice", "knows", "Bob");
636        // q_turtle! hashes "knows" to something, but we hardcoded predicate 42 in bytecode, so let's mock it
637        let trigger_quin = NQuin {
638            subject: 123,
639            predicate: 42,
640            object: 456,
641            context: 789,
642            metadata: 0b01 << 61,
643            parity: 0,
644        };
645
646        let result = vm.execute_implication(&trigger_quin);
647        assert!(
648            result.is_some(),
649            "Implication should have yielded a consequent Quin"
650        );
651
652        let output = result.unwrap();
653        assert_eq!(output.subject, 123, "Subject was not bound properly");
654        assert_eq!(
655            output.predicate, 100,
656            "Consequent predicate not emitted properly"
657        );
658        assert_eq!(output.object, 999, "Consequent object not emitted properly");
659        assert_eq!(output.context, 789, "Context was not carried over");
660        assert_eq!(
661            output.identify_routing_lane(),
662            crate::PermissiveRoutingLane::EnforcePermissiveCommons,
663            "Routing lane was not inherited"
664        );
665        assert_eq!(
666            output.extract_lamport_clock(),
667            1,
668            "Lamport clock did not advance"
669        );
670
671        // Let's verify q_turtle compile-time macro works
672        let qt = crate::q_turtle!("Alice", "knows", "Bob");
673        assert_eq!(qt.subject, crate::q_hash("Alice"));
674        assert_eq!(qt.predicate, crate::q_hash("knows"));
675        assert_eq!(qt.object, crate::q_hash("Bob"));
676        assert_eq!(
677            qt.identify_routing_lane(),
678            crate::PermissiveRoutingLane::EnforcePermissiveCommons
679        );
680    }
681
682    #[test]
683    fn test_webizen_float_logic() {
684        let mut vm = WebizenVM::new();
685        // Pack 3.14 as a canonical inline float (FrameLayout INLINE_TAG_FLOAT).
686        let float_val = 3.14_f32;
687        let tagged_object = crate::frame_layout::pack_float_object(float_val);
688
689        let q = NQuin {
690            subject: 0,
691            predicate: 0,
692            object: tagged_object,
693            context: 0,
694            metadata: 0,
695            parity: 0,
696        };
697
698        let bytecode = vec![
699            WebizenOpcode::LessThan {
700                vector_id: 2,
701                value: 4.0,
702            }, // 3.14 < 4.0
703            WebizenOpcode::HaltIfFalse,
704            WebizenOpcode::GreaterThan {
705                vector_id: 2,
706                value: 3.0,
707            }, // 3.14 > 3.0
708            WebizenOpcode::HaltIfFalse,
709        ];
710
711        vm.load_bytecode(&bytecode);
712        assert_eq!(
713            vm.execute_constraint(&q),
714            true,
715            "VM failed to execute continuous float bounds"
716        );
717    }
718
719    #[test]
720    fn test_prune_defeasible_claims_partitions_in_place() {
721        let hard_fact = NQuin {
722            subject: 1,
723            predicate: 10,
724            object: 100,
725            context: 7,
726            metadata: 0,
727            parity: 0,
728        };
729        let defeasible_same_subject = NQuin {
730            subject: 1,
731            predicate: 11,
732            object: 101,
733            context: 7,
734            metadata: 1 << 60,
735            parity: 0,
736        };
737        let defeasible_other_subject = NQuin {
738            subject: 2,
739            predicate: 12,
740            object: 102,
741            context: 7,
742            metadata: 1 << 60,
743            parity: 0,
744        };
745
746        let mut graph = [hard_fact, defeasible_same_subject, defeasible_other_subject];
747        let retained = WebizenVM::prune_defeasible_claims(&mut graph);
748
749        assert_eq!(retained, 2);
750        assert_eq!(graph[0], hard_fact);
751        assert_eq!(graph[1], defeasible_other_subject);
752        assert_eq!(graph[2], NQuin::default());
753    }
754
755    #[test]
756    fn test_execute_differential_diagnostics_writes_to_output_buffer() {
757        let trigger_quin = NQuin {
758            subject: 123,
759            predicate: 100,
760            object: 200,
761            context: 789,
762            metadata: 0b01 << 61,
763            parity: 0,
764        };
765        let mut out = [NQuin::default(); 1];
766
767        let written = execute_differential_diagnostics(&[trigger_quin], &mut out).unwrap();
768
769        assert_eq!(written, 1);
770        assert_eq!(out[0].subject, 123);
771        assert_eq!(out[0].predicate, 300);
772        assert_eq!(out[0].object, 400);
773        assert_eq!(out[0].context, 789);
774    }
775
776    #[test]
777    fn test_execute_differential_diagnostics_reports_output_overflow() {
778        let trigger = NQuin {
779            subject: 123,
780            predicate: 100,
781            object: 200,
782            context: 789,
783            metadata: 0,
784            parity: 0,
785        };
786        let inputs = [
787            trigger,
788            NQuin {
789                subject: 456,
790                ..trigger
791            },
792        ];
793        let mut out = [NQuin::default(); 1];
794
795        let result = execute_differential_diagnostics(&inputs, &mut out);
796
797        assert_eq!(result, Err(DiagnosticError::OutputBufferFull));
798    }
799}