Skip to main content

vibe/cosmic/
colocated.rs

1//! Co-located realities and paraconsistent isolation (OCS §9).
2//!
3//! Multiple fictional, historical, or hypothetical layers can share
4//! the exact same physical coordinates without collision.
5//!
6//! Reference: OCS Specification v2.2.0 §9.
7
8use crate::cosmic::transforms::Geodetic;
9use crate::value::Value;
10use std::collections::BTreeMap;
11
12/// A co-located reality layer (OCS §9).
13#[derive(Debug, Clone, PartialEq)]
14pub struct CoLocatedLayer {
15    /// USRI of this reality layer
16    pub usri: String,
17    /// Human-readable name
18    pub name: String,
19    /// The physical geodetic coordinates this layer is co-located at
20    pub geodetic: Geodetic,
21    /// Whether this is the physical base layer
22    pub is_physical_base: bool,
23}
24
25impl CoLocatedLayer {
26    /// Create a physical base layer (OCS §9).
27    pub fn physical_base(geodetic: Geodetic) -> Self {
28        Self {
29            usri: "urn:omni:v1:physical:observable:standard:earth:wgs84".into(),
30            name: "Physical Reality".into(),
31            geodetic,
32            is_physical_base: true,
33        }
34    }
35
36    /// Create a co-located fictional layer (OCS §9.1).
37    pub fn fictional(name: &str, usri: &str, geodetic: Geodetic) -> Self {
38        Self {
39            usri: usri.into(),
40            name: name.into(),
41            geodetic,
42            is_physical_base: false,
43        }
44    }
45
46    /// Create a co-located historical layer (OCS §9.1).
47    pub fn historical(name: &str, usri: &str, geodetic: Geodetic) -> Self {
48        Self {
49            usri: usri.into(),
50            name: name.into(),
51            geodetic,
52            is_physical_base: false,
53        }
54    }
55
56    /// Converts to value.
57    pub fn to_value(&self) -> Value {
58        let mut rec = BTreeMap::new();
59        rec.insert("usri".into(), Value::String(self.usri.clone()));
60        rec.insert("name".into(), Value::String(self.name.clone()));
61        rec.insert("lat".into(), Value::F64(self.geodetic.lat_deg));
62        rec.insert("lon".into(), Value::F64(self.geodetic.lon_deg));
63        rec.insert("alt".into(), Value::F64(self.geodetic.alt_m));
64        rec.insert(
65            "is_physical_base".into(),
66            Value::Bool(self.is_physical_base),
67        );
68        Value::Record(rec)
69    }
70}
71
72/// A stack of co-located reality layers at the same physical position (OCS §9).
73#[derive(Debug, Clone)]
74pub struct CoLocatedStack {
75    /// All layers at this position, ordered from physical base outward
76    pub layers: Vec<CoLocatedLayer>,
77}
78
79impl CoLocatedStack {
80    /// Creates a new `CoLocatedStack`.
81    pub fn new(physical: CoLocatedLayer) -> Self {
82        Self {
83            layers: vec![physical],
84        }
85    }
86
87    /// Add a co-located layer (OCS §9).
88    pub fn add_layer(&mut self, layer: CoLocatedLayer) {
89        // Verify it's co-located at the same position
90        let base = &self.layers[0];
91        let dist = crate::cosmic::transforms::geodetic_distance(base.geodetic, layer.geodetic);
92        // Layers must be at the same physical location (within 1 km tolerance)
93        if dist > 1000.0 {
94            return; // Not co-located — silently reject
95        }
96        self.layers.push(layer);
97    }
98
99    /// Get the physical base layer.
100    pub fn physical_base(&self) -> &CoLocatedLayer {
101        &self.layers[0]
102    }
103
104    /// Get all non-physical layers.
105    pub fn fictional_layers(&self) -> Vec<&CoLocatedLayer> {
106        self.layers.iter().filter(|l| !l.is_physical_base).collect()
107    }
108
109    /// Verify paraconsistent isolation (OCS §9.2).
110    ///
111    /// The lexical isolation rule: inner layers inherit spatial anchors
112    /// from outer containers, but mutations in inner layers can never
113    /// mutate or leak into parent layers.
114    pub fn verify_isolation(&self) -> bool {
115        // Physical base must be first
116        if self.layers.is_empty() || !self.layers[0].is_physical_base {
117            return false;
118        }
119        // Only one physical base allowed
120        self.layers.iter().filter(|l| l.is_physical_base).count() == 1
121    }
122
123    /// Check that a mutation in a layer index doesn't affect the physical base (OCS-T06).
124    pub fn check_no_mutation_leak(&self, layer_index: usize) -> bool {
125        if layer_index == 0 {
126            return true; // Can't leak into yourself
127        }
128        if layer_index >= self.layers.len() {
129            return true;
130        }
131        // The physical base coordinates must not change
132        // (This is a structural check — the actual mutation prevention
133        // is enforced by the paraconsistent isolation context hashing)
134        self.verify_isolation()
135    }
136
137    /// Converts to value.
138    pub fn to_value(&self) -> Value {
139        Value::List(self.layers.iter().map(|l| l.to_value()).collect())
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn physical_base_layer() {
149        let layer = CoLocatedLayer::physical_base(Geodetic {
150            lat_deg: 37.8080,
151            lon_deg: -122.4177,
152            alt_m: 10.0,
153        });
154        assert!(layer.is_physical_base);
155    }
156
157    #[test]
158    fn fictional_layer() {
159        let layer = CoLocatedLayer::fictional(
160            "Starfleet Academy",
161            "urn:omni:v1:fiction:star-trek:prime:earth:san-francisco:starfleet-academy",
162            Geodetic {
163                lat_deg: 37.8080,
164                lon_deg: -122.4177,
165                alt_m: 10.0,
166            },
167        );
168        assert!(!layer.is_physical_base);
169        assert_eq!(layer.name, "Starfleet Academy");
170    }
171
172    #[test]
173    fn co_located_stack_add_layer() {
174        let base = CoLocatedLayer::physical_base(Geodetic {
175            lat_deg: 37.8080,
176            lon_deg: -122.4177,
177            alt_m: 10.0,
178        });
179        let mut stack = CoLocatedStack::new(base);
180        let fiction = CoLocatedLayer::fictional(
181            "Starfleet HQ",
182            "urn:omni:v1:fiction:star-trek:prime:earth:san-francisco",
183            Geodetic {
184                lat_deg: 37.8080,
185                lon_deg: -122.4177,
186                alt_m: 10.0,
187            },
188        );
189        stack.add_layer(fiction);
190        assert_eq!(stack.layers.len(), 2);
191    }
192
193    #[test]
194    fn co_located_rejects_distant_layer() {
195        let base = CoLocatedLayer::physical_base(Geodetic {
196            lat_deg: 37.8080,
197            lon_deg: -122.4177,
198            alt_m: 10.0,
199        });
200        let mut stack = CoLocatedStack::new(base);
201        let distant = CoLocatedLayer::fictional(
202            "NYC Layer",
203            "urn:omni:v1:fiction:marvel:earth-616:nyc",
204            Geodetic {
205                lat_deg: 40.7291,
206                lon_deg: -73.9996,
207                alt_m: 15.0,
208            },
209        );
210        stack.add_layer(distant);
211        // Should not be added — not co-located
212        assert_eq!(stack.layers.len(), 1);
213    }
214
215    #[test]
216    fn isolation_verified() {
217        let base = CoLocatedLayer::physical_base(Geodetic {
218            lat_deg: 37.8,
219            lon_deg: -122.4,
220            alt_m: 10.0,
221        });
222        let stack = CoLocatedStack::new(base);
223        assert!(stack.verify_isolation());
224    }
225
226    #[test]
227    fn isolation_rejects_two_physical_bases() {
228        let base1 = CoLocatedLayer::physical_base(Geodetic {
229            lat_deg: 37.8,
230            lon_deg: -122.4,
231            alt_m: 10.0,
232        });
233        let base2 = CoLocatedLayer::physical_base(Geodetic {
234            lat_deg: 37.8,
235            lon_deg: -122.4,
236            alt_m: 10.0,
237        });
238        let mut stack = CoLocatedStack::new(base1);
239        stack.layers.push(base2);
240        assert!(!stack.verify_isolation());
241    }
242
243    #[test]
244    fn no_mutation_leak_to_physical() {
245        let base = CoLocatedLayer::physical_base(Geodetic {
246            lat_deg: 37.8,
247            lon_deg: -122.4,
248            alt_m: 10.0,
249        });
250        let fiction = CoLocatedLayer::fictional(
251            "Fiction",
252            "urn:omni:v1:fiction:test",
253            Geodetic {
254                lat_deg: 37.8,
255                lon_deg: -122.4,
256                alt_m: 10.0,
257            },
258        );
259        let mut stack = CoLocatedStack::new(base);
260        stack.add_layer(fiction);
261        // Mutations in layer 1 (fiction) should not leak to layer 0 (physical)
262        assert!(stack.check_no_mutation_leak(1));
263    }
264
265    #[test]
266    fn fictional_layers_filter() {
267        let base = CoLocatedLayer::physical_base(Geodetic {
268            lat_deg: 37.8,
269            lon_deg: -122.4,
270            alt_m: 10.0,
271        });
272        let mut stack = CoLocatedStack::new(base);
273        stack.add_layer(CoLocatedLayer::fictional(
274            "F1",
275            "urn:omni:v1:fiction:a",
276            Geodetic {
277                lat_deg: 37.8,
278                lon_deg: -122.4,
279                alt_m: 10.0,
280            },
281        ));
282        stack.add_layer(CoLocatedLayer::historical(
283            "1906 SF",
284            "urn:omni:v1:theorized:history:earth:sf-1906",
285            Geodetic {
286                lat_deg: 37.8,
287                lon_deg: -122.4,
288                alt_m: 10.0,
289            },
290        ));
291        let fiction = stack.fictional_layers();
292        // Historical is not physical_base, so it's included in non-physical
293        assert_eq!(fiction.len(), 2);
294    }
295
296    #[test]
297    fn layer_to_value() {
298        let layer = CoLocatedLayer::physical_base(Geodetic {
299            lat_deg: 37.8,
300            lon_deg: -122.4,
301            alt_m: 10.0,
302        });
303        let v = layer.to_value();
304        match v {
305            Value::Record(r) => {
306                assert!(r.contains_key("lat"));
307                assert!(r.contains_key("is_physical_base"));
308            }
309            _ => panic!("expected Record"),
310        }
311    }
312}