Skip to main content

wellfare_core/
webizen.rs

1/// WebizenVM — zero-allocation constraint engine for health policy enforcement.
2///
3/// Port of the Core 1 Webizen from qualia-core-db, extended with numeric comparison
4/// opcodes needed by the N3 clinical rules and SHACL health constraints.
5/// No wgpu or external deps — compiles in the default WASM binary.
6///
7/// Routing lanes match qualiaDB PermissiveRoutingLane:
8///   0 = PassthroughStandard       — local queries, telemetry
9///   1 = EnforcePermissiveCommons  — cooperative obligation gates
10///   2 = EnforceBilateralMicroCommons — N3Logic / guardian rules (requires identity)
11///   3 = SpatiotemporalAmbiguous   — GeoSPARQL / NPU path (future)
12
13/// One instruction in the Webizen ISA.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub enum WebizenOpcode {
16    /// Exact-match opcodes (match qualiaDB Core 1)
17    MatchSubject(u64),
18    MatchPredicate(u64),
19    MatchObject(u64),
20    EvalMetadataMask(u32),
21    BindRegister {
22        vector_id: u8,
23        register_index: usize,
24    },
25    MatchRegister {
26        vector_id: u8,
27        register_index: usize,
28    },
29    HaltIfFalse,
30    /// Numeric comparison opcodes (extension for N3Logic rules)
31    /// Compare the float value in register`register_index` against threshold.
32    LessThan {
33        register_index: usize,
34        threshold: f64,
35    },
36    GreaterThan {
37        register_index: usize,
38        threshold: f64,
39    },
40    /// Load a literal f64 into a float register slot (slots 8-15).
41    LoadFloat {
42        register_index: usize,
43        value: f64,
44    },
45    /// Halt-and-pass if the condition is false (inverse of HaltIfFalse).
46    HaltIfTrue,
47}
48
49/// Routing lane constants matching qualiaDB PermissiveRoutingLane.
50pub const LANE_PASSTHROUGH: u8 = 0;
51pub const LANE_PERMISSIVE: u8 = 1;
52pub const LANE_BILATERAL: u8 = 2;
53pub const LANE_SPATIOTEMPORAL: u8 = 3;
54
55/// A named constraint rule: bytecode + routing lane.
56pub struct WebizenRule {
57    pub name: &'static str,
58    pub routing_lane: u8,
59    pub bytecode: &'static [WebizenOpcode],
60}
61
62/// Zero-allocation VM: 16 u64 registers (0-7) + 16 f64 float slots (8-15 via float_regs).
63pub struct WebizenVM {
64    pub registers: [Option<u64>; 16],
65    pub float_regs: [f64; 16],
66    bytecode_buf: [Option<WebizenOpcode>; 64],
67}
68
69impl WebizenVM {
70    /// Creates a new instance.
71    pub fn new() -> Self {
72        Self {
73            registers: [None; 16],
74            float_regs: [0.0; 16],
75            bytecode_buf: [None; 64],
76        }
77    }
78
79    /// Loads Webizen bytecode.
80    pub fn load_bytecode(&mut self, ops: &[WebizenOpcode]) {
81        for slot in self.bytecode_buf.iter_mut() {
82            *slot = None;
83        }
84        for (i, &op) in ops.iter().enumerate().take(64) {
85            self.bytecode_buf[i] = Some(op);
86        }
87    }
88
89    /// Evaluate the loaded bytecode against a quin tuple (s,p,o,c,m).
90    /// Returns `true` if all constraints pass.
91    pub fn execute(&mut self, s: u64, p: u64, o: u64, c: u64, m: u64) -> bool {
92        let mut flag = true;
93        for op in self.bytecode_buf.iter().flatten().copied() {
94            match op {
95                WebizenOpcode::MatchSubject(v) => flag = s == v,
96                WebizenOpcode::MatchPredicate(v) => flag = p == v,
97                WebizenOpcode::MatchObject(v) => flag = o == v,
98                WebizenOpcode::EvalMetadataMask(mask) => {
99                    flag = ((m & 0xFFFF) as u32 & mask) == mask;
100                }
101                WebizenOpcode::BindRegister {
102                    vector_id,
103                    register_index,
104                } => {
105                    let v = match vector_id {
106                        0 => s,
107                        1 => p,
108                        2 => o,
109                        3 => c,
110                        _ => 0,
111                    };
112                    self.registers[register_index] = Some(v);
113                    flag = true;
114                }
115                WebizenOpcode::MatchRegister {
116                    vector_id,
117                    register_index,
118                } => {
119                    let v = match vector_id {
120                        0 => s,
121                        1 => p,
122                        2 => o,
123                        3 => c,
124                        _ => 0,
125                    };
126                    flag = self.registers[register_index] == Some(v);
127                }
128                WebizenOpcode::LoadFloat {
129                    register_index,
130                    value,
131                } => {
132                    self.float_regs[register_index] = value;
133                    flag = true;
134                }
135                WebizenOpcode::LessThan {
136                    register_index,
137                    threshold,
138                } => {
139                    flag = self.float_regs[register_index] < threshold;
140                }
141                WebizenOpcode::GreaterThan {
142                    register_index,
143                    threshold,
144                } => {
145                    flag = self.float_regs[register_index] > threshold;
146                }
147                WebizenOpcode::HaltIfFalse => {
148                    if !flag {
149                        return false;
150                    }
151                }
152                WebizenOpcode::HaltIfTrue => {
153                    if flag {
154                        return true;
155                    }
156                }
157            }
158        }
159        flag
160    }
161
162    /// Evaluate numeric thresholds only (no quin context needed).
163    /// Loads `value` into float register 0 and runs comparison opcodes.
164    pub fn check_threshold(&mut self, value: f64, ops: &[WebizenOpcode]) -> bool {
165        self.float_regs[0] = value;
166        self.load_bytecode(ops);
167        self.execute(0, 0, 0, 0, 0)
168    }
169}
170
171/// Pre-compiled SHACL access-profile constraints from shapes.rs, expressed as
172/// WebizenOpcode bytecode for per-quin evaluation (W6 requirement).
173///
174/// These operate on Lexicon IDs — the JS Lexicon assigns u64 to each URI/literal.
175/// For policy gates, we check the routing lane in the metadata field.
176pub mod policy_rules {
177    use super::*;
178
179    // Routing lane 1 (PermissiveCommons) — cooperative work obligation satisfied gate.
180    // Bytecode: EvalMetadataMask(MASK_WORK_OBLIGATION_SATISFIED = 0b0000_1000 = 8)
181    pub const COOPERATIVE_OBLIGATION_GATE: &[WebizenOpcode] = &[
182        WebizenOpcode::EvalMetadataMask(0x0008),
183        WebizenOpcode::HaltIfFalse,
184    ];
185
186    // Routing lane 2 (BilateralMicroCommons) — guardian identity verified.
187    // Bytecode: EvalMetadataMask(MASK_AUTHENTICATED_NATURAL_PERSON = 0b0000_0001 = 1)
188    pub const GUARDIAN_IDENTITY_GATE: &[WebizenOpcode] = &[
189        WebizenOpcode::EvalMetadataMask(0x0001),
190        WebizenOpcode::HaltIfFalse,
191    ];
192
193    // Routing lane 2 — bilateral commercial gate blocked.
194    // Bytecode: EvalMetadataMask(MASK_COMMERCIAL_BILLABLE_GATE = 0b0000_0100 = 4) → halt if set.
195    pub const COMMERCIAL_BLOCK_GATE: &[WebizenOpcode] = &[
196        WebizenOpcode::EvalMetadataMask(0x0004),
197        WebizenOpcode::HaltIfTrue, // if commercial flag is set, reject
198    ];
199}
200
201/// Evaluate a named policy constraint against a quin.
202/// Returns `(passed: bool, lane: u8)`.
203pub fn evaluate_policy_constraint(
204    name: &str,
205    s: u64,
206    p: u64,
207    o: u64,
208    c: u64,
209    m: u64,
210) -> (bool, u8) {
211    let mut vm = WebizenVM::new();
212    let (ops, lane) = match name {
213        "cooperative_obligation" => (policy_rules::COOPERATIVE_OBLIGATION_GATE, LANE_PERMISSIVE),
214        "guardian_identity" => (policy_rules::GUARDIAN_IDENTITY_GATE, LANE_BILATERAL),
215        "commercial_block" => (policy_rules::COMMERCIAL_BLOCK_GATE, LANE_BILATERAL),
216        _ => return (true, LANE_PASSTHROUGH), // unknown constraint → passthrough
217    };
218    vm.load_bytecode(ops);
219    (vm.execute(s, p, o, c, m), lane)
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn test_numeric_comparison() {
228        let mut vm = WebizenVM::new();
229        // sleepHours < 6 — should pass for 5.5h
230        let ops = &[
231            WebizenOpcode::LessThan {
232                register_index: 0,
233                threshold: 6.0,
234            },
235            WebizenOpcode::HaltIfFalse,
236        ];
237        assert!(vm.check_threshold(5.5, ops), "5.5h should be < 6h");
238        assert!(!vm.check_threshold(7.0, ops), "7h should not be < 6h");
239    }
240
241    #[test]
242    fn test_policy_gate_passthrough() {
243        // metadata = 0 → no obligation satisfied → gate should reject
244        let (passed, lane) = evaluate_policy_constraint("cooperative_obligation", 0, 0, 0, 0, 0);
245        assert!(!passed);
246        assert_eq!(lane, LANE_PERMISSIVE);
247    }
248
249    #[test]
250    fn test_policy_gate_satisfied() {
251        // metadata with MASK_WORK_OBLIGATION_SATISFIED (bit 3) set
252        let m = 0x0008u64;
253        let (passed, lane) = evaluate_policy_constraint("cooperative_obligation", 0, 0, 0, 0, m);
254        assert!(passed);
255        assert_eq!(lane, LANE_PERMISSIVE);
256    }
257}