Skip to main content

vibe/cosmic/
grounding.rs

1//! Grounding status and granular collapse operator (OCS §10, Packet OCS-13).
2//!
3//! Reference: OCS Specification v2.2.0 §10 & Playbook v4 Packet OCS-13.
4
5use crate::value::Value;
6use std::collections::BTreeMap;
7
8/// Epistemic grounding classification (OCS §10.1).
9#[derive(Debug, Clone, PartialEq)]
10pub enum GroundingStatus {
11    /// Explicitly anchored to a physical, archaeological, geological, or astronomical artifact.
12    EmpiricallyAnchored {
13        anchor_iri: String,
14        confidence: f32,
15        stratum_or_epoch: Option<String>,
16    },
17    /// Historically or geographically plausible interpolation (unverified but consistent).
18    PlausibleInterpolation,
19    /// Known artistic, literary, or narrative embellishment.
20    NarrativeFiction,
21    /// Counterfactual element violating physical law or verified historical record.
22    CounterfactualMythos,
23}
24
25impl GroundingStatus {
26    /// `str` form.
27    pub fn as_str(&self) -> &'static str {
28        match self {
29            Self::EmpiricallyAnchored { .. } => "EmpiricallyAnchored",
30            Self::PlausibleInterpolation => "PlausibleInterpolation",
31            Self::NarrativeFiction => "NarrativeFiction",
32            Self::CounterfactualMythos => "CounterfactualMythos",
33        }
34    }
35
36    /// Quantum context coordinate $q$ for `Tensor10D` integration (Packet OCS-13):
37    /// - `EmpiricallyAnchored` $\implies q \in [0.0, 1.0)$ ($q = 0.0$ at full confidence $1.0$).
38    /// - Uncollapsed narrative / counterfactual realms $\implies q \ge 1.0$.
39    pub fn quantum_context_q(&self) -> f32 {
40        match self {
41            Self::EmpiricallyAnchored { confidence, .. } => {
42                (1.0 - confidence.clamp(0.0, 1.0)).min(0.99)
43            }
44            Self::PlausibleInterpolation => 1.0,
45            Self::NarrativeFiction => 2.0,
46            Self::CounterfactualMythos => 3.0,
47        }
48    }
49
50    /// Whether this element should be collapsed onto physical spacetime ($q < 1.0$).
51    pub fn is_collapsible(&self) -> bool {
52        matches!(self, Self::EmpiricallyAnchored { .. }) && self.quantum_context_q() < 1.0
53    }
54
55    /// Converts to value.
56    pub fn to_value(&self) -> Value {
57        let mut rec = BTreeMap::new();
58        rec.insert("status".into(), Value::String(self.as_str().into()));
59        rec.insert(
60            "quantum_context_q".into(),
61            Value::F64(self.quantum_context_q() as f64),
62        );
63        if let Self::EmpiricallyAnchored {
64            anchor_iri,
65            confidence,
66            stratum_or_epoch,
67        } = self
68        {
69            rec.insert("anchor_iri".into(), Value::String(anchor_iri.clone()));
70            rec.insert("confidence".into(), Value::F64(*confidence as f64));
71            if let Some(s) = stratum_or_epoch {
72                rec.insert("stratum_or_epoch".into(), Value::String(s.clone()));
73            }
74        }
75        Value::Record(rec)
76    }
77}
78
79/// A narrative entity with grounding classification (OCS §10).
80#[derive(Debug, Clone)]
81pub struct NarrativeEntity {
82    pub name: String,
83    pub realm_usri: String,
84    pub grounding: GroundingStatus,
85}
86
87impl NarrativeEntity {
88    /// Create a collapsed (empirically anchored) entity.
89    pub fn anchored(name: &str, realm: &str, anchor_iri: &str, confidence: f32) -> Self {
90        Self {
91            name: name.into(),
92            realm_usri: realm.into(),
93            grounding: GroundingStatus::EmpiricallyAnchored {
94                anchor_iri: anchor_iri.into(),
95                confidence,
96                stratum_or_epoch: None,
97            },
98        }
99    }
100
101    /// Create a counterfactual/mythological entity.
102    pub fn mythos(name: &str, realm: &str) -> Self {
103        Self {
104            name: name.into(),
105            realm_usri: realm.into(),
106            grounding: GroundingStatus::CounterfactualMythos,
107        }
108    }
109
110    /// Converts to value.
111    pub fn to_value(&self) -> Value {
112        let mut rec = BTreeMap::new();
113        rec.insert("name".into(), Value::String(self.name.clone()));
114        rec.insert("realm_usri".into(), Value::String(self.realm_usri.clone()));
115        rec.insert("grounding".into(), self.grounding.to_value());
116        Value::Record(rec)
117    }
118}
119
120/// Granular collapse operator Ĉ (OCS §10.2, Packet OCS-13).
121///
122/// Given a set of narrative entities, returns only those that are
123/// empirically anchored ($q < 1.0$, collapsible onto physical spacetime),
124/// leaving counterfactual or fictional entities uncollapsed in their narrative realm.
125pub fn collapse_entities(entities: &[NarrativeEntity]) -> Vec<&NarrativeEntity> {
126    entities
127        .iter()
128        .filter(|e| e.grounding.is_collapsible())
129        .collect()
130}
131
132/// Normalized log-sum-exp distance metric subtracting $\ln(N)$ so $d(x, x) = 0.0$ (Packet OCS-13).
133///
134/// $$d_{\text{LSE}}(\mathbf{x}, \mathbf{y}) = \ln\!\left(\sum_{i=1}^{N} e^{|x_i - y_i|}\right) - \ln(N)$$
135pub fn normalized_lse_distance(a: &[f64], b: &[f64]) -> f64 {
136    if a.is_empty() || a.len() != b.len() {
137        return f64::INFINITY;
138    }
139    let n = a.len() as f64;
140    let max_diff = a
141        .iter()
142        .zip(b.iter())
143        .map(|(x, y)| (x - y).abs())
144        .fold(0.0_f64, f64::max);
145    let sum_exp: f64 = a
146        .iter()
147        .zip(b.iter())
148        .map(|(x, y)| ((x - y).abs() - max_diff).exp())
149        .sum();
150    (max_diff + sum_exp.ln() - n.ln()).max(0.0)
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn empirically_anchored_is_collapsible() {
159        let status = GroundingStatus::EmpiricallyAnchored {
160            anchor_iri: "urn:omni:v1:physical:earth:hisarlik".into(),
161            confidence: 0.95,
162            stratum_or_epoch: Some("VIIa".into()),
163        };
164        assert!(status.is_collapsible());
165        assert!(status.quantum_context_q() < 1.0);
166    }
167
168    #[test]
169    fn counterfactual_not_collapsible() {
170        assert!(!GroundingStatus::CounterfactualMythos.is_collapsible());
171        assert!(GroundingStatus::CounterfactualMythos.quantum_context_q() >= 1.0);
172    }
173
174    #[test]
175    fn narrative_fiction_not_collapsible() {
176        assert!(!GroundingStatus::NarrativeFiction.is_collapsible());
177        assert!(GroundingStatus::NarrativeFiction.quantum_context_q() >= 1.0);
178    }
179
180    #[test]
181    fn collapse_troy_and_athena() {
182        let troy = NarrativeEntity::anchored(
183            "ancient_troy_citadel",
184            "urn:omni:v1:narrative:homer:iliad",
185            "urn:omni:v1:physical:earth:hisarlik",
186            0.95,
187        );
188        let athena = NarrativeEntity::mythos("goddess_athena", "urn:omni:v1:narrative:homer:iliad");
189        let entities = vec![troy.clone(), athena.clone()];
190        let collapsed = collapse_entities(&entities);
191        assert_eq!(collapsed.len(), 1);
192        assert_eq!(collapsed[0].name, "ancient_troy_citadel");
193        // Verify uncollapsed mythos entity remains in narrative realm with q >= 1.0
194        assert_eq!(athena.realm_usri, "urn:omni:v1:narrative:homer:iliad");
195        assert!(athena.grounding.quantum_context_q() >= 1.0);
196    }
197
198    #[test]
199    fn normalized_lse_distance_zero_on_identical_vectors() {
200        let x = [12.5, -4.2, 88.0];
201        assert!(normalized_lse_distance(&x, &x).abs() < 1e-12);
202        let y = [13.5, -4.2, 88.0];
203        assert!(normalized_lse_distance(&x, &y) > 0.0);
204    }
205
206    #[test]
207    fn grounding_to_value() {
208        let status = GroundingStatus::EmpiricallyAnchored {
209            anchor_iri: "test".into(),
210            confidence: 0.8,
211            stratum_or_epoch: None,
212        };
213        let v = status.to_value();
214        match v {
215            Value::Record(r) => {
216                assert_eq!(
217                    r.get("status"),
218                    Some(&Value::String("EmpiricallyAnchored".into()))
219                );
220                if let Some(Value::F64(c)) = r.get("confidence") {
221                    assert!((*c - 0.8).abs() < 1e-6, "confidence mismatch: {}", c);
222                } else {
223                    panic!("expected F64 confidence");
224                }
225            }
226            _ => panic!("expected Record"),
227        }
228    }
229
230    #[test]
231    fn narrative_entity_to_value() {
232        let e = NarrativeEntity::anchored("test", "realm", "anchor", 0.9);
233        let v = e.to_value();
234        match v {
235            Value::Record(r) => {
236                assert_eq!(r.get("name"), Some(&Value::String("test".into())));
237                assert!(r.contains_key("grounding"));
238            }
239            _ => panic!("expected Record"),
240        }
241    }
242}