Skip to main content

vibe/cosmic/
theory.rs

1//! Theory packages, law nature, and assurance hierarchy (OCS §11).
2//!
3//! Extends the law_package module with OCS-specific theory metadata.
4//!
5//! Reference: OCS Specification v2.2.0 §11.
6
7use crate::value::Value;
8use std::collections::BTreeMap;
9
10/// Law nature — the epistemic classification of a law (OCS §11.1).
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum LawNature {
13    /// Empirically verified or standard physical law (Maxwell, Einstein GR, Standard Model).
14    Physical,
15    /// Formal scientific hypothesis under active investigation (MOND, String Compactification).
16    TheoreticalHypothesis,
17    /// Mathematically consistent solution requiring hypothetical conditions (Alcubierre, Wormholes).
18    HypotheticalExotic,
19    /// Fictional lore for games, literature, or worldbuilding (Star Trek Warp).
20    Fictional,
21}
22
23impl LawNature {
24    /// `str` form.
25    pub fn as_str(&self) -> &'static str {
26        match self {
27            Self::Physical => "Physical",
28            Self::TheoreticalHypothesis => "TheoreticalHypothesis",
29            Self::HypotheticalExotic => "HypotheticalExotic",
30            Self::Fictional => "Fictional",
31        }
32    }
33
34    /// Constructs from str.
35    pub fn from_str(s: &str) -> Option<Self> {
36        match s {
37            "Physical" => Some(Self::Physical),
38            "TheoreticalHypothesis" => Some(Self::TheoreticalHypothesis),
39            "HypotheticalExotic" => Some(Self::HypotheticalExotic),
40            "Fictional" => Some(Self::Fictional),
41            _ => None,
42        }
43    }
44}
45
46/// Progressive assurance hierarchy (OCS §11.2).
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
48pub enum AssuranceLevel {
49    /// Speculative / Fictional: unconstrained conjecture, zero empirical anchors.
50    A0,
51    /// Mathematically Formalized: self-consistent equations and action principles.
52    A1,
53    /// Computationally Verified: numerically stable, validated against CPU/GPU oracles.
54    A2,
55    /// Empirically Calibrated: validated against real datasets (Gaia, JWST, LIGO). χ² ≈ 1.0.
56    A3,
57    /// Empirical Metrology Standard: fundamental SI definitions and consensus constants.
58    A4,
59}
60
61impl AssuranceLevel {
62    /// `str` form.
63    pub fn as_str(&self) -> &'static str {
64        match self {
65            Self::A0 => "A0",
66            Self::A1 => "A1",
67            Self::A2 => "A2",
68            Self::A3 => "A3",
69            Self::A4 => "A4",
70        }
71    }
72
73    /// Constructs from str.
74    pub fn from_str(s: &str) -> Option<Self> {
75        match s {
76            "A0" => Some(Self::A0),
77            "A1" => Some(Self::A1),
78            "A2" => Some(Self::A2),
79            "A3" => Some(Self::A3),
80            "A4" => Some(Self::A4),
81            _ => None,
82        }
83    }
84}
85
86/// Theory lineage relationship (OCS §11.1).
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
88pub enum TheoryLineage {
89    Refines,
90    Supersedes,
91    Approximates,
92    CompetesWith,
93}
94
95impl TheoryLineage {
96    /// `str` form.
97    pub fn as_str(&self) -> &'static str {
98        match self {
99            Self::Refines => "Refines",
100            Self::Supersedes => "Supersedes",
101            Self::Approximates => "Approximates",
102            Self::CompetesWith => "CompetesWith",
103        }
104    }
105}
106
107/// Applicability envelope — the domain where a theory applies (OCS §11.1).
108#[derive(Debug, Clone, PartialEq)]
109pub struct ApplicabilityEnvelope {
110    /// Minimum scale (m) where the theory is valid.
111    pub min_scale_m: f64,
112    /// Maximum scale (m) where the theory is valid.
113    pub max_scale_m: f64,
114    /// Whether the theory applies in strong-field gravity.
115    pub strong_field: bool,
116    /// Whether the theory applies in weak-field gravity.
117    pub weak_field: bool,
118}
119
120/// A theory package — a signed, classified law with provenance (OCS §11.1).
121#[derive(Debug, Clone)]
122pub struct TheoryPackage {
123    pub theory_id: String,
124    pub name: String,
125    pub author_did: String,
126    pub nature: LawNature,
127    pub assurance_level: AssuranceLevel,
128    /// Evidential interval (μ: support, λ: refutation) in E_τ
129    pub evidential_interval: (f32, f32),
130    pub lineage: Option<(TheoryLineage, String)>,
131    pub empirical_anchors: Vec<String>,
132    pub residual_chi_squared: f64,
133    pub applicability: ApplicabilityEnvelope,
134    pub signature: Vec<u8>,
135}
136
137impl TheoryPackage {
138    /// Create a new theory package.
139    pub fn new(
140        id: &str,
141        name: &str,
142        author_did: &str,
143        nature: LawNature,
144        assurance: AssuranceLevel,
145    ) -> Self {
146        Self {
147            theory_id: id.into(),
148            name: name.into(),
149            author_did: author_did.into(),
150            nature,
151            assurance_level: assurance,
152            evidential_interval: (0.0, 0.0),
153            lineage: None,
154            empirical_anchors: Vec::new(),
155            residual_chi_squared: 0.0,
156            applicability: ApplicabilityEnvelope {
157                min_scale_m: 0.0,
158                max_scale_m: f64::INFINITY,
159                strong_field: false,
160                weak_field: true,
161            },
162            signature: Vec::new(),
163        }
164    }
165
166    /// Set evidential interval (μ, λ).
167    pub fn with_evidence(mut self, mu: f32, lambda: f32) -> Self {
168        self.evidential_interval = (mu, lambda);
169        self
170    }
171
172    /// Add an empirical anchor IRI.
173    pub fn with_anchor(mut self, iri: &str) -> Self {
174        self.empirical_anchors.push(iri.into());
175        self
176    }
177
178    /// Set residual chi-squared.
179    pub fn with_chi_squared(mut self, chi2: f64) -> Self {
180        self.residual_chi_squared = chi2;
181        self
182    }
183
184    /// Set lineage.
185    pub fn with_lineage(mut self, relation: TheoryLineage, target: &str) -> Self {
186        self.lineage = Some((relation, target.into()));
187        self
188    }
189
190    /// Whether this theory is empirically calibrated (A3+).
191    pub fn is_empirically_calibrated(&self) -> bool {
192        self.assurance_level >= AssuranceLevel::A3
193    }
194
195    /// Whether this theory is fictional.
196    pub fn is_fictional(&self) -> bool {
197        self.nature == LawNature::Fictional
198    }
199
200    /// Converts to value.
201    pub fn to_value(&self) -> Value {
202        let mut rec = BTreeMap::new();
203        rec.insert("theory_id".into(), Value::String(self.theory_id.clone()));
204        rec.insert("name".into(), Value::String(self.name.clone()));
205        rec.insert("author_did".into(), Value::String(self.author_did.clone()));
206        rec.insert("nature".into(), Value::String(self.nature.as_str().into()));
207        rec.insert(
208            "assurance_level".into(),
209            Value::String(self.assurance_level.as_str().into()),
210        );
211        rec.insert("mu".into(), Value::F64(self.evidential_interval.0 as f64));
212        rec.insert(
213            "lambda".into(),
214            Value::F64(self.evidential_interval.1 as f64),
215        );
216        rec.insert(
217            "residual_chi_squared".into(),
218            Value::F64(self.residual_chi_squared),
219        );
220        if let Some((rel, target)) = &self.lineage {
221            rec.insert(
222                "lineage_relation".into(),
223                Value::String(rel.as_str().into()),
224            );
225            rec.insert("lineage_target".into(), Value::String(target.clone()));
226        }
227        if !self.empirical_anchors.is_empty() {
228            rec.insert(
229                "empirical_anchors".into(),
230                Value::List(
231                    self.empirical_anchors
232                        .iter()
233                        .map(|s| Value::String(s.clone()))
234                        .collect(),
235                ),
236            );
237        }
238        Value::Record(rec)
239    }
240}
241
242#[cfg(test)]
243mod tests {
244    use super::*;
245
246    #[test]
247    fn law_nature_round_trip() {
248        for n in [
249            LawNature::Physical,
250            LawNature::TheoreticalHypothesis,
251            LawNature::Fictional,
252        ] {
253            assert_eq!(LawNature::from_str(n.as_str()), Some(n));
254        }
255    }
256
257    #[test]
258    fn assurance_ordering() {
259        assert!(AssuranceLevel::A4 > AssuranceLevel::A3);
260        assert!(AssuranceLevel::A3 > AssuranceLevel::A0);
261    }
262
263    #[test]
264    fn theory_package_basic() {
265        let t = TheoryPackage::new(
266            "lcdm",
267            "ΛCDM Standard",
268            "did:q42:person:author",
269            LawNature::Physical,
270            AssuranceLevel::A3,
271        )
272        .with_evidence(0.85, 0.15)
273        .with_chi_squared(1.04)
274        .with_anchor("urn:omni:v1:physical:gaia-dr3");
275        assert!(t.is_empirically_calibrated());
276        assert!(!t.is_fictional());
277        assert_eq!(t.evidential_interval, (0.85, 0.15));
278    }
279
280    #[test]
281    fn theory_package_fictional() {
282        let t = TheoryPackage::new(
283            "warp",
284            "Warp Drive",
285            "did:q42:person:author",
286            LawNature::Fictional,
287            AssuranceLevel::A0,
288        );
289        assert!(t.is_fictional());
290        assert!(!t.is_empirically_calibrated());
291    }
292
293    #[test]
294    fn theory_package_lineage() {
295        let t = TheoryPackage::new(
296            "mond",
297            "MOND",
298            "did:q42:person:author",
299            LawNature::TheoreticalHypothesis,
300            AssuranceLevel::A1,
301        )
302        .with_lineage(TheoryLineage::CompetesWith, "lcdm");
303        assert!(t.lineage.is_some());
304        let (rel, target) = t.lineage.unwrap();
305        assert_eq!(rel, TheoryLineage::CompetesWith);
306        assert_eq!(target, "lcdm");
307    }
308
309    #[test]
310    fn theory_to_value() {
311        let t = TheoryPackage::new(
312            "test",
313            "Test Theory",
314            "did:q42:person:x",
315            LawNature::Physical,
316            AssuranceLevel::A2,
317        )
318        .with_evidence(0.5, 0.3);
319        let v = t.to_value();
320        match v {
321            Value::Record(r) => {
322                assert_eq!(r.get("theory_id"), Some(&Value::String("test".into())));
323                assert_eq!(r.get("nature"), Some(&Value::String("Physical".into())));
324                assert_eq!(r.get("assurance_level"), Some(&Value::String("A2".into())));
325                assert_eq!(r.get("mu"), Some(&Value::F64(0.5)));
326            }
327            _ => panic!("expected Record"),
328        }
329    }
330
331    #[test]
332    fn assurance_from_str() {
333        assert_eq!(AssuranceLevel::from_str("A3"), Some(AssuranceLevel::A3));
334        assert_eq!(AssuranceLevel::from_str("A0"), Some(AssuranceLevel::A0));
335        assert_eq!(AssuranceLevel::from_str("invalid"), None);
336    }
337}