Skip to main content

vibe/cosmic/
opcode.rs

1//! NQuin cosmic opcodes and 48-byte metadata layout (OCS §14.2).
2//!
3//! The OCS defines five opcodes in the `0x50–0x55` range, packed into
4//! bits `[0..7]` of the `predicate` field of an `NQuin`:
5//!
6//! | Opcode              | Value | Meaning                                    |
7//! |---------------------|-------|--------------------------------------------|
8//! | `OP_COSMIC_POSE`    | 0x50  | Entity has a spacetime pose in a realm     |
9//! | `OP_REALM_TRANSIT`  | 0x51  | Entity transits between realms/frames      |
10//! | `OP_OBSERVER_FIBER` | 0x53  | Observer fiber attachment to an entity     |
11//! | `OP_MICRO_POSE`     | 0x54  | Microscopic-scale pose (sub-atomic)        |
12//! | `OP_ELEMENT_COLLAPSE` | 0x55 | Granular element collapse onto physical    |
13//!
14//! These are in the `0x50+` range, above the LTL range (`0x40–0x44`)
15//! and do not conflict with any existing modality.
16//!
17//! ## 48-byte NQuin Layout for Cosmic Operations (OCS §14.2)
18//!
19//! ```text
20//! Field      Bits      Content
21//! ─────────────────────────────────────────────────────────────────
22//! subject    [63]      MSB flag (1 = did:q42 entity/observer pointer)
23//!            [0..62]   q_hash(entity_or_observer_did)
24//!
25//! predicate  [63]      0
26//!            [8..62]   q_hash("cosmic:hasSpacetimePose") << 8
27//!            [0..7]    Opcode (0x50–0x55)
28//!
29//! object     [63]      MSB=1 (did:q42 topological pointer to Pose/Anchor)
30//!            [0..62]   q_hash(pose_or_record_iri)
31//!
32//! context    [56..63]  Sensitivity Class (PUBLIC=0, RESTRICTED=1, CLASSIFIED=2)
33//!            [0..55]   q_hash(realm_usri) (56-bit scoped realm hash)
34//!
35//! metadata   [61..62]  PermissiveRoutingLane (01=Commons, 10=Bilateral Isolated)
36//!            [32..60]  Lamport Logical Clock / Epoch Timestamp (29 bits)
37//!            [0..31]   Realm Class & Scale Level Index
38//!                       bits [0..7]:  realm class index
39//!                       bits [8..15]: hierarchy level (L_-2..L_12)
40//!                       bits [16..31]: nesting depth + reserved
41//!
42//! parity     [0..63]   XOR fold: subject ^ predicate ^ object ^ context ^ metadata
43//! ```
44//!
45//! Reference: OCS Specification v2.2.0 §14.2.
46
47use super::cb_usri::{CompactBinaryUsri, HierarchyLevel};
48use super::usri::RealmClass;
49
50/// FNV-1a 64-bit hash (matching q_hash used throughout QualiaDB).
51fn fnv1a_64(s: &str) -> u64 {
52    let mut h: u64 = 0xcbf29ce484222325;
53    for b in s.as_bytes() {
54        h ^= *b as u64;
55        h = h.wrapping_mul(0x100000001b3);
56    }
57    h
58}
59
60// ── Opcode constants (OCS §14.2) ───────────────────────────────────
61
62/// Entity has a spacetime pose in a realm.
63pub const OP_COSMIC_POSE: u8 = 0x50;
64
65/// Entity transits between realms or reference frames.
66pub const OP_REALM_TRANSIT: u8 = 0x51;
67
68/// Observer fiber attachment to an entity.
69pub const OP_OBSERVER_FIBER: u8 = 0x53;
70
71/// Microscopic-scale pose (sub-atomic / quantum realm).
72pub const OP_MICRO_POSE: u8 = 0x54;
73
74/// Granular element collapse onto physical spacetime.
75pub const OP_ELEMENT_COLLAPSE: u8 = 0x55;
76
77/// The canonical predicate IRI for cosmic pose operations.
78pub const COSMIC_POSE_IRI: &str = "cosmic:hasSpacetimePose";
79
80/// Sensitivity class constants (OCS §14.2, matching NQuin context field).
81pub const SENSITIVITY_PUBLIC: u8 = 0;
82pub const SENSITIVITY_RESTRICTED: u8 = 1;
83pub const SENSITIVITY_CLASSIFIED: u8 = 2;
84
85/// PermissiveRoutingLane constants (OCS §14.2, matching NQuin metadata field).
86pub const LANE_PASSTHROUGH: u8 = 0b00;
87pub const LANE_COMMONS: u8 = 0b01;
88pub const LANE_BILATERAL: u8 = 0b10;
89pub const LANE_SPATIAL: u8 = 0b11;
90
91/// A 48-byte cosmic NQuin built from OCS components.
92///
93/// This is a `repr(C)` flat struct matching the `NQuin` ABI in
94/// `qualia-core-db`. It can be transmuted to `NQuin` via `bytemuck`
95/// when crossing the crate boundary.
96#[repr(C)]
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, bytemuck::Pod, bytemuck::Zeroable)]
98pub struct CosmicNQuin {
99    pub subject: u64,
100    pub predicate: u64,
101    pub object: u64,
102    pub context: u64,
103    pub metadata: u64,
104    pub parity: u64,
105}
106
107impl CosmicNQuin {
108    /// Build a cosmic pose NQuin (OCS §14.2, OP_COSMIC_POSE).
109    ///
110    /// Encodes: "entity `subject_did` has spacetime pose `pose_iri`
111    /// in realm `realm_usri` at level `level`".
112    pub fn cosmic_pose(
113        subject_did: &str,
114        pose_iri: &str,
115        realm_usri: &str,
116        level: HierarchyLevel,
117        sensitivity: u8,
118        lamport_clock: u32,
119    ) -> Self {
120        Self::build(
121            OP_COSMIC_POSE,
122            subject_did,
123            pose_iri,
124            realm_usri,
125            level,
126            0, // nesting depth
127            sensitivity,
128            LANE_COMMONS,
129            lamport_clock,
130        )
131    }
132
133    /// Build a realm transit NQuin (OCS §14.2, OP_REALM_TRANSIT).
134    pub fn realm_transit(
135        subject_did: &str,
136        target_realm_usri: &str,
137        source_realm_usri: &str,
138        level: HierarchyLevel,
139        sensitivity: u8,
140        lamport_clock: u32,
141    ) -> Self {
142        Self::build(
143            OP_REALM_TRANSIT,
144            subject_did,
145            target_realm_usri,
146            source_realm_usri,
147            level,
148            0,
149            sensitivity,
150            LANE_BILATERAL,
151            lamport_clock,
152        )
153    }
154
155    /// Build an observer fiber NQuin (OCS §14.2, OP_OBSERVER_FIBER).
156    pub fn observer_fiber(
157        observer_did: &str,
158        perceived_frame_usi: &str,
159        realm_usri: &str,
160        level: HierarchyLevel,
161        sensitivity: u8,
162        lamport_clock: u32,
163    ) -> Self {
164        Self::build(
165            OP_OBSERVER_FIBER,
166            observer_did,
167            perceived_frame_usi,
168            realm_usri,
169            level,
170            0,
171            sensitivity,
172            LANE_BILATERAL,
173            lamport_clock,
174        )
175    }
176
177    /// Build a micro-pose NQuin (OCS §14.2, OP_MICRO_POSE).
178    pub fn micro_pose(
179        subject_did: &str,
180        pose_iri: &str,
181        realm_usri: &str,
182        level: HierarchyLevel,
183        sensitivity: u8,
184        lamport_clock: u32,
185    ) -> Self {
186        Self::build(
187            OP_MICRO_POSE,
188            subject_did,
189            pose_iri,
190            realm_usri,
191            level,
192            0,
193            sensitivity,
194            LANE_COMMONS,
195            lamport_clock,
196        )
197    }
198
199    /// Build an element collapse NQuin (OCS §14.2, OP_ELEMENT_COLLAPSE).
200    pub fn element_collapse(
201        narrative_entity_iri: &str,
202        physical_anchor_iri: &str,
203        realm_usri: &str,
204        level: HierarchyLevel,
205        sensitivity: u8,
206        lamport_clock: u32,
207    ) -> Self {
208        Self::build(
209            OP_ELEMENT_COLLAPSE,
210            narrative_entity_iri,
211            physical_anchor_iri,
212            realm_usri,
213            level,
214            0,
215            sensitivity,
216            LANE_COMMONS,
217            lamport_clock,
218        )
219    }
220
221    /// Core builder for all cosmic NQuin types (OCS §14.2).
222    #[allow(clippy::too_many_arguments)]
223    fn build(
224        opcode: u8,
225        subject_did: &str,
226        object_iri: &str,
227        realm_usri: &str,
228        level: HierarchyLevel,
229        nesting_depth: u8,
230        sensitivity: u8,
231        routing_lane: u8,
232        lamport_clock: u32,
233    ) -> Self {
234        // Subject: MSB=1 (did:q42 pointer), bits [0..62] = q_hash(did)
235        let subject_hash = fnv1a_64(subject_did) & 0x7FFF_FFFF_FFFF_FFFF;
236        let subject = subject_hash | (1u64 << 63); // MSB=1 for did:q42 pointer
237
238        // Predicate: [63]=0, [8..62] = q_hash(cosmic:hasSpacetimePose) << 8, [0..7] = opcode
239        let pose_hash = fnv1a_64(COSMIC_POSE_IRI) & 0x003F_FFFF_FFFF_FFFF; // 54-bit hash
240        let predicate = (pose_hash << 8) | (opcode as u64);
241
242        // Object: MSB=1 (did:q42 topological pointer), bits [0..62] = q_hash(iri)
243        let object_hash = fnv1a_64(object_iri) & 0x7FFF_FFFF_FFFF_FFFF;
244        let object = object_hash | (1u64 << 63); // MSB=1 for did:q42 pointer
245
246        // Context: [56..63] = sensitivity class, [0..55] = q_hash(realm_usri) (56-bit)
247        let realm_hash = fnv1a_64(realm_usri) & 0x00FF_FFFF_FFFF_FFFF; // 56-bit
248        let context = ((sensitivity as u64) << 56) | realm_hash;
249
250        // Metadata: [61..62] = routing lane, [32..60] = Lamport clock (29 bits),
251        //            [0..31] = realm class + scale level + nesting depth
252        let lane_bits = ((routing_lane as u64) & 0b11) << 61;
253        let clock_bits = ((lamport_clock as u64) & 0x1FFF_FFFF) << 32;
254        // Lower 32 bits: [0..7] = realm class (derived from CB-USRI), [8..15] = level, [16..23] = depth
255        let realm_class = derive_realm_class_from_usri(realm_usri);
256        let lower32 =
257            (realm_class as u64) | ((level.as_u8() as u64) << 8) | ((nesting_depth as u64) << 16);
258        let metadata = lane_bits | clock_bits | lower32;
259
260        // Parity: XOR fold
261        let parity = subject ^ predicate ^ object ^ context ^ metadata;
262
263        Self {
264            subject,
265            predicate,
266            object,
267            context,
268            metadata,
269            parity,
270        }
271    }
272
273    /// Extract the opcode from the predicate field.
274    pub fn opcode(&self) -> u8 {
275        (self.predicate & 0xFF) as u8
276    }
277
278    /// Extract the subject DID hash (without MSB).
279    pub fn subject_hash(&self) -> u64 {
280        self.subject & 0x7FFF_FFFF_FFFF_FFFF
281    }
282
283    /// Extract the object IRI hash (without MSB).
284    pub fn object_hash(&self) -> u64 {
285        self.object & 0x7FFF_FFFF_FFFF_FFFF
286    }
287
288    /// Extract the sensitivity class from the context field.
289    pub fn sensitivity(&self) -> u8 {
290        (self.context >> 56) as u8
291    }
292
293    /// Extract the realm hash from the context field (56-bit).
294    pub fn realm_hash(&self) -> u64 {
295        self.context & 0x00FF_FFFF_FFFF_FFFF
296    }
297
298    /// Extract the routing lane from the metadata field.
299    pub fn routing_lane(&self) -> u8 {
300        ((self.metadata >> 61) & 0b11) as u8
301    }
302
303    /// Extract the Lamport logical clock from the metadata field (29 bits).
304    pub fn lamport_clock(&self) -> u32 {
305        ((self.metadata >> 32) & 0x1FFF_FFFF) as u32
306    }
307
308    /// Extract the realm class index from the metadata lower 32 bits.
309    pub fn realm_class_index(&self) -> u8 {
310        (self.metadata & 0xFF) as u8
311    }
312
313    /// Extract the hierarchy level from the metadata.
314    pub fn hierarchy_level(&self) -> Option<HierarchyLevel> {
315        HierarchyLevel::from_u8(((self.metadata >> 8) & 0xFF) as u8)
316    }
317
318    /// Extract the nesting depth from the metadata.
319    pub fn nesting_depth(&self) -> u8 {
320        ((self.metadata >> 16) & 0xFF) as u8
321    }
322
323    /// Verify the parity field (XOR fold check).
324    pub fn verify_parity(&self) -> bool {
325        self.parity == (self.subject ^ self.predicate ^ self.object ^ self.context ^ self.metadata)
326    }
327
328    /// Encode to 48 bytes.
329    pub fn to_bytes(&self) -> [u8; 48] {
330        bytemuck::cast(*self)
331    }
332
333    /// Decode from 48 bytes.
334    pub fn from_bytes(bytes: &[u8; 48]) -> Self {
335        *bytemuck::cast_ref(bytes)
336    }
337
338    /// Size in bytes (always 48 for NQuin ABI).
339    pub const fn size_bytes() -> usize {
340        48
341    }
342}
343
344/// Derive a realm class index from a USRI string.
345fn derive_realm_class_from_usri(usri: &str) -> u8 {
346    // Try to parse the USRI and extract the realm class
347    if let Ok(parsed) = super::usri::Usri::parse(usri) {
348        parsed.realm_class.as_u8()
349    } else {
350        // Default to Physical (0) for unparseable strings
351        RealmClass::Physical.as_u8()
352    }
353}
354
355/// Build a CosmicNQuin from a CompactBinaryUsri (OCS §13.2 + §14.2).
356///
357/// This bridges the 16-byte CB-USRI (zero-heap hot path identifier)
358/// to the 48-byte NQuin (semantic graph record).
359pub fn from_cb_usri(
360    cb: &CompactBinaryUsri,
361    subject_did: &str,
362    object_iri: &str,
363    opcode: u8,
364    lamport_clock: u32,
365) -> CosmicNQuin {
366    let level = HierarchyLevel::from_u8(cb.level()).unwrap_or(HierarchyLevel::L5);
367    let nesting_depth = cb.nesting_depth();
368    let realm_class_idx = cb.realm_class();
369
370    // Subject: MSB=1, hash of DID
371    let subject = (fnv1a_64(subject_did) & 0x7FFF_FFFF_FFFF_FFFF) | (1u64 << 63);
372
373    // Predicate: cosmic pose hash + opcode
374    let pose_hash = fnv1a_64(COSMIC_POSE_IRI) & 0x003F_FFFF_FFFF_FFFF;
375    let predicate = (pose_hash << 8) | (opcode as u64);
376
377    // Object: MSB=1, hash of IRI
378    let object = (fnv1a_64(object_iri) & 0x7FFF_FFFF_FFFF_FFFF) | (1u64 << 63);
379
380    // Context: sensitivity=PUBLIC, realm hash from CB-USRI path hash (56-bit)
381    let context = (SENSITIVITY_PUBLIC as u64) << 56 | (cb.path_hash() & 0x00FF_FFFF_FFFF_FFFF);
382
383    // Metadata: lane=Commons, clock, lower32 = realm_class | level | depth
384    let metadata = ((LANE_COMMONS as u64) << 61)
385        | ((lamport_clock as u64 & 0x1FFF_FFFF) << 32)
386        | (realm_class_idx as u64)
387        | ((level.as_u8() as u64) << 8)
388        | ((nesting_depth as u64) << 16);
389
390    let parity = subject ^ predicate ^ object ^ context ^ metadata;
391
392    CosmicNQuin {
393        subject,
394        predicate,
395        object,
396        context,
397        metadata,
398        parity,
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405
406    #[test]
407    fn opcodes_in_correct_range() {
408        // OCS §14.2: opcodes 0x50-0x55
409        assert_eq!(OP_COSMIC_POSE, 0x50);
410        assert_eq!(OP_REALM_TRANSIT, 0x51);
411        assert_eq!(OP_OBSERVER_FIBER, 0x53);
412        assert_eq!(OP_MICRO_POSE, 0x54);
413        assert_eq!(OP_ELEMENT_COLLAPSE, 0x55);
414    }
415
416    #[test]
417    fn opcodes_above_ltl_range() {
418        // AGENTS.md: LTL owns 0x40-0x44, cosmic starts at 0x50
419        assert!(OP_COSMIC_POSE > 0x44);
420        assert!(OP_ELEMENT_COLLAPSE > 0x44);
421    }
422
423    #[test]
424    fn cosmic_pose_builds_correctly() {
425        let q = CosmicNQuin::cosmic_pose(
426            "did:q42:person:alice",
427            "urn:omni:v1:physical:observable:standard:earth:wgs84#pose",
428            "urn:omni:v1:physical:observable:standard:earth:wgs84",
429            HierarchyLevel::L5,
430            SENSITIVITY_PUBLIC,
431            12345,
432        );
433        assert_eq!(q.opcode(), OP_COSMIC_POSE);
434        assert!(q.subject & (1u64 << 63) != 0, "subject MSB should be set");
435        assert!(q.object & (1u64 << 63) != 0, "object MSB should be set");
436        assert_eq!(q.sensitivity(), SENSITIVITY_PUBLIC);
437        assert_eq!(q.lamport_clock(), 12345);
438        assert_eq!(q.hierarchy_level(), Some(HierarchyLevel::L5));
439        assert!(q.verify_parity());
440    }
441
442    #[test]
443    fn realm_transit_uses_bilateral_lane() {
444        let q = CosmicNQuin::realm_transit(
445            "did:q42:person:alice",
446            "urn:omni:v1:fiction:star-trek:prime",
447            "urn:omni:v1:physical:observable:standard:earth",
448            HierarchyLevel::L5,
449            SENSITIVITY_RESTRICTED,
450            100,
451        );
452        assert_eq!(q.opcode(), OP_REALM_TRANSIT);
453        assert_eq!(q.routing_lane(), LANE_BILATERAL);
454        assert_eq!(q.sensitivity(), SENSITIVITY_RESTRICTED);
455    }
456
457    #[test]
458    fn observer_fiber_builds() {
459        let q = CosmicNQuin::observer_fiber(
460            "did:q42:person:bob",
461            "urn:omni:v1:phenomenology:bob:perceived",
462            "urn:omni:v1:phenomenology:bob",
463            HierarchyLevel::L4,
464            SENSITIVITY_CLASSIFIED,
465            999,
466        );
467        assert_eq!(q.opcode(), OP_OBSERVER_FIBER);
468        assert_eq!(q.sensitivity(), SENSITIVITY_CLASSIFIED);
469        assert_eq!(q.routing_lane(), LANE_BILATERAL);
470    }
471
472    #[test]
473    fn micro_pose_uses_correct_level() {
474        let q = CosmicNQuin::micro_pose(
475            "did:q42:atom:hydrogen-1",
476            "urn:omni:v1:physical:observable:standard:hydrogen",
477            "urn:omni:v1:physical:observable:standard:hydrogen",
478            HierarchyLevel::L2,
479            SENSITIVITY_PUBLIC,
480            1,
481        );
482        assert_eq!(q.opcode(), OP_MICRO_POSE);
483        assert_eq!(q.hierarchy_level(), Some(HierarchyLevel::L2));
484    }
485
486    #[test]
487    fn element_collapse_builds() {
488        let q = CosmicNQuin::element_collapse(
489            "urn:omni:v1:narrative:homer:iliad:troy",
490            "urn:omni:v1:physical:observable:standard:earth:hisarlik",
491            "urn:omni:v1:narrative:homer:iliad",
492            HierarchyLevel::L5,
493            SENSITIVITY_PUBLIC,
494            42,
495        );
496        assert_eq!(q.opcode(), OP_ELEMENT_COLLAPSE);
497        assert_eq!(q.lamport_clock(), 42);
498    }
499
500    #[test]
501    fn parity_is_verified() {
502        let q = CosmicNQuin::cosmic_pose(
503            "did:q42:person:test",
504            "pose",
505            "urn:omni:v1:physical:observable:standard:earth",
506            HierarchyLevel::L5,
507            SENSITIVITY_PUBLIC,
508            1,
509        );
510        assert!(q.verify_parity());
511    }
512
513    #[test]
514    fn parity_detects_corruption() {
515        let mut q = CosmicNQuin::cosmic_pose(
516            "did:q42:person:test",
517            "pose",
518            "urn:omni:v1:physical:observable:standard:earth",
519            HierarchyLevel::L5,
520            SENSITIVITY_PUBLIC,
521            1,
522        );
523        assert_eq!(q.parity, q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata);
524        q.metadata ^= 1; // Corrupt one bit in metadata (5-field parity check)
525        assert!(!q.verify_parity());
526        q.metadata ^= 1;
527        q.subject ^= 1; // Corrupt one bit
528        assert!(!q.verify_parity());
529    }
530
531    #[test]
532    fn bytes_round_trip() {
533        let q = CosmicNQuin::cosmic_pose(
534            "did:q42:person:alice",
535            "pose",
536            "urn:omni:v1:physical:observable:standard:earth",
537            HierarchyLevel::L5,
538            SENSITIVITY_PUBLIC,
539            100,
540        );
541        let bytes = q.to_bytes();
542        assert_eq!(bytes.len(), 48);
543        let recovered = CosmicNQuin::from_bytes(&bytes);
544        assert_eq!(q, recovered);
545    }
546
547    #[test]
548    fn size_is_48_bytes() {
549        assert_eq!(CosmicNQuin::size_bytes(), 48);
550        assert_eq!(std::mem::size_of::<CosmicNQuin>(), 48);
551    }
552
553    #[test]
554    fn from_cb_usri_builds() {
555        let cb = CompactBinaryUsri::from_usri(
556            "urn:omni:v1:physical:observable:standard:earth:wgs84",
557            RealmClass::Physical,
558            HierarchyLevel::L5,
559            0,
560            "geo(lat=37.8,lon=-122.4)",
561        );
562        let q = from_cb_usri(&cb, "did:q42:person:alice", "pose-iri", OP_COSMIC_POSE, 500);
563        assert_eq!(q.opcode(), OP_COSMIC_POSE);
564        assert_eq!(q.hierarchy_level(), Some(HierarchyLevel::L5));
565        assert_eq!(q.realm_class_index(), RealmClass::Physical.as_u8());
566        assert!(q.verify_parity());
567    }
568
569    #[test]
570    fn realm_class_derived_from_usri() {
571        let q = CosmicNQuin::cosmic_pose(
572            "did:q42:person:test",
573            "pose",
574            "urn:omni:v1:fiction:star-trek:prime:earth",
575            HierarchyLevel::L5,
576            SENSITIVITY_PUBLIC,
577            1,
578        );
579        assert_eq!(q.realm_class_index(), RealmClass::Fiction.as_u8());
580    }
581
582    #[test]
583    fn nesting_depth_extracted() {
584        let q = CosmicNQuin::cosmic_pose(
585            "did:q42:person:test",
586            "pose",
587            "urn:omni:v1:physical:observable:standard:earth",
588            HierarchyLevel::L5,
589            SENSITIVITY_PUBLIC,
590            1,
591        );
592        // Default nesting depth is 0
593        assert_eq!(q.nesting_depth(), 0);
594    }
595
596    #[test]
597    fn lamport_clock_wraps_29_bits() {
598        let q = CosmicNQuin::cosmic_pose(
599            "did:q42:person:test",
600            "pose",
601            "urn:omni:v1:physical:observable:standard:earth",
602            HierarchyLevel::L5,
603            SENSITIVITY_PUBLIC,
604            0x1FFF_FFFF, // max 29-bit value
605        );
606        assert_eq!(q.lamport_clock(), 0x1FFF_FFFF);
607    }
608}