Skip to main content

qualia_cooperative_core/
record.rs

1use serde::{Deserialize, Serialize};
2
3/// FNV-1a hash matching the QualiaDB canonical q_hash
4pub const fn q_hash(bytes: &[u8]) -> u64 {
5    let mut hash: u64 = 0xcbf29ce484222325;
6    let mut i = 0;
7    while i < bytes.len() {
8        hash ^= bytes[i] as u64;
9        hash = hash.wrapping_mul(0x100000001b3);
10        i += 1;
11    }
12    hash
13}
14
15/// q_hash of a string.
16pub const fn q_hash_str(s: &str) -> u64 {
17    q_hash(s.as_bytes())
18}
19
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21#[repr(C)]
22pub struct NQuin {
23    pub subject: u64,
24    pub predicate: u64,
25    pub object: u64,
26    pub context: u64,
27    pub metadata: u64,
28    pub parity: u64,
29}
30
31impl NQuin {
32    /// Creates a new instance.
33    pub fn new(s: u64, p: u64, o: u64, c: u64, m: u64) -> Self {
34        let parity = s ^ p ^ o ^ c;
35        Self {
36            subject: s,
37            predicate: p,
38            object: o,
39            context: c,
40            metadata: m,
41            parity,
42        }
43    }
44}
45
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
47pub enum EpistemicStatus {
48    Asserted,
49    Hypothesis,
50    Disputed,
51    Refuted,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55pub enum EvidenceType {
56    SelfReported,
57    DeviceMeasured,
58    ClinicianObserved,
59    Inferred,
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63pub enum SensitivityClass {
64    Public,
65    Restricted,
66    Classified,
67}
68
69impl SensitivityClass {
70    /// Converts to metadata-mask.
71    pub fn to_metadata_mask(&self) -> u64 {
72        match self {
73            SensitivityClass::Public => 0,
74            SensitivityClass::Restricted => 1 << 56,
75            SensitivityClass::Classified => 2 << 56,
76        }
77    }
78}
79
80/// A deterministic Record Envelope
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct RecordEnvelope {
83    pub id: String,
84    pub owner_did: String,
85    pub author_did: String,
86    pub proxy_did: Option<String>,
87    pub epistemic_status: EpistemicStatus,
88    pub evidence_type: EvidenceType,
89    pub sensitivity: SensitivityClass,
90    pub asserted_time_unix: u32,
91    /// High-resolution instant (T71 bridge). Preferred over `asserted_time_unix`
92    /// when present; the u32 field is kept for backward-compatible deserialization.
93    #[serde(skip_serializing_if = "Option::is_none", default)]
94    pub asserted_instant: Option<InstantBridge>,
95    pub valid_time_start_unix: Option<u32>,
96    /// High-resolution valid-time start (T71 bridge). Preferred over
97    /// `valid_time_start_unix` when present.
98    #[serde(skip_serializing_if = "Option::is_none", default)]
99    pub valid_time_start_instant: Option<InstantBridge>,
100    pub valid_time_end_unix: Option<u32>,
101    /// High-resolution valid-time end (T71 bridge). Preferred over
102    /// `valid_time_end_unix` when present.
103    #[serde(skip_serializing_if = "Option::is_none", default)]
104    pub valid_time_end_instant: Option<InstantBridge>,
105    pub predecessor_id: Option<String>,
106    pub blob_hash: Option<String>, // Document/Media reference
107    pub tombstone: bool,
108}
109
110impl RecordEnvelope {
111    /// Zero-allocation compiler: writes the envelope Quins into the provided slice.
112    /// Returns the number of Quins written.
113    pub fn compile_to_quins(&self, out: &mut [NQuin]) -> usize {
114        let mut count = 0;
115        let id_hash = q_hash_str(&self.id);
116        let ctx = q_hash_str(&self.owner_did);
117        let meta = self.sensitivity.to_metadata_mask();
118
119        if count < out.len() {
120            out[count] = NQuin::new(
121                id_hash,
122                q_hash_str("q42:hasAuthor"),
123                q_hash_str(&self.author_did),
124                ctx,
125                meta,
126            );
127            count += 1;
128        }
129
130        if let Some(ref proxy) = self.proxy_did {
131            if count < out.len() {
132                out[count] = NQuin::new(
133                    id_hash,
134                    q_hash_str("q42:hasProxy"),
135                    q_hash_str(proxy),
136                    ctx,
137                    meta,
138                );
139                count += 1;
140            }
141        }
142
143        if let Some(ref pred) = self.predecessor_id {
144            if count < out.len() {
145                out[count] = NQuin::new(
146                    id_hash,
147                    q_hash_str("q42:precedes"),
148                    q_hash_str(pred),
149                    ctx,
150                    meta,
151                );
152                count += 1;
153            }
154        }
155
156        if let Some(ref blob) = self.blob_hash {
157            if count < out.len() {
158                out[count] = NQuin::new(
159                    id_hash,
160                    q_hash_str("q42:hasBlob"),
161                    q_hash_str(blob),
162                    ctx,
163                    meta,
164                );
165                count += 1;
166            }
167        }
168
169        if self.tombstone && count < out.len() {
170            out[count] = NQuin::new(id_hash, q_hash_str("q42:isTombstone"), 1, ctx, meta);
171            count += 1;
172        }
173
174        count
175    }
176
177    /// Resolve the asserted instant, preferring the high-resolution
178    /// `InstantBridge` field when present and falling back to the coarse
179    /// `u32` Unix seconds otherwise (T71 bridge).
180    pub fn asserted_instant(&self) -> InstantBridge {
181        self.asserted_instant
182            .unwrap_or_else(|| InstantBridge::unix(self.asserted_time_unix as i64, 0))
183    }
184
185    /// Resolve the valid-time start instant, preferring the high-resolution
186    /// `InstantBridge` field when present and falling back to the coarse
187    /// `u32` Unix seconds otherwise (T71 bridge).
188    pub fn valid_time_start_instant(&self) -> Option<InstantBridge> {
189        self.valid_time_start_instant.or_else(|| {
190            self.valid_time_start_unix
191                .map(|t| InstantBridge::unix(t as i64, 0))
192        })
193    }
194
195    /// Resolve the valid-time end instant, preferring the high-resolution
196    /// `InstantBridge` field when present and falling back to the coarse
197    /// `u32` Unix seconds otherwise (T71 bridge).
198    pub fn valid_time_end_instant(&self) -> Option<InstantBridge> {
199        self.valid_time_end_instant.or_else(|| {
200            self.valid_time_end_unix
201                .map(|t| InstantBridge::unix(t as i64, 0))
202        })
203    }
204
205    /// Create a RecordEnvelope with an InstantBridge for asserted time (T71 bridge).
206    pub fn with_asserted_instant(
207        id: &str,
208        owner_did: &str,
209        author_did: &str,
210        epistemic_status: EpistemicStatus,
211        evidence_type: EvidenceType,
212        sensitivity: SensitivityClass,
213        asserted: &InstantBridge,
214        blob_hash: Option<String>,
215    ) -> Self {
216        let asserted_unix = asserted.secs as u32;
217        Self {
218            id: id.into(),
219            owner_did: owner_did.into(),
220            author_did: author_did.into(),
221            proxy_did: None,
222            epistemic_status,
223            evidence_type,
224            sensitivity,
225            asserted_time_unix: asserted_unix,
226            asserted_instant: Some(*asserted),
227            valid_time_start_unix: None,
228            valid_time_start_instant: None,
229            valid_time_end_unix: None,
230            valid_time_end_instant: None,
231            predecessor_id: None,
232            blob_hash,
233            tombstone: false,
234        }
235    }
236
237    /// Create a RecordEnvelope with InstantBridges for asserted and valid time (T71 bridge).
238    #[allow(clippy::too_many_arguments)]
239    pub fn with_instants(
240        id: &str,
241        owner_did: &str,
242        author_did: &str,
243        epistemic_status: EpistemicStatus,
244        evidence_type: EvidenceType,
245        sensitivity: SensitivityClass,
246        asserted: &InstantBridge,
247        valid_start: Option<&InstantBridge>,
248        valid_end: Option<&InstantBridge>,
249        blob_hash: Option<String>,
250    ) -> Self {
251        Self {
252            id: id.into(),
253            owner_did: owner_did.into(),
254            author_did: author_did.into(),
255            proxy_did: None,
256            epistemic_status,
257            evidence_type,
258            sensitivity,
259            asserted_time_unix: asserted.secs as u32,
260            asserted_instant: Some(*asserted),
261            valid_time_start_unix: valid_start.map(|i| i.secs as u32),
262            valid_time_start_instant: valid_start.copied(),
263            valid_time_end_unix: valid_end.map(|i| i.secs as u32),
264            valid_time_end_instant: valid_end.copied(),
265            predecessor_id: None,
266            blob_hash,
267            tombstone: false,
268        }
269    }
270
271    /// The duration of the valid time window (T71 bridge).
272    pub fn valid_time_duration(&self) -> Option<DurationBridge> {
273        let start = self.valid_time_start_instant()?;
274        let end = self.valid_time_end_instant()?;
275        Some(end.duration_since(&start))
276    }
277}
278
279/// Lightweight nanosecond-resolution instant bridge (T71).
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
281pub struct InstantBridge {
282    /// Unix seconds
283    pub secs: i64,
284    /// Nanoseconds within the second (0–999,999,999)
285    pub nanos: u32,
286}
287
288impl InstantBridge {
289    /// Create a Unix instant from seconds + nanoseconds.
290    pub fn unix(secs: i64, nanos: u32) -> Self {
291        Self { secs, nanos }
292    }
293
294    /// True if this instant is the zero value (epoch + 0 nanos).
295    pub fn is_zero(&self) -> bool {
296        self.secs == 0 && self.nanos == 0
297    }
298
299    /// Project to Unix seconds (drops sub-second precision).
300    pub fn to_unix_secs(&self) -> i64 {
301        self.secs
302    }
303
304    /// Project to Unix nanoseconds.
305    pub fn to_unix_nanos(&self) -> i64 {
306        self.secs * 1_000_000_000 + self.nanos as i64
307    }
308
309    /// Convert from a coarse u32 Unix timestamp.
310    pub fn from_coarse(unix_secs: u32) -> Self {
311        Self::unix(unix_secs as i64, 0)
312    }
313
314    /// The duration between two instants: `self - earlier`.
315    pub fn duration_since(&self, earlier: &InstantBridge) -> DurationBridge {
316        DurationBridge::from_nanos(self.to_unix_nanos() - earlier.to_unix_nanos())
317    }
318
319    /// Add a duration to this instant.
320    pub fn add_duration(&self, d: &DurationBridge) -> InstantBridge {
321        InstantBridge::from_unix_nanos(self.to_unix_nanos() + d.total_nanos())
322    }
323
324    /// Subtract a duration from this instant.
325    pub fn sub_duration(&self, d: &DurationBridge) -> InstantBridge {
326        InstantBridge::from_unix_nanos(self.to_unix_nanos() - d.total_nanos())
327    }
328
329    fn from_unix_nanos(total_nanos: i64) -> InstantBridge {
330        let secs = total_nanos / 1_000_000_000;
331        let rem = total_nanos % 1_000_000_000;
332        if rem < 0 {
333            InstantBridge::unix(secs - 1, (rem + 1_000_000_000) as u32)
334        } else {
335            InstantBridge::unix(secs, rem as u32)
336        }
337    }
338
339    /// Whether this instant is before another.
340    pub fn is_before(&self, other: &InstantBridge) -> bool {
341        self.to_unix_nanos() < other.to_unix_nanos()
342    }
343
344    /// Whether this instant is after another.
345    pub fn is_after(&self, other: &InstantBridge) -> bool {
346        self.to_unix_nanos() > other.to_unix_nanos()
347    }
348
349    /// The earlier of two instants.
350    pub fn min(self, other: InstantBridge) -> InstantBridge {
351        if self.is_before(&other) {
352            self
353        } else {
354            other
355        }
356    }
357
358    /// The later of two instants.
359    pub fn max(self, other: InstantBridge) -> InstantBridge {
360        if self.is_after(&other) {
361            self
362        } else {
363            other
364        }
365    }
366}
367
368impl Ord for InstantBridge {
369    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
370        self.to_unix_nanos().cmp(&other.to_unix_nanos())
371    }
372}
373
374impl PartialOrd for InstantBridge {
375    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
376        Some(self.cmp(other))
377    }
378}
379
380/// Lightweight duration bridge (T71).
381#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
382pub struct DurationBridge {
383    /// Seconds (may be negative)
384    pub secs: i64,
385    /// Nanoseconds within the second (0–999,999,999)
386    pub nanos: u32,
387}
388
389impl DurationBridge {
390    /// Create a duration from seconds + nanoseconds.
391    pub fn new(secs: i64, nanos: u32) -> Self {
392        Self { secs, nanos }
393    }
394
395    /// Create a duration from total nanoseconds (may be negative).
396    pub fn from_nanos(total_nanos: i64) -> Self {
397        let secs = total_nanos / 1_000_000_000;
398        let rem = total_nanos % 1_000_000_000;
399        if rem < 0 {
400            Self {
401                secs: secs - 1,
402                nanos: (rem + 1_000_000_000) as u32,
403            }
404        } else {
405            Self {
406                secs,
407                nanos: rem as u32,
408            }
409        }
410    }
411
412    /// Create a duration from seconds.
413    pub fn from_secs(secs: i64) -> Self {
414        Self { secs, nanos: 0 }
415    }
416
417    /// Total nanoseconds (may be negative).
418    pub fn total_nanos(&self) -> i64 {
419        self.secs * 1_000_000_000 + self.nanos as i64
420    }
421
422    /// Total milliseconds (may be negative, truncates sub-ms).
423    pub fn total_millis(&self) -> i64 {
424        self.total_nanos() / 1_000_000
425    }
426
427    /// Whether this duration is positive (self > 0).
428    pub fn is_positive(&self) -> bool {
429        self.total_nanos() > 0
430    }
431
432    /// Whether this duration is zero.
433    pub fn is_zero(&self) -> bool {
434        self.total_nanos() == 0
435    }
436
437    /// Absolute value of this duration.
438    pub fn abs(self) -> Self {
439        let n = self.total_nanos();
440        if n < 0 {
441            Self::from_nanos(-n)
442        } else {
443            self
444        }
445    }
446}
447
448#[cfg(feature = "qualia")]
449impl From<InstantBridge> for vibe::Instant {
450    fn from(b: InstantBridge) -> Self {
451        vibe::Instant::unix(b.secs, b.nanos)
452    }
453}
454
455#[cfg(feature = "qualia")]
456impl From<&vibe::Instant> for InstantBridge {
457    fn from(i: &vibe::Instant) -> Self {
458        Self {
459            secs: i.secs,
460            nanos: i.nanos,
461        }
462    }
463}
464
465#[cfg(feature = "qualia")]
466impl From<DurationBridge> for vibe::Duration {
467    fn from(d: DurationBridge) -> Self {
468        vibe::Duration {
469            secs: d.secs,
470            nanos: d.nanos,
471        }
472    }
473}
474
475#[cfg(feature = "qualia")]
476impl From<&vibe::Duration> for DurationBridge {
477    fn from(d: &vibe::Duration) -> Self {
478        Self {
479            secs: d.secs,
480            nanos: d.nanos,
481        }
482    }
483}
484
485#[cfg(test)]
486#[path = "record_tests.rs"]
487mod tests;