Skip to main content

vibe/cosmic/
observer.rs

1//! Observer fiber, affective status, correlated atlas uncertainty, presheaf gluing,
2//! and epistemic divergence (OCS §8, Packet OCS-13 & §6.2.5.1).
3//!
4//! Reference: OCS Specification v2.2.0 §8 & Playbook v4 §6.2.5.1.
5
6use crate::value::Value;
7use std::collections::BTreeMap;
8
9/// Affective status vector (OCS §8.2).
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct AffectiveStatus {
12    /// [-1.0: Severe Threat/Panic, +1.0: Deep Safety/Trust]
13    pub safety_threat_index: f32,
14    /// [-1.0: Extreme Grief/Depression, +1.0: Joy/Euphoria]
15    pub emotional_valence: f32,
16    /// [0.0: Comatose/Sedated, 1.0: Hyper-vigilant]
17    pub arousal_level: f32,
18    /// [0.0: Fully Grounded, 1.0: Complete Depersonalization]
19    pub dissociation_index: f32,
20    /// [0.0: Baseline, 1.0: Active Flashback/Trigger]
21    pub trauma_reactivity: f32,
22}
23
24impl Default for AffectiveStatus {
25    fn default() -> Self {
26        Self {
27            safety_threat_index: 0.0,
28            emotional_valence: 0.0,
29            arousal_level: 0.5,
30            dissociation_index: 0.0,
31            trauma_reactivity: 0.0,
32        }
33    }
34}
35
36impl AffectiveStatus {
37    /// Clamp all values to their valid ranges.
38    pub fn clamped(&self) -> Self {
39        Self {
40            safety_threat_index: self.safety_threat_index.clamp(-1.0, 1.0),
41            emotional_valence: self.emotional_valence.clamp(-1.0, 1.0),
42            arousal_level: self.arousal_level.clamp(0.0, 1.0),
43            dissociation_index: self.dissociation_index.clamp(0.0, 1.0),
44            trauma_reactivity: self.trauma_reactivity.clamp(0.0, 1.0),
45        }
46    }
47
48    /// Whether this observer is in a hyper-vigilant state (OCS-T11, Packet OCS-13).
49    ///
50    /// Note: `safety_threat_index` is in `[-1.0: Severe Threat/Panic, +1.0: Deep Safety/Trust]`,
51    /// so severe threat is `< -0.8` (not `> 0.8`), or high arousal `> 0.9` (or `>= 0.9` with active
52    /// trauma reactivity).
53    pub fn is_hyper_vigilant(&self) -> bool {
54        self.safety_threat_index < -0.8
55            || self.arousal_level > 0.9
56            || (self.arousal_level >= 0.9 && self.trauma_reactivity > 0.0)
57    }
58
59    /// Converts to value.
60    pub fn to_value(&self) -> Value {
61        let mut rec = BTreeMap::new();
62        rec.insert(
63            "safety_threat_index".into(),
64            Value::F64(self.safety_threat_index as f64),
65        );
66        rec.insert(
67            "emotional_valence".into(),
68            Value::F64(self.emotional_valence as f64),
69        );
70        rec.insert(
71            "arousal_level".into(),
72            Value::F64(self.arousal_level as f64),
73        );
74        rec.insert(
75            "dissociation_index".into(),
76            Value::F64(self.dissociation_index as f64),
77        );
78        rec.insert(
79            "trauma_reactivity".into(),
80            Value::F64(self.trauma_reactivity as f64),
81        );
82        Value::Record(rec)
83    }
84}
85
86/// A doxastic belief with evidential weight (OCS §8.2).
87#[derive(Debug, Clone, PartialEq)]
88pub struct DoxasticBelief {
89    pub proposition_iri: String,
90    /// Evidential support weight μ ∈ [0, 1]
91    pub mu: f32,
92    /// Evidential refutation weight λ ∈ [0, 1]
93    pub lambda: f32,
94}
95
96impl DoxasticBelief {
97    /// Converts to `Value::Record`.
98    pub fn to_value(&self) -> Value {
99        let mut rec = BTreeMap::new();
100        rec.insert(
101            "proposition_iri".into(),
102            Value::String(self.proposition_iri.clone()),
103        );
104        rec.insert("mu".into(), Value::F64(self.mu as f64));
105        rec.insert("lambda".into(), Value::F64(self.lambda as f64));
106        Value::Record(rec)
107    }
108}
109
110/// Cognitive lens — perceptual/sensory transfer function (OCS §8.2).
111#[derive(Debug, Clone, PartialEq)]
112pub struct CognitiveLens {
113    pub lens_id: String,
114    /// Sensory acuity multiplier (1.0 = normal)
115    pub sensory_acuity: f32,
116    /// Whether this lens applies indoctrinated worldview filtering
117    pub worldview_filter: bool,
118}
119
120impl Default for CognitiveLens {
121    fn default() -> Self {
122        Self {
123            lens_id: "default".into(),
124            sensory_acuity: 1.0,
125            worldview_filter: false,
126        }
127    }
128}
129
130/// Observer fiber — the inward inversion modeling how an observer
131/// perceives, filters, and constructs their experienced reality (OCS §8.2, §6.2.5.1).
132///
133/// Includes split correlated uncertainty (`shared_anchor_var` vs `local_chart_var`) so
134/// relative displacements between two observers sharing a coarse anchor cancel the
135/// coarse anchor variance rather than inflating local relative error.
136#[derive(Debug, Clone)]
137pub struct ObserverFiber {
138    pub observer_did: String,
139    pub semantic_cohort: Option<String>,
140    pub affective_state: AffectiveStatus,
141    pub epistemic_beliefs: Vec<DoxasticBelief>,
142    pub cognitive_lens: CognitiveLens,
143    pub perceived_frame_usi: String,
144    /// Optional shared coarse anchor identifier (e.g. sector / spacecraft / habitat USRI hash).
145    pub shared_anchor_id: Option<u64>,
146    /// Positional variance ($\text{m}^2$) of the coarse anchor relative to a cosmic root frame.
147    pub shared_anchor_var: f64,
148    /// Positional variance ($\text{m}^2$) within the local chart relative to `shared_anchor_id`.
149    pub local_chart_var: f64,
150}
151
152impl ObserverFiber {
153    /// Creates a new `ObserverFiber`.
154    pub fn new(observer_did: &str, perceived_frame: &str) -> Self {
155        Self {
156            observer_did: observer_did.into(),
157            semantic_cohort: None,
158            affective_state: AffectiveStatus::default(),
159            epistemic_beliefs: Vec::new(),
160            cognitive_lens: CognitiveLens::default(),
161            perceived_frame_usi: perceived_frame.into(),
162            shared_anchor_id: None,
163            shared_anchor_var: 0.0,
164            local_chart_var: 0.0,
165        }
166    }
167
168    /// Configure correlated anchor variance vs local chart variance (§6.2.5.1).
169    pub fn with_correlated_uncertainty(
170        mut self,
171        shared_anchor_id: u64,
172        shared_anchor_var: f64,
173        local_chart_var: f64,
174    ) -> Self {
175        self.shared_anchor_id = Some(shared_anchor_id);
176        self.shared_anchor_var = shared_anchor_var.max(0.0);
177        self.local_chart_var = local_chart_var.max(0.0);
178        self
179    }
180
181    /// Whether this observer fiber is in a hyper-vigilant state (Packet OCS-13).
182    pub fn is_hyper_vigilant(&self) -> bool {
183        self.affective_state.safety_threat_index < -0.8
184            || self.affective_state.arousal_level > 0.9
185            || self.affective_state.is_hyper_vigilant()
186    }
187
188    /// Total absolute positional variance ($\text{m}^2$) relative to the cosmic root frame.
189    pub fn total_positional_variance(&self) -> f64 {
190        self.shared_anchor_var.max(0.0) + self.local_chart_var.max(0.0)
191    }
192
193    /// Relative displacement variance ($\text{m}^2$) between `self` and `other` (§6.2.5.1).
194    ///
195    /// When both observers share the same `shared_anchor_id`, the common-mode coarse anchor
196    /// variance cancels in $\Delta\mathbf{x} = \mathbf{x}_A - \mathbf{x}_B$, leaving only
197    /// `self.local_chart_var + other.local_chart_var`.
198    pub fn relative_displacement_variance(&self, other: &Self) -> f64 {
199        let local_sum = self.local_chart_var.max(0.0) + other.local_chart_var.max(0.0);
200        match (self.shared_anchor_id, other.shared_anchor_id) {
201            (Some(a), Some(b)) if a == b => local_sum,
202            _ => local_sum + self.shared_anchor_var.max(0.0) + other.shared_anchor_var.max(0.0),
203        }
204    }
205
206    /// Standard deviation ($\text{m}$) of the relative displacement between `self` and `other`.
207    pub fn relative_displacement_std(&self, other: &Self) -> f64 {
208        self.relative_displacement_variance(other).sqrt()
209    }
210
211    /// Check presheaf overlap compatibility on $U_i \cap U_j$ before gluing/merging two
212    /// observer fibers (§6.2.5.1).
213    ///
214    /// Two fibers are compatible on their overlap if:
215    /// 1. For every shared `proposition_iri`, $|\mu_A - \mu_B| \le \text{max\_belief\_divergence}$
216    ///    and $|\lambda_A - \lambda_B| \le \text{max\_belief\_divergence}$.
217    /// 2. If both fibers reference the same `shared_anchor_id`, their `shared_anchor_var`
218    ///    estimates agree within relative tolerance.
219    pub fn check_presheaf_overlap(
220        &self,
221        other: &Self,
222        max_belief_divergence: f32,
223    ) -> Result<(), String> {
224        if let (Some(a), Some(b)) = (self.shared_anchor_id, other.shared_anchor_id) {
225            if a == b {
226                let diff = (self.shared_anchor_var - other.shared_anchor_var).abs();
227                let scale = self
228                    .shared_anchor_var
229                    .abs()
230                    .max(other.shared_anchor_var.abs())
231                    .max(1.0);
232                if diff / scale > 1e-3 {
233                    return Err(format!(
234                        "Presheaf overlap mismatch on shared_anchor_id {}: anchor variance {} vs {}",
235                        a, self.shared_anchor_var, other.shared_anchor_var
236                    ));
237                }
238            }
239        }
240
241        for b1 in &self.epistemic_beliefs {
242            if let Some(b2) = other
243                .epistemic_beliefs
244                .iter()
245                .find(|cand| cand.proposition_iri == b1.proposition_iri)
246            {
247                let d_mu = (b1.mu - b2.mu).abs();
248                let d_lambda = (b1.lambda - b2.lambda).abs();
249                if d_mu > max_belief_divergence || d_lambda > max_belief_divergence {
250                    return Err(format!(
251                        "Presheaf section conflict on proposition '{}': (mu={}, lambda={}) vs (mu={}, lambda={})",
252                        b1.proposition_iri, b1.mu, b1.lambda, b2.mu, b2.lambda
253                    ));
254                }
255            }
256        }
257        Ok(())
258    }
259
260    /// Glue two compatible observer fibers over their overlap $U_i \cap U_j$ (§6.2.5.1).
261    ///
262    /// Fails closed if `check_presheaf_overlap` detects a contradiction on shared propositions
263    /// or anchor metadata.
264    pub fn merge_presheaf_compatible(
265        &self,
266        other: &Self,
267        max_belief_divergence: f32,
268    ) -> Result<ObserverFiber, String> {
269        self.check_presheaf_overlap(other, max_belief_divergence)?;
270
271        let mut merged_beliefs = self.epistemic_beliefs.clone();
272        for b2 in &other.epistemic_beliefs {
273            if let Some(existing) = merged_beliefs
274                .iter_mut()
275                .find(|cand| cand.proposition_iri == b2.proposition_iri)
276            {
277                existing.mu = 0.5 * (existing.mu + b2.mu);
278                existing.lambda = 0.5 * (existing.lambda + b2.lambda);
279            } else {
280                merged_beliefs.push(b2.clone());
281            }
282        }
283
284        let merged_local_var = if self.local_chart_var > 0.0 && other.local_chart_var > 0.0 {
285            1.0 / (1.0 / self.local_chart_var + 1.0 / other.local_chart_var)
286        } else {
287            self.local_chart_var.max(other.local_chart_var)
288        };
289
290        Ok(ObserverFiber {
291            observer_did: self.observer_did.clone(),
292            semantic_cohort: self
293                .semantic_cohort
294                .clone()
295                .or_else(|| other.semantic_cohort.clone()),
296            affective_state: self.affective_state,
297            epistemic_beliefs: merged_beliefs,
298            cognitive_lens: self.cognitive_lens.clone(),
299            perceived_frame_usi: self.perceived_frame_usi.clone(),
300            shared_anchor_id: self.shared_anchor_id.or(other.shared_anchor_id),
301            shared_anchor_var: self.shared_anchor_var.max(other.shared_anchor_var),
302            local_chart_var: merged_local_var,
303        })
304    }
305
306    /// Clinical epistemic divergence tensor Δ_epistemic (OCS §8.3).
307    ///
308    /// Simple scalar version: the L2 norm of the difference between
309    /// the perceived frame and the empirical frame, weighted by
310    /// dissociation and trauma reactivity.
311    pub fn epistemic_divergence(
312        &self,
313        empirical_frame_coords: &[f64],
314        perceived_coords: &[f64],
315    ) -> f64 {
316        if empirical_frame_coords.len() != perceived_coords.len() {
317            return f64::INFINITY;
318        }
319        let sum_sq: f64 = empirical_frame_coords
320            .iter()
321            .zip(perceived_coords.iter())
322            .map(|(e, p)| {
323                let d = e - p;
324                d * d
325            })
326            .sum();
327        let base = sum_sq.sqrt();
328        // Weight by dissociation + trauma reactivity
329        let weight = 1.0
330            + self.affective_state.dissociation_index as f64
331            + self.affective_state.trauma_reactivity as f64;
332        base * weight
333    }
334
335    /// Whether this observer needs grounding intervention (OCS-T11).
336    pub fn needs_grounding(&self) -> bool {
337        self.is_hyper_vigilant() || self.affective_state.dissociation_index >= 0.7
338    }
339
340    /// Project the observer's phenomenological and doxastic state onto an explicit
341    /// **Claim/Opinion** record (`plane = "ClaimOpinion"`) without mutating physical
342    /// coordinates or `NaturalAgent` identity (Packet OCS-13).
343    pub fn to_epistemic_claim_record(&self) -> Value {
344        let mut rec = BTreeMap::new();
345        rec.insert("plane".into(), Value::String("ClaimOpinion".into()));
346        rec.insert(
347            "observer_handle".into(),
348            Value::String(self.observer_did.clone()),
349        );
350        rec.insert(
351            "perceived_frame_usi".into(),
352            Value::String(self.perceived_frame_usi.clone()),
353        );
354        rec.insert(
355            "is_hyper_vigilant".into(),
356            Value::Bool(self.is_hyper_vigilant()),
357        );
358        rec.insert(
359            "needs_grounding".into(),
360            Value::Bool(self.needs_grounding()),
361        );
362        rec.insert("affective_state".into(), self.affective_state.to_value());
363        rec.insert(
364            "beliefs".into(),
365            Value::List(
366                self.epistemic_beliefs
367                    .iter()
368                    .map(DoxasticBelief::to_value)
369                    .collect(),
370            ),
371        );
372        rec.insert(
373            "shared_anchor_var".into(),
374            Value::F64(self.shared_anchor_var),
375        );
376        rec.insert("local_chart_var".into(), Value::F64(self.local_chart_var));
377        Value::Record(rec)
378    }
379
380    /// Converts to value.
381    pub fn to_value(&self) -> Value {
382        let mut rec = BTreeMap::new();
383        rec.insert(
384            "observer_did".into(),
385            Value::String(self.observer_did.clone()),
386        );
387        if let Some(cohort) = &self.semantic_cohort {
388            rec.insert("semantic_cohort".into(), Value::String(cohort.clone()));
389        }
390        rec.insert("affective_state".into(), self.affective_state.to_value());
391        rec.insert(
392            "perceived_frame_usi".into(),
393            Value::String(self.perceived_frame_usi.clone()),
394        );
395        Value::Record(rec)
396    }
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn default_affective_is_neutral() {
405        let a = AffectiveStatus::default();
406        assert_eq!(a.safety_threat_index, 0.0);
407        assert_eq!(a.emotional_valence, 0.0);
408        assert_eq!(a.arousal_level, 0.5);
409    }
410
411    #[test]
412    fn hyper_vigilant_detection() {
413        // Severe threat (-0.9 < -0.8) triggers hyper-vigilance
414        let threat = AffectiveStatus {
415            safety_threat_index: -0.9,
416            ..Default::default()
417        };
418        assert!(threat.is_hyper_vigilant());
419
420        // High arousal (0.95 > 0.9) triggers hyper-vigilance
421        let high_arousal = AffectiveStatus {
422            arousal_level: 0.95,
423            ..Default::default()
424        };
425        assert!(high_arousal.is_hyper_vigilant());
426
427        // Deep safety (+0.9) with calm arousal must NOT be flagged as hyper-vigilant
428        let safe = AffectiveStatus {
429            safety_threat_index: 0.9,
430            ..Default::default()
431        };
432        assert!(!safe.is_hyper_vigilant());
433    }
434
435    #[test]
436    fn not_hyper_vigilant() {
437        let a = AffectiveStatus::default();
438        assert!(!a.is_hyper_vigilant());
439    }
440
441    #[test]
442    fn affective_clamp() {
443        let a = AffectiveStatus {
444            safety_threat_index: 5.0,
445            emotional_valence: -3.0,
446            arousal_level: 2.0,
447            dissociation_index: -1.0,
448            trauma_reactivity: 10.0,
449        };
450        let c = a.clamped();
451        assert_eq!(c.safety_threat_index, 1.0);
452        assert_eq!(c.emotional_valence, -1.0);
453        assert_eq!(c.arousal_level, 1.0);
454        assert_eq!(c.dissociation_index, 0.0);
455        assert_eq!(c.trauma_reactivity, 1.0);
456    }
457
458    #[test]
459    fn epistemic_divergence_zero() {
460        let obs = ObserverFiber::new("did:q42:person:test", "urn:omni:v1:phenomenology:test");
461        let coords = [1.0, 2.0, 3.0];
462        let d = obs.epistemic_divergence(&coords, &coords);
463        assert!(d.abs() < 1e-10);
464    }
465
466    #[test]
467    fn epistemic_divergence_nonzero() {
468        let obs = ObserverFiber::new("did:q42:person:test", "urn:omni:v1:phenomenology:test");
469        let empirical = [0.0, 0.0, 0.0];
470        let perceived = [3.0, 4.0, 0.0]; // distance = 5
471        let d = obs.epistemic_divergence(&empirical, &perceived);
472        assert!((d - 5.0).abs() < 1e-10, "got {} expected 5.0", d);
473    }
474
475    #[test]
476    fn epistemic_divergence_weighted_by_dissociation() {
477        let mut obs = ObserverFiber::new("did:q42:person:test", "urn:omni:v1:phenomenology:test");
478        obs.affective_state.dissociation_index = 1.0;
479        let empirical = [0.0, 0.0, 0.0];
480        let perceived = [3.0, 4.0, 0.0]; // distance = 5
481        let d = obs.epistemic_divergence(&empirical, &perceived);
482        // weight = 1 + 1.0 + 0.0 = 2.0 → 5 * 2 = 10
483        assert!((d - 10.0).abs() < 1e-10, "got {} expected 10.0", d);
484    }
485
486    #[test]
487    fn needs_grounding_hyper_vigilant() {
488        let mut obs = ObserverFiber::new("did:q42:person:test", "frame");
489        obs.affective_state.safety_threat_index = -0.9;
490        assert!(obs.is_hyper_vigilant());
491        assert!(obs.needs_grounding());
492    }
493
494    #[test]
495    fn needs_grounding_dissociation() {
496        let mut obs = ObserverFiber::new("did:q42:person:test", "frame");
497        obs.affective_state.dissociation_index = 0.8;
498        assert!(obs.needs_grounding());
499    }
500
501    #[test]
502    fn correlated_anchor_variance_cancels_for_shared_anchor() {
503        // Two observers inside the same deep-space habitat (anchor 42):
504        // Coarse habitat position relative to BCRS has huge variance (1e12 m^2 -> 1000 km std),
505        // while each observer's local chart variance inside the room is 1e-6 m^2 (1 mm std).
506        let obs_a = ObserverFiber::new("did:q42:obs:a", "urn:omni:v1:phenomenology:a")
507            .with_correlated_uncertainty(42, 1.0e12, 1.0e-6);
508        let obs_b = ObserverFiber::new("did:q42:obs:b", "urn:omni:v1:phenomenology:b")
509            .with_correlated_uncertainty(42, 1.0e12, 1.0e-6);
510        let obs_unshared = ObserverFiber::new("did:q42:obs:c", "urn:omni:v1:phenomenology:c")
511            .with_correlated_uncertainty(99, 1.0e12, 1.0e-6);
512
513        let rel_var_shared = obs_a.relative_displacement_variance(&obs_b);
514        assert!(
515            (rel_var_shared - 2.0e-6).abs() < 1e-12,
516            "shared anchor variance must cancel: got {}",
517            rel_var_shared
518        );
519        assert!((obs_a.relative_displacement_std(&obs_b) - (2.0e-6_f64).sqrt()).abs() < 1e-9);
520
521        let rel_var_unshared = obs_a.relative_displacement_variance(&obs_unshared);
522        assert!(rel_var_unshared > 1.9e12);
523    }
524
525    #[test]
526    fn presheaf_overlap_compatibility_and_epistemic_claim_projection() {
527        let mut obs_a = ObserverFiber::new("did:q42:obs:a", "urn:omni:v1:phenomenology:a")
528            .with_correlated_uncertainty(7, 100.0, 0.04);
529        obs_a.epistemic_beliefs.push(DoxasticBelief {
530            proposition_iri: "urn:qualia:prop:door-locked".into(),
531            mu: 0.85,
532            lambda: 0.05,
533        });
534
535        let mut obs_b = ObserverFiber::new("did:q42:obs:b", "urn:omni:v1:phenomenology:b")
536            .with_correlated_uncertainty(7, 100.0, 0.04);
537        obs_b.epistemic_beliefs.push(DoxasticBelief {
538            proposition_iri: "urn:qualia:prop:door-locked".into(),
539            mu: 0.80,
540            lambda: 0.08,
541        });
542
543        let merged = obs_a.merge_presheaf_compatible(&obs_b, 0.10).unwrap();
544        assert_eq!(merged.epistemic_beliefs.len(), 1);
545        assert!((merged.local_chart_var - 0.02).abs() < 1e-9);
546
547        // Contradictory belief on overlap must fail closed
548        let mut obs_conflict = obs_b.clone();
549        obs_conflict.epistemic_beliefs[0].mu = 0.10;
550        obs_conflict.epistemic_beliefs[0].lambda = 0.85;
551        assert!(obs_a.merge_presheaf_compatible(&obs_conflict, 0.10).is_err());
552
553        // Verify ClaimOpinion plane projection
554        let claim = obs_a.to_epistemic_claim_record();
555        match claim {
556            Value::Record(r) => {
557                assert_eq!(
558                    r.get("plane"),
559                    Some(&Value::String("ClaimOpinion".into()))
560                );
561                assert_eq!(
562                    r.get("observer_handle"),
563                    Some(&Value::String("did:q42:obs:a".into()))
564                );
565            }
566            _ => panic!("expected ClaimOpinion Record"),
567        }
568    }
569
570    #[test]
571    fn observer_to_value() {
572        let obs = ObserverFiber::new("did:q42:person:alice", "urn:omni:v1:phenomenology:alice");
573        let v = obs.to_value();
574        match v {
575            Value::Record(r) => {
576                assert_eq!(
577                    r.get("observer_did"),
578                    Some(&Value::String("did:q42:person:alice".into()))
579                );
580                assert!(r.contains_key("affective_state"));
581            }
582            _ => panic!("expected Record"),
583        }
584    }
585
586    #[test]
587    fn affective_to_value() {
588        let a = AffectiveStatus::default();
589        let v = a.to_value();
590        match v {
591            Value::Record(r) => {
592                assert!(r.contains_key("safety_threat_index"));
593                assert!(r.contains_key("emotional_valence"));
594            }
595            _ => panic!("expected Record"),
596        }
597    }
598}