diff --git a/crates/ghostlight-dungeon/src/eve.rs b/crates/ghostlight-dungeon/src/eve.rs index 5dfbeca..907ad29 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::{AffordanceKind, ControllerMode, DecisionAction, WorldPhase, WorldSnapshot}, + world::{ControllerMode, WorldPhase, WorldSnapshot}, }; use anyhow::{Context, bail}; use chrono::{DateTime, Utc}; @@ -231,13 +231,15 @@ pub(crate) fn authenticated_surface( let story = world .events .iter() - .map(|event| match &event.invocation.action { - DecisionAction::Speak { text } => json!({ - "id":format!("world.event.{}", event.revision), - "kind":"text", - "props":{"value":text}, - "children":[] - }), + .filter_map(|event| { + event.invocation.speech.as_ref().map(|text| { + json!({ + "id":format!("world.event.{}", event.revision), + "kind":"text", + "props":{"value":text.as_str()}, + "children":[] + }) + }) }) .collect::>(); children.push(json!({ @@ -250,10 +252,20 @@ pub(crate) fn authenticated_surface( let principal = crate::world::PrincipalId::new(account); let opportunity = world.opportunities.iter().find_map(|opportunity| { world.subjects.iter().find_map(|subject| { - let affordance_id = subject.affordances.get(&AffordanceKind::Speak)?; + // The catalog entry is found by kind name among the + // subject's granted entries: the control is a + // projection of state, not a second vocabulary. + let affordance_id = world + .affordances + .iter() + .find(|entry| { + entry.entry.kind.0 == "speak" + && subject.affordances.contains(&entry.id) + }) + .map(|entry| entry.id)?; (subject.id == opportunity.scope.subject_id && subject.human_controller.as_ref() == Some(&principal) - && opportunity.affordance_ids.contains(affordance_id)) + && opportunity.affordance_ids.contains(&affordance_id)) .then_some((opportunity, affordance_id)) }) }); diff --git a/crates/ghostlight-dungeon/src/runtime.rs b/crates/ghostlight-dungeon/src/runtime.rs index ac2f6a4..f314c84 100644 --- a/crates/ghostlight-dungeon/src/runtime.rs +++ b/crates/ghostlight-dungeon/src/runtime.rs @@ -12,9 +12,9 @@ use crate::{ world::{ AffordanceId, CommandBody, CommandId, ControllerError, ControllerModels, ControllerPendingReason, ControllerRunner, ControllerWorkCustody, CreateWorldIntent, - DecisionAction, DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, - NarrativeRun, OperationalRun, PrincipalCommandIntent, PrincipalId, SubmissionDisposition, - SubmitReceipt, WorldMailbox, WorldSnapshot, + DecisionInvocation, DecisionOpportunity, KernelError, MailboxError, NarrativeRun, + OperationalRun, PrincipalCommandIntent, PrincipalId, SubmissionDisposition, SubmitReceipt, + Utterance, WorldMailbox, WorldSnapshot, }, }; use anyhow::{Context, bail, ensure}; @@ -1149,6 +1149,7 @@ fn controller_error_disposition(error: &ControllerError) -> &'static str { | ControllerError::AmbiguousOpportunity | ControllerError::OpportunityMismatch | ControllerError::SpeakUnavailable + | ControllerError::NoGrantedAffordance | ControllerError::CommandMismatch | ControllerError::MissingControllerWork | ControllerError::World(_) => "denied", @@ -1231,11 +1232,18 @@ async fn execute_world( "world.speak" => { let payload: SpeakPayload = serde_json::from_value(invocation.payload.clone()) .map_err(|error| RuntimeCommandError::Payload(error.to_string()))?; + // `world.speak` stays an ingress for the Speak entry specifically. + // A generic `world.act` is only useful beside per-affordance Eve + // controls derived from the catalog, and that is a projection pass. CommandBody::ExerciseDecision { opportunity: payload.opportunity, invocation: DecisionInvocation { - affordance_id: payload.affordance_id, - action: DecisionAction::Speak { text: payload.text }, + affordance: payload.affordance_id, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new(payload.text).ok_or_else(|| { + RuntimeCommandError::Payload("spoken text is not canonical".into()) + })?), }, } } @@ -1740,7 +1748,6 @@ fn sibling_state_lock_path(path: &std::path::Path) -> PathBuf { mod tests { use super::*; use crate::idunn_health::tests::route_observation_fixture; - use crate::world::AffordanceKind; use axum::{ body::{Body, to_bytes}, http::Request, @@ -2149,7 +2156,14 @@ mod tests { let world = current_world(&fixture.state).await.unwrap().unwrap(); let opportunity = world.opportunities[0].clone(); - let affordance = world.subjects[0].affordances[&AffordanceKind::Speak]; + let affordance = *world + .affordances + .iter() + .find(|entry| { + entry.entry.kind.0 == "speak" && world.subjects[0].affordances.contains(&entry.id) + }) + .map(|entry| &entry.id) + .unwrap(); let spoken = post( &fixture.state, &fixture.cookie, diff --git a/crates/ghostlight-dungeon/src/world/action.rs b/crates/ghostlight-dungeon/src/world/action.rs new file mode 100644 index 0000000..db4faf9 --- /dev/null +++ b/crates/ghostlight-dungeon/src/world/action.rs @@ -0,0 +1,1128 @@ +//! The invocation pipeline: catalog lookup, role binding, precondition +//! evaluation, effect-ceiling checking, band selection, and lowering. +//! +//! One entry point, [`exercise`], reached from `reduce`'s `ExerciseDecision` arm +//! and from `apply_effect`'s `DecisionExercised` arm, so a forged effect is +//! re-derived by the same function that produced the honest one. Nothing else +//! 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, +}; +use super::{ + AccessKind, AffordanceId, CommandId, DecisionEvent, DecisionInvocation, DecisionOpportunity, + EdgeId, EntityId, EventId, KernelError, Magnitude, SubjectId, Target, WorldId, WorldState, + digest, +}; +use serde::Serialize; +use std::collections::{BTreeMap, BTreeSet}; + +/// The complete failure set of one affordance invocation. Sorted and complete +/// like `Mismatch`, and like it never serialized: it states the affordance +/// contract, which no commit records. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum ActionMismatch { + UnboundRole { + role: Role, + }, + UnknownRole { + role: Role, + }, + DuplicateRoleBinding { + role: Role, + }, + UnknownTarget { + role: Role, + }, + TargetKindMismatch { + role: Role, + expected: RefKind, + actual: RefKind, + }, + ActorNotPresent { + precondition: usize, + }, + TargetUnreachable { + precondition: usize, + }, + InsufficientHolding { + precondition: usize, + }, + SlotNotProposed { + slot: usize, + }, + UnknownSlot { + slot: usize, + }, + DuplicateSlotProposal { + slot: usize, + }, + MagnitudeShapeMismatch { + slot: usize, + }, + MagnitudeOverCeiling { + slot: usize, + }, + ZeroMagnitude { + slot: usize, + }, + SpeechRequired, + SpeechNotCarried, + EmptySpeech, +} + +/// The band draw's whole preimage. Five fields, none of them from the +/// invocation's payload: the proposer varies the attempt and cannot vary the +/// draw. `affordance` is the kernel-resolved granted entry, checked against the +/// grants before this value is built. +#[derive(Serialize)] +struct BandPreimage { + world_id: WorldId, + revision: u64, + command_id: CommandId, + affordance: AffordanceId, + band_count: usize, +} + +/// Catalog lookup, binding, admission, draw, lowering, event. Stages 1 through 4 +/// accumulate one complete rejection set and return it sorted before anything is +/// drawn or lowered, so nothing past the gate can fail on caller input. +pub(super) fn exercise( + state: &WorldState, + command_id: CommandId, + current: &DecisionOpportunity, + invocation: &DecisionInvocation, +) -> Result { + let entry = state + .affordance_catalog + .get(&invocation.affordance) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into()))?; + let actor = current.scope.subject_id; + let mut rejections = Vec::new(); + + let bindings = bind_roles(state, entry, invocation, &mut rejections); + check_preconditions(state, actor, entry, &bindings, &mut rejections); + check_proposals(entry, invocation, &mut rejections); + + if !rejections.is_empty() { + rejections.sort(); + return Err(KernelError::ActionRejected(rejections)); + } + + let band = select_band(state, command_id, invocation.affordance, entry)?; + let operations = lower(entry, band, invocation, &bindings)?; + let effects = if operations.is_empty() { + Vec::new() + } else { + // The same resolver, the same per-operation preconditions, the same + // conservation equation the declaration lane passes. + patch::resolve_patch( + state, + command_id, + &WorldPatch { + declarations: Vec::new(), + operations, + evidence: Vec::new(), + }, + ) + .map_err(KernelError::PatchRejected)? + .operations + }; + + let revision = state + .revision + .checked_add(1) + .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; + Ok(DecisionEvent { + id: EventId::for_command(command_id), + revision, + scope: current.scope, + controller_id: current.controller_id, + invocation: invocation.clone(), + band, + effects, + }) +} + +/// Stage 2. The acting subject is never a role: it is always the scope's own +/// subject. A binding that happens to name the actor is legal and unremarkable. +fn bind_roles( + state: &WorldState, + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) -> BTreeMap { + let declared: BTreeMap<&Role, RefKind> = entry + .roles + .iter() + .map(|spec| (&spec.role, spec.kind)) + .collect(); + let mut bound: BTreeMap = BTreeMap::new(); + let mut seen: BTreeSet<&Role> = BTreeSet::new(); + for binding in &invocation.bindings { + if !seen.insert(&binding.role) { + rejections.push(ActionMismatch::DuplicateRoleBinding { + role: binding.role.clone(), + }); + continue; + } + let Some(expected) = declared.get(&binding.role).copied() else { + rejections.push(ActionMismatch::UnknownRole { + role: binding.role.clone(), + }); + continue; + }; + let Some(actual) = live_kind(state, binding.target) else { + rejections.push(ActionMismatch::UnknownTarget { + role: binding.role.clone(), + }); + continue; + }; + let fits = match (expected, actual) { + (RefKind::Subject(None), RefKind::Subject(_)) => true, + (expected, actual) => expected == actual, + }; + if fits { + bound.insert(binding.role.clone(), binding.target); + } else { + rejections.push(ActionMismatch::TargetKindMismatch { + role: binding.role.clone(), + expected, + actual, + }); + } + } + for spec in &entry.roles { + if !seen.contains(&spec.role) { + rejections.push(ActionMismatch::UnboundRole { + role: spec.role.clone(), + }); + } + } + bound +} + +/// What a target actually is in committed state. `None` means the target keys no +/// live partition in its namespace. +fn live_kind(state: &WorldState, target: Target) -> Option { + match target { + Target::Subject(subject_id) => state + .subjects + .get(&subject_id) + .map(|subject| RefKind::Subject(Some(subject.kind))), + Target::Entity(entity_id) => state + .entities + .get(&entity_id) + .map(|record| RefKind::Entity(record.kind)), + Target::Edge(edge_id) => state + .edges + .get(&edge_id) + .map(|_| RefKind::Edge(patch::EdgeKind::Route)), + } +} + +/// Stage 3, in declaration order, each failure carrying its index so a test can +/// name the exact precondition that refused. +fn check_preconditions( + state: &WorldState, + actor: SubjectId, + entry: &Affordance, + bindings: &BTreeMap, + rejections: &mut Vec, +) { + for (index, precondition) in entry.preconditions.iter().enumerate() { + match precondition { + Precondition::Present { at } => { + let Some(Target::Entity(place)) = bindings.get(at).copied() else { + continue; + }; + if state.positions.get(&actor).map(|position| position.place) != Some(place) { + rejections.push(ActionMismatch::ActorNotPresent { + precondition: index, + }); + } + } + Precondition::Reachable { to, within } => { + let Some(Target::Entity(place)) = bindings.get(to).copied() else { + continue; + }; + if !reachable(state, actor, place, *within) { + rejections.push(ActionMismatch::TargetUnreachable { + precondition: index, + }); + } + } + Precondition::Holds { resource, at_least } => { + let Some(Target::Entity(entity_id)) = bindings.get(resource).copied() else { + continue; + }; + let held = state + .holdings + .get(&actor) + .and_then(|held| held.get(&entity_id)) + .map_or(0, |quantity| quantity.0); + if held < at_least.0 { + rejections.push(ActionMismatch::InsufficientHolding { + precondition: index, + }); + } + } + } + } +} + +/// Dijkstra over the live route graph, admitting only open public routes and +/// relaxing in `EdgeId` order, pruning any path whose accumulated cost exceeds +/// `within`. Cost 0 — already standing there — succeeds; `Present` is the strict +/// form. An unplaced actor reaches nothing. +/// +/// This reads routes the scope digest does not cover, which is deliberate: the +/// alternative binds a proposal to a transitively large slice of world topology +/// and rejects it whenever anything near the actor commits. Admission runs at +/// commit against live state instead, so a route that closed while the proposal +/// was in flight makes this fail rather than letting a stale path commit. +fn reachable(state: &WorldState, actor: SubjectId, destination: EntityId, within: Cost) -> bool { + let Some(origin) = state.positions.get(&actor).map(|position| position.place) else { + return false; + }; + let mut best: BTreeMap = BTreeMap::from([(origin, 0)]); + let mut settled: BTreeSet = BTreeSet::new(); + let ceiling = u64::from(within.0); + loop { + let Some((place, cost)) = best + .iter() + .filter(|(place, _)| !settled.contains(place)) + .min_by_key(|(place, cost)| (**cost, **place)) + .map(|(place, cost)| (*place, *cost)) + else { + return false; + }; + if place == destination { + return true; + } + settled.insert(place); + let outbound: Vec<(EdgeId, EntityId, u64)> = state + .edges + .iter() + .filter(|(_, record)| record.is_open() && record.access() == AccessKind::Public) + .filter_map(|(edge_id, record)| { + let (from, to) = record.endpoints(); + let next = if from == place { + to + } else if to == place { + from + } else { + return None; + }; + Some((*edge_id, next, u64::from(record.cost().0))) + }) + .collect(); + for (_, next, step) in outbound { + let total = cost + step; + if total <= ceiling && best.get(&next).is_none_or(|known| total < *known) { + best.insert(next, total); + } + } + } +} + +/// Stage 4. Every slot is checked, not just the ones the selected band names: +/// the proposer cannot see the band, so it commits to a complete attempt, and +/// checking every slot makes the ceiling total. +fn check_proposals( + entry: &Affordance, + invocation: &DecisionInvocation, + rejections: &mut Vec, +) { + let mut seen: BTreeSet = BTreeSet::new(); + for proposed in &invocation.proposed { + if !seen.insert(proposed.slot) { + rejections.push(ActionMismatch::DuplicateSlotProposal { + slot: proposed.slot, + }); + continue; + } + let Some(slot) = entry.effect_slots.get(proposed.slot) else { + rejections.push(ActionMismatch::UnknownSlot { + slot: proposed.slot, + }); + continue; + }; + match (slot.bounds, proposed.magnitude) { + (Bounds::None, Magnitude::None) => {} + (Bounds::Quantity(ceiling), Magnitude::Quantity(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + (Bounds::Cost(ceiling), Magnitude::Cost(value)) => { + if value.0 == 0 { + rejections.push(ActionMismatch::ZeroMagnitude { + slot: proposed.slot, + }); + } else if value.0 > ceiling.0 { + rejections.push(ActionMismatch::MagnitudeOverCeiling { + slot: proposed.slot, + }); + } + } + _ => rejections.push(ActionMismatch::MagnitudeShapeMismatch { + slot: proposed.slot, + }), + } + } + for slot in 0..entry.effect_slots.len() { + if !seen.contains(&slot) { + rejections.push(ActionMismatch::SlotNotProposed { slot }); + } + } + // `Utterance` 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) { + (None, true) => rejections.push(ActionMismatch::SpeechRequired), + (Some(_), false) => rejections.push(ActionMismatch::SpeechNotCarried), + (Some(speech), true) if !patch::is_canonical_text(speech.as_str()) => { + rejections.push(ActionMismatch::EmptySpeech); + } + _ => {} + } +} + +/// The only entropy in the kernel: one digest, one modulo, one cumulative walk. +/// Modulo rather than rejection sampling — the bias is bounded by +/// `total_weight / 2^64`, and a rejection loop would need its counter in the +/// preimage, which is a second entropy shape for a rounding error nobody can +/// measure. +fn select_band( + state: &WorldState, + command_id: CommandId, + affordance: AffordanceId, + entry: &Affordance, +) -> Result { + let draw = digest(&BandPreimage { + world_id: state.world_id, + revision: state.revision, + command_id, + affordance, + band_count: entry.outcome_bands.len(), + })?; + let head = draw + .strip_prefix("sha256:") + .and_then(|hex| hex.get(..16)) + .and_then(|head| u64::from_str_radix(head, 16).ok()) + .ok_or_else(|| KernelError::Invariant("band draw digest is not hex".into()))?; + let total: u128 = entry + .outcome_bands + .iter() + .map(|band| u128::from(band.weight)) + .sum(); + if total == 0 { + return Err(KernelError::Invariant( + "affordance has no outcome band".into(), + )); + } + let mut position = u128::from(head) % total; + for (index, band) in entry.outcome_bands.iter().enumerate() { + let weight = u128::from(band.weight); + if position < weight { + return Ok(index); + } + position -= weight; + } + Err(KernelError::Invariant( + "band weights did not cover the draw".into(), + )) +} + +/// Stage 7. One arm per `ComponentOpKind`, every referent read from the slot's +/// roles resolved through the bindings, every magnitude from the proposal for +/// that slot. An empty band lowers to nothing. +fn lower( + entry: &Affordance, + band: usize, + invocation: &DecisionInvocation, + bindings: &BTreeMap, +) -> Result, KernelError> { + let malformed = || KernelError::Invariant("admitted affordance slot is malformed".into()); + let band = entry + .outcome_bands + .get(band) + .ok_or_else(|| KernelError::Invariant("selected band does not exist".into()))?; + let mut operations = Vec::new(); + for slot_index in &band.effects { + let slot = entry.effect_slots.get(*slot_index).ok_or_else(malformed)?; + let magnitude = invocation + .proposed + .iter() + .find(|proposed| proposed.slot == *slot_index) + .map(|proposed| proposed.magnitude) + .ok_or_else(malformed)?; + let target = |position: usize| -> Result { + slot.roles + .get(position) + .and_then(|role| bindings.get(role)) + .copied() + .ok_or_else(malformed) + }; + let subject = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Subject(subject_id) => Ok(patch::Ref::Existing(subject_id)), + _ => Err(malformed()), + } + }; + let entity = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Entity(entity_id) => Ok(patch::Ref::Existing(entity_id)), + _ => Err(malformed()), + } + }; + let edge = |position: usize| -> Result, KernelError> { + match target(position)? { + Target::Edge(edge_id) => Ok(patch::Ref::Existing(edge_id)), + _ => Err(malformed()), + } + }; + let quantity = || -> Result { + match magnitude { + Magnitude::Quantity(value) => Ok(value), + _ => Err(malformed()), + } + }; + let dependency = |position: usize| -> Result { + Ok(match target(position)? { + Target::Subject(subject_id) => { + patch::DependencyRef::Subject(patch::Ref::Existing(subject_id)) + } + Target::Entity(entity_id) => { + patch::DependencyRef::Resource(patch::Ref::Existing(entity_id)) + } + Target::Edge(edge_id) => patch::DependencyRef::Route(patch::Ref::Existing(edge_id)), + }) + }; + operations.push(match slot.op_kind { + ComponentOpKind::Relocate => patch::ComponentOp::Relocate { + subject: subject(0)?, + via: edge(1)?, + }, + ComponentOpKind::OpenRoute => patch::ComponentOp::OpenRoute { route: edge(0)? }, + ComponentOpKind::CloseRoute => patch::ComponentOp::CloseRoute { route: edge(0)? }, + ComponentOpKind::AlterCost => patch::ComponentOp::AlterCost { + route: edge(0)?, + cost: match magnitude { + Magnitude::Cost(value) => value, + _ => return Err(malformed()), + }, + }, + ComponentOpKind::Transfer => patch::ComponentOp::Transfer { + from: subject(0)?, + to: subject(1)?, + resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Transform => patch::ComponentOp::Transform { + holder: subject(0)?, + from_resource: entity(1)?, + into_resource: entity(2)?, + qty: quantity()?, + }, + ComponentOpKind::Consume => patch::ComponentOp::Consume { + holder: subject(0)?, + resource: entity(1)?, + qty: quantity()?, + }, + ComponentOpKind::Bind => patch::ComponentOp::Bind { + subject: subject(0)?, + target: dependency(1)?, + }, + ComponentOpKind::Release => patch::ComponentOp::Release { + subject: subject(0)?, + target: dependency(1)?, + }, + }); + } + Ok(operations) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::world::custody_tests::custody_kernel; + use crate::world::patch::{ComponentOp, Ref as PatchRef, ResolvedOp}; + use crate::world::tests::{ + OPENING_BALANCE, activate, affordance_named, auth_principal, command, custody_world, + operations, opportunity_for, player, submit_owner, + }; + use crate::world::{ + AuthenticatedCaller, CallerId, CommandBody, EntityKind, ProposedEffect, RoleBinding, + SubmitReceipt, Utterance, WorldEffect, WorldKernel, WorldSnapshot, apply_effect, + }; + use std::collections::BTreeSet; + + struct Bench { + kernel: WorldKernel, + active: WorldSnapshot, + carry: AffordanceId, + clerk: SubjectId, + keeper: SubjectId, + tithe: EntityId, + ingot: EntityId, + yard: EntityId, + gate: EntityId, + shutter: EdgeId, + } + + fn bench(directory: &std::path::Path, title: &str) -> Bench { + let mut kernel = custody_kernel(directory, title); + let (topology, custody, active) = custody_world(&mut kernel); + let carry = affordance_named(&active, "carry"); + Bench { + kernel, + active, + carry, + clerk: custody.holder, + keeper: custody.counterparty, + tithe: custody.tithe, + ingot: custody.ingot, + yard: topology.yard, + gate: topology.gate, + shutter: topology.shutter, + } + } + + fn binding(role: &str, target: Target) -> RoleBinding { + RoleBinding { + role: Role(role.into()), + target, + } + } + + impl Bench { + /// A Carry the clerk proposes. The actor is never a role, so a Carry + /// that moves the actor's own goods binds `from` to its own id. + fn carry_of(&self, qty: u64, place: EntityId, resource: EntityId) -> DecisionInvocation { + DecisionInvocation { + affordance: self.carry, + bindings: vec![ + binding("from", Target::Subject(self.clerk)), + binding("recipient", Target::Subject(self.keeper)), + binding("place", Target::Entity(place)), + binding("resource", Target::Entity(resource)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(qty)), + }], + speech: None, + } + } + + fn carry(&self, qty: u64, place: EntityId) -> DecisionInvocation { + self.carry_of(qty, place, self.tithe) + } + + fn clerk_opportunity(&self) -> DecisionOpportunity { + opportunity_for(&self.active, self.clerk) + } + + fn try_exercise( + &self, + invocation: &DecisionInvocation, + ) -> Result { + exercise( + &self.kernel.state, + CommandId::issue(), + &self.clerk_opportunity(), + invocation, + ) + } + + fn rejections(&self, invocation: &DecisionInvocation) -> Vec { + match self.try_exercise(invocation) { + Err(KernelError::ActionRejected(rejected)) => rejected, + other => panic!("expected an action rejection, got {other:?}"), + } + } + + fn commit(&mut self, invocation: DecisionInvocation) -> SubmitReceipt { + let opportunity = self.clerk_opportunity(); + let caller = CallerId::Controller(opportunity.controller_id); + self.kernel + .submit( + command( + &self.active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity, + invocation, + }, + ), + &AuthenticatedCaller::fixture(caller), + ) + .expect("the invocation commits") + } + + fn held(&self, holder: SubjectId) -> u64 { + self.kernel + .state + .holdings + .get(&holder) + .and_then(|held| held.get(&self.tithe)) + .map_or(0, |quantity| quantity.0) + } + + /// The same Carry attempt against a sibling entry: one dial moved, one + /// name. The catalog is Draft-only, so a variant is declared rather + /// than patched into committed state. + fn variant(&self, invocation: &DecisionInvocation, kind: &str) -> DecisionInvocation { + DecisionInvocation { + affordance: affordance_named(&self.active, kind), + ..invocation.clone() + } + } + + fn refresh(&mut self) { + self.active = self.kernel.snapshot().unwrap(); + } + } + + #[test] + fn a_missing_present_precondition_names_itself() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Present"); + let before = bench.kernel.state.clone(); + + // The clerk stands in the yard, so a Carry bound to the gate fails the + // first precondition and nothing else. + assert_eq!( + bench.rejections(&bench.carry(1, bench.gate)), + vec![ActionMismatch::ActorNotPresent { precondition: 0 }] + ); + assert_eq!(bench.kernel.state.revision, before.revision); + assert_eq!(bench.kernel.state.holdings, before.holdings); + assert_eq!(bench.kernel.state.events, before.events); + } + + #[test] + fn spending_more_than_held_fails_the_holds_precondition() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Holds"); + let greedy = bench.variant(&bench.carry(1, bench.yard), "carry_greedy"); + assert_eq!( + bench.rejections(&greedy), + vec![ActionMismatch::InsufficientHolding { precondition: 1 }] + ); + + // Absence is zero, so a resource the clerk holds none of gives the same + // name at the boundary rather than a second one. + let ingot = bench.variant(&bench.carry_of(1, bench.yard, bench.ingot), "carry_holds"); + assert_eq!( + bench.rejections(&ingot), + vec![ActionMismatch::InsufficientHolding { precondition: 0 }] + ); + } + + #[test] + fn a_reachable_precondition_reads_only_open_public_routes() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Reachable"); + // Yard to gate over open public routes is the ramp (12) plus the span + // (7): the shutter is closed and the toll stair is restricted. A budget + // of NEAR_REACH covers only the shutter, FAR_REACH covers the two-hop + // path. + let attempt = bench.carry(1, bench.gate); + let near = bench.variant(&attempt, "carry_near"); + let far = bench.variant(&attempt, "carry_far"); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + assert!(bench.try_exercise(&far).is_ok()); + + // Opening the one-hop shutter shortens the path, and closing it again + // restores the two-hop cost: the check reads the live graph rather than + // anything the proposal was bound against. + let before = bench.kernel.snapshot().unwrap(); + submit_owner( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::OpenRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert!(bench.try_exercise(&near).is_ok()); + + let before = bench.kernel.snapshot().unwrap(); + submit_owner( + &mut bench.kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: PatchRef::Existing(bench.shutter), + }]), + ); + bench.refresh(); + assert_eq!( + bench.rejections(&near), + vec![ActionMismatch::TargetUnreachable { precondition: 0 }] + ); + } + + #[test] + fn an_unbound_or_miskinded_role_is_rejected_with_the_complete_set() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Roles"); + let mut invocation = bench.carry(1, bench.yard); + // Drop `recipient`, add an undeclared role, and bind `resource` to a + // place: one rejection carrying all three, sorted. + invocation.bindings = vec![ + binding("from", Target::Subject(bench.clerk)), + binding("place", Target::Entity(bench.yard)), + binding("resource", Target::Entity(bench.yard)), + binding("porter", Target::Subject(bench.keeper)), + ]; + let mut expected = vec![ + ActionMismatch::UnboundRole { + role: Role("recipient".into()), + }, + ActionMismatch::UnknownRole { + role: Role("porter".into()), + }, + ActionMismatch::TargetKindMismatch { + role: Role("resource".into()), + expected: RefKind::Entity(EntityKind::Resource), + actual: RefKind::Entity(EntityKind::Place), + }, + ]; + expected.sort(); + assert_eq!(bench.rejections(&invocation), expected); + } + + #[test] + fn a_duplicated_or_unknown_binding_target_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Bindings"); + let mut twice = bench.carry(1, bench.yard); + twice + .bindings + .push(binding("resource", Target::Entity(bench.tithe))); + assert!( + bench + .rejections(&twice) + .contains(&ActionMismatch::DuplicateRoleBinding { + role: Role("resource".into()) + }) + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.bindings[3] = binding("resource", Target::Entity(EntityId::issue())); + assert!( + bench + .rejections(&unknown) + .contains(&ActionMismatch::UnknownTarget { + role: Role("resource".into()) + }) + ); + } + + #[test] + fn a_magnitude_over_its_slot_ceiling_is_rejected_and_within_it_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Ceiling"); + assert_eq!( + bench.rejections(&bench.carry(4, bench.yard)), + vec![ActionMismatch::MagnitudeOverCeiling { slot: 0 }] + ); + + let clerk_before = bench.held(bench.clerk); + let keeper_before = bench.held(bench.keeper); + let receipt = bench.commit(bench.carry(3, bench.yard)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(bench.held(bench.clerk), clerk_before - 3); + assert_eq!(bench.held(bench.keeper), keeper_before + 3); + assert_eq!( + bench.held(bench.clerk) + bench.held(bench.keeper), + clerk_before + keeper_before, + "the conserved total is unchanged" + ); + } + + #[test] + fn a_magnitude_of_the_wrong_shape_or_zero_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Shape"); + for magnitude in [Magnitude::Cost(Cost(2)), Magnitude::None] { + let mut invocation = bench.carry(1, bench.yard); + invocation.proposed[0].magnitude = magnitude; + assert_eq!( + bench.rejections(&invocation), + vec![ActionMismatch::MagnitudeShapeMismatch { slot: 0 }] + ); + } + assert_eq!( + bench.rejections(&bench.carry(0, bench.yard)), + vec![ActionMismatch::ZeroMagnitude { slot: 0 }] + ); + } + + #[test] + fn every_slot_must_be_proposed_exactly_once() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Slots"); + let mut missing = bench.carry(1, bench.yard); + missing.proposed.clear(); + assert_eq!( + bench.rejections(&missing), + vec![ActionMismatch::SlotNotProposed { slot: 0 }] + ); + + let mut twice = bench.carry(1, bench.yard); + twice.proposed.push(twice.proposed[0]); + assert_eq!( + bench.rejections(&twice), + vec![ActionMismatch::DuplicateSlotProposal { slot: 0 }] + ); + + let mut unknown = bench.carry(1, bench.yard); + unknown.proposed.push(ProposedEffect { + slot: 7, + magnitude: Magnitude::None, + }); + assert_eq!( + bench.rejections(&unknown), + vec![ActionMismatch::UnknownSlot { slot: 7 }] + ); + } + + #[test] + fn speech_is_required_exactly_when_the_entry_carries_it() { + 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()); + assert_eq!( + bench.rejections(&spoken_carry), + vec![ActionMismatch::SpeechNotCarried] + ); + + let speak = affordance_named(&bench.active, "speak"); + let mut silent_speak = DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: None, + }; + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::SpeechRequired] + ); + + // `Utterance` 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()); + assert_eq!( + bench.rejections(&silent_speak), + vec![ActionMismatch::EmptySpeech] + ); + } + + #[test] + fn the_same_command_id_always_selects_the_same_band() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "Bands"); + // Three equally weighted bands, so the draw alone decides. + let opportunity = bench.clerk_opportunity(); + let invocation = bench.variant(&bench.carry(1, bench.yard), "carry_chance"); + let draw = |command_id: CommandId, invocation: &DecisionInvocation| { + exercise(&bench.kernel.state, command_id, &opportunity, invocation) + .expect("the invocation is admissible") + .band + }; + + let command_id = CommandId::issue(); + let fixed = draw(command_id, &invocation); + for _ in 0..100 { + assert_eq!(draw(command_id, &invocation), fixed); + } + + // No caller-supplied value influences the draw: not a binding order, + // not a magnitude. + let mut reordered = invocation.clone(); + reordered.bindings.reverse(); + assert_eq!(draw(command_id, &reordered), fixed); + let mut heavier = invocation.clone(); + heavier.proposed[0].magnitude = Magnitude::Quantity(Quantity(3)); + assert_eq!(draw(command_id, &heavier), fixed); + + // The command id is the only varying term at one revision. + let mut seen = BTreeSet::new(); + for _ in 0..64 { + seen.insert(draw(CommandId::issue(), &invocation)); + } + assert!( + seen.len() > 1, + "varying only the command id must reach more than one band" + ); + } + + #[test] + fn a_zero_effect_band_commits_nothing_but_the_event() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "EmptyBand"); + let idle = bench.variant(&bench.carry(3, bench.yard), "carry_idle"); + + let holdings = bench.kernel.state.holdings.clone(); + let positions = bench.kernel.state.positions.clone(); + let edges = bench.kernel.state.edges.clone(); + let revision = bench.kernel.state.revision; + + let event = bench + .try_exercise(&idle) + .expect("an empty band is admissible"); + assert_eq!(event.band, 0); + assert!(event.effects.is_empty()); + + let receipt = bench.commit(idle); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(bench.kernel.state.holdings, holdings); + assert_eq!(bench.kernel.state.positions, positions); + assert_eq!(bench.kernel.state.edges, edges); + assert_eq!(bench.kernel.state.events.len(), 1); + assert_eq!(bench.kernel.state.revision, revision + 1); + } + + #[test] + fn a_committed_event_carries_the_exact_lowered_operations() { + let directory = tempfile::tempdir().unwrap(); + let mut bench = bench(directory.path(), "Lowering"); + let receipt = bench.commit(bench.carry(2, bench.yard)); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = bench + .kernel + .state + .events + .last() + .expect("the committed event"); + assert_eq!( + event.effects, + vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(2), + }] + ); + } + + #[test] + fn a_forged_band_or_forged_effect_does_not_apply() { + let directory = tempfile::tempdir().unwrap(); + let bench = bench(directory.path(), "ForgedAction"); + let opportunity = bench.clerk_opportunity(); + let command_id = CommandId::issue(); + let honest = exercise( + &bench.kernel.state, + command_id, + &opportunity, + &bench.carry(2, bench.yard), + ) + .unwrap(); + let caller = CallerId::Controller(opportunity.controller_id); + + for forged in [ + DecisionEvent { + band: 3, + ..honest.clone() + }, + DecisionEvent { + effects: vec![ResolvedOp::Transfer { + from: bench.clerk, + to: bench.keeper, + resource: bench.tithe, + qty: Quantity(OPENING_BALANCE), + }], + ..honest.clone() + }, + ] { + let mut candidate = bench.kernel.state.clone(); + let error = apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity: opportunity.clone(), + event: forged, + }, + ) + .unwrap_err(); + assert!(matches!(error, KernelError::Invariant(_))); + assert_eq!(candidate, bench.kernel.state); + } + + // The honest event still applies through the same arm. + let mut candidate = bench.kernel.state.clone(); + apply_effect( + &mut candidate, + command_id, + &caller, + &WorldEffect::DecisionExercised { + opportunity, + event: honest, + }, + ) + .unwrap(); + assert_ne!(candidate.holdings, bench.kernel.state.holdings); + } + + #[test] + fn the_kernel_speak_entry_commits_its_utterance_and_no_operation() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = custody_kernel(directory.path(), "SpeakEntry"); + let _topology = activate(&mut kernel); + let active = kernel.snapshot().unwrap(); + let speak = affordance_named(&active, "speak"); + let human = active + .subjects + .iter() + .find(|subject| subject.human_controller.is_some()) + .expect("the human subject") + .id; + let holdings = kernel.state.holdings.clone(); + let receipt = kernel + .submit( + command( + &active, + CommandId::new(), + CallerId::Principal(player()), + CommandBody::ExerciseDecision { + opportunity: opportunity_for(&active, human), + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("I open the door.").unwrap()), + }, + }, + ), + &auth_principal(player()), + ) + .expect("the Speak entry commits"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + let event = kernel.state.events.last().unwrap(); + assert_eq!(event.band, 0); + assert!(event.effects.is_empty()); + assert_eq!( + event.invocation.speech.as_ref().map(Utterance::as_str), + Some("I open the door.") + ); + assert_eq!(kernel.state.holdings, holdings); + } +} diff --git a/crates/ghostlight-dungeon/src/world/controllers.rs b/crates/ghostlight-dungeon/src/world/controllers.rs index 8d5adfd..5da16de 100644 --- a/crates/ghostlight-dungeon/src/world/controllers.rs +++ b/crates/ghostlight-dungeon/src/world/controllers.rs @@ -7,9 +7,10 @@ //! affordance fields. use crate::world::{ - AffordanceId, AffordanceKind, CommandId, CommitReceipt, ControllerMode, DecisionAction, - DecisionInvocation, DecisionOpportunity, DependencyTarget, KernelError, MailboxError, - SubjectId, SubjectSnapshot, SubmitReceipt, WorldMailbox, WorldSnapshot, + AffordanceId, AffordanceSnapshot, Bounds, CommandId, CommitReceipt, ControllerMode, Cost, + DecisionInvocation, DecisionOpportunity, DependencyTarget, EdgeId, EntityId, EntityKind, + KernelError, Magnitude, MailboxError, ProposedEffect, Quantity, RefKind, RoleBinding, + SubjectId, SubjectSnapshot, SubmitReceipt, Target, Utterance, WorldMailbox, WorldSnapshot, }; use async_trait::async_trait; use chrono::Utc; @@ -44,10 +45,18 @@ 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.v3"; -const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v3"; +const CONTROLLER_WORK_ROW: &str = "controller_work.v4"; +const CONTROLLER_WORK_SCHEMA: &str = "ghostlight.controller_work.v4"; -const SPEAK_TOOL: &str = "speak"; +/// 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 +/// is a projection of a catalog entry. +const INTERPRETER_SPEAK_TOOL: &str = "speak"; + +/// The kind name the narrative lane looks for among its granted entries. The +/// kernel carries the name and branches on it nowhere; matching on it here is a +/// consumer reading data, which is where genre belongs. +const SPEAK_KIND: &str = "speak"; const RECORD_GAP_TOOL: &str = "record_gap"; const RECORD_NEED_TOOL: &str = "record_need"; const FINISH_INTERPRETATION_TOOL: &str = "finish_interpretation"; @@ -359,7 +368,7 @@ enum NarrativeCheckpoint { persona_model: String, interpreter_model: String, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + granted: Vec, invocation: PreparedInference, }, Persona { @@ -368,7 +377,7 @@ enum NarrativeCheckpoint { typed_view: String, interpreter_model: String, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + granted: Vec, projector_output: InferenceOutput, invocation: PreparedInference, }, @@ -377,7 +386,7 @@ enum NarrativeCheckpoint { turn: PersonaTurn, interpreter_prompt: String, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + granted: Vec, completed: Vec, invocation: PreparedInference, }, @@ -386,7 +395,7 @@ enum NarrativeCheckpoint { turn: PersonaTurn, interpreter_prompt: String, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + granted: Vec, completed: Vec, }, NoProposal { @@ -405,7 +414,7 @@ enum OperationalCheckpoint { command_id: CommandId, agent_prompt: String, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + granted: Vec, completed: Vec, invocation: PreparedInference, }, @@ -413,7 +422,7 @@ enum OperationalCheckpoint { command_id: CommandId, agent_prompt: String, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + granted: Vec, completed: Vec, }, NoProposal { @@ -496,14 +505,14 @@ impl NarrativeCheckpoint { persona_model, interpreter_model, opportunity, - speak_affordance, + granted, invocation, } => { base_checkpoint_is_valid( identity, typed_view, opportunity, - *speak_affordance, + granted, ControllerMode::NarrativePersona, ) && canonical_model(persona_model) && canonical_model(interpreter_model) @@ -521,7 +530,7 @@ impl NarrativeCheckpoint { typed_view, interpreter_model, opportunity, - speak_affordance, + granted, projector_output, invocation, } => { @@ -541,7 +550,7 @@ impl NarrativeCheckpoint { identity, typed_view, opportunity, - *speak_affordance, + granted, ControllerMode::NarrativePersona, ) && canonical_model(interpreter_model) && canonical_model(&invocation.invocation.request.model) @@ -556,13 +565,13 @@ impl NarrativeCheckpoint { turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed, invocation, } => { turn_matches_opportunity(turn, opportunity) && opportunity.controller_mode == ControllerMode::NarrativePersona - && opportunity.affordance_ids.contains(speak_affordance) + && granted_matches_opportunity(granted, opportunity) && !interpreter_prompt.is_empty() && canonical_model(&invocation.invocation.request.model) && match evaluate_interpreter_loop(turn, interpreter_prompt, completed) { @@ -589,13 +598,13 @@ impl NarrativeCheckpoint { turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed, .. } => { turn_matches_opportunity(turn, opportunity) && opportunity.controller_mode == ControllerMode::NarrativePersona - && opportunity.affordance_ids.contains(speak_affordance) + && granted_matches_opportunity(granted, opportunity) && derive_narrative_capture(turn, interpreter_prompt, completed) .is_ok_and(|capture| capture.proposal.is_some()) } @@ -638,20 +647,21 @@ impl OperationalCheckpoint { command_id, agent_prompt, opportunity, - speak_affordance, + granted, completed, invocation, } => { opportunity.controller_mode == ControllerMode::OperationalAgent - && opportunity.affordance_ids.contains(speak_affordance) + && granted_matches_opportunity(granted, opportunity) && !agent_prompt.is_empty() && canonical_model(&invocation.invocation.request.model) - && match evaluate_operational_loop(agent_prompt, completed) { + && match evaluate_operational_loop(agent_prompt, granted, completed) { Ok(OperationalLoopEvaluation::Continue { conversation }) => { operational_request( *command_id, completed.len(), &invocation.invocation.request.model, + granted, conversation, ) .is_ok_and(|expected| { @@ -669,13 +679,13 @@ impl OperationalCheckpoint { Self::ReadyToSubmit { agent_prompt, opportunity, - speak_affordance, + granted, completed, .. } => { opportunity.controller_mode == ControllerMode::OperationalAgent - && opportunity.affordance_ids.contains(speak_affordance) - && derive_operational_capture(agent_prompt, completed) + && granted_matches_opportunity(granted, opportunity) + && derive_operational_capture(agent_prompt, granted, completed) .is_ok_and(|capture| capture.proposal.is_some()) } Self::NoProposal { @@ -685,7 +695,7 @@ impl OperationalCheckpoint { .. } => { opportunity.controller_mode == ControllerMode::OperationalAgent - && derive_operational_capture(agent_prompt, completed) + && derive_operational_capture(agent_prompt, &[], completed) .is_ok_and(|capture| capture.proposal.is_none()) } } @@ -715,7 +725,7 @@ pub(crate) struct TranslationGapSummary { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub(crate) struct OperationalCapture { - pub(crate) proposal: Option, + pub(crate) proposal: Option, pub(crate) needs: Vec, pub(crate) inference_receipts: Vec, } @@ -724,14 +734,26 @@ fn base_checkpoint_is_valid( identity: &str, typed_view: &str, opportunity: &DecisionOpportunity, - speak_affordance: AffordanceId, + granted: &[AffordanceSnapshot], mode: ControllerMode, ) -> bool { !identity.is_empty() && identity.trim() == identity && !typed_view.is_empty() && opportunity.controller_mode == mode - && opportunity.affordance_ids.contains(&speak_affordance) + && granted_matches_opportunity(granted, opportunity) +} + +/// A resumed run rebuilds byte-identical tool schemas only if it still holds the +/// same entries the opportunity grants. +fn granted_matches_opportunity( + granted: &[AffordanceSnapshot], + opportunity: &DecisionOpportunity, +) -> bool { + !granted.is_empty() + && granted + .iter() + .all(|entry| opportunity.affordance_ids.contains(&entry.id)) } fn turn_matches_opportunity(turn: &PersonaTurn, opportunity: &DecisionOpportunity) -> bool { @@ -770,9 +792,10 @@ fn derive_narrative_capture( fn derive_operational_capture( agent_prompt: &str, + granted: &[AffordanceSnapshot], completed: &[InferenceOutput], ) -> Result { - match evaluate_operational_loop(agent_prompt, completed)? { + match evaluate_operational_loop(agent_prompt, granted, completed)? { OperationalLoopEvaluation::Complete { capture } => Ok(capture), OperationalLoopEvaluation::Continue { .. } => Err(ControllerError::Serialization( "terminal operational checkpoint has unfinished evidence".into(), @@ -1149,7 +1172,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC persona_model, interpreter_model, opportunity, - speak_affordance, + granted, invocation: existing_invocation, }, NarrativeCheckpoint::Persona { @@ -1158,7 +1181,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC typed_view: next_typed_view, interpreter_model: next_interpreter_model, opportunity: next_opportunity, - speak_affordance: next_speak_affordance, + granted: next_granted, invocation, .. }, @@ -1168,7 +1191,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC && typed_view == next_typed_view && interpreter_model == next_interpreter_model && opportunity == next_opportunity - && speak_affordance == next_speak_affordance + && granted == next_granted && &invocation.invocation.request.model == persona_model && invocation.invocation.caller_runtime_id == existing_invocation.invocation.caller_runtime_id @@ -1180,7 +1203,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC typed_view, interpreter_model, opportunity, - speak_affordance, + granted, projector_output, invocation: existing_invocation, }, @@ -1189,7 +1212,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC turn, interpreter_prompt, opportunity: next_opportunity, - speak_affordance: next_speak_affordance, + granted: next_granted, completed, invocation, }, @@ -1210,7 +1233,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC }); command_id == next_command_id && opportunity == next_opportunity - && speak_affordance == next_speak_affordance + && granted == next_granted && completed.is_empty() && interpreter_prompt == &expected_prompt && turn.binding().projector_receipt_digest == projector_receipt @@ -1224,7 +1247,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed, invocation: existing_invocation, }, @@ -1233,7 +1256,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC turn: next_turn, interpreter_prompt: next_interpreter_prompt, opportunity: next_opportunity, - speak_affordance: next_speak_affordance, + granted: next_granted, completed: next_completed, invocation: next_invocation, }, @@ -1242,7 +1265,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC && turn == next_turn && interpreter_prompt == next_interpreter_prompt && opportunity == next_opportunity - && speak_affordance == next_speak_affordance + && granted == next_granted && completed_advances(completed, next_completed) && existing_invocation.invocation.request.model == next_invocation.invocation.request.model @@ -1255,7 +1278,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed, .. }, @@ -1264,7 +1287,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC turn: next_turn, interpreter_prompt: next_interpreter_prompt, opportunity: next_opportunity, - speak_affordance: next_speak_affordance, + granted: next_granted, completed: next_completed, }, ) => { @@ -1272,7 +1295,7 @@ fn valid_narrative_progression(existing: &NarrativeCheckpoint, next: &NarrativeC && turn == next_turn && interpreter_prompt == next_interpreter_prompt && opportunity == next_opportunity - && speak_affordance == next_speak_affordance + && granted == next_granted && completed_advances(completed, next_completed) } ( @@ -1312,7 +1335,7 @@ fn valid_operational_progression( command_id, agent_prompt, opportunity, - speak_affordance, + granted, completed, invocation: existing_invocation, }, @@ -1320,7 +1343,7 @@ fn valid_operational_progression( command_id: next_command_id, agent_prompt: next_agent_prompt, opportunity: next_opportunity, - speak_affordance: next_speak_affordance, + granted: next_granted, completed: next_completed, invocation: next_invocation, }, @@ -1328,7 +1351,7 @@ fn valid_operational_progression( command_id == next_command_id && agent_prompt == next_agent_prompt && opportunity == next_opportunity - && speak_affordance == next_speak_affordance + && granted == next_granted && completed_advances(completed, next_completed) && existing_invocation.invocation.request.model == next_invocation.invocation.request.model @@ -1340,7 +1363,7 @@ fn valid_operational_progression( command_id, agent_prompt, opportunity, - speak_affordance, + granted, completed, .. }, @@ -1348,14 +1371,14 @@ fn valid_operational_progression( command_id: next_command_id, agent_prompt: next_agent_prompt, opportunity: next_opportunity, - speak_affordance: next_speak_affordance, + granted: next_granted, completed: next_completed, }, ) => { command_id == next_command_id && agent_prompt == next_agent_prompt && opportunity == next_opportunity - && speak_affordance == next_speak_affordance + && granted == next_granted && completed_advances(completed, next_completed) } ( @@ -1591,6 +1614,8 @@ pub(crate) enum ControllerError { OpportunityMismatch, #[error("controller opportunity has no Speak affordance")] SpeakUnavailable, + #[error("controller opportunity grants no affordance")] + NoGrantedAffordance, #[error("Eve command ID does not match persisted controller work")] CommandMismatch, #[error("no persisted controller work exists for this Eve command")] @@ -1757,7 +1782,7 @@ impl ControllerRunner { persona_model: self.models.persona.clone(), interpreter_model: self.models.interpreter.clone(), opportunity: selected.opportunity, - speak_affordance: selected.speak_affordance, + granted: selected.granted.clone(), invocation: self.prepare(projector_request( command_id, &self.models.projector, @@ -1819,29 +1844,31 @@ impl ControllerRunner { let agent_prompt = build_operational_agent_prompt(&OperationalAgentPrompt { identity: &identity, typed_view: &typed_view, - available_tools: "speak(text), record_need(detail), finish_without_proposal()", + available_tools: &catalog_signatures(&selected.granted), decision_pressure: "Choose whether this decision owner should speak now.", domain_guidance: "", step_budget: TOOL_STEP_BUDGET, }); - let initial_conversation = match evaluate_operational_loop(&agent_prompt, &[])? { - OperationalLoopEvaluation::Continue { conversation } => conversation, - OperationalLoopEvaluation::Complete { .. } => { - return Err(ControllerError::Serialization( - "empty operational evidence unexpectedly finalized".into(), - )); - } - }; + let initial_conversation = + match evaluate_operational_loop(&agent_prompt, &selected.granted, &[])? { + OperationalLoopEvaluation::Continue { conversation } => conversation, + OperationalLoopEvaluation::Complete { .. } => { + return Err(ControllerError::Serialization( + "empty operational evidence unexpectedly finalized".into(), + )); + } + }; let checkpoint = OperationalCheckpoint::AgentInFlight { command_id, agent_prompt, opportunity: selected.opportunity, - speak_affordance: selected.speak_affordance, + granted: selected.granted.clone(), completed: Vec::new(), invocation: self.prepare(operational_request( command_id, 0, &self.models.operational_agent, + &selected.granted, initial_conversation, )?)?, }; @@ -1889,7 +1916,7 @@ impl ControllerRunner { command_id, agent_prompt, opportunity, - speak_affordance, + granted, mut completed, invocation, } = checkpoint.clone() @@ -1908,14 +1935,14 @@ impl ControllerRunner { }, }; completed.push(output); - match evaluate_operational_loop(&agent_prompt, &completed) { + match evaluate_operational_loop(&agent_prompt, &granted, &completed) { Ok(OperationalLoopEvaluation::Complete { capture }) => { let next = if capture.proposal.is_some() { OperationalCheckpoint::ReadyToSubmit { command_id, agent_prompt, opportunity, - speak_affordance, + granted, completed, } } else { @@ -1944,14 +1971,15 @@ impl ControllerRunner { command_id, agent_prompt, opportunity, - speak_affordance, completed, invocation: self.prepare(operational_request( command_id, round, &model, + &granted, conversation, )?)?, + granted, }; match self .persist(ControllerWork::Operational(next.clone())) @@ -2035,19 +2063,25 @@ impl ControllerRunner { Err(ControllerError::AmbiguousOpportunity) }; }; - let speak_affordance = subject + let granted: Vec = snapshot .affordances - .get(&AffordanceKind::Speak) - .copied() - .filter(|id| opportunity.affordance_ids.contains(id)) - .ok_or(ControllerError::SpeakUnavailable)?; + .iter() + .filter(|entry| { + subject.affordances.contains(&entry.id) + && opportunity.affordance_ids.contains(&entry.id) + }) + .cloned() + .collect(); + if granted.is_empty() { + return Err(ControllerError::NoGrantedAffordance); + } Ok(SelectedDecision { snapshot, subject, // The run's own bound value, not the fresh snapshot's: one run binds // one opportunity, persists it, and submits it unchanged. opportunity: exact_opportunity.clone(), - speak_affordance, + granted, }) } @@ -2102,7 +2136,7 @@ impl ControllerRunner { persona_model, interpreter_model, opportunity, - speak_affordance, + granted, invocation, } = checkpoint.clone() else { @@ -2140,7 +2174,7 @@ impl ControllerRunner { typed_view, interpreter_model, opportunity, - speak_affordance, + granted, projector_output, invocation: self.prepare(persona_request( command_id, @@ -2172,7 +2206,7 @@ impl ControllerRunner { typed_view, interpreter_model, opportunity, - speak_affordance, + granted, projector_output, invocation, } = checkpoint.clone() @@ -2230,7 +2264,7 @@ impl ControllerRunner { turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed: Vec::new(), invocation: self.prepare(interpreter_request( command_id, @@ -2263,7 +2297,7 @@ impl ControllerRunner { turn, interpreter_prompt, opportunity, - speak_affordance, + granted, mut completed, invocation, } = checkpoint.clone() @@ -2290,7 +2324,7 @@ impl ControllerRunner { turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed, } } else { @@ -2321,7 +2355,7 @@ impl ControllerRunner { turn, interpreter_prompt, opportunity, - speak_affordance, + granted, completed, invocation: self.prepare(interpreter_request( command_id, @@ -2531,7 +2565,9 @@ struct SelectedDecision { snapshot: WorldSnapshot, subject: SubjectSnapshot, opportunity: DecisionOpportunity, - speak_affordance: AffordanceId, + /// The entries this opportunity grants, in `AffordanceId` order. Every + /// model-facing surface is a projection of exactly this list. + granted: Vec, } impl SelectedDecision { @@ -2544,9 +2580,7 @@ impl SelectedDecision { "label": self.subject.label, "kind": self.subject.kind, }, - "permission": { - "speak": true, - }, + "permission": catalog_permissions(&self.granted), })) .map_err(|error| ControllerError::Serialization(error.to_string())) } @@ -2564,9 +2598,7 @@ impl SelectedDecision { "kind": self.subject.kind, "place": self.typed_place(), }, - "permission": { - "speak": true, - }, + "permission": catalog_permissions(&self.granted), "routes": self.typed_routes(), "holdings": self.typed_holdings(), "dependencies": self.typed_dependencies(), @@ -2663,16 +2695,21 @@ impl SelectedDecision { .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 .iter() - .map(|event| match &event.invocation.action { - DecisionAction::Speak { text } => json!({ - "revision": event.revision, - "speaker_subject_id": event.scope.subject_id, - "text": text, - }), + .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(), + }) + }) }) .collect() } @@ -2681,35 +2718,47 @@ impl SelectedDecision { self.snapshot .events .iter() - .map(|event| match &event.invocation.action { - DecisionAction::Speak { 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, - })) - } + .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(), + })) }) .collect() } } -fn speak_invocation(speak_affordance: AffordanceId, text: String) -> DecisionInvocation { - DecisionInvocation { - affordance_id: speak_affordance, - action: DecisionAction::Speak { text }, - } +/// The narrative lane speaks and does nothing else, so it finds its entry by +/// kind name among the entries the kernel granted this opportunity. +fn speak_invocation( + granted: &[AffordanceSnapshot], + text: String, +) -> Result { + let entry = granted + .iter() + .find(|entry| entry.entry.kind.0 == SPEAK_KIND) + .ok_or(ControllerError::SpeakUnavailable)?; + let speech = Utterance::new(text).ok_or_else(|| { + ControllerError::Serialization("Persona proposal is not canonical utterance text".into()) + })?; + Ok(DecisionInvocation { + affordance: entry.id, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(speech), + }) } fn narrative_invocation( @@ -2718,7 +2767,7 @@ fn narrative_invocation( let NarrativeCheckpoint::ReadyToSubmit { turn, interpreter_prompt, - speak_affordance, + granted, completed, .. } = checkpoint @@ -2737,7 +2786,7 @@ fn narrative_invocation( .get(span.start_byte..span.end_byte) .ok_or_else(|| ControllerError::Serialization("Persona proposal span is not exact".into()))? .to_owned(); - Ok(speak_invocation(*speak_affordance, text)) + speak_invocation(granted, text) } fn operational_invocation( @@ -2745,7 +2794,7 @@ fn operational_invocation( ) -> Result { let OperationalCheckpoint::ReadyToSubmit { agent_prompt, - speak_affordance, + granted, completed, .. } = checkpoint @@ -2754,12 +2803,11 @@ fn operational_invocation( "operational work is not ready to submit".into(), )); }; - let text = derive_operational_capture(agent_prompt, completed)? + derive_operational_capture(agent_prompt, granted, completed)? .proposal .ok_or_else(|| { ControllerError::Serialization("operational work has no exact proposal".into()) - })?; - Ok(speak_invocation(*speak_affordance, text)) + }) } fn narrative_capture( @@ -2826,17 +2874,21 @@ fn completed_operational( checkpoint: &OperationalCheckpoint, submission: SubmissionDisposition, ) -> Result { - let (agent_prompt, completed) = match checkpoint { + // A `NoProposal` checkpoint holds no granted catalog: it reached the end of + // its turn without one, so the empty set is what its capture re-derives + // against. + let (agent_prompt, granted, completed) = match checkpoint { OperationalCheckpoint::ReadyToSubmit { agent_prompt, + granted, completed, .. - } - | OperationalCheckpoint::NoProposal { + } => (agent_prompt, granted.as_slice(), completed), + OperationalCheckpoint::NoProposal { agent_prompt, completed, .. - } => (agent_prompt, completed), + } => (agent_prompt, [].as_slice(), completed), OperationalCheckpoint::AgentInFlight { .. } => { return Err(ControllerError::Serialization( "completed operational work is not terminal".into(), @@ -2844,7 +2896,7 @@ fn completed_operational( } }; Ok(OperationalRun::Completed(OperationalDecision { - capture: derive_operational_capture(agent_prompt, completed)?, + capture: derive_operational_capture(agent_prompt, granted, completed)?, submission, })) } @@ -2921,40 +2973,41 @@ fn evaluate_interpreter_loop( arguments: arguments.clone(), }); let result = match name.as_str() { - SPEAK_TOOL => match serde_json::from_str::(arguments) - { - Ok(call) if !captured_speech => { - let derived_text = source - .source_prose() - .get(call.source_start_byte..call.source_end_byte) - .unwrap_or_default() - .to_owned(); - let feedback = accumulator.capture_proposal( - SpeakProposal { text: derived_text }, - call.source_start_byte, - call.source_end_byte, - ); - captured_speech = feedback == CaptureToolFeedback::Accepted; - format!("{feedback:?}") - } - Ok(call) => { - let feedback = accumulator.record_gap(RecordGapToolCall { + INTERPRETER_SPEAK_TOOL => { + match serde_json::from_str::(arguments) { + Ok(call) if !captured_speech => { + let derived_text = source + .source_prose() + .get(call.source_start_byte..call.source_end_byte) + .unwrap_or_default() + .to_owned(); + let feedback = accumulator.capture_proposal( + SpeakProposal { text: derived_text }, + call.source_start_byte, + call.source_end_byte, + ); + captured_speech = feedback == CaptureToolFeedback::Accepted; + format!("{feedback:?}") + } + Ok(call) => { + let feedback = accumulator.record_gap(RecordGapToolCall { kind: TranslationGapKind::Ambiguity, source_start_byte: call.source_start_byte, source_end_byte: call.source_end_byte, detail: "More than one speech proposal was offered; this runner permits one decision invocation per opportunity.".into(), }); - format!("{feedback:?}") + format!("{feedback:?}") + } + Err(error) => format!( + "{:?}", + accumulator.record_tool_decode_failure( + name, + arguments, + &error.to_string(), + ) + ), } - Err(error) => format!( - "{:?}", - accumulator.record_tool_decode_failure( - name, - arguments, - &error.to_string(), - ) - ), - }, + } RECORD_GAP_TOOL => { match serde_json::from_str::(arguments) { Ok(call) => format!("{:?}", accumulator.record_gap(call)), @@ -3036,6 +3089,7 @@ enum OperationalLoopEvaluation { fn evaluate_operational_loop( prompt: &str, + granted: &[AffordanceSnapshot], completed: &[InferenceOutput], ) -> Result { let mut conversation = vec![CodexInputItem::UserText { @@ -3074,13 +3128,16 @@ fn evaluate_operational_loop( name: name.clone(), arguments: arguments.clone(), }); + let entry = granted.iter().find(|entry| entry.entry.kind.0 == *name); let result = match name.as_str() { - SPEAK_TOOL => match serde_json::from_str::(arguments) - { - Ok(call) if terminal_choice.is_none() => { - proposal = Some(call.text); - terminal_choice = Some(SPEAK_TOOL); - "speech proposal captured".into() + _ if entry.is_some() => match decode_catalog_call( + entry.expect("the entry matched above"), + arguments, + ) { + Ok(invocation) if terminal_choice.is_none() => { + proposal = Some(invocation); + terminal_choice = Some(name.clone()); + "invocation captured".into() } Ok(_) => { needs.push(ControllerNeed { @@ -3088,8 +3145,8 @@ fn evaluate_operational_loop( }); "one terminal choice is already captured".into() } - Err(error) => { - needs.push(tool_decode_need(name, arguments, &error.to_string())); + Err(detail) => { + needs.push(tool_decode_need(name, arguments, &detail)); "arguments recorded as a need".into() } }, @@ -3115,7 +3172,7 @@ fn evaluate_operational_loop( detail: "finish_without_proposal contradicted an existing terminal choice".into(), }); } - terminal_choice = Some(FINISH_WITHOUT_PROPOSAL_TOOL); + terminal_choice = Some(FINISH_WITHOUT_PROPOSAL_TOOL.to_owned()); "decision finished without a proposal".into() } Err(error) => { @@ -3287,6 +3344,7 @@ fn operational_request( command_id: CommandId, round: usize, model: &str, + granted: &[AffordanceSnapshot], input: Vec, ) -> Result { tool_request( @@ -3296,7 +3354,7 @@ fn operational_request( model, "Use only the supplied tools for this permissioned decision. Returning no proposal is valid.", input, - operational_tools(), + catalog_tools(granted), ) } @@ -3329,7 +3387,7 @@ fn tool_request( fn interpreter_tools() -> Vec { vec![ tool( - SPEAK_TOOL, + INTERPRETER_SPEAK_TOOL, "Capture one exact spoken utterance by byte span in the preserved Persona prose; the harness derives the utterance verbatim.", json!({ "type":"object", @@ -3364,34 +3422,217 @@ fn interpreter_tools() -> Vec { ] } -fn operational_tools() -> Vec { - vec![ - tool( - SPEAK_TOOL, - "Propose one exact utterance for this decision owner.", - json!({ - "type":"object", - "additionalProperties":false, - "properties":{"text":{"type":"string"}}, - "required":["text"] - }), - ), - tool( - RECORD_NEED_TOOL, - "Record information or capability the agent would need but does not currently have.", - json!({ - "type":"object", - "additionalProperties":false, - "properties":{"detail":{"type":"string"}}, - "required":["detail"] - }), - ), - tool( - FINISH_WITHOUT_PROPOSAL_TOOL, - "Finish this opportunity without proposing an action.", - empty_schema(), - ), - ] +/// One generated tool per granted entry, plus the two turn-enders. There is no +/// hand-written claim about what a subject may do anywhere: the model-facing +/// catalog, its prose signature line, and the typed view's permission block are +/// three projections of `granted` and cannot drift. +/// +/// A schema carries the affordance *name*, its role parameters, and its bounded +/// slots — never an affordance id, an opportunity, a revision, a world, a +/// controller, or a caller. `record_need` and `finish_without_proposal` survive +/// because they are not world operations: they end a turn without proposing. +fn catalog_tools(granted: &[AffordanceSnapshot]) -> Vec { + let mut tools: Vec = granted + .iter() + .map(|entry| { + let mut properties = serde_json::Map::new(); + let mut required = Vec::new(); + for spec in &entry.entry.roles { + properties.insert( + spec.role.0.clone(), + json!({"type": "string", "description": role_description(spec.kind)}), + ); + required.push(Value::String(spec.role.0.clone())); + } + for (index, slot) in entry.entry.effect_slots.iter().enumerate() { + // The ceiling is in the schema, so the model is told the bound + // rather than discovering it through a rejection. + let (name, ceiling) = match slot.bounds { + Bounds::None => continue, + Bounds::Quantity(max) => (slot_property(index, "qty"), u64::from(max.0)), + Bounds::Cost(max) => (slot_property(index, "cost"), u64::from(max.0)), + }; + properties.insert( + name.clone(), + json!({"type": "integer", "minimum": 1, "maximum": ceiling}), + ); + required.push(Value::String(name)); + } + if entry.entry.carries_speech { + properties.insert("text".into(), json!({"type": "string"})); + required.push(Value::String("text".into())); + } + tool( + &entry.entry.kind.0, + &format!("Invoke the {} affordance.", entry.entry.kind.0), + json!({ + "type": "object", + "additionalProperties": false, + "required": required, + "properties": Value::Object(properties), + }), + ) + }) + .collect(); + tools.push(tool( + RECORD_NEED_TOOL, + "Record information or capability the agent would need but does not currently have.", + json!({ + "type":"object", + "additionalProperties":false, + "properties":{"detail":{"type":"string"}}, + "required":["detail"] + }), + )); + tools.push(tool( + FINISH_WITHOUT_PROPOSAL_TOOL, + "Finish this opportunity without proposing an action.", + empty_schema(), + )); + tools +} + +/// The same iteration rendered as one prose line, so the prompt's tool list and +/// the schemas have one owner. +fn catalog_signatures(granted: &[AffordanceSnapshot]) -> String { + let mut signatures: Vec = granted + .iter() + .map(|entry| { + let mut parameters: Vec = entry + .entry + .roles + .iter() + .map(|spec| spec.role.0.clone()) + .collect(); + for (index, slot) in entry.entry.effect_slots.iter().enumerate() { + match slot.bounds { + Bounds::None => {} + Bounds::Quantity(_) => parameters.push(slot_property(index, "qty")), + Bounds::Cost(_) => parameters.push(slot_property(index, "cost")), + } + } + if entry.entry.carries_speech { + parameters.push("text".into()); + } + format!("{}({})", entry.entry.kind.0, parameters.join(", ")) + }) + .collect(); + signatures.push("record_need(detail)".into()); + signatures.push("finish_without_proposal()".into()); + signatures.join(", ") +} + +/// The typed view's permission block: the granted entries by name, derived from +/// the same list the schemas come from. +fn catalog_permissions(granted: &[AffordanceSnapshot]) -> Value { + Value::Object( + granted + .iter() + .map(|entry| (entry.entry.kind.0.clone(), Value::Bool(true))) + .collect(), + ) +} + +fn slot_property(index: usize, dimension: &str) -> String { + format!("slot_{index}_{dimension}") +} + +fn role_description(kind: RefKind) -> &'static str { + match kind { + RefKind::Subject(_) => "a subject id", + RefKind::Entity(EntityKind::Place) => "a place id", + RefKind::Entity(EntityKind::Resource) => "a resource id", + RefKind::Entity(EntityKind::Fact) => "a fact id", + RefKind::Entity(EntityKind::Channel) => "a channel id", + RefKind::Edge(_) => "a route id", + RefKind::Affordance => "an affordance name", + } +} + +/// A catalog tool call lowered to an invocation. A property that will not parse +/// becomes a `ControllerNeed` through the existing accumulator, never a kernel +/// round trip. +fn decode_catalog_call( + entry: &AffordanceSnapshot, + arguments: &str, +) -> Result { + let Ok(Value::Object(fields)) = serde_json::from_str::(arguments) else { + return Err("arguments are not a JSON object".into()); + }; + let mut bindings = Vec::new(); + for spec in &entry.entry.roles { + let raw = fields + .get(&spec.role.0) + .and_then(Value::as_str) + .ok_or_else(|| format!("role `{}` is missing or not a string", spec.role.0))?; + // The id newtypes are serde-transparent over `Uuid`, so the one + // deserializer parses them and no caller reaches inside them. + let id = Value::String(raw.to_owned()); + let unparsed = || format!("role `{}` is not a UUID", spec.role.0); + let target = match spec.kind { + RefKind::Subject(_) => { + Target::Subject(serde_json::from_value::(id).map_err(|_| unparsed())?) + } + RefKind::Entity(_) => { + Target::Entity(serde_json::from_value::(id).map_err(|_| unparsed())?) + } + RefKind::Edge(_) => { + Target::Edge(serde_json::from_value::(id).map_err(|_| unparsed())?) + } + RefKind::Affordance => { + return Err(format!( + "role `{}` names no bindable namespace", + spec.role.0 + )); + } + }; + bindings.push(RoleBinding { + role: spec.role.clone(), + target, + }); + } + let mut proposed = Vec::new(); + for (index, slot) in entry.entry.effect_slots.iter().enumerate() { + let magnitude = match slot.bounds { + Bounds::None => Magnitude::None, + Bounds::Quantity(_) => { + let name = slot_property(index, "qty"); + let value = fields + .get(&name) + .and_then(Value::as_u64) + .ok_or_else(|| format!("`{name}` is missing or not a positive integer"))?; + Magnitude::Quantity(Quantity(value)) + } + Bounds::Cost(_) => { + let name = slot_property(index, "cost"); + let value = fields + .get(&name) + .and_then(Value::as_u64) + .and_then(|value| u32::try_from(value).ok()) + .ok_or_else(|| format!("`{name}` is missing or out of range"))?; + Magnitude::Cost(Cost(value)) + } + }; + proposed.push(ProposedEffect { + slot: index, + magnitude, + }); + } + let speech = if entry.entry.carries_speech { + let text = fields + .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())?) + } else { + None + }; + Ok(DecisionInvocation { + affordance: entry.id, + bindings, + proposed, + speech, + }) } fn empty_schema() -> Value { @@ -3443,6 +3684,16 @@ fn purpose_name(purpose: InferencePurpose) -> &'static str { #[cfg(test)] mod tests { use super::*; + use crate::world::patch::{kernel_speak_entry, kernel_speak_grant}; + + /// The granted catalog every controller fixture works against: the + /// kernel-built Speak entry under a fixture id. + fn speak_snapshot(id: AffordanceId) -> AffordanceSnapshot { + AffordanceSnapshot { + id, + entry: kernel_speak_entry(), + } + } use crate::world::{ AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, ControllerId, CreateWorld, DecisionScope, Declaration, DraftHandle, EventId, NewController, PrincipalId, ScopeDigest, @@ -3617,7 +3868,7 @@ mod tests { controller_id: actor_controller, controller_mode: ControllerMode::NarrativePersona, human_controller: None, - affordances: BTreeMap::from([(AffordanceKind::Speak, speak_affordance)]), + affordances: BTreeSet::from([speak_affordance]), position: None, holdings: BTreeMap::new(), dependencies: BTreeSet::new(), @@ -3630,7 +3881,7 @@ mod tests { controller_id: speaker_controller, controller_mode: ControllerMode::OperationalAgent, human_controller: None, - affordances: BTreeMap::new(), + affordances: BTreeSet::new(), position: None, holdings: BTreeMap::new(), dependencies: BTreeSet::new(), @@ -3645,6 +3896,7 @@ mod tests { draft_approvals: BTreeSet::new(), required_approvers: BTreeSet::new(), subjects: vec![actor.clone(), speaker], + affordances: vec![speak_snapshot(speak_affordance)], places: Vec::new(), resources: Vec::new(), routes: Vec::new(), @@ -3656,11 +3908,13 @@ mod tests { }, controller_id: speaker_controller, invocation: DecisionInvocation { - affordance_id: AffordanceId::issue(), - action: DecisionAction::Speak { - text: "The lower hinge is flooding.".into(), - }, + 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(), @@ -3670,7 +3924,7 @@ mod tests { snapshot, subject: actor, opportunity, - speak_affordance, + granted: vec![speak_snapshot(speak_affordance)], }; let context = selected.projector_context().unwrap(); @@ -3746,7 +4000,7 @@ mod tests { controller_id: actor_controller, controller_mode: ControllerMode::OperationalAgent, human_controller: None, - affordances: BTreeMap::from([(AffordanceKind::Speak, speak_affordance)]), + affordances: BTreeSet::from([speak_affordance]), position: Some(yard), holdings: BTreeMap::new(), dependencies: BTreeSet::new(), @@ -3759,7 +4013,7 @@ mod tests { controller_id: other_controller, controller_mode: ControllerMode::OperationalAgent, human_controller: None, - affordances: BTreeMap::new(), + affordances: BTreeSet::new(), position: Some(vault), holdings: BTreeMap::new(), dependencies: BTreeSet::new(), @@ -3783,6 +4037,7 @@ mod tests { world_id: opportunity.world_id, revision: opportunity.revision, phase: WorldPhase::Active, + affordances: vec![speak_snapshot(opportunity.affordance_ids[0])], owner: PrincipalId::new("scope-fixture-owner"), title: "Kharad".into(), draft_approvals: BTreeSet::new(), @@ -3807,7 +4062,7 @@ mod tests { snapshot, subject: actor, opportunity, - speak_affordance, + granted: vec![speak_snapshot(speak_affordance)], }; let view = selected.typed_view().unwrap(); @@ -3862,7 +4117,11 @@ mod tests { #[test] fn controller_tool_schemas_cannot_claim_authority_or_envelopes() { - for definition in interpreter_tools().into_iter().chain(operational_tools()) { + let granted = vec![speak_snapshot(AffordanceId::issue())]; + for definition in interpreter_tools() + .into_iter() + .chain(catalog_tools(&granted)) + { let schema: Value = serde_json::from_str(&definition.parameters_json).unwrap(); assert_eq!(schema["additionalProperties"], false); let properties = schema["properties"].as_object().unwrap(); @@ -3881,15 +4140,15 @@ mod tests { } } assert_eq!( - operational_tools() + catalog_tools(&granted) .iter() .map(|tool| tool.name.as_str()) .collect::>(), - vec![SPEAK_TOOL, RECORD_NEED_TOOL, FINISH_WITHOUT_PROPOSAL_TOOL] + vec![SPEAK_KIND, RECORD_NEED_TOOL, FINISH_WITHOUT_PROPOSAL_TOOL] ); let interpreter_speak = interpreter_tools() .into_iter() - .find(|tool| tool.name == SPEAK_TOOL) + .find(|tool| tool.name == INTERPRETER_SPEAK_TOOL) .unwrap(); let schema: Value = serde_json::from_str(&interpreter_speak.parameters_json).unwrap(); assert!( @@ -3907,6 +4166,140 @@ mod tests { ); } + #[test] + fn the_generated_tool_catalog_equals_the_granted_catalog() { + use crate::world::{ + Affordance, AffordanceKindName, Bounds, ComponentOpKind, EffectSlot, OutcomeBand, + Quantity, RefKind, Role, RoleSpec, + }; + + let carry = AffordanceSnapshot { + id: AffordanceId::issue(), + entry: Affordance { + kind: AffordanceKindName("carry".into()), + roles: vec![ + RoleSpec { + role: Role("recipient".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("resource".into()), + kind: RefKind::Entity(crate::world::EntityKind::Resource), + }, + ], + preconditions: Vec::new(), + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("recipient".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }], + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: vec![0], + }], + carries_speech: false, + }, + }; + let speak = speak_snapshot(AffordanceId::issue()); + let granted = vec![carry.clone(), speak.clone()]; + + // The tool names are exactly the granted entries' kind names plus the + // two turn-enders, in that order. + assert_eq!( + catalog_tools(&granted) + .iter() + .map(|tool| tool.name.as_str()) + .collect::>(), + vec![ + "carry", + SPEAK_KIND, + RECORD_NEED_TOOL, + FINISH_WITHOUT_PROPOSAL_TOOL + ] + ); + + // Each tool requires exactly its roles, its bounded slots, and `text` + // where the entry carries speech, and each bounded slot states its own + // ceiling. + let tools = catalog_tools(&granted); + let schema_of = |name: &str| -> Value { + serde_json::from_str( + &tools + .iter() + .find(|tool| tool.name == name) + .expect("a generated tool") + .parameters_json, + ) + .unwrap() + }; + let carry_schema = schema_of("carry"); + assert_eq!( + carry_schema["required"], + json!(["recipient", "resource", "slot_0_qty"]) + ); + assert_eq!( + carry_schema["properties"]["slot_0_qty"]["maximum"], + json!(3) + ); + assert_eq!( + carry_schema["properties"]["slot_0_qty"]["minimum"], + json!(1) + ); + assert_eq!(schema_of(SPEAK_KIND)["required"], json!(["text"])); + + // The three model-facing surfaces name the same entries in the same + // order, so none of them can drift from the kernel's grant. + assert_eq!( + catalog_signatures(&granted), + "carry(recipient, resource, slot_0_qty), speak(text), record_need(detail), finish_without_proposal()" + ); + assert_eq!( + catalog_permissions(&granted), + json!({"carry": true, "speak": true}) + ); + + // A subject granted nothing gets no world tools, only the turn-enders. + assert_eq!( + catalog_tools(&[]) + .iter() + .map(|tool| tool.name.as_str()) + .collect::>(), + vec![RECORD_NEED_TOOL, FINISH_WITHOUT_PROPOSAL_TOOL] + ); + + // No generated schema carries an affordance id or an authority envelope. + for tool in catalog_tools(&granted) { + let schema: Value = serde_json::from_str(&tool.parameters_json).unwrap(); + let properties = schema["properties"].as_object().unwrap(); + for forbidden in [ + "affordance", + "affordance_id", + "opportunity", + "revision", + "world_id", + "controller_id", + "caller", + "command_id", + ] { + assert!(!properties.contains_key(forbidden)); + } + assert!( + !tool + .parameters_json + .contains(&encoded_id(&carry.id).unwrap()) + ); + assert!( + !tool + .parameters_json + .contains(&encoded_id(&speak.id).unwrap()) + ); + } + } + #[test] fn provider_request_and_conversation_ids_are_deterministic_from_the_eve_command() { let command_id = CommandId::new(); @@ -4028,18 +4421,20 @@ mod tests { model: &str, completed: Vec, ) -> ControllerWork { + let granted = vec![speak_snapshot(opportunity.affordance_ids[0])]; let OperationalLoopEvaluation::Continue { conversation } = - evaluate_operational_loop(agent_prompt, &completed).unwrap() + evaluate_operational_loop(agent_prompt, &granted, &completed).unwrap() else { panic!("operational fixture unexpectedly finalized") }; let request = - operational_request(command_id, completed.len(), model, conversation).unwrap(); + operational_request(command_id, completed.len(), model, &granted, conversation) + .unwrap(); ControllerWork::Operational(OperationalCheckpoint::AgentInFlight { command_id, agent_prompt: agent_prompt.into(), opportunity: opportunity.clone(), - speak_affordance: opportunity.affordance_ids[0], + granted, completed, invocation: fixture_prepared(request).unwrap(), }) @@ -4080,7 +4475,7 @@ mod tests { turn: turn.clone(), interpreter_prompt: interpreter_prompt.into(), opportunity: opportunity.clone(), - speak_affordance: opportunity.affordance_ids[0], + granted: vec![speak_snapshot(opportunity.affordance_ids[0])], completed, invocation: fixture_prepared(request).unwrap(), }) @@ -4177,7 +4572,7 @@ mod tests { label: "Subject".into(), kind: SubjectKind::Person, controller, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, })], operations: Vec::new(), @@ -4248,7 +4643,7 @@ mod tests { vec![ InferenceEvent::ToolCall { call_id: "call_bad_span".into(), - name: SPEAK_TOOL.into(), + name: INTERPRETER_SPEAK_TOOL.into(), arguments: json!({ "source_start_byte":source.len() + 10, "source_end_byte":source.len() + 20 @@ -4257,7 +4652,7 @@ mod tests { }, InferenceEvent::ToolCall { call_id: "call_speak".into(), - name: SPEAK_TOOL.into(), + name: INTERPRETER_SPEAK_TOOL.into(), arguments: json!({ "source_start_byte":start, "source_end_byte":start + speech.len() @@ -4349,7 +4744,7 @@ mod tests { }, InferenceEvent::ToolCall { call_id: "speak".into(), - name: SPEAK_TOOL.into(), + name: INTERPRETER_SPEAK_TOOL.into(), arguments: json!({"text":"Close the western span."}).to_string(), }, ], @@ -4640,7 +5035,7 @@ mod tests { vec![ InferenceEvent::ToolCall { call_id: "bad-span".into(), - name: SPEAK_TOOL.into(), + name: INTERPRETER_SPEAK_TOOL.into(), arguments: json!({ "source_start_byte": source.len() + 1, "source_end_byte": source.len() + 2 @@ -4649,7 +5044,7 @@ mod tests { }, InferenceEvent::ToolCall { call_id: "exact-span".into(), - name: SPEAK_TOOL.into(), + name: INTERPRETER_SPEAK_TOOL.into(), arguments: json!({ "source_start_byte": start, "source_end_byte": start + speech.len() @@ -4719,10 +5114,12 @@ mod tests { let snapshot = mailbox.snapshot().await.unwrap(); assert_eq!(snapshot.events.len(), 1); assert_eq!( - snapshot.events[0].invocation.action, - DecisionAction::Speak { - text: speech.into() - } + snapshot.events[0] + .invocation + .speech + .as_ref() + .map(Utterance::as_str), + Some(speech) ); drop(reopened_terminal); @@ -4775,7 +5172,7 @@ mod tests { controller: NewController::Human { principal: human.clone(), }, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }), Declaration::Subject(SubjectDeclaration { @@ -4783,7 +5180,7 @@ mod tests { label: "Mara, a watch officer who answers direct roll calls aloud in one short sentence".into(), kind: SubjectKind::Person, controller: NewController::NarrativePersona, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }), Declaration::Subject(SubjectDeclaration { @@ -4791,7 +5188,7 @@ mod tests { label: "The Signal Council, which answers direct roll calls aloud with one short operational sentence".into(), kind: SubjectKind::Institution, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }), ], @@ -4861,9 +5258,13 @@ mod tests { .find(|opportunity| opportunity.controller_id == human_subject.controller_id) .cloned() .unwrap(); - let human_speak = *human_subject + let human_speak = *snapshot .affordances - .get(&AffordanceKind::Speak) + .iter() + .find(|entry| { + entry.entry.kind.0 == SPEAK_KIND && human_subject.affordances.contains(&entry.id) + }) + .map(|entry| &entry.id) .unwrap(); let seed = "Mara and the Signal Council, answer the midnight roll call aloud now. Each of you, say in one short sentence that you hear me."; let seed_command = CommandId::new(); @@ -4877,8 +5278,10 @@ mod tests { body: CommandBody::ExerciseDecision { opportunity: human_opportunity, invocation: DecisionInvocation { - affordance_id: human_speak, - action: DecisionAction::Speak { text: seed.into() }, + affordance: human_speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new(seed).unwrap()), }, }, }, @@ -4900,8 +5303,8 @@ mod tests { snapshot = mailbox.snapshot().await.unwrap(); assert!(snapshot.events.len() == 1); - let DecisionAction::Speak { text: seeded_text } = &snapshot.events[0].invocation.action; - assert!(seeded_text.as_bytes() == seed.as_bytes()); + let seeded_text = snapshot.events[0].invocation.speech.as_ref().unwrap(); + assert!(seeded_text.as_str().as_bytes() == seed.as_bytes()); let narrative_subject = snapshot .subjects .iter() @@ -4985,7 +5388,7 @@ mod tests { .filter_map(|event| match event { InferenceEvent::ToolCall { name, arguments, .. - } if name == SPEAK_TOOL => { + } if name == INTERPRETER_SPEAK_TOOL => { serde_json::from_str::(arguments).ok() } InferenceEvent::Text(_) | InferenceEvent::ToolCall { .. } => None, @@ -5006,10 +5409,8 @@ mod tests { .iter() .find(|event| event.controller_id == narrative_subject.controller_id) .unwrap(); - let DecisionAction::Speak { - text: committed_narrative_speech, - } = &narrative_event.invocation.action; - assert!(committed_narrative_speech.as_bytes() == narrative_speech.as_bytes()); + let committed_narrative_speech = narrative_event.invocation.speech.as_ref().unwrap(); + assert!(committed_narrative_speech.as_str().as_bytes() == narrative_speech.as_bytes()); let operational_subject = snapshot .subjects @@ -5044,7 +5445,9 @@ mod tests { .capture() .proposal .as_ref() + .and_then(|invocation| invocation.speech.as_ref()) .unwrap() + .as_str() .to_owned(); assert!(!operational_speech.trim().is_empty()); let ControllerWorkLookup::Confirmed(ControllerWork::Operational( @@ -5062,7 +5465,7 @@ mod tests { .find_map(|event| match event { InferenceEvent::ToolCall { name, arguments, .. - } if name == SPEAK_TOOL => { + } if name == SPEAK_KIND => { serde_json::from_str::(arguments).ok() } InferenceEvent::Text(_) | InferenceEvent::ToolCall { .. } => None, @@ -5078,10 +5481,8 @@ mod tests { .iter() .find(|event| event.controller_id == operational_subject.controller_id) .unwrap(); - let DecisionAction::Speak { - text: committed_operational_speech, - } = &operational_event.invocation.action; - assert!(committed_operational_speech.as_bytes() == operational_speech.as_bytes()); + let committed_operational_speech = operational_event.invocation.speech.as_ref().unwrap(); + assert!(committed_operational_speech.as_str().as_bytes() == operational_speech.as_bytes()); drop(runner); drop(mailbox); diff --git a/crates/ghostlight-dungeon/src/world/journal.rs b/crates/ghostlight-dungeon/src/world/journal.rs index aab73ad..3736584 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.custody.v1"; -const COMMIT_ROW: &str = "world_commit.custody.v1"; +const STATE_ROW: &str = "world_state.affordance.v1"; +const COMMIT_ROW: &str = "world_commit.affordance.v1"; #[derive(Debug, Error)] pub(super) enum JournalError { @@ -557,27 +557,36 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { "controller assignment references an unknown subject".into(), )); } - let mut scope_kinds = BTreeSet::new(); - let mut scopes_with_grants = BTreeSet::new(); - for grant in state.affordance_grants.values() { - if !state.controller_assignments.contains_key(&grant.scope) - || !scope_kinds.insert((grant.scope, grant.kind)) + for (scope, granted) in &state.affordance_grants { + if !state.controller_assignments.contains_key(scope) + || granted.is_empty() + || granted + .iter() + .any(|affordance_id| !state.affordance_catalog.contains_key(affordance_id)) { return Err(JournalError::Corrupt( - "affordance grant is duplicated or unscoped".into(), + "affordance grant is empty, unscoped, or names no catalog entry".into(), )); } - scopes_with_grants.insert(grant.scope); } if state .controller_assignments .keys() - .any(|scope| !scopes_with_grants.contains(scope)) + .any(|scope| !state.affordance_grants.contains_key(scope)) { return Err(JournalError::Corrupt( "decision scope has no affordance grant".into(), )); } + // Every stored entry still passes the declaration validator, so a forged + // catalog row cannot install an entry the resolver would have refused. + for entry in state.affordance_catalog.values() { + if !super::patch::entry_is_admissible(entry) { + return Err(JournalError::Corrupt( + "stored affordance entry is not admissible".into(), + )); + } + } let required = super::required_approvers(state); if !state.draft_approvals.is_subset(&required) || (state.phase != super::WorldPhase::Draft && !required.is_subset(&state.draft_approvals)) @@ -593,19 +602,21 @@ fn verify_state_shape(state: &WorldState) -> Result<(), JournalError> { .controller_assignments .get(&event.scope) .ok_or_else(|| JournalError::Corrupt("event references an unknown scope".into()))?; - let grant = state - .affordance_grants - .get(&event.invocation.affordance_id) + let entry = state + .affordance_catalog + .get(&event.invocation.affordance) .ok_or_else(|| JournalError::Corrupt("event uses an unknown affordance".into()))?; if !event_ids.insert(event.id) || event.revision == 0 || event.revision > state.revision || event.revision <= previous_event_revision || event.controller_id != assignment.id() - || grant.scope != event.scope - || grant.kind != event.invocation.action.kind() - || super::validated_invocation(&event.invocation).map_err(kernel_error)? - != event.invocation + || !state + .affordance_grants + .get(&event.scope) + .is_some_and(|granted| granted.contains(&event.invocation.affordance)) + || event.band >= entry.outcome_bands.len() + || (entry.outcome_bands[event.band].effects.is_empty() && !event.effects.is_empty()) { return Err(JournalError::Corrupt( "decision event is noncanonical or violates controller scope".into(), @@ -636,7 +647,13 @@ fn apply_committed_command( "committed effect is not the deterministic reduction of its command".into(), )); } - apply_effect(state, &commit.command.caller(), &expected_effect).map_err(kernel_error) + apply_effect( + state, + command.id, + &commit.command.caller(), + &expected_effect, + ) + .map_err(kernel_error) } fn require_schema(row: &CultCacheEnvelope, schema: &str) -> Result<(), JournalError> { @@ -691,10 +708,12 @@ fn kernel_error(error: KernelError) -> JournalError { #[cfg(test)] mod tests { use super::*; + use crate::world::patch::kernel_speak_grant; + use crate::world::tests::speak_entry; use crate::world::{ - AffordanceKind, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, - Declaration, DraftHandle, EntityDeclaration, EntityId, EntityKind, NewController, Position, - PrincipalId, Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CreateWorld, Declaration, + DraftHandle, EntityDeclaration, EntityId, EntityKind, NewController, Position, PrincipalId, + Ref, SubjectDeclaration, SubjectKind, WorldKernel, WorldPatch, }; #[derive(serde::Serialize, serde::Deserialize)] @@ -739,7 +758,7 @@ mod tests { controller: NewController::Human { principal: owner.clone(), }, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }), }; @@ -819,7 +838,7 @@ mod tests { controller: NewController::Human { principal: owner.clone(), }, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }), }; @@ -848,7 +867,7 @@ mod tests { label: "The Rhythm Authority".into(), kind: SubjectKind::Institution, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak_entry(&kernel)]), position: Some(Ref::Draft(DraftHandle::new("rhythm-road"))), }), ], @@ -955,7 +974,7 @@ mod tests { label: "Owner".into(), kind: SubjectKind::Person, controller: NewController::Human { principal: owner }, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }), }; @@ -1183,6 +1202,88 @@ mod custody_tests { ); } + /// Replay recomputes `reduce`, so the band and the lowered operations are + /// re-derived rather than trusted: a stored event whose band or effects the + /// seed does not reproduce fails effect equality on the way back in. + #[test] + fn restart_replay_after_an_action_is_exact() { + use crate::world::tests::affordance_named; + use crate::world::{AuthenticatedCaller, Magnitude, ProposedEffect, RoleBinding, Target}; + + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("world.cc"); + let authenticated = auth_principal(owner()); + let (mut kernel, _) = WorldKernel::create( + &path, + creation(CommandId::new(), "ActionReplay"), + &authenticated, + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let custody = admit_custody(&mut kernel, &topology); + let active = crate::world::tests::activate(&mut kernel); + let carry = affordance_named(&active, "carry"); + let opportunity = crate::world::tests::opportunity_for(&active, custody.holder); + let caller = CallerId::Controller(opportunity.controller_id); + + let role = |name: &str, target| RoleBinding { + role: crate::world::Role(name.into()), + target, + }; + let envelope = command( + &active, + CommandId::new(), + caller.clone(), + CommandBody::ExerciseDecision { + opportunity: opportunity.clone(), + invocation: crate::world::DecisionInvocation { + affordance: carry, + bindings: vec![ + role("from", Target::Subject(custody.holder)), + role("recipient", Target::Subject(custody.counterparty)), + role("place", Target::Entity(topology.yard)), + role("resource", Target::Entity(custody.tithe)), + ], + proposed: vec![ProposedEffect { + slot: 0, + magnitude: Magnitude::Quantity(Quantity(2)), + }], + speech: None, + }, + }, + ); + let authenticated_controller = AuthenticatedCaller::fixture(caller); + let SubmitReceipt::Applied(receipt) = kernel + .submit(envelope.clone(), &authenticated_controller) + .unwrap() + else { + panic!("expected an applied invocation"); + }; + let accepted = kernel.snapshot().unwrap(); + let committed = accepted.events.last().expect("the committed event").clone(); + assert!(!committed.effects.is_empty()); + let world_id = accepted.world_id; + drop(kernel); + + 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"), + &committed + ); + assert_eq!( + reopened + .submit(envelope, &authenticated_controller) + .unwrap(), + SubmitReceipt::AlreadyApplied(receipt) + ); + } + /// A store written at the pass-2 schema is refused outright. There is no /// migration adapter, and the refusal is the behaviour. #[test] diff --git a/crates/ghostlight-dungeon/src/world/mailbox.rs b/crates/ghostlight-dungeon/src/world/mailbox.rs index 807a0dd..ee0043c 100644 --- a/crates/ghostlight-dungeon/src/world/mailbox.rs +++ b/crates/ghostlight-dungeon/src/world/mailbox.rs @@ -1,12 +1,11 @@ use super::{ - AffordanceKind, AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, - CreateWorld, CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, - Declaration, DraftHandle, KernelError, NewController, PrincipalCommandIntent, PrincipalId, + AuthenticatedCaller, CallerId, CommandBody, CommandEnvelope, CommandId, CreateWorld, + CreateWorldIntent, CreationReceipt, DecisionInvocation, DecisionOpportunity, Declaration, + DraftHandle, KernelError, NewController, PrincipalCommandIntent, PrincipalId, SubjectDeclaration, SubjectKind, SubmitReceipt, WorldKernel, WorldPatch, WorldSnapshot, - journal, prepare_creation, + journal, patch::kernel_speak_grant, prepare_creation, }; use crate::app_session::VerifiedPrincipalEvidence; -use std::collections::BTreeSet; use std::path::Path; use thiserror::Error; use tokio::sync::{mpsc, oneshot}; @@ -99,7 +98,7 @@ impl WorldMailbox { label: label.trim().to_owned(), kind, controller, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }) }; @@ -520,8 +519,8 @@ async fn run_owner(mut owned: OwnedWorld, mut receiver: mpsc::Receiver) mod tests { use super::*; use crate::world::{ - AffordanceKind, CallerId, CommandBody, Declaration, DraftHandle, EntityDeclaration, - EntityKind, Mismatch, NewController, PrincipalId, SubjectDeclaration, SubjectKind, WorldId, + CallerId, CommandBody, Declaration, DraftHandle, EntityDeclaration, EntityKind, Mismatch, + NewController, PrincipalId, SubjectDeclaration, SubjectKind, WorldId, }; use std::{collections::BTreeSet, path::PathBuf}; use tempfile::TempDir; @@ -543,7 +542,7 @@ mod tests { controller: NewController::Human { principal: PrincipalId::new("owner"), }, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, })], operations: Vec::new(), @@ -926,7 +925,7 @@ mod tests { label: label.into(), kind: SubjectKind::Person, controller, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }) }; @@ -978,8 +977,10 @@ mod tests { let unrelated = pick(crate::world::ControllerMode::NarrativePersona); let speak = |opportunity: &DecisionOpportunity, text: &str| DecisionInvocation { - affordance_id: opportunity.affordance_ids[0], - action: crate::world::DecisionAction::Speak { text: text.into() }, + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(crate::world::Utterance::new(text).unwrap()), }; mailbox .submit_controller( @@ -1043,10 +1044,10 @@ mod tests { CommandId::new(), &forged, DecisionInvocation { - affordance_id: forged.affordance_ids[0], - action: crate::world::DecisionAction::Speak { - text: "Let me in.".into(), - }, + affordance: forged.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(crate::world::Utterance::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 81b154a..f0cdae1 100644 --- a/crates/ghostlight-dungeon/src/world/mod.rs +++ b/crates/ghostlight-dungeon/src/world/mod.rs @@ -5,11 +5,13 @@ //! Controllers may use models, but models never own lifecycle, scope, affordances, //! opportunities, reduction, or persistence. +mod action; mod controllers; mod journal; mod mailbox; mod patch; +pub(crate) use action::ActionMismatch; pub(crate) use controllers::{ ControllerError, ControllerModels, ControllerOpenError, ControllerPendingReason, ControllerRunner, ControllerWorkCustody, NarrativeCapture, NarrativeDecision, NarrativePending, @@ -18,11 +20,13 @@ pub(crate) use controllers::{ }; pub(crate) use mailbox::{MailboxError, WorldMailbox}; pub(crate) use patch::{ - AccessKind, Cost, Declaration, DependencyTarget, DraftHandle, EntityDeclaration, EntityKind, - EvidenceRef, Mismatch, PatchAnswer, Position, Quantity, Ref, SubjectDeclaration, WorldPatch, + AccessKind, Affordance, AffordanceKindName, Bounds, ComponentOpKind, Cost, Declaration, + DependencyTarget, DraftHandle, EffectSlot, EntityDeclaration, EntityKind, EvidenceRef, + Mismatch, OutcomeBand, PatchAnswer, Position, Precondition, Quantity, Ref, RefKind, Role, + RoleSpec, SubjectDeclaration, WorldPatch, }; #[cfg(test)] -use patch::{ComponentOp, DependencyRef, RouteDeclaration}; +use patch::{AffordanceDeclaration, ComponentOp, DependencyRef, RouteDeclaration}; use patch::{EdgeRecord, EntityRecord, LedgerDelta, ResolvedOp, ResolvedPatch}; use chrono::{DateTime, Utc}; @@ -34,8 +38,8 @@ use std::path::Path; use thiserror::Error; use uuid::Uuid; -pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.custody.v1"; -pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.custody.v1"; +pub(crate) const STATE_SCHEMA: &str = "ghostlight.world_state.affordance.v1"; +pub(crate) const COMMIT_SCHEMA: &str = "ghostlight.world_commit.affordance.v1"; /// Compatibility tag derived from [`STATE_SCHEMA`]: the trailing /// `-` pair (e.g. `foundation-v1`). Callers that publish a @@ -167,12 +171,6 @@ pub(crate) enum ControllerMode { OperationalAgent, } -#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] -#[serde(rename_all = "snake_case")] -pub(crate) enum AffordanceKind { - Speak, -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "type", rename_all = "snake_case")] pub(crate) enum NewController { @@ -261,7 +259,10 @@ struct ScopePreimage<'a> { world_id: WorldId, subject_id: SubjectId, controller: &'a ControllerAssignment, - affordances: BTreeMap, + /// The granted entries *and their definitions*: preconditions and ceilings + /// are what admission reads, so a change to a granted entry must change the + /// digest. + affordances: BTreeMap, components: &'a ScopeComponents, } @@ -283,25 +284,72 @@ impl DecisionOpportunity { } } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -#[serde(tag = "type", rename_all = "snake_case")] -pub(crate) enum DecisionAction { - Speak { text: String }, +/// The referent a role is bound to. Canonical IDs only: an invocation happens +/// in Active, where no declaration exists, so a draft reference is +/// unrepresentable here and the action lane runs no draft resolution. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "target", content = "id", rename_all = "snake_case")] +pub(crate) enum Target { + Subject(SubjectId), + Entity(EntityId), + Edge(EdgeId), } -impl DecisionAction { - fn kind(&self) -> AffordanceKind { - match self { - Self::Speak { .. } => AffordanceKind::Speak, +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoleBinding { + pub(crate) role: Role, + 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 { + None, + Quantity(Quantity), + Cost(Cost), +} + +/// One proposal against one effect slot. It carries no referents: they all come +/// from the slot's roles resolved through the invocation's bindings, so an +/// invocation cannot name a target its affordance declared no role for and the +/// ceiling check is a comparison rather than a graph walk. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct ProposedEffect { + pub(crate) slot: usize, + pub(crate) magnitude: Magnitude, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub(crate) struct DecisionInvocation { - pub(crate) affordance_id: AffordanceId, - pub(crate) action: DecisionAction, + pub(crate) affordance: AffordanceId, + pub(crate) bindings: Vec, + /// Exactly one entry per slot in the entry, in any order. + pub(crate) proposed: Vec, + pub(crate) speech: Option, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -398,12 +446,6 @@ impl ControllerAssignment { } } -#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] -struct AffordanceGrant { - scope: DecisionScope, - kind: AffordanceKind, -} - #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub(crate) struct DecisionEvent { pub(crate) id: EventId, @@ -411,6 +453,12 @@ pub(crate) struct DecisionEvent { pub(crate) scope: DecisionScope, pub(crate) controller_id: ControllerId, pub(crate) invocation: DecisionInvocation, + /// Index into the entry's `outcome_bands`. Re-derived and compared at apply + /// and at replay, never trusted. + pub(crate) band: usize, + /// The selected band's slots, lowered through the invocation's bindings. + /// Empty when the selected band names no effects. + pub(crate) effects: Vec, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -433,7 +481,12 @@ struct WorldState { /// What each subject depends on. Never empty for a present key. dependencies: BTreeMap>, controller_assignments: BTreeMap, - affordance_grants: BTreeMap, + /// What an affordance *is*. World-authored, Draft-only, written by + /// `admit_resolved` alone. + affordance_catalog: BTreeMap, + /// Who may exercise which entry. A grant carries no payload, so a duplicate + /// grant is unrepresentable rather than checked. + affordance_grants: BTreeMap>, events: Vec, state_digest: String, last_commit_digest: Option, @@ -513,7 +566,7 @@ pub(crate) struct SubjectSnapshot { pub(crate) controller_id: ControllerId, pub(crate) controller_mode: ControllerMode, pub(crate) human_controller: Option, - pub(crate) affordances: BTreeMap, + pub(crate) affordances: BTreeSet, pub(crate) position: Option, /// This subject's own holdings and dependencies, and the routes incident to /// its place: exactly what its scope digest reads, lowered from the one @@ -523,6 +576,16 @@ pub(crate) struct SubjectSnapshot { pub(crate) incident_routes: Vec, } +/// One catalog entry as consumers read it. The whole entry, because every +/// derived surface — tool schemas, signature prose, the typed view's permission +/// block — is a projection of it and a narrower snapshot would be a second +/// vocabulary to keep in step. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(crate) struct AffordanceSnapshot { + pub(crate) id: AffordanceId, + pub(crate) entry: Affordance, +} + #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ResourceSnapshot { pub(crate) id: EntityId, @@ -557,6 +620,7 @@ pub(crate) struct WorldSnapshot { pub(crate) draft_approvals: BTreeSet, pub(crate) required_approvers: BTreeSet, pub(crate) subjects: Vec, + pub(crate) affordances: Vec, pub(crate) places: Vec, pub(crate) resources: Vec, pub(crate) routes: Vec, @@ -630,8 +694,8 @@ pub(crate) enum KernelError { EmptyPrincipal, #[error("patch rejected: {0:?}")] PatchRejected(Vec), - #[error("spoken action must not be empty")] - EmptySpeech, + #[error("action rejected: {0:?}")] + ActionRejected(Vec), #[error("command targets another world")] WorldMismatch, #[error("authenticated caller does not match the command")] @@ -661,8 +725,6 @@ pub(crate) enum KernelError { ControllerMismatch, #[error("decision affordance is not granted by the opportunity")] AffordanceDenied, - #[error("decision action does not match its affordance")] - AffordanceMismatch, #[error("expected revision {expected}, current revision {actual}")] RevisionMismatch { expected: u64, actual: u64 }, #[error("command ID was reused with different content")] @@ -867,7 +929,7 @@ impl WorldKernel { let effect = reduce(&self.state, &command)?; let mut candidate = self.state.clone(); - apply_effect(&mut candidate, &command.caller, &effect)?; + apply_effect(&mut candidate, command.id, &command.caller, &effect)?; candidate.revision = candidate .revision .checked_add(1) @@ -994,29 +1056,8 @@ fn reduce(state: &WorldState, command: &CommandEnvelope) -> Result Result<() .values() .map(ControllerAssignment::id) .collect(); - let mut scope_kinds: BTreeSet<(DecisionScope, AffordanceKind)> = state - .affordance_grants - .values() - .map(|grant| (grant.scope, grant.kind)) - .collect(); + for entry in &resolved.affordances { + if state + .affordance_catalog + .insert(entry.affordance_id, entry.affordance.clone()) + .is_some() + { + return Err(KernelError::Invariant( + "admitted affordance ID collision".into(), + )); + } + } for subject in &resolved.subjects { let scope = DecisionScope { subject_id: subject.subject_id, @@ -1268,18 +1316,17 @@ fn admit_resolved(state: &mut WorldState, resolved: &ResolvedPatch) -> Result<() "admitted position collides with an existing one".into(), )); } - for (affordance_id, grant) in &subject.affordances { - if grant.scope != scope - || !scope_kinds.insert((scope, grant.kind)) - || state - .affordance_grants - .insert(*affordance_id, grant.clone()) - .is_some() - { + for affordance_id in &subject.affordances { + if !state.affordance_catalog.contains_key(affordance_id) { return Err(KernelError::Invariant( - "admitted affordance is unscoped or collides".into(), + "admitted grant names no catalog entry".into(), )); } + state + .affordance_grants + .entry(scope) + .or_default() + .insert(*affordance_id); } } apply_operations(state, &resolved.operations, &resolved.evidence) @@ -1653,10 +1700,9 @@ fn snapshot(state: &WorldState) -> Result { })?; let affordances = state .affordance_grants - .iter() - .filter(|(_, grant)| grant.scope == scope) - .map(|(affordance_id, grant)| (grant.kind, *affordance_id)) - .collect(); + .get(&scope) + .cloned() + .unwrap_or_default(); let components = scope_components(state, *subject_id); Ok(SubjectSnapshot { id: *subject_id, @@ -1717,6 +1763,14 @@ fn snapshot(state: &WorldState) -> Result { draft_approvals: state.draft_approvals.clone(), required_approvers: required_approvers(state), subjects, + affordances: state + .affordance_catalog + .iter() + .map(|(affordance_id, entry)| AffordanceSnapshot { + id: *affordance_id, + entry: entry.clone(), + }) + .collect(), places, resources, routes, @@ -1737,9 +1791,10 @@ fn derive_opportunities(state: &WorldState) -> Result, .map(|(scope, controller)| { let affordance_ids: Vec<_> = state .affordance_grants - .iter() - .filter(|(_, grant)| grant.scope == *scope) - .map(|(affordance_id, _)| *affordance_id) + .get(scope) + .into_iter() + .flatten() + .copied() .collect(); if affordance_ids.is_empty() { return Err(KernelError::Invariant( @@ -1759,6 +1814,47 @@ fn derive_opportunities(state: &WorldState) -> Result, .collect() } +/// The entries one scope is granted, paired with their definitions. A grant +/// naming no catalog entry is a corrupt kernel rather than a rejection: one +/// owner writes both partitions in one commit. +fn granted_entries( + state: &WorldState, + scope: DecisionScope, +) -> Result, KernelError> { + state + .affordance_grants + .get(&scope) + .into_iter() + .flatten() + .map(|affordance_id| { + state + .affordance_catalog + .get(affordance_id) + .map(|entry| (*affordance_id, entry)) + .ok_or_else(|| KernelError::Invariant("granted affordance has no entry".into())) + }) + .collect() +} + +/// The membership half of the affordance check, shared by `reduce` and +/// `apply_effect`: the opportunity offers the entry and the scope holds it. +fn require_granted( + state: &WorldState, + current: &DecisionOpportunity, + affordance: AffordanceId, +) -> Result<(), KernelError> { + if current.affordance_ids.contains(&affordance) + && state + .affordance_grants + .get(¤t.scope) + .is_some_and(|granted| granted.contains(&affordance)) + { + Ok(()) + } else { + Err(KernelError::AffordanceDenied) + } +} + /// The sole producer of a `ScopeDigest`. The components it reads come from /// `scope_components`, which the snapshot reads too. fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result { @@ -1766,12 +1862,7 @@ fn scope_digest(state: &WorldState, scope: DecisionScope) -> Result Result Result { } } -fn validated_invocation(value: &DecisionInvocation) -> Result { - let action = match &value.action { - DecisionAction::Speak { text } if text.trim().is_empty() => { - return Err(KernelError::EmptySpeech); - } - DecisionAction::Speak { text } => DecisionAction::Speak { text: text.clone() }, - }; - Ok(DecisionInvocation { - affordance_id: value.affordance_id, - action, - }) -} - fn validate_principal(value: &PrincipalId) -> Result<(), KernelError> { if value.0.trim().is_empty() || value.0.trim() != value.0 { Err(KernelError::EmptyPrincipal) @@ -1877,8 +1960,11 @@ fn validate_assignment(value: &ControllerAssignment) -> Result<(), KernelError> Ok(()) } +/// `command_id` is the band draw's only per-command term, so the arm that +/// re-derives an exercised decision needs the same one `reduce` drew from. fn apply_effect( state: &mut WorldState, + command_id: CommandId, caller: &CallerId, effect: &WorldEffect, ) -> Result<(), KernelError> { @@ -1928,31 +2014,25 @@ fn apply_effect( .ok_or_else(|| { KernelError::Invariant("decision scope lost its controller".into()) })?; - let grant = state - .affordance_grants - .get(&event.invocation.affordance_id) - .ok_or(KernelError::AffordanceDenied)?; - let expected_revision = state - .revision - .checked_add(1) - .ok_or_else(|| KernelError::Serialization("world revision overflow".into()))?; - if state.phase != WorldPhase::Active - || caller != &assignment.expected_caller() - || event.revision != expected_revision - || event.scope != current.scope - || event.controller_id != current.controller_id - || !current - .affordance_ids - .contains(&event.invocation.affordance_id) - || grant.scope != current.scope - || grant.kind != event.invocation.action.kind() - || validated_invocation(&event.invocation)? != event.invocation - { + if state.phase != WorldPhase::Active || caller != &assignment.expected_caller() { return Err(KernelError::Invariant( "decision effect does not match exact opportunity authority".into(), )); } + require_granted(state, ¤t, event.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, &event.invocation)?; + if derived != *event { + return Err(KernelError::Invariant( + "decision effect does not derive from its opportunity".into(), + )); + } state.events.push(event.clone()); + if !event.effects.is_empty() { + apply_operations(state, &event.effects, &[])?; + } } WorldEffect::DecisionDeclined { opportunity } => { let current = exact_opportunity(state, opportunity)?; @@ -1993,6 +2073,7 @@ fn commit_digest(commit: &WorldCommit) -> Result { #[cfg(test)] mod tests { + use super::patch::kernel_speak_grant; use super::*; pub(super) fn owner() -> PrincipalId { @@ -2018,11 +2099,38 @@ mod tests { label: label.into(), kind, controller, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: kernel_speak_grant(), position: None, }) } + /// 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. + pub(super) fn speak_entry(kernel: &WorldKernel) -> Ref { + Ref::Existing( + *kernel + .state + .affordance_catalog + .iter() + .find(|(_, entry)| entry.kind.0 == "speak") + .map(|(affordance_id, _)| affordance_id) + .expect("genesis admits the kernel Speak entry"), + ) + } + + /// A catalog entry by kind name. An affordance id names an entry, not a + /// subject's copy of one, so a test that needs an entry a scope does not + /// hold asks for it by name rather than by list position. + pub(super) fn affordance_named(snapshot: &WorldSnapshot, kind: &str) -> AffordanceId { + snapshot + .affordances + .iter() + .find(|entry| entry.entry.kind.0 == kind) + .map(|entry| entry.id) + .expect("the fixture world declares this affordance") + } + pub(super) fn creation(id: CommandId, title: &str) -> CreateWorld { CreateWorld { id, @@ -2032,6 +2140,21 @@ mod tests { operations: Vec::new(), evidence: Vec::new(), declarations: vec![ + // 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. + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new("convene"), + kind: AffordanceKindName("convene".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + }), subject( "player", "The Player", @@ -2046,12 +2169,17 @@ mod tests { SubjectKind::Person, NewController::NarrativePersona, ), - subject( - "operator", - "The Council", - SubjectKind::Institution, - NewController::OperationalAgent, - ), + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("operator"), + label: "The Council".into(), + kind: SubjectKind::Institution, + controller: NewController::OperationalAgent, + affordances: kernel_speak_grant() + .into_iter() + .chain(std::iter::once(Ref::Draft(DraftHandle::new("convene")))) + .collect(), + position: None, + }), ], }, } @@ -2151,7 +2279,7 @@ mod tests { }) } - pub(super) fn topology_patch() -> WorldPatch { + pub(super) fn topology_patch(speak: Ref) -> WorldPatch { WorldPatch { declarations: vec![ place("yard", "The Cavity Yard"), @@ -2194,7 +2322,7 @@ mod tests { label: "The Walker".into(), kind: SubjectKind::Person, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak]), position: Some(Ref::Draft(DraftHandle::new("yard"))), }), ], @@ -2214,7 +2342,7 @@ mod tests { &before, CommandBody::AdmitPatch { answers: None, - patch: topology_patch(), + patch: topology_patch(speak_entry(kernel)), }, ); assert!(matches!(receipt, SubmitReceipt::Applied(_))); @@ -2276,29 +2404,192 @@ mod tests { }) } - fn holder(handle: &str, label: &str, place: EntityId) -> Declaration { + fn holder(handle: &str, label: &str, place: EntityId, speak: Ref) -> Declaration { Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Institution, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: std::iter::once(speak) + .chain(carry_affordances().into_iter().map(|declaration| { + let Declaration::Affordance(entry) = declaration else { + unreachable!("carry_affordances declares only affordances") + }; + Ref::Draft(entry.handle) + })) + .collect(), position: Some(Ref::Existing(place)), }) } + pub(super) const CARRY_HANDLE: &str = "carry"; + + /// The worked affordances for the action lane. Every one carries the same + /// four roles and the same bounded `Transfer` slot, so a test varies exactly + /// one thing — a precondition or a band table — by naming a different entry + /// rather than by reaching into a committed catalog. The catalog is + /// Draft-only, so authoring it is how a world gets a verb. + fn carry_variant( + handle: &str, + kind: &str, + preconditions: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles: vec![ + RoleSpec { + role: Role("from".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("recipient".into()), + kind: RefKind::Subject(None), + }, + RoleSpec { + role: Role("place".into()), + kind: RefKind::Entity(EntityKind::Place), + }, + RoleSpec { + role: Role("resource".into()), + kind: RefKind::Entity(EntityKind::Resource), + }, + ], + preconditions, + effect_slots: vec![EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: vec![ + Role("from".into()), + Role("recipient".into()), + Role("resource".into()), + ], + bounds: Bounds::Quantity(Quantity(3)), + }], + outcome_bands, + carries_speech: false, + }) + } + + fn certain_band() -> Vec { + vec![OutcomeBand { + weight: 1, + effects: vec![0], + }] + } + + fn place_role() -> Role { + Role("place".into()) + } + + /// Carry, and five variants that each move one dial: a holding demand above + /// the opening balance, a reach budget short of the two-hop path, one that + /// covers it, a band that names no effect, and three equally weighted bands. + pub(super) fn carry_affordances() -> Vec { + vec![ + carry_variant( + CARRY_HANDLE, + "carry", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-greedy", + "carry_greedy", + vec![ + Precondition::Present { at: place_role() }, + Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(OPENING_BALANCE + 1), + }, + ], + certain_band(), + ), + carry_variant( + "carry-holds", + "carry_holds", + vec![Precondition::Holds { + resource: Role("resource".into()), + at_least: Quantity(1), + }], + certain_band(), + ), + carry_variant( + "carry-near", + "carry_near", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(NEAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-far", + "carry_far", + vec![Precondition::Reachable { + to: place_role(), + within: Cost(FAR_REACH), + }], + certain_band(), + ), + carry_variant( + "carry-idle", + "carry_idle", + Vec::new(), + vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + ), + carry_variant( + "carry-chance", + "carry_chance", + Vec::new(), + vec![ + OutcomeBand { + weight: 1, + effects: vec![0], + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + OutcomeBand { + weight: 1, + effects: Vec::new(), + }, + ], + ), + ] + } + + /// Yard to gate over the open shutter alone. + pub(super) const NEAR_REACH: u32 = 5; + /// Yard to gate over the ramp and the span, which is the only open public + /// path while the shutter is closed. + pub(super) const FAR_REACH: u32 = 19; + /// Declarations and evidence are Draft-only, so the resources, the holders, /// and the one evidenced `Admit` that creates the opening balance all land /// before activation. There is no holdings declaration field: quantity is /// created by `Admit` and by nothing else, in this lane as in every other. - pub(super) fn custody_patch(topology: &Topology) -> WorldPatch { + pub(super) fn custody_patch(topology: &Topology, speak: Ref) -> WorldPatch { WorldPatch { - declarations: vec![ - resource("tithe", "The Rhythm Tithe"), - resource("ingot", "The Cut Ingot"), - holder("clerk", "The Ledger Clerk", topology.yard), - holder("keeper", "The Gate Keeper", topology.gate), - ], + declarations: carry_affordances() + .into_iter() + .chain([ + resource("tithe", "The Rhythm Tithe"), + resource("ingot", "The Cut Ingot"), + holder("clerk", "The Ledger Clerk", topology.yard, speak.clone()), + holder("keeper", "The Gate Keeper", topology.gate, speak), + ]) + .collect(), operations: vec![ComponentOp::Admit { holder: Ref::Draft(DraftHandle::new("clerk")), resource: Ref::Draft(DraftHandle::new("tithe")), @@ -2316,7 +2607,7 @@ mod tests { &before, CommandBody::AdmitPatch { answers: None, - patch: custody_patch(topology), + patch: custody_patch(topology, speak_entry(kernel)), }, ); assert!(matches!(receipt, SubmitReceipt::Applied(_))); @@ -2412,8 +2703,10 @@ mod tests { fn speak(opportunity: &DecisionOpportunity, text: &str) -> DecisionInvocation { DecisionInvocation { - affordance_id: opportunity.affordance_ids[0], - action: DecisionAction::Speak { text: text.into() }, + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new(text).unwrap()), } } @@ -2582,15 +2875,29 @@ mod tests { assert_ne!(scope_digest(&changed_controller, scope).unwrap(), base); let mut changed_grants = kernel.state.clone(); - changed_grants.affordance_grants.insert( - AffordanceId::issue(), - AffordanceGrant { - scope, - kind: AffordanceKind::Speak, - }, - ); + let extra = AffordanceId::issue(); + changed_grants + .affordance_catalog + .insert(extra, patch::kernel_speak_entry()); + changed_grants + .affordance_grants + .entry(scope) + .or_default() + .insert(extra); assert_ne!(scope_digest(&changed_grants, scope).unwrap(), base); + // The digest reads the granted entries' definitions, not only their + // ids: admission reads preconditions and ceilings, so altering an entry + // must move the digest. + let mut changed_entry = kernel.state.clone(); + let granted = *kernel.state.affordance_grants[&scope].first().unwrap(); + changed_entry + .affordance_catalog + .get_mut(&granted) + .unwrap() + .carries_speech = false; + assert_ne!(scope_digest(&changed_entry, scope).unwrap(), base); + let mut changed_position = kernel.state.clone(); changed_position.positions.insert( topology.walker, @@ -2665,7 +2972,7 @@ mod tests { CommandId::new(), CallerId::Principal(player()), CommandBody::ExerciseDecision { - invocation: speak(&player_opportunity, " I open the door. "), + invocation: speak(&player_opportunity, "I open the door."), opportunity: player_opportunity, }, ), @@ -2675,10 +2982,12 @@ mod tests { let after_player = kernel.snapshot().unwrap(); assert_eq!(after_player.events.len(), 1); assert_eq!( - after_player.events[0].invocation.action, - DecisionAction::Speak { - text: " I open the door. ".into() - } + after_player.events[0] + .invocation + .speech + .as_ref() + .map(Utterance::as_str), + Some("I open the door.") ); let persona_opportunity = opportunity(&after_player, ControllerMode::NarrativePersona); @@ -2807,12 +3116,14 @@ mod tests { .unwrap(); let active = activate(&mut kernel); let original = opportunity(&active, ControllerMode::Human); - let other_scope = opportunity(&active, ControllerMode::NarrativePersona); + // An entry only the operational subject is granted: the human's scope + // does not hold it, which is what denial means now that an affordance id + // names a catalog entry rather than one subject's copy of one. let denied_invocation = DecisionInvocation { - affordance_id: other_scope.affordance_ids[0], - action: DecisionAction::Speak { - text: "No grant".into(), - }, + affordance: affordance_named(&active, "convene"), + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("No grant").unwrap()), }; assert!(matches!( kernel.submit( @@ -2842,10 +3153,10 @@ mod tests { CallerId::Principal(player()), CommandBody::ExerciseDecision { invocation: DecisionInvocation { - affordance_id: forged_affordance, - action: DecisionAction::Speak { - text: "Forged".into() - }, + affordance: forged_affordance, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("Forged").unwrap()), }, opportunity: tampered, }, @@ -3216,7 +3527,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[1] = invalid.patch.declarations[0].clone(); + invalid.patch.declarations[2] = invalid.patch.declarations[1].clone(); let Err(KernelError::PatchRejected(rejected)) = WorldKernel::create(&path, invalid, &auth_principal(owner())) else { @@ -3411,6 +3722,7 @@ mod tests { // A new place elsewhere, a route that touches neither the walker's // place nor it, and a second placed subject: all outside the scope. + let speak = speak_entry(&kernel); let before = kernel.snapshot().unwrap(); submit_owner( &mut kernel, @@ -3438,7 +3750,7 @@ mod tests { label: "The Runner".into(), kind: SubjectKind::Person, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak.clone()]), position: Some(Ref::Existing(topology.road)), }), ], @@ -3536,9 +3848,12 @@ mod tests { let persona = opportunity(&active, ControllerMode::NarrativePersona); let operator = opportunity(&active, ControllerMode::OperationalAgent); - // The persona claims the operator's affordance and lists it as its own. + // The persona claims the operator's entry and lists it as its own. + let convened = affordance_named(&active, "convene"); + assert!(operator.affordance_ids.contains(&convened)); + assert!(!persona.affordance_ids.contains(&convened)); let mut forged = persona.clone(); - forged.affordance_ids = vec![operator.affordance_ids[0], persona.affordance_ids[0]]; + forged.affordance_ids = vec![convened, persona.affordance_ids[0]]; let caller = CallerId::Controller(persona.controller_id); let error = kernel .submit( @@ -3549,10 +3864,10 @@ mod tests { CommandBody::ExerciseDecision { opportunity: forged, invocation: DecisionInvocation { - affordance_id: operator.affordance_ids[0], - action: DecisionAction::Speak { - text: "Not my grant.".into(), - }, + affordance: convened, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("Not my grant.").unwrap()), }, }, ), @@ -3562,6 +3877,76 @@ mod tests { assert!(matches!(error, KernelError::AffordanceDenied)); assert_eq!(kernel.snapshot().unwrap(), active); } + + #[test] + fn a_stale_grant_rejects_but_a_distant_route_reaches_admission_instead() { + let dir = tempfile::tempdir().unwrap(); + let (mut kernel, _) = WorldKernel::create( + dir.path().join("world.cc"), + creation(CommandId::new(), "BindingAndAdmission"), + &auth_principal(owner()), + ) + .unwrap(); + let topology = admit_topology(&mut kernel); + let active = activate(&mut kernel); + let bound = opportunity_for(&active, topology.walker); + let speak = affordance_named(&active, "speak"); + + // Binding is scope-digest equality, and the digest reads the granted + // entries' definitions: altering one moves the digest, so a proposal + // bound before that change no longer binds. + let mut altered = kernel.state.clone(); + altered + .affordance_catalog + .get_mut(&speak) + .expect("the Speak entry") + .carries_speech = false; + assert_ne!( + scope_digest(&altered, bound.scope).unwrap(), + scope_digest(&kernel.state, bound.scope).unwrap() + ); + + // A route the actor does not stand beside is outside the digest, so + // closing it leaves the binding intact. That is deliberate: admission + // re-reads the live graph at commit, so nothing commits on stale + // topology and a proposal is not invalidated by distant traffic. + let before_digest = scope_digest(&kernel.state, bound.scope).unwrap(); + let before = kernel.snapshot().unwrap(); + submit_owner( + &mut kernel, + &before, + operations(vec![ComponentOp::CloseRoute { + route: Ref::Existing(topology.span), + }]), + ); + assert_eq!( + scope_digest(&kernel.state, bound.scope).unwrap(), + before_digest, + "a route outside the actor's incident set does not rebind the proposal" + ); + + let snapshot = kernel.snapshot().unwrap(); + let receipt = kernel + .submit( + command( + &snapshot, + CommandId::new(), + CallerId::Controller(bound.controller_id), + CommandBody::ExerciseDecision { + opportunity: bound.clone(), + invocation: DecisionInvocation { + affordance: speak, + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("Still here.").unwrap()), + }, + }, + ), + &AuthenticatedCaller::fixture(CallerId::Controller(bound.controller_id)), + ) + .expect("a distant route closing does not rebind this proposal"); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + } } #[cfg(test)] @@ -3569,11 +3954,11 @@ mod custody_tests { use super::tests::{ OPENING_BALANCE, TITHE_RECEIPT, activate, admit_custody, admit_topology, auth_principal, command, creation, custody_world, operations, opportunity_for, owner, reject_owner, - submit_owner, + speak_entry, submit_owner, }; use super::*; - fn custody_kernel(path: &Path, title: &str) -> WorldKernel { + pub(super) fn custody_kernel(path: &Path, title: &str) -> WorldKernel { WorldKernel::create( path.join("world.cc"), creation(CommandId::new(), title), @@ -3609,6 +3994,7 @@ mod custody_tests { subjects: Vec::new(), entities: Vec::new(), routes: Vec::new(), + affordances: Vec::new(), operations: vec![ResolvedOp::Transfer { from: custody.holder, to: custody.counterparty, @@ -3618,8 +4004,13 @@ mod custody_tests { evidence: Vec::new(), }, }; - let error = - apply_effect(&mut candidate, &CallerId::Principal(owner()), &forged).unwrap_err(); + let error = apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forged, + ) + .unwrap_err(); assert!(matches!(error, KernelError::Invariant(_))); assert_eq!(candidate.holdings, before); @@ -3654,6 +4045,7 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = custody_kernel(directory.path(), "Unevidenced"); let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); let before = kernel.snapshot().unwrap(); let commits = kernel.journal.commit_count(); @@ -3675,7 +4067,7 @@ mod custody_tests { label: "The Ledger Clerk".into(), kind: SubjectKind::Institution, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak.clone()]), position: Some(Ref::Existing(topology.yard)), }), ], @@ -4091,10 +4483,10 @@ mod custody_tests { CommandBody::ExerciseDecision { opportunity: bound.clone(), invocation: DecisionInvocation { - affordance_id: bound.affordance_ids[0], - action: DecisionAction::Speak { - text: "The tithe is short.".into(), - }, + affordance: bound.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("The tithe is short.").unwrap()), }, }, ), @@ -4191,6 +4583,7 @@ mod custody_tests { subjects: Vec::new(), entities: Vec::new(), routes: Vec::new(), + affordances: Vec::new(), operations, evidence: Vec::new(), }, @@ -4207,6 +4600,7 @@ mod custody_tests { let mut candidate = kernel.state.clone(); let error = apply_effect( &mut candidate, + CommandId::issue(), &CallerId::Principal(owner()), &forge(vec![transfer(5), transfer(5)]), ) @@ -4223,6 +4617,7 @@ mod custody_tests { let mut conserving = kernel.state.clone(); apply_effect( &mut conserving, + CommandId::issue(), &CallerId::Principal(owner()), &forge(vec![ transfer(5), @@ -4256,6 +4651,7 @@ mod custody_tests { let mut candidate = kernel.state.clone(); let error = apply_effect( &mut candidate, + CommandId::issue(), &CallerId::Principal(owner()), &forge(vec![degenerate]), ) @@ -4271,6 +4667,7 @@ mod custody_tests { let mut unevidenced = kernel.state.clone(); let error = apply_effect( &mut unevidenced, + CommandId::issue(), &CallerId::Principal(owner()), &forge(vec![ResolvedOp::Admit { holder: custody.holder, @@ -4295,6 +4692,7 @@ mod custody_tests { let directory = tempfile::tempdir().unwrap(); let mut kernel = custody_kernel(directory.path(), "Overflow"); let topology = admit_topology(&mut kernel); + let speak = speak_entry(&kernel); let before = kernel.snapshot().unwrap(); let commits = kernel.journal.commit_count(); @@ -4322,7 +4720,7 @@ mod custody_tests { label: "The Ledger Clerk".into(), kind: SubjectKind::Institution, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak.clone()]), position: Some(Ref::Existing(topology.yard)), }), ], @@ -4368,10 +4766,10 @@ mod custody_tests { let exercise = |opportunity: &DecisionOpportunity| CommandBody::ExerciseDecision { opportunity: opportunity.clone(), invocation: DecisionInvocation { - affordance_id: opportunity.affordance_ids[0], - action: DecisionAction::Speak { - text: "Counted before the tithe arrived.".into(), - }, + affordance: opportunity.affordance_ids[0], + bindings: Vec::new(), + proposed: Vec::new(), + speech: Some(Utterance::new("Counted before the tithe arrived.").unwrap()), }, }; diff --git a/crates/ghostlight-dungeon/src/world/patch.rs b/crates/ghostlight-dungeon/src/world/patch.rs index 5b3d875..e901d55 100644 --- a/crates/ghostlight-dungeon/src/world/patch.rs +++ b/crates/ghostlight-dungeon/src/world/patch.rs @@ -7,8 +7,8 @@ //! after that set is empty, so a rejected patch never mints an ID. use super::{ - AffordanceGrant, AffordanceId, AffordanceKind, CommandId, ControllerAssignment, ControllerId, - DecisionScope, EdgeId, EntityId, NewController, SubjectId, SubjectKind, SubjectState, WorldId, + AffordanceId, CommandId, ControllerAssignment, ControllerId, EdgeId, EntityId, NewController, + SubjectId, SubjectKind, SubjectState, WorldId, }; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -96,14 +96,17 @@ pub(crate) struct Position { /// expectation carries `None` where the referring position constrains the /// namespace but not the kind. /// -/// Not serializable: a `RefKind` is never persisted. It lives in `Mismatch`, in -/// the resolution index, and in the three constants below, all of which stay in -/// memory for the length of one reduction. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +/// It is one predicate serving three readers: the resolution index, `Mismatch`, +/// and an affordance's `RoleSpec`, which persists inside the catalog and so +/// requires the serde derives. `Affordance` names the catalog namespace, which +/// carries no components and can never be a role's target. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(tag = "namespace", content = "kind", rename_all = "snake_case")] pub(crate) enum RefKind { Subject(Option), Entity(EntityKind), Edge(EdgeKind), + Affordance, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] @@ -125,12 +128,186 @@ pub(crate) enum Ref { Draft(DraftHandle), } -/// A referent in any of the three namespaces. +/// A referent in any of the three referent namespaces, or in the catalog. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub(crate) enum RefName { Subject(Ref), Entity(Ref), Edge(Ref), + Affordance(Ref), +} + +/// A world-declared affordance name. Canonical text, `[a-z][a-z0-9_]{0,47}`, +/// because it becomes a generated tool name and a tool name must be stable, +/// unique, and safe. The kernel carries it and branches on it nowhere; that is +/// what keeps genre out of the reducer. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct AffordanceKindName(pub(crate) String); + +/// A named slot in one affordance, bound to a referent at invocation time. +/// Canonical text, `[a-z][a-z0-9_]{0,31}` — it becomes a tool parameter name. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(transparent)] +pub(crate) struct Role(pub(crate) String); + +/// What a role must be bound to. `RefKind` is reused rather than mirrored: it +/// already spells subject, entity kind, and edge kind, so the binding kind-check +/// and the declaration kind-check are one predicate. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(deny_unknown_fields)] +pub(crate) struct RoleSpec { + pub(crate) role: Role, + pub(crate) kind: RefKind, +} + +/// What must already be true of committed state before an invocation is +/// admitted. Only the three whose components exist: `Authorized`, `Knows`, +/// `CanReach`, and `Committed` land in the pass that adds `Authority`, +/// `Knowledge`, `Channel`, and `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 { + /// The acting subject's Position names the place bound to `at`. + Present { at: Role }, + /// A path exists from the actor's place to the place bound to `to`, over + /// open public routes, with summed cost at most `within`. + Reachable { to: Role, within: Cost }, + /// The acting subject's own holding of the resource bound to `resource` is + /// at least `at_least`. + Holds { resource: Role, at_least: Quantity }, +} + +/// Exactly the operations an affordance may propose. Nine, not the resolver's +/// ten: `Admit` is absent because minting quantity requires an `EvidenceRef` and +/// an invocation carries no evidence list, so admitting it here would be a +/// second creation path beside the single evidenced one. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "snake_case")] +pub(crate) enum ComponentOpKind { + Relocate, + OpenRoute, + CloseRoute, + AlterCost, + Transfer, + Transform, + Consume, + Bind, + Release, +} + +/// The referent shape of one operation: the single source of both the +/// declaration check and the lowering. +pub(super) enum RoleKindRule { + Exact(RefKind), + AnyDependencyTarget, +} + +/// Which magnitude, if any, an operation carries. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BoundsDimension { + None, + Quantity, + Cost, +} + +impl ComponentOpKind { + pub(super) fn arity(self) -> Vec { + let subject = RoleKindRule::Exact(ANY_SUBJECT); + let route = || RoleKindRule::Exact(ROUTE); + let resource = || RoleKindRule::Exact(RefKind::Entity(EntityKind::Resource)); + match self { + Self::Relocate => vec![subject, route()], + Self::OpenRoute | Self::CloseRoute | Self::AlterCost => vec![route()], + Self::Transfer => vec![subject, RoleKindRule::Exact(ANY_SUBJECT), resource()], + Self::Transform => vec![subject, resource(), resource()], + Self::Consume => vec![subject, resource()], + Self::Bind | Self::Release => vec![subject, RoleKindRule::AnyDependencyTarget], + } + } + + pub(super) fn dimension(self) -> BoundsDimension { + match self { + Self::Relocate | Self::OpenRoute | Self::CloseRoute | Self::Bind | Self::Release => { + BoundsDimension::None + } + Self::Transfer | Self::Transform | Self::Consume => BoundsDimension::Quantity, + Self::AlterCost => BoundsDimension::Cost, + } + } +} + +/// Whether a declared role kind can serve a position governed by this rule. +pub(super) fn role_kind_fits(rule: &RoleKindRule, declared: RefKind) -> bool { + match rule { + RoleKindRule::Exact(RefKind::Subject(_)) => matches!(declared, RefKind::Subject(_)), + RoleKindRule::Exact(expected) => *expected == declared, + RoleKindRule::AnyDependencyTarget => matches!( + declared, + RefKind::Subject(_) | RefKind::Entity(EntityKind::Resource) | RefKind::Edge(_) + ), + } +} + +/// The magnitude ceiling for one slot. A closed enum matched to the operation's +/// dimension rather than a struct of optional ceilings: an `Option` ceiling that +/// is `None` is not a ceiling, and a struct admits the nonsense of a cost +/// ceiling on a `Transfer`. +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "bound", content = "max", rename_all = "snake_case")] +pub(crate) enum Bounds { + None, + Quantity(Quantity), + Cost(Cost), +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct EffectSlot { + pub(crate) op_kind: ComponentOpKind, + /// Positional: exactly the referents `op_kind` takes, in `arity()` order. + pub(crate) roles: Vec, + pub(crate) bounds: Bounds, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct OutcomeBand { + /// At least 1. A zero-weight band is a branch that can never be selected. + pub(crate) weight: u32, + /// Indices into `effect_slots`, strictly increasing. Empty is legal and is + /// how a world expresses "the attempt does nothing". + pub(crate) effects: Vec, +} + +/// One catalog entry: what an affordance *is*. Who may use it is +/// `affordance_grants` and nothing else, so an entry carries no audience. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Affordance { + pub(crate) kind: AffordanceKindName, + /// Ordered, so the generated tool's parameters are stable across builds. + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + /// Every invocation of this entry carries exactly one utterance. The + /// kernel's only behaviour is to record it in the event; any world may + /// declare a speaking affordance, so this is not a Speak special case. + pub(crate) carries_speech: bool, +} + +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct AffordanceDeclaration { + pub(crate) handle: DraftHandle, + pub(crate) kind: AffordanceKindName, + pub(crate) roles: Vec, + pub(crate) preconditions: Vec, + pub(crate) effect_slots: Vec, + pub(crate) outcome_bands: Vec, + pub(crate) carries_speech: bool, } /// Where a failed check appeared. One way to say it, for declarations and @@ -164,7 +341,10 @@ pub(crate) struct SubjectDeclaration { pub(crate) label: String, pub(crate) kind: SubjectKind, pub(crate) controller: NewController, - pub(crate) affordances: BTreeSet, + /// The catalog entries this subject may exercise. Every entry is a + /// reference, so a genesis patch declares a catalog and grants from it + /// atomically. + pub(crate) affordances: BTreeSet>, pub(crate) position: Option>, } @@ -197,6 +377,7 @@ pub(crate) enum Declaration { Subject(SubjectDeclaration), Entity(EntityDeclaration), Route(RouteDeclaration), + Affordance(AffordanceDeclaration), } /// The operations that change a component of an already canonical structure. @@ -371,6 +552,62 @@ pub(crate) enum Mismatch { CustodyNotConserved { resource: RefName, }, + /// `kind` is not `[a-z][a-z0-9_]{0,47}`, or a `Role` is not + /// `[a-z][a-z0-9_]{0,31}`. Tool and parameter names must be safe. + InvalidAffordanceName { + handle: DraftHandle, + }, + /// Two entries in the candidate graph share one kind name; the generated + /// tool catalog would have two tools with one name. + DuplicateAffordanceKind { + handle: DraftHandle, + }, + DuplicateRole { + handle: DraftHandle, + role: Role, + }, + /// A precondition or a slot names a role the entry does not declare. + UnknownRole { + handle: DraftHandle, + role: Role, + }, + /// A declared role's `RefKind` cannot serve the position that reads it, or + /// names a namespace no invocation target can bind. + RoleKindUnfit { + handle: DraftHandle, + role: Role, + }, + SlotRoleArity { + handle: DraftHandle, + slot: usize, + }, + /// The slot's `Bounds` variant does not match its `op_kind`'s dimension, or + /// the ceiling is zero, or a cost ceiling is outside `1..=MAX_ROUTE_COST`. + SlotBoundMismatch { + handle: DraftHandle, + slot: usize, + }, + NoOutcomeBand { + handle: DraftHandle, + }, + ZeroBandWeight { + handle: DraftHandle, + band: usize, + }, + /// A band names a slot index the entry does not have. + DanglingBandEffect { + handle: DraftHandle, + band: usize, + }, + /// A band's `effects` are not strictly increasing. + BandEffectsNotCanonical { + handle: DraftHandle, + band: usize, + }, + /// No effect slots and no speech: the entry can never change anything. + InertAffordance { + handle: DraftHandle, + }, } #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] @@ -448,7 +685,7 @@ pub(super) struct ResolvedSubject { pub(super) subject_id: SubjectId, pub(super) subject: SubjectState, pub(super) controller: ControllerAssignment, - pub(super) affordances: BTreeMap, + pub(super) affordances: BTreeSet, pub(super) position: Option, } @@ -459,6 +696,14 @@ pub(super) struct ResolvedEntity { pub(super) entity: EntityRecord, } +/// The handle-to-ID binding for one catalog entry. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +pub(super) struct ResolvedAffordance { + pub(super) handle: DraftHandle, + pub(super) affordance_id: AffordanceId, + pub(super) affordance: Affordance, +} + #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] pub(super) struct ResolvedRoute { pub(super) handle: DraftHandle, @@ -471,7 +716,7 @@ pub(super) struct ResolvedRoute { /// does not have. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] #[serde(tag = "op", rename_all = "snake_case")] -pub(super) enum ResolvedOp { +pub(crate) enum ResolvedOp { Relocate { subject_id: SubjectId, edge_id: EdgeId, @@ -563,6 +808,7 @@ pub(super) struct ResolvedPatch { pub(super) subjects: Vec, pub(super) entities: Vec, pub(super) routes: Vec, + pub(super) affordances: Vec, pub(super) operations: Vec, pub(super) evidence: Vec, } @@ -572,6 +818,7 @@ impl ResolvedPatch { self.subjects.is_empty() && self.entities.is_empty() && self.routes.is_empty() + && self.affordances.is_empty() && self.evidence.is_empty() } } @@ -645,12 +892,6 @@ fn derive_id( Uuid::from_bytes(bytes) } -fn affordance_slug(kind: AffordanceKind) -> &'static str { - match kind { - AffordanceKind::Speak => "speak", - } -} - pub(super) fn is_canonical_text(value: &str) -> bool { !value.trim().is_empty() && value.trim() == value } @@ -659,6 +900,246 @@ pub(super) fn is_valid_cost(cost: Cost) -> bool { (1..=MAX_ROUTE_COST).contains(&cost.0) } +/// `[a-z][a-z0-9_]{0,max-1}`. Affordance kinds and roles become generated tool +/// and parameter names, so the alphabet is the safe one and the bound is stated +/// rather than assumed. +fn is_tool_name(value: &str, max: usize) -> bool { + let mut characters = value.chars(); + characters + .next() + .is_some_and(|first| first.is_ascii_lowercase()) + && value.len() <= max + && value.chars().all(|character| { + character.is_ascii_lowercase() || character.is_ascii_digit() || character == '_' + }) +} + +/// The handle of the kernel-built Speak entry. It is indexed in the same draft +/// index as world-declared entries, so a genesis subject grants it with an +/// ordinary `Ref::Draft` and there is no second grant path. +pub(super) const KERNEL_SPEAK_HANDLE: &str = "ghostlight.affordance.speak"; + +/// The grant every genesis subject carries: a draft reference to the +/// kernel-built entry, resolved by the ordinary handle index. World ingress and +/// every fixture name this rather than repeating the handle literal. +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. +pub(super) fn kernel_speak_entry() -> Affordance { + Affordance { + kind: AffordanceKindName("speak".into()), + roles: Vec::new(), + preconditions: Vec::new(), + effect_slots: Vec::new(), + outcome_bands: vec![OutcomeBand { + weight: 1, + effects: Vec::new(), + }], + carries_speech: true, + } +} + +/// Whether a stored catalog entry would still be admitted by the declaration +/// validator. One validator, two readers: the resolver rejects a bad entry, and +/// journal recovery refuses a store that already holds one. +pub(super) fn entry_is_admissible(entry: &Affordance) -> bool { + let mut mismatches = Vec::new(); + validate_affordance( + &DraftHandle::new(""), + &entry.kind, + &entry.roles, + &entry.preconditions, + &entry.effect_slots, + &entry.outcome_bands, + entry.carries_speech, + &mut mismatches, + ); + mismatches.is_empty() +} + +/// The catalog-entry resolver, beside `resolve_entity`/`_subject`/`_route`. An +/// entry carries no components, so there is nothing to check past namespace +/// agreement. +fn resolve_affordance( + site: Site, + reference: &Ref, + index: &BTreeMap, + catalog: &BTreeMap, + mismatches: &mut Vec, +) -> Option> { + match reference { + Ref::Draft(named) => match index.get(named) { + None => { + mismatches.push(Mismatch::UnresolvedDraft { + site, + referent: named.clone(), + expected: RefKind::Affordance, + }); + None + } + Some(kind) if *kind != RefKind::Affordance => { + mismatches.push(Mismatch::WrongKind { + site, + referent: RefName::Affordance(reference.clone()), + expected: RefKind::Affordance, + actual: *kind, + }); + None + } + Some(_) => Some(Key::Draft(named.clone())), + }, + Ref::Existing(affordance_id) => { + if catalog.contains_key(affordance_id) { + Some(Key::Existing(*affordance_id)) + } else { + mismatches.push(Mismatch::UnknownCanonical { + site, + expected: RefKind::Affordance, + }); + None + } + } + } +} + +/// The one validator of a catalog entry, run per declared entry in declaration +/// order inside the resolver's accumulate-then-gate loop. +fn validate_affordance( + handle: &DraftHandle, + kind: &AffordanceKindName, + roles: &[RoleSpec], + preconditions: &[Precondition], + effect_slots: &[EffectSlot], + outcome_bands: &[OutcomeBand], + carries_speech: bool, + mismatches: &mut Vec, +) { + let site = || Site::Declaration(handle.clone()); + if !is_tool_name(&kind.0, 48) || roles.iter().any(|spec| !is_tool_name(&spec.role.0, 32)) { + mismatches.push(Mismatch::InvalidAffordanceName { + handle: handle.clone(), + }); + } + let mut declared: BTreeMap = BTreeMap::new(); + for spec in roles { + match declared.entry(spec.role.clone()) { + Entry::Vacant(slot) => { + slot.insert(spec.kind); + } + Entry::Occupied(_) => mismatches.push(Mismatch::DuplicateRole { + handle: handle.clone(), + role: spec.role.clone(), + }), + } + // No `Target` names the catalog namespace, so a role of that kind could + // never be bound. + if spec.kind == RefKind::Affordance { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: spec.role.clone(), + }); + } + } + let require = + |role: &Role, expected: RefKind, mismatches: &mut Vec| match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(actual) if *actual != expected => mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }), + Some(_) => {} + }; + for precondition in preconditions { + match precondition { + Precondition::Present { at } => { + require(at, RefKind::Entity(EntityKind::Place), mismatches); + } + Precondition::Reachable { to, within } => { + require(to, RefKind::Entity(EntityKind::Place), mismatches); + if !is_valid_cost(*within) { + mismatches.push(Mismatch::InvalidCost { site: site() }); + } + } + Precondition::Holds { resource, .. } => { + require(resource, RefKind::Entity(EntityKind::Resource), mismatches); + } + } + } + for (index, slot) in effect_slots.iter().enumerate() { + let arity = slot.op_kind.arity(); + if slot.roles.len() != arity.len() { + mismatches.push(Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: index, + }); + } + for (role, rule) in slot.roles.iter().zip(arity.iter()) { + match declared.get(role) { + None => mismatches.push(Mismatch::UnknownRole { + handle: handle.clone(), + role: role.clone(), + }), + Some(declared_kind) if !role_kind_fits(rule, *declared_kind) => { + mismatches.push(Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: role.clone(), + }); + } + Some(_) => {} + } + } + let fits = match (slot.op_kind.dimension(), slot.bounds) { + (BoundsDimension::None, Bounds::None) => true, + (BoundsDimension::Quantity, Bounds::Quantity(ceiling)) => ceiling.0 >= 1, + (BoundsDimension::Cost, Bounds::Cost(ceiling)) => is_valid_cost(ceiling), + _ => false, + }; + if !fits { + mismatches.push(Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: index, + }); + } + } + if outcome_bands.is_empty() { + mismatches.push(Mismatch::NoOutcomeBand { + handle: handle.clone(), + }); + } + for (index, band) in outcome_bands.iter().enumerate() { + if band.weight == 0 { + mismatches.push(Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: index, + }); + } + if band.effects.iter().any(|slot| *slot >= effect_slots.len()) { + mismatches.push(Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: index, + }); + } + if band.effects.windows(2).any(|pair| pair[0] >= pair[1]) { + mismatches.push(Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: index, + }); + } + } + if effect_slots.is_empty() && !carries_speech { + mismatches.push(Mismatch::InertAffordance { + handle: handle.clone(), + }); + } +} + /// The one entity resolver. `expected` names the kind the referring site /// requires; a handle or ID that answers with another kind is `WrongKind`. fn resolve_entity( @@ -861,23 +1342,45 @@ pub(super) fn resolve_patch( let mut mismatches = Vec::new(); let mut index: BTreeMap = BTreeMap::new(); + // The kernel-built Speak entry enters the same index as a world-declared + // one, before the declaration loop, so a world reusing its handle collides + // as a duplicate handle rather than through a reserved-name check. + let speak_handle = DraftHandle::new(KERNEL_SPEAK_HANDLE); + if admits_human { + index.insert(speak_handle.clone(), RefKind::Affordance); + } + let mut kind_names: BTreeSet = state + .affordance_catalog + .values() + .map(|entry| entry.kind.clone()) + .collect(); + if admits_human { + kind_names.insert(kernel_speak_entry().kind); + } + for (position, declaration) in patch.declarations.iter().enumerate() { let (handle, label, kind) = match declaration { Declaration::Subject(subject) => ( &subject.handle, - &subject.label, + Some(&subject.label), RefKind::Subject(Some(subject.kind)), ), - Declaration::Entity(entity) => { - (&entity.handle, &entity.label, RefKind::Entity(entity.kind)) - } - Declaration::Route(route) => (&route.handle, &route.label, ROUTE), + Declaration::Entity(entity) => ( + &entity.handle, + Some(&entity.label), + RefKind::Entity(entity.kind), + ), + Declaration::Route(route) => (&route.handle, Some(&route.label), ROUTE), + // A catalog entry's name is its `kind`, checked by the entry + // validator against the tool-name alphabet rather than against the + // label rule. + Declaration::Affordance(affordance) => (&affordance.handle, None, RefKind::Affordance), }; let named = is_canonical_text(&handle.0); if !named { mismatches.push(Mismatch::EmptyHandle { position }); } - if !is_canonical_text(label) { + if label.is_some_and(|label| !is_canonical_text(label)) { mismatches.push(Mismatch::EmptyLabel { handle: handle.clone(), }); @@ -892,6 +1395,23 @@ pub(super) fn resolve_patch( }), } } + if let Declaration::Affordance(affordance) = declaration { + validate_affordance( + &affordance.handle, + &affordance.kind, + &affordance.roles, + &affordance.preconditions, + &affordance.effect_slots, + &affordance.outcome_bands, + affordance.carries_speech, + &mut mismatches, + ); + if !kind_names.insert(affordance.kind.clone()) { + mismatches.push(Mismatch::DuplicateAffordanceKind { + handle: affordance.handle.clone(), + }); + } + } if let Declaration::Subject(subject) = declaration { if subject.affordances.is_empty() { mismatches.push(Mismatch::NoAffordances { @@ -1006,7 +1526,17 @@ pub(super) fn resolve_patch( } } } + Declaration::Affordance(_) => {} Declaration::Subject(subject) => { + for reference in &subject.affordances { + resolve_affordance( + Site::Declaration(subject.handle.clone()), + reference, + &index, + &state.affordance_catalog, + &mut mismatches, + ); + } if let Some(reference) = &subject.position && let Some(place) = resolve_entity( Site::Declaration(subject.handle.clone()), @@ -1578,6 +2108,69 @@ pub(super) fn resolve_patch( }); } + let mut allocated_affordances: BTreeMap = BTreeMap::new(); + let mut affordances = Vec::new(); + let allocate_affordance = |handle: &DraftHandle, + entry: Affordance, + affordances: &mut Vec, + allocated: &mut BTreeMap, + collisions: &mut Vec| { + let affordance_id = AffordanceId(derive_id( + AFFORDANCE_NAMESPACE, + world_id, + command_id, + handle, + None, + )); + if state.affordance_catalog.contains_key(&affordance_id) { + collisions.push(Mismatch::CanonicalCollision { + handle: handle.clone(), + }); + } + allocated.insert(handle.clone(), affordance_id); + affordances.push(ResolvedAffordance { + handle: handle.clone(), + affordance_id, + affordance: entry, + }); + }; + if admits_human { + allocate_affordance( + &speak_handle, + kernel_speak_entry(), + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + for declaration in &patch.declarations { + let Declaration::Affordance(input) = declaration else { + continue; + }; + allocate_affordance( + &input.handle, + Affordance { + kind: input.kind.clone(), + roles: input.roles.clone(), + preconditions: input.preconditions.clone(), + effect_slots: input.effect_slots.clone(), + outcome_bands: input.outcome_bands.clone(), + carries_speech: input.carries_speech, + }, + &mut affordances, + &mut allocated_affordances, + &mut collisions, + ); + } + let affordance_id_of = |key: &Key| -> AffordanceId { + match key { + Key::Existing(affordance_id) => *affordance_id, + Key::Draft(handle) => *allocated_affordances + .get(handle) + .expect("a draft affordance reference resolved above"), + } + }; + let mut allocated_subjects: BTreeMap = BTreeMap::new(); let mut subjects = Vec::new(); for declaration in &patch.declarations { @@ -1597,7 +2190,6 @@ pub(super) fn resolve_patch( }); } allocated_subjects.insert(input.handle.clone(), subject_id); - let scope = DecisionScope { subject_id }; let controller_id = ControllerId(derive_id( CONTROLLER_NAMESPACE, world_id, @@ -1617,19 +2209,10 @@ pub(super) fn resolve_patch( ControllerAssignment::OperationalAgent { controller_id } } }; - let affordances = input + let granted = input .affordances .iter() - .map(|kind| { - let affordance_id = AffordanceId(derive_id( - AFFORDANCE_NAMESPACE, - world_id, - command_id, - &input.handle, - Some(affordance_slug(*kind)), - )); - (affordance_id, AffordanceGrant { scope, kind: *kind }) - }) + .map(|reference| affordance_id_of(&key_of(reference))) .collect(); subjects.push(ResolvedSubject { handle: input.handle.clone(), @@ -1639,7 +2222,7 @@ pub(super) fn resolve_patch( kind: input.kind, }, controller, - affordances, + affordances: granted, position: input.position.as_ref().map(|reference| Position { place: entity_id_of(&key_of(reference)), }), @@ -1755,6 +2338,7 @@ pub(super) fn resolve_patch( subjects, entities, routes, + affordances, operations, evidence: patch.evidence.clone(), }) @@ -1800,7 +2384,8 @@ pub(super) fn containment_terminates( mod tests { use super::*; use crate::world::tests::{ - activate, admit_topology, auth_principal, command, creation, owner, player, submit_owner, + 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, @@ -1835,13 +2420,22 @@ mod tests { }) } - fn institution(handle: &str, label: &str, position: Option>) -> Declaration { + /// Every fixture institution is declared by a post-genesis `AdmitPatch`, so + /// it grants the committed Speak entry by canonical reference: the kernel + /// synthesizes that entry once, at genesis, and a later patch names it like + /// any other structure a previous commit allocated. + fn institution( + kernel: &WorldKernel, + handle: &str, + label: &str, + position: Option>, + ) -> Declaration { Declaration::Subject(SubjectDeclaration { handle: DraftHandle::new(handle), label: label.into(), kind: SubjectKind::Institution, controller: NewController::OperationalAgent, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak_entry(kernel)]), position, }) } @@ -1877,6 +2471,348 @@ mod tests { } } + /// A minimal admissible entry, so a validation test changes exactly one + /// thing and names exactly one rejection. + fn catalog_entry( + handle: &str, + kind: &str, + roles: Vec, + effect_slots: Vec, + outcome_bands: Vec, + ) -> Declaration { + Declaration::Affordance(AffordanceDeclaration { + handle: DraftHandle::new(handle), + kind: AffordanceKindName(kind.into()), + roles, + preconditions: Vec::new(), + effect_slots, + outcome_bands, + carries_speech: false, + }) + } + + fn role_spec(role: &str, kind: RefKind) -> RoleSpec { + RoleSpec { + role: Role(role.into()), + kind, + } + } + + fn transfer_slot(roles: Vec<&str>, bounds: Bounds) -> EffectSlot { + EffectSlot { + op_kind: ComponentOpKind::Transfer, + roles: roles.into_iter().map(|role| Role(role.into())).collect(), + bounds, + } + } + + fn transfer_roles() -> Vec { + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Resource)), + ] + } + + fn band(effects: Vec) -> OutcomeBand { + OutcomeBand { weight: 1, effects } + } + + #[test] + fn a_catalog_entry_with_a_dangling_or_noncanonical_band_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let slots = vec![ + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))), + ]; + let handle = DraftHandle::new("verb"); + + for (bands, expected) in [ + ( + vec![band(vec![2])], + Mismatch::DanglingBandEffect { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![band(vec![1, 0])], + Mismatch::BandEffectsNotCanonical { + handle: handle.clone(), + band: 0, + }, + ), + ( + vec![OutcomeBand { + weight: 0, + effects: vec![0], + }], + Mismatch::ZeroBandWeight { + handle: handle.clone(), + band: 0, + }, + ), + ( + Vec::new(), + Mismatch::NoOutcomeBand { + handle: handle.clone(), + }, + ), + ] { + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + slots.clone(), + bands, + )])), + ); + assert_eq!(rejected, vec![expected]); + assert!(kernel.state.affordance_catalog.len() == before.affordances.len()); + } + + // No effect slots and no speech: the entry could never change anything. + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + Vec::new(), + Vec::new(), + vec![band(Vec::new())], + )])), + ); + assert_eq!(rejected, vec![Mismatch::InertAffordance { handle }]); + } + + #[test] + fn a_slot_whose_roles_do_not_match_its_operation_is_rejected() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let handle = DraftHandle::new("verb"); + + // A `Transfer` takes three referents, not two. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotRoleArity { + handle: handle.clone(), + slot: 0 + }] + ); + + // Its third referent is a resource, not a place. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + vec![ + role_spec("from", RefKind::Subject(None)), + role_spec("to", RefKind::Subject(None)), + role_spec("goods", RefKind::Entity(EntityKind::Place)), + ], + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::RoleKindUnfit { + handle: handle.clone(), + role: Role("goods".into()) + }] + ); + + // A `Transfer` carries a quantity, so an unbounded slot has no ceiling. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot(vec!["from", "to", "goods"], Bounds::None)], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::SlotBoundMismatch { + handle: handle.clone(), + slot: 0 + }] + ); + + // A slot naming a role the entry does not declare. + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "cargo"], + Bounds::Quantity(Quantity(2)) + )], + vec![band(vec![0])], + )])), + ), + vec![Mismatch::UnknownRole { + handle, + role: Role("cargo".into()) + }] + ); + } + + #[test] + fn a_grant_naming_an_undeclared_affordance_is_rejected_and_the_same_patch_commits() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let entries_before = kernel.state.affordance_catalog.len(); + let subjects_before = kernel.state.subjects.len(); + + let granting = |handle: &str| { + Declaration::Subject(SubjectDeclaration { + handle: DraftHandle::new("late-arrival"), + label: "A Late Arrival".into(), + kind: SubjectKind::Person, + controller: NewController::NarrativePersona, + affordances: BTreeSet::from([Ref::Draft(DraftHandle::new(handle))]), + position: None, + }) + }; + + assert_eq!( + reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![granting("verb")])) + ), + vec![Mismatch::UnresolvedDraft { + site: Site::Declaration(DraftHandle::new("late-arrival")), + referent: DraftHandle::new("verb"), + expected: RefKind::Affordance, + }] + ); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before); + assert_eq!(kernel.state.subjects.len(), subjects_before); + + // Declaring the entry in the same patch commits both atomically. + let receipt = submit_owner( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "verb", + "verb", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + ), + granting("verb"), + ])), + ); + assert!(matches!(receipt, SubmitReceipt::Applied(_))); + assert_eq!(kernel.state.affordance_catalog.len(), entries_before + 1); + assert_eq!(kernel.state.subjects.len(), subjects_before + 1); + let granted = kernel + .state + .affordance_grants + .values() + .find(|entries| entries.len() == 1) + .expect("the new subject's grant set"); + assert!( + granted + .iter() + .all(|id| kernel.state.affordance_catalog.contains_key(id)) + ); + } + + #[test] + fn two_entries_cannot_share_one_kind_name() { + let directory = tempfile::tempdir().unwrap(); + let mut kernel = draft_world(directory.path()); + let before = kernel.snapshot().unwrap(); + let slot = transfer_slot(vec!["from", "to", "goods"], Bounds::Quantity(Quantity(2))); + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![ + catalog_entry( + "first", + "haul", + transfer_roles(), + vec![slot.clone()], + vec![band(vec![0])], + ), + catalog_entry( + "second", + "haul", + transfer_roles(), + vec![slot], + vec![band(vec![0])], + ), + ])), + ); + assert_eq!( + rejected, + vec![Mismatch::DuplicateAffordanceKind { + handle: DraftHandle::new("second") + }] + ); + + // A kind name outside the tool-name alphabet is refused for the same + // reason: it becomes a generated tool name. + let rejected = reject_owner( + &mut kernel, + &before, + admit(patch_of(vec![catalog_entry( + "loud", + "Haul It", + transfer_roles(), + vec![transfer_slot( + vec!["from", "to", "goods"], + Bounds::Quantity(Quantity(2)), + )], + vec![band(vec![0])], + )])), + ); + assert_eq!( + rejected, + vec![Mismatch::InvalidAffordanceName { + handle: DraftHandle::new("loud") + }] + ); + } + fn draft_world(directory: &std::path::Path) -> WorldKernel { WorldKernel::create( directory.join("world.cc"), @@ -1903,6 +2839,7 @@ mod tests { CommandId::new(), CallerId::Principal(owner()), admit(patch_of(vec![institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), @@ -1938,26 +2875,24 @@ mod tests { let before = kernel.snapshot().unwrap(); let commits_before = kernel.journal.commit_count(); - let receipt = submit_owner( - &mut kernel, - &before, - admit(patch_of(vec![ - entity("cavity-yard", "The Cavity Yard", EntityKind::Place), - entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place), - route( - "yard-road", - "The Yard Ramp", - "cavity-yard", - "kharad-rhythm-road", - 12, - ), - institution( - "rhythm-authority", - "The Rhythm Authority", - Some(Ref::Draft(draft("kharad-rhythm-road"))), - ), - ])), - ); + let patch = patch_of(vec![ + entity("cavity-yard", "The Cavity Yard", EntityKind::Place), + entity("kharad-rhythm-road", "The Rhythm Road", EntityKind::Place), + route( + "yard-road", + "The Yard Ramp", + "cavity-yard", + "kharad-rhythm-road", + 12, + ), + institution( + &kernel, + "rhythm-authority", + "The Rhythm Authority", + Some(Ref::Draft(draft("kharad-rhythm-road"))), + ), + ]); + let receipt = submit_owner(&mut kernel, &before, admit(patch)); assert!(matches!(receipt, SubmitReceipt::Applied(_))); let after = kernel.snapshot().unwrap(); @@ -2016,6 +2951,7 @@ mod tests { admit(patch_of(vec![ entity("rhythm-tithe", "The Rhythm Tithe", EntityKind::Resource), institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("rhythm-tithe"))), @@ -2054,6 +2990,7 @@ mod tests { entity("rhythm-road", "The Rhythm Road", EntityKind::Place), entity("rhythm-road", " ", EntityKind::Place), institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("cavity-yard"))), @@ -2065,7 +3002,7 @@ mod tests { controller: NewController::Human { principal: player(), }, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak_entry(&kernel)]), position: None, }), ]); @@ -2107,6 +3044,7 @@ mod tests { entity("rhythm-road", "The Rhythm Road", EntityKind::Place), entity("cavity-yard", "The Cavity Yard", EntityKind::Place), institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("cavity-yard"))), @@ -2116,7 +3054,7 @@ mod tests { label: "A Late Arrival".into(), kind: SubjectKind::Person, controller: NewController::NarrativePersona, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak_entry(&kernel)]), position: None, }), ]); @@ -2541,6 +3479,7 @@ mod tests { admit(patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("rhythm-road"))), @@ -2582,7 +3521,7 @@ mod tests { label: "Another Player".into(), kind: SubjectKind::Person, controller: NewController::NarrativePersona, - affordances: BTreeSet::from([AffordanceKind::Speak]), + affordances: BTreeSet::from([speak_entry(&kernel)]), position: None, })]); submit_owner(&mut kernel, &before, admit(patch.clone())); @@ -2625,6 +3564,7 @@ mod tests { command_id, CallerId::Principal(owner()), admit(patch_of(vec![institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("kharad-rhythm-road"))), @@ -2692,6 +3632,7 @@ mod tests { let patch = patch_of(vec![ entity("rhythm-road", "The Rhythm Road", EntityKind::Place), institution( + &kernel, "rhythm-authority", "The Rhythm Authority", Some(Ref::Draft(DraftHandle::new("rhythm-road"))), @@ -2712,6 +3653,7 @@ mod tests { let mut candidate = kernel.state.clone(); let forged_error = super::super::apply_effect( &mut candidate, + CommandId::issue(), &CallerId::Principal(owner()), &super::super::WorldEffect::PatchAdmitted { resolved: forged }, ) @@ -2720,17 +3662,31 @@ mod tests { // Stale: the honest effect applied twice collides on its own IDs. let mut candidate = kernel.state.clone(); - super::super::apply_effect(&mut candidate, &CallerId::Principal(owner()), &honest).unwrap(); - let stale_error = - super::super::apply_effect(&mut candidate, &CallerId::Principal(owner()), &honest) - .unwrap_err(); + super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap(); + let stale_error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap_err(); assert!(matches!(stale_error, KernelError::Invariant(_))); // A non-owner caller never reaches admission. let mut candidate = kernel.state.clone(); - let unauthorized = - super::super::apply_effect(&mut candidate, &CallerId::Principal(player()), &honest) - .unwrap_err(); + let unauthorized = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(player()), + &honest, + ) + .unwrap_err(); assert!(matches!(unauthorized, KernelError::Invariant(_))); assert_eq!(candidate, kernel.state); @@ -2738,9 +3694,13 @@ mod tests { let active = activate(&mut kernel); assert_eq!(active.revision, before.revision + 3); let mut candidate = kernel.state.clone(); - let wrong_phase = - super::super::apply_effect(&mut candidate, &CallerId::Principal(owner()), &honest) - .unwrap_err(); + let wrong_phase = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &honest, + ) + .unwrap_err(); assert!(matches!(wrong_phase, KernelError::Invariant(_))); assert_eq!(candidate, kernel.state); } @@ -2863,6 +3823,7 @@ mod tests { subjects: Vec::new(), entities: Vec::new(), routes: Vec::new(), + affordances: Vec::new(), operations: vec![ResolvedOp::Relocate { subject_id: topology.walker, edge_id, @@ -2871,9 +3832,13 @@ mod tests { }, }; let mut candidate = kernel.state.clone(); - let error = - super::super::apply_effect(&mut candidate, &CallerId::Principal(owner()), &forged) - .unwrap_err(); + let error = super::super::apply_effect( + &mut candidate, + CommandId::issue(), + &CallerId::Principal(owner()), + &forged, + ) + .unwrap_err(); assert!(matches!(error, KernelError::Invariant(_))); assert_eq!(candidate, kernel.state); }