diff --git a/crates/ghostlight-dungeon/src/world/action.rs b/crates/ghostlight-dungeon/src/world/action.rs index 758f9c9..31a569e 100644 --- a/crates/ghostlight-dungeon/src/world/action.rs +++ b/crates/ghostlight-dungeon/src/world/action.rs @@ -429,7 +429,7 @@ fn check_preconditions( let Some(audience) = bound_audience(via, bindings) else { continue; }; - if !super::audience(state, actor, &audience).contains(&actor) { + if !super::can_broadcast(state, actor, &audience) { rejections.push(ActionMismatch::NoAudience { precondition: index, }); @@ -868,9 +868,9 @@ mod tests { over_place, over_subject, player, reject_owner, submit_owner, }; use crate::world::{ - AffordanceKindName, AuthenticatedCaller, CallerId, CommandBody, Declaration, EntityKind, - ProposedEffect, RoleBinding, Statement, SubmitReceipt, WorldEffect, WorldKernel, - WorldPatch, WorldSnapshot, apply_effect, + AffordanceKindName, AuthenticatedCaller, AuthoredSource, CallerId, CommandBody, Confidence, + Declaration, EffectSlot, EntityKind, ProposedEffect, RoleBinding, Statement, SubmitReceipt, + WorldEffect, WorldKernel, WorldPatch, WorldSnapshot, apply_effect, }; use std::collections::BTreeSet; @@ -2531,4 +2531,61 @@ mod tests { ); } } + + /// `resolve_patch`'s candidate knowledge map never models `Communicate`'s + /// fan-out (see the comment beside its construction in `patch.rs`), and + /// that omission is safe only because no `ComponentOpKind` an affordance + /// may declare can lower to a knowledge write carrying + /// `KnowledgeSource::Told`. `AcquireKnowledge` is the only + /// `ComponentOpKind` that touches knowledge at all, and `lower` fixes its + /// source to `AuthoredSource::Witnessed` here, at the one call site that + /// turns a declared slot into a `ComponentOp` — a type that has no `Told` + /// variant to begin with. This test pins that lowering so a future author + /// cannot widen it without this assertion naming the change. + #[test] + fn no_component_op_kind_lowers_to_a_told_knowledge_write() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "AcquireKnowledgeLowering"); + let entry = Affordance { + kind: AffordanceKindName("witness".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::AcquireKnowledge { + confidence: Confidence::Believed, + }, + roles: vec![Role("subject".into()), Role("fact".into())], + bounds: Bounds::None, + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }; + let bindings = BTreeMap::from([ + (Role("subject".into()), Target::Subject(bench.clerk)), + (Role("fact".into()), Target::Entity(bench.tithe)), + ]); + let invocation = DecisionInvocation { + affordance: bench.carry, + bindings: Vec::new(), + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::None, + }], + speech: None, + }; + let lowered = lower(&entry, 0, &invocation, &bindings).expect("the acquire slot lowers"); + assert_eq!( + lowered, + vec![ComponentOp::AcquireKnowledge { + subject: PatchRef::Existing(bench.clerk), + fact: PatchRef::Existing(bench.tithe), + source: AuthoredSource::Witnessed, + confidence: Confidence::Believed, + }], + "AcquireKnowledge must lower with a Witnessed source, never a forged teller" + ); + } } diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 59b3315..daf4484 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -8,10 +8,11 @@ use crate::world::{ AffordanceId, AffordanceSnapshot, AuthorityGrant, Bounds, CommandId, CommitReceipt, Confidence, - ControllerMode, Cost, DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId, - EntityId, EntityKind, FactStandingView, KernelError, KnowledgeSnapshot, KnowledgeSource, - Magnitude, MailboxError, OfficeSnapshot, ProposedEffect, Quantity, RefKind, RoleBinding, - Statement, SubjectId, SubjectSnapshot, SubmitReceipt, Target, WorldMailbox, WorldSnapshot, + ControllerMode, ControllerPort, Cost, DecisionInvocation, DecisionOpportunity, + DependencyTarget, EdgeId, 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; @@ -1675,7 +1676,7 @@ enum ControllerWorldSubmission { } pub(crate) struct ControllerRunner { - mailbox: WorldMailbox, + mailbox: ControllerPort, inference: Arc, work: Arc, models: ControllerModels, @@ -1684,7 +1685,11 @@ pub(crate) struct ControllerRunner { impl ControllerRunner { /// Opens the complete production controller organ. Runtime supplies /// deployment configuration, but cannot replace either the inference - /// transport or the durable controller-work owner. + /// transport or the durable controller-work owner. The caller still hands + /// over a whole `WorldMailbox` — that stays the one owner-facing type — + /// but this constructor is where it narrows to a `ControllerPort` before + /// the runner ever sees it, so nothing inside this module can reach past + /// the five requests a controller lane makes. pub(crate) fn open( mailbox: WorldMailbox, connector_endpoint: SocketAddr, @@ -1703,7 +1708,7 @@ impl ControllerRunner { )?; let work = CultCacheControllerWorkStore::open(controller_work_path)?; Ok(Self { - mailbox, + mailbox: ControllerPort::new(mailbox), inference: Arc::new(inference), work: Arc::new(work), models, @@ -1718,7 +1723,7 @@ impl ControllerRunner { models: ControllerModels, ) -> Self { Self { - mailbox, + mailbox: ControllerPort::new(mailbox), inference, work, models, @@ -3804,6 +3809,41 @@ mod tests { assert!(decode_controller_work(&row).is_err()); } + /// The schema bump to `v5` refuses a prior store rather than migrating it + /// silently: `open` walks every row and demands both the row type and the + /// schema id match the current constants, so a `controller_work.v4` row + /// left over from before the bump is an open-time error, not a quietly + /// dropped or reinterpreted checkpoint. + #[test] + fn a_controller_work_v4_row_is_refused_at_open() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("controller-work.cc"); + let command_id = CommandId::new(); + let opportunity = fixture_opportunity(ControllerMode::OperationalAgent); + let work = operational_in_flight( + command_id, + &opportunity, + "Hold the bridge.", + "operational-model", + vec![], + ); + { + let mut store = OwnedRedbMessagePackBackingStore::new(&path).unwrap(); + let row = CultCacheEnvelope { + key: store_key(command_id).unwrap(), + r#type: "controller_work.v4".into(), + payload: rmp_serde::to_vec_named(&work).unwrap(), + stored_at: Utc::now().to_rfc3339(), + schema_id: Some("ghostlight.controller_work.v4".into()), + }; + store.push(&row).unwrap(); + } + let Err(error) = CultCacheControllerWorkStore::open(&path) else { + panic!("a v4 row was accepted by the v5 store"); + }; + assert!(matches!(error, ControllerWorkStoreError::Fault { .. })); + } + #[test] fn in_flight_progression_cannot_substitute_a_model() { let operational_command = CommandId::new(); diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index 5921163..b8dd80e 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -399,6 +399,73 @@ impl WorldMailbox { } } +/// The narrow port `ControllerRunner` is built against, instead of the whole +/// `WorldMailbox`. It forwards exactly the five requests a controller lane +/// makes today — a snapshot to read from, and the four commit paths a +/// controller may exercise or decline through — and names nothing else. In +/// particular it has no `operator_log` method: "no controller lane calls the +/// human operator's story feed" used to be a convention about who calls a +/// `pub(crate)` method on `WorldMailbox`. Now it is a fact about which methods +/// this type has. Adding `.operator_log()` to `controllers.rs` fails to +/// compile, because `ControllerPort` never named it; that failure is the +/// proof, not a test that runs and passes. +#[derive(Clone)] +pub(crate) struct ControllerPort { + mailbox: WorldMailbox, +} + +impl ControllerPort { + pub(crate) fn new(mailbox: WorldMailbox) -> Self { + Self { mailbox } + } + + pub(crate) async fn snapshot(&self) -> Result { + self.mailbox.snapshot().await + } + + pub(crate) async fn controller_receipt( + &self, + command_id: CommandId, + opportunity: &super::DecisionOpportunity, + invocation: &super::DecisionInvocation, + ) -> Result, MailboxError> { + self.mailbox + .controller_receipt(command_id, opportunity, invocation) + .await + } + + pub(crate) async fn controller_decline_receipt( + &self, + command_id: CommandId, + opportunity: &super::DecisionOpportunity, + ) -> Result, MailboxError> { + self.mailbox + .controller_decline_receipt(command_id, opportunity) + .await + } + + pub(crate) async fn submit_controller( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + invocation: DecisionInvocation, + ) -> Result { + self.mailbox + .submit_controller(command_id, opportunity, invocation) + .await + } + + pub(crate) async fn submit_controller_decline( + &self, + command_id: CommandId, + opportunity: &DecisionOpportunity, + ) -> Result { + self.mailbox + .submit_controller_decline(command_id, opportunity) + .await + } +} + fn mailbox_outcome(error: KernelError) -> MailboxError { match error { KernelError::RecoveryRequired { command_id } => MailboxError::OutcomeUnknown { command_id }, diff --git a/crates/ghostlight-dungeon/src/world/mod.rs b/crates/ghostlight-dungeon/src/world/mod.rs index 1bdbb4d..e4239f1 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -18,7 +18,7 @@ pub(crate) use controllers::{ NarrativeRun, OperationalCapture, OperationalDecision, OperationalPending, OperationalRun, SourceRange, SubmissionDisposition, TranslationGapSummary, }; -pub(crate) use mailbox::{MailboxError, WorldMailbox}; +pub(crate) use mailbox::{ControllerPort, MailboxError, WorldMailbox}; pub(crate) use patch::{ AccessKind, Affordance, AffordanceKindName, Audience, AuthoredSource, AuthorityGrant, AuthorityKindName, AuthorityTarget, Bounds, ChannelRecord, ComponentOpKind, Confidence, Cost, @@ -2090,7 +2090,7 @@ fn apply_operation( "a telling names no live speaker or fact".into(), )); } - if !audience(state, *speaker, to).contains(speaker) { + if !can_broadcast(state, *speaker, to) { return Err(KernelError::Invariant( "a speaker is outside its own audience".into(), )); @@ -2155,9 +2155,13 @@ fn apply_operation( } /// 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. +/// the statement is never copied into it and the label is never derived from +/// it. Labels resolve no references, so identical labels across every claim +/// are unremarkable. The statement itself lives in `facts[fact].statement` +/// and is also carried inside the committed `AssertClaim` effect on the +/// event that minted it; `facts` is the one readable home a projection may +/// consult, and the event copy is the replay witness, never a second read +/// surface. const CLAIM_LABEL: &str = "claim"; /// Whether a channel's reach and controller name live structure. @@ -2201,7 +2205,7 @@ fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet = match &record.reach { + match &record.reach { Reach::Subjects(members) => members.clone(), Reach::Place(root) => state .positions @@ -2211,17 +2215,32 @@ fn audience(state: &WorldState, actor: SubjectId, of: &Audience) -> BTreeSet bool { + if audience(state, actor, of).contains(&actor) { + return true; + } + match of { + Audience::Channel(channel) => state + .channels + .get(channel) + .is_some_and(|record| record.controller == Some(actor)), + Audience::Colocated => false, + } +} + /// 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 @@ -2999,9 +3018,10 @@ 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. + /// What a committed event actually asserted, read from the one readable + /// home of an utterance: `facts[fact].statement`. The committed event's + /// own `AssertClaim` effect carries the same bytes as the replay witness, + /// but no projection reads that copy; `facts` is the surface. pub(super) fn spoken<'a>(state: &'a WorldState, event: &DecisionEvent) -> Option<&'a str> { event .speech @@ -8212,13 +8232,11 @@ mod soul_knowledge_tests { .expect("a speech act names its claim") } - /// A channel's controller is folded into `audience` itself rather than only - /// into the `CanBroadcast` check, so it is a recipient of every telling on - /// its own channel and not merely a permitted speaker. A controller standing - /// outside its channel's reach therefore learns what is broadcast there. - /// - /// This test does not endorse that reach; it pins it, because the widening - /// is a knowledge path the declared reach does not describe. + /// A channel's controller carries exactly one privilege: `can_broadcast` + /// lets it sound the horn from outside the declared reach. `audience` + /// itself never folds the controller in, so the controller is not a + /// recipient of a telling it did not stand inside, whether the telling is + /// its own or another subject's. #[test] fn soul_a_channel_controller_hears_what_it_is_out_of_reach_of() { let directory = tempfile::tempdir().unwrap(); @@ -8239,6 +8257,37 @@ mod soul_knowledge_tests { Reach::Subjects(BTreeSet::from([speech.listener])) ); + // The controller may still speak from outside its own reach — the horn + // belongs to the temple — and the listener, who stands inside the + // reach, hears it. + utter( + &mut kernel, + &active, + speech.speaker, + say( + speech.proclaim, + vec![binding("channel", Target::Entity(speech.horn))], + "The horn is mine to sound.", + ), + ) + .expect("the controller may speak on its own channel"); + let controllers_claim = minted_claim(&kernel); + assert_eq!( + knows(&kernel, speech.listener, controllers_claim), + Some(Knowledge { + confidence: Confidence::Believed, + source: KnowledgeSource::Told { + by: speech.speaker, + via: Some(speech.horn), + }, + }) + ); + // The controller gains no knowledge of its own claim: it is outside + // the reach, and speaking privilege is not audience membership. + assert_eq!(knows(&kernel, speech.speaker, controllers_claim), None); + + // Now the listener speaks on the same channel. + let active = kernel.snapshot().unwrap(); utter( &mut kernel, &active, @@ -8253,17 +8302,12 @@ mod soul_knowledge_tests { let claim = minted_claim(&kernel); // The declared reach names the listener alone, and the listener spoke, - // so the declared fan-out is empty. The controller learns it anyway. + // so the declared fan-out is empty. The controller — outside the + // reach, and not the speaker this time either — learns nothing. assert_eq!( knows(&kernel, speech.speaker, claim), - Some(Knowledge { - confidence: Confidence::Believed, - source: KnowledgeSource::Told { - by: speech.listener, - via: Some(speech.horn), - }, - }), - "the controller is a recipient, not only a permitted speaker" + None, + "the controller does not gain knowledge through fan-out" ); assert_eq!(knows(&kernel, speech.bystander, claim), None); assert_eq!(knows(&kernel, speech.stranger, claim), None); @@ -8649,11 +8693,14 @@ mod soul_knowledge_tests { } } - /// The utterance does not have exactly one home in `WorldState`. It is the - /// minted claim's statement in `facts`, and it is also stored a second time - /// inside the committed event's own `AssertClaim` effect. Those two are the - /// whole of it, and neither reaches a subject-facing surface, but the - /// "one home" claim is false as written. + /// The statement's bytes are stored twice, and only one of the two copies + /// is a read surface. `facts[fact].statement` is the readable home: + /// `spoken()` and every projection consult it. The committed event's own + /// `AssertClaim` effect carries the same bytes as the replay witness — + /// required so `apply_effect` can re-derive the identical event on replay + /// without re-deriving the statement from elsewhere — but nothing reads + /// that copy back out. Those two are the whole of it, and neither reaches + /// a subject-facing surface. #[test] fn soul_the_utterance_is_stored_in_facts_and_in_the_committed_effect() { let directory = tempfile::tempdir().unwrap(); @@ -8686,7 +8733,7 @@ mod soul_knowledge_tests { statement: Statement::new(text).unwrap(), by: speech.speaker, }, - "the committed event stores the statement a second time" + "the event carries the statement as a replay witness, not a second read surface" ); // Those two are the whole of it: strip `facts` and `events` and the // rest of the state is silent. @@ -8709,9 +8756,12 @@ mod soul_knowledge_tests { /// `operator_log` is unscoped by construction: it renders every committed /// act's utterance regardless of who holds knowledge of it. That is correct /// for the human operator's story feed and is exactly why it must never - /// become reachable from a controller lane. `ControllerRunner` owns a - /// `WorldMailbox`, and `WorldMailbox::operator_log` is `pub(crate)`, so the - /// separation is a convention about who calls it, not a type boundary. + /// become reachable from a controller lane. `ControllerRunner` no longer + /// owns a `WorldMailbox`; it owns a `ControllerPort`, which forwards + /// exactly the five requests a controller lane makes and has no + /// `operator_log` method at all. The separation is a type boundary now: + /// `WorldMailbox::operator_log` stays `pub(crate)` for the operator/story + /// feed owner, but nothing inside `controllers.rs` can name it. #[test] fn soul_the_operator_log_is_unscoped_and_must_stay_owner_only() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index f1c7bce..2162a36 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -1674,7 +1674,10 @@ struct RouteCandidate { /// [`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. +/// are variable-width, so the concatenation is unambiguous — `discriminator` +/// included: a bare presence byte followed by a length prefix means +/// `Some("")` and `None` write different bytes, where an unprefixed +/// `Some("")` would have written nothing, same as `None`. pub(super) fn derive_id( namespace: &str, world_id: WorldId, @@ -1688,8 +1691,13 @@ pub(super) fn derive_id( hasher.update(command_id.0.as_bytes()); hasher.update((handle.0.len() as u64).to_be_bytes()); hasher.update(handle.0.as_bytes()); - if let Some(discriminator) = discriminator { - hasher.update(discriminator.as_bytes()); + match discriminator { + Some(discriminator) => { + hasher.update([1u8]); + hasher.update((discriminator.len() as u64).to_be_bytes()); + hasher.update(discriminator.as_bytes()); + } + None => hasher.update([0u8]), } let mut bytes = [0u8; 16]; bytes.copy_from_slice(&hasher.finalize()[..16]); @@ -2670,6 +2678,20 @@ pub(super) fn resolve_patch( // `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. + // + // This candidate map does not model `Communicate` at all — it has no case + // that inserts a `Told` entry into it, so it cannot answer "does this + // patch already know what a pending telling would land." That is safe + // today only because no `ComponentOp` can construct a `KnowledgeSource` + // carrying `Told`: `AcquireKnowledge` takes an `AuthoredSource`, and that + // type has exactly two variants, `Witnessed` and `Evidenced` — `Told` is + // unrepresentable there by construction (see `AuthoredSource`'s own doc + // comment), and `action::no_component_op_kind_lowers_to_a_told_knowledge_write` + // pins the one lowering site that could otherwise drift. If a future + // operation is ever given the power to write `Told` directly — bypassing + // `Communicate`'s own apply-time fan-out — it must model that fan-out into + // this candidate graph first, or `resolve_patch` will silently reason + // about a knowledge state the apply pass will not produce. let mut knowledge: BTreeMap<(Key, Key), KnowledgeCandidate> = state .knowledge .iter() @@ -5596,6 +5618,47 @@ mod tests { ); } + /// `discriminator` is length-prefixed like `handle`, so `Some("")` and + /// `None` write different bytes into the preimage and cannot collide — + /// and neither can any other pair of discriminators whose bytes would + /// otherwise concatenate to the same string. + #[test] + fn derive_id_does_not_collide_some_empty_discriminator_with_none() { + let directory = tempfile::tempdir().unwrap(); + let (kernel, _) = WorldKernel::create( + &directory.path().join("world.cc"), + creation(CommandId::new(), "DeriveId"), + &auth_principal(owner()), + ) + .unwrap(); + let world_id = kernel.state.world_id; + let command_id = CommandId::new(); + let handle = DraftHandle::new("a-handle"); + assert_ne!( + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, None), + derive_id(SUBJECT_NAMESPACE, world_id, command_id, &handle, Some("")), + ); + // A concatenation-style collision across the handle/discriminator + // boundary: without a length prefix on the discriminator, "ab" + "" + // and "a" + "b" would hash identically. + assert_ne!( + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("ab"), + Some(""), + ), + derive_id( + SUBJECT_NAMESPACE, + world_id, + command_id, + &DraftHandle::new("a"), + Some("b"), + ), + ); + } + /// The `PatchAdmitted` arm is not a trusting applier. A forged effect, a /// replayed one, a non-owner caller, and the Active phase each die inside /// `apply_effect`, without the journal's reduce-equality check running.