1use crate::value::Value;
11use std::collections::BTreeMap;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum RealmClass {
16 Physical,
17 Theorized,
18 QuantumBranch,
19 Hypothetical,
20 Fiction,
21 Simulation,
22 Phenomenology,
23 Noosphere,
24 Narrative,
25 Microverse,
26}
27
28impl RealmClass {
29 pub const ALL: [Self; 10] = [
31 Self::Physical,
32 Self::Theorized,
33 Self::QuantumBranch,
34 Self::Hypothetical,
35 Self::Fiction,
36 Self::Simulation,
37 Self::Phenomenology,
38 Self::Noosphere,
39 Self::Narrative,
40 Self::Microverse,
41 ];
42
43 pub fn as_str(&self) -> &'static str {
45 match self {
46 Self::Physical => "physical",
47 Self::Theorized => "theorized",
48 Self::QuantumBranch => "quantum-branch",
49 Self::Hypothetical => "hypothetical",
50 Self::Fiction => "fiction",
51 Self::Simulation => "simulation",
52 Self::Phenomenology => "phenomenology",
53 Self::Noosphere => "noosphere",
54 Self::Narrative => "narrative",
55 Self::Microverse => "microverse",
56 }
57 }
58
59 pub fn as_u8(&self) -> u8 {
61 match self {
62 Self::Physical => 0,
63 Self::Theorized => 1,
64 Self::QuantumBranch => 2,
65 Self::Fiction => 3,
66 Self::Phenomenology => 4,
67 Self::Noosphere => 5,
68 Self::Microverse => 6,
69 Self::Hypothetical => 7,
70 Self::Simulation => 8,
71 Self::Narrative => 9,
72 }
73 }
74
75 pub fn from_u8(v: u8) -> Option<Self> {
77 match v {
78 0 => Some(Self::Physical),
79 1 => Some(Self::Theorized),
80 2 => Some(Self::QuantumBranch),
81 3 => Some(Self::Fiction),
82 4 => Some(Self::Phenomenology),
83 5 => Some(Self::Noosphere),
84 6 => Some(Self::Microverse),
85 7 => Some(Self::Hypothetical),
86 8 => Some(Self::Simulation),
87 9 => Some(Self::Narrative),
88 _ => None,
89 }
90 }
91
92 pub fn from_g_coord_realm(s: &str) -> Option<Self> {
95 match s {
96 "earth" | "cosmos" => Some(Self::Physical),
97 "fictional" => Some(Self::Fiction),
98 "speculative" => Some(Self::Hypothetical),
99 "viewpoint" => Some(Self::Phenomenology),
100 other => Self::from_str(other),
101 }
102 }
103
104 pub fn to_g_coord_realm(&self) -> &'static str {
108 match self {
109 Self::Physical | Self::Microverse => "cosmos",
110 Self::Theorized | Self::QuantumBranch | Self::Hypothetical => "speculative",
111 Self::Fiction | Self::Simulation | Self::Narrative => "fictional",
112 Self::Phenomenology | Self::Noosphere => "viewpoint",
113 }
114 }
115
116 pub fn from_str(s: &str) -> Option<Self> {
118 match s {
119 "physical" => Some(Self::Physical),
120 "theorized" => Some(Self::Theorized),
121 "quantum-branch" => Some(Self::QuantumBranch),
122 "hypothetical" => Some(Self::Hypothetical),
123 "fiction" => Some(Self::Fiction),
124 "simulation" => Some(Self::Simulation),
125 "phenomenology" => Some(Self::Phenomenology),
126 "noosphere" => Some(Self::Noosphere),
127 "narrative" => Some(Self::Narrative),
128 "microverse" => Some(Self::Microverse),
129 _ => None,
130 }
131 }
132}
133
134#[derive(Debug, Clone, PartialEq)]
136pub struct Usri {
137 pub version: String,
138 pub realm_class: RealmClass,
139 pub universe_or_observer: String,
140 pub branch_or_state: String,
141 pub hierarchy_path: String,
142 pub nested: Vec<String>,
143 pub collapsed: Vec<String>,
144 pub anchor: String,
145}
146
147impl Usri {
148 pub fn parse(s: &str) -> Result<Self, String> {
150 let s = s
151 .strip_prefix("urn:omni:")
152 .ok_or("USRI must start with 'urn:omni:'")?;
153
154 let (main, anchor) = match s.split_once('#') {
156 Some((m, a)) => (m, a.to_string()),
157 None => (s, String::new()),
158 };
159
160 let parts: Vec<&str> = main.splitn(2, '/').collect();
162 let main_path = parts[0];
163 let extra = parts.get(1).unwrap_or(&"");
164
165 let segments: Vec<&str> = main_path.split(':').collect();
167 if segments.len() < 5 {
168 return Err(format!(
169 "USRI needs at least 5 colon-separated segments, got {}",
170 segments.len()
171 ));
172 }
173
174 let version = segments[0].to_string();
175 let realm_class = RealmClass::from_str(segments[1])
176 .ok_or_else(|| format!("unknown realm class: {}", segments[1]))?;
177 let universe_or_observer = segments[2].to_string();
178 let branch_or_state = segments[3].to_string();
179 let hierarchy_path = segments[4..].join(":");
181
182 let mut nested = Vec::new();
184 let mut collapsed = Vec::new();
185 if !extra.is_empty() {
186 for seg in extra.split('/') {
187 if let Some(spec) = seg.strip_prefix("nested:") {
188 nested.push(spec.to_string());
189 } else if let Some(spec) = seg.strip_prefix("collapsed:") {
190 collapsed.push(spec.to_string());
191 }
192 }
193 }
194
195 Ok(Self {
196 version,
197 realm_class,
198 universe_or_observer,
199 branch_or_state,
200 hierarchy_path,
201 nested,
202 collapsed,
203 anchor,
204 })
205 }
206
207 pub fn to_string(&self) -> String {
209 let mut out = format!(
210 "urn:omni:{}:{}:{}:{}:{}",
211 self.version,
212 self.realm_class.as_str(),
213 self.universe_or_observer,
214 self.branch_or_state,
215 self.hierarchy_path,
216 );
217 for n in &self.nested {
218 out.push_str(&format!("/nested:{}", n));
219 }
220 for c in &self.collapsed {
221 out.push_str(&format!("/collapsed:{}", c));
222 }
223 if !self.anchor.is_empty() {
224 out.push_str(&format!("#{}", self.anchor));
225 }
226 out
227 }
228
229 pub fn g_coord_realm(&self) -> &'static str {
232 if self.realm_class == RealmClass::Physical
233 && self
234 .hierarchy_path
235 .split(':')
236 .any(|seg| seg.eq_ignore_ascii_case("earth"))
237 {
238 "earth"
239 } else {
240 self.realm_class.to_g_coord_realm()
241 }
242 }
243
244 pub fn to_value(&self) -> Value {
246 let mut rec = BTreeMap::new();
247 rec.insert("version".into(), Value::String(self.version.clone()));
248 rec.insert(
249 "realm_class".into(),
250 Value::String(self.realm_class.as_str().into()),
251 );
252 rec.insert(
253 "universe_or_observer".into(),
254 Value::String(self.universe_or_observer.clone()),
255 );
256 rec.insert(
257 "branch_or_state".into(),
258 Value::String(self.branch_or_state.clone()),
259 );
260 rec.insert(
261 "hierarchy_path".into(),
262 Value::String(self.hierarchy_path.clone()),
263 );
264 if !self.nested.is_empty() {
265 rec.insert(
266 "nested".into(),
267 Value::List(
268 self.nested
269 .iter()
270 .map(|s| Value::String(s.clone()))
271 .collect(),
272 ),
273 );
274 }
275 if !self.collapsed.is_empty() {
276 rec.insert(
277 "collapsed".into(),
278 Value::List(
279 self.collapsed
280 .iter()
281 .map(|s| Value::String(s.clone()))
282 .collect(),
283 ),
284 );
285 }
286 if !self.anchor.is_empty() {
287 rec.insert("anchor".into(), Value::String(self.anchor.clone()));
288 }
289 Value::Record(rec)
290 }
291}
292
293pub fn g_coord_realm_to_realm_class(g_coord: &str) -> Option<RealmClass> {
296 RealmClass::from_g_coord_realm(g_coord)
297}
298
299pub fn realm_class_to_g_coord_realm(rc: RealmClass) -> &'static str {
301 rc.to_g_coord_realm()
302}
303
304#[cfg(test)]
305mod tests {
306 use super::*;
307
308 #[test]
309 fn parse_physical_earth_wgs84() {
310 let u = Usri::parse(
311 "urn:omni:v1:physical:observable:standard:laniakea:virgo:milkyway:sol:earth:wgs84",
312 )
313 .unwrap();
314 assert_eq!(u.version, "v1");
315 assert_eq!(u.realm_class, RealmClass::Physical);
316 assert_eq!(u.universe_or_observer, "observable");
317 assert_eq!(u.branch_or_state, "standard");
318 assert!(u.hierarchy_path.contains("earth"));
319 assert!(u.hierarchy_path.contains("wgs84"));
320 }
321
322 #[test]
323 fn parse_with_geo_anchor() {
324 let u = Usri::parse(
325 "urn:omni:v1:physical:observable:standard:earth:wgs84#geo(lat=37.8080,lon=-122.4177,alt=10.0)",
326 )
327 .unwrap();
328 assert_eq!(u.anchor, "geo(lat=37.8080,lon=-122.4177,alt=10.0)");
329 }
330
331 #[test]
332 fn parse_fiction_star_trek() {
333 let u = Usri::parse(
334 "urn:omni:v1:fiction:star-trek:prime:alpha-quadrant:sector-001:sol:earth:san-francisco:starfleet-academy",
335 )
336 .unwrap();
337 assert_eq!(u.realm_class, RealmClass::Fiction);
338 assert_eq!(u.universe_or_observer, "star-trek");
339 assert_eq!(u.branch_or_state, "prime");
340 }
341
342 #[test]
343 fn parse_with_nested_and_collapsed() {
344 let u = Usri::parse(
345 "urn:omni:v1:narrative:homer:iliad:troy:scaian-gate/collapsed:physical:observable:standard:earth:wgs84:turkey:hisarlik:stratum-viia#geo(lat=39.9575,lon=26.2389,alt=35)",
346 )
347 .unwrap();
348 assert_eq!(u.realm_class, RealmClass::Narrative);
349 assert_eq!(u.collapsed.len(), 1);
350 assert!(u.collapsed[0].contains("hisarlik"));
351 assert!(u.anchor.contains("39.9575"));
352 }
353
354 #[test]
355 fn round_trip_physical() {
356 let original = "urn:omni:v1:physical:observable:standard:earth:wgs84";
357 let u = Usri::parse(original).unwrap();
358 assert_eq!(u.to_string(), original);
359 }
360
361 #[test]
362 fn round_trip_with_anchor() {
363 let original =
364 "urn:omni:v1:physical:observable:standard:earth:wgs84#geo(lat=37.8,lon=-122.4)";
365 let u = Usri::parse(original).unwrap();
366 assert_eq!(u.to_string(), original);
367 }
368
369 #[test]
370 fn round_trip_with_collapsed() {
371 let original = "urn:omni:v1:narrative:homer:iliad:troy/collapsed:physical:earth:hisarlik";
372 let u = Usri::parse(original).unwrap();
373 assert_eq!(u.to_string(), original);
374 }
375
376 #[test]
377 fn realm_class_round_trip() {
378 for rc in RealmClass::ALL {
379 let s = rc.as_str();
380 assert_eq!(RealmClass::from_str(s), Some(rc));
381 assert_eq!(RealmClass::from_u8(rc.as_u8()), Some(rc));
382 let g_coord = rc.to_g_coord_realm();
383 assert!(
384 matches!(
385 g_coord,
386 "earth" | "cosmos" | "fictional" | "speculative" | "viewpoint"
387 ),
388 "unexpected G-COORD realm {g_coord}"
389 );
390 assert!(RealmClass::from_g_coord_realm(g_coord).is_some());
391 for level in super::super::cb_usri::HierarchyLevel::ALL {
392 let uri = format!("urn:omni:v1:{s}:universe:branch:sol:earth#anchor");
393 let parsed = Usri::parse(&uri).unwrap();
394 assert_eq!(parsed.realm_class, rc);
395 assert_eq!(parsed.to_string(), uri);
396 let cb = super::super::cb_usri::CompactBinaryUsri::from_usri(
397 &uri,
398 rc,
399 level,
400 1,
401 &parsed.anchor,
402 );
403 assert_eq!(cb.realm_class(), rc.as_u8());
404 assert_eq!(cb.level(), level.as_u8());
405 let ctx = cb.to_quin_context_token();
406 assert_eq!(ctx & (1u64 << 63), 0);
407 }
408 }
409 assert_eq!(RealmClass::from_g_coord_realm("earth"), Some(RealmClass::Physical));
410 assert_eq!(RealmClass::from_g_coord_realm("cosmos"), Some(RealmClass::Physical));
411 assert_eq!(RealmClass::from_g_coord_realm("fictional"), Some(RealmClass::Fiction));
412 assert_eq!(RealmClass::from_g_coord_realm("speculative"), Some(RealmClass::Hypothetical));
413 assert_eq!(RealmClass::from_g_coord_realm("viewpoint"), Some(RealmClass::Phenomenology));
414 let earth_usri = Usri::parse("urn:omni:v1:physical:observable:standard:sol:earth:wgs84").unwrap();
415 assert_eq!(earth_usri.g_coord_realm(), "earth");
416 let mars_usri = Usri::parse("urn:omni:v1:physical:observable:standard:sol:mars").unwrap();
417 assert_eq!(mars_usri.g_coord_realm(), "cosmos");
418 let fixture = include_str!("../../fixtures/g_coord_realms.vibe");
419 assert!(crate::load_program(fixture).is_ok());
420 for rc in [
421 RealmClass::Physical,
422 RealmClass::Fiction,
423 RealmClass::Narrative,
424 RealmClass::Phenomenology,
425 RealmClass::Microverse,
426 ] {
427 let s = rc.as_str();
428 assert_eq!(RealmClass::from_str(s), Some(rc));
429 }
430 }
431
432 #[test]
433 fn invalid_usri_fails() {
434 assert!(Usri::parse("not-a-usri").is_err());
435 assert!(Usri::parse("urn:omni:v1:badrealm:x:y:z").is_err());
436 }
437
438 #[test]
439 fn to_value_has_realm_class() {
440 let u = Usri::parse("urn:omni:v1:physical:observable:standard:earth").unwrap();
441 let v = u.to_value();
442 match v {
443 Value::Record(r) => {
444 assert_eq!(
445 r.get("realm_class"),
446 Some(&Value::String("physical".into()))
447 );
448 assert_eq!(r.get("version"), Some(&Value::String("v1".into())));
449 }
450 _ => panic!("expected Record"),
451 }
452 }
453}