From b8ff18282e81b5f7a7a6a652f637949f64c3766c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Fri, 4 Sep 2026 23:02:53 +0200 Subject: [PATCH] Give the world Knowledge, Channels, and Fact standing Speech stops being a broadcast event everyone can read and becomes a typed claim that some subjects hold. Three partitions carry it: `facts` (one row per `EntityKind::Fact`, write-once), `channels` (one row per `EntityKind::Channel`), and `knowledge`, which is the sole owner of who-heard-what. `state.events` is demoted from perception surface to causal record. The events log records what was done; the knowledge partition decides what a subject may act on and what its projection may contain. `WorldSnapshot.events` is deleted outright, so `controllers.rs` structurally cannot read an unscoped log; the human operator's story feed moves to `WorldKernel::operator_log`, reached through its own mailbox request and passed to `eve::authenticated_surface` beside the snapshot. Two pure functions state reach and nothing else does: `audience` (who is in earshot) and `fan_out` (who gains knowledge from one telling). Co-location is the actor's exact place; a channel's `Reach::Place` is the subtree, through the same `covers_place` walk a jurisdiction uses. A telling never overwrites a holder and `Believed` is fixed by the kernel, so no speaker owns another subject's credence. The kernel Speak entry gains its real shape: one `CanBroadcast` precondition, so an unplaced subject fails with `NoAudience` rather than being heard by everyone. A `carries_speech` entry must name exactly one audience, and `exercise` prepends two kernel-owned operations no slot or band can influence: `AssertClaim` mints the fact, `Communicate` fans it out. That makes `action::exercise` the second `derive_id` call site; the "only `admit_resolved` allocates" rule is rewritten rather than amended. The kernel does not compare two statements. There is no dedup, no interning, no contradiction check, and no similarity. Deception is a `Claimed` fact standing beside its asserter's own knowledge of a different one, and the meaning of that gap belongs to a reader. `STATE_SCHEMA`/`COMMIT_SCHEMA` become `.knowledge.v1` and the controller work schema moves to v5; a pre-pass store is refused with no migration path. Co-Authored-By: Claude Opus 5 --- crates/ghostlight-dungeon/src/eve.rs | 15 +- crates/ghostlight-dungeon/src/runtime.rs | 34 +- crates/ghostlight-dungeon/src/world/action.rs | 193 +- .../src/world/controllers.rs | 334 ++- .../ghostlight-dungeon/src/world/journal.rs | 116 +- .../ghostlight-dungeon/src/world/mailbox.rs | 120 +- crates/ghostlight-dungeon/src/world/mod.rs | 1846 ++++++++++++++++- crates/ghostlight-dungeon/src/world/patch.rs | 1035 ++++++++- 8 files changed, 3422 insertions(+), 271 deletions(-) diff --git a/crates/ghostlight-dungeon/src/eve.rs b/crates/ghostlight-dungeon/src/eve.rs index 907ad29..43bf63a 100644 --- a/crates/ghostlight-dungeon/src/eve.rs +++ b/crates/ghostlight-dungeon/src/eve.rs @@ -2,7 +2,7 @@ use crate::{ mesh::{COMMAND_BOUNDARY, COMMAND_RESULT_SCHEMA, PROVIDER_ID, SURFACE_ID}, - world::{ControllerMode, WorldPhase, WorldSnapshot}, + world::{ControllerMode, OperatorEvent, WorldPhase, WorldSnapshot}, }; use anyhow::{Context, bail}; use chrono::{DateTime, Utc}; @@ -100,9 +100,13 @@ fn anonymous_surface_at(version: u64) -> Value { ) } +/// `operator_log` arrives beside the snapshot rather than inside it: the story +/// feed is the human operator's surface, and no subject-facing lane may reach an +/// unscoped event log. pub(crate) fn authenticated_surface( account: &str, snapshot: Option<&WorldSnapshot>, + operator_log: &[OperatorEvent], ) -> anyhow::Result { let version = surface_version(snapshot); let mut children = vec![json!({ @@ -182,7 +186,7 @@ pub(crate) fn authenticated_surface( "children":[{ "id":"world.summary.body", "kind":"text", - "props":{"value":format!("{} subject(s), {} committed event(s)", world.subjects.len(), world.events.len())}, + "props":{"value":format!("{} subject(s), {} committed event(s)", world.subjects.len(), operator_log.len())}, "children":[] }] })); @@ -228,11 +232,10 @@ pub(crate) fn authenticated_surface( } } WorldPhase::Active => { - let story = world - .events + let story = operator_log .iter() .filter_map(|event| { - event.invocation.speech.as_ref().map(|text| { + event.speech.as_ref().map(|text| { json!({ "id":format!("world.event.{}", event.revision), "kind":"text", @@ -533,7 +536,7 @@ mod tests { #[test] fn empty_authenticated_surface_has_create_without_session_zero() { - let surface = authenticated_surface("sha256:owner", None).unwrap(); + let surface = authenticated_surface("sha256:owner", None, &[]).unwrap(); let encoded = serde_json::to_string(&surface).unwrap(); assert!(encoded.contains("world.create")); assert!(encoded.contains("narrative_persona_label")); diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index f314c84..8e4d35f 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -13,8 +13,8 @@ use crate::{ AffordanceId, CommandBody, CommandId, ControllerError, ControllerModels, ControllerPendingReason, ControllerRunner, ControllerWorkCustody, CreateWorldIntent, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun, - OperationalRun, PrincipalCommandIntent, PrincipalId, SubmissionDisposition, SubmitReceipt, - Utterance, WorldMailbox, WorldSnapshot, + OperationalRun, PrincipalCommandIntent, PrincipalId, Statement, SubmissionDisposition, + SubmitReceipt, WorldMailbox, WorldSnapshot, }, }; use anyhow::{Context, bail, ensure}; @@ -442,9 +442,11 @@ async fn eve_surface( let Some(principal) = authenticated_principal(&headers, &state).await else { return Json(eve::anonymous_surface()).into_response(); }; - match current_world(&state).await.and_then(|snapshot| { - eve::authenticated_surface(principal.account_subject_hash(), snapshot.as_ref()) - }) { + match current_operator_view(&state) + .await + .and_then(|(snapshot, log)| { + eve::authenticated_surface(principal.account_subject_hash(), snapshot.as_ref(), &log) + }) { Ok(surface) => Json(surface).into_response(), Err(error) => ( StatusCode::INTERNAL_SERVER_ERROR, @@ -1241,7 +1243,7 @@ async fn execute_world( affordance: payload.affordance_id, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new(payload.text).ok_or_else(|| { + speech: Some(Statement::new(payload.text).ok_or_else(|| { RuntimeCommandError::Payload("spoken text is not canonical".into()) })?), }, @@ -1305,6 +1307,21 @@ async fn current_world(state: &AppState) -> anyhow::Result } } +/// The two halves of the operator surface, fetched together: the projection of +/// world state, and the story feed the human reads. The feed is deliberately not +/// a snapshot field, so no controller lane can reach it. +async fn current_operator_view( + state: &AppState, +) -> anyhow::Result<(Option, Vec)> { + let snapshot = current_world(state).await?; + let log = match state.world.operator_log().await { + Ok(log) => log, + Err(MailboxError::Kernel(KernelError::WorldNotCreated)) => Vec::new(), + Err(error) => return Err(error.into()), + }; + Ok((snapshot, log)) +} + async fn publish_projection(state: &AppState) -> anyhow::Result { let snapshot = current_world(state).await?; let version = eve::surface_version(snapshot.as_ref()); @@ -2181,8 +2198,9 @@ mod tests { ) .await; assert_eq!(spoken["sourceVersion"], 4); - let world = current_world(&fixture.state).await.unwrap().unwrap(); - assert_eq!(world.events.len(), 1); + let (world, log) = current_operator_view(&fixture.state).await.unwrap(); + assert!(world.is_some()); + assert_eq!(log.len(), 1); } #[tokio::test] diff --git a/crates/ghostlight-dungeon/src/world/action.rs b/crates/ghostlight-dungeon/src/world/action.rs index c8f8139..758f9c9 100644 --- a/crates/ghostlight-dungeon/src/world/action.rs +++ b/crates/ghostlight-dungeon/src/world/action.rs @@ -7,8 +7,8 @@ //! draws a band, and the draw goes through the one `digest()` owner. use super::patch::{ - self, Affordance, Bounds, ComponentOpKind, Cost, Precondition, Quantity, RefKind, Role, - WorldPatch, + self, Affordance, Audience, AudienceSpec, Bounds, ComponentOpKind, Cost, Precondition, + Quantity, RefKind, Role, WorldPatch, }; use super::{ AffordanceId, AuthorityGrant, AuthorityTarget, CommandId, DecisionEvent, DecisionInvocation, @@ -89,6 +89,23 @@ pub(crate) enum ActionMismatch { DelegationNotMonotone { slot: usize, }, + /// The actor does not hold the bound fact at the required confidence. A + /// re-appraisal that lowered its own confidence while the proposal was in + /// flight arrives here rather than as a rebind: confidence is admission-only. + FactUnknown { + precondition: usize, + }, + /// The actor has no audience at all: unplaced for co-location, or outside a + /// channel it does not control. + NoAudience { + precondition: usize, + }, + /// The addressed subject is not inside that audience. A target that walked + /// out of the room while the proposal was in flight arrives here: the + /// preimage holds what the actor *is*, not the world it reaches. + CannotReach { + precondition: usize, + }, } /// The band draw's whole preimage. Five fields, none of them from the @@ -136,7 +153,7 @@ pub(super) fn exercise( let band = select_band(state, command_id, granted.id, entry)?; let operations = lower(entry, band, invocation, &bindings)?; - let effects = if operations.is_empty() { + let mut effects = if operations.is_empty() { Vec::new() } else { // The same resolver, the same per-operation preconditions, the same @@ -154,6 +171,41 @@ pub(super) fn exercise( .operations }; + // The speech lowering: kernel-owned, not a slot, and unreachable by any + // proposer, band, or effect ceiling. The audience comes from the entry's one + // speech precondition, so a world's `whisper` and `proclaim` lower through + // the same two operations with a different audience and the kernel learns no + // genre. Addressing does not narrow the fan-out: a voice fills its audience. + let speech = match (&invocation.speech, entry.carries_speech) { + (Some(statement), true) => { + let fact = EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + state.world_id, + command_id, + &patch::DraftHandle::new(SPEECH_HANDLE), + Some(SPEECH_INDEX), + )); + let to = speech_audience(entry, &bindings)?; + effects.splice( + 0..0, + [ + patch::ResolvedOp::AssertClaim { + fact, + statement: statement.clone(), + by: actor, + }, + patch::ResolvedOp::Communicate { + speaker: actor, + fact, + to, + }, + ], + ); + Some(fact) + } + _ => None, + }; + let revision = state .revision .checked_add(1) @@ -163,12 +215,42 @@ pub(super) fn exercise( revision, scope: current.scope, controller_id: current.controller_id, - invocation: invocation.clone(), + affordance: granted.id, + speech, band, effects, }) } +/// The synthetic handle every minted claim allocates under. It is synthesized +/// only in Active and declarations are Draft-only, so no world-declared handle +/// can collide with it. +const SPEECH_HANDLE: &str = "ghostlight.speech"; + +/// The speech index, passed as `derive_id`'s discriminator. It is `0` for every +/// invocation because one invocation carries one utterance; it exists so a later +/// multi-utterance turn needs no second allocation idiom. +const SPEECH_INDEX: &str = "0"; + +/// The audience a speech-carrying entry names. The declaration validator already +/// refused an entry with none (`SpeechWithoutAudience`) or two +/// (`AmbiguousSpeechAudience`), so anything else here is a corrupt catalog. +fn speech_audience( + entry: &Affordance, + bindings: &BTreeMap, +) -> Result { + entry + .preconditions + .iter() + .find_map(|precondition| match precondition { + Precondition::CanBroadcast { via } | Precondition::CanReach { via, .. } => { + bound_audience(via, bindings) + } + _ => None, + }) + .ok_or_else(|| KernelError::Invariant("a speech-carrying entry names no audience".into())) +} + /// Stage 2. The acting subject is never a declared role: the kernel binds the /// reserved name `actor` to it and refuses an invocation that tries to. A /// binding that happens to name the actor through a declared role is legal and @@ -328,10 +410,61 @@ fn check_preconditions( }); } } + Precondition::Knows { fact, at_least } => { + let Some(Target::Entity(entity_id)) = bindings.get(fact).copied() else { + continue; + }; + if !state + .knowledge + .get(&actor) + .and_then(|held| held.get(&entity_id)) + .is_some_and(|held| held.confidence >= *at_least) + { + rejections.push(ActionMismatch::FactUnknown { + precondition: index, + }); + } + } + Precondition::CanBroadcast { via } => { + let Some(audience) = bound_audience(via, bindings) else { + continue; + }; + if !super::audience(state, actor, &audience).contains(&actor) { + rejections.push(ActionMismatch::NoAudience { + precondition: index, + }); + } + } + Precondition::CanReach { subject, via } => { + let Some(Target::Subject(target)) = bindings.get(subject).copied() else { + continue; + }; + let Some(audience) = bound_audience(via, bindings) else { + continue; + }; + if !super::audience(state, actor, &audience).contains(&target) { + rejections.push(ActionMismatch::CannotReach { + precondition: index, + }); + } + } } } } +/// The catalog's role indirection lowered to the canonical audience: the entry +/// names a role, the invoker binds a channel to it, and every reader of reach +/// sees one shape. `None` means the role is unbound, which stage 2 already named. +fn bound_audience(via: &AudienceSpec, bindings: &BTreeMap) -> Option { + match via { + AudienceSpec::Colocated => Some(Audience::Colocated), + AudienceSpec::Channel(role) => match bindings.get(role).copied() { + Some(Target::Entity(entity_id)) => Some(Audience::Channel(entity_id)), + _ => None, + }, + } +} + /// Stage 4, beside the ceilings: an authority a slot would grant or revoke /// must not exceed the actor's own. For a grant this is the monotonicity /// envelope — no holder mints authority it does not itself hold. For a @@ -506,7 +639,7 @@ fn check_proposals( rejections.push(ActionMismatch::SlotNotProposed { slot }); } } - // `Utterance` is serde-transparent, so a value that arrived through + // `Statement` is serde-transparent, so a value that arrived through // deserialization rather than through the constructor is re-checked here // rather than trusted. match (&invocation.speech, entry.carries_speech) { @@ -703,6 +836,18 @@ fn lower( institution: subject(0)?, office: office.clone(), }, + ComponentOpKind::AcquireKnowledge { confidence } => { + patch::ComponentOp::AcquireKnowledge { + subject: subject(0)?, + fact: entity(1)?, + source: patch::AuthoredSource::Witnessed, + confidence: *confidence, + } + } + ComponentOpKind::Forget => patch::ComponentOp::Forget { + subject: subject(0)?, + fact: entity(1)?, + }, }); } Ok(operations) @@ -724,7 +869,7 @@ mod tests { }; use crate::world::{ AffordanceKindName, AuthenticatedCaller, CallerId, CommandBody, Declaration, EntityKind, - ProposedEffect, RoleBinding, SubmitReceipt, Utterance, WorldEffect, WorldKernel, + ProposedEffect, RoleBinding, Statement, SubmitReceipt, WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, }; use std::collections::BTreeSet; @@ -1083,7 +1228,7 @@ mod tests { let directory = tempfile::tempdir().unwrap(); let bench = bench(directory.path(), "Speech"); let mut spoken_carry = bench.carry(1, bench.yard); - spoken_carry.speech = Some(Utterance::new("Take it.").unwrap()); + spoken_carry.speech = Some(Statement::new("Take it.").unwrap()); assert_eq!( bench.rejections(&spoken_carry), vec![ActionMismatch::SpeechNotCarried] @@ -1101,9 +1246,9 @@ mod tests { vec![ActionMismatch::SpeechRequired] ); - // `Utterance` is serde-transparent, so a value that arrived without the + // `Statement` is serde-transparent, so a value that arrived without the // constructor is re-checked here rather than trusted. - silent_speak.speech = Some(serde_json::from_str::("\" \"").unwrap()); + silent_speak.speech = Some(serde_json::from_str::("\" \"").unwrap()); assert_eq!( bench.rejections(&silent_speak), vec![ActionMismatch::EmptySpeech] @@ -1354,13 +1499,8 @@ mod tests { let bench = bench(directory.path(), "ForgedAction"); let opportunity = bench.clerk_opportunity(); let command_id = CommandId::issue(); - let honest = draw_once( - &bench.kernel.state, - command_id, - &opportunity, - &bench.carry(2, bench.yard), - ) - .unwrap(); + let invocation = bench.carry(2, bench.yard); + let honest = draw_once(&bench.kernel.state, command_id, &opportunity, &invocation).unwrap(); let caller = CallerId::Controller(opportunity.controller_id); for forged in [ @@ -1385,6 +1525,7 @@ mod tests { &caller, &WorldEffect::DecisionExercised { opportunity: opportunity.clone(), + invocation: invocation.clone(), event: forged, }, ) @@ -1401,6 +1542,7 @@ mod tests { &caller, &WorldEffect::DecisionExercised { opportunity, + invocation: invocation.clone(), event: honest, }, ) @@ -1434,7 +1576,7 @@ mod tests { affordance: speak, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("I open the door.").unwrap()), + speech: Some(Statement::new("I open the door.").unwrap()), }, }, ), @@ -1444,9 +1586,10 @@ mod tests { assert!(matches!(receipt, SubmitReceipt::Applied(_))); let event = kernel.state.events.last().unwrap(); assert_eq!(event.band, 0); - assert!(event.effects.is_empty()); + // The two the speech lowering prepends, and nothing from a slot. + assert_eq!(event.effects.len(), 2); assert_eq!( - event.invocation.speech.as_ref().map(Utterance::as_str), + crate::world::tests::spoken(&kernel.state, event), Some("I open the door.") ); assert_eq!(kernel.state.holdings, holdings); @@ -1483,7 +1626,7 @@ mod tests { kind: &str, bindings: Vec, proposed: Vec, - speech: Option, + speech: Option, ) -> DecisionInvocation { DecisionInvocation { affordance: affordance_named(&self.active, kind), @@ -1773,7 +1916,9 @@ mod tests { role: Role("actor".into()), kind: RefKind::Subject(None), }], - preconditions: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], effect_slots: Vec::new(), outcome_bands: vec![OutcomeBand { weight: 1, @@ -1962,7 +2107,7 @@ mod tests { "petition", Vec::new(), Vec::new(), - Some(Utterance::new("The tithe was taken twice.").unwrap()), + Some(Statement::new("The tithe was taken twice.").unwrap()), ); assert_eq!( bench.rejected_as(bench.civic.outsider, &petition), @@ -1980,9 +2125,9 @@ mod tests { .events .last() .expect("the committed event"); - assert!(event.effects.is_empty()); + assert_eq!(event.effects.len(), 2); assert_eq!( - event.invocation.speech.as_ref().map(Utterance::as_str), + crate::world::tests::spoken(&bench.kernel.state, event), Some("The tithe was taken twice.") ); diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 4ef42d5..59b3315 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -7,11 +7,11 @@ //! affordance fields. use crate::world::{ - AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt, + AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt, Confidence, ControllerMode, Cost, DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId, - EntityId, EntityKind, KernelError, Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, - Quantity, RefKind, RoleBinding, SubjectId, SubjectSnapshot, SubmitReceipt, Target, Utterance, - WorldMailbox, WorldSnapshot, + EntityId, EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, + Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, RoleBinding, + Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, WorldMailbox, WorldSnapshot, }; use async_trait::async_trait; use chrono::Utc; @@ -46,8 +46,8 @@ const MAX_CONNECTOR_FRAME_BYTES: usize = 1_052_672; const REQUEST_EXPIRY: Duration = Duration::from_secs(300); const TOOL_STEP_BUDGET: usize = 4; const PERSONA_WORD_BUDGET: usize = 180; -const CONTROLLER_WORK_ROW: &str = "controller_work.v4"; -const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v4"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v5"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v5"; /// The Interpreter's byte-span capture tool. It is not the generated `speak` /// affordance tool: one captures an utterance out of preserved prose, the other @@ -2607,7 +2607,8 @@ impl SelectedDecision { "offices_held": Self::typed_offices(&self.subject.offices_held), "offices_granted": Self::typed_offices(&self.subject.offices_granted), "redress": self.typed_redress(), - "visible_events": self.typed_visible_events(), + "knowledge": self.typed_knowledge(), + "channels": self.typed_channels(), })) .map_err(|error| ControllerError::Serialization(error.to_string())) } @@ -2740,53 +2741,77 @@ impl SelectedDecision { } fn visible_stimulus(&self) -> Result { - serde_json::to_string_pretty(&self.projector_visible_events()?) + serde_json::to_string_pretty(&self.projector_knowledge()) .map_err(|error| ControllerError::Serialization(error.to_string())) } - /// Only spoken events. What one subject perceives of another's action is a - /// `Knowledge` question and has no component yet; rendering every action - /// here would decide that every subject perceives everything. - fn typed_visible_events(&self) -> Vec { - self.snapshot - .events + /// The acting subject's own knowledge, and nothing else. A subject perceives + /// a speech act if and only if it holds `Knowledge` of that act's fact, so + /// this is a renderer over one kernel-derived field rather than a walk that + /// decides reach a second time. Confidence reaches the Projector as prose + /// uncertainty, which makes the prompt's instruction a description of the + /// surface instead of its enforcement. + fn projector_knowledge(&self) -> Vec { + self.subject + .knowledge .iter() - .filter_map(|event| { - event.invocation.speech.as_ref().map(|text| { - json!({ - "revision": event.revision, - "speaker_subject_id": event.scope.subject_id, - "text": text.as_str(), - }) + .map(|entry| { + json!({ + "speaker": self.speaker_label(entry), + "certainty": entry.confidence, + "text": entry.statement.as_str(), }) }) .collect() } - fn projector_visible_events(&self) -> Result, ControllerError> { - self.snapshot - .events + /// Attribution comes from the listener's own knowledge, never from an event + /// scope: a subject that holds a fact it was never told sees the statement + /// with no speaker, because it knows the thing and not the telling. A label + /// is resolved only for a subject that spoke to this one. + fn speaker_label(&self, entry: &KnowledgeSnapshot) -> Value { + match entry.source { + KnowledgeSource::Told { by, .. } => self + .snapshot + .subjects + .iter() + .find(|subject| subject.id == by) + .map_or(Value::Null, |subject| Value::String(subject.label.clone())), + KnowledgeSource::Witnessed | KnowledgeSource::Evidenced => Value::Null, + } + } + + fn typed_knowledge(&self) -> Vec { + self.subject + .knowledge .iter() - .filter_map(|event| event.invocation.speech.as_ref().map(|text| (event, text))) - .map(|(event, text)| { - let speaker = self - .snapshot - .subjects - .iter() - .find(|subject| subject.id == event.scope.subject_id) - .map(|subject| subject.label.as_str()) - .ok_or_else(|| { - ControllerError::Serialization( - "visible event speaker is absent from the canonical snapshot".into(), - ) - })?; - Ok(json!({ - "speaker": speaker, - "text": text.as_str(), - })) + .map(|entry| { + json!({ + "fact": entry.fact, + "statement": entry.statement.as_str(), + "standing": match entry.standing { + FactStandingView::Canonical => json!({"standing": "canonical"}), + FactStandingView::Claimed { by } => { + json!({"standing": "claimed", "by": by}) + } + }, + "confidence": entry.confidence, + "source": entry.source, + "spoken_at": entry.spoken_at, + }) }) .collect() } + + /// Only the channels this subject controls, by id. Who else is in reach is a + /// question about other subjects, so no reach set is carried. + fn typed_channels(&self) -> Vec { + self.subject + .controls + .iter() + .map(|channel| json!({"id": channel})) + .collect() + } } /// The narrative lane speaks and does nothing else, so it finds its entry by @@ -2799,7 +2824,7 @@ fn speak_invocation( .iter() .find(|entry| entry.entry.kind.0 == SPEAK_KIND) .ok_or(ControllerError::SpeakUnavailable)?; - let speech = Utterance::new(text).ok_or_else(|| { + let speech = Statement::new(text).ok_or_else(|| { ControllerError::Serialization("Persona proposal is not canonical utterance text".into()) })?; Ok(DecisionInvocation { @@ -3672,7 +3697,7 @@ fn decode_catalog_call( .get("text") .and_then(Value::as_str) .ok_or_else(|| "`text` is missing or not a string".to_owned())?; - Some(Utterance::new(text).ok_or_else(|| "`text` is not canonical".to_owned())?) + Some(Statement::new(text).ok_or_else(|| "`text` is not canonical".to_owned())?) } else { None }; @@ -3745,7 +3770,7 @@ mod tests { } use crate::world::{ AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, ControllerId, CreateWorld, - DecisionScope, Declaration, DraftHandle, EventId, NewController, PrincipalId, ScopeDigest, + DecisionScope, Declaration, DraftHandle, NewController, PrincipalId, ScopeDigest, SubjectDeclaration, SubjectKind, WorldId, WorldPatch, WorldPhase, }; use std::{ @@ -3910,6 +3935,10 @@ mod tests { controller_mode: ControllerMode::NarrativePersona, affordance_ids: vec![speak_affordance], }; + // Mara was told. Iris also holds a fact of her own that Mara was never + // told, and no surface of Mara's may carry it. + let heard = EntityId::issue(); + let unheard = EntityId::issue(); let actor = SubjectSnapshot { id: actor_id, label: "Mara at the rain gate".into(), @@ -3926,6 +3955,18 @@ mod tests { offices_held: Vec::new(), offices_granted: Vec::new(), redress: Vec::new(), + knowledge: vec![KnowledgeSnapshot { + fact: heard, + statement: Statement::new("The lower hinge is flooding.").unwrap(), + standing: FactStandingView::Claimed { by: speaker_id }, + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speaker_id, + via: None, + }, + spoken_at: Some(40), + }], + controls: BTreeSet::new(), }; let speaker = SubjectSnapshot { id: speaker_id, @@ -3943,6 +3984,15 @@ mod tests { offices_held: Vec::new(), offices_granted: Vec::new(), redress: Vec::new(), + knowledge: vec![KnowledgeSnapshot { + fact: unheard, + statement: Statement::new("The tollhouse ledger is short.").unwrap(), + standing: FactStandingView::Canonical, + confidence: Confidence::Certain, + source: KnowledgeSource::Witnessed, + spoken_at: None, + }], + controls: BTreeSet::new(), }; let snapshot = WorldSnapshot { world_id: opportunity.world_id, @@ -3957,22 +4007,6 @@ mod tests { places: Vec::new(), resources: Vec::new(), routes: Vec::new(), - events: vec![crate::world::DecisionEvent { - id: EventId::for_command(CommandId::new()), - revision: 40, - scope: DecisionScope { - subject_id: speaker_id, - }, - controller_id: speaker_controller, - invocation: DecisionInvocation { - affordance: AffordanceId::issue(), - bindings: Vec::new(), - proposed: Vec::new(), - speech: Some(Utterance::new("The lower hinge is flooding.").unwrap()), - }, - band: 0, - effects: Vec::new(), - }], opportunities: vec![opportunity.clone()], state_digest: "sha256:projector-must-not-see-this-digest".into(), last_commit_digest: Some("sha256:projector-must-not-see-the-commit".into()), @@ -4003,14 +4037,112 @@ mod tests { ); } assert!(projector_surface.contains("Mara at the rain gate")); + // The speaker's label is resolved because Mara was told by her, and the + // statement appears because Mara holds it. Iris's own unheard fact does + // not: a subject's view carries its own knowledge and no one else's. assert!(projector_surface.contains("Iris in the tollhouse")); assert!(projector_surface.contains("The lower hinge is flooding.")); + assert!(!projector_surface.contains("The tollhouse ledger is short.")); let operational_surface = selected.typed_view().unwrap(); assert!(operational_surface.contains("state_digest")); - assert!(operational_surface.contains("speaker_subject_id")); + assert!(operational_surface.contains("The lower hinge is flooding.")); + assert!(!operational_surface.contains("The tollhouse ledger is short.")); } + /// Verification 5, second half, over real committed state: a subject + /// perceives a speech act if and only if it holds `Knowledge` of that act's + /// fact. The speaker speaks in the hall; the listener perceives it, the + /// bystander one containment level down does not, the placeless stranger + /// does not, and no surface of any of the three carries the utterance bytes + /// except the listener's. + #[test] + fn a_subject_does_not_perceive_speech_it_was_not_in_reach_of() { + use crate::world::tests::{auth_principal, command, opportunity_for, owner, speech_world}; + use crate::world::{ + AuthenticatedCaller, DecisionInvocation, Role, RoleBinding, Statement, SubmitReceipt, + Target, WorldKernel, + }; + + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + crate::world::tests::creation(CommandId::new(), "Leakage"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + let utterance = "The lower hinge is flooding tonight."; + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let receipt = kernel + .submit( + command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: DecisionInvocation { + affordance: speech.whisper, + bindings: vec![RoleBinding { + role: Role("target".into()), + target: Target::Subject(speech.listener), + }], + proposed: Vec::new(), + speech: Some(Statement::new(utterance).unwrap()), + }, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the whisper commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + + let snapshot = kernel.snapshot().unwrap(); + let surfaces = |subject_id| { + let subject = snapshot + .subjects + .iter() + .find(|subject| subject.id == subject_id) + .expect("the subject") + .clone(); + let opportunity = opportunity_for(&snapshot, subject_id); + let granted: Vec = snapshot + .affordances + .iter() + .filter(|entry| subject.affordances.contains(&entry.id)) + .cloned() + .collect(); + let selected = SelectedDecision { + snapshot: snapshot.clone(), + subject, + opportunity, + granted, + }; + format!( + "{}\n{}\n{}", + selected.projector_context().unwrap(), + selected.visible_stimulus().unwrap(), + selected.typed_view().unwrap(), + ) + }; + + assert!(surfaces(speech.listener).contains(utterance)); + for deaf in [speech.bystander, speech.stranger, speech.speaker] { + assert!( + !surfaces(deaf).contains(utterance), + "a subject perceived speech it holds no knowledge of" + ); + } + // The listener sees who told it, and nothing about anyone else's + // knowledge, holdings, or position. + let heard = surfaces(speech.listener); + assert!(heard.contains("The Hall Speaker")); + assert!(!heard.contains("The Yard Bystander")); + assert!(!heard.contains("The Placeless Stranger")); + } /// Soul falsification: the typed view carries the acting subject's own place /// and the routes incident to it, and no more. Another subject's position /// and a route that touches neither endpoint stay out of the surface. @@ -4066,6 +4198,8 @@ mod tests { offices_held: Vec::new(), offices_granted: Vec::new(), redress: Vec::new(), + knowledge: Vec::new(), + controls: BTreeSet::new(), }; let other = SubjectSnapshot { id: other_id, @@ -4083,6 +4217,8 @@ mod tests { offices_held: Vec::new(), offices_granted: Vec::new(), redress: Vec::new(), + knowledge: Vec::new(), + controls: BTreeSet::new(), }; let named_place = |id, label: &str| PlaceSnapshot { id, @@ -4118,7 +4254,6 @@ mod tests { named_route(first_edge, "The Yard Ramp", yard, road), named_route(second_edge, "The Vault Stair", road, vault), ], - events: Vec::new(), opportunities: vec![opportunity.clone()], state_digest: "sha256:state".into(), last_commit_digest: None, @@ -4660,14 +4795,25 @@ mod tests { owner: owner.clone(), title: "Controller Fixture".into(), patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("subject"), - label: "Subject".into(), - kind: SubjectKind::Person, - controller, - affordances: kernel_speak_grant(), - position: None, - })], + declarations: vec![ + Declaration::Entity(crate::world::EntityDeclaration { + handle: DraftHandle::new("commons"), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("subject"), + label: "Subject".into(), + kind: SubjectKind::Person, + controller, + affordances: kernel_speak_grant(), + // Speech needs a room to fill. + position: Some(crate::world::Ref::Draft(DraftHandle::new( + "commons", + ))), + }), + ], operations: Vec::new(), evidence: Vec::new(), }, @@ -4816,7 +4962,7 @@ mod tests { replayed.submission, SubmissionDisposition::PreviouslyConfirmed(_) )); - assert_eq!(mailbox.snapshot().await.unwrap().events.len(), 1); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); drop(runner); drop(mailbox); task.await.unwrap(); @@ -4875,7 +5021,7 @@ mod tests { replayed.submission, SubmissionDisposition::PreviouslyConfirmed(_) )); - assert_eq!(mailbox.snapshot().await.unwrap().events.len(), 1); + assert_eq!(mailbox.operator_log().await.unwrap().len(), 1); drop(runner); drop(mailbox); task.await.unwrap(); @@ -4943,7 +5089,7 @@ mod tests { assert_eq!(applied.resulting_revision, opportunity.revision + 1); let after = mailbox.snapshot().await.unwrap(); assert_eq!(after.revision, opportunity.revision + 1); - assert!(after.events.is_empty()); + assert!(mailbox.operator_log().await.unwrap().is_empty()); let refreshed = after.opportunities[0].clone(); assert_ne!(refreshed, opportunity); assert_eq!(refreshed.scope_digest, opportunity.scope_digest); @@ -5032,7 +5178,7 @@ mod tests { assert_eq!(applied.resulting_revision, opportunity.revision + 1); let after = mailbox.snapshot().await.unwrap(); assert_eq!(after.revision, opportunity.revision + 1); - assert!(after.events.is_empty()); + assert!(mailbox.operator_log().await.unwrap().is_empty()); let OperationalRun::Completed(replayed) = runner .run_operational(command_id, &opportunity) @@ -5204,16 +5350,9 @@ mod tests { derive_narrative_capture(turn, interpreter_prompt, completed).unwrap(), captured ); - let snapshot = mailbox.snapshot().await.unwrap(); - assert_eq!(snapshot.events.len(), 1); - assert_eq!( - snapshot.events[0] - .invocation - .speech - .as_ref() - .map(Utterance::as_str), - Some(speech) - ); + let log = mailbox.operator_log().await.unwrap(); + assert_eq!(log.len(), 1); + assert_eq!(log[0].speech.as_ref().map(Statement::as_str), Some(speech)); drop(reopened_terminal); drop(mailbox); @@ -5374,7 +5513,7 @@ mod tests { affordance: human_speak, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new(seed).unwrap()), + speech: Some(Statement::new(seed).unwrap()), }, }, }, @@ -5395,8 +5534,9 @@ mod tests { .unwrap(); snapshot = mailbox.snapshot().await.unwrap(); - assert!(snapshot.events.len() == 1); - let seeded_text = snapshot.events[0].invocation.speech.as_ref().unwrap(); + let log = mailbox.operator_log().await.unwrap(); + assert!(log.len() == 1); + let seeded_text = log[0].speech.as_ref().unwrap(); assert!(seeded_text.as_str().as_bytes() == seed.as_bytes()); let narrative_subject = snapshot .subjects @@ -5495,14 +5635,14 @@ mod tests { assert!(interpreter_speak.source_end_byte == narrative_span.end_byte); snapshot = mailbox.snapshot().await.unwrap(); - assert!(snapshot.events.len() == 2); + let log = mailbox.operator_log().await.unwrap(); + assert!(log.len() == 2); assert!(snapshot.revision == narrative_opportunity.revision + 1); - let narrative_event = snapshot - .events + let narrative_event = log .iter() - .find(|event| event.controller_id == narrative_subject.controller_id) + .find(|event| event.speaker == narrative_subject.id) .unwrap(); - let committed_narrative_speech = narrative_event.invocation.speech.as_ref().unwrap(); + let committed_narrative_speech = narrative_event.speech.as_ref().unwrap(); assert!(committed_narrative_speech.as_str().as_bytes() == narrative_speech.as_bytes()); let operational_subject = snapshot @@ -5567,14 +5707,14 @@ mod tests { assert!(operational_speak.text.as_bytes() == operational_speech.as_bytes()); snapshot = mailbox.snapshot().await.unwrap(); - assert!(snapshot.events.len() == 3); + let log = mailbox.operator_log().await.unwrap(); + assert!(log.len() == 3); assert!(snapshot.revision == operational_opportunity.revision + 1); - let operational_event = snapshot - .events + let operational_event = log .iter() - .find(|event| event.controller_id == operational_subject.controller_id) + .find(|event| event.speaker == operational_subject.id) .unwrap(); - let committed_operational_speech = operational_event.invocation.speech.as_ref().unwrap(); + let committed_operational_speech = operational_event.speech.as_ref().unwrap(); assert!(committed_operational_speech.as_str().as_bytes() == operational_speech.as_bytes()); drop(runner); diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index 1d39400..d7390a4 100644 --- a/crates/ghostlight-dungeon/src/world/journal.rs +++ b/crates/ghostlight-dungeon/src/world/journal.rs @@ -12,8 +12,8 @@ use std::{ }; use thiserror::Error; -const STATE_ROW: &str = "world_state.authority.v1"; -const COMMIT_ROW: &str = "world_commit.authority.v1"; +const STATE_ROW: &str = "world_state.knowledge.v1"; +const COMMIT_ROW: &str = "world_commit.knowledge.v1"; #[derive(Debug, Error)] pub(super) enum JournalError { @@ -527,6 +527,80 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { )); } } + // Facts, channels, and knowledge. The `facts`/`channels` bijections run both + // ways: a payload row without its entity, or an entity of that kind without + // its payload, is a referenceable half-thing. + for (entity_id, record) in &state.facts { + let standing_is_live = match &record.standing { + super::FactStanding::Canonical { evidence } => { + super::patch::is_canonical_text(evidence.text()) + } + super::FactStanding::Claimed { by } => state.subjects.contains_key(by), + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Fact) + || !super::patch::is_canonical_text(record.statement.as_str()) + || !standing_is_live + { + return Err(JournalError::Corrupt( + "a fact names no canonical entity, statement, or standing".into(), + )); + } + } + for (entity_id, record) in &state.channels { + let reach_is_live = match &record.reach { + super::Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + super::Reach::Place(place) => is_place(place), + }; + if !state + .entities + .get(entity_id) + .is_some_and(|entity| entity.kind == super::EntityKind::Channel) + || !reach_is_live + || !record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) + { + return Err(JournalError::Corrupt( + "a channel names no canonical entity, reach, or controller".into(), + )); + } + } + for (entity_id, entity) in &state.entities { + let paired = match entity.kind { + super::EntityKind::Fact => state.facts.contains_key(entity_id), + super::EntityKind::Channel => state.channels.contains_key(entity_id), + super::EntityKind::Place | super::EntityKind::Resource => true, + }; + if !paired { + return Err(JournalError::Corrupt( + "a fact or channel entity carries no payload row".into(), + )); + } + } + for (subject_id, held) in &state.knowledge { + let entry_is_live = |entry: &super::Knowledge| match entry.source { + super::KnowledgeSource::Told { by, via } => { + state.subjects.contains_key(&by) + && via.is_none_or(|channel| state.channels.contains_key(&channel)) + } + super::KnowledgeSource::Witnessed | super::KnowledgeSource::Evidenced => true, + }; + if !state.subjects.contains_key(subject_id) + || held.is_empty() + || held + .iter() + .any(|(fact, entry)| !state.facts.contains_key(fact) || !entry_is_live(entry)) + { + return Err(JournalError::Corrupt( + "knowledge does not name a canonical subject, fact, and source".into(), + )); + } + } // The civic subgraph, in the slot the deleted `authority_scope` check // occupied: a jurisdiction names live ground under a canonical kind, an // office sits on an institution and lends something to a person who holds @@ -663,6 +737,7 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { )); } let mut event_ids = BTreeSet::new(); + let mut claimed = BTreeSet::new(); let mut previous_event_revision = 0; for event in &state.events { let assignment = state @@ -671,8 +746,19 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { .ok_or_else(|| JournalError::Corrupt("event references an unknown scope".into()))?; let entry = state .affordance_catalog - .get(&event.invocation.affordance) + .get(&event.affordance) .ok_or_else(|| JournalError::Corrupt("event uses an unknown affordance".into()))?; + // A speech event names the claim it minted, and that claim is asserted + // by the acting subject and by no other event. + let speech_is_canonical = event.speech.is_none_or(|fact| { + claimed.insert(fact) + && state.facts.get(&fact).is_some_and(|record| { + record.standing + == super::FactStanding::Claimed { + by: event.scope.subject_id, + } + }) + }); if !event_ids.insert(event.id) || event.revision == 0 || event.revision > state.revision @@ -681,9 +767,15 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { || !state .affordance_grants .get(&event.scope) - .is_some_and(|granted| granted.contains(&event.invocation.affordance)) + .is_some_and(|granted| granted.contains(&event.affordance)) || event.band >= entry.outcome_bands.len() - || (entry.outcome_bands[event.band].effects.is_empty() && !event.effects.is_empty()) + || event.speech.is_some() != entry.carries_speech + // One lowered operation per band effect, plus the two the speech + // lowering prepends. + || entry.outcome_bands[event.band].effects.len() + + if event.speech.is_some() { 2 } else { 0 } + != event.effects.len() + || !speech_is_canonical { return Err(JournalError::Corrupt( "decision event is noncanonical or violates controller scope".into(), @@ -1758,7 +1850,12 @@ mod custody_tests { panic!("expected an applied invocation"); }; let accepted = kernel.snapshot().unwrap(); - let committed = accepted.events.last().expect("the committed event").clone(); + let committed = kernel + .state + .events + .last() + .expect("the committed event") + .clone(); assert!(!committed.effects.is_empty()); let world_id = accepted.world_id; drop(kernel); @@ -1766,12 +1863,7 @@ mod custody_tests { let mut reopened = WorldKernel::open(&path, world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), accepted); assert_eq!( - reopened - .snapshot() - .unwrap() - .events - .last() - .expect("the replayed event"), + reopened.state.events.last().expect("the replayed event"), &committed ); assert_eq!( diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index ee0043c..5921163 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -1,9 +1,9 @@ use super::{ AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration, - DraftHandle, KernelError, NewController, PrincipalCommandIntent, PrincipalId, - SubjectDeclaration, SubjectKind, SubmitReceipt, WorldKernel, WorldPatch, WorldSnapshot, - journal, patch::kernel_speak_grant, prepare_creation, + DraftHandle, EntityDeclaration, EntityKind, KernelError, NewController, OperatorEvent, + PrincipalCommandIntent, PrincipalId, Ref, SubjectDeclaration, SubjectKind, SubmitReceipt, + WorldKernel, WorldPatch, WorldSnapshot, journal, patch::kernel_speak_grant, prepare_creation, }; use crate::app_session::VerifiedPrincipalEvidence; use std::path::Path; @@ -11,6 +11,10 @@ use thiserror::Error; use tokio::sync::{mpsc, oneshot}; use tokio::task::JoinHandle; +/// The one place a world starts with, so its first subjects can hear each +/// other. A world that wants more declares them through the patch lane. +const GENESIS_PLACE: &str = "commons"; + const REQUEST_CAPACITY: usize = 32; #[derive(Clone, Debug)] @@ -48,6 +52,11 @@ enum Request { Snapshot { reply: oneshot::Sender>, }, + /// The human operator's story feed. Separate from `Snapshot` so no + /// controller lane can reach an unscoped event log. + OperatorLog { + reply: oneshot::Sender, KernelError>>, + }, ControllerReceipt { command_id: CommandId, opportunity: super::DecisionOpportunity, @@ -92,6 +101,9 @@ impl WorldMailbox { let principal_id = PrincipalId::new(principal.account_subject_hash()); // Ingress owns label normalization; the reducer only admits canonical // labels. + // A world needs a room. Co-located speech fills the place its speaker + // stands in, so ingress declares one and stands every genesis subject + // there rather than creating a world where nobody can be heard. let declare = |handle: &str, label: String, kind, controller| { Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(handle), @@ -99,17 +111,25 @@ impl WorldMailbox { kind, controller, affordances: kernel_speak_grant(), - position: None, + position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))), }) }; - let mut declarations = vec![declare( - "first-person", - input.human_subject_label, - SubjectKind::Person, - NewController::Human { - principal: principal_id.clone(), - }, - )]; + let mut declarations = vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(GENESIS_PLACE), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + declare( + "first-person", + input.human_subject_label, + SubjectKind::Person, + NewController::Human { + principal: principal_id.clone(), + }, + ), + ]; if let Some(label) = input.narrative_persona_label { declarations.push(declare( "narrative-persona", @@ -306,6 +326,21 @@ impl WorldMailbox { .await } + /// The human operator's story feed. It is not a perception surface, and no + /// controller lane calls it. + pub(crate) async fn operator_log(&self) -> Result, MailboxError> { + let (reply, response) = oneshot::channel(); + self.sender + .send(Request::OperatorLog { reply }) + .await + .map_err(|_| MailboxError::Unavailable)?; + + response + .await + .map_err(|_| MailboxError::Unavailable)? + .map_err(MailboxError::Kernel) + } + pub(crate) async fn snapshot(&self) -> Result { let (reply, response) = oneshot::channel(); self.sender @@ -472,6 +507,19 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver) return; } } + Request::OperatorLog { reply } => { + let result = match &owned { + OwnedWorld::Empty(_) => Err(KernelError::WorldNotCreated), + OwnedWorld::Live(kernel) => kernel.operator_log(), + }; + let owner_must_stop = result + .as_ref() + .is_err_and(KernelError::requires_owner_restart); + let _ = reply.send(result); + if owner_must_stop { + return; + } + } Request::ControllerReceipt { command_id, opportunity, @@ -535,16 +583,24 @@ mod tests { owner: PrincipalId::new("owner"), title: title.into(), patch: WorldPatch { - declarations: vec![Declaration::Subject(SubjectDeclaration { - handle: DraftHandle::new("operator"), - label: "Operator".into(), - kind: SubjectKind::Person, - controller: NewController::Human { - principal: PrincipalId::new("owner"), - }, - affordances: kernel_speak_grant(), - position: None, - })], + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(GENESIS_PLACE), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("operator"), + label: "Operator".into(), + kind: SubjectKind::Person, + controller: NewController::Human { + principal: PrincipalId::new("owner"), + }, + affordances: kernel_speak_grant(), + position: Some(Ref::Draft(DraftHandle::new(GENESIS_PLACE))), + }), + ], operations: Vec::new(), evidence: Vec::new(), }, @@ -627,7 +683,7 @@ mod tests { invalid .patch .declarations - .push(invalid.patch.declarations[0].clone()); + .push(invalid.patch.declarations[1].clone()); let Err(MailboxError::Kernel(KernelError::PatchRejected(rejected))) = mailbox.create_fixture(invalid, &authenticated).await else { @@ -919,6 +975,8 @@ mod tests { let (mailbox, _task) = WorldMailbox::open(directory.path().join("world.cc")).unwrap(); let owner = PrincipalId::new("owner"); let authenticated = authenticated_owner(); + // Two rooms, not one: a telling reaches its own room, so the bound + // subject must stand somewhere the unrelated speaker does not. let declare = |handle: &str, label: &str, controller: NewController| { Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(handle), @@ -926,7 +984,15 @@ mod tests { kind: SubjectKind::Person, controller, affordances: kernel_speak_grant(), - position: None, + position: Some(Ref::Draft(DraftHandle::new(format!("room-{handle}")))), + }) + }; + let room = |handle: &str| { + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(format!("room-{handle}")), + label: format!("The {handle} room"), + kind: EntityKind::Place, + container: None, }) }; let created = mailbox @@ -937,6 +1003,8 @@ mod tests { title: "Soul Stamping".into(), patch: WorldPatch { declarations: vec![ + room("witness"), + room("council"), declare("witness", "The Witness", NewController::NarrativePersona), declare("council", "The Council", NewController::OperationalAgent), ], @@ -980,7 +1048,7 @@ mod tests { affordance: opportunity.affordance_ids[0], bindings: Vec::new(), proposed: Vec::new(), - speech: Some(crate::world::Utterance::new(text).unwrap()), + speech: Some(crate::world::Statement::new(text).unwrap()), }; mailbox .submit_controller( @@ -1047,7 +1115,7 @@ mod tests { affordance: forged.affordance_ids[0], bindings: Vec::new(), proposed: Vec::new(), - speech: Some(crate::world::Utterance::new("Let me in.").unwrap()), + speech: Some(crate::world::Statement::new("Let me in.").unwrap()), }, ) .await; diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 63d33e2..8f9fa1d 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -20,14 +20,18 @@ pub(crate) use controllers::{ }; pub(crate) use mailbox::{MailboxError, WorldMailbox}; pub(crate) use patch::{ - AccessKind, Affordance, AffordanceKindName, AuthorityGrant, AuthorityKindName, AuthorityTarget, - Bounds, ComponentOpKind, Cost, Declaration, DependencyTarget, DraftHandle, EffectSlot, - EntityDeclaration, EntityKind, EvidenceRef, Forum, GrievanceKindName, Mismatch, Office, - OfficeName, OutcomeBand, PatchAnswer, Position, Precondition, Quantity, Ref, RefKind, Role, - RoleSpec, SubjectDeclaration, WorldPatch, + AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant, + AuthorityKindName, AuthorityTarget, Bounds, ChannelRecord, ComponentOpKind, Confidence, Cost, + Declaration, DependencyTarget, DraftHandle, EffectSlot, EntityDeclaration, EntityKind, + EvidenceRef, FactRecord, FactStanding, Forum, GrievanceKindName, Knowledge, KnowledgeSource, + Mismatch, Office, OfficeName, OutcomeBand, PatchAnswer, Position, Precondition, Quantity, + Reach, Ref, RefKind, Role, RoleSpec, Statement, SubjectDeclaration, WorldPatch, }; #[cfg(test)] -use patch::{AffordanceDeclaration, ComponentOp, DependencyRef, RouteDeclaration}; +use patch::{ + AffordanceDeclaration, AudienceRef, AudienceSpec, ChannelDeclaration, ComponentOp, + DependencyRef, FactDeclaration, FactStandingRef, ReachRef, RouteDeclaration, +}; #[cfg(test)] pub(crate) use patch::{AuthorityGrantRef, AuthorityTargetRef}; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; @@ -41,8 +45,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.authority.v1"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.authority.v1"; +pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.knowledge.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.knowledge.v1"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `-` pair (e.g. `foundation-v1`). Callers that publish a @@ -105,8 +109,11 @@ impl WorldId { } // Subject, entity, controller, and affordance IDs are derived, never drawn. -// `patch::derive_id` is the only allocator; these fixtures exist so tests can -// name an ID that no partition holds. +// `patch::derive_id` is the only allocator, and it is called from exactly two +// sites: `patch::resolve_patch` and `action::exercise`. The action lane mints +// exactly one referent per invocation — always an `EntityKind::Fact`, always +// `Claimed` by the acting subject, never caller-named, never any other kind. +// These fixtures exist so tests can name an ID that no partition holds. #[cfg(test)] impl SubjectId { fn issue() -> Self { @@ -305,27 +312,6 @@ pub(crate) struct RoleBinding { pub(crate) target: Target, } -/// Canonical nonempty text. Emptiness is one `ActionMismatch` inside the -/// complete set, not a kernel error of its own. -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(transparent)] -pub(crate) struct Utterance(String); - -impl Utterance { - pub(crate) fn new(value: impl Into) -> Option { - let value = value.into(); - if patch::is_canonical_text(&value) { - Some(Self(value)) - } else { - None - } - } - - pub(crate) fn as_str(&self) -> &str { - &self.0 - } -} - #[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "magnitude", content = "value", rename_all = "snake_case")] pub(crate) enum Magnitude { @@ -352,7 +338,9 @@ pub(crate) struct DecisionInvocation { pub(crate) bindings: Vec, /// Exactly one entry per slot in the entry, in any order. pub(crate) proposed: Vec, - pub(crate) speech: Option, + /// Command input, and the only place an utterance's text enters the kernel. + /// The committed home of those bytes is `facts[fact].statement`. + pub(crate) speech: Option, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -455,7 +443,13 @@ pub(crate) struct DecisionEvent { pub(crate) revision: u64, pub(crate) scope: DecisionScope, pub(crate) controller_id: ControllerId, - pub(crate) invocation: DecisionInvocation, + /// The entry exercised. The invocation itself lives on the effect: the + /// invocation is what the caller said, the event is what the world recorded. + pub(crate) affordance: AffordanceId, + /// The claim this act asserted, if it carried speech. Never the text: the + /// event is the world's record and every reader reads it, so it carries the + /// fact id and the statement lives in `facts` alone. + pub(crate) speech: Option, /// Index into the entry's `outcome_bands`. Re-derived and compared at apply /// and at replay, never trusted. pub(crate) band: usize, @@ -483,6 +477,17 @@ struct WorldState { holdings: BTreeMap>, /// What each subject depends on. Never empty for a present key. dependencies: BTreeMap>, + /// One row per `EntityKind::Fact` entity, and no orphan either way. Facts + /// are write-once: declaration and `AssertClaim` are the only writers, and + /// standing never changes after admission. + facts: BTreeMap, + /// One row per `EntityKind::Channel` entity, and no orphan either way. + channels: BTreeMap, + /// What each subject knows. The sole owner of who-heard-what: `events` + /// records what was done, and this decides what a subject may act on and + /// what its projection may contain. Never empty for a present key, and + /// absence is "knows nothing of it" — forgetting removes the key. + knowledge: BTreeMap>, /// What ground each subject has jurisdiction over, and under which /// world-declared kind. Never empty for a present key. No subject holds two /// grants of one kind over overlapping ground, so nothing ever arbitrates @@ -527,6 +532,10 @@ enum WorldEffect { WorldActivated, DecisionExercised { opportunity: DecisionOpportunity, + /// The command's own input, kept beside the event rather than inside it: + /// the invocation is what the caller said, the event is what the world + /// recorded, and only the first carries text. + invocation: DecisionInvocation, event: DecisionEvent, }, DecisionDeclined { @@ -603,6 +612,38 @@ pub(crate) struct SubjectSnapshot { /// View-only: the forums whose standing covers this subject, through the /// same covering predicate `HasStanding` uses. pub(crate) redress: Vec, + /// Every fact this subject holds, with the statement resolved. The sole + /// perception surface: a subject perceives a speech act if and only if it + /// holds `Knowledge` of that act's fact. Ordered by `spoken_at` then `fact`. + pub(crate) knowledge: Vec, + /// The channels this subject controls, by id. Not their reach: who else is + /// in earshot is a question about other subjects. + pub(crate) controls: BTreeSet, +} + +/// What a subject knows of one fact. `standing` carries no `EvidenceRef`: a +/// receipt is non-fictional provenance and never enters a subject-facing +/// surface, so a subject learns *that* a fact is canonical and never which +/// receipt admitted it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct KnowledgeSnapshot { + pub(crate) fact: EntityId, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingView, + pub(crate) confidence: Confidence, + /// The speaker a subject sees is `Told { by }`. A subject holding a fact it + /// was never told sees the statement with no speaker, which is correct: it + /// knows the thing, not the telling. + pub(crate) source: KnowledgeSource, + /// The revision of the speech act that minted this claim, when some + /// committed event asserted it. + pub(crate) spoken_at: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum FactStandingView { + Canonical, + Claimed { by: SubjectId }, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -671,12 +712,22 @@ pub(crate) struct WorldSnapshot { pub(crate) places: Vec, pub(crate) resources: Vec, pub(crate) routes: Vec, - pub(crate) events: Vec, pub(crate) opportunities: Vec, pub(crate) state_digest: String, pub(crate) last_commit_digest: Option, } +/// One committed act as the human operator's story feed reads it. It is the +/// operator surface, not a perception surface: no subject-facing lane receives +/// it, and `SelectedDecision` never sees an event log at all. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct OperatorEvent { + pub(crate) revision: u64, + pub(crate) speaker: SubjectId, + pub(crate) speaker_label: String, + pub(crate) speech: Option, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct CommitReceipt { pub(crate) command_id: CommandId, @@ -941,6 +992,14 @@ impl WorldKernel { snapshot(&self.state) } + /// The human operator's story feed. Separate from `snapshot` so that no + /// controller lane can reach an unscoped event log: a `WorldSnapshot` field + /// no consumer may read in full would be a loaded gun with a comment on it. + fn operator_log(&self) -> Result, KernelError> { + self.journal.ensure_healthy()?; + operator_log(&self.state) + } + fn submit( &mut self, command: CommandEnvelope, @@ -1107,6 +1166,7 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result Result { require_owner(state, &command.caller)?; - // Draft admits declarations, evidence, and operations. Active admits - // operations only, so it never mints a canonical ID. + // Draft admits declarations, evidence, and operations; Active admits + // operations only. The patch lane therefore structurally cannot mint + // the claim every utterance asserts, which is why `action::exercise` + // is the second `derive_id` call site. if state.phase == WorldPhase::Active && !(patch.declarations.is_empty() && patch.evidence.is_empty()) { @@ -1172,6 +1234,9 @@ impl WorldState { positions: BTreeMap::new(), holdings: BTreeMap::new(), dependencies: BTreeMap::new(), + facts: BTreeMap::new(), + channels: BTreeMap::new(), + knowledge: BTreeMap::new(), authority: BTreeMap::new(), selection: BTreeMap::new(), redress: BTreeMap::new(), @@ -1379,6 +1444,59 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<() .insert(*affordance_id); } } + // Facts and channels: one `entities` row and one payload row per + // declaration, written together so the bijection has one writer. + for declared in &resolved.facts { + let claimed_by_a_stranger = match &declared.fact.standing { + FactStanding::Canonical { evidence } => { + !(patch::is_canonical_text(evidence.text()) && resolved.evidence.contains(evidence)) + } + FactStanding::Claimed { by } => !state.subjects.contains_key(by), + }; + if !patch::is_canonical_text(&declared.entity.label) + || !patch::is_canonical_text(declared.fact.statement.as_str()) + || declared.entity.kind != EntityKind::Fact + || claimed_by_a_stranger + { + return Err(KernelError::Invariant( + "admitted fact is noncanonical, unevidenced, or asserted by no live subject".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .facts + .insert(declared.entity_id, declared.fact.clone()) + .is_some() + { + return Err(KernelError::Invariant("admitted fact ID collision".into())); + } + } + for declared in &resolved.channels { + if !patch::is_canonical_text(&declared.entity.label) + || declared.entity.kind != EntityKind::Channel + || !channel_referents_exist(state, &declared.channel) + { + return Err(KernelError::Invariant( + "admitted channel is noncanonical or names no live reach".into(), + )); + } + if state + .entities + .insert(declared.entity_id, declared.entity.clone()) + .is_some() + || state + .channels + .insert(declared.entity_id, declared.channel.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted channel ID collision".into(), + )); + } + } apply_operations(state, &resolved.operations, &resolved.evidence) } @@ -1871,10 +1989,264 @@ fn apply_operation( )); } } + ResolvedOp::AssertClaim { + fact, + statement, + by, + } => { + if !state.subjects.contains_key(by) || !patch::is_canonical_text(statement.as_str()) { + return Err(KernelError::Invariant( + "a claim names no live asserter or no canonical statement".into(), + )); + } + if state + .entities + .insert( + *fact, + EntityRecord { + label: CLAIM_LABEL.into(), + kind: EntityKind::Fact, + container: None, + }, + ) + .is_some() + || state + .facts + .insert( + *fact, + FactRecord { + statement: statement.clone(), + standing: FactStanding::Claimed { by: *by }, + }, + ) + .is_some() + { + return Err(KernelError::Invariant("minted claim ID collision".into())); + } + } + ResolvedOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let Some(record) = state.facts.get(fact) else { + return Err(KernelError::Invariant( + "knowledge operation names no canonical fact".into(), + )); + }; + if !state.subjects.contains_key(subject) + || (*source == AuthoredSource::Evidenced + && !matches!(record.standing, FactStanding::Canonical { .. })) + { + return Err(KernelError::Invariant( + "knowledge operation names no live subject, or evidences a claim".into(), + )); + } + let entry = Knowledge { + confidence: *confidence, + source: match source { + AuthoredSource::Witnessed => KnowledgeSource::Witnessed, + AuthoredSource::Evidenced => KnowledgeSource::Evidenced, + }, + }; + if state + .knowledge + .get(subject) + .and_then(|held| held.get(fact)) + .is_some_and(|held| *held == entry) + { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + state + .knowledge + .entry(*subject) + .or_default() + .insert(*fact, entry); + } + ResolvedOp::Forget { subject, fact } => { + let (removed, emptied) = state + .knowledge + .get_mut(subject) + .map(|held| { + let removed = held.remove(fact).is_some(); + (removed, held.is_empty()) + }) + .unwrap_or((false, false)); + if !removed { + return Err(KernelError::Invariant( + "knowledge operation changes nothing".into(), + )); + } + if emptied { + state.knowledge.remove(subject); + } + } + ResolvedOp::Communicate { speaker, fact, to } => { + if !state.subjects.contains_key(speaker) || !state.facts.contains_key(fact) { + return Err(KernelError::Invariant( + "a telling names no live speaker or fact".into(), + )); + } + if !audience(state, *speaker, to).contains(speaker) { + return Err(KernelError::Invariant( + "a speaker is outside its own audience".into(), + )); + } + // An empty fan-out is legal: the delta of a telling is a property of + // the world — an empty room, a silenced channel — not a defect in + // the proposal. Speaking alone commits the claim and lands nothing. + for listener in fan_out(state, *speaker, *fact, to) { + state.knowledge.entry(listener).or_default().insert( + *fact, + Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: *speaker, + via: to.channel(), + }, + }, + ); + } + } + ResolvedOp::SetReach { channel, reach } => { + let current = state + .channels + .get(channel) + .ok_or_else(|| KernelError::Invariant("channel operation names no channel".into()))? + .clone(); + let record = ChannelRecord { + reach: reach.clone(), + controller: current.controller, + }; + if !channel_referents_exist(state, &record) { + return Err(KernelError::Invariant( + "a reach names no live subject or place".into(), + )); + } + if current.reach == *reach { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + state.channels.insert(*channel, record); + } + ResolvedOp::SetController { + channel, + controller, + } => { + if controller.is_some_and(|subject_id| !state.subjects.contains_key(&subject_id)) { + return Err(unknown()); + } + let seat = state.channels.get_mut(channel).ok_or_else(|| { + KernelError::Invariant("channel operation names no channel".into()) + })?; + if seat.controller == *controller { + return Err(KernelError::Invariant( + "channel operation changes nothing".into(), + )); + } + seat.controller = *controller; + } } Ok(()) } +/// The label every minted claim carries. A label is a name, not a transcript: +/// the statement is never copied into it and the label is never derived from it, +/// so the utterance has one home in state. Labels resolve no references, so +/// identical labels across every claim are unremarkable. +const CLAIM_LABEL: &str = "claim"; + +/// Whether a channel's reach and controller name live structure. +fn channel_referents_exist(state: &WorldState, record: &ChannelRecord) -> bool { + let reach = match &record.reach { + Reach::Subjects(members) => members + .iter() + .all(|subject_id| state.subjects.contains_key(subject_id)), + Reach::Place(place) => state + .entities + .get(place) + .is_some_and(|entity| entity.kind == EntityKind::Place), + }; + reach + && record + .controller + .is_none_or(|subject_id| state.subjects.contains_key(&subject_id)) +} + +/// The one statement of reach. Called by both speech preconditions, by a +/// `Communicate`'s admission, and by its apply. Nothing else computes an +/// audience. +/// +/// Co-location is the actor's exact place, not its subtree: a voice fills a +/// room, not the district containing it. A channel's `Reach::Place` is +/// deliberately wider, because a declared broadcast area is a declared choice. +fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet { + match of { + Audience::Colocated => { + let Some(here) = state.positions.get(&actor).copied() else { + return BTreeSet::new(); + }; + state + .positions + .iter() + .filter(|(_, position)| **position == here) + .map(|(subject_id, _)| *subject_id) + .collect() + } + Audience::Channel(channel) => { + let Some(record) = state.channels.get(channel) else { + return BTreeSet::new(); + }; + let mut inside: BTreeSet = match &record.reach { + Reach::Subjects(members) => members.clone(), + Reach::Place(root) => state + .positions + .iter() + .filter(|(_, position)| { + patch::covers_place(&state.entities, *root, position.place) + }) + .map(|(subject_id, _)| *subject_id) + .collect(), + }; + // The controller may speak on its own channel whether or not it + // stands inside its reach: the horn belongs to the temple. + if let Some(controller) = record.controller { + inside.insert(controller); + } + inside + } + } +} + +/// Who gains knowledge from one telling: the audience, less the speaker and less +/// anyone who already holds the fact. A telling never overwrites and never +/// downgrades — the knower owns its own credence, and a speaker who could reset +/// a listener's confidence by repeating itself would own another subject's mind +/// through an effect nobody checked. `Believed` is fixed by the kernel and is +/// not a field on the operation, so a speaker cannot choose how much a listener +/// believes it. +fn fan_out( + state: &WorldState, + speaker: SubjectId, + fact: EntityId, + to: &Audience, +) -> BTreeSet { + audience(state, speaker, to) + .into_iter() + .filter(|listener| { + *listener != speaker + && !state + .knowledge + .get(listener) + .is_some_and(|held| held.contains_key(&fact)) + }) + .collect() +} + /// Whether an authority target names a live subject or a live place. fn authority_referent_exists(state: &WorldState, target: AuthorityTarget) -> bool { match target { @@ -1967,6 +2339,17 @@ pub(super) struct ScopeComponents { /// jurisdiction, and only delegated kinds enter — an institution's `judge` /// jurisdiction never churns a `levy`-only incumbent's proposals. delegated: BTreeMap>>, + /// The keys of this subject's own knowledge. Keys, not payloads: a statement + /// is immutable, so it cannot change without the key changing, and + /// confidence is admission-only — a re-appraisal that lowers a subject's own + /// confidence does not reject its own in-flight proposal, because `Knows` + /// re-checks at commit and fails closed with `FactUnknown`. + knows: BTreeSet, + /// The channels this subject controls, with their records. Membership of a + /// channel it merely hears never enters: a 1,000-member channel would churn + /// a thousand digests per membership change, which is whole-world binding by + /// the front door. + controls: BTreeMap, } /// Whether an authority target covers a referent. The one statement of @@ -2085,10 +2468,55 @@ fn scope_components(state: &WorldState, subject_id: SubjectId) -> ScopeComponent .cloned() .unwrap_or_default(), delegated: delegated_authority(state, subject_id), + knows: state + .knowledge + .get(&subject_id) + .into_iter() + .flat_map(BTreeMap::keys) + .copied() + .collect(), + controls: state + .channels + .iter() + .filter(|(_, record)| record.controller == Some(subject_id)) + .map(|(entity_id, record)| (*entity_id, record.clone())) + .collect(), } } +/// The human operator's story feed, derived from the causal record. The events +/// log is not a perception surface: `knowledge` is the sole answer to what a +/// subject may act on and what its projection may contain. +fn operator_log(state: &WorldState) -> Result, KernelError> { + state + .events + .iter() + .map(|event| { + let speaker = state + .subjects + .get(&event.scope.subject_id) + .ok_or_else(|| KernelError::Invariant("event names no live subject".into()))?; + Ok(OperatorEvent { + revision: event.revision, + speaker: event.scope.subject_id, + speaker_label: speaker.label.clone(), + speech: event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.clone()), + }) + }) + .collect() +} + fn snapshot(state: &WorldState) -> Result { + // One pass over the causal record so each subject's own knowledge map can be + // stamped with the revision that minted each claim it holds. + let spoken_at: BTreeMap = state + .events + .iter() + .filter_map(|event| event.speech.map(|fact| (fact, event.revision))) + .collect(); let subjects = state .subjects .iter() @@ -2147,6 +2575,32 @@ fn snapshot(state: &WorldState) -> Result { forum: forum.forum, }) .collect(); + // The sole perception surface, derived here rather than in a + // controller: a controller that recomputed perception would be a + // second answer to who heard what. + let mut knowledge: Vec = state + .knowledge + .get(subject_id) + .into_iter() + .flatten() + .map(|(fact, held)| { + let record = state.facts.get(fact).ok_or_else(|| { + KernelError::Invariant("knowledge names no canonical fact".into()) + })?; + Ok(KnowledgeSnapshot { + fact: *fact, + statement: record.statement.clone(), + standing: match &record.standing { + FactStanding::Canonical { .. } => FactStandingView::Canonical, + FactStanding::Claimed { by } => FactStandingView::Claimed { by: *by }, + }, + confidence: held.confidence, + source: held.source, + spoken_at: spoken_at.get(fact).copied(), + }) + }) + .collect::, KernelError>>()?; + knowledge.sort_by_key(|entry| (entry.spoken_at, entry.fact)); Ok(SubjectSnapshot { id: *subject_id, label: subject.label.clone(), @@ -2163,6 +2617,8 @@ fn snapshot(state: &WorldState) -> Result { offices_held, offices_granted, redress, + knowledge, + controls: components.controls.into_keys().collect(), }) }) .collect::, KernelError>>()?; @@ -2221,7 +2677,6 @@ fn snapshot(state: &WorldState) -> Result { places, resources, routes, - events: state.events.clone(), opportunities: derive_opportunities(state)?, state_digest: state.state_digest.clone(), last_commit_digest: state.last_commit_digest.clone(), @@ -2470,7 +2925,11 @@ fn apply_effect( } state.phase = WorldPhase::Active; } - WorldEffect::DecisionExercised { opportunity, event } => { + WorldEffect::DecisionExercised { + opportunity, + invocation, + event, + } => { let current = exact_opportunity(state, opportunity)?; let assignment = state .controller_assignments @@ -2483,12 +2942,11 @@ fn apply_effect( "decision effect does not match exact opportunity authority".into(), )); } - let granted = require_granted(state, ¤t, event.invocation.affordance)?; + let granted = require_granted(state, ¤t, invocation.affordance)?; // The whole event is re-derived by the function that produced the - // honest one, so a forged band, operation, magnitude, or utterance - // is one comparison rather than a clause apiece. - let derived = - action::exercise(state, command_id, ¤t, &granted, &event.invocation)?; + // honest one, so a forged band, operation, magnitude, minted claim, + // or utterance is one comparison rather than a clause apiece. + let derived = action::exercise(state, command_id, ¤t, &granted, invocation)?; if derived != *event { return Err(KernelError::Invariant( "decision effect does not derive from its opportunity".into(), @@ -2541,6 +2999,16 @@ mod tests { use super::patch::kernel_speak_grant; use super::*; + /// What a committed event actually asserted, read from the one home of an + /// utterance: the minted claim's statement. No other partition holds those + /// bytes. + pub(super) fn spoken<'a>(state: &'a WorldState, event: &DecisionEvent) -> Option<&'a str> { + event + .speech + .and_then(|fact| state.facts.get(&fact)) + .map(|record| record.statement.as_str()) + } + pub(super) fn owner() -> PrincipalId { PrincipalId::new("owner@example.test") } @@ -2565,10 +3033,20 @@ mod tests { kind, controller, affordances: kernel_speak_grant(), - position: None, + // The fixture world is one room. Co-located speech needs a place to + // fill, so every fixture subject stands in the commons. + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), }) } + /// The one place the base fixture world declares. + pub(super) const COMMONS: &str = "commons"; + + /// How many entities the base fixture world admits at genesis: the commons + /// and nothing else. A patch-lane test that proves a rejection allocated + /// nothing compares against this rather than against zero. + pub(super) const FIXTURE_ENTITIES: usize = 1; + /// The committed Speak entry. A post-genesis declaration grants it by /// canonical reference, like every other structure a previous commit /// allocated: the kernel synthesizes the entry once, at genesis. @@ -2605,6 +3083,12 @@ mod tests { operations: Vec::new(), evidence: Vec::new(), declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new(COMMONS), + label: "The Commons".into(), + kind: EntityKind::Place, + container: None, + }), // A second, world-declared entry granted to exactly one // subject, so the fixture world has more than one verb and // grant sets differ between scopes. @@ -2612,7 +3096,11 @@ mod tests { handle: DraftHandle::new("convene"), kind: AffordanceKindName("convene".into()), roles: Vec::new(), - preconditions: Vec::new(), + // A speech-carrying entry must name exactly one + // audience for the lowering to read. + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], effect_slots: Vec::new(), outcome_bands: vec![OutcomeBand { weight: 1, @@ -2643,7 +3131,7 @@ mod tests { .into_iter() .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) .collect(), - position: None, + position: Some(Ref::Draft(DraftHandle::new(COMMONS))), }), ], }, @@ -3378,9 +3866,15 @@ mod tests { "petition", "petition", Vec::new(), - vec![Precondition::HasStanding { - grievance: grievance(SEIZURE_GRIEVANCE), - }], + vec![ + Precondition::HasStanding { + grievance: grievance(SEIZURE_GRIEVANCE), + }, + // A petition is spoken, so the entry names where it lands. + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ], Vec::new(), vec![OutcomeBand { weight: 1, @@ -3490,6 +3984,17 @@ mod tests { Ref::Existing(topology.road), &["levy", "petition"], ), + // Deliberately unplaced: a place-subtree jurisdiction covers a + // subject through its position, so a subject with none is + // covered by nothing. + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("nowhere"), + label: "The Unhoused".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: civic_grants(&["levy", "petition"], &speak), + position: None, + }), ]) .collect(); WorldPatch { @@ -3612,6 +4117,209 @@ mod tests { (topology, civic, active) } + /// The speech bench: a hall containing a yard, a speaker and a listener in + /// the hall, a bystander in the yard, a stranger nowhere, one evidenced + /// canonical fact, and a horn that carries over the hall subtree. + pub(super) struct Speech { + pub(super) hall: EntityId, + pub(super) yard: EntityId, + pub(super) speaker: SubjectId, + pub(super) listener: SubjectId, + pub(super) bystander: SubjectId, + pub(super) stranger: SubjectId, + pub(super) flood: EntityId, + pub(super) horn: EntityId, + pub(super) whisper: AffordanceId, + pub(super) proclaim: AffordanceId, + pub(super) recant: AffordanceId, + pub(super) stair: EdgeId, + } + + pub(super) const FLOOD_STATEMENT: &str = "The lower hinge is flooding."; + pub(super) const FLOOD_EVIDENCE: &str = "vault:flood-survey"; + + /// A world with one room inside another, four subjects, a fact, and a + /// channel. Two world-declared speaking entries exercise both audiences: an + /// addressed co-located `whisper` and a channel-bound `proclaim`. + pub(super) fn speech_world(kernel: &mut WorldKernel) -> (Speech, WorldSnapshot) { + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(kernel); + let person = |handle: &str, label: &str, place: Option<&str>| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new(handle), + label: label.into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([ + speak.clone(), + Ref::Draft(DraftHandle::new("whisper")), + Ref::Draft(DraftHandle::new("proclaim")), + Ref::Draft(DraftHandle::new("recant")), + ]), + position: place.map(|place| Ref::Draft(DraftHandle::new(place))), + }) + }; + submit_owner( + kernel, + &before, + CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + evidence: vec![EvidenceRef::new(FLOOD_EVIDENCE)], + operations: Vec::new(), + declarations: vec![ + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("hall"), + label: "The Long Hall".into(), + kind: EntityKind::Place, + container: None, + }), + Declaration::Entity(EntityDeclaration { + handle: DraftHandle::new("yard"), + label: "The Cavity Yard".into(), + kind: EntityKind::Place, + container: Some(Ref::Draft(DraftHandle::new("hall"))), + }), + Declaration::Route(RouteDeclaration { + handle: DraftHandle::new("stair"), + label: "The Yard Stair".into(), + from: Ref::Draft(DraftHandle::new("yard")), + to: Ref::Draft(DraftHandle::new("hall")), + access: AccessKind::Public, + cost: Cost(1), + }), + Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("flood"), + label: "the flooding of the lower hinge".into(), + statement: Statement::new(FLOOD_STATEMENT).unwrap(), + standing: FactStandingRef::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + }, + }), + // Addressed speech: the audience is still the room. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("whisper"), + kind: AffordanceKindName("whisper".into()), + roles: vec![RoleSpec { + role: Role("target".into()), + kind: RefKind::Subject(None), + }], + preconditions: vec![Precondition::CanReach { + subject: Role("target".into()), + via: AudienceSpec::Colocated, + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("proclaim"), + kind: AffordanceKindName("proclaim".into()), + roles: vec![RoleSpec { + role: Role("channel".into()), + kind: RefKind::Entity(EntityKind::Channel), + }], + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Channel(Role("channel".into())), + }], + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), + // `Knows` plus the one knowledge operation an affordance + // may propose: a subject may only unremember what it + // holds with certainty. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("recant"), + kind: AffordanceKindName("recant".into()), + roles: vec![RoleSpec { + role: Role("fact".into()), + kind: RefKind::Entity(EntityKind::Fact), + }], + preconditions: vec![Precondition::Knows { + fact: Role("fact".into()), + at_least: Confidence::Certain, + }], + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Forget, + roles: vec![Role("actor".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }), + person("speaker", "The Hall Speaker", Some("hall")), + person("listener", "The Hall Listener", Some("hall")), + person("bystander", "The Yard Bystander", Some("yard")), + person("stranger", "The Placeless Stranger", None), + Declaration::Channel(ChannelDeclaration { + handle: DraftHandle::new("horn"), + label: "The Temple Horn".into(), + reach: ReachRef::Place(Ref::Draft(DraftHandle::new("hall"))), + controller: Some(Ref::Draft(DraftHandle::new("speaker"))), + }), + ], + }, + }, + ); + let active = activate(kernel); + let place = |label: &str| { + active + .places + .iter() + .find(|place| place.label == label) + .expect("the declared place") + .id + }; + let who = |label: &str| { + active + .subjects + .iter() + .find(|subject| subject.label == label) + .expect("the declared subject") + .id + }; + let fact = *kernel + .state + .facts + .iter() + .find(|(_, record)| record.statement.as_str() == FLOOD_STATEMENT) + .expect("the declared fact") + .0; + let horn = *kernel + .state + .channels + .keys() + .next() + .expect("the declared channel"); + ( + Speech { + hall: place("The Long Hall"), + yard: place("The Cavity Yard"), + speaker: who("The Hall Speaker"), + listener: who("The Hall Listener"), + bystander: who("The Yard Bystander"), + stranger: who("The Placeless Stranger"), + flood: fact, + horn, + whisper: affordance_named(&active, "whisper"), + proclaim: affordance_named(&active, "proclaim"), + recant: affordance_named(&active, "recant"), + stair: active.routes[0].id, + }, + active, + ) + } + /// Submits as owner and returns the complete mismatch set. pub(super) fn reject_owner( kernel: &mut WorldKernel, @@ -3672,7 +4380,7 @@ mod tests { affordance: opportunity.affordance_ids[0], bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new(text).unwrap()), + speech: Some(Statement::new(text).unwrap()), } } @@ -3748,9 +4456,9 @@ mod tests { ) .unwrap(); assert!(matches!(receipt, SubmitReceipt::Applied(_))); - let after = kernel.snapshot().unwrap(); - assert_eq!(after.events.len(), 2); - assert_eq!(after.events[1].revision, bound.revision + 2); + let after = kernel.state.events.clone(); + assert_eq!(after.len(), 2); + assert_eq!(after[1].revision, bound.revision + 2); } /// Closing a route incident to the subject's place changes exactly what the @@ -3946,13 +4654,9 @@ mod tests { ) .unwrap(); let after_player = kernel.snapshot().unwrap(); - assert_eq!(after_player.events.len(), 1); + assert_eq!(kernel.state.events.len(), 1); assert_eq!( - after_player.events[0] - .invocation - .speech - .as_ref() - .map(Utterance::as_str), + spoken(&kernel.state, &kernel.state.events[0]), Some("I open the door.") ); @@ -3973,7 +4677,7 @@ mod tests { ) .unwrap(); let after_persona = kernel.snapshot().unwrap(); - assert_eq!(after_persona.events.len(), 2); + assert_eq!(kernel.state.events.len(), 2); assert!( after_persona .opportunities @@ -4089,7 +4793,7 @@ mod tests { affordance: affordance_named(&active, "convene"), bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("No grant").unwrap()), + speech: Some(Statement::new("No grant").unwrap()), }; assert!(matches!( kernel.submit( @@ -4122,7 +4826,7 @@ mod tests { affordance: forged_affordance, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("Forged").unwrap()), + speech: Some(Statement::new("Forged").unwrap()), }, opportunity: tampered, }, @@ -4326,7 +5030,7 @@ mod tests { }; let after = kernel.snapshot().unwrap(); assert_eq!(after.revision, active.revision + 1); - assert!(after.events.is_empty()); + assert!(kernel.state.events.is_empty()); let refreshed = opportunity(&after, ControllerMode::OperationalAgent); assert_ne!(refreshed, decision); assert_eq!( @@ -4493,7 +5197,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("world.cc"); let mut invalid = creation(CommandId::new(), "Nope"); - invalid.patch.declarations[2] = invalid.patch.declarations[1].clone(); + invalid.patch.declarations[3] = invalid.patch.declarations[2].clone(); let Err(KernelError::PatchRejected(rejected)) = WorldKernel::create(&path, invalid, &auth_principal(owner())) else { @@ -4833,7 +5537,7 @@ mod tests { affordance: convened, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("Not my grant.").unwrap()), + speech: Some(Statement::new("Not my grant.").unwrap()), }, }, ), @@ -4898,7 +5602,7 @@ mod tests { affordance: convened, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("The council convenes.").unwrap()), + speech: Some(Statement::new("The council convenes.").unwrap()), }, }, ), @@ -4992,7 +5696,7 @@ mod tests { affordance: speak, bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("Still here.").unwrap()), + speech: Some(Statement::new("Still here.").unwrap()), }, }, ), @@ -5610,6 +6314,8 @@ mod custody_tests { entities: Vec::new(), routes: Vec::new(), affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), operations: vec![ResolvedOp::Transfer { from: custody.holder, to: custody.counterparty, @@ -6101,7 +6807,7 @@ mod custody_tests { affordance: bound.affordance_ids[0], bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("The tithe is short.").unwrap()), + speech: Some(Statement::new("The tithe is short.").unwrap()), }, }, ), @@ -6199,6 +6905,8 @@ mod custody_tests { entities: Vec::new(), routes: Vec::new(), affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), operations, evidence: Vec::new(), }, @@ -6384,7 +7092,7 @@ mod custody_tests { affordance: opportunity.affordance_ids[0], bindings: Vec::new(), proposed: Vec::new(), - speech: Some(Utterance::new("Counted before the tithe arrived.").unwrap()), + speech: Some(Statement::new("Counted before the tithe arrived.").unwrap()), }, }; @@ -6418,3 +7126,1003 @@ mod custody_tests { assert!(matches!(receipt, SubmitReceipt::Applied(_))); } } + +/// Pass 6: `Knowledge`, `Channel`, `Fact` standing, and the non-leakage rule. +/// A subject perceives a speech act if and only if it holds `Knowledge` of that +/// act's fact — the knowledge partition is the sole owner of who-heard-what. +#[cfg(test)] +mod knowledge_tests { + use super::patch::{RefName, Site}; + use super::tests::{ + FLOOD_EVIDENCE, FLOOD_STATEMENT, Speech, auth_principal, command, creation, operations, + opportunity_for, owner, reject_owner, speech_world, spoken, submit_owner, + }; + use super::*; + use std::path::Path; + + fn speech_kernel(path: &Path, title: &str) -> (WorldKernel, Speech, WorldSnapshot) { + let mut kernel = WorldKernel::create( + path.join("world.cc"), + creation(CommandId::new(), title), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + (kernel, speech, active) + } + + fn utter( + kernel: &mut WorldKernel, + snapshot: &WorldSnapshot, + actor: SubjectId, + invocation: DecisionInvocation, + ) -> Result { + let opportunity = opportunity_for(snapshot, actor); + let caller = CallerId::Controller(opportunity.controller_id); + kernel.submit( + command( + snapshot, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + } + + fn say(affordance: AffordanceId, bindings: Vec, text: &str) -> DecisionInvocation { + DecisionInvocation { + affordance, + bindings, + proposed: Vec::new(), + speech: Some(Statement::new(text).unwrap()), + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + fn rejected(result: Result) -> Vec { + match result { + Err(KernelError::ActionRejected(mismatches)) => mismatches, + other => panic!("expected a rejected invocation, got {other:?}"), + } + } + + fn knows(kernel: &WorldKernel, subject: SubjectId, fact: EntityId) -> Option { + kernel + .state + .knowledge + .get(&subject) + .and_then(|held| held.get(&fact)) + .copied() + } + + fn acquire(subject: SubjectId, fact: EntityId, source: AuthoredSource) -> ComponentOp { + ComponentOp::AcquireKnowledge { + subject: Ref::Existing(subject), + fact: Ref::Existing(fact), + source, + confidence: Confidence::Certain, + } + } + + fn minted_claim(kernel: &WorldKernel) -> EntityId { + kernel + .state + .events + .last() + .expect("the committed event") + .speech + .expect("a speech act names its claim") + } + + /// Verification 5, first half: a patch adds knowledge only by citing an + /// accessible fact, and a rejected citation allocates nothing. + #[test] + fn knowledge_citing_an_inaccessible_fact_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Inaccessible"); + let before = kernel.state.clone(); + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + EntityId::issue(), + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::UnknownCanonical { + site: Site::Operation(0), + expected: RefKind::Entity(EntityKind::Fact), + }] + ); + // A live referent of the wrong kind names the kind it actually is. + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.hall, + AuthoredSource::Witnessed + )]), + ), + vec![Mismatch::WrongKind { + site: Site::Operation(0), + referent: RefName::Entity(Ref::Existing(speech.hall)), + expected: RefKind::Entity(EntityKind::Fact), + actual: RefKind::Entity(EntityKind::Place), + }] + ); + assert_eq!(kernel.state, before); + + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + assert_eq!( + knows(&kernel, speech.listener, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Witnessed) + ); + } + + /// Standing is what a fact *is*, so both halves are checked at declaration: + /// canon needs its receipt in the same patch, a claim needs a live asserter. + #[test] + fn a_canonical_fact_needs_evidence_and_a_claim_needs_an_asserter() { + let directory = tempfile::tempdir().unwrap(); + let mut draft = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "Standing"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let start = draft.snapshot().unwrap(); + let declare = + |standing: FactStandingRef, evidence: Vec| CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Fact(FactDeclaration { + handle: DraftHandle::new("rumour"), + label: "a rumour".into(), + statement: Statement::new("The reeve took two tithes.").unwrap(), + standing, + })], + operations: Vec::new(), + evidence, + }, + }; + + assert_eq!( + reject_owner( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:absent"), + }, + Vec::new(), + ), + ), + vec![Mismatch::FactWithoutEvidence { + handle: DraftHandle::new("rumour"), + }] + ); + assert_eq!( + reject_owner( + &mut draft, + &start, + declare( + FactStandingRef::Claimed { + by: Ref::Draft(DraftHandle::new("nobody")), + }, + Vec::new(), + ), + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("rumour")), + referent: DraftHandle::new("nobody"), + expected: RefKind::Subject(None), + }] + ); + assert!(draft.state.facts.is_empty()); + + submit_owner( + &mut draft, + &start, + declare( + FactStandingRef::Canonical { + evidence: EvidenceRef::new("vault:rumour"), + }, + vec![EvidenceRef::new("vault:rumour")], + ), + ); + assert_eq!(draft.state.facts.len(), 1); + // The bijection holds in both directions. + let fact = *draft.state.facts.keys().next().unwrap(); + assert_eq!(draft.state.entities[&fact].kind, EntityKind::Fact); + } + + /// A receipt vouches for canon. It cannot vouch for an assertion the kernel + /// never evaluated. + #[test] + fn evidenced_knowledge_of_a_claim_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Evidenced"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The gate was left open.", + ), + ) + .expect("the proclamation commits"); + let claim = minted_claim(&kernel); + let active = kernel.snapshot().unwrap(); + + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + claim, + AuthoredSource::Evidenced + )]), + ), + vec![Mismatch::EvidencedKnowledgeOfClaim { operation: 0 }] + ); + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.stranger, + speech.flood, + AuthoredSource::Evidenced, + )]), + ); + assert_eq!( + knows(&kernel, speech.stranger, speech.flood).map(|held| held.source), + Some(KnowledgeSource::Evidenced) + ); + assert_eq!( + kernel.state.facts[&speech.flood].standing, + FactStanding::Canonical { + evidence: EvidenceRef::new(FLOOD_EVIDENCE), + } + ); + } + + /// The fan-out is the audience, less the speaker: co-located speech fills + /// the exact room, and the utterance lands in `facts` and nowhere else. + #[test] + fn speak_fans_out_to_the_audience_and_not_beyond() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "FanOut"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Mind the hinge.", + ), + ) + .expect("the whisper commits"); + + let event = kernel.state.events.last().expect("the committed event"); + let claim = event.speech.expect("a speech act names its claim"); + assert_eq!(spoken(&kernel.state, event), Some("Mind the hinge.")); + assert_eq!( + knows(&kernel, speech.listener, claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: None, + }, + }) + ); + // The yard is inside the hall, but a voice fills a room and not the + // district containing it. The speaker's own claim is not implied. + for outside in [speech.bystander, speech.stranger, speech.speaker] { + assert_eq!(knows(&kernel, outside, claim), None); + } + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + // The utterance has exactly one home: a label is a name, not a + // transcript. + assert_ne!(kernel.state.entities[&claim].label, "Mind the hinge."); + } + + /// Co-location is the exact place; a channel's `Reach::Place` is the + /// subtree, through the same containment walk a jurisdiction uses. + #[test] + fn co_location_reach_is_the_exact_place_and_a_channel_place_is_the_subtree() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Reach"); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn carries.", + ), + ) + .expect("the proclamation commits"); + let broadcast = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, broadcast).is_some()); + assert!(knows(&kernel, speech.bystander, broadcast).is_some()); + assert_eq!(knows(&kernel, speech.stranger, broadcast), None); + + // The same speaker's voice reaches only the hall. + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "A voice does not.", + ), + ) + .expect("the whisper commits"); + let voiced = minted_claim(&kernel); + assert!(knows(&kernel, speech.listener, voiced).is_some()); + assert_eq!(knows(&kernel, speech.bystander, voiced), None); + + // Moving the bystander up the stair puts it in both audiences. + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Now you hear it.", + ), + ) + .expect("the whisper commits"); + assert!(knows(&kernel, speech.bystander, minted_claim(&kernel)).is_some()); + } + + /// The delta of a telling is a property of the world, not a defect in the + /// proposal: speaking alone commits the claim and the event and lands + /// nothing. + #[test] + fn speaking_into_an_empty_room_commits_the_claim_and_lands_nothing() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "EmptyRoom"); + let knowledge_before = kernel.state.knowledge.clone(); + utter( + &mut kernel, + &active, + speech.bystander, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Nobody is here.", + ), + ) + .expect("speech into an empty room commits"); + + assert_eq!(kernel.state.knowledge, knowledge_before); + assert_eq!(kernel.state.events.len(), 1); + assert_eq!( + spoken(&kernel.state, kernel.state.events.last().unwrap()), + Some("Nobody is here.") + ); + assert_eq!( + kernel + .state + .facts + .values() + .filter(|record| matches!(record.standing, FactStanding::Claimed { .. })) + .count(), + 1 + ); + } + + /// The horn belongs to the temple: its controller may speak on it whether + /// or not it stands inside its reach, and removing the controller flips the + /// same invocation to exactly one named failure. + #[test] + fn a_channel_controller_may_speak_outside_its_own_reach() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Controller"); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.listener)])), + }]), + ); + let proclaim = || { + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn still carries.", + ) + }; + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.speaker, proclaim()) + .expect("the controller may speak on its own channel"); + + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetController { + channel: Ref::Existing(speech.horn), + controller: None, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, proclaim())), + vec![ActionMismatch::NoAudience { precondition: 0 }] + ); + } + + /// Addressing does not narrow the audience, and a target outside it names + /// itself. A target that walked in mid-flight commits, and the whole + /// audience receives the telling, not only the addressed subject. + #[test] + fn an_addressed_subject_outside_the_audience_names_itself() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Addressing"); + let whisper = || { + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.bystander))], + "Come inside.", + ) + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.speaker, whisper())), + vec![ActionMismatch::CannotReach { precondition: 0 }] + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Relocate { + subject: Ref::Existing(speech.bystander), + via: Ref::Existing(speech.stair), + }]), + ); + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.speaker, whisper()) + .expect("the addressed subject is now in the room"); + let claim = minted_claim(&kernel); + assert!(knows(&kernel, speech.bystander, claim).is_some()); + assert!( + knows(&kernel, speech.listener, claim).is_some(), + "speaking to someone in a room is heard by the room" + ); + } + + /// `Knows` compares confidence with one `>=`, and `Forget` removes the key + /// rather than storing a zero. + #[test] + fn knows_fails_below_its_confidence_and_forget_removes() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Knows"); + let recant = || DecisionInvocation { + affordance: speech.recant, + bindings: vec![binding("fact", Target::Entity(speech.flood))], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + }; + assert_eq!( + rejected(utter(&mut kernel, &active, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }] + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::AcquireKnowledge { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }]), + ); + let active = kernel.snapshot().unwrap(); + assert_eq!( + rejected(utter(&mut kernel, &active, speech.listener, recant())), + vec![ActionMismatch::FactUnknown { precondition: 0 }], + "Believed falls short of Certain" + ); + + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let active = kernel.snapshot().unwrap(); + utter(&mut kernel, &active, speech.listener, recant()) + .expect("certainty admits the recant"); + // Absence is the one shape of knowing nothing: no empty inner map. + assert!(!kernel.state.knowledge.contains_key(&speech.listener)); + + let active = kernel.snapshot().unwrap(); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Forget { + subject: Ref::Existing(speech.listener), + fact: Ref::Existing(speech.flood), + }]), + ), + vec![Mismatch::NoOperationEffect { operation: 0 }] + ); + } + + /// A telling never overwrites and never downgrades: the knower owns its own + /// credence. + #[test] + fn a_telling_never_overwrites_a_holder() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "NoOverwrite"); + submit_owner( + &mut kernel, + &active, + operations(vec![acquire( + speech.listener, + speech.flood, + AuthoredSource::Witnessed, + )]), + ); + let before = knows(&kernel, speech.listener, speech.flood); + let active = kernel.snapshot().unwrap(); + + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + assert_eq!(knows(&kernel, speech.listener, speech.flood), before); + assert_eq!( + knows(&kernel, speech.bystander, speech.flood), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + }) + ); + } + + /// Ontology admission: communication reaches only subjects inside the + /// channel's reach, and a speaker outside it is not speaking. + #[test] + fn communicating_from_outside_the_audience_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "OutsideAudience"); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Colocated, + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.stranger), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ), + vec![Mismatch::SpeakerOutsideAudience { operation: 0 }] + ); + assert!(kernel.state.knowledge.is_empty()); + } + + /// The two allocation sites, asserted: only `derive_id` allocates, and the + /// action lane's one referent per invocation is reproduced by calling it + /// directly with the recorded world, command, handle, and discriminator. + #[test] + fn every_canonical_id_comes_from_one_of_two_sites() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Allocation"); + let world_id = kernel.state.world_id; + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let entities_before = kernel.state.entities.len(); + kernel + .submit( + command( + &active, + command_id, + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation: say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Counted.", + ), + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the whisper commits"); + + let claim = minted_claim(&kernel); + assert_eq!( + claim, + EntityId(patch::derive_id( + patch::ENTITY_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ghostlight.speech"), + Some("0"), + )) + ); + // Exactly one referent, always a fact, always claimed by the actor. + assert_eq!(kernel.state.entities.len(), entities_before + 1); + assert_eq!(kernel.state.entities[&claim].kind, EntityKind::Fact); + assert_eq!( + kernel.state.facts[&claim].standing, + FactStanding::Claimed { by: speech.speaker } + ); + } + + /// Replay is exact because every allocation derives from committed inputs + /// and every fan-out is re-derived at apply from the audience plus live + /// state. + #[test] + fn restart_replay_after_speech_is_exact() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let (speech, world_id, expected) = { + let mut kernel = WorldKernel::create( + &path, + creation(CommandId::new(), "ReplaySpeech"), + &auth_principal(owner()), + ) + .expect("a created world") + .0; + let (speech, active) = speech_world(&mut kernel); + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "One.", + ), + ) + .expect("the first proclamation commits"); + let active = kernel.snapshot().unwrap(); + utter( + &mut kernel, + &active, + speech.listener, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.speaker))], + "Two.", + ), + ) + .expect("the whisper commits"); + let active = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::Communicate { + speaker: Ref::Existing(speech.speaker), + fact: Ref::Existing(speech.flood), + to: AudienceRef::Channel(Ref::Existing(speech.horn)), + }]), + ); + let world_id = kernel.state.world_id; + (speech, world_id, kernel.state.clone()) + }; + + let reopened = WorldKernel::open(&path, world_id).expect("the store replays"); + assert_eq!(reopened.state.facts, expected.facts); + assert_eq!(reopened.state.channels, expected.channels); + assert_eq!(reopened.state.knowledge, expected.knowledge); + assert_eq!(reopened.state.events, expected.events); + assert_eq!(reopened.state, expected); + assert!(!reopened.state.knowledge[&speech.bystander].is_empty()); + } + + /// A forged claim does not apply, and a forged recipient list is + /// unrepresentable: `ResolvedOp::Communicate` stores an audience, never + /// recipients. + #[test] + fn a_forged_claim_or_forged_recipient_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "Forgery"); + let command_id = CommandId::new(); + let opportunity = opportunity_for(&active, speech.speaker); + let caller = CallerId::Controller(opportunity.controller_id); + let invocation = say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "Honest.", + ); + let granted = require_granted(&kernel.state, &opportunity, invocation.affordance).unwrap(); + let honest = action::exercise( + &kernel.state, + command_id, + &opportunity, + &granted, + &invocation, + ) + .expect("the honest event derives"); + let fact = honest.speech.expect("the honest claim"); + + let mut forged_claim = honest.clone(); + forged_claim.speech = Some(speech.flood); + let mut forged_statement = honest.clone(); + forged_statement.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Forged.").unwrap(), + by: speech.speaker, + }; + let mut forged_asserter = honest.clone(); + forged_asserter.effects[0] = ResolvedOp::AssertClaim { + fact, + statement: Statement::new("Honest.").unwrap(), + by: speech.listener, + }; + for forged in [forged_claim, forged_statement, forged_asserter] { + let mut candidate = kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + invocation: invocation.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, kernel.state); + } + + // A recipient list cannot be forged because none is stored. + assert!(matches!( + honest.effects[1], + ResolvedOp::Communicate { + to: Audience::Channel(_), + .. + } + )); + let mut candidate = kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity, + invocation, + event: honest, + }, + ) + .expect("the honest event applies"); + assert!(candidate.knowledge.contains_key(&speech.listener)); + } + + /// The scope table: a telling rebinds its listener and leaves a bystander + /// alone, and a reach change moves only the controller's digest. + #[test] + fn a_telling_moves_only_the_listeners_scope() { + let directory = tempfile::tempdir().unwrap(); + let (mut kernel, speech, active) = speech_kernel(directory.path(), "ScopeMove"); + let digest = |kernel: &WorldKernel, subject: SubjectId| { + scope_digest( + &kernel.state, + DecisionScope { + subject_id: subject, + }, + ) + .unwrap() + }; + let listener_before = digest(&kernel, speech.listener); + let bystander_before = digest(&kernel, speech.bystander); + + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + "Only you.", + ), + ) + .expect("the whisper commits"); + assert_ne!(digest(&kernel, speech.listener), listener_before); + assert_eq!(digest(&kernel, speech.bystander), bystander_before); + + // Reach membership is admission-only: adding a hearer moves the + // controller's digest and nobody else's. + let active = kernel.snapshot().unwrap(); + let hearer_before = digest(&kernel, speech.listener); + let speaker_before = digest(&kernel, speech.speaker); + submit_owner( + &mut kernel, + &active, + operations(vec![ComponentOp::SetReach { + channel: Ref::Existing(speech.horn), + reach: ReachRef::Subjects(BTreeSet::from([Ref::Existing(speech.stranger)])), + }]), + ); + assert_eq!(digest(&kernel, speech.listener), hearer_before); + assert_ne!(digest(&kernel, speech.speaker), speaker_before); + } + + /// A speech-carrying entry names exactly one audience: none is unlowerable + /// and two is unchoosable. Each rejection allocates no `AffordanceId`. + #[test] + fn a_speech_carrying_entry_must_declare_exactly_one_audience() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = WorldKernel::create( + directory.path().join("world.cc"), + creation(CommandId::new(), "SpeechAudience"), + &auth_principal(owner()), + ) + .expect("a draft world") + .0; + let before = kernel.snapshot().unwrap(); + let catalog_before = kernel.state.affordance_catalog.len(); + let declare = |preconditions: Vec| CommandBody::AdmitPatch { + answers: None, + patch: WorldPatch { + declarations: vec![Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("herald"), + kind: AffordanceKindName("herald".into()), + roles: Vec::new(), + preconditions, + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + })], + operations: Vec::new(), + evidence: Vec::new(), + }, + }; + assert_eq!( + reject_owner(&mut kernel, &before, declare(Vec::new())), + vec![Mismatch::SpeechWithoutAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!( + reject_owner( + &mut kernel, + &before, + declare(vec![ + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }, + ]), + ), + vec![Mismatch::AmbiguousSpeechAudience { + handle: DraftHandle::new("herald"), + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), catalog_before); + } + + /// The kernel does not compare two statements: no dedup, no interning, no + /// contradiction check, no similarity. A claim byte-identical to a + /// canonical fact and one that plainly negates it commit identically. + #[test] + fn the_kernel_never_compares_two_statements() { + let directory = tempfile::tempdir().unwrap(); + let run = |name: &str, text: &str| { + let room = directory.path().join(name); + std::fs::create_dir_all(&room).unwrap(); + let (mut kernel, speech, active) = speech_kernel(&room, name); + let receipt = utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.whisper, + vec![binding("target", Target::Subject(speech.listener))], + text, + ), + ) + .expect("both statements commit identically"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = kernel.state.events.last().unwrap().clone(); + (kernel, speech, event) + }; + let (agreeing, agreeing_speech, agreeing_event) = run("agree", FLOOD_STATEMENT); + let (negating, _, negating_event) = run("negate", "The lower hinge is dry."); + + assert_eq!(agreeing_event.band, negating_event.band); + assert_eq!(agreeing_event.effects.len(), negating_event.effects.len()); + assert_eq!(agreeing.state.facts.len(), negating.state.facts.len()); + // Two facts with byte-identical statements are two facts: the claim is + // not the canonical fact it repeats, and neither run learned anything + // about the other's meaning. + let claim = agreeing_event.speech.unwrap(); + assert_ne!(claim, agreeing_speech.flood); + assert_eq!( + agreeing.state.facts[&claim].statement, + agreeing.state.facts[&agreeing_speech.flood].statement + ); + assert_ne!( + agreeing.state.facts[&claim].standing, + agreeing.state.facts[&agreeing_speech.flood].standing + ); + } +} diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 793eb0f..f1c7bce 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -1,5 +1,10 @@ //! Closed-patch resolution: the one owner of draft handles, reference kinds, and -//! canonical ID allocation for every admission lane. +//! declaration-lane ID allocation. +//! +//! Only [`derive_id`] allocates a canonical ID, and it is called from exactly +//! two sites: [`resolve_patch`] here, and `action::exercise`, which mints one +//! referent per speech-carrying invocation — always a `Claimed` fact asserted by +//! the acting subject. //! //! A patch names structure two ways and no other way: an exact canonical ID that //! already keys a partition, or a draft handle declared in the same patch. @@ -259,11 +264,172 @@ pub(crate) struct RoleSpec { pub(crate) kind: RefKind, } +/// Committed world text: canonical, non-empty. The kernel stores it, hands it to +/// a projection, and reads it no other way. Nothing compares two `Statement`s: +/// no dedup, no interning, no contradiction check, no similarity. Two facts with +/// byte-identical statements are two facts. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Statement(String); + +impl Statement { + pub(crate) fn new(value: impl Into) -> Option { + let value = value.into(); + is_canonical_text(&value).then_some(Self(value)) + } + + pub(crate) fn as_str(&self) -> &str { + &self.0 + } +} + +/// How a fact stands. Immutable after admission: there is no `SetStanding`. A +/// claim never becomes canon and canon never degrades to a claim, so nothing +/// ever has to decide which of two facts wins. A world in which a court rules on +/// a rumour declares a *new* `Canonical` fact; the rumour survives beside it, +/// which is what makes a later `Redress` reading possible at all. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStanding { + /// Admitted with a receipt, through the same evidence gate `Admit` uses. + Canonical { evidence: EvidenceRef }, + /// Asserted by a subject. The kernel does not evaluate the assertion. + Claimed { by: SubjectId }, +} + +/// The proposal-time twin of [`FactStanding`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "standing", rename_all = "snake_case")] +pub(crate) enum FactStandingRef { + Canonical { evidence: EvidenceRef }, + Claimed { by: Ref }, +} + +/// One `EntityKind::Fact` row's payload. Write-once: only declaration and +/// `AssertClaim` ever write `facts`. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactRecord { + pub(crate) statement: Statement, + pub(crate) standing: FactStanding, +} + +/// Where a channel carries. A place reach is the subtree, through the same +/// [`covers_place`] walk a `PlaceSubtree` jurisdiction uses. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum Reach { + /// Exactly these subjects. May be empty: an empty reach is the named + /// silenced state, which is the outcome this component exists to hold. + Subjects(BTreeSet), + /// Everyone positioned at that place or anywhere inside it. + Place(EntityId), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "reach", content = "of", rename_all = "snake_case")] +pub(crate) enum ReachRef { + Subjects(BTreeSet>), + Place(Ref), +} + +/// One `EntityKind::Channel` row's payload. It carries no latency: there is no +/// clock, so a latency field would be read by nothing and bound by nothing. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelRecord { + pub(crate) reach: Reach, + /// Who may speak on it besides those inside its reach, and whose scope + /// digest binds it. The horn belongs to the temple, not to whoever happens + /// to be within earshot of it. + pub(crate) controller: Option, +} + +/// A small closed ordinal. Ordered ascending by declaration order, so derived +/// `Ord` *is* the semantics and `Knows { at_least }` is one `>=`. Three levels: +/// two cannot express "I heard it but I doubt it", which is the state deception +/// produces; four or more is a scale nothing in the vocabulary distinguishes. +/// There is no zero — forgetting is a removed key, exactly as `Quantity(0)` is +/// unstorable. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Confidence { + Doubted, + Believed, + Certain, +} + +/// Three sources, three writers, no overlap: `Witnessed` and `Evidenced` are +/// written by `AcquireKnowledge`, `Told` only by `Communicate`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum KnowledgeSource { + Witnessed, + /// `via: None` is co-location. + Told { + by: SubjectId, + via: Option, + }, + Evidenced, +} + +/// What one subject holds of one fact. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Knowledge { + pub(crate) confidence: Confidence, + pub(crate) source: KnowledgeSource, +} + +/// The source an author may write. `Told` is unrepresentable here: only +/// `Communicate` writes it, so no author can forge a teller. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "source", rename_all = "snake_case")] +pub(crate) enum AuthoredSource { + Witnessed, + Evidenced, +} + +/// Where a telling lands. `Colocated` is derived from `positions` at check and +/// at apply; it is never a stored channel, so no entity is minted per place and +/// no world must enumerate a village to let people talk in a room. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Audience { + Colocated, + Channel(EntityId), +} + +impl Audience { + pub(super) fn channel(self) -> Option { + match self { + Self::Colocated => None, + Self::Channel(entity_id) => Some(entity_id), + } + } +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceRef { + Colocated, + Channel(Ref), +} + +/// The catalog form: a declared affordance names a role, the invoker binds a +/// channel to it, and `exercise` lowers this plus the bindings into the +/// canonical [`Audience`]. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub(crate) enum AudienceSpec { + Colocated, + Channel(Role), +} + /// What must already be true of committed state before an invocation is -/// admitted. Only the ones whose components exist: `Knows`, `CanReach`, and -/// `Committed` land in the pass that adds `Knowledge`, `Channel`, and -/// `Commitment`. A variant whose only behaviour would be to be refused is a -/// placeholder wearing a check. +/// admitted. Only the ones whose components exist: `Committed` lands in the pass +/// that adds `Commitment`. A variant whose only behaviour would be to be refused +/// is a placeholder wearing a check. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "precondition", rename_all = "snake_case")] pub(crate) enum Precondition { @@ -281,6 +447,16 @@ pub(crate) enum Precondition { Authorized { over: Role, kind: AuthorityKindName }, /// A forum takes `grievance` and the acting subject is inside its standing. HasStanding { grievance: GrievanceKindName }, + /// The acting subject holds the fact bound to `fact` at `at_least` or + /// better. + Knows { fact: Role, at_least: Confidence }, + /// The acting subject has an audience at all: it is positioned, for + /// co-location, or it is inside the bound channel's reach or is its + /// controller. + CanBroadcast { via: AudienceSpec }, + /// The referent bound to `subject` is inside that audience. Addressing does + /// not narrow the audience: a telling still lands on everyone in it. + CanReach { subject: Role, via: AudienceSpec }, } /// Exactly the operations an affordance may propose. `Admit` is absent because @@ -306,10 +482,24 @@ pub(crate) enum ComponentOpKind { Consume, Bind, Release, - GrantAuthority { kind: AuthorityKindName }, - RevokeAuthority { kind: AuthorityKindName }, - InstallIncumbent { office: OfficeName }, - VacateOffice { office: OfficeName }, + GrantAuthority { + kind: AuthorityKindName, + }, + RevokeAuthority { + kind: AuthorityKindName, + }, + InstallIncumbent { + office: OfficeName, + }, + VacateOffice { + office: OfficeName, + }, + /// Source is fixed to `Witnessed`: only `Communicate` writes a teller, and + /// `Evidenced` needs a patch's evidence list, which an invocation has not. + AcquireKnowledge { + confidence: Confidence, + }, + Forget, } /// The referent shape of one operation: the single source of both the @@ -345,6 +535,9 @@ impl ComponentOpKind { } Self::InstallIncumbent { .. } => vec![subject(), subject()], Self::VacateOffice { .. } => vec![subject()], + Self::AcquireKnowledge { .. } | Self::Forget => { + vec![subject(), RoleKindRule::Exact(FACT)] + } } } @@ -461,6 +654,10 @@ impl EvidenceRef { pub(super) fn new(value: impl Into) -> Self { Self(value.into()) } + + pub(super) fn text(&self) -> &str { + &self.0 + } } /// `position` is the subject's presence: one place it stands in. A subject @@ -502,13 +699,39 @@ pub(crate) struct RouteDeclaration { pub(crate) cost: Cost, } +/// A fact's label is a short authored name ("the flooding of the lower hinge"), +/// never a transcript: the statement is never copied into the label and the +/// label is never derived from the statement, so the utterance has exactly one +/// home in state. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct FactDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) statement: Statement, + pub(crate) standing: FactStandingRef, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ChannelDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) label: String, + pub(crate) reach: ReachRef, + pub(crate) controller: Option>, +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub(crate) enum Declaration { Subject(SubjectDeclaration), + /// Places and resources only. `Fact` and `Channel` carry a payload and have + /// their own declarations, so a referenceable empty one is unrepresentable. Entity(EntityDeclaration), Route(RouteDeclaration), Affordance(AffordanceDeclaration), + Fact(FactDeclaration), + Channel(ChannelDeclaration), } /// The operations that change a component of an already canonical structure. @@ -608,6 +831,33 @@ pub(crate) enum ComponentOp { CloseForum { grievance: GrievanceKindName, }, + /// Source is authored: `Witnessed` by an author or an affordance, + /// `Evidenced` only over a `Canonical` fact. + AcquireKnowledge { + subject: Ref, + fact: Ref, + source: AuthoredSource, + confidence: Confidence, + }, + /// One telling. It stores the audience, never the recipients: the fan-out is + /// re-derived at apply from live `positions` and `channels`. + Communicate { + speaker: Ref, + fact: Ref, + to: AudienceRef, + }, + Forget { + subject: Ref, + fact: Ref, + }, + SetReach { + channel: Ref, + reach: ReachRef, + }, + SetController { + channel: Ref, + controller: Option>, + }, } /// Empty on purpose: an `Option` can only be `None`, so the @@ -823,6 +1073,38 @@ pub(crate) enum Mismatch { ReservedRole { handle: DraftHandle, }, + /// An `EntityDeclaration` naming `Fact` or `Channel`. Those kinds carry a + /// payload and have their own declaration; a payload-less one would make a + /// referenceable, empty fact a legal state. + PayloadEntityKind { + handle: DraftHandle, + }, + /// A `Canonical` fact declaration whose `EvidenceRef` is not listed in this + /// patch's `evidence`. + FactWithoutEvidence { + handle: DraftHandle, + }, + EmptyStatement { + handle: DraftHandle, + }, + /// `AcquireKnowledge { source: Evidenced }` over a `Claimed` fact. + EvidencedKnowledgeOfClaim { + operation: usize, + }, + /// A `Communicate` whose speaker is neither inside the audience nor the + /// channel's controller. + SpeakerOutsideAudience { + operation: usize, + }, + /// A catalog entry with `carries_speech` and no `CanBroadcast` or + /// `CanReach`: its speech would have no audience to lower. + SpeechWithoutAudience { + handle: DraftHandle, + }, + /// More than one, so the lowering could not choose. + AmbiguousSpeechAudience { + handle: DraftHandle, + }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -919,6 +1201,24 @@ pub(super) struct ResolvedAffordance { pub(super) affordance: Affordance, } +/// A declared fact: one `entities` row and one `facts` row, allocated together +/// so the bijection has one writer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedFact { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) fact: FactRecord, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedChannel { + pub(super) handle: DraftHandle, + pub(super) entity_id: EntityId, + pub(super) entity: EntityRecord, + pub(super) channel: ChannelRecord, +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub(super) struct ResolvedRoute { pub(super) handle: DraftHandle, @@ -1011,6 +1311,42 @@ pub(crate) enum ResolvedOp { CloseForum { grievance: GrievanceKindName, }, + AcquireKnowledge { + subject: SubjectId, + fact: EntityId, + source: AuthoredSource, + confidence: Confidence, + }, + /// Stores the audience, never the recipients. `apply_operation` re-derives + /// the fan-out from live `positions`/`channels`, exactly as `Relocate` + /// stores `edge_id` and re-derives the destination, so a forged effect + /// cannot assert a landing the world does not have. + Communicate { + speaker: SubjectId, + fact: EntityId, + to: Audience, + }, + Forget { + subject: SubjectId, + fact: EntityId, + }, + SetReach { + channel: EntityId, + reach: Reach, + }, + SetController { + channel: EntityId, + controller: Option, + }, + /// Kernel-only: no [`ComponentOp`] twin, because no proposer may author one. + /// Synthesized by `action::exercise` for a speech-carrying invocation and by + /// nothing else. Inserts the entity row and the `facts` row; it writes no + /// knowledge, because a speaker's own knowledge of its claim is not implied. + AssertClaim { + fact: EntityId, + statement: Statement, + by: SubjectId, + }, } /// One resource's movement across a whole patch. Accumulators are `u128` so an @@ -1058,6 +1394,8 @@ pub(super) struct ResolvedPatch { pub(super) entities: Vec, pub(super) routes: Vec, pub(super) affordances: Vec, + pub(super) facts: Vec, + pub(super) channels: Vec, pub(super) operations: Vec, pub(super) evidence: Vec, } @@ -1068,17 +1406,21 @@ impl ResolvedPatch { && self.entities.is_empty() && self.routes.is_empty() && self.affordances.is_empty() + && self.facts.is_empty() + && self.channels.is_empty() && self.evidence.is_empty() } } const SUBJECT_NAMESPACE: &str = "ghostlight.id.subject.v1"; -const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; +pub(super) const ENTITY_NAMESPACE: &str = "ghostlight.id.entity.v1"; const EDGE_NAMESPACE: &str = "ghostlight.id.edge.v1"; const CONTROLLER_NAMESPACE: &str = "ghostlight.id.controller.v1"; const AFFORDANCE_NAMESPACE: &str = "ghostlight.id.affordance.v1"; const PLACE: RefKind = RefKind::Entity(EntityKind::Place); +const FACT: RefKind = RefKind::Entity(EntityKind::Fact); +const CHANNEL: RefKind = RefKind::Entity(EntityKind::Channel); const ROUTE: RefKind = RefKind::Edge(EdgeKind::Route); const ANY_SUBJECT: RefKind = RefKind::Subject(None); @@ -1243,6 +1585,82 @@ fn candidate_effective_authority( effective } +/// A fact in the candidate graph. Only its standing matters to resolution: the +/// statement is never read and never compared. +#[derive(Clone, Debug, PartialEq, Eq)] +enum FactCandidate { + Canonical, + Claimed(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum ReachKey { + Subjects(BTreeSet>), + Place(Key), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ChannelCandidate { + reach: ReachKey, + controller: Option>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum KnowledgeSourceKey { + Witnessed, + Told { + by: Key, + via: Option>, + }, + Evidenced, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct KnowledgeCandidate { + confidence: Confidence, + source: KnowledgeSourceKey, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +enum AudienceKey { + Colocated, + Channel(Key), +} + +/// Whether a subject is inside an audience over the candidate graph: the same +/// question `audience()` answers over committed state, asked before any ID is +/// minted. A controller is inside its own channel's audience for the purpose of +/// speaking on it — the horn belongs to the temple. +fn candidate_in_audience( + subject: &Key, + audience: &AudienceKey, + speaker: &Key, + positions: &BTreeMap, Key>, + channels: &BTreeMap, ChannelCandidate>, + containers: &BTreeMap, Key>, +) -> bool { + match audience { + AudienceKey::Colocated => match (positions.get(speaker), positions.get(subject)) { + (Some(here), Some(there)) => here == there, + _ => false, + }, + AudienceKey::Channel(channel) => { + let Some(record) = channels.get(channel) else { + return false; + }; + if record.controller.as_ref() == Some(subject) { + return true; + } + match &record.reach { + ReachKey::Subjects(members) => members.contains(subject), + ReachKey::Place(root) => positions + .get(subject) + .is_some_and(|place| key_covers_place(root, place, containers)), + } + } + } +} + #[derive(Clone, Debug)] struct RouteCandidate { from: Key, @@ -1252,11 +1670,12 @@ struct RouteCandidate { open: bool, } -/// The only canonical ID allocator. Deterministic on purpose: journal replay -/// recomputes `reduce` and requires effect equality, so a reduce arm can never -/// draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they are -/// variable-width, so the concatenation is unambiguous. -fn derive_id( +/// The only canonical ID allocator, called from exactly two sites: +/// [`resolve_patch`] and `action::exercise`. Deterministic on purpose: journal +/// replay recomputes `reduce` and requires effect equality, so a reduce arm can +/// never draw a `Uuid::new_v4`. Preimage fields are length-prefixed where they +/// are variable-width, so the concatenation is unambiguous. +pub(super) fn derive_id( namespace: &str, world_id: WorldId, command_id: CommandId, @@ -1324,14 +1743,18 @@ pub(super) fn kernel_speak_grant() -> BTreeSet> { BTreeSet::from([Ref::Draft(DraftHandle::new(KERNEL_SPEAK_HANDLE))]) } -/// Zero preconditions, zero slots, one empty band, one utterance. Speech reaches -/// everyone because `Channel` does not exist yet; a reach check that always -/// passed would look like the invariant is enforced. +/// Zero roles, zero slots, one empty band, one utterance, and one audience: a +/// voice fills the room it is standing in. Zero roles is load-bearing — the +/// Interpreter lane submits no bindings and Eve's speak payload carries only +/// text. The precondition is not vacuous: an unplaced subject has no +/// co-location audience and fails with `NoAudience`. pub(super) fn kernel_speak_entry() -> Affordance { Affordance { kind: AffordanceKindName("speak".into()), roles: Vec::new(), - preconditions: Vec::new(), + preconditions: vec![Precondition::CanBroadcast { + via: AudienceSpec::Colocated, + }], effect_slots: Vec::new(), outcome_bands: vec![OutcomeBand { weight: 1, @@ -1462,6 +1885,21 @@ fn validate_affordance( }), Some(_) => {} }; + let require_subject = |role: &Role, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(RefKind::Subject(_)) => {} + Some(_) => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + }; + let require_audience = |via: &AudienceSpec, mismatches: &mut Vec| match via { + AudienceSpec::Colocated => {} + AudienceSpec::Channel(role) => require(role, CHANNEL, mismatches), + }; for precondition in preconditions { match precondition { Precondition::Present { at } => { @@ -1501,6 +1939,34 @@ fn validate_affordance( mismatches.push(Mismatch::InvalidCivicName { site: site() }); } } + Precondition::Knows { fact, .. } => require(fact, FACT, mismatches), + Precondition::CanBroadcast { via } => require_audience(via, mismatches), + Precondition::CanReach { subject, via } => { + require_subject(subject, mismatches); + require_audience(via, mismatches); + } + } + } + // A speech-carrying entry must name exactly one audience: the lowering reads + // it, so none is unlowerable and two is unchoosable. + if carries_speech { + let audiences = preconditions + .iter() + .filter(|precondition| { + matches!( + precondition, + Precondition::CanBroadcast { .. } | Precondition::CanReach { .. } + ) + }) + .count(); + if audiences == 0 { + mismatches.push(Mismatch::SpeechWithoutAudience { + handle: handle.clone(), + }); + } else if audiences > 1 { + mismatches.push(Mismatch::AmbiguousSpeechAudience { + handle: handle.clone(), + }); } } for (index, slot) in effect_slots.iter().enumerate() { @@ -1819,6 +2285,78 @@ fn resolve_office_institution( named.then_some(key) } +/// The one reach resolver: every member of a subject set, or one place. +fn resolve_reach( + site: Site, + reach: &ReachRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match reach { + ReachRef::Subjects(members) => { + let mut resolved = BTreeSet::new(); + let mut complete = true; + for reference in members { + match resolve_subject(site.clone(), reference, index, &state.subjects, mismatches) { + Some(key) => { + resolved.insert(key); + } + None => complete = false, + } + } + complete.then_some(ReachKey::Subjects(resolved)) + } + ReachRef::Place(reference) => resolve_entity( + site, + EntityKind::Place, + reference, + index, + &state.entities, + mismatches, + ) + .map(ReachKey::Place), + } +} + +/// A channel controller is optional, so "declared none" and "named one that did +/// not resolve" are two answers, not one. +fn resolve_controller( + site: Site, + controller: &Option>, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option>> { + match controller { + None => Some(None), + Some(reference) => { + resolve_subject(site, reference, index, &state.subjects, mismatches).map(Some) + } + } +} + +fn resolve_audience( + site: Site, + audience: &AudienceRef, + index: &BTreeMap, + state: &super::WorldState, + mismatches: &mut Vec, +) -> Option { + match audience { + AudienceRef::Colocated => Some(AudienceKey::Colocated), + AudienceRef::Channel(reference) => resolve_entity( + site, + EntityKind::Channel, + reference, + index, + &state.entities, + mismatches, + ) + .map(AudienceKey::Channel), + } +} + fn resolve_authority_target( site: Site, target: &AuthorityTargetRef, @@ -1916,6 +2454,8 @@ pub(super) fn resolve_patch( // validator against the tool-name alphabet rather than against the // label rule. Declaration::Affordance(affordance) => (&affordance.handle, None, RefKind::Affordance), + Declaration::Fact(fact) => (&fact.handle, Some(&fact.label), FACT), + Declaration::Channel(channel) => (&channel.handle, Some(&channel.label), CHANNEL), }; let named = is_canonical_text(&handle.0); if !named { @@ -1953,6 +2493,29 @@ pub(super) fn resolve_patch( }); } } + if let Declaration::Entity(entity) = declaration + && matches!(entity.kind, EntityKind::Fact | EntityKind::Channel) + { + mismatches.push(Mismatch::PayloadEntityKind { + handle: handle.clone(), + }); + } + if let Declaration::Fact(fact) = declaration { + if !is_canonical_text(fact.statement.as_str()) { + mismatches.push(Mismatch::EmptyStatement { + handle: handle.clone(), + }); + } + // The same predicate `Admit` uses, moved into the declaration loop so + // one rule serves evidenced quantity and evidenced canon alike. + if let FactStandingRef::Canonical { evidence } = &fact.standing + && !(is_canonical_text(&evidence.0) && patch.evidence.contains(evidence)) + { + mismatches.push(Mismatch::FactWithoutEvidence { + handle: handle.clone(), + }); + } + } if let Declaration::Subject(subject) = declaration { if subject.affordances.is_empty() { mismatches.push(Mismatch::NoAffordances { @@ -2072,6 +2635,63 @@ pub(super) fn resolve_patch( ) }) .collect(); + let mut facts: BTreeMap, FactCandidate> = state + .facts + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + match &record.standing { + FactStanding::Canonical { .. } => FactCandidate::Canonical, + FactStanding::Claimed { by } => FactCandidate::Claimed(Key::Existing(*by)), + }, + ) + }) + .collect(); + let mut channels: BTreeMap, ChannelCandidate> = state + .channels + .iter() + .map(|(entity_id, record)| { + ( + Key::Existing(*entity_id), + ChannelCandidate { + reach: match &record.reach { + Reach::Subjects(members) => { + ReachKey::Subjects(members.iter().copied().map(Key::Existing).collect()) + } + Reach::Place(place) => ReachKey::Place(Key::Existing(*place)), + }, + controller: record.controller.map(Key::Existing), + }, + ) + }) + .collect(); + // Keys and payload, so an `AcquireKnowledge` that changes nothing is + // `NoOperationEffect` before any ID is minted. A `Communicate` never enters: + // its fan-out is re-derived at apply, and a telling is a canonical change + // whatever the room holds. + let mut knowledge: BTreeMap<(Key, Key), KnowledgeCandidate> = state + .knowledge + .iter() + .flat_map(|(subject_id, held)| { + held.iter().map(move |(fact, entry)| { + ( + (Key::Existing(*subject_id), Key::Existing(*fact)), + KnowledgeCandidate { + confidence: entry.confidence, + source: match entry.source { + KnowledgeSource::Witnessed => KnowledgeSourceKey::Witnessed, + KnowledgeSource::Evidenced => KnowledgeSourceKey::Evidenced, + KnowledgeSource::Told { by, via } => KnowledgeSourceKey::Told { + by: Key::Existing(by), + via: via.map(Key::Existing), + }, + }, + }, + ) + }) + }) + .collect(); let mut deltas: BTreeMap, LedgerDelta> = BTreeMap::new(); let mut declared_places: Vec<(DraftHandle, Key)> = Vec::new(); @@ -2103,6 +2723,44 @@ pub(super) fn resolve_patch( } } Declaration::Affordance(_) => {} + Declaration::Fact(fact) => { + let standing = match &fact.standing { + FactStandingRef::Canonical { .. } => Some(FactCandidate::Canonical), + FactStandingRef::Claimed { by } => resolve_subject( + Site::Declaration(fact.handle.clone()), + by, + &index, + &state.subjects, + &mut mismatches, + ) + .map(FactCandidate::Claimed), + }; + if let Some(standing) = standing { + facts.insert(Key::Draft(fact.handle.clone()), standing); + } + } + Declaration::Channel(channel) => { + let reach = resolve_reach( + Site::Declaration(channel.handle.clone()), + &channel.reach, + &index, + state, + &mut mismatches, + ); + let controller = resolve_controller( + Site::Declaration(channel.handle.clone()), + &channel.controller, + &index, + state, + &mut mismatches, + ); + if let (Some(reach), Some(controller)) = (reach, controller) { + channels.insert( + Key::Draft(channel.handle.clone()), + ChannelCandidate { reach, controller }, + ); + } + } Declaration::Subject(subject) => { for reference in &subject.affordances { resolve_affordance( @@ -2833,6 +3491,188 @@ pub(super) fn resolve_patch( }); } } + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + // Evidenced knowledge is knowledge of canon. A receipt cannot + // vouch for an assertion the kernel never evaluated. + if *source == AuthoredSource::Evidenced + && facts.get(&fact_key) != Some(&FactCandidate::Canonical) + { + mismatches.push(Mismatch::EvidencedKnowledgeOfClaim { + operation: position, + }); + continue; + } + let entry = KnowledgeCandidate { + confidence: *confidence, + source: match source { + AuthoredSource::Witnessed => KnowledgeSourceKey::Witnessed, + AuthoredSource::Evidenced => KnowledgeSourceKey::Evidenced, + }, + }; + let slot = (subject_key, fact_key); + if knowledge.get(&slot) == Some(&entry) { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + knowledge.insert(slot, entry); + } + } + ComponentOp::Forget { subject, fact } => { + let subject_key = resolve_subject( + Site::Operation(position), + subject, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let (Some(subject_key), Some(fact_key)) = (subject_key, fact_key) else { + continue; + }; + if knowledge.remove(&(subject_key, fact_key)).is_none() { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } + } + ComponentOp::Communicate { speaker, fact, to } => { + let speaker_key = resolve_subject( + Site::Operation(position), + speaker, + &index, + &state.subjects, + &mut mismatches, + ); + let fact_key = resolve_entity( + Site::Operation(position), + EntityKind::Fact, + fact, + &index, + &state.entities, + &mut mismatches, + ); + let audience = resolve_audience( + Site::Operation(position), + to, + &index, + state, + &mut mismatches, + ); + let (Some(speaker_key), Some(_), Some(audience)) = + (speaker_key, fact_key, audience) + else { + continue; + }; + // Ontology admission: communication reaches only subjects inside + // the channel's reach, and a speaker outside it is not speaking. + if !candidate_in_audience( + &speaker_key, + &audience, + &speaker_key, + &positions, + &channels, + &containers, + ) { + mismatches.push(Mismatch::SpeakerOutsideAudience { + operation: position, + }); + } + } + ComponentOp::SetReach { channel, reach } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let reach_key = resolve_reach( + Site::Operation(position), + reach, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(reach_key)) = (channel_key, reach_key) else { + continue; + }; + let Some(candidate) = channels.get_mut(&channel_key) else { + continue; + }; + if candidate.reach == reach_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.reach = reach_key; + } + } + ComponentOp::SetController { + channel, + controller, + } => { + let channel_key = resolve_entity( + Site::Operation(position), + EntityKind::Channel, + channel, + &index, + &state.entities, + &mut mismatches, + ); + let controller_key = resolve_controller( + Site::Operation(position), + controller, + &index, + state, + &mut mismatches, + ); + let (Some(channel_key), Some(controller_key)) = (channel_key, controller_key) + else { + continue; + }; + let Some(candidate) = channels.get_mut(&channel_key) else { + continue; + }; + if candidate.controller == controller_key { + mismatches.push(Mismatch::NoOperationEffect { + operation: position, + }); + } else { + candidate.controller = controller_key; + } + } } // Disjointness, checked against the complete candidate graph after each // operation that could widen someone's jurisdiction, so two operations @@ -2926,6 +3766,30 @@ pub(super) fn resolve_patch( }, }); } + // Facts and channels allocate through the same entity namespace and the same + // `derive_id`, so no namespace is added and `RefKind::Entity` types every + // reference to one. They stay out of `entities` above so that vector remains + // a zip over the place and resource declarations. + for declaration in &patch.declarations { + let handle = match declaration { + Declaration::Fact(fact) => &fact.handle, + Declaration::Channel(channel) => &channel.handle, + _ => continue, + }; + let entity_id = EntityId(derive_id( + ENTITY_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.entities.contains_key(&entity_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated_entities.insert(handle.clone(), entity_id); + } let entity_id_of = |key: &Key| -> EntityId { match key { Key::Existing(entity_id) => *entity_id, @@ -3145,6 +4009,68 @@ pub(super) fn resolve_patch( } } }; + let reach_of = |reach: &ReachRef| -> Reach { + match reach { + ReachRef::Subjects(members) => Reach::Subjects( + members + .iter() + .map(|reference| subject_id_of(&key_of(reference))) + .collect(), + ), + ReachRef::Place(reference) => Reach::Place(entity_id_of(&key_of(reference))), + } + }; + let controller_of = |controller: &Option>| -> Option { + controller + .as_ref() + .map(|reference| subject_id_of(&key_of(reference))) + }; + let audience_of = |audience: &AudienceRef| -> Audience { + match audience { + AudienceRef::Colocated => Audience::Colocated, + AudienceRef::Channel(reference) => Audience::Channel(entity_id_of(&key_of(reference))), + } + }; + let mut declared_facts = Vec::new(); + let mut declared_channels = Vec::new(); + for declaration in &patch.declarations { + match declaration { + Declaration::Fact(fact) => declared_facts.push(ResolvedFact { + handle: fact.handle.clone(), + entity_id: entity_id_of(&Key::Draft(fact.handle.clone())), + entity: EntityRecord { + label: fact.label.clone(), + kind: EntityKind::Fact, + container: None, + }, + fact: FactRecord { + statement: fact.statement.clone(), + standing: match &fact.standing { + FactStandingRef::Canonical { evidence } => FactStanding::Canonical { + evidence: evidence.clone(), + }, + FactStandingRef::Claimed { by } => FactStanding::Claimed { + by: subject_id_of(&key_of(by)), + }, + }, + }, + }), + Declaration::Channel(channel) => declared_channels.push(ResolvedChannel { + handle: channel.handle.clone(), + entity_id: entity_id_of(&Key::Draft(channel.handle.clone())), + entity: EntityRecord { + label: channel.label.clone(), + kind: EntityKind::Channel, + container: None, + }, + channel: ChannelRecord { + reach: reach_of(&channel.reach), + controller: controller_of(&channel.controller), + }, + }), + _ => {} + } + } let grant_of = |grant: &AuthorityGrantRef| -> AuthorityGrant { AuthorityGrant { kind: grant.kind.clone(), @@ -3271,6 +4197,37 @@ pub(super) fn resolve_patch( ComponentOp::CloseForum { grievance } => ResolvedOp::CloseForum { grievance: grievance.clone(), }, + ComponentOp::AcquireKnowledge { + subject, + fact, + source, + confidence, + } => ResolvedOp::AcquireKnowledge { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + source: *source, + confidence: *confidence, + }, + ComponentOp::Communicate { speaker, fact, to } => ResolvedOp::Communicate { + speaker: subject_id_of(&key_of(speaker)), + fact: entity_id_of(&key_of(fact)), + to: audience_of(to), + }, + ComponentOp::Forget { subject, fact } => ResolvedOp::Forget { + subject: subject_id_of(&key_of(subject)), + fact: entity_id_of(&key_of(fact)), + }, + ComponentOp::SetReach { channel, reach } => ResolvedOp::SetReach { + channel: entity_id_of(&key_of(channel)), + reach: reach_of(reach), + }, + ComponentOp::SetController { + channel, + controller, + } => ResolvedOp::SetController { + channel: entity_id_of(&key_of(channel)), + controller: controller_of(controller), + }, }) .collect(); @@ -3284,6 +4241,8 @@ pub(super) fn resolve_patch( entities, routes, affordances, + facts: declared_facts, + channels: declared_channels, operations, evidence: patch.evidence.clone(), }) @@ -3400,8 +4359,8 @@ pub(super) fn containment_terminates( mod tests { use super::*; use crate::world::tests::{ - activate, admit_topology, auth_principal, command, creation, owner, player, reject_owner, - speak_entry, submit_owner, + FIXTURE_ENTITIES, activate, admit_topology, auth_principal, command, creation, owner, + player, reject_owner, speak_entry, submit_owner, }; use crate::world::{ CallerId, CommandBody, CommandId, KernelError, SubmitReceipt, WorldKernel, WorldPhase, @@ -3878,7 +4837,7 @@ mod tests { ); assert_eq!(kernel.snapshot().unwrap(), before); assert_eq!(kernel.journal.commit_count(), commits_before); - assert!(kernel.state.entities.is_empty()); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); assert_eq!(kernel.state.subjects.len(), before.subjects.len()); } @@ -3914,7 +4873,7 @@ mod tests { let after = kernel.snapshot().unwrap(); assert_eq!(after.revision, before.revision + 1); assert_eq!(kernel.journal.commit_count(), commits_before + 1); - assert_eq!(kernel.state.entities.len(), 2); + assert_eq!(kernel.state.entities.len(), 3); let road = *kernel .state .entities @@ -4076,7 +5035,7 @@ mod tests { ]); let receipt = submit_owner(&mut kernel, &before, admit(repaired)); assert!(matches!(receipt, SubmitReceipt::Applied(_))); - assert_eq!(kernel.state.entities.len(), 2); + assert_eq!(kernel.state.entities.len(), 3); } #[test] @@ -4145,7 +5104,7 @@ mod tests { } assert_eq!(kernel.journal.commit_count(), commits_before); assert_eq!(kernel.snapshot().unwrap(), active); - assert!(kernel.state.entities.is_empty()); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); } /// Three places whose containers form a cycle name themselves, and the @@ -4192,7 +5151,7 @@ mod tests { expected.sort(); assert_eq!(mismatches, expected); assert_eq!(kernel.snapshot().unwrap(), before); - assert!(kernel.state.entities.is_empty()); + assert_eq!(kernel.state.entities.len(), FIXTURE_ENTITIES); } #[test] @@ -4417,7 +5376,7 @@ mod tests { let snapshot = kernel.snapshot().unwrap(); assert_eq!(snapshot, kernel.snapshot().unwrap()); - assert_eq!(snapshot.places.len(), 3); + assert_eq!(snapshot.places.len(), 4); let place_ids: Vec<_> = snapshot.places.iter().map(|place| place.id).collect(); let mut sorted_places = place_ids.clone(); sorted_places.sort(); @@ -4628,7 +5587,7 @@ mod tests { let reopened = WorldKernel::open(&path, before.world_id).unwrap(); assert_eq!(reopened.snapshot().unwrap(), before); assert_eq!(reopened.journal.commit_count(), 1); - assert!(reopened.state.entities.is_empty()); + assert_eq!(reopened.state.entities.len(), FIXTURE_ENTITIES); assert!( !reopened .state @@ -4755,6 +5714,22 @@ mod tests { ); let topology = admit_topology(&mut kernel); + // Every fixture subject stands somewhere now, so the unplaced case is + // declared here rather than borrowed from a genesis accident. + let before = kernel.snapshot().unwrap(); + let speak = speak_entry(&kernel); + submit_owner( + &mut kernel, + &before, + admit(patch_of(vec![Declaration::Subject(SubjectDeclaration { + handle: draft("nowhere"), + label: "The Unplaced".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([speak]), + position: None, + })])), + ); let active = activate(&mut kernel); let commits_before = kernel.journal.commit_count(); let unplaced = *kernel @@ -4762,7 +5737,7 @@ mod tests { .subjects .iter() .find(|(subject_id, _)| !kernel.state.positions.contains_key(*subject_id)) - .expect("a genesis subject was declared without a position") + .expect("the unplaced subject this test declared") .0; // Relocating a subject that stands nowhere. @@ -4840,6 +5815,8 @@ mod tests { entities: Vec::new(), routes: Vec::new(), affordances: Vec::new(), + facts: Vec::new(), + channels: Vec::new(), operations: vec![ResolvedOp::Relocate { subject_id: topology.walker, edge_id,