Skip to main content

qualia_core_db/poet_host/
mod.rs

1//! Vibe execution host over a caller-owned Quin snapshot (P5).
2//!
3//! Scripts never write `parity`. The host seals via `NQuin::calculate_parity`.
4//! The host is independent of Poet, which is one UI/client of it. Document NLP
5//! lives in `crate::nlp`, next to `text_span` and `lexicon`.
6
7pub mod bridge;
8pub mod catalog;
9pub mod catalog_ttl;
10pub mod invoke;
11mod scan;
12mod values;
13pub mod scoped_effects;
14pub mod vibe_sentinel;
15#[cfg(not(target_arch = "wasm32"))]
16pub mod native_authority;
17
18use scan::{collect_matches, subject_present};
19pub use values::format_value;
20pub(crate) use values::{hash_val, value_to_quin};
21use values::{reifier_quin, shape_local_name};
22
23use crate::lexicon::generate_60bit_token;
24use crate::NQuin;
25use vibe::{eval_cell, eval_function, load_program, Diagnostic, Env, Host, Value};
26
27/// Topics `pulse.publish` may use in 0.1. Anything else is E500.
28pub const PULSE_ALLOW_PREFIXES: &[&str] = &["clinic/", "poet/", "pulse/"];
29
30/// Admission and coalescing policy for ticks under load (T68).
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum TickPolicy {
33    /// Process every tick, even if behind (may cause lag).
34    ProcessAll,
35    /// Coalesce: if a tick is in progress, drop intermediate ticks
36    /// and process only the latest. Default.
37    Coalesce,
38    /// Drop ticks while processing (may lose events).
39    Drop,
40}
41
42impl Default for TickPolicy {
43    /// `Coalesce` — drop intermediate ticks while one is in flight.
44    fn default() -> Self {
45        Self::Coalesce
46    }
47}
48
49/// State machine managing tick admission under load (T68).
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct TickController {
52    pub policy: TickPolicy,
53    pub in_flight: bool,
54    pub pending_ticks: usize,
55    pub total_processed: u64,
56    pub total_coalesced: u64,
57    pub total_dropped: u64,
58}
59
60impl Default for TickController {
61    /// Controller under the default `Coalesce` policy.
62    fn default() -> Self {
63        Self::new(TickPolicy::Coalesce)
64    }
65}
66
67impl TickController {
68    /// Fresh controller under `policy` with all counters zeroed.
69    pub fn new(policy: TickPolicy) -> Self {
70        Self {
71            policy,
72            in_flight: false,
73            pending_ticks: 0,
74            total_processed: 0,
75            total_coalesced: 0,
76            total_dropped: 0,
77        }
78    }
79
80    /// Request a new tick. Returns `true` if the tick should immediately be executed.
81    pub fn request_tick(&mut self) -> bool {
82        if !self.in_flight {
83            self.in_flight = true;
84            self.total_processed += 1;
85            return true;
86        }
87
88        match self.policy {
89            TickPolicy::ProcessAll => {
90                self.pending_ticks += 1;
91                false
92            }
93            TickPolicy::Coalesce => {
94                if self.pending_ticks > 0 {
95                    self.total_coalesced += 1;
96                }
97                self.pending_ticks = 1;
98                false
99            }
100            TickPolicy::Drop => {
101                self.total_dropped += 1;
102                false
103            }
104        }
105    }
106
107    /// Finish current tick processing. Returns `true` if a coalesced or queued tick should now execute.
108    pub fn finish_tick(&mut self) -> bool {
109        if self.pending_ticks > 0 {
110            self.pending_ticks -= 1;
111            self.total_processed += 1;
112            self.in_flight = true;
113            true
114        } else {
115            self.in_flight = false;
116            false
117        }
118    }
119}
120
121/// A recorded `pulse.publish` call — the 0.1 receipt for UI / audit display.
122///
123/// When the snapshot is `attached` to the live daemon graph, each publish also
124/// emits a [`crate::pulse_transport::PulseEvent`] to the process-wide broadcast
125/// channel so SSE / WebSocket subscribers receive it in real time.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct PulseRecord {
128    /// The topic string (validated against [`PULSE_ALLOW_PREFIXES`]).
129    pub topic: String,
130    /// Compact textual summary of the payload value.
131    pub payload_summary: String,
132    /// Monotonic sequence number from the pulse transport (0 when detached).
133    pub seq: u64,
134}
135
136/// RDF 1.2 reifier predicate used by staged `<< s p o ~ r >>` quins.
137const RDF_REIFIES: &[u8] = b"http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies";
138
139/// Provenance and semantic view metadata for an admitted Q42 volume/slice (G50).
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct AdmittedQ42ViewReceipt {
142    pub pack_identity: String,
143    pub entry_key: String,
144    pub entry_digest: [u8; 32],
145    pub q42_version: u32,
146    pub quin_count: usize,
147    pub block_count: u64,
148}
149
150#[derive(Debug, Clone, Default)]
151pub struct AdmittedQ42View {
152    pub receipt: Option<AdmittedQ42ViewReceipt>,
153    pub quins: Vec<NQuin>,
154    pub lexicon_entries: std::collections::HashMap<u64, String>,
155}
156
157/// In-memory graph revision used as the 0.1 live host.
158///
159/// When `attached`, queries refresh from the native daemon graph and commits
160/// extend it. WASM has no daemon_graph — attach is always false there.
161#[derive(Debug, Clone, Default)]
162pub struct PoetSnapshot {
163    pub committed: Vec<NQuin>,
164    staged: Vec<NQuin>,
165    pub revision: u64,
166    pub published: Vec<PulseRecord>,
167    pub attached: bool,
168    /// Set to `true` when `graph_query` is called during an evaluation.
169    /// The desktop harness resets this before each `eval_cell_src` and reads
170    /// it after to determine whether the cell is graph-dependent (reactive).
171    pub graph_read_during_eval: bool,
172    /// Set to `true` when `time_unix` is called during an evaluation.
173    /// The desktop harness resets this before each `eval_cell_src` and reads
174    /// it after to determine whether the cell is time-dependent (reactive on tick).
175    pub time_read_during_eval: bool,
176    /// Controller managing tick admission and coalescing under load (T68).
177    pub tick_controller: TickController,
178    /// HID event ring buffer (T46). 4096-sample quota — host constant,
179    /// not a language constant. Fail-closed when full.
180    pub hid_events: HidEventBuffer,
181    /// Instrument trace ledger (R12). Records instrument acts for
182    /// customer-readable audit. NOT a provider byline (CLAUDE.md §16).
183    pub trace_ledger: crate::governance::instrument_trace::InstrumentTraceLedger,
184    /// Remaining 42 MB Sentinel budget after the last eval (P16.6).
185    pub last_eval_workspace_left: u64,
186    /// Admitted isolated read-only Q42 semantic views (G50).
187    pub admitted_views: Vec<AdmittedQ42View>,
188    /// Key vault storing Ed25519 signing seeds for crypto operations.
189    pub key_vault: std::collections::HashMap<String, [u8; 32]>,
190}
191
192/// Canonical name for the mutable Vibe execution environment.
193///
194/// `PoetSnapshot` remains available for source compatibility with the Poet UI.
195pub type VibeHost = PoetSnapshot;
196
197/// Canonical name for a Vibe host's caller-owned Quin snapshot.
198pub type VibeHostSnapshot = PoetSnapshot;
199
200/// Maximum number of HID events buffered in the host (T46).
201/// 4096 samples = ~4 seconds at 1000 Hz, enough for one frame batch.
202pub const HID_SAMPLE_QUOTA: usize = 4096;
203
204/// A fixed-capacity ring buffer for HID events (T46).
205///
206/// Uses a Vec internally but enforces the 4096-sample quota.
207/// When full, new events are rejected (fail-closed).
208#[derive(Debug, Clone)]
209pub struct HidEventBuffer {
210    events: Vec<HidEventSlot>,
211    head: usize,
212    count: usize,
213}
214
215/// A compact HID event slot for the ring buffer (T46).
216/// Stores the essential fields without String allocation.
217#[derive(Debug, Clone, Copy, Default)]
218pub struct HidEventSlot {
219    pub timestamp_ns: u64,
220    pub source_hash: u64,
221    pub event_kind: u8,
222    pub x: f32,
223    pub y: f32,
224    pub z: f32,
225    pub capability_lease: u64, // 0 = none
226}
227
228impl HidEventBuffer {
229    /// Empty ring buffer of `HID_SAMPLE_QUOTA` slots.
230    pub fn new() -> Self {
231        Self {
232            events: vec![HidEventSlot::default(); HID_SAMPLE_QUOTA],
233            head: 0,
234            count: 0,
235        }
236    }
237
238    /// Enqueue a HID event. Returns Err if the quota is full (T46).
239    pub fn enqueue(&mut self, event: HidEventSlot) -> Result<(), &'static str> {
240        if self.count >= HID_SAMPLE_QUOTA {
241            return Err("HID event buffer full (4096-sample quota exceeded)");
242        }
243        let tail = (self.head + self.count) % HID_SAMPLE_QUOTA;
244        self.events[tail] = event;
245        self.count += 1;
246        Ok(())
247    }
248
249    /// Dequeue the oldest HID event.
250    pub fn dequeue(&mut self) -> Option<HidEventSlot> {
251        if self.count == 0 {
252            return None;
253        }
254        let event = self.events[self.head];
255        self.head = (self.head + 1) % HID_SAMPLE_QUOTA;
256        self.count -= 1;
257        Some(event)
258    }
259
260    /// Current number of buffered events.
261    pub fn count(&self) -> usize {
262        self.count
263    }
264
265    /// Whether the buffer is full.
266    pub fn is_full(&self) -> bool {
267        self.count >= HID_SAMPLE_QUOTA
268    }
269
270    /// Whether the buffer is empty.
271    pub fn is_empty(&self) -> bool {
272        self.count == 0
273    }
274
275    /// Clear all events.
276    pub fn clear(&mut self) {
277        self.head = 0;
278        self.count = 0;
279    }
280}
281
282impl Default for HidEventBuffer {
283    /// Same as [`HidEventBuffer::new`].
284    fn default() -> Self {
285        Self::new()
286    }
287}
288
289impl PoetSnapshot {
290    /// Detached snapshot seeded with `quins` at revision 1 — no daemon
291    /// attachment, no published events.
292    pub fn with_seed(quins: Vec<NQuin>) -> Self {
293        Self {
294            committed: quins,
295            staged: Vec::new(),
296            revision: 1,
297            published: Vec::new(),
298            attached: false,
299            graph_read_during_eval: false,
300            time_read_during_eval: false,
301            tick_controller: TickController::default(),
302            hid_events: HidEventBuffer::new(),
303            trace_ledger: crate::governance::instrument_trace::InstrumentTraceLedger::new(),
304            last_eval_workspace_left: vibe::SENTINEL_BYTES,
305            admitted_views: Vec::new(),
306            key_vault: std::collections::HashMap::new(),
307        }
308    }
309
310    /// Prefer the process daemon graph; fall back to the demo seed.
311    pub fn live() -> Self {
312        #[cfg(not(target_arch = "wasm32"))]
313        {
314            if crate::daemon_graph::graph_quin_count() > 0 {
315                return Self::from_daemon();
316            }
317        }
318        Self::with_demo_seed()
319    }
320
321    /// Snapshot attached to the process daemon graph — reads/delegates
322    /// go through `daemon_graph`, `committed` stays empty.
323    #[cfg(not(target_arch = "wasm32"))]
324    pub fn from_daemon() -> Self {
325        Self {
326            committed: Vec::new(),
327            staged: Vec::new(),
328            revision: crate::daemon_graph::graph_revision().max(1),
329            published: Vec::new(),
330            attached: true,
331            graph_read_during_eval: false,
332            time_read_during_eval: false,
333            tick_controller: TickController::default(),
334            hid_events: HidEventBuffer::new(),
335            trace_ledger: crate::governance::instrument_trace::InstrumentTraceLedger::new(),
336            last_eval_workspace_left: vibe::SENTINEL_BYTES,
337            admitted_views: Vec::new(),
338            key_vault: std::collections::HashMap::new(),
339        }
340    }
341
342    /// Evidence-level string: `"live"` when attached to the daemon
343    /// graph, `"partial"` for a detached snapshot.
344    pub fn honesty(&self) -> &'static str {
345        if self.attached {
346            "live"
347        } else {
348            "partial"
349        }
350    }
351
352    /// Run `f` on the live quin slice — the daemon read guard when
353    /// attached, otherwise the committed vec.
354    pub(crate) fn with_live_quins<R>(&self, f: impl FnOnce(&[NQuin]) -> R) -> R {
355        #[cfg(not(target_arch = "wasm32"))]
356        if self.attached {
357            let guard = crate::daemon_graph::graph_read_guard();
358            return f(guard.as_slice());
359        }
360        f(&self.committed)
361    }
362
363    /// Quins visible to this snapshot — the daemon count when attached,
364    /// else `committed.len()`.
365    pub fn visible_count(&self) -> usize {
366        #[cfg(not(target_arch = "wasm32"))]
367        if self.attached {
368            return crate::daemon_graph::graph_quin_count();
369        }
370        self.committed.len()
371    }
372
373    /// Clinic + catchment seed so the harness query sample is not empty.
374    pub fn with_demo_seed() -> Self {
375        let pred = generate_60bit_token(b"clinic:hasCondition");
376        let seed = NQuin {
377            subject: generate_60bit_token(b"https://qualiadb.org/catchment/NorthSpring"),
378            predicate: pred,
379            object: generate_60bit_token(b"https://qualiadb.org/meteo/Rain"),
380            context: generate_60bit_token(b"https://qualiadb.org/graphs/lived-memory"),
381            metadata: 0,
382            parity: 0,
383        };
384        let mut q = seed;
385        q.parity = NQuin::calculate_parity(q.subject, q.predicate, q.object, q.context, q.metadata);
386        Self::with_seed(vec![q])
387    }
388
389    /// Ingest an externally sealed quin — into the daemon graph when
390    /// attached (revision refreshed), else appended to `committed`.
391    pub fn ingest_sealed(&mut self, quin: NQuin) {
392        #[cfg(not(target_arch = "wasm32"))]
393        if self.attached {
394            crate::daemon_graph::extend_with_ontology_quins_slice(&[quin]);
395            self.revision = crate::daemon_graph::graph_revision().max(self.revision);
396            return;
397        }
398        self.committed.push(quin);
399    }
400
401    /// Advance the snapshot revision (wrapping) after an out-of-band
402    /// mutation the commit path didn't observe.
403    pub fn bump_revision(&mut self) {
404        self.revision = self.revision.wrapping_add(1);
405    }
406
407    /// Fork this snapshot into a detached, isolated copy for dry-run
408    /// evaluation (reflection Stage 3, JudgeFrame verification, etc.).
409    ///
410    /// The fork inherits the current committed quins (a snapshot of the
411    /// live graph at this revision) but is **never attached** — commits
412    /// to the fork stay in the fork and cannot reach the daemon graph.
413    /// The staged deltas are cleared (a dry-run starts from the committed
414    /// baseline, not from in-flight staged changes).
415    ///
416    /// This is the R4 isolation boundary: reflection stage 3 and judge
417    /// frames evaluate against the fork, not the live host.
418    pub fn fork(&self) -> Self {
419        Self {
420            committed: self.committed.clone(),
421            staged: Vec::new(),
422            revision: self.revision,
423            published: Vec::new(),
424            attached: false,
425            graph_read_during_eval: false,
426            time_read_during_eval: false,
427            tick_controller: self.tick_controller.clone(),
428            hid_events: self.hid_events.clone(),
429            trace_ledger: self.trace_ledger.clone(),
430            last_eval_workspace_left: self.last_eval_workspace_left,
431            admitted_views: self.admitted_views.clone(),
432            key_vault: self.key_vault.clone(),
433        }
434    }
435
436    /// Commit staged deltas into the committed set (used by dry-run forks
437    /// to simulate a commit without touching the live graph).
438    pub fn commit_staged(&mut self) {
439        self.committed.append(&mut self.staged);
440        self.bump_revision();
441    }
442
443    /// Discard all staged deltas without committing (rollback).
444    pub fn rollback_staged(&mut self) {
445        self.staged.clear();
446    }
447
448    /// Admit an in-memory/byte-backed Q42 slice into an isolated read-only semantic view (G50).
449    ///
450    /// Validates:
451    /// 1. Entry SHA-256 digest (if expected_digest is provided).
452    /// 2. Q42 header bounds and supported format version (v3/v4).
453    /// 3. Caller-buffered SuperBlock decompression and Quin parity checks for all Quins.
454    /// 4. Embedded Q42LEX lexicon decoding into an isolated term map.
455    ///
456    /// Fail-closed guarantee: any corruption, digest mismatch, or budget error
457    /// rejects admission immediately WITHOUT altering previously admitted views or
458    /// resident committed graph.
459    ///
460    /// When `load_into_committed` is true, also appends admitted Quins to `self.committed`
461    /// and bumps revision so queries (`GraphDatabase.sparql`, `SHACL.validate`) see them.
462    pub fn admit_q42_slice(
463        &mut self,
464        bytes: &[u8],
465        pack_identity: &str,
466        entry_key: &str,
467        expected_digest: Option<&[u8; 32]>,
468        load_into_committed: bool,
469    ) -> Result<AdmittedQ42ViewReceipt, String> {
470        if bytes.len() > vibe::SENTINEL_BYTES as usize {
471            return Err("Q42 slice exceeds 42MB Sentinel budget".into());
472        }
473
474        // 1. Digest check
475        if let Some(expected) = expected_digest {
476            use sha2::{Digest, Sha256};
477            let mut hasher = Sha256::new();
478            hasher.update(bytes);
479            let actual: [u8; 32] = hasher.finalize().into();
480            if actual != *expected {
481                return Err("Q42 slice digest mismatch".into());
482            }
483        }
484
485        // 2. Open via Q42RangeVolume
486        use crate::q42::q42_volume::{
487            OpfsSliceRangeSource, Q42RangeVolume, MAX_COMPRESSED_SUPERBLOCK_SIZE, QUIN_SIZE,
488            SUPERBLOCK_HEADER, SUPERBLOCK_SIZE,
489        };
490        let source = OpfsSliceRangeSource::new(bytes);
491        let vol = Q42RangeVolume::open(source)
492            .map_err(|e| format!("Q42 range volume header invalid: {e}"))?;
493
494        let block_count = vol.block_count() as usize;
495        let mut admitted_quins = Vec::new();
496
497        // 3. Decompress and verify each block and its quins
498        let mut compressed = vec![0u8; MAX_COMPRESSED_SUPERBLOCK_SIZE];
499        let mut decoded = vec![0u8; SUPERBLOCK_SIZE];
500
501        for b in 0..block_count {
502            vol.read_superblock_into(b, &mut compressed, &mut decoded)
503                .map_err(|e| format!("Q42 block {b} decompression failed: {e}"))?;
504
505            let count = u64::from_le_bytes(decoded[16..24].try_into().unwrap()) as usize;
506            if count > crate::QUINS_PER_BLOCK {
507                return Err(format!("Q42 block {b} quin count {count} exceeds capacity"));
508            }
509
510            for q_idx in 0..count {
511                let off = SUPERBLOCK_HEADER + q_idx * QUIN_SIZE;
512                let quin = NQuin {
513                    subject: u64::from_le_bytes(decoded[off..off + 8].try_into().unwrap()),
514                    predicate: u64::from_le_bytes(decoded[off + 8..off + 16].try_into().unwrap()),
515                    object: u64::from_le_bytes(decoded[off + 16..off + 24].try_into().unwrap()),
516                    context: u64::from_le_bytes(decoded[off + 24..off + 32].try_into().unwrap()),
517                    metadata: u64::from_le_bytes(decoded[off + 32..off + 40].try_into().unwrap()),
518                    parity: u64::from_le_bytes(decoded[off + 40..off + 48].try_into().unwrap()),
519                };
520
521                let expected_parity = NQuin::calculate_parity(
522                    quin.subject,
523                    quin.predicate,
524                    quin.object,
525                    quin.context,
526                    quin.metadata,
527                );
528                if quin.parity != expected_parity {
529                    return Err(format!(
530                        "Q42 block {b} quin {q_idx} parity corrupt: expected {expected_parity:#x}, got {:#x}",
531                        quin.parity
532                    ));
533                }
534                admitted_quins.push(quin);
535            }
536        }
537
538        // 4. Decode embedded lexicon if present
539        let mut lexicon_entries = std::collections::HashMap::new();
540        let header = vol.header();
541        if header.lex_length > 0 {
542            let lex_off = header.lex_offset as usize;
543            let lex_len = header.lex_length as usize;
544            if let Some(lex_slice) = bytes.get(lex_off..lex_off + lex_len) {
545                if let Ok(lex_mmap) = crate::q42_lex::Q42LexMmap::from_bytes(lex_slice) {
546                    for q in &admitted_quins {
547                        if let Some(s) = lex_mmap.lookup_owned(q.subject) {
548                            lexicon_entries.insert(q.subject, s);
549                        }
550                        if let Some(s) = lex_mmap.lookup_owned(q.predicate) {
551                            lexicon_entries.insert(q.predicate, s);
552                        }
553                        let masked_obj = q.object & 0x0FFF_FFFF_FFFF_FFFF;
554                        if let Some(s) = lex_mmap.lookup_owned(masked_obj) {
555                            lexicon_entries.insert(masked_obj, s);
556                        }
557                    }
558                }
559            }
560        }
561
562        // 5. Commit into admitted views
563        let receipt = AdmittedQ42ViewReceipt {
564            pack_identity: pack_identity.to_string(),
565            entry_key: entry_key.to_string(),
566            entry_digest: {
567                use sha2::{Digest, Sha256};
568                Sha256::digest(bytes).into()
569            },
570            q42_version: header.version as u32,
571            quin_count: admitted_quins.len(),
572            block_count: header.block_count,
573        };
574
575        if load_into_committed {
576            self.committed.extend_from_slice(&admitted_quins);
577            self.revision = self.revision.saturating_add(1);
578        }
579
580        self.admitted_views.push(AdmittedQ42View {
581            receipt: Some(receipt.clone()),
582            quins: admitted_quins,
583            lexicon_entries,
584        });
585
586        Ok(receipt)
587    }
588
589    /// Resolve a hash term against admitted lexicon views.
590    pub fn resolve_admitted_lexicon_term(&self, hash: u64) -> Option<&str> {
591        let masked = hash & 0x0FFF_FFFF_FFFF_FFFF;
592        for view in self.admitted_views.iter().rev() {
593            if let Some(term) = view
594                .lexicon_entries
595                .get(&hash)
596                .or_else(|| view.lexicon_entries.get(&masked))
597            {
598                return Some(term.as_str());
599            }
600        }
601        None
602    }
603
604    /// Number of staged (uncommitted) quins.
605    pub fn staged_count(&self) -> usize {
606        self.staged.len()
607    }
608
609    /// Record an instrument trace entry (R12).
610    /// This is a customer-readable audit trail, NOT a provider byline.
611    pub fn trace(&mut self, entry: crate::governance::instrument_trace::TraceEntry) {
612        self.trace_ledger.record(entry);
613    }
614
615    /// Convenience: record a simple trace entry for a capability invoke.
616    pub fn trace_invoke(&mut self, invoke_id: &str, success: bool, cost: Option<u64>) {
617        use crate::governance::instrument_trace::TraceEntry;
618        self.trace(TraceEntry {
619            instrument_id: "vibe_host".into(),
620            act: format!("invoke:{}", invoke_id),
621            targets: Vec::new(),
622            started_at: 0,
623            completed_at: 0,
624            lease_id: None,
625            cost,
626            success,
627            diagnostic: None,
628        });
629    }
630
631    /// Parse, check, and evaluate a full VibeScript program source —
632    /// resets the graph/time-read honesty flags first and records the
633    /// post-eval workspace headroom in `last_eval_workspace_left`.
634    pub fn eval_program_src(&mut self, src: &str) -> Result<Value, Diagnostic> {
635        self.graph_read_during_eval = false;
636        self.time_read_during_eval = false;
637        let program = vibe::parse_program(src)?;
638        vibe::check_program(&program)?;
639        let mut env = Env::default();
640        let mut engine = vibe::Engine::with_program(self, vibe::Budget::default(), &program);
641        let result = engine.eval_program(&program, &mut env);
642        self.last_eval_workspace_left = engine.workspace_left();
643        result
644    }
645
646    /// Write committed + staged quins into the 42 MB Sentinel arena (P16.6).
647    #[cfg(not(target_arch = "wasm32"))]
648    pub fn seal_eval_quins_into_arena(&self, arena: &mut crate::webizen::SlgArena) -> usize {
649        let mut n = 0usize;
650        for q in self.committed.iter().chain(self.staged.iter()) {
651            arena.write_table(*q);
652            n += 1;
653        }
654        n
655    }
656
657    /// Evaluate one notebook cell source against this snapshot; resets
658    /// the read flags first (left uncleared on failure — an incomplete
659    /// cell keeps its flags).
660    pub fn eval_cell_src(&mut self, src: &str) -> Result<Value, Diagnostic> {
661        self.graph_read_during_eval = false;
662        self.time_read_during_eval = false;
663        let mut env = Env::default();
664        let result = eval_cell(src, self, &mut env);
665        // If evaluation failed, leave the flag as-is (the cell didn't complete).
666        result
667    }
668
669    /// Call function `name` from program source `src` with `args`,
670    /// evaluated against this snapshot.
671    pub fn eval_fn(
672        &mut self,
673        src: &str,
674        name: &str,
675        args: Vec<Value>,
676    ) -> Result<Value, Diagnostic> {
677        let program = load_program(src)?;
678        let mut env = Env::default();
679        eval_function(&program, name, args, self, &mut env)
680    }
681
682    /// Dispatch a hook event (`on <path>(…)`) on a checked program.
683    ///
684    /// `path` is the event path segments (e.g. `["pulse", "message"]` for
685    /// `on pulse:message(…)`, or `["tick"]` for `on tick(…)`). `args` are
686    /// bound to the hook's parameters in declaration order. Returns
687    /// `Ok(Value::Null)` if no matching hook exists in the program.
688    pub fn dispatch_hook_src(
689        &mut self,
690        src: &str,
691        path: &[String],
692        args: Vec<Value>,
693    ) -> Result<Value, Diagnostic> {
694        let program = load_program(src)?;
695        let mut env = Env::default();
696        vibe::dispatch_hook(&program, path, args, self, &mut env)
697    }
698
699    /// Direct capability.invoke from a host (desktop renderer, tests).
700    pub fn invoke_id(&mut self, id: &str, args: Value) -> Result<Value, Diagnostic> {
701        invoke::dispatch(self, id, &args, vibe::Span { start: 0, end: 0 })
702    }
703}
704
705impl Host for PoetSnapshot {
706    /// `graph.query` — match s/p/o patterns (any may be absent) against
707    /// the live or committed quins, up to `take` results; sets the
708    /// `graph_read_during_eval` honesty flag.
709    fn graph_query(
710        &mut self,
711        args: &[Value],
712        take: u64,
713        _span: vibe::Span,
714    ) -> Result<Value, Diagnostic> {
715        self.graph_read_during_eval = true;
716        let s = args.first();
717        let p = args.get(1);
718        let o = args.get(2);
719        let mut out = Vec::new();
720        #[cfg(not(target_arch = "wasm32"))]
721        if self.attached {
722            let guard = crate::daemon_graph::graph_read_guard();
723            collect_matches(guard.as_slice(), s, p, o, take, &mut out);
724            self.revision = crate::daemon_graph::graph_revision().max(self.revision);
725            return Ok(Value::List(out));
726        }
727        collect_matches(&self.committed, s, p, o, take, &mut out);
728        Ok(Value::List(out))
729    }
730
731    /// `graph.stage` — buffer `term` (triple, reified term, or Quin)
732    /// into `staged` for the next commit; E600 when the value encodes
733    /// no stageable quin.
734    fn graph_stage(&mut self, term: &Value, span: vibe::Span) -> Result<Value, Diagnostic> {
735        let mut pushed = 0usize;
736        if let Some(q) = value_to_quin(term, 0) {
737            self.staged.push(q);
738            pushed += 1;
739        }
740        if let Some(q) = reifier_quin(term, 0) {
741            self.staged.push(q);
742            pushed += 1;
743        }
744        if pushed > 0 {
745            return Ok(Value::Null);
746        }
747        Err(Diagnostic::new(
748            vibe::DiagCode::E600,
749            span,
750            "graph.stage expects a triple, reified term, or Quin",
751        ))
752    }
753
754    /// `graph.begin` — no-op: staging is implicit, no explicit
755    /// transaction state to open.
756    fn graph_begin(&mut self, _span: vibe::Span) -> Result<(), Diagnostic> {
757        Ok(())
758    }
759
760    /// `graph.abort` — drop every staged quin without committing.
761    fn graph_abort(&mut self, _span: vibe::Span) -> Result<(), Diagnostic> {
762        self.staged.clear();
763        Ok(())
764    }
765
766    /// `graph.commit` — flush `staged` into the daemon graph (attached)
767    /// or `committed` (detached), bump the revision, and return a
768    /// `Receipt`. Committing an empty stage is a no-op `Receipt`.
769    fn graph_commit(&mut self, _span: vibe::Span) -> Result<Value, Diagnostic> {
770        if !self.staged.is_empty() {
771            #[cfg(not(target_arch = "wasm32"))]
772            if self.attached {
773                crate::daemon_graph::extend_with_ontology_quins_slice(&self.staged);
774                self.staged.clear();
775                self.revision = crate::daemon_graph::graph_revision().max(1);
776            } else {
777                self.committed.append(&mut self.staged);
778                self.revision = self.revision.wrapping_add(1);
779            }
780            #[cfg(target_arch = "wasm32")]
781            {
782                self.committed.append(&mut self.staged);
783                self.revision = self.revision.wrapping_add(1);
784            }
785        }
786        Ok(Value::Receipt)
787    }
788
789    /// `aura.validate` — validate `node` against a named shape; only
790    /// the built-in `EmergencyAlertShape`/`ReifierPresent` shapes are
791    /// honest in this build (false otherwise / for unhashable nodes).
792    fn aura_validate(
793        &mut self,
794        node: &Value,
795        shape: &Value,
796        _span: vibe::Span,
797    ) -> Result<Value, Diagnostic> {
798        let Some(id) = hash_val(node) else {
799            return Ok(Value::Bool(false));
800        };
801        let shape_name = shape_local_name(shape);
802        // No shape-IRI registry exists. Only these built-ins are honest 0.1.
803        if !matches!(
804            shape_name.as_str(),
805            "EmergencyAlertShape" | "ReifierPresent"
806        ) {
807            return Ok(Value::Bool(false));
808        }
809        let reifies = generate_60bit_token(RDF_REIFIES);
810        if subject_present(&self.staged, id, Some(reifies))
811            || subject_present(&self.committed, id, Some(reifies))
812        {
813            return Ok(Value::Bool(true));
814        }
815        #[cfg(any(
816            not(target_arch = "wasm32"),
817            feature = "wasm-ontology",
818            feature = "wasm-logic",
819            feature = "wasm-scientific",
820            feature = "wasm-full"
821        ))]
822        {
823            use crate::query::shacl_compiler::{validate_shacl_property, ShaclConstraint};
824            #[cfg(not(target_arch = "wasm32"))]
825            if self.attached {
826                let guard = crate::daemon_graph::graph_read_guard();
827                return Ok(Value::Bool(validate_shacl_property(
828                    guard.as_slice(),
829                    id,
830                    reifies,
831                    &[ShaclConstraint::MinCount(1)],
832                )));
833            }
834            return Ok(Value::Bool(validate_shacl_property(
835                &self.committed,
836                id,
837                reifies,
838                &[ShaclConstraint::MinCount(1)],
839            )));
840        }
841        #[cfg(not(any(
842            not(target_arch = "wasm32"),
843            feature = "wasm-ontology",
844            feature = "wasm-logic",
845            feature = "wasm-scientific",
846            feature = "wasm-full"
847        )))]
848        {
849            let _ = reifies;
850            Ok(Value::Bool(false))
851        }
852    }
853
854    /// `pulse.publish` — emit `payload` on `topic` (E500 unless the
855    /// topic is on `PULSE_ALLOW_PREFIXES`); goes through the process
856    /// pulse transport when attached, and is always journaled into
857    /// `published`.
858    fn pulse_publish(
859        &mut self,
860        topic: &str,
861        payload: &Value,
862        span: vibe::Span,
863    ) -> Result<Value, Diagnostic> {
864        if !PULSE_ALLOW_PREFIXES
865            .iter()
866            .any(|prefix| topic == *prefix || topic.starts_with(prefix))
867        {
868            return Err(Diagnostic::new(
869                vibe::DiagCode::E500,
870                span,
871                format!("pulse topic `{topic}` is not on the 0.1 allowlist"),
872            ));
873        }
874        let payload_summary = format_value(payload);
875        // When attached to the live daemon, emit through the process-wide
876        // pulse transport so SSE / WebSocket subscribers receive the event.
877        #[cfg(not(target_arch = "wasm32"))]
878        let seq = if self.attached {
879            crate::pulse_transport::publish(topic, &payload_summary)
880        } else {
881            0
882        };
883        #[cfg(target_arch = "wasm32")]
884        let seq = 0u64;
885        self.published.push(PulseRecord {
886            topic: topic.to_string(),
887            payload_summary,
888            seq,
889        });
890        Ok(Value::Null)
891    }
892
893    /// `time.now` — current instant built on `time_unix` (E600 if the
894    /// clock read produced something unexpected).
895    fn time_now(&mut self, span: vibe::Span) -> Result<Value, Diagnostic> {
896        let secs = match self.time_unix(span)? {
897            Value::I64(s) => s,
898            Value::Instant(i) => return Ok(Value::Instant(i)),
899            other => {
900                return Err(Diagnostic::new(
901                    vibe::DiagCode::E600,
902                    span,
903                    format!("time_unix produced {other}"),
904                ));
905            }
906        };
907        Ok(Value::Instant(vibe::Instant::unix(secs, 0)))
908    }
909
910    /// Host environment — `WasmSandbox` on wasm32, `NativeDesktop`
911    /// otherwise.
912    fn environment(&self) -> vibe::HostEnvironment {
913        #[cfg(target_arch = "wasm32")]
914        {
915            vibe::HostEnvironment::WasmSandbox
916        }
917        #[cfg(not(target_arch = "wasm32"))]
918        {
919            vibe::HostEnvironment::NativeDesktop
920        }
921    }
922
923    /// The tier this host will actually use — `ScalarCpu`.
924    fn acceleration_tier(&self) -> vibe::AccelerationTier {
925        vibe::AccelerationTier::ScalarCpu
926    }
927
928    /// The best acceleration tier hardware-probed on this machine.
929    fn available_acceleration(&self) -> vibe::AccelerationTier {
930        vibe::detect_available_tier()
931    }
932
933    /// `time.unix` — seconds since epoch; sets `time_read_during_eval`.
934    /// WASM has no wall clock and returns 0 (receipt-injected clocks
935    /// handle replay).
936    fn time_unix(&mut self, span: vibe::Span) -> Result<Value, Diagnostic> {
937        self.time_read_during_eval = true;
938        // WASM has no wall clock; the host injects replay clocks via receipts.
939        #[cfg(target_arch = "wasm32")]
940        {
941            let _ = span;
942            Ok(Value::I64(0))
943        }
944        #[cfg(not(target_arch = "wasm32"))]
945        {
946            use std::time::{SystemTime, UNIX_EPOCH};
947            match SystemTime::now().duration_since(UNIX_EPOCH) {
948                Ok(d) => Ok(Value::I64(d.as_secs() as i64)),
949                Err(_) => Err(Diagnostic::new(
950                    vibe::DiagCode::E600,
951                    span,
952                    "system clock is before Unix epoch",
953                )),
954            }
955        }
956    }
957
958    /// `graph.snapshot` — the current revision (`U64`); refreshes from
959    /// the daemon when attached.
960    fn graph_snapshot(&mut self, _span: vibe::Span) -> Result<Value, Diagnostic> {
961        #[cfg(not(target_arch = "wasm32"))]
962        if self.attached {
963            self.revision = crate::daemon_graph::graph_revision().max(1);
964        }
965        Ok(Value::U64(self.revision))
966    }
967
968    /// `capability.resolve` — look up invoke-id `id` in the catalog,
969    /// honesty-tagged by attachment state.
970    fn capability_resolve(&mut self, id: &str, _span: vibe::Span) -> Result<Value, Diagnostic> {
971        Ok(catalog::resolve_id_with(id, self.attached))
972    }
973
974    /// `capability.invoke` — dispatch invoke-id `id` through
975    /// `invoke::dispatch`.
976    fn capability_invoke(
977        &mut self,
978        id: &str,
979        args: &Value,
980        span: vibe::Span,
981    ) -> Result<Value, Diagnostic> {
982        invoke::dispatch(self, id, args, span)
983    }
984
985    /// `quin.seal` — wrap raw s/p/o/c u64s into a `QuinRef` (metadata
986    /// 0, parity recomputed); the script never sees the parity field.
987    fn quin_seal(
988        &mut self,
989        subject: u64,
990        predicate: u64,
991        object: u64,
992        context: u64,
993        _span: vibe::Span,
994    ) -> Result<Value, Diagnostic> {
995        let metadata = 0;
996        let _parity = NQuin::calculate_parity(subject, predicate, object, context, metadata);
997        Ok(Value::QuinRef(vibe::QuinRef::from_raw(
998            subject, predicate, object, context, metadata, _parity,
999        )))
1000    }
1001
1002    /// `hash_iri` — the 60-bit token hash of `iri` (bits 60–63 free
1003    /// for type tags).
1004    fn hash_iri(&self, iri: &str) -> u64 {
1005        generate_60bit_token(iri.as_bytes())
1006    }
1007
1008    // ── Crypto operations — delegate to cryptographic_library ───────
1009
1010    /// `crypto.hash` — SHA-256/SHA-512/BLAKE3 of `data`, returned as a
1011    /// hash-result record; E100 for other algorithm names.
1012    /// `crypto.hash` — SHA-256/SHA-512/BLAKE3 of `data`, returned as a
1013    /// hash-result record; E100 for other algorithm names.
1014    fn crypto_hash(
1015        &mut self,
1016        algorithm: &str,
1017        data: &str,
1018        span: vibe::Span,
1019    ) -> Result<Value, Diagnostic> {
1020        let bytes = data.as_bytes();
1021        let (hash_hex, hash_bytes_len) = match algorithm {
1022            "SHA-256" => {
1023                use sha2::{Digest, Sha256};
1024                let mut hasher = Sha256::new();
1025                hasher.update(bytes);
1026                let digest = hasher.finalize();
1027                (vibe::crypto::to_hex(&digest), digest.len())
1028            }
1029            "SHA-512" => {
1030                use sha2::{Digest, Sha512};
1031                let mut hasher = Sha512::new();
1032                hasher.update(bytes);
1033                let digest = hasher.finalize();
1034                (vibe::crypto::to_hex(&digest), digest.len())
1035            }
1036            "BLAKE3" => {
1037                let digest = blake3::hash(bytes);
1038                let bytes_arr = digest.as_bytes();
1039                (vibe::crypto::to_hex(bytes_arr), bytes_arr.len())
1040            }
1041            _ => {
1042                return Err(Diagnostic::new(
1043                    vibe::DiagCode::E100,
1044                    span,
1045                    format!("crypto.hash: unsupported algorithm {algorithm}"),
1046                ));
1047            }
1048        };
1049        Ok(vibe::crypto::hash_result_value(
1050            algorithm,
1051            &hash_hex,
1052            hash_bytes_len,
1053        ))
1054    }
1055
1056    /// `crypto.hkdf` — HKDF-SHA256 expand of `ikm`/`info` to `length`
1057    /// bytes, hex-encoded; E100 on expansion failure.
1058    fn crypto_hkdf(
1059        &mut self,
1060        ikm: &str,
1061        info: &str,
1062        length: u64,
1063        span: vibe::Span,
1064    ) -> Result<Value, Diagnostic> {
1065        use hkdf::Hkdf;
1066        use sha2::Sha256;
1067        let ikm_bytes = ikm.as_bytes();
1068        let info_bytes = info.as_bytes();
1069        let hk = Hkdf::<Sha256>::new(None, ikm_bytes);
1070        let mut okm = vec![0u8; length as usize];
1071        hk.expand(info_bytes, &mut okm).map_err(|e| {
1072            Diagnostic::new(
1073                vibe::DiagCode::E100,
1074                span,
1075                format!("crypto.hkdf: expansion failed: {e}"),
1076            )
1077        })?;
1078        Ok(Value::String(vibe::crypto::to_hex(&okm)))
1079    }
1080
1081    /// `crypto.aead_encrypt` — AEAD-encrypt `plaintext` (AES-256-GCM:
1082    /// 32-byte key, 12-byte nonce, hex input) with `aad`; E100 on bad
1083    /// hex, wrong sizes, or an unsupported algorithm.
1084    fn crypto_aead_encrypt(
1085        &mut self,
1086        algorithm: &str,
1087        key_hex: &str,
1088        nonce_hex: &str,
1089        plaintext: &str,
1090        aad: &str,
1091        span: vibe::Span,
1092    ) -> Result<Value, Diagnostic> {
1093        let key = vibe::crypto::from_hex(key_hex).ok_or_else(|| {
1094            Diagnostic::new(
1095                vibe::DiagCode::E100,
1096                span,
1097                "crypto.aead_encrypt: invalid key hex",
1098            )
1099        })?;
1100        let nonce = vibe::crypto::from_hex(nonce_hex).ok_or_else(|| {
1101            Diagnostic::new(
1102                vibe::DiagCode::E100,
1103                span,
1104                "crypto.aead_encrypt: invalid nonce hex",
1105            )
1106        })?;
1107
1108        let aad_bytes = aad.as_bytes();
1109        let pt_bytes = plaintext.as_bytes();
1110
1111        let (ciphertext, tag): (Vec<u8>, Vec<u8>) = match algorithm {
1112            "AES-256-GCM" => {
1113                use aes_gcm::aead::Aead;
1114                use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
1115                let key_arr: &[u8; 32] = key.as_slice().try_into().map_err(|_| {
1116                    Diagnostic::new(
1117                        vibe::DiagCode::E100,
1118                        span,
1119                        "AES-256-GCM key must be 32 bytes",
1120                    )
1121                })?;
1122                let nonce_arr: &[u8; 12] = nonce.as_slice().try_into().map_err(|_| {
1123                    Diagnostic::new(
1124                        vibe::DiagCode::E100,
1125                        span,
1126                        "AES-256-GCM nonce must be 12 bytes",
1127                    )
1128                })?;
1129                let cipher = Aes256Gcm::new(key_arr.into());
1130                let nonce_obj = Nonce::from(*nonce_arr);
1131                let payload = aes_gcm::aead::Payload {
1132                    msg: pt_bytes,
1133                    aad: aad_bytes,
1134                };
1135                let ct = cipher.encrypt(&nonce_obj, payload).map_err(|e| {
1136                    Diagnostic::new(
1137                        vibe::DiagCode::E100,
1138                        span,
1139                        format!("AES-256-GCM encrypt failed: {e}"),
1140                    )
1141                })?;
1142                // AES-GCM appends the 16-byte tag to the ciphertext.
1143                let tag = ct[ct.len().saturating_sub(16)..].to_vec();
1144                let ct = ct[..ct.len().saturating_sub(16)].to_vec();
1145                (ct, tag)
1146            }
1147            "ChaCha20-Poly1305" => {
1148                use chacha20poly1305::aead::Aead;
1149                use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
1150                let key_arr: &[u8; 32] = key.as_slice().try_into().map_err(|_| {
1151                    Diagnostic::new(vibe::DiagCode::E100, span, "ChaCha20 key must be 32 bytes")
1152                })?;
1153                let nonce_arr: &[u8; 12] = nonce.as_slice().try_into().map_err(|_| {
1154                    Diagnostic::new(
1155                        vibe::DiagCode::E100,
1156                        span,
1157                        "ChaCha20 nonce must be 12 bytes",
1158                    )
1159                })?;
1160                let cipher = ChaCha20Poly1305::new(key_arr.into());
1161                let nonce_obj = Nonce::from(*nonce_arr);
1162                let payload = chacha20poly1305::aead::Payload {
1163                    msg: pt_bytes,
1164                    aad: aad_bytes,
1165                };
1166                let ct = cipher.encrypt(&nonce_obj, payload).map_err(|e| {
1167                    Diagnostic::new(
1168                        vibe::DiagCode::E100,
1169                        span,
1170                        format!("ChaCha20 encrypt failed: {e}"),
1171                    )
1172                })?;
1173                let tag = ct[ct.len().saturating_sub(16)..].to_vec();
1174                let ct = ct[..ct.len().saturating_sub(16)].to_vec();
1175                (ct, tag)
1176            }
1177            "XChaCha20-Poly1305" => {
1178                use chacha20poly1305::aead::Aead;
1179                use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
1180                let key_arr: &[u8; 32] = key.as_slice().try_into().map_err(|_| {
1181                    Diagnostic::new(vibe::DiagCode::E100, span, "XChaCha20 key must be 32 bytes")
1182                })?;
1183                let nonce_arr: &[u8; 24] = nonce.as_slice().try_into().map_err(|_| {
1184                    Diagnostic::new(
1185                        vibe::DiagCode::E100,
1186                        span,
1187                        "XChaCha20 nonce must be 24 bytes",
1188                    )
1189                })?;
1190                let cipher = XChaCha20Poly1305::new(key_arr.into());
1191                let nonce_obj = XNonce::from(*nonce_arr);
1192                let payload = chacha20poly1305::aead::Payload {
1193                    msg: pt_bytes,
1194                    aad: aad_bytes,
1195                };
1196                let ct = cipher.encrypt(&nonce_obj, payload).map_err(|e| {
1197                    Diagnostic::new(
1198                        vibe::DiagCode::E100,
1199                        span,
1200                        format!("XChaCha20 encrypt failed: {e}"),
1201                    )
1202                })?;
1203                let tag = ct[ct.len().saturating_sub(16)..].to_vec();
1204                let ct = ct[..ct.len().saturating_sub(16)].to_vec();
1205                (ct, tag)
1206            }
1207            _ => {
1208                return Err(Diagnostic::new(
1209                    vibe::DiagCode::E100,
1210                    span,
1211                    format!("crypto.aead_encrypt: unsupported algorithm {algorithm}"),
1212                ));
1213            }
1214        };
1215
1216        Ok(vibe::crypto::encrypted_data_value(
1217            algorithm,
1218            &vibe::crypto::to_hex(&ciphertext),
1219            &vibe::crypto::to_hex(&tag),
1220            &vibe::crypto::to_hex(&nonce),
1221        ))
1222    }
1223
1224    /// `crypto.aead_decrypt` — AEAD-decrypt with the same hex contract
1225    /// as `crypto_aead_encrypt`; E100 on bad input or auth failure.
1226    fn crypto_aead_decrypt(
1227        &mut self,
1228        algorithm: &str,
1229        key_hex: &str,
1230        nonce_hex: &str,
1231        ciphertext_hex: &str,
1232        tag_hex: &str,
1233        aad: &str,
1234        span: vibe::Span,
1235    ) -> Result<Value, Diagnostic> {
1236        let key = vibe::crypto::from_hex(key_hex).ok_or_else(|| {
1237            Diagnostic::new(
1238                vibe::DiagCode::E100,
1239                span,
1240                "crypto.aead_decrypt: invalid key hex",
1241            )
1242        })?;
1243        let nonce = vibe::crypto::from_hex(nonce_hex).ok_or_else(|| {
1244            Diagnostic::new(
1245                vibe::DiagCode::E100,
1246                span,
1247                "crypto.aead_decrypt: invalid nonce hex",
1248            )
1249        })?;
1250        let ciphertext = vibe::crypto::from_hex(ciphertext_hex).ok_or_else(|| {
1251            Diagnostic::new(
1252                vibe::DiagCode::E100,
1253                span,
1254                "crypto.aead_decrypt: invalid ciphertext hex",
1255            )
1256        })?;
1257        let tag = vibe::crypto::from_hex(tag_hex).ok_or_else(|| {
1258            Diagnostic::new(
1259                vibe::DiagCode::E100,
1260                span,
1261                "crypto.aead_decrypt: invalid tag hex",
1262            )
1263        })?;
1264
1265        let aad_bytes = aad.as_bytes();
1266        // Combine ciphertext + tag (AEAD libraries expect them concatenated).
1267        let mut ct_tag = ciphertext.clone();
1268        ct_tag.extend_from_slice(&tag);
1269
1270        let plaintext = match algorithm {
1271            "AES-256-GCM" => {
1272                use aes_gcm::aead::Aead;
1273                use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
1274                let key_arr: &[u8; 32] = key.as_slice().try_into().map_err(|_| {
1275                    Diagnostic::new(
1276                        vibe::DiagCode::E100,
1277                        span,
1278                        "AES-256-GCM key must be 32 bytes",
1279                    )
1280                })?;
1281                let nonce_arr: &[u8; 12] = nonce.as_slice().try_into().map_err(|_| {
1282                    Diagnostic::new(
1283                        vibe::DiagCode::E100,
1284                        span,
1285                        "AES-256-GCM nonce must be 12 bytes",
1286                    )
1287                })?;
1288                let cipher = Aes256Gcm::new(key_arr.into());
1289                let nonce_obj = Nonce::from(*nonce_arr);
1290                let payload = aes_gcm::aead::Payload {
1291                    msg: &ct_tag,
1292                    aad: aad_bytes,
1293                };
1294                cipher.decrypt(&nonce_obj, payload).map_err(|e| {
1295                    Diagnostic::new(
1296                        vibe::DiagCode::E100,
1297                        span,
1298                        format!("AES-256-GCM decrypt failed: {e}"),
1299                    )
1300                })?
1301            }
1302            "ChaCha20-Poly1305" => {
1303                use chacha20poly1305::aead::Aead;
1304                use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
1305                let key_arr: &[u8; 32] = key.as_slice().try_into().map_err(|_| {
1306                    Diagnostic::new(vibe::DiagCode::E100, span, "ChaCha20 key must be 32 bytes")
1307                })?;
1308                let nonce_arr: &[u8; 12] = nonce.as_slice().try_into().map_err(|_| {
1309                    Diagnostic::new(
1310                        vibe::DiagCode::E100,
1311                        span,
1312                        "ChaCha20 nonce must be 12 bytes",
1313                    )
1314                })?;
1315                let cipher = ChaCha20Poly1305::new(key_arr.into());
1316                let nonce_obj = Nonce::from(*nonce_arr);
1317                let payload = chacha20poly1305::aead::Payload {
1318                    msg: &ct_tag,
1319                    aad: aad_bytes,
1320                };
1321                cipher.decrypt(&nonce_obj, payload).map_err(|e| {
1322                    Diagnostic::new(
1323                        vibe::DiagCode::E100,
1324                        span,
1325                        format!("ChaCha20 decrypt failed: {e}"),
1326                    )
1327                })?
1328            }
1329            "XChaCha20-Poly1305" => {
1330                use chacha20poly1305::aead::Aead;
1331                use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
1332                let key_arr: &[u8; 32] = key.as_slice().try_into().map_err(|_| {
1333                    Diagnostic::new(vibe::DiagCode::E100, span, "XChaCha20 key must be 32 bytes")
1334                })?;
1335                let nonce_arr: &[u8; 24] = nonce.as_slice().try_into().map_err(|_| {
1336                    Diagnostic::new(
1337                        vibe::DiagCode::E100,
1338                        span,
1339                        "XChaCha20 nonce must be 24 bytes",
1340                    )
1341                })?;
1342                let cipher = XChaCha20Poly1305::new(key_arr.into());
1343                let nonce_obj = XNonce::from(*nonce_arr);
1344                let payload = chacha20poly1305::aead::Payload {
1345                    msg: &ct_tag,
1346                    aad: aad_bytes,
1347                };
1348                cipher.decrypt(&nonce_obj, payload).map_err(|e| {
1349                    Diagnostic::new(
1350                        vibe::DiagCode::E100,
1351                        span,
1352                        format!("XChaCha20 decrypt failed: {e}"),
1353                    )
1354                })?
1355            }
1356            _ => {
1357                return Err(Diagnostic::new(
1358                    vibe::DiagCode::E100,
1359                    span,
1360                    format!("crypto.aead_decrypt: unsupported algorithm {algorithm}"),
1361                ));
1362            }
1363        };
1364
1365        Ok(Value::String(
1366            String::from_utf8_lossy(&plaintext).into_owned(),
1367        ))
1368    }
1369
1370    /// `crypto.sign` — signs `data` with key identified by `key_id`.
1371    fn crypto_sign(
1372        &mut self,
1373        key_id: &str,
1374        data: &str,
1375        span: vibe::Span,
1376    ) -> Result<Value, Diagnostic> {
1377        let seed = self.key_vault.get(key_id).ok_or_else(|| {
1378            Diagnostic::new(
1379                vibe::DiagCode::E702,
1380                span,
1381                format!("crypto.sign: key '{key_id}' not found in key vault"),
1382            )
1383        })?;
1384        use ed25519_dalek::Signer;
1385        let signing_key = ed25519_dalek::SigningKey::from_bytes(seed);
1386        let signature = signing_key.sign(data.as_bytes());
1387        Ok(Value::String(vibe::crypto::to_hex(&signature.to_bytes())))
1388    }
1389
1390    /// `crypto.verify` — verifies `data` against `signature_hex` using key_id or raw public key hex.
1391    fn crypto_verify(
1392        &mut self,
1393        key_id: &str,
1394        data: &str,
1395        signature_hex: &str,
1396        span: vibe::Span,
1397    ) -> Result<Value, Diagnostic> {
1398        let vk = if let Some(seed) = self.key_vault.get(key_id) {
1399            let signing_key = ed25519_dalek::SigningKey::from_bytes(seed);
1400            signing_key.verifying_key()
1401        } else {
1402            let vk_bytes = vibe::crypto::from_hex(key_id).ok_or_else(|| {
1403                Diagnostic::new(
1404                    vibe::DiagCode::E702,
1405                    span,
1406                    format!("crypto.verify: unknown key id or invalid hex '{key_id}'"),
1407                )
1408            })?;
1409            let vk_arr: [u8; 32] = vk_bytes.try_into().map_err(|_| {
1410                Diagnostic::new(
1411                    vibe::DiagCode::E100,
1412                    span,
1413                    "crypto.verify: verifying key must be 32 bytes",
1414                )
1415            })?;
1416            ed25519_dalek::VerifyingKey::from_bytes(&vk_arr).map_err(|e| {
1417                Diagnostic::new(
1418                    vibe::DiagCode::E100,
1419                    span,
1420                    format!("crypto.verify: invalid verifying key: {e}"),
1421                )
1422            })?
1423        };
1424
1425        let sig_bytes = vibe::crypto::from_hex(signature_hex).ok_or_else(|| {
1426            Diagnostic::new(
1427                vibe::DiagCode::E100,
1428                span,
1429                "crypto.verify: invalid signature hex",
1430            )
1431        })?;
1432        let sig_arr: [u8; 64] = sig_bytes.try_into().map_err(|_| {
1433            Diagnostic::new(
1434                vibe::DiagCode::E100,
1435                span,
1436                "crypto.verify: signature must be 64 bytes",
1437            )
1438        })?;
1439        let sig = ed25519_dalek::Signature::from_bytes(&sig_arr);
1440        use ed25519_dalek::Verifier;
1441        let valid = vk.verify(data.as_bytes(), &sig).is_ok();
1442        Ok(Value::Bool(valid))
1443    }
1444
1445    /// `crypto.generate_key` — generates an Ed25519 keypair and registers it in the key vault.
1446    fn crypto_generate_key(
1447        &mut self,
1448        algorithm: &str,
1449        span: vibe::Span,
1450    ) -> Result<Value, Diagnostic> {
1451        let algo_upper = algorithm.to_ascii_uppercase();
1452        if algo_upper != "ED25519" && algo_upper != "EDDSA" {
1453            return Err(Diagnostic::new(
1454                vibe::DiagCode::E100,
1455                span,
1456                format!("crypto.generate_key: unsupported algorithm '{algorithm}', expected 'Ed25519'"),
1457            ));
1458        }
1459
1460        let mut seed = [0u8; 32];
1461        if let Err(e) = getrandom::fill(&mut seed) {
1462            return Err(Diagnostic::new(
1463                vibe::DiagCode::E100,
1464                span,
1465                format!("crypto.generate_key: OS entropy failed: {e}"),
1466            ));
1467        }
1468
1469        let signing_key = ed25519_dalek::SigningKey::from_bytes(&seed);
1470        let verifying_key = signing_key.verifying_key();
1471        let key_id = format!("key:ed25519:{}", self.key_vault.len());
1472        self.key_vault.insert(key_id.clone(), seed);
1473
1474        let mut record = std::collections::BTreeMap::new();
1475        record.insert("key_id".to_string(), Value::String(key_id));
1476        record.insert("public_key".to_string(), Value::String(vibe::crypto::to_hex(verifying_key.as_bytes())));
1477        record.insert("algorithm".to_string(), Value::String("Ed25519".to_string()));
1478        Ok(Value::Record(record))
1479    }
1480
1481    // ── ZK proof operations — delegate to crypto::zk_predicates / zk_proofs ─
1482
1483    /// `zk.prove_threshold` — prove `value >= threshold` via
1484    /// `crypto::zk_predicates`; E702 when `zk-culling` is off, E100 on
1485    /// prover failure.
1486    fn zk_prove_threshold(
1487        &mut self,
1488        value: u64,
1489        threshold: u64,
1490        span: vibe::Span,
1491    ) -> Result<Value, Diagnostic> {
1492        #[cfg(feature = "zk-culling")]
1493        {
1494            use crate::crypto::zk_predicates;
1495            let proof = zk_predicates::prove_threshold(value, threshold).map_err(|e| {
1496                Diagnostic::new(
1497                    vibe::DiagCode::E100,
1498                    span,
1499                    format!("zk.prove_threshold: {e}"),
1500                )
1501            })?;
1502            let proof_hex = vibe::crypto::to_hex(&proof.proof);
1503            let vk_hex = vibe::crypto::to_hex(&proof.vk);
1504            Ok(vibe::crypto::zk_proof_value(
1505                &proof_hex,
1506                &vk_hex,
1507                &format!("zk_threshold_{}_{}", value, threshold),
1508                "threshold",
1509            ))
1510        }
1511        #[cfg(not(feature = "zk-culling"))]
1512        {
1513            let _ = (value, threshold);
1514            Err(Diagnostic::new(
1515                vibe::DiagCode::E702,
1516                span,
1517                "zk.prove_threshold: zk-culling feature not enabled",
1518            ))
1519        }
1520    }
1521
1522    /// `zk.verify_threshold` — verify a threshold proof (`proof_hex`,
1523    /// `vk_hex`) against `threshold`; E702 when `zk-culling` is off.
1524    fn zk_verify_threshold(
1525        &mut self,
1526        proof_hex: &str,
1527        vk_hex: &str,
1528        threshold: u64,
1529        span: vibe::Span,
1530    ) -> Result<Value, Diagnostic> {
1531        #[cfg(feature = "zk-culling")]
1532        {
1533            use crate::crypto::zk_predicates::{verify_threshold, PredicateProof};
1534            let proof_bytes = vibe::crypto::from_hex(proof_hex).ok_or_else(|| {
1535                Diagnostic::new(
1536                    vibe::DiagCode::E100,
1537                    span,
1538                    "zk.verify_threshold: invalid proof hex",
1539                )
1540            })?;
1541            let vk_bytes = vibe::crypto::from_hex(vk_hex).ok_or_else(|| {
1542                Diagnostic::new(
1543                    vibe::DiagCode::E100,
1544                    span,
1545                    "zk.verify_threshold: invalid vk hex",
1546                )
1547            })?;
1548            let proof = PredicateProof {
1549                proof: proof_bytes,
1550                vk: vk_bytes,
1551            };
1552            let valid = verify_threshold(&proof, threshold);
1553            Ok(Value::Bool(valid))
1554        }
1555        #[cfg(not(feature = "zk-culling"))]
1556        {
1557            let _ = (proof_hex, vk_hex, threshold);
1558            Err(Diagnostic::new(
1559                vibe::DiagCode::E702,
1560                span,
1561                "zk.verify_threshold: zk-culling feature not enabled",
1562            ))
1563        }
1564    }
1565
1566    /// `zk.prove_range` — prove `lo <= value <= hi` via
1567    /// `crypto::zk_predicates::prove_range`; E702 when `zk-culling` is off.
1568    fn zk_prove_range(
1569        &mut self,
1570        value: u64,
1571        lo: u64,
1572        hi: u64,
1573        span: vibe::Span,
1574    ) -> Result<Value, Diagnostic> {
1575        #[cfg(feature = "zk-culling")]
1576        {
1577            use crate::crypto::zk_predicates;
1578            let proof = zk_predicates::prove_range(value, lo, hi).map_err(|e| {
1579                Diagnostic::new(vibe::DiagCode::E100, span, format!("zk.prove_range: {e}"))
1580            })?;
1581            let proof_hex = vibe::crypto::to_hex(&proof.proof);
1582            let vk_hex = vibe::crypto::to_hex(&proof.vk);
1583            Ok(vibe::crypto::zk_proof_value(
1584                &proof_hex,
1585                &vk_hex,
1586                &format!("zk_range_{}_{}_{}", value, lo, hi),
1587                "range",
1588            ))
1589        }
1590        #[cfg(not(feature = "zk-culling"))]
1591        {
1592            let _ = (value, lo, hi);
1593            Err(Diagnostic::new(
1594                vibe::DiagCode::E702,
1595                span,
1596                "zk.prove_range: zk-culling feature not enabled",
1597            ))
1598        }
1599    }
1600
1601    /// `zk.verify_range` — verify a range proof against `lo`/`hi`;
1602    /// E702 when `zk-culling` is off.
1603    fn zk_verify_range(
1604        &mut self,
1605        proof_hex: &str,
1606        vk_hex: &str,
1607        lo: u64,
1608        hi: u64,
1609        span: vibe::Span,
1610    ) -> Result<Value, Diagnostic> {
1611        #[cfg(feature = "zk-culling")]
1612        {
1613            use crate::crypto::zk_predicates::{verify_range, PredicateProof};
1614            let proof_bytes = vibe::crypto::from_hex(proof_hex).ok_or_else(|| {
1615                Diagnostic::new(
1616                    vibe::DiagCode::E100,
1617                    span,
1618                    "zk.verify_range: invalid proof hex",
1619                )
1620            })?;
1621            let vk_bytes = vibe::crypto::from_hex(vk_hex).ok_or_else(|| {
1622                Diagnostic::new(
1623                    vibe::DiagCode::E100,
1624                    span,
1625                    "zk.verify_range: invalid vk hex",
1626                )
1627            })?;
1628            let proof = PredicateProof {
1629                proof: proof_bytes,
1630                vk: vk_bytes,
1631            };
1632            let valid = verify_range(&proof, lo, hi);
1633            Ok(Value::Bool(valid))
1634        }
1635        #[cfg(not(feature = "zk-culling"))]
1636        {
1637            let _ = (proof_hex, vk_hex, lo, hi);
1638            Err(Diagnostic::new(
1639                vibe::DiagCode::E702,
1640                span,
1641                "zk.verify_range: zk-culling feature not enabled",
1642            ))
1643        }
1644    }
1645
1646    /// `zk.prove_matmul` — prove a `m×k × k×n` integer matmul via
1647    /// `ZkProofSystem::prove_matrix_multiply`; E702 when `zk-culling`
1648    /// is off.
1649    fn zk_prove_matmul(
1650        &mut self,
1651        m: u64,
1652        k: u64,
1653        n: u64,
1654        a: &[i128],
1655        b: &[i128],
1656        span: vibe::Span,
1657    ) -> Result<Value, Diagnostic> {
1658        #[cfg(feature = "zk-culling")]
1659        {
1660            use crate::crypto::zk_proofs::ZkProofSystem;
1661            let mut zk = ZkProofSystem::new();
1662            let (valid, result) = zk
1663                .prove_matrix_multiply(m as usize, k as usize, n as usize, a, b)
1664                .map_err(|e| {
1665                    Diagnostic::new(vibe::DiagCode::E100, span, format!("zk.prove_matmul: {e}"))
1666                })?;
1667            Ok(vibe::crypto::zk_matmul_result_value(valid, &result))
1668        }
1669        #[cfg(not(feature = "zk-culling"))]
1670        {
1671            let _ = (m, k, n, a, b);
1672            Err(Diagnostic::new(
1673                vibe::DiagCode::E702,
1674                span,
1675                "zk.prove_matmul: zk-culling feature not enabled",
1676            ))
1677        }
1678    }
1679
1680    /// `zk.list_circuits` — the registered ZK circuit names; E702 when
1681    /// `zk-culling` is off.
1682    fn zk_list_circuits(&mut self, _span: vibe::Span) -> Result<Value, Diagnostic> {
1683        #[cfg(feature = "zk-culling")]
1684        {
1685            use crate::crypto::zk_proofs::ZkProofSystem;
1686            let zk = ZkProofSystem::new();
1687            let circuits: Vec<Value> = zk.list_circuits().into_iter().map(Value::String).collect();
1688            Ok(Value::List(circuits))
1689        }
1690        #[cfg(not(feature = "zk-culling"))]
1691        {
1692            Err(Diagnostic::new(
1693                vibe::DiagCode::E702,
1694                _span,
1695                "zk.list_circuits: zk-culling feature not enabled",
1696            ))
1697        }
1698    }
1699
1700    /// Poll for the next HID event from the ring buffer (T42).
1701    /// Non-blocking: returns Null if no event is available.
1702    fn hid_poll(&mut self, _span: vibe::Span) -> Result<Value, Diagnostic> {
1703        match self.hid_events.dequeue() {
1704            None => Ok(Value::Null),
1705            Some(slot) => Ok(hid_slot_to_value(&slot)),
1706        }
1707    }
1708
1709    /// Wait for the next HID event with a timeout (T42).
1710    /// Currently non-blocking (polls once). A blocking implementation
1711    /// would require platform-specific async infrastructure.
1712    fn hid_wait(&mut self, _timeout_ns: u64, _span: vibe::Span) -> Result<Value, Diagnostic> {
1713        match self.hid_events.dequeue() {
1714            None => Ok(Value::Null),
1715            Some(slot) => Ok(hid_slot_to_value(&slot)),
1716        }
1717    }
1718
1719    /// R4: PoetSnapshot supports isolation via `fork()`.
1720    /// A forked snapshot has `attached = false`, so graph writes stay in
1721    /// the fork's staged deltas and never reach the daemon graph.
1722    fn supports_isolation(&self) -> bool {
1723        true
1724    }
1725}
1726
1727/// Convert a HidEventSlot to a VibeScript Value record (T42).
1728fn hid_slot_to_value(slot: &HidEventSlot) -> Value {
1729    let mut rec = std::collections::BTreeMap::new();
1730    rec.insert("timestamp_ns".into(), Value::U64(slot.timestamp_ns));
1731    rec.insert("source_hash".into(), Value::U64(slot.source_hash));
1732    rec.insert("event_kind".into(), Value::U64(slot.event_kind as u64));
1733    rec.insert("x".into(), Value::F64(slot.x as f64));
1734    rec.insert("y".into(), Value::F64(slot.y as f64));
1735    rec.insert("z".into(), Value::F64(slot.z as f64));
1736    if slot.capability_lease != 0 {
1737        rec.insert("capability_lease".into(), Value::U64(slot.capability_lease));
1738    }
1739    Value::Record(rec)
1740}
1741
1742/// Convert an InboundEvent to a compact HidEventSlot for the ring buffer (T42).
1743/// The source_id is hashed to fit in u64. The event kind is stored as u8.
1744impl PoetSnapshot {
1745    /// Enqueue an InboundEvent into the HID ring buffer (T42).
1746    /// Returns Err if the buffer is full (fail-closed).
1747    pub fn enqueue_hid_event(
1748        &mut self,
1749        event: &vibe::hid::InboundEvent,
1750    ) -> Result<(), &'static str> {
1751        let source_hash = crate::lexicon::generate_60bit_token(event.source_id.as_bytes());
1752        let event_kind = match event.kind {
1753            vibe::hid::EventKind::Pointer => 0,
1754            vibe::hid::EventKind::Keyboard => 1,
1755            vibe::hid::EventKind::Touch => 2,
1756            vibe::hid::EventKind::Biosignal => 3,
1757            vibe::hid::EventKind::Depth => 4,
1758            vibe::hid::EventKind::Skeleton => 5,
1759            vibe::hid::EventKind::Imu => 6,
1760            vibe::hid::EventKind::Audio => 7,
1761            vibe::hid::EventKind::Sensor => 8,
1762            vibe::hid::EventKind::Assistive => 9,
1763            vibe::hid::EventKind::Gamepad => 10,
1764            vibe::hid::EventKind::SpatialHead => 11,
1765            vibe::hid::EventKind::SpatialHand => 12,
1766            vibe::hid::EventKind::SpatialGaze => 13,
1767            vibe::hid::EventKind::Midi => 14,
1768            vibe::hid::EventKind::Haptic => 15,
1769        };
1770        // Extract x/y/z from inline payload if available
1771        let (x, y, z) = match &event.payload {
1772            vibe::hid::EventPayload::Inline(m) => {
1773                let x = match m.get("x").or_else(|| m.get("ox")) {
1774                    Some(Value::F64(v)) => *v as f32,
1775                    Some(Value::I64(v)) => *v as f32,
1776                    Some(Value::U64(v)) => *v as f32,
1777                    _ => 0.0,
1778                };
1779                let y = match m.get("y").or_else(|| m.get("oy")) {
1780                    Some(Value::F64(v)) => *v as f32,
1781                    Some(Value::I64(v)) => *v as f32,
1782                    Some(Value::U64(v)) => *v as f32,
1783                    _ => 0.0,
1784                };
1785                let z = match m.get("z").or_else(|| m.get("oz")) {
1786                    Some(Value::F64(v)) => *v as f32,
1787                    Some(Value::I64(v)) => *v as f32,
1788                    Some(Value::U64(v)) => *v as f32,
1789                    _ => 0.0,
1790                };
1791                (x, y, z)
1792            }
1793            _ => (0.0, 0.0, 0.0),
1794        };
1795        let slot = HidEventSlot {
1796            timestamp_ns: event.timestamp_ns,
1797            source_hash,
1798            event_kind,
1799            x,
1800            y,
1801            z,
1802            capability_lease: event.capability_lease.unwrap_or(0),
1803        };
1804        self.hid_events.enqueue(slot)
1805    }
1806
1807    /// Drain all HID events from the ring buffer (T42).
1808    /// Returns a Vec of event Values in FIFO order.
1809    pub fn drain_hid_events(&mut self) -> Vec<Value> {
1810        let mut events = Vec::new();
1811        while let Some(slot) = self.hid_events.dequeue() {
1812            events.push(hid_slot_to_value(&slot));
1813        }
1814        events
1815    }
1816
1817    /// Number of HID events currently buffered (T42).
1818    pub fn hid_event_count(&self) -> usize {
1819        self.hid_events.count()
1820    }
1821}
1822
1823#[cfg(test)]
1824mod tests {
1825    use super::*;
1826
1827    #[test]
1828    fn live_cell_math() {
1829        let mut snap = PoetSnapshot::default();
1830        let v = snap.eval_cell_src("= math.max(1, math.min(9, 4))").unwrap();
1831        assert_eq!(v.as_f64(), Some(4.0));
1832    }
1833
1834    #[test]
1835    fn lamp_evals_on_poet_snapshot() {
1836        let src = include_str!("../../../vibe/fixtures/lamp.vibe");
1837        let mut snap = PoetSnapshot::default();
1838        snap.eval_program_src(src)
1839            .unwrap_or_else(|e| panic!("PoetHost lamp: {e}"));
1840        assert_eq!(snap.environment(), vibe::HostEnvironment::NativeDesktop);
1841        assert_eq!(snap.acceleration_tier(), vibe::AccelerationTier::ScalarCpu);
1842    }
1843
1844    #[test]
1845    fn obligate_term_lowers_to_nquin_on_poet_host() {
1846        let src = r#"
1847            using DeonticLogic;
1848            pure fn term() -> Record {
1849                return obligate { "sign" };
1850            }
1851        "#;
1852        let mut snap = PoetSnapshot::default();
1853        let v = snap
1854            .eval_fn(src, "term", Vec::new())
1855            .unwrap_or_else(|e| panic!("PoetHost deontic: {e}"));
1856        let Value::Record(m) = v else {
1857            panic!("expected record, got {v}");
1858        };
1859        assert_eq!(
1860            m.get("id"),
1861            Some(&Value::String("DeonticLogic.evaluate".into()))
1862        );
1863        assert_eq!(m.get("evaluated"), Some(&Value::Bool(true)));
1864        match m.get("verdicts") {
1865            Some(Value::List(xs)) => {
1866                assert!(!xs.is_empty());
1867                assert!(
1868                    !xs.iter()
1869                        .any(|row| matches!(row, Value::String(s) if s.contains("opcode="))),
1870                    "verdicts must be records, not JSON-ish strings"
1871                );
1872            }
1873            other => panic!("expected verdict list, got {other:?}"),
1874        }
1875    }
1876
1877    #[test]
1878    fn knows_term_lowers_to_nquin_on_poet_host() {
1879        let src = r#"
1880            using EpistemicLogic;
1881            pure fn term() -> Record {
1882                return knows { "fever" };
1883            }
1884        "#;
1885        let mut snap = PoetSnapshot::default();
1886        let v = snap
1887            .eval_fn(src, "term", Vec::new())
1888            .unwrap_or_else(|e| panic!("PoetHost epistemic: {e}"));
1889        let Value::Record(m) = v else {
1890            panic!("expected record, got {v}");
1891        };
1892        assert_eq!(
1893            m.get("id"),
1894            Some(&Value::String("EpistemicLogic.evaluate".into()))
1895        );
1896        assert_eq!(m.get("evaluated"), Some(&Value::Bool(true)));
1897        assert!(m.get("verdict_count").is_some());
1898    }
1899
1900    #[test]
1901    fn eval_records_sentinel_workspace() {
1902        let mut snap = PoetSnapshot::default();
1903        snap.eval_program_src("cell a := 1;\n")
1904            .unwrap_or_else(|e| panic!("{e}"));
1905        assert!(
1906            snap.last_eval_workspace_left <= vibe::SENTINEL_BYTES,
1907            "workspace {} exceeds Sentinel",
1908            snap.last_eval_workspace_left
1909        );
1910    }
1911
1912    #[cfg(not(target_arch = "wasm32"))]
1913    #[test]
1914    fn eval_quins_seal_into_slg_arena() {
1915        let q = crate::modalities::logic::deontic::compile_norm_quin(
1916            crate::lexicon::generate_60bit_token(b"did:q:test"),
1917            crate::modalities::logic::deontic::OP_OBLIGATE,
1918            crate::lexicon::generate_60bit_token(b"vibe:action"),
1919            crate::lexicon::generate_60bit_token(b"sign"),
1920            crate::lexicon::generate_60bit_token(b"vibe:contract"),
1921            0,
1922            false,
1923        );
1924        let snap = PoetSnapshot::with_seed(vec![q]);
1925        let mut arena = crate::webizen::SlgArena::new();
1926        let n = snap.seal_eval_quins_into_arena(&mut arena);
1927        assert_eq!(n, 1);
1928        assert!(arena
1929            .check_table(q.subject, q.predicate, q.object)
1930            .is_some());
1931    }
1932
1933    #[test]
1934    fn t42_enqueue_and_poll_hid_event() {
1935        let mut snap = PoetSnapshot::default();
1936        let event = vibe::hid::InboundEvent::pointer_move(1000, "mouse:0", 10.5, 20.5);
1937        assert!(snap.enqueue_hid_event(&event).is_ok());
1938        assert_eq!(snap.hid_event_count(), 1);
1939
1940        // Poll via Host trait
1941        let v = snap.hid_poll(vibe::Span::point(0)).unwrap();
1942        match v {
1943            Value::Record(r) => {
1944                assert_eq!(r.get("timestamp_ns"), Some(&Value::U64(1000)));
1945                assert_eq!(r.get("event_kind"), Some(&Value::U64(0))); // Pointer
1946                                                                       // x and y should be extracted from inline payload
1947                if let Some(Value::F64(x)) = r.get("x") {
1948                    assert!((x - 10.5).abs() < 0.01);
1949                } else {
1950                    panic!("expected x coordinate");
1951                }
1952            }
1953            other => panic!("expected record, got {other:?}"),
1954        }
1955        assert_eq!(snap.hid_event_count(), 0);
1956    }
1957
1958    #[test]
1959    fn t42_hid_poll_empty_returns_null() {
1960        let mut snap = PoetSnapshot::default();
1961        let v = snap.hid_poll(vibe::Span::point(0)).unwrap();
1962        assert_eq!(v, Value::Null);
1963    }
1964
1965    #[test]
1966    fn t42_enqueue_keyboard_event() {
1967        let mut snap = PoetSnapshot::default();
1968        let event = vibe::hid::InboundEvent::keyboard(2000, "keyboard:0", 65, true);
1969        assert!(snap.enqueue_hid_event(&event).is_ok());
1970
1971        let v = snap.hid_poll(vibe::Span::point(0)).unwrap();
1972        match v {
1973            Value::Record(r) => {
1974                assert_eq!(r.get("event_kind"), Some(&Value::U64(1))); // Keyboard
1975            }
1976            other => panic!("expected record, got {other:?}"),
1977        }
1978    }
1979
1980    #[test]
1981    fn t42_drain_hid_events() {
1982        let mut snap = PoetSnapshot::default();
1983        for i in 0..5 {
1984            let event = vibe::hid::InboundEvent::pointer_move(i * 1000, "mouse:0", 0.0, 0.0);
1985            snap.enqueue_hid_event(&event).unwrap();
1986        }
1987        assert_eq!(snap.hid_event_count(), 5);
1988        let drained = snap.drain_hid_events();
1989        assert_eq!(drained.len(), 5);
1990        assert_eq!(snap.hid_event_count(), 0);
1991    }
1992
1993    #[test]
1994    fn t42_hid_wait_returns_event() {
1995        let mut snap = PoetSnapshot::default();
1996        let event = vibe::hid::InboundEvent::pointer_move(5000, "mouse:0", 1.0, 2.0);
1997        snap.enqueue_hid_event(&event).unwrap();
1998
1999        let v = snap.hid_wait(1_000_000, vibe::Span::point(0)).unwrap();
2000        match v {
2001            Value::Record(r) => {
2002                assert_eq!(r.get("timestamp_ns"), Some(&Value::U64(5000)));
2003            }
2004            other => panic!("expected record, got {other:?}"),
2005        }
2006    }
2007
2008    #[test]
2009    fn t42_hid_wait_empty_returns_null() {
2010        let mut snap = PoetSnapshot::default();
2011        let v = snap.hid_wait(0, vibe::Span::point(0)).unwrap();
2012        assert_eq!(v, Value::Null);
2013    }
2014
2015
2016
2017    #[test]
2018    fn t46_hid_buffer_enqueue_dequeue() {
2019        let mut buf = HidEventBuffer::new();
2020        assert!(buf.is_empty());
2021        let event = HidEventSlot {
2022            timestamp_ns: 1000,
2023            source_hash: 0xABC,
2024            event_kind: 1,
2025            x: 10.0,
2026            y: 20.0,
2027            z: 0.0,
2028            capability_lease: 0,
2029        };
2030        assert!(buf.enqueue(event).is_ok());
2031        assert_eq!(buf.count(), 1);
2032        let dequeued = buf.dequeue().unwrap();
2033        assert_eq!(dequeued.timestamp_ns, 1000);
2034        assert!(buf.is_empty());
2035    }
2036
2037    #[test]
2038    fn t46_hid_buffer_quota_enforced() {
2039        let mut buf = HidEventBuffer::new();
2040        // Fill to quota
2041        for i in 0..HID_SAMPLE_QUOTA {
2042            let event = HidEventSlot {
2043                timestamp_ns: i as u64,
2044                source_hash: 0,
2045                event_kind: 0,
2046                x: 0.0,
2047                y: 0.0,
2048                z: 0.0,
2049                capability_lease: 0,
2050            };
2051            assert!(buf.enqueue(event).is_ok(), "enqueue {} should succeed", i);
2052        }
2053        assert!(buf.is_full());
2054        // Next enqueue should fail (fail-closed)
2055        let overflow = HidEventSlot::default();
2056        assert!(buf.enqueue(overflow).is_err(), "should reject when full");
2057    }
2058
2059    #[test]
2060    fn t46_hid_buffer_fifo_order() {
2061        let mut buf = HidEventBuffer::new();
2062        for i in 0..10 {
2063            buf.enqueue(HidEventSlot {
2064                timestamp_ns: i,
2065                ..Default::default()
2066            })
2067            .unwrap();
2068        }
2069        for i in 0..10 {
2070            let event = buf.dequeue().unwrap();
2071            assert_eq!(event.timestamp_ns, i, "FIFO order violated at {}", i);
2072        }
2073    }
2074
2075    #[test]
2076    fn t46_hid_buffer_clear() {
2077        let mut buf = HidEventBuffer::new();
2078        buf.enqueue(HidEventSlot::default()).unwrap();
2079        assert!(!buf.is_empty());
2080        buf.clear();
2081        assert!(buf.is_empty());
2082    }
2083
2084    #[test]
2085    fn t46_hid_quota_is_4096() {
2086        assert_eq!(HID_SAMPLE_QUOTA, 4096);
2087    }
2088
2089    #[test]
2090    fn t46_snapshot_has_hid_buffer() {
2091        let snap = PoetSnapshot::with_seed(Vec::new());
2092        assert!(snap.hid_events.is_empty());
2093    }
2094
2095    #[test]
2096    fn crypto_sha256_through_vibe() {
2097        let mut snap = PoetSnapshot::default();
2098        let src = r#"
2099            import "crypto" as crypto;
2100            fn hash_it() {
2101                return crypto.sha256("hello");
2102            }
2103        "#;
2104        let v = snap.eval_fn(src, "hash_it", vec![]).unwrap();
2105        let rec = match v {
2106            Value::Record(r) => r,
2107            _ => panic!("expected Record"),
2108        };
2109        let hex = match rec.get("hex") {
2110            Some(Value::String(s)) => s.clone(),
2111            _ => panic!("expected hex String"),
2112        };
2113        // SHA-256("hello") = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
2114        assert_eq!(
2115            hex,
2116            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
2117        );
2118    }
2119
2120    #[test]
2121    fn crypto_blake3_through_vibe() {
2122        let mut snap = PoetSnapshot::default();
2123        let src = r#"
2124            import "crypto" as crypto;
2125            fn hash_it() {
2126                return crypto.blake3("hello");
2127            }
2128        "#;
2129        let v = snap.eval_fn(src, "hash_it", vec![]).unwrap();
2130        let rec = match v {
2131            Value::Record(r) => r,
2132            _ => panic!("expected Record"),
2133        };
2134        let algorithm = match rec.get("algorithm") {
2135            Some(Value::String(s)) => s.clone(),
2136            _ => panic!("expected algorithm String"),
2137        };
2138        assert_eq!(algorithm, "BLAKE3");
2139        // BLAKE3 hash is 32 bytes
2140        let bytes = match rec.get("bytes") {
2141            Some(Value::U64(n)) => *n,
2142            _ => panic!("expected bytes U64"),
2143        };
2144        assert_eq!(bytes, 32);
2145    }
2146
2147    #[test]
2148    fn crypto_hkdf_through_vibe() {
2149        let mut snap = PoetSnapshot::default();
2150        let src = r#"
2151            import "crypto" as crypto;
2152            fn derive() {
2153                return crypto.hkdf_sha256("input key material", "info", 32);
2154            }
2155        "#;
2156        let v = snap.eval_fn(src, "derive", vec![]).unwrap();
2157        match v {
2158            Value::String(hex) => {
2159                // 32 bytes = 64 hex chars
2160                assert_eq!(hex.len(), 64);
2161            }
2162            _ => panic!("expected String"),
2163        }
2164    }
2165
2166    #[test]
2167    fn crypto_aead_round_trip_through_vibe() {
2168        let mut snap = PoetSnapshot::default();
2169        // Use a 32-byte key (64 hex chars) and 12-byte nonce (24 hex chars)
2170        let key_hex = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
2171        let nonce_hex = "0102030405060708090a0b0c";
2172        let src = format!(
2173            r#"
2174            import "crypto" as crypto;
2175            fn encrypt_it() {{
2176                return crypto.aead_encrypt("AES-256-GCM", "{}", "{}", "secret message", "aad");
2177            }}
2178            fn decrypt_it(ct_hex: String, tag_hex: String) {{
2179                return crypto.aead_decrypt("AES-256-GCM", "{}", "{}", ct_hex, tag_hex, "aad");
2180            }}
2181        "#,
2182            key_hex, nonce_hex, key_hex, nonce_hex
2183        );
2184        let enc = snap.eval_fn(&src, "encrypt_it", vec![]).unwrap();
2185        let enc_rec = match &enc {
2186            Value::Record(r) => r,
2187            _ => panic!("expected Record"),
2188        };
2189        let ct_hex = match enc_rec.get("ciphertext_hex") {
2190            Some(Value::String(s)) => s.clone(),
2191            _ => panic!("expected ciphertext_hex"),
2192        };
2193        let tag_hex = match enc_rec.get("tag_hex") {
2194            Some(Value::String(s)) => s.clone(),
2195            _ => panic!("expected tag_hex"),
2196        };
2197        let dec = snap
2198            .eval_fn(
2199                &src,
2200                "decrypt_it",
2201                vec![Value::String(ct_hex), Value::String(tag_hex)],
2202            )
2203            .unwrap();
2204        match dec {
2205            Value::String(s) => assert_eq!(s, "secret message"),
2206            _ => panic!("expected String"),
2207        }
2208    }
2209
2210
2211
2212    // ── ZK proof tests (real Groth16 over BLS12-381) ───────────────────
2213
2214    #[test]
2215    fn zk_threshold_prove_and_verify_through_vibe() {
2216        let mut snap = PoetSnapshot::default();
2217        let src = r#"
2218            import "zk" as zk;
2219            fn prove_age() {
2220                return zk.prove_threshold(21, 18);
2221            }
2222        "#;
2223        let proof_val = snap.eval_fn(src, "prove_age", vec![]).unwrap();
2224        let rec = match &proof_val {
2225            Value::Record(r) => r,
2226            _ => panic!("expected Record"),
2227        };
2228        let proof_hex = match rec.get("proof_hex") {
2229            Some(Value::String(s)) => s.clone(),
2230            _ => panic!("expected proof_hex"),
2231        };
2232        let vk_hex = match rec.get("vk_hex") {
2233            Some(Value::String(s)) => s.clone(),
2234            _ => panic!("expected vk_hex"),
2235        };
2236
2237        // Verify the proof against the correct threshold (18).
2238        let verify_src = format!(
2239            r#"
2240            import "zk" as zk;
2241            fn verify_age(proof_hex: String, vk_hex: String) {{
2242                return zk.verify_threshold(proof_hex, vk_hex, 18);
2243            }}
2244        "#
2245        );
2246        let result = snap
2247            .eval_fn(
2248                &verify_src,
2249                "verify_age",
2250                vec![Value::String(proof_hex), Value::String(vk_hex)],
2251            )
2252            .unwrap();
2253        assert!(match result {
2254            Value::Bool(b) => b,
2255            _ => false,
2256        });
2257    }
2258
2259    #[test]
2260    fn zk_threshold_wrong_threshold_fails() {
2261        let mut snap = PoetSnapshot::default();
2262        // Prove value=21 >= threshold=18
2263        let prove_src = r#"
2264            import "zk" as zk;
2265            fn prove() {
2266                return zk.prove_threshold(21, 18);
2267            }
2268        "#;
2269        let proof_val = snap.eval_fn(prove_src, "prove", vec![]).unwrap();
2270        let rec = match &proof_val {
2271            Value::Record(r) => r,
2272            _ => panic!("expected Record"),
2273        };
2274        let proof_hex = match rec.get("proof_hex") {
2275            Some(Value::String(s)) => s.clone(),
2276            _ => panic!("expected proof_hex"),
2277        };
2278        let vk_hex = match rec.get("vk_hex") {
2279            Some(Value::String(s)) => s.clone(),
2280            _ => panic!("expected vk_hex"),
2281        };
2282
2283        // Verify against the WRONG threshold (21) — should fail.
2284        // A proof made for threshold=18 does not verify against threshold=21.
2285        let verify_src = format!(
2286            r#"
2287            import "zk" as zk;
2288            fn verify(proof_hex: String, vk_hex: String) {{
2289                return zk.verify_threshold(proof_hex, vk_hex, 21);
2290            }}
2291        "#
2292        );
2293        let result = snap
2294            .eval_fn(
2295                &verify_src,
2296                "verify",
2297                vec![Value::String(proof_hex), Value::String(vk_hex)],
2298            )
2299            .unwrap();
2300        assert!(match result {
2301            Value::Bool(b) => !b,
2302            _ => false,
2303        });
2304    }
2305
2306    #[test]
2307    fn zk_threshold_false_statement_unprovable() {
2308        let mut snap = PoetSnapshot::default();
2309        // Try to prove value=15 >= threshold=18 — should fail (unprovable).
2310        let src = r#"
2311            import "zk" as zk;
2312            fn prove_false() {
2313                return zk.prove_threshold(15, 18);
2314            }
2315        "#;
2316        let result = snap.eval_fn(src, "prove_false", vec![]);
2317        assert!(result.is_err());
2318    }
2319
2320    #[test]
2321    fn zk_range_prove_and_verify_through_vibe() {
2322        let mut snap = PoetSnapshot::default();
2323        // Prove 25 is in [18, 65]
2324        let prove_src = r#"
2325            import "zk" as zk;
2326            fn prove() {
2327                return zk.prove_range(25, 18, 65);
2328            }
2329        "#;
2330        let proof_val = snap.eval_fn(prove_src, "prove", vec![]).unwrap();
2331        let rec = match &proof_val {
2332            Value::Record(r) => r,
2333            _ => panic!("expected Record"),
2334        };
2335        let proof_hex = match rec.get("proof_hex") {
2336            Some(Value::String(s)) => s.clone(),
2337            _ => panic!("expected proof_hex"),
2338        };
2339        let vk_hex = match rec.get("vk_hex") {
2340            Some(Value::String(s)) => s.clone(),
2341            _ => panic!("expected vk_hex"),
2342        };
2343
2344        // Verify against the correct bounds.
2345        let verify_src = format!(
2346            r#"
2347            import "zk" as zk;
2348            fn verify(proof_hex: String, vk_hex: String) {{
2349                return zk.verify_range(proof_hex, vk_hex, 18, 65);
2350            }}
2351        "#
2352        );
2353        let result = snap
2354            .eval_fn(
2355                &verify_src,
2356                "verify",
2357                vec![Value::String(proof_hex), Value::String(vk_hex)],
2358            )
2359            .unwrap();
2360        assert!(match result {
2361            Value::Bool(b) => b,
2362            _ => false,
2363        });
2364    }
2365
2366    #[test]
2367    fn zk_range_outside_bounds_unprovable() {
2368        let mut snap = PoetSnapshot::default();
2369        // Try to prove 100 is in [18, 65] — should fail.
2370        let src = r#"
2371            import "zk" as zk;
2372            fn prove_false() {
2373                return zk.prove_range(100, 18, 65);
2374            }
2375        "#;
2376        let result = snap.eval_fn(src, "prove_false", vec![]);
2377        assert!(result.is_err());
2378    }
2379
2380    #[test]
2381    fn zk_matmul_prove_through_vibe() {
2382        let mut snap = PoetSnapshot::default();
2383        // 2x2 matrix multiply: A = [[1,2],[3,4]], B = [[5,6],[7,8]]
2384        // C = [[19,22],[43,50]]
2385        let src = r#"
2386            import "zk" as zk;
2387            fn prove() {
2388                return zk.prove_matmul(2, 2, 2, [1, 2, 3, 4], [5, 6, 7, 8]);
2389            }
2390        "#;
2391        let result = snap.eval_fn(src, "prove", vec![]).unwrap();
2392        let rec = match &result {
2393            Value::Record(r) => r,
2394            _ => panic!("expected Record"),
2395        };
2396        // The proof should be valid.
2397        assert_eq!(
2398            match rec.get("valid").unwrap() {
2399                Value::Bool(b) => *b,
2400                _ => panic!("expected Bool"),
2401            },
2402            true
2403        );
2404        // The result should be [19, 22, 43, 50].
2405        match rec.get("result").unwrap() {
2406            Value::List(xs) => {
2407                assert_eq!(xs.len(), 4);
2408                assert_eq!(
2409                    match &xs[0] {
2410                        Value::I64(n) => *n,
2411                        _ => panic!("expected I64"),
2412                    },
2413                    19
2414                );
2415                assert_eq!(
2416                    match &xs[1] {
2417                        Value::I64(n) => *n,
2418                        _ => panic!("expected I64"),
2419                    },
2420                    22
2421                );
2422                assert_eq!(
2423                    match &xs[2] {
2424                        Value::I64(n) => *n,
2425                        _ => panic!("expected I64"),
2426                    },
2427                    43
2428                );
2429                assert_eq!(
2430                    match &xs[3] {
2431                        Value::I64(n) => *n,
2432                        _ => panic!("expected I64"),
2433                    },
2434                    50
2435                );
2436            }
2437            _ => panic!("expected List"),
2438        }
2439    }
2440
2441    #[test]
2442    fn demo_seed_is_queryable() {
2443        let mut snap = PoetSnapshot::with_demo_seed();
2444        let src = r#"
2445requires [ capability("graph.read") ];
2446fn count() {
2447    let rows = graph.query(?s, clinic:hasCondition, ?o, take: 8)?;
2448    return rows;
2449}
2450"#;
2451        let v = snap.eval_fn(src, "count", vec![]).unwrap();
2452        match v {
2453            Value::List(xs) => assert_eq!(xs.len(), 1),
2454            other => panic!("{other:?}"),
2455        }
2456    }
2457
2458    #[test]
2459    fn live_query_and_commit() {
2460        let pred = generate_60bit_token(b"clinic:hasCondition");
2461        let seed = NQuin {
2462            subject: 1,
2463            predicate: pred,
2464            object: 2,
2465            context: 0,
2466            metadata: 0,
2467            parity: NQuin::calculate_parity(1, pred, 2, 0, 0),
2468        };
2469        let mut snap = PoetSnapshot::with_seed(vec![seed]);
2470        let src = r#"
2471requires [ capability("graph.read") ];
2472fn count() {
2473    let rows = graph.query(?s, clinic:hasCondition, ?o, take: 8)?;
2474    return rows;
2475}
2476"#;
2477        let v = snap.eval_fn(src, "count", vec![]).unwrap();
2478        match v {
2479            Value::List(xs) => assert_eq!(xs.len(), 1),
2480            other => panic!("{other:?}"),
2481        }
2482    }
2483
2484    #[test]
2485    fn graph_snapshot_and_capability_resolve() {
2486        let mut snap = PoetSnapshot::with_demo_seed();
2487        let src = r#"
2488fn peek() {
2489    return capability.resolve("graph.read");
2490}
2491"#;
2492        let v = snap.eval_fn(src, "peek", vec![]).unwrap();
2493        match v {
2494            Value::Record(r) => {
2495                assert_eq!(r.get("vibe_bound"), Some(&Value::Bool(true)));
2496            }
2497            other => panic!("{other:?}"),
2498        }
2499        let snap_src = r#"
2500requires [ capability("graph.read") ];
2501fn snap() { return graph.snapshot(); }
2502"#;
2503        let rev = snap.eval_fn(snap_src, "snap", vec![]).unwrap();
2504        assert_eq!(rev, Value::U64(1));
2505    }
2506
2507    #[test]
2508    fn aura_validate_sees_staged_reifier_and_rejects_unknown() {
2509        let mut snap = PoetSnapshot::default();
2510        let src = r#"
2511prefix clinic: <https://qualiadb.org/clinic/>;
2512requires [
2513    capability("graph.write"),
2514    capability("aura.validate")
2515];
2516effect fn check() -> Result<Receipt, string> {
2517    let stated = << clinic:sensor_1 clinic:emitsAlert clinic:Overheat ~ clinic:claim_1 >>;
2518    transaction {
2519        graph.stage(stated);
2520        if !aura.validate(clinic:claim_1, clinic:EmergencyAlertShape) {
2521            return Err("shape");
2522        }
2523        if aura.validate(clinic:missing, clinic:EmergencyAlertShape) {
2524            return Err("unknown should fail");
2525        }
2526        graph.commit()?;
2527    };
2528    return Ok(receipt_empty());
2529}
2530"#;
2531        let v = snap.eval_fn(src, "check", vec![]).unwrap();
2532        assert!(matches!(v, Value::Ok(_)));
2533        assert_eq!(snap.committed.len(), 2);
2534    }
2535
2536    #[test]
2537    fn seal_does_not_expose_parity_to_script() {
2538        let mut snap = PoetSnapshot::default();
2539        let src = r#"
2540fn make() {
2541    return quin.statement(
2542        subject: <https://example.org/s>,
2543        predicate: <https://example.org/p>,
2544        object: <https://example.org/o>,
2545        context: <https://example.org/g>
2546    );
2547}
2548"#;
2549        let v = snap.eval_fn(src, "make", vec![]).unwrap();
2550        assert!(matches!(v, Value::QuinRef(_)));
2551    }
2552
2553    #[test]
2554    fn transaction_abort_drops_unstaged_commit() {
2555        let mut snap = PoetSnapshot::default();
2556        let src = r#"
2557prefix clinic: <https://qualiadb.org/clinic/>;
2558requires [ capability("graph.write") ];
2559effect fn nope() -> Result<Receipt, string> {
2560    transaction {
2561        let stated = << clinic:a clinic:p clinic:o ~ clinic:r >>;
2562        graph.stage(stated);
2563        return Err("abort");
2564    };
2565    return Ok(receipt_empty());
2566}
2567"#;
2568        let v = snap.eval_fn(src, "nope", vec![]).unwrap();
2569        assert!(matches!(v, Value::Err(_)));
2570        assert!(snap.committed.is_empty());
2571        assert!(snap.staged.is_empty());
2572    }
2573
2574    #[test]
2575    fn pulse_rejects_off_allowlist() {
2576        let mut snap = PoetSnapshot::default();
2577        let src = r#"
2578requires [ capability("pulse.publish") ];
2579effect fn go() {
2580    effect pulse.publish("not-allowed/x", 1);
2581    return null;
2582}
2583"#;
2584        let err = snap.eval_fn(src, "go", vec![]).unwrap_err();
2585        assert_eq!(err.code, vibe::DiagCode::E500);
2586    }
2587
2588    #[test]
2589    fn pulse_records_payload_summary() {
2590        let mut snap = PoetSnapshot::default();
2591        let src = r#"
2592requires [ capability("pulse.publish") ];
2593effect fn go() {
2594    effect pulse.publish("pulse/test-payload", "hello world");
2595    return null;
2596}
2597"#;
2598        snap.eval_fn(src, "go", vec![]).unwrap();
2599        assert_eq!(snap.published.len(), 1);
2600        assert_eq!(snap.published[0].topic, "pulse/test-payload");
2601        assert!(
2602            snap.published[0].payload_summary.contains("hello world"),
2603            "payload summary should contain the payload text, got: {}",
2604            snap.published[0].payload_summary
2605        );
2606        // Detached snapshot → seq is 0 (no transport emission).
2607        assert_eq!(snap.published[0].seq, 0);
2608    }
2609
2610    #[cfg(not(target_arch = "wasm32"))]
2611    #[test]
2612    fn pulse_attached_emits_to_transport() {
2613        use crate::pulse_transport;
2614        let mut snap = PoetSnapshot::from_daemon();
2615        let mut rx = pulse_transport::subscribe();
2616        let src = r#"
2617requires [ capability("pulse.publish") ];
2618effect fn go() {
2619    effect pulse.publish("pulse/transport-test", 42);
2620    return null;
2621}
2622"#;
2623        snap.eval_fn(src, "go", vec![]).unwrap();
2624        assert_eq!(snap.published.len(), 1);
2625        assert!(snap.published[0].seq > 0, "attached pulse should get a seq");
2626        let event = rx
2627            .try_recv()
2628            .expect("transport subscriber should receive event");
2629        assert_eq!(event.topic, "pulse/transport-test");
2630        assert_eq!(event.seq, snap.published[0].seq);
2631    }
2632
2633    #[test]
2634    fn dispatch_hook_routes_pulse_message_to_function() {
2635        let mut snap = PoetSnapshot::with_demo_seed();
2636        let src = r#"
2637requires [
2638    capability("graph.write"),
2639    capability("pulse.publish", topic: "clinic/alerts")
2640];
2641effect fn raise_alert(value: f64) {
2642    if value > 85.0 {
2643        effect pulse.publish("clinic/alerts", value);
2644    }
2645    return null;
2646}
2647on pulse:message(topic: string, value: f64) {
2648    return raise_alert(value);
2649}
2650"#;
2651        let path = vec!["pulse".to_string(), "message".to_string()];
2652        let v = snap
2653            .dispatch_hook_src(
2654                src,
2655                &path,
2656                vec![Value::String("clinic/alerts".into()), Value::F64(90.0)],
2657            )
2658            .unwrap();
2659        assert_eq!(v, Value::Null);
2660        assert_eq!(
2661            snap.published.len(),
2662            1,
2663            "hook should have triggered a publish"
2664        );
2665        assert_eq!(snap.published[0].topic, "clinic/alerts");
2666    }
2667
2668    #[test]
2669    fn dispatch_hook_unknown_path_returns_null() {
2670        let mut snap = PoetSnapshot::default();
2671        let src = r#"
2672on tick() {
2673    return null;
2674}
2675"#;
2676        let path = vec!["unknown".to_string()];
2677        let v = snap.dispatch_hook_src(src, &path, vec![]).unwrap();
2678        assert_eq!(v, Value::Null);
2679    }
2680
2681    #[cfg(not(target_arch = "wasm32"))]
2682    #[test]
2683    fn attach_reads_daemon_graph() {
2684        let seed = NQuin {
2685            subject: 0x00C0_FFEE_0000_0001,
2686            predicate: 0x00C0_FFEE_0000_0002,
2687            object: 0x00C0_FFEE_0000_0003,
2688            context: 0,
2689            metadata: 0,
2690            parity: NQuin::calculate_parity(
2691                0x00C0_FFEE_0000_0001,
2692                0x00C0_FFEE_0000_0002,
2693                0x00C0_FFEE_0000_0003,
2694                0,
2695                0,
2696            ),
2697        };
2698        crate::daemon_graph::extend_with_ontology_quins_slice(&[seed]);
2699        let mut snap = PoetSnapshot::from_daemon();
2700        assert!(snap.attached);
2701        assert!(snap.committed.is_empty());
2702        assert_eq!(snap.honesty(), "live");
2703        let src = r#"
2704requires [ capability("graph.read") ];
2705fn find() {
2706    return graph.query(?s, ?p, ?o, take: 64)?;
2707}
2708"#;
2709        let v = snap.eval_fn(src, "find", vec![]).unwrap();
2710        match v {
2711            Value::List(xs) => {
2712                assert!(xs.iter().any(|row| matches!(
2713                    row,
2714                    Value::QuinRef(qr) if qr.raw_fields()[0] == seed.subject
2715                )));
2716            }
2717            other => panic!("{other:?}"),
2718        }
2719    }
2720
2721    #[test]
2722    fn time_unix_returns_wall_clock_on_native() {
2723        let mut snap = PoetSnapshot::default();
2724        let src = "effect fn now() { return time.unix(); }";
2725        let v = snap.eval_fn(src, "now", vec![]).unwrap();
2726        // Native: real wall clock is positive. WASM: 0 (default). Both are I64.
2727        #[cfg(not(target_arch = "wasm32"))]
2728        assert!(v.as_i64().unwrap_or(0) > 0, "wall clock should be positive");
2729        #[cfg(target_arch = "wasm32")]
2730        assert_eq!(v.as_i64(), Some(0));
2731    }
2732
2733    #[test]
2734    fn time_unix_resolves_as_partial_vibe_binding() {
2735        match crate::poet_host::catalog::resolve_id("time.unix") {
2736            Value::Record(r) => {
2737                assert_eq!(r.get("vibe_bound"), Some(&Value::Bool(true)));
2738            }
2739            other => panic!("{other:?}"),
2740        }
2741    }
2742
2743    #[test]
2744    fn invoke_lists_engine_and_rejects_unknown() {
2745        let mut snap = PoetSnapshot::default();
2746        let src = r#"
2747requires [ capability("capability.invoke"), capability("CapabilityDiscovery.list") ];
2748effect fn list() {
2749    return capability.invoke("CapabilityDiscovery.list", null);
2750}
2751"#;
2752        let v = snap.eval_fn(src, "list", vec![]).unwrap();
2753        match v {
2754            Value::Record(r) => match r.get("invoke") {
2755                Some(Value::List(xs)) => assert!(!xs.is_empty()),
2756                other => panic!("{other:?}"),
2757            },
2758            other => panic!("{other:?}"),
2759        }
2760        let err = snap
2761            .eval_fn(
2762                r#"
2763requires [ capability("capability.invoke") ];
2764effect fn boom() {
2765    return capability.invoke("DoesNotExist.nope", null);
2766}
2767"#,
2768                "boom",
2769                vec![],
2770            )
2771            .unwrap_err();
2772        assert_eq!(err.code, vibe::DiagCode::E300);
2773    }
2774
2775    #[test]
2776    fn time_unix_sets_time_read_during_eval() {
2777        let mut snap = PoetSnapshot::default();
2778        let src = "effect fn now() { return time.unix(); }";
2779        snap.eval_fn(src, "now", vec![]).unwrap();
2780        assert!(
2781            snap.time_read_during_eval,
2782            "time.unix should set time_read_during_eval"
2783        );
2784    }
2785
2786    #[test]
2787    fn eval_cell_resets_time_read_during_eval() {
2788        let mut snap = PoetSnapshot::default();
2789        // First, trigger time_unix via a function call.
2790        snap.eval_fn("effect fn now() { return time.unix(); }", "now", vec![])
2791            .unwrap();
2792        assert!(snap.time_read_during_eval);
2793        // Now eval a cell that doesn't use time — flag should reset to false.
2794        snap.eval_cell_src("= 1 + 2").unwrap();
2795        assert!(
2796            !snap.time_read_during_eval,
2797            "eval_cell_src should reset time_read_during_eval"
2798        );
2799    }
2800
2801
2802    #[test]
2803    fn dispatch_tick_no_hook_returns_null() {
2804        let mut snap = PoetSnapshot::default();
2805        let src = r#"
2806on pulse:message(topic: string) {
2807    return null;
2808}
2809"#;
2810        let path = vec!["tick".to_string()];
2811        let v = snap.dispatch_hook_src(src, &path, vec![]).unwrap();
2812        assert_eq!(v, Value::Null, "no matching tick hook should return null");
2813    }
2814
2815    // ── Phase G: Golden corpus — capability.invoke fixtures ──────────────
2816
2817    #[test]
2818    fn g_physics_wave_1d_invoke() {
2819        let mut snap = PoetSnapshot::default();
2820        let src = r#"
2821requires [ capability("capability.invoke"), capability("Physics.wave_1d") ];
2822effect fn go() {
2823    return capability.invoke("Physics.wave_1d", {
2824        u0: [0.0, 0.5, 1.0, 0.5, 0.0],
2825        v0: [0.0, 0.0, 0.0, 0.0, 0.0],
2826        c: 1.0,
2827        dx: 0.1,
2828        total_time: 0.5,
2829        samples: 10
2830    });
2831}
2832"#;
2833        let v = snap.eval_fn(src, "go", vec![]).unwrap();
2834        match v {
2835            Value::Record(r) => {
2836                assert!(
2837                    r.contains_key("energy_initial"),
2838                    "wave_1d should return energy_initial"
2839                );
2840                assert!(
2841                    r.contains_key("energy_final"),
2842                    "wave_1d should return energy_final"
2843                );
2844            }
2845            other => panic!("expected record, got {other:?}"),
2846        }
2847    }
2848
2849    #[test]
2850    fn g_physics_harmonic_oscillator_invoke() {
2851        let mut snap = PoetSnapshot::default();
2852        let src = r#"
2853requires [ capability("capability.invoke"), capability("Physics.harmonic_oscillator") ];
2854effect fn go() {
2855    return capability.invoke("Physics.harmonic_oscillator", {
2856        mass: 1.0,
2857        k_spring: 4.0,
2858        x0: 1.0,
2859        v0: 0.0,
2860        t_start: 0.0,
2861        t_end: 2.0,
2862        t_count: 10
2863    });
2864}
2865"#;
2866        let v = snap.eval_fn(src, "go", vec![]).unwrap();
2867        match v {
2868            Value::Record(r) => {
2869                assert!(
2870                    r.contains_key("positions"),
2871                    "oscillator should return positions"
2872                );
2873            }
2874            other => panic!("expected record, got {other:?}"),
2875        }
2876    }
2877
2878    #[test]
2879    fn g_spectral_emf_to_rgb_invoke() {
2880        let mut snap = PoetSnapshot::default();
2881        let src = r#"
2882requires [ capability("capability.invoke"), capability("Spectral.emf_to_rgb") ];
2883effect fn go() {
2884    return capability.invoke("Spectral.emf_to_rgb", {
2885        alpha: 1.0,
2886        mu: 0.45,
2887        sigma: 0.1
2888    });
2889}
2890"#;
2891        let v = snap.eval_fn(src, "go", vec![]).unwrap();
2892        match v {
2893            Value::Record(r) => {
2894                let css = r.get("css").expect("emf_to_rgb should return css field");
2895                match css {
2896                    Value::String(s) => assert!(
2897                        s.starts_with("rgb("),
2898                        "emf_to_rgb css should start with rgb(: {s}"
2899                    ),
2900                    other => panic!("css should be string, got {other:?}"),
2901                }
2902            }
2903            other => panic!("expected record, got {other:?}"),
2904        }
2905    }
2906
2907    #[test]
2908    fn g_render_svg_path_invoke() {
2909        let mut snap = PoetSnapshot::default();
2910        let src = r##"
2911requires [ capability("capability.invoke"), capability("Render.svg_path") ];
2912effect fn go() {
2913    return capability.invoke("Render.svg_path", {
2914        points: [10.0, 10.0, 90.0, 90.0, 50.0, 30.0],
2915        stroke: "#ff0000",
2916        stroke_width: 2.0,
2917        fill: "none"
2918    });
2919}
2920"##;
2921        let v = snap.eval_fn(src, "go", vec![]).unwrap();
2922        match v {
2923            Value::Record(r) => {
2924                let svg = r.get("svg").expect("svg_path should return svg field");
2925                match svg {
2926                    Value::String(s) => {
2927                        assert!(
2928                            s.contains("<path"),
2929                            "svg_path should return <path element: {s}"
2930                        );
2931                        assert!(
2932                            s.contains("M 10 10 L 90 90"),
2933                            "svg_path should contain d attribute"
2934                        );
2935                    }
2936                    other => panic!("svg should be string, got {other:?}"),
2937                }
2938            }
2939            other => panic!("expected record, got {other:?}"),
2940        }
2941    }
2942
2943    #[test]
2944    fn g_render_css_animation_invoke() {
2945        let mut snap = PoetSnapshot::default();
2946        let src = r#"
2947requires [ capability("capability.invoke"), capability("Render.css_animation") ];
2948effect fn go() {
2949    return capability.invoke("Render.css_animation", {
2950        name: "fade",
2951        property: "opacity",
2952        keyframes: [
2953            { time: 0.0, value: 1.0 },
2954            { time: 2.0, value: 0.0 }
2955        ]
2956    });
2957}
2958"#;
2959        let v = snap.eval_fn(src, "go", vec![]).unwrap();
2960        match v {
2961            Value::Record(r) => {
2962                let css = r.get("css").expect("css_animation should return css field");
2963                match css {
2964                    Value::String(s) => {
2965                        assert!(
2966                            s.contains("@keyframes"),
2967                            "css_animation should return @keyframes: {s}"
2968                        );
2969                        assert!(
2970                            s.contains("fade"),
2971                            "css_animation should contain animation name"
2972                        );
2973                    }
2974                    other => panic!("css should be string, got {other:?}"),
2975                }
2976            }
2977            other => panic!("expected record, got {other:?}"),
2978        }
2979    }
2980
2981    #[test]
2982    fn g_render_svg_circle_invoke() {
2983        let mut snap = PoetSnapshot::default();
2984        let src = r##"
2985requires [ capability("capability.invoke"), capability("Render.svg_circle") ];
2986effect fn go() {
2987    return capability.invoke("Render.svg_circle", {
2988        cx: 50.0,
2989        cy: 50.0,
2990        r: 25.0,
2991        stroke: "blue",
2992        fill: "yellow"
2993    });
2994}
2995"##;
2996        let v = snap.eval_fn(src, "go", vec![]).unwrap();
2997        match v {
2998            Value::Record(r) => {
2999                let svg = r.get("svg").expect("svg_circle should return svg field");
3000                match svg {
3001                    Value::String(s) => {
3002                        assert!(
3003                            s.contains("<circle"),
3004                            "svg_circle should return <circle: {s}"
3005                        );
3006                        assert!(s.contains("cx=\"50\""), "svg_circle should contain cx");
3007                    }
3008                    other => panic!("svg should be string, got {other:?}"),
3009                }
3010            }
3011            other => panic!("expected record, got {other:?}"),
3012        }
3013    }
3014
3015
3016    #[test]
3017    fn g_time_dependent_cell_recomputes_on_re_eval() {
3018        let mut snap = PoetSnapshot::default();
3019        let src = "effect fn now() { return time.unix(); }";
3020        let v1 = snap.eval_fn(src, "now", vec![]).unwrap();
3021        // On native, time.unix returns wall clock — should be non-zero (usually).
3022        // On WASM, returns 0. Just verify it doesn't panic and returns I64.
3023        assert!(matches!(v1, Value::I64(_)), "time.unix should return I64");
3024        assert!(
3025            snap.time_read_during_eval,
3026            "time_read_during_eval should be set"
3027        );
3028    }
3029
3030    #[test]
3031    fn tick_process_all() {
3032        let mut ctrl = TickController::new(TickPolicy::ProcessAll);
3033        assert!(ctrl.request_tick()); // tick 1 in flight
3034        assert!(!ctrl.request_tick()); // tick 2 queued
3035        assert!(!ctrl.request_tick()); // tick 3 queued
3036        assert_eq!(ctrl.pending_ticks, 2);
3037
3038        assert!(ctrl.finish_tick()); // finishes tick 1, starts tick 2
3039        assert_eq!(ctrl.pending_ticks, 1);
3040        assert!(ctrl.finish_tick()); // finishes tick 2, starts tick 3
3041        assert_eq!(ctrl.pending_ticks, 0);
3042        assert!(!ctrl.finish_tick()); // finishes tick 3, idle
3043        assert!(!ctrl.in_flight);
3044        assert_eq!(ctrl.total_processed, 3);
3045    }
3046
3047    #[test]
3048    fn tick_coalesce() {
3049        let mut ctrl = TickController::new(TickPolicy::Coalesce);
3050        assert!(ctrl.request_tick()); // tick 1 in flight
3051        assert!(!ctrl.request_tick()); // tick 2 pending (coalesced)
3052        assert!(!ctrl.request_tick()); // tick 3 collapses into pending
3053        assert!(!ctrl.request_tick()); // tick 4 collapses into pending
3054        assert_eq!(ctrl.pending_ticks, 1);
3055        assert_eq!(ctrl.total_coalesced, 2);
3056
3057        assert!(ctrl.finish_tick()); // finishes tick 1, executes single coalesced tick
3058        assert_eq!(ctrl.pending_ticks, 0);
3059        assert!(!ctrl.finish_tick()); // finishes coalesced tick, idle
3060        assert!(!ctrl.in_flight);
3061        assert_eq!(ctrl.total_processed, 2);
3062    }
3063
3064    #[test]
3065    fn tick_drop() {
3066        let mut ctrl = TickController::new(TickPolicy::Drop);
3067        assert!(ctrl.request_tick()); // tick 1 in flight
3068        assert!(!ctrl.request_tick()); // tick 2 dropped
3069        assert!(!ctrl.request_tick()); // tick 3 dropped
3070        assert_eq!(ctrl.pending_ticks, 0);
3071        assert_eq!(ctrl.total_dropped, 2);
3072
3073        assert!(!ctrl.finish_tick()); // finishes tick 1, idle (nothing pending)
3074        assert!(!ctrl.in_flight);
3075        assert_eq!(ctrl.total_processed, 1);
3076    }
3077
3078    // ── T53/W11: GBNF constrained sampler invoke fixtures ──────────────────
3079
3080    #[test]
3081    fn g_sampler_configure_invoke() {
3082        let mut snap = PoetSnapshot::default();
3083        let src = r#"
3084requires [ capability("capability.invoke"), capability("sampler.configure") ];
3085effect fn go() {
3086    return capability.invoke("sampler.configure", {
3087        temperature: 0.0,
3088        top_k: 0,
3089        top_p: 1.0,
3090        seed: 42
3091    });
3092}
3093"#;
3094        let v = snap.eval_fn(src, "go", vec![]).unwrap();
3095        assert_eq!(v, Value::Bool(true));
3096    }
3097
3098    #[test]
3099    fn g_sampler_sample_greedy_invoke() {
3100        let mut snap = PoetSnapshot::default();
3101        let src = r#"
3102requires [ capability("capability.invoke"), capability("sampler.sample") ];
3103effect fn go() {
3104    return capability.invoke("sampler.sample", [0.1, 0.9, 0.3, 0.7]);
3105}
3106"#;
3107        let v = snap.eval_fn(src, "go", vec![]).unwrap();
3108        // Greedy (temperature 0) → argmax = 1
3109        assert_eq!(v, Value::U64(1));
3110    }
3111
3112    #[test]
3113    fn g_sampler_constrain_disable_invoke() {
3114        let mut snap = PoetSnapshot::default();
3115        let src = r#"
3116requires [ capability("capability.invoke"), capability("sampler.constrain_disable") ];
3117effect fn go() {
3118    return capability.invoke("sampler.constrain_disable", null);
3119}
3120"#;
3121        let v = snap.eval_fn(src, "go", vec![]).unwrap();
3122        assert_eq!(v, Value::Bool(true));
3123    }
3124
3125    #[test]
3126    fn g_sampler_constrain_reset_invoke() {
3127        let mut snap = PoetSnapshot::default();
3128        let src = r#"
3129requires [ capability("capability.invoke"), capability("sampler.constrain_reset") ];
3130effect fn go() {
3131    return capability.invoke("sampler.constrain_reset", null);
3132}
3133"#;
3134        let v = snap.eval_fn(src, "go", vec![]).unwrap();
3135        assert_eq!(v, Value::Bool(true));
3136    }
3137
3138    /// R4: PoetSnapshot reports supports_isolation = true.
3139    #[test]
3140    fn r4_supports_isolation() {
3141        let snap = PoetSnapshot::default();
3142        assert!(snap.supports_isolation());
3143    }
3144
3145    /// R4: A forked snapshot is not attached to the daemon graph.
3146    #[test]
3147    fn r4_fork_is_not_attached() {
3148        let snap = PoetSnapshot::default();
3149        let forked = snap.fork();
3150        assert!(!forked.attached);
3151        assert!(forked.supports_isolation());
3152    }
3153
3154    /// R4: A forked snapshot's staged writes do not reach the parent.
3155    #[test]
3156    fn r4_fork_staged_isolation() {
3157        use vibe::Host;
3158        let parent = PoetSnapshot::default();
3159        let mut forked = parent.fork();
3160        // Stage a triple in the fork
3161        let term = vibe::Value::Triple(
3162            Box::new(vibe::Value::U64(1)),
3163            Box::new(vibe::Value::U64(2)),
3164            Box::new(vibe::Value::U64(3)),
3165        );
3166        let _ = forked.graph_stage(&term, vibe::Span::point(0));
3167        // Parent should have no staged deltas
3168        assert!(parent.staged.is_empty());
3169        // Fork should have staged deltas
3170        assert!(!forked.staged.is_empty());
3171    }
3172
3173    /// R12: PoetSnapshot has an instrument trace ledger.
3174    #[test]
3175    fn r12_trace_ledger_exists() {
3176        let snap = PoetSnapshot::default();
3177        assert_eq!(snap.trace_ledger.entries().len(), 0);
3178    }
3179
3180    /// R12: trace_invoke records an entry.
3181    #[test]
3182    fn r12_trace_invoke_records() {
3183        let mut snap = PoetSnapshot::default();
3184        snap.trace_invoke("sampler.configure", true, Some(42));
3185        assert_eq!(snap.trace_ledger.entries().len(), 1);
3186        let e = &snap.trace_ledger.entries()[0];
3187        assert_eq!(e.act, "invoke:sampler.configure");
3188        assert!(e.success);
3189        assert_eq!(e.cost, Some(42));
3190    }
3191
3192    /// R12: trace ledger survives fork.
3193    #[test]
3194    fn r12_trace_ledger_fork() {
3195        let mut snap = PoetSnapshot::default();
3196        snap.trace_invoke("graph.commit", true, None);
3197        let forked = snap.fork();
3198        // Fork should have the same trace history
3199        assert_eq!(forked.trace_ledger.entries().len(), 1);
3200    }
3201
3202    /// R12: trace ledger filters by act.
3203    #[test]
3204    fn r12_trace_ledger_filter() {
3205        let mut snap = PoetSnapshot::default();
3206        snap.trace_invoke("sampler.configure", true, None);
3207        snap.trace_invoke("graph.commit", false, None);
3208        snap.trace_invoke("sampler.sample", true, None);
3209        assert_eq!(snap.trace_ledger.entries().len(), 3);
3210        let commits = snap.trace_ledger.entries_for_act("invoke:graph.commit");
3211        assert_eq!(commits.len(), 1);
3212        assert!(!commits[0].success);
3213    }
3214
3215    #[test]
3216    #[cfg(not(target_arch = "wasm32"))]
3217    fn test_admit_q42_slice_success_and_fail_closed() {
3218        use crate::q42_volume::write_unified_volume;
3219        use std::collections::HashMap;
3220
3221        let tmp = tempfile::NamedTempFile::new().unwrap();
3222        let mut lex = HashMap::new();
3223        let s_hash = crate::lexicon::generate_60bit_token(b"http://example.org/koala");
3224        let p_hash = crate::lexicon::generate_60bit_token(b"http://example.org/status");
3225        let o_hash = crate::lexicon::generate_60bit_token(b"http://example.org/vulnerable");
3226        lex.insert(s_hash, "http://example.org/koala".to_string());
3227        lex.insert(p_hash, "http://example.org/status".to_string());
3228        lex.insert(o_hash, "http://example.org/vulnerable".to_string());
3229
3230        let mut quin = NQuin {
3231            subject: s_hash,
3232            predicate: p_hash,
3233            object: o_hash,
3234            context: 0,
3235            metadata: 0,
3236            parity: 0,
3237        };
3238        quin.parity = NQuin::calculate_parity(
3239            quin.subject,
3240            quin.predicate,
3241            quin.object,
3242            quin.context,
3243            quin.metadata,
3244        );
3245
3246        write_unified_volume(
3247            tmp.path(),
3248            &lex,
3249            &[(quin.object, quin.object)],
3250            &[vec![quin]],
3251        )
3252        .unwrap();
3253
3254        let bytes = std::fs::read(tmp.path()).unwrap();
3255        let mut snap = PoetSnapshot::default();
3256        let prior_revision = snap.revision;
3257
3258        // 1. Successful admission
3259        let receipt = snap
3260            .admit_q42_slice(&bytes, "eco:pack:sample", "sem/taxonomy.q42", None, true)
3261            .expect("admission should succeed");
3262
3263        assert_eq!(receipt.quin_count, 1);
3264        assert_eq!(receipt.pack_identity, "eco:pack:sample");
3265        assert_eq!(receipt.entry_key, "sem/taxonomy.q42");
3266        assert_eq!(snap.committed.len(), 1);
3267        assert_eq!(snap.committed[0].subject, s_hash);
3268        assert!(snap.revision > prior_revision);
3269
3270        // Term resolution from admitted lexicon
3271        assert_eq!(
3272            snap.resolve_admitted_lexicon_term(s_hash),
3273            Some("http://example.org/koala")
3274        );
3275        assert_eq!(
3276            snap.resolve_admitted_lexicon_term(p_hash),
3277            Some("http://example.org/status")
3278        );
3279
3280        // 2. Digest mismatch fail-closed
3281        let bad_digest = [0xFFu8; 32];
3282        let err = snap.admit_q42_slice(
3283            &bytes,
3284            "eco:pack:bad",
3285            "sem/bad.q42",
3286            Some(&bad_digest),
3287            true,
3288        );
3289        assert!(err.is_err());
3290        assert_eq!(
3291            snap.committed.len(),
3292            1,
3293            "prior state must not be modified on fail-closed"
3294        );
3295
3296        // 3. Corrupted bytes fail-closed
3297        let mut corrupt_bytes = bytes.clone();
3298        let last = corrupt_bytes.len() - 10;
3299        corrupt_bytes[last] ^= 0xFF;
3300        let err2 = snap.admit_q42_slice(
3301            &corrupt_bytes,
3302            "eco:pack:corrupt",
3303            "sem/corrupt.q42",
3304            None,
3305            true,
3306        );
3307        assert!(err2.is_err());
3308        assert_eq!(
3309            snap.committed.len(),
3310            1,
3311            "prior state must not be modified on corrupt fail-closed"
3312        );
3313    }
3314}