Skip to main content

domainforge_core/application/
world.rs

1//! `world_ref`: the ergonomic, immutable reference to exactly one resolved
2//! semantic-world revision.
3//!
4//! A world revision is identified by [`DomainModelIdentity::canonical_digest`]
5//! and nothing else; this module defines no second hash. The canonical text
6//! form is defined here once:
7//!
8//! ```text
9//! world:<name>@sha256:<64 lowercase hex>
10//! ```
11//!
12//! * [`WorldRef`] — immutable; durable and consequential records pin this.
13//! * [`WorldAlias`] — mutable selector `world:<name>`; must be resolved to a
14//!   [`WorldRef`] before consequential execution ([`WorldCatalog::pin`]).
15//! * [`WorldLabel`] — presentation metadata only; never identity.
16//!
17//! The digest binds the exact source set, the semantic closure, the producer
18//! release and the interpretation/canonicalization versions. A comment-only
19//! source edit or a DomainForge upgrade therefore mints a new `world_ref`;
20//! [`DomainModelIdentity::semantic_closure_hash`] is the field that proves two
21//! revisions mean the same thing.
22
23use super::envelope::{CanonicalSemanticEnvelopeDocument, DomainModelIdentity};
24use serde::{Deserialize, Deserializer, Serialize, Serializer};
25use std::collections::BTreeMap;
26use std::fmt;
27use std::str::FromStr;
28
29/// The only identity-preimage scheme this module accepts.
30pub const SUPPORTED_IDENTITY_SCHEME: &str = "v2-full-preimage";
31const WORLD_PREFIX: &str = "world:";
32const DIGEST_PREFIX: &str = "sha256:";
33const MAX_NAME_LEN: usize = 64;
34const MAX_LABEL_LEN: usize = 200;
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum WorldRefError {
38    Malformed(String),
39    InvalidName(String),
40    InvalidDigest(String),
41    InvalidLabel(String),
42    DigestMismatch {
43        expected: String,
44        actual: String,
45    },
46    UnsupportedIdentityScheme(String),
47    MalformedIdentity(String),
48    UnknownWorld(String),
49    UnknownAlias(String),
50    NameConflict {
51        digest: String,
52        existing: String,
53        requested: String,
54    },
55}
56
57impl fmt::Display for WorldRefError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::Malformed(s) => write!(f, "malformed world reference: {s}"),
61            Self::InvalidName(s) => write!(f, "invalid world name: {s}"),
62            Self::InvalidDigest(s) => write!(f, "invalid world digest: {s}"),
63            Self::InvalidLabel(s) => write!(f, "invalid world label: {s}"),
64            Self::DigestMismatch { expected, actual } => write!(
65                f,
66                "world identity digest mismatch: reference pins {expected}, identity hashes to {actual}"
67            ),
68            Self::UnsupportedIdentityScheme(s) => {
69                write!(f, "unsupported identity scheme '{s}' (expected {SUPPORTED_IDENTITY_SCHEME})")
70            }
71            Self::MalformedIdentity(s) => write!(f, "malformed domain model identity: {s}"),
72            Self::UnknownWorld(s) => write!(f, "unknown world: {s}"),
73            Self::UnknownAlias(s) => write!(f, "unknown world alias: {s}"),
74            Self::NameConflict { digest, existing, requested } => write!(
75                f,
76                "world {digest} is already registered as '{existing}', not '{requested}'"
77            ),
78        }
79    }
80}
81
82impl std::error::Error for WorldRefError {}
83
84fn is_lower_hex(s: &str) -> bool {
85    s.bytes()
86        .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
87}
88
89fn validate_digest(text: &str) -> Result<(), WorldRefError> {
90    let hex = text
91        .strip_prefix(DIGEST_PREFIX)
92        .ok_or_else(|| WorldRefError::InvalidDigest(format!("'{text}' is not sha256:<hex>")))?;
93    if hex.len() != 64 || !is_lower_hex(hex) {
94        return Err(WorldRefError::InvalidDigest(format!(
95            "'{text}' is not sha256: followed by 64 lowercase hex digits"
96        )));
97    }
98    Ok(())
99}
100
101/// `[a-z][a-z0-9]*([._-][a-z0-9]+)*`, at most 64 characters.
102#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
103pub struct WorldName(String);
104
105impl WorldName {
106    pub fn as_str(&self) -> &str {
107        &self.0
108    }
109}
110
111impl FromStr for WorldName {
112    type Err = WorldRefError;
113    fn from_str(s: &str) -> Result<Self, Self::Err> {
114        let bytes = s.as_bytes();
115        let bad = |why: &str| WorldRefError::InvalidName(format!("'{s}': {why}"));
116        if bytes.is_empty() || bytes.len() > MAX_NAME_LEN {
117            return Err(bad("length must be 1..=64"));
118        }
119        if !bytes[0].is_ascii_lowercase() {
120            return Err(bad("must start with a lowercase letter"));
121        }
122        let mut prev_sep = false;
123        for &b in bytes {
124            let sep = matches!(b, b'.' | b'_' | b'-');
125            if !(b.is_ascii_lowercase() || b.is_ascii_digit() || sep) {
126                return Err(bad("only lowercase letters, digits and . _ -"));
127            }
128            if sep && prev_sep {
129                return Err(bad("separators must not repeat"));
130            }
131            prev_sep = sep;
132        }
133        if prev_sep {
134            return Err(bad("must not end with a separator"));
135        }
136        Ok(Self(s.to_string()))
137    }
138}
139
140impl fmt::Display for WorldName {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.write_str(&self.0)
143    }
144}
145
146/// Immutable reference to one resolved semantic-world revision.
147#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
148pub struct WorldRef {
149    name: WorldName,
150    /// `sha256:<64 lowercase hex>`, exactly `DomainModelIdentity::canonical_digest()`.
151    digest: String,
152}
153
154impl WorldRef {
155    /// Mint a reference from a DomainForge identity. Fails closed on an
156    /// unsupported identity scheme or malformed hash fields.
157    pub fn from_identity(
158        name: WorldName,
159        identity: &DomainModelIdentity,
160    ) -> Result<Self, WorldRefError> {
161        identity.validate()?;
162        Ok(Self {
163            name,
164            digest: identity.canonical_digest(),
165        })
166    }
167
168    pub fn name(&self) -> &WorldName {
169        &self.name
170    }
171
172    /// `sha256:<hex>`, identical to `DomainModelIdentity::canonical_digest()`.
173    pub fn digest(&self) -> String {
174        self.digest.clone()
175    }
176
177    /// Recompute the identity digest and require it to equal the pinned one.
178    pub fn verify_identity(&self, identity: &DomainModelIdentity) -> Result<(), WorldRefError> {
179        identity.validate()?;
180        let actual = identity.canonical_digest();
181        if actual == self.digest {
182            Ok(())
183        } else {
184            Err(WorldRefError::DigestMismatch {
185                expected: self.digest.clone(),
186                actual,
187            })
188        }
189    }
190}
191
192impl FromStr for WorldRef {
193    type Err = WorldRefError;
194    fn from_str(s: &str) -> Result<Self, Self::Err> {
195        let rest = s
196            .strip_prefix(WORLD_PREFIX)
197            .ok_or_else(|| WorldRefError::Malformed(format!("'{s}' lacks the 'world:' scheme")))?;
198        let (name, digest) = rest.split_once('@').ok_or_else(|| {
199            WorldRefError::Malformed(format!("'{s}' has no @sha256:<digest> (is it an alias?)"))
200        })?;
201        let name: WorldName = name.parse()?;
202        validate_digest(digest)?;
203        Ok(Self {
204            name,
205            digest: digest.to_string(),
206        })
207    }
208}
209
210impl fmt::Display for WorldRef {
211    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212        write!(f, "{WORLD_PREFIX}{}@{}", self.name, self.digest)
213    }
214}
215
216impl Serialize for WorldRef {
217    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
218        s.serialize_str(&self.to_string())
219    }
220}
221
222impl<'de> Deserialize<'de> for WorldRef {
223    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
224        let text = String::deserialize(d)?;
225        text.parse().map_err(serde::de::Error::custom)
226    }
227}
228
229/// Mutable selector `world:<name>`. Never identity.
230#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
231pub struct WorldAlias(WorldName);
232
233impl WorldAlias {
234    pub fn name(&self) -> &WorldName {
235        &self.0
236    }
237}
238
239impl FromStr for WorldAlias {
240    type Err = WorldRefError;
241    fn from_str(s: &str) -> Result<Self, Self::Err> {
242        let rest = s
243            .strip_prefix(WORLD_PREFIX)
244            .ok_or_else(|| WorldRefError::Malformed(format!("'{s}' lacks the 'world:' scheme")))?;
245        if rest.contains('@') {
246            return Err(WorldRefError::Malformed(format!(
247                "'{s}' pins a digest; it is a world_ref, not an alias"
248            )));
249        }
250        Ok(Self(rest.parse()?))
251    }
252}
253
254impl fmt::Display for WorldAlias {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        write!(f, "{WORLD_PREFIX}{}", self.0)
257    }
258}
259
260/// Human-readable name, e.g. `GodSpeed Corporate World`. Presentation only.
261#[derive(Debug, Clone, PartialEq, Eq)]
262pub struct WorldLabel(String);
263
264impl WorldLabel {
265    pub fn new(text: &str) -> Result<Self, WorldRefError> {
266        let trimmed = text.trim();
267        if trimmed.is_empty() || trimmed.chars().count() > MAX_LABEL_LEN {
268            return Err(WorldRefError::InvalidLabel(
269                "must be 1..=200 characters after trimming".into(),
270            ));
271        }
272        if trimmed.chars().any(char::is_control) {
273            return Err(WorldRefError::InvalidLabel(
274                "contains control characters".into(),
275            ));
276        }
277        Ok(Self(trimmed.to_string()))
278    }
279
280    pub fn as_str(&self) -> &str {
281        &self.0
282    }
283}
284
285impl DomainModelIdentity {
286    /// Build the identity of a resolved model from its canonical document.
287    /// `content_hash` is the document's `self_hash`; the pack-set hash is the
288    /// document's (the empty pack set still hashes a fixed frame).
289    pub fn from_document(
290        doc: &CanonicalSemanticEnvelopeDocument,
291        registry_content_hash: Option<&str>,
292    ) -> Self {
293        Self {
294            identity_scheme_version: SUPPORTED_IDENTITY_SCHEME.to_string(),
295            producer: doc.producer.name.clone(),
296            producer_version: doc.producer.version.clone(),
297            language_schema_version: doc.inputs.language_schema_version.clone(),
298            compiler_interpretation_version: doc.envelope.compiler_interpretation_version.clone(),
299            canonicalization_version: doc.envelope.canonicalization_version.clone(),
300            source_set_hash: doc.inputs.source_set_hash.clone(),
301            content_hash: doc.self_hash.clone(),
302            semantic_closure_hash: doc.semantic_closure_hash.clone(),
303            semantic_pack_set_hash: Some(doc.inputs.semantic_pack_set_hash.clone()),
304            registry_content_hash: registry_content_hash.map(str::to_string),
305        }
306    }
307
308    /// Fail closed on an unsupported scheme or malformed hash fields.
309    pub fn validate(&self) -> Result<(), WorldRefError> {
310        if self.identity_scheme_version != SUPPORTED_IDENTITY_SCHEME {
311            return Err(WorldRefError::UnsupportedIdentityScheme(
312                self.identity_scheme_version.clone(),
313            ));
314        }
315        let required = [
316            ("source_set_hash", &self.source_set_hash),
317            ("content_hash", &self.content_hash),
318            ("semantic_closure_hash", &self.semantic_closure_hash),
319        ];
320        for (field, value) in required {
321            validate_digest(value)
322                .map_err(|e| WorldRefError::MalformedIdentity(format!("{field}: {e}")))?;
323        }
324        for (field, value) in [
325            ("semantic_pack_set_hash", &self.semantic_pack_set_hash),
326            ("registry_content_hash", &self.registry_content_hash),
327        ] {
328            if let Some(v) = value {
329                validate_digest(v)
330                    .map_err(|e| WorldRefError::MalformedIdentity(format!("{field}: {e}")))?;
331            }
332        }
333        Ok(())
334    }
335}
336
337/// In-memory catalog of verified, immutable worlds plus mutable aliases.
338/// Worlds are append-only: a registered revision is never replaced or removed,
339/// and alias retargeting only appends to history.
340#[derive(Debug, Default, Clone)]
341pub struct WorldCatalog {
342    worlds: BTreeMap<String, (WorldRef, DomainModelIdentity)>,
343    aliases: BTreeMap<WorldName, Vec<WorldRef>>,
344}
345
346impl WorldCatalog {
347    /// Verify and register a world. Idempotent for the same name and identity.
348    /// A digest has exactly one canonical name within a catalog.
349    pub fn register(
350        &mut self,
351        name: WorldName,
352        identity: DomainModelIdentity,
353    ) -> Result<WorldRef, WorldRefError> {
354        let world = WorldRef::from_identity(name, &identity)?;
355        if let Some((existing, _)) = self.worlds.get(&world.digest) {
356            if existing.name != world.name {
357                return Err(WorldRefError::NameConflict {
358                    digest: world.digest.clone(),
359                    existing: existing.name.to_string(),
360                    requested: world.name.to_string(),
361                });
362            }
363            return Ok(existing.clone());
364        }
365        self.worlds
366            .insert(world.digest.clone(), (world.clone(), identity));
367        Ok(world)
368    }
369
370    /// The registered identity for a reference; unknown references fail closed.
371    pub fn lookup(&self, world: &WorldRef) -> Result<&DomainModelIdentity, WorldRefError> {
372        match self.worlds.get(&world.digest) {
373            Some((registered, identity)) if registered.name == world.name => Ok(identity),
374            Some((registered, _)) => Err(WorldRefError::NameConflict {
375                digest: world.digest.clone(),
376                existing: registered.name.to_string(),
377                requested: world.name.to_string(),
378            }),
379            None => Err(WorldRefError::UnknownWorld(world.to_string())),
380        }
381    }
382
383    /// Known world and a presented identity that hashes to the pinned digest.
384    pub fn verify(
385        &self,
386        world: &WorldRef,
387        presented: &DomainModelIdentity,
388    ) -> Result<(), WorldRefError> {
389        self.lookup(world)?;
390        world.verify_identity(presented)
391    }
392
393    /// Point an alias at a registered world. Appends to the alias history.
394    pub fn retarget_alias(
395        &mut self,
396        alias: &WorldAlias,
397        target: &WorldRef,
398    ) -> Result<(), WorldRefError> {
399        self.lookup(target)?;
400        self.aliases
401            .entry(alias.0.clone())
402            .or_default()
403            .push(target.clone());
404        Ok(())
405    }
406
407    pub fn resolve_alias(&self, alias: &WorldAlias) -> Result<WorldRef, WorldRefError> {
408        self.aliases
409            .get(&alias.0)
410            .and_then(|history| history.last())
411            .cloned()
412            .ok_or_else(|| WorldRefError::UnknownAlias(alias.to_string()))
413    }
414
415    /// Every revision the alias has ever pointed at, oldest first.
416    pub fn alias_history(&self, alias: &WorldAlias) -> Vec<WorldRef> {
417        self.aliases.get(&alias.0).cloned().unwrap_or_default()
418    }
419
420    /// Resolve a selector to a known immutable [`WorldRef`] for consequential
421    /// use. Accepts a pinned `world:<name>@sha256:<digest>` (must be known) or
422    /// an alias `world:<name>` (must be known and is resolved now). Anything
423    /// else fails closed.
424    pub fn pin(&self, selector: &str) -> Result<WorldRef, WorldRefError> {
425        if selector.contains('@') {
426            let world: WorldRef = selector.parse()?;
427            self.lookup(&world)?;
428            Ok(world)
429        } else {
430            self.resolve_alias(&selector.parse::<WorldAlias>()?)
431        }
432    }
433}
434
435// ---- string/JSON entry points shared by the Python, TypeScript and WASM bindings ----
436//
437// Bindings call these and add no logic of their own.
438
439/// Resolve a source map and return its `DomainModelIdentity` as canonical JSON.
440pub fn domain_model_identity_json(
441    entry_logical_path: &str,
442    sources_json: &str,
443    registry_content_hash: Option<&str>,
444) -> Result<String, Vec<super::ApplicationDiagnostic>> {
445    let doc = super::resolve_semantic_envelope(entry_logical_path, sources_json)?;
446    let identity = DomainModelIdentity::from_document(&doc, registry_content_hash);
447    let value = serde_json::to_value(&identity).expect("DomainModelIdentity serializes");
448    Ok(crate::semantic_pack::canonical_json::canonical_json(&value))
449}
450
451fn identity_from_json(identity_json: &str) -> Result<DomainModelIdentity, WorldRefError> {
452    serde_json::from_str(identity_json)
453        .map_err(|e| WorldRefError::MalformedIdentity(format!("not a DomainModelIdentity: {e}")))
454}
455
456/// Mint the canonical `world:<name>@sha256:<digest>` text from identity JSON.
457pub fn world_ref_from_identity_json(
458    name: &str,
459    identity_json: &str,
460) -> Result<String, WorldRefError> {
461    let identity = identity_from_json(identity_json)?;
462    Ok(WorldRef::from_identity(name.parse()?, &identity)?.to_string())
463}
464
465/// Verify that identity JSON hashes to the digest pinned by a world_ref.
466pub fn verify_world_ref_json(world_ref: &str, identity_json: &str) -> Result<(), WorldRefError> {
467    let world: WorldRef = world_ref.parse()?;
468    world.verify_identity(&identity_from_json(identity_json)?)
469}
470
471/// Parse and return the canonical text of a world_ref (rejects anything else).
472pub fn canonical_world_ref(text: &str) -> Result<String, WorldRefError> {
473    Ok(text.parse::<WorldRef>()?.to_string())
474}