diff --git a/crates/ghostlight/src/controllers.rs b/crates/ghostlight/src/controllers.rs index 18d060c..735e6d0 100644 --- a/crates/ghostlight/src/controllers.rs +++ b/crates/ghostlight/src/controllers.rs @@ -6905,6 +6905,7 @@ mod tests { AffordanceSnapshot { id, entry: kernel_speak_entry(), + render_path: None, } } use crate::{ @@ -7285,6 +7286,7 @@ mod tests { last_acted_at: None, }; let snapshot = WorldSnapshot { + grammar: None, lens_weights: crate::tests::stock_weights(), world_id: opportunity.world_id, revision: opportunity.revision, @@ -7407,6 +7409,7 @@ mod tests { last_acted_at: None, }; let snapshot = WorldSnapshot { + grammar: None, lens_weights: crate::tests::stock_weights(), world_id: opportunity.world_id, revision: opportunity.revision, @@ -7672,6 +7675,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) @@ -7826,6 +7830,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) @@ -9071,6 +9076,7 @@ mod tests { last_acted_at: None, }; let snapshot = WorldSnapshot { + grammar: None, lens_weights: crate::tests::stock_weights(), world_id: opportunity.world_id, revision: opportunity.revision, @@ -9233,6 +9239,7 @@ mod tests { open: true, }; let snapshot = WorldSnapshot { + grammar: None, lens_weights: crate::tests::stock_weights(), world_id: opportunity.world_id, revision: opportunity.revision, @@ -9434,6 +9441,7 @@ mod tests { }], carries_speech: false, }, + render_path: None, }; let speak = speak_snapshot(AffordanceId::issue()); let granted = vec![carry.clone(), speak.clone()]; @@ -9734,6 +9742,7 @@ mod tests { affordance_ids: vec![speak_affordance], }; let snapshot = WorldSnapshot { + grammar: None, lens_weights: crate::tests::stock_weights(), world_id: opportunity.world_id, revision: opportunity.revision, @@ -10773,6 +10782,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) @@ -11386,6 +11396,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &owner_caller, ) @@ -11904,6 +11915,7 @@ mod tests { ]), }, }, + grammar: None, }, &authenticated, ) @@ -13582,6 +13594,7 @@ mod tests { evidence: Vec::new(), }, scale_intent, + grammar: None, }, &authenticated, ) @@ -14568,6 +14581,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) @@ -15116,6 +15130,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) @@ -15588,6 +15603,7 @@ mod tests { targets: BTreeMap::from([(SubjectKind::Person, target)]), jurisdictions: BTreeMap::from([(DraftHandle::new("sere"), 1000)]), }, + grammar: None, }, &authenticated, ) @@ -16503,6 +16519,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: intent, + grammar: None, }; let (mailbox, task) = WorldMailbox::open(directory.path().join("two-roots.cc")).unwrap(); @@ -18019,6 +18036,7 @@ mod tests { evidence: vec![ledger], }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) @@ -18547,6 +18565,7 @@ mod tests { evidence: vec![ledger], }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) diff --git a/crates/ghostlight/src/grammar.rs b/crates/ghostlight/src/grammar.rs new file mode 100644 index 0000000..f5eac43 --- /dev/null +++ b/crates/ghostlight/src/grammar.rs @@ -0,0 +1,168 @@ +//! The action grammar a world is bound to at creation. +//! +//! A grammar is the closed set of affordance kinds a world may declare, each +//! with its role signature and the one render path its acts take. The grammar's +//! home is the Aetheria repo; the kernel holds only this binding: the verbs it +//! enforces, and a content digest that names exactly which grammar that was. +//! The digest is derived here and nowhere else, so a binding cannot claim a +//! digest its verbs do not have. + +use crate::SubjectKind; +use crate::patch::{EntityKind, RefKind, RoleSpec}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; + +/// How an act of one verb reaches the player: filmed in the engine as a ship +/// action, or shown as Aetheria's portrait-and-choices conversation. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum RenderPath { + ShipAction, + Conversation, +} + +/// What a grammar role may be bound to, in the grammar's own vocabulary. Each +/// lowers to exactly one kernel `RefKind`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub enum GrammarReferentKind { + Person, + Faction, + Population, + Place, + Cargo, +} + +impl GrammarReferentKind { + fn ref_kind(self) -> RefKind { + match self { + Self::Person => RefKind::Subject(Some(SubjectKind::Person)), + Self::Faction => RefKind::Subject(Some(SubjectKind::Institution)), + Self::Population => RefKind::Subject(Some(SubjectKind::Population)), + Self::Place => RefKind::Entity(EntityKind::Place), + Self::Cargo => RefKind::Entity(EntityKind::Resource), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarRole { + pub role: String, + pub referent: GrammarReferentKind, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +pub struct GrammarVerb { + pub render_path: RenderPath, + /// In signature order: the order is part of the verb. + pub roles: Vec, +} + +impl GrammarVerb { + /// Whether a declared role list is this verb's signature: same names, same + /// referent kinds, same order. + pub(crate) fn admits_roles(&self, roles: &[RoleSpec]) -> bool { + self.roles.len() == roles.len() + && self + .roles + .iter() + .zip(roles) + .all(|(want, have)| want.role == have.role.0 && want.referent.ref_kind() == have.kind) + } +} + +#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)] +pub enum GrammarError { + #[error("grammar schema id is empty")] + EmptySchemaId, + #[error("grammar declares one verb kind twice")] + DuplicateVerb, + #[error("grammar digest does not match its verbs")] + DigestMismatch, +} + +/// Which grammar a world is bound to: its schema id, revision and content +/// digest. What a consumer reads; the verb table stays in the binding. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GrammarIdentity { + pub schema_id: String, + pub revision: u32, + pub digest: String, +} + +/// The grammar a world was created under. Immutable: the only constructor +/// derives the digest, and deserialisation re-derives it and refuses a mismatch. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(try_from = "RawBinding")] +pub struct GrammarBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +#[derive(Deserialize)] +struct RawBinding { + schema_id: String, + revision: u32, + digest: String, + verbs: BTreeMap, +} + +impl TryFrom for GrammarBinding { + type Error = GrammarError; + + fn try_from(raw: RawBinding) -> Result { + let bound = Self::new(raw.schema_id, raw.revision, raw.verbs)?; + if bound.digest != raw.digest { + return Err(GrammarError::DigestMismatch); + } + Ok(bound) + } +} + +impl GrammarBinding { + /// The one constructor. Verbs arrive in any order and are keyed by kind; + /// the digest is the sha256 of the canonical encoding of the kind-sorted + /// verbs, so the same verbs bind to the same digest however they were listed. + pub fn new( + schema_id: impl Into, + revision: u32, + verbs: impl IntoIterator, + ) -> Result { + let schema_id = schema_id.into(); + if schema_id.is_empty() { + return Err(GrammarError::EmptySchemaId); + } + let mut table = BTreeMap::new(); + for (kind, verb) in verbs { + if table.insert(kind, verb).is_some() { + return Err(GrammarError::DuplicateVerb); + } + } + let encoded = rmp_serde::to_vec_named(&table).expect("a verb table encodes"); + let digest = format!("sha256:{:x}", Sha256::digest(encoded)); + Ok(Self { + schema_id, + revision, + digest, + verbs: table, + }) + } + + pub fn identity(&self) -> GrammarIdentity { + GrammarIdentity { + schema_id: self.schema_id.clone(), + revision: self.revision, + digest: self.digest.clone(), + } + } + + pub(crate) fn verb(&self, kind: &str) -> Option<&GrammarVerb> { + self.verbs.get(kind) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/ghostlight/src/grammar/tests.rs b/crates/ghostlight/src/grammar/tests.rs new file mode 100644 index 0000000..3153699 --- /dev/null +++ b/crates/ghostlight/src/grammar/tests.rs @@ -0,0 +1,512 @@ +use super::*; +use crate::patch::{ + AffordanceDeclaration, AffordanceKindName, Declaration, DraftHandle, EntityKind, Mismatch, + OutcomeBand, Role, RoleSpec, +}; +use crate::tests::{auth_principal, command, creation, owner}; +use crate::{ + CallerId, CommandBody, CommandId, CreateWorld, KernelError, SubjectKind, SubmitReceipt, + WorldId, WorldKernel, WorldPatch, +}; + +fn verb(path: RenderPath, roles: &[(&str, GrammarReferentKind)]) -> GrammarVerb { + GrammarVerb { + render_path: path, + roles: roles + .iter() + .map(|(role, referent)| GrammarRole { + role: (*role).into(), + referent: *referent, + }) + .collect(), + } +} + +/// What the fixture world's genesis needs: the kernel speak entry and the +/// fixture's own `convene`. Anything else a test wants is added to it. +fn grammar_with(extra: &[(&str, GrammarVerb)]) -> GrammarBinding { + let mut verbs = vec![ + ("speak".to_owned(), verb(RenderPath::Conversation, &[])), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + verbs.extend( + extra + .iter() + .map(|(kind, v)| ((*kind).to_owned(), v.clone())), + ); + GrammarBinding::new("aetheria.grammar", 3, verbs).unwrap() +} + +fn bound(grammar: Option, title: &str) -> CreateWorld { + let mut world = creation(CommandId::new(), title); + world.grammar = grammar; + world +} + +fn declare(handle: &str, kind: &str, roles: &[(&str, RefKind)]) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: roles + .iter() + .map(|(role, kind)| RoleSpec { + role: Role((*role).into()), + kind: *kind, + }) + .collect(), + preconditions: Vec::new(), + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: false, + }) +} + +fn patch_of(declarations: Vec) -> WorldPatch { + WorldPatch { + declarations, + operations: Vec::new(), + evidence: Vec::new(), + } +} + +fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::PatchRejected(set)) => set, + Err(other) => panic!("expected a patch refusal, got {other:?}"), + Ok(_) => panic!("expected a patch refusal, the command was admitted"), + } +} + +/// Each call gets its own store path: kernels are created, not reopened. +fn create(world: CreateWorld) -> (tempfile::TempDir, Result) { + let directory = tempfile::tempdir().unwrap(); + let result = WorldKernel::create( + directory.path().join("world.cc"), + world, + &auth_principal(owner()), + ) + .map(|(kernel, _)| kernel); + (directory, result) +} + +fn admit(kernel: &mut WorldKernel, patch: WorldPatch) -> Result { + let snapshot = kernel.snapshot().unwrap(); + kernel.submit( + command( + &snapshot, + CommandId::new(), + CallerId::Principal(owner()), + CommandBody::AdmitPatch { + answers: None, + patch, + }, + ), + &auth_principal(owner()), + ) +} + +fn person() -> RefKind { + RefKind::Subject(Some(SubjectKind::Person)) +} + +fn place() -> RefKind { + RefKind::Entity(EntityKind::Place) +} + +fn not_in_grammar(handle: &str) -> Vec { + vec![Mismatch::AffordanceKindNotInGrammar { + handle: DraftHandle::new(handle), + }] +} + +fn disagrees(handle: &str) -> Vec { + vec![Mismatch::AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle::new(handle), + }] +} + +#[test] +fn grammar_world_refuses_an_affordance_kind_outside_the_grammar() { + // Genesis: a declared kind the binding lacks is refused. + let mut world = bound(Some(grammar_with(&[])), "Outside"); + world.patch.declarations.push(declare("wave", "wave", &[])); + assert_eq!(rejected(create(world).1), not_in_grammar("wave")); + + // A later AdmitPatch: the same kind is refused, and a verb the grammar + // does carry is admitted by the same path. + let extra = [("hail", verb(RenderPath::Conversation, &[]))]; + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Outside")); + let mut kernel = kernel.unwrap(); + assert_eq!( + rejected(admit( + &mut kernel, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); + let receipt = admit(&mut kernel, patch_of(vec![declare("hail", "hail", &[])])).unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); +} + +#[test] +fn grammar_world_refuses_a_role_signature_the_grammar_does_not_carry() { + let extra = [ + ( + "meet", + verb( + RenderPath::ShipAction, + &[ + ("who", GrammarReferentKind::Person), + ("where_", GrammarReferentKind::Place), + ], + ), + ), + ("hail", verb(RenderPath::Conversation, &[])), + ]; + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Signatures")); + let mut kernel = kernel.unwrap(); + for (label, roles) in [ + ("renamed", vec![("whom", person()), ("where_", place())]), + ("rekinded", vec![("who", person()), ("where_", person())]), + ("swapped", vec![("where_", place()), ("who", person())]), + ("short", vec![("who", person())]), + ( + "long", + vec![("who", person()), ("where_", place()), ("why", person())], + ), + ] { + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare(label, "meet", &roles)]), + )); + assert_eq!(set, disagrees(label), "{label}"); + } + // A role on a verb the grammar declares with none. + let set = rejected(admit( + &mut kernel, + patch_of(vec![declare("hail", "hail", &[("who", person())])]), + )); + assert_eq!(set, disagrees("hail")); + // The exact signature is admitted. + let receipt = admit( + &mut kernel, + patch_of(vec![declare( + "meet", + "meet", + &[("who", person()), ("where_", place())], + )]), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); +} + +#[test] +fn each_grammar_referent_kind_admits_exactly_its_own_kernel_kind() { + let kinds = [ + (GrammarReferentKind::Person, person()), + ( + GrammarReferentKind::Faction, + RefKind::Subject(Some(SubjectKind::Institution)), + ), + ( + GrammarReferentKind::Population, + RefKind::Subject(Some(SubjectKind::Population)), + ), + (GrammarReferentKind::Place, place()), + ( + GrammarReferentKind::Cargo, + RefKind::Entity(EntityKind::Resource), + ), + ]; + for (referent, own) in &kinds { + let extra = [("act", verb(RenderPath::ShipAction, &[("with", *referent)]))]; + for (_, offered) in &kinds { + let (_dir, kernel) = create(bound(Some(grammar_with(&extra)), "Referents")); + let mut kernel = kernel.unwrap(); + let result = admit( + &mut kernel, + patch_of(vec![declare("act", "act", &[("with", *offered)])]), + ); + if offered == own { + assert!( + matches!(result, Ok(SubmitReceipt::Applied(_))), + "{referent:?} refused its own kind" + ); + } else { + assert_eq!( + rejected(result), + disagrees("act"), + "{referent:?} admitted {offered:?}" + ); + } + } + } +} + +#[test] +fn grammar_world_without_speak_refuses_the_kernel_speak_grant() { + let no_speak = GrammarBinding::new( + "aetheria.grammar", + 1, + [("convene".to_owned(), verb(RenderPath::Conversation, &[]))], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(no_speak), "Mute")).1), + not_in_grammar(crate::patch::KERNEL_SPEAK_HANDLE) + ); + + // The kernel entry is held to the signature as well as the kind. + let loud = GrammarBinding::new( + "aetheria.grammar", + 1, + [ + ( + "speak".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("convene".to_owned(), verb(RenderPath::Conversation, &[])), + ], + ) + .unwrap(); + assert_eq!( + rejected(create(bound(Some(loud), "Loud")).1), + disagrees(crate::patch::KERNEL_SPEAK_HANDLE) + ); +} + +#[test] +fn unbound_world_keeps_the_open_catalog() { + let mut world = bound(None, "Open"); + world + .patch + .declarations + .push(declare("wave", "wave", &[("at", person())])); + let (_dir, kernel) = create(world); + let mut kernel = kernel.unwrap(); + let receipt = admit( + &mut kernel, + patch_of(vec![declare("beacon", "beacon", &[])]), + ) + .unwrap(); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let snapshot = kernel.snapshot().unwrap(); + assert!(snapshot.grammar.is_none()); + assert!(snapshot.affordances.len() >= 4); + assert!(snapshot.affordances.iter().all(|a| a.render_path.is_none())); + + // The state row of a world with no grammar carries no grammar key, so its + // bytes and digests are those of a world written before grammars existed. + let encoded = rmp_serde::to_vec_named(&kernel.state).unwrap(); + let keys: std::collections::BTreeMap = + rmp_serde::from_slice(&encoded).unwrap(); + assert!(!keys.contains_key("grammar")); + assert!(keys.contains_key("brief")); +} + +#[test] +fn a_bound_world_reports_its_grammar_and_derives_render_paths_from_it() { + let extra = [("dock", verb(RenderPath::ShipAction, &[]))]; + let grammar = grammar_with(&extra); + let identity = grammar.identity(); + let (_dir, kernel) = create(bound(Some(grammar), "Reports")); + let mut kernel = kernel.unwrap(); + admit(&mut kernel, patch_of(vec![declare("dock", "dock", &[])])).unwrap(); + let snapshot = kernel.snapshot().unwrap(); + assert_eq!(snapshot.grammar, Some(identity)); + let path_of = |kind: &str| { + snapshot + .affordances + .iter() + .find(|a| a.entry.kind.0 == kind) + .unwrap_or_else(|| panic!("{kind} is in the catalog")) + .render_path + }; + assert_eq!(path_of("dock"), Some(RenderPath::ShipAction)); + assert_eq!(path_of("convene"), Some(RenderPath::Conversation)); + assert_eq!(path_of("speak"), Some(RenderPath::Conversation)); +} + +#[test] +fn a_reopened_grammar_world_still_holds_its_grammar() { + let grammar = grammar_with(&[]); + let identity = grammar.identity(); + let (directory, kernel) = create(bound(Some(grammar), "Reopened")); + let kernel = kernel.unwrap(); + let world_id = kernel.snapshot().unwrap().world_id; + drop(kernel); + let mut reopened = WorldKernel::open(directory.path().join("world.cc"), world_id).unwrap(); + assert_eq!(reopened.snapshot().unwrap().grammar, Some(identity)); + assert_eq!( + rejected(admit( + &mut reopened, + patch_of(vec![declare("wave", "wave", &[])]) + )), + not_in_grammar("wave") + ); +} + +#[test] +fn the_bound_grammar_is_part_of_the_world_state_digest() { + let (_dir, kernel) = create(bound(Some(grammar_with(&[])), "Digested")); + let kernel = kernel.unwrap(); + let bound_digest = crate::state_digest(&kernel.state).unwrap(); + let mut state = kernel.state.clone(); + state.grammar = None; + let open_digest = crate::state_digest(&state).unwrap(); + state.grammar = Some(grammar_with(&[("dock", verb(RenderPath::ShipAction, &[]))])); + let other_digest = crate::state_digest(&state).unwrap(); + assert_ne!(bound_digest, open_digest); + assert_ne!(bound_digest, other_digest); +} + +#[test] +fn grammar_digest_is_derived_and_order_free() { + let forward = [ + ("alpha".to_owned(), verb(RenderPath::ShipAction, &[])), + ( + "beta".to_owned(), + verb( + RenderPath::Conversation, + &[("to", GrammarReferentKind::Person)], + ), + ), + ("gamma".to_owned(), verb(RenderPath::Conversation, &[])), + ]; + let mut reversed = forward.clone(); + reversed.reverse(); + let a = GrammarBinding::new("aetheria.grammar", 1, forward.clone()).unwrap(); + let b = GrammarBinding::new("aetheria.grammar", 1, reversed).unwrap(); + assert_eq!(a.digest, b.digest); + assert_eq!(a, b); + + // Content-derived: each part of a verb moves the digest. + let changed = |edit: &dyn Fn(&mut Vec<(String, GrammarVerb)>)| { + let mut verbs = forward.to_vec(); + edit(&mut verbs); + GrammarBinding::new("aetheria.grammar", 1, verbs) + .unwrap() + .digest + }; + assert_ne!( + a.digest, + changed(&|v| v[0].1.render_path = RenderPath::Conversation) + ); + assert_ne!( + a.digest, + changed(&|v| v[1].1.roles[0].role = "from".into()) + ); + assert_ne!( + a.digest, + changed(&|v| v[1].1.roles[0].referent = GrammarReferentKind::Faction) + ); + assert_ne!(a.digest, changed(&|v| v[2].0 = "delta".into())); + assert_ne!( + a.digest, + changed(&|v| { + v.pop(); + }) + ); + // Role order is part of a verb. + let ordered = |roles: &[(&str, GrammarReferentKind)]| { + GrammarBinding::new( + "g", + 1, + [("meet".to_owned(), verb(RenderPath::ShipAction, roles))], + ) + .unwrap() + .digest + }; + assert_ne!( + ordered(&[ + ("a", GrammarReferentKind::Person), + ("b", GrammarReferentKind::Place) + ]), + ordered(&[ + ("b", GrammarReferentKind::Place), + ("a", GrammarReferentKind::Person) + ]) + ); + // The identity reads the same fields back. + let identity = a.identity(); + assert_eq!(identity.schema_id, "aetheria.grammar"); + assert_eq!(identity.revision, 1); + assert_eq!(identity.digest, a.digest); +} + +#[test] +fn a_tampered_grammar_digest_fails_to_deserialise() { + let binding = grammar_with(&[]); + let value = serde_json::to_value(&binding).unwrap(); + // Untouched: the round trip holds. + let back: GrammarBinding = serde_json::from_value(value.clone()).unwrap(); + assert_eq!(back, binding); + + // A digest the verbs do not have. + let mut forged = value.clone(); + forged["digest"] = "sha256:00".into(); + assert!(serde_json::from_value::(forged.clone()).is_err()); + + // A verb edited under the digest it already had. + let mut edited = value; + edited["verbs"]["convene"]["render_path"] = "ship_action".into(); + assert!(serde_json::from_value::(edited).is_err()); + + // The named encoding a state row uses refuses it the same way. + let bytes = rmp_serde::to_vec_named(&forged).unwrap(); + assert!(rmp_serde::from_slice::(&bytes).is_err()); +} + +#[test] +fn a_grammar_names_each_verb_once_and_has_a_schema() { + assert_eq!( + GrammarBinding::new("", 1, Vec::new()).unwrap_err(), + GrammarError::EmptySchemaId + ); + assert_eq!( + GrammarBinding::new( + "g", + 1, + [ + ("hail".to_owned(), verb(RenderPath::Conversation, &[])), + ("hail".to_owned(), verb(RenderPath::ShipAction, &[])), + ] + ) + .unwrap_err(), + GrammarError::DuplicateVerb + ); +} + +/// The fixture world was written by the code at base 367e2eb, which has no +/// grammar field anywhere. Reopening it must reproduce the digests that code +/// recorded. +#[test] +fn existing_world_reopens_with_unchanged_digests() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + std::fs::write(&path, include_bytes!("../../tests/fixtures/base_world.cc")).unwrap(); + let world_id: WorldId = + serde_json::from_str(include_str!("../../tests/fixtures/base_world.id").trim()).unwrap(); + let kernel = WorldKernel::open(&path, world_id).expect("a base-written world reopens"); + let snapshot = kernel.snapshot().unwrap(); + let recorded = include_str!("../../tests/fixtures/base_world.digests"); + let mut lines = recorded.lines(); + assert_eq!(snapshot.revision.to_string(), lines.next().unwrap()); + assert_eq!(snapshot.state_digest, lines.next().unwrap()); + assert_eq!( + snapshot.last_commit_digest.as_deref(), + Some(lines.next().unwrap()) + ); + assert!(snapshot.grammar.is_none()); + // Its state still derives the recorded digest from its bytes. + assert_eq!( + crate::state_digest(&kernel.state).unwrap(), + snapshot.state_digest + ); +} diff --git a/crates/ghostlight/src/journal.rs b/crates/ghostlight/src/journal.rs index 982a807..e617f5c 100644 --- a/crates/ghostlight/src/journal.rs +++ b/crates/ghostlight/src/journal.rs @@ -1109,6 +1109,7 @@ mod tests { position: None, }), scale_intent: WorldScaleIntentRef::default(), + grammar: None, }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); @@ -1192,6 +1193,7 @@ mod tests { position: None, }), scale_intent: WorldScaleIntentRef::default(), + grammar: None, }; let (mut kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let snapshot = kernel.snapshot().unwrap(); @@ -1757,6 +1759,7 @@ mod tests { position: None, }), scale_intent: WorldScaleIntentRef::default(), + grammar: None, }; let (kernel, _) = WorldKernel::create(&path, creation, &authenticated).unwrap(); let mut forged_head = kernel.state.clone(); diff --git a/crates/ghostlight/src/lib.rs b/crates/ghostlight/src/lib.rs index 68a60f5..3da046a 100644 --- a/crates/ghostlight/src/lib.rs +++ b/crates/ghostlight/src/lib.rs @@ -61,6 +61,7 @@ mod consumer; mod controllers; mod cover; mod elaboration; +mod grammar; mod journal; mod lens; mod local_inference; @@ -95,6 +96,10 @@ pub use elaboration::{ ElaborationCheckpoint, ElaborationRunner, ElaboratorSession, EvidenceError, EvidenceQuery, EvidenceReceipt, EvidenceSource, SeedCheckpoint, SeedOutcome, SeedRunner, select_row, }; +pub use grammar::{ + GrammarBinding, GrammarError, GrammarIdentity, GrammarReferentKind, GrammarRole, GrammarVerb, + RenderPath, +}; pub use lens::{Lens, LensWeights}; pub use local_inference::{DEFAULT_LOCAL_MODEL_PREFIX, LocalBinding}; #[cfg(feature = "test-support")] @@ -425,6 +430,10 @@ struct CreateWorld { /// The world's flavor as genesis writes it. `SetLensWeights` may replace /// it later; this command carries what the world began with. lens_weights: LensWeights, + /// The grammar the world is bound to for its whole life, or none for an + /// open-catalog world. Authored here and nowhere else: genesis installs it. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option, } /// Unattributed creation intent. World ingress derives ownership, controller @@ -828,6 +837,11 @@ struct WorldState { /// Authored at creation and never mutated; the one prose the world says /// about itself, projected as guidance to every lane. brief: String, + /// Bound by genesis and never written again; absent from a world with no + /// grammar, so such a world's state and digests are what they were before + /// grammars existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + grammar: Option, draft_approvals: BTreeSet, subjects: BTreeMap, entities: BTreeMap, @@ -1135,6 +1149,9 @@ pub(crate) struct ForumSnapshot { pub struct AffordanceSnapshot { pub id: AffordanceId, pub entry: Affordance, + /// Derived from the world's grammar by this entry's kind; none when the + /// world has no grammar. + pub render_path: Option, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -1197,6 +1214,8 @@ pub struct WorldSnapshot { pub owner: PrincipalId, pub title: String, pub brief: String, + /// The bound grammar's identity; none for a world with an open catalog. + pub grammar: Option, pub draft_approvals: BTreeSet, pub required_approvers: BTreeSet, pub subjects: Vec, @@ -1425,7 +1444,12 @@ fn prepare_creation( // derived ID, so it is minted before resolution rather than by it. let world_id = WorldId::issue(); let resolved = patch::resolve_patch( - &WorldState::empty(world_id, input.owner.clone(), title.clone()), + &WorldState::empty( + world_id, + input.owner.clone(), + title.clone(), + input.grammar.clone(), + ), input.id, &input.patch, Some(&input.scale_intent), @@ -1896,7 +1920,12 @@ impl WorldState { /// The world before any structure. Genesis resolves its own patch against /// this value, so the genesis lane and `AdmitPatch` share one resolver /// signature instead of hand-passing empty partitions. - fn empty(world_id: WorldId, owner: PrincipalId, title: String) -> Self { + fn empty( + world_id: WorldId, + owner: PrincipalId, + title: String, + grammar: Option, + ) -> Self { Self { schema: STATE_SCHEMA.into(), world_id, @@ -1905,6 +1934,7 @@ impl WorldState { owner, title, brief: String::new(), + grammar, draft_approvals: BTreeSet::new(), subjects: BTreeMap::new(), entities: BTreeMap::new(), @@ -1962,7 +1992,7 @@ impl WorldState { // The same re-derive-and-compare that `apply_committed_command` runs for // every other command. Deterministic allocation is what lets one // equality replace a field-by-field binding zip. - let mut state = Self::empty(world_id, owner.clone(), title.clone()); + let mut state = Self::empty(world_id, owner.clone(), title.clone(), command.grammar.clone()); state.brief = brief.clone(); let expected = patch::resolve_patch( &state, @@ -4079,6 +4109,7 @@ fn snapshot(state: &WorldState) -> Result { owner: state.owner.clone(), title: state.title.clone(), brief: state.brief.clone(), + grammar: state.grammar.as_ref().map(GrammarBinding::identity), draft_approvals: state.draft_approvals.clone(), required_approvers: required_approvers(state), subjects, @@ -4088,6 +4119,11 @@ fn snapshot(state: &WorldState) -> Result { .map(|(affordance_id, entry)| AffordanceSnapshot { id: *affordance_id, entry: entry.clone(), + render_path: state + .grammar + .as_ref() + .and_then(|grammar| grammar.verb(&entry.kind.0)) + .map(|verb| verb.render_path), }) .collect(), places, @@ -5545,6 +5581,7 @@ mod tests { }, scale_intent: WorldScaleIntentRef::default(), lens_weights: stock_weights(), + grammar: None, } } @@ -15162,7 +15199,7 @@ mod clock_tests { })); let title = normalize_title(&input.title).unwrap(); let resolved = patch::resolve_patch( - &WorldState::empty(world_id, input.owner.clone(), title.clone()), + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), input.id, &input.patch, Some(&input.scale_intent), @@ -15191,7 +15228,7 @@ mod clock_tests { }); let title = normalize_title(&input.title).unwrap(); let resolved = patch::resolve_patch( - &WorldState::empty(world_id, input.owner.clone(), title.clone()), + &WorldState::empty(world_id, input.owner.clone(), title.clone(), None), input.id, &input.patch, Some(&input.scale_intent), diff --git a/crates/ghostlight/src/mailbox.rs b/crates/ghostlight/src/mailbox.rs index 3593348..93f239d 100644 --- a/crates/ghostlight/src/mailbox.rs +++ b/crates/ghostlight/src/mailbox.rs @@ -189,6 +189,7 @@ impl WorldMailbox { }, scale_intent, lens_weights: input.lens_weights, + grammar: None, }, AuthenticatedCaller::verified_principal(principal_id), ) @@ -988,6 +989,7 @@ mod tests { fn creation(id: CommandId, title: &str) -> CreateWorld { CreateWorld { lens_weights: crate::tests::stock_weights(), + grammar: None, id, owner: PrincipalId::new("owner"), title: title.into(), @@ -1425,6 +1427,7 @@ mod tests { evidence: Vec::new(), }, scale_intent: WorldScaleIntentRef::default(), + grammar: None, }, &authenticated, ) diff --git a/crates/ghostlight/src/patch.rs b/crates/ghostlight/src/patch.rs index abac54f..c67432e 100644 --- a/crates/ghostlight/src/patch.rs +++ b/crates/ghostlight/src/patch.rs @@ -1350,6 +1350,16 @@ pub enum Mismatch { EmptyLabel { handle: DraftHandle, }, + /// The world is bound to a grammar and this affordance's kind is not one of + /// its verbs. + AffordanceKindNotInGrammar { + handle: DraftHandle, + }, + /// The kind is a verb of the bound grammar, but the declared roles are not + /// its signature (name, referent kind or order). + AffordanceRolesDisagreeWithGrammar { + handle: DraftHandle, + }, UnresolvedDraft { site: Site, referent: DraftHandle, @@ -3061,6 +3071,31 @@ fn candidate_set( } } +/// A bound grammar is the whole catalog: a kind it lacks, or a role signature +/// it does not carry, is refused. A world with no grammar is not checked. +fn check_against_grammar( + state: &super::WorldState, + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + mismatches: &mut Vec, +) { + let Some(grammar) = &state.grammar else { + return; + }; + match grammar.verb(&kind.0) { + None => mismatches.push(Mismatch::AffordanceKindNotInGrammar { + handle: handle.clone(), + }), + Some(verb) if !verb.admits_roles(roles) => { + mismatches.push(Mismatch::AffordanceRolesDisagreeWithGrammar { + handle: handle.clone(), + }) + } + Some(_) => {} + } +} + /// The one resolution owner for every admission lane: declarations, references, /// topology admission, and operation preconditions. Every check runs against the /// complete candidate graph — what the world already holds plus what this patch @@ -3084,6 +3119,11 @@ pub(super) fn resolve_patch( if admits_human { index.insert(speak_handle.clone(), RefKind::Affordance); } + if admits_human { + // The kernel-built entry is held to the grammar like any declaration. + let speak = kernel_speak_entry(); + check_against_grammar(state, &speak_handle, &speak.kind, &speak.roles, &mut mismatches); + } let mut kind_names: BTreeSet = state .affordance_catalog .values() @@ -3143,6 +3183,13 @@ pub(super) fn resolve_patch( affordance.carries_speech, &mut mismatches, ); + check_against_grammar( + state, + &affordance.handle, + &affordance.kind, + &affordance.roles, + &mut mismatches, + ); if !kind_names.insert(affordance.kind.clone()) { mismatches.push(Mismatch::DuplicateAffordanceKind { handle: affordance.handle.clone(), diff --git a/crates/ghostlight/src/sdk_inference.rs b/crates/ghostlight/src/sdk_inference.rs index 68a88a1..8319da5 100644 --- a/crates/ghostlight/src/sdk_inference.rs +++ b/crates/ghostlight/src/sdk_inference.rs @@ -1274,6 +1274,7 @@ mod tests { let granted = vec![AffordanceSnapshot { id: AffordanceId::issue(), entry: kernel_speak_entry(), + render_path: None, }]; let speak = granted[0].entry.kind.0.clone(); let link = ScriptedLink::new(vec![ @@ -1990,6 +1991,7 @@ mod tests { let granted = vec![AffordanceSnapshot { id: AffordanceId::issue(), entry: kernel_speak_entry(), + render_path: None, }]; let mut emitted: Vec<(String, String)> = patch_tools() .into_iter() diff --git a/crates/ghostlight/src/table.rs b/crates/ghostlight/src/table.rs index 054285c..66e0882 100644 --- a/crates/ghostlight/src/table.rs +++ b/crates/ghostlight/src/table.rs @@ -2489,6 +2489,7 @@ mod tests { outcome_bands: Vec::new(), carries_speech: false, }, + render_path: None, } } diff --git a/crates/ghostlight/tests/fixtures/base_world.cc b/crates/ghostlight/tests/fixtures/base_world.cc new file mode 100644 index 0000000..d4c8ead Binary files /dev/null and b/crates/ghostlight/tests/fixtures/base_world.cc differ diff --git a/crates/ghostlight/tests/fixtures/base_world.digests b/crates/ghostlight/tests/fixtures/base_world.digests new file mode 100644 index 0000000..ab9edc3 --- /dev/null +++ b/crates/ghostlight/tests/fixtures/base_world.digests @@ -0,0 +1,3 @@ +3 +sha256:b706f57cb417603366a1f47a5dd099fbf68bfecc5b2e8d61d281630791d1d76d +sha256:2039956a26c3d5b073d101e5898ac5a60a9eb63a3b93f447b2d8f78ef4caf979 diff --git a/crates/ghostlight/tests/fixtures/base_world.id b/crates/ghostlight/tests/fixtures/base_world.id new file mode 100644 index 0000000..f23316a --- /dev/null +++ b/crates/ghostlight/tests/fixtures/base_world.id @@ -0,0 +1 @@ +"a534b32a-4d00-429c-bf6c-ce1d55385380"