Affordances become world-authored catalog entries with preconditions, ceilings, and bands

An action stops being an enum the kernel understands and becomes a lookup into
world-authored data: preconditions over live state, magnitudes under declared
ceilings, one deterministic band, lowered into the same ResolvedOps the patch
path already applies.

Cut first, with no compatibility path: DecisionAction and its kind(),
AffordanceKind, the AffordanceGrant struct and the (scope, kind) uniqueness
scan, affordance_slug, validated_invocation and its three call sites,
KernelError::EmptySpeech and ::AffordanceMismatch, the seven-clause equality
chain in apply_effect's DecisionExercised arm, the grant-kind comparison in
replay, speak_invocation's parallel constructor, and all three hand-written
claims about what a subject may do (the available_tools prose, the
operational_tools schemas, and the typed view's speak permission literal).

WorldState gains affordance_catalog, the sole store of what an affordance is,
written only by admit_resolved from a resolved patch and validated only by
resolve_patch. affordance_grants collapses to a set per scope, so a duplicate
grant is unrepresentable rather than checked and derive_opportunities is a map
lookup. Declaration::Affordance authors an entry; a subject grants entries by
reference, so one genesis patch declares a catalog and grants from it
atomically. Speak is the kernel-built entry under an ordinary draft handle:
zero preconditions, zero slots, one empty band, one utterance.

world/action.rs owns the pipeline behind one entry point, exercise(), called
from both reduce and apply_effect so a forged effect is re-derived by the
function that produced the honest one. It binds roles, evaluates Present,
Reachable, and Holds, checks every slot against its ceiling, draws one band
through the existing digest() owner over a named BandPreimage, lowers the
selected band's slots through the bindings, and admits them through the same
resolver. Effects ride on the event and apply through apply_operations, so an
affordance's Transfer meets the same conservation equation as a declaration.
ActionMismatch is a sibling of Mismatch, complete, sorted, and never
serialized; it surfaces as KernelError::ActionRejected.

Binding and admission are two checks, not one. Binding is scope-digest
equality, and the digest now reads the granted entries' definitions. Admission
runs at commit against live state, so a route closing mid-flight is
TargetUnreachable rather than ScopeChanged, and a proposal is not invalidated
by distant traffic.

The OperationalAgent tool catalog, its prose signature line, and the typed
view's permission block are three projections of the granted entries, naming
affordance kinds and role parameters and never an affordance id.

State, commit, and controller-work schemas bump; a pre-pass store is refused.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-04 20:11:01 +02:00
commit f9cd0177e7
8 changed files with 3577 additions and 557 deletions

View file

@ -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::<Vec<_>>();
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))
})
});

View file

@ -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,

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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]

View file

@ -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<Request>)
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;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff